/*========================================================================================
  
$rcsfile: AvailabilitySearchInput.js $

$Revision: 1.1.2.2 $ $Date: 2006/03/23 15:45:33 $

Summary:	JavaScript file for the AvailabilitySearchInput control. Content moved from the C# code.

------------------------------------------------------------------------------------------
This file is part of the Navitaire NewSkies application.
Copyright (C) Navitaire.  All rights reserved.
========================================================================================*/




var ElementsState = new Array();
var ExistingMarkets = new Array();

function fNuevosValores(){
		  
SortedStations = new Array("MEX","TLC","ACA","CUN","CME","CTM","CJS","CEN","CUL","CUU","GDL","HMO","HUX","SJD","LMM","MID","MTY","PVR","TAM","TAP","TIJ","TGZ","VER","VSA","ZIH");
Stations = new Array();


//function Station(code, name, validOrig, validDest, mktsArray)

Stations["ACA"] = new Station("ACA", "Acapulco", true, true, new Array("TLC","MEX"));
Stations["CUN"] = new Station("CUN", "Cancun", true, true, new Array("MTY","TLC","MEX","GDL"));
Stations["CME"] = new Station("CME", "Cd Carmen", true, true, new Array("MEX"));
Stations["CJS"] = new Station("CJS", "Cd Juarez", true, true, new Array("MEX"));
Stations["CUU"] = new Station("CUU", "Chihuahua", true, true, new Array("TLC","MEX"));

Stations["LMM"] = new Station("LMM", "Los Mochis", true, true, new Array("MEX"));
Stations["CUL"] = new Station("CUL", "Culiacan", true, true, new Array("MEX","TIJ"));

Stations["CEN"] = new Station("CEN", "Cd Obregon", true, true, new Array("MEX"));
Stations["CTM"] = new Station("CTM", "Chetumal", true, true, new Array("MEX"));
Stations["GDL"] = new Station("GDL", "Guadalajara", true, true, new Array("MTY","SJD","TIJ","TLC","MEX","CUN"));
Stations["HMO"] = new Station("HMO", "Hermosillo", true, true, new Array("MEX"));
Stations["HUX"] = new Station("HUX", "Huatulco", true, true, new Array("MEX"));
Stations["SJD"] = new Station("SJD", "Los Cabos", true, true, new Array("GDL","TLC","MEX"));
Stations["MEX"] = new Station("MEX", "Mexico D.F.", true, true, new Array("ACA","CJS","CTM","GDL","HMO","MID","MTY","CUN","CEN","CUL","CUU","LMM","PVR","CME","TAM","TAP","TIJ","TGZ","HUX","SJD","VER","VSA","ZIH"));
Stations["MID"] = new Station("MID", "Merida", true, true, new Array("MEX"));

Stations["MTY"] = new Station("MTY", "Monterrey", true, true, new Array("CUN","GDL","TLC","MEX"));
Stations["TAM"] = new Station("TAM", "Tampico", true, true, new Array("MEX"));
Stations["TAP"] = new Station("TAP", "Tapachula", true, true, new Array("MEX"));
Stations["TIJ"] = new Station("TIJ", "Tijuana", true, true, new Array("GDL","MEX","CUL"));
Stations["TLC"] = new Station("TLC", "Toluca", true, true, new Array("ACA","CUN","CUU","GDL","MTY","NAS","PVR","SJD","ZIH"));
Stations["TGZ"] = new Station("TGZ", "Tuxtla Gtz.", true, true, new Array("MEX"));
Stations["PVR"] = new Station("PVR", "Puerto Vallarta", true, true, new Array("MEX","TLC"));
Stations["VER"] = new Station("VER", "Veracruz", true, true, new Array("MEX"));
Stations["VSA"] = new Station("VSA", "Villahermosa", true, true, new Array("MEX"));
Stations["ZIH"] = new Station("ZIH", "Ixtapa Zihuatanejo", true, true, new Array("TLC","MEX"));

  
  
 }
	

