/*****
 ***** MultiSearchValidator object
 ***** Functions for the Multi-city international search form
 ****/

function MultiSearchValidator(earliestBookingDate,formId,departCalendarSet,dataContainer){
	this.departCalendar = new Array();
	this.maxFlightLines = maxRows;
	this.earliestBookingDate=earliestBookingDate;
	this.formId=formId;
	this.dataContainer=dataContainer;
	for (i=0; i<this.maxFlightLines; i++){
  	this.departCalendar[i]=departCalendarSet[i];
	}
	this.invalidLocationOptions=['','select a city','Select a City','selectacity','separator'];
	this.depCity = new Array();
	this.arrCity = new Array();
	this.depDate = new Array();
}

MultiSearchValidator.prototype.set=function(frmelem, value){
  for(var i=0;i<frmelem.length;i++){
  	if(frmelem.options[i].value==value) {
  		frmelem.options[i].selected = true;
  		break;
  	}
  }
}

MultiSearchValidator.prototype.validateDates=function(){
	
	if(this.departCalendar[0].getDate().getTime()<this.earliestBookingDate.getTime()){
		alert(this.dataContainer.errorMsgs['bookingForm.error.startdate']);
		//alert('Online bookings must be made for flights departing after '+this.earliestBookingDate.format('DDDD D mmmm YYYY HH:00')+'.\nDeparture date needs to be on or after this date.');
		this.departCalendar[0].monthYearField.focus();
		return false;
	}
	for (i=1; i<this.userFlights; i++){
  	if (this.departCalendar[i].getDate().getTime() < this.departCalendar[i-1].getDate().getTime()){
  		
		alert(this.dataContainer.errorMsgs['bookingForm.error.orderFlights']);
  		this.departCalendar[i].monthYearField.focus();
  		return false;
		}
	}
	return true;
}

MultiSearchValidator.prototype.validateLocations=function(){
  /* 1st determine the last user inputed flight line */ 
	var endFltIndex = -1;
	for(var i=0;i<this.maxFlightLines;++i){
		var isFlightLine=true;
  	for(var j=0;j<this.invalidLocationOptions.length;++j){
  		if(this.depCity[i].value==this.invalidLocationOptions[j]){
      	for(var k=0;k<this.invalidLocationOptions.length;++k){
      		if(this.arrCity[i].value==this.invalidLocationOptions[k]){
						isFlightLine=false;
    				break;
      		}
      	}
  		}
  	}
		if (isFlightLine){
			endFltIndex = i;
		}
	}
	/* Now validate each city pair up to the last user entered flight line */
	if (endFltIndex==-1){
		
		alert(this.dataContainer.errorMsgs['bookingForm.error.mustSelect']);
  	this.depCity[0].focus();
		this.userFlights = 0;
  	return false;
	}
	this.userFlights = endFltIndex+1;
	for(var fltIdx=0;fltIdx<=endFltIndex;++fltIdx){
  	for(var i=0;i<this.invalidLocationOptions.length;++i){
  		if(this.depCity[fltIdx].value==this.invalidLocationOptions[i]){
  			
			alert(this.dataContainer.errorMsgs['bookingForm.error.departurelocation']);
			this.depCity[fltIdx].focus();
  			return false;
  		}
  	}
  	for(var i=0;i<this.invalidLocationOptions.length;++i){
  		if(this.arrCity[fltIdx].value==this.invalidLocationOptions[i]){
  			alert(this.dataContainer.errorMsgs['bookingForm.error.arrivallocation']);
  			this.arrCity[fltIdx].focus();
  			return false;
  		}
  	}
  	if(this.depCity[fltIdx].value==this.arrCity[fltIdx].value){
  		alert(this.dataContainer.errorMsgs['bookingForm.error.departurearrivallocation']);
  		this.arrCity[fltIdx].focus();
  		return false;
  	}
	}
	return true
}

MultiSearchValidator.prototype.validatePax=function(){
	var numAdults=parseInt(this.adults.value);
	var numChild=parseInt(this.children.value);
	var numInfant=parseInt(this.infants.value);
	var totalPax=numAdults+numChild+numInfant;
	var maxPax=9;
	if(totalPax>maxPax){
		alert(this.dataContainer.errorMsgs['bookingForm.error.maxpaxs']);
		this.adults.focus();
		return false;
	}
	if(numInfant>numAdults){
		alert(this.dataContainer.errorMsgs['bookingForm.error.infant']);
		this.infants.focus();
		return false;
	}
	return true;
}

MultiSearchValidator.prototype.isSearchByBestPrice=function(){
  for(var i=0;i<this.searchOption.length;++i){
  	if((this.searchOption[i].value=='B' || this.searchOption[i].value=='mustTravel')&&this.searchOption[i].checked){
  		return true;
  	}
  }
	return false;
}

/**
 * Creates a cookie to store the input of a multi-city flight search and sets it in the document
 */
