// JavaScript Document

/**
 * Used to parse the city option value and get the city code.
 * @param val city option value
 */
function parseCityCode( val )
{
    if( !(val == "" || val.indexOf('_ @') > -1 || val.indexOf('_-@') > -1) )
    {
        var start = val.indexOf('_', 0);
        var end = val.indexOf('@', start);
        return val.substring(start + 1, end);
    }
    else
    {
        return "";
    }
}

/**
 * Used to load the current date for the date dropdowns in the search panel.
 */
function setOnloadDate()
{
    var dt = new Date();
    document.getElementById('checkInDate').value = dateToStringByFormat(dt, "DD/MM/YYY");
    ShowDepartDate();
}

/**
 * Used to set the departure date in the date drop downs, in the search panel.
 */
function ShowDepartDate()
{
    doChangeDateDropDown('checkInDate', 'date_Day', 'date_Month', 'date_Year');
    var checkinDate = document.getElementById('checkInDate').value;
    var nights = document.getElementById('noNights').value.split(',')[0];
    var dt = getDate(checkinDate, nights);
    dt = dateToString(dt);
    document.getElementById('checkoutDate').value = dt;
    ShowReturnDate();
}

/**
 * Used to set the return date in the date drop downs, in the search panel.
 */
function ShowReturnDate()
{
    doChangeDateDropDown('checkoutDate', 'return_date_Day', 'return_date_Month', 'return_date_Year');
    setNumberofNights();
}

/**
 * Used to change the date dropdowns.
 * @param dateField Field containing the date in the format of DD/MM/YYYY to be used to change the date drop downs.
 * @param dateDrop Id of the date drop down element.
 * @param monthDrop Id of the month dropdwon element.
 * @param yearDrop Id of the year dropdown element.
 */
function doChangeDateDropDown( dateField, dateDrop, monthDrop, yearDrop )
{
    var date = document.getElementById(dateField).value;
    var dt = getDate(date, 0);
    document.getElementById(dateDrop).selectedIndex = dt.getDate() - 1;
    document.getElementById(monthDrop).selectedIndex = (dt.getMonth() );
    var year = dt.getFullYear();
    var yearDropDwn = document.getElementById(yearDrop);
    //removeAllOptions(yearDropDwn);
    var options = yearDropDwn.options;
    var yearCode = year.toString().substring(2, 4);
    var lastVal = parseFloat(options[options.length - 1].value);
    if( lastVal < parseFloat(yearCode) )
    {
        var gap = parseFloat(yearCode) - lastVal;
        for( var x = 0; x < gap; x++ )
        {
            lastVal++;
            var temp = lastVal;
            if( lastVal.toString().length == 1 )
            {
                temp = '0' + lastVal.toString();
            }

            //only for 2000's
            temp = '20' + lastVal;
            yearDropDwn.options[options.length] = new Option(temp, temp.substring(2, 4));
        }
    }
    options = yearDropDwn.options;
    for( var x = 0; x < options.length; x++ )
    {
        if( options[x].value.indexOf(yearCode) > -1 )
        {
            yearDropDwn.selectedIndex = x;
        }
    }
}

/**
 * Used to do the date validation when a date is changed. If the date gap is greater than 30 days, the date is automatically
 * set to the date of checkin date plus + 30.
 * @param checkin True if the changing date is checkin date and false otherwise.
 */
function changeDate( checkin )
{
    var date, month, year;
    if( checkin )
    {
        dateValidateChecikn();
        ShowDepartDate();
    }
    else
    {
        date = document.getElementById('return_date_Day').value;
        month = document.getElementById('return_date_Month').value;
        year = "20" + document.getElementById('return_date_Year').value;

        dateValidateReturn(date, month, year);
        ShowReturnDate();
    }
    setNumberofNights();
}

/**
 * Used to validate the return dates
 * @param date date
 * @param month month starting from 1 - 12
 * @param year year 
 */
function dateValidateReturn( date, month, year )
{
    var nights = document.getElementById('noNights').value.split(',')[0];

    var dt = getDateSeperate(date, month, year, 0);
    var checkinDate = document.getElementById('checkInDate').value;
    var now = getDate(checkinDate, nights);
    now = getDate(checkinDate, (parseFloat(nights) + 29));
    if( dt > now )
    {
        document.getElementById('checkoutDate').value = dateToString(now);
    }
    else
    {
        dt = dateToString(dt);
        document.getElementById('checkoutDate').value = dt;
    }
}

