﻿var x = 0;
var LeftHTML = "";
var popHTML = "";
var journeyType = "";
var lastPOPUPID = "";

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, "");
};
var reg = new RegExp("[0-9]+");
function findStops() {
    var txtZipCode = document.getElementById("txtZipCode").value;
    if (txtZipCode.trim() == "") {
        //document.getElementById("errormsg").style.display = 'block';
				document.getElementById("txtZipCode").value = "Please enter a zip code.";
    }
    else {
        document.getElementById("errormsg").style.display = 'none';
        showLightbox();
        $("#lightbox").show();
        document.getElementById('lightbox').style.marginTop = '75px';
        $.ajax
            ({
                url: "busstop.aspx",
                data: "zipCode=" + document.getElementById('txtZipCode').value,
                success: function(message1) {
                    $("#lightbox").append(message1);
                    document.getElementById('lightboxcontainer').style.width = '820px';
                    document.getElementById('overlay').style.height = '1200px';
                    showStops();

                }
            });
    }
}

// MS Added to change jp back to coach for homepage
function changejp(){
	resetMessages();
	$("#frm1").show();
	$("#1_lnk").attr("src", Imageurl + "coach_blue_btn_hover.gif");
	$("#2_lnk").attr("src",  Imageurl + "train_blue_btn.gif");
	$("#coach").removeClass("width100");
	$("#coach").addClass("width102");
	$("#train").removeClass("width102");
	$("#train").addClass("width100");
	$("#frm2").hide();
	bIsSelected = 1;
	iMonthLimit = 6;
	SetCoachTabSrc(iCurrentColor);
	iSelectedday = 0;
	OneWay=1;
}
// MS END

function startSearch() {
    try {
        if (WeatherLabels) {
            initMap(mapKey);
            geocoder_search();
        }
    }
    catch (er) {
        timerId = setTimeout("startSearch()", 1000);
    }
}

function initMap() {
    VMAPI.registerKey("JSBS20071019125005322879916507");
    VMAPI.setLanguage("gbr");
}

function geocoder_search() {
    setDivStatus();
    var LocationCode = document.getElementById('form_CP').value.toUpperCase();
    LocationCode = $.trim(LocationCode);
    geosearch = new VMGeoSearch();
    myaddress = new VMAddress();
    Start_geocoder = new VMGeocoder();
    var elements_formulaire = document.forms['geocoder_form'].elements;
    myaddress.address = null;
    if (reg.test(LocationCode)) {
        myaddress.zipCode = LocationCode;
        myaddress.city = 'LONDON';
    }
    else
        myaddress.city = LocationCode;
    // = (document.getElementById('form_CP').value).toUpperCase();
    //myaddress.city = 'BRISTOL';
    myaddress.countryVMCode = '1138';
    geosearch.addEventHandler("onCallBack", poi_definition);
    geosearch.search(myaddress);
    Start_geocoder.search(myaddress);
}

function poi_definition() {
    index = 0;
    poiDefinition = new VMPOIDefinition();
    poiDefinition.addEventHandler("onCallBack", poi_search);
    poiDefinition.getDefiniton("123420");
}

/* With the location, and the POI type, we can start the search */
function poi_search() {
    myPOIsearch = new VMPOISearch(poiDefinition);
    myPOIsearch.addEventHandler("onCallBack", search_iti);
    myPOIsearch.search(geosearch.results[index].coords);
}
/*Itinary function*/
function search_iti() {
    map = new VMMap(document.getElementById("yourmapdiv"));
    if (myPOIsearch != null && myPOIsearch.result != null && myPOIsearch.result.VMPOIs != null && myPOIsearch.result.VMPOIs.length > 0) {
        myPOIlist = myPOIsearch.result;
    }

    if (myPOIsearch != null && myPOIsearch.result != null && myPOIsearch.result.VMPOIs != null && x < myPOIsearch.result.VMPOIs.length) {
        CalculateITI();
    }
}

function CalculateITI() {
    try {
        if (x < myPOIsearch.result.VMPOIs.length) {
            myiti = new VMItinerary();
            myiti.addStopOver(Start_geocoder.result);

            myiti.addStopOver(new VMLonLat(myPOIsearch.result.VMPOIs[x].coords.lon, myPOIsearch.result.VMPOIs[x].coords.lat));
            myiti.setItineraryType('0');
            myiti.setItineraryVehicleType('1');
            myiti.setCarType('2');
            myiti.addEventHandler("onCallBack", iti_found);
            myiti.search();
        }
        else {
            document.getElementById("mapLoader").style.display = "none";
            document.getElementById("yourhtmldiv").innerHTML = '<div class="busStopHeader">Coach stops<br/><hr/></div>' + LeftHTML;  //myPOIlist.getHTML();
            LeftHTML = "";
            popHTML = "";
            x = 0;

            map.drawMapFromLayers();
            map.showMapTools(0);
            document.getElementById("dvContent").style.display = "block"; IsClick = true;
            SetZoom();
        }
    }
    catch (ex) { x++; CalculateITI(); }
}

