/* загружаем плеер */
function loadPlayer(url,container,type) {
    if (url !== undefined && container !== undefined && type !== undefined) {
        var height = type == 'video' ? '340' : '80';
        var flashvars = {
            st: 'http://'+window.location.host+'/netcat_files/js/'+type+'-skin.txt',
            way: url,
            wmode: 'transparent',
            time_seconds: '500',
            skin: 'white',
            autoplay: '0',
            volume: '70',
            scale: 'exactfit'
        }
        var params = {
            src: 'http://'+window.location.host+'/netcat_files/js/'+type+'-player.swf',
            type: 'application/x-shockwave-flash',
            wmode: 'transparent',
            allowfullscreen: 'true'
        }
        swfobject.embedSWF('http://'+window.location.host+'/netcat_files/js/'+type+'-player.swf',container,'605',height,'10.0.0',false,flashvars,params);
    }
} 

/**
 *  Установка cookie
 */ 
function setCookie(name, value, path, domain, expires, secure) {
 
 var today = new Date();
 today.setTime(today.getTime());

 
 // Для установки времени в часах удалить * 24,  
 // для минут - удалить * 60 * 24
 if (expires){
  // expires = expires * 1000 * 60 * 60 * 24;
  expires = expires * 1000 * 60 * 60;
 }
 var expires_date = new Date( today.getTime() + (expires) );

 document.cookie = name + "=" +escape( value ) +
  ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
  ( ( 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);
}

/**
 * var_dump 
 */
function dump(obj) {
    var out = '';
    for (var i in obj) {
        out += i + ": " + obj[i] + "\n";
    }

    //alert(out);
    var pre = document.createElement('pre');
    pre.innerHTML = '';
    pre.innerHTML = out;
    document.body.appendChild(pre)
}

// построение селекторов
function buildSelectors(selector, options) {
    if (typeof options == 'object') {
        var selectedValue = 0;
        if ( selector.attr('id') === "kladr_region" ) {
            selectedValue = $("#selectedRegion").val() != undefined ? $("#selectedRegion").val() : 0;
        }
        if ( selector.attr('id') === "kladr_city" ) {
            selectedValue = $("#selectedCity").val() != undefined ? $("#selectedCity").val() : 0;
        }

        selector.find('option').remove();
        $.each(options, function(val, text){
            isChecked = selectedValue == val ? " selected='selected'" : "";
            selector.append("<option value='"+val+"'"+isChecked+">"+text+"</option>");
        });
        selector.parent().show();
        selector.change();
    }
}

// для ie6
if($.browser.msie && $.browser.version=='6.0') DD_belatedPNG.fix('.png2fix');

$(function() {

		// в калькуляторах, первый столбец жирным
  	$('table.calctbl tr').find('td:first').css('font-weight', 'bold');
  	$('table.calctbl tr').find('td:first').css('vertical-align', 'top');
  	
    // ajax loading
    $("#ajax_loading")
        .bind("ajaxSend", function() {
            $(this).show();
        })
        .bind("ajaxComplete", function() {
            $(this).hide();
    });

    // скрываем список городов
    $('body').bind('click', function(event) {
        if ( ! $(event.target).closest('div#region_popup').length ) {
            $('div#region_popup').hide();
        }
        if ( ! $(event.target).closest('div#polis_popup').length ) {
            $('div#polis_popup').hide();
        }
    });   

    // выбираем город
    $('a.select_city').click(function() {
        var link_id = $(this).attr('id');
        var city_id = link_id.substr(link_id.indexOf('_')+1);
        setCookie('selected_city_id_old', getCookie('selected_city_id'), '/', '', 24);
        setCookie('selected_city_id', city_id, '/', '', 24);
				// переход на сургут
				if(city_id == 181)
				{
				  window.location.pathname = '/actions/wheretobuy/surgut/';
				  return false;
				}
        
				var pattern = "^(([^:/\\?#]+):)?(//(([^:/\\?#]*)(?::([^/\\?#]*))?))?([^\\?#]*)(\\?([^#]*))?(#(.*))?$";
    		var rx = new RegExp(pattern);
				var parts = rx.exec(document.URL);
				
				// переход на страницу выбранного филиала
				if(parts[7] == '/actions/wheretobuy/branches/' && parts[9])
				{
					window.location.search = 'city=' + city_id;
					return false;
				}
				if(parts[7] == '/actions/wheretobuy/surgut/')
				{
				  window.location.assign('/actions/wheretobuy/branches/?city=' + city_id);
					return false;
				}
				 
				window.location.href = window.location.href;
        return false;
    });

    // обработка персональных данных
/*
    $('a.open_window').click(function() {
        personaldata = window.open($(this).attr('href'), 'personaldata', 'location=1,width=650,height=650,screenX=500,screenY=200');
        return false;
    });
*/

    /**
     * Анкета кандидата
     */

    // tableData
    oTable = $('#experience_table').dataTable({
      'bAutoWidth': false,
      'bInfo': false,
      'bLengthChange': false,
      'bPaginate': false,
      'bSort': false,
      'bFilter': false,
      'oLanguage': {
           'sEmptyTable': 'Нет записей'
      },
           
      "fnDrawCallback": function ( oSettings ) {
            for ( var i=0, iLen=oSettings.aiDisplay.length ; i<iLen ; i++ ) {
                $('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr ).html( i+1 );
            }
	  }

    });

    // добавление записи
    $('#add_table_row').click(function() {
     oTable.dataTable().fnAddData(
      [
        '',
        $('span#date_selectors').html(),
        '<input type=\'text\' name=\'jobs[post][]\' value=\'\' />',
        '<textarea cols=\'25\' rows=\'3\' name=\'jobs[obligations][]\'></textarea>',
        '<input type=\'text\' name=\'jobs[organization][]\' value=\'\' />',
        '<textarea cols=\'20\' rows=\'3\' name=\'jobs[reason][]\'></textarea>',
        '<input class=\'box\' type=\'checkbox\' name=\'jobs[insurance][]\' value=\'1\' />',
        '<input class=\'box\' type=\'checkbox\' name=\'jobs[selling][]\' value=\'1\' />',
        '<input class=\'box\' type=\'checkbox\' name=\'jobs[leading][]\' value=\'1\' />',
        '<a href=\'#\' title=\'удалить строку\' class=\'del_table_row\'>&nbsp;</a>'
      ]
     );

     return false;
    });

    // удаление строки в таблице анкеты
    $('#experience_table a.del_table_row').live('click', function () {
        var ind = this.parentNode.parentNode.rowIndex;
        oTable.dataTable().fnDeleteRow(ind-2);
        return false;
    });

    // выбор checkbox при submit формы
    $('form#jobsTable').submit(function() {
        $('#experience_table input[class=box]:not(:checked)').attr('checked', 'checked').attr('value', '0');
    });

    // удаление расчета
    $('a.del_calc').click(function() {
        var link = $(this);
        var calcID = link.attr('id').substr(5); 
        var calcName = link.parent().parent().find('td:eq(1) p').html();

        $.alerts.okButton = 'Удалить';
        $.alerts.cancelButton = 'Отмена';
        jConfirm('Подтвердите удаление расчета № '+calcID+' по калькулятору «'+calcName+'»', '', 
            function(response) {
            if (response == true) {
                $.post('http://'+location.host+'/ajax/deletecalc.php', {'calcID': calcID}, function(data) {
                    if (data == 'success') {
                        link.parent().parent().html("<td colspan='5' style='height: 50px; background-color: #eee; text-align: center;'>Запись удалена</td>");
                    }
                });
            }
        });

        return false;
    });

    // подтверждение расчета
    $('a.confirm_policy').click(function(){
        $.get('http://'+location.host+$(this).attr('href'), function(data) {
            if (data == 'success') {
                //$('div#result_div').addClass('result_success').html("Полис подтвержден.").show();
                window.location.reload();
            } else {
                $('div#result_div').addClass('result_error').html("Ошибка подтверждения полиса.").show();
            }
        });

        return false;
    });

    // платеж просрочен info
    $('img.tip').tooltip({
        track: true,
        delay: 0,
        fade: 200,
        bodyHandler: function () {
            return $('#tooltip_text').html();
        },
        showURL: false
    });

    // выбор полиса в формах "Внести изменения в полис" 
    // и "Продлить полис"
    $('#select_policy, #input_policy').change(function() {
        if($(this).val() && $(this).attr('id') == 'select_policy')
        {
					$('#input_policy').val('');
				}
        if($(this).val() && $(this).attr('id') == 'input_policy')
        {
					$('#select_policy').val('-1');
				}
        if ( $(this).val() ) {
            // получаем дату
            $.getJSON('http://'+location.host+'/ajax/getpolicydate.php?policyID='+$(this).val(), function(obj) {
                if (typeof obj == 'object') {
                    if (obj.status == 'success') {
                        $('input[name=f_DateStart_day]').val(obj.day);
                        $('input[name=f_DateStart_month]').val(obj.month);
                        $('input[name=f_DateStart_year]').val(obj.year);
                        $('input[name=f_DateStart]').val(obj.day + '.' + obj.month + '.' + obj.year);
                        $('input#policyInID').val(obj.id);
                    } else {
                        $('input[name=f_DateStart_day]').val('');
                        $('input[name=f_DateStart_month]').val('');
                        $('input[name=f_DateStart_year]').val('');
                        $('input[name=f_DateStart]').val('');
                        $('input#policyInID').val('0');
                    }
                }
            });
        } else {
            $('input[name=f_DateStart_day]').val('');
            $('input[name=f_DateStart_month]').val('');
            $('input[name=f_DateStart_year]').val('');
            $('input[name=f_DateStart]').val('');
        }

    }).change();

    // переход по шагам в процессе покупки полиса
    $('input#prev_step').click(function() {
        var step = $('input#step');
        $.post('http://'+location.host+'/ajax/form_step_back.php', {'step': parseInt(step.val())}, function(data) {
          if (data) {
            window.location.href = window.location.href;
          }
        });
        step.val( parseInt(step.val()) - 1 );
    });
    $('input#next_step').click(function() {
        var step = $('input#step');
        step.val( parseInt(step.val()) + 1 );
    });

    // сохранить расчет
    $('#calc_save').click(function() {
        $.alerts.okButton = 'Закрыть';
        var calculation = $('input#calculation').val();
        if ( calculation != '' ) {
            $.getJSON('http://'+location.host+'/ajax/savecalculation.php', {'calcHash': calculation}, function(obj) {				
                if (typeof obj == 'object'){
                    if (obj.status == 'success') {
                        window.location.href = obj.url;
                    } else {
                        jAlert('Ошибка сохранения расчета.');
                    }
                }
            });


        } else {
            jAlert('Сначала необходимо произвести расчет.');
        }

        return false;
    });

    // продолжить по телефону
    $('#calc_phone_continue').click(function(){
    	$.alerts.okButton = 'Закрыть';
        var calculation = $('input#calculation').val();
        if ( calculation != '' ) {
            var link = $(this).attr('href') + '?calculation=' + calculation;
            window.location.href = link;
        } else {
            jAlert('Сначала необходимо произвести расчет.');
        }

        return false;
    });

    // купить
    $('#calc_buy').click(function(){
      $.alerts.okButton = 'Закрыть';
        var calculation = $('input#calculation').val();
        if (!calculation)
				{
            jAlert('Сначала необходимо произвести расчет.');
            return false;
        }
    });

    // переключение способов доставки
    $('input.delivery_type_select').change(function(){
        var hide = 3 - $(this).val();
        var show = $(this).val();
        $('div#delivery_block_'+hide).slideUp();
        $('div#delivery_block_'+show).slideDown();
    });

    // получение филиалов в городе
    $('select#delivery_region_select').change(function(){
        $.alerts.okButton = 'Закрыть';
        var regionId = $(this).val();

        $.getJSON('http://'+location.host+'/ajax/getdeliveryoffice.php', {'regionId': regionId}, function(obj) {
            if (typeof obj == 'object') {
                if (obj.status == 'success') {
                    $('#delivery_office').html(obj.result);
                } else {
                    jAlert('Ошибка получения данных по региону.');
                }
            }
        });
    }).change();

    // форма подписки
    $('#subscription_form input').change(function(){
        var news_subs = $('#subscription_form input:eq(0)');
        var offers_subs = $('#subscription_form input:eq(1)');
        var email = $('#subscription_form input:eq(2)');

        var subs_checked = news_subs.is(':checked') || offers_subs.is(':checked');
        var email_entered = email.val() != '' ? true :false;
        var errors = $('#subscription_form label[generated=true]:visible').length ? true : false;

        if ( !subs_checked || !email_entered ) {
            $('#subscription_form input[type=submit]').attr('disabled', 'disabled');
        } else if ( !errors ) {
            $('#subscription_form input[type=submit]').removeAttr('disabled');
        }
    });

    $('#subscription_form').validate({
        rules: {
            email: {
                required: true,
                email: true,
                remote: 'http://'+location.host+'/ajax/checksubscriptionemail.php'
            }, 
        },
        messages: {
            email: "E-mail введен неверно или уже используется"
        }
    });

    /**
     * Форма регистрации
     */
    var cache = new Array();
    cache['subject'] = new Array();
    cache['region'] = new Array();
    
    // выбор субъекта
    var megaCity = {
			'77_Москва': '77_0_1_0_Москва',
			'78_Санкт-Петербург': '78_0_1_0_Санкт-Петербург'
			};

		if((megaCity[$("select#kladr_subject").val()] != undefined) && ($("select#kladr_region").val() == 0))
		{
			$("div#kladr_city_wrapper").hide();
		}

    $("select#kladr_subject").change(function(){
        var subject = $(this).val();

        if ( subject != 0 ) {
            $("select#kladr_city").find("option").remove();
            $("div#kladr_city_wrapper").hide();

            // если нет в кэше
            if ( cache['subject'][subject] === undefined ) {
                $.getJSON('http://'+location.host+'/ajax/getkladrrecords.php', {'subject': subject}, function(response) {
                    if (typeof response == 'object') {
                        if (response.status == 'success') {
                            result = response.result;
                            cache['subject'][subject] = result;
                            buildSelectors($("select#kladr_region"), result);
                            if((megaCity[subject] != undefined) && ($("select#kladr_region").val() == 0))
                            {
                            	$("select#kladr_region").val(megaCity[subject]);
                            	$("div#kladr_city_wrapper").hide();
														}
                        }
                    }
                });
            } else {
                result = cache['subject'][subject];
                buildSelectors($("select#kladr_region"), result);
            }


        } else {
            $("select#kladr_region").find("option").remove();
            $("div#kladr_region_wrapper").hide();
            $("select#kladr_city").find("option").remove();
            $("div#kladr_city_wrapper").hide();
        }
    }).change();

    // выбор региона
    $("select#kladr_region").change(function(){
        var region = $(this).val();

        if ( region != 0 ) {

            // если нет в кэше
            if ( cache['region'][region] === undefined ) {
                $.getJSON('http://'+location.host+'/ajax/getkladrrecords.php', {'region': region}, function(response) {
                    if (typeof response == 'object') {
                        if (response.status == 'success') {
                            result = response.result;
                            cache['region'][region] = result;
                            buildSelectors($("select#kladr_city"), result);
                            
                            $("select#kladr_city").val(region);//find("option:selected").html("----");
                            if(megaCity[$("select#kladr_subject").val()] != undefined)
                            {
                            	$("div#kladr_city_wrapper").hide();
														}
                        } else {
                            $("select#kladr_city").find("option").remove();
                            $("div#kladr_city_wrapper").hide();
                        }
                    }
                });
            } else {
                result = cache['region'][region];
                buildSelectors($("select#kladr_city"), result);
            }
            subject = $("select#kladr_region").val();
            if($("select#kladr_subject").val() != undefined && region)
            {
            	$("div#kladr_city_wrapper").hide();
						}
        } else {
            $("select#kladr_city").find("option").remove();
            $("div#kladr_city_wrapper").hide();
        }
    });

    // подробное описание руководства
    $("a.show_management").click(function(){
        $(this).next().toggle();
        $(this).find('span').toggleClass('dnone');
        return false;
    });

    // подстветка
    $(".list_table tr").mouseover(function(){
        $(this).addClass("tr_hover");
    });
    $(".list_table tr").mouseout(function(){
        $(this).removeClass("tr_hover");
    });

    // табы
/*
    var tabs = {'physical': 'legal', 'legal': 'physical'};
    $("div.tab").mouseover(function(){
        var id = $(this).attr('id');
        var panelId = id.substr(id.indexOf('_')+1);

        $("#"+tabs[panelId]+"").hide();
        $("#tab_"+tabs[panelId]+"").removeClass('tab_active');

        $("#"+panelId+"").show();
        if (!$(this).hasClass('tab_active')) $(this).addClass('tab_active');

    });

    $("div#tabs").mouseleave(function(){
        if (!$("div#tab_physical").hasClass('tab_title')) {
            $("div#physical").hide();
            $("div#legal").hide();
        }
    });
*/
    // слайд шоу
    $('#slides').slides({
        preload: true,
        preloadImage: '/images/ajax-loader.gif',
        generateNextPrev: false,
        play: 5000,
        pause: 1,
        hoverPause: true,
        effect: 'fade'
    });

    $('.panel a').mouseover(function(){
        $(this).addClass('panel_active');
        $(this).children('img').eq(0).hide();
        $(this).children('img').eq(1).show();
    });

    $('.panel a').mouseleave(function(){
        $(this).removeClass('panel_active');
        $(this).children('img').eq(1).hide();
        $(this).children('img').eq(0).show();
    });

    $('a.city, a.threeangle').click(function(){
        $('#region_popup').toggle();
        return false;
    });

    $('#calculate_link').click(function(){
        $('#polis_popup').show();
        return false;
    });
    
    $('#calculate_link2').click(function(){
        $('#polis_popup').hide();
        return false;
    });

    $('#subscribe_link').click(function(){
        $('#subscribe_popup').show();
        return false;
    });

    $('#subscribe_link2').click(function(){
        $('#subscribe_popup').hide();
        return false;
    });
		   
	// стрелка левого меню
	intHeight = $('.left_menu .select div').height() + 10
	//	$('<div class="triangle"/>').insertBefore('.left_menu li.select div')
	intMid = intHeight/2;
	$('.left_menu .triangle').css('border-top',intMid+'px solid transparent')
	$('.left_menu .triangle').css('border-left','25px solid #556670')
	$('.left_menu .triangle').css('border-bottom',intMid+'px solid transparent')
	$('.left_menu .triangle').css('display','inline-block')
	// --
	
	// алфавитный указатель в 2 колонки
	intLenght = $('.content_branches div').children().length
	intMid = Math.round(intLenght/2)
	$('<div class="branch_first_column"/>').appendTo('.content_branches')
	$('<div class="branch_second_column"/>').appendTo('.content_branches')
	$('<div class="clearfix"/>').appendTo('.content_branches')
	n = 0
	$('.content_branches div.branch').each(function(){
		n = n + $(this).children().length
		sContent = $(this).html()
		if(n <= intMid + 1){
			$(".branch_first_column").append(sContent);
		}else{
			$(".branch_second_column").append(sContent);
		}
		$(this).remove()
	})
	$('.content_branches').show();
	// --
	
	// фон у строк таблиц
	$('table tr:even td').css('background','#F1F3F3');
	$('.noeven tr td').css('background','none');
	// --
	
	// города
	$('.city_link').bind('click', function(){
	  $('.city_list').toggle();
	  return false;
	});
	// --
	
  // баян по клику
	$('.h-year a').bind('click', function(){
	  $(this).parent().parent().find('.h-text').toggle();
	  return false;
	});
	$('.bayan-title a').bind('click', function(){
	  $(this).parent().parent().find('.bayan-text').toggle();
	  return false;
	});
	// --

	// при включении галки, активировать тектовое поле для ввода значения
  if($('#adminForm #f1380').attr('checked'))
  {
		$('input[name="f_StatusCardNumber"]').attr('disabled', '');
		$('#StatusCardNumber').show(0);
	}
	else
	{
		$('input[name="f_StatusCardNumber"]').attr('disabled', '1');
		$('#StatusCardNumber').hide(0);
	}
	$('#adminForm #f1380').bind('change', function(){
	  if($(this).attr('checked'))
	  {
			$('input[name="f_StatusCardNumber"]').removeAttr('disabled');
			$('#StatusCardNumber').show(0);
		}
		else
		{
			$('input[name="f_StatusCardNumber"]').attr('disabled', '1');
			$('#StatusCardNumber').hide(0);
		}
	});
	// --

	// tooltip
	$(".i-click").text('Кликнуть');
   $(".i-i").each(function(){
		  var text = '';
		  txt = $(this).html();
		  $(this).html('<span class="t-info">' + txt + '</span>').show(0);
	 		$(this).qtip({
    		content: txt,
    		style: {width: {max: 300}}
    	});
   });

	// fancy box
	$('.fancy_text').fancybox({
		'transitionIn'	: 'none',
		'transitionOut'	: 'none'
	});
	$('.fancy_iframe, .open_window').fancybox({
		'type'	: 'iframe',
		'transitionIn'	: 'none',
		'transitionOut'	: 'none',
		'height'			: '55%',
		'autoScale'			: false
		});

	// Календарики
	var d = new Date();
	curYear = parseInt(d.getFullYear());
	curDay = parseInt(d.getDate());
	curMonth = parseInt(d.getMonth());
	
	date_options_ru = {
		changeYear:true,
		changeMonth:true,
		showAnim: '',
		firstDay: 1,
		dateFormat: 'dd.mm.yy',
		monthNamesShort: ['Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],
		dayNames: ['Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота'],
		dayNamesMin: ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб']
	};
	
	date_options_global = {
		yearRange: (curYear - 80) + ':' + curYear,
		changeYear:true,
		changeMonth:true,
		showAnim: '',
		firstDay: 1,
		dateFormat: 'dd.mm.yy',
		monthNamesShort: ['Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],
		dayNames: ['Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота'],
		dayNamesMin: ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб']
	};
	date_options_1 = {
		yearRange: (curYear - 80) + ':' + curYear,
		defaultDate: new Date(curYear, curMonth, curDay),
		maxDate:new Date(curYear, curMonth, curDay),
		minDate:new Date(curYear - 80, 01, 01),
		currentText: 'Now',
		dateFormat: 'dd.mm.yy'
	};
	date_options_2 = {
		yearRange: curYear + ':' + (curYear + 50),
		defaultDate: new Date(curYear, curMonth, curDay),
		maxDate:new Date(curYear + 50, 0, 01),
		minDate:new Date(curYear, 0, curDay),
		currentText: 'Now',
		dateFormat: 'dd.mm.yy'
	};
	date_options_3 = {
		yearRange: curYear + ':' + (curYear + 10),
		defaultDate: new Date(curYear, curMonth, curDay),
		minDate:new Date(curYear, 0, curDay),
		maxDate:new Date(curYear + 10, 0, 01),
		currentText: 'Now',
		dateFormat: 'dd.mm.yy'
	};
	date_options_4 = {
		yearRange: (curYear - 60) + ':' + curYear,
		defaultDate: new Date(curYear, curMonth, curDay),
		maxDate:new Date(curYear, curMonth, curDay),
		minDate:new Date(curYear - 60, 01, 01),
		currentText: 'Now',
		dateFormat: 'dd.mm.yy'
	};
	$('.date1').each(function(e){
	  value = $(this).attr('value');
		$(this).attr('defaultValue', value);
	});
	$('.date').datepicker(date_options_global);
	
	$('.date3').datepicker(date_options_global);
	$('.date3').datepicker("option", date_options_2);

	$('.date4').datepicker(date_options_global);
	$('.date4').datepicker("option", date_options_4);
	
	$('.date0').datepicker(date_options_global);
	$('.date0').datepicker("option", date_options_global);
	$('.date0').datepicker("option", date_options_3);
	$('.date1').datepicker(date_options_global);
	$('.date1').datepicker("option", date_options_1);
	$('.date1').each(function(e){
		$(this).datepicker('setDate', $(this).attr('defaultValue'));
	});
	$('.date').datepicker("option", date_options_ru);
	$('.date1').datepicker("option", date_options_ru);
	$('.date2').datepicker("option", date_options_ru);
	$('.date3').datepicker("option", date_options_ru);
	$('.date4').datepicker("option", date_options_ru);
	$('.date5').datepicker("option", date_options_ru);
	$('#date').datepicker("option", date_options_ru);
	// /Календарики

	$('#date').focus(function(){
		$(this).next('div').css('display','block');
	});
	
	$('.date, .date0, .date1, .date2').qtip({
		content: 'Формат: дд.мм.гггг',
		style: {width: {max: 300}}
	});
	$('.phone, [name=f_Phone]').qtip({
		content: 'формат: +7 (ххх) ххх-хх-хх',
		style: {width: {max: 300}}
	});
});