function esPuntoAPunto(Origen,Destino){

  
 return true;

/* Declarando las Rutas de Punto a Punto

 var Mercado = new Array(18);
 var Pares   = new Array(2)
 var Encontrado = 'NO';
            
  var ren,col;

  for (reng = 0; reng<=18; reng++){
       
       Mercado[reng] = new Array(2)
       

    }

	
    Mercado[0][0] = 'ACA';
    Mercado[0][1] = 'TLC';


    Mercado[1][0] = 'CJS';
    Mercado[1][1] = 'TLC';

    Mercado[2][0] = 'CME';
    Mercado[2][1] = 'TLC';

    Mercado[3][0] = 'CUN';
    Mercado[3][1] = 'MTY';

    Mercado[4][0] = 'CUN';
    Mercado[4][1] = 'TLC';

    Mercado[5][0] = 'CUU';
    Mercado[5][1] = 'TLC';

    Mercado[6][0] = 'GDL';
    Mercado[6][1] = 'MTY';

    Mercado[7][0] = 'GDL';
    Mercado[7][1] = 'SJD';

    Mercado[8][0] = 'GDL';
    Mercado[8][1] = 'TLC';

    Mercado[9][0] = 'GUA';
    Mercado[9][1] = 'TLC';

    Mercado[10][0] = 'HUX';
    Mercado[10][1] = 'TLC';

    Mercado[11][0] = 'MID';
    Mercado[11][1] = 'TLC';

    Mercado[12][0] = 'MTY';
    Mercado[12][1] = 'TLC';

    Mercado[13][0] = 'PVR';
    Mercado[13][1] = 'TLC';

    Mercado[14][0] = 'SJD';
    Mercado[14][1] = 'TLC';

    Mercado[15][0] = 'TAM';
    Mercado[15][1] = 'TLC';

    Mercado[16][0] = 'TGZ';
    Mercado[16][1] = 'TLC';

    Mercado[17][0] = 'TLC';
    Mercado[17][1] = 'VER';

    Mercado[18][0] = 'TLC';
    Mercado[18][1] = 'ZIH';


  for (reng = 0; reng<=18; reng++){
       
     
      if( Mercado[reng][0] == Origen && Mercado[reng][1] == Destino){
                      
          return true;
        }

      if( Mercado[reng][1] == Origen && Mercado[reng][0] == Destino){
                      
          return true;
        }

    }

    
  if (Encontrado == 'NO') 
     return false; */
}			

function Station(code, name, validOrig, validDest, mktsArray)
{
	this.code = code;
	this.name = name;
	this.validOrig = validOrig;
	this.validDest = validDest;
	this.mkts = mktsArray;
}

// Assumes that Stations and SortedStations arrays were initialized and populated above

//changeDest(this, document['SkySales']['AVAILABILITYSEARCHINPUT_DropDownListMarketDestination1'], document['SkySales']['AVAILABILITYSEARCHINPUT_DropDownListMarketDestination1'].options[document['SkySales']['AVAILABILITYSEARCHINPUT_DropDownListMarketDestination1'].selectedIndex].value)
function changeDest(o, d, dVal)
{
	//alert(o.value + ":" + d.value + ":" + dVal);

	//Inicializa las rutas
     if (o.value == '') { return;}
	fNuevosValores();
       

	if (!document.images) {	return;	}

	if (!d) { alert("There's no DropDownDest!");	return;	}

	var dLabel = d.options[0].text;
	var oIx = eval(o.selectedIndex);
	var dIx = 0;
	var name = '';

	//alert(oIx);

	if (oIx > 0)
	{
		var oVal = o.options[oIx].value;

		// clear and begin new destList
		d.length = 1;
		d.options[0] = new Option(dLabel);
        if(d.getAttribute('requiredEmpty'))
        {
		    d.options[0].value = d.getAttribute('requiredEmpty');
        }
        
		for (var i=0; i < SortedStations.length; i++)
		{
			for (j=0; j<Stations[oVal].mkts.length; j++)
			{
				var stnCode	= Stations[oVal].mkts[j];
				if ((SortedStations[i] == stnCode) && (Stations[stnCode].validDest == true))
				{
					if ( stnCode == dVal ) { dIx = d.length; }

					d.length += 1;
					if (showStationCodes)
					{
						name = Stations[stnCode].name + ' (' + Stations[stnCode].code + ')';
					}
					else
					{
						name = Stations[stnCode].name;
					}
					
					
					
					if (o.value =='XXX'){
						
						if (Stations[stnCode].code =='XXX'){
						  break;	
						}
						
					}
					
					d.options[d.length-1] = new Option( name );
					d.options[d.length-1].value = Stations[stnCode].code;


					  if (stnCode == 'TLC' || stnCode == 'MEX'){                                            
                         
                      			   d.options[d.length-1].style.color = 'blue';
			         	   d.options[d.length-1].style.fontWeight = 'bold';                                        

                       			}



					break;
				}
			}

			if (d.length-1 == Stations[oVal].mkts.length) { break; }
		}

		d.selectedIndex = dIx;
	}
	else
	{
		fillList(d, dVal);
	}
} // end changeDest

