var e_location_default_value;
var arrivalSelBox;
var selectedContext;

function setContext(sContext) {
    selectedContext = sContext;
}

function setTripType(tripType) {
    document.getElementById('TRIP_TYPE').value = tripType;
}
function getTripType() {
    return document.getElementById('TRIP_TYPE').value;
}

function setEmbeddedTransaction(embeddedTransaction) {
    document.getElementById('EMBEDDED_TRANSACTION').value = embeddedTransaction;
}

function fillArrivalAirports(departureAirport, arrivalAirport) {
    var airportFrom = document.getElementById(departureAirport);
    var airportTo = document.getElementById(arrivalAirport);

    airportTo.length = null;
    for (var i = 0; i < airportMappingArray[airportFrom.options[airportFrom.selectedIndex].value].length; i++) {
        airportTo.options[i] = new Option(airportArray[airportMappingArray[airportFrom.options[airportFrom.selectedIndex].value][i]], airportMappingArray[airportFrom.options[airportFrom.selectedIndex].value][i]);
    }
    airportTo.options[0].selected = true;
}

function setDisplay(pEleName, show) {
    var obElem = pElement(pEleName);
    if (obElem) {
        if (show)
            obElem.style.display = "";
        else
            obElem.style.display = "none";
    }
}

function pElement(pEleName) {
    var obElem;
    if (document.getElementById) {
        obElem = document.getElementById(pEleName);
    }
    else if (document.all) {
        obElem = document.all(pEleName);
    }
    else
        return null;
    return obElem;
}


function leapYear(year) {
    return (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) ;
}

function isDate(checkDate) {
    var date = checkDate.getDate();
    var month = checkDate.getMonth() + 1;
    var year = checkDate.getYear();
    var result = false
    var now = new Date();
    var thisYear = now.getYear();
    var thisMonth = now.getMonth() + 1;
    var thisDate = now.getDate();

    if (thisYear < 1900) thisYear += 1900; // Needed for dates thisYear - 1900

    // Primary check for validity.
    if (month > 0 && month < 13 && !isNaN(month) && !isNaN(date)) {
        if (month == 2) {
            if (date == 29 && leapYear(year)) {
                result = true;
            }
            else {
                result = ( date > 0 && date < 29 );
            }
        }
        else if (month == 4 || month == 6 || month == 9 || month == 11) {
            result = ( date > 0 && date < 31 );
        }
        else {
            result = ( date > 0 && date < 32 );
        }
    }
    return result;
}

function checkDates(departDate, arrivalDate, startDate, endDate, errorMsg, restrictDepartBooking) {
    var dToDay = new Date();
    var msgInvalidDeparture = errorMsg["invalidDepartureTime"];
    var msgInvalidReturning = errorMsg["invalidReturningTime"];
    var msgInvalidBookingPeriod = errorMsg["invalidBookingPeriod"];
    dToDay.setDate(dToDay.getDate() - 1);

    if (departDate == "") {
        alert(msgInvalidDeparture);
        return false;
    }
    else if (! isDate(departDate)) {
        alert(msgInvalidDeparture);
        return false;
    }
    else if (departDate < dToDay) {
        alert(msgInvalidDeparture);
        return false;
    }
    else if (arrivalDate != "") {
        if (! isDate(arrivalDate)) {
            alert(msgInvalidReturning);
            return false;
        }
        else if ((arrivalDate < departDate)) {
            alert(msgInvalidReturning);
            return false;
        }
    }
    if (restrictDepartBooking) {
        if (departDate > endDate) {
            alert(msgInvalidBookingPeriod);
            return false;
        }
    } else {
        if ((startDate != "") && (endDate != "")) {
            if ((departDate < startDate) || (arrivalDate > endDate) || (departDate > endDate)) {
                alert(msgInvalidBookingPeriod);
                return false;
            }
        }
    }
    return true;
}

