﻿//Hold Global variables and Map refresh functions
var map;
var mylat; var mylong;
var geocoder;
var locations = [
            new google.maps.LatLng(32.845857, -85.983852),
            new google.maps.LatLng(32.914349, -85.967554)
            ];
var markers = new Array();
var infowindows = new Array();
var Companies;
var mapDiv;
var currentDirections = null;
var oldDirections = [];
var directionsDisplay;
var directionsService;
var OpenWindowStack = new Array();
var locationmarker = null;
var currenttab = null;
var nearby = false;
var prevCompanies = null;
var georesponseTimerId = null;
function maintainHistory() {
    this.name = null;
    this.content = null;
    this.mapstate = null;
}


function Toggle(tabname) {


    if (tabname.length <= 0) {
        //currenttab = OpenWindowStack.pop();
        var popHistory = OpenWindowStack.pop();
        //alert("value" + popHistory.name);
        if (popHistory != null) {
            //alert("pop name" + popHistory.name);
            //alert("pop content" + popHistory.content);
            //alert("pop state" + popHistory.mapstate);
            Companies = popHistory.mapstate;
            var panels = jQuery(".panels > div");
            var panel_name = popHistory.name;
            jQuery("#" + panel_name).html(popHistory.content);
            jQuery(".panels > div").hide();
            jQuery("#" + panel_name).show();
            //jQuery("#" + panel_name).jScrollPane();
            var currenttab = jQuery("#" + panel_name).attr("index");
            jQuery(".panels").attr("active", currenttab);
            if (jQuery.isEmptyObject(Companies) || Companies.length <= 0) {
                jQuery('#imgSpinner').show();
                var mapDiv = jQuery("#mapDiv");
                var bounds = new google.maps.LatLngBounds();
                if (mapDiv.length > 0) {
                    ClearMarkers();
                    markers = new Array();
                    jQuery("#listing").html(popHistory.content);
                    try {
                        jQuery('#listing').touchScroll();
                        //jQuery('#listing').jScrollPane();
                    }
                    catch (e)
                            { }
                    jQuery('#imgSpinner').hide();
                    displayMap();
                }
            }
            else {
                if (popHistory.name == "directions_panel") {
                    calcRouteOnPop(popHistory.mapstate[0], popHistory.mapstate[1]);
                }
                else {
                    ClearMarkers();
                    Markcompanies(false);

                }
            }
            if (directionsDisplay != null) {
                directionsDisplay.setMap(null);
            }


        }
        //                if (currenttab != null) {
        //                    var panels = jQuery(".panels > div");
        //                    var panel_name = jQuery(panels[currenttab - 1]).attr("id");
        //                    jQuery(".panels > div").hide();
        //                    jQuery("#" + panel_name).show();
        //                    jQuery(".panels").attr("active", currenttab);
        //                }
        if (OpenWindowStack.length <= 1) {
            jQuery(".backlink").fadeOut();
        }
        else {
            jQuery(".backlink").fadeIn();
        }
        tb_init('a.thickbox, area.thickbox, input.thickbox');
    }
    else {
        var currentPanel = jQuery(".panels").attr("active");
        var panels = jQuery(".panels > div")//.filter("[active|="en"]");                
        if (currentPanel > 0) {
            var pushHistory = new maintainHistory();
            pushHistory.name = jQuery(panels[currentPanel - 1]).attr("id");
            pushHistory.content = jQuery(panels[currentPanel - 1]).html();
            pushHistory.mapstate = prevCompanies;
            //alert("push" + history.name);
            //alert("push" + history.content);
            //alert("push" + history.mapstate);


            OpenWindowStack.push(pushHistory);
            jQuery(panels[currentPanel - 1]).html("");
            // OpenWindowStack.push(currentPanel);
            if (OpenWindowStack.length <= 1) {
                jQuery(".backlink").fadeOut();
            }
            else {
                jQuery(".backlink").fadeIn();
            }
            var newtab = jQuery(".panels > div[id='" + tabname + "']");
            var newactiveidx = jQuery(newtab).attr("index");
            //alert(newactiveidx);
            jQuery(".panels").attr("active", newactiveidx);
            jQuery(panels[currentPanel - 1]).hide();
            jQuery(newtab).show();

        }
        else {
            var newtab = jQuery(".panels > div[id='" + tabname + "']");
            var newactiveidx = jQuery(newtab).attr("index");
            jQuery(".panels").attr("active", newactiveidx);
            jQuery(newtab).show();
        }

        if (tabname != "directions_panel") {
            if (directionsDisplay != null) {
                directionsDisplay.setMap(null);
            }
        }
    }
}
function ClearMarkers() {
    for (var idx in markers) {
        markers[idx].setMap(null);
    }
    markers = new Array();
}
function RefreshMap() {
    var mapDiv = jQuery("#mapDiv");
    var bounds = new google.maps.LatLngBounds();
    if (mapDiv.length > 0) {
        for (var idx = 0; idx < locations.length; idx++) {
            bounds.extend(locations[idx]);
            markers[idx] = new google.maps.Marker({
                position: locations[idx], map: map
            });
            google.maps.event.addListener(markers[idx], 'click', function () {
                var coord;
                //Get Position of Marker clicked from markers array
                var pos = ItemIndex(markers, this);
                infowindows[pos] = new google.maps.InfoWindow({
                    content: "location is" + pos
                });
                infowindows[pos].open(map, this);
            });
        }

        map.fitBounds(bounds);
    } //if end
} //Function end
function Markcompanies(displayhtml) {
    if (displayhtml == null)
        displayhtml = true;
    jQuery('#imgSpinner').show();
    var companyUl = "";
    var mapDiv = jQuery("#mapDiv");
    var bounds = new google.maps.LatLngBounds();
    if (mapDiv.length > 0) {
        ClearMarkers();
        markers = new Array();
        if (jQuery.isEmptyObject(Companies) || Companies.length <= 0) {
            companyUl = "<h1>No Company found.</h1>";
        }
        else {
            jQuery('#imgSpinner').show();
            if (jQuery("#ctl00_ddlSearchType").val() == "1")
                companyUl = "<h1>Search result for Company:" + jQuery("#ctl00_TxtSearch").val() + "</h1><table class='searchersult'>";
            else
                companyUl = "<h1>Search result for City:" + jQuery("#ctl00_TxtSearch").val() + "</h1><table class='searchersult'>";
            //companyUl = "<h1>Search result for City:" + jQuery("#ctl00_ddlSearchType option:selected").text() + "</h1><table class='searchersult'>";
            for (var idx in Companies) {
                var currentcompany = Companies[idx];
                if (displayhtml) {
                    if ((idx % 2) == 1) {
                        companyUl += "<tr class='odd'>";
                    }
                    else {
                        companyUl += "<tr class='even'>";
                    }
                    companyUl += "<td style='font-size: 28px; vertical-align: middle;'><b>" + parseInt(parseInt(idx) + 1) + "</b></td><td style='padding:5px;display:block;width:100%;'>" + GetInfoWindowContent(currentcompany) + "</td></tr>";
                }
                var coordinates;
                try {
                    coordinates = new google.maps.LatLng(currentcompany["address"]["latitude"], currentcompany["address"]["longitude"]);
                }
                catch (e) {
                    coordinates = new google.maps.LatLng(currentcompany["Company"]["address"]["latitude"], currentcompany["Company"]["address"]["longitude"]);
                }


                bounds.extend(coordinates);
                markers[idx] = new StyledMarker({ styleIcon: new StyledIcon(StyledIconTypes.BUBBLE, { color: "00ff00", text: "" + parseInt(parseInt(idx) + 1) + "" }), position: coordinates, map: map });
                google.maps.event.addListener(markers[idx], 'click', function () {
                    var coord;
                    //Get Position of Marker clicked from markers array
                    var pos = ItemIndex(markers, this);
                    infowindows[pos] = new google.maps.InfoWindow({
                        content: GetInfoWindowContent(Companies[pos])
                    });
                    infowindows[pos].open(map, this);
                });
            }
            if (Companies.length > 1) {
                map.fitBounds(bounds);
            }
            companyUl += "</table>";
        }

        //jQuery("#company_info").html(companyUl);
        if (displayhtml) {
            jQuery("#listing").html(companyUl);
            try {
                jQuery('#listing').touchScroll();
            }
            catch (e)
                            { }
        }
        // Toggle("listing");
        //                jQuery("#directions_panel").hide();
        //                jQuery("#company_info").show();
        //OpenWindowStack.push("#listing");
        jQuery('#imgSpinner').hide();
    } //if end
} //Function end
function MarkNearBycompanies(DisplayMsg) {
    jQuery('#imgSpinner').show();
    var companyUl = "";
    if (DisplayMsg.length <= 0) {
        if (nearby) {
            companyUl = "<h1>Nearby Companies:</h1><table class='searchersult'>";
        }
        else {
            companyUl = "<h1>Nearby Companies:" + jQuery("#ctl00_TxtSearch").val() + "</h1><table class='searchersult'>";
        }
    }
    else {
        companyUl = "<h1>" + DisplayMsg + "</h1><table class='searchersult'>";
    }
    var mapDiv = jQuery("#mapDiv");
    var bounds = new google.maps.LatLngBounds();
    if (mapDiv.length > 0) {
        ClearMarkers();
        markers = new Array();
        if (jQuery.isEmptyObject(Companies) || Companies.length <= 0) {
            companyUl = "<h1>No Company found near your location \"" + jQuery("#ctl00_txtLocation").val() + "\" </h1>";
        }
        else {
            jQuery('#imgSpinner').show();
            for (var idx in Companies) {
                var currentcompany = Companies[idx];
                if ((idx % 2) == 1) {
                    companyUl += "<tr class='odd'>";
                }
                else {
                    companyUl += "<tr class='even'>";
                }
                companyUl += "<td style='font-size: 28px; vertical-align: middle;'><b>" + parseInt(parseInt(idx) + 1) + "</b></td><td style='padding:5px;display:block;width:100%;'>" + GetInfoWindowContent(currentcompany) + "</td></tr>";
                var coordinates = new google.maps.LatLng(currentcompany["address"]["latitude"], currentcompany["address"]["longitude"]);
                bounds.extend(coordinates);

                markers[idx] = new StyledMarker({ styleIcon: new StyledIcon(StyledIconTypes.BUBBLE, { color: "00ff00", text: "" + parseInt(parseInt(idx) + 1) + "" }), position: coordinates, map: map });
                google.maps.event.addListener(markers[idx], 'click', function () {
                    var coord;
                    //Get Position of Marker clicked from markers array
                    var pos = ItemIndex(markers, this);
                    infowindows[pos] = new google.maps.InfoWindow({
                        content: GetInfoWindowContent(Companies[pos])
                    });
                    infowindows[pos].open(map, this);
                });
            }
            map.fitBounds(bounds);
            companyUl += "</table>";
        }
        jQuery("#listing").html(companyUl);
        try {
            jQuery('#listing').touchScroll();
        }
        catch (e)
                            { }

        jQuery('#imgSpinner').hide();
    } //if end
    else {

    }
    jQuery('#imgSpinner').hide();
} //Function end

