﻿var __waitStatus = 0;
function __setWaitStatus()
{
	__waitStatus++;
	if( __waitStatus==1 )
	{
		document.body.style.cursor = "wait";
		__setSearchFormEnabled(false);
	}
}
function __clearWaitStatus()
{
	if( __waitStatus > 0 ) __waitStatus--;
	if( __waitStatus==0 )
	{
		document.body.style.cursor = "auto";
		__setSearchFormEnabled(true);
	}
}
function __setStatusText( str )
{
	document.getElementById("__ajax_status").innerHTML = str;
}

function __failedCallback(error)
{
    __setStatusText("Ошибка: "+error.get_message());
	__clearWaitStatus();
}

function __highlightInstr(item)
{
}

var __data = new Object();
function __initPacketPricesFilters( dicts ) 
{
	try
	{
		__data.availmode_available = document.forms["search_frm"].availmode_available;
		__data.availmode_online = document.forms["search_frm"].availmode_online;
		__data.availmode_all = document.forms["search_frm"].availmode_all;
		__data.depcity = document.forms["search_frm"].depcity;
		__data.transtype = document.forms["search_frm"].transtype;
		__data.country = document.forms["search_frm"].country;
		__data.datefrom = document.forms["search_frm"].datefrom;
		__data.dateto = document.forms["search_frm"].dateto;
		__data.tourtype = document.forms["search_frm"].tourtype;
		__data.resort = document.forms["search_frm"].resort;
		__data.spo = document.forms["search_frm"].spo;
		__data.nights_tab = document.getElementById("nights_tab");
		__data.hotelcategories_tab = document.getElementById("hotelcategories_tab");
		__data.foodtypes_tab = document.getElementById("foodtypes_tab");
		__data.hotels_tab = document.getElementById("hotels_tab");
		__data.hotelservices_tab = document.getElementById("hotelservices_tab");

		__data.hid_nights = document.forms["search_frm"].hid_nights;
		__data.hid_hotelcategories = document.forms["search_frm"].hid_hotelcategories;
		__data.hid_foodtypes = document.forms["search_frm"].hid_foodtypes;
		__data.hid_hotels = document.forms["search_frm"].hid_hotels;
		__data.hid_hotelservices = document.forms["search_frm"].hid_hotelservices;
		__data.hid_parms = document.forms["search_frm"].hid_parms;
		
		__data.searchIndicator = document.getElementById("divSearchIndicator");
		__data.searchIndicator.style.display = "none";
		

		__data.availmode_available.onclick = function() { __loadDictionariesStart( Gpi.Vko.Search.PacketPricesAction2.AvailabilityModeChanged ); };
		__data.availmode_online.onclick = function() { __loadDictionariesStart( Gpi.Vko.Search.PacketPricesAction2.AvailabilityModeChanged ); };
		__data.availmode_all.onclick = function() { __loadDictionariesStart( Gpi.Vko.Search.PacketPricesAction2.AvailabilityModeChanged ); };
		__data.depcity.onchange = function() { __highlightInstr('instr_transtype'); __loadDictionariesStart( Gpi.Vko.Search.PacketPricesAction2.DepCityChanged ); }
		__data.transtype.onchange = function() { __highlightInstr('instr_country'); __loadDictionariesStart( Gpi.Vko.Search.PacketPricesAction2.TransportTypeChanged ); }
		__data.country.onchange = function() { __highlightInstr('instr_dates'); __loadDictionariesStart( Gpi.Vko.Search.PacketPricesAction2.CountryChanged ); }
		__data.datefrom.onchange = function() 
			{ 
				if( __parseDate(__data.datefrom.value)==null ) { alert('Введена некорректная дата'); __data.datefrom.value = __data.datefrom_prevValue; } 
				else __data.datefrom_prevValue = __data.datefrom.value;

				var d1 = __parseDate(__data.datefrom.value);
				var d2 = __parseDate(__data.dateto.value);
				if( d1>d2 ) __data.dateto.value = __data.datefrom.value;

				if (Math.floor(((d2 - d1) / (60 * 60 * 24)) / 1000) > 30) {
				    alert('Диапазон дат не должен превышать 30 день');
//				    d1.setTime(d2.getTime() - 1000 * 60 * 60 * 24 * 30);
//				    __data.datefrom.value = d1.getDate() + "." + (d1.getMonth() + 1) + "." + d1.getYear();
				    d2.setTime(d1.getTime() + 1000 * 60 * 60 * 24 * 30);
				    __data.dateto.value = d2.getDate() + "." + (d2.getMonth() + 1) + "." + d2.getYear();
				}
				
				__highlightInstr('instr_tourtype'); __loadDictionariesStart( Gpi.Vko.Search.PacketPricesAction2.DatesChanged ); 
			}
		__data.dateto.onchange = function() 
			{ 
				if( __parseDate(__data.dateto.value)==null ) { alert('Введена некорректная дата'); __data.dateto.value = __data.dateto_prevValue; } 
				else __data.dateto_prevValue = __data.dateto.value;

				var d1 = __parseDate(__data.datefrom.value);
				var d2 = __parseDate(__data.dateto.value);
				if( d1>d2 ) __data.datefrom.value = __data.dateto.value;

				if (Math.floor(((d2 - d1) / (60 * 60 * 24)) / 1000) > 30) {
				    alert('Диапазон дат не должен превышать 30 день');
				    d2.setTime(d1.getTime() + 1000 * 60 * 60 * 24 * 30);
				    __data.dateto.value = d2.getDate() + "." + (d2.getMonth() + 1) + "." + d2.getYear();
				}
				
				__highlightInstr('instr_tourtype'); __loadDictionariesStart( Gpi.Vko.Search.PacketPricesAction2.DatesChanged );
			}
		__data.tourtype.onchange = function() { __highlightInstr('instr_search_or_continue'); __loadDictionariesStart( Gpi.Vko.Search.PacketPricesAction2.TourTypeChanged ); }
		__data.resort.onchange = function() { __highlightInstr('instr_nights'); __loadDictionariesStart( Gpi.Vko.Search.PacketPricesAction2.ResortChanged ); }
		__data.spo.onchange = function() { __highlightInstr('instr_spo'); __loadDictionariesStart( Gpi.Vko.Search.PacketPricesAction2.SpoChanged ); }

		__data.nights_onchange = function() { __highlightInstr('instr_hotelcategories'); }
		__data.hotelcategories_onchange = function() { __highlightInstr('instr_foodtypes'); }
		__data.foodtypes_onchange = function() { __highlightInstr('instr_hotels'); }
		__data.hotels_onchange = function() { __highlightInstr('instr_parms'); }
		document.forms["search_frm"].adults.onchange = function() { __checkMaxPriceVisible(); __highlightInstr('instr_hotelservices'); this.value=this.value.replace(/[^\d]/g,''); }
		document.forms["search_frm"].childs.onchange = function() { __checkMaxPriceVisible(); __highlightInstr('instr_hotelservices'); this.value=this.value.replace(/[^\d]/g,''); }

		var onKeyPressHandler = function(t) { 
			var e = typeof(event)!='undefined' ? event : t;
			var ch;
			if (e.which == null) ch = String.fromCharCode(e.keyCode);    // IE
			else if (e.which > 0) ch = String.fromCharCode(e.which);	  // All others
			else return;   // special key

			return '0'<=ch && ch<='9' || ch=='\u0008' || ch=='\u0009';
		}

		document.forms["search_frm"].adults.onkeypress = onKeyPressHandler;
		document.forms["search_frm"].childs.onkeypress = onKeyPressHandler;
		document.forms["search_frm"].maxprice.onkeypress = onKeyPressHandler;

		document.forms["search_frm"].maxprice.onchange = function() { __highlightInstr('instr_hotelservices'); this.value=this.value.replace(/[^\d]/g,''); }
		document.forms["search_frm"].currency.onchange = function() { __highlightInstr('instr_hotelservices'); }
		document.forms["search_frm"].sort.onchange = function() { __highlightInstr('instr_hotelservices'); }
		__data.hotelservices_onchange = function() { __highlightInstr('instr_search'); }

		__loadDictionariesCallback( dicts );
		__checkMaxPriceVisible();
	}
	catch(e)
	{
		alert(e.message);
	}
}

