// JavaScript Document
var only = true;
var tarif_url = '';
var tmon = true;

var tarif_flags = {};
$(document).ready(function() {
	// accordion
	initAccordion({
		accordionClass : 'accordion',
		slideSpeed     : 200, // slide animation speed
		activeClass    : 'active',
		openedClass    : 'opened'
	});
	
	// table expander
	/*
	initTabExpander({
		tabEl       : 'table.tab-tarifs',
		tabExpander : 'a.link-expander',
		closedClass : 'tab-close'
	});
	*/
	
	// sitemap expander
	// initSidemapExpander ();
	

	if ($('#street').length > 0) {
		$("#street").autocomplete("/ajax/autocomplete.php?action=street", {
		  delay:10,
		  minChars:2,
		  matchSubset:1,
		  autoFill:true,
		  matchContains:1,
		  cacheLength:10,
		  selectFirst:true,
		  formatItem:liFormat,
		  maxItemsToShow:20,
		  onItemSelect:selectItem,
		  extraParams: {region: region}
		});
	}
	
	if ($('#house').length > 0) {
		$("#house").autocomplete("/ajax/autocomplete.php?action=house", {
		  delay:10,
		  minChars:1,
		  matchSubset:1,
		  autoFill:true,
		  matchContains:1,
		  cacheLength:10,
		  selectFirst:true,
		  formatItem:liFormat,
		  maxItemsToShow:30,
		  onItemSelect:selectItem,
		  extraParams: {region:region, adr: function(){
			  return $("input#street").val();
		  }}
		});
		
		$('#house').bind('blur', function(){
			$('#house').flushCache();
		});
	}
	
	
	$('a.submit').bind('click', function(){
		var _form = $(this).parents('form');
		if (validate(_form)) {
			$(this).parents('form').submit();
		}
		return false;
	});
	
	$("input[name='house-status-1']").bind('click', function(){
		var checked = ($("input[name='house-status-1']:checked").length > 0);
		alert(checked);
		if (checked) {
			$('strong.normal').show();
		} else {
			$('strong.normal').hide();
		}
	});
	
	$("div.customCheckbox").live('click', function(){
		var id = $(this).attr('customcheckboxid');
		if (id == 'customCheckbox0') {
			$('ul.cover-map span.normal').css('display', 'none');
		} else if(id == 'customCheckbox1') {
			$('ul.cover-map span.orng').css('display', 'none');
		} else if(id == 'customCheckbox2') {
			$('ul.cover-map span.grey999').css('display', 'none');
		}
		
		display_map();
	});

	$("div.customCheckboxChecked").live('click', function(){
		var id = $(this).attr('customcheckboxid');
		if (id == 'customCheckbox0') {
			$('ul.cover-map span.normal').css('display', 'inline');
		} else if(id == 'customCheckbox1') {
			$('ul.cover-map span.orng').css('display', 'inline');
		} else if(id == 'customCheckbox2') {
			$('ul.cover-map span.grey999').css('display', 'inline');
		}
		display_map();		
	});
	
	$('a.qlink').toggle(
		function() {
			var active = $('.qb .answer:visible');
			$(active).parents('.qb').find('a.qlink').click();
			
			var answer = $(this).parents('.qb').find('.answer');
			$(answer).slideDown('fast');
			return false;
		}, 
		function() {
			var answer = $(this).parents('.qb').find('.answer');
			$(answer).slideUp('fast');
			return false;
		}
	);
	
	$('a.qlink2').toggle(
		function() {
			var answer = $(this).parents('.qb').find('.answer');
			$(answer).slideUp('fast');
			return false;
		},
		function() {
			var active = $('.qb .answer:visible');
			$(active).parents('.qb').find('a.qlink').click();
			
			var answer = $(this).parents('.qb').find('.answer');
			$(answer).slideDown('fast');
			return false;
		}
	);
	
	
	$('.expander a.open').bind('click', function(){
		$('.expander a.close').removeClass('active');
		$('.expander a.open').addClass('active');
												 
		if ($('.answer').length > 0) {
			$('.answer').slideDown('fast');
		}
		
		if ($('.tns').length > 0) {
			$('.column-center ul.tns li ul.tns').slideDown('fast');
		}
		
		return false;
	});

	$('.expander a.close').bind('click', function(){
		$('.expander a.open').removeClass('active');
		$('.expander a.close').addClass('active');
												  
		if ($('.answer').length > 0) {
			$('.answer').slideUp('fast');
		}
		if ($('.tns').length > 0) {
			$('.column-center ul.tns li ul.tns').slideUp('fast');
		}
												  
		return false;
	});
	
	
	if (animated) {
		$("#promo").everyTime(_delay, function(i) {
			var _a = $(".promo img:visible").parents('a:first');
			var id = $(_a).attr('id');
			id = id.split('_');
			var num = parseInt(id[1]) + 1;
			
			if ($('a#promo_' + num.toString()).length > 0) {
				var next = 'promo_' + num.toString();
			} else {
				var next = 'promo_1';
			}
	
			$(_a).fadeOut('slow', function(){
				//$('.p a').removeClass('this_slide');
				//$('.slider_pages a#' + next_link).addClass('this_slide');
				$('a#' + next).fadeIn('slow');
			});
		});
	}
	
	$.getJSON("/inside/search/",
		function(data){
			$('input#search').jsonSuggest(data, {maxResults:20});
			if ($('#search2').length > 0) {			
				$('input#search2').jsonSuggest(data, {maxResults:20});
			}
		}
	);
	
	$(".date").mask("99.99.9999");

    $.datepicker.setDefaults($.extend({showMonthAfterYear: false}, $.datepicker.regional['ru']));
    $("#date").datepicker({
            onSelect: function(dateText, inst) {
  		        v = $('#date').val();
  		        //document.dForm.submit();
  	    }
    });
	
	display_map();
	
	// Страница с таблицей тарифов
	// label - обработка нажатия на label, например "Безлимитный 3027", "450", "3072" или "-"
	$('.tab-tarifs input[type=radio]').live('click', function () {
	    //var _form = $(this).parents('form');
		var vals = '';
		$('.column-center .custom-form form').each(function(){
			if (vals != '') {
				vals = vals + '&';
			}
			vals = vals + $(this).serialize();
		});
		
		$('#overlay').show();
		$.post(tarif_url + '?isNaked=1', vals, function(data){
			$('#loaded-area').html(data);
			
			$('div.custom-form').urForm({
				replaceRadios : true,
				replaceCheckboxes : true,
				replaceSelects : true
			});
			after_tarif_load();
			
			if (tmon) $('a#calc-mon').click(); else $('a#calc-day').click();
			$('#overlay').hide();
		});
	});
	// custom input - обработка нажатия на сам кастомный input[type=radio]
	$('.tab-tarifs .customRadio, .tab-tarifs .customRadioChecked').live('click', function () {
		//alert($(this).parent().find('input[type=radio]').attr('checked'));

		var vals = '';
		$('.column-center .custom-form form').each(function(){
			if (vals != '') {
				vals = vals + '&';
			}
			vals = vals + $(this).serialize();
		});
		
		$('#overlay').show();		
		$.post(tarif_url + '?isNaked=1', vals, function(data){
			$('#loaded-area').html(data);
			
			$('div.custom-form').urForm({
				replaceRadios : true,
				replaceCheckboxes : true,
				replaceSelects : true
			});
			after_tarif_load();			
			if (tmon) $('a#calc-mon').click(); else $('a#calc-day').click();
			$('#overlay').hide();			
		});
	});
	
	// CHECKBOXES - Дополнительные услуги
	// label - обработка нажатия на label, например "IP TV 01", "450", "2" или "0.30"
	$('.tab-tarifs input[type=checkbox]').live('click', function () {
		//alert($(this).attr('checked'));
		
		var vals = '';
		$('.column-center .custom-form form').each(function(){
			if (vals != '') {
				vals = vals + '&';
			}
			vals = vals + $(this).serialize();
		});
		
		$('#overlay').show();		
		$.post(tarif_url + '?isNaked=1', vals, function(data){
			$('#loaded-area').html(data);
			
			$('div.custom-form').urForm({
				replaceRadios : true,
				replaceCheckboxes : true,
				replaceSelects : true
			});
			after_tarif_load();			
			
			if (tmon) $('a#calc-mon').click(); else $('a#calc-day').click();			
			$('#overlay').hide();			
		});
		
	});
	// custom input - обработка нажатия на кастомный input[type=checkbox]
	$('.tab-tarifs .customCheckbox, .tab-tarifs .customCheckboxChecked').live('click', function () {
		//alert($(this).parent().find('input[type=checkbox]').attr('checked'));
		var vals = '';
		$('.column-center .custom-form form').each(function(){
			if (vals != '') {
				vals = vals + '&';
			}
			vals = vals + $(this).serialize();
		});
		
		$('#overlay').show();		
		$.post(tarif_url + '?isNaked=1', vals, function(data){
			$('#loaded-area').html(data);
			
			$('div.custom-form').urForm({
				replaceRadios : true,
				replaceCheckboxes : true,
				replaceSelects : true
			});
			after_tarif_load();			

			if (tmon) $('a#calc-mon').click(); else $('a#calc-day').click();			
			$('#overlay').hide();			
		});
	});
	
	$('a#calc-day').live('click', function(){
		$('span.tmon').hide();
		$('span.tday').show();
		tmon = false;
		return false;
	});
	
	$('a#calc-mon').live('click', function(){
		$('span.tmon').show();
		$('span.tday').hide();
		tmon = true;
		return false;
	});
	
	$('a.link-connect').live('click', function(){
		var vals = '';
		$('.column-center .custom-form form').each(function(){
			if (vals != '') {
				vals = vals + '&';
			}
			vals = vals + $(this).serialize();
		});
		$('form#caa_form input[name=tarif_data]').val(vals);
		$('form#caa_form').submit();
	});
	
	$('a#calc-reset').live('click', function(){
		$.post(tarif_url + '?isNaked=1', '', function(data){
			$('#loaded-area').html(data);
			$('div.custom-form').urForm({
				replaceRadios : true,
				replaceCheckboxes : true,
				replaceSelects : true
			});
			after_tarif_load();			

			
			if (tmon) $('a#calc-mon').click(); else $('a#calc-day').click();			
		});
		return false;
	});
	
	$('table.tab-tarifs a.link-expander').live('click', function(){
		var table = $(this).parents('table.tab-tarifs');
		if ($(table).hasClass('tab-close')) {
			$(table).removeClass('tab-close');
			var id = table.attr('id');
			id = id.split('_');
			tarif_flags[id[1]] = '';
		} else {
			$(table).addClass('tab-close');
			var id = table.attr('id');
			id = id.split('_');
			tarif_flags[id[1]] = 'closed';
		}
		return false;
	});
	
});

