﻿// JavaScript Document


var taxiTimeoutId=0;


// Add trim() to any string
String.prototype.trim = function(){
    return this.replace(/^[\s\u00a0]+|[\s\u00a0]+$/g, '');
};

function getFromAirportItems(map,loc) {
	var items = new Array();
	for (var i=0;i<loc.length;i++) {
		var v;
		try {
			v = map[loc[i][0]];
		} catch (err) {
			v = 0;
		}
		if (v) {
			items.push(loc[i]);
		}
	}
	return items;
}

function getFromAirportNItems(map,loc, count) {
	var items = new Array();
	for (var i=0;i<loc.length;i++) {
		var v;
		try {
			v = map[loc[i][0]];
		} catch (err) {
			v = 0;
		}
		if (v) {
			items.push(loc[i]);
		}
		if( items.length>=count ){
			break;
		}
	}
	return items;
}

function getFromMoscowAirportItems(map,loc) {
	var items = new Array();
	for (var i=0;i<loc.length;i++) {
		var v;
		try {
			v = map[loc[i][0]];
		} catch (err) {
			v = 0;
		}
		if (v) {
			items.push(loc[i]);
		}
	}
	return items;
}

												
function getToAirportItems(map,loc,origin) {
	var items = new Array();
	var allowed = map[origin]
	for (var i=0;i<loc.length;i++) {
		if ( jQuery.inArray(loc[i][0], allowed)>-1 ) {
			items.push(loc[i]);
		}
	}
	return items;
}

function printForm() {	
	for (i=0;i<$(".mandatory").length;i++)	{
		if ($(".mandatory:eq("+i+")").val()=="") {
			alert("Please, fill in all neccessary fields.");
			return;
		}		
	}
	window.print();
}

var planeMapTimeout;
function initPlane() {
	$(".plan-img map area").each(function(){
		$(this).attr("ttl",$(this).attr("alt"));
		$(this).attr("alt","");
	});
	
	var $selector = $(".plan-img .img-wrap .selector");
	var $info = $(".plan-img .info");
	var _img = new Image();
	_img.src = $(".plan-img .img-wrap img").attr("src");
	setTimeout(function () {$(".plan-img .img-wrap").css("width",_img.width+"px"); },300 );
	$(".plan-img map area").click(
		function () {
			return false;
		}
	);	
	$(".plan-img map area").mouseover(
		function () {	
			clearTimeout(planeMapTimeout);
			var coords = $(this).attr("coords").split(",");
			var selWidth = coords[2]-coords[0];
			var selHeigth = coords[3]-coords[1];
			$selector.css({width:selWidth+"px",height:selHeigth+"px",left:coords[0]+"px",top:coords[1]+"px"}).show();
			$info.html($(this).attr("ttl"));
		}
	);
	$(".plan-img map area").mouseout(
		function () {			
			planeMapTimeout=setTimeout(function(){$selector.hide();$info.html("");},400);			
		}
	);
	$selector.mouseover(
		function () {			
			clearTimeout(planeMapTimeout);
		}
	);
	$selector.mouseout(
		function () {			
			planeMapTimeout=setTimeout(function(){$selector.hide();$info.html("");},400);			
		}
	);
}

function initPopups() {
	$("a.popupLink").click(
		function () {			
			var popup = $("#"+$(this).attr("popupid"));			
			var exec = $(this).attr("exec");
			if(exec!=null){
				eval(exec);
			}			
			if (popup.is(":visible")) {
				popup.hide(300);
			} else {
				$(".popup").hide(300);
				popup.show(300);
				positionPopup(popup,$(this));
				popup.bgiframe();
			}
			return false;
		}
	);
	$("body").click(
		function(e){
			if (($(e.target).parent(".popupText").length==0)&&(e.target.className!="popupText")&&(e.target.className!="popupHead")) {
				$(".popup[id!=loginError]").filter(".popup[id!=loginPopup").hide(300);
			}
		}
	);
}

function positionPopup(_popup,_source) {
	var popupWidth = 262; //TODO
	var sourcePos = _source.position();	
	//var maxRight = $("body > table:eq(2)").width() + ($("body").width()-$("body > table:eq(2)").width())/2;
	var maxRight = 760 + ($("body").width()-760)/2;
	var maxLeft = maxRight - popupWidth;
	_popup.css({
		left: (sourcePos.left>maxLeft)?((maxRight-popupWidth-4)+"px"):(sourcePos.left + "px"),
		top: (sourcePos.top + _source.outerHeight()+2) + "px"
	});
	
}


function initRules() {
	setTimeout(function(){initContents();},5);
	setTimeout(function(){
	$(".rules_content ol > li").each( 
		function () {
			var _cur=$(this);
		_cur.prepend(" ");		
		appendNumber(_cur);
	});
						},10);
	
}
			
function appendNumber (_in) {
	var _control = _in;					
	do {
		var _parent = _control.parent("ol");
		var _curInd = _parent.children("li").index(_control);
		_in.prepend((_curInd+1)+".");
		var _control =  _parent.parent("li");	
	} 
	while (_control.length!=0)
}

function initContents() {
	$(".contents").html("");
	var sectionsNum = $(".rules_content > ol > li").length;
	for (var i=0; i<sectionsNum; i++) {
		$(".contents").append("<li>"+(i+1)+". <a href='#sect"+(i+1)+"'>"+$(".rules_content > ol > li:eq("+i+")").contents().get(0).nodeValue+"</a></li>");
		$(".rules_content > ol > li:eq("+i+")").prepend("<a name='sect"+(i+1)+"'></a>");
	}
	var subsects = new Array(2,3,4);
	for (var i=0;i<subsects.length;i++){
		var parentItems = $(".rules_content > ol > li:eq("+subsects[i]+") > ol > li");
		var contentItem = $(".contents > li:eq("+subsects[i]+")");
		contentItem.append("<ol/>");
		for (var j=0;j<parentItems.length;j++) {
			contentItem.children("ol").append("<li>"+(subsects[i]+1)+"."+(j+1)+". <a href='#subsect"+(subsects[i]+1)+(j+1)+"'>"+$(parentItems[j]).contents().get(0).nodeValue+"</a></li>");			
			$(parentItems[j]).prepend("<a name='subsect"+(subsects[i]+1)+(j+1)+"'></a>");

		}		
	}
}