function iti_found() {
    try {
        if (myPOIsearch != null && myPOIsearch.result != null && myPOIsearch.result.VMPOIs != null) {
            if (myiti.getTotalDistance() < 1000)
                journeyType = "walk";
            else
                journeyType = "car";
            var TotalTime = Math.round(myiti.getTotalTime() / 60);

            poiHTML = "<div style='width:200px'><strong>" + myPOIsearch.result.VMPOIs[x].name + "</strong><br>";
            poiHTML += TotalTime == 1 ? TotalTime + " min by " : TotalTime + " mins by " + journeyType + " from " + (document.getElementById('form_CP').value).toUpperCase() + "<br/><br/>";
            poiHTML += "<br>" + myPOIsearch.result.VMPOIs[x].displayAddress;
            poiHTML += "<br/><br/>" + '<a href="#?" style="color:#1F70C7;font-weight:bold;font-size:11px"  onclick="setLink(\'true\',\'' + myPOIsearch.result.VMPOIs[x].name + '\',\'' + myPOIsearch.result.VMPOIs[x].id + '\')">Travel from this stop</a><br/><a href="#?" style="color:#1F70C7;font-weight:bold;font-size:11px" onclick="setLink(\'false\',\'' + myPOIsearch.result.VMPOIs[x].name + '\',\'' + myPOIsearch.result.VMPOIs[x].id + '\')">Travel to this stop</a>';

            //alert(myPOIsearch.result.VMPOIs[x].id);
            popHTML = "<div class='popupText'><span><strong>" + myPOIsearch.result.VMPOIs[x].name + "</strong></span><br/>";
            popHTML += TotalTime == 1 ? TotalTime + " min by " : TotalTime + " mins by " + journeyType + " from " + (document.getElementById('form_CP').value).toUpperCase() + "<br/><br/>";
            popHTML += myPOIsearch.result.VMPOIs[x].displayAddress + "<br/>";


            LeftHTML += '<div class="divMapInfo"><div class="divLeftMapNo">' + (x + 1) + '.' + '</div><div class="divLeftMapInfo">' + myPOIsearch.result.VMPOIs[x].name + '</div><div class="divRightMapInfo"><a href="#?" id="a' + x + '" onclick="ShowPoPup(event,\'a' + x + '\',\'div' + x + '\')">Details</a></div><div class="divMapInfoPOPUP" id="div' + x + '"><div class="divPOPCancelButton"><a href="#?" class="windowButton" style="float:right" onclick="hide(\'div' + x + '\')"></a></div>' + popHTML + '<br/><br/><a href="#?"  onclick="setLink(\'true\',\'' + myPOIsearch.result.VMPOIs[x].name + '\',\'' + myPOIsearch.result.VMPOIs[x].id + '\',\'div' + x + '\')">Travel from this stop</a><br/><a href="#?" onclick="setLink(\'false\',\'' + myPOIsearch.result.VMPOIs[x].name + '\',\'' + myPOIsearch.result.VMPOIs[x].id + '\',\'div' + x + '\')">Travel to this stop</a></div></div></div>';
            j = 0;
            iconsHTML = "";
            while (j < myPOIsearch.result.VMPOIs[x].metaNums.length) {
                if ((myPOIsearch.result.VMPOIs[x].definition.getCriteriaByNum(j + 1))
                            && (myPOIsearch.result.VMPOIs[x].definition.getCriteriaByNum(j + 1).isDisplay)
                            && (myPOIsearch.result.VMPOIs[x].definition.getCriteriaByNum(j + 1).type == 0)
                            && (myPOIsearch.result.VMPOIs[x].metaNums[j] != 0)) {
                    iconsHTML += "<img src='/viamichelin/client_data/TEST_FO/113981/" + myPOIsearch.result.VMPOIs[x].definition.language + "/images/" + myPOIsearch.result.VMPOIs[x].definition.getCriteriaByNum(j + 1).number + "_" + myPOIsearch.result.VMPOIs[x].metaNums[j] + ".gif' align='absmiddle' title='" + myPOIsearch.result.VMPOIs[x].definition.getCriteriaByNum(j + 1).getLibValue(myPOIsearch.result.VMPOIs[x].metaNums[j]) + "'/> ";

                }
                j++;
            }
            poiHTML += "<br>" + iconsHTML;
            poiHTML += "</div>";
            myPOIlayer = myPOIsearch.result.VMPOIs[x].getLayer();
            myPOIlayer.setExpandLayer(poiHTML);
            map.addLayer(myPOIlayer);
            x++;
            CalculateITI();
        }
        else {
            x++;
            CalculateITI();
        }
    }
    catch (ex) {
        x++;
        CalculateITI();
    }
}
function ShowPoPup(e, ControlID, DivID) {
    if (lastPOPUPID != "")
        document.getElementById(lastPOPUPID).style.display = 'none';
    //    document.getElementById(DivID).style.left = e.clientX + 'px';
    //    document.getElementById(DivID).style.top = e.clientY + document.documentElement.scrollTop + 'px';
    var pos = $("#" + ControlID).offset();
    var width = $("#" + ControlID).width();
    var ScreenWidth = ((screen.width - 820) / 2) - 50;
    $("#" + DivID).css({ "left": (pos.left) - ScreenWidth + "px", "top": (pos.top - 75) + "px" });
    document.getElementById(DivID).style.display = 'block';
    lastPOPUPID = DivID;
}
function hide(obj) {
    document.getElementById(obj).style.display = 'none';
}

