// ski_seatseeker_v1-1

// check date ranges in getFlights()


// globals...
var xmlhttp;
var xmlDoc;

var allRoutes = new Array(); // master array - holds the route arrays of flight objects
var allRoutesIndex = new Array(); // matches route number to airport code and number of flights




function whenLoaded() {
//alert("start");
    document.getElementById('outAirportSelector').value="TLS";
    newStart("TLS");
    window.setTimeout("doNext()",2000)
}



 function doNext()
 {
    document.getElementById('inAirportSelector').value="LGW";
    checkDepAirport("LGW");

 }

function destinationSelector() {
    var txt;
    txt = "<h4>Choose your destination:</h4>";
    txt += "<table><tr><td><select id=\'outAirportSelector\' name=\'destinationSelector\' onChange=\'newStart(this.value);\'>";
    txt += "<option value=\'\' selected=\"selected\">-- Destination Airport --<\/option>";
    txt += "<option value=\'VDB\'>Fagernes (VDB) - Norway<\/option>";     
    txt += "<option value=\'GVA\'>Geneva (GVA) - Switzerland<\/option>";
    txt += "<option value=\'GNB\'>Grenoble (GNB) - France<\/option>";
    txt += "<option value=\'INN\'>Innsbruck (INN) - Austria<\/option>";
    txt += "<option value=\'OSD\'>Ostersund (OSD) - Sweden<\/option>";
    txt += "<option value=\'SZG\'>Salzburg (SZG) - Austria<\/option>";
    txt += "<option value=\'SOF\'>Sofia (SOF) - Bulgaria<\/option>";
    txt += "<option value=\'TLS\'>Toulouse (TLS) - France<\/option>";
    txt += "<option value=\'TRN\'>Turin (TRN) - Italy<\/option>";
    txt += "<option value=\'VRN\'>Verona (VRN) - Italy<\/option>"    
    txt += "<\/select><\/tr><\/table>"

    document.getElementById("destinationSelector").innerHTML=txt;
    document.getElementById("destinationSelector").style.display="block";
}

function newStart(destAirport) {

    document.getElementById("airportSelector").innerHTML="";
    document.getElementById("airportSelector").style.display="none";
    document.getElementById("loader").innerHTML="";
    document.getElementById("loader").style.display="none";
    document.getElementById("outTable").innerHTML="";
    document.getElementById("outTable").style.display="none";
    document.getElementById("paxTable").innerHTML="";
    document.getElementById("paxTable").style.display="none";

    if (destAirport != '') {
        var d = new Date();
        var  cacheBuster = d.getTime();
        var url="/skylights/xml/FlightData_TOSRETURN_" + destAirport +  "_skidata.xml?cb=" + cacheBuster;
    //  var url="xml/skiData_RETURN_" + destAirport +  ".xml?cb=" + cacheBuster;
        loadXMLDoc(url)
    }
}

function pageProcesses() {
        buildArrays();
        buildSelector();
        //buildOutTable();
}

function buildArrays() {

    // this is bad... but need to clear down the master arrays...

        var trash1, trash2;
        var allRoutesMaxlength = allRoutes.length;
        var allRoutesIndexMaxlength = allRoutesIndex.length;

        for (tt=0; tt<allRoutesMaxlength; tt++) {trash1 = allRoutes.pop()};
        allRoutes[0] = "null";
        for (ss=0; ss<allRoutesIndexMaxlength; ss++) {trash2 = allRoutesIndex.pop()};
        allRoutesIndex[0] = "null";


    route = xmlDoc.getElementsByTagName("route");
    for (r=0; r<route.length; r++)
    {
        // master array - format is allroutes[route-index][flight-index]
        var stuffing = getFlights(r, route);
        allRoutes[r] = stuffing;
        // array for route number vs route airport code,  number of flights on route
        allRoutesIndex[r] = new Array(route[r].getAttribute("DepAiportCode"), route[r].getElementsByTagName("flight").length)
    }
}