/**
 * Used to validate checkin date.
 */
function dateValidateChecikn()
{
    var date, month, year;

    date = document.getElementById('date_Day').value;
    month = document.getElementById('date_Month').value;
    year = "20" + document.getElementById('date_Year').value;
    var dt = getDateSeperate(date, month, year, 0);
    var now = new Date();
    dt = dateToString(dt);
    document.getElementById('checkInDate').value = dt;
}

/**
 * Used to get the date object by the given date plus given nights
 * @param currentDate Date string in the format DD/MM/YYY
 * @param nights Number of nights.
 */
function getDate( currentDate, nights )
{
    var dt = new Date();
    dt.setFullYear(currentDate.substring(6, 10), currentDate.substring(3, 5) - 1, (parseFloat(currentDate.substring(0, 2)) + parseFloat(nights)));
    return dt;
}

/**
 * Used to get the date object with the given parametsres.
 * @param date date
 * @param month month starting from 1 - 12
 * @param year year
 * @param nights
 */
function getDateSeperate( date, month, year, nights )
{
    var dt = new Date();
    dt.setFullYear(parseFloat(year), parseFloat(month) - 1, parseFloat(date) + parseFloat(nights));
    return dt;
}


function dateToString( dt )
{
    return dateToStringByFormat(dt, "DD/MM/YYY");
}

function setNumberofNights()
{
    var checkin = document.getElementById('checkInDate').value;
    checkin = getDate(checkin, 0);
    var returnDate = document.getElementById('checkoutDate').value;
    returnDate = getDate(returnDate, 0);
    if( getDateDiff(returnDate, checkin) <= 30 )
    {
        document.getElementById('noNights').selectedIndex = (getDateDiff(returnDate, checkin) - 1);
    }
}

function getDateDiff( d1, d2 )
{
    d1 = d1.getTime();
    d2 = d2.getTime();
    //Math.round to fix the daylight saving.
    return Math.round(((d1 - d2) / (1000 * 60 * 60 * 24)));
}

function setFinalData()
{
    document.getElementById('Flight1_Date').value = document.getElementById('checkInDate').value;
    document.getElementById('CinDateMonthFirst').value = dateToStringByFormat(getDate(document.getElementById('checkInDate').value, 0), "MM/DD/YYY");
    document.getElementById('Flight2_Date').value = document.getElementById('checkoutDate').value;
    document.getElementById('CoutDateMonthFirst').value = dateToStringByFormat(getDate(document.getElementById('checkoutDate').value, 0), "MM/DD/YYY");
    document.getElementById('F1mm').value = document.getElementById('date_Month').value;
    document.getElementById('F1yy').value = '20' + document.getElementById('date_Year').value;
}

function dateToStringByFormat( dt, format )
{
    var date;
    if( format.indexOf("MM/DD/YYY") > -1 )
    {
        date = ((dt.getMonth() + 1) < 10 ? ("0" + (dt.getMonth() + 1)) : (dt.getMonth() + 1) ) + "/" + (dt.getDate() <= 9 ? ("0" + dt.getDate()) : dt.getDate()) + "/" + dt.getFullYear();
    }
    else if( format.indexOf("DD/MM/YYY") > -1 )
    {
        date = (dt.getDate() <= 9 ? ("0" + dt.getDate()) : dt.getDate()) + "/" + ((dt.getMonth() + 1) < 10 ? ("0" + (dt.getMonth() + 1)) : (dt.getMonth() + 1) ) + "/" + dt.getFullYear();
    }
    return date;
}

/**
 * Used to select the destinations cities depending on the given departure city value.
 * @param val value of the selected deprture option, in format of "Aberdeen_ABZ@GB"
 * @param id Id of the destination select element
 */
