function debug(string){

	if($.browser.msie)
		return false;

	if(typeof(console) == "object")
		console.log(string);
	return false;
}
/*
jQuery.each(jQuery.browser, function(i, val) {
      if(val == true)
      alert(i);
    });
*/

var activeAction = false;

var DropicusSystem = function(jElement){

	var isActive = false;
	var isHovered = false;
	var blocks = '<div id="dropicus" class="hidden">'+
        '<div class="t">'+
            '<div class="l">'+
                '<div class="dropicus_content">'+
                '</div>'+
            '</div>'+
            '<ins class="r"></ins>'+
            '<ins class="clear"></ins>'+
        '</div>'+
        '<ins class="b"><ins class="r"></ins></ins>'+
        '<ins class="real_close_button"></ins>'+
    '<div class="closebutton hidden"></div></div>';

	var dropicus = [];
	var body = $('body');
	var maxWidth = 300;

	$('.dropicus').each(function(){

		if($c.browser.opera)
			$(this).find('.iconus').addClass('opera');

		$(this).click(function(){
			return fOpen($(this));
		});
		dropicus.push($(this));
	});

	body.append(blocks);
	var 	jDropicus = $('#dropicus'),
			jContent = jDropicus.find('.dropicus_content'),
			jButton = jDropicus.find('.closebutton');

	jButton.hover(function(){$(this).addClass('hover')},function(){$(this).removeClass('hover')}).click(function(){fClose();return false});

	$(document).click(function() {
		if (isActive == true && isHovered == false) fClose();
	});

	function fOpen(jLinks)
	{
		if(jLinks.hasClass('pseudo'))
		{
			isActive = true;
			isHovered = true;

			jDropicus.removeClass('hidden');
			jContent.html('<div class="caption">'+jLinks.html()+'</div><div class="clear"></div>'+jLinks.prev().html());
			LoginFormsControl(jContent.find('form.login_form'));


			var iWidth = 20;
			var tlWidth = jDropicus.find('.t .l');
			var tWidth = jDropicus.find('.t');
			var bWidth = jDropicus.find('.b');

			if(jLinks.hasClass('closed'))
			{
				jButton.removeClass('hidden');
			}
			else
			{
				jButton.addClass('hidden');
			}

			jDropicus.hover(function(){isHovered=true;},function(){isHovered=false;})

			jDropicus.find('.caption').click(function(){fClose();return false;});
			jDropicus.find('.caption').hover(function(){$(this).addClass('hover')},function(){$(this).removeClass('hover')});

			jDropicus.find('label.clickable').click(function(){

				var input = $(this).parent().find('input[type=radio],input[type=checkbox]');
				(input.attr('checked'))?input.attr('checked',false):input.attr('checked',true);

			}).disableTextSelect();

			var y = jLinks.parents('.dropicus_parent').offset().top -3;
			var x = jLinks.offset().left - 8;

			//Дефолтим элементы
			jDropicus.removeAttr('style');
			tlWidth.removeAttr('style');
			tWidth.removeAttr('style');
			bWidth.removeAttr('style');

			if ($c.browser.msie) {
				jDropicus.find('.t .r').css('zoom', '2');
			}

			jContent.children().each(function() {

				if(typeof(jLinks.attr('id')) == 'string')
					$(this).addClass(jLinks.attr('id'));

				var elWidth = $(this).width();
				if(typeof(elWidth) == 'number')
				{

					if (elWidth > iWidth) iWidth = elWidth;

					if(iWidth > maxWidth || $(this).hasClass('max'))
					{
						$(this).width(maxWidth);
						iWidth = maxWidth;
					}
				}
			});

			if (($c.browser.msie && parseInt($c.browser.version) >= 6)) {
				tlWidth.css('z-index','1')
				tWidth.width(iWidth+27);
				tlWidth.width(iWidth);
				bWidth.width(iWidth+16);
			}
			else if($c.browser.opera)
			{
				tlWidth.css('z-index','1')
				tWidth.width(iWidth+21);
				tlWidth.width(iWidth);
				bWidth.width(iWidth+16);
			}
			//else if($c.browser.)

			//выравнивание справа
			if(x+iWidth > body.width())
			{
				jDropicus.addClass('right');
				jDropicus.css({'top':parseInt(y),'right':parseInt(body.width() - (x+jLinks.width())-19)});
				jDropicus.find('.caption').css({'text-align':'right'});
			}
			else
			{
				jDropicus.removeClass('right');
				jDropicus.css({'top':parseInt(y),'left':parseInt(x)});
			}
			return false;
		}
		else
		{
			//Переходим по ссылке, если нет класса pseudo
			return true;
		}
		return false;
	}

	function fClose()
	{
		isActive = false;
		jDropicus.addClass('hidden');
		return false;
	}

}

