/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);
//advert - advert_place_edit, advert_place_user_tpl
function show_doc (id) {

	obj=document.getElementById(id);
	if (obj.style.display=='block')
	obj.style.display='none';
	else {
		obj.style.display='block';
	}
	return false;
}
function cw(file,x,y) {
  var x=x;
  var y=y;
  var left=(screen.Width-x)/2;
  var top=(screen.Height-y)/2;
  var html ='<html>\n<head>\n<title>Информетр</title>\n<style type="text/css">\nbody {margin:0;padding:0;}\n</style>\n</head>\n</html>\n<body bgcolor="#ffffff" marginwidth="0" marginheight="0" topmargin="0" leftmargin="0" text="#000000">\n<a href="#" onclick="window.close(); return false;"><img src="'+file+'" width="'+x+'" height="'+y+'" border="0" alt="Закрыть окно"></a>\n</body>\n</html>';
  var win1=window.open("","ppp",'width='+x+',height='+y+',scrollbars=0,left='+left+',top='+top+'');
  win1.document.open();
  win1.document.write(html);
  win1.document.close();
  win1.focus();
}

var col=1;
//consult 
//http://dev.informetr.ru/journal/consult
function sh_doc (bl,id) {
	obj=document.getElementById(id);
	var path=siteURL;
	var sp=bl.getElementsByTagName("span");
	if (obj.style.display=='block') {
	obj.style.display='none';
     path=siteURL+'/im/cplus.gif';
	bl.style.color="#b0015a";
	bl.style.background='url('+path+') left center no-repeat';
	sp[0].style.borderBottom="1px dashed #b0015a";
      sp[0].innerHTML='Показать ответ';
	}
	else {

		obj.style.display='block';

            sp[0].innerHTML='Скрыть ответ';
			path=siteURL+'/im/cminus.gif';
         	bl.style.background='url('+path+') left center no-repeat';
	}
}
//consult 
//http://dev.informetr.ru/journal/consult
function show_all_doc (el) {
	var i=1;
	var divs= new Array();
	var arr='';
	arr='a'+i;
    var path=siteURL;
	var dd=document.getElementById('consult').getElementsByTagName('DD');
	if (el.getElementsByTagName('span')[0].innerHTML=='Скрыть все ответы') {
         while (document.getElementById(arr))
	     {
		divs[i-1]=document.getElementById(arr);
		divs[i-1].style.display='none';
		     for (var j=0;j<dd.length;j++) {
			     var span=dd[j].getElementsByTagName('span');
			     if (span.length!=0) {
				    span[0].innerHTML='Показать ответ';
                            el.getElementsByTagName('span')[0].innerHTML='Развернуть все ответы';
				    var div=span[0].parentNode;
				    span[0].style.borderBottom="1px dashed #b0015a";
				    div.style.color="#b0015a";
					 path=siteURL+'/im/cplus.gif';
                            div.style.background='url('+path+') left center no-repeat';
			     }
		     }

         i=i+1;
	   arr='a'+i;
           }
   col=1;
   }
  else {
	while (document.getElementById(arr))
	{
         divs[i-1]=document.getElementById(arr);

	   divs[i-1].style.display='block';
	   for (var j=0;j<dd.length;j++) {
	      var span=dd[j].getElementsByTagName('span');
		if (span.length!=0) {
			span[0].innerHTML='Скрыть ответ';
                  el.getElementsByTagName('span')[0].innerHTML='Скрыть все ответы';
                  var div=span[0].parentNode;
				  path=siteURL+'/im/cminus.gif';
                  div.style.background='url('+path+') left center no-repeat';
			}
	    }
        i=i+1;
	 arr='a'+i;

	 }
	col=0;
       }
}
//consult form - ask question
function check (ch) {
	obj=document.getElementById('pc');
	checkbox=document.getElementById(ch);
	if (checkbox.checked) {
		obj.style.display='block';
	}
	else {
		obj.style.display='none';
	}
}

//??
var k=1;
function change_text (id) {
show_doc('opl');
obj=document.getElementById(id);
obj1=document.getElementById('all');
if (k==1) {
obj.innerHTML='Меньше&nbsp;критериев';
obj1.innerHTML='Все категории';
k++;
}
else {
	k=1;
	obj.innerHTML='Больше&nbsp;критериев';
	obj1.innerHTML='Категории';
}
}

