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

function launchGoogleMapsPickup() {
        if (!checkGoogleCarPickupField())
            return;

        if (document.searchForm.pickup.value != "")
        {
            document.searchForm.pickupAirport.value = fromCode;
            document.searchForm.dropoffAirport.value = toCode;
            document.searchForm.searchAt.value = "googlemaps_pickup";
            document.searchForm.submit();
        }
        else
        {
            alert('You must enter a destination first.');
        }
    }

    function launchGoogleMapsDropoff() {
        if (!checkGoogleCarDropoffField())
            return;

        if (document.searchForm.dropoff.value != "")
        {
            document.searchForm.pickupAirport.value = fromCode;
            document.searchForm.dropoffAirport.value = toCode;
            document.searchForm.searchAt.value = "googlemaps_dropoff";
            document.searchForm.submit();
        }
        else
        {
            alert('You must enter a destination first.');
        }
    }

function toggleAutoSuggest(which) {
       // function determines which autosuggest should be activated based on
       // whichone variable

	if ( which == 'airport' )
	{
		carAirportAuto.setupTxt1();
        carAirportAuto.setupTxt2();
	}
	else
	{
		carCityAuto.setupTxt1();
        carCityAuto.setupTxt2();
	}
}

    function doInit() {
        carAirportAuto.setupTxt1();
        carAirportAuto.setupTxt2();
        getLatestInfo();
    }

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

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

        if (!checkCarFields())
            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.diff.checked)
            {
                alert('Hotwire does not currently support different drop off points.');
                return;
            }
        }

        if (to == 'carrentalexpress')
        {
            if (document.searchForm.diff.checked)
            {
                alert('CarRentalExpress does not currently support different drop off points.');
                return;
            }
        }


        if (document.searchForm.city.checked)
        {
            if (to == 'cheapoair')
            {
                alert('Sorry, car-rentals search is not currently available for city locations on Cheapoair.');
                return;
            }

            if (document.searchForm.diff.checked) {
                if (to == 'priceline') {
                    alert('Sorry, Priceline does not support different drop off locations for cities at this time.');
                    return;
                }
                else if (to == 'orbitz') {
                    alert('Sorry, Orbitz does not support different drop off locations for cities at this time.');
                    return;
                }
                else if (to == 'sidestep') {
                    alert('Sorry, SideStep does not support different drop off locations for cities at this time.');
                    return;
                }
            }
        }


        document.searchForm.searchAt.value = to;
        pageTracker._trackPageview('/outgoing/' + to);
        document.searchForm.submit();
    }

function historyInit() {
    // any history initialization will go here

    // write out the necessary html for the search history box
    writeSearchHistory();

    // fills out the form with the text from last session
    getLatestInfo();
}

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

function getLatestInfo() {

    var entry = readCookie('carlast');

//    if (entry == '')
//        return;

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

    var pickup = entries[0] || '';
    var dropoff = entries[1] || '';
    var chkdropoff = entries[2] || '';
    var pdate = entries[3] || '';
    var ptime = entries[4] || 12;
    var ddate = entries[5] || '';
    var dtime = entries[6] || 12;
    var isair = entries[7] || '';
    var pair = entries[8] || '';
    var dair = entries[9] || '';

    if (chkdropoff == 'true') {
        document.searchForm.diff.checked = true;

        if (document.searchForm.diff.onclick)
        {
            document.searchForm.diff.onclick();
        }
        else
            document.searchForm.diff.click();
    } else {
        if (document.searchForm.diff.checked == true)
            if (document.searchForm.diff.onclick)
                document.searchForm.diff.onclick();
            else
                document.searchForm.diff.click();

        document.searchForm.diff.checked = false;
    }

    if (isair != '') {
        if (isair == 'true') {
            document.searchForm.city.checked = false;
            document.searchForm.airport.checked = true;

            if (document.searchForm.airport.onclick)
            	document.searchForm.airport.onclick();
        	else
            	document.searchForm.airport.click();
        } else {
            document.searchForm.airport.checked = false;
            document.searchForm.city.checked = true;

            if (document.searchForm.city.onclick)
            	document.searchForm.city.onclick();
        	else
            	document.searchForm.city.click();
        }
    }

    if (pair != '') {
        document.searchForm.pickupAirport.value = pair;
        fromCode = pair;
    }

    if (dair != '') {
        document.searchForm.dropoffAirport.value = dair;
        toCode = dair;
    }

    if (pickup != '') {
        document.searchForm.pickup.value = pickup;
    }

    if (dropoff != '' && document.searchForm.dropoff) {
        document.searchForm.dropoff.value = dropoff;
    }

    if (pdate != '') {
        document.searchForm.pickup_date.value = pdate;
    }

//    if (ptime != '') {
        document.searchForm.ptime.value = ptime;
//    }

    if (ddate != '') {
        document.searchForm.dropoff_date.value = ddate;
    }

//    if (dtime != '') {
        document.searchForm.dtime.value = dtime;
//    }
}

