// This function sets the recent search as an entry in the cookie and calls
// addRecentSearch function to add the recent search as an option in the
// recent searches drop-down list.


function setRecentSearch() {
	// set expiry date of cookie to within 30 days.
	var today = new Date();
	var exp_days = 30 * 1000 * 60 * 60 * 24;
	var expires_date = new Date( today.getTime() + (exp_days) );
	var trip_type = '';
	
	// on home page, trip type are three radio buttons while on results page
	// it is a drop-down list.
	if ( document.getElementById( 'trip_type' ).type == 'radio' ) {
		if ( document.SearchFare.trip_type[0].checked ) {
			trip_type = 'return';
		}
		else if ( document.SearchFare.trip_type[1].checked ) {
			trip_type = 'oneway';
		}
		else {
			trip_type = 'multicity';
		}
	}
	else {
		var tripType_ddl = document.SearchFare.trip_type;
		var tripType_ddl_val = tripType_ddl.options[ tripType_ddl.selectedIndex ].value;
		if ( tripType_ddl_val == '1' ) {
			trip_type = 'return';
		}
		else if ( tripType_ddl_val == '0' ) {
			trip_type = 'oneway';
		}
		else {
			trip_type = 'multicity';
		}
	}
	 var return_date = document.getElementById( "return_date" ).value;
    /* var return_date = ( trip_type == 'return' || trip_type == 'multicity' ) ? 
        document.getElementById( "return_date" ).value : ''; */
    var depApt = document.getElementById("gateway_departure").value;
    var retApt = document.getElementById("gateway_return").value;
    depApt = depApt.replace(/-/g, '|');
    retApt = retApt.replace(/-/g, '|');

	var depApt2 = '';
	var retApt2 = '';
	if ( trip_type == 'multicity' ) {
		depApt2 = document.getElementById( 'dest_departure' ).value;
		retApt2 = document.getElementById( 'dest_return' ).value;
		depApt2 = depApt2.replace(/-/g, '|');
		retApt2 = retApt2.replace(/-/g, '|');
    }
	var cookieVal = getCookieVal( "flightssearch" );
	var searchData = depApt + '-' +
					 retApt + '-' +
					 depApt2 + '-' +
					 retApt2 + '-' +
					 document.getElementById( "depart_date" ).value + '-' +
					 return_date + '-' +
                     // fare type (i.e. economy, business, or first)
					 document.getElementById( "cls" ).value + '-' +
					 document.getElementById( "adult" ).value + '-' +
					 document.getElementById( "child" ).value + '-' +
					 document.getElementById( "infant" ).value + '-' +
					 trip_type;
	cookieVal = searchData + ':' + cookieVal;
    // limit 10 records
	var records = cookieVal.split(':');
	if(records.length > 10) {
		cookieVal = records[0]+':'+records[1]+':'+records[2]+':'+records[3]+
                    ':'+records[4]+':'+records[5]+':'+records[6]+':'+
                    records[7]+':'+records[8]+':'+records[9];

        var recentSearches_ddl = document.getElementById( "recentSearches_ddl" );
	    while ( recentSearches_ddl.length > 10 ) {
            recentSearches_ddl.remove( 10 );
        }
    }
    document.cookie = "flightssearch=" + escape( cookieVal ) + ";expires=" +
                      expires_date.toGMTString() + ";path=/";
    return true;
}

