﻿var showTop20ExitPop = false;
var tileClickCount = 0;

function changeReturnVisibility(divId, visible) {
	if(visible)
		//document.getElementById(divId).style.visibility = 'inline';
		document.getElementById(divId).style.visibility = 'visible';
	else
		//document.getElementById(divId).style.visibility = 'none';
		document.getElementById(divId).style.visibility = 'hidden';
}

function expandTravelers(childrenId, upToId, expand)
{
	if(expand)
	{
		$(childrenId).style.display = 'none';
		$(upToId).style.display = 'inline';
	}
	else
	{
		$(childrenId).style.display = 'inline';
		$(upToId).style.display = 'none';
	}
}

function changeTravellersString(stringId, adultsDropDown, childrenDropDown, seniorsDropDown, infantsDropDown, travelersDropDown, callersId, passengerParagraph, infantParagraph) {
 countTravelers(stringId, adultsDropDown, childrenDropDown, seniorsDropDown, infantsDropDown, travelersDropDown, callersId, passengerParagraph, infantParagraph);


 var adultCount = $(adultsDropDown).options[$(adultsDropDown).selectedIndex].text;
 var childrenCount = $(childrenDropDown).options[$(childrenDropDown).selectedIndex].text;
 var seniorCount = $(seniorsDropDown).options[$(seniorsDropDown).selectedIndex].text;
 var infantCount = $(infantsDropDown).options[$(infantsDropDown).selectedIndex].text;


 resultString = "";

 resultString += (adultCount > 0 ? (adultCount == 1 ? "1 adult" : adultCount + " adults") : "");

 if(childrenCount > 0) {
   if(adultCount > 0)
     resultString += ", ";
   
   resultString += (childrenCount == 1 ? "1 child" : childrenCount + " children");
 }


 if(seniorCount > 0) {
    if(childrenCount > 0 || adultCount > 0)
      resultString += ", ";
    
    resultString += (seniorCount == 1 ? "1 senior" : seniorCount + " seniors");
 }
 

 if(infantCount > 0) {
    if(childrenCount > 0 || adultCount > 0 || seniorCount > 0)
      resultString += ", ";
    
    resultString += (infantCount == 1 ? "1 infant" : infantCount + " infants");
 }



 $(stringId).innerHTML = resultString;
}



// counts the number of travelers and updates the travelers drop down
function countTravelers(stringId, adultsDropDown, childrenDropDown, seniorsDropDown, infantsDropDown, travelersDropDown, callersId, passengerParagraph, infantParagraph) {
	var adultCount = $(adultsDropDown).options[$(adultsDropDown).selectedIndex].text;
	var childrenCount = $(childrenDropDown).options[$(childrenDropDown).selectedIndex].text;
	var seniorCount = $(seniorsDropDown).options[$(seniorsDropDown).selectedIndex].text;
	var infantCount = $(infantsDropDown).options[$(infantsDropDown).selectedIndex].text;


	total = parseInt(adultCount) + parseInt(childrenCount) + parseInt(seniorCount) + parseInt(infantCount);
	

	if(callersId && total > 9) {
		diff = total - 9;
		callersCountTxt = $(callersId).options[$(callersId).selectedIndex].text;
		callersCount = parseInt(callersCountTxt);

		total -= diff;
		
		$(callersId).selectedIndex = callersCount - diff;
		resetParagraphStyleWithTimeout(passengerParagraph, 2000);
	}
	
	if(total<1) {
		$(adultsDropDown).selectedIndex = 1;
		total = $(adultsDropDown).selectedIndex;
	}
	
	
	$(travelersDropDown).selectedIndex = total - 1;

	// check if the following condition was not respected: #adults + #seniors >= #infants
	if(verifyInfantNumber(callersId, adultsDropDown, seniorsDropDown, infantsDropDown) == false){
		countTravelers(stringId, adultsDropDown, childrenDropDown, seniorsDropDown, infantsDropDown, travelersDropDown, callersId, passengerParagraph, infantParagraph);
		resetParagraphStyleWithTimeout(infantParagraph, 2000);
	}
}


// counts the number of travelers and updates the travelers drop down
function countTravelersBak(stringId, adultsDropDown, childrenDropDown, seniorsDropDown, infantsDropDown, travelersDropDown) {
	var adultCount = $(adultsDropDown).options[$(adultsDropDown).selectedIndex].text;
	var childrenCount = $(childrenDropDown).options[$(childrenDropDown).selectedIndex].text;
	var seniorCount = $(seniorsDropDown).options[$(seniorsDropDown).selectedIndex].text;
	var infantCount = $(infantsDropDown).options[$(infantsDropDown).selectedIndex].text;
	
	total = parseInt(adultCount) + parseInt(childrenCount) + parseInt(seniorCount) + parseInt(infantCount);
	
	
	$(travelersDropDown).selectedIndex = total - 1;
}