// Assumes that Stations and SortedStations arrays were initialized and populated above
function fillList(d, dVal)
{
	 //Inicializa las rutas

	fNuevosValores();

	if (!d) { alert("There's no DropDownDest!"); return; }

	var dLabel = d.options[0].text;

	if ((dVal == '') && (d.selectedIndex > -1))
	{
		dVal = d.options[ d.selectedIndex ].value;
	}
	var dIx = 0;

	d.length = 1;
	d.options[0] = new Option(dLabel);
	if(d.getAttribute('requiredEmpty'))
    {
        d.options[0].value = d.getAttribute('requiredEmpty');
    }       
	
	var name = '';
	for (var i=0; i<SortedStations.length; i++)
	{
		
		stnCode	= SortedStations[i];
		if (Stations[stnCode].validDest == true)
		{
			if (dVal == stnCode)
			{
				dIx = d.length;
			}

                       // BEGIN
			if( i == 2)
			{
                         
			 /*d.length += 1;
			 d.options[d.length-1] = new Option( "------------------------------------");
			 d.options[d.length-1].value = d.options[0].value;
			 d.options[d.length-1].disabled = true;*/
                       
			}
			// END
			d.length += 1;
			if (showStationCodes)
			{
				name = Stations[stnCode].name + ' (' + Stations[stnCode].code + ')';
			}
			else
			{
				name = Stations[stnCode].name;
			}
			

			d.options[d.length-1] = new Option( name );
			d.options[d.length-1].value = Stations[stnCode].code;

			
			if (stnCode == 'TLC' || stnCode == 'MEX'){                                            
                         
                         d.options[d.length-1].style.color = 'blue';
			 d.options[d.length-1].style.fontWeight = 'bold';                                        

                       }

     		

		}
	}

	d.selectedIndex = dIx;

}	// end fillList

function HideShowMarket(mktIx, disp)
{

	if(!document.getElementById || !document.createTextNode)
		return true;

	var labelDate = document.getElementById(applicationJavaScriptHtmlId + '_LabelMarketDate' + mktIx);
	var labelStation = document.getElementById(applicationJavaScriptHtmlId + '_LabelMarketStation' + mktIx);
	var labelStationOut = document.getElementById(applicationJavaScriptHtmlId + '_LabelMarketStationOut' + mktIx);
	var orig = document.getElementById(applicationJavaScriptHtmlId + '_TextBoxMarketOrigin' + mktIx);
	var dest = document.getElementById(applicationJavaScriptHtmlId + '_TextBoxMarketDestination' + mktIx);
	var listOrigin = document.getElementById(applicationJavaScriptHtmlId + '_DropDownListMarketOrigin' + mktIx);
	var listDest = document.getElementById(applicationJavaScriptHtmlId + '_DropDownListMarketDestination' + mktIx);
	var day = document.getElementById(applicationJavaScriptHtmlId + '_DropDownListMarketDay' + mktIx);
	var month = document.getElementById(applicationJavaScriptHtmlId + '_DropDownListMarketMonth' + mktIx);
	var dateRange = document.getElementById(applicationJavaScriptHtmlId + '_DropDownListMarketDateRange' + mktIx);
	var cal = document.getElementById(applicationJavaScriptHtmlId + '_HyperLinkMarketCalendar' + mktIx);
	var block = document.getElementById(applicationJavaScriptHtmlId + '_Market' + mktIx + 'Block');
	var marketHeader = document.getElementById(applicationJavaScriptHtmlId + '_DropDownListMarketDay' + mktIx + 'Header');
	
	if (labelDate) labelDate.style.display=disp;
	if (labelStation) labelStation.style.display=disp;
	if (labelStationOut) labelStationOut.style.display=disp;
	if (orig) orig.style.display=disp;
	if (dest) dest.style.display=disp;
	if (listOrigin) listOrigin.style.display=disp;
	if (listDest) listDest.style.display=disp;
	if (day) day.style.display=disp;
	if (month) month.style.display=disp;
	if (dateRange) dateRange.style.display=disp;
	if (cal) cal.style.display=disp;
	if (block) block.style.display=disp;
	if (marketHeader) marketHeader.style.display=disp;
}

function DisableEnableMarket(mktIx, disableStatus)
{

	if(!document.getElementById || !document.createTextNode)
		return true;

	var orig = document.getElementById(applicationJavaScriptHtmlId + '_TextBoxMarketOrigin' + mktIx);
	var dest = document.getElementById(applicationJavaScriptHtmlId + '_TextBoxMarketDestination' + mktIx);
	var listOrigin = document.getElementById(applicationJavaScriptHtmlId + '_DropDownListMarketOrigin' + mktIx);
	var listDest = document.getElementById(applicationJavaScriptHtmlId + '_DropDownListMarketDestination' + mktIx);
	var day = document.getElementById(applicationJavaScriptHtmlId + '_DropDownListMarketDay' + mktIx);
	var month = document.getElementById(applicationJavaScriptHtmlId + '_DropDownListMarketMonth' + mktIx);
	var dateRange = document.getElementById(applicationJavaScriptHtmlId + '_DropDownListMarketDateRange' + mktIx);
	var cal = document.getElementById(applicationJavaScriptHtmlId + '_HyperLinkMarketCalendar' + mktIx);
	
	if (orig) orig.disabled=disableStatus;
	if (dest) dest.disabled=disableStatus;
	if (listOrigin) listOrigin.disabled=disableStatus;
	if (listDest) listDest.disabled=disableStatus;
	if (day) day.disabled=disableStatus;
	if (month) month.disabled=disableStatus;
	if (dateRange) dateRange.disabled=disableStatus;
	if (cal) cal.disabled=disableStatus;
}