var LoginFormsControl = function(loginforms) {
	loginforms.each(function(){
		var log = $(this).find('input:first'), pass = $(this).find('input:eq(1)').parents('tr'), regcheck = $(this).find('input:eq(3)'), f = $(this),
		old_action = f.attr('action'), back = $(document.createElement('INPUT')).attr({type:'hidden', value:window.location.href, name: 'back'}),
		domain = $(document.createElement('INPUT')).attr({type:'hidden', value:'', name: 'domain'});
		regcheck.change(function(){
			pass[this.checked? 'hide' : 'show']();
		}).change().parent().show();

		f.submit(function(){
			if (/^[^@]+@?$/.test(log.attr('value'))) log.attr('value',log.attr('value').replace('@','')+'@rambler.ru');
			if (/(@rambler\.ru|@myrambler\.ru|@lenta\.ru|@autorambler\.ru|@ro\.ru|@r0\.ru)/.test(log.attr('value'))) {
				f.attr('action', 'http://id.rambler.ru/script/auth.cgi?mode=login');
				if(regcheck[0].checked) {
					var dialog_res = confirm('Домотека — проект Рамблера. Если "' + log.attr('value') + '" — это Ваш уже зарегистрированый E-mail, просто снимите '
						+ 'галочку "регистрация", введите пароль и мы Вас пустим.\n'
						+ 'Если же Вы хотите зарегистрироваться на Рамблере, нажмите ОК. Если хотите остаться на этой странице и использовать другой E-mail, нажмите Отмену')
					if(dialog_res) {
						f.attr({
							action: 'http://id.rambler.ru/script/newuser.cgi?back_immediate=1',
							method: 'post'
						})
					} else {
						return false;
					}
				}

				domain.attr('value',log.attr('value').split('@')[1]);
				f.append(domain);
				if(f.find('input[name=back]').length == 0)
					f.append(back);
				else {
					var input = f.find('input[name=back]');
					if(input.val()[0] == '/')
						input.val('http://' + window.location.host + input.val());
				}

				log.attr('name','login');
				pass.find('input').attr('name','passw');
				return;
			}
			regcheck[0].checked? f.attr('action','/d_user/signup') : f.attr('action', old_action);
			return;
		})
	})
}



var CustomSimpleDropdown = function(jElement){
	var
		jPseudoLink = jElement.find('span.pseudo'),
		jDropCont = jElement.find('.dropdown_ul'),
		jTimeout = 0,
		bDropOpen = false;

	$(document).click(
		function(){
			jDropCont.removeClass('dropdown_active_ul');
		}
	);

	jPseudoLink.click(
		function(e){
			e.preventDefault();
			e.stopPropagation();
			jDropCont.toggleClass('dropdown_active_ul');
		}
	);

	jDropCont.mouseenter(dropContEnter);
	jDropCont.mouseleave(dropContLeave);

	function dropContEnter(e){
		clearTimeout(jTimeout);
	};
	function dropContLeave(e){
		jTimeout = setTimeout(function(){jDropCont.removeClass('dropdown_active_ul');}, 800);
	};
};