function __setSearchFormEnabled( bEnabled )
{
	__data.availmode_available.disabled = !bEnabled;
	__data.availmode_online.disabled = !bEnabled;
	__data.availmode_all.disabled = !bEnabled;
	__data.depcity.disabled = !bEnabled;
	__data.transtype.disabled = !bEnabled;
	__data.country.disabled = !bEnabled;
	__data.datefrom.disabled = !bEnabled;
	__data.dateto.disabled = !bEnabled;
	__data.tourtype.disabled = !bEnabled;
	__data.resort.disabled = !bEnabled;
	__data.spo.disabled = !bEnabled;
	__data.searchIndicator.style.display = bEnabled ? "none" : "inline";
}

function __checkMaxPriceVisible()
{
	var visible = document.forms["search_frm"].adults.value!="" || document.forms["search_frm"].childs.value!="";
	document.getElementById( "maxprice_box" ).style.display = visible ? "block" : "none";
}

function __loadDictionariesStart( action, loadSingleDictName  )
{
	try
	{
		var filters = __getPacketPricesSearchFilters();
		var parms = __getPacketPricesDictionaryParms( loadSingleDictName );

		__setWaitStatus();
		__setStatusText( "" );

		Gpi.Vko.SearchWS.LoadPacketPricesDictionaries( filters, action, parms, __loadDictionariesCallback, __failedCallback, void 0 );
	}
	catch(e)
	{
		alert(e.message);
	}
}