var k=1;
function change_text2 (id) {
show_doc('opl');
obj=document.getElementById(id);
obj1=document.getElementById('all');
if (k==1) {
obj.innerHTML='Больше&nbsp;критериев';
obj1.innerHTML='Категории';
k++;
}
else {
	k=1;
	obj.innerHTML='Меньше&nbsp;критериев';
	obj1.innerHTML='Все категории';
}
}
/*
function sort_table (id,id1) {
	el=document.getElementById(id);

	if (k==2) {
		div=document.getElementById('bottom');
		div.id="top";
		k=1;

		//alert(k);
	}
	else {
		div=document.getElementById('top');
		div.id="bottom";
		k++;

		//alert(k);
	}
}*/
function oncheck () {
	var k=0;
	var ul=document.getElementById('checklist');
	var li=ul.firstChild;

	if (li.nodeType==3) {
	li=li.nextSibling;
	}

    while (li!=null) {

		if (li.getElementsByTagName('ul').length!=0) {

				var inp=li.firstChild;

				inp.onclick=function () {
				    var li=this.parentNode;
				    var ul2=li.getElementsByTagName('ul');
					var checks=ul2[0].getElementsByTagName('input');
					for (var i=0; i<checks.length;i++)  {
								if (k==0) {
								this.checked=false;
								checks[i].checked=false;
								}
								else {
								this.checked=true;
								checks[i].checked=true;
								}
				     }
					if (k==0)
					{
					k=1;
					}
					else
					{
					k=0;
					}
				}
		   }
		li=li.nextSibling;

		while (li.nodeType==3) {
		li=li.nextSibling;
		}
	}
}
/*house_info hover*/
function light (id) {
	div=document.getElementById(id);
	trs=div.getElementsByTagName('tr');
	for (var i in trs) {
		trs[i].onmouseover= function () {
			this.style.background='#f9f9f9';
		}
		trs[i].onmouseout=function() {
			this.style.background='white';
		}
	}
}
/*
function showshadow () {


	if (document.getElementById('gallery')) {
		var ul=document.getElementById('gallery');
		var li=ul.getElementsByTagName('LI');
		var div=ul.getElementsByTagName('DIV');
		for (var i=0;i<div.length;i++) {
			if (div[i].className=='shadow') {
				var k=0;
				function move () {
					//li[i].style.border='1px solid red';

					if ((k!=1)||(k==null)) {
					var div=this.getElementsByTagName('DIV');
					if (div[0].className=='shadow') {
						div[0].style.display="none";
					}
					}
					if (k==1) {
						k=0;
					}
				}
				function out (){

					if ((k!=1)||(k==null)) {
						//alert(k);
					var div=this.getElementsByTagName('DIV');
					if (div[0].className=='shadow') {

						div[0].style.display="block";
					}
					if (k==1) {
						k=0;
					}
					}
				}

				li[i].onmouseover=move;
				li[i].onmouseout=out;
				li[i].onclick=function(){
					var ul=document.getElementById('gallery');
					var li=ul.getElementsByTagName('LI');
					for (var i=0;i<li.length;i++) {
						if (li[i]!=this) {
						var div=li[i].getElementsByTagName('DIV');
						div[0].style.display="block";
						}
					}
					var div=this.getElementsByTagName('DIV');
					if (div[0].className=='shadow') {
						div[0].style.display="none";
					}
					k=1;
					this.onmouseover=move;
					this.onmouseout=out;

				}

			}

		}

	}

}*/
//advert http://dev.informetr.ru/advert - hover on stars
function show_note(id,k,active) {



	var increase_note=document.getElementById('increase-note');
	var mark_note=document.getElementById('mark-note');

	if (active) {
		s = '';
		s += '<div class="wrap">';
		s += '<h6>Объявление поднято.</h6>';
		s += '<p>Кликните на стрелочку, чтобы узнать об этой SMS-услуге подробнее.</p>';
		s += '</div>';
		increase_note.innerHTML = s;
		s = '';
		s += '<div class="wrap">';
		s += '<h6>Объявление выделено цветом и звездочкой.</h6>';
		s += '<p>Кликните на звездочку, чтобы узнать об этой SMS-услуге подробнее.</p>';
		s += '</div>';
		mark_note.innerHTML = s;
	} else {
		s = '';
		s += '<div class="wrap">';
		s += '<h6>Это объявление можно поднять на первое место.</h6>';
		s += '<p>На номер 1151 отправьте SMS:<br>';
		s += ' <strong>#485<span id="aup">'+id+'</span></strong></p>';
		s += '<p>Цена услуги: <strong>35&nbsp;руб.</strong></p>';
		s += '</div>';
		increase_note.innerHTML = s;
		s = '';
		s += '<div class="wrap">';
		s += '<h6>Это объявление можно выделить цветом и звездочкой.</h6>';
		s += '<p>На номер 1151 отправьте SMS:<br>';
		s += '<strong>#484<span id="aselect">'+id+'</span></strong></p>';
		s += '<p>Цена услуги: <strong>35&nbsp;руб.</strong></p>';
		s += '</div>';
		mark_note.innerHTML = s;
	}


//    <div id="increase-note">
//    </div>
//     <div id="mark-note">
//    </div>




	//var block=document.getElementById(k+id);
	var kid=k+id;
//	alert(kid);
	var block=document.getElementById(kid);
	var coords = block.offsetTop;
	var offsetLeft = 0;
	var offsetTop = 0;
	offsetTop=$('#'+kid).offset().top;
	offsetLeft=$('#'+kid).offset().left;
	var headerH=$('.b-header').height()+$('.b-top-nav').height()+$('.b-topban').height();
	//alert(headerH);
	/*while(offsetTrail) {
	offsetLeft += offsetTrail.offsetLeft;
	offsetTop += offsetTrail.offsetTop;
	offsetTrail = offsetTrail.offsetParent;
	}*/
	switch (k)
	{
		case 'm': {
			mark_note.style.display="block";
			mark_note.style.left=(offsetLeft-mark_note.offsetWidth-5)+'px';
			mark_note.style.top=offsetTop-105+'px';
			block.onmouseout=function() {hide_note('i')};
			break;
		}

		case 'i': {
			increase_note.style.display="block";
			increase_note.style.left=(offsetLeft-increase_note.offsetWidth-5)+'px';
			increase_note.style.top=offsetTop-105+'px';
			block.onmouseout=function() {hide_note('m')};
			break;
		}
	}



	}
