﻿var ajax_loading_image = '<div style="position: relative; left: 0px; width: 100%; height: 0px; overflow: visible; visibility: visible; display: block"><div style="margin-left: -27px; position: absolute; top: 1px; left: 1px; width: 55px; height: 55px visibility: visible"><img style="margin-left:50%; margin-right:50%" margin-top:50%; margin-bottom:50%" src="/images/ajax-loader.gif" /></div></div>';

////////////////Function to reload container from web control////////////////
var xmlHttp_reload_container = null;
function reload_container(control_url, container_object) {
    if (xmlHttp_reload_container) {
        xmlHttp_reload_container.abort();
    }

    if (container_object.innerHTML.search(ajax_loading_image) == -1) {
    //if (document.getElementById('ajax_loading_image').innerHTML.search(ajax_loading_image) == -1) {
        container_object.innerHTML = ajax_loading_image + container_object.innerHTML;
        //document.getElementById('ajax_loading_image').innerHTML = ajax_loading_image;
    }
    var xmlDoc = null;

    // Create xmlHttp Object
    try {
        // Firefox, Opera 8.0+, Safari
        xmlHttp_reload_container = new XMLHttpRequest();
    }
    catch (e) {
        try {
            // Internet Explorer
            xmlHttp_reload_container = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            try {
                xmlHttp_reload_container = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) {
                alert("Your browser does not support AJAX!");
                return false;
            }
        }
    }

    // Event Handler - EventListener
    xmlHttp_reload_container.onreadystatechange = function() {
        if (xmlHttp_reload_container.readyState == 4) // 4: The Request is complete
        {
            xmlDoc = xmlHttp_reload_container.responseText; // Response

            if (container_object && xmlDoc) {
                _gaq.push(['_trackPageview', control_url]);
                container_object.innerHTML = xmlDoc;
            }
            else {
                container_object.innerHTML = container_object.innerHTML.replace(ajax_loading_image, '');
                //document.getElementById('ajax_loading_image').innerHTML = '';
            }

            xmlDoc = null;
            xmlHttp_reload_container = null;
        }
    }

//    xmlHttp_reload_container.onabort = function () {
//        container_object.innerHTML = container_object.innerHTML.replace(ajax_loading_image, '');
//    }

    // Request
    var myRand = parseInt(Math.random() * 999999);
    if (control_url.indexOf('?') > 0) {
        xmlHttp_reload_container.open("GET", control_url + '&rand=' + myRand, true);
    }
    else {
        xmlHttp_reload_container.open("GET", control_url + '?rand=' + myRand, true);
    }
    xmlHttp_reload_container.send(null);
}

////////////////Function to reload container from map movement////////////////
function reload_container_map(control_url, container_object, xmlHttp_reload_container) {
    if (xmlHttp_reload_container) {
        xmlHttp_reload_container.abort();
    }

    if (container_object.innerHTML.search(ajax_loading_image) == -1) {
        container_object.innerHTML = ajax_loading_image + container_object.innerHTML
    }
    var xmlDoc = null;

    // Create xmlHttp Object
    try {
        // Firefox, Opera 8.0+, Safari
        xmlHttp_reload_container = new XMLHttpRequest();
    }
    catch (e) {
        try {
            // Internet Explorer
            xmlHttp_reload_container = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            try {
                xmlHttp_reload_container = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) {
                alert("Your browser does not support AJAX!");
                return false;
            }
        }
    }

    // Event Handler - EventListener
    xmlHttp_reload_container.onreadystatechange = function() {
        if (xmlHttp_reload_container.readyState == 4) // 4: The Request is complete
        {
            xmlDoc = xmlHttp_reload_container.responseText; // Response

            if (container_object && xmlDoc) {
                _gaq.push(['_trackPageview', control_url]);
                container_object.innerHTML = xmlDoc;
                document.getElementById('ajax_loading_image').innerHTML = '';
            }
            else {
                //container_object.innerHTML = container_object.innerHTML.replace(ajax_loading_image, '');
                document.getElementById('ajax_loading_image').innerHTML = '';
            }

            xmlDoc = null;
            xmlHttp_reload_container = null;
        }
    }

    // Request
    var myRand = parseInt(Math.random() * 999999);
    if (control_url.indexOf('?') > 0) {
        xmlHttp_reload_container.open("GET", control_url + '&rand=' + myRand, true);
    }
    else {
        xmlHttp_reload_container.open("GET", control_url + '?rand=' + myRand, true);
    }
    xmlHttp_reload_container.send(null);
}

