var MAX_NUM_SEARCHES = 3;
var SEARCH_EXPIRATION = 15; // number of days

// getDhtmlObj(name)
//
// @summary: Function is used to allow DHTML processing across a wide-range of browsers
// @params: name - the name of the element (in the id= part of the html)
// @output: returns an object you can use to manipulate a page's DOM

function getDhtmlObj(name) {
	 if (document.getElementById)
	 {
	   this.obj = document.getElementById(name);
	this.style = document.getElementById(name).style;
	 }
	 else if (document.all)
	 {
	   this.obj = document.all[name];
	this.style = document.all[name].style;
	 }
	 else if (document.layers)
	 {
	  	this.obj = document.layers[name];
	  	this.style = document.layers[name];
	 }
}

function doInit()
{
	// prepopulate with last search
	setTimeout( 'getLatestInfo()', 100);
}

function writeSearchHistory() 
{
    var count = parseInt(readCookie('flightcount'));

    x = new getDhtmlObj('list1');

    if (isNaN(count))
    {
        x.obj.innerHTML = '<li><a href="#">No recent searches</a></li>';
    }
    else
    {
        var i = 0;

        x.obj.innerHTML = '';

        for (i=count-1;i>=0;i--)
        {
            
            var entry = readCookie('flightentry'+i);

            var entries = entry.split('?');

/*
    var radTripRound = document.searchForm.radioTripRound.checked;
    var radTripOneway = document.searchForm.radioTripOneway.checked;
    var selAdults = document.searchForm.selTravelers.value;
    var txtFrom = document.searchForm.txtFrom.value;
    var txtTo = document.searchForm.txtTo.value;
    var txtDepartDate = document.searchForm.txtDeparture.value;
    var txtDepartTime = document.searchForm.selDepartureTime.value;
    var txtReturnDate = document.searchForm.txtReturning.value;
    var txtReturnTime = document.searchForm.selReturningTime.value;
*/

            var roundtrip = entries[0];
            var adults = entries[1];
            var fromName = entries[2].split('-');
            var fromCity = fromName[0];
            var toName = entries[3].split('-');
            var toCity = toName[0];
            var from = entries[8];
            var to = entries[9];
            var departdate = entries[4];
            var departtime = entries[5];
            var returndate = entries[6];
            var returntime = entries[7];

		

            var tripType = 'one-way';

            if (roundtrip == 'true')
                tripType = 'round-trip';

            var fromTime = '';

            switch (departtime) 
            {
                case '0':
                    fromTime = 'Anytime';
                    break;
                case '1':
                    fromTime = 'Early Morn.';
                    break;
                case '2':
                    fromTime = 'Morning';
                    break;
                case '3':
                    fromTime = 'Noon';
                    break;
                case '4':
                    fromTime = 'Afternoon';
                    break;
                case '5':
                    fromTime = 'Evening';
                    break;
                case '6':
                    fromTime = 'Night';
                    break;                            
            }

            var toTime = '';

            switch (returntime) 
            {
                case '0':
                    toTime = 'Anytime';
                    break;
                case '1':
                    toTime = 'Early Morn.';
                    break;
                case '2':
                    toTime = 'Morning';
                    break;
                case '3':
                    toTime = 'Noon';
                    break;
                case '4':
                    toTime = 'Afternoon';
                    break;
                case '5':
                    toTime = 'Evening';
                    break;
                case '6':
                    toTime = 'Night';
                    break;                            
            }

            var endString = 'traveler';

            if (adults > 1)
                endString = 'travelers';

            if (tripType == 'round-trip') {
                var theString = fromCity + '(' + from + ') to ' + toCity + '(' +  to + '), ' + tripType + ', ' + departdate + ' ' + fromTime + ' - ' +
                                returndate + ' ' + toTime + ', ' + adults + ' ' + endString;
            }
            else {
                var theString = fromCity + '(' + from + ') to ' + toCity + '(' +  to + '), ' + tripType + ', ' + departdate + ' ' + fromTime + ', ' +
                                adults + ' ' + endString;
            }

            x.obj.innerHTML = x.obj.innerHTML + '<li><a href="javascript:doNothing()" onclick="loadSearch(' + i + ')">' +
                              theString + '</a></li>';
        }
    }
}