function initButtons() {
	//Initializing buttons
	$(document).ready(function(){ 
		$("a.button").click(function () {$(this).get(0).blur() });

		//bind google Analytics
		$("#buyTicketButton").bind("click",function(){
			if( typeof(_gaq)!="undefined" ){
				recordOutboundLinkNoRedirect('Buy ticket', 'Bot buttons '+getCurLang());
			}
		});

		$("#transferButton").bind("click",function(){
			if( typeof(_gaq)!="undefined" ){

				var selectedTransfer = $("input[name='transferType']").filter(":checked").val();
				var actionName="Transfer_2_step_"+selectedTransfer;

				recordOutboundLinkNoRedirect(actionName, 'Bot buttons '+getCurLang());
			}
		});

		$("#carSearchButton").bind("click",function(){
			if( typeof(_gaq)!="undefined" ){
				recordOutboundLinkNoRedirect('Search car', 'Bot buttons '+getCurLang());
			}
		});

		$("#searchHotelButton").bind("click",function(){
			if( typeof(_gaq)!="undefined" ){
				recordOutboundLinkNoRedirect('Search hotel', 'Bot buttons '+getCurLang());
			}
		});

		$("#myBookingButton").bind("click",function(){
			if( typeof(_gaq)!="undefined" ){
				recordOutboundLinkNoRedirect('My booking', 'Bot buttons '+getCurLang());
			}
		});

		$("#boardSearchButton").bind("click",function(){
			if( typeof(_gaq)!="undefined" ){
				recordOutboundLinkNoRedirect('Search board', 'Bot buttons '+getCurLang());
			}
		});

		$("#webCheckInSearchButton").bind("click",function(){
			if( typeof(_gaq)!="undefined" ){
				recordOutboundLinkNoRedirect('Check-in', 'Bot buttons '+getCurLang());
			}
		});

		$("#step_one a.button").bind("click",function(){
			if( typeof(_gaq)!="undefined" ){
				recordOutboundLinkNoRedirect('Transfer_1_step', 'Bot buttons '+getCurLang());
			}
		});

	});
}
function getCurLang(){
	if( typeof(langPath)=="undefined" )	{ return ""; }
		
	return langPath.substring( langPath.length-3 ,langPath.length-1).toUpperCase();
}


var timeoutHideHandler;
var timeoutShowHandler;
var menuDelayShow = 200;
var menuDelayHide = 400;

function initMainNav(lang) {	
	
	//preloading images
	var path=$("#main_nav td img").eq(0).attr("src");
	for (var i=1; i<$("#main_nav td").length;i++){
		var img1=new Image();
		img1.src=path.substring(0, path.lastIndexOf("/"))+"/"+lang+i+"uns.gif";
		var img2=new Image();
		img2.src=path.substring(0, path.lastIndexOf("/"))+"/"+lang+i+"sel.gif";
		var img3=new Image();
		img3.src=path.substring(0, path.lastIndexOf("/"))+"/"+lang+i+"cur.gif";
	}	

	$("#main_nav td > a").hover(
		function () {
			clearTimeout(timeoutShowHandler);
			clearTimeout(timeoutHideHandler);
			if (!$(this).next("ul").hasClass("shown")){
				hideMenus();
				$(this).addClass("hover");
				
				var imgName=$(this).children("img").attr("src");				
				if (imgName.indexOf("cur.gif")==-1 ) {
					$(this).children("img").attr("src",imgName.replace("uns.gif","sel.gif") );
					
				}
				if ($(this).next("ul").length > 0) {
					showMenus(this);					
				}				
			}			
	    },
		function () {
			clearTimeout(timeoutShowHandler);
			clearTimeout(timeoutHideHandler);
			timeoutHideHandler=setTimeout('hideMenus()',menuDelayHide);
		});
	$("#main_nav  td > ul").hover(
		function (){
			clearTimeout(timeoutShowHandler);
			clearTimeout(timeoutHideHandler);
		},
		function (){
			timeoutHideHandler=setTimeout('hideMenus()',menuDelayHide);
	});
	$("#main_nav  td > ul > li").hover(
		function (){$(this).addClass("hover");},
		function (){$(this).removeClass("hover");}
	);
}
					
function showMenus (_ctrl) {
				
	clearTimeout(timeoutShowHandler);
	timeoutShowHandler = setTimeout(function() { 
		var _ul = $(_ctrl).next("ul");									 
		_ul.show().addClass("shown").css("visibility","hidden");			
		_ul.bgiframe();		
						
					//positioning dropdown if needed
		if (_ul.attr("hassize")!="has") {
			var curShown = _ul;
			var curItem = $(_ctrl);
			if (jQuery.boxModel) {				
						var maxwidth = 0;
				curShown.children("li").each(function(){					
					var curWidth = $(this).outerWidth();
							maxwidth = (maxwidth<curWidth)?curWidth:maxwidth;
						});					
				
				if (maxwidth > curItem.children("img").width()) {
							curShown.css("width",(maxwidth)+"px");
							curShown.find("a").css("width",(maxwidth-2-20)+"px");
							curShown.find("li").css("width",(maxwidth-2)+"px");
						}
						else{
							var curWidth = curItem.width();
					curShown.css("width",(curWidth)+"px");
							curShown.find("a").css("width",(curWidth-2-20)+"px");
					curShown.find("li").css("width",(curWidth-2)+"px");
						
				}
						}
						//positioning dropdown menu
						var dropLeft = curShown.position().left;
			var dropWidth = curShown.outerWidth();
						var menuWidth = $("#main_nav").width();
						if ((dropLeft+dropWidth)>menuWidth)	{
							var itemLeft = curItem.find("img").position().left;
				var itemWidth = curItem.outerWidth();
							var itemRight = itemLeft + itemWidth;
							curShown.css("right",(menuWidth-itemRight)+"px");
						}
						curShown.attr("hassize","has");
					}
	
		_ul.css("visibility","visible");

	},menuDelayShow);	
				}				

function hideMenus() {
	$("#main_nav td > ul").hide().removeClass("shown");
	$("#main_nav td a").removeClass("hover");
	$("#main_nav td > a > img[src*='sel.gif']").each(function () {		
		$(this).attr("src",$(this).attr("src").replace("sel.gif","uns.gif") );
	});					
}
	
function hideMenus() {
	$("#main_nav td > ul").hide().removeClass("shown");
	$("#main_nav td a").removeClass("hover");
	$("#main_nav td > a > img[src*='sel.gif']").each(function () {		
		$(this).attr("src",$(this).attr("src").replace("sel.gif","uns.gif") );
	});					
}

function initAccordeon() {
	$(".accordeon > ul > li > a > img").click(
		function(){
			if ($(this).hasClass("expanded")) 
			{
				$(this).parent().next("ul").slideUp(200);
				var newSrc = ($(this).attr("src").indexOf("active")!=-1)?"img/decor/acc_active_collapsed.gif":"img/decor/acc_collapsed.gif";
				$(this).attr("src",newSrc);
				$(this).removeClass("expanded");
				$(this).parent().blur();
			}			
			else
			{
				$(this).parent().next("ul").slideDown(200);	
				var newSrc = ($(this).attr("src").indexOf("active")!=-1)?"img/decor/acc_active_expanded.gif":"img/decor/acc_expanded.gif";
				$(this).attr("src",newSrc);
				$(this).addClass("expanded");
				$(this).parent().blur();
			}
		}		 
	);
}