function ChangeView(view_name) {
    if (mapDiv != null) {
        map.setMapTypeId(view_name);
    }
}
function ItemIndex(arr, obj) {
    try {
        if (!Array.prototype.indexOf) {
            Array.prototype.indexOf = function (elt /*, from*/) {
                var len = this.length;

                var from = Number(arguments[1]) || 0;
                from = (from < 0)
                    ? Math.ceil(from)
                    : Math.floor(from);
                if (from < 0)
                    from += len;

                for (; from < len; from++) {
                    if (from in this &&
                    this[from] === elt)
                        return from;
                }
                return -1;
            };
        }
        return arr.indexOf(obj);
    }
    catch (e) {
        return -1;
    }
}
function capitaliseFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}
function GetInfoWindowContent(Company) {
    if (!jQuery.isEmptyObject(Company)) {
        //var company;
        try {
            if (Company["id"] != null) {
                Company = Company;
            }
            else {
                if (Company["Company"] != null) {
                    Company = Company["Company"];
                }
            }
        }
        catch (e) {
            alert("Error occur" + e);
        }
        var coordinates = new google.maps.LatLng(Company["address"]["latitude"], Company["address"]["longitude"]);
        var Curlatlng = new google.maps.LatLng(mylat, mylong);
        var content = "<div  class='company'><a class='title' href=\"javascript:ShowCompanyMoreInfo(" + Company["id"] + ");map.setCenter(new google.maps.LatLng(" + Company["address"]["latitude"] + "," + Company["address"]["longitude"] + "));map.setZoom(12);\">" + Company["name"].toLowerCase() + "</a><br/>" + Company["address"]["street"].toLowerCase() + "<br/>" + capitaliseFirstLetter(Company["address"]["city"].toLowerCase()) + ", " + Company["address"]["state"] + "&nbsp;&nbsp;&nbsp;" + Company["address"]["zip"] + "<br/>" + Company["address"]["country"];
        content = content + "<br/><a href=\"javascript:ShowCompanyMoreInfo(" + Company["id"] + ");map.setCenter(new google.maps.LatLng(" + Company["address"]["latitude"] + "," + Company["address"]["longitude"] + "));map.setZoom(12);\">View Details</a>&nbsp;&nbsp;";
        if (jQuery("#ctl00_hdnLocation").val().length > 0) {
            content = content + "<a href=\"javascript:calcRoute(new google.maps.LatLng(" + mylat + "," + mylong + "),new google.maps.LatLng(" + Company["address"]["latitude"] + "," + Company["address"]["longitude"] + "));\">Directions</a>";
        }
        content = content + "&nbsp;&nbsp;<a href=\"javascript:SetFavorite(" + Company["id"] + ");\">Favorite</a>";
        content = content + "</div>";
        return content;
    }
    else {
        return "";
    }

}

