function setCity(json) {
	$.ajax({
		url: '/index.php',
		data: 'q='+json.city+'&go=ajax/autocomplete&extra=',
		success: function(response) {
			if(response != "Нет совпадений") {
			
				var responseStr = response.split('*')[0];
				var airport = responseStr.substr(responseStr.length-3, 3);
				var html = responseStr.substr(0, responseStr.length-4);
				
				$('#out_search_auto').val(html);
				$('#out_search_auto').attr("check", html);
				
				$('#span_out_search').empty();
				$('#span_out_search').addClass('dist');
				$('#span_out_search').removeClass('grey');
				
				$('#span_out_search').append(html);
				
				$('#out_iata_auto').val(airport);
			}
		}
	});
}

$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});

$(function() {
if($.getUrlVar('tune-search') == null){
    $.getJSON("https://www.aviacassa.ru/geo/geolocate.php?jsoncallback=?");
}
});

//comment
(function($) {
    $.fn.easyTooltip = function(options){      
        // default configuration properties
        var defaults = {    
            xOffset: 10,        
            yOffset: 25,
            tooltipId: "easyTooltip",
            clickRemove: false,
            content: "",
            useElement: ""
        }; 
            
        var options = $.extend(defaults, options);  
        var content;
                
        this.each(function() {                  
            var title = $(this).attr("title");                
            $(this).hover(function(e){                                                                            
                content = (options.content != "") ? options.content : title;
                content = (options.useElement != "") ? $("#" + options.useElement).html() : content;
                $(this).attr("title","");                                                      
                if (content != "" && content != undefined){            
                    $("body").append("<div id='"+ options.tooltipId +"'>"+ content +"</div>");        
                    $("#" + options.tooltipId)
                        .css("position","absolute")
                        .css("top",(e.pageY - options.yOffset) + "px")
                        .css("left",(e.pageX + options.xOffset) + "px")                        
                        .css("display","none")
                        .fadeIn("fast")
                }
            },
            function(){    
                $("#" + options.tooltipId).remove();
                $(this).attr("title",title);
            });    
            $(this).mousemove(function(e){
                $("#" + options.tooltipId)
                    .css("top",(e.pageY - options.yOffset) + "px")
                    .css("left",(e.pageX + options.xOffset) + "px")                    
            });    
            if(options.clickRemove){
                $(this).mousedown(function(e){
                    $("#" + options.tooltipId).remove();
                    $(this).attr("title",title);
                });                
            }
        });
      
    };

})(jQuery);

/*
 * jQuery plugin: fieldSelection - v0.1.0 - last change: 2006-12-16
 * (c) 2006 Alex Brem <alex@0xab.cd> - http://blog.0xab.cd
 */

(function() {
    var fieldSelection = {
        getSelection: function() {
            var e = this.jquery ? this[0] : this;

            return (
                /* mozilla / dom 3.0 */
                ('selectionStart' in e && function() {
                    var l = e.selectionEnd - e.selectionStart;
                    return {
                        start: e.selectionStart,
                        end: e.selectionEnd,
                        length: l,
                        text: e.value.substr(e.selectionStart, l)};
                })

                /* exploder */
                || (document.selection && function() {

                   // e.focus();

                    var r = document.selection.createRange();
                    if (r == null) {
                        return {
                            start: 0,
                            end: e.value.length,
                            length: 0};
                    }

                    var re = e.createTextRange();
                    var rc = re.duplicate();
                    re.moveToBookmark(r.getBookmark());
                    rc.setEndPoint('EndToStart', re);

                    // IE bug - it counts newline as 2 symbols when getting selection coordinates,
                    //  but counts it as one symbol when setting selection
                    var rcLen = rc.text.length,
                        i,
                        rcLenOut = rcLen;
                    for (i = 0; i < rcLen; i++) {
                        if (rc.text.charCodeAt(i) == 13) rcLenOut--;
                    }
                    var rLen = r.text.length,
                        rLenOut = rLen;
                    for (i = 0; i < rLen; i++) {
                        if (r.text.charCodeAt(i) == 13) rLenOut--;
                    }

                    return {
                        start: rcLenOut,
                        end: rcLenOut + rLenOut,
                        length: rLenOut,
                        text: r.text};
                })

                /* browser not supported */
                || function() {
                    return {
                        start: 0,
                        end: e.value.length,
                        length: 0};
                }

            )();

        },

        setSelection: function(start, end) {
            var e = document.getElementById($(this).attr('id')); // I don't know why... but $(this) don't want to work today :-/
            if (!e) {
                return $(this);
            } else if (e.setSelectionRange) { /* WebKit */
                e.focus(); e.setSelectionRange(start, end);
            } else if (e.createTextRange) { /* IE */
                var range = e.createTextRange();
                range.collapse(true);
                range.moveEnd('character', end);
                range.moveStart('character', start);
                range.select();
            } else if (e.selectionStart) { /* Others */
                e.selectionStart = start;
                e.selectionEnd = end;
            }

            return $(this);
        },

        replaceSelection: function() {
            var e = this.jquery ? this[0] : this;
            var text = arguments[0] || '';

            return (
                /* mozilla / dom 3.0 */
                ('selectionStart' in e && function() {
                    e.value = e.value.substr(0, e.selectionStart) + text + e.value.substr(e.selectionEnd, e.value.length);
                    return this;
                })

                /* exploder */
                || (document.selection && function() {
                    e.focus();
                    document.selection.createRange().text = text;
                    return this;
                })

                /* browser not supported */
                || function() {
                    e.value += text;
                    return this;
                }
            )();
        }
    };

    jQuery.each(fieldSelection, function(i) { jQuery.fn[i] = this; });

})();


/* Calendar

1. Сгенерировать массив календаря вокруг текущей даты (текущий месяц + N месяцев вперёд (24). Учитывать високосные годы. Текущая дата должна быть задана при инициализации календаря (дата на сервере)
2. Отобразить календарь, обеспечить переключение месяцев
3. Нужен массив праздничных дней
4. Нужно передавать календарю кол-во дат маршрута
5. Отобразить выбранный диапазон дат (учитывая кол-во точек маршрута)
6. Сделать проверку на правильность диапазона
7. Отрабатывать клик по дате следующим образом:
- Если ни одна из дат не выбрана — выбрать эту дату в качестве первой точки маршрута
- Если есть выбранные даты, но есть хотя бы одна свободная, при этом выбранная дата больше предыдущей — выбрать эту дату в качестве очередной точки маршрута
- ... если дата меньше предыдущей — сбросить все даты, установить выбранную дату в качестве первой точки маршрута
- Если есть выбранные даты, но нет свободных — сбросить все даты, установить выбранную дату в качестве первой точки маршрута
8. Менять значения скрытых селектов

*/

var CALENDAR_MONTHS = ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'];
var CALENDAR_DAYS = ['пн', 'вт', 'ср', 'чт', 'пт', 'сб', 'вс'];

var CALENDAR_SIZE = 24; /* Кол-во месяцев вперёд */
var CALENDAR_MONTH_WIDTH = 196 + 50; /* Ширина одного месяца...*/

