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];
  }
}

// historyInit()
//
// @summary: initializes the history box and fills out form with last session's text
// @params: none
// @output: none

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

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

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

    var lastwhere = entries[0] || '';
    var lastcheckin = entries[1] || '';
    var lastcheckout = entries[2] || '';
    var lastguests = entries[3] || 1;
    var lastrooms = entries[4] || 1;
    var isair = entries[5] || '';
    var aircode = entries[6] || '';

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

    if (aircode != '') {
        document.searchForm.whereAirport.value = aircode;
        fromCode = aircode;
    }

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

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

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

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

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

// 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 where = document.searchForm.where.value;
    var checkin = document.searchForm.checkin.value;
    var checkout = document.searchForm.checkout.value;
    var guests = document.searchForm.guests.value;
    var rooms = document.searchForm.rooms.value;
    var isair = document.searchForm.airport.checked;
    var aircode = document.searchForm.whereAirport.value;

    if (aircode == where)
        aircode = '';

    var myStr = where+'?'+checkin+'?'+checkout+'?'+guests+'?'+rooms+'?'+isair+'?'+aircode;

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

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

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

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

    var where = entries[0] || '';
    var dateIn = entries[1] || '';
    var dateOut = entries[2] || '';
    var guests = entries[3] || 1;
    var rooms = entries[4] || 1;
    var isair = entries[5] || '';
    var aircode = entries[6] || '';

    document.searchForm.where.value = where;
    document.searchForm.checkin.value = dateIn;
    document.searchForm.checkout.value = dateOut;
    document.searchForm.guests.value = guests;
    document.searchForm.rooms.value = rooms;

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

    document.searchForm.whereAirport.value = aircode;
    fromCode = aircode;

    // hide the popup box
/*
    var x = new getDhtmlObj('list1');

    x.style.visibility = 'hidden';*/
}

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

    var guestStr = ' guests, ';
    var roomStr = ' rooms</a>';

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

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

            var where = entries[0];
            var dateIn = entries[1];
            var dateOut = entries[2];
            var guests = entries[3];
            var rooms = entries[4];
            var isair = entries[5];
            var aircode = entries[6];

            if (isair == 'true') {
                whereCode = aircode;

                // get the city, st or city, country
                var fullName = where.split( '-' );
                where = fullName[0] + '(' + whereCode + ')';
            } else {
                whereArr = where.split(',');

                if (whereArr.length >= 3) {
                    // for cases like Seattle, WA, United States;
                    // we don't want "United States" to appear on it

                    where = whereArr[0] + ', ' + whereArr[1];
                }
            }

            if (parseInt(guests) == 1)
                guestStr = ' Guest, ';
            else
                guestStr = ' Guests, ';

            if (parseInt(rooms) == 1)
                roomStr = ' Room</a>';
            else
                roomStr = ' Rooms</a>';

            x.obj.innerHTML = x.obj.innerHTML + '<li><a href="javascript:doNothing()" onclick="loadSearch(' + i + ')">' +
                              where + ', Check-in ' + dateIn + ' - Check-out ' + dateOut + '; ' + guests + guestStr + rooms +
                              roomStr + '</li>';
        }
    }
}

function concatItems(where,datein,dateout,guests,rooms,isair,aircode) {
    return where+'?'+datein+'?'+dateout+'?'+guests+'?'+rooms+'?'+isair+'?'+aircode;
}

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

    if (isNaN(count))
        return -1;

    var i = 0;

    var where = document.searchForm.where.value;
    var txtDateIn = document.searchForm.checkin.value;
    var txtDateOut = document.searchForm.checkout.value;
    var txtGuests = document.searchForm.guests.value;
    var txtRooms = document.searchForm.rooms.value;
    var isair = document.searchForm.airport.checked;
    var aircode = document.searchForm.whereAirport.value;

    if (isair == 'false')
        aircode = '';

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

        if (entry.toUpperCase() == concatItems(where,txtDateIn,txtDateOut,txtGuests,txtRooms,isair,aircode).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('count'));

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

        var where = document.searchForm.where.value;
        var txtDateIn = document.searchForm.checkin.value;
        var txtDateOut = document.searchForm.checkout.value;
        var txtGuests = document.searchForm.guests.value;
        var txtRooms = document.searchForm.rooms.value;
        var isair = document.searchForm.airport.checked;
        var aircode = document.searchForm.whereAirport.value;

        if (isair == 'false')
            aircode = '';

        var myStr = where + '?' + txtDateIn + '?' + txtDateOut + '?' + txtGuests + '?' + txtRooms + '?' + isair + '?' +
                    aircode;

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

        var txtCount = String(count+1);

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

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

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

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

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

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

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

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

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

	// now write the search being done to the top slot
	writeCookie( 'entry' + (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('count'));

    // if count is not a number, then no searches exists
    if (isNaN(count))
        return;

    var i = 0;

    for (i=0;i<count;i++)
    {
        writeCookie('entry'+i, '', true);
    }

    writeCookie('count', '', true);
    writeCookie('last','',true);
}

/*
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 doInit()
{
	enableCityAC();
	enableAirportAC();
    getLatestInfo();
}

function toggleAutoSuggest( which )
{
	if ( which == 'airport' )
	{
		enableAirportAC();
	}
	else
	{
		enableCityAC();
	}
}

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

    if (!checkHotelFields())
        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 (document.searchForm.AirportOrCity[1].checked)
    {
        if (to == 'hotelclub')
        {   
            alert('Sorry, Booktor does not support hotel search for Airport locations on HotelClub.');
            return;
        }
        else if (to == 'travelation')
        {
            alert('Sorry, Booktor does not support hotel search for Airport locations on Travelation.');
            return;
        }
        else if (to == 'asiarooms')
        {
            alert('Sorry, Booktor does not support hotel search for Airport locations on AsiaRooms.');
            return;
        }
    }

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

 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 checkHotelFields() {
    if (document.searchForm.where.value.length < 1) {
        alert('Please enter a city or airport.');
        return false;
    }

    if (!verifyDateField(document.searchForm.checkin.value) ||
         document.searchForm.checkin.value.length == 0) {
        alert('Please enter a valid "Check-In" date.');
        return false;
    }

    if (!verifyDateField(document.searchForm.checkout.value) ||
         document.searchForm.checkout.value.length == 0) {
        alert('Please enter a valid "Check-Out" date.');
        return false;
    }

    return true;
}

function checkGoogleHotelField() {
    if (document.searchForm.where.value.length < 1) {
        alert('Please enter a city or airport.');
        return false;
    }

    return true;
}

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

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

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

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

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

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

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

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

function hotels_ondomloaded()
{
    Event.observe($('airport'), 'click', hotels_airport_clicked);
    Event.observe($('city'), 'click', hotels_city_clicked);
}

odl.register(hotels_ondomloaded);