function hide_note(k) {
	var increase_note=document.getElementById('increase-note');
	var mark_note=document.getElementById('mark-note');
	switch (k)
	{
		case 'm': {
		increase_note.style.display="none";
		break;
		}

		case 'i': {
			mark_note.style.display="none";
			break;
		}
	}

}
/*function mainmenu(){
$(" #nav ul ").css({display: "none"}); // Opera Fix



$(" #nav li").hover(function(){
		var ul=$(this).find('ul:first');
		w=ul.width();
		h=ul.height();
		l=ul.offset().left;
		t=ul.offset().top;
		var ifr=$('<iframe src="about:blank" frameborder="no"></iframe>');
		$('body').append(ifr);
		ifr.addClass('menu-bg');
		ifr.css({left:l,top:t,height:h,width:w,zIndex:2});
		$(this).addClass('m-hover');
		$(this).find('ul:first').css({visibility:"visible",display: "none"}).show();
		},function(){
			$('.menu-bg').remove();
			$(this).removeClass('m-hover');
			$(this).find('ul:first').css({visibility: "hidden"});
		});
}*/
/*cabinet show-hide messages*/
function hide_open_answer(question){
	if (question.hasClass('answer-opened')) {
		question.toggleClass('answer-hidden');
		question.toggleClass('answer-opened');
		question.next().hide();
		}
	else {
		question.next().show();
		question.toggleClass('answer-hidden');
		question.toggleClass('answer-opened');
		}
	return false;
}