// same as above, but updates the subfilters based on the number of chosen travelers
function changeTravelerNumberBak(stringId, adultsDropDown, childrenDropDown, seniorsDropDown, infantsDropDown, travelersDropDown, passengerParagraph, infantParagraph) {
	var numTravelers = $(travelersDropDown).selectedIndex + 1;

	$(adultsDropDown).selectedIndex = numTravelers <= 9 ? numTravelers : 9;

	if(numTravelers > 9)
		$(childrenDropDown).selectedIndex = numTravelers <= 18 ? numTravelers - 9 : 9;
	else
		$(childrenDropDown).selectedIndex = 0;

	if(numTravelers > 18)
		$(seniorsDropDown).selectedIndex = numTravelers <= 27 ? numTravelers - 18 : 9;
	else
		$(seniorsDropDown).selectedIndex = 0;

	if(numTravelers > 27)
		$(infantsDropDown).selectedIndex = numTravelers - 27;
	else
		$(infantsDropDown).selectedIndex = 0;


	changeTravellersString(stringId, adultsDropDown, childrenDropDown, seniorsDropDown, infantsDropDown, travelersDropDown, passengerParagraph, infantParagraph);
}




// same as above, but updates the subfilters based on the number of chosen travelers
function changeTravelerNumber(stringId, adultsDropDown, childrenDropDown, seniorsDropDown, infantsDropDown, travelersDropDown, passengerParagraph, infantParagraph) {
	var numTravelers = $(travelersDropDown).selectedIndex + 1;
	
	$(adultsDropDown).selectedIndex = numTravelers;
	
	$(childrenDropDown).selectedIndex = 0;
	$(seniorsDropDown).selectedIndex = 0;
	$(infantsDropDown).selectedIndex = 0;

	changeTravellersString(stringId, adultsDropDown, childrenDropDown, seniorsDropDown, infantsDropDown, travelersDropDown, passengerParagraph, infantParagraph);
}

// verifies that the number of infants isn't higher than the number of adult and senior passengers combined.
// returns true if no inconsistencies were found and false if a problem was found (and solved)
function verifyInfantNumber(callersId, adultsDropDown, seniorsDropDown, infantsDropDown){
	var adultCount = $(adultsDropDown).options[$(adultsDropDown).selectedIndex].text;
	var seniorCount = $(seniorsDropDown).options[$(seniorsDropDown).selectedIndex].text;
	var infantCount = $(infantsDropDown).options[$(infantsDropDown).selectedIndex].text;
	
	if(parseInt(adultCount) + parseInt(seniorCount) < parseInt(infantCount)){
		
		// find the difference
		diff = parseInt(infantCount) - (parseInt(adultCount) + parseInt(seniorCount));
		
		// if the inconsistency came from changing the infants dropdown we need to subtract this difference
		if(callersId == infantsDropDown)
			$(callersId).selectedIndex -= diff;
		
		// if it came from the adult or senior dropdown, we have to add this difference
		else
			$(callersId).selectedIndex += diff;	
		
		return false;	
	}
	return true;	
}

// this function resets a paragraphs style.
function resetParagraphStyle(paragraph){
	$(paragraph).className = 'none';
}

// this function resets a paragraphs style with a delay of timeout seconds.
function resetParagraphStyleWithTimeout(paragraph, timeout){
	$(paragraph).className = 'ErrorText';
	setTimeout("resetParagraphStyle('" + paragraph + "');", timeout);
}



