var gdir;
var geocoder = null;
var marker;
var map;
var fromAddress;
var toAddress;

function initialize(mapID) {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById(mapID));
        map.setCenter(center, 9);
        map.setUIToDefault();
        gdir = new GDirections(map, document.getElementById("directions_response"));
        GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);
        marker = new GMarker(center);
        GEvent.addListener(marker, "click", function() {
            marker.openInfoWindowHtml(popUp);
        });
        map.addOverlay(marker);
        //marker.openInfoWindowHtml("test");
    }
    else {
        //document.getElementById("map_container").style.display = "none";
    }
}

function resetMap() {
    map.clearOverlays();
    map.setZoom(7);
    map.panTo(center);
    map.addOverlay(marker);
    marker.openInfoWindowHtml(popUp);
}

function setDirections() {
    /*if (typeof (Page_ClientValidate) == 'function') {
        isValid = Page_ClientValidate();
    }*/
    fromAddress = document.getElementById("ctl00_MainContentePlaceHolder_DirectionsInput").value;
    if (fromAddress.toLowerCase() !== "type your address.") {
        if (fromAddress.toLowerCase() !== "") {
            processing();

            //if(fromAddress=="")
            //{alert("Please enter either a postcode, or a street and town and try again.");resetMap();return;}
            //toAddress = "HBP Systems Woodhouse Road, Scunthorpe @ 53.5744, -0.6231";
            var locale = "en_UK";

            map.clearOverlays();
            gdir.load("from: " + fromAddress + " to: " + toAddress);
        }
    }
    //else {
    //    return false;
    //}
}

function handleErrors() {
    processing();
    if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS) {
        alert("We couldn't find your exact address \"" + fromAddress + "\". This may be because the address you specified is relatively new, incorrect, or you may have to be more specific.\n\nPlease try again.\n\nIf this problem persists, please contact HBP on 01724 400 300");
        resetMap();
        return;
    }
    if (gdir.getStatus().code == G_GEO_SERVER_ERROR) {
        alert("Your directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code + "\n\nPlease try again, putting either postcode or street and town in to the directions box");
        resetMap();
        return;
    }
    if (gdir.getStatus().code == G_GEO_MISSING_QUERY) {
        alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
        resetMap();
        return;
    }
    //   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
    //     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);

    if (gdir.getStatus().code == G_GEO_BAD_KEY) {
        alert("We could not process your query at this present time.\n\n Please contact HBP on 01724 400 300 with the following error:\n\n Error code: " + gdir.getStatus().code + " - Map Key Invalid");
        resetMap();
        return;
    }
    if (gdir.getStatus().code == G_GEO_BAD_REQUEST) {
        alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
        resetMap();
        return;
    }
    else {
        alert("Please check your address and try again.");
        resetMap();
        return;
    }

}

function onGDirectionsLoad() {
    //processing();
    // Use this function to access information about the latest load()
    // results.

    // e.g.
    // document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
    // and yada yada yada...
    document.getElementById("directions_response_container").style.display = "block";
}
function processing() {
    //if(document.getElementById("processing").style.display=="none")
    //	{document.getElementById("processing").style.display="block"}
    //else{document.getElementById("processing").style.display="none"}
}

function view(request, width, height, title, description, type) {
    width = (width == "") ? "500" : width;
    height = (height == "") ? "500" : height;
    type = (type == undefined) ? null : type;
    description = (description == "" || description == undefined) ? "" : description;
    var frameSrc = request.href;
    title = (title == "undefined" ? request.title : title)
    if (type == null) {
        frameSrc = frameSrc + "?&iframe=true&width=" + width + "&height=" + height;
    }
    jQuery.prettyPhoto.open(frameSrc, description, title);
}

function printerFriendlyDirections(request) {
    var description = (description == "" || description == undefined) ? "" : description;
    var frameSrc = request.href;
    var title = request.title;
    var prettyPhotoRequest = frameSrc;
    prettyPhotoRequest = frameSrc + "?&mapdirections=http://maps.google.com/maps?f=d&source=s_d&saddr=" + fromAddress.replace(/ /g, "+") + "&daddr=" + toAddress.replace(/ /g, "+").replace(/@/g, "%40") + "&hl=en&geocode=FXjUEQMd5BL-_yl13iGvC6DYRzGZKtXdWjqWUg%3BFQB7MQMdBH72_w&mra=ls&sll=37.0625,-95.677068&sspn=33.435463,134.912109&ie=UTF8&z=7&layer=c&pw=2&?iframe=true&width=800&height=600"
    jQuery.prettyPhoto.open(prettyPhotoRequest, description, title);
}

function popUp() {
    return "<div class='pop_up'><span class='business_name'>" + CustomerName + "</span><br/>" + Address[0] + ", " + Address[1] + "<br />" + Address[2] + ", " + Address[3] + "<br /><br /><span><a href='mailto:" + EmailAddress + "' title='Send Email to " + CustomerName + "'>" + EmailAddress + "</a><br /><a href='" + CorporateWebAddress + "' title='" + CustomerName + " Home' class='map_text_link'>" + CorporateSiteName + "</a></span></div>"
}

function CheckQueryString() {
    var URL = document.URL;
    if (URL.match("viewmap=true")) {
        jQuery.scrollTo('#ctl00_ctl07_DowloadLinkImg', 500); return false;
    }
}

var SnippetCount = 0;
var SnippetHeight = 0;
var ThisArray = Array();
var FirstSet = true;
var Texts = Array();

function SetHeight(SnippetId, ParentId, TextId) {
    var Text = document.getElementById(TextId);
    var Snippet = document.getElementById(SnippetId);
    var Parent = document.getElementById(ParentId);
    ThisArray.push(Snippet);
    Texts.push(Text);
    SnippetCount++

    if (SnippetCount > 2) {
        var i;
        for (i = 0; i < ThisArray.length; i++) {
            // set snippet default height
            if (SnippetHeight < 1) {
                SnippetHeight = ThisArray[i].clientHeight;
            }
            // set smallet snippet height
            if (ThisArray[i].clientHeight > SnippetHeight) {
                SnippetHeight = ThisArray[i].clientHeight;
            }
        }
        for (i = 0; i < ThisArray.length; i++) {
            if (ThisArray[i].clientHeight < SnippetHeight) {
                var listTags = ThisArray[i].getElementsByTagName("li");
                for (j = 0; j < listTags.length; j++) {
                    if (listTags[j].className.match("footer")) {
                        listTags[j].style.paddingTop = (SnippetHeight - ThisArray[i].clientHeight) + "px";
                    }                       
                }
            }  
        }
        
        // reset count
        SnippetCount = 0;
        SnippetHeight = 0;
        ThisArray.length = 0;
        Texts.length = 0;
    }
}

function ie() {
    var isIe = navigator.userAgent.toLowerCase().match("msie");
    return isIe;
}