//Масив, в который заполняются элементы panel control
var aPanelControls = [];
//
var iActivePanelControl = -1;
//Обработчик контейнеров .panel_control которые преобразуются в селекты
var PanelControl = function(jElement, iNum) {
	//Текущий контейнер
	var c;
	var jControl = $(this);
	var
		//Берем элемент .value внутри контейнера
		jValue = jElement.find('.value'),
		//Берем элемент .list
		jList = jElement.find('.list'),
		//Берем элемент закрывающий список.
		jCloseBtn = jElement.find('.close_button'),

		iNum = iNum,
		//Кнопка для обработки нажатия
		jButton = jElement.find('button');

	//Если список пуст или содержит одну строку
	if(typeof(jList) != undefined && jList.find('label a span').length == 1)
	{
		jElement.addClass('noselect');
		return;
	}

	jList.find('label').parent().prepend('<label class="list_caption"><a><span><input class="item" type="radio" name="" value=""/></span></a></label>');

	if(jElement.find('.real_close_button').length > 0)
	{
		jElement.find('.real_close_button').hover(function(){$(this).addClass('hover')},function(){$(this).removeClass('hover')}).click(function(){hide()});
	}

	/*Фикс перевода строк в ие*/
	if ($c.browser.msie && parseInt($c.browser.version) > 6) {
		jElement.find('.value .t .l').css('width',((jElement.find('.value .t .l a').text().length*0.55)+1)+'em');
		jElement.find('.value .t').css('width',(jElement.find('.value .t .l').width()+20)+"px");

		$(window).resize(function(){
			jElement.find('.value .t .l').css('width',((jElement.find('.value .t .l a').text().length*0.55)+1)+'em');
			jElement.find('.value .t').css('width',(jElement.find('.value .t .l').width()+20)+"px");
		});
	}


	//Перемещаем стрелку
	jCloseBtn.css('left',(jValue.find('.arr').offset().left - jValue.offset().left + 3)+'px');

	/* events */
	// whole page -- close list if there's a list open
	$(document).click(function() {
		if (iActivePanelControl >= 0) aPanelControls[iActivePanelControl].hide();
	});
	// closed item -- show
	jValue.click(function(e) {
		e.stopPropagation();
		show();
	});
	// list -- cancel clicks on white fields
	jList.click(function(e) {
		e.stopPropagation();
	});

	// Обработка текстовых полей
	jList.find('label, label input[type=text]').each(function() {

		$(this).click(function(e) {
			e.preventDefault();
			e.stopPropagation();
		});
		$(this).blur(function(e) {
			selectItem($(this).parents('label').find('a span'), true);
		});
		$(this).keypress(function(e) {
			c = e.which ? e.which : e.keyCode;
			if (c == 13) {
				e.preventDefault();
				selectItem($(this).parents('label').find('a span'), false);
			}
			return checkNumKeys(e);
		});
		$(this).keydown(function(e) {
			return checkNumKeys(e);
		});
	});

	// list items
	jList.find('label a span').each(function() {
		if($(this).hasClass('terminated'))
		{
			$(this).click(function(e) {
				e.stopPropagation();
				e.preventDefault();
				$(this).parents('.panel_control').next().addClass('hidden');
				selectItem($(this), false);
			});
		}
		else if($(this).hasClass('determinated'))
		{
			$(this).click(function(e) {
				e.stopPropagation();
				e.preventDefault();
				$(this).parents('.panel_control').next().removeClass('hidden');
				selectItem($(this), false);
			});
		}
		else
		{
			$(this).click(function(e) {
				e.stopPropagation();
				e.preventDefault();
				selectItem($(this), false);
			});
		}
	});

	// close button
	jCloseBtn.click(function(e) {
		hide();
	});

	//Обработка нажатия кнопки
	jButton.click(function(e){
		jElement.addClass('press');
		setTimeout(function(){jElement.removeClass('press');return true;}, 500);
	});


	jList.find('.t').scroll(function(){this.scrollTop = 0;});

	if(iNum == 0)
	{
		setTimeout(function(){updateResults()},500);
	}

	/* methods */
	function show() {

		if (iActivePanelControl != iNum) {
			if (iActivePanelControl >= 0) aPanelControls[iActivePanelControl].hide();
			iActivePanelControl = iNum;

			jElement.addClass('panel_active');

			jCloseBtn.css('left',(jValue.find('.arr').offset().left - jValue.offset().left + 3)+'px');
			var selected = jList.find('a.selected input');
			jList.find('.list_caption span').html('<input class="item" type="radio" name="'+selected.attr("name")+'" value="'+selected.attr('value')+'" />'+jValue.find('span').html());

			if ($c.browser.msie) {
				jElement.find('.list .t .r').css('zoom', '2');
			}
			if (($c.browser.msie && parseInt($c.browser.version) >= 6) || $c.browser.opera) {
				var iWidth = 20;
				jElement.find('.list a, .list label ins, table, .list .notes').each(function() {
					if ($(this).width() > iWidth) iWidth = $(this).width();
					if ($c.browser.opera && $(this).hasClass('notes')) iWidth = iWidth+3;
				});
				jList.css('z-index','1000');
				jElement.find('.list .t').css('width', (iWidth + 36) + 'px');
				jElement.find('.list .t .l').css('width', (iWidth) + 'px');

			}

			if ($c.browser.msie) {
				jElement.find('.list .t .r').css('zoom', '1');
			}

		}

		if($c.browser.msie && $('#search_catalog_results').length > 0)
		{
			new TableSelectus($('#search_catalog_results'));
		}

	};

	function hide() {

		iActivePanelControl = -1;
		jElement.removeClass('panel_active');

		/*Фикс перевода строк в ие*/
		if ($c.browser.msie && parseInt($c.browser.version) > 6 || $c.browser.opera) {

			jElement.find('.value .t .l').css('width',((jElement.find('.value .t .l a').text().length*(0.55-(jElement.find('.value .t .l a').text().length/6*0.01)))+1)+'em');
			jElement.find('.value .t').css('width',(jElement.find('.value .t .l').width()+20)+"px");
		}

		if($c.browser.msie && $('#search_catalog_results').length > 0)
		{
			new TableSelectus($('#search_catalog_results'));
		}
	};

	function selectItem(jInnerElement, bNotHide) {

		if (jInnerElement.length) {
			var jInput = jInnerElement.parents('label').find('input[type=radio]').eq(0);
			var jIntervalEl = jInnerElement.parents('label').find('input[type=text]');
			var jAfterRazm = jInnerElement.parents('label').find('span.aftr');

			//Единицы счисления после сложныхэлементов
			var razm = '<span class="rur">р</span>';
			if(jAfterRazm.length == 1) razm = jAfterRazm.html();

			if(jInnerElement.parents('label').hasClass('list_caption'))
			{
				hide();
				return true;
			}

			//
			var jSecret = jInnerElement.parents('label').find('.secret_bugs input[type=checkbox]');
			if(jInput.hasClass('ch_terminator'))
			{
				jList.find('.secret_bugs input[type=checkbox]').attr('checked',false);
			}
			if(jSecret.length > 0)
			{
				jSecret.attr('checked',true);

			}

			if (!jInput.get(0).checked || jIntervalEl.length) {
				jInput.get(0).checked = true;

				jList.find('a').removeClass('selected');
				jInput.parents('a').eq(0).addClass('selected');

				if (jIntervalEl.length == 2) {
					var _one = formatPrice(jIntervalEl.get(0).value);
					var _two = formatPrice(jIntervalEl.get(1).value);

					debug(_one +" -- "+_two);

					if((_one == 0 || _one == '') && (_two == 0 || _two == '')){
						jValue.find('a span').text('за любую сумму');
					}
					else if(_one == 0 || _one == ''){
						jValue.find('a span').html(jInnerElement.text() + ' до '+_two+razm);
					}
					else if (_two == 0 || _two == ''){
						jValue.find('a span').html(jInnerElement.text() + ' от '+_one+razm);
					}
					else {
						jValue.find('a span').html(jInnerElement.text() + ' ' + _one + ' – ' + _two+razm);
					}
				}
				else if(jIntervalEl.length == 1)
				{
					var _one = formatPrice(jIntervalEl.get(0).value);
					jValue.find('a span').html(jInnerElement.text() + ' ' + _one+razm);
				}
				else {
					jValue.find('a span').text(jInnerElement.text());
				}
				updateResults();

				if(jIntervalEl.length > 0)
				{
					//jElement.css('width',jInnerElement.parents('ins').width()+15);
					//jValue.find('.t .l').css('width',jInnerElement.parents('ins').width()+15);
					//jValue.find('.b').css('width',jInnerElement.parents('ins').width()+26);
				}
				else
				{
					//jElement.css('width',jInnerElement.parents('a').width()+15);
					//jValue.find('.t .l').css('width',jInnerElement.parents('a').width()+15);
					//jValue.find('.b').css('width',jInnerElement.parents('a').width()+26);
				}

			}
			if (!bNotHide) hide();
		}
	};

	function updateResults() {

		var eFormEl = jElement.parents('.main_filter');
		var gForm = eFormEl;

		if(eFormEl.length < 1)
			return false;

		eFormEl = eFormEl.find('input');

		var hValues = {}
		for (var i = 0; i < eFormEl.length; i++) {
			switch (eFormEl[i].type) {
				case 'radio':
					if (eFormEl[i].checked) hValues[eFormEl[i].name] = eFormEl[i].value;
					break;
				case 'text':
					hValues[eFormEl[i].name] = eFormEl[i].value;
			}
		}

		$.ajax({
			type: "GET",
			url: url_getSearchResultsCount,
			data: hValues,
			dataType: "json",
			success: function(data) {

				gForm.find('.found .number').text(data.results);


				if(data.results == 0)
				{
					gForm.find('.button').addClass('disable');
	            	gForm.find('.button button').attr('disabled', 'disabled');
				}
	            else
	            {
					gForm.find('.button').removeClass('disable');
	            	gForm.find('.button button').removeAttr('disabled');
	            }

				if($c.browser.msie && $('#search_catalog_results').length > 0)
				{
					new TableSelectus($('#search_catalog_results'));
				}

				return false;
			}
		});
		return false;

	};

	function checkNumKeys(evt) {
		var bWrongChar = true;
		var iKeyCode = evt.keyCode;
		var sType = evt.type;
		var bKeypress = (sType == 'keypress');

		var bCtrlKey = evt.ctrlKey || evt.metaKey;
		var bShiftKey = evt.shiftKey;
		if (iKeyCode == 0 || iKeyCode == 8 || iKeyCode == 9 || iKeyCode == 12 || iKeyCode == 16 || iKeyCode == 17 || iKeyCode == 18 || iKeyCode == 33 || iKeyCode == 34 || iKeyCode == 35 || iKeyCode == 36 || iKeyCode == 37 || iKeyCode == 38 || iKeyCode == 39 || iKeyCode == 40 || (iKeyCode == 46 && !window.opera) ||	(iKeyCode > 47 && iKeyCode < 58) || (iKeyCode > 95 && iKeyCode < 106 && !bKeypress) || iKeyCode == 91 || iKeyCode == 224 ) bWrongChar = false;

		if ( (bCtrlKey && iKeyCode == 65) || (bCtrlKey && iKeyCode == 67) || (bCtrlKey && iKeyCode == 86) || (bCtrlKey && iKeyCode == 88) ) bWrongChar = false;

		if ( (bShiftKey && (iKeyCode > 47 && iKeyCode < 58)) ) bWrongChar = true;

		if (bWrongChar) {
			evt.returnValue = false;
			evt.cancelBubble = true;
			if (evt.preventDefault) evt.preventDefault();
			return false;
		}
		return true;
	};

	function formatPrice(num){
		var re=/^(\d+)([\.,](\d+))?$/;
		var _m, str=new String(num);
		if((_m = str.match(re))) {
			var _int = _m[1];
			if (Number(_int) < 10000) return _int;
			else {
				var new_num='';
				var i;
				for(i = 1; i * 3< _int.length; i++)
					new_num = ' ' + _int.substring(_int.length - i * 3, _int.length - (i - 1) * 3) + new_num;
				return _int.substr(0, 3 - i * 3 + _int.length) + new_num;
			}
		} else return str;
	};

	return {
		iNum: iNum,
		show: show,
		hide: hide
	};
}