function selectDestinationCity( val, id )
{
    var mapWiseCountry = new Object();
    var cityCode = parseCityCode(val);
    var obj = document.getElementById(id);
    removeAllDOM(obj);
    var index = 0;
    if( cityCode.length > 0 )
    {
        //parse the DestinationJSON file.
        var destinations = eval('DestinationJSON');

        if( destinations )
        {
            for( var des in destinations )
            {
                var destination = destinations[des];
                var departures = destination.dep;

                if( departures )
                {
                    var depCities = departures.split(",");
                    if( depCities )
                    {
                        for( var cityIndex = 0; cityIndex < depCities.length; cityIndex++ )
                        {
                            var city = depCities[cityIndex];

                            //if the departure should be selected
                            if( city.indexOf(cityCode) > -1 )
                            {
                                //group the destinations country wise
                                var country = destination.country;
                                var countryArr;
                                if( mapWiseCountry[country] )
                                {
                                    countryArr = mapWiseCountry[country];
                                }
                                else
                                {
                                    countryArr = new Array();
                                }
                                var cityObj = new Object();
                                cityObj['code'] = des;
                                cityObj['obj'] = destination;
                                countryArr.push(cityObj);
                                mapWiseCountry[country] = countryArr;
                                break;
                            }
                        }
                    }
                }
            }
            for( var key in mapWiseCountry )
            {
                var countryArr = mapWiseCountry[key];
                countryArr = countryArr.sort(sortCities);
                var optionGp;
                for( var countryIndex = 0; countryIndex < countryArr.length; countryIndex++ )
                {
                    var cityObj = countryArr[countryIndex];
                    var destination = cityObj['obj'];
                    var des = cityObj['code'];

                    if( countryIndex == 0 )
                    {
                        var country = destination.country;
                        optionGp = document.createElement('optgroup');
                        optionGp.label = country;
                    }

                    //option value format : Algarve_ALGV@AIRPORT
                    var optionVal = destination.name + "_" + des + "@" + destination.airport;
                    var oOption = document.createElement('option');
                    oOption.value = optionVal;
                    oOption.innerHTML = destination.name;
                    optionGp.appendChild(oOption);
                    if( (countryIndex + 1) == countryArr.length )
                    {
                        obj.appendChild(optionGp);
                    }
                }
            }
            obj.selectedIndex = 0;
            setSelectedCity(obj.value);
        }
    }
    else
    {
        obj[0] = new Option("Select City", "");
    }
}

function sortCities(a, b)
{
    var destinationA = a['obj'];
    var destinationB = b['obj'];
    var nameA = destinationA.name;
    var nameB = destinationB.name;

    if(nameA > nameB)
    {
        return 1;
    }
    else if(nameA < nameB)
    {
        return -1;
    }
    else
    {
        return 0;
    }
}

/**
 * Used to remove all the child elements from a parent node
 * @param obj parent element
 */
function removeAllDOM( obj )
{
    var children = obj.childNodes;
	var len = children.length;
    for( var x = 0; x < len; x++ )
    {
        obj.removeChild(children[0]);
    }
}

/**
 * Used to remove all the options from a Select element
 * @param obj Select element
 */
function removeAllOptions( obj )
{
    var length = obj.length;
    for( var x = 0; x < length; x++ )
    {
        obj.remove(0);
    }
}

/**
 * Used to get the size of an any kind of object
 * @param obj The object, of which the size is needed.
 */
Object.size = function( obj )
{
    var size = 0, key;
    for( key in obj )
    {
        if( obj.hasOwnProperty(key) )
        {
            size++;
        }
    }
    return size;
};


function validateDateForSubmit()
{
    if (!document.getElementById('noNights').value)
    {
        alert("Please select valid dates");
        return false;
    }
    var checkin = getDate(document.getElementById('checkInDate').value, document.getElementById('noNights').value);
    var checkout = getDate(document.getElementById('checkoutDate').value, 0);
    if( checkout > checkin )
    {
        checkin = getDate(document.getElementById('checkInDate').value, 30);
        if (checkout > checkin)
        {
            alert("Date range should be limited to 30 days");
            return false;    
        }
    }
    else if (checkin > checkout)
    {
        alert("Please enter a valid return date");
        return false;
    }
    return true;
}

function selectOption( value, id )
{
    var obj = document.getElementById(id);
    var options = obj.length;
    for( var x = 0; x < options; x++ )
    {
        if( obj[x].value.indexOf(value) > -1 )
        {
            obj.selectedIndex = x;
            break;
        }
    }
}