function addPassport(_table,_info) {
	var rowsNum = $("#"+_table+" tbody tr").length;
	if (rowsNum < 15) {
		var code = $("#"+_table+" thead tr.edit-tamplate").html();
		var code2 = code.replace(/-1/g , rowsNum);
		$("#"+_table+" tbody").append("<tr>" + code2 + "</tr>");
		$("#"+_info).show();
	}

	
}

function initFaq() {
	$(".faq h3>a").toggle(
		function () {
			$(this).parent("h3").next("div").fadeIn("300");
		},
		function () {
			$(this).parent("h3").next("div").fadeOut("300");
		}						  
	);
}

function initTopLog() {
	$("#fake-login").focus(
		function() {
		 	$("#fake-login").hide();
			$("#real-login").show();
			$("#real-login").focus();

		}
	);
	$("#real-login").blur(
		function() {
			if ($(this).val()=="") {
				setTimeout(function(){$("#real-login").hide();},0);
			 	setTimeout(function(){$("#fake-login").show();},0);			
			}
		}
	);
	
	$("#fake-pw").focus(
		function() {
			$("#fake-pw").hide();
			$("#real-pw").show();
			$("#real-pw").focus();

		}
	);
	$("#real-pw").blur(
		function() {
			if ($(this).val()=="") {
				setTimeout(function(){$("#real-pw").hide();},0);
			 	setTimeout(function(){$("#fake-pw").show();},0);			
			}
		}
	);

	$(".log-form").keypress(function (e) {
		if (e.which == 13) {
			loginSubmitForm('ffpLoginForm');
		}
	}); 

}

function initBotTabs () {
	var activeTab = location.hash;
        if (activeTab&&activeTab!="#") {

		//switch inner tabs to  parent
		if(activeTab == "#to_airport" || activeTab == "#from_airport" ){
			activeTab = "#tab_buy";
		}		
		if(activeTab == "#flight-reg-pnr" || activeTab == "#flight-reg-eticket" ){
			activeTab = "#tab_reg";
		}

		setBotTab(activeTab);
	} 
	$(".bot > .tabs > li > span > a:first-child").click(function(){setBotTab($(this).attr("href"));initBuySection();initDeparrRadio();$(".ac_results,.ac_iframe,.ac_options").hide();return false;});

	$(".bot #transfer-tab .tabs > li > span > a:first-child").click(function(){

			$("#step_one").show();
			$(".homepage .bot #step_progress").hide();
			$("#step_two").hide();
			$("#step_progress").hide();
			
			$("#botBuyExpressError").hide();

                        $(".bot #transfer-tab .tabs > li").removeClass("active");

			if( $(this).attr("href")=="#from_airport" ){
				$(".tab6").addClass("active");
				$("#to_airport_div").show();
				$("#from_airport_div").hide();
			}else if($(this).attr("href")=="#to_airport") {
				$(".tab5").addClass("active");
				$("#from_airport_div").show();
				$("#to_airport_div").hide();
			}

			if( $(this).attr("href")=="#flight-reg-pnr" ){
				$(".tab7").addClass("active");
				$("#tab_reg_pnr").show();
				$("#tab_reg_eticket").hide();
			}else if($(this).attr("href")=="#flight-reg-eticket") {
				$(".tab8").addClass("active");
				$("#tab_reg_eticket").show();
				$("#tab_reg_pnr").hide();
			}
                        
			return false;
		});
}

function setBotTab(_tabid) {
	$(".bot > .tabs > li").removeClass("active");
	$(".bot > .tabs > li > span > a[href='"+_tabid+"']").parent().parent().addClass("active");
	$(".bot > .bot-content").hide();
	$(".bot "+_tabid).show();
}

function setLabelFocus () {
	var _ctrl=$(this);
	if (_ctrl.attr("defval")) {
		_ctrl.removeClass("control-notinit").val(_ctrl.attr("defval")).unbind("focus",setLabelFocus);

	} else 
	if (_ctrl.attr("hassuggest")) {
		if (_ctrl.attr("firstfoc")) {
			_ctrl.removeClass("control-notinit");
		} else {
			_ctrl.removeClass("control-notinit").val("").attr("firstfoc","firstfoc");
			
		}
	}
	else {				
		_ctrl.removeClass("control-notinit").val("").unbind("focus",setLabelFocus);				
		setTimeout(function(o) {return function() { 
		   $(o).focus();
		  }}(this),100);
	}
}


jQuery.fn.label= function () {
	var _ctrl=$(this);
	if (_ctrl.get(0).tagName=="INPUT") {
		_ctrl.val(_ctrl.attr("alt")); 
		_ctrl.focus(setLabelFocus);
	}
	if (_ctrl.get(0).tagName=="SELECT") {
		_ctrl.prepend("<option>" + _ctrl.attr("alt") +"</option>");
		_ctrl.children("option:eq(0)").attr("selected","selected");
		_ctrl.mousedown(function(){ 
			_ctrl.removeClass("control-notinit").unbind('mousedown').unbind('focus');
			_ctrl.children("option:eq(0)").remove();
			//_ctrl.children("option:eq(1)").get(0).selected="true"; 
		});
		_ctrl.focus(function(){ 
			_ctrl.removeClass("control-notinit").unbind('mousedown').unbind('focus');
			_ctrl.children("option:eq(0)").remove();	
		});
	}	

    return _ctrl;
}

jQuery.fn.setDatepickerDate = function (_date) { 
	var dt = new Date(_date);
	var dateString = '';

	if (dt.getDate() < 10) {
		dateString += '0';
	}
	dateString += dt.getDate() + '.';
	if (dt.getMonth()+1 < 10) {
		dateString += '0';
	}
	dateString += dt.getMonth()+1 + '.';
	dateString += dt.getFullYear();

	$(this).attr("defval",dateString);
	return $(this);
}

function initBuySection () {	
	if ((siteState != 0) && ($("#tab_buy > #buy-select > div.active, #tab_buy > #buy-select > div.static").attr("id") == "buy_flight"))
		setBuySection("buy_express");

	$('#tab_buy > #buy-select > div').hover(
		function () { if ($(this).hasClass("static")) {$(this).addClass('hover');}}, 
		function () {$(this).removeClass('hover')}
	);
	$("#tab_buy > #buy-select > div.active, #tab_buy > #buy-select > div.static").click(function(){setBuySection($(this).attr("id"));
		if ($(this).attr("id") == "buy_flight") {
			showServicesUnavailableBlock();
		} else {
			hideServicesUnavailableBlock();
		}
	});
}