/////////////////Function to handle map marker click. Needs to redraw markers and replace timetable panels for the given AtcoCode////////////////
var xmlHttp_naptan_times_refresh = null;
function naptan_times_refresh(AtcoCode, NaptanStopName, NaptanStopType, UseCache) {
    if (xmlHttp_naptan_times_refresh) {
        xmlHttp_naptan_times_refresh.abort();
    }

    if (document.getElementById("TravelPlanningTimesDeparturesPanel").innerHTML.search(ajax_loading_image) == -1) {
        document.getElementById("TravelPlanningTimesDeparturesPanel").innerHTML = ajax_loading_image + document.getElementById("TravelPlanningTimesDeparturesPanel").innerHTML
    }

    var xmlDoc = null;
    // Create xmlHttp Object
    try {
        // Firefox, Opera 8.0+, Safari
        xmlHttp_naptan_times_refresh = new XMLHttpRequest();
    }
    catch (e) {
        try {
            // Internet Explorer
            xmlHttp_naptan_times_refresh = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            try {
                xmlHttp_naptan_times_refresh = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) {
                alert("Your browser does not support AJAX!");
                return false;
            }
        }
    }
    // Event Handler - EventListener
    xmlHttp_naptan_times_refresh.onreadystatechange = function() {
    if (xmlHttp_naptan_times_refresh.readyState == 4) // 4: The Request is complete
        {
            xmlDoc = xmlHttp_naptan_times_refresh.responseText; // Response

            if (document.getElementById("TravelPlanningTimesDeparturesPanel") && xmlDoc) {
                _gaq.push(['_trackPageview', '/controls/travel-planning-times-ajaxwrapper.aspx?AtcoCode=' + AtcoCode + '&NaptanStopName=' + NaptanStopName + '&NaptanStopType=' + NaptanStopType + '&UseCache=' + UseCache]);
                document.getElementById("TravelPlanningTimesDeparturesPanel").innerHTML = xmlDoc;
            }
            else {
                document.getElementById("TravelPlanningTimesDeparturesPanel").innerHTML = document.getElementById("TravelPlanningTimesDeparturesPanel").innerHTML.replace(ajax_loading_image, '')
            }

            xmlDoc = null;
            xmlHttp_naptan_times_refresh = null;
        }
    }
    // Request to Send
    var myRand = parseInt(Math.random() * 999999);
    xmlHttp_naptan_times_refresh.open("GET", "/controls/travel-planning-times-ajaxwrapper.aspx?AtcoCode=" + AtcoCode + "&NaptanStopName=" + NaptanStopName + "&NaptanStopType=" + NaptanStopType + "&UseCache=" + UseCache + "&rand=" + myRand, true);
    xmlHttp_naptan_times_refresh.send(null);
}

////////////////Functions to handle Journey Planner click events////////////////
function swap_elements(element_1, element_2) {
    var temp_1 = element_1.value;
    var temp_2 = element_2.value;

    element_1.value = temp_2;
    element_2.value = temp_1;
}

function go_handler() {
    var origin_name = escape(document.getElementById('Origin_Name').value);
    var destination_name = escape(document.getElementById('Destination_Name').value);
    var origin_name_id = escape(document.getElementById('Origin_Name_ID').value);
    var destination_name_id = escape(document.getElementById('Destination_Name_ID').value);

    var departure_day = escape(document.getElementById('day').value);
    var departure_month = escape(document.getElementById('month').value);
    var departure_hour = escape(document.getElementById('hour').value);
    var departure_minute = escape(document.getElementById('minute').value);

    if (origin_name == '' || origin_name == escape('From (enter location or choose on the map)') || origin_name == 'To') {
        alert('You must enter a starting point for your journey');
        document.getElementById('Origin_Name').focus();
        return;
    }
    if (destination_name == '' || destination_name == escape('From (enter location or choose on the map)') || destination_name == 'To') {
        alert('You must enter an end point for your journey');
        document.getElementById('Destination_Name').focus();
        return;
    }
    reload_container('/controls/travel-planning-journey-planner-step2-ajaxwrapper.aspx?Origin_Name=' + origin_name + '&Origin_Name_ID=' + origin_name_id + '&Destination_Name=' + destination_name + '&Destination_Name_ID=' + destination_name_id + '&departure_day=' + departure_day + '&departure_month=' + departure_month + '&departure_hour=' + departure_hour + '&departure_minute=' + departure_minute, document.getElementById('TravelPlanningJourneyPlannerContainer'));
}