function AVAILABILITYSEARCHINPUT_Validate(validateEventArgs)
{
	
	if (CheckCities() && CheckDates() && CheckPassengers() && CheckPaxCount())
	{
		return true;
	}

	return false;
}

function CheckPassengers()
{
	var tooManyInfants = localizedTextTooManyInfants;
	var ds = document['SkySales'];
	var adult = GetSelectedValue(applicationJavaScriptHtmlId + '_DropDownListAdult')*1;
	var child = GetSelectedValue(applicationJavaScriptHtmlId + '_DropDownListChild')*1; 
	var infant = GetSelectedValue(applicationJavaScriptHtmlId + '_DropDownListInfant')*1; 

	if ((adult) && (infant) && (infant > adult))
	{
		alert(tooManyInfants);
		return false;
	}

	return true;
}

function UpdateCalendarDate(updateCalendarDateEventArgs)
{
	var ds = document['SkySales'];
	var dropDownListMarketDay = applicationJavaScriptHtmlId + '_DropDownListMarketDay' + updateCalendarDateEventArgs.passedInfo;
	var dropDownListMarketMonth = applicationJavaScriptHtmlId + '_DropDownListMarketMonth' + updateCalendarDateEventArgs.passedInfo;
			
	var month = updateCalendarDateEventArgs.dateSelected.getMonth() + 1;
	if(month < 10)
	{
		month = '0' + month;
	}
	var day = updateCalendarDateEventArgs.dateSelected.getDate();
	if(day < 10)
	{
		day = '0' + day;
	}
			
	var srt='-'+updateCalendarDateEventArgs.dateSelected.getYear();
	var a=srt.substring(srt.length-2,srt.length);
					
	ds[dropDownListMarketMonth].value = '20'+a + '-' + month;
	//ds[dropDownListMarketMonth].value = updateCalendarDateEventArgs.dateSelected.getYear() + '-' + month;
	ds[dropDownListMarketDay].value = day;
}


// find the index of where value is in the list
// and returns the index.
function findIndexByValue(list, value)
{
	var i=0;
	while ( i< list.length )
	{
		if ( list[i].value == value )
			return i;
		i++;
	}
	return -1;
}

function addOption(list, text, value)
{
	var idx = list.length;
	list[idx]=new Option(text);
	list[idx].value=value;
	list.selectedIndex=idx;
	return idx;
}

function setDatesState(state, mktIx)
{
	ElementsState['DropDownListMarketDay'+mktIx] = state;
	ElementsState['DropDownListMarketMonth'+mktIx] = state;
	ElementsState['DropDownListMarketDateRange'+mktIx] = state;
	ElementsState['HyperLinkMarketCalendar'+mktIx] = state;
}

function setPaxsState(state)
{
	ElementsState['DropDownListAdult'] = state;
	ElementsState['DropDownListChild'] = state;
	ElementsState['DropDownListInfant'] = state;
	ElementsState['PassengersBlock'] = state;
}

function setMarketState(state, mktIx)
{
	ElementsState['Market'+mktIx+'Block'] = state;
}

function validateElement(elementName)
{
	if ((document['SkySales'][applicationJavaScriptHtmlId + '_' + elementName]) && (ElementsState[elementName]!= 'cancel') ) 
		return true;
	return false;
}


//This functions uses the global variable applicationNumberOfMarketsToOffer, defined in the XSLT file for the 
//AvailabilitySearchInput control.
function ReturnDateDisplay()
{
	if(!document.getElementById || !document.createTextNode)
		return true;

	var selected   = GetMarketStructure();

	if (selected == 'OneWay')
	{
		for (mktIx=2; mktIx<=applicationNumberOfMarketsToOffer; mktIx++)
			HideShowMarket(mktIx, 'none');
	}
	else  if (selected == 'RoundTrip')
	{
		for (mktIx=2; mktIx<=applicationNumberOfMarketsToOffer; mktIx++)
			HideShowMarket(mktIx, 'none');
		var mktIx = 2;
		var disp = 'inline';
		var labelDate = document.getElementById(applicationJavaScriptHtmlId + '_LabelMarketDate' + mktIx);
		var day = document.getElementById(applicationJavaScriptHtmlId + '_DropDownListMarketDay' + mktIx);
		var month = document.getElementById(applicationJavaScriptHtmlId + '_DropDownListMarketMonth' + mktIx);
		var dateRange = document.getElementById(applicationJavaScriptHtmlId + '_DropDownListMarketDateRange' + mktIx);
		var cal = document.getElementById(applicationJavaScriptHtmlId + '_HyperLinkMarketCalendar' + mktIx);
        var marketHeader = document.getElementById(applicationJavaScriptHtmlId + '_DropDownListMarketDay' + mktIx + 'Header');
        
		if (labelDate) labelDate.style.display=disp;
		if (day) day.style.display=disp;
		if (month) month.style.display=disp;
		if (dateRange) dateRange.style.display=disp;
		if (cal) cal.style.display=disp;
        if (marketHeader) marketHeader.style.display=disp;
	}
	else  if (selected == 'OpenJaw')
	{
		for (mktIx=1; mktIx<3; mktIx++)
			HideShowMarket(mktIx, 'inline');
		for (mktIx=3; mktIx<=applicationNumberOfMarketsToOffer; mktIx++)
			HideShowMarket(mktIx, 'none');
	}
	else
	{
		for (mktIx=2; mktIx<=applicationNumberOfMarketsToOffer; mktIx++)
			HideShowMarket(mktIx, 'inline');
	}	
}

