// JavaScript / jQuery code for GTWS


$( function() { // Executes when the DOM is loaded
    //return;
    init();
    executeGenericFunction();
    executeTemplateFunction();
});

function executeGenericFunction() {
    $("#nojavascript").hide();
    
    $("input[name = loadstoredjourney]").hide();    // Stored journey
    
    // Stored journey dropdown
    $("#stored_journey")
        .bind('change',function(event) { lookupStoredJourneyDetails(event); });

    try { $("input[id ^= stop][id $= _search]").autocomplete(
        '/app/ajax/addressFastFind', {
        formatItem: formatItem,
        max: 30,
        width: 400
    }).result(processResult); } catch(e) {};

    $("input[name = cancel_booking]").click(function(event) { return(confirm("Cancel booking - are you sure?")); });
    
    if ($("#job_desp_instructions").length > 0) {
        $("#job_desp_instructions").textlimit('#counter',200);
    }

    try {
        $('#job_pickup_date_jqui')
            .datepicker({ 
                minDate: 0,
                maxDate: $('#gtwsjs_maxDate').attr("value"),
                numberOfMonths: parseInt($('#gtwsjs_numberOfMonths').attr("value")) ? parseInt($('#gtwsjs_numberOfMonths').attr("value")) : 1
            })
            .attr("readonly","readonly");
    } catch(e) {}
    
    try {
        $('#list_start_date,#list_end_date')
            .datepicker({
                changeMonth: true
                //dateFormat: 'dd/mm/yy'
            })
            .attr("readonly","readonly")
            .bind("change",function(event){ enforceDateRange(event.target.id,"list_start_date","list_end_date",61);
                                            enforceDateOrder(event.target.id,"list_start_date","list_end_date");
                                          });
    } catch(e) {};
}

function formatItem(row) {
    return row[1].substring(10);
};

function processPopulateStop(data) {
    stop = triggerID.replace("_search","");
    
    $("#" + stop + "_address_name").val(data.address_name);
    $("#" + stop + "_address1").val(data.address1);
    $("#" + stop + "_address2").val(data.address2);
    $("#" + stop + "_address3").val(data.address3);
    $("#" + stop + "_address4").val(data.address4);
    $("#" + stop + "_postcode").val(data.postcode);
    $("#" + stop + "_search").val('');
}

function processResult(event, row) {
    $.get($("#postcodeDetailLookupURI").html(), { postcoderef : row[0] }, processPopulateStop, 'json');
    triggerID = event.target.id;
};


// ===============================================================================================
//  Automatically call a function whose name is that of the template being shown
//  E.g., if the template being shown is "login.tt2", this will execute a "login()" function if one exists.
//  Can be used for 'onLoad' type processing, removing buttons because we've got JavaScript, setting up events, etc.  
// ===============================================================================================
function executeTemplateFunction() {    
    var templatePathname = $("#templateName").attr("title");                                                      // login/login.tt2

    if (typeof(templatePathname) != 'undefined' && templatePathname != '') {                           
        var templateFilename = templatePathname.lastIndexOf("/")+1;
        var templateName = templatePathname.substr(templateFilename, templatePathname.length - templateFilename); // login.tt2
        templateName = templateName.replace(".tt2","");                                                           // login
        if (templateName == "home") {
            templateName = "homeFunction";                                                                        // Avoid calling window.home()
        }
        if (templateName == "confirm") {
            templateName = "confirmFunction";                                                                     // Avoid calling confirm() (reserved word!)
        }
        var templateFunction = templateName + '()';                                                               // login()
        try      { eval(templateFunction); }                                                                      // Call it
        catch(e) { //alert(e + " when calling " + templateFunction)
                 };
    } else {} // Calling page has not provided an ID
}

// ===============================================================================================
// homeFunction - called when we find a 'home.tt2' template
// ===============================================================================================
function homeFunction() {
    //alert("Testing homeFunction");
}

// ===============================================================================================
// Init - always called
// ===============================================================================================
function init() {

    // Globals
    triggerID = '';
    msInOneDay = 1000*60*60*24; // Number of milliseconds in one day
    
    loadScrollPosition();
    
    try {
        $.datepicker
            .setDefaults({
                showButtonPanel: true,
                dateFormat: 'dd M yy',
                duration: 0,
                showOn: 'button',
                buttonImage: '/static/images/calendar.gif',
                buttonImageOnly: true,
                showAnim: 'fadeIn',
                hideIfNoPrevNext: true
            });
    }
    catch(e) {};
    
    try { activateToolTips(); } catch(e) {};
    
    // Show print dialogue on any page with input with id of "print" set to "yes"
    if($("#print").attr("value") == 'yes') {
        window.print();
    }
    
}