function go_handler_step2() {
    var origin_name = escape(document.getElementById('Origin_Name').value);
    var destination_name = escape(document.getElementById('Destination_Name').value);
    if (document.getElementById('Origin_Name_ID') != null) {
        var origin_name_id = escape(document.getElementById('Origin_Name_ID').value);
    }
    else {
        var origin_name_id = ''
    }
    if (document.getElementById('Destination_Name_ID') != null) {
        var destination_name_id = escape(document.getElementById('Destination_Name_ID').value);
    }
    else {
        var destination_name_id = ''
    }

    var departure_day = escape(document.getElementById('day').value);
    var departure_month = escape(document.getElementById('month').value);
    var departure_hour = escape(document.getElementById('hour').value);
    var departure_minute = escape(document.getElementById('minute').value);
    
    if (origin_name == '' || origin_name == escape('enter a new location or choose on the map')) {
        alert('You must enter a starting point for your journey');
        document.getElementById('Origin_Name').focus();
        return;
    }
    if (destination_name == '' || destination_name == escape('enter a new location or choose on the map')) {
        alert('You must enter an end point for your journey');
        document.getElementById('Destination_Name').focus();
        return;
    }
    reload_container('/controls/travel-planning-journey-planner-step2-ajaxwrapper.aspx?Origin_Name=' + origin_name + '&Origin_Name_ID=' + origin_name_id + '&Destination_Name=' + destination_name + '&Destination_Name_ID=' + destination_name_id + '&departure_day=' + departure_day + '&departure_month=' + departure_month + '&departure_hour=' + departure_hour + '&departure_minute=' + departure_minute, document.getElementById('TravelPlanningJourneyPlannerContainer'));
}

function toggle_journeydetails(element, journeylistsize) {
    for (i = 0; i <= journeylistsize - 1; i++) {
        if (element == i) {
            if (document.getElementById('journey' + i).style.display == "block") { //We are deselecting
                document.getElementById('journey' + i).style.display = "none";
                document.getElementById('select_journey' + i).src = '/images/arrow.gif';

                for (j = 0; j <= journeylistsize - 1; j++) {
                    document.getElementById('results' + j).style.display = "block";
                }
            }
            else { //We are selecting
                document.getElementById('journey' + i).style.display = "block";
                document.getElementById('select_journey' + i).src = '/images/arrow-back.gif';

                for (j = 0; j <= journeylistsize - 1; j++) {
                    if (element == j) {
                        document.getElementById('results' + j).style.display = "block";
                    }
                    else {
                        document.getElementById('results' + j).style.display = "none";
                    } 
                }
            }
        }
        else {
            document.getElementById('journey' + i).style.display = "none"
            document.getElementById('select_journey' + i).src = '/images/arrow.gif';
        }    
    }

    return;
}

function toggle_journeytimes() {
    if (document.getElementById('journeyplan_traveltimes').style.display == "block") {
        document.getElementById('journeyplan_traveltimes').style.display = "none";
        document.getElementById('journeyplan_selecttimes').style.display = "block";
    }
    else {
        document.getElementById('journeyplan_traveltimes').style.display = "block";
        document.getElementById('journeyplan_selecttimes').style.display = "none";
    }
    return;
}

function toggle_history() {
    if (document.getElementById("TravelPlanningJourneyPlannerHistoryPanel").style.display == "block") {
        document.getElementById("TravelPlanningJourneyPlannerHistoryPanel").style.display = "none";
        document.getElementById("TravelPlanningJourneyPlannerContainer").style.display = "block";
    }
    else {
        document.getElementById("TravelPlanningJourneyPlannerHistoryPanel").style.display = "block";
        document.getElementById("TravelPlanningJourneyPlannerFavouritesPanel").style.display = "none";
        document.getElementById("TravelPlanningJourneyPlannerContainer").style.display = "none";
        //Reload History Panel with latest data
        reload_container('/controls/travel-planning-journey-planner-history-ajaxwrapper.aspx', document.getElementById('TravelPlanningJourneyPlannerHistoryPanel'));
    }
    return;
}

function toggle_favourites() {
    if (document.getElementById("TravelPlanningJourneyPlannerFavouritesPanel").style.display == "block") {
        document.getElementById("TravelPlanningJourneyPlannerFavouritesPanel").style.display = "none";
        document.getElementById("TravelPlanningJourneyPlannerContainer").style.display = "block";
    }
    else {
        document.getElementById("TravelPlanningJourneyPlannerFavouritesPanel").style.display = "block";
        document.getElementById("TravelPlanningJourneyPlannerHistoryPanel").style.display = "none";
        document.getElementById("TravelPlanningJourneyPlannerContainer").style.display = "none";
        //Reload Favourites Panel with latest data
        reload_container('/controls/travel-planning-journey-planner-favourites-ajaxwrapper.aspx', document.getElementById('TravelPlanningJourneyPlannerFavouritesPanel'));
    }
    return;
}

//Function to handle journey plan marker clicks
function marker_journeyplan_click(LocationID, LocationName) {
    if (document.getElementById('Origin_Name') != null) {
        //If the origin is not set, set it
        if (document.getElementById('Origin_Name').value == '' || document.getElementById('Origin_Name').value == 'From (enter location or choose on the map)') {
            document.getElementById('Origin_Name').value = LocationName;
            document.getElementById('Origin_Name_ID').value = LocationID;
        }
        //otherwise set destination
        else {
            document.getElementById('Destination_Name').value = LocationName;
            document.getElementById('Destination_Name_ID').value = LocationID;
        }
    }
}