function liFormat (row, i, num) {
  //var result = row[0] + "<em class="qnt">" + row[1] + " тыс.чел.</em>";
  var result = row[0];
  return result;
}

function selectItem(li) {
  if( li == null ) var sValue = "Ничего не выбрано!";
  if( !!li.extra ) var sValue = li.extra[2];
  else var sValue = li.selectValue;
  alert("Выбрана запись с ID: " + sValue);
}

function validate(_form) {
	$('input', _form).removeClass('check_error');
	$('textarea', _form).removeClass('check_error');		
	var error = false;
	
	$('.required', _form).each(function(){
		var v = $(this).val();
		if (v == '') {
			$(this).addClass('check_error');
			error = true;
		}
	});
	
	if (error) {
		alert('Не заполнены обязательные поля');
		return false;
	}

	if ($("input.email", _form).length > 0) {
		var email= $("input.email", _form).val();
		if (email != '') {
			var reg= new RegExp("[0-9a-z_]+@[0-9a-z_^.]+\\.[a-z]{2,3}", 'i')
			if (!reg.test(email)) {
				$("input.email").addClass('check_error');
				alert('Введенный Email не прошел проверку на валидность');
				return false;
			}
		}
	}
	return true;
}

function display_map() {
	$('ul.cover-map li').each(function(){
		var cnt = 0;
		$('span', this).each(function(){
			if ($(this).css('display') != 'none') {
				cnt++;
			}
		});
		
		if (cnt == 0) {
			$(this).css('display', 'none');
		} else {
			$(this).css('display', 'list-item');
		}
	});
}

function after_tarif_load() {
	$('table.tab-tarifs').each(function(){
		var id = $(this).attr('id');
		id = id.split('_');
		if (typeof(tarif_flags[id[1]]) != "undefined") {
			if (tarif_flags[id[1]] == 'closed') {
				$(this).addClass('tab-close');
			} else {
				$(this).removeClass('tab-close');
			}
		}
	});
}
