﻿//-------------------Start up--------------------------------------------------------


//----------------------------------------------------------------------------------------


function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}


function appendMiniMapToClinicList(sClinicsToShowCount) {
    var iLiClinics = $jQ("#ulContainerList").find(".liItems")
    iCounter = 0;
    for (var ii = 0; ii < $jQ(iLiClinics).length; ii++) {
        iCounter++;
        var sLat = $jQ(iLiClinics[ii]).attr("lat");
        var sLon = $jQ(iLiClinics[ii]).attr("lon");
        var arrIdClinic = $jQ(iLiClinics[ii]).attr("id").split("_");

        if ($jQ("#myMap_" + arrIdClinic[1]).length == 0) {
            GetMapMini(sLat, sLon, iCounter, "divMiniMap_" + arrIdClinic[1]);
        }
        if (sClinicsToShowCount == iCounter.toString()) {
            break;
        }
    }
    $jQ("#hclContent").find(".MapTypeId_m").find(":input").hide();

}


function addJavascript(jsname, pos) {
    var th = document.getElementsByTagName(pos)[0];
    var s = document.createElement('script');
    s.setAttribute('type', 'text/javascript');
    s.setAttribute('src', jsname);
    th.appendChild(s);
}



function SetToolTip(elementNameClass) {
    $jQ(elementNameClass).css("cursor", "help");
    $jQ(elementNameClass).qtip({
        prerender: true,
        content: this.title,
        style: { classes: 'ui-tooltip-blue' },
        position: { my: 'top center', at: 'bottom center', viewport: $jQ(window)
        }
    })
}

function SetToolTipWithExternal(elementNameClass, externalElement) {
    $jQ(elementNameClass).css("cursor", "help");
    $jQ(elementNameClass).qtip({
        prerender: true,
        content: $jQ(externalElement).val(),
        style: { classes: 'ui-tooltip-blue' },
        position: { my: 'top center', at: 'bottom center', viewport: $jQ(window)
        }
    })
}




function MakeGeocodeRequest() {
    var sBingKey = $jQ("#hiddenBingMapKey").val();
    var sBingMapCulture = $jQ("#hiddenBingMapCulture").val();
    var sBingMapCountryRegion = $jQ("#hiddenBingMapCountryRegion").val();

    var sSearchString = $jQ("#txtQuery").val();
    sSearchString = sSearchString.replace(":", "");
    if (sSearchString.length > 1) {
        if (sSearchString.toLowerCase().indexOf(", " + $jQ("#hiddenBingMapCountry").val()) > 0 || sSearchString.toLowerCase().indexOf("," + $jQ("#hiddenBingMapCountry").val()) > 0)
        { }
        else {
            sSearchString = sSearchString + ", " + $jQ("#hiddenBingMapCountry").val();
        }
    }

   //alert(sSearchString);

    var geocodeRequest = "http://dev.virtualearth.net/REST/v1/Locations/" + encodeURIComponent(sSearchString) + "?output=json&jsonp=GeocodeCallback&countryRegion=" + sBingMapCountryRegion + "&c=" + sBingMapCulture + "&key=" + sBingKey;

    CreateJavaScriptInclude(geocodeRequest);
}

function GeocodeCallback(result) {
    $jQ("#divResults").hide();
    $jQ("#divResults").html("");
    try //In case the service returns nothing - happens!
        {
            var sAddress = $jQ("#txtQuery").val();
        var sResults = result.resourceSets[0].estimatedTotal;
         switch (sResults) {
            case 0: 
                
               // $jQ("#hclForm").attr("action", "");
                $jQ("#hiddenSearchAddress").val(sAddress);
                $jQ("#hiddenSearchAddressLattitude").val("");
                $jQ("#hiddenSearchAddressLongitude").val("");
                $jQ("#hiddenHclNoResult").val(true);
                document.forms[0].submit();
                break;
            case 1:
                var location_name = result.resourceSets[0].resources[0].address.formattedAddress;
                var bbox = result.resourceSets[0].resources[0].bbox;
                var objCoords = result.resourceSets[0].resources[0].point;
                /*
                $jQ("#hiddenSearchAddress").val(location_name);
                $jQ("#hiddenSearchAddressLattitude").val(objCoords.coordinates[0]);
                $jQ("#hiddenSearchAddressLongitude").val(objCoords.coordinates[1]);
                $jQ("#hiddenHclNoResult").val(false);
                document.forms[0].submit();
                */
                SendCoordinates(objCoords.coordinates[0], objCoords.coordinates[1], location_name, encodeURIComponent(sAddress));

                break;
            default: // more than 1 result
                DisableScroll();
                document.getElementById("divResults").style.display = "inline";
                var divElement = document.createElement("div");
                divElement.className = "geoDidYouMean";
                divElement.innerHTML = "Did you mean..";
                document.getElementById("divResults").appendChild(divElement);

                var ulElement = document.createElement("ul");
                ulElement.setAttribute("id", "ulResult");
                for (var i = 0; i < result.resourceSets[0].resources.length; i++) {
                    var location_name = result.resourceSets[0].resources[i].address.formattedAddress;
                    var arrlocation_name = location_name.split(", ");
                    var bbox = result.resourceSets[0].resources[i].bbox;
                    var objCoords = result.resourceSets[0].resources[i].point;
                    var liElement = document.createElement("li");
                    var aHrefElement = document.createElement("a");
                    aHrefElement.setAttribute("id", "link_" + i);
                    aHrefElement.setAttribute("href", "javascript:SendCoordinates('" + objCoords.coordinates[0] + "','" + objCoords.coordinates[1] + "','" + location_name + "','" + encodeURIComponent(sAddress)+ "');");
                    aHrefElement.className = "DataItems"
                    aHrefElement.innerHTML = location_name;
                    liElement.appendChild(aHrefElement);
                    ulElement.appendChild(liElement);
                }
                document.getElementById("divResults").appendChild(ulElement);
                break;
        }
        $jQ('.DataItems').keydown(function(event, obj) {
            if (event.keyCode == 40) {
                var clicked = $jQ(this);

                var arrId = clicked.attr("id").split("_");
                var id = arrId[1];
                id = id - 0;

                $jQ(this).blur(function() {
                    $jQ(this).removeClass("ComboBoxDropDownActive");
                });
                id = id - 0 + 1;
                $jQ('#link_' + id).focus();
                $jQ('#link_' + id).addClass("ComboBoxDropDownActive");
                DisableScroll();
            }
            if (event.keyCode == 38) {
                $jQ(this).blur(function() {
                    $jQ(this).removeClass("ComboBoxDropDownActive");
                });
                var clicked = $jQ(this);
                var arrId = clicked.attr("id").split("_");
                var id = arrId[1];
                id = id - 1;
                if (id < 0) {
                    $jQ("#txtQuery").focus();
                }
                else {
                    $jQ("#link_" + id).focus();
                    $jQ("#link_" + id).addClass("ComboBoxDropDownActive");
                    DisableScroll();
                }
            }
        });
    }
    catch (e) {
    alert(e)
       // MakeGeocodeRequest();
    }
}

function CreateJavaScriptInclude(request) {
    var script = document.createElement("script");
    script.setAttribute("type", "text/javascript");
    script.setAttribute("src", request);
    document.body.appendChild(script);
}

var timerDivSearchResult = 0;

function ResetCloseSearchResultDiv(obj) {

    clearTimeout(timerDivSearchResult);
    timerDivSearchResult = 0;
}

function CloseSearchResultDiv(obj) {
    var objElementId = $jQ(obj).attr("id");
    var DivElement = "$jQ('#" + objElementId + "').hide();EnableScroll();";
    timerDivSearchResult = setTimeout(DivElement, 2000);
}

function SendCoordinates(lat, lon, locationName, locationNameOriginal) {
    $jQ("#hiddenSearchAddress").val(locationName);
    $jQ("#hiddenSearchAddressLattitude").val(lat);
    $jQ("#hiddenSearchAddressLongitude").val(lon);
    $jQ("#hiddenSearchAddressOriginal").val(locationNameOriginal);
    $jQ("#hiddenHclNoResult").val(false);

    document.forms[0].submit();
}