function refreshFlights(container, loadingDiv, tipsFrame, div1, div2, oldHeader, newHeader) {
	new Ajax.Request('AjaxSearchMade.aspx');

	var flightPars = getFlightParameters();
	
	$(container).innerHTML = $(loadingDiv).innerHTML;
	new OutSystems.UpdatePanel($(container), 'UpdateFlights.aspx?Random=' + Math.random() + getFlightParametersAsQueryString(),{});
	
	
	$(tipsFrame).innerHTML = "Loading...";

	//Update header
	$(oldHeader).innerHTML = $(newHeader).innerHTML;
	$(oldHeader).up().vAlign = '';

	// aramos: paste after merge
	new OutSystems.UpdatePanel($(tipsFrame), 'AjaxTips.aspx?CurrentLocale=' + currentLocale + '&IsNewPage=true&UseAdSense=' + useAdSense + "&s_source=" + s_source + '&Suffix=' + adSenseSuffix + '&ClientId=' + adSenseClientId + '&Channel=' + adSenseChannel + '&NumberOfAds=' + adSenseNumberOfAds + '&InterfaceLanguage=' + adSenseLanguage + '&RealTracking=' + adSenseRealTracking + '&IsAirport=true&Origin='+flightPars.originCode+'&Destination='+flightPars.destinationCode+'&FadedLogos=' + fadedLogo + '&SearchMade=True&ActiveTab=1&TabDeals=1&DestinationCityCode=' + flightPars.destinationCode + "&LocaleId=" + currentLocaleId+ '&AdsenseAlternateWithSignupWidget=' + adsenseAlternateWithSignupWidget, {asynchronous:true});
	
	// we need to show the flightsResultDiv (div2) and hide the destinationsDiv (div1)
	if((div1 != '') && ($(div1) != null )) {
		$(div1).hide();
	}
	$(div2).show();
	
	
	return false;
}



// changes the size of the upper right div
function swapSizes(divId) {
	divDoc = document.getElementById(divId);
	
	if(divDoc.style.height == '300px')
		divDoc.style.height = '326px';
	else
		divDoc.style.height = '300px';
}



function verifyInputs() {
	var validForm = true;
	
	var fromCityDoc = document.getElementById('wtDepartureAirport');
	var toCityDoc = document.getElementById('wtDestinationAirport');
	
	var fromCityDropDownDoc = document.getElementById('wtdropDownCities');
	
	
	// screen with drop-downs
	if(fromCityDropDownDoc) {
		var parsedValue = fromCityDropDownDoc.value.substr( fromCityDropDownDoc.value.lastIndexOf('_') + 1, fromCityDropDownDoc.value.length);
		
		// no departure city
		if(parsedValue == "Null" && toCityDoc.value != '') {
			alert('Please enter your departure city.');
			validForm = false;
		}
		
		// no destination city
		if(parsedValue != "Null" && toCityDoc.value == '') {
			alert('Please enter your destination city.');
			validForm = false;
		}
		
		
		// no departure and no destination city
		if(parsedValue == "Null" && toCityDoc.value == '') {
			alert('Please enter your departure and destination cities.');
			validForm = false;
		}

		var departureCode = $('wtOriginCode').value;
		var destinationCode = $('wtDestinationCode').value;
		
		// validate that origin and destination cities are different
		if(parsedValue != "Null" && toCityDoc.value != '' && departureCode == destinationCode) {
			alert('Please enter a destination city different from the departure city.');
			validForm = false;
		}
		
	}
	
	// screen without drop-downs
	else {
		// no departure city
		if(fromCityDoc.value == '' && toCityDoc.value != '') {
			alert('Please enter your departure city.');
			validForm = false;
		}
	
		// no destination city
		if(fromCityDoc.value != '' && toCityDoc.value == '') {
			alert('Please enter your destination city.');
			validForm = false;
		}
		
		// no departure and no destination city
		if(fromCityDoc.value == '' && toCityDoc.value == '') {
			alert('Please enter your departure and destination cities.');
			validForm = false;
		}
		
		
		// validate that origin and destination cities are different
		if(fromCityDoc != '' && toCityDoc.value != '' && toCityDoc.value == fromCityDoc.value){
			alert('Please enter a destination city different from the departure city.');
			validForm = false;
		}
	}
	
	
	var checkinDateDoc = document.getElementById('wtdeparteDateWidget');
	var checkoutDateDoc = document.getElementById('wtreturnDateWidget');
	
	var checkinDate = new Date(getDateFromString(checkinDateDoc.value ,dateFormat));
	var checkoutDate = new Date(getDateFromString(checkoutDateDoc.value ,dateFormat));
	
	var checkinIsDate = isDate(checkinDateDoc.value);
	var checkoutIsDate = isDate(checkoutDateDoc.value);
	
	if(checkinDateDoc.value == '') {
		alert('Please enter a valid departure date.');
		//return false;
		validForm = false;
	}
	
	
	
	tmpDate = new Date();
	currentDate = curDateForValidation;
	
	if(checkinDate.valueOf() < currentDate.valueOf() && checkinIsDate ) {
		alert('The departure date cannot be in the past.\nPlease also check your system date and time as they may be incorrect.');
		//return false;
		validForm = false;
	}

	if(checkinDate.valueOf() - currentDate.valueOf() > (1000 * 3600 * 24 * 331) && checkinIsDate ) {
		alert('SuperSearch only supports searches for travel within the next 330 days.\nPlease also check your system date and time as they may be incorrect.');
		//return false;
		validForm = false;
	}
	
	if(document.getElementById('wtRoundTrip').checked == true || !checkoutIsDate) {
		if(checkoutDateDoc.value == '') {
			alert('Please insert a valid return date.');
			//return false;
			validForm = false;
		}
		
		
		if( checkoutIsDate && checkinDate.valueOf() > checkoutDate.valueOf() ) {
			alert('The return date must occur after the departure date. Please change the date.');
			//return false;
			validForm = false;
		}

		if(validForm && checkoutIsDate && checkoutDate.valueOf() - currentDate.valueOf() > (1000 * 3600 * 24 * 331) ) {
			alert('SuperSearch only supports searches for travel within the next 330 days.');
			//return false;
			validForm = false;
		}
	
	}
	
	
	if( checkinIsDate ){
		$('wtdeparteDateParagraph').setAttribute("class", "Invisible"); 
		$('wtdeparteDateParagraph').setAttribute("className", "Invisible"); // IE fix
	}
	if( checkoutIsDate ){
		$('wtreturnDateParagraph').setAttribute("class", "Invisible"); 
		$('wtreturnDateParagraph').setAttribute("className", "Invisible"); // IE fix
	}
	
	
	if( !checkinIsDate ){
		$('wtdeparteDateParagraph').setAttribute("class", "WarningText"); 
		$('wtdeparteDateParagraph').setAttribute("className", "WarningText"); // IE fix
		
		validForm = false;
	}
	
	if( !checkoutIsDate && $('wtRoundTrip').checked ) {
		$('wtreturnDateParagraph').setAttribute("class", "WarningText"); 
		$('wtreturnDateParagraph').setAttribute("className", "WarningText"); // IE fix
		
		validForm = false;
	}	
	
	// set dates to correct format
	if( validForm )
	{
		checkinDateDoc.value = getStringFromDate(checkinDate ,dateFormat);
		checkoutDateDoc.value = getStringFromDate(checkoutDate ,dateFormat);
	}
	
	//return true;
	return validForm;
}