//Function to handle autocomplete selection
function journeyplan_origin_input_select(LocationID, LocationName) {
    document.getElementById('Origin_Name').value = LocationName;
    document.getElementById('Origin_Name_ID').value = LocationID;
    // Clear autocomplete box
    document.getElementById('journeyplan_origin_autocomplete').innerHTML = '';
    document.getElementById('journeyplan_origin_autocomplete').style.display = 'none';
}

//Populate journeyplan origin autocomplete
function journeyplan_origin_input(name) {
    //Clear hidden ID field on edit
    document.getElementById('Origin_Name_ID').value = ""
  
    if (name.length >= 2) {
        var xmlHttp = null;
        var xmlDoc = null;
        // Create xmlHttp Object
        try {
            // Firefox, Opera 8.0+, Safari
            xmlHttp = new XMLHttpRequest();
        }
        catch (e) {
            try {
                // Internet Explorer
                xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e) {
                try {
                    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                }
                catch (e) {
                    alert("Your browser does not support AJAX!");
                    return false;
                }
            }
        }
        // Event Handler - EventListener
        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState == 4) // 4: The Request is complete
            {
                xmlDoc = xmlHttp.responseXML; // Response

                //Get autocomplete content by looping through XML
                autoCompleteText = ''
                x = xmlDoc.getElementsByTagName("LocationMatch");
                //If there are more than one matching results
                if (x.length > 0) {
                    for (i = 0; i <= x.length - 1; i++) {
                        NearestLocationID = xmlDoc.getElementsByTagName("NearestLocationID")[i].childNodes[0].nodeValue;
                        NearestLocationName = xmlDoc.getElementsByTagName("NearestLocationName")[i].childNodes[0].nodeValue;

                        autoCompleteText += '<a class="small" href="javascript:journeyplan_origin_input_select(' + NearestLocationID + ', \'' + NearestLocationName.replace('\'', '’') + '\');">' + NearestLocationName + '</a><br />\n';
                    }

                    document.getElementById('journeyplan_origin_autocomplete').innerHTML = autoCompleteText;
                    document.getElementById('journeyplan_origin_autocomplete').style.display = 'block';
                }
                //if there is no match
                else {
                    document.getElementById('journeyplan_origin_autocomplete').innerHTML = '';
                    document.getElementById('journeyplan_origin_autocomplete').style.display = 'none';
                }

                xmlDoc = null;
                xmlHttp = null;
            }
        }
        // Request to Send
        var myRand = parseInt(Math.random() * 999999);
        xmlHttp.open("GET", "/ws-internal/client_side/travelfor.asmx/GeoCodeJourneyPlanLocationsByName?Name=" + name + "&rand=" + myRand, true);
        xmlHttp.send(null);
    }
    else {
        document.getElementById('journeyplan_origin_autocomplete').innerHTML = '';
        document.getElementById('journeyplan_origin_autocomplete').style.display = 'none';
    }
}

//Function to handle autocomplete selection
function journeyplan_destination_input_select(LocationID, LocationName) {
    document.getElementById('Destination_Name').value = LocationName;
    document.getElementById('Destination_Name_ID').value = LocationID;
    // Clear autocomplete box
    document.getElementById('journeyplan_destination_autocomplete').innerHTML = '';
    document.getElementById('journeyplan_destination_autocomplete').style.display = 'none';
}