// 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 pickup = document.searchForm.pickup.value;
    if (document.searchForm.dropoff)
        var dropoff = document.searchForm.dropoff.value;
    else
        var dropoff = '';
    var chkDifferentDropoff = document.searchForm.diff.checked;
    var pickup_date = document.searchForm.pickup_date.value;
    var ptime = document.searchForm.ptime.value;
    var dropoff_date = document.searchForm.dropoff_date.value;
    var dtime = document.searchForm.dtime.value;
    var isAir = document.searchForm.airport.checked;
    var pickupAir = document.searchForm.pickupAirport.value;
    var dropoffAir = document.searchForm.dropoffAirport.value;

    if (isAir == 'false') {
        pickupAir = '';
        dropoffAir = '';
    }

    var myStr = concatItems(pickup,dropoff,chkDifferentDropoff,pickup_date,
                            ptime,dropoff_date,dtime,isAir,pickupAir,dropoffAir);

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

// 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('carcount'));

//    if (isNaN(count))
//        return;

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

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

/*
    var pickup = document.searchForm.pickup.value;
    var dropoff = document.searchForm.dropoff.value;
    var chkDifferentDropoff = document.searchForm.diff.checked;
    var pickup_date = document.searchForm.pickup_date.value;
    var ptime = document.searchForm.ptime.value;
    var dropoff_date = document.searchForm.dropoff_date.value;
    var dtime = document.searchForm.dtime.value;
*/

    var pickup = entries[0] || '';
    var dropoff = entries[1] || '';
    var chkdropoff = entries[2] || '';
    var pdate = entries[3] || '';
    var ptime = entries[4] || 12;
    var ddate = entries[5] || '';
    var dtime = entries[6] || 12;
    var isair = entries[7] || '';
    var pair = entries[8] || '';
    var dair = entries[9] || '';

    if (chkdropoff == 'true') {
        document.searchForm.diff.checked = true;

        if (document.searchForm.diff.onclick)
            document.searchForm.diff.onclick();
        else
            document.searchForm.diff.click();
    } else {
        if (document.searchForm.diff.checked == true)
            if (document.searchForm.diff.onclick)
                document.searchForm.diff.onclick();
            else
                document.searchForm.diff.click();

        document.searchForm.diff.checked = false;
        hide_rows( true );
    }

    if (isair == 'true') {
        document.searchForm.city.checked = false;
        document.searchForm.airport.checked = true;

        if (document.searchForm.airport.onclick)
           	document.searchForm.airport.onclick();
       	else
           	document.searchForm.airport.click();
    } else {
        document.searchForm.airport.checked = false;
        document.searchForm.city.checked = true;

        if (document.searchForm.city.onclick)
           	document.searchForm.city.onclick();
       	else
           	document.searchForm.city.click();
    }

    document.searchForm.pickupAirport.value = pair;
    fromCode = pair;
    document.searchForm.dropoffAirport.value = dair;
    toCode = dair;

    document.searchForm.pickup.value = pickup;
    document.searchForm.dropoff.value = dropoff;
    document.searchForm.pickup_date.value = pdate;
    document.searchForm.ptime.value = ptime;
    document.searchForm.dropoff_date.value = ddate;
    document.searchForm.dtime.value = dtime;
}

// writeSearchHistory()
//
// @summary: modifies the inner HTML of the history popup box to represent what's inside the cookie
// @params: none
// @return: none, modifies the inner HTML of the history popup