function GetMapMini(lat, lon, enumValue, parentElementId) {

    var sBingKey = $jQ("#hiddenBingMapKey").val();
    parentElement = document.getElementById(parentElementId);
    var arrParentElement = $jQ(parentElement).attr("id").split("_");
    var iIdUnique = arrParentElement[1];
    var divMap = document.createElement("div");
    divMap.className = "divMapHolder";
    divMap.setAttribute("id", "myMap_" + iIdUnique);
    divMap.setAttribute("lat", lat);
    divMap.setAttribute("lon", lon);

    $jQ(divMap).bind("click", { IdUnique: iIdUnique, Enum: enumValue, Lat: lat, Lon: lon }, function(event) {
        showLargeMap(event.data.IdUnique,  event.data.Lat, event.data.Lon);
    });
    var divMapOverlay = document.createElement("div");
    divMapOverlay.setAttribute("id", "divMap_" + iIdUnique);
    divMapOverlay.className = "divOverlay noOpacity";
    divMap.appendChild(divMapOverlay);

    var divMapOverlayPlusMinus = document.createElement("div");
    divMapOverlayPlusMinus.setAttribute("id", "divPlusMinus_" + iIdUnique);
    divMapOverlayPlusMinus.className = "divPlusMinus plusSign";
    divMap.appendChild(divMapOverlayPlusMinus);

    var divMapOverlaySmallPin = document.createElement("div");
    divMapOverlaySmallPin.setAttribute("id", "divOverlaySmallPin_" + iIdUnique);
    divMapOverlaySmallPin.className = "divOverlaySmallPin";
    divMapOverlaySmallPin.innerHTML = enumValue.toString();
    divMap.appendChild(divMapOverlaySmallPin);
    parentElement.appendChild(divMap);

    var map = null;
    // Initialize the map
    map = new Microsoft.Maps.Map(document.getElementById("myMap_" + iIdUnique), { credentials: sBingKey, backgroundColor: '#ffffff', showCopyright: false, enableClickableLogo: false, disableKeyboardInput: true, disableTouchInput: true, showDashboard: false, showMapTypeSelector: false, showScalebar: false, fixedMapPosition: true, disableUserInput: true, disableMouseInput: false, enableSearchLogo: false });
    var loc = new Microsoft.Maps.Location(lat, lon);
    map.setView({ center: loc, zoom: 14 });
}



function GetMapLarge(idUnique, lat, lon) {
    var sBingKey = $jQ("#hiddenBingMapKey").val();
    var parentElement = $jQ("#divContainerContent_" + idUnique);
    if ($jQ(parentElement).length == 1) {
        var divMap = document.createElement("div");
        divMap.className = "divMapLarge";
        $jQ(divMap).attr("id", "divLargeMap_" + idUnique);
        $jQ(parentElement).append(divMap);
    }
    var enumValue = $jQ("#imgPin_" + idUnique).text();
    var map = null;    
    // Initialize the map
    map = new Microsoft.Maps.Map(document.getElementById("divLargeMap_" + idUnique.toString()), {
        credentials: sBingKey,
        backgroundColor: '#ffffff',
        showCopyright: false,
        enableClickableLogo: false,
        showDashboard: true,
        showMapTypeSelector: false,
        showScalebar: false,
        fixedMapPosition: false,
        disableUserInput: false,
        enableSearchLogo: false
    });
    var loc = new Microsoft.Maps.Location(lat, lon);
    var pin = new Microsoft.Maps.Pushpin(loc, { icon: 'images/mini_pin_magenta.png', width: 25, height: 34, text: enumValue.toString(),typeName:'MapPushPin', textOffset: new Microsoft.Maps.Point(0, 5), draggable: false });
    map.entities.push(pin);
    // Center the map on the location
    map.setView({ center: loc, zoom: 14 });

    $jQ("#divLargeMap_" + idUnique.toString()).append("<div id='divMapSolutionButtonClose'><img src='images/minus_magenta.png' style='cursor:pointer;' alt='' onclick='resetAllFields()'/></div>");

   // window.setTimeout(function () {
    $jQ("#hclContent").find(".MapTypeId_m").find(":input").hide();
   // }, 100);

}



function showLargeMap(idUnique, lat, lon) {
    //Netminers
    $netminers.push(
        ['postPageView', 'HCL > ' + $jQ('#hiddenViewType').val() + ' > show map > ' + idUnique]
        );
    //---------



    var bShowMap = false;
    if ($jQ("#divLargeMap_" + idUnique).length == 0) {
        //show Map
        bShowMap = true;
    }
    
    resetAllFields();

    if (bShowMap == true) {
        document.getElementById("liMapLink_" + idUnique).className = "activeLink";
        document.getElementById("liMapLink_" + idUnique).childNodes[0].className = "activeLinkHref";
      
        //highlight active clinic pin
        var imgPinBig = $jQ("#divItemContainerList").parent().find(".imgPinBigInactive");
        for (ii = 0; ii < imgPinBig.length; ii++) {
            var arrImgPinBig = $jQ(imgPinBig[ii]).attr("id").split("_");
            if (arrImgPinBig[1] == idUnique.toString()) {
                $jQ(imgPinBig[ii]).removeClass("imgPinBigInactive").addClass("imgPinBigActive");
            }
        }

        var divOverlay = $jQ(".divMapHolder").parent().find(".divOverlay");
        for (ii = 0; ii < divOverlay.length; ii++) {
            var arrDivOverlay = $jQ(divOverlay[ii]).attr("id").split("_");
            if (arrDivOverlay[1] == idUnique.toString()) {
                $jQ(divOverlay[ii]).removeClass("noOpacity").addClass("Opacity");

            }
        }
        var divPlusMinus = $jQ(".divMapHolder").parent().find(".divPlusMinus");
        for (ii = 0; ii < divPlusMinus.length; ii++) {
            var arrDivPlusMinus = $jQ(divPlusMinus[ii]).attr("id").split("_");
            if (arrDivPlusMinus[1] == idUnique.toString()) {
               
                $jQ(divPlusMinus[ii]).removeClass("plusSign").addClass("minusSign");
            }
           
        }
        GetMapLarge(idUnique, lat, lon);
        SetActiveClinicId(idUnique);
    }
    else {
        SetActiveClinicId(); 
    
    }
}

function GetEmailForm(idUnique) {

    //Netminers
    $netminers.push(
        ['postPageView', 'HCL > ' + $jQ('#hiddenViewType').val() + ' > show email form > ' + idUnique]
        );
    //---------



    var parentElement = $jQ("#divContainerContent_" + idUnique);
    var bCurrentOpen = false;
    if ($jQ("#divContainerContent_" + idUnique).find("#divSendEmailForm").length == 1) {
        bCurrentOpen = true;
    }

    resetAllFields();

    if (bCurrentOpen == false) {
        //highlight active clinic pin
        var imgPinBig = $jQ("#divItemContainerList").parent().find(".imgPinBigInactive");
        for (ii = 0; ii < imgPinBig.length; ii++) {
            var arrImgPinBig = $jQ(imgPinBig[ii]).attr("id").split("_");
            if (arrImgPinBig[1] == idUnique.toString()) {
                $jQ(imgPinBig[ii]).removeClass("imgPinBigInactive").addClass("imgPinBigActive");
            }
        }
        document.getElementById("liEmailLink_" + idUnique).className = "activeLink";
        document.getElementById("liEmailLink_" + idUnique).childNodes[0].className = "activeLinkHref";
        $jQ(parentElement).append($jQ("#divSendEmailForm"));
        $jQ("#divSendEmailForm").fadeIn("slow");
        $jQ("#btnHclSendEmailSend").unbind("click").bind("click", { UniqueId: idUnique }, function(event) {

        
        SendInfoAsEmail(event.data.UniqueId);
        
        });
        
        var UlElement = $jQ("#liDataItem_" + idUnique).find("ul").find("li");

        var sClinicDetails = $jQ("#hiddenLanguageMessageIntro").val() + "\n\r\n\r";
        var i = 0;
        $jQ.each(UlElement, function (idx, itm) {
            i++;
            if ($jQ(this).attr("class") == "liPrintLink")
            { return false; }
            if ($jQ(this).attr("class") != "HclClinicLabels") {


                if (itm.innerHTML.indexOf("<A", 0) == 0 || itm.innerHTML.indexOf("<a", 0) == 0) {
                    sClinicDetails += $jQ(this).text() + "\n\r";
                }
                else {
                    sClinicDetails += itm.innerHTML.replace("<BR>", "\n").replace("<BR>", "\n").replace("</BR>", "\n").replace("<br>", "\n").replace("</br>", "\n") + "\n";
                }
               
            }

        });
        // sClinicDetails = Url.decode(sClinicDetails);

        sClinicDetails = sClinicDetails.replace(/&amp;/g, "&");
        $jQ("#txtHclSendEmailOptionalMessage").val(sClinicDetails);
        
        
    }
}