// readCookie()
//
// @summary: attempts to read specified cookie
// @params: name - name of the cookie to read
// @output: a string value, which represents what the cookie name was defined as.  Returns '' if no match was
//          found.

function readCookie(name) {
    var cookieArray = document.cookie.split(';');
    var i = 0;

    for (i=0;i<cookieArray.length;i++)
    {
        var ck = cookieArray[i];

        var nameValPair = ck.split('=');

        if (trim(nameValPair[0]) == name)
            return nameValPair[1];
    }

    return '';
}

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

function concatItems(roundtrip,adults,from,to,departdate,departtime,returndate,returntime,fromair,toair) {
    return roundtrip+'?'+adults+'?'+from+'?'+to+'?'+departdate+'?'+departtime+'?'+returndate+'?'+returntime+'?'+fromair+'?'+toair;
}


// writeCookie()
//
// @summary: helper function used to write cookies
// @params: name - name of the cookie
//          value - value to save
//          del - whether or not to delete this specific cookie (if it exists)
// @output: nothing, the cookie is stored in document.cookie

function writeCookie(name, value, del) {
    // default to the value set globally
    var days = SEARCH_EXPIRATION;

    // if del is true then we must delete this cookie
    if (del == true)
        days = -5;

    var date = new Date();

    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));

    // check if there is a semicolon
    var goodStr = value;
    goodStr = goodStr.replace(/;/,'');

    var result = name + "=" + value + "; expires=" + date.toGMTString() + "; path=/";

    // set this cookie
    document.cookie = result;
}


// deleteCookie()
//
// @summary: delete's the specified cookie
// @params: name - name of the cookie to delete
// @output: none

function deleteCookie(name) {
    writeCookie(name,'',true);
}

// saveLatestInfo()
//
// @summary: saves information from the form to the last session spots in the cookie, in case
//           the user leaves the site.
// @params: none
// @output: none

function saveLatestInfo() {
   	var radTripRound = document.searchForm.rtrip.checked;
    var radTripOneway = document.searchForm.oneway.checked;
    var selAdults = document.searchForm.travelers.value;
    var txtFrom = document.searchForm.from.value;
    var txtTo = document.searchForm.to.value;
    var txtDepartDate = document.searchForm.leave.value;
    var txtDepartTime = document.searchForm.ltime.value;
    var txtReturnDate = document.searchForm.rdate.value;
    var txtReturnTime = document.searchForm.rtime.value;
    var txtFromAir = document.searchForm.fromAirport.value;
    var txtToAir = document.searchForm.toAirport.value;

    var myStr = concatItems(radTripRound, selAdults, txtFrom, txtTo, txtDepartDate, 
                            txtDepartTime, txtReturnDate, txtReturnTime, txtFromAir, txtToAir);

    writeCookie('flightlast', myStr, false);
}

// addSearch()
//
// @summary: adds this search session to the cookie if it doesn't already exist.
// @params: none, reads in form values
// @output: none

function addSearch() {
    // check if this search doesn't exist already
    var searchIndex = doesSearchExist();
    
    if ( searchIndex == -1 )
    {
        // it doesn't, let's add it to the cookie

        var count = parseInt(readCookie('flightcount'));

        if (isNaN(count))
            count = 0;
         
        if ( count >= MAX_NUM_SEARCHES )
        {
        	// if there are three searches currently, we need to delete the oldest and leave a slot for the new one
        	makeRoom();
        	count = parseInt(readCookie('flightcount'));
        }

	    var radTripRound = document.searchForm.rtrip.checked;
	    var radTripOneway = document.searchForm.oneway.checked;
	    var selAdults = document.searchForm.travelers.value;
	    var txtFrom = document.searchForm.from.value;
	    var txtTo = document.searchForm.to.value;
	    var txtDepartDate = document.searchForm.leave.value;
	    var txtDepartTime = document.searchForm.ltime.value;
	    var txtReturnDate = document.searchForm.rdate.value;
	    var txtReturnTime = document.searchForm.rtime.value;
	    var txtFromAir = document.searchForm.fromAirport.value;
	    var txtToAir = document.searchForm.toAirport.value;

        var myStr = concatItems(radTripRound,selAdults,txtFrom,txtTo,txtDepartDate,
                                txtDepartTime,txtReturnDate,txtReturnTime,txtFromAir,txtToAir);

        writeCookie('flightentry'+count, myStr, false);

        var txtCount = String(count+1);

        writeCookie('flightcount', txtCount, false);

    }
    else // we know the search exists, we just need to shift it to the first slot 
    {
    	makeMostRecent( searchIndex );
    }
}