$(function(){
	$(window).resize(function(){
		//CALENDAR_MONTH_WIDTH=$(".calendar .month").width()+parseInt($(".calendar .month").css("margin-right"))+"px"	
	})
})

var calendar_scroll_active = 0; /* Флаг устанавливается во время анимации и снимается после */

var month_active = 0; /* Первый из двух месяцев в блоке */

var date_today; /* Тут будет храниться сегодняшняя дата */

var date_array = new Array(); /* Тут будет храниться массив выбранных дат */
var dates_num = 2; /* Кол-во полей дат для выбора */
var dates_current = 1; /* Какая дата выбирается сейчас */
var dates_selected = 0; /* Сколько дат выбрано всего */

/* Доопределим класс Date */

Date.prototype.copy = function () {
  return new Date(this.getTime());
};

Date.prototype.lastday = function() {
  var d = new Date(this.getFullYear(), this.getMonth() + 1, 0);
  return d.getDate();
};

Date.prototype.getDaysBetween = function(d) {
  var d2;

  // дополнительный код для свойств аргументов
  if (arguments.length == 0) {
    d2 = new Date();
  } else if (d instanceof Date) {
    d2 = new Date(d.getTime());
  } else if (typeof d == "string") {
    d2 = new Date(d);
  } else if (arguments.length >= 3) {
    var dte = [0, 0, 0, 0, 0, 0];
    for (var i = 0; i < arguments.length; i++) {
      dte  [i] = arguments[i];
    }
    d2 = new Date(dte[0], dte[1], dte[2], dte[3], dte[4], dte[5]);
  } else if (typeof d == "number") {
    d2 = new Date(d);
  } else {
    return null;
  }

  if (d2 == "Invalid Date")
    return null;
  // Конец дополнительного кода

  d2.setHours(this.getHours(), this.getMinutes(), this.getSeconds(), this.getMilliseconds());

  var diff = d2.getTime() - this.getTime();
  return (diff)/this.msPERDAY;
};

Date.prototype.addDays = function(d) {
  this.setDate( this.getDate() + d );
};

Date.prototype.addWeeks = function(w) {
  this.addDays(w * 7);
};

Date.prototype.addMonths= function(m) {
  var d = this.getDate();
  this.setMonth(this.getMonth() + m);

  if (this.getDate() < d)
    this.setDate(0);
};

Date.prototype.addYears = function(y) {
  var m = this.getMonth();
  this.setFullYear(this.getFullYear() + y);

  if (m < this.getMonth()) {
    this.setDate(0);
  }
};

Date.prototype.getMonthsBetween = function(d) {
  var sDate, eDate;
  var d1 = this.getFullYear() * 12 + this.getMonth();
  var d2 = d.getFullYear() * 12 + d.getMonth();
  var sign;
  var months = 0;

  if (this == d) {
    months = 0;
  } else if (d1 == d2) { //тот же год и месяц
    months = (d.getDate() - this.getDate()) / this.lastday();
  } else {
    if (d1 <  d2) {
      sDate = this;
      eDate = d;
      sign = 1;
    } else {
      sDate = d;
      eDate = this;
      sign = -1;
    }

    var sAdj = sDate.lastday() - sDate.getDate();
    var eAdj = eDate.getDate();
    var adj = (sAdj + eAdj) / sDate.lastday() - 1;
    months = Math.abs(d2 - d1) + adj;
    months = (months * sign)
  }
  return months;
};

function scrollMonth(direction) {
	/* var current_position = $('.months_inside').position(); */
	if(direction == 'left') {
		if(month_active > 0) {
			month_active--;
			calendar_scroll_active = 1;
			$('.months_inside').animate({marginLeft: '+=' + CALENDAR_MONTH_WIDTH},500, function(){calendar_scroll_active = 0});
			updateCalendarTitles();
		}
	}
	if(direction == 'right') {
		if(month_active < CALENDAR_SIZE - 2) {
			month_active++;
			calendar_scroll_active = 1;
			$('.months_inside').animate({marginLeft: '-=' + CALENDAR_MONTH_WIDTH},500, function(){calendar_scroll_active = 0});
			updateCalendarTitles();
		}
	}
}

function updateCalendarTitles() {
	var tmpdate = new Date(date_today.getFullYear(), date_today.getMonth(), 1);
	tmpdate.addMonths(month_active);
	$('#calendar .monthes .period .first').text(CALENDAR_MONTHS[tmpdate.getMonth()]+" "+ tmpdate.getFullYear());
	tmpdate.addMonths(1);
	$('#calendar .monthes .period .second').text(CALENDAR_MONTHS[tmpdate.getMonth()]+" "+ tmpdate.getFullYear());
	tmpdate.addMonths(1);
//	$('#calendar .monthes .next').text(CALENDAR_MONTHS[tmpdate.getMonth()]);
	tmpdate.addMonths(-3);
//	$('#calendar .monthes .prev').text(CALENDAR_MONTHS[tmpdate.getMonth()]);

	if(month_active == 0) {
		$('#calendar .monthes .prev').hide();
	} else {
		$('#calendar .monthes .prev').show();
	}
	if(month_active == CALENDAR_SIZE - 2) {
		$('#calendar .monthes .next').hide();
	} else {
		$('#calendar .monthes .next').show();
	}
}

function createCalendar(sTodayDate) {
	date_today = new Date(sTodayDate);
	var date_counter = date_today.copy();

	//var calendar = $('#calendar');
	$('#calendar').append('<div class="inner"><div class="monthes"><div class="period"><span class="first"></span>  <span class="second"></span></div><a class="prev">&nbsp;</a><a class="next">&nbsp;</a></div><div class="months_area"><div class="months_inside"></div></div></div>');
	$('.months_inside').css({width: (CALENDAR_MONTH_WIDTH * CALENDAR_SIZE) + 'px'});

	$('#calendar .monthes .prev').click(function(){
		if(calendar_scroll_active == 0) scrollMonth('left');
	});
	$('#calendar .monthes .next').click(function(){
		if(calendar_scroll_active == 0) scrollMonth('right');
	});

	for (var i = 0; i < CALENDAR_SIZE; i++) {
		tmpdatestart = new Date(date_counter.getFullYear(), date_counter.getMonth(), 1);
		tmpdateend = new Date(date_counter.getFullYear(), date_counter.getMonth()+1, 0);
		var month = date_counter.getMonth();

		var roll = 1 - tmpdatestart.getDay();
		if(roll > 0) roll = -6;

		tmpdatestart.addDays(roll);

		roll = 7 - tmpdateend.getDay();
		if(roll >= 7) roll = 0;

		tmpdateend.addDays(roll);

		$('#calendar .months_inside').append('<div class="month" id="m'+i+'"></div>');
		var m = $('#m'+i);

		m.append('<div class="name">пн</div><div class="name">вт</div><div class="name">ср</div><div class="name">чт</div><div class="name">пт</div><div class="name red">сб</div><div class="name red">вс</div>');


		while(tmpdatestart <= tmpdateend) {
			if(tmpdatestart < date_today) {
				m.append('<div class="empty">&nbsp;&nbsp;</div>');
			} else {
				if(tmpdatestart.getMonth() != month){
					if(tmpdatestart.getDay() == 0 || tmpdatestart.getDay() == 6){
						m.append('<div class="day redlight" title="'+tmpdatestart.toDateString()+'">'+tmpdatestart.getDate()+'</div>');
					} else {
						m.append('<div class="day grey" title="'+tmpdatestart.toDateString()+'">'+tmpdatestart.getDate()+'</div>');
					}
				} else {
					if(tmpdatestart.getDay() == 0 || tmpdatestart.getDay() == 6){
						m.append('<div class="day red" title="'+tmpdatestart.toDateString()+'">'+tmpdatestart.getDate()+'</div>');
					} else {
						m.append('<div class="day" title="'+tmpdatestart.toDateString()+'">'+tmpdatestart.getDate()+'</div>');
					}
				}
			}
			tmpdatestart.addDays(1);
		}

		date_counter.addMonths(1);
	}
	updateCalendarTitles();

	$('#calendar .day').hover(function(){
		$(this).addClass('c'+dates_current);
	}, function(){
		$(this).removeClass('c'+dates_current);
	});


	$('#calendar .day').click(function(){
		DayClicked(this);
	});
}