function setBuySection (_sectid) {	
	$("#tab_buy > #buy-select > div.active").removeClass("active").addClass("static");;	
	$("#tab_buy > #buy-select > #"+_sectid).removeClass("hover").removeClass("static").addClass("active");		
 	$("#tab_buy > .buy-section").hide();	
	$("#tab_buy > ."+_sectid).show();
}

function initDeparrRadio () {
	setDeparrSection($("#tab_deparr input:checked").attr("id"));
	$("#tab_deparr input[type=radio]").click(function(){setTimeout(function(){setDeparrSection($("#tab_deparr label > input:checked").attr("id"));},100) });
	$("#tab_deparr label").click(function(){setTimeout(function(){setBuySection($("#tab_buy > #buy-select > div.active").attr("id"));},50) });
}

function setDeparrSection (_sectid) {	
	var cursect = $("#tab_deparr #"+_sectid);
	$("#tab_deparr label").removeClass("active");	
	cursect.parent().addClass("active");	
 	$("#tab_deparr input.text[id!='board_departure'],#tab_deparr input.custom_dropdown").attr("disabled","disabled").addClass("disabled");
	cursect.parent().parent().parent().find("input.text,input.custom_dropdown").removeAttr("disabled").removeClass("disabled");

}

function populateDropdown(idCode, idTarget, sourOrigin) {
	var code = document.getElementById(idCode).value;
	if (code != '') {
		for (var i=0; i<sourOrigin.length; i++) {
			if (code == sourOrigin[i].code) {
				document.getElementById(idTarget).value = originName[code].name + ' (' + sourOrigin[i].code + ')';
				break;
			}
		}
	}
}

function checkOneWay() {
	$("#oneWay").click(function(){checkWay();});
	$("#returnWay").click(function(){checkWay();});
}

function checkWay () {
	if ($("#oneWay").get(0).checked) {
			$("#flight_return").attr("disabled","disabled").addClass('disabled');
		}
		else {
			$("#flight_return").removeAttr("disabled").removeClass('disabled');	
		}
}

function isChrome() {
	if (navigator.userAgent.toLowerCase().indexOf('chrome') == -1) {
		if (document.getElementById('chromeLink')) {
			document.getElementById('chromeLink').style.display = 'block';
		}
	}
}
/*
var months = {"1":"января","2":"февраля","3":"марта","4":"апреля","5":"мая","6":"июня","7":"июля","8":"августа","9":"сентября","10":"октября","11":"ноября","12":"декабря"};
var weekdays = {"1":"воскресенье","2":"понедельник","3":"вторник","4":"среда","5":"четверг","6":"пятница","7":"суббота"};
var time_of_day = {"0":"ночь","1":"утро","2":"день","3":"вечер"};

var clouds_variants = {"0":"ясно","1":"малооблачно","2":"облачно","3":"пасмурно"};
var falls_variants = {"4":"дождь","5":"ливень","6":"снег","7":"снег","8":"гроза"};
var falls_possibility = {"0":"возможен ","1":"возможна "};
*/
function getDay(obj) {
	return obj.day + " " + months[obj.month];
}

function getTemp(obj) {
	return obj.temp_min + ", " + obj.temp_max;
}

function getClouds(obj) {
	return clouds_variants[obj.clouds];
}

function getFalls(obj) {
	var clouds = clouds_variants[obj.clouds];
	var falls = "";
	if (obj.falls >=4 && obj.falls <= 8) {
		switch (obj.falls) {
			case 4:
			case 5:
				falls = (obj.rpower == 0) ? falls_possibility[0] : falls_variants[obj.falls];
				break;
			case 6:
			case 7:
				falls = (obj.rpower == 0) ? falls_possibility[1] : falls_variants[obj.falls];
				break;
			case 8:
				falls = (obj.spower == 0) ? falls_possibility[2] : falls_variants[obj.falls];
				break;
			default:
				falls = falls_variants[obj.falls]
				break;
		}
	}
	return (falls != '') ? (clouds + ", " + falls) : clouds; 
}

function getIcon(obj) {
	var _f = null;
	switch (obj.falls) {
		case 4:
		case 5:
		case 8:
			_f = 1;
			break;
		case 6:
		case 7:
			_f = 3;
			break;
		default:
			_f = 0;
			break;
	}
	var icon = 0;
	switch (obj.clouds) {
		case 0:
			icon = 0;
			break;
		case 1:
			icon = 1 + _f;
			break;
		case 2:
			icon = 5 + _f;
			break;
		case 3:
			icon = 9 + _f;
			break;
	}
	return ((obj.tod == 1 || obj.tod == 2) ? "/images/icons/weather/day/" : "/images/icons/weather/night/") + icon + ".gif";
}



function showWeather(code) {
	if (typeof (weather) != "undefined" && typeof (weather[code]) != "undefined" && weather[code] != "undefined" ) {
		var now = weather[code][0];

		$today = $(".weather .today");
		$today.text($today.text() + ", " + getDay(now) + " ");
		$("<span class='textBold'>" + getTemp(now) + "</span>").appendTo($today);
		$today.after("<img src='" + getIcon(now) + "' title='" + getFalls(now) + "'/>");

		$table = $(".weather > table > tbody");
		$.each(weather[code], function(i, obj){
			var tr = "";
			tr += "<tr><td class='first'><span class='textBold'>" + getDay(obj) + "</span><br/>" + weekdays[obj.weekday] + "</td>";
			tr += "<td>" + time_of_day[obj.tod] + "</td>";
			tr += "<td class='second'><img src='" + getIcon(obj) + "' title='" + getFalls(obj) + "'/>" + getClouds(obj) + "</td>";
			tr += "<td class='degree'>" + getTemp(obj) + "</td>";
			tr += "<td class='presure'>" + obj.press_min + "</td></tr>";
			$(tr).appendTo($table);
        });
		$(".weather").show();
	}
}
function showPartners() {
	var type = $('#categoryList').val();
	var location = $('#locationList').val();
	if (document.getElementById('hotel_text')) document.getElementById('hotel_text').style.display = 'none';
	if (document.getElementById('car_text')) document.getElementById('car_text').style.display = 'none';
	if (document.getElementById('spa_text')) document.getElementById('spa_text').style.display = 'none';
	if (cases[type] && cases[type][location]) {
		if (type == 'hotel' && document.getElementById('hotel_text')){
			$('#case_hotel').text(cases[type][location]);
			document.getElementById('hotel_text').style.display = 'block';			
		} else if (type == 'car' && document.getElementById('car_text')) {
			$('#case_car').text(cases[type][location]);
			document.getElementById('car_text').style.display = 'block';			
		}		
	}
	var link = sResults[type][location];
	$(document).ready(function(){ s7.getAJAXContent(link,"#partners") });
}

