/**
 * $Id$
 *
 * argument list: [from, to], outbound, inbound, priceGroup
 *
 * <li>if <param>from</param> is specified <param>to</param> most also
 *     be specified and vice versa, both values most be a 3 letter airport code
 *     like CPH or BCN
 *
 * <li>outbound is the outbound departure date and is specified as ddMMyyyy
 *
 * <li>inbound is the inbound departure date and is specified as ddMMyyyy
 *
 * <li>priceGroup sets the default price group and is specified by the price
 *     group id
 *
 * <li>priceValuta sets the default valuta and is specified by a 3 letter
 *     currency code like DKK or EUR
 *
 *
 */
function validateForm() {
    var ok = true;
    var fromAirport = document.forms["booking"].elements["fromAirport"];
    var toAirport = document.forms["booking"].elements["toAirport"];
    var fromAirportCode = fromAirport.options[fromAirport.selectedIndex].value;
    var toAirportCode = toAirport.options[toAirport.selectedIndex].value;
    if (fromAirportCode == "" || toAirportCode == "") {
    	alert(err_no_airports);
    	ok = false;
    }
    if (pas.getNumPassengers() <= 0) {
    	alert(err_no_passengers);
    	ok = false;
    }
    return ok;
}

function getSearchObj() {
    var o = {};
    var a = document.location.search.split('&');
    if (a.length>0) {
        a[0] = a[0].substr(1);
    }
    for (var i=0;i<a.length;i++) {
        var a2 = a[i].split('=');
        o[a2[0]] = a2[1];
    }
    return o;
}

function submitForm() {
    if (validateForm()) {
    	if (outboundCalendar != null && inboundCalendar != null) {
    		setDates(outboundCalendar.getDate(), inboundCalendar.getDate());
    	}
        var path = location.pathname.substr(0, location.pathname.lastIndexOf('/') + 1);
        var dExpire = new Date(new Date().getTime() + (60000 * 15));
        var form = new FormSerializer('booking');
        Cookie.set(INSTALLATION_ID + '_booking1', form.serialize(), dExpire, path);

        document.forms['booking'].submit();
    }
}


function setDates(outboundCalendarDate, inboundCalendarDate) {

	document.getElementById("outboundDay").value = outboundCalendarDate.getDate();
    document.getElementById("outboundMonth").value = outboundCalendarDate.getMonth();
    document.getElementById("outboundYear").value = outboundCalendarDate.getFullYear();

    document.getElementById("inboundDay").value = inboundCalendarDate.getDate();
    document.getElementById("inboundMonth").value = inboundCalendarDate.getMonth();
    document.getElementById("inboundYear").value = inboundCalendarDate.getFullYear();

    return true;
}


/** Sets the from and to airport selections to the
 *  specified values.
 *
 *  @param from a 3 letter airport code or an airport id number
 *  @param to   a 3 letter airport code or an airport id number
 */

function initRoutes(from, to) {
   if (typeof(from) == "number") {
        routeChooser.setSelectedId(from, to);
    } else {
        routeChooser.setSelectedCode(from, to);
    }
}


/** Sets the outbound and inbound date selection to the specified dates
 *
 *  @param outbound a string with the format of ddMMyyyy
 *  @param inbound  a string with the format of ddMMyyyy
 */

function initDates(outbound, inbound) {
    var currentDate;
    var maximumDate;
    var outboundDate;
    var inboundDate;

	currentDate = new Date();
    maximumDate = new Date(currentDate.getFullYear() + 1, currentDate.getMonth(), currentDate.getDate());
    maximumInboundDate = new Date(currentDate.getFullYear() + 1, currentDate.getMonth() + 1, currentDate.getDate());

    if (outbound == null) {
        outboundDate = currentDate;
    } else {
        outboundDate = outbound;
    }

    if (inbound == null) {
        inboundDate = outboundDate;
    } else {
        inboundDate = inbound;
    }

    if (null != outboundCalendar) {
	    if (outboundDate.getTime() > currentDate.getTime()) {
	        outboundCalendar.setDate(outboundDate);
	    } else {
	        outboundCalendar.setDate(currentDate);
	    }
	    outboundCalendar.setMaxDate(maximumDate);
	
	    if (inboundDate.getTime() > currentDate.getTime()) {
	        inboundCalendar.setDate(inboundDate);
	    } else {
	        inboundCalendar.setDate(currentDate);
	    }
	    inboundCalendar.setMaxDate(maximumInboundDate);
    } else {
    	setDates(outboundDate, inboundDate);
    }
}