function updateCalendar(){
	var stop_execution = false;
	$('#calendar .day').removeClass('empty s0 s1 s2 s3 s4 s5');
	var returnback = $("#trip-type").attr("checked");
	dates_current = 1;
	dates_selected = 0;
	var previous_date = new Date();
	var max_date = previous_date.copy();
	max_date.addMonths(CALENDAR_SIZE);

	for(var i=0;i<dates_num;i++){
		if(!stop_execution){

			var day = parseInt($('.inputdata:not(#back_departure_date) input[name=day'+i+']').val(),10);
			var month = parseInt($('.inputdata:not(#back_departure_date) input[name=month'+i+']').val(),10);
			var year = parseInt($('.inputdata:not(#back_departure_date) input[name=year'+i+']').val(),10);

			if($('#trip-type').is(':checked') && i==1){
				var day = parseInt($('#back_departure_date input[name=day'+i+']').val(),10);
				var month = parseInt($('#back_departure_date input[name=month'+i+']').val(),10);
				var year = parseInt($('#back_departure_date input[name=year'+i+']').val(),10);
			}

			if((day > 1 && day <= 31) && (month > 1 && month <= 12) && (year >= 2000 && year <= 2099)){
				var newdate = new Date(year, month - 1, day);
				if(newdate.valueOf() > previous_date.valueOf()) {
					DayClicked($('#calendar .day[title='+ newdate.toDateString() +']'));
					previous_date = newdate.copy();

					if (parseInt(day)<10) day = "0"+day;
					if (parseInt(month)<10) month = "0"+month;
					
					$("#departure_date"+i).val(""+ day + "." + month + "." + year);
				} else stop_execution = true;
			} else stop_execution = true;
		}
	}
}

function drawDates(dontupdateform) {
	for(var i=1;i<=5;i++){
		$('#calendar .s'+i).removeClass('s'+i);
		$('#calendar .c'+i).removeClass('c'+i);
	}
	$('#calendar .s0').removeClass('s0');

	for(var i=0;i<dates_selected-1;i++){
		var tmpdate = date_array[i].copy();
		var todate = date_array[i+1].copy();
		var m = getDateNum(tmpdate);
		$('#calendar #m'+m+' .day[title="'+ tmpdate.toDateString()+'"]').addClass('s'+(i+1));
		tmpdate.addDays(1);
		while(tmpdate < todate){
			var m = getDateNum(tmpdate);
			$('#calendar #m'+m+' .day[title="'+ tmpdate.toDateString()+'"]').addClass('s0');
			tmpdate.addDays(1);
		}
	}
	
	var tmpdate = date_array[i].copy();
	var m = getDateNum(tmpdate);
	$('#calendar #m'+m+' .day[title="'+ tmpdate.toDateString()+'"]').addClass('s'+(i+1));

	if(!dontupdateform)	{
		FormSetDate();
	}
}

function DayClicked(obj, dontupdateform){
	var date_selected = new Date($(obj).attr('title'));

	if(dates_selected == dates_num) {
		dates_selected = 0;
		dates_current = 1;
	}

	if(date_selected >= date_today) {
		for(var i=1;i<dates_current;i++){
			if(date_selected < date_array[i-1]){
				/* Попытка указать дату предшествующую вылету - Сбрасываем и начинаем сначала*/
				dates_current = 1;
				dates_selected = 0;
				break;
			}
		}
		if(dates_current <= dates_num) {
			date_array[dates_current - 1] = date_selected.copy();
			dates_current++;
			if(dates_current > dates_num) dates_current = 1;
			dates_selected++;
		}
	}
	drawDates(dontupdateform);
}
function getDateNum(dt) {
	/* dt is Date */
	var m = 0;
	var todate = new Date(dt.getFullYear(), dt.getMonth());
	var tmpdate = new Date(date_today.getFullYear(), date_today.getMonth());
	while(tmpdate < todate){
		m++;
		tmpdate.addMonths(1);
	}
	return m;
}

function FormSetDate(){
	for(var i=1;i<=5;i++){
		var date = new Date($('#calendar .s'+i).attr("title"));
		var day = date.getDate();
		var month = date.getMonth()+1;
		var year = date.getFullYear();
		if (day) {
			if (parseInt(day)<10) {day = "0"+day}
			if (parseInt(month)<10) {month = "0"+month}

			$(".addflight input[name=day"+(i-1)+"], .direction input[name=day"+(i-1)+"]").attr("value", day).addClass("black");
			$(".addflight input[name=month"+(i-1)+"], .direction input[name=month"+(i-1)+"]").attr("value", month).addClass("black");
			$(".addflight input[name=year"+(i-1)+"], .direction input[name=year"+(i-1)+"]").attr("value", year).addClass("black");
			$("#departure_date-error, #back_departure_date-error, #cr_date2-error, #cr_date1-error, #cr_date3-error, #cr_date4-error").css("display", "none")

			if ($(".backtoggle").css("display") == "none" && i-1 == 1){
				$(".plate_yellow #departure_date"+(i-1)).val(""+ day + "." + month + "." + year);
			} else {
				$("#departure_date"+(i-1)).val(""+ day + "." + month + "." + year);				
			}	
		}
	}
	if (!$.browser.msie){ 
		$('.enter_date input').fadeOut(1).fadeIn(1);
	}
}

var mousemoved = 1;
var step = 0;
var tuneSearch=false;
var next = "";



/* app.js */


