$(document).ready(function() {


	$('.kladrSelect').change(function() {
		kladrnum = $(this).val();
//		alert($(this).closest('div').next('div').html());
		a = Math.random();
		$(this).closest('div').next('div').find('select').attr('disabled', true).load('/inc/utils/kladr_list.php?kladrnum='+kladrnum+"&a="+a,function() {
					$(this).attr('disabled', false);
				});
	});

	// Отправка формы и получение результата
	$('.submitGraphForm').click(function () {
		
		$(this).parents('form').find('input[name=imgWidth]').val($('.viewGraph').width()-30);
		
		serializedForm = $(this).parents('form').attr('action')+'?'+$(this).parents('form').formSerialize();
	//	alert(serializedForm);
		btnHTML = $(this).html();
		btn = $(this);		
		
		switch($(this).attr('rel')) {
			case "1":
				$(this).attr('disabled', true).html('Загрузка таблицы...');
				$(btn).parents('.act').find('.viewResult').fadeTo(300, .5).load(serializedForm,function() {
					$(this).fadeTo(300,1);
					$(btn).attr('disabled', false).html(btnHTML);
				});
				break;
			default:
				$(this).attr('disabled', true).html('Построение графика...');
				$('.viewGraph').fadeTo(300, .5).append('<img src="" class="hidden">');
			
				$('.viewGraph .hidden').bind('error', 
					function(){
						$(this).fadeIn().prev().remove();
					  	alert("Ошибка загрузки изображения. Попробуйте позже.");
						$(btn).attr('disabled', false).html(btnHTML);
						$(this).unbind();
					})
					.attr('src', serializedForm.replace('&amp;','&'))
					.load(function() {
						$(this).fadeIn().prev().remove();
						$(this).parent().fadeTo(300,1).children().removeClass('hidden');
						$(btn).attr('disabled', false).html(btnHTML);
					});
			
		}
		
//		alert($('.viewGraph').html());
		
		return false;
	})

	// Инициализация календаря
	$.extend(DateInput.DEFAULT_OPTS, {stringToDate: function(string) {var matches;if (matches = string.match(/^(\d{2,2})\.(\d{2,2})\.(\d{4,4})$/)) {return new Date(matches[3], matches[2] - 1, matches[1]);} else {return null;};},
	  dateToString: function(date) {var month = (date.getMonth() + 1).toString();var dom = date.getDate().toString();if (month.length == 1) month = "0" + month;if (dom.length == 1) dom = "0" + dom;return dom + "." + month + "." + date.getFullYear();}});
  	$(".dateInput").date_input();

	/*Работа с блоками вывода радиокнопок и чекбоксов*/
	$('.checkbox-label').click(function () {
		if($(this).hasClass('act-label') == true)
			{
			$(this).children('input[type=checkbox]').attr("checked", false);
			$(this).removeClass('act-label');
			}
		else
			{
			$(this).children('input[type=checkbox]').attr("checked", true);
			$(this).addClass('act-label');
			}
	});
	$('.radio-label').click(function (e, outsideclick) {
		if($(this).find('input[type=radio]').attr('checked') != true || outsideclick == 1)
			{
			$(this).find('input[type=radio]').attr('checked', true);
			$(this).parent().find('.radio-label').removeClass('act-label');
			$(this).addClass('act-label');
			}
	});
	$('.radio-label').find('input[type=radio]').click(function() {
		$(this).closest('.radio-label').trigger('click',1);
	});

	/*Вывод блока авторизации пользователя*/
	$('.auth a').click(function() {
		$(this).css('display', 'none');
		$(this).next().css('display', 'block');
	});

	/* Показ панели с деревом объектов*/
	$('.showPanel').click(function() {
//		alert(parseInt($('.panelView').css("left")));
		if(parseInt($('.panelView').css("left")) != 0)
			{
			$('.panelView').animate({left: 0});
			shadowShow();
			}
		else
			{
			$('.panelView').animate({left: "-250px"});
			shadowHide();
			}
		return false;
	});
	$('.shadow').click(function() {
		$('.panelView').animate({left: "-250px"});
		shadowHide();
		});

	/* Работа с деревом объектов */
	regionTreePrepare();

	// Для всех добавленных переключателей задаём реакцию на клик
	$('.switch').live('click', function() {
		if($(this).hasClass('switch-closed'))
			{
			$(this).removeClass('switch-closed');
			$(this).addClass('switch-opened');
			$(this).parents('li').children('ul:first').slideDown();
			}
		else
			{
			$(this).removeClass('switch-opened');
			$(this).addClass('switch-closed');
			$(this).parents('li').children('ul:first').stop(true, true);
			$(this).parents('li').children('ul:first').slideUp();
			}
		return false;
	});

	/*Работа с вкладками*/ 
	$('.tabs a').click(function() {
		// Если клацнули по активной, то ничего не делаем
		if($(this).closest('li').hasClass('act'))
			return false;
		classToAct = this.className;
		$(this).closest('ul').children('.act').removeClass('act'); // Делаем все неактивными
		$(this).closest('li').addClass('act');		// Текущую активной
		
		$('.tab-content[class~="act"]').removeClass('act').hide();		// Скрываем текущий контент
		$('.tab-content[class~="'+classToAct+'"]').show().addClass('act');// Покаываем новый контент

		// Указываем в cookies активную вкладку для страницы
		var myRe = /id=([0-9]+)\&?/ig;
		var id_page = myRe.exec(location.search);
		if(typeof id_page != 'undefined' && id_page != null)
			setCookie ('page_options['+id_page[1]+']', classToAct, '', '/')
		$(this).closest('li').find('li:first').find('a').trigger('click');
		return false;
	});
	
});


function shadowShow() {
	$('.shadow').css('display', 'block');
	$('.shadow').animate({opacity: "0.7"});
}
function shadowHide() {
	$('.shadow').animate({opacity: 0}, function() {
		$('.shadow').css('display', 'none');
		}
	);
}

function print_(){
window.print() ;
}

function regionTreePrepare() {
	$('.region-tree ul').each(function () {
		// выставляем родительскому li + или - в зависимости от наличия класса 'opened'
		if($(this).parent('li').hasClass('opened'))
			$(this).parent('li').prepend('<a href="#" class="switch switch-opened"></a> ');
		else
			$(this).parent('li').prepend('<a href="#" class="switch switch-closed"></a> ');
		});
	// для всех дочерних li выводим все ul, если у li класс 'opened'
	$('.region-tree').find('li').each(function () {
		if($(this).hasClass('opened'))
			$(this).children('ul:first').css('display', 'block');
		else
			$(this).children('ul:first').css('display', 'none');
		});
}

function setCookie (name, value, expires, path, domain, secure) {
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}

function getContent() {
	var content = new Array();
	content[0] = $('.title').html();
	content[1] = $('.tab-holder').find('.act').html();
	return content;
}
