var app_version = '$Rev: 89 $';
var SEARCH_EXPIRATION = 15; // number of days

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

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

// 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 '';
}

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

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

function removeChildren(where)
{
    while (where.childNodes.length > 0) {
        where.removeChild(where.childNodes[0]);
    }
}

function show_menu_1(e)
{
    Event.stop(e);
    var m = $('list1');
    var f = $('iframe1');
    if ('none' != m.style.display) {
        m.style.display = 'none';
    }
    else {
        m.style.display = 'block';
    }
	var listHeight = (m.getHeight() - 4) + 'px';
    if (null != f) {
    	f.setStyle({ height: listHeight });
        f.style.display = m.style.display;
    }
}

function show_menu_2(e)
{
    Event.stop(e);
    var m = $('list2');
    if ('none' != m.style.display) {
        m.style.display = 'none';
    }
    else {
        m.style.display = 'block';
    }
}

function hideMenus(e)
{
    var x = $('list3');
    if (null != x) {
        x.style.display = 'none';
    }

    var x = $('list2');
    if (null != x) {
        x.style.display = 'none';
    }

    x = $('list1');
    if (null != x) {
        x.style.display = 'none';
    }

    x = $('iframe1');
    if (null != x) {
        x.style.display = 'none';
    }
}

function menu1_item_clicked(e)
{
    Event.stop(e);
    hideMenus();
    Event.observe($('pulldown1'), 'click', show_menu_1);
}

function menu2_item_clicked(e)
{
    Event.stop(e);
    hideMenus();
}

function hide_rows(value)
{
    $('r1', 'r2', 'r3', 'r4').each(
        function(e)
        {
            e.style.display = (true == value) ? 'none' : '';
        }
    );
}

function onLoad()
{
    var cookie_ver = readCookie('myversion');
    if (app_version != cookie_ver) {
        var cks = [
            /^\s*car/,
            /^\s*count/, /^\s*entry/, /^\s*last/,
            /^\s*flight/
        ];

        var cookieArray = document.cookie.split(';');
        var len = cookieArray.length;
        for (var i=0; i<len; ++i) {
            var ck = cookieArray[i];
            var nameValPair = ck.split('=');
            var name = nameValPair[0];
            cks.each(
                function(re)
                {
                    if (re.test(name)) {
                        deleteCookie(name);
                    }
                }
            );
        }
    }

    writeCookie('myversion', app_version, false);

//    return '';

    if ($('pulldown1')) {
        Event.observe($('pulldown1'), 'click', show_menu_1);
        Event.observe($('img1'), 'click', show_menu_1);
    }

    if ($('pulldown2')) {
        Event.observe($('pulldown2'), 'click', show_menu_2);
        Event.observe($('img2'), 'click', show_menu_2);
    }

    Event.observe(document.documentElement, 'click', hideMenus);

    if ($('list1')) {
        if ('undefined' != typeof writeSearchHistory) {
    	   writeSearchHistory();
        }

        $A($('list1').getElementsByTagName('a')).each(
            function(node)
            {
                Event.observe(node, 'click', menu1_item_clicked);
            }
        );
    }

    if ($('list2')) {
        $A($('list2').getElementsByTagName('a')).each(
            function(node)
            {
                Event.observe(node, 'click', menu2_item_clicked);
            }
        );
    }


    if ($('pulldown3')) {
        $('pulldown3', 'img3').invoke('observe', 'click',
            function(e)
            {
                Event.stop(e);
                var m = $('list3');
                m.style.display = ('none' != m.style.display) ? 'none' : 'block';
            }
        );
    }

    if ($('list3')) {
        $('list3').select('a').invoke('observe', 'click',
            function(e)
            {
                // FIX BY ANDY:

                //Event.stop(e);

                // commented the above out as it was preventing the links from triggering successfully.

                hideMenus();
                $('pulldown3').update(Event.findElement(e, 'a').innerHTML);
            }
        )
    }

    //if (null != $('diff')) {
        //$('diff').checked = false;
    //}
}

Event.observe(window, 'load', onLoad);