/**
 * Двигающаяся машинка
 * @param {} jElement
 */
var jCarLeftPosition = 0;
var HomePageSlider = function(jElement){
	var
		jScroll = jElement.find('.object_wrapper_top_scroll'),
		jContent = jElement.find('.object_wrapper table'),
		jMargin = jElement.find('.object_wrapper_2'),
		jFaderHeight = jElement.find('.object_wrapper'),
		jCar = $('#race_car'),
		iMovingWidth = 0,
		iScrollWidth = 0;
	var jCarImg = jCar.find('.race_car_img');
	var jInnerDiv = jScroll.find('div');
	var jFade = jElement.find('.object_fader');

	/*Rie: Убираем машинку, если скролл не нужен*/
	if(jContent.width() < jScroll.width())
		return;

	jCar.show();
	jInnerDiv.width(jContent.width() + (parseInt(jMargin.css('marginLeft'))) * 2);
	jCar.css('top', (jInnerDiv.height() - 22) + 'px');

	centerCar();

	$(window).resize(function(){
		centerCar();
	});

	if($c.browser.msie)
		jFade.height(jFaderHeight.height());



	var TimeId;
	var jCarLeftPosition=0;
	jScroll.scroll(function() {
		jContent.css(
			{
				left: -jScroll[0].scrollLeft
			}
		);

		var jCarPosition = jCar.position();
		var ScrollLap = parseInt(jScroll[0].scrollLeft / iScrollWidth * iMovingWidth);
		var CarPath = ScrollLap - jCarPosition.left;

		//if(($c.browser.version > 9.5 && ($c.browser.opera)) || !$c.browser.opera)
		/*{
			if(CarPath <= 0 && jCarImg.attr('class') != 'race_car_img ')
			{
				jCarImg.addClass('invert');
			}
			else if(CarPath > 0 && jCarImg.attr('class') == 'race_car_img invert')
			{
				jCarImg.removeClass('invert');
			}

			clearTimeout(TimeId);
			jCar.stop();
			TimeId = setTimeout(function(){jCar.animate({ left: ScrollLap }, "500");return true;});
		//}*/
		//else
		//{
			if(jCarPosition.left < jCarLeftPosition && jCarImg.attr('class') != 'race_car_img ')
			{
				jCarImg.addClass('invert');
			}
			else if(jCarPosition.left > jCarLeftPosition && jCarImg.attr('class') == 'race_car_img invert')
			{
				jCarImg.removeClass('invert');
			}
			jCarLeftPosition = jCarPosition.left;

			jCar.css('left', ScrollLap);
		//}
	});

	$c.measurer.bind(centerCar);
	function centerCar() {
		var k = ($.browser.mozilla)? 0.9 : 1;

		if (jScroll.width() > jInnerDiv.width()) jCar.width(jScroll.width());
		else jCar.width(jScroll.width() / jInnerDiv.width() * jScroll.width() * k);

		iMovingWidth = jScroll.width() - jCar.width();
		iScrollWidth = jInnerDiv.width() - jScroll.width();

		jScroll[0].scrollLeft = parseInt(iScrollWidth/2);

		jContent.css(
			{
				left: -jScroll[0].scrollLeft
			}
		);

		jCar.css('left', parseInt(jScroll[0].scrollLeft / iScrollWidth * iMovingWidth));
	}
};