//Populate journeyplan origin autocomplete
function journeyplan_destination_input(name) {
    //Clear hidden ID field on edit
    document.getElementById('Destination_Name_ID').value = ""
    if (name.length >= 2) {
        var xmlHttp = null;
        var xmlDoc = null;
        // Create xmlHttp Object
        try {
            // Firefox, Opera 8.0+, Safari
            xmlHttp = new XMLHttpRequest();
        }
        catch (e) {
            try {
                // Internet Explorer
                xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e) {
                try {
                    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                }
                catch (e) {
                    alert("Your browser does not support AJAX!");
                    return false;
                }
            }
        }
        // Event Handler - EventListener
        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState == 4) // 4: The Request is complete
            {
                xmlDoc = xmlHttp.responseXML; // Response

                //Get autocomplete content by looping through XML
                autoCompleteText = ''
                x = xmlDoc.getElementsByTagName("LocationMatch");
                //If there are more than one matching results
                if (x.length > 0) {
                    for (i = 0; i <= x.length - 1; i++) {
                        NearestLocationID = xmlDoc.getElementsByTagName("NearestLocationID")[i].childNodes[0].nodeValue;
                        NearestLocationName = xmlDoc.getElementsByTagName("NearestLocationName")[i].childNodes[0].nodeValue;

                        autoCompleteText += '<a class="small" href="javascript:journeyplan_destination_input_select(' + NearestLocationID + ', \'' + NearestLocationName.replace('\'', '’') + '\');">' + NearestLocationName + '</a><br />\n';
                    }

                    document.getElementById('journeyplan_destination_autocomplete').innerHTML = autoCompleteText;
                    document.getElementById('journeyplan_destination_autocomplete').style.display = 'block';
                }
                //if there is no match
                else {
                    document.getElementById('journeyplan_destination_autocomplete').innerHTML = '';
                    document.getElementById('journeyplan_destination_autocomplete').style.display = 'none';
                }

                xmlDoc = null;
                xmlHttp = null;
            }
        }
        // Request to Send
        var myRand = parseInt(Math.random() * 999999);
        xmlHttp.open("GET", "/ws-internal/client_side/travelfor.asmx/GeoCodeJourneyPlanLocationsByName?Name=" + name + "&rand=" + myRand, true);
        xmlHttp.send(null);
    }
    else {
        document.getElementById('journeyplan_destination_autocomplete').innerHTML = '';
        document.getElementById('journeyplan_destination_autocomplete').style.display = 'none';
    }
}

function plan_new_journey() {
    //Reactivate journey planner markers
    journeyplanner_map_showmarkers = true;
    //Reload Journey Planner
    reload_container('/controls/travel-planning-journey-planner-step1-ajaxwrapper.aspx', document.getElementById('TravelPlanningJourneyPlannerContainer'));
    //Reload Journey Planner map with markers
    dropmarkers_journeyplan(map_planner);
}

/////////////////Functions to handle Travel For Me click events////////////////
function toggle_travelforme() {
    if (document.getElementById('travelforme_locations').style.display == "block") {
        document.getElementById('travelforme_locations').style.display = "none";
        //document.getElementById('travelforme_more').style.display = "block";
    }
    else {
        document.getElementById('travelforme_locations').style.display = "block";
        //document.getElementById('travelforme_more').style.display = "none";
    }
    return;
}

function set_home() {
    var xmlHttp = null;
    var xmlDoc = null;

    // Create xmlHttp Object
    try {
        // Firefox, Opera 8.0+, Safari
        xmlHttp = new XMLHttpRequest();
    }
    catch (e) {
        try {
            // Internet Explorer
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            try {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) {
                alert("Your browser does not support AJAX!");
                return false;
            }
        }
    }

    // Event Handler - EventListener
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4) // 4: The Request is complete
        {
            xmlDoc = xmlHttp.responseXML; // Response

            reload_container('/controls/travelforme-ajaxwrapper.aspx', document.getElementById('TravelForMePanel'));

            xmlDoc = null;
            xmlHttp = null;
        }
    }

    // Request
    var myRand = parseInt(Math.random() * 999999);
    xmlHttp.open("GET", "/handlers/setHome.aspx?Rand=" + myRand + "&URL=" + escape(location.pathname), true);
    xmlHttp.send(null);
}

function set_work() {
    var xmlHttp = null;
    var xmlDoc = null;

    // Create xmlHttp Object
    try {
        // Firefox, Opera 8.0+, Safari
        xmlHttp = new XMLHttpRequest();
    }
    catch (e) {
        try {
            // Internet Explorer
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            try {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) {
                alert("Your browser does not support AJAX!");
                return false;
            }
        }
    }

    // Event Handler - EventListener
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4) // 4: The Request is complete
        {
            xmlDoc = xmlHttp.responseXML; // Response

            reload_container('/controls/travelforme-ajaxwrapper.aspx', document.getElementById('TravelForMePanel'));

            xmlDoc = null;
            xmlHttp = null;
        }
    }

    // Request
    var myRand = parseInt(Math.random() * 999999);
    xmlHttp.open("GET", "/handlers/setWork.aspx?Rand=" + myRand + "&URL=" + escape(location.pathname), true);
    xmlHttp.send(null);
}

//////////////////Functions to handle Edit Home Page click events////////////////
function edithome_click() {
    document.getElementById('edithome').style.display = 'none';
    document.getElementById('edithome_input').style.display = 'block';
}

function edithome_redirect(search, location_id, location_name) {
    if (search != '') {
        //Try to match postcode. If no match we will perform a search later.
        redirect_postcode(search);
    }
    else if (location_id != '') {
        document.getElementById('edithome_autocomplete').style.display = 'none';
        document.getElementById('edithome_input_name').value = location_name;
        redirect_location_id(location_id);
    }
}

var xmlHttp_edithome_input = null;