// ===============================================================================================
// ActivateToolTips
// ===============================================================================================
function activateToolTips() {
    
    // Set default options
    try{
        jQuery.bt.options.width = 400;
        jQuery.bt.options.shrinkToFit = true;
        jQuery.bt.options.positions = ['top'];
        jQuery.bt.options.fill = "rgba(244,225,216,.8)";
        jQuery.bt.options.strokeStyle = "#761409";
        jQuery.bt.options.cornerRadius = 10;
    }
    catch(e) {};

    // Activate tool tips for all elements with a title
    $('input[title],select[title]').bt();
    
}

// ===============================================================================================
// Login
// ===============================================================================================
function login() {
    $("#username").focus();
}

// ===============================================================================================
// Job
// ===============================================================================================
function job() {
    
    $("#mop").bind('change',function(event) {
        if ($("#mop").val() == 'A') {
            $("#matterNumberBlock").show();
            try {
                $("#jobTypeBlock").show();
            } catch(e) {};
        }
        else {
            $("#matterNumberBlock").hide();
            try {
                $("#jobTypeBlock").hide();
            } catch(e) {};
        }
     });
    
    $("#job_jobnumber_drop").bind('change',function(event) {
        $("#matterNumberNotValid").hide();
        $("#matter_number").val(
            $("#job_jobnumber_drop").val() == 0 ? '' : $("#job_jobnumber_drop").val()
         );
     });
    
    $("#matter_number").bind('keyup',function(event) {
        // Hide matter number error if it's changed
        $("#matterNumberNotValid").hide();
        
        // Set dropdown if there's a match
        var select = $("#job_jobnumber_drop")[0];
        select.selectedIndex = 0;
        for (var i = 0; i < select.length; i ++) {
            if (select.options[i].value == $("#matter_number").val()) {
                select.selectedIndex = i;
            }
        }
     });
    
    $("#matter_number").bind('click',function(event) {
        if(! $("#matter_number").val()) {
            $("#matterNumberNotValid").hide();
        }
     });
    
}

// ===============================================================================================
// Stops
// ===============================================================================================
function stops() {
    
    // Remove lookup buttons
    $("input[name *= addrsel]").remove();           // Predefined addresses
    $("input[id $= _dropselect]").remove();         // Premises
    
    // Predefined address dropdown
    $("select[id $= _addr]")
        .bind('change', function(event) { populateAddressFromPredefined(event); });
        
    // Postcode lookup - change input type to 'button' if we introduce this
    //$("input[name ^= stop][name $= _lookup]")
    //    .bind('click',function(event) { lookupPostcode(event); }); 
        
    // Premises dropdown
    $("select[id $= _postcodedrop]")
        .bind('change', function(event) { lookupPostcodeDetails(event) });
        
    // When postcode lookup button is clicked, store the page scroll position for use after refresh
    $("input[name $= _lookup]")
        .bind('click', function(event) { saveScrollPosition(event); });
}

//function lookupPostcode(event) {}

function lookupPostcodeDetails(event) {
    triggerID = event.target.id;
    $("#" + triggerID + "_container").hide();                       // Remove dropdown when premises are chosen
    $("#" + triggerID.replace("postcodedrop","loading")).show();    // Show animated 'loading' image
    $.getJSON("/app/ajax/postcodeDetailLookup",
                "postcoderef=" + $("#" + triggerID).attr("value"),
                populateAddressFromPremises);
}

function populateAddressFromPremises(address) {
    var stop = triggerID.replace("postcodedrop","");  // E.g. "stop1_"
    for (var field in address) {        
        $("#" + stop + field).val(address[field]);
    }
    $("#" + stop + "loading").hide();   // Hide animated 'loading' image
    setAddressNameLabel(stop,0);        // Set address label to the standard one
}

//function populateAddressFromPostcode(address) {}