function GetMarketStructure()
{
	var radioGroup = document['SkySales'][applicationHtmlId + 'RadioButtonMarketStructure'];

	var selected   = '';

	if (radioGroup)
	{
		if (radioGroup[0]) // array of buttons
		{
			for (var i=0; i<radioGroup.length; i++)
			{
				if (radioGroup[i].checked)
				{
					selected = radioGroup[i].value;
					break;
				}
			}
		}
		else // single button
		{
			selected = radioGroup.value;
		}

		if (selected=='OneWay')
		{
			numMarketsToValidate=1;
			numDatesToValidate=1;
		}
		else if (selected=='RoundTrip')
		{
			numMarketsToValidate=1;
			numDatesToValidate=2;
		}
		else if (selected=='OpenJaw')
		{
			numMarketsToValidate=2;
			numDatesToValidate=2;
		}
		else 
		{
			numMarketsToValidate=applicationNumberOfMarketsToOffer; //set to max
			numDatesToValidate=applicationNumberOfMarketsToOffer;
		}

		return selected;
	}				
}
	

/*
* Validates that the first departure date selected is not before the current date
* Validates that the date for marketN is not earlier than marketN-1
*/
function CheckDates()
{	
	var ds=document['SkySales'];					
	var dateToCompare = applicationFormatedDate; 
	var dayToday = applicationFormatedDay;
	var monthYearValue = applicationFormatedDateTime;
	for (var mktIx=1; mktIx<=numDatesToValidate; mktIx++)
	{
		if (MarketAction[mktIx] == 'Cancel')
			continue;

		if (!validateElement('DropDownListMarketDay' + mktIx))
			continue;

		var mktDay 	= ds[applicationJavaScriptHtmlId + '_DropDownListMarketDay'+mktIx].options[ds[applicationJavaScriptHtmlId + '_DropDownListMarketDay'+mktIx].selectedIndex].value;
		var mktMonth	= ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth'+mktIx].options[ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth'+mktIx].selectedIndex].value.substring(5, 7);
		var mktYear	= ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth'+mktIx].options[ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth'+mktIx].selectedIndex].value.substring(0, 4);
		var mktMonthText	= ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth'+mktIx].options[ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth'+mktIx].selectedIndex].text;
		var mkt2Lines	= 0;	// TODO: set this to 1 if/when mkt2 month and day lists have a default '-' item at index 0.
		var mktDate = ''+mktYear+mktMonth+mktDay;
		
		if (! CheckDaysOfMonth(mktDay, mktMonth, mktYear))
		{
			alert(localizedTextInvalidDatePre + mktDay + localizedTextInvalidDateMid + mktMonthText + localizedTextInvalidDatePost);
			return false;
		}
		
		// don't check date if liftstatus is not default
		if (mktDate < dateToCompare && MarketLiftStatus[mktIx]== applicationLiftStatus)
		{
			if (mktIx == 1)
			{
				// if dptr of first market is past date, display alert and set to current date
				var msg=localizedTextPastDatePre;

				// don't want to reset the date when it's not 'change'
				// 'retain' is supposed to keep the old dates
				if (MarketAction[mktIx]=='New' || MarketAction[mktIx]=='Change')
				{
					msg=msg+localizedTextPastDatePost;
					alert(msg);
					ds[applicationJavaScriptHtmlId + '_DropDownListMarketDay'+mktIx].options.selectedIndex = dayToday - 1;
					ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth'+mktIx].options.selectedIndex = findIndexByValue(ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth'+mktIx],monthYearValue);
				}
				else
					alert(msg);
				return false;
			}
			else
			{
				var msg=localizedTextEarlierDatePre;
				if (MarketAction[mktIx]=='New' || MarketAction[mktIx]=='Change')
				{
					msg=msg+localizedTextEarlierDatePost;
					alert(msg);
					ds[applicationJavaScriptHtmlId + '_DropDownListMarketDay'+mktIx].options.selectedIndex = eval(ds[applicationJavaScriptHtmlId + '_DropDownListMarketDay'+(mktIx-1)].options.selectedIndex) + mkt2Lines;
					ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth'+mktIx].options.selectedIndex = eval(ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth'+(mktIx-1)].options.selectedIndex) + mkt2Lines;
				}
				else
					alert(msg);
				return false;
			}
		}
		
		dateToCompare = mktDate;

	}

	dateToCompare = applicationFormatedDate;
	
	// look for first market that's not 'Cancel'and not 'Retain'
	// these are the markets where availability will be obtained
	for (var mktIx=1; mktIx<=numDatesToValidate; mktIx++)
	{
		if (MarketAction[mktIx] == 'Cancel' || MarketAction[mktIx] == 'Retain')
			continue;
		if (!validateElement('DropDownListMarketDay' + mktIx))
			continue;

	var mktDay 	= ds[applicationJavaScriptHtmlId + '_DropDownListMarketDay'+mktIx].options[ds[applicationJavaScriptHtmlId + '_DropDownListMarketDay'+mktIx].selectedIndex].value;
	var mktMonth	= ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth'+mktIx].options[ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth'+mktIx].selectedIndex].value.substring(5, 7);
	var mktYear	= ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth'+mktIx].options[ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth'+mktIx].selectedIndex].value.substring(0, 4);
	var mktDate = ''+mktYear+mktMonth+mktDay;

	if (mktDate == dateToCompare)
	{
		var todayDateMsg = localizedTextTodaysDateMessage;
		if (todayDateMsg)
		{
			alert(todayDateMsg);
		}
	}
	break; 
	} // end loop to look for first market that's not 'Cancel'and not 'Retain'

	return true;
}