//Populate autocomplete
function edithome_input(name) {
    if (xmlHttp_edithome_input) {
        xmlHttp_edithome_input.abort();
    }

    if (name.length >= 2) {
        var xmlDoc = null;
        // Create xmlHttp Object
        try {
            // Firefox, Opera 8.0+, Safari
            xmlHttp_edithome_input = new XMLHttpRequest();
        }
        catch (e) {
            try {
                // Internet Explorer
                xmlHttp_edithome_input = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e) {
                try {
                    xmlHttp_edithome_input = new ActiveXObject("Microsoft.XMLHTTP");
                }
                catch (e) {
                    alert("Your browser does not support AJAX!");
                    return false;
                }
            }
        }
        // Event Handler - EventListener
        xmlHttp_edithome_input.onreadystatechange = function() {
            if (xmlHttp_edithome_input.readyState == 4) // 4: The Request is complete
            {
                xmlDoc = xmlHttp_edithome_input.responseXML; // Response

                //Get autocomplete content by looping through XML
                autoCompleteText = ''
                x = xmlDoc.getElementsByTagName("LocationMatch");
                //If there are matching results
                if (x.length > 0) {
                    for (i = 0; i <= x.length - 1; i++) {
                        NearestLocationID = xmlDoc.getElementsByTagName("NearestLocationID")[i].childNodes[0].nodeValue;
                        NearestLocation = xmlDoc.getElementsByTagName("NearestLocation")[i].childNodes[0].nodeValue;
                        NearestLocationCounty = xmlDoc.getElementsByTagName("NearestLocationCounty")[i].childNodes[0].nodeValue;

                        autoCompleteText += '<a class="small" href="javascript:edithome_redirect(\'\', ' + NearestLocationID + ', \'' + NearestLocation + ' - ' + NearestLocationCounty + '\');">' + NearestLocation + ' - ' + NearestLocationCounty + '</a><br />\n';
                    }

                    document.getElementById('edithome_autocomplete').innerHTML = autoCompleteText;
                    document.getElementById('edithome_autocomplete').style.display = 'block';
                }
                //if there are no matches
                else {
                    //document.getElementById('edithome_autocomplete').innerHTML = '<div class="small">No matching town/village</div>\n';
                    document.getElementById('edithome_autocomplete').style.display = 'none';
                }
                
                xmlDoc = null;
                xmlHttp_edithome_input = null;
            }
        }
        // Request to Send
        var myRand = parseInt(Math.random() * 999999);
        xmlHttp_edithome_input.open("GET", "/ws-internal/client_side/travelfor.asmx/GeoCodeByName?Name=" + name + "&rand=" + myRand, true);
        xmlHttp_edithome_input.send(null);
    }
    else {
        document.getElementById('edithome_autocomplete').innerHTML = '';
        document.getElementById('edithome_autocomplete').style.display = 'none';
    }
}

//Function to redirect based on entered postcode
function redirect_postcode(postcode) {

    if (postcode == '') {
        alert('You must enter a postcode or your nearest location.\nPlease try again.');
    }
    else {

        var xmlHttp = null;
        var xmlDoc = null;

        // Create xmlHttp Object
        try {
            // Firefox, Opera 8.0+, Safari
            xmlHttp = new XMLHttpRequest();
        }
        catch (e) {
            try {
                // Internet Explorer
                xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e) {
                try {
                    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                }
                catch (e) {
                    alert("Your browser does not support AJAX!");
                    return false;
                }
            }
        }

        // Event Handler - EventListener
        xmlHttp.onreadystatechange = function () {
            if (xmlHttp.readyState == 4) // 4: The Request is complete
            {
                xmlDoc = xmlHttp.responseXML; // Response

                //Check for valid postcode
                if (xmlDoc.getElementsByTagName("Postcode")[0].childNodes[0].nodeValue == 'Postcode Does Not Exist') {
                    //alert('That is not a valid UK postcode.\nPlease try again or select a matching location from the list.');
                    //If postcode doesn't match do a search
                    dosearch(postcode);
                }
                else {

                    //Call 'GeoCodeByLocation' to obtain location details of new map centre
                    NearestLocation = xmlDoc.getElementsByTagName("NearestLocation")[0].childNodes[0].nodeValue;
                    NearestLocationCounty = xmlDoc.getElementsByTagName("NearestLocationCounty")[0].childNodes[0].nodeValue;
                    NearestStreet = xmlDoc.getElementsByTagName("NearestStreet")[0].childNodes[0].nodeValue;

                    NearestLocation = NearestLocation.replace(/ /g, '_');
                    NearestLocationCounty = NearestLocationCounty.replace(/ /g, '_');
                    NearestStreet = NearestStreet.replace(/ /g, '_');

                    postcode = postcode.toUpperCase();
                    postcode = postcode.replace(/ /g, '+');

                    _gaq.push(['_trackEvent', 'Edit_Location', 'Postcode', postcode]);

                    window.location = '/handlers/updateMemberLocations.aspx?title=' + escape(postcode) + '&url=' + escape('/' + NearestLocationCounty + '/' + NearestLocation + '/' + NearestStreet + '/');
                    //window.location = escape('/' + NearestLocationCounty + '/' + NearestLocation + '/' + NearestStreet + '/');
                }

                xmlDoc = null;
                xmlHttp = null;
            }
        }

        // Request
        var myRand = parseInt(Math.random() * 999999);
        xmlHttp.open("GET", "/ws-internal/client_side/travelfor.asmx/GeoCodeByPostcode?Rand=" + myRand + "&Postcode=" + postcode, true);
        xmlHttp.send(null);
    }
}