function checkPax(arrOfSelect, errorMsg) {
    var numChildren = 0;
    var numAdults = 0;
    var numPass = 0;
    var numInfants = 0;
    var maxPass = 9;
    var msgMaxPassangers = errorMsg["maxNumberOfPassangers"];
    var msgMaxInfants = errorMsg["maxNumberOfInfants"];
    var msgLeastOnePassanger = errorMsg["atLeastOnePassanger"];
    var msgLeastOneAdult = errorMsg["atLeastOneAdult"];

    for (var i = 0; i < arrOfSelect.length; i++) {
        var selectName = document.getElementById(arrOfSelect[i]);
        if (selectName.name == "INF") {
            numInfants = parseInt(selectName.options[selectName.selectedIndex].value);
        }
        else {
            numPass += parseInt(selectName.options[selectName.selectedIndex].value);
            if (selectName.name == "CHD") {
                numChildren = parseInt(selectName.options[selectName.selectedIndex].value);
            }
            else {
                numAdults += parseInt(selectName.options[selectName.selectedIndex].value);
            }
        }
    }

    //  TODO this is for gift certificate
    //   document.form.PAX_COUNT.value = (numInfants+numPass);

    if (numPass > maxPass) {
        alert(msgMaxPassangers);
        return false;
    }
    else if (numInfants > numAdults) {
        alert(msgMaxInfants);
        return false;
    }
    else if (numPass == 0) {
        alert(msgLeastOnePassanger);
        return false;
    }
    else if (numAdults == 0 && numChildren > 0) {
        alert(msgLeastOneAdult);
        return false;
    }
    else {
        clearPax();
        var paxCounter = 1;
        for (var it = 0; it < arrOfSelect.length; it++) {
            var selectName = document.getElementById(arrOfSelect[it]);
            if (arrOfSelect[it] != "INF") {
                for (j = 0; j < parseInt(selectName.options[selectName.selectedIndex].value); j++) {
                    document.getElementById('TRAVELLER_TYPE_' + paxCounter++).value = arrOfSelect[it];
                }
            }
        }
        for (var i = 1; i <= numInfants; i++) {
            document.getElementById('HAS_INFANT_' + i).value = 'TRUE';
        }
    }
    return true;
}

function clearPax() {
    for (var i = 1; i < 10; i++) {
        document.getElementById('HAS_INFANT_' + i).value = 'FALSE';
    }
    for (var i = 1; i < 10; i++) {
        document.getElementById('TRAVELLER_TYPE_' + i).value = '';
    }

}
function getDate(strDate) {
    var returnDate = '';
    if ((strDate != '') && (strDate.indexOf("dd") == -1)) {
        var arr = strDate.split(".");
        if (arr.length == 0) {
            arr = strDate.split("/");
        }
        if (arr.length == 3) {
            returnDate = new Date(arr[2], (arr[1] - 1), arr[0]);
        }
    }
    return returnDate;
}

function getDate(strDate, locale) {
    var returnDate = '';
    if ((strDate != '') && (strDate.indexOf("dd") == -1)) {
        var arr = strDate.split(".");
        if (arr.length < 3) {
            arr = strDate.split("/");
        }
        if (arr.length == 3) {
            if ('en_US' == locale) {
                //  MM/DD/YYYY
                returnDate = new Date(arr[2], (arr[0] - 1), arr[1]);
            }
            else {
                // DD.MM.YYYY
                returnDate = new Date(arr[2], (arr[1] - 1), arr[0]);
            }
        }
    }
    return returnDate;
}

function getAmadeusFormattedDate(date) {
    var amadeusDateStr = '';
    amadeusDateStr = date.getFullYear();

    if ((date.getMonth() + 1) < 10) {
        amadeusDateStr += '0';
    }
    amadeusDateStr += '' + (date.getMonth() + 1);
    if (date.getDate() < 10) {
        amadeusDateStr += '0';
    }
    amadeusDateStr += '' + date.getDate();
    amadeusDateStr += '0000'

    return amadeusDateStr;
}

function setSelected(selectBoxId, val) {
    if (document.getElementById(selectBoxId) != null) {
        select = document.getElementById(selectBoxId);
        if (select.tagName == 'SELECT') {
            for (var i = 0; i < select.options.length; i++) {
                if (select.options[i].value == val)
                    select.options[i].selected = true;
            }
            /*Need to do this to get proper arrival airports*/
            if (selectBoxId == 'B_LOCATION_1') {
                getArrivalAirports('B_LOCATION_1', 'E_LOCATION_1', 0, selectedContext);
            }
            else if (selectBoxId == 'E_LOCATION_1') {
                e_location_default_value = val;
                /*used because sometimes ajax is slow*/
            }
        }
        else if (select.tagName == 'INPUT') {
            if (val != null) {
                if (select.type == 'checkbox') {
                    select.checked = eval(val);
                }
                else if (select.type == 'radio') {
                    select.checked = eval(val);
                }
                else {
                    /*unescape for date params on com site (mm/dd/yyyy) containing escape car %2F=/ */
                    select.value = unescape(val);
                }

            }
        }
    }
}

function clearElement(elem) {
    document.getElementById(elem).value = '';
}