function getFlights(q, route) {

    var x=route[q].getElementsByTagName("flight");
    var y=route[q].getElementsByTagName("prices");
    var temp = new Array();

    for (i=0;i<x.length;i++) {
        if ((y[i].getAttribute("AdultFare") !=0) && (x[i].getAttribute("OutFlightNumber").substring(0,3) == "TCX")) { // no zero price text & only TCX
        if( ((x[i].getAttribute("OutDepDateTime").replace(/-/g,"")).slice(0,8) >= 20101201) &&
            ((x[i].getAttribute("OutDepDateTime").replace(/-/g,"")).slice(0,8) <= 20110430) ) { // date test - between 15 dec and 15 apr
               
               temp[temp.length] = new FlightObj(x[i].getAttribute("OutDepDateTime"),
                                                    x[i].getAttribute("RetDepDateTime"),
                                                    x[i].getAttribute("URLLink"),
                                                    clean(y[i].getAttribute("AdultFare")),
                                                    x[i].getAttribute("OutFlightNumber") );
            }
        }
    }
    return temp;
}

function clean(cost) {
    cleanCost = cost.replace(/,/, "");
    return cleanCost
}

function buildSelector() {
//alert("start buildSelect");
    var txt="";
    txt += "<h4>Departing from:</h4>";
    txt += "<table><tr><td><select id=\'inAirportSelector\' name=\'inAirportSelector\' onChange=\'checkDepAirport(this.value);\'>";

    if (allRoutesIndex[0] != "null") {
        txt += "<option value=\'\'>--Departing Airport--<\/option>"
        for(q=0; q<allRoutesIndex.length; q++)
        {
            var depAirport = allRoutesIndex[q][0];
            txt += "<option value=\'" + depAirport +"\'>" + codeToAirport (depAirport) + "<\/option>"
        }
    }
    else {
        txt += "<option value=\'\'>Sorry, no flights available<\/option>"
    }

    txt += "<\/select><\/tr><\/table>"

    document.getElementById("airportSelector").innerHTML=txt;
    document.getElementById("airportSelector").style.display="block";
// alert("end buildSelect");   
}

function checkDepAirport(depAirport) {

if (depAirport != '') {
    buildOutTable(depAirport);
    }
}


function buildOutTable(depAirport) {
    var allRoutesIndexNum;
    var temp = new Array();

    // build Temp array
    if(allRoutes[getAllRoutesIndexFromAirportCode(depAirport)].length != "") {
        for(t=0; t<(allRoutes[getAllRoutesIndexFromAirportCode(depAirport)].length); t++)
        {
            temp.push(allRoutes[getAllRoutesIndexFromAirportCode(depAirport)][t]);
            //alert(allRoutes[getAllRoutesIndexFromAirportCode(buildWith)][t].flightNumber)
        }

        // clean and sort array depending on parameters passed...sorted by price, return 10 results

        // always return flights
            temp.sort(sortByadultFare);
            temp = temp.slice(removeZeroPrice(temp));
            temp = temp.slice(0,10);


            var txt = "";

        // build and output content

            txt += "<h4>Choose a return flight:</h4>";
            txt += "<table>";
            txt +="<tr ><td><\/td><td><span class=\"headerText\">Departs<\/span><\/td><td width=\"20px\"><span class=\"headerText\">Nts<\/span><\/td><td width=\"30px\"><span class=\"headerText\">From<\/span><\/td><\/tr>";

        for (i=0;i<temp.length;i++)
        {
            if (i%2) { //odd
                txt += "<tr>";
            }
            else {
                txt += "<tr class=\"stripe\">"
            }

            txt +=  "<td><input onClick=\'buildPaxTable()\' name=\'uRLLink\' type=\'radio\' value=\'" + temp[i].uRLLink + "\'\/><\/td>";


            // get data for row test
            /*
            var dateTxt = "<td>Out: " + temp[i].outDepDateTime.substring(8,10) + " " + dateToMonth(temp[i].outDepDateTime.substring(5,7)) + " " + "\'" + temp[i].outDepDateTime.substring(2,4) + "<br \/> Back: " + temp[i].retDepDateTime.substring(8,10) + " " + dateToMonth(temp[i].retDepDateTime.substring(5,7)) + " " + "\'" + temp[i].retDepDateTime.substring(2,4) +
            "<br \/> From: " + temp[i].uRLLink.substring(80,83) +
            "<br \/> To: " + temp[i].uRLLink.substring(208,211)+ "<\/td>";
            */

            // get data for row

            var outDay = temp[i].outDepDateTime.substring(8,10);
            var outMonth = temp[i].outDepDateTime.substring(5,7);
            var outYear = temp[i].outDepDateTime.substring(2,4);
            var retDay = temp[i].retDepDateTime.substring(8,10)
            var retMonth = temp[i].retDepDateTime.substring(5,7)
            var retYear = temp[i].retDepDateTime.substring(2,4)

            var dateTxt = "<td>" + outDay + " " + dateToMonth(outMonth) + " " + "\'" + outYear + "<\/td>";
            var nightsTxt ="<td>" + getDaysApart(outDay, outMonth, outYear, retDay, retMonth, retYear) + "<\/td>";

           var priceTxt = "<td><b>&pound;" + ((temp[i].adultFare).toFixed(2)) + "<\/b><\/td>";

            txt += dateTxt + nightsTxt + priceTxt ;
            txt += "<\/tr>" +"\n";
        }
        txt += "<\/table>";
        document.getElementById("outTable").innerHTML=txt;
        document.getElementById("outTable").style.display="block";
    }
}