function showPartnersIndex() {
	var type = $('#categoryList').val();
	var location = $('#locationList').val();
	window.location = "../partners.html?type=" + type + "&location=" + location;
}

function showPartnersFromURL() {
	var params =  window.location.search.substring(1); 
	var type = '';
	var location = '';	
	if (params.match('type') && params.match('location')) {
		var pairs = params.split("&");
		for(var i = 0; i < pairs.length; i++) {
			var pos = pairs[i].indexOf('=');
			if (pos == -1) continue;
			var argname = pairs[i].substring(0,pos);
			if (argname == 'type') type = pairs[i].substring(pos+1);
			else if (argname == 'location') location = pairs[i].substring(pos+1);
		}		
		if (type.length != 0 && location.length != 0) {
			var categoryList = document.getElementById('categoryList');
			for (var i = 0; i < categoryList.length; i++) {
				if (categoryList.options[i].value == type) {
					categoryList.selectedIndex = i;
				}
			}
			var locationList = document.getElementById('locationList');
			for (var i = 0; i < locationList.length; i++) {
				if (locationList.options[i].value == location) {
					locationList.selectedIndex = i;
				}
			}
			showPartners();
		}
	}
}

function initPaging() {
	reloadPaging(1);
}

var error_text_default = "error";

var s7 = {

  getAJAXContent : function (source, destination, type, _data, onSuccess, onError) {
    var _type = (type) ? type : "GET";
    this.setAJAXContent('<div class="b-ajax-progress"><img alt="" src="/images/ajax.gif" /></div>',destination);
    $.ajax({
      type: _type,
      url: source,
      data: _data,
      cache: false,
      timeout: 60000, /* in milliseconds */
      dataType: "html",
      success: function(html, textStatus){
        s7.setAJAXContent(html, destination);
        if (onSuccess && jQuery.isFunction(onSuccess)) {
          onSuccess();
        }
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        s7.setAJAXContent(
          '<div class="b-ajax-error">'+error_text_default+'</div>', destination);
        if (onError && jQuery.isFunction(onError)) {
          onError();
        }
      }
    });
  },

  setAJAXContent : function  (html, destination) {
    var _destination = $(destination);
    _destination.html(html);
  }
}

var chosenCategory = '';
var chosenLocation = '';


function changeCategory() {
	var category = $('#categoryList').val();
	var dropdown = document.getElementById('locationList');
	var opt;
	chosenCategory = category;
	dropdown.options.length = 0;
	for (var i = 0; i < dropdownByType[category].length; i++) {
		opt = new Option(sNames[dropdownByType[category][i]],dropdownByType[category][i]);
		if (dropdownByType[category][i] == chosenLocation) {
			opt.setAttribute('selected', true);
		}
		dropdown.options[i] = opt;
	}
}

function changeLocation() {
	var location = $('#locationList').val();
	var dropdown = document.getElementById('categoryList');
	var opt;
	chosenLocation = location;
	dropdown.options.length = 0;
	for (var i = 0; i < dropdownByLocation[location].length; i++) {
		opt = new Option(sNames[dropdownByLocation[location][i]],dropdownByLocation[location][i]);
		if (dropdownByLocation[location][i] == chosenCategory) {
			opt.setAttribute('selected', true);
		}
		dropdown.options[i] = opt;
	}
}

function reloadPaging(page) {
	var partnersQuant = $('#partners > div > table.div-partner-page').size();
	if (partnersQuant != 0) {
		var from = page*5 -4;
		var to;
		if (page*5 > partnersQuant) to = partnersQuant;
		else to =  page*5;
		$('#partnersCurrent').html(from + '-' + to);
		$('#partnersTotal').html(partnersQuant);
		if (partnersQuant > 5 ) {
			document.getElementById('manyPages').style.display = '';
			$('#partPaging').html('|');
			for (var i=1; i<=Math.ceil(partnersQuant/5); i++) {
				if (i == page) {
					document.getElementById('page'+i).style.display = '';
					$('#partPaging').append(' <a><span class="current">' + i + '</span></a> |');				
				}
				else {
					document.getElementById('page'+i).style.display = 'none';
					$('#partPaging').append(' <a href="javascript:void(0)" onclick="reloadPaging('+ i +')"><span class="next">' + i + '</span></a> |');
				}
			}
		} else {
			document.getElementById('manyPages').style.display = 'none';
		}
	}
}


function searchYandexMapObject( inputElement ){

	var MIN_SYMBOLS_COUNT = 3;
	var text = $.trim($(inputElement).val());

	if( text<MIN_SYMBOLS_COUNT ){
	    return false;
	}

	var part = encodeURIComponent(text);

	var testUrl = "http://suggest-maps.yandex.ru/suggest-geo?callback=?&_=1300282255720&ll=37.609218%2C55.753559&spn=2.223358%2C0.534389&part="+part+"&highlight=1&fullpath=1&sep=1&search_type=all";

	$.getJSON(testUrl,
		function(data, textStatus) {
	        
			var phrases = new Array();

			$.each( data[1],function(index,value){
			    var objectName = value[2];
			
			    if( value[0]=="maps" && ( containsSubString( objectName, "Москва" )||containsSubString( objectName, "Московская область" )||containsSubString( objectName, "Moscow" ) )  ){
				phrases.push(objectName);
			    }
			});
	
		        $( inputElement ).autocomplete( "option", "source", phrases );
			$( inputElement ).autocomplete( "option", "delay", 0 );
	});             
}

function containsSubString( str, substr ){
    return (str.indexOf(substr) >=0);
}