if ('undefined' != typeof odl) {
    function OnDomLoadedHandler()
    {
        var city    = $('city');
        var airport = $('airport');
        var rtrip   = $('rtrip');
        var oneway  = $('oneway');
        var x       = $('where_span');

        if (null != city && null != airport && null != x) {
            if (0 != $$('.hotels').length) {
                //Hotels
                city.checked = true;
                x.firstChild.nodeValue = '(city)';
            }
            else {
                //Cars
                airport.checked = true;
                x.firstChild.nodeValue = '(airport)';
                $('where_span2').firstChild.nodeValue = '(airport)';
            }

            Event.observe(
                city,
                'click',
                function()
                {
                    $('where_span').firstChild.nodeValue = '(city)';
                    if ($('where_span2')) {
                        $('where_span2').firstChild.nodeValue = '(city)';
                    }
                }
            );

            Event.observe(
                airport,
                'click',
                function()
                {
                    $('where_span').firstChild.nodeValue = '(airport)';
                    if ($('where_span2')) {
                        $('where_span2').firstChild.nodeValue = '(airport)';
                    }
                }
            );
        }
        else if (null != oneway && null != rtrip) {
            function round_trip()
            {
                $($('rdate').parentNode).show();
                $($('return_label').parentNode).show();
                $($('rtime').parentNode).show();
            }

            function one_way()
            {
                $($('rdate').parentNode).hide();
                $($('return_label').parentNode).hide();
                $($('rtime').parentNode).hide();
            }

            rtrip.checked = true;
            round_trip();

            Event.observe(rtrip, 'click', round_trip);
            Event.observe(oneway, 'click', one_way);
        }
    }

    odl.register(OnDomLoadedHandler);
}

function clear_recent_searches()
{
	deleteSearches();

	// update the interface
    writeSearchHistory();

	if ( $('diff') != null && $('diff').checked ) // this will reset the different drop off lcoation for the cars
    {
    	hide_rows(true);
    }

    if ( $('oneway') != null && $('oneway').checked ) // this will reset the round trip portion of the flights
    {
    	// copied from above since the above code is not available on a global scope
    	$($('rdate').parentNode).show();
        $($('return_label').parentNode).show();
        $($('rtime').parentNode).show();
    }

    // and then reset the form
    document.searchForm.reset();
    //document.searchForm.rtrip.click();
}

function doNothing()
{
	return;
}

function verifyDayMonth(month,day,year) {

    // first we need to check to see that this day is in the future, and not in the past
    var currentDate = new Date();

    var givenDate = new Date();

    if (year < 100) {
        givenDate.setFullYear(Math.floor(currentDate.getFullYear() / 100) + year, month-1, day);
    }
    else {
        givenDate.setFullYear(year, month-1, day);
    }

    if (givenDate < currentDate) {
        return false;
    }

    var monthDays = new Array(12);

    // first we determine if it's a leap year (leap years have 29 days for february)
    if (year % 4 == 0) {
        // it's a leap year, february will have 29 days.
        monthDays[0] = 31; // jan
        monthDays[1] = 29; // feb
        monthDays[2] = 31; // mar
        monthDays[3] = 30; // apr
        monthDays[4] = 31; // may
        monthDays[5] = 30; // jun
        monthDays[6] = 31; // jul
        monthDays[7] = 31; // aug
        monthDays[8] = 30; // sep
        monthDays[9] = 31; // oct
        monthDays[10] = 30; // nov
        monthDays[11] = 31; // dec
    } else {
        // it's *not* a leap year, february will have 28 days.
        monthDays[0] = 31; // jan
        monthDays[1] = 28; // feb
        monthDays[2] = 31; // mar
        monthDays[3] = 30; // apr
        monthDays[4] = 31; // may
        monthDays[5] = 30; // jun
        monthDays[6] = 31; // jul
        monthDays[7] = 31; // aug
        monthDays[8] = 30; // sep
        monthDays[9] = 31; // oct
        monthDays[10] = 30; // nov
        monthDays[11] = 31; // dec
    }

    if (month < 1 || month > 12) {
        return false;
    }

    var daysInThisMonth = monthDays[month-1];

    if (day < 1 || day > daysInThisMonth) {
        return false;
    }

    return true;
}

function verifyDateField(s) {
    var Reg_fullyear = /([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{4})/;

    var Reg_halfyear = /([0-9]{1,2})\/([0-9]{1,2})\/([0-9]{2})/;

    var groups = Reg_fullyear.exec(s);

    if (groups != null) {
        return verifyDayMonth(groups[1], groups[2], groups[3]);
    } else {
        groups = Reg_halfyear.exec(s);
        if (groups != null) {
            return verifyDayMonth(groups[1], groups[2], groups[3]);
        } else {
            return false;
        }
    }

    return true;
}