function getDaysApart (outDay, outMonth, outYear, retDay, retMonth, retYear) {
        var retDate = new Date(0);
        var outDate = new Date(0);

        retDate.setYear("20"+retYear);
        retDate.setMonth(retMonth-1);
        retDate.setDate(retDay);

        outDate.setYear("20"+outYear);
        outDate.setMonth(outMonth-1);
        outDate.setDate(outDay);

        if ( outDate.getTime() < retDate.getTime() ) {
            difference = retDate.getTime() - outDate.getTime();
            difference = Math.round(difference/(1000*60*60*24));
        }
        return difference;
}



function removeZeroPrice (temp) {
        temp.sort(sortByadultFare);
        if (temp[0].adultFare==0) {
            var cutOff=0;
            for(i=1; i<temp.length; i++) {
                if ( (temp[i-1].adultFare==0) && (temp[i].adultFare!=0) ) {
                    cutOff=i;
                }
            }
        return cutOff;
        }
}


function getAllRoutesIndexFromAirportCode(airportCode) {
    var allRoutesIndexNum;
    for (i=0; i<allRoutesIndex.length; i++)
    {
        if (allRoutesIndex[i][0]==airportCode)
        {
            allRoutesIndexNum=i;
            break;
        }
    }
    return allRoutesIndexNum
}


function buildPaxTable() {
    var txt;
    txt = "<h4>How many travelling?<\/h4>";
    txt += "<table><tr><td colspan=\'2\'>Adults (18+ years)<\/td><td colspan=\'2\'><select id=\'pax_adult\' name=\'deals_ADULT\'><option value=\'1\'>1<\/option><option value=\'2\' selected=\'selected\'>2<\/option><option value=\'3\'>3<\/option><option value=\'4\'>4<\/option><option value=\'5\'>5<\/option><option value=\'6\'>6<\/option><option value=\'7\'>7<\/option><option value=\'8\'>8<\/option><option value=\'9\'>9<\/option><\/select><\/td><\/tr>";
    txt += "<tr><td colspan=\'2\'>Children (2-17 years)<\/td><td colspan=\'2\'><select id=\'pax_child\' name=\'deals_CHILD\'><option value=\'0\' selected=\'selected\'>0<\/option><option value=\'1\'>1<\/option><option value=\'2\' >2<\/option><option value=\'3\'>3<\/option><option value=\'4\'>4<\/option><option value=\'5\'>5<\/option><option value=\'6\'>6<\/option><option value=\'7\'>7<\/option><option value=\'8\'>8<\/option><option value=\'9\'>9<\/option><\/select><\/td><\/tr>";
    txt += "<tr><td colspan=\'2\'>Infants (0-23 months)<\/td><td colspan=\'2\'><select id=\'pax_infant\' name=\'deals_INFANT\'><option value=\'0\' selected=\'selected\'>0<\/option><option value=\'1\'>1<\/option><option value=\'2\'>2<\/option><option value=\'3\'>3<\/option><option value=\'4\'>4<\/option><option value=\'5\'>5<\/option><option value=\'6\'>6<\/option><option value=\'7\'>7<\/option><option value=\'8\'>8<\/option><option value=\'9\'>9<\/option><\/select><\/td><\/tr>";
    txt += "<tr><td colspan=\'3\'><button type=\'button\' onClick=\'process(this.form)\'><\/button><\/td><\/tr>";
    txt += "<\/table>";

    document.getElementById("paxTable").innerHTML=txt;
    document.getElementById("paxTable").style.display="block";
}