function showMapSolution() {
    var sBingKey = $jQ("#hiddenBingMapKey").val();
   
    $jQ("#divMapSolution").empty();
    parentElement = document.getElementById("divMapSolution");

    mapSolution = new Microsoft.Maps.Map(parentElement, {
        credentials: sBingKey,
        backgroundColor: '#ffffff',
        showCopyright: false,
        enableClickableLogo: false,
        showDashboard: true,
        showMapTypeSelector: false,
        showScalebar: true,
        fixedMapPosition: false,
        disableUserInput: false,
        enableSearchLogo: false
    });
 
    var addNavButton = function(mapElement, content, onclick) {
        $jQ(mapElement).find('.OverlaysTL').append(
        $jQ('<div>').addClass('NewNavBarSeeAll').append(
        // Add a Separator between this button and any existing buttons
        $jQ('<span>').addClass('NavBar_separator')
    ).append(
        // Add the Custom Button itself
        $jQ('<a>').attr('href', '#').addClass('NavBar_button').
            append($jQ('<span>').html(content).click(onclick))
    ));
    };
    window.setTimeout(function () {
        // Add Custom Button to NavBar
        addNavButton(
        document.getElementById('divMapSolution'), // <- Maps DIV
        $jQ('#hiddenBingMapViewAll').val(), // <- Content of Button - You can put HTML in here if you want
        function () { // <- Method to call during buttons Click event
            ShowPushPinsOnMapSolution($jQ("#hiddenClinicShow").val());
        }
    ); 

    }, 100);
    $jQ("#hclContent").find(".MapTypeId_m").find(":input").hide();





}



function showMoreClinics() {
    var objClinicItems = $jQ("#divItemContainerList").find(".liItems");
    var sShowDataType = $jQ("#hiddenShowDataAs").val();   //either "list" or "map"
    var sClinicsShow = $jQ("#hiddenClinicShow").val();
    var iClinicsShow = sClinicsShow - 0;
    if (iClinicsShow < objClinicItems.length) {
        iClinicsShow += 5;
        $jQ("#hiddenClinicShow").val(iClinicsShow);
        $jQ("#spanDisplaySearchResultLineCount").html(iClinicsShow.toString());
    }

        var i = 0;
        $jQ.each(objClinicItems, function(idx, itm) {
            i++;
            var arrIdUnique = $jQ(this).attr("id").split("_");

            if (i <= iClinicsShow) {
                hclHideClinic(arrIdUnique[1], false, sShowDataType);
            }
            else
            { hclHideClinic(arrIdUnique[1], true, sShowDataType); }

            if (i == iClinicsShow) {
                $jQ.scrollTo("#" + $jQ(this).attr("id"));
            }
        });
    if (sShowDataType == "list") {
        appendMiniMapToClinicList(iClinicsShow.toString());
        hclSortClinicsBy();
    }
    else {
        ShowPushPinsOnMapSolution(iClinicsShow);
    }
}


function showLessClinics() {
    var objClinicItems = $jQ("#divItemContainerList").find(".liItems");
    var sShowDataType = $jQ("#hiddenShowDataAs").val();   //either "list" or "map"
    var sClinicsShow = $jQ("#hiddenClinicShow").val();
    var iClinicsShow = sClinicsShow - 0;

    if (iClinicsShow > 5) {
        iClinicsShow -= 5;
        $jQ("#hiddenClinicShow").val(iClinicsShow);
        $jQ("#spanDisplaySearchResultLineCount").html(iClinicsShow.toString());

    }
        var i = 0;
        $jQ.each(objClinicItems, function(idx, itm) {
            i++;
            var arrIdUnique = $jQ(this).attr("id").split("_");
            if (i <= iClinicsShow) {
                hclHideClinic(arrIdUnique[1], false, sShowDataType)
            }
            else
            { hclHideClinic(arrIdUnique[1], true, sShowDataType) }
        });
 
    if (sShowDataType == "list") {
        appendMiniMapToClinicList(iClinicsShow.toString());
        hclSortClinicsBy();
    }
    else {
        ShowPushPinsOnMapSolution(iClinicsShow);
    }
}


function validateEmail(email) {
    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if (!filter.test(email)) { return false; }
    else { return true; }
}



function SendInfoAsEmail(idUnique) {
    var sName = $jQ("#txtHclSendEmailName").val();
    var sYourEmail = $jQ("#txtHclSendEmailYourEmail").val();
    var sRecipentsEmail = $jQ("#txtHclSendEmailRecipentsEmail").val();
    var sOptionalMessage = $jQ("#txtHclSendEmailOptionalMessage").val();
    var sErrorMsg = "";     

    if ($jQ.trim(sName).length < 2) {
        sErrorMsg += $jQ("#divHclEmailYourName").html() + ": " + $jQ("#hiddenLanguageEmailErrorInvalidName").val() + "<br>";
        $jQ("#txtHclSendEmailName").addClass("HclSendEmailInputError");
    }
    else {
        $jQ("#txtHclSendEmailName").removeClass("HclSendEmailInputError");
    }

    if (validateEmail(sYourEmail) == false) {
        sErrorMsg += $jQ("#divHclEmailYourEmail").html() + ": " + $jQ("#hiddenLanguageEmailErrorInvalidEmail").val() + "<br>";
        $jQ("#txtHclSendEmailYourEmail").addClass("HclSendEmailInputError");
    }
    else {
        $jQ("#txtHclSendEmailYourEmail").removeClass("HclSendEmailInputError");
    }

    if (validateEmail(sRecipentsEmail) == false) {
        sErrorMsg += $jQ("#divHclEmailRecipentsEmail").html() + ": " + $jQ("#hiddenLanguageEmailErrorInvalidEmail").val() + "<br>";
        $jQ("#txtHclSendEmailRecipentsEmail").addClass("HclSendEmailInputError");
    }
    else {
        $jQ("#txtHclSendEmailRecipentsEmail").removeClass("HclSendEmailInputError");
    }


    if (sErrorMsg.length > 0) {
        $jQ("#divSendEmailFormStatusMsg").removeClass("divSendEmailFormStatusMsgSuccess").addClass("divSendEmailFormStatusMsgError");
        $jQ("#divSendEmailFormStatusMsg").html(sErrorMsg);
    }
    else {
            //No errors - rdy to send
        $jQ("#btnHclSendEmailSend").attr("disabled", "disabled");


        $jQ.ajax({
            type: "POST",
            url: "HclDoAjax.aspx",
            cache: false,
            dataType: "html",
            data: ({ type: 'sendmail', id: idUnique, name: encodeURIComponent(sName), youremail: encodeURIComponent(sYourEmail), recipentsemail: encodeURIComponent(sRecipentsEmail), message: encodeURIComponent(sOptionalMessage) }),
            beforeSend: function () {
                // Handle the beforeSend event
            },
            success: function (data) {
                var arrData = data.split("$¤^");
                if (arrData[0] == "success") {
                    $jQ("#btnHclSendEmailSend").removeAttr("disabled");
                    $jQ("#divSendEmailFormStatusMsg").removeClass("divSendEmailFormStatusMsgError").addClass("divSendEmailFormStatusMsgSuccess");
                    $jQ("#divEmailFormContent").hide();
                    $jQ("#divEmailSentMessage").show();
                    //Netminers
                    $netminers.push(
                    ['postPageView', 'HCL > ' + $jQ('#hiddenViewType').val() + ' > email sent > ' + idUnique]
                    );
                    //---------

                }
                else {
                    $jQ("#btnHclSendEmailSend").removeAttr("disabled");
                    $jQ("#divSendEmailFormStatusMsg").removeClass("divSendEmailFormStatusMsgSuccess").addClass("divSendEmailFormStatusMsgError");

                    var sErrorMsg = "";
                    if (arrData[1] == "NotSent") {
                        sErrorMsg = $jQ("#hiddenLanguageEmailNotSent").val();
                    }
                    else if (arrData[1] == "AlreadySent") {
                        sErrorMsg = $jQ("#hiddenLanguageEmailAlreadySent").val();
                    }
                    $jQ("#divSendEmailFormStatusMsg").html(sErrorMsg);
                }
            }, error: function (data) { alert('error'); },
            complete: function (data) {
            }
        });
    }
}