function validateYandexObject( inputElement ){
	//validate form
	var message = '';

	var transferValueObject = getTransferValueObject();

	if(transferValueObject.isToAirport){
		if (transferValueObject.textTo == '' || transferValueObject.textTo == $("#transfer_origin_airport_to").attr("alt") ){
		    message += error_transfer_destination.toString() + "<br/>";
		}
	}else{
	        if (transferValueObject.textFrom == '' || transferValueObject.textFrom == $("#transfer_origin_airport").attr("alt")){
		    message += error_transfer_origin.toString() + "<br/>";
		}
	}

	var mess1 = '';
	if (transferValueObject.departureDate == ''
	    || transferValueObject.departureDate == $("#transfer_departure").attr("alt")
	    || transferValueObject.departureDate == $("#transfer_departure_to").attr("alt") ){
		message += error_date_departure2.toString() + "<br/>";
	} else {
	    mess1 = validateDate(transferValueObject.departureDate, true, false);
	    if (mess1 != '') {
		message += mess1 + "<br/>";
	    }
	}

	if (message != '') {
	    $('#botBuyExpressError').html(message).show();
	    return false;
	} else {
	    $('#botBuyExpressError').hide();
	}

	var geocodeString = $(inputElement).val();

	if(typeof(geocodeString)=="undefined" || geocodeString=="" || geocodeString==$(inputElement).attr("alt")){
	    loadTransferPrice("");
	    return false;
	}

	//dev.s7.ru
	//var key='AKAvi00BAAAAcqy3HgMA-6K78l1Cza1KQCnzCcGKCgnOOGIAAAAAAAAAAAAuOVIhalwsYEeFCaIORO7FgQL6Fg==';
	//s7.ru

	var key='AP1Z-E0BAAAAjugKDQIAJT5cgVG05zWRyznDlsdxGj5nfuYAAAAAAAAAAACHlu45VFv5a9V2AYf_GQBYlX_EAw==';

	var llString   = "37.192552,55.487591";
	var spnString  = "38.025884,56.017719";
	var rspnString = 1;

//	if(transferValueObject.house!=""){
//	    geocodeString += ", "+ transferValueObject.house;
//	}

        var url = 'http://geocode-maps.yandex.ru/1.x/?' + 
	    $.param({geocode:geocodeString, ll:llString, spn:spnString, rspn:rspnString }) +
	    '&key='+key+'&format=json&callback=?';

	$("#botBuyExpressError").hide();

	$.getJSON(url,
		function(data, textStatus) {
		  if( typeof(data.response)=="undefined" ){
			return;
		    }
		
		var resultsCount = data.response.GeoObjectCollection.metaDataProperty.GeocoderResponseMetaData.found;
		
		if(resultsCount==0){// object not found
		    //$("#botBuyExpressError").text(error_transfer_object_not_found.toString());
		    //$("#botBuyExpressError").show();
		    
		    var request = data.response.GeoObjectCollection.metaDataProperty.GeocoderResponseMetaData.request;
		    
		    loadTransferPrice(request);
		    return false;
		}else if( resultsCount>=1 ){//if found only one object
		    var text = data.response.GeoObjectCollection.featureMember[0].GeoObject.metaDataProperty.GeocoderMetaData.text;
		    loadTransferPrice(text);
		    return false;
		}
		
		var searchResults = new Array();
		var searchNearestResults = new Array();
		var sourceArray = data.response.GeoObjectCollection.featureMember;
		
		for( var i=0;i<sourceArray.length;i++){
		    var kind = sourceArray[i].GeoObject.metaDataProperty.GeocoderMetaData.kind;
		    var text = sourceArray[i].GeoObject.metaDataProperty.GeocoderMetaData.text;

		    if( kind=="house" || kind=="metro" || kind=="other" ){
			searchResults.push(text);
		    }else{
			searchNearestResults.push(text);
		    }
		};

		if(searchResults.length==1){
		    loadTransferPrice(searchResults[0]);
		    return false;
		}

		if( searchResults.length>0 || searchNearestResults.length>0 ){
		
		    var objectsListHtml = "<ul class='object-list'>";
		    $.each(searchResults, function(index,value){
			objectsListHtml += "<li class='object-item'>"+value+"</li>";
		    });
		    objectsListHtml += "</ul>";
		
		    var nearestsListHtml = "<ul class='nearest-object-list'>";
		    $.each(searchNearestResults, function(index,value){
			nearestsListHtml += "<li class='nearest-object-item'>"+value+"</li>";
		    });
		    nearestsListHtml += "</ul>";

		    $("#objectsList *").remove();
		    $("#objectsList").append(objectsListHtml);
		    
		    $('.object-item').bind('mouseenter', function() {
			$('.object-item').removeClass('entered');
			$(this).addClass('entered');
		    });
		    $('.object-item').bind('mouseleave', function() {
		    	$('.object-item').removeClass('entered');
		    });
		    
		    $('.object-item').bind('click', function() {
			var objectName = $(this).text();
			$(inputElement).val(objectName);
			loadTransferPrice( objectName );
		    });

		    $("#nearestsObjectsList *").remove();
		    $("#nearestsObjectsList").append(nearestsListHtml);

		    $('.nearest-object-item').bind('mouseenter', function() {
		    	$('.nearest-object-item').removeClass('entered');
		    	$(this).addClass('entered');
		    });
		    $('.nearest-object-item').bind('mouseleave', function() {
		    	$('.nearest-object-item').removeClass('entered');
		    });

		    $('.nearest-object-item').bind('click', function() {
    			var objectName = $(this).text();
    			$(inputElement).val(objectName);
    			$("#selectObjectPopup").dialog("close");
		    });
		    $("#selectObjectPopup").dialog("open");
		}
	});
}

function loadTransferPrice(objectName){

	if( objectName=="" ){
	    $("#addressFounded").val( 'false' );
	}

	$("#selectObjectPopup").dialog("close");
        $(".homepage .bot #step_two .transfer-type .transfer-price .price").hide();
        $("#defaultTaxiPrice").hide();

	var transferValueObject = getTransferValueObject();

        loadExpressPrice(transferValueObject);
	loadTaxiPrice(transferValueObject,objectName);

	if(transferValueObject.serviceClass=='B'){
	    loadAETimetable(transferValueObject);
	    $('#time').css("visibility","visible");
	    $('#time').show();
	}else{
	    $('#time').css("visibility","hidden");
	    $('#time').hide();
	}

        $('#timetable').show();

	//printPath();

	$(".homepage .bot #step_one").hide();
	$(".homepage .bot #step_progress").show();

	return false;
}



function loadExpressPrice(transferValueObject) {

        var url = '/servlet/express?method=price';
	var from = transferValueObject.expressFrom;
	var to = transferValueObject.expressTo;
	var date = transferValueObject.departureDate;
	var time = transferValueObject.expressTime;
	var adults = transferValueObject.adultCount.toString();
	var childs = transferValueObject.childCount.toString();
	var service = transferValueObject.serviceClass;

	var formData = {from: from, to: to, departureDate: date, departureTime: time, adultCount: adults, childCount: childs, serviceClass: service};
	if (from != '' && to != '' && date != '' && adults != '' && childs != '' && service != '') {
		$.ajax({type:"GET", url:url, data:formData, dataType:"script", success:function(data,textStat){
			if (expressPrice != null) {
				var price = expressPrice.substring(0, expressPrice.indexOf(','));
				$('#aePrice').text(price);
				$('.homepage .bot #step_two #transferTypeAE .transfer-price .price').show();
			}
		} });
	}
}