$(function() {
	$("table.transparent tr:last td").css("border", "none")

	$(".steps div.step a").hover(
		function(){
                        if (!$(this).parent().hasClass('green'))
                                $(this).parent().next('div').find("div.right").css("background", "url(templates/boring/images/step_green_point.png) left top no-repeat")
                },
                function(){
                        if (!$(this).parent().hasClass('green'))
                                $(this).parent().next('div').find("div.right").css("background", "url(templates/boring/images/step_white_point.png) left top no-repeat")
                }
	)
	$(".flightclasses a").click(function(){
			if ($(this).hasClass('active_class')){
					$(this).css("background-position", "0 0px").removeClass('active_class');
					$("input[name=class]", $(this).parent()).val('all');
					$('.cr_class').val('all');
			}
			else{
					$("a", $(this).parent()).css("background-position", "0 0").removeClass('active_class');
					$(this).css("background-position", "0 -50px").addClass('active_class');
					$("input[name=class]", $(this).parent()).val($(this).attr('id'));
					$('.cr_class').val($(this).attr('id'));
			}
		})
	/*вываливающийся список для формы на главной*/
	$("#dropdownmain1, #dropdownmain2").click(function(){
		var checked = "";
		$(".dest", $(this)).css("display", "none")
		$("input[type=text]", $(this)).css("display", "block")
		var list = $(this).nextAll(".ac_results").css("display", "block")

		$("li", list).click(function(){
			$(this).html()
			$("input", $(this).parents(".ac_results").prevAll(".search")).css("display", "none")
			$(".dest", $(this).parents(".ac_results").css("display", "none").prevAll(".search")).css("display", "block").html($(this).html())
		})
	})

	$("#todroplist3").click(function(){
		var parent = $(this).parents(".fordroplist")
		$(".ac_results", parent).css("display", "block")
		$(".ac_results li", parent).click(function(){
			$("input[type=text]", parent).css("display", "none")
			$("div#listentered", parent).html($(this).html())
			$(".ac_results", parent).css("display", "none")
		})
	})

	$("body").click(function(evt){
		evt=evt||event;
		if (!$(evt.target).parents().hasClass("inputdata")  && !$(evt.target).parents().hasClass("fordroplist")){
			$("div.ac_results").css("display", "none")
		}
	})

	/*для форм с подсказками*/
	/*$("input[value]").each(function(){
		$(this).attr("comment", $(this).attr("value").length)
	})*/
	//$("input[value][comment]").each(handleFormComments);
init_inputs();
	$("form").submit(function(){
		$("input[value][comment]", $(this)).each(function(){
			var value = $.trim($(this).attr("value"));
			var comment = $.trim($(this).attr("comment"));
			if (value == comment){
				$(this).removeAttr("comment").val("");
			}
		})
	})


	/*установление ползунка при клике на края линейки*/
	$(".diaposons .diaposon .line .rightarea").click(
		function(){
			var slider = $(this).parent(".line").children(".ui-slider").attr("id")
			var val0 = $("#"+slider).slider("values", 0)
			$("#"+slider).slider({
				values: [val0, 1440]
			})
			$("span."+slider+" .to").text("24:00")
		}
	)
	$(".diaposons .diaposon .line .leftarea").click(
		function(){
			var slider = $(this).parent(".line").children(".ui-slider").attr("id")
			var val1 = $("#"+slider).slider("values", 1)
			$("#"+slider).slider({
				values: [0, val1]
			})
			$("span."+slider+" .from").text("00:00")
		}
	)

	$(".diaposons .red .ui-slider a:first").css("background", "url(/static/cms/sites/43/images/diaposon/red_left.gif) left top no-repeat")
	$(".diaposons .red .ui-slider a:last").css("background", "url(/static/cms/sites/43/images/diaposon/red_right.gif) left top no-repeat")

	$(".diaposons .yellow .ui-slider a:first").css("background", "url(/static/cms/sites/43/images/diaposon/yellow_left.gif) left top no-repeat")
	$(".diaposons .yellow .ui-slider a:last").css("background", "url(/static/cms/sites/43/images/diaposon/yellow_right.gif) left top no-repeat")

	$(".diaposons .green .ui-slider a:first").css("background", "url(/static/cms/sites/43/images/diaposon/green_left.gif) left top no-repeat")
	$(".diaposons .green .ui-slider a:last").css("background", "url(/static/cms/sites/43/images/diaposon/green_right.gif) left top no-repeat")

	$(".diaposons .blue .ui-slider a:first").css("background", "url(/static/cms/sites/43/images/diaposon/blue_left.gif) left top no-repeat")
	$(".diaposons .blue .ui-slider a:last").css("background", "url(/static/cms/sites/43/images/diaposon/blue_right.gif) left top no-repeat")

	$(".diaposons .violet .ui-slider a:first").css("background", "url(/static/cms/sites/43/images/diaposon/violet_left.gif) left top no-repeat")
	$(".diaposons .violet .ui-slider a:last").css("background", "url(/static/cms/sites/43/images/diaposon/violet_right.gif) left top no-repeat")

	/*переключение верхнего блока "туда-обратно"*/
	$("#search-form #trip-type").click(function(){
triptype();
		if ($(this).attr("checked")) {
			$("#point-image").attr("src", "/static/cms/sites/43/images/direct_points.png").css("margin-top", "35px")
			$(".backtoggle").css("display", "block")
			$("#search-form .search").eq(0).css("width", "294px")
			$("#search-form .search").eq(1).css("width", "294px")

		} else {
			$("#point-image").attr("src", "/static/cms/sites/43/images/direct_point.gif").css("margin-top", "38px")
			$(".backtoggle").css("display", "none")
			$("#search-form .search").eq(0).css("width", "352px")
			$("#search-form .search").eq(1).css("width", "352px")
		}
	});

	/*переключение "добавить пункт назначения"*/
	$("#addpunkt").click(addflight);
	function addflight() {
		$("#trip-type").removeAttr("checked").css("display", "none").next().css("display", "none");
		$(".backtoggle").css("display", "none");
		$(".direction .search").eq(0).css("width", "352px");
		$(".direction .search").eq(1).css("width", "352px");
		$("img.change").attr("src", "/static/cms/sites/43/images/direct_point.png")
		next = $(this).attr("next");
		$(".reservation").css("padding-bottom", "26px");
		$(".reservation .wrapplates").css("background", "url(/static/cms/sites/43/images/bgwrapplates.png) left bottom no-repeat")

		if (step < 4) {
			fill_location(step, tuneSearch);
			addValidateClass(next);
			$(".addflight img.close").eq(next-1).css("display", "none");
			$(".addflight .close").eq(next).css("display", "block");
			$(".direction").css("background", "url('/static/cms/sites/43/images/navigation_plate_nobg.png') left top no-repeat")
			$(".addflight").eq(next).css("display", "block");
			step = eval(next)+1;
		}

		if (step == 4) {
			$("#hideshowaddpunkt").css("visibility", "hidden")
		}

		$("#addpunkt").attr("next", step);
		dates_num = step+1;
		if(dates_selected == step) dates_current = dates_num;
		updateCalendar();
		triptype();
		return false;
	}

	function destinate(){
		var returnback = $("#trip-type").attr("checked");
		if (returnback){
			if ($(".backtoggle").css("display") == "block" && $(".backtoggle").children().length == 0) {
				//$(".backtoggle").html("<label>Когда назад:</label><div class='inputdata' id='back_departure_date'><img src='/static/cms/sites/43/images/bg_input_left.gif' width='6' height='32' alt='' class='left' /><div class='search enter_date' ><input type='text' name='day1' comment='дд' value='' /> . <input type='text' name='month1'  comment='мм'  value='' /> . <input type='text' name='year1'  comment='гггг' value='' class='year' /><input type='hidden' id='departure_date1' /></div><img src='/static/cms/sites/43/images/bg_input_right.gif' width='4' height='32' alt='' class='right' /></div>");
				$("input[value][comment]").each(handleFormComments);
			}
			dates_num = 2;
			//drawDates()
		} else {
			//$(".backtoggle *").remove()
			//$("a.find").attr("href", "boring_avia_01_target_results_01.html")
			dates_num = 1;
			//drawDates()

		}
		updateCalendar();
	}

	$("#trip-type").click(destinate);

	$(".addflight .close").click(function(){	
		var InputIndex = $(this).parent(".addflight").index();
		
		$("div#span_cr_search_"+InputIndex+"").text("");
		$("div#span_cr_back_search_"+InputIndex+"").text("");
		
		$("input[name=cr_search["+InputIndex+"]]").val("").attr("check", "");
		$("input[name=cr_iata["+InputIndex+"]]").val("");


		$("input[name=cr_back_search["+InputIndex+"]]").val("").attr("check", "");
		$("input[name=cr_back_iata["+InputIndex+"]]").val("");

		$(".addflight #departure_date"+InputIndex+"").val("");
		$(".addflight input[name=day"+InputIndex+"]").attr("comment", "дд").val("дд").removeClass("black");
		$(".addflight input[name=month"+InputIndex+"]").attr("comment", "мм").val("мм").removeClass("black");
		$(".addflight input[name=year"+InputIndex+"]").attr("comment", "гггг").val("гггг").removeClass("black");
		

		$("#hideshowaddpunkt").css("visibility", "visible")
		$(this).parent(".addflight").css("display", "none");
		$where = $(this).parent(".addflight").prev()
		$("img.close", $where).css("display", "block")
		step -= 1;
		dates_num = step+1;
		if(dates_selected == step + 1) {
			dates_selected--;
		}
		if(dates_current == step) {
			dates_current = 1;
		}
		removeValidateClass(step);
		$("#addpunkt").attr("next", step)
		if (step == 0){
			//$("a.find").attr("href", "boring_avia_01_target_results_01.html")
			$("#trip-type").removeAttr("checked").css("display", "inline").next().css("display", "inline")
			$(".reservation").css("padding-bottom", "10px")
		}
		updateCalendar();
		triptype();
	})

	/*показывем полную форму при клике на инпут для контентной страницы*/
	$("#search-form .direction input").focus(function(){
		$(".hidefullform .col1, .hidefullform .col2").css("display", "block")
		$(".hidefullform .reservation").css({"background" : "url(/static/cms/sites/43/images/reg_bottom_bg.gif) left bottom no-repeat  #356AA1", "margin-bottom" : "19px"})
		$(".reservation .top_bg").css({"background" : 'url(/static/cms/sites/43/images/reg_top_bg.jpg) left 24px no-repeat', "min-height" : "310px"})
	})



	/*переключение "хочу детей"*/
	$("#addchildren").toggle(
		  function () {
			$(this).html("<a href=''>Не хочу детей</a>").children().css("background", "url('/static/cms/sites/43/images/minus_punkt.gif') left center no-repeat")
			$("#childrenselect").css("display", "block")
			$("#footer").css("bottom", "0")
		  },
		  function () {
			$(this).html("<a href=''>Хочу детей</a>").css("background", "url('/static/cms/sites/43/images/add_punkt.gif') left center no-repeat")
			$("#childrenselect").css("display", "none")
			$("#footer").css("bottom", "0")
		  }
	)

	$(".passengerscount a[value]").click(function(){
		checkpassengeerscount($(this));
		return false;
	})

	/*определяет показывть ли блок "хочу детеей"*/
	$("#childrenselect .passengerscount").each(function(){
		var ischild = parseInt($("input[type=hidden]", $(this)).val())
		if (ischild>0) {
			$("#addchildren").html("<a href=''>Не хочу детей</a>").children().css("background", "url('/static/cms/sites/43/images/minus_punkt.gif') left center no-repeat")
			$("#childrenselect").css("display", "block")
		}
	})


	/*выставление количества пассажиров, если те зараннее указаны в скрытых полях*/
	$(".passengerscount").each(function(){
		var value = $("input[type=hidden]", $(this)).val()
		$("a[value]", $(this)).css("background-position", "0 0").removeAttr("current")
		$("a[value="+value+"]", $(this)).attr("current", "1").css("background-position", "0 -40px")
	})

	$(".passengerscount a[current=1]").each(function(){
		checkpassengeerscount($(this))
	})

	/*функция выбора количества пассажиров*/
	function checkpassengeerscount(obj){
		if (obj.css("opacity") != "1") {
			return false
		}

		$parent = obj.parent();
		var currentval =  parseInt(obj.attr("value"));
		$("input[name="+$parent.attr("id")+"]", $parent).attr("value", currentval)

		$("a", $parent).css("background-position", "0 0").removeAttr("current").css("opacity", "1")
		obj.css("background-position", "0 -40px").attr("current", "1")

		var maxpassengers = 6;
		var aviableshow = 0;
		var peoplecount = 0;

		$(".passengerscount input[type=hidden]").each(function(){
			peoplecount+= parseInt($(this).val())
		})

		aviableshow = maxpassengers-peoplecount;

		$(".passengerscount").each(function(){
		var index = parseInt($("a[current]", $(this)).index())
			var thvalue = $(this).find("a[current]").attr('value');
			$("a[value]", $(this)).css("opacity", "1");
			$("a[value="+(thvalue*1+aviableshow*1)+"]", $(this)).nextAll("a[value]").css("opacity", "0.2");
		})

	}

	/*подсветка и выделение звёздочкой полётов*/

	$(".blueborderedflights, .blueborderedflight, .yellowborderedflights,  .yellowborderedflight").click(function(evt){
		evt=evt||event;
		var parent = $(evt.target).parents(".selectflight").attr("class")
		var display = $(".hideflights", $(this)).css("display")


		if (parent == "selectflight" && display != "block") {
			display = "block"
		}

		if (display == "none") {
			$(".hideflights", $(this)).css("display", "block")
		} else {
			$(".hideflights", $(this)).css("display", "none")
		}

	})

	$(".chooseflight a.star").click(function(){
		var parent1 = $(this).parents(".blueborderedflights").attr("class")
		var parent2 = $(this).parents(".yellowborderedflights").attr("class")
		var parent3 = $(this).parents(".blueborderedflight").attr("class")
		var parent4 = $(this).parents(".yellowborderedflight").attr("class")


		if (parent1){
			var parent = $(this).parents(".blueborderedflights")
			$(parent).removeClass().addClass("yellowborderedflights")
			$(".chooseflight", $(parent)).removeClass("star").css("background", "url('/static/cms/sites/43/images/star_yellow.gif') right top no-repeat")
			$("img.top", $(parent)).attr("src", "/static/cms/sites/43/images/top_yellow_pieces.gif")
			$("img.bot", $(parent)).attr("src", "/static/cms/sites/43/images/bottom_yellow_pieces.gif")
			$("img.top.no_show", $(parent)).attr("src", "/static/cms/sites/43/images/top_blue_pieces_print.gif")
			$("img.bot.no_show", $(parent)).attr("src", "/static/cms/sites/43/images/bottom_blue_pieces_print.gif")
		}

		if (parent2){
			var parent = $(this).parents(".yellowborderedflights")
			$(parent).removeClass().addClass("blueborderedflights")
			$(".chooseflight", $(parent)).addClass("star").css("background", "none")
			$("img.top", $(parent)).attr("src", "/static/cms/sites/43/images/top_blue_pieces.gif")
			$("img.top.no_show", $(parent)).attr("src", "/static/cms/sites/43/images/top_blue_pieces_print.gif")
			$("img.bot", $(parent)).attr("src", "/static/cms/sites/43/images/bottom_blue_pieces.gif")
			$("img.bot.no_show", $(parent)).attr("src", "/static/cms/sites/43/images/bottom_blue_pieces_print.gif")
		}

		if (parent3){
			var parent = $(this).parents(".blueborderedflight")
			$(parent).removeClass().addClass("yellowborderedflight")
			$(".chooseflight", $(parent)).removeClass("star").css("background", "url('/static/cms/sites/43/images/star_yellow.gif') right top no-repeat")
		}

		if (parent4){
			var parent = $(this).parents(".yellowborderedflight")
			$(parent).removeClass().addClass("blueborderedflight")
			$(".chooseflight", $(parent)).addClass("star").css("background", "none")
		}

		return false;
	})

	/*прячем и показывем список рейсов на разноцветных плашках вверху*/
	$("a#hideshowplates").toggle(function(){
			$(this).text("показать")
			$("#hideplates").css("display", "none")
		},
		function(){
			$(this).text("свернуть")
			$("#hideplates").css("display", "block")
		}
	)

	/*выпадающий список для сортировки*/
	$(".drop_button").click(function(evt){
		var list = $(this).nextAll(".list")
		$(list).toggle()
		$("li", $(list)).click(function(){
			var val = $(this).attr("val");
			if (!val) {
				var val = $(this).text();
			}

			$("input[type=hidden]", $(list)).attr("value", val).trigger('change');
			$(list).css("display", "none")
			$("li", $(list)).unbind("click");
		})

	})




		 $(".list ul input[type=hidden]").each(function(){
                var current_val = $(this).val()
                var list_val = $(this).closest('ul').find("li[val="+current_val+"]").html();
                if (list_val){
                        $(this).closest(".list").prev("div").html(list_val);
                } else {
                        $(this).closest(".list").prev("div").html(current_val);
                }
        })

        $(".list ul input[type=hidden]").change(function(){
                var current_val = $(this).val()
                var list_val = $(this).closest('ul').find("li[val="+current_val+"]:eq(0)").html();
                if (list_val){
                        $(this).closest(".list").prev("div").html(list_val);
                } else {
                        $(this).closest(".list").prev("div").html(current_val);
                }
        })
	$("body").click(function(evt){
		evt=evt||event;
		if ($(evt.target).attr("class") != "drop_button"){
			$("form .list").css("display", "none");
		}
	})

	/*стираем неправильные даты*/
	$('.enter_date input').live('blur',function(e){
		var inputname = $.trim($(this).attr("name")).substr(0, $.trim($(this).attr("name")).length-1);
		var inputlength = $(this).val().length;
		var inputvalue = $(this).val();
		if (inputname == "day") {
			if (inputlength > 2)	{
				$(this).val("")
			}

			if (inputvalue > 31) {
				$(this).val("")
			}
		}

		if (inputname == "month") {
			if (inputlength > 2)	{
				$(this).val("")
			}

			if (inputvalue > 12) {
				$(this).val("")
			}
		}
		

		if (inputname == "year") {
			if (inputlength > 4)	{
				$(this).val("")
			}

			if (inputvalue < new Date().getFullYear()) {
				$(this).val("")
			}
		}
	})

	$('.enter_date input').live('keypress',function(e){
		if(e.which >= 48 && e.which <= 57){

		} else {
			return false;
		}
	});
	$('.enter_date input').live('keyup',function(e){
		var chars = 2;
		if($(this).is("[name*=year]")) chars = 4;

if(!$(this).is(':hidden') && $(this).getSelection().start == chars){
$(this).next().focus();			
		}



		
		if(e.keyCode != 37 && e.keyCode != 39){
			if($(this).val().length >= 2) updateCalendar();
		} else {

		}
	});


	/*показываем только полеты со звездочками*/
	$("#showonlistars").toggle(
		function(){
			$(this).html("Показать  все рейсы");
			$(".blueborderedflight, .blueborderedflights").css("display", "none");
		},

		function(){
			$(this).html("Показать  только <img src='/static/cms/sites/43/images/star_yellow.gif' width='21' height='19' alt='' />")
			$(".blueborderedflight, .blueborderedflights").css("display", "block");
			if (document.getElementById('filtered').value!='0')	filteravia(0);
		}
	)

	/*включаем фильтр*/
	$("input.dropfilter").click(function(){
          $(".leftcolumn input[type=checkbox]").removeAttr("checked")
        $('#slider1').slider( 'values' , 0 , 1)
        $('#slider1').slider( 'values' , 1 , 1440)
        $("span.slider1 .from").text('00:01')
        $("span.slider1 .to").text('24:00')

        $('#slider2').slider( 'values' , 0 , 1)
        $('#slider2').slider( 'values' , 1 , 1440)
        $("span.slider2 .from").text('00:01')
        $("span.slider2 .to").text('24:00')

        $('#slider3').slider( 'values' , 0 , 1)
        $('#slider3').slider( 'values' , 1 , 1440)
        $("span.slider3 .from").text('00:01')
        $("span.slider3 .to").text('24:00')

        $('#slider4').slider( 'values' , 0 , 1)
        $('#slider4').slider( 'values' , 1 , 1440)
        $("span.slider4 .from").text('00:01')
        $("span.slider4 .to").text('24:00')

        $('#slider5').slider( 'values' , 0 , 1)
        $('#slider5').slider( 'values' , 1 , 1440)
        $("span.slider5 .from").text('00:01')
        $("span.slider5 .to").text('24:00')
        filteravia(0);
	})

	//работа с скроллером
	var scrollcontheight;
	var scrolldownid;
	var scrollupid;
	var toppanel;
	var scroller = $(".scrollpanel .pane");

	var height;

	var canDrag = false;
	var shift_y;



	$("a[ovr]").overlay({		
		mask: {		
			color: '#000',
			loadSpeed: 500,
			opacity: 0.7
		},
		
		closeOnClick: false,		
		fixed: true
	});



	function blockEvent(event) {
		if (!event) {
			event = $(window).event;
		}
		if(event.stopPropagation) event.stopPropagation();
		else event.cancelBubble = true;
		if(event.preventDefault) event.preventDefault();
		else event.returnValue = false;
	}


	$(".scrollpanel a.next").mousedown(function(){
		scrollup()
	})

	function scrollup(){
		height = -1*($(".scrollerins").height()-319)
		var topvar = parseInt($(".scrollerins").css("top"))
		toppanel = 209/height*topvar
		setPosition(toppanel)

		if (topvar > height){
			$(".scrollerins").animate({top: topvar-1+"px"}, 0)
		}
		scrollupid = setTimeout(scrollup, "0")
	}

	$(".scrollpanel a.next").mouseup(function(){
		clearTimeout(scrollupid)
	})

	/*скроллим при клике вверх*/
	$(".scrollpanel a.prev").mousedown(function(){
		scrolldown()
	})

	function scrolldown(){
		var topvar = parseInt($(".scrollerins").css("top"))
		toppanel = 209/height*topvar
		setPosition(toppanel)
		if (topvar < 0){
			$(".scrollerins").animate({top: topvar+1+"px"}, 0)
		}
		scrolldownid = setTimeout(scrolldown, "0")
	}

	$(".scrollpanel a.prev").mouseup(function(){
		clearTimeout(scrolldownid)
	})

	// Эта переменная нам поможет определить:
	// Мы просто двигаем мышью по экрану или все-таки перетаскиваем ползунок

	//var scrollcontheight = parseInt($(".scrollerins").css("height"))-305;

	// Захватить
	scroller.mousedown(function(event){
		drag(event)
	});

	// Перетащить
	$(document).mousemove(function(event){
		move(event)
	})

	// Бросить
	$(document).mouseup(function(){
		drop()
	})

	// Здесь будем хранить начальный сдвиг ползунка

	function drag(event){
		if (!event){
			// Всем известно, что в Mozilla event передается как параметр
			// А в IE его можно получить вот так:
			event = $(window).event;
		}
		// Отметим, что мы захватили ползунок.
		// Теперь при сдвиге мыши, ползунок должен сдвинуться вместе с ней
		canDrag = true;
		// А так же запомним начальный сдвиг
		shift_y = event.clientY - parseInt(scroller.css("top"));
		blockEvent(event);
		return false;
	}

	function move(event){
		if (!event){
			event = $(window).event;
		}
		// Здесь мы как раз и проверяем:
		// Сдвигать ли нам ползунок вслед за мышью, или оставить его неподвижным
		if (canDrag) {
			setPosition(event.clientY - shift_y);
			blockEvent(event);
		}
		return false;
	}

	function drop(){
		// Освобождаем ползунок
		canDrag = false;
	}

	function setPosition(newPosition){
		if ((newPosition <= 209) && (newPosition >= 0)) {
			scroller.css("top", newPosition+"px")
		} else if (newPosition > 209) {
			scroller.css("top",  "209px");
			return false;
		} else {
			scroller.css("top",  "0");
			return false;
		}
		var top = Math.round((scrollcontheight/100)*newPosition*100/209)
		$(".scrollerins").css("top", -top+"px")
		return false;
	}

	$("div[forinput]").each(function(){
		var placename  = $(this).attr("forinput")
		var value = $("input[type=hidden][name="+placename+"]").val()
		$(this).text(value)
	})

	/*закрепление табло*/
	/*временно отключаем
	if ($.browser.msie && jQuery.browser.version == 6.0) {
		var ie6 = true;
	}
	$(window).scroll(function () {
		if ($(this).scrollTop() >134){
			$(".tablo").css({"position" : "fixed", "top" : "0", "z-index" : "1000", "background" : "url(/static/cms/sites/43/images/tablo_rounded.png) left top no-repeat", "height" : "119px"})
			if(ie6){
				var toppos = eval(document.documentElement.scrollTop)
				$(".tablo").css({"position" : "absolute", "top" : toppos})
			}
		}
		if ($(this).scrollTop() <= 134){
			$(".tablo").css({"position" : "relative", "background" : "url(/static/cms/sites/43/images/tablo.png) left top no-repeat", "height" : "116px"})
		}
    });*/

	$(".reservation #point-image").click(function(){
		var OutNew = $("input[name=in_search]").val();
		var OutIataNew = $("input[name=in_iata]").val();

		var InNew= $("input[name=out_search]").val();
		var InIataNew= $("input[name=out_iata]").val();

		$("input[name=in_search]").val(InNew);
		$("input[name=in_iata]").val(InIataNew);

		$("input[name=out_search]").val(OutNew);
		$("input[name=out_iata]").val(OutIataNew);


		var from = $((".row:first .dest"), $(this).parent()).html()
		var to = $(".dest", $(this).next()).html()
		$((".row:first .dest"), $(this).parent()).html(to)
		$(".dest", $(this).next()).html(from)
	})

	$("#departure_date-error, #back_departure_date-error, #cr_date2-error, #cr_date1-error, #cr_date3-error, #cr_date4-error").click(function(){
		$(this).css("display", "none")
	})

	/*оформляем таблицу*/
	$("div#content .col12 table:not(.nodecor)").each(function(){
                $(this).addClass('decor');
		$(this).removeAttr("border").css("width", "100%").wrap("<div class='wrap_table'></div>").before("<img src='/static/cms/sites/43/images/blue_left_c_top_table.gif' width='5' height='5' alt='' class='t_c_l' /><img src='/static/cms/sites/43/images/blue_right_c_top_table.gif' width='5' height='5' alt='' class='t_c_r' />").after("<img src='/static/cms/sites/43/images/left_bot_c_table1.gif' width='5' height='5' alt='' class='b_c_l' /><img src='/static/cms/sites/43/images/right_bot_c_table1.gif' width='5' height='5' alt='' class='b_c_r' />");
	})


	$("div#content .col12 table:not(.nodecor) tr:first td").each(function(){
		$(this).replaceWith("<th>"+ $(this).text() + "</th>")
	})

	$(".hasDatepicker").live("focus", function(){
		//$(this).css("color", "black")
	})

	//вырезаем сортировку по классам
	$(".bluebordered.flightclasses").css("display", "none");

	$("#popup").focus();
})