/** Sets the ticket type selection
 *
 *  @param ticketType if the string equals 'oneway' oneway will be set
 *  as default otherwise return.
 */

function initTicketType(ticketType) {
    var ticketSelector;

    ticketSelector = document.getElementById("tickettype");
    if (ticketType == "oneway") {
        ticketTypeChooser.setSelected(ticketTypeChooser.getOneWayElement());
        routeChooser.onFromChanged();
    } else {
        ticketTypeChooser.setSelected(ticketTypeChooser.getRoundTripElement());
        routeChooser.onFromChanged();
    }
}


/** Sets the price group selection to the pricegroup with the specified name
 *
 *  @param priceGroupId an number specifying the pricegroup id
 */

function initPriceGroup(priceGroupId) {
    var priceGroupSelector;

    priceGroupSelector = document.getElementById("priceGroup");

    if (priceGroupSelector.options == null) {
        priceGroupSelector.value = priceGroupId;
    } else {
        for (var i = 0; i < priceGroupSelector.options.length; i++) {

            if (priceGroupSelector.options[i].value == priceGroupId) {
                priceGroupSelector.options[i].selected = true;
                return;
            }
        }
    }
}


/** Sets the valuta selection to the specified valuta
 *
 *  @param priceValutaId a 3 letter valuta code
 */

function initPriceValuta(priceValutaId) {
    var priceValutaSelector;

    priceValutaSelector = document.getElementById("priceValuta");

    for (var i = 0; i < priceValutaSelector.options.length; i++) {
        if (priceValutaSelector.options[i].value == priceValutaId) {
            priceValutaSelector.options[i].selected = true;
            return;
        }
    }
}

function initSearchPeriod(cookieData) {
    var searchPeriod = document.getElementById("search_period");
    if (cookieData != null && cookieData.search_period != null && searchPeriod != null) {
        for (var i = 0; i < searchPeriod.options.length; i++) {
            if (searchPeriod.options[i].value == cookieData.search_period) {
                searchPeriod.selectedIndex = i;
                break;
            }
        }
    }
}

function initPassengers(cookieData) {
    var items;
    var selector;

    for (items in cookieData) {
        if (items.substring(0, 11) == "personType_") {
            selector = document.getElementById(items);
            selector.value = cookieData[items];
            selector.onchange();
        }
    }
}

function init() {

    var oArgs;
    var cookieData;

    oArgs = getSearchObj();

    eval('cookieData = ' + Cookie.get(INSTALLATION_ID + '_booking1'));

    initSearchPeriod(cookieData);

    if (oArgs.outbound) {
        var outboundDate;
        var inboundDate;
        var year;
        var month;
        var date;

        year = parseInt(oArgs.outbound.substring(0,4),10);
        month = parseInt(oArgs.outbound.substring(4,6),10) -1;
        date = parseInt(oArgs.outbound.substring(6,8),10)

        date += oArgs.outboundDayOffset != null ? parseInt(oArgs.outboundDayOffset) : 0;

        outboundDate = new Date(year, month , date);
        inboundDate = outboundDate;

        initDates(outboundDate, inboundDate);
    } else if (cookieData != null && cookieData.outboundDay) {
        var outboundDate;
        var inboundDate;

        outboundDate = new Date(cookieData.outboundYear, cookieData.outboundMonth, cookieData.outboundDay);
        inboundDate = new Date(cookieData.inboundYear, cookieData.inboundMonth, cookieData.inboundDay);

        initDates(outboundDate, inboundDate);
    } else {
        initDates(new Date(), new Date());
    }

    if(cookieData != null && cookieData.tickettype) {
        initTicketType(cookieData.tickettype);
    } else {
        ticketTypeChooser.setSelected(ticketTypeChooser.getRoundTripElement());
        routeChooser.onFromChanged();
    }


    if (oArgs.priceGroup) {
        initPriceGroup(oArgs.priceGroup);

    } else if (cookieData != null && cookieData.priceGroup){
        initPriceGroup(cookieData.priceGroup);
    }


    if (oArgs.priceValuta) {
        initPriceValuta(oArgs.priceValuta);
    } else if (cookieData != null && cookieData.priceValuta){
        initPriceValuta(cookieData.priceValuta);
    }

    if(cookieData != null && cookieData.personType_1) {
        initPassengers(cookieData);
    }
    else {
        // If nothing is stored in cookie, adults is set to 1 (personType_1 is always adult)
        var selector = document.getElementById("personType_1");
        selector.value = 1;
        selector.onchange();
    }
}

var form;
var err_no_airports = "";
var err_no_passengers = "";