function writeSearchHistory() {
    var count = parseInt(readCookie('carcount'));
    var timeTable = new Array(24);

    // this used to be a loop -- but I unrolled it for a few reasons
    //
    // 1.) It's faster and easier to read this way
    // 2.) The Midnight and Noon times

    timeTable[0] = 'Midnight';
    timeTable[1] = '1:00AM';
    timeTable[2] = '2:00AM';
    timeTable[3] = '3:00AM';
    timeTable[4] = '4:00AM';
    timeTable[5] = '5:00AM';
    timeTable[6] = '6:00AM';
    timeTable[7] = '7:00AM';
    timeTable[8] = '8:00AM';
    timeTable[9] = '9:00AM';
    timeTable[10] = '10:00AM';
    timeTable[11] = '11:00AM';
    timeTable[12] = 'Noon';
    timeTable[13] = '1:00PM';
    timeTable[14] = '2:00PM';
    timeTable[15] = '3:00PM';
    timeTable[16] = '4:00PM';
    timeTable[17] = '5:00PM';
    timeTable[18] = '6:00PM';
    timeTable[19] = '7:00PM';
    timeTable[20] = '8:00PM';
    timeTable[21] = '9:00PM';
    timeTable[22] = '10:00PM';
    timeTable[23] = '11:00PM';

    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('carentry'+i);

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

/*
    var pickup = document.searchForm.pickup.value;
    var dropoff = document.searchForm.dropoff.value;
    var chkDifferentDropoff = document.searchForm.diff.checked;
    var pickup_date = document.searchForm.pickup_date.value;
    var ptime = document.searchForm.ptime.value;
    var dropoff_date = document.searchForm.dropoff_date.value;
    var dtime = document.searchForm.dtime.value;
*/

            var pickup = entries[0];
            var dropoff = entries[1];
            var chkdropoff = entries[2];
            var pdate = entries[3];
            var ptime = entries[4];
            var ddate = entries[5];
            var dtime = entries[6];
            var isair = entries[7];
            var pair = entries[8];
            var dair = entries[9];

            // do the necessary processing to get the location (city, st/city, country)
            var pickupName = pickup.split('-');
            var pickupLoc = pickupName[0];

            if ( chkdropoff == 'true' )
            {
            	var dropoffName = dropoff.split('-');
           		var dropoffLoc = dropoffName[0];
            }

            if (isair == 'true') {
                pickupCode = pair;
                dropoffCode = dair;

                // do the necessary processing to get the location (city, st/city, country)
	            var pickupName = pickup.split('-');
	            var pickupLoc = pickupName[0];

	            // build the pickup part of the string here
	            var pickupString = pickupLoc + ' (' + pickupCode + ') ';

	            if ( chkdropoff == 'true' )
	            {
	            	var dropoffName = dropoff.split('-');
	           		var dropoffLoc = dropoffName[0];
	           		var dropoffString = dropoffLoc + ' (' + dropoffCode + ') ';
	            }

            } else {
                pickupArr = pickup.split(',');

                if (pickupArr.length >= 3) {
                    pickup = pickupArr[0] + ', ' + pickupArr[1];
                }

                pickupString = pickup + ' ';

                dropoffArr = dropoff.split(',');

                if (dropoffArr.length >= 3) {
                    dropoff = dropoffArr[0] + ', ' + dropoffArr[1];
                }

                dropoffString = dropoff + ' ';
            }


            var myStr = '';

            if (chkdropoff == 'true') {
                var myStr = '<li><a href="javascript:doNothing();" onclick="javascript:loadSearch(' + i + ')">Pick up, ' + pickupString + pdate + ' ' + timeTable[ptime] + ' - ' +
                            'Drop off, ' + dropoffString + ddate + ' ' + timeTable[dtime] + '</a></li>';
            }
            else {
                var myStr = '<li><a href="javascript:doNothing();" onclick="javascript:loadSearch(' + i + ')">Pick up, ' + pickupString + pdate + ' ' + timeTable[ptime] + ' - ' +
                            'Drop off, ' + ddate + ' ' + timeTable[dtime] + '</a></li>';
            }

            x.obj.innerHTML = x.obj.innerHTML + myStr;
        }
    }
}

function concatItems(pickup,dropoff,diffdropoff,pdate,ptime,ddate,dtime,isair,pair,dair) {
    return pickup+'?'+dropoff+'?'+diffdropoff+'?'+pdate+'?'+ptime+'?'+ddate+'?'+dtime+'?'+isair+'?'+pair+'?'+dair;
}

// 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('carcount'));

    if (isNaN(count))
        return -1;

    var i = 0;

    var pickup = document.searchForm.pickup.value;
    var chkDifferentDropoff = document.searchForm.diff.checked;
    if (chkDifferentDropoff == true)
        var dropoff = document.searchForm.dropoff.value;
    else
        var dropoff = '';
    var pickup_date = document.searchForm.pickup_date.value;
    var ptime = document.searchForm.ptime.value;
    var dropoff_date = document.searchForm.dropoff_date.value;
    var dtime = document.searchForm.dtime.value;
    var isAir = document.searchForm.airport.checked;
    var pickupAir = document.searchForm.pickupAirport.value;
    var dropoffAir = document.searchForm.dropoffAirport.value;

    if (isAir == 'false') {
        pickupAir = '';
        dropoffAir = '';
    }

    for (i=0;i<count;i++)
    {
        var entry = readCookie('carentry'+i);

        if (entry.toUpperCase() == concatItems(pickup,dropoff,chkDifferentDropoff,
                                               pickup_date,ptime,dropoff_date,
                                               dtime,isAir,pickupAir,dropoffAir).toUpperCase())
            return i;

    }

    return -1;
}