var ExtendedCheckbox = function(jElement) {
	var
		headCheckbox = jElement.find('.header_control input'),
		childCheckbox = jElement.find('.child_controls input');

	headCheckbox.click(headClick);
	childCheckbox.click(childClick);

	function headClick() {
		if (headCheckbox.is(':checked')) {
			childCheckbox.attr('checked', 'checked');
		} else {
			childCheckbox.removeAttr('checked');
		}
	}

	function childClick() {
		var checkedNum = childCheckbox.filter(':checked');
		var allChecked = (checkedNum.length == childCheckbox.length) ? true : false;
		if (allChecked) {
			headCheckbox.attr('checked', 'checked');
		} else {
			headCheckbox.removeAttr('checked');
		}
	}
}

var PhotoSwitcher = function(jElement) {
	var
		jContainer = jElement,
		jLinksContainer = jElement.find('.photo_chooser');
	jLinksContainer.find('a, b').each(function() {
		$(this).click(function() {
			jContainer.attr('class', $(this).attr('id'));
			return false;
		});
	});
}


$(function() {

	if($c.browser.msie)
		$('body').addClass('msie');
	else if ($c.browser.safari)
		$('body').addClass('safari');
	else if ($c.browser.opera)
		$('body').addClass('opera');
	else if ($c.browser.mozilla)
		$('body').addClass('mozilla');
	else if ($c.browser.webkit)
		$('body').addClass('webkit');

	new CustomSimpleDropdown($('#header .rambler_services .dropdown_container'));

	$('.panel_control').each(function() {
		var iPanelControlNum = aPanelControls.length;

		aPanelControls[iPanelControlNum] = new PanelControl($(this), iPanelControlNum);



		/*
		$(this).find('.favorite').click(function(){
			$('#notes_list_favorites_object').append('<span id="'+$(this).attr('name')+'">'+$(this).parents('.catalog_results_item').find('.object_title')+'<ins class="delete_item"></ins></span>');
		});

		$(this).find('.compare').click(function(){
			$('#notes_list_compare_object').append('<span id="'+$(this).attr('name')+'">'+$(this).parents('.catalog_results_item').find('.object_title')+'<ins class="delete_item"></ins></span>');
		});
*/
	});

	if(typeof(MiddleSearch) == 'function'){

		new MiddleSearch();

		/*В ie наблюдаются проблемы с z-index выподающих меню.*/
		if($c.browser.msie)
			$('form.main_filter').css('z-index','1000');
	}

	if(typeof(ManegersList) == 'function'){

		new ManegersList();
	}

	new DropicusSystem();
	LoginFormsControl($("form.login_form"));


	if(typeof(rNotes) == 'function'){
		new rNotes($('.favorite'));
	}

	if($('#search_catalog_results').length > 0)
	{
		new TableSelectus($('#search_catalog_results'));
	}

	if ($('#homepage_object_block').length) {
		new HomePageSlider($('#homepage_object_block'));
	}
	if ($('#photo_cont').length) {
		new PhotoSwitcher($('#photo_cont'));
	}
});