/*форматирование вывода времени для ползунка слайдера*/
function timeformat(time){
	var hours = Math.floor(time/60);
	if (hours < 10) {
		hours = "0"+hours;
	}
	var minutes = time-(hours*60);
	if (minutes < 10) {
		minutes = "0"+minutes;
	}
	var insert =  hours+":"+minutes;
	return(insert)
}

/*табло*/
var signs = {
	l_0 : "А",
	l_1 : "Б",
	l_2 : "В",
	l_3 : "Г",
	l_4 : "Д",
	l_5 : "Е",
	l_6 : "Ё",
	l_7 : "Ж",
	l_8 : "З",
	l_9 : "И",
	l_10 : "Й",
	l_11 : "К",
	l_12 : "Л",
	l_13 : "М",
	l_14 : "Н",
	l_15 : "О",
	l_16 : "П",
	l_17 : "Р",
	l_18 : "С",
	l_19 : "Т",
	l_20 : "У",
	l_21 : "Ф",
	l_22 : "Х",
	l_23 : "Ц",
	l_24 : "Ч",
	l_25 : "Ш",
	l_26 : "Щ",
	l_27 : "Ъ",
	l_28 : "Ы",
	l_29 : "Ь",
	l_30 : "Э",
	l_31 : "Ю",
	l_32 : "Я",
	l_33 : "A",
	l_34 : "B",
	l_35 : "C",
	l_36 : "D",
	l_37 : "E",
	l_38 : "F",
	l_39 : "G",
	l_40 : "H",
	l_41 : "I",
	l_42 : "J",
	l_43 : "K",
	l_44 : "L",
	l_45 : "M",
	l_46 : "N",
	l_47 : "O",
	l_48 : "P",
	l_49 : "Q",
	l_50 : "R",
	l_51 : "S",
	l_52 : "T",
	l_53 : "U",
	l_54 : "V",
	l_55 : "W",
	l_56 : "X",
	l_57 : "Y",
	l_58 : "Z",
	l_59 : "1",
	l_60 : "2",
	l_61 : "3",
	l_62 : "4",
	l_63 : "5",
	l_64 : "6",
	l_65 : "7",
	l_66 : "8",
	l_67 : "9",
	l_68 : "0",
	l_69 : "-",
	l_70 : ".",
	l_71 : ",",
	l_72 : ":",
	l_73 : ";",
	l_74 : "(",
	l_75 : ")",
	l_76 : "!",
	l_77 : "?",
	l_78 : '"',
	l_79 : "'",
	l_80 : '%',
	l_81 : '+',
	l_82 : '=',
	l_83 : '#',
	l_84 : '$',
	l_97 : "*",
	l_Y : "^",
	l_W : "~"
}