function process(form) {
    var deals_totalPax;
    var deals_adultPax = document.getElementById("pax_adult");
    var deals_childPax = document.getElementById("pax_child");
    var deals_infantPax = document.getElementById("pax_infant");
    var deals_url;

    var deals_root="http://www1.flythomascook.com/flytc/productSearch.vm?";


    var deals_searchType=               "&searchType=R";
    var deals_departureCode=            "&departureCode=" + getCheckedValue(document.getElementById("inputForm").uRLLink).substring(80,83);
    var deals_departureDay=         "&departureDay=" + getCheckedValue(document.getElementById("inputForm").uRLLink).substring(97,99);
    var deals_departureYearMonth=   "&departureYearMonth=" + getCheckedValue(document.getElementById("inputForm").uRLLink).substring(119,126);
    var deals_departureDateMinus=   "&departureDateMinus=" + 7;
    var deals_departureDatePlus=    "&departureDatePlus=" + 7;
    var deals_noAdults=                 "&noAdults=" + deals_adultPax.options[deals_adultPax.selectedIndex].value;
    var deals_noChildren=               "&noChildren=" + deals_childPax.options[deals_childPax.selectedIndex].value;
    var deals_destinationCode=      "&destinationCode=" + getCheckedValue(document.getElementById("inputForm").uRLLink).substring(208,211);
    var deals_returnDay=                "&returnDay=" + getCheckedValue(document.getElementById("inputForm").uRLLink).substring(222,224);
    var deals_returnYearMonth=      "&returnYearMonth=" + getCheckedValue(document.getElementById("inputForm").uRLLink).substring(241,248);;
    var deals_noInfants=                    "&noInfants=" + deals_infantPax.options[deals_infantPax.selectedIndex].value;

//http://www1.flythomascook.com/flytc/productSearch.vm?searchType=R&amp;departureCode=LGW&amp;departureDay=13&amp;departureYearMonth=2007-01&amp;departureDateMinus=7&amp;departureDatePlus=7&amp;noAdults=2&amp;noChildren=0&amp;destinationCode=SOF&amp;returnDay=20&amp;returnYearMonth=2007-01&amp;noInfants=0


    // pax check
    if (parseInt(deals_adultPax.options[deals_adultPax.selectedIndex].value) + parseInt(deals_childPax.options[deals_childPax.selectedIndex].value) + parseInt(deals_infantPax.options[deals_infantPax.selectedIndex].value) > 9) {
        alert("You are allowed a maximum of 9 passengers \n per booking online. If your party is larger \n than this, please call our reservation center.");
        return false;
    }

    if (parseInt(deals_infantPax.options[deals_infantPax.selectedIndex].value) > parseInt(deals_adultPax.options[deals_adultPax.selectedIndex].value)) {
        alert("Sorry, you cannot select more infants \n than the number of adults travelling.");
        return false;
    }

    //build url for deep link
    var deals_url = deals_root+deals_searchType+deals_departureCode+deals_departureDay+deals_departureYearMonth+deals_departureDateMinus+deals_departureDatePlus+deals_noAdults+deals_noChildren+deals_destinationCode+deals_returnDay+deals_returnYearMonth+deals_noInfants

    //build url for nedstat tracking
    //var nedstat_url = "http://uk.sitestat.com/tcook/flythomascook/s?flytc.ski-deals." +
    //                          "from-" + deals_departureCode.substring(15,18) +
    //                          ".to-" + deals_destinationCode.substring(17,20) +
    //                          ".date-" + deals_departureYearMonth.substring(20,24) + deals_departureYearMonth.substring(25,27) + deals_departureDay.substring(14,16) +
    //                          "&ns_type=clickout&ns_url=" ;

    //window.location.href = nedstat_url + deals_url;
    window.location.href = deals_url;
}