var PageSelectBlocks = function()
{
	$('#layout').find('select.visual').each(function(){

		prepareSelectBlock($(this));
		$(this).addClass('ready');
	});

	function prepareSelectBlock(input)
	{
		var selected = input.find('option[selected=true]');
		var selName = input.attr('name');
		var options = input.find('option');
		var drop = '';

		input.html('<div class="container_select hidden"></div><a href="#" class="selectus pseudo"><input type="radio" name="'+selName+'" value="'+selected.attr('value')+'" checked="checked" />'+selected.text()+'</a><ins class="arrowus"></ins>');

		drop = '<div class="selectdrop">';
		drop += '<a href="#" class="pseudo" name="'+selected.attr('value')+'">'+selected.text()+'</a><br/>';
		options.each(function(){
			if($(this).attr('selected') == '')
			{
				drop += '<a href="#" class="pseudo" name="'+$(this).val()+'">'+$(this).text()+'</a><br/>';
			}
		});
		drop += '</div>';

		var container = control.find('.container_select');
		container.html(drop);

		var selectors = control.find('a.selectus');

		selectors.click(function(){
			resultsBlock.change(control);

			dropElement.addClass('hidden');

			var capt = '<h6><a class="list_caption" href="#" class="pseudo" name="'+$(this).find('input').attr('value')+'">'+$(this).text()+'</a><ins class="arrowus"></ins></h6>';
			var dropin = control.find('.container_select').html();

			dropElement.html(capt+dropin);
			dropElement.css({
				left:selectors.offset().left - dropElement.parent().offset().left-7,
				top:selectors.offset().top+(selectors.height()/2) - dropElement.parent().offset().top+7
			});
			dropElement.removeClass('hidden');

			dropElement.find('ins.arrowus').css({left:(dropElement.find('.list_caption').width()+10)+'px'})

			//Скрываем при убирании указателя
			dropElement.hover(function(){
					return false;
				},function(){
					dropElement.addClass('hidden');
				});

			dropElement.find('a').each(function(){
			$(this).click(function(){

				//Восстанавливаем блоки при переключении
				//Если есть деактивированные элементы вызванные из данного параграфа
				if(typeof(isDisabled[pclass]) == 'object')
				{
					for(var key in isDisabled[pclass])
					{
						if(typeof(isDisabled[pclass]) == undefined)
							break;

						if(typeof(isDisabled[pclass][key]) != 'object')
							break;

						isDisabled[pclass][key].removeClass('hidden');
					}
					isDisabled[pclass] = undefined;
				}
				if(typeof(isParagraph[pclass]) == 'object')
				{
					for(var key in isParagraph[pclass])
					{
						if(typeof(isParagraph[pclass]) == undefined)
							continue;

						if(typeof(isParagraph[pclass][key]) != 'object')
							continue;

						isParagraph[pclass][key].removeClass('hidden');
					}
					isParagraph[pclass] = undefined;
				}

				sessionSelect[selName] = $(this).attr('name');
				selectors.html('<input type="radio" name="'+selName+'" value="'+$(this).attr('name')+'" checked="checked" />'+$(this).text())+'<ins class="arrowus"></ins>';
				dropElement.addClass('hidden');

					for(var key in settings["select|"+selName])
					{
						if(typeof(key) != 'string' )
							continue;

						if(typeof(settings["select|"+selName][key]) != 'object')
								continue;

						var vOption = settings["select|"+selName][key];

						//Команда открыть блок с чекбоксами
						if(key == 'refresh')
						{
							for(var i=0;i<vOption.length;i++)
							{
								if(typeof(vOption[i]) != 'string')
									continue;

								reset_paragraph(vOption[i]);
							}
						}
						else if(key == 'options')
						{
							var opt = $(this).attr('name');
							var error = [];

							if(typeof(vOption[opt]) == 'string' || typeof(vOption[opt]) == 'object')
							{
								applyCommand(pclass,vOption[opt],control,$(this).attr('name'));
							}
							else if(typeof(vOption['default']) == 'string' || typeof(vOption['default']) == 'object')
							{
								applyCommand(pclass, vOption['default'],control,$(this).attr('name'));
							}
							else
								continue;
						}

					}
					return false;
				});
			});

			return false;
		});
	}
}