function OpenCalendar(market)
{
	// do nothing if market is not visible or disabled
	if (MarketAction[market]=='Cancel' || MarketAction[market]=='Retain')
	return;

	var ds = document['SkySales'];
	var dropDownListMarketDay = applicationJavaScriptHtmlId + '_DropDownListMarketDay' + market;
	var dropDownListMarketMonth = applicationJavaScriptHtmlId + '_DropDownListMarketMonth' + market;
	var selectedMonth = ds[dropDownListMarketMonth].options[ds[dropDownListMarketMonth].options.selectedIndex].value;
	var selectedDay = ds[dropDownListMarketDay].options[ds[dropDownListMarketDay].options.selectedIndex].value; 
	var appendUrl = '';
	if(market > 1)
	{
		var dropDownListMarketDayPrev = applicationJavaScriptHtmlId + '_DropDownListMarketDay'+(market-1);
		var dropDownListMarketMonthPrev = applicationJavaScriptHtmlId + '_DropDownListMarketMonth'+(market-1);
		var lockDownDay = ds[dropDownListMarketDayPrev].options[ds[dropDownListMarketDayPrev].options.selectedIndex].value;
		var lockDownMonth = ds[dropDownListMarketMonthPrev].options[ds[dropDownListMarketMonthPrev].options.selectedIndex].value;
		appendUrl = '&lockDownDay=' + lockDownDay + '&lockDownMonth=' + lockDownMonth;
	}
	var url = applicationCalendarUriQueryString + 'passedInfo=' + market + '&selectedMonth=' + selectedMonth + '&selectedDay=' + selectedDay + appendUrl;

	if (!window.calendarWindow || calendarWindow.closed)	// has not yet been defined
	{
		calendarWindow = window.open(url,'calendar','width=250,height=251,toolbar=0,status=0,location=0,menubar=0,scrollbars=0,resizable=0');
		//calendarWindow = window.open(url,'calendar','width=250,height=251,toolbar=1,status=1,location=1,menubar=1,scrollbars=1,resizable=1');
	}
	else	// has been defined
	{
		// still open
		calendarWindow.focus();
	}
}