function ShowCompanyMoreInfo(id) {
    jQuery("#company_info").load(sitepath + "GetCompanyInfo.aspx?id=" + id + "&rnd=" + new Date().getTime(), function (response, status, xhr) {
        prevCompanies = Companies;
        if (status == "error") {
            var msg = "Sorry but there was an error: ";
            jQuery("#company_info").html(msg + xhr.status + " " + xhr.statusText);
            Toggle("company_info");
        }
        else {
            Toggle("company_info");
            if (response.length <= 0) {
                jQuery("#company_info").html("<h1>Error occure while featching company information.</h1>");
            }
            else {
                var retval = xhr.getResponseHeader("RequestStatus");
                if (retval != "") {
                    switch (retval) {
                        case "1":
                            var CompanyStatus = xhr.getResponseHeader("CompanyStatus");
                            Companies = new Array();
                            Companies[0] = jQuery.parseJSON(xhr.getResponseHeader("Companies"));
                            jQuery("#company_info").html(response);
                            Markcompanies(false);
                            if (CompanyStatus == "flagged") {
                                alert("This company has been flagged, so the information may or may not be correct.");
                            }
                            try {
                                jQuery('#company_info').touchScroll();
                            }
                            catch (e)
                            { }

                            break;
                        case "2":
                            jQuery("#company_info").html("<h1>Error occure while featching company information.</h1>");
                            break;
                        case "3":
                            Companies = new Array();
                            Companies[0] = jQuery.parseJSON(xhr.getResponseHeader("Companies"));
                            Markcompanies();
                            break;
                        case "4":
                            document.location.assign(sitepath + "default.aspx?msg=You have been idle for at least 20 minutes and have been logged out. Please sign in again to continue.");
                            //jQuery("#company_info").html("Session Expire. Please click <a href='" + sitepath + "default.aspx'>here</a> to relogin.");
                            break;
                    }
                }
            }
        }
    });

}
function ShowUserHistory() {
    jQuery('#imgSpinner').show();
    prevCompanies = Companies;
    Companies = null;
    jQuery("#history").html("");
    jQuery("#history").load(sitepath + "GetUserHistory.aspx?rnd=" + new Date().getTime(), function (response, status, xhr) {
        if (status == "error") {
            var msg = "Sorry but there was an error: ";
            jQuery("#history").html(msg + xhr.status + " " + xhr.statusText);
            Toggle("history");
        }
        else {
            Toggle("history");
            if (response.length <= 0) {
                jQuery("#history").html("<h1>Currently no history exists</h1>");
            }
            else {
                var retval = xhr.getResponseHeader("RequestStatus");
                if (retval != "") {
                    switch (retval) {
                        case "1":
                            break;
                        case "2":
                            jQuery("#history").html("<h1>Currently no history exists</h1>");
                            break;
                        case "3":
                            break;
                        case "4":
                            //jQuery("#history").html("Session Expire. Please click <a href='" + sitepath + "default.aspx'>here</a> to relogin.");
                            document.location.assign(sitepath + "default.aspx?msg=You have been idle for at least 20 minutes and have been logged out. Please sign in again to continue.");
                            break;
                    }
                }
            }
        }
        displayMap();
        try {
            jQuery('#history').touchScroll();
        }
        catch (e)
                            { }

        jQuery('#imgSpinner').hide();
    });




}
function ShowUserFavorite() {
    jQuery("#favorite").html("");
    jQuery("#favorite").load(sitepath + "GetUserFavories.aspx?rnd=" + new Date().getTime(), function (response, status, xhr) {

        prevCompanies = Companies;
        if (status == "error") {
            var msg = "Sorry but there was an error: ";
            jQuery("#favorite").html(msg + xhr.status + " " + xhr.statusText);
            Toggle("favorite");
        }
        else {
            Toggle("favorite");
            if (response.length <= 0) {
                jQuery("#favorite").html("<h1>Currently no Favorites added</h1>");
                //Toggle("favorite");
            }
            else {
                var retval = xhr.getResponseHeader("RequestStatus");
                if (retval != "") {
                    switch (retval) {
                        case "1":
                            Companies = new Array();
                            Companies = jQuery.parseJSON(xhr.getResponseHeader("Companies"));
                            jQuery("#favorite").html(response);
                            Markcompanies();
                            break;
                        case "2":
                            jQuery("#favorite").html("<h1>Currently no Favorites added</h1>");
                            break;
                        case "3":
                            break;
                        case "4":
                            //jQuery("#favorite").html("Session Expire. Please click <a href='" + sitepath + "default.aspx'>here</a> to relogin.");
                            document.location.assign(sitepath + "default.aspx?msg=You have been idle for at least 20 minutes and have been logged out. Please sign in again to continue.");
                            break;
                    }
                }
            }

        }
        try {
            jQuery('#favorite').touchScroll();
        }
        catch (e)
                            { }
    });

}
function ShowUserNearByCompanies() {
    Toggle("listing");
    jQuery('#imgSpinner').show();
    //alert("lat=" + mylat + " and lng=" + mylong);
    var url = sitepath + 'GetUserNearBy.aspx?lat=' + mylat + '&lng=' + mylong + "&rnd=" + new Date().getTime();
    jQuery.getJSON(url, function (data, status, xhr) {
        var retval = xhr.getResponseHeader("RequestStatus");
        switch (retval) {
            case "1":
                prevCompanies = Companies;
                Companies = data;
                MarkNearBycompanies("\"" + jQuery("#ctl00_txtLocation").val() + "\" Nearby companies.");
                break;
            case "2":
                jQuery("#listing").html("<h1>No Company found near your location \"" + jQuery("#ctl00_txtLocation").val() + "\". </h1>");
                //Toggle("listing");
                break;
            case "3":
                break;
            case "4":
                document.location.assign(sitepath + "default.aspx?msg=You have been idle for at least 20 minutes and have been logged out. Please sign in again to continue.");
                break;
        }
    });
}
function getCompaniesAt(pos_lat, pos_lng) {
    jQuery('#imgSpinner').show();
    prevCompanies = Companies;
    Toggle("listing");
    jQuery("#listing").html("");
    jQuery.getJSON(sitepath + 'GetUserNearBy.aspx?lat=' + pos_lat + '&lng=' + pos_lng + "&rnd=" + new Date().getTime(), function (data, status, xhr) {
        Companies = data;
        nearby = true;
        Markcompanies();
    });
}
function getCompaniesNearBy(CompanyId, name) {
    if (name == null)
        name = "Companies";
    jQuery('#imgSpinner').show();
    jQuery.getJSON(sitepath + 'GetCompanyNearBy.aspx?id=' + CompanyId + "&rnd=" + new Date().getTime(), function (data, status, xhr) {
        prevCompanies = Companies;
        Toggle("listing");
        Companies = data;
        nearby = true;
        MarkNearBycompanies(name + " Nearby companies");
        jQuery('#imgSpinner').hide();
    });
}
function SetFavorite(id) {
    jQuery('#imgSpinner').show();
    jQuery.get(sitepath + "SetFavorite.aspx?id=" + id + "&rnd=" + new Date().getTime(), function (data) {
        if (data) {
            alert("Added to favorites..");
        }
        else {
            alert("Adding to favorites failed.");
        }
        jQuery('#imgSpinner').hide();
    }
            );

}
function SetFlag(id) {
    jQuery('#imgSpinner').show();
    if (confirm("Are you sure you want to continue with this flag?")) {
        jQuery.get(sitepath + "SetFlag.aspx?id=" + id + "&reason=test&rnd=" + new Date().getTime(), function (data) {
            if (data) {
                alert("Company Flagged.");
            }
            else {
                alert("Company Flaging failed.");
            }
            jQuery('#imgSpinner').hide();
            jQuery("#FlagType").hide();
        }
            );
    }
    else {
        jQuery('#imgSpinner').hide();
    }

}
function DeleteHistory() {

    if (confirm('Do you really want to delete All?')) {
        jQuery.get(sitepath + "DeleteHistory.aspx?reason=test&rnd=" + new Date().getTime(), function (data) {
            if (data) {
                jQuery("#history").html("<h1>Currently no history exists</h1>");
                jQuery("#cmdDeleteHistory").hide();
                alert("History Deleted.");
            }
            else {
                alert("Deletion failed.");
            }

        }
            );


    }

}
function CollectDirectionHit(id) {
    jQuery('#imgSpinner').show();
    jQuery.get(sitepath + "CollectDirectionHits.aspx?id=" + id + "&rnd=" + new Date().getTime(), function (data) {
        jQuery('#imgSpinner').hide();
    });
}