function getCheckedValue(radioObj) {
    if(!radioObj)
        return "";
    var radioLength = radioObj.length;
    if(radioLength == undefined)
        if(radioObj.checked)
            return radioObj.value;
        else
            return "";
    for(var i = 0; i < radioLength; i++) {
        if(radioObj[i].checked) {
            return radioObj[i].value;
        }
    }
    return "";
}


function plusDaysToDate(linkCode, plusDays) {
    var outYear, outMonth, outDay, inDate, inYear, inMonth, inDay, inDateStr;
    var plusDaysMS = (1000*60*60*24*plusDays);

    outYear = linkCode.substring(0,4);
    outMonth = linkCode.substring(4,6);
    outDay = linkCode.substring(6,8);

    outDate = new Date();
    inDate = new Date();

    outDate.setFullYear(outYear, outMonth-1, outDay);
    outMS = outDate.getTime();
    inDateMS = (outMS + plusDaysMS);

    inDate.setTime(inDateMS);

    inYear = String(inDate.getFullYear());
    inMonth= String(inDate.getMonth()+1);
    inDay= String(inDate.getDate());

    if (inMonth.length == 1) inMonth =  "0".concat (inMonth);
    if (inDay.length == 1) inDay = "0".concat (inDay);

    inDateStr = inYear.concat(inMonth, inDay);
    return inDateStr;
}