function makeRoom()
{
	 var count = parseInt(readCookie('flightcount'));

    if (isNaN(count) || count < MAX_NUM_SEARCHES ) // we should only be able to get in here if count == 3
        return;
    
    // the object here is to take saved searches 1 and 2 and shift them to 0 and 1, respectively
    for ( var i = 1 ; i < count ; i++ )
    {
    	var newSearchNum = i - 1;
    
    	var curSearch = readCookie( 'flightentry'+i );
    	writeCookie( 'flightentry'+newSearchNum, curSearch, false );
    }
    
    // everything has been shifted up, so now we need to delete that last one
    
    while ( count > MAX_NUM_SEARCHES-1 )
    {
    	deleteCookie( 'flightentry'+count );
    	count--;
    }
   
    writeCookie( 'flightcount', String(count), false );
}

function makeMostRecent( index )
{
	var count = readCookie( 'flightcount' );

	if ( isNaN( count ) || index == count-1 )
		return;
		
	var newSearch = readCookie( 'flightentry' + index );
	
	// start at the search we're doing and shift everything down
	for ( var i = index + 1 ; i < count ; i++ )
	{
		indexToWriteTo = i - 1;
		var curSearch = readCookie( 'flightentry' + i );
	
		writeCookie( 'flightentry' + indexToWriteTo, curSearch, false );
	}
	
	// now write the search being done to the top slot
	writeCookie( 'flightentry' + (count-1), newSearch, false );
}
	
function deleteSearches() 
{
    var count = parseInt(readCookie('flightcount'));

    if (isNaN(count))
        return;

    var i = 0;

    for (i=0;i<count;i++)
    {
        deleteCookie('flightentry'+i);
    }

    deleteCookie('flightcount');
    deleteCookie('flightlast');
}

function checkFlightFields() {
    if (document.searchForm.from.value.length < 1) {
        alert('Please enter a "From" airport.');
        return false;    
    }

    if (document.searchForm.to.value.length < 1) {
        alert('Please enter a "To" airport.');
        return false;    
    }

    if (!verifyDateField(document.searchForm.leave.value) ||
         document.searchForm.leave.value.length < 1) {
        alert('Please enter a valid "Depart" date.');
        return false;    
    }

    if (!document.searchForm.oneway.checked) {
        if (!verifyDateField(document.searchForm.rdate.value) ||
             document.searchForm.rdate.value.length < 1) {
            alert('Please enter a valid "Return" date.');
            return false;    
        }
    }

    return true;
}

// doesSearchExist()
//
// @summary: checks to see if a search exists inside a cookie
// @params: none, reads form elements from page
// @output: true or false

function doesSearchExist() {
    var count = parseInt(readCookie('flightcount'));

    if (isNaN(count))
        return -1;

    var i = 0;

    var radTripRound = document.searchForm.rtrip.checked;
    var radTripOneway = document.searchForm.oneway.checked;
    var selAdults = document.searchForm.travelers.value;
    var txtFrom = document.searchForm.from.value;
    var txtTo = document.searchForm.to.value;
    var txtDepartDate = document.searchForm.leave.value;
    var txtDepartTime = document.searchForm.ltime.value;
    var txtReturnDate = document.searchForm.rdate.value;
    var txtReturnTime = document.searchForm.rtime.value;
    var txtFromAir = document.searchForm.fromAirport.value;
    var txtToAir = document.searchForm.toAirport.value;

    for (i=0;i<count;i++)
    {
        var entry = readCookie('flightentry'+i);
        
        if (entry.toUpperCase() == concatItems(radTripRound,selAdults,txtFrom,txtTo,txtDepartDate,
                                               txtDepartTime,txtReturnDate,txtReturnTime,txtFromAir,txtToAir).toUpperCase())
            return i;

    }

    return -1;
}