function calcRoute(source, dest) {
    var route = [
            new google.maps.LatLng(32.845857, -85.983852),
            new google.maps.LatLng(32.914349, -85.967554)
            ];
    jQuery("#directions_panel").html("");
    var start = source;
    var end = dest;
    var request = {
        origin: start,
        destination: end,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    //            var directionsDisplay;
    if (directionsService == null) {
        directionsService = new google.maps.DirectionsService();
    }
    if (directionsDisplay == null) {
        directionsDisplay = new google.maps.DirectionsRenderer({
            'map': map,
            'preserveViewport': true,
            'draggable': false
        });
    }
    directionsDisplay.setPanel(document.getElementById("directions_panel"));
    directionsService.route(request, function (response, status) {
        prevCompanies = Companies;
        if (status == google.maps.DirectionsStatus.OK) {
            //directionsDisplay.setDirections(response);
            ClearMarkers();
            if (locationmarker != null) {
                locationmarker.setMap(null);
            }
            //alert(status);
            if (currentDirections) {
                directionsDisplay.setMap(null); //Call To clear old path
                directionsDisplay.setMap(map); //Set Map again
                directionsDisplay.setDirections(response); //Draw new path
                currentDirections = directionsDisplay.getDirections(); //Hold current path to handle last path
            }
            else {
                currentDirections = directionsDisplay.getDirections();
                directionsDisplay.setDirections(response);
            }
            jQuery("#directions_panel").append("<a class='print' href='javascript:printElem(\"directions_panel\",{ leaveOpen: true, printMode: \"popup\" })'>Print</a>");
            Toggle("directions_panel");
            Companies = new Array();
            Companies.push(source);
            Companies.push(dest);
            var bounds = new google.maps.LatLngBounds();
            bounds.extend(source);
            bounds.extend(dest);
            map.fitBounds(bounds);
            try {
                jQuery('#directions_panel').touchScroll();
            }
            catch (e)
                            { }

        }
        else {
            //ZERO_RESULTS
            jQuery("#directions_panel").html("<h3>Unable to get direction. Seems your current location to company location is unreachable.Please try to change you current location using <a href='javascript:DisplayLocationBox(true);'>Change default location</a>.</h3>");
            Toggle("directions_panel");
            Companies = null;
            displayMap();

        }
    });
}


function calcRouteOnPop(source, dest) {
    var route = [
            new google.maps.LatLng(32.845857, -85.983852),
            new google.maps.LatLng(32.914349, -85.967554)
            ];
    jQuery("#directions_panel").html("");
    var start = source;
    var end = dest;
    var request = {
        origin: start,
        destination: end,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    //            var directionsDisplay;
    if (directionsService == null) {
        directionsService = new google.maps.DirectionsService();
    }
    if (directionsDisplay == null) {
        directionsDisplay = new google.maps.DirectionsRenderer({
            'map': map,
            'preserveViewport': true,
            'draggable': false
        });
    }
    directionsDisplay.setPanel(document.getElementById("directions_panel"));
    directionsService.route(request, function (response, status) {
        prevCompanies = Companies;
        if (status == google.maps.DirectionsStatus.OK) {
            //directionsDisplay.setDirections(response);
            ClearMarkers();
            if (locationmarker != null) {
                locationmarker.setMap(null);
            }
            //alert(status);
            if (currentDirections) {
                directionsDisplay.setMap(null); //Call To clear old path
                directionsDisplay.setMap(map); //Set Map again
                directionsDisplay.setDirections(response); //Draw new path
                currentDirections = directionsDisplay.getDirections(); //Hold current path to handle last path
            }
            else {
                currentDirections = directionsDisplay.getDirections();
                directionsDisplay.setDirections(response);
            }
            jQuery("#directions_panel").append("<a class='print' href='javascript:printElem(\"directions_panel\",{ leaveOpen: true, printMode: \"popup\" })'>Print</a>");
            var bounds = new google.maps.LatLngBounds();
            bounds.extend(source);
            bounds.extend(dest);
            map.fitBounds(bounds);
            try {
                jQuery('#directions_panel').touchScroll();
            }
            catch (e)
                            { }

        }
        else {
            //ZERO_RESULTS
            jQuery("#directions_panel").html("<h3>Unable to get direction. Seems your current location to company location is unreachable.Please try to change you current location using <a href='javascript:DisplayLocationBox(true);'>Change default location</a>.</h3>");

        }
    });
}





function DisplayLocationBox(show) {
    if (show) {
        jQuery("#DisplayLocationDiv").hide();
        jQuery("#ChangeLocationDiv").show();
        jQuery(".spinner").hide();
    }
    else {
        jQuery("#DisplayLocationDiv").show();
        jQuery("#ChangeLocationDiv").hide();
    }
}
function printElem(div_name, options) {
    jQuery('#' + div_name).printElement(options);
}
function codeAddress(address) {
    jQuery('#imgSpinner').show();
    if (address.length > 0) {
        geocoder = new google.maps.Geocoder();

        geocoder.geocode({ 'address': address }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                mylat = results[0].geometry.location.lat();
                mylong = results[0].geometry.location.lng();
                Save_Location_To_Session(mylat, mylong);
                Save_Location(mylat, mylong);
                display();
                DisplayLocationBox(false);
                //                    jQuery("#div_location").hide();
            } else {
                //alert("Geocode was not successful for the following reason: " + status);
                //                    jQuery("#div_location").show();
                DisplayLocationBox(true);
            }
        });
    }
    else {
        DisplayLocationBox(true);
    }
}
function GetUserProfileAddress() {
    jQuery('#imgSpinner').show();
    jQuery.get(sitepath + "GetUserProfileAddress.aspx?rnd=" + new Date().getTime(), function (response, status, xhr) {
        if (status == "error") {
            var msg = "Sorry but there was an error: ";
            jQuery("#directions_panel").html(msg + xhr.status + " " + xhr.statusText);
            jQuery("#directions_panel").show();
            jQuery("#company_info").hide();
        }
        else {
            jQuery("#txtAddress").val(response);
            jQuery("#ctl00_txtLocation").val(response);
        }

        if (response.length > 0) {
            LocateAddress();
        }
        else {
            DisplayLocationBox(true);
        }
        jQuery('#imgSpinner').hide();
    });
}
function LocateAddress() {
    jQuery('#imgSpinner').show();
    codeAddress(jQuery("#txtAddress").val());
    DisplayLocationBox(false);
    // jQuery('#imgSpinner').hide();          
}
function getCoordinatesFromAddress(address) {
    jQuery('#imgSpinner').show();
    if (address.length > 0) {
        geocoder = new google.maps.Geocoder();
        geocoder.geocode({ 'address': address }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                var temp_mylat = results[0].geometry.location.lat();
                var temp_mylong = results[0].geometry.location.lng();
                var loc = new google.maps.LatLng(temp_mylat, temp_mylong);
                getCompaniesAt(temp_mylat, temp_mylong);
            } else {
                var loc = new google.maps.LatLng(mylat, mylong);
                getCompaniesAt(loc.lat(), loc.lng());
            }
            //jQuery('#imgSpinner').hide();
        });
    }
}
function NoUserLocationResponse() {
    //alert("reply very late");
    if (jQuery("#ctl00_hdnLocation").val().length <= 0) {
        GetUserProfileAddress();
    }
    clearTimeout(georesponseTimerId);
}
function GetCurrentPosition() {
    jQuery('#imgSpinner').show();
    if (loggedin) {
        if (jQuery("#ctl00_hdnLocation").val().length > 0) {
            var savedvalue = jQuery("#ctl00_hdnLocation").val();
            var arr = savedvalue.split(",");
            mylat = arr[0];
            mylong = arr[1];
            Save_Location(mylat, mylong);
            //if (jQuery("#mapdiv").length > 0) 
            {
                try {
                    var latlng = new google.maps.LatLng(mylat, mylong);
                    map.setCenter(latlng);
                    display();
                }
                catch (e) { }
            }
        }
        else {
            georesponseTimerId = setInterval(NoUserLocationResponse, 15000);
            if (navigator.geolocation) {

                //locate position
                navigator.geolocation.getCurrentPosition(SetPosition, errorFunction, {
                    maximumAge: 60000,
                    timeout: 10000
                });
            }
            else {
                // test to see if the blackberry location API is supported
                if (window.blackberry && blackberry.location.GPSSupported) {
                    //It will error on refresh and all javascript processing on the page will stop
                    //blackberry.location.onLocationUpdate(locationCB());
                    var gps = blackberry.location.GPSSupported;
                    // set to Assisted mode
                    blackberry.location.setAidMode(1);
                    blackberry.location.refreshLocation();
                    setblackberryPosition(blackberry.location.latitude, blackberry.location.longitude);
                    // RIGHT: pass a string that calls our method
                    blackberry.location.onLocationUpdate(locationCB());
                    // set to Autonomous mode
                    blackberry.location.setAidMode(2);
                    //refresh the location
                    blackberry.location.refreshLocation();
                }
                else {
                    GetUserProfileAddress();
                }
            }
        }
        jQuery('#mapDiv').ajaxSend(function () {
            jQuery('#imgSpinner').show();
        });
        //                jQuery('#mapDiv').ajaxComplete(function () {
        //                    jQuery('#imgSpinner').hide();
        //                });
        //                jQuery('#mapDiv').ajaxError(function () {
        //                    jQuery('#imgSpinner').hide();
        //                });
        jQuery('#mapDiv').ajaxStop(function () {
            jQuery('#imgSpinner').hide();
        });
        var hash = "";
        if (location.hash.length > 0) {
            hash = location.hash;
            switch (hash) {
                case "#Favorite":
                    Toggle("favorite");
                    break;
                case "#History":
                    Toggle("history");
                    break;
                default:
                    break;
            }

        }
    }
}