// This function receives searchData for a search (the record thats in the
// cookie) and adds it as an option in the recent searches drop-down list.
function addRecentSearch( searchData ) {
	try {
		var monthOfYear = new Array();
			monthOfYear[0] = "Jan";
			monthOfYear[1] = "Feb";	
			monthOfYear[2] = "Mar";
			monthOfYear[3] = "Apr";
			monthOfYear[4] = "May";
			monthOfYear[5] = "Jun";
			monthOfYear[6] = "Jul";
			monthOfYear[7] = "Aug";
			monthOfYear[8] = "Sep";
			monthOfYear[9] = "Oct";
			monthOfYear[10] = "Nov";
			monthOfYear[11] = "Dec";
		var items = unescape( searchData ).split( '-' );
			items[0] = items[0].replace( /\|/g, '-' );
			items[1] = items[1].replace( /\|/g, '-' );
			items[2] = items[2].replace( /\|/g, '-' );
			items[3] = items[3].replace( /\|/g, '-' );

		var retArr = formatLocationStr( items[0] );
		var gateway_dep_str = retArr[0];
		var gateway_dep_apt = retArr[1];
		retArr = formatLocationStr( items[1] );
		var gateway_ret_str = retArr[0];
		var gateway_ret_apt = retArr[1];
		var dep_airport;
		var ret_airport;
		var dep_temp = new Array();
		dep_temp = gateway_dep_str.split(',');
		if(dep_temp[2]==undefined){
			dep_airport='';
	    }
	    else{
			var aird_len = dep_temp[2].indexOf('-');
			if( aird_len != -1){
				dep_airport = dep_temp[2].substr(aird_len+1,2);
			}
			else{
				dep_airport = dep_temp[2].substr(1,2);
			}
		}
		var ret_temp = new Array();
		ret_temp = gateway_ret_str.split(',');
	    if(ret_temp[2]==undefined){
		    ret_airport='';
	    }
	    else{
	    	var airr_len = ret_temp[2].indexOf('-');
			if( airr_len != -1) {
				ret_airport = ret_temp[2].substr(airr_len+1,2);
			}
			else {
				ret_airport = ret_temp[2].substr(1,2);
			}
	    }
	
		dep_date = monthOfYear[(items[4].substr(0,2))-1] + ' ' + items[4].substr(3,2);
		ret_date = monthOfYear[(items[5].substr(0,2))-1] + ' ' + items[5].substr(3,2);

		// drop-down list option
		var ddlOption = document.createElement( 'option' );
		if ( items[10] == 'return' || items[10] == 'oneway' ) {
				// Make sure gateway_dep_str is not longer then 8 chars.
			var len_dep = gateway_dep_str.indexOf(',');
				if ( gateway_dep_str.length > len_dep ) {
				    gateway_dep_str = gateway_dep_str.substr( 0, len_dep) + ', ' + gateway_dep_apt;
				}

				// Make sure gateway_ret_str is not longer then 8 chars.
			var len_ret = gateway_ret_str.indexOf(',');
				if ( gateway_ret_str.length > len_ret ) {
				    gateway_ret_str = gateway_ret_str.substr( 0, len_ret) + ', ' + gateway_ret_apt;
				}

				if ( items[10] == 'return' ) {
				    // set the text for the recent search.
				    ddlOption.text = gateway_dep_str  + " - " + gateway_ret_str + " | " +  dep_date + " - " + ret_date;
				}
				else {
				   
				    ddlOption.text = gateway_dep_str + " - " + gateway_ret_str  + " | " +  dep_date;
				}
		}
		else if ( items[10] == 'multicity' ) {  // multi city is selected
			var len_dep = gateway_dep_str.indexOf(',');
				if ( gateway_dep_str.length > len_dep ) {
					gateway_dep_str = gateway_dep_str.substr( 0, len_dep ) + ', ' + gateway_dep_apt;
				}
		    // Make sure gateway_ret_str is not longer then 8 chars.
			var len_ret = gateway_ret_str.indexOf(',');
		    	if ( gateway_ret_str.length > len_ret ) {
		    		gateway_ret_str = gateway_ret_str.substr( 0, len_ret ) + ', ' + gateway_ret_apt;
				}
			retArr = formatLocationStr( items[2] );
		    var dest_dep_str = retArr[0];
		    var dest_dep_apt = retArr[1];

		    retArr = formatLocationStr( items[3] );
		    var dest_ret_str = retArr[0];
		    var dest_ret_apt = retArr[1];

			var len_dep1 = dest_dep_str.indexOf(',');
		    	if ( dest_dep_str.length > len_dep1 ) {
		    	    dest_dep_str = dest_dep_str.substr( 0, len_dep1 ) + ', ' + dest_dep_apt;
			    }

		    // Make sure gateway_ret_str is not longer then 8 chars.
			var len_ret1 = dest_ret_str.indexOf(',');
			    if ( dest_ret_str.length > len_ret1 ) {
			        dest_ret_str = dest_ret_str.substr( 0, len_ret1 ) + ', ' + dest_ret_apt;
			    }
		        // set the text for the recent search.
		        ddlOption.text = gateway_dep_str + " - " + gateway_ret_str + " - " + dest_dep_str + " - " + dest_ret_str + " | " +
		                            dep_date + " - " + ret_date;
		}
		ddlOption.value = searchData;
		recSearches = document.getElementById( 'recentSearches_ddl' );
		try {
		    recSearches.add( ddlOption, recSearches.options[1] );
		}
		catch ( e ) {
		    recSearches.add( ddlOption, 1 );
		}
		document.getElementById("recentSearches").style.display = "block";
	}
	catch(err) { } 
}

// This function gets passed one of the location strings from the search form,
// formats it for the recent search text, and returns an array with the first
// element as this formatted string, and the second element being the extracted
// airport code (which will be appended to the location string later).
function formatLocationStr(locationStr) {
	try {
		var pattern = /^(.*?)\,\s*(.*?)\s*-\s*(.*?)\((...)\)$/;
		var locationStrInfo = pattern.exec( locationStr );
		var newLocationStr = locationStrInfo[1];
		if ( locationStrInfo[2] ) {
			newLocationStr += ', ' + locationStrInfo[2];
		}
		if ( locationStrInfo[3] ) {
			newLocationStr += ', ' + locationStrInfo[3];
		}
		var retArr = new Array();
		retArr[0] = newLocationStr;
		retArr[1] = locationStrInfo[4];
		
		return retArr;
	}
	catch(err) { } 
}