/** Инициализация всех добавлялок заметок на странице
 * @param {} NotesCheckElement
 * @return {Boolean}
 */
var rNotes = function(NotesCheckElement){

	if(typeof(url_postAppendNotesElement) == 'undefined' || typeof(CountNotesElement) == 'undefined')
		return false;

	var ParentNotes = $('#notes_block');
	if(ParentNotes.length == 0)
		return false;

	var ParentNotesText = ParentNotes.find('.text');

	if(ParentNotes.find('.count').length == 0 && CountNotesElement > 0)
		ParentNotesText.append('<span class="count">('+CountNotesElement+')</span>');
	else if(ParentNotes.find('.count').length == 0 && CountNotesElement == 0)
		ParentNotesText.append('<span class="count"></span>');

	var ParentNotesCount = ParentNotesText.find('.count');

	//ParentNotesText.hover(function(){$(this).addClass('hoverus')},function(){$(this).removeClass('hoverus')});

	setStatus();

	NotesCheckElement.each(function(){
		new rNotesAppend($(this),ParentNotes,ParentNotesText,ParentNotesCount,false);

		$(this).css({
		      'MozUserSelect' : 'none'
		    }).bind('selectstart', function() {
		      return false;
		    }).mousedown(function() {
		      return false;
	    });
	});
	/*
	ParentNotes.click(function(){
		if(ParentNotes.hasClass('pseudo'))
		{
			return false;
		}
		else
			ParentNotes.find('.list').css('display','none');
	});
	*/
	function setStatus(){
		if(CountNotesElement > 0)
			ParentNotes.removeClass('pseudo');
		else
			ParentNotes.addClass('pseudo');
		return true;
	}
}
var popup;
var popupCount;
var popupCountOld = 0;
var stat = true;
var fourT;
var rNotesAppend = function(jElement,jParentNotes,jParentText,jParentCount,isDebug)
{
	var NotesOffset = jParentNotes.offset();
	var x = NotesOffset.left-10,
		y = NotesOffset.top-7;

	var html = $(window);

	var is_active;
	var sTextDefault = 'в&nbsp;заметки';
	var sTextChanged = 'удалить из&nbsp;заметок';

	var jTextBlock = jElement.find('.tool_text').eq(0);

	//Идентификатор недвижимости
	var dIdThisObject = jElement.attr('id');


	if(jElement.hasClass('selected'))
	{
		is_active = true;
	}
	else
	{
		is_active = false;
	}

	if(jTextBlock.length == 0)
	{
		return false;
	}

	jElement.click(function(){
		//jElement.addClass('loading');
		popupCountOld = CountNotesElement;
		if(!is_active)
		{
			setCaption(true);
			is_active = true;

			CountNotesElement++;
			jElement.addClass('selected');
			animateNote();
			setStatus(CountNotesElement);
		}
        else
        {
			setCaption(false);
			is_active=false;

			CountNotesElement--;
			jElement.removeClass('selected');
			animateNote();
			setStatus(CountNotesElement);
        }


		$.ajax({
			type: "POST",
			url: url_postAppendNotesElement,
			data: getData(),
			dataType: "json",
			success: function(data) {
				//jElement.removeClass('loading');

				if(typeof(data) != 'object')
				{
					return false;
				}
				else if(typeof(data.result) == 'string' && data.result == 'success')
				{
					return false;
				}
	            return false;
			},
			error:{
				//jElement.removeClass('loading');
			}
		});
		return false
	});



	function animateNote()
	{
		if(typeof(popup) == 'undefined' && stat == true)
		{
			NotesOffset = jParentNotes.offset();
			x = NotesOffset.left-10;
			y = NotesOffset.top-7;

			stat = false;
			jParentNotes.css('visibility','hidden');

			if(!$c.browser.opera)
			{
				//Создаем декоративный элемент
				$('body').append('<div id="popupNotes" class="hidden"><a href="'+jParentNotes.attr('href')+'">'+jParentText.html()+'</a></div>');
				popup = $('#popupNotes');
				popupCount = popup.find('.count');

				popup.css({'left':x,'top':y});
				popup.removeClass('hidden');
			}
			else
			{
				//Создаем декоративный элемент
				$('body').append('<div id="popupNotes" class="hidden opera"><div class="decoration"><a href="'+jParentNotes.attr('href')+'">'+jParentText.html()+'</a></div></div>');
				popup = $('#popupNotes');
				popupCount = popup.find('.count');

				popup.css({'left':x,'top':y});
				popup.removeClass('hidden');
			}
		}

		var popupTop = popup.offset().top;
		var topLine = html.scrollTop()+20;

		popupCount.html(getCount(CountNotesElement));

		if(CountNotesElement == 0)
		{

			stat = true;
			popup.animate({'top':y},'normal',function(){
				popup.remove();
				popup=undefined;
				jParentNotes.css('visibility','visible');
				return false;
			});
			return false;
		}

		popup.stop();
		clearTimeout(fourT);


		var alfa = Math.abs(parseInt((popupTop - topLine-20)/5));
		var beta = Math.abs(parseInt((alfa)/5));

		if(html.scrollTop() > jParentNotes.offset().top)
		{
			if(typeof(popup) != "undefined")
			popup.stop()
				.animate({'top':topLine+alfa},'fast')
				.animate({'top':topLine-beta},'normal')
				.animate({'top':topLine},'slow',
					function(){
						fourT = setTimeout(function(){if(typeof(popup) != "undefined") popup.animate({'top':y},'slow')},3000);
					}
				);
		}
		else
		{
			fourT = setTimeout(function(){
				if(typeof(popup) != "undefined"){
					popup.animate({'top':y},'slow')}
			},5000);
		}

		$(window).resize(function() {
			if(typeof(popup) != "undefined"){
				popup.css('left',jParentNotes.offset().left);
			}
		});









		/*


		popupCount.html(getCount(CountNotesElement));

		if(stat == false)
			clearTimeout(fourT);
		//clearTimeout(threeT);

		debug('status = '+stat);

			if(stat == true)
			{
				stat = false;
				debug('status = '+stat);
				popup.stop().animate({'top':html.scrollTop()+30},'fast').animate({'top':html.scrollTop()-10},'normal').animate({'top':html.scrollTop()},'slow',
				function(){
					//threeT = setTimeout(function(){popupCount.html(getCount(CountNotesElement));},1000);
					fourT = setTimeout(function(){popup.animate({'top':y},'fast',function(){stat=true;debug('Status_Change TRUE');});},10000);
				});
			}
			else
			{
				popup.stop().animate({'top':html.scrollTop()},1000);
				//threeT = setTimeout(function(){popupCount.html(getCount(CountNotesElement));},1000);
				fourT = setTimeout(function(){popup.animate({'top':y},'fast',function(){stat=true;})},10000);
			}
		}
		*/
	}

	function getCount(num)
	{
		return '('+num+')';
	}

	function getData (){
		if(is_active)
		{
			var data = {"delete":dIdThisObject};
		}
		else
		{
			var data = {"append":dIdThisObject};
		}
	}

	function setCaption(res)
	{
		jTextBlock.addClass('fix_border');
		if(res)
		{
			jTextBlock.html(sTextChanged);
			setTimeout(function(){jTextBlock.removeClass('fix_border')},100);
		}
		else
		{
			jTextBlock.html(sTextDefault);
			setTimeout(function(){jTextBlock.removeClass('fix_border')},100);
		}
		return true;
	}

	function setStatus(value){

		var val = CountNotesElement;
		if(typeof(value) == 'string' || typeof(value) == 'number')
			val = value;

		if(val > 0)
		{
			//jParentCount.html('('+val+')');
			jParentNotes.removeClass('pseudo');
		}
		else
		{
			//jParentCount.html('');
			jParentNotes.addClass('pseudo');
		}
		return true;
	}

}