function ShowHclData(dataType) {

    var sDataType = "showdata=list"
    if (dataType == 1) { sDataType = "showdata=map"; }
       var sCurrentUrl = location.href;
       var arrCurrentUrl = location.href.split("?");

       if (arrCurrentUrl.length > 1) {
        sCurrentUrl = arrCurrentUrl[0];
        var arrQuery = arrCurrentUrl[1].split("&");
        var sNewQuery = "";
        var bQueryParameterFoundShowData = false;
        var bQueryParameterFoundClinicsCount = false;
        var bQueryParameterFoundActiveClinic = false;
        for (ii = 0; ii < arrQuery.length; ii++) {
            if (ii > 0 && $jQ.trim(arrQuery[ii]).length > 0) {
                sNewQuery += "&";
            }
            if (arrQuery[ii].indexOf("showdata=") != -1) {
                sNewQuery += sDataType;
                bQueryParameterFoundShowData = true;
            }
            else if (arrQuery[ii].indexOf("clinicscount=") != -1) {
                sNewQuery += "clinicscount=" + $jQ("#hiddenClinicShow").val();
                bQueryParameterFoundClinicsCount = true;
            }
            else if (arrQuery[ii].indexOf("activeclinic=") != -1) {
                sNewQuery += "activeclinic=" + $jQ("#hiddenActiveClinic").val();
                bQueryParameterFoundActiveClinic = true;
            }
            else {
                sNewQuery += arrQuery[ii];
            }
        }
        if (bQueryParameterFoundShowData == false) {
            sNewQuery += "&" + sDataType;
        }
        if (bQueryParameterFoundClinicsCount == false) {
            sNewQuery += "&clinicscount=" + $jQ("#hiddenClinicShow").val();
        }
        if (bQueryParameterFoundActiveClinic == false) {
            sNewQuery += "&activeclinic=" + $jQ("#hiddenActiveClinic").val();
        }
        document.location.href = sCurrentUrl + "?" + sNewQuery;

    }
    else {
        sCurrentUrl = sCurrentUrl + "?" + sDataType;
        document.location.href = sCurrentUrl;
    }
}

function AddPushpinsMapSolution(idUnique, lat, lon, enumValue) {
    var loc = new Microsoft.Maps.Location(lat, lon);
    var pin = new Microsoft.Maps.Pushpin(loc, { icon: 'images/mini_pin_magenta.png', width: 25, height: 34,typeName:'MapSolutionPushpin', text: enumValue.toString() , zIndex: 200 - enumValue, textOffset: new Microsoft.Maps.Point(0, 5), draggable: false });
    var pushpinClick = Microsoft.Maps.Events.addHandler(pin, 'click', displayEventInfo);
    mapSolution.entities.push(pin);
}

function ShowPushPinsOnMapSolution(NumberToDisplay) {
    mapSolution.entities.clear();
    var objClinicItems = $jQ("#divItemContainerList").find(".liItems.hclClinicShow");
    if (objClinicItems.length >0) {
        var ArrContainerMapDataBounds = new Array();
        var enumValue = 0;
        for (ii = 0; ii < objClinicItems.length; ii++) {
            enumValue++;
            var sliDataItemId = $jQ(objClinicItems[ii]).attr("id");
            var arrliDataItemId = sliDataItemId.split("_");
            var idUnique = arrliDataItemId[1];
            var sLat = $jQ(objClinicItems[ii]).attr("lat");
            var sLon = $jQ(objClinicItems[ii]).attr("lon");
            
            AddPushpinsMapSolution(idUnique, sLat, sLon,enumValue);
            ArrContainerMapDataBounds[ii] = new Microsoft.Maps.Location(sLat, sLon);
        }
        mapSolution.setView({ bounds: Microsoft.Maps.LocationRect.fromLocations(ArrContainerMapDataBounds) });
    }
}


displayEventInfo = function(e) {
    ///imgPinBigInactive
    var obj = e.target;
    var info = "Events info - " + e.eventName + "\n";
    info += "Target : " + obj.getText();
    info += "Target : " + obj;

    var objLocation = obj.getLocation();
    mapSolution.setView({ center: new Microsoft.Maps.Location(objLocation.latitude, objLocation.longitude), zoom: 15 });

    var temp = $jQ("#ulContainerList").parent().find(".hclClinicShow").find(".imgPinBigInactive, .imgPinBigActive")
    for (ii = 0; ii < temp.length; ii++) {
        if ($jQ(temp[ii]).text() == obj.getText()) {
            var sId = $jQ(temp[ii]).attr("id");
            if (sId.length > 0) {
                var arrId = sId.split("_");
                var id = arrId[1];
                showSingleClinicOnMapSolution(id);
            }
            break;
        }
    }
}

function showSingleClinicOnMapSolution(idUnique) {
    //Netminers
    $netminers.push(
        ['postPageView', 'HCL > ' + $jQ('#hiddenViewType').val() + ' > show single clinic > ' + idUnique]
        );
    //---------

    $jQ("#divItemContainerList").find(".liItems.hclClinicShow").addClass("hclMapSolutionHide");
    $jQ("#liDataItem_" + idUnique).removeClass("hclMapSolutionHide"); 
}

function SetActiveClinicId(enumValue) {
    $jQ("#hiddenActiveClinic").val(enumValue);
}

function hclSortClinicsBy() {
    
    var arrDropdownValue = $jQ("#hclSelectSortBy").val().split("|");
    var attributeId = arrDropdownValue[0];
    var type = arrDropdownValue[1];
    var iClinicsShow = $jQ("#hiddenClinicShow").val();
    var objListItemsShow = $jQ("#ulContainerList").parent().find(".hclClinicShow");
    var objListItemsNotShow = $jQ("#ulContainerList").parent().find(".hclClinicNotShow");
    var mylist = $jQ("#ulContainerList");
    objListItemsShow.sort(function(a, b) {
        if (type == "id") {
            var tempcompA = $jQ(a).attr(attributeId).split("_");
            var tempcompB = $jQ(b).attr(attributeId).split("_");
            var compA = parseFloat(tempcompA[1]);
            var compB = parseFloat(tempcompB[1]);
        }
        else if (type == "number") {
            var compA = parseFloat($jQ(a).attr(attributeId));
            var compB = parseFloat($jQ(b).attr(attributeId));
        }
        else {
            var compA = $jQ(a).attr(attributeId).toUpperCase();
            var compB = $jQ(b).attr(attributeId).toUpperCase();
        }
        return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
    })
    $jQ.each(objListItemsShow, function(idx, itm) { mylist.append(itm); });
    var i = 0;
    //setting pin numbers on large pins
    var objLargePins = objListItemsShow.find(".imgPinBigInactive, .imgPinBigActive");

    $jQ.each(objLargePins, function(idx, itm) {
        i++;
        $jQ(this).html(i.toString());
    });
    //setting pin numbers on small pins

    i = 0;
    var objSmallPins = objListItemsShow.find(".divOverlaySmallPin");
    //  alert(objSmallPins.length);
    $jQ.each(objSmallPins, function(idx, itm) {
        i++;
        $jQ(this).html(i.toString());
    });

    i = 0;
    var objMapHolder = objListItemsShow.find(".divMapHolder");
    $jQ.each(objMapHolder, function(idx, itm) {
        i++;
        var arrIdUnique = $jQ(this).attr("id").split("_");
        $jQ(this).unbind("click").bind("click", { IdUnique: arrIdUnique[1], Enum: i.toString(), Lat: $jQ(this).attr("lat"), Lon: $jQ(this).attr("lon") }, function(event) {
            showLargeMap(event.data.IdUnique, event.data.Lat, event.data.Lon);
        });
    });
    mylist.append(objListItemsNotShow);
    //Setting the correct EnumValue on the pushpin after sorting. :)
    if ($jQ("#ulContainerList").find(".divMapLarge").length == 1) {
        var arrIdUnique = $jQ("#ulContainerList").find(".divMapLarge").attr("id").split("_");
        var enumValue = $jQ("#imgPin_" + arrIdUnique[1]).text();
        var divChilds = $jQ("#ulContainerList").find(".MapPushPin").children();
        $jQ(divChilds[1]).text(enumValue);
    }
}

function hclHideClinic(iIdUnique, bHideClinic, sShowDataAs) {
    if (sShowDataAs == "map") {
        //Map
        if (bHideClinic == true) {
            $jQ("#liDataItem_" + iIdUnique).removeClass("hclClinicShow").addClass("hclClinicNotShow").addClass("hclMapSolutionHide"); 
        }
        else {
                $jQ("#liDataItem_" + iIdUnique).removeClass("hclClinicNotShow").addClass("hclClinicShow").addClass("hclMapSolutionHide");
       }
    }
    else {
    //List
        if (bHideClinic == true) {
            $jQ("#liDataItem_" + iIdUnique).removeClass("hclClinicShow").addClass("hclClinicNotShow");
        }
        else {
            $jQ("#liDataItem_" + iIdUnique).removeClass("hclClinicNotShow").addClass("hclClinicShow");
        }
    }
}