var color = "white";
var ie = $.browser.msie;


function animate(coords, pos,  color, type) {	

	if (color == "white")	{
		$("div", $(".tablo .letter")).eq(pos).css("background", "url(/static/cms/sites/43/images/letters_white.png) left top no-repeat")
	}

	if (color == "yellow"){
		$("div", $(".tablo .letter")).eq(pos).css("background", "url(/static/cms/sites/43/images/letters_yellow.png) left top no-repeat")
	} 

	$("div", $(".tablo .letter").eq(pos)).css("top", "-"+coords+"px");
	clearTimeout(timerid2);
	return false;	

	if (ie == true){
		$("div", $(".tablo .letter").eq(pos)).css("top", "-"+coords+"px");
		clearTimeout(timerid2);
		return false;	
	}

	if (type == "static")	{
		$("div", $(".tablo .letter").eq(pos)).css("top", "-"+coords+"px");
		clearTimeout(timerid2);
		return false;	
	}

	var topstyle = parseInt($("div", $(".tablo .letter").eq(pos)).css("top").split("px")[0])*(-1);
	var top = topstyle+123; 

	if (top>coords) {
		top = coords;
	}

	var timerid2;

	
	
	//$(".email").text(topstyle+" "+coords)
	//если новая буква выше предыдущей
	if (coords < topstyle) {				
		 if (topstyle == coords-41 || coords == 0) {
			 $("div", $(".tablo .letter").eq(pos)).css("left", "0");
		 } else {
			 $("div", $(".tablo .letter").eq(pos)).css("left", "-31px");
		 }
		$("div", $(".tablo .letter").eq(pos)).css("top", "-"+top+"px");
		 timerid2 = setTimeout(function(){animate(coords, pos, color)}, 50)
	
		//если дошли до пробела, возвращаемся наверх
		if (topstyle == 3977) {
			$("div", $(".tablo .letter").eq(pos)).css("top", "0px");
			timerid2 = setTimeout(function(){animate(coords, pos,  color)}, 50);
		}
	}
	
	//если новая буква ниже предыдущей
	if (coords > topstyle) {
		 $("div", $(".tablo .letter").eq(pos)).css("left", "0");
		 $("div", $(".tablo .letter").eq(pos)).css("top", "-"+top+"px");
		 timerid2 = setTimeout(function(){animate(coords, pos, color)}, 50)
	}
	
	//если буква встала на свое место, останавливаем анимацию
	if (coords == topstyle) {		
		 $("div", $(".tablo .letter").eq(pos)).css("left", "0");
		clearTimeout(timerid2);
		return false;				
	}
}