var tempEventArgs;
var retryCount = 0;
function UpdateFlightSearch(eventArgs)
{
	//Safe retry if the object hasn't been initialized yet
	if (ExistingMarkets == null || ExistingMarkets.length == 0)
	{
		tempEventArgs = eventArgs;
		retryCount++;
		if (retryCount < 4)
		{
			setTimeout('UpdateFlightSearch(tempEventArgs)',50);
		}
		
		return;
	}
	
	var allowOpenJaw = applicationOpenJawEnabled;
	var ds = document['SkySales'];

	for (var i=0; i<eventArgs.SelectedModificationsArray.length; i++)
	{

		var orig = ds[applicationJavaScriptHtmlId + '_TextBoxMarketOrigin' + (i+1)];
		var dest = ds[applicationJavaScriptHtmlId + '_TextBoxMarketDestination' + (i+1)]; 
		var listOrigin = ds[applicationJavaScriptHtmlId + '_DropDownListMarketOrigin' + (i+1)]; 
		var listDest = ds[applicationJavaScriptHtmlId + '_DropDownListMarketDestination' + (i+1)]; 
		var day = ds[applicationJavaScriptHtmlId + '_DropDownListMarketDay' + (i+1)];
		var month = ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth' + (i+1)];

		if ( eventArgs.SelectedModificationsArray[i] == 'Retain')
		{
			var ds = document['SkySales'];
			var idx=-1;
			// revert values to market from existing booking 
			if (orig) orig.value=ExistingMarkets[i+1].orig;
			if (dest) dest.value=ExistingMarkets[i+1].dest;

			if (listOrigin)
			{
					listOrigin.selectedIndex=findIndexByValue(listOrigin,ExistingMarkets[i+1].orig);
					changeDest(listOrigin, listDest, listOrigin,ExistingMarkets[i+1].orig);
					idx= findIndexByValue(listDest,ExistingMarkets[i+1].dest);
					if (idx== '-1')
						addOption(listDest,ExistingMarkets[i+1].dest, ExistingMarkets[i+1].dest);
					else
						listDest.selectedIndex=idx;
			}
			if (day) day.selectedIndex=findIndexByValue(day,ExistingMarkets[i+1].day);
			if (month)
			{
			
				idx=findIndexByValue(month,ExistingMarkets[i+1].monthYearValue);
				if (idx== '-1')
					addOption(month, ExistingMarkets[i+1].monthYear, ExistingMarkets[i+1].monthYearValue);
				else
					month.selectedIndex=idx;
					
			}
			// diabled = retained
			setStationsState('retain', i+1);
			setDatesState('retain', i+1);
			setMarketState('retain', i+1);
			setPaxsState('retain');
			MarketAction[i+1] = 'Retain';
		}
		else if ( eventArgs.SelectedModificationsArray[i] == 'Change')
		{
			// enabled = change
			setDatesState('change', i+1);
			setMarketState('change', i+1);
			MarketAction[i+1] = 'Change';
			if (exists('Retain'))
			{
				setPaxsState('retain');
				if (allowOpenJaw)
					setStationsState('change', i+1);
				else
					setStationsState('cancel', i+1);
			}
			else //if all other mkts == Change or Cancel
			{
				setStationsState('change', i+1);
				setPaxsState('change');
			}
		}
		else // mkt == 'Cancel'
		{

			if (orig) orig.value=localizedTextTextBoxMarketOrigin;
			if (dest) dest.value=localizedTextTextBoxMarketDestination;

			if (listOrigin)
			{
					listOrigin.selectedIndex=findIndexByValue(listOrigin,'???');
					listDest.selectedIndex=findIndexByValue(listDest,'???');
			}

			// hidden = cancel
			setStationsState('cancel', i+1);
			setDatesState('cancel', i+1);
			setMarketState('cancel', i+1);
			MarketAction[i+1] = 'Cancel';
			if (all('Cancel'))
				setPaxsState('cancel');
		}
	}

	changeInterface();

}

function changeInterface()
{
	if(!document.getElementById || !document.createTextNode)
		return true;

	var ds = document['SkySales'];
	for (var id in ElementsState)
	{
		if (ElementsState[id] == 'retain')
		{
			if (document.getElementById(applicationJavaScriptHtmlId + '_'+id)) document.getElementById(applicationJavaScriptHtmlId + '_'+id).style.display = 'inline';
			if (ds[applicationJavaScriptHtmlId + '_'+id]) ds[applicationJavaScriptHtmlId + '_'+id].disabled = true;
		}
		else if (ElementsState[id] == 'change')
		{
			if (document.getElementById(applicationJavaScriptHtmlId + '_'+id)) document.getElementById(applicationJavaScriptHtmlId + '_'+id).style.display = 'inline';
			if (ds[applicationJavaScriptHtmlId + '_'+id]) ds[applicationJavaScriptHtmlId + '_'+id].disabled = false;
		}
		else if (ElementsState[id] == 'cancel')
		{
			if (document.getElementById(applicationJavaScriptHtmlId + '_'+id)) document.getElementById(applicationJavaScriptHtmlId + '_'+id).style.display = 'none';
		}
	}
}

function ExistingMarket(orig,dest,day,monthYear,monthYearValue)
{
	this.orig = orig;
	this.dest = dest;
	this.day = day;
	this.monthYear = monthYear;
	this.monthYearValue = monthYearValue;
}

function all(action)
{
	var radioGroupCount = applicationNumberOfMarketsToOffer;
	for (var i=1; i<=radioGroupCount; i++)
	{
		if ( GetCheckedValue(applicationHtmlId + 'RadioGroupMarket'+i) != action) return false;
	}
	return true;
}

function exists(action)
{
	var radioGroupCount = applicationNumberOfMarketsToOffer;
	for (var i=1; i<=radioGroupCount; i++)
	{ 
		if ( GetCheckedValue(applicationHtmlId + 'RadioGroupMarket'+i) == action) return true;
	}
	return false;
}

function CheckPaxCount()
{
	var dropDownNames = applicationPassengerArrayValues.split(",");
	var ds = document['SkySales'];
	var paxDropdownRendered = false;
	
	if(document.getElementById && document.createTextNode)
	{
		var paxCount = 0;
		var undefined;

		for(var i=0; i < dropDownNames.length; i++)
		{
			if (ds[dropDownNames[i]] != undefined)
			{
				paxDropdownRendered = true;
				paxCount = paxCount + parseInt(ds[dropDownNames[i]].value);
			}
		}

		if (paxDropdownRendered && paxCount == 0)
		{
			alert(localizedTextLessThanOnePassenger);
			return false;
		}
		else if (paxCount > applicationBookingMaxPassengers)
		{
			alert(localizedTextExceedsMaxPaxAllowed + applicationBookingMaxPassengers);
			return false;
		}
	}
	
	return true;
}