function displayMap() {
    //alert("inside displaymap");
    //alert(mylat + " " + mylong);
    var latlng = new google.maps.LatLng(mylat, mylong);
    map.setCenter(latlng);
    map.setZoom(4);            //Add marker

    var image = 'images/blue-dot.png';
    if (locationmarker != null) {
        locationmarker.setMap(null);
        ClearMarkers();
    }

    locationmarker = new google.maps.Marker({
        position: latlng,
        map: map,
        icon: image,
        animation: google.maps.Animation.DROP,
        title: "You are here"
    });

    var infowindow = new google.maps.InfoWindow({
        content: "<strong>Your Location</strong>"
    });
    google.maps.event.addListener(locationmarker, 'click', function () {
        infowindow.open(map, locationmarker);
    });
}

//Display function
function display() {

    jQuery('#imgSpinner').show();
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(mylat, mylong);
    geocoder.geocode({ 'latLng': latlng }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[1]) {
                jQuery("#txtAddress").val(results[1].formatted_address);
                jQuery("#ctl00_txtLocation").val(results[1].formatted_address);
            }
        }
        else {
            alert("Geocoder failed due to: " + status);
        }

    });

    //Add marker
    //alert("location marker" + locationmarker);
    var image = 'images/blue-dot.png';
    if (locationmarker != null) {
        locationmarker.setMap(null);
        ClearMarkers();
    }
    locationmarker = new google.maps.Marker({
        position: latlng,
        map: map,
        icon: image,
        animation: google.maps.Animation.DROP,
        title: "You are here"
    });
    //            markers = new Array();
    //            markers[0] = locationmarker;            
    var infowindow = new google.maps.InfoWindow({
        content: "<strong>Your Location</strong>"
    });
    google.maps.event.addListener(locationmarker, 'click', function () {
        infowindow.open(map, locationmarker);
    });
    ShowUserNearByCompanies();
    Save_Location_To_Session(mylat, mylong);
}