// airport validation code, puts an error message in the screen if an airport was not found
//
// @param locationId id of the input containing the airport name or code.
// @param messageId id of the paragraph where the error message will appear.
// @param inputId id of the input the user uses
function airportValidation(locationId, messageId, inputId, locale) {	
	//var url = 'ValidAirport.aspx';	
	//var url = '" + GetAjaxPagesURL() + "ValidAirport.aspx';
	
	var locationValue = $(locationId).value;
	var pars = "str=" + locationValue + "&Locale=" + locale;
	
	var myAjax = new Ajax.Request(validateURL, {	method: 'get', 
							parameters: pars, 
							onComplete: function(originalRequest) {
								if(originalRequest.responseText != "") {
									if($(inputId) != null)
										$(inputId).value = originalRequest.responseText;

									$(messageId).setAttribute("class", "Invisible"); 
									$(messageId).setAttribute("className", "Invisible"); // IE fix
								}
								if(originalRequest.responseText == "") {
									if($(inputId).value != "") {
										$(messageId).setAttribute("class", "WarningText"); 
										$(messageId).setAttribute("className", "WarningText"); // IE fix
									}
								}
							}
						 }); 
	
}


// this variable is used to check if the search parameters have been changed.
var searchChanged = false;


function dropDownCitiesChanged(dropDownId, hiddenInputId) {
	var selectedValue = $(dropDownId).value;
	
	var parsedValue = selectedValue.substr( selectedValue.lastIndexOf('_') + 1, selectedValue.length);
	
	if(parsedValue != "Null") {
		$(hiddenInputId).value = parsedValue;
	}
}