function __getPacketPricesSearchFilters()
{
	var f = new Vko.Pricing.PacketPricesSearchQuery();

	if( __data.availmode_available.checked )
	{
		f.AvailabilityMode = Vko.Pricing.AvailabilityModes.Available;
	}
	else if( __data.availmode_online.checked ) 
	{
		f.AvailabilityMode = Vko.Pricing.AvailabilityModes.Online;
	}
	else
	{
		f.AvailabilityMode = Vko.Pricing.AvailabilityModes.All;
	}

	f.DepCityID = __getComboBoxValue( __data.depcity );
	f.TransportTypeID = __getComboBoxValue( __data.transtype );
	f.CountryID = __getComboBoxValue( __data.country );
	f.DateFrom = __parseDate( __data.datefrom.value );
	f.DateTo = __parseDate( __data.dateto.value );
	f.TourTypeID = __getComboBoxValue( __data.tourtype );
	f.ResortID = __getComboBoxValue( __data.resort );
	f.SpoCodeFilter = __getSpoComboBoxValue( __data.spo );

	if( __data.hid_nights.value=="1" ) f.Nights = __getIds( __data.nights );
	if( __data.hid_hotelcategories.value=="1" ) f.HotelCategoryIDs = __getIds( __data.hotelcategories );
	if( __data.hid_foodtypes.value=="1" ) f.FoodTypeIDs = __getIds( __data.foodtypes );
	if( __data.hid_hotels.value=="1" )
	{
		var ids = __getTextIds( __data.hotels );
		var makets = new Array();
		var hotels = new Array();
		for( var i in ids )
		{
			if( '0'<=ids[i].substring(0,1) && ids[i].substring(0,1)<='9' ) hotels[hotels.length] = parseInt( ids[i] );
			else if( ids[i].substring(0,1)=='M' ) makets[makets.length] = parseInt( ids[i].substring(1) );
		}
		f.MaketIDs = makets;
		f.HotelIDs = hotels;
	}
	if( __data.hid_hotelservices.value=="1" )
	{
		var ids = __getTextIds( __data.hotelservices );
		var services = new Array();
		var recommendations = new Array();
		for( var i in ids )
		{
			if( '0'<=ids[i].substring(0,1) && ids[i].substring(0,1)<='9' ) services[services.length] = parseInt( ids[i] );
			else if( ids[i].substring(0,1)=='R' ) recommendations[recommendations.length] = parseInt( ids[i].substring(1) );
		}
		f.HotelServiceIDs = services;
		f.VkoRecommendationIDs = recommendations;
	}
		

	if( __data.hid_parms.value=="1" ) 
	{
	}
	
	return f;
}

function __getSpoComboBoxValue( ctl )
{
	if( ctl.value!="" )
	{
		var parts = ctl.value.split(' ',2);
		var res = new Vko.Pricing.SpoCodeFilter();
		res.TourOperatorID = parseInt( parts[0] );
		res.SpoCode = parts[1];
		return res;
	}
	else
	{
		return  null;
	}
}