function showStops() {
    document.getElementById('form_CP').value = document.getElementById('txtZipCode').value;
    startSearch();
}
function setDivStatus() {
    if (document.getElementById("yourmapdiv") != null)
        document.getElementById("yourmapdiv").innerHTML = "";
    if (document.getElementById("dvContent") != null)
        document.getElementById("dvContent").style.display = 'none';
    if (document.getElementById("mapLoader") != null)
        document.getElementById("mapLoader").style.display = "block";
}
function setLink(IsFrom, val, LocationID, DivID) {
    if (DivID == undefined)
        DivID = null;
    if (IsFrom == 'true') {
        document.getElementById('txtFrom').value = val;
        document.getElementById('fromc').value = LocationID;
        IsFromLightBox = true;
        //document.getElementById('divtxtfrom').className = 'lblwidthtextHightlight';
        //var t1 = setTimeout('document.getElementById("divtxtfrom").className = "lblwidthtext"', 5000);
				document.getElementById('txtFrom').className = 'lblwidthtextHightlightHome';
        var t1 = setTimeout('document.getElementById("txtFrom").className = "tr_input"', 5000);
    }
    else {
        document.getElementById('txtTo').value = val;
        document.getElementById('toc').value = LocationID;
        IsToLightBox = true;
        //document.getElementById('divtxtto').className = 'lblwidthtextHightlight';
        //var t1 = setTimeout('document.getElementById("divtxtto").className = "lblwidthtext"', 5000);
				document.getElementById('txtTo').className = 'lblwidthtextHightlightHome';
        var t1 = setTimeout('document.getElementById("txtTo").className = "tr_input"', 5000);
    }

    if (DivID != null) {
        hide(DivID);
    }
    hideLightbox();
}
function RestartEvents() {
    var form_CP = document.getElementById("form_CP").value;
    if (form_CP.trim() == "") {
        document.getElementById("errormsg").style.display = 'block';
        return false;
    }
    else {
        document.getElementById("errormsg").style.display = 'none';
        geosearch = null;
        myaddress = null;
        Start_geocoder = null;
        poiDefinition = null;
        myPOIsearch = null;
        map = null;
        myiti = null;
        geocoder_search();
    }
}

function IsVisiblePopUp(chk) {
    if (!chk.checked) {
        var imgArr = document.getElementsByTagName('img');
        for (var i = 0; i < imgArr.length; i++) {
            if (imgArr[i].src == 'http://www2.viamichelin.com/apijs/res/gbr/img/map/poiEXCEP.gif')
                imgArr[i].style.display = "none";
        }
    }
    else {
        var imgArr = document.getElementsByTagName('img');
        for (var i = 0; i < imgArr.length; i++) {
            if (imgArr[i].src == 'http://www2.viamichelin.com/apijs/res/gbr/img/map/poiEXCEP.gif')
                imgArr[i].style.display = "block";
        }
    }
}
var ClearTimer;

function SetZoom() {
    if (ZoomLevel != '-1')
        ClearTimer = setTimeout('setMapZoom()', 4000);
}
function setMapZoom() {
    map.changeMapScale(ZoomLevel);
    clearTimeout(ClearTimer);
} is_ie = (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent));




is_ie5 = (is_ie && /msie 5\.0/i.test(navigator.userAgent));
/// detect Opera browser
is_opera = /opera/i.test(navigator.userAgent);
/// detect KHTML-based browsers
is_khtml = /Konqueror|Safari|KHTML/i.test(navigator.userAgent);

function stopEvent(ev) {
    //var ev=(window.event)?event:ev;
    ev || (ev = window.event);
    if (is_ie) {
        ev.cancelBubble = true;
        ev.returnValue = false;
    } else {
        ev.preventDefault();
        ev.stopPropagation();
    }
    //return false;
}

function Button_Click(e) {
    try {
        var evt = e ? e : window.event;
        var evtCode = (evt.which) ? evt.which : evt.keyCode;
        if (evtCode == 13) {
            document.getElementById('btnSearchBusStop').focus();
            //document.getElementById('btnSearchBusStop').click();
        }
    }
    catch (ex)
    { }
}

function BusStop_Click(e) {
    var evt = e ? e : window.event;
    var evtCode = (evt.which) ? evt.which : evt.keyCode;
    if (evtCode == 13) {
        document.getElementById('btnfindStops').focus();
        document.getElementById('btnfindStops').click();
        return false;
    }
    else
        return true;


}