function searchButtonClick(originCodeId, fromParagraphId, departureAirportId, 
			       destinationCodeId, toParagraphId, destinationAirportId,
				stepsBlock1Id, stepsBlock2Id,
				searchFirstId, searchSecondId,
				departeDateId, departeDateParagraphId,
				returnDateId, returnDateParagraphId,
				searchResultsLoadingId, destinationsDivId, flightsResultDivId,
				roundTrip,
				locale,
				usUrl, defaultUrl, CurrentLocale, imageDivId,oldHeader, newHeader,
			   rightColumnId		

				) {
	
	


	oldScreenState = saveScreenState('td.LeftTableCellContent');


	
	//Emergency FIX - Please solve this!
	airportValidation(originCodeId, fromParagraphId, departureAirportId, CurrentLocale);
	airportValidation(destinationCodeId, toParagraphId, destinationAirportId, CurrentLocale);


	if( verifyInputs() == false )
		return false;
	
	
	searchChanged = false;
	

	
	sendRankings( $(originCodeId).value, $(destinationCodeId).value, locale );
	
	
	visibleAds = "";
	newScreenRating = "";
	
	if(stepsBlock1Id != '' && stepsBlock2Id != '') {
		//$(stepsBlock1Id).toggle(); 
		//$(stepsBlock2Id).toggle(); 
		$(stepsBlock1Id).style.display = 'none';
		$(stepsBlock2Id).style.display = 'block';
	}

	if(imageDivId != null && imageDivId != '')
		$(imageDivId).hide();
	
	//$(searchFirstId).toggle(); 
	//$(searchSecondId).toggle();
	$(searchFirstId).style.display = 'none';
	$(searchSecondId).style.display = '';
	
	try {
		// update the HotDeals iframe - try catch to avoid AD BLOCKERS
		new OutSystems.UpdatePanel($('HotDeals'), 'HotDeals.aspx?Random=' + Math.random() + '&ActiveTab=1&IsResultsPage=true&Origin=' + $(originCodeId).value + '&Destination=' + $(destinationCodeId).value,{});
		$('HotDeals').up().removeClassName('Invisible');
		$('HotDeals').up().show();
	}
	catch(err) {}

	if(rightColumnId!= null && rightColumnId!= '')
		$(rightColumnId).style.borderStyle = 'none';
	
	refreshFlights('FlightsContainer', searchResultsLoadingId, 'TipsContainer', destinationsDivId, flightsResultDivId, oldHeader, newHeader); 
	$('TipsContainer').up().removeClassName('Invisible');
	$('TipsContainer').up().show();

	return true;
}


var originJSVar = "";
var destinatinJSVar = "";
var searchTypeIsRoundTrip = "true";
var isFirstSearch = true;

function trackPage(num) {
	try {
		if(num == 1)
			pageTracker._trackPageview('/SuperSearchTracking/Flights/scenario' + scenarioNumber + '/Search');
		if(num == 2)
			pageTracker._trackPageview('/SuperSearchTracking/Flights/scenario' + scenarioNumber + '/SearchAgain');
		if(num == 3) {
			if(isFirstSearch)
				pageTracker._trackPageview('/SuperSearchTracking/Flights/scenario' + scenarioNumber + '/SearchEnter')
			else
				pageTracker._trackPageview('/SuperSearchTracking/Flights/scenario' + scenarioNumber + '/SearchAgainEnter');
		}
	} catch(e) {}
}


function verifyDropDown() {
	var dropDown = $('wtdropDownCities');
	var cityId = $('wtOriginCode').value;
		
	if( dropDown != null && cityId != '') {
		for(var i = 0; i < dropDown.options.length; i++) {
			if( dropDown.options[i].value == '__ossli_' + cityId) {
				dropDown.selectedIndex = i;
			}
		}
	}

}

function showTop20Popunder(envprefix, source) {
	var pop = window.open('http://' + envprefix + 'top20.travelzoo.com/ss/Top20Popup.aspx?signupbox=top&source=' + source ,'signup800','width=800,height=300,scrollbars=yes');
	if(pop) pop.blur();

}

function showTop20ExitPopup(envprefix, source) {
	var pop = window.open('http://' + envprefix + 'top20.travelzoo.com/ss/Inline.aspx?signupbox=top&source=' + source ,'signup377','width=377,height=181,scrollbars=no,resizable=no,menubar=no,location=no,toolbar=no,status=no,left=0,top=0');
	if(pop) pop.focus();

}

function showOverlay(envprefix, source, position, tileClicksForOverlay) {
	if(tileClickCount >= tileClicksForOverlay)
	{
		alert('overlay');
		//var pop = window.open('http://' + envprefix + 'top20.travelzoo.com/ss/Inline.aspx?signupbox=top&source=' + source ,'overlay','width=377,height=181,scrollbars=no,resizable=no,menubar=no,location=no,toolbar=no,status=no,left=0,top=0');
		//if(pop) pop.focus();
	}

}