//Function to redirect based on entered location id
function redirect_location_id(location_id) {

    var xmlHttp = null;
    var xmlDoc = null;

    // Create xmlHttp Object
    try {
        // Firefox, Opera 8.0+, Safari
        xmlHttp = new XMLHttpRequest();
    }
    catch (e) {
        try {
            // Internet Explorer
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            try {
                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) {
                alert("Your browser does not support AJAX!");
                return false;
            }
        }
    }

    // Event Handler - EventListener
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4) // 4: The Request is complete
        {
            xmlDoc = xmlHttp.responseXML; // Response

            //Check for valid postcode
            if (xmlDoc.getElementsByTagName("Postcode")[0].childNodes[0].nodeValue == 'Location Does Not Exist') {
                alert('That is not a valid location.\nPlease try again or select a matching location from the list.');
            }
            else {

                //Call 'GeoCodeByLocation' to obtain location details of new map centre
                NearestLocation = xmlDoc.getElementsByTagName("NearestLocation")[0].childNodes[0].nodeValue;
                NearestLocationCounty = xmlDoc.getElementsByTagName("NearestLocationCounty")[0].childNodes[0].nodeValue;

                NearestLocation = NearestLocation.replace(/ /g, '_');
                NearestLocationCounty = NearestLocationCounty.replace(/ /g, '_');

                _gaq.push(['_trackEvent', 'Edit_Location', 'Location', NearestLocation]);

                window.location = '/handlers/updateMemberLocations.aspx?title=' + escape(xmlDoc.getElementsByTagName("NearestLocation")[0].childNodes[0].nodeValue) + '&url=' + escape('/' + NearestLocationCounty + '/' + NearestLocation + '/');
                //window.location = escape('/' + NearestLocationCounty + '/' + NearestLocation + '/');
            }

            xmlDoc = null;
            xmlHttp = null;
        }
    }

    // Request
    var myRand = parseInt(Math.random() * 999999);
    xmlHttp.open("GET", "/ws-internal/client_side/travelfor.asmx/GeoCodeByLocationID?Rand=" + myRand + "&LocationID=" + location_id, true);
    xmlHttp.send(null);
}

//////////////////Script for whats on module//////////////////
//$(function() {
//    var tabContainers = $('div.tabs-whatson > div');
//    tabContainers.hide().filter(':first').show();

//    $('div.tabs-whatson ul.tabNavigation a').click(function() {
//        tabContainers.hide();
//        tabContainers.filter(this.hash).show();
//        $('div.tabs-whatson ul.tabNavigation a').removeClass('selected');
//        $(this).addClass('selected');
//        return false;
//    }).filter(':first').click();
//});

function whatsontab_click(tab_name) {
    document.getElementById("WhatsOnAll").style.display = "none";
    document.getElementById("WhatsOnMusic").style.display = "none";
    document.getElementById("WhatsOnTheatre").style.display = "none";
    document.getElementById("WhatsOnComedy").style.display = "none";
    document.getElementById("WhatsOnEvents").style.display = "none";
    document.getElementById("WhatsOnSport").style.display = "none";
    document.getElementById("WhatsOnTabAll").className = "";
    document.getElementById("WhatsOnTabMusic").className = "";
    document.getElementById("WhatsOnTabTheatre").className = "";
    document.getElementById("WhatsOnTabComedy").className = "";
    document.getElementById("WhatsOnTabEvents").className = "";
    document.getElementById("WhatsOnTabSport").className = "";

    _gaq.push(['_trackPageview', '/WhatsOn/' + tab_name + '/']);
    
    document.getElementById("WhatsOn" + tab_name).style.display = "block";
    document.getElementById("WhatsOnTab" + tab_name).className = "selected";
}

//////////////////Helper functions////////////////
function getQuerystring(key, default_) {
    if (default_ == null) default_ = "";
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
    var qs = regex.exec(window.location.href);
    if (qs == null)
        return default_;
    else
        return qs[1];
}