//Update position Variables
function SetPosition(pos) {
    mylat = pos.coords.latitude;
    mylong = pos.coords.longitude;
    Save_Location(mylat, mylong);
    var latlng = new google.maps.LatLng(mylat, mylong);
    //alert(map);
    if (map != null) {
        try {
            map.setCenter(latlng);
        }
        catch (e) { }
    }
    display();
    return true;
}
function setblackberryPosition(lat, lng) {
    mylat = lat;
    mylong = lng;
    var latlng = new google.maps.LatLng(mylat, mylong);
    map.setCenter(latlng);
    Save_Location(mylat, mylong);
    display();
    return true;
}
function locationCB() {
    var gps = blackberry.location.GPSSupported;
    // set to Assisted mode
    blackberry.location.setAidMode(1);
    blackberry.location.refreshLocation();
    setblackberryPosition(blackberry.location.latitude, blackberry.location.longitude);
}
//Error Functions Below
function errorFunction(err) {
    if (google.gears) {
        // Try Google Gears Geolocation
        //browserSupportFlag = true;
        var geo = google.gears.factory.create('beta.geolocation');
        geo.getCurrentPosition(SetPosition, handleError);
    }
    else {
        try {
            DisplayLocationBox(true);
        }
        catch (e) {
            // alert("Address find error");
        }
    }
}
function geo_error() {
    //alert("Could not find you!");
    jQuery("#a").ready(function () {
    });
}
function handleError(positionError) {
    // alert('Attempt to get location failed: ' + positionError.message);
}
function Save_Location(lat_val, lng_val) {
    jQuery('#imgSpinner').show();
    jQuery("#ctl00_hdnLocation").val(lat_val + "," + lng_val);
}
function Save_Location_To_Session(lat_val, lng_val) {
    jQuery('#imgSpinner').show();
    jQuery.get(sitepath + 'SetUserLocation.aspx?lat=' + mylat + '&lng=' + mylong + "&rnd=" + new Date().getTime(), function (data) {
        if (data) {
            return true;
        }
        else {
            return false;
        }

    });
}
function getAbsolutePath() {
    var loc = window.location;
    var pathName = loc.pathname.substring(0, loc.pathname.lastIndexOf('/') + 1);
    return loc.href.substring(0, loc.href.length - ((loc.pathname + loc.search + loc.hash).length - pathName.length));
}
function getArgs() {
    var args = new Array();
    var query = location.search.substring(1);
    var pairs = query.split("&");
    for (var i = 0; i < pairs.length; i++) {
        var pos = pairs[i].indexOf('=');
        if (pos == -1) continue;
        var argname = pairs[i].substring(0, pos);
        var value = pairs[i].substring(pos + 1);
        args[argname] = unescape(value);
    }
    return args;
}
jQuery(document).ready(function () {
    var Args = getArgs();
    if (Args["msg"] != null) {
        var msgctrl = jQuery(".alert"); //jQuery("#ctl00_pagemid_DropZone2_columnDisplay_ctl00_controlcolumn_ctl00_WidgetHost_WidgetHost_widget_sign_in_lblMessage");
        if (msgctrl.length > 0) {
            jQuery(msgctrl).html(Args["msg"]);
        }
    }
    else {
        var hash = "";
        if (location.hash.length > 0) {
            hash = location.hash;
            //alert(hash);
            switch (hash) {
                case "#Favorite":
                    ShowUserFavorite();
                    jQuery("#ctl00_btnFavorite").addClass("active");
                    jQuery("#ctl00_btnHistory").removeClass("active");
                    jQuery("#nav_search > a").removeClass("active");
                    break;
                case "#History":
                    ShowUserHistory();
                    jQuery("#ctl00_btnHistory").addClass("active");
                    jQuery("#ctl00_btnFavorite").removeClass("active");
                    jQuery("#nav_search > a").removeClass("active");
                    break;
                default:
                    break;
            }
            if (jQuery("#ctl00_hdnLocation").val().length > 0) {
                var savedvalue = jQuery("#ctl00_hdnLocation").val();
                var arr = savedvalue.split(",");
                mylat = arr[0];
                mylong = arr[1];
                var latlng = new google.maps.LatLng(mylat, mylong);
                geocoder = new google.maps.Geocoder();
                geocoder.geocode({
                    'latLng': latlng
                }, function (results, status) {
                    // alert("status1" + status);
                    if (status == google.maps.GeocoderStatus.OK) {
                        if (results[1]) {
                            jQuery("#txtAddress").val(results[1].formatted_address);
                            jQuery("#ctl00_txtLocation").val(results[1].formatted_address);
                            //alert(!issearch);
                            if (!issearch) {
                                display();
                            }

                        }
                    }
                });
            }
        } else {
            var s = location.pathname.toLowerCase().split("/");
            var pagename = "";
            if (s.length > 0) {
                pagename = (s[s.length - 1]);
            }
            try {
                switch (pagename) {
                    case "default.aspx":
                        jQuery("#nav_home > a").addClass("active");
                        jQuery("#nav_search > a").addClass("active");
                        break;
                    case "environments.html":
                        jQuery("#nav_environment > a").addClass("active");
                        break;
                    case "purchase_details.html":
                        jQuery("#nav_puchase > a").addClass("active");
                        break;
                    case "contactus.html":
                        jQuery("#nav_help > a ").addClass("active");
                        break;
                    case "":
                        jQuery("#nav_home > a").addClass("active");
                        jQuery("#nav_search > a").addClass("active");
                        break;
                    case "communityprofile.aspx":
                        jQuery("#ctl00_lnkProfile").addClass("active");
                }
            }
            catch (e)
            { }
            //ShowUserFavorite()
            jQuery('#ctl00_BtnSearch').bind('click', function () {
                if (jQuery("#ctl00_TxtSearch").val().length > 0) {
                    if (jQuery("#ctl00_ddlSearchType").val() == "1") return true;
                    else {

                        try {
                            //alert("before search call");
                            getCoordinatesFromAddress(jQuery("#ctl00_TxtSearch").val());
                        } catch (e) {
                            //alert("Error" + e);
                        }


                        return false;
                    }
                } else {
                    return false;
                }
            });
            if (jQuery("#ctl00_hdnLocation").val().length > 0) {
                var savedvalue = jQuery("#ctl00_hdnLocation").val();
                var arr = savedvalue.split(",");
                mylat = arr[0];
                mylong = arr[1];
                var latlng = new google.maps.LatLng(mylat, mylong);
                geocoder = new google.maps.Geocoder();
                geocoder.geocode({
                    'latLng': latlng
                }, function (results, status) {
                    //alert("status2" + status);
                    if (status == google.maps.GeocoderStatus.OK) {
                        //alert("resulat" + results[1]);
                        if (results[1]) {
                            jQuery("#txtAddress").val(results[1].formatted_address);
                            //alert("result address" + results[1].formatted_address);
                            jQuery("#ctl00_txtLocation").val(results[1].formatted_address);
                            //alert(!issearch);
                            if (!issearch) {
                                //alert("inside if not of issearch");
                                display();
                            }
                        }
                    } else {
                        //alert("Geocoder failed due to: " + status);
                    }

                });
            }
            GetCurrentPosition();
        }

        //                window.onorientationchange = function () {

        //                    var orientation = window.orientation;
        //                    alert(orientation);
        //                    switch (orientation) {
        //                        case 0:
        //                            document.body.setAttribute("class", "portrait");
        //                            break;
        //                        case 90:
        //                            document.body.setAttribute("class", "landscapeLeft");
        //                            break;
        //                        case -90:

        //                            document.body.setAttribute("class", "landscapeRight");

        //                            break;
        //                    }
        //                }
    }
});
function setactive(obj) {
    jQuery("#ctl00_btnFavorite").removeClass("active");
    jQuery("#ctl00_btnHistory").removeClass("active");
    jQuery("#nav_search > a").removeClass("active");
    jQuery(obj).addClass("active");
}