//default cookie
function set_cookie_data(recentSearches) {
	
	var arrdata= recentSearches.split("-");
	if ( arrdata[10] == 'return') {
		$("#multicity_row").slideUp(); 
		$("#return_date").attr("disabled", false);
	    $("#return_date").datepicker("enable");
		document.SearchFare.gateway_departure.value =arrdata[0].replace( /\|/g, '-' );
		document.SearchFare.gateway_return.value =arrdata[1].replace( /\|/g, '-' );
		document.SearchFare.dest_departure.value =arrdata[2].replace( /\|/g, '-' );
		document.SearchFare.dest_return.value =arrdata[3].replace( /\|/g, '-' );
		document.SearchFare.depart_date.value =arrdata[4];
		document.SearchFare.return_date.value =arrdata[5];
		document.SearchFare.cls.value =arrdata[6];      
		document.SearchFare.adult.value =arrdata[7];
		document.SearchFare.child.value =arrdata[8];
		document.SearchFare.infant.value =arrdata[9];
		document.SearchFare.trip_type[0].checked = true; 
	}
	else if(arrdata[10] == 'oneway') {
		$("#multicity_row").slideUp();
		$("#return_date").attr("disabled", true);
	    $("#return_date").datepicker("disable");
		document.SearchFare.gateway_departure.value =arrdata[0].replace( /\|/g, '-' );
		document.SearchFare.gateway_return.value =arrdata[1].replace( /\|/g, '-' );
		document.SearchFare.dest_departure.value =arrdata[2].replace( /\|/g, '-' );
		document.SearchFare.dest_return.value =arrdata[3].replace( /\|/g, '-' );
		document.SearchFare.depart_date.value =arrdata[4];
		document.SearchFare.return_date.value =arrdata[5];
		document.SearchFare.cls.value =arrdata[6];      
		document.SearchFare.adult.value =arrdata[7];
		document.SearchFare.child.value =arrdata[8];
		document.SearchFare.infant.value =arrdata[9];
		document.SearchFare.trip_type[1].checked = true; 
	}
	else if ( arrdata[10] == 'multicity' ) {  // multi city is selected
		$("#multicity_row").slideDown();
		$("#return_date").attr("disabled", false);
	    $("#return_date").datepicker("enable");						
		document.SearchFare.gateway_departure.value =arrdata[0].replace( /\|/g, '-' );
		document.SearchFare.gateway_return.value =arrdata[1].replace( /\|/g, '-' );
		document.SearchFare.dest_departure.value =arrdata[2].replace( /\|/g, '-' );
		document.SearchFare.dest_return.value =arrdata[3].replace( /\|/g, '-' );
		document.SearchFare.depart_date.value =arrdata[4].replace( /\|/g, '-' );
		document.SearchFare.return_date.value =arrdata[5];
		document.SearchFare.cls.value =arrdata[6];      
		document.SearchFare.adult.value =arrdata[7];
		document.SearchFare.child.value =arrdata[8];
		document.SearchFare.infant.value =arrdata[9];
		document.SearchFare.trip_type[2].checked = true;         
	}
}

// This function populates the recent searches drop-down list with any recent
// searches found in the recent searches cookie.
function getRecentSearches() {

    if ( getCookieVal( "flightssearch" ) ) {
        var cookiestring = unescape( getCookieVal( "flightssearch" ) );
        var recentSearches = cookiestring.split( ':' );
        var output = '';

        var recentSearches_ddl ;
	try {
		recentSearches_ddl = document.getElementById( "recentSearches_ddl" );
	}catch (e) {}
	if(!recentSearches_ddl){
		return;
	}
        // Here we remove any recent searches in the drop-down list.
        for ( var i = 1; i < recentSearches_ddl.options.length; i++ ) {
            recentSearches_ddl.remove( i );
        }

        // Here we add the recent searches to the drop-down list starting
        // from the oldest (end of cookie value) to the newest. The drop-down
        // list will contain newest to oldest searches (addRecentSearch
        // function adds each search right below the default "Select a recent
        // search" option).
		recentSearches = unique(recentSearches);
		
		/*last record store as a default cookie*/
        set_cookie_data(recentSearches[0]);
		
		var count=0;	
        for ( var i = recentSearches.length - 1; i >= 0; i-- ) {
            if ( unescape( recentSearches[i] ) ) {
	            var items = unescape( recentSearches[i] ).split( '-' );
   	            if ( CheckDate(items[4]) ) {
            		addRecentSearch( recentSearches[i] );
            		count++;
		        }
		        else
		        {	
		        	continue;
			    }
            }
        }
        if(count == 0)
        document.getElementById("recentSearches").style.display = "none";
        else
        document.getElementById("recentSearches").style.display = "block";
    }
}