function deleteCookie(name, path, domain) {
    if (getCookie(name)) document.cookie = name + "=" +
((path) ? ";path=" + path : "") +
((domain) ? ";domain=" + domain : "") +
";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function getCookie(name) {
    var start = document.cookie.indexOf(name + "=");
    var len = start + name.length + 1;
    if ((!start) && (name != document.cookie.substring(0, name.length))) {
        return null;
    }
    if (start == -1) return null;
    var end = document.cookie.indexOf(";", len);
    if (end == -1) end = document.cookie.length;
    return unescape(document.cookie.substring(len, end));
}

function fb_login() {
    FB.login(function(response) {
      if (response.session) {
        if (response.perms) {
          // user is logged in and granted some permissions.
          // perms is a comma separated list of granted permissions
                // A user has logged in, and a new cookie has been saved
                reload_container('/controls/travelforme-ajaxwrapper.aspx', document.getElementById('TravelForMePanel'));
        } else {
          // user is logged in, but did not grant any permissions
                // A user has logged in, and a new cookie has been saved
                reload_container('/controls/travelforme-ajaxwrapper.aspx', document.getElementById('TravelForMePanel'));
        }
      } else {
        // user is not logged in
                // The user has logged out, and the cookie has been cleared
                reload_container('/controls/travelforme-ajaxwrapper-logout.aspx', document.getElementById('TravelForMePanel'));
      }
  }, { perms: 'email,publish_stream,user_checkins,friends_checkins' });
}

function buyticket_handler() {
    var origin = escape(document.getElementById('origin').value);
    var destination = escape(document.getElementById('destination').value);

    var outDate = Left(escape(document.getElementById('departure_month').value), 4) + '-' + Right(escape(document.getElementById('departure_month').value), 2) + '-' + escape(document.getElementById('departure_day').value);  //'2011-05-16'
    var outHour = escape(document.getElementById('departure_hour').value);
    var outMin = escape(document.getElementById('departure_minute').value);
    var returnDate = Left(escape(document.getElementById('return_month').value), 4) + '-' + Right(escape(document.getElementById('return_month').value), 2) + '-' + escape(document.getElementById('return_day').value);
    var returnHour = escape(document.getElementById('return_hour').value);
    var returnMin = escape(document.getElementById('return_minute').value);

    var adults = escape(document.getElementById('adults').value);
    var children = escape(document.getElementById('children').value);

    if (origin == '' || origin == escape('Departing From')) {
        alert('You must enter a starting point for your journey');
        document.getElementById('origin').focus();
        return;
    }
    if (destination == '' || destination == escape('To')) {
        alert('You must enter an end point for your journey');
        document.getElementById('destination').focus();
        return;
    }

    //var randomnumber = Math.floor(Math.random() * 2)
    //if (randomnumber == 1) {
    //    window.open('/handlers/externalclick.aspx?label=signupandsave_traintickets_mytrainticket&url=http%3A%2F%2Fwww.awin1.com%2Fcread.php%3Fawinmid%3D2927%26awinaffid%3D104479%26clickref%3Dsignupandsave_traintickets%26p%3D' + encodeURIComponent(encodeURIComponent('http://ticketing.mytrainticket.co.uk/set-requested-journey?&marketingScheme=&single=0&origin=' + origin + '&destination=' + destination + '&outCalendar=&outDate=' + outDate + '&outArriveDepart=DepartAfter&outHour=' + outHour + '&outMin=' + outMin + '&returnCalendar=&returnDate=' + returnDate + '&returnArriveDepart=DepartAfter&returnHour=' + returnHour + '&returnMin=' + returnMin + '&adults=' + adults + '&children=' + children + '&railcard=&source=aw', '_mytrainticket', 'width=1050,height=850')));
    //} else {
        window.open('/handlers/externalclick.aspx?label=signupandsave_traintickets_thetrainline&url=http%3A%2F%2Fclkgb.tradedoubler.com%2Fclick%3Fp%3D3447%26a%3D1803280%26g%3D16933664%26url%3D' + encodeURIComponent(encodeURIComponent('http://www.thetrainline.com/buytickets/datapassedin.aspx?utm_source=Affiliates&utm_campaign=QTT&ori=' + origin + '&dest=' + destination + '&outDate=' + outDate + '&outHourField=' + outHour + '&outMinuteField=' + outMin + '&inDate=' + returnDate + '&inHourField=' + returnHour + '&inMinuteField=' + returnMin + '&noa=' + adults + '&noc=' + children + '', '_thetrainline', 'width=1050,height=850')));
    //}
}

function Left(str, n) {
    if (n <= 0)
        return "";
    else if (n > String(str).length)
        return str;
    else
        return String(str).substring(0, n);
}

function Right(str, n) {
    if (n <= 0)
        return "";
    else if (n > String(str).length)
        return str;
    else {
        var iLen = String(str).length;
        return String(str).substring(iLen, iLen - n);
    }
}