MultiSearchValidator.prototype.setSelectionDetailsCke=function(type){
	var departDates="|DEPDATES:";
	var departCities="|DEPCITY:";
	var arriveCities="|ARRCITY:";
	var flightLinesCount=0;
	for (i=0; i<this.maxFlightLines; i++) {
				departCities+=","+this.depCity[i].value;
				arriveCities+=","+this.arrCity[i].value;
				departDates+=","+this.departCalendar[i].serialize();
				if (this.arrCity[i].value != '')
					flightLinesCount++;
	}
	var srcOption;
	var isDomestic=document.getElementById("isDomestic").value;
	
	if (this.isSearchByBestPrice()){
	if(isDomestic == 'true'){	 
	srcOption="|SRCHBY:F";
	}else{
		srcOption="|SRCHBY:B";
	}
	}
	else if(isDomestic == 'true'){
		 srcOption="|SRCHBY:T";
	}else{
		srcOption="|SRCHBY:S";
	}
	var z="selections=FLIGHTS:"+flightLinesCount+
			"|FARE:"+this.cabin.value+
			departDates+
			departCities+
			arriveCities+
			"|PSGRS:"+this.adults.value+
			","+this.children.value+
			","+this.infants.value+
			srcOption;
    document.cookie=z+";path=/travel";
		
/* alert('Cookie:\n\n[FLIGHTS:'+flightLinesCount+'\n'+departCities+'\n'+arriveCities+'\n'+departDates+'\n|PSGRS:'+this.adults.value+','+this.children.value+','+this.infants.value+srcOption+']'); */
    /* 
    	note that the path to the cookie has been set to /regions
    	this means that all requests to pages in the regions app
    	will have this cookie passed to them.  This is an overhead.
    	The reason for this change was that this cookie is used by the 
    	homepage ( non-struts, path regions/dyn) and the new quickSearch page
    	(struts, path regions/do/dyn).
    */
}

MultiSearchValidator.prototype.intMultiCityInitialise=function(){
	var form=document.getElementById(this.formId);
	for (i=0; i<this.maxFlightLines; i++) {
				this.depCity[i]=document.getElementById("depCity["+i+"]");
				this.arrCity[i]=document.getElementById("arrCity["+i+"]");
				this.depDate[i]=document.getElementById("depDate["+i+"]");
	}
	this.adults=form.adults;
	this.children=form.children;
	this.infants=form.infants;
	this.cabin=form.cabin;
	this.searchOption=form.searchOption;
	this.region=form.region;
	this.validateRoute=form.validateRoute;
}

MultiSearchValidator.prototype.intMultiCityValidateAndSubmit=function(){
	this.intMultiCityInitialise();
	// The order these validate methods are called in is important.
	if(!this.validateLocations()){return false;}
	if(!this.validateDates()){return false;}
	if(!this.validatePax()){return false;}
	this.setSelectionDetailsCke();
	document.intMultiCityForm.submit();
	//addPastSearch_Multi();
	return true;
}

/**
 * Sets fields common to all regions in the multi-city flight search form
 */
MultiSearchValidator.prototype.setCommonFields=function(depCity, arrCity, depDate, adults, children, infants, srchBy, fare){
	this.set(this.adults, adults);
	this.set(this.children, children);
	this.set(this.infants, infants);
	this.set(this.cabin,fare);
	
	for (i=0; i<this.maxFlightLines; i++) {
		this.set(this.depCity[i], depCity[i]);
		this.set(this.arrCity[i], arrCity[i]);
		this.departCalendar[i].deserialize(depDate[i]);
	}
	
  if (srchBy == 'B' || srchBy == 'F') {
  	this.searchOption[0].checked=true;
  } else {
  	this.searchOption[1].checked=true;
  }
}

/**
 * Parses the cookie string and populates corresponding fields in the flight search form
 * NB: the order in which form fields are set is important. 
 */
MultiSearchValidator.prototype.setSelections=function(){
	
		if((document.cookie.indexOf("selections="))!=-1){
			var val=getCookieValue("selections");
/*			var regionInd=val.indexOf("REGION:");
			var reg=val.substring(regionInd+7,regionInd+9);
			if(region==reg)
			{
*/
				var fareInd=val.indexOf("FARE:");
				var psgrsInd=val.indexOf("PSGRS:");
				var srchByInd=val.indexOf("SRCHBY:");
      	var departDateInd=val.indexOf("DEPDATES:,");
      	var departCityInd=val.indexOf("DEPCITY:,");
      	var arriveCityInd=val.indexOf("ARRCITY:,");

				var valueSet=val.substring(departDateInd+10,departCityInd-1);
				var dateSet=valueSet.split(",");
				valueSet=val.substring(departCityInd+9,arriveCityInd-1);
				var depCitySet=valueSet.split(",");
				valueSet=val.substring(arriveCityInd+9,psgrsInd-1);
				var arrCitySet=valueSet.split(",");

				var fare=val.substring(fareInd+5,fareInd+6);
				var srchBy=val.substring(srchByInd+7,srchByInd+8);
				var adults=val.substring(psgrsInd+6,psgrsInd+7);
				var children=val.substring(psgrsInd+8,psgrsInd+9);
				var infants=val.substring(psgrsInd+10,psgrsInd+11);

				this.intMultiCityInitialise();
				
				this.setCommonFields(depCitySet, arrCitySet, dateSet, adults, children, infants, srchBy, fare);
/*			} REGIONS CHECK */
		}
}