function loadTaxiPrice(transferValueObject,objectName) {

	var PASSENGERS_PER_CAR = 4;

	$("#defaultTaxiPrice").hide();

	var carsCount = Math.ceil(( transferValueObject.childCount + transferValueObject.adultCount )/PASSENGERS_PER_CAR);

	var val = buildRoutes(transferValueObject,carsCount,objectName);
	//var val = '{"routes":[{"arrivalAddress":{"fullAddress":"DME"},"destinationAddress":{"fullAddress":"SVO"}}],"carsCount":"1"}';

        var jHandler = "doMap";

	clearTimeout( taxiTimeoutId );
	taxiTimeoutId = setTimeout( function(){
		var isProgress = ($("#step_progress").css("display")=="block");

	    
	    if(isProgress){
		$("#addressFounded").val("false");
		
		$("#taxiDestination").html("");
		$("#taxiDestination").html( "<span>"+taxi_address_not_found+"</span>");

		$("#transferPriceLabel").hide();
		$("#defaultTaxiPriceFrom").hide();
		
		$(".homepage .bot #step_progress").hide();
		$(".homepage .bot #step_two").show();
	    }
	}, 3000)

//    var url = "http://172.21.10.88:18080/taxi-rest/rest/requestPrice?callback=" + jHandler + "&json=" + encodeURIComponent(val)+"&jsoncallback=?";
	var url = "http://service.s7.ru/taxi-rest/rest/requestPrice?callback=" + jHandler + "&json=" + encodeURIComponent(val)+"&jsoncallback=?";

    $.getJSON(url, null, null, "json");
    $("#transferPriceLabel").show();
    printPath();
}


function doMap(obj){

	var transferValueObject = getTransferValueObject();
	var carsCount = transferValueObject.carsCount;

	var priceValue = "";
	var priceType = "";
	var pricePromotion = "";
	
	
	for(  var i=0; i< obj.prices.length; i++){
	    if( obj.prices[i].priceType=="TRIP" || obj.prices[i].priceType=="HALF_HOUR" ){
		priceValue = obj.prices[i].money.amount;
		priceType = obj.prices[i].priceType;

		///break;
	    }

	    if( obj.prices[i].priceType=="PROMOTION" ){
		    pricePromotion = obj.prices[i].money.amount;
;
	    }
	}

	if( pricePromotion!="" ){
	    priceValue=pricePromotion;
	}

	priceValue = priceValue; 

//	$("#taxiPricePerKm").hide();
	$("#taxiPriceHalfHour").hide();
	$("#defaultTaxiPriceFrom").hide();

	if( priceType=="HALF_HOUR" ){

		var pricePerKm=0;
		
		for(  var i=0; i< obj.prices.length; i++){
		    if( obj.prices[i].priceType=="PER_KM" ){
			pricePerKm = obj.prices[i].money.amount; 

			break;
		    }
		}
		$("#taxiPricePerKm").text( pricePerKm);
		$("#taxiPriceHalfHour").text(priceValue);

		$("#taxiPricePerKm").show();
		$("#taxiPriceHalfHour").show();
		$("#defaultTaxiPrice").show();

		$("#defaultTaxiPriceFrom").show();

		$("#addressFounded").val("true");

	}else if ( priceType=="TRIP" ){
		$('.homepage .bot #step_two #transferTypeTaxi .transfer-price .price').show();
		$("#defaultTaxiPrice").hide();

		$("#defaultTaxiPriceFrom").hide();

		$("#taxiPrice").text(priceValue);

		$("#addressFounded").val("true");
	}else{
		$("#addressFounded").val("false");
	}

	printPath();

	$(".homepage .bot #step_progress").hide();
	$(".homepage .bot #step_two").show();
}


function printPath(){
	var transferValueObject = getTransferValueObject();
	var taxiPath = "";

	var delim = "<br/>";
	var space = " ";

	var from = taxi_from + ":";
	var to   = taxi_to   + ":";

	if( transferValueObject.textFrom!="" && transferValueObject.textTo!="" ){
		taxiPath =  from+
			    space+
			    transferValueObject.textFrom+
			    delim+
			    to+
			    space+
			    transferValueObject.textTo;
	}

	var addressFounded = $("#addressFounded").val();

	$("#taxiDestination *").remove();

	if( addressFounded == 'true' ){
		$("#taxiDestination").html(taxiPath);
	}else{
		$("#taxiDestination").html("<span>"+taxi_address_not_found+"</span>");
	}

	var aePath =	from+
			space+
			transferValueObject.expressOrigin+
			delim+
			to+
			space+
			transferValueObject.expressDestination;

	$("#expressDestination").html(aePath);
}



function buildRoutes(transferValueObject,carsCount, objectName) {

    var from =  transferValueObject.from;
	var to   =  transferValueObject.to;

	if(transferValueObject.isToAirport){
	    from = objectName;
        }else{
    	    to   = objectName;
	}

	var routes = 
	    '{"routes":[{"arrivalAddress":{"fullAddress":"'+from
	    +'"},"destinationAddress":{"fullAddress":"'+to
	    +'"}}],"carsCount":"'+carsCount+'"}';

	return routes;
}



function getTransferValueObject(){

	var PASSENGERS_PER_CAR = 4;

	var chdCount  = 0;
	var adtCount  = 0;
	var srvcClass = "";
	var depDate   = "";
	var aeFrom    = "";
	var aeTo      = "";
	var aeTime    = "";
	var aeDest    = "";
	var aeOrig    = "";
	var taxiOrig  = "";

	var txtTo     = "";
	var txtFrom   = "";

	var origin    = "";
	var destination = "";

	var houseNum    = "";

	var isSelectedToAirportTab = $("#to_airport_div").css("display")=="block";

	if(isSelectedToAirportTab){
		adtCount  = parseInt($("#adultCount_to").val());
		chdCount  = parseInt($("#childCount_to").val());
		depDate   = $("#transfer_departure_to").val();
		srvcClass = $("#serviceClass_to").val();
		taxiDest  = $("#transfer_to_airport").val();
		aeDest  = $("#transfer_origin_airport_to").val();

		var railwayCode = $("#transfer_origin_to").val();
		if( typeof(railwayCode)!="undefined" && railwayCode!="" ){
		    aeFrom = expressMap[railwayCode][0];
		    aeTo = railwayCode;

		    $.each( expressList, function( index,value ){
		        if( value[0]==aeFrom ){
			    aeOrig = value[1];
		        }
		    });
		}

		//aeOrig = $("#transfer_origin_airport_to").val();

//		txtTo = $("#transfer_to_airport").val();
//		txtFrom = $("#transfer_origin_airport_to").val();

		txtFrom = $("#transfer_to_airport").val();
		txtTo = $("#transfer_origin_airport_to").val();

		origin = $("#transfer_to_airport").val();
		destination = $("#transfer_origin_to").val();
		//destination = $("#transfer_origin_to").val();
		//origin = $("#transfer_origin_airport_to").val();
		
		houseNum =  $("#house_transfer_to").val();
	}else{
		adtCount  = parseInt($("#adultCount").val());
		chdCount  = parseInt($("#childCount").val());
		depDate   = $("#transfer_departure").val();
		srvcClass = $("#serviceClass").val();
		taxiDest  = $("#transfer_to").val();

	        var airportCode =$("#transfer_origin").val();
	        if( typeof(airportCode)!="undefined" && airportCode!="" ){
		        var railwayCode = expressMap[airportCode][0];

		    $.each( expressList, function( index,value ){
		        if( value[0]==railwayCode ){
			    aeDest = value[1];
		        }
		    });

		    aeFrom = airportCode;
		    aeTo = expressMap[airportCode][0];
		}
		aeOrig = $("#transfer_origin_airport").val();
		
		txtFrom = $("#transfer_origin_airport").val();
		txtTo = $("#transfer_to").val();
	
		origin = $("#transfer_origin").val();
		destination = $("#transfer_to").val();
		
		houseNum =  $("#house_transfer").val();
	}

	if( houseNum == $("#house_transfer_to").attr("alt") ){
	    houseNum="";
	}

	if( txtFrom == $("#transfer_origin_airport").attr("alt") || txtFrom == $("#transfer_to").attr("alt")  ){
	    txtFrom="";
	}
	if( txtTo==$("#transfer_origin_airport").attr("alt") || txtTo==$("#transfer_to").attr("alt")){
		txtTo="";
	}

	aeTime = $("#time").val();

	var carsCountNum = Math.ceil(( chdCount + adtCount )/PASSENGERS_PER_CAR);
    
	var valueObject = {
		isToAirport:isSelectedToAirportTab,
		from: origin,
		to: destination,
		adultCount:adtCount,
		childCount:chdCount,
		serviceClass:srvcClass,
		departureDate:depDate,
		expressFrom:aeFrom,
		expressTo:aeTo,
		expressTime:aeTime,
		expressDestination:aeDest,
		expressOrigin:aeOrig,
		taxiDestination:taxiDest,
		textFrom:txtFrom,
		textTo:txtTo,
		house:houseNum,
		carsCount: carsCountNum
	};

	return valueObject;
}