function __getPacketPricesDictionaryParms( loadSingleDictName )
{
	var parms = new Gpi.Vko.Search.PacketPricesDictionaryParms();

	if( loadSingleDictName )
	{
		parms[loadSingleDictName] = true;
	}
	else
	{
		parms.LoadNights = __data.hid_nights.value=="1";
		parms.LoadHotelCategories = __data.hid_hotelcategories.value=="1";
		parms.LoadFoodTypes = __data.hid_foodtypes.value=="1";
		parms.LoadHotels = __data.hid_hotels.value=="1";
		parms.LoadHotelServices = __data.hid_hotelservices.value=="1";
	}
	return parms;
}
function __cancelLoadDictionaries()
{
	__setSearchFormEnabled(true);
}

function __loadDictionariesCallback( res )
{
	try
	{
		if( res.SearchFilters.AvailabilityMode == Vko.Pricing.AvailabilityModes.Available )
		{
			__data.availmode_available.checked = true;
		}
		else if( res.SearchFilters.AvailabilityMode == Vko.Pricing.AvailabilityModes.Online ) 
		{
			__data.availmode_online.checked = true;
		}
		else 
		{
			__data.availmode_all.checked = true;
		}

		if( res.DepCities!=null )
		{
			__bindComboBox( __data.depcity, res.DepCities, res.SearchFilters.DepCityID );
		}
		if( res.TransportTypes!=null )
		{
			__bindComboBox( __data.transtype, res.TransportTypes, res.SearchFilters.TransportTypeID );
		}
		if( res.Countries!=null )
		{
			__bindComboBox( __data.country, res.Countries, res.SearchFilters.CountryID );
		}
		__data.datefrom_prevValue = __data.datefrom.value = __formatDate( res.SearchFilters.DateFrom );
		__data.dateto_prevValue = __data.dateto.value = __formatDate( res.SearchFilters.DateTo );
		
		if(res.Dates != null)
		{
		    calendar1.setActiveDates(res.Dates);
		    calendar2.setActiveDates(res.Dates);
		}
		if( res.TourTypes!=null )
		{
			__bindComboBox( __data.tourtype, res.TourTypes, res.SearchFilters.TourTypeID, true, 'Не имеет значения' );
		}
		if( res.Resorts!=null )
		{
			__bindComboBoxGeo( __data.resort, res.Resorts, res.SearchFilters.ResortID, true, 'Не имеет значения' );
		}
		if( res.SpoCodes!=null )
		{
			for( var i=0; i<res.SpoCodes.length; ++i )
			{
				res.SpoCodes[i].ID = ""+res.SpoCodes[i].TourOperatorID+" "+res.SpoCodes[i].SpoCode;
			}
			var selectedId = res.SearchFilters.SpoCodeFilter!=null ? ""+res.SearchFilters.SpoCodeFilter.TourOperatorID+" "+res.SearchFilters.SpoCodeFilter.SpoCode : null;
			__bindComboBox( __data.spo, res.SpoCodes, selectedId, true );
		}
		if( res.Nights!=null )
		{
			__data.nights = __bindCheckBoxList( "nights", __data.nights_tab, res.Nights, res.SearchFilters.Nights, __data.nights_onchange, 'Все' );
		}
		if( res.HotelCategories!=null )
		{
			__data.hotelcategories = __bindCheckBoxList( "hotelcategories", __data.hotelcategories_tab, res.HotelCategories, res.SearchFilters.HotelCategoryIDs, __data.hotelcategories_onchange, 'Все' );
		}
		if( res.FoodTypes!=null )
		{
			__data.foodtypes = __bindCheckBoxList(  "foodtypes", __data.foodtypes_tab, res.FoodTypes, res.SearchFilters.FoodTypeIDs, __data.foodtypes_onchange, 'Все' );
		}
		if( res.Hotels!=null )
		{
			var dictionary = new Array();
			for( var i in res.Makets ) 
			{
				var item = new Object();
				item.ID = "M"+res.Makets[i].ID;
				item.Name = res.Makets[i].Name;
				dictionary[dictionary.length] = item;
			}
			if( res.Makets.length!=0 && res.Hotels.length!=0 )
				dictionary[dictionary.length]=null;
			for( var i in res.Hotels )
			{
				dictionary[dictionary.length] = res.Hotels[i];
			}

			var selectedIDs = new Array();
			if( res.SearchFilters.MaketIDs!=null )
				for( var i in res.SearchFilters.MaketIDs ) 
					selectedIDs[selectedIDs.length] = "M"+res.SearchFilters.MaketIDs[i];
			if( res.SearchFilters.HotelIDs!=null )
				for( var i in res.SearchFilters.HotelIDs ) 
					selectedIDs[selectedIDs.length] = res.SearchFilters.HotelIDs[i];

			__data.hotels = __bindCheckBoxList( "hotels", __data.hotels_tab, dictionary, selectedIDs, __data.hotels_onchange, 'Все' );
		}
		if( res.HotelServices!=null )
		{
			var dictionary = new Array();
			for( var i in res.HotelServices )
			{
				dictionary[dictionary.length] = res.HotelServices[i];
			}
			for( var i in res.VkoRecommendations )
			{
				res.VkoRecommendations[i].ID = "R"+res.VkoRecommendations[i].ID;
				res.VkoRecommendations[i].ServiceGroupName = "Рекомендации VKO";
				dictionary[dictionary.length] = res.VkoRecommendations[i];
			}

			var selectedIDs = new Array();
			if( res.SearchFilters.HotelServiceIDs!=null )
				for( var i in res.SearchFilters.HotelServiceIDs ) 
					selectedIDs[selectedIDs.length] = res.SearchFilters.HotelServiceIDs[i];
			if( res.SearchFilters.VkoRecommendationIDs!=null )
				for( var i in res.SearchFilters.VkoRecommendationIDs ) 
					selectedIDs[selectedIDs.length] = "R"+res.SearchFilters.VkoRecommendationIDs[i];

			__data.hotelservices = __bindCheckBoxHotelServices( "hotelservices", __data.hotelservices_tab, 4, dictionary, selectedIDs, __data.hotelservices_onchange );
		}
	}
	catch(e)
	{
		alert( e.message );
	}
	
	__clearWaitStatus();
	__setStatusText( "" );
	__refreshHotelsDisabled();
}