$(document).ready(function() {
	var color_bnr=["#ec6e9b","#fd9747","#7fb275"];
	$('.b-ads-text-icon').each(function(){
		var r=Math.round(Math.random() * 2);		
		$(this).css('background-color',color_bnr[r]);
	});
	
	
	if ($('.lightbox').length) {
	
		$('.lightbox').lightbox();
	}
	$('.textarea-change').each(function(i){
			var html=$(this).html();
			var newTextArea=$(this).replaceWith('<textarea rows="2" cols="10" class="b-text-area" id="textarea'+i+'"></textarea>');
			$('#textarea'+i).val(html.toLowerCase());
		}); 	

//request form button
function button_enable(){
	$('#send-help-form').removeAttr('disabled');
	$('.disable').toggleClass('disable',false);
	}

//request form button
function button_disable(){
	$('.b-send-button').addClass('disable');
	$('#send-help-form').attr('disabled','disabled');
	}


//advert filter 
    $('#filter-form').submit(function(e){
    	$('#filter-form	select[name], #filter-form input[name]').each(function(){
    		if ($(this).attr('value') == '' || $(this).attr('value') == '0' || $(this).attr('value') == 0) {
    			//alert($(this).attr('name'));
    			$(this).attr('disabled', 'disabled');
    		}
    	});
    });


/*
//cabinet
 function filterChecks() {

    var inputs=$('.b-advert-filter .b-check-list input');
    var counter=0;
    var wholeLength=inputs.length;
    var button=$('.b-advert-filter .g-button');
    inputs.each(function(){
      if ($(this).is(':checked')) {
          counter++;
      }
    });
     if (counter==0) {
        button.attr('disabled','disabled');
     }
     else {
        button.removeAttr('disabled');
     }
}
filterChecks();
 $('.b-advert-filter li').click(filterChecks);
    var links=$('.b-cabinet-actions a');
    var button=$('.b-cabinet-period .b-button');
    var select=$('.b-cabinet-period select');
    var label=$('.b-cabinet-period label');
    function disableLinks() {
         return false;
     }
     function tableChecks() {
         var inputs=$('.b-cabinet-adverts-list input');
         var counter=0;
         var wholeLength=inputs.length;
         inputs.each(function(){
              if ($(this).is(':checked')) {
                  counter++;
              }
          });
         if (counter==0) {
            button.attr('disabled','disabled');
            select.attr('disabled','disabled');
            links.addClass('b-disabled');
            label.addClass('b-disabled-label');
         }
         else {
            button.removeAttr('disabled');
            select.removeAttr('disabled');
            links.removeClass('b-disabled');
            label.removeClass('b-disabled-label');
         }
     }
     tableChecks();
     $('.b-cabinet-adverts-list input').click(tableChecks);

     var ch=0;
     function cabinetCheck() {
        if (ch) {
             $('.b-cabinet-adverts-list input').removeAttr('checked');

            button.attr('disabled','disabled');
            select.attr('disabled','disabled');
            //links.bind('click',disableLinks).addClass('b-disabled');
            links.addClass('b-disabled');
            label.addClass('b-disabled-label');
            ch=0;
         }
         else {
            $('.b-cabinet-adverts-list input:enabled').attr('checked','checked');
            button.removeAttr('disabled');
            select.removeAttr('disabled');
            links.removeClass('b-disabled');
            //links.unbind('click').removeClass('b-disabled');
            label.removeClass('b-disabled-label');
            ch=1;
         }
     }
     $('.b-cabinet-adverts-list .b-main-check').click(cabinetCheck);

     var searchText=$('.b-cabinet-search .b-search-input').attr('value');
     $('.b-cabinet-search .b-search-input').focus(function(){
         if ($(this).attr('value')==searchText) {
             $(this).attr('value','').css('color','#333');
         }
     });
     $('.b-cabinet-search .b-search-input').blur(function(){
         if ($(this).attr('value')=='') {
             $(this).attr('value',searchText).css('color','#ccc');
         }
     });*/
//ie bg
if($.browser.msie) {
    try {
    document.execCommand('BackgroundImageCache', false, true);
  	} catch(e) {}

  }    
//mainmenu();
//functions for enter window

   	$('#enter-button').click(
   	function() {
   		dk_JsHttpRequest_pswd();
//   		$('#auth_block').hide();
//   		setTimeout(function(){document.location.reload(true);},5000);
   	});
   	
   	$('#auth_block .b-close').click(function(){
   		$('#auth_block').hide();
   	});

   	$('#pswd').focus(function(){
   		dk_JsHttpRequest_login();
   	})
   	.keyup(function(event){
   		try {
   			if(event.keyCode==13)
    			document.getElementById('login_form_partner').submit();
   		} catch (e) {};

   	});

	if ($('#filter-button').length) {
	   	$('#filter-button').click(function(){
			if ($('#price_interval_max').length) {

				price_interval_min = ( $('#price_interval_min').attr('value') == '' ) ? 0 : parseInt($('#price_interval_min').attr('value'))  ;

				if (!(/^\d*$/.test(price_interval_min))) {
		   			alert('Значение поля «Цена От» должно быть целым числом.');
		   			return false;
				}
				price_interval_max = ( $('#price_interval_max').attr('value') == '' ) ? 1000000000000000 : parseInt($('#price_interval_max').attr('value'))  ;
				if (!(/^\d*$/.test(price_interval_max))) {
		   			alert('Значение поля «Цена До» должно быть целым числом.');
		   			return false;
				}

		   		if (price_interval_max < price_interval_min) {
		   			alert('Поле «Цена От» должно быть меньше по значению поля «Цена До».');
		   			return false;
		   		}
			}
			return true;
	   	});
	}


    $('.b-telephone-list li .b-minus').live("click",function(){
    	$(this).parent().remove();
    });
    $('.b-delete-phone').eq('0').click(function(){
    	var l=$('.b-telephone-list li').length+1;
    	$('.b-telephone-list').append('<li><input id="inp'+l+'" name="number'+l+'" value="" class="number"><img class="b-minus" src="'+siteURL+'/im/minus-2.png" title="Удалить телефон" alt="Удалить телефон"/></li>');

    	//$('.b-telephone-list')
    	return false;
    });
	//cabinet archive
	$('#make-archive').click(function(){
		if (!confirm('Архивировать выбранные объявления?')) return false;
		if ($(this).hasClass('b-disabled'))
		return false;
		var checkedArray=new Array();
		$('.b-cabinet-adverts-list tbody .b-input input:checked').each(function(){
			checkedArray.push($(this).attr('id'));
		});
		//alert(checkedArray);
		$.post(siteURL+'/ajax/archive.php',{ch:[checkedArray]},function(data){
			alert(data);
			window.location.href = siteURL+'/cabinet/';
			//window.location.reload();
		});

		return false;
	});

	$('.changeRows').click(function(){
		$.cookie('informetr_cabinet_rows', ($(this).html() == 'Все') ? 1000000 : $(this).html() , {path:'/'});
		//window.location.href = window.location.href;
//		window.location.href = siteURL+'/cabinet/';
		//return false;
	});

	$('#my_adverts_list').click(function(){
		//alert('Reset cookie');
		if ($.cookie('informetr_cabinet_rows') == null)	
			$.cookie('informetr_cabinet_rows', 20 , {path:'/'});
		if ($.cookie('informetr_cabinet_section_1') == null)	
			$.cookie('informetr_cabinet_section_1', 1 , {path:'/'});
		if ($.cookie('informetr_cabinet_section_2') == null)	
			$.cookie('informetr_cabinet_section_2', 1 , {path:'/'});
		if ($.cookie('informetr_cabinet_section_3') == null)	
			$.cookie('informetr_cabinet_section_3', 1 , {path:'/'});
		if ($.cookie('informetr_cabinet_section_4') == null)	
			$.cookie('informetr_cabinet_section_4', 1 , {path:'/'});
		if ($.cookie('informetr_cabinet_section_5') == null)	
			$.cookie('informetr_cabinet_section_5', 1 , {path:'/'});
		if ($.cookie('informetr_cabinet_section_6') == null)	
			$.cookie('informetr_cabinet_section_6', 1 , {path:'/'});
		if ($.cookie('informetr_cabinet_order') == null)	
			$.cookie('informetr_cabinet_order', 2 , {path:'/'});
		if ($.cookie('informetr_cabinet_sort') == null)	
			$.cookie('informetr_cabinet_sort', 1 , {path:'/'});
		window.location.href = siteURL+'/cabinet/';
		return false;
	});

	$('#order_1').click(function() {
		$.cookie('informetr_cabinet_order', 1, {path:'/'});
		var sort = $.cookie('informetr_cabinet_sort');
		sort = (sort == 1) ? 0 : 1;
		$.cookie('informetr_cabinet_sort', sort, {path:'/'});
		window.location.href = siteURL+'/cabinet/';
		return false;
	});

	$('#order_2').click(function() {
		$.cookie('informetr_cabinet_order', 2, {path:'/'});
		var sort = $.cookie('informetr_cabinet_sort');
		sort = (sort == 1) ? 0 : 1;
		$.cookie('informetr_cabinet_sort', sort, {path:'/'});
		window.location.href = siteURL+'/cabinet/';
		return false;
	});

	$('#prolong').click(function(){

//		if (!confirm('Продлить выбранные объявления '+$('#period :selected').text()+'?')) return false;

		if ($(this).hasClass('b-disabled'))
		return false;

		var actual_checked = false;
		var checkedArray = new Array();
		$('.b-cabinet-adverts-list tbody .b-input input:checked').each(function(){
//			checkedArray.push($(this).attr('id'));
			if ($(this).parent().parent().attr('class') == 'b-expiring') {
				checkedArray.push($(this).attr('id'));
			} else {
				actual_checked = true;
			}
		});

		//if (actual_checked) alert('Продлению подлежат объявления с истекающим сроком размещения.');

		var selPeriod=$('#period').attr('value');
		$.post(siteURL+'/ajax/prolong.php',{ch:[checkedArray], selPeriod:selPeriod, actual_checked:actual_checked},function(data){

			//alert('Re');
			alert(data);
//			window.location.reload();
			window.location.href = siteURL+'/cabinet/';
		});

		return false;
	});
	$('.b-switching .b-switcher .b-item').click(function(){
		if ($(this).hasClass('b-selected')) return false;

		var allSwitchItems=$('.b-switching .b-switcher .b-item');

		allSwitchItems.filter('.b-selected').removeClass('b-selected');

		$(this).addClass('b-selected');
		var index=$('.b-switching .b-switcher .b-item').index($(this));
		var allItems=$(this).parents('.b-switching').find('.b-switch-item');
		$(this).parents('.b-switching').find('.b-switch-item').hide();
		allItems.eq(index).show();

	});

	//$('.b-cabinet-layout .g-block1').css('bottom',$('body').height()-$('.b-cabinet-layout .g-block1').height()-$('.b-cabinet-layout .b-cabinet-header').height()-140);

	$('#section-choice a:not(".b-close")').click(function(){
		var parent=$(this).parent();
		if (parent.parent().attr('class') == 'choose_issue') return true;

		$('#section-choice li').css('z-index',1);
		parent.css('z-index','1000');
		$('.b-choice-popup').hide();
		var me=$(this);
		setTimeout(function(){$.scrollTo(me, 400, {queue:true,axis:'y'})},200);
		parent.find('.b-choice-popup').toggle();

		return false;
	});

	$('body').bind('click',function(){
         $('.b-choice-popup').hide();
     });
     $('.b-choice-popup').click(function(e){
        e.stopPropagation();
     });
	 $('.b-choice-popup .b-close').click(function(){
		$(this).parents('.b-choice-popup').hide();

		return false;
	 });

	$('#form_ask #theme_select select').change(function(){
	 	if ($(this).find('option:selected').attr('value')==9) {
	 		$('#form_ask .b-unvisible').show();
	 	}
	 	else {
	 		if ($('#form_ask .b-unvisible').is(':visible')){
	 			$('#form_ask .b-unvisible').hide();
	 		}
	 	}
	 });
	 $('.code-field').each(function(){
      var target=$(this);
      $(this).click(function(){
          target[0].select();
      });

   });

   var textareaFlag=true;
   function trim(str, charlist){
   	charlist = !charlist ? ' \s\xA0' : charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '\$1');
	var re = new RegExp('^[' + charlist + ']+|[' + charlist + ']+$', 'g');
	return str.replace(re, '');
   }
   $('#adv_info .send-message').click(function(){
		
   		var yScroll=0;
		var leaveForm;
		 
	
		yScroll = self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);

		if (self.innerHeight) { // all except Explorer
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers

			windowHeight = document.body.clientHeight;
		}
		$('.message-area').val('Знаете название агентства — напишите');
		leaveForm=$('.b-leave-message').detach();
		leaveForm.appendTo('body');
   		$('.b-leave-message').css({top:yScroll-40+(windowHeight-$('.b-leave-message').height())/2+'px'}).show();
   		$('#abstractadvert_message_form').show();
   		$('.success').hide();
		//$('#abstractadvert_message_form').submit(function(){

		$('#send-button').live('click',function(){

   		 	if (textareaFlag||($('.message-area').val()=='')||(!$.trim($('.message-area').val()).length)) {

   		 		$('.b-leave-message .b-error').slideDown();
   		 		return false;
   		 		}

			$('#abstractadvert_message_form').hide();

			var pageHref = senderName = senderText = '';
			//alert(siteURL);
			senderText = $('#msg').attr('value');
			pageHref = window.location.toString();



           	$.post(siteURL + '/ajax/partnerspy.php', {senderText:senderText, pageHref:pageHref}, function(data){
				//alert(data);
				$('.success').show();
				$('.b-message .b-error').slideUp();
 				return false;
         	});

 			return false;


	   });
   		return false;
   });

   $('.b-feedback a, .b-in-house-help a').click(function(){


		$('#success_div').hide();
		$('#help_form').show();
		button_disable();
   		var yScroll=0;

		yScroll = self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);

		if (self.innerHeight) { // all except Explorer
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers

			windowHeight = document.body.clientHeight;
		}
   		$('.b-message').css({top:yScroll-90+(windowHeight-$('.b-message').height())/2+'px'}).show();
   		return false;
   });

 $('.message-input[name=phone_field], #offer-msg').keyup(function(){
		$('#offer-msg').css('display','block');
		if(($.trim($('.message-input[name=phone_field]').val()).length>0)&&($.trim($('#offer-msg').val()).length>0)) {	
			button_enable();
			} else button_disable();
   });


   $('.close-form').live('click',function(){
   		$('.b-message').hide();
   		$('.b-message .b-error').hide();
   		textareaFlag=true;
   });

    $('.close-help-form').live('click',function(){
   		$('.b-message').hide();
   		$('.b-message .b-error').hide();
   		textareaFlag=true;
		$('#success_div').hide();
		$('#help_form').show();
   });

   $('.message-area').live('focus', function(){
   		$(this).val('');
   		$('.b-message .b-error').slideUp();
   		textareaFlag=false;
   });

   if ($('#ref_garage_id').length != 0) {
	   $('#ref_realty_type_id').change(function(){
	   		label = $('#ref_garage_id').parent().find('span').eq('0');
	   		var dt = $('#ref_deal_type_id').val();
	   		if (
	   				($(this).val() == '3' || $(this).val() == '20')
	   // при типах сделки "Сниму" и "Куплю" поле "Общество" не обязательное
	   				&& (dt != '32' && dt != '9' && dt != '29' && dt != '6')
	   			) {
	   			if (label.attr('class') == 'g-not-required-title') {
		   			str = label.text();
		   			label.html('<nobr>'+str+'*</nobr>');
		   			label.removeClass('g-not-required-title').addClass('g-required-title');
	   			}
	   		} else {
	   			str = label.html().replace('*', '');
	   			label.html(str);
	   			label.removeClass('g-required-title').addClass('g-not-required-title');
	   		}
	   });
   }