/*
* Validates that there's 1 set of O&D entered if one way is selected
* Validates that there's 1 set of O&D entered if round trip is selected
* Validates that there's 2 sets of O&D entered if open jaw is selected
* For TripPlanner, the number of markets to search is however many was entered
* For Round trip, validates that the origin is the same as the ultimate/last
* destination
* Validates that Origin is not the same as destination
* Sets the global variables numDatesToValidate and numMarketsToValidate
*/
function CheckCities()
{

	var selected   = GetMarketStructure();
		
	var ds = document['SkySales'];
	var stations = new Array();

	var i=-1;
	for (var mktIx=1; mktIx<=numMarketsToValidate; mktIx++)
	{
		if (MarketAction[mktIx] == 'Cancel')
			continue;
			
		if (applicationUseDropDownForStations)
		{
			if (validateElement('DropDownListMarketOrigin' + mktIx))
				{
					i+=1;
					stations[i] = ds[applicationJavaScriptHtmlId + '_DropDownListMarketOrigin' + mktIx];
					if (IsEmpty(stations[i], '???'))
					{
						if ( selected=='TripPlanner' && mktIx>1)
						{
							// an empty origin signals the end of the requested market
							numMarketsToValidate = mktIx-1;
							numDatesToValidate = mktIx-1;
							break;
						}
						else
						{
							alert(localizedMissingOrigin);
							return false;
						}
					}
				}
				else if (selected=='TripPlanner' && mktIx>1)
				{
					// an empty origin signals the end of the requested market
					numMarketsToValidate = mktIx-1;
					numDatesToValidate = mktIx-1;
					break;
					
				}

				if (validateElement('DropDownListMarketDestination' + mktIx))
				{
					i+=1;
					stations[i] = ds[applicationJavaScriptHtmlId + '_DropDownListMarketDestination' + mktIx];
					if (IsEmpty(stations[i], '???'))
					{
						alert(localizedMissingDest);
						return false;
					}
					
				}
		
		}
		else
		{
			if (validateElement('TextBoxMarketOrigin' + mktIx))
				{
					i+=1;
					stations[i] = ds[applicationJavaScriptHtmlId + '_TextBoxMarketOrigin' + mktIx];
					if (IsEmpty(stations[i], localizedTextTextBoxMarketOrigin))
					{
						if (selected=='TripPlanner' && mktIx>1)
						{
							// an empty origin signals the end of the requested market
							numMarketsToValidate = mktIx-1;
							numDatesToValidate = mktIx-1;
							break;
						}
						else
						{
							alert(localizedMissingOrigin);
							return false;
						}
					}
				}
				else if (selected=='TripPlanner' && mktIx>1)
				{
					// an empty origin signals the end of the requested market
					numMarketsToValidate = mktIx-1;
					numDatesToValidate = mktIx-1;
					break;
					
				}

				if (validateElement('TextBoxMarketDestination' + mktIx))
				{
					i+=1;
					stations[i] = ds[applicationJavaScriptHtmlId + '_TextBoxMarketDestination' + mktIx];
					if (IsEmpty(stations[i], localizedTextTextBoxMarketDestination))
					{
						alert(localizedMissingDest);
						return false;
					}
					
					if (stations[i].value.toUpperCase() == stations[i-1].value.toUpperCase())
					{
						alert(localizedSameOriginDestination);
						return false;
					}
				}
		}
	} // end loop mktIx<=numMarketsToValidate
	
	if (!applicationOpenJawEnabled)
	{
		var ok = true;
		if (stations.length > 2) 
		{
			for (var i=1; i<stations.length-1; i+=2)
			{
				if (stations[i].value.toUpperCase() != stations[i+1].value.toUpperCase()) 
				{
					ok = false;
					break;
				}
			}
		}
		if (!ok)
		{
			alert (localizedInvalidCityPairs);
			return false;
		}
	}
	
	return true;
} // end of AVAILABILITYSEARCH_checkCities

function setStationsState(state, mktIx)
{
	if (applicationUseDropDownForStations)
	{
		ElementsState['DropDownListMarketOrigin'+mktIx] = state;
		ElementsState['DropDownListMarketDestination'+mktIx] = state;
	}
	else
	{
		ElementsState['TextBoxMarketOrigin'+mktIx] = state;
		ElementsState['TextBoxMarketDestination'+mktIx] = state;
	}
}

function AVAILABILITYSEARCHINPUT_Validate()
{
	
	if (CheckCities() && CheckPassengers() && CheckPaxCount())
	{
		return true;
	}

	return false;
}


var jsLoaded = true;