function resetAllFields() //Used to deHighlight all fields and remove content inside the content Container..
{
    if ($jQ("#dummy").find(".divMapDirections").length == 0) {
        $jQ("#dummy").append($jQ("#divMapDirections"));
        $jQ("#divDirectionsContainer").html("");
        $jQ("#divMapDirections").find(':input').each(function() {
            switch (this.type) {
                case 'password':
                case 'select-multiple':
                case 'select-one':
                case 'text':
                    $jQ(this).val('');
                    break;
                case 'textarea':
                    $jQ(this).val('');
                    break;
                case 'checkbox':
                case 'radio':
                    this.checked = false;
            }
        });
    }
    $jQ("#divMapDirections").hide();


    if ($jQ("#dummy").find(".divSendEmailForm").length == 0) {
        $jQ("#dummy").append($jQ("#divSendEmailForm"));

        $jQ("#divSendEmailForm").hide();
        $jQ("#divSendEmailForm").find(':input').each(function() {
            switch (this.type) {
                case 'password':
                case 'select-multiple':
                case 'select-one':
                case 'text':
                    $jQ(this).val('');
                    break;
                case 'textarea':
                    $jQ(this).val('');
                    break;
                case 'checkbox':
                case 'radio':
                    this.checked = false;
            }
        });
    }
    $jQ("#divEmailFormContent").show();
    $jQ("#divEmailSentMessage").hide();

    $jQ(".divMapHolder").parent().find(".divOverlay").removeClass("Opacity").addClass("noOpacity");
    $jQ(".divContainerContent").empty();
    $jQ(".ulLinks").parent().find(".activeLink").children().removeClass("activeLinkHref").addClass("inactiveLinkHref");
    $jQ(".ulLinks").parent().find(".activeLink").removeClass("activeLink").addClass("inactiveLink");
    $jQ(".divMapHolder").parent().find(".divPlusMinus").removeClass("minusSign").addClass("plusSign");
    if ($jQ("#hiddenShowData").val() == "list") {
        $jQ(".divMapHolder").parent().find(".divOverlay.Opacity").removeClass("divOverlay Opacity").addClass("divOverlay noOpacity");

        $jQ(".divMapHolder").parent().find(".divPlusMinus").removeClass("minusSign").addClass("plusSign");

    }
    $jQ("#divItemContainerList").parent().find(".imgPinBigActive").removeClass("imgPinBigActive").addClass("imgPinBigInactive");


    //hide OpeningHours
    $jQ(".DivOpeningHours").addClass("DivOpeningHoursNoShow");
    //hide Misc Text
    $jQ(".DivMisc").addClass("DivMiscNoShow");

}

function GetDirections(idUnique) {

    //Netminers
    $netminers.push(
        ['postPageView', 'HCL > ' + $jQ('#hiddenViewType').val() + ' > show get directions > ' + idUnique]
        );
    //---------

    var parentElement = $jQ("#divContainerContent_" + idUnique);
    //removing all child elements within ContainerContent
    var bCurrentOpen = false;
    if ($jQ("#divContainerContent_" + idUnique).find("#divMapDirections").length == 1) {
        bCurrentOpen = true;
    }


    resetAllFields();

    if (bCurrentOpen == false) {
        //highlight active clinic pin
        $jQ("#divPrintDirections").hide();
        $jQ("#hclInputTextDirectionsFrom").val($jQ("#hiddenLanguageDirectionFrom").val());


        window.setTimeout(function () { $jQ("#hclInputTextDirectionsFrom").focus() }, 100);
        
       
        var imgPinBig = $jQ("#divItemContainerList").parent().find(".imgPinBigInactive");
        for (ii = 0; ii < imgPinBig.length; ii++) {
            var arrImgPinBig = $jQ(imgPinBig[ii]).attr("id").split("_");
            if (arrImgPinBig[1] == idUnique.toString()) {
                $jQ(imgPinBig[ii]).removeClass("imgPinBigInactive").addClass("imgPinBigActive");
            }
        }
        document.getElementById("liDirectionsLink_" + idUnique).className = "activeLink";
        document.getElementById("liDirectionsLink_" + idUnique).childNodes[0].className = "activeLinkHref";
        $jQ(parentElement).append($jQ("#divMapDirections"));
        $jQ("#divMapDirections").fadeIn("slow");
     //   $jQ("#hclInputTextDirectionsFrom").val($jQ("#hiddenSearchAddress").val());
        $jQ("#hclInputTextDirectionsTo").val($jQ("#hclClinicFormattedAddress_" + idUnique).val());
       
       /*
        $jQ("#hclInputTextDirectionsFrom").unbind("keydown").bind("keydown", function (event) {
            switch (event.keyCode) {
                case 13:
                    setDirectionsStartAndLoadMap()
                    $jQ("#hclInputTextDirectionsFrom").focus();
                    return false;
                    break;
            }
        });
        */
        var objSearchField = $jQ("#divDirectionsSuggestionHolder").find(":input");
        $jQ("#hclInputButtonDirectionSearch").unbind("click").bind("click", function (event) {

            //Setting default text in Directions from



         /*   var gedged = document.getElementById("divDirectionsSuggestionHolder");
            var gedged2 = $jQ("#divDirectionsSuggestionHolder");

            var divResultContainer = $jQ("<div></div>")
            divResultContainer.append("test");
            divResultContainer.width($jQ(objSearchField).width());
            divResultContainer.attr("id", "divDirectionsSuggestionDropdown");
            divResultContainer.addClass("SuggestionDropdown");
           */             
            });

        /*
        $jQ(objSearchField).unbind("keydown").bind("keydown", function (event) {
            switch (event.keyCode) {
                case 13: alert($jQ("#divDirectionsSuggestionDropdown").length);
                    $jQ("#divDirectionsSuggestionDropdown").show();
                    $jQ(objSearchField).focus();
                    return false;
                    break;
            }
            

            $jQ(divResultContainer).mouseover(function () {
                ResetCloseSearchResultDiv($jQ(divResultContainer));
            });
            $jQ(divResultContainer).mouseout(function () {
                CloseSearchResultDiv($jQ(divResultContainer));
            });

            gedged2.prepend(divResultContainer);

            setDirectionsStartAndLoadMap()
        });
        */
        sCurrentUnique = idUnique;
        GetDirectionsCallMap();
    }
}

var mapDirections;
var sCurrentUnique;

function GetDirectionsCallMap() {
    var sBingKey = $jQ("#hiddenBingMapKey").val();
    $jQ("#divMapDirectionsContainer").empty();
    $jQ("#divDirectionSuggestionDropdown").hide();
    
        mapDirections = new Microsoft.Maps.Map(document.getElementById("divMapDirectionsContainer"), { credentials: sBingKey, backgroundColor: '#ffffff',
        showCopyright: false,
        enableClickableLogo: false,
        showDashboard: true,
        showMapTypeSelector: false,
        showScalebar: true,
        fixedMapPosition: false,
        disableUserInput: false,
        enableSearchLogo: false,
        disableKeyboardInput :true

    });
    var sLat = $jQ("#hiddenBingMapCountryLatitude").val();
    var sLon = $jQ("#hiddenBingMapCountryLongitude").val();
    var loc = new Microsoft.Maps.Location(sLat, sLon);

    if ($jQ("#hclInputTextDirectionsFrom").val().length > 0 && $jQ("#hclInputTextDirectionsFrom").val() != $jQ("#hiddenLanguageDirectionFrom").val()) 
    {
        mapDirections.getCredentials(CallRouteService);
    }
    else 
    {
        mapDirections.setView({ center: loc, zoom: 6 });
        $jQ("#divDirectionsContainer").html("<h5>"+ $jQ("#hiddenLanguageDirectionsStartText").val()+"</h5>");
    }

    $jQ("#hclContent").find(".MapTypeId_m").find(":input").hide();

}




function CallRouteService(credentials ) {
    //var sBingKey = $jQ("#hiddenBingMapKey").val();
    var sBingMapCulture = $jQ("#hiddenBingMapCulture").val();
    var sBingMapCountryRegion = $jQ("#hiddenBingMapCountryRegion").val();
    var sStart = "";
    var sEnd = "";
    if ($jQ("#hclInputTextDirectionsFrom").val().length > 0) { 
    sStart = $jQ("#hclInputTextDirectionsFrom").val();
    }
    sEnd = encodeURIComponent($jQ("#hclInputTextDirectionsTo").val());

    //alert(sStart + "   " + sEnd);

    var objActiveClinicLi = $jQ("#divMapDirections").parents(".liItems").filter(":first");

    if ($jQ(objActiveClinicLi).length == 1)
    {
        sEnd = $jQ(objActiveClinicLi).attr("lat") + "," + $jQ(objActiveClinicLi).attr("lon");
       // alert(sEnd);
    }

    var sDistanceUnit = "mi"
    if ($jQ("#hiddenLanguageDistanceUnit").val() == "km") {
        sDistanceUnit = "km";
    }


    var routeRequest = "http://dev.virtualearth.net/REST/v1/Routes?wp.0=" + encodeURIComponent(sStart) + "&wp.1=" + sEnd + "&routePathOutput=Points&distanceUnit=" + sDistanceUnit + "&output=json&jsonp=RouteCallback&countryRegion=" + sBingMapCountryRegion + "&c=" + sBingMapCulture + "&key=" + credentials;

   // $jQ("#spanTestGed").text(routeRequest);
    CreateJavaScriptInclude(routeRequest);

    //20110816 bjo
   // $jQ("<script/>", { src: routeRequest, type: "text/javascript"}).appendTo("#divMapDirectionsContainer"); 
}