function codeToAirport (code) {
    var airport =  new Array();
    airport ["ABZ"] = "Aberdeen (ABZ)";
    airport ["BFS"] = "Belfast (BFS)";
    airport ["BHX"] = "Birmingham (BHX)";
    airport ["BOH"] = "Bournemouth (BOH)";
    airport ["BRS"] = "Bristol (BRS)";
    airport ["CWL"] = "Cardiff (CWL)";
    airport ["DSA"] = "Doncaster Robin Hood (DSA)";
    airport ["MME"] = "Durham Tees-Valley (MME)";
    airport ["EDI"] = "Edinburgh (EDI)";
    airport ["EXT"] = "Exeter (EXT)";
    airport ["GLA"] = "Glasgow (GLA)";
    airport ["HUY"] = "Humberside (HUY)";
    airport ["LBA"] = "Leeds/Bradford (LBA)";
    airport ["LPL"] = "Liverpool (LPL)";
    airport ["LGW"] = "London Gatwick (LGW)";
    airport ["LHR"] = "London Heathrow (LHR)";
    airport ["STN"] = "London Stansted (STN)";
    airport ["MAN"] = "Manchester (MAN)";
    airport ["NCL"] = "Newcastle (NCL)";
    airport ["NWI"] = "Norwich (NWI)"
    airport ["EMA"] = "Nottingham East Midlands (EMA)";

    airport["AGA"] = "Agadir";
    airport["ALC"] = "Alicante";
    airport["LEI"] = "Almeria";
    airport["AYT"] = "Antalya";
    airport["BJL"] = "Banjul";
    airport["BJV"] = "Bodrum";
    airport["BOJ"] = "Bourgas";
    airport["YYC"] = "Calgary";
    airport["CUN"] = "Cancun";
    airport["CTA"] = "Catania";
    airport["CMB"] = "Colombo";
    airport["CFU"] = "Corfu";
    airport["GOI"] = "Dabolim/Goa";
    airport["DLM"] = "Dalaman";
    airport["POP"] = "Dominican Republic/Puerto Plata";
    airport["VDB"] = "Fagernes";
    airport["FAO"] = "Faro";
    airport["SFB"] = "Florida/Sanford";
    airport["FUE"] = "Fuerteventura";
    airport["FNC"] = "Funchal/Madeira";
    airport["GVA"] = "Geneva";
    airport["GRO"] = "Gerona";
    airport["GNB"] = "Grenoble";
    airport["LPA"] = "Gran Canaria";
    airport["YHZ"] = "Halifax";
    airport["SKG"] = "Halkidiki";
    airport["HER"] = "Heraklion/Crete";
    airport["HRG"] = "Hurghada";
    airport["IBZ"] = "Ibiza";
    airport["INN"] = "Innsbruck";
    airport["ADB"] = "Izmir";
    airport["XRY"] = "Jerez";
    airport["KLX"] = "Kalamata";
    airport["KVA"] = "Kavala";
    airport["EFL"] = "Kefalonia";
    airport["KTT"] = "Kittila";
    airport["KGS"] = "Kos";
    airport["TRV"] = "Trivandrum";
    airport["ACE"] = "Lanzarote";
    airport["LCA"] = "Larnaca/Cyprus";
    airport["LXS"] = "Lemnos";
    airport["LXR"] = "Luxor";
    airport["LYS"] = "Lyon";
    airport["PMI"] = "Majorca/Palma";
    airport["AGP"] = "Malaga";
    airport["MLE"] = "Male";
    airport["MLA"] = "Malta";
    airport["RMF"] = "Marsa Alam";
    airport["MAH"] = "Menorca";
    airport["MBA"] = "Mombasa";
    airport["MIR"] = "Monastir/Tunisia";
    airport["MBJ"] = "Montego Bay";
    airport["YUL"] = "Montreal";
    airport["NAP"] = "Naples";
    airport["OSD"] = "Ostersund";
    airport["OSL"] = "Oslo";
    airport["YOW"] = "Ottawa";
    airport["PFO"] = "Paphos";
    airport["PDV"] = "Plovdiv";
    airport["PUJ"] = "Punta Cana";
    airport["PVK"] = "Preveza";
    airport["YQB"] = "Quebec";
    airport["REU"] = "Reus";
    airport["RHO"] = "Rhodes";
    airport["RVN"] = "Rovaniemi";
    airport["SSA"] = "Salvador Dois de Julho";
    airport["SZG"] = "Salzburg";
    airport["JTR"] = "Santorini";
    airport["SSH"] = "Sharm El Sheikh";
    airport["JSI"] = "Skiathos";
    airport["SOF"] = "Sofia";
    airport["SPU"] = "Split";
    airport["TFS"] = "Tenerife";
    airport["TLS"] = "Toulouse";
    airport["YYZ"] = "Toronto";
    airport["TRN"] = "Turin";
    airport["YVR"] = "Vancouver";
    airport["VAR"] = "Varna/Bulgaria";
    airport["VBS"] = "Brescia";
    airport["VCE"] = "Venice";
    airport["VRN"] = "Verona";
    airport["ZTH"] = "Zante";
    return airport[code];
}


function dateToMonth (month) {
    //var months =  new Array("January", "February", "March", "April", "May", "June", "July" , "August", "September", "October", "November", "December");
    var months =  new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul" , "Aug", "Sep", "Oct", "Nov", "Dec");
    return months[month-1];
}


function sortByadultFare(a, b) { // to change order: return ((x < y) ? 1 : ((x > y) ? -1 : 0));
    var x = a.adultFare;
    var y = b.adultFare;
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}



function FlightObj (outDepDateTime, retDepDateTime, uRLLink, adultFare, outFlightNumber) {
    this.outDepDateTime=outDepDateTime;
    this.retDepDateTime=retDepDateTime;
    this.uRLLink=uRLLink;
    this.adultFare=parseFloat(adultFare);
    this.outFlightNumber=outFlightNumber;
    //methods...
    this.showAllFlight=showAllFlight;
}



function showAllFlight(Array, location) {
var txt=""
for (i=0;i<Array.length;i++)
    {
        txt += Array[i].outDepDateTime + " " +
                Array[i].retDepDateTime + " " +
                Array[i].uRLLink + " " +
                Array[i].adultFare + "<br/>" ;
    }
    document.getElementById(location).innerHTML=txt;
    document.getElementById(location).style.display="block";
}