function loadList(data) {
    DWRUtil.removeAllOptions(arrivalSelBox);
    DWRUtil.addOptions(arrivalSelBox, data);
    if (e_location_default_value != '') {
        setSelected('E_LOCATION_1', e_location_default_value);
        e_location_default_value = '';
    }
}
/*ajax check for service fee*/
function getContextBasedServiceFee(departureAirport, arrivalAirport, soGl, arrOfSelect, context) {
    var paxArr = new Array();
    var paxCount = new Array();
    var count = 0;

    for (var i = 0; i < arrOfSelect.length; i++) {
        var selectName = document.getElementById(arrOfSelect[i]);
        var nrOfPax = parseInt(selectName.options[selectName.selectedIndex].value);
        if (nrOfPax > 0) {
            paxArr[count] = selectName.name;
            paxCount[count] = nrOfPax;
            count++;
        }
    }
    seleroAmadeusManager.getContextBasedServiceFee(departureAirport, arrivalAirport, soGl, paxArr, paxCount, context, loadServiceFeeXML);

}
function getServiceFeeForSearch(departureAirport, arrivalAirport, soGl) {
    seleroAmadeusManager.getServiceFeeForSearch(departureAirport, arrivalAirport, soGl, loadServiceFeeXML);
}

/*load data from ajax service fee check*/
function loadServiceFeeXML(data) {
    DWRUtil.setValue("SO_SITE_PROMPT_FEE", data.promptFee);
    DWRUtil.setValue("SO_LANG_SERVICE_FEE_CHARGE", data.serviceFeeCharge);
    document.getElementById('SO_GL').value = data.soGl;
    /*Code for Google Analytics - Check if Google tags are included on the page*/
    if (typeof __utmLinkPost != 'undefined') {
        /*Call utmLinkPost to transfer web analytics variables between icelandair web and booking engine*/
        document.airBookingForm.value = __utmLinkPost(document.airBookingForm);
    }    
    document.airBookingForm.submit();
}
function getArrivalAirports(departureDropDown, arrivalDropDown, ordernumber, context) {
    DWREngine.setErrorHandler(null);
    arrivalSelBox = arrivalDropDown;
    var firstSelected = document.getElementById(departureDropDown).value;
    seleroAmadeusManager.getArrivalAirports(firstSelected, context, document.getElementById("locale").value, ordernumber, loadList);
}
function getFormattedDate(date) {
    return date.getDate() + '.' + (date.getMonth() + 1) + '.' + date.getFullYear()
}
function checkForServiceFee(serviceFeeEnabled, contextBased, paxArr, context) {
    if (serviceFeeEnabled) {
        if (!contextBased) {
            if (document.getElementById('E_LOCATION_1')) {
                getServiceFeeForSearch(document.getElementById('B_LOCATION_1').value, document.getElementById('E_LOCATION_1').value, document.getElementById('SO_GL').value);
            }
            else {
                getServiceFeeForSearch(document.getElementById('B_LOCATION_1').value, '', document.getElementById('SO_GL').value);
            }
        } else {
            getContextBasedServiceFee(document.getElementById('B_LOCATION_1').value, document.getElementById('E_LOCATION_1').value, document.getElementById('SO_GL').value, paxArr, context)
        }
    } else {
        /*Code for Google Analytics - Check if Google tags are included on the page*/
        if (typeof __utmLinkPost != 'undefined') {
            /*Call utmLinkPost to transfer web analytics variables between icelandair web and booking engine*/
            document.airBookingForm.value = __utmLinkPost(document.airBookingForm);
        }        
        document.airBookingForm.submit();         
    }
}
/*loads settings if owd airport route*/
function isOwdAirportRouting(data, oneWayTripType, embeddedTransFlightSchedule) {
    var dDate = getDate(document.getElementById('departDate').value, document.getElementById('locale').value);
    var toDay = new Date();
    toDay.setDate(toDay.getDate() + 3);
    var range = '7';
    if (dDate < toDay) {
        range = '3';
    }
    if (getTripType() == oneWayTripType) {
        if (data.fareFamily != null) {
            setValue('COMMERCIAL_FARE_FAMILY_1', data.fareFamily.fareFamily);
            setValue('PRICING_TYPE', 'O');
            setValue('DATE_RANGE_VALUE_1', range);
            setValue('DATE_RANGE_VALUE_2', range);
        } else {
            setEmbeddedTransaction(embeddedTransFlightSchedule);
        }
    } else {/*round trip*/
        if (data.owdEnabled) {
            setValue('COMMERCIAL_FARE_FAMILY_1', data.fareFamily.fareFamily);
            setValue('PRICING_TYPE', 'O');
            setValue('DATE_RANGE_VALUE_1', range);
            setValue('DATE_RANGE_VALUE_2', range);
        } else if (data.fareFamily != null) {
            setValue('COMMERCIAL_FARE_FAMILY_1', data.fareFamily.fareFamily);
        }
    }
}
/*checks if input or selecbox before setting a value*/
function setValue(elemId, elemValue) {
    elem = document.getElementById(elemId);
    if(elem != null){
        if (elem.tagName == 'SELECT') {
            elem.options[elem.selectedIndex].value = elemValue;
        } else if (elem.tagName == 'INPUT') {
            elem.value = elemValue;
        }
    }
}