function populateAddressFromPredefined(event) { // Process predefined address dropdown select
  
    if (!document.getElementById("stop1_address1")) {                   // Check we've got an address to populate
        return;
    }
    
    var triggerID = event.target.id;                                        // Which drop-down triggered this event?  e.g. "stop1_addr"
    var stop = triggerID.replace("addr","");                                // "stop1_"
  
    var addressRef = $("#" + triggerID)[0].value;                           // Get address reference from drop-down

    // List of address line fields hidden in the page within SPANs
    var addressFields = ['address_name','address1','address2','address3','address4','postcode','type_description','zone'];
  
    for(var field in addressFields) {                                       // Copy address lines from SPANS within hidden DIV
        var sourceField = $("#" + addressRef + "_" + addressFields[field]); // ID of hidden SPAN containing the address line we're intereted in
        var destField   = $("#" + stop + addressFields[field])[0];          // ID of displayed (or hidden) address line we're copying to
        try { destField.value = sourceField.text(); } catch(e) {};          // Copy
    }

    setAddressNameLabel(stop,addressRef);
}

function setAddressNameLabel(stop,addressRef) {
    // Set the Address Name label appropriately
    var typeDescription = $("#" + addressRef + "_" + "type_description").text();   // Determine the type description for this address ref
  
    // Clear all possible labels / inputs first
    var addressname = stop + "address_name_";
    try { $("#" + addressname + "label_flight_no")[0].style.display="none"; } catch(e) {}   // Label
    try { $("#" + stop + "label_flight_no")[0].style.display="none"; } catch(e) {}   // Label
    try { $("#" + addressname + "flight_no")[0].style.display="none"; } catch(e) {}         // Input
    try { $("#" + stop + "flight_no")[0].style.display="none"; } catch(e) {}         // Input
    try { $("#" + addressname + "label_flight_time")[0].style.display="none"; } catch(e) {} // Label
    try { $("#" + stop + "label_flight_time")[0].style.display="none"; } catch(e) {} // Label
    try { $("#" + addressname + "flight_time")[0].style.display="none"; } catch(e) {}       // Input
    try { $("#" + stop + "flight_time")[0].style.display="none"; } catch(e) {}       // Input
    try { $("#" + addressname + "notes_flightno")[0].style.display="none"; } catch(e) {}    // Label
    try { $("#" + addressname + "label_rail")[0].style.display="none";     } catch(e) {}    // Label
    try { $("#" + addressname + "label_standard")[0].style.display="none"; } catch(e) {}    // Label
    try { $("#" + addressname )[0].style.display="none"; } catch(e) {}                      // Input

    // Display the appropriate ones
    if (typeDescription.toUpperCase().search(/AIRPORT/) +1) {
        try { $("#" + addressname + "label_flight_no")[0].style.display="block"; } catch(e) {}
        try { $("#" + stop + "label_flight_no")[0].style.display="block"; } catch(e) {}
        try { $("#" + addressname + "notes_flightno")[0].style.display="block"; } catch(e) {}
        try { $("#" + addressname + "flight_no")[0].style.display="block"; } catch(e) {}    // Input
        try { $("#" + stop + "flight_no")[0].style.display="block"; } catch(e) {}    // Input
        try { $("#" + stop + "label_flight_time")[0].style.display="block"; } catch(e) {}
        try { $("#" + stop + "flight_time")[0].style.display="block"; } catch(e) {}  // Input
    }
    else if (typeDescription.toUpperCase().search(/RAIL|EUROSTAR/) +1) {
        try { $("#" + addressname + "label_rail")[0].style.display="block"; } catch(e) {}
    }
    else {
        try { $("#" + addressname + "label_standard")[0].style.display="block"; } catch(e) {}
        try { $("#" + addressname)[0].style.display="block"; } catch(e) {}                  // Input
    }
}

function lookupStoredJourneyDetails(event) {
    $("#stored_journey_loading").show();
    $("input[name = loadstoredjourney]").trigger("click");
}

// ===============================================================================================
// 
// ===============================================================================================
function journeystops() {
    journey();
    stops();
}

// ===============================================================================================
// Select (reports page)
// ===============================================================================================
function select() {
    
    try {
        $('#report_startdate,#report_enddate')
            .datepicker({
                changeMonth: true
            })
            .attr("readonly","readonly");
        } catch(e) {}

}

// ===============================================================================================
// Journey
// ===============================================================================================
function journey () {}

// ===============================================================================================
// Contact
// ===============================================================================================
function contact () {
    
    $("#dan_whotocontact_select").hide();
    
    $("#dan_whotocontact")
        .bind('change', function(event) { saveScrollPosition(event); $("#dan_whotocontact_select").trigger("click"); });
        
}