function RouteCallback(result) {
    var output = $jQ("#divDirectionsContainer");
    $jQ(output).empty();
    var resultsHeader = document.createElement("h5");
    var resultsList = document.createElement("ol");
    resultsList.className = "olListDrivingDirections";
    var resultsDistance = document.createElement("h5");
    $jQ(output).append(resultsHeader);
    $jQ(output).append(resultsList);
    $jQ(output).append(resultsDistance);

    if (result && result.resourceSets && result.resourceSets.length > 0 && result.resourceSets[0].resources && result.resourceSets[0].resources.length > 0) {
        //$jQ(resultsHeader).html($jQ("#hiddenLanguageRouteFrom").val() + " " + result.resourceSets[0].resources[0].routeLegs[0].startLocation.name + " " + $jQ("#hiddenLanguageRouteTo").val() + " " + result.resourceSets[0].resources[0].routeLegs[0].endLocation.name);
        var resultsListItem = null;
        for (var i = 0; i < result.resourceSets[0].resources[0].routeLegs[0].itineraryItems.length; ++i) {
            resultsListItem = document.createElement("li");
            $jQ(resultsList).append(resultsListItem);
            resultStr = result.resourceSets[0].resources[0].routeLegs[0].itineraryItems[i].instruction.text;
            if (result.resourceSets[0].resources[0].routeLegs[0].itineraryItems[i].travelDistance != "0") {
                var sDistance = result.resourceSets[0].resources[0].routeLegs[0].itineraryItems[i].travelDistance;
                sDistance = (Math.round(sDistance * 100) / 100).toString();
                sDistance = sDistance.replace(getDelimiter(), $jQ("#hiddenDelimiter").val());
                $jQ(resultsListItem).html(resultStr + " <b>" + sDistance + " " + $jQ("#hiddenLanguageDistanceUnit").val() + "</b>");
            }
            else {
                $jQ(resultsListItem).html(resultStr);
            }
        }
        var sTotalWayPoints = result.resourceSets[0].resources[0].routeLegs[0].itineraryItems.length.toString();
        var sTotalDistance = result.resourceSets[0].resources[0].travelDistance
        sTotalDistance = (Math.round(sTotalDistance * 100) / 100).toString();
        sTotalDistance = sTotalDistance.replace(getDelimiter(), $jQ("#hiddenDelimiter").val())
        $jQ(resultsDistance).html($jQ("#hiddenLanguageDrivingDistance").val() + ": " + sTotalDistance  + " " + $jQ("#hiddenLanguageDistanceUnit").val() + "<br/><br/>");
        var bbox = result.resourceSets[0].resources[0].bbox;
        var viewBoundaries = Microsoft.Maps.LocationRect.fromLocations(new Microsoft.Maps.Location(bbox[0], bbox[1]), new Microsoft.Maps.Location(bbox[2], bbox[3]));
        mapDirections.setView({ bounds: viewBoundaries });
        var routeline = result.resourceSets[0].resources[0].routePath.line; var routepoints = new Array();
       
       
      
        for (var i = 0; i < routeline.coordinates.length; i++) {

            routepoints[i] = new Microsoft.Maps.Location(routeline.coordinates[i][0], routeline.coordinates[i][1]);
        }
        var routeshape = new Microsoft.Maps.Polyline(routepoints, { strokeColor: new Microsoft.Maps.Color(150, 198, 22, 141) });
        

      
        
       

        
        var startPushpinOptions = { icon: 'images/mini_pin_green.png', width: 25, height: 34, text: $jQ("#hiddenLanguageRouteFromMarker").val(), textOffset: new Microsoft.Maps.Point(0, 5), draggable: false };
        var startPin = new Microsoft.Maps.Pushpin(new Microsoft.Maps.Location(routeline.coordinates[0][0], routeline.coordinates[0][1]), startPushpinOptions);
        var endPushpinOptions = { icon: 'images/mini_pin_red.png', width: 25, height: 34, text: $jQ("#hiddenLanguageRouteToMarker").val(), textOffset: new Microsoft.Maps.Point(0, 5), draggable: false };
        var endPin = new Microsoft.Maps.Pushpin(new Microsoft.Maps.Location(routeline.coordinates[routeline.coordinates.length - 1][0], routeline.coordinates[routeline.coordinates.length - 1][1]), endPushpinOptions);
        mapDirections.entities.push(startPin);
        mapDirections.entities.push(endPin);
      //  mapDirections.entities.push(routeshape);
        //Enable print button

        if ($jQ("#divPrintDirections").closest(".divContainerContent").length == 1) {
            $jQ("#divPrintDirections").show();
            var arrIdDirection = $jQ("#divPrintDirections").closest(".divContainerContent").attr("id").split("_");
            $jQ("#divPrintDirections").parent().attr("target", "_blank");

            var objParentElement = $jQ("#divMapDirections").parents(".liItems").filter(":first");

            var sAddressTo = "";
            if ($jQ(objParentElement).length == 1)
            {
            sAddressTo = $jQ(objParentElement).attr("lat") + ","+$jQ(objParentElement).attr("lon");
            }
            else
            {
            sAddressTo = encodeURIComponent($jQ("#hclInputTextDirectionsTo").val());
            }

            var sBingMapCountryRegion = $jQ("#hiddenBingMapCountryRegion").val();
            var sBingMapCulture = $jQ("#hiddenBingMapCulture").val();
            var sLanguageDistanceUnit  = $jQ("#hiddenLanguageDistanceUnit").val();

            $jQ("#divPrintDirections").parent().attr("href", "showClinicData.aspx?vt=directions&id=" + arrIdDirection[1] + "&adrfrom=" + encodeURIComponent($jQ("#hclInputTextDirectionsFrom").val()) + "&adrto=" + sAddressTo + "&countryregion=" + sBingMapCountryRegion + "&culture=" + sBingMapCulture + "&dm=" + sLanguageDistanceUnit+"");
        }



        
        //Fejlen sker her..
        window.setTimeout(function () {
            // Add Custom Button to NavBar
            try {
                mapDirections.entities.push(routeshape);
            }
            catch (e)
            {  }
        }, 1500);
        //...
        
    }
    else {
        if (typeof (result.errorDetails) != 'undefined') {
           // resultsHeader.innerHTML = result.errorDetails[0];
        }
        $jQ(resultsHeader).html($jQ("#hiddenLanguageNoRouteFound").val());
        var sLat = $jQ("#hiddenBingMapCountryLatitude").val();
        var sLon = $jQ("#hiddenBingMapCountryLongitude").val();
        var loc = new Microsoft.Maps.Location(sLat, sLon);
        mapDirections.setView({ center: loc, zoom: 6 });
    }
    //her er fejlen sket
}

function setDirectionsStartAndLoadMap(idUnique) {
    sCurrentUnique = idUnique;
    GetDirectionsCallMap();
}



function doShowMapSolution() {
    $jQ("#divMapSolution").removeClass("divMapLargeMapSolutionNoShow");
    $jQ("#hiddenShowDataAs").val("map");
    $jQ("#divMenuList").removeClass("DivMenuSelected").addClass("DivMenuUnSelected");
    $jQ("#divMenuMap").removeClass("DivMenuUnSelected").addClass("DivMenuSelected");
    var objClinicItems = $jQ("#divItemContainerList").find(".liItems.hclClinicShow").addClass("hclMapSolutionHide");
    //Making all pins pink
    $jQ(".liItems").find(".imgPinBigInactive,.imgPinBigActive").addClass("imgPinBigActivePinkOverRule");
    //Always set the first dispenser active
    $jQ("#divItemContainerList").find(".liItems.hclClinicShow:first").removeClass("hclMapSolutionHide");
    //disable Sort
    if ($jQ("#divSortClinics").parent().find(".selectSortByShow").length == 1)
    {
        $jQ("#divSortClinics").parent().find(".selectSortByShow").removeClass("selectSortByShow").addClass("selectSortByNoShow");
    }
    //hide minimap
    $jQ(".liItems").find(".divMiniMap").hide();
    //hide map link
    $jQ(".liItems").find(".liMapLink").hide();
    showMapSolution();
    ShowPushPinsOnMapSolution($jQ("#hiddenClinicShow").val());
}