function showword(coords, type){
	for (var i = 0; i<coords.length; i++) {
		if (coords[i] == "Y"){
			coords.splice(i, 1)					
			color = "yellow"
		}

		if (coords[i] == "W"){
			coords.splice(i, 1)				
			color = "white"
		}
		animate(coords[i]*41, i, color, type)
	}					
}


var wordindex=0;

/*создание массива с координатами каждой буквы строки*/
function coordsofword(letterarray, type) {
	var readycoords = new Array();	
	for (var i = 0; i< letterarray.length;  i++) {
		for (var key in signs) {	
			if (signs[key] == letterarray[i]) {
				var top = key.toString().split("_")[1];							
				readycoords[i] = top.toString();
			}								
		}				
	}


	/*выставляем пробелы после окончания фразы*/
	var wordlength = 0;
	for (i=0; i<readycoords.length; i++)	{				
		wordlength++;
		if (readycoords[i] == "Y") {
			wordlength--;
		}

		if (readycoords[i] == "W") {
			wordlength--;
		}
	}

	if (wordlength < 59) {
		$("div", $(".tablo div div.letter").eq(wordlength-1).nextAll()).css("top", "-3977px");	
	}

	showword(readycoords, type)
}	

$(document).mousemove(function(){
	mousemoved = 1;
});