// ===============================================================================================
// Confirm
// ===============================================================================================
function confirmFunction () {
    
    try {
        $('#job_pickup_date_jqui')
            .datepicker({ 
                minDate: 0,
                maxDate: $('#gtwsjs_maxDate').attr("value"),
                numberOfMonths: parseInt($('#gtwsjs_numberOfMonths').attr("value")) ? parseInt($('#gtwsjs_numberOfMonths').attr("value")) : 1
            })
            .attr("readonly","readonly");
    } catch(e) {};
}

// ===============================================================================================
// ASAP
// ===============================================================================================
function asap () {
    job();
    stops();
    $("#stored_journey")
        .bind('change', function(event) { changeAsapStopVisibility() });
}

function changeAsapStopVisibility() {
    if ($("#stored_journey").attr("value") > 0) {
        $("#stops").hide();
    }
    else {
        $("#stops").show();
    }
}

// ===============================================================================================
// Bookings History etc. (list.tt2)
// ===============================================================================================
function list () {}

function enforceDateRange(triggerPicker,date1,date2,range) {
    // Ensure date1 and date2 are within a <range> day range
    // E.g. of a 61 day range: 01/11/2009 - 31/12/2009
    
    var fromDate = $('#' + date1).datepicker('getDate');
    var toDate   = $('#' + date2).datepicker('getDate');
    var daysDifference = daysBetween(fromDate,toDate);
        
    if(daysDifference > (range-1)) {
        if(date1 == triggerPicker) {
            toDate.setTime(fromDate.getTime() + ((range-1) * msInOneDay));
            $('#' + date2).datepicker('setDate',toDate);
            alert("'To' date has been adjusted to comply with the range limit.");
        }
        else {
            fromDate.setTime(toDate.getTime() - ((range-1) * msInOneDay));
            $('#' + date1).datepicker('setDate',fromDate);
            alert("'From' date has been adjusted to comply with the range limit.");
        }
    }
}

function enforceDateOrder(triggerPicker,date1,date2) {
    // Ensure that date1 does not exceed date2
    
    var fromDate = $('#' + date1).datepicker('getDate');
    var toDate   = $('#' + date2).datepicker('getDate');
    
    if(toDate < fromDate) {
        if(date2 == triggerPicker) {
            $('#' + date1).datepicker('setDate',toDate);
        }
        else {
            $('#' + date2).datepicker('setDate',fromDate);
        }
    }
}

// ===============================================================================================
// Profile -> Addresses
// ===============================================================================================
function addresses() {
    // Remove lookup buttons
    $("input[id $= stop0_dropselect]").remove(); // Premises select

    // Premises dropdown
    $("select[id $= _postcodedrop]")
        .bind('change', function(event) { lookupPostcodeDetails(event) });
}

// ===============================================================================================
// Profile -> Stored Journeys
// ===============================================================================================
function journeys() {
    // Remove lookup buttons
    $("input[name = journey_add_address]").hide(); // Predefined address select

    // Predefined address dropdown
    $("select[name = journey_address]")
        .bind('change', function(event) { addAddressToStoredJourney(event) });
}

function addAddressToStoredJourney(event) {
    $("#predefined_address_loading").show();
    $("input[name = journey_add_address]").trigger("click");
}

// ===============================================================================================
// Single booking page
// ===============================================================================================
function singlebookingpage () {
    journey();
    stops();
    contact();
}

// ===============================================================================================
// Utility Functions
// ===============================================================================================
function daysBetween(date1,date2) {

    // Convert both dates to milliseconds
    var date1_ms = date1.getTime();
    var date2_ms = date2.getTime();

    // Calculate the difference in milliseconds
    var difference_ms = (date2_ms - date1_ms);
    
    // Convert back to days and return
    return Math.round(difference_ms/msInOneDay);
}

function saveScrollPosition (event) {
    $("#scroll_y").val($(window).scrollTop());
    //alert("Got scroll position: " + $("#scroll_y").attr("value"));
}

function loadScrollPosition() {
    var scroll_y = $("#scroll_y").attr("value");
    //alert("About to set scroll position to: " + scroll_y );
    if(scroll_y) {
        try { $.scrollTo(scroll_y,0); } catch(e) {};
    }
    // Reset the scroll position
    $("#scroll_y").val(0);
}