function doShowListSolution() {
    $jQ("#divMapSolution").addClass("divMapLargeMapSolutionNoShow");
    $jQ("#hiddenShowDataAs").val("list");
    $jQ("#divMenuList").removeClass("DivMenuUnSelected").addClass("DivMenuSelected");
    $jQ("#divMenuMap").removeClass("DivMenuSelected").addClass("DivMenuUnSelected");
    $jQ(".liItems").find(".imgPinBigActivePinkOverRule").removeClass("imgPinBigActivePinkOverRule");
    //show minimap
    $jQ(".liItems").find(".divMiniMap").show();
    //show map link
    $jQ(".liItems").find(".liMapLink").show();
    //enable Sort
    if ($jQ("#divSortClinics").parent().find(".selectSortByNoShow").length == 1) {
        $jQ("#divSortClinics").parent().find(".selectSortByNoShow").removeClass("selectSortByNoShow").addClass("selectSortByShow");
    }
    var objClinicItems = $jQ("#divItemContainerList").find(".liItems.hclClinicShow, .liItems.hclClinicNotShow").removeClass("hclMapSolutionHide");
    appendMiniMapToClinicList($jQ("#hiddenClinicShow").val());
}

function getDelimiter() {
    var tempVar = 1 / 2;
    if (tempVar.toString().indexOf(",",0) > 0) {
        return ",";
    }
    if (tempVar.toString().indexOf(".",0) > 0) {
        return ".";
    }
}



function DisableScroll() {
    var ar = new Array(33, 34, 35, 36, 37, 38, 39, 40);
    $jQ(document).bind("keydown", function(e) {
        var key = e.which;
        if ($jQ.inArray(key, ar) > -1) {
            e.preventDefault();
            return false;
        }
        return true;
    })
}

function EnableScroll() {
    $jQ(document).unbind("keydown");
}


function MakeGeocodeRequestFront() {
    var sBingKey = $jQ("#hiddenBingMapKey").val();
    var sBingMapCulture = $jQ("#hiddenBingMapCulture").val();
    var sBingMapCountryRegion = $jQ("#hiddenBingMapCountryRegion").val();
    var sFrontQueryValue = $jQ("#txtFrontQuery").val();
    sFrontQueryValue = sFrontQueryValue.replace(":", "");
    if ($jQ("#hiddenSearchFieldDefaultText").val() != sFrontQueryValue && sFrontQueryValue.length > 1) {
        if (sFrontQueryValue.toLowerCase().indexOf(", " + $jQ("#hiddenBingMapCountry").val()) > 0 || sFrontQueryValue.toLowerCase().indexOf("," + $jQ("#hiddenBingMapCountry").val()) > 0)
        { }
        else {
            sFrontQueryValue = sFrontQueryValue + ", " + $jQ("#hiddenBingMapCountry").val();
        }
        //alert($jQ("#hiddenBingMapCountry").val());

        var geocodeRequest = "http://dev.virtualearth.net/REST/v1/Locations/" + encodeURIComponent(sFrontQueryValue) + "?output=json&jsonp=GeocodeCallbackFront&countryRegion=" + sBingMapCountryRegion + "&c=" + sBingMapCulture + "&key=" + sBingKey;

       // $jQ("#spanBingTest").html(geocodeRequest);
        CreateJavaScriptInclude(geocodeRequest);
    }
}


function GeocodeCallbackFront(result) {
    $jQ("divFrontResult").hide();
    $jQ("#divFrontResult").html("");
    try //In case the service returns nothing - happens!
        {
        var sAddress = $jQ("#txtFrontQuery").val();
        var sResults = result.resourceSets[0].estimatedTotal;
        switch (sResults) {
            case 0:
               
                break;
            case 1:
                var location_name = result.resourceSets[0].resources[0].address.formattedAddress;
                var bbox = result.resourceSets[0].resources[0].bbox;
                var objCoords = result.resourceSets[0].resources[0].point;
                SendCoordinates(objCoords.coordinates[0], objCoords.coordinates[1], location_name, encodeURIComponent(sAddress));
                break;
            default: // more than 1 result
                DisableScroll();
                $jQ("#divFrontResult").show();
                var divElement = document.createElement("div");
                divElement.className = "geoDidYouMean";
                divElement.innerHTML = $jQ("#hiddenLanguageDidYouMean").val();
                document.getElementById("divFrontResult").appendChild(divElement);

                var ulElement = document.createElement("ul");
                ulElement.setAttribute("id", "ulResult");
                for (var i = 0; i < result.resourceSets[0].resources.length; i++) {
                    var location_name = result.resourceSets[0].resources[i].address.formattedAddress;
                    var arrlocation_name = location_name.split(", ");
                    var bbox = result.resourceSets[0].resources[i].bbox;
                    var objCoords = result.resourceSets[0].resources[i].point;
                    var liElement = document.createElement("li");
                    var aHrefElement = document.createElement("a");
                    aHrefElement.setAttribute("id", "link_" + i);
                    aHrefElement.setAttribute("href", "javascript:SendCoordinates('" + objCoords.coordinates[0] + "','" + objCoords.coordinates[1] + "','" + location_name + "','" + encodeURIComponent(sAddress) + "');");
                    aHrefElement.className = "DataItems"
                    aHrefElement.innerHTML = location_name;
                    liElement.appendChild(aHrefElement);
                    ulElement.appendChild(liElement);
                }
                document.getElementById("divFrontResult").appendChild(ulElement);
                break;
        }
        $jQ('.DataItems').keydown(function(event, obj) {
            if (event.keyCode == 40) {
                var clicked = $jQ(this);

                var arrId = clicked.attr("id").split("_");
                var id = arrId[1];
                id = id - 0;

                $jQ(this).blur(function() {
                    $jQ(this).removeClass('ComboBoxDropDownActive');
                });
                id = id - 0 + 1;
                $jQ('#link_' + id).focus();
                $jQ('#link_' + id).addClass('ComboBoxDropDownActive');
            }
            if (event.keyCode == 38) {
                $jQ(this).blur(function() {
                    $jQ(this).removeClass('ComboBoxDropDownActive');
                });
                var clicked = $jQ(this);
                var arrId = clicked.attr("id").split("_");
                var id = arrId[1];
                id = id - 1;
                if (id < 0) {
                    $jQ('#txtFrontQuery').focus();
                }
                else {
                    $jQ('#link_' + id).focus();
                    $jQ('#link_' + id).addClass('ComboBoxDropDownActive');
                }
            }
        });
    }
    catch (e) {
        MakeGeocodeRequestFront();
    }
}




function MakeGeocodeRequestDirection() {
    var sBingKey = $jQ("#hiddenBingMapKey").val();
    var sBingMapCulture = $jQ("#hiddenBingMapCulture").val();
    var sBingMapCountryRegion = $jQ("#hiddenBingMapCountryRegion").val();
    var sQueryValue = $jQ("#hclInputTextDirectionsFrom").val();
    sQueryValue = sQueryValue.replace(":", "");
    if ($jQ("#hiddenLanguageDirectionFrom").val() != sQueryValue && sQueryValue.length > 1) {
        if (sQueryValue.toLowerCase().indexOf(", " + $jQ("#hiddenBingMapCountry").val()) > 0 || sQueryValue.toLowerCase().indexOf("," + $jQ("#hiddenBingMapCountry").val()) > 0)
        { }
        else {
            sQueryValue = sQueryValue + ", " + $jQ("#hiddenBingMapCountry").val();
        }
        var geocodeRequest = "http://dev.virtualearth.net/REST/v1/Locations/" + encodeURIComponent(sQueryValue) + "?output=json&jsonp=GeocodeCallbackDirection&countryRegion=" + sBingMapCountryRegion + "&c=" + sBingMapCulture + "&key=" + sBingKey;
        CreateJavaScriptInclude(geocodeRequest);
    }
}