function submitTransferForm(){

	var MAX_TAXI_PASSENGERS = 9;

	var transferMethod = $("#step_two input[name='transferType']:checked'").val();
	var transferValueObject = getTransferValueObject();

	$('#botBuyExpressError').hide();

	if( transferMethod=="AE" ){
		$("#form_express input[name='serviceClass']")

		$("#form_express input[name='from_express']").val(transferValueObject.expressOrigin);
		$("#form_express input[name='to_express']").val(transferValueObject.expressDestination);
		$("#form_express input[name='from']").val(transferValueObject.expressFrom);
		$("#form_express input[name='to']").val(transferValueObject.expressTo);

		var direction = getDirection(transferValueObject);

		$("#form_express input[name='direction']").val(direction);

		$("#form_express input[name='departureDate']").val(transferValueObject.departureDate);
		$("#form_express input[name='departureTime']").val(transferValueObject.expressTime);

		$("#form_express input[name='adultCount']").val(transferValueObject.adultCount);
		$("#form_express input[name='childCount']").val(transferValueObject.childCount);

		$("#form_express input[name='serviceClass']").val(transferValueObject.serviceClass);

		doExpressSearch();
	}else if( transferMethod=="TAXI" ){
	    var message="";
	
	    if( (transferValueObject.adultCount+transferValueObject.childCount)>MAX_TAXI_PASSENGERS ){
		message += error_transfer_passengers_count.toString() + "<br/>";
		$('#botBuyExpressError').html(message).show();
		return false;
	    }
	
	    doTaxiSearch();
	}
}


function doTaxiSearch(){

    var transferValueObject = getTransferValueObject();

    var form = document.forms['form_taxi'];

    if( transferValueObject.isToAirport ){
	$("input[name='model.direction']").val( "toAirport" );
	$("input[name='airport']").val( transferValueObject.to );

	$("input[name='model.origin']").val( transferValueObject.from );
	$("input[name='model.destination']").val( transferValueObject.to );
    }else{
	$("input[name='model.direction']").val( "fromAirport" );
	$("input[name='airport']").val( transferValueObject.from );

	$("input[name='model.origin']").val( transferValueObject.from );
	$("input[name='model.destination']").val( transferValueObject.taxiDestination );
    }

    $("input[name='model.count']").val( transferValueObject.carsCount );
    $("input[name='model.date']").val(transferValueObject.departureDate);

    var addressFounded = $("#addressFounded").val();

    if( addressFounded=='false' ){
	 var actionName = $(form).attr("action");

	 actionName = actionName.substring(0,actionName.lastIndexOf('/')+1);
	 $(form).attr("action", actionName);
    }

    form.submit();
}


function loadAETimetable(transferValueObject) {

	var url = '/servlet/express?method=timetable';
	var direction = getAEdestination(transferValueObject);
	var date = transferValueObject.departureDate;

	var formData = {direction: direction, date: date};

	if (direction != '' && date != '') {
		url +="&direction="+direction+"&date="+date;
	    
		$.ajax({type:"GET", url:url,/* data:formData ,*/ dataType:"script", success:function(data,textStat){
			if (expressTimetable != null) {
				$('#time > option:gt(0)').remove();
				for (var i = 0; i < expressTimetable.length; i++) {
					$('#time').append("<option value='"+expressTimetable[i]+"'>"+expressTimetable[i]+"</option>");
				}
			}
		} });
	}
}

function getDirection(transferValueObject){
		var direction = 0;
		if (transferValueObject.expressFrom == "VKO" || transferValueObject.expressTo == "VKO") {
		    direction = 1;
		} else if (transferValueObject.expressFrom == "DME" || transferValueObject.expressTo == "DME") {
		    direction = 2;
		} else if (transferValueObject.expressFrom == "SVO" || transferValueObject.expressTo == "SVO") {
		    direction = 3;
		}

	return direction;
}

function getAEdestination(transferValueObject){
    var dest = "";

    if(transferValueObject.isToAirport){
	dest=transferValueObject.expressFrom;
    }else{
	dest=transferValueObject.expressTo;
    }

    return dest;
}

function showTimetableAE(url) {
    var transferValueObject = getTransferValueObject();

    return openPopup(url+'?direction='+getDirection(transferValueObject)+'&request_locale='+$('input[name=request_locale]').val());
}


function recordOutboundLink(link, category, action) {
  try {
    var pageTracker=_gat._getTracker("UA-5927973-1");
    pageTracker._trackEvent(action,category);
    setTimeout('document.location = "' + link.href + '"', 100)
  }catch(err){}
}

function recordOutboundLinkNoRedirect(category, action) {
  try {
    var pageTracker=_gat._getTracker("UA-5927973-1");
    pageTracker._trackEvent(action,category);
//    setTimeout('document.location = "' + link.href + '"', 100)
  }catch(err){}
}