function __setCheckBoxListWaiting2( tab )
{
    if(__waitStatus == 0)
        __setCheckBoxListWaiting(tab);
}

function __getVisible(ID)
{
	var LevelID = "level"+ID;
	var currentDisplayValue = document.getElementById(LevelID).style.display;
	var currentVisible = !(currentDisplayValue == "none");
	return currentVisible;
}
function __toggleVisible(ID,loadSingleDictName,bVisible)
{
	try
	{
		var LevelID = "level"+ID;
		var hidID = "hid"+ID;
		var currentDisplayValue = document.getElementById(LevelID).style.display;
		var currentVisible = !(currentDisplayValue == "none");
		var newVisible = typeof(bVisible)=="undefined" ? !currentVisible : bVisible;

		if( currentVisible==false && newVisible==true && __waitStatus == 0  )
		{	
			document.getElementById(LevelID).style.display = "";
			document.getElementById(hidID).value = "1";
			//eval('document.image' + ID + '.src = "/images/arr_up.gif"');

			__loadDictionariesStart( Gpi.Vko.Search.PacketPricesAction2.None, loadSingleDictName );
		}
		else if( currentVisible==true && newVisible==false )
		{	
			document.getElementById(hidID).value = "";
			document.getElementById(LevelID).style.display = "none";
			//eval('document.image' + ID + '.src = "/images/arr_down.gif"');
		}
	}
	catch( e )
	{
		alert( e.message );
	}
}

function __toggleHotels()
{
//	__setCheckBoxListWaiting2(__data.hotels_tab);
//	__toggleVisible("_hotels","LoadHotels"); 
//	__toggleVisible("_hotelservices","LoadHotelServices",false);
}

function __refreshHotelsDisabled()
{
	var ID="_hotels";
	var LevelID = "level"+ID;
	var hidID = "hid"+ID;
	document.getElementById(LevelID).disabled = __getVisible("_hotelservices");
}
function __toggleHotelServices()
{
	__setCheckBoxListWaiting2(__data.hotelservices_tab);
	__toggleVisible("_hotelservices","LoadHotelServices"); 
	//__toggleVisible("_hotels","LoadHotels"); 

	__refreshHotelsDisabled();


	var upndown = document.getElementById('upndown').src;
	if(document.getElementById('upndown').src == 'http://www.vkotravel.com/images/up.gif')
	{
	
		document.getElementById('upndown').src = "http://www.vkotravel.com/images/down.gif";
	}
	else {document.getElementById('upndown').src = "http://www.vkotravel.com/images/up.gif";}
}