// Function for get the unique data
function unique(a)
{
   var r = new Array();
   o:for(var i = 0, n = a.length; i < n; i++)
   {
      for(var x = 0, y = r.length; x < y; x++)
      {
         if(r[x]==a[i]) continue o;
      }
      r[r.length] = a[i];
   }
   return r;
}

// This function runs when one of the recent searches is selected from the
// drop-down list.
function showPrev() {
	if(document.SearchFare.recentSearches_ddl.value==""){
		return false;
	}
    var searchData = document.SearchFare.recentSearches_ddl.value.split('-');
    searchData[0] = searchData[0].replace( /\|/g, '-' );
    searchData[1] = searchData[1].replace( /\|/g, '-' );
    searchData[2] = searchData[2].replace( /\|/g, '-' );
    searchData[3] = searchData[3].replace( /\|/g, '-' );
	
    // on home page, trip type are three radio buttons while on results page
    // it is a drop-down list. modified jquery added. 22-3-2010 dilip
    if ( document.getElementById( 'trip_type' ).type == 'radio' ) {
        // Selecting the appropriate trip type radio button.
        if ( searchData[10] == 'return' ) {
            document.SearchFare.trip_type[0].checked = true;
            $("#multicity_row").slideUp(); 
			$("#return_date").attr("disabled", false);
		    $("#return_date").datepicker("enable");
        }
        else if ( searchData[10] == 'oneway' ) {
            document.SearchFare.trip_type[1].checked = true;
            $("#multicity_row").slideUp();
			$("#return_date").attr("disabled", true);
		    $("#return_date").datepicker("disable");
        }
        else { //multicity
            document.SearchFare.trip_type[2].checked = true;
	       	$("#multicity_row").slideDown();
			$("#return_date").attr("disabled", false);
		    $("#return_date").datepicker("enable");

        }
    }
    else {
        // Selecting the appropriate trip type drop-down list option.
        if ( searchData[10] == 'return' ) {
            document.SearchFare.trip_type.options[1].selected = true;
            $("#multicity_row").slideUp(); 
			$("#return_date").attr("disabled", false);
		    $("#return_date").datepicker("enable");
        }
        else if ( searchData[10] == 'oneway' ) {
            document.SearchFare.trip_type.options[0].selected = true;
            $("#multicity_row").slideUp();
			$("#return_date").attr("disabled", true);
		    $("#return_date").datepicker("disable");
        }
        else { //multicity
            document.SearchFare.trip_type.options[2].selected = true;
			$("#multicity_row").slideDown();
			$("#return_date").attr("disabled", false);
		    $("#return_date").datepicker("enable");
        }
    }

    document.getElementById('gateway_departure').value = searchData[0];
    document.getElementById('gateway_return').value = searchData[1];
    document.getElementById('dest_departure').value = searchData[2];
    document.getElementById('dest_return').value = searchData[3];

    document.getElementById("depart_date").value = searchData[4];
    document.getElementById('return_date').value = searchData[5];

    document.getElementById('cls').value = searchData[6];
    document.getElementById('adult').value = searchData[7];
    document.getElementById('child').value = searchData[8];
    document.getElementById('infant').value = searchData[9];
}

// This function either returns the value of the cookie with the name that
// was passed to this function or returns an empty string if no such cookie
// could be found.
function getCookieVal( name ) {
   var exp = new RegExp( escape( name ) + "=([^;]+)" );
   if ( exp.test( document.cookie + ";" ) )
   {
      exp.exec( document.cookie + ";" );
      return unescape( RegExp.$1 );
   }
   else
   {
      return '';
   }
}

function CheckDate(return_date){
	var sDate= get_today();
	var rDate = return_date;
	
	var mon1  = parseInt(sDate.substring(0,2),10);
    var dt1 = parseInt(sDate.substring(3,5),10);
    var yr1  = parseInt(sDate.substring(6,10),10);
    var mon2  = parseInt(rDate.substring(0,2),10);
    var dt2 = parseInt(rDate.substring(3,5),10);
    var yr2  = parseInt(rDate.substring(6,10),10);
    
    sDate = new Date(yr1, mon1-1, dt1);
    rDate = new Date(yr2, mon2-1, dt2);
    
	if(sDate == rDate){
		return true;
	}	
	else if (sDate > rDate){
		return false;
	}
return true;
}

function get_today(){
   var today = new Date();
   var month=(today.getMonth()+1)<= 9 ?"0"+(today.getMonth()+1):(today.getMonth()+1);
   var date = today.getDate()<=9?"0"+today.getDate():today.getDate();
   var date_str = month + '/' + date + '/' + today.getFullYear();
   return date_str;
}