//new-mesage-popup
	$('.new .b-innovation-link').click(function(){
		$.cookie('lastMessageSeen', 1 , {expires: 1000, path:'/'});
		if ($('.b-new-message').css('display')=='none') $('.b-new-message').show();
		return false;
	});


	$('.b-new-message-close, .b-new-message-content .b-innovation-link').click(function(){
		$.cookie('lastMessageSeen', 1 , {expires: 1000, path:'/'});
		$('.b-new-message').hide();
		return false;
	});
//hide-open answer
	$('.b-message_list ins').click(function(){
		hide_open_answer($(this).parent());
	});
	$('.b-message_list span').click(function(){
		hide_open_answer($(this).parent());
	});
	$('.cabinet-message dd').click(function(){
		$.cookie('lastMessageSeen', 1 , {expires: 1000, path:'/'});
		if ($('.b-message_list dt:first').hasClass('answer-hidden')) {
			hide_open_answer($('.b-message_list dt:first'));
			$('.b-new-message').hide();
			}
		else{
		$('.b-new-message').hide();
		}
	});
//hide-open all answer
	$('.cabinet-message-menu .b-innovation-link').click(function(){
		if ($(this).hasClass('open-all')) {
			hide_open_answer($('.b-message_list dt.answer-hidden'));
			$(this).toggleClass('open-all');
			$(this).toggleClass('close-all');
			$(this).empty();
			$(this).append('Скрыть все сообщения');
		}
		else{
			hide_open_answer($('.b-message_list dt.answer-opened'));
			$(this).toggleClass('close-all');
			$(this).toggleClass('open-all');
			$(this).empty();
			$(this).append('Открыть все сообщения');
		}
	});

   	$('#ref_garage_id').change(function(){

   		ref_garage_id = $('#ref_garage_id').val();

       	$.post(siteURL + '/ajax/garagestreet.php', {ref_garage_id:ref_garage_id}, function(data){
			street_id = data;
			$('#street_id').val(street_id);
			return false;
     	});

   	});

   	if ($('#ref_land_category_id').length != 0) {

   		if ($('#ref_realty_type_id').val() != '49' && $('#ref_realty_type_id').val() != '66') {
			$('#ref_land_category_id').val(0);
			$('#ref_land_category_id').attr('disabled', 'disabled');
   		}

		$('#ref_realty_type_id').change(function(){

	   		//alert($(this).val());
			label = $('#ref_land_category_id').parent().find('span').eq('0');
	   		var dt = $('#ref_deal_type_id').val();
			if ($(this).val() == '49' || $(this).val() == '66') {
				$('#ref_land_category_id').removeAttr('disabled');
		   		if (
		   				// при типах сделки "Сниму" и "Куплю" поле "Категория земль" не обязательное
		   				(dt == '43' || dt == '20' || dt == '45' || dt == '22')
				) {
					if (label.attr('class') == 'g-required-title') {
						str = label.html().replace('*', '');
						label.html(str);
						label.removeClass('g-required-title').addClass('g-not-required-title');
					}
				} else {
					if (label.attr('class') == 'g-not-required-title') {
						str = label.text();
						label.html('<nobr>'+str+'*</nobr>');
						label.removeClass('g-not-required-title').addClass('g-required-title');
					}
				}
			} else {
				$('#ref_land_category_id').val(0);
				$('#ref_land_category_id').attr('disabled', 'disabled');
				str = label.html().replace('*', '');
				label.html(str);
				label.removeClass('g-required-title').addClass('g-not-required-title');
			}


		});

   	}

   	if ($('#house_id').length != 0) {
   		$('#house_id').change(function(){

   			var houseId = 	$(this).val();
   			//alert(houseId);
			$.post(siteURL+'/ajax/microdistrict.php',{house_id:houseId},function(data){
				//alert(data);
				$('#ref_microdistrict_id').val(data);
			});
   		});
   	}

   	if ($('#ref_microdistrict_id').length != 0) {
   		$('#city_id').change(function(){
			if ($(this).val() != 1) {
				$('#ref_microdistrict_id').val(0);
				$('#ref_microdistrict_id').attr('disabled', 'disabled');
			} else {
				$('#ref_microdistrict_id').removeAttr('disabled');
			}
   		});
   	}


	if ($('.b-message').hasClass('nojs-form')){
		$('.nojs-form').removeClass('nojs-form');
		var yScroll=0;
setTimeout(function(){
			yScroll = self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);

			if (self.innerHeight) { // all except Explorer
				windowHeight = self.innerHeight;
			} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
				windowHeight = document.documentElement.clientHeight;
			} else if (document.body) { // other Explorers

				windowHeight = document.body.clientHeight;
			}

		yPosition=yScroll-90+(windowHeight-$('.b-message').height())/2;
			//var yPosition=$('#feedback').offset().top-$('.b-message').height()-50-$('#feedback').height();

				$('.b-message').css('top',yPosition+'px').show();
		},500);




	}

$('#ttree .b-tree-icon').click(function(){
	var icon=$(this);
	var innerList=icon.parent().children('.b-tree-inner-list');
	if (innerList.is(':hidden')) {
		innerList.show();
		icon.addClass('b-tree-icon-open');
	}
	else {
	innerList.hide();
	icon.removeClass('b-tree-icon-open');
	}
})

$('.add-to-notepad').click(function(){
	var me=$(this);
		if(me.hasClass('add-to-notepad')){
			me.removeClass('add-to-notepad');
			me.addClass('added-to-notepad');
			if (me.hasClass('notepad_inner')) me.find('.notepad-text').replaceWith('<span class="notepad-text">Добавлено в блокнот </span>');
		}
		else {
			me.removeClass('added-to-notepad');
			me.addClass('add-to-notepad');
			if (me.hasClass('notepad_inner')) me.find('.notepad-text').replaceWith('<span class="notepad-text">Добавить в блокнот </span>');
		}
});
});