var TableSelectus = function(tables){

	var sibligsItem = [];

	tables.find('.catalog_results_item').each(function(){

		$(this).unbind().addClass('row_hover').removeClass('row_hover');

		$(this).hover(function(){is_hover($(this))},function(){is_nohover($(this))});

		$(this).click(function(){is_toggle($(this))});

		sibligsItem.push($(this));
	});

	function is_hover(jItem)
	{
		if(activeAction == true)
			return false;

		jItem.addClass('row_hover');
		jItem.find('.tools').addClass('hovered');
	}

	function is_nohover(jItem)
	{
		if(activeAction == true)
			return false;

		jItem.removeClass('row_hover');
		jItem.find('.tools').removeClass('hovered');
	}

	function is_toggle(jItem)
	{
		if(activeAction == true)
			return false;

		if(jItem.hasClass('row_toggle'))
		{
			jItem.removeClass('row_toggle');
		}
		else
		{
			for(var t=0;sibligsItem.length > t;t++)
			{
				sibligsItem[t].removeClass('row_toggle');
			}

			jItem.addClass('row_toggle');
		}
	}
}

/**
 * Enables/Disables text selection, saves selected text
 *
 * @example jQuery('p').enableTextSelect(); / jQuery('#selectable-area').disableTextSelec();
 * @cat plugin
 * @type jQuery
 *
 */
jQuery.fn.disableTextSelect = function() {
  return this.each(function() {
    $(this).css({
      'MozUserSelect' : 'none'
    }).bind('selectstart', function() {
      return false;
    }).mousedown(function() {
      return false;
    });
  });
};

jQuery.fn.enableTextSelect = function() {
  return this.each(function() {
    $(this).css({
      'MozUserSelect':''
    }).unbind('selectstart').mousedown(function() {
      return true;
    });
  });
};