var timerid;

function delay(word_array, stop, type){
	if (stop == "stop"){
		clearTimeout(timerid);
		return false;
	}

	if (mousemoved ==1){ 
		var array_from_word = new Array();	

		for (var i=0; i<word_array[wordindex].toString().length; i++) {
			array_from_word[""+i+""] = word_array[wordindex].toString().substring(i, i+1).toUpperCase()	
		}
		wordindex++;
		coordsofword(array_from_word, type)	
		mousemoved = 0;
	}	

	timerid = setTimeout(function(){delay(word_array, "", type);}, 5000)	

	if (wordindex == word_array.length){
		clearTimeout(timerid);
		if (word_array.length > 1){
			wordindex=0;
			timerid = setTimeout(function(){delay(word_array, "", type);}, 5000)
		}
	}	
}

function handleFormComments(){
	var value = $.trim($(this).attr("value"))
	var comment = $.trim($(this).attr("comment"))
	if (value.length > 0 && value != comment){
		$(this).removeAttr("comment").addClass("black");
	} else if (value.length == 0){
		$(this).val(comment);
		$(this).focus(function(){
			val = $(this).val();
			vallength = $.trim(val).length;
			if(vallength == 0 || val == comment){
				$(this).val("").addClass("black");
			}
		})
		$(this).blur(function(){
			val = $(this).val();
			vallength = $.trim(val).length;
			if(vallength == 0){
				$(this).removeClass("black").val(comment);
			}
		})
	}
}