function GeocodeCallbackDirection(result) {
    $jQ("#divDirectionSuggestionDropdown").hide();
    $jQ("#divDirectionSuggestionDropdown").html("");
    try //In case the service returns nothing - happens!
        {
        var sResults = result.resourceSets[0].estimatedTotal;
        switch (sResults) {
            case 0:
                var sAddress = $jQ("#hclInputTextDirectionsFrom").val();
               // alert();
                break;
            case 1:
                var location_name = result.resourceSets[0].resources[0].address.formattedAddress;
                var bbox = result.resourceSets[0].resources[0].bbox;
                var objCoords = result.resourceSets[0].resources[0].point;
                SendDirectionCoordinates(objCoords.coordinates[0], objCoords.coordinates[1], location_name);
                break;
            default: // more than 1 result
                DisableScroll();
                $jQ("#divDirectionSuggestionDropdown").show();
                var divElement = document.createElement("div");
                divElement.className = "geoDidYouMean";
                divElement.innerHTML = "Did you mean..";
                document.getElementById("divDirectionSuggestionDropdown").appendChild(divElement);

                var ulElement = document.createElement("ul");
                ulElement.setAttribute("id", "ulResultDirection");
                for (var i = 0; i < result.resourceSets[0].resources.length; i++) {
                    var location_name = result.resourceSets[0].resources[i].address.formattedAddress;
                    var arrlocation_name = location_name.split(", ");
                    var bbox = result.resourceSets[0].resources[i].bbox;
                    var objCoords = result.resourceSets[0].resources[i].point;
                    var liElement = document.createElement("li");
                    var aHrefElement = document.createElement("a");
                    aHrefElement.setAttribute("id", "linkDirection_" + i);
                    aHrefElement.setAttribute("href", "javascript:SendDirectionCoordinates('" + objCoords.coordinates[0] + "','" + objCoords.coordinates[1] + "','" + location_name + "');");
                    aHrefElement.className = "DataItems"
                    aHrefElement.innerHTML = location_name;
                    liElement.appendChild(aHrefElement);
                    ulElement.appendChild(liElement);
                }
                document.getElementById("divDirectionSuggestionDropdown").appendChild(ulElement);
                break;
        }
        $jQ('.DataItems').keydown(function (event, obj) {
            if (event.keyCode == 40) {
                var clicked = $jQ(this);

                var arrId = clicked.attr("id").split("_");
                var id = arrId[1];
                id = id - 0;

                $jQ(this).blur(function () {
                    $jQ(this).removeClass('ComboBoxDropDownActive');
                });
                id = id - 0 + 1;
                $jQ('#linkDirection_' + id).focus();
                $jQ('#linkDirection_' + id).addClass('ComboBoxDropDownActive');
            }
            if (event.keyCode == 38) {
                $jQ(this).blur(function () {
                    $jQ(this).removeClass('ComboBoxDropDownActive');
                });
                var clicked = $jQ(this);
                var arrId = clicked.attr("id").split("_");
                var id = arrId[1];
                id = id - 1;
                if (id < 0) {
                    $jQ('#hclInputTextDirectionsFrom').focus();
                }
                else {
                    $jQ('#linkDirection_' + id).focus();
                    $jQ('#linkDirection_' + id).addClass('ComboBoxDropDownActive');
                }
            }
        });
    }
    catch (e) {
        MakeGeocodeRequestDirection();
    }
}


function SendDirectionCoordinates(lat, lon, locationName) {
    $jQ("#hclInputTextDirectionsFrom").val(locationName); 
    $jQ("#hiddenSearchAddressLattitude").val(lat);
    $jQ("#hiddenSearchAddressLongitude").val(lon);
    $jQ("#hiddenHclNoResult").val(false);
    GetDirectionsCallMap();

}


function showOpeningHours(idUnique) {
    //Netminers
    $netminers.push(
        ['postPageView', 'HCL > ' + $jQ('#hiddenViewType').val() + ' > show opening hours > ' + idUnique]
        );
    //---------

    var bCurrentOpen = false;
    if ($jQ("#DivOpeningHours_" + idUnique).is(':visible')) {
        bCurrentOpen = true;
    }
    resetAllFields();
    if (bCurrentOpen == false) {
        //highlight active clinic pin
        var imgPinBig = $jQ("#divItemContainerList").parent().find(".imgPinBigInactive");
        for (ii = 0; ii < imgPinBig.length; ii++) {
            var arrImgPinBig = $jQ(imgPinBig[ii]).attr("id").split("_");
            if (arrImgPinBig[1] == idUnique.toString()) {
                $jQ(imgPinBig[ii]).removeClass("imgPinBigInactive").addClass("imgPinBigActive");
            }
        }
        document.getElementById("liOpeninghoursLink_" + idUnique).className = "activeLink";
        document.getElementById("liOpeninghoursLink_" + idUnique).childNodes[0].className = "activeLinkHref";
        $jQ("#DivOpeningHours_" + idUnique).removeClass("DivOpeningHoursNoShow");
    }
}

function showMisc(idUnique) {

    //Netminers
    $netminers.push(
        ['postPageView', 'HCL > ' + $jQ('#hiddenViewType').val() + ' > show misc > ' + idUnique]
        );
    //---------

    var bCurrentOpen = false;
    if ($jQ("#DivMisc_" + idUnique).is(':visible')) {
        bCurrentOpen = true;
    }
    resetAllFields();
    if (bCurrentOpen == false) {
        //highlight active clinic pin
        var imgPinBig = $jQ("#divItemContainerList").parent().find(".imgPinBigInactive");
        for (ii = 0; ii < imgPinBig.length; ii++) {
            var arrImgPinBig = $jQ(imgPinBig[ii]).attr("id").split("_");
            if (arrImgPinBig[1] == idUnique.toString()) {
                $jQ(imgPinBig[ii]).removeClass("imgPinBigInactive").addClass("imgPinBigActive");
            }
        }
        document.getElementById("liMiscLink_" + idUnique).className = "activeLink";
        document.getElementById("liMiscLink_" + idUnique).childNodes[0].className = "activeLinkHref";
        $jQ("#DivMisc_" + idUnique).removeClass("DivMiscNoShow");
    }
}

/**
*
*  URL encode / decode
*  http://www.webtoolkit.info/
*
**/

var Url = {

    // public method for url encoding
    encode: function (string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode: function (string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode: function (string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode: function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while (i < utftext.length) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}

/*
function gedged() {
    var sBingKey = $jQ("#hiddenBingMapKey").val();
    var sLatitude = $jQ("#selectCountryDropdown option:selected").attr("latitude");
    var sLongitude = $jQ("#selectCountryDropdown option:selected").attr("longitude");
    var sZoomLevel = $jQ("#selectCountryDropdown option:selected").attr("zoomlevel");
    sZoomLevel = sZoomLevel - 0;

    $jQ("#divFrontMap").html('');
    var map = null;
    // Initialize the map
    map = new Microsoft.Maps.Map(document.getElementById("divFrontMap"), { credentials: sBingKey, backgroundColor: '#ffffff', showCopyright: false, enableClickableLogo: false, disableKeyboardInput: true, disableTouchInput: true, showDashboard: false, showMapTypeSelector: false, showScalebar: false, fixedMapPosition: true, disableUserInput: true, disableMouseInput: false, enableSearchLogo: false });

    var loc = new Microsoft.Maps.Location(sLatitude, sLongitude);
    map.setView({ center: loc, zoom: sZoomLevel });

}
*/

function onchange_SelectCountry() {
    var sBingKey = $jQ("#hiddenBingMapKey").val();


    var sValue = $jQ("#selectCountryDropdown option:selected").attr("value")


    $netminers.push(
        ['postFieldChange', 'countryDropdown', sValue]
        );
    
    $jQ('#divFrontSearcContainer').hide();
    if (sValue != "") {

        var objSelectedItem = $jQ("#selectCountryDropdown option:selected");
        var sCountry = $jQ(objSelectedItem).text();
        var sCulture = $jQ(objSelectedItem).attr("culture");
        var sLatitude = $jQ(objSelectedItem).attr("latitude");
        var sLongitude = $jQ(objSelectedItem).attr("longitude");
        var sZoomLevel = $jQ(objSelectedItem).attr("zoomlevel");
        var sAutoLoadResultSet = $jQ(objSelectedItem).attr("autoloadresultset");
        sAutoLoadResultSet = sAutoLoadResultSet.toLowerCase();
        
        $jQ("#hiddenBingMapCulture").val(sCulture);
        $jQ("#hiddenBingMapCountryRegion").val(sCountry);
        $jQ("#hiddenBingMapCountry").val(sCountry);
        $jQ("#hiddenConfigurationId").val(sValue);
        $jQ("#hiddenAutoLoadResultSet").val(sAutoLoadResultSet);
        sZoomLevel = sZoomLevel - 0;

        if (sAutoLoadResultSet == "true") {
            document.forms[0].submit();
        }
        else {
            $jQ('#divFrontSearcContainer').show();

            $jQ("#divFrontMap").html('');
            var map = null;
            // Initialize the map
            map = new Microsoft.Maps.Map(document.getElementById("divFrontMap"), { credentials: sBingKey, backgroundColor: '#ffffff', showCopyright: false, enableClickableLogo: false, disableKeyboardInput: true, disableTouchInput: true, showDashboard: false, showMapTypeSelector: false, showScalebar: false, fixedMapPosition: true, disableUserInput: true, disableMouseInput: false, enableSearchLogo: false });

            var loc = new Microsoft.Maps.Location(sLatitude, sLongitude);
            map.setView({ center: loc, zoom: sZoomLevel });
        }
    }
}