// 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('carcount'));

        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('carcount'));
        }

        var pickup = document.searchForm.pickup.value;
        var chkDifferentDropoff = document.searchForm.diff.checked;
        if (chkDifferentDropoff == true)
            var dropoff = document.searchForm.dropoff.value;
        else
            var dropoff = '';
        var pickup_date = document.searchForm.pickup_date.value;
        var ptime = document.searchForm.ptime.value;
        var dropoff_date = document.searchForm.dropoff_date.value;
        var dtime = document.searchForm.dtime.value;
        var isAir = document.searchForm.airport.checked;
        var pickupAir = document.searchForm.pickupAirport.value;
        var dropoffAir = document.searchForm.dropoffAirport.value;

        if (isAir == 'false') {
            pickupAir = '';
            dropoffAir = '';
        }

        var myStr = concatItems(pickup,dropoff,chkDifferentDropoff,pickup_date,
                                ptime,dropoff_date,dtime,isAir,pickupAir,dropoffAir);

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

        var txtCount = String(count+1);

        writeCookie('carcount', 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('carcount'));

    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( 'carentry'+i );
    	writeCookie( 'carentry'+newSearchNum, curSearch, false );
    }

    // everything has been shifted up, so now we need to delete that last one

    while ( count > MAX_NUM_SEARCHES-1 )
    {
    	deleteCookie( 'carentry'+count );
    	count--;
    }

    writeCookie( 'carcount', String(count), false );
}

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

	if ( isNaN( count ) || index == count-1 )
		return;

	var newSearch = readCookie( 'carentry' + 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( 'carentry' + i );

		writeCookie( 'carentry' + indexToWriteTo, curSearch, false );
	}

	// now write the search being done to the top slot
	writeCookie( 'carentry' + (count-1), newSearch, false );
}

// deleteSearches()
//
// @summary: deletes all searches from the cookie (effectively erasing "search history")
// @params: none
// @output: none

function deleteSearches() {
    var count = parseInt(readCookie('carcount'));

    if (isNaN(count))
        return;

    var i = 0;

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

    deleteCookie('carcount');
    deleteCookie('carlast');
}

/*
function showCarHistory(name) {
    var x = new getObj(name);

    x.style.visibility = 'visible';

}

function hideCarHistory(name) {
    var x = new getObj(name);

    x.style.visibility = 'hidden';

}


function showHistory(name) {
    var x = new getObj(name);

    x.style.visibility = 'visible';

    // extremely ugly hack to get IE to comply with the z-order
    var y = new getObj('selTravelers');
    y.style.visibility = 'hidden';
}

function hideHistory(name) {
    var x = new getObj(name);

    x.style.visibility = 'hidden';

    // extremely ugly hack to get IE to comply with the z-order
    var y = new getObj('selTravelers');
    y.style.visibility = 'visible';
}*/

function launchGoogleMaps() {
    if (!checkGoogleHotelField())
        return;

    if (document.searchForm.where.value != "")
    {
        document.searchForm.whereAirport.value = fromCode;
        document.searchForm.searchAt.value = "googlemaps";
        document.searchForm.submit();
    }
    else
    {
        alert('You must enter a destination first.');
    }
}

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 checkCarFields() {
    if (document.searchForm.pickup.value.length < 1) {
        alert('Please enter a "Pick-up" location.');
        return false;
    }

    if (document.searchForm.diff.checked) {
        if (document.searchForm.dropoff.value.length < 1) {
            alert('Please enter a "Drop-off" location.');
            return false;
        }
    }

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

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

    return true;
}

function checkGoogleCarPickupField() {
    if (document.searchForm.pickup.value.length < 1) {
        alert('Please enter a "Pick-up" location.');
        return false;
    }

    return true;
}

function checkGoogleCarDropoffField() {
    if (document.searchForm.dropoff.value.length < 1) {
        alert('Please enter a "Drop-off" location.');
        return false;
    }

    return true;
}

function cars_airport_clicked()
{
    var count = parseInt(readCookie('carcount'));
    if (isNaN(count)) {
        count = 0;
    }

    for (var i=count-1; i>=0; --i) {
        var entry = readCookie('carentry'+i);
        if ('' == trim(entry)) {
            continue;
        }

        var entries = entry.split('?');
        var isair = entries[7];
        if ('true' == isair) {
            loadSearch(i);
            return;
        }
    }

    loadSearch(-1);
    $('airport').checked = true;
}

function cars_city_clicked()
{
    var count = parseInt(readCookie('carcount'));
    if (isNaN(count)) {
        count = 0;
    }

    for (var i=count-1; i>=0; --i) {
        var entry = readCookie('carentry'+i);
        if ('' == trim(entry)) {
            continue;
        }

        var entries = entry.split('?');
        var isair = entries[7];
        if ('false' == isair) {
            loadSearch(i);
            return;
        }
    }

    loadSearch(-1);
    $('city').checked = true;
}

function cars_ondomloaded()
{
    Event.observe($('airport'), 'click', cars_airport_clicked);
    Event.observe($('city'), 'click', cars_city_clicked);
}

odl.register(cars_ondomloaded);