function submitTo(to)
{
    if (fromCode != '')
        document.searchForm.fromAirport.value = fromCode;

    if (toCode != '')
        document.searchForm.toAirport.value = toCode;

    if (!checkFlightFields())
        return;

    addSearch();

    // update the search history
    writeSearchHistory();

    // save this entry as the latest session text (for when the user returns all the fields will be filled out)
    saveLatestInfo();

    if (to == 'hotwire')
    {
        if (document.searchForm.oneway.checked)
        {
            alert('Hotwire does not currently support one-way search at this time.');
            return;
        }
    }

    if (to == 'cheapair')
    {
        if (document.searchForm.travelers.value > 4)
        {
            alert('Cheapair search supports a maximum of 4 travelers.  Please choose 4 or fewer travelers to search Cheapair.');
            return;            
        }
    }

    if (to == 'bookit')
    {
        if (document.searchForm.oneway.checked)
        {
            alert('Bookit does not currently support one-way search at this time.');
            return;
        }
    }

    if (to == 'lastminutetravel')
    {
        if (document.searchForm.oneway.checked)
        {
            alert('Sorry, Booktor does not currently support one-way searches on LastMinuteTravel at this time.');
            return;
        }
    }


    document.searchForm.searchAt.value = to;
    document.searchForm.submit();
}

// loadSearch(index)
//
// @summary:  called by the history links on the page -- this function will load saved search values into the form.
// @params: index - index of the search inside the cookie
// @output: none, form is modified on page

function loadSearch(index) {

    var count = parseInt(readCookie('flightcount'));

    if (isNaN(count))
        return;

    var entry = readCookie('flightentry'+index);

    var entries = entry.split('?');

    var roundtrip = entries[0];
    var adults = entries[1];
    var from = entries[2];
    var to = entries[3];
    var departdate = entries[4];
    var departtime = entries[5];
    var returndate = entries[6];
    var returntime = entries[7];
    var fromair = entries[8];
    var toair = entries[9];

    if (roundtrip == 'true') {
        document.searchForm.oneway.checked = false;        
        document.searchForm.rtrip.checked = true;

        if (document.searchForm.rtrip.onclick)
            document.searchForm.rtrip.onclick(); // for mozilla
        else
            document.searchForm.rtrip.click(); // for IE
    }
    else {
        document.searchForm.rtrip.checked = false;
        document.searchForm.oneway.checked = true;      
        if (document.searchForm.oneway.onclick)
            document.searchForm.oneway.onclick(); // for mozilla
        else
            document.searchForm.oneway.click(); // for IE  
    }

    document.searchForm.fromAirport.value = fromair;
    fromCode = fromair;
    document.searchForm.toAirport.value = toair;
    toCode = toair;

    document.searchForm.travelers.value = adults;
    document.searchForm.from.value = from;
    document.searchForm.to.value = to;
    document.searchForm.leave.value = departdate;
    document.searchForm.ltime.value = departtime;
    document.searchForm.rdate.value = returndate;
    document.searchForm.rtime.value = returntime;

    // hide the popup box
}

// getLatestInfo()
//
// @summary: fills out the form with the last known information
// @params: none
// @output: none, form elements are modified

function getLatestInfo() {

    var entry = readCookie('flightlast');

    if (entry == '')
        return;

        var entries = entry.split('?');

    var roundtrip = entries[0];
    var adults = entries[1];
    var from = entries[2];
    var to = entries[3];
    var departdate = entries[4];
    var departtime = entries[5];
    var returndate = entries[6];
    var returntime = entries[7];
    var fromair = entries[8];
    var toair = entries[9];

    if (roundtrip == 'true') {
        document.searchForm.oneway.checked = false;        
        document.searchForm.rtrip.checked = true;

        if (document.searchForm.rtrip.onclick)
            document.searchForm.rtrip.onclick(); // for mozilla
        else
            document.searchForm.rtrip.click(); // for IE
    }
    else {
        document.searchForm.rtrip.checked = false;
        document.searchForm.oneway.checked = true;      
        if (document.searchForm.oneway.onclick)
            document.searchForm.oneway.onclick(); // for mozilla
        else
            document.searchForm.oneway.click(); // for IE  
    }

    document.searchForm.fromAirport.value = fromair;
    fromCode = fromair;
    document.searchForm.toAirport.value = toair;
    toCode = toair;

    document.searchForm.travelers.value = adults;
    document.searchForm.from.value = from;
    document.searchForm.to.value = to;
    document.searchForm.leave.value = departdate;
    document.searchForm.ltime.value = departtime;
    document.searchForm.rdate.value = returndate;
    document.searchForm.rtime.value = returntime;
}