var longitude = null;
var latitude = null;

function dexknowsrdlogger(bdcz, bdcr)
{
  try {
    var myImage = new Image();
    var imgSrc='';
    var ourDate = new Date();
    var interaction_ord = "" + ourDate.getFullYear() + (ourDate.getMonth() + 1) + ourDate.getDate() + ourDate.getHours() + ourDate.getMinutes() + ourDate.getSeconds() + Math.floor(Math.random()*11) ;
    imgSrc = interaction_rdurl + '/RDlog.gif?bdcf=' +  interaction_nodeuuid + '&mktid=' + escape(interaction_mktid) + '&mkw=' + escape(interaction_mkw) + '&bdcz=' + bdcz + '&bdcs=' + interaction_bdcs + '&bdcr=' + bdcr + '&ord=' +interaction_ord;
    myImage.src = imgSrc;
    } catch (e) {}	 
}

function processOnlineClick(id)
{
   //alert(document.getElementById(id).checked );
}

function SelectAll(id) {
var currentstyle = document.getElementById(id).style.className;
var currentvalue = document.getElementById(id).value;
   if (document.getElementById(id).disabled == false){
       document.getElementById(id).focus();
       document.getElementById(id).select();
    
       document.getElementById(id).className = 'ce-location-enter';
   }
}

function disablelocation(id)
{

   if(document.getElementById(id).disabled == true){
       document.getElementById(id).disabled = false ;   
    }
    else{
       document.getElementById(id).disabled = true ;
       document.getElementById(id).value = 'City, State';
    }
}


function locationfocus(id)
{
     //document.getElementById('location-search-error').innerHTML="&nbsp;";

}


function checkEnter(e){
    var characterCode

    if(e && e.which){ 
        e = e;
        characterCode = e.which ;
    }
    else{
        e = event;
        characterCode = e.keyCode;
    }

    if(characterCode == 13){ 
        DexGeoAjaxCall(document.getElementById('location').value);
        return false ;
    }
    else{
        return true ;
    }

}



function DexGeoAjaxCall(q) {

 dexknowsrdlogger('j.dexknows.formOpen.i', 0);

 
 if (q == "City, State" ) {

     try { document.getElementById('location-search-error').style.visibility = 'block'; } catch (e) { }
     document.getElementById('location-search-error').style.display = 'block';
     document.getElementById('location-search-error').innerHTML = "Please enter a location";
     document.getElementById('location').focus();

 } else {
        var req = null;
        var LocalityName = null;
        var Accuracy = null;
        var AdministrativeAreaName = null;
        var coordinates = null;
        var CountryNameCode = null;
        var PostalCodeNumber = null;
        //alert("Started...");

        if (window.XMLHttpRequest)
        {
                req = new XMLHttpRequest();
                if (req.overrideMimeType) 
                {
                        req.overrideMimeType('text/xml');
                }
        } 
        else if (window.ActiveXObject) 
        {
                try {
                        req = new ActiveXObject("Msxml2.XMLHTTP");
                } catch (e)
                {
                        try {
                                req = new ActiveXObject("Microsoft.XMLHTTP");
                        } catch (e) {}
                }
        }


        req.onreadystatechange = function() {
            //alert("Wait server...");
            if (req.readyState == 4) {
                if (req.status == 200 && req.responseText.indexOf("Servlet Exception") == -1) {
                    //alert("got google geo code document:" + req.responseText);
                    try {
                        LocalityName = req.responseXML.getElementsByTagName('LocalityName')[0].firstChild.data;
                    } catch (e) { LocalityName = "" }

                    try {
                        if (LocalityName == "") {
                            try {
                                Accuracy = req.responseXML.getElementsByTagName("AddressDetails")[0].getAttribute("Accuracy");
                            } catch (e) { LocalityName = "" }
                            if (Accuracy == "4") {
                                try {
                                    LocalityName = req.responseXML.getElementsByTagName('DependentLocalityName')[0].firstChild.data;
                                } catch (e) { LocalityName = "" }
                                if (LocalityName == "") {
                                    try {
                                        LocalityName = req.responseXML.getElementsByTagName('AddressLine')[0].firstChild.data;
                                    } catch (e) { LocalityName = "" }
                                }
                                //alert("new locality assigned");
                            }
                        }
                    } catch (e) { LocalityName = "" }

                    try {
                        CountryNameCode = req.responseXML.getElementsByTagName('CountryNameCode')[0].firstChild.data;
                    } catch (e) { CountryNameCode = "" }

                    try {
                        PostalCodeNumber = req.responseXML.getElementsByTagName('PostalCodeNumber')[0].firstChild.data;
                    } catch (e) { PostalCodeNumber = "" }

                    try {
                        AdministrativeAreaName = req.responseXML.getElementsByTagName('AdministrativeAreaName')[0].firstChild.data;
                    } catch (e) { AdministrativeAreaName = "" }


                    try {
                        coordinates = req.responseXML.getElementsByTagName('coordinates')[0].firstChild.data;
                        //alert("got: " + coordinates);
                        var locArray = coordinates.split(",")
                        for (var i = 0; i < locArray.length; i++) {
                            if (i == 0) longitude = locArray[i];
                            if (i == 1) latitude = locArray[i];

                        }
                        //alert("set long / lat to " + longitude + ":" +latitude) ;

                    } catch (e) { coordinates = "" }

                    if (CountryNameCode == "") {
                        try { document.getElementById('location-search-error').style.visibility = 'block'; } catch (e) { }
                        document.getElementById('location-search-error').style.display = 'block';
                        document.getElementById('location-search-error').innerHTML = "Please try another location";
                        document.getElementById('location').focus();
                    }
                    else if (CountryNameCode != "US") {
                        try { document.getElementById('location-search-error').style.visibility = 'block'; } catch (e) { }
                        document.getElementById('location-search-error').style.display = 'block';
                        document.getElementById('location-search-error').innerHTML = "Please enter a location in the USA";
                        document.getElementById('location').focus();
                    }
                    else if (CountryNameCode == "US") {
                        var wherevalue = ""
                        try {
                            wherevalue = LocalityName;
                            if (wherevalue.length > 0) wherevalue += ", " + AdministrativeAreaName;
                        } catch (e) { }
                        /*try {
                        document.cookie = "localdata=" + escape(longitude) + "|" + escape(latitude) + "|" + escape(wherevalue) + "; path=/";
                        } catch (e) { }*/

                        var loc = document.location + "";
                        loc = loc.replace("index.asp", "");
                        loc = loc.replace("weblistings.asp", "");
                        loc = loc.replace("companyprofiles.asp", "");
                        var newatts = "";
                        var altered = false;

                        loc = loc.replace("o-exclude-online", "");
                        loc = loc.replace("----", "--");

                        // strip out anchor
                        if (loc.indexOf("#") > -1) {
                            try {
                                loc = loc.substring(0, loc.indexOf("#"));
                            } catch (e) { }
                        }
                        // strip out querystring
                        if (loc.indexOf("?") > -1) {
                            try {
                                loc = loc.substring(0, loc.indexOf("?"));
                            } catch (e) { }
                        }

                        //if the loc already has location information, remove it before adding the new location
                        if (loc.indexOf("/m/") > -1) {
                            //alert(loc);

                            var locatts = loc.substring(loc.indexOf("/m/") + 3, loc.length);
                            if (locatts.charAt(locatts.length - 1) == "/") {
                                locatts = locatts.substring(0, locatts.length - 1);
                                var locattsArray = locatts.split("--")
                                for (var i = 0; i < locattsArray.length; i++) {
                                    var thisatt = locattsArray[i];
                                    //alert(thisatt);
                                    if (thisatt.length > 2 && (thisatt.substring(0, 2) == "c-" || thisatt.substring(0, 2) == "s-" || thisatt.substring(0, 2) == "z-")) {

                                    } else {
                                        if (newatts.length > 0) newatts = newatts + "--";
                                        newatts = newatts + thisatt;
                                        altered = true;
                                        //alert("normal found: " + thisatt);
                                    }
                                }
                            }
                            //alert(locatts);
                            var locstem = loc.substring(0, loc.indexOf("/m/"));
                            locstem = locstem + "/m/"
                            loc = locstem + newatts;
                            //if(newatts.length > 0 && newatts.indexOf("--") == -1 ) loc=loc+"--";
                            //alert(loc);
                        }

                        var dashdash = "--";

                        if (loc.indexOf("/m/") == -1) {
                            loc = loc + "m/"
                        }
                        /*else if ( loc.charAt (loc.length - 1) == "/" ) {
                        loc=loc.substring(0,loc.length -1);
                        }*/

                        if (loc.charAt(loc.length - 1) == "-" || newatts.length == 0) dashdash = "";
                        else dashdash = "--";

                        if (PostalCodeNumber != null && PostalCodeNumber.length > 0) {
                            loc = loc + dashdash + "z-" + PostalCodeNumber.toLowerCase().replace(/ /g, "_");
                            altered = true;
                        }

                        if (loc.indexOf("--") == -1 && altered == false) dashdash = "";
                        else dashdash = "--";

                        if (AdministrativeAreaName != null && AdministrativeAreaName.length > 0) {
                            loc = loc + dashdash + "s-" + AdministrativeAreaName.toLowerCase().replace(/ /g, "_");
                            altered = true;
                        }

                        if (loc.indexOf("--") == -1 && altered == false) dashdash = "";
                        else dashdash = "--";

                        if (LocalityName != null && LocalityName.length > 0) {
                            loc = loc + dashdash + "c-" + LocalityName.toLowerCase().replace(/ /g, "_");
                            altered = true;
                        }

                        if (altered) {
                            if (loc.charAt(loc.length - 1) != "/") {
                                loc = loc + "/";
                            }
                            loc = loc.replace("----", "--");
                            dexknowsrdlogger('j.dexknows.formComplete.i', 0);
                            document.location = loc;
                        } else {
                            document.getElementById('location-search-error').innerHTML = "Please try another location";
                            document.getElementById('location').focus();
                        }
                    }

                }
                else {
                    window.status = "Error: returned status code " + req.status + " " + req.statusText;
                }
            }
        }; 

        req.open("GET", "/include/googlegeo.asp?q=" + escape(q) + "+USA&buster=" + escape(new Date()), true); 
        req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
        req.send(null); 

    }
}


function cm_createMarker(point, title, html) {
    var markerOpts2 = {};
    markerOpts2 = {
        "icon": icon,
        "draggable": true,
        "clickable": true,
        "labelClass": "markerclass" + markerclassid++ + "",
        "labelText": "<span style=\"font-family:arial;font-weight:bold;font-size:14px;\"> " + title + "</span>",
        "labelOffset": new GSize(-16, -8)
    };
    var markerOpts = {};
    markerOpts = {
        "icon": icon,
        "draggable": true,
        "clickable": true,
        "labelText": "<span style=\"font-family:arial;font-weight:bold;font-size:14px;\"> " + title + "</span>",
        "labelOffset": new GSize(-16, -8)
    };
    var marker = new LabeledMarker(point, markerOpts);
    GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(html);
    });

    return marker;
}

function cm_markerClicked(markerNum) {
    var opts = { maxWidth: 200 };
    mapMarkers[markerNum].openInfoWindowHtml(mapHTMLS[markerNum], opts);
}

function cm_markerClickedReverse(markerNum) {
    //alert("got: " + listingArray.length );
    var reverseNum = (listingArray.length - markerNum) - 1;

    var opts = { maxWidth: 200 };
    mapMarkers[reverseNum].openInfoWindowHtml(mapHTMLS[reverseNum], opts);
}

function cm_markerClickedLetter(markerLetter) {
    //alert("got: " + listingArray.length );
    var markerNum = 0;
    if (markerLetter == 'A') markerNum = 0;
    if (markerLetter == 'B') markerNum = 1;
    if (markerLetter == 'C') markerNum = 2;
    if (markerLetter == 'D') markerNum = 3;
    if (markerLetter == 'E') markerNum = 4;
    if (markerLetter == 'F') markerNum = 5;
    if (markerLetter == 'G') markerNum = 6;
    if (markerLetter == 'H') markerNum = 7;
    if (markerLetter == 'I') markerNum = 8;
    if (markerLetter == 'J') markerNum = 9;
    if (markerLetter == 'K') markerNum = 10;
    if (markerLetter == 'L') markerNum = 11;
    if (markerLetter == 'M') markerNum = 12;
    if (markerLetter == 'N') markerNum = 13;
    if (markerLetter == 'O') markerNum = 14;
    if (markerLetter == 'P') markerNum = 15;
    if (markerLetter == 'Q') markerNum = 16;
    if (markerLetter == 'R') markerNum = 17;
    if (markerLetter == 'S') markerNum = 18;
    if (markerLetter == 'T') markerNum = 19;
    var opts = { maxWidth: 200 };
    //alert("showing: " + markerLetter + ":" + markerNum);
    mapMarkers[markerNum].openInfoWindowHtml(mapHTMLS[markerNum], opts);
}


var mapUtil = {

minLat: null,
maxLat: null,
minLng: null,
maxLng: null,

calculateBorders: function(latitude, longitude) {
    latitude = Number(latitude);
    longitude = Number(longitude);
    if(typeof(latitude) == 'number' && typeof(longitude) == 'number') {
    if(mapUtil.minLat == null || mapUtil.minLat > latitude) {
    mapUtil.minLat = latitude;
}

if(mapUtil.maxLat == null || mapUtil.maxLat < latitude) {
    mapUtil.maxLat = latitude;
}

if(mapUtil.minLng == null || mapUtil.minLng > longitude) {
    mapUtil.minLng = longitude;
}

if(mapUtil.minLax == null || mapUtil.maxLng < longitude) {
    mapUtil.maxLng = longitude;
}
}
},

zoomToViewAll: function() {
    var visibleBounds = mapUtil.getVisibleBounds();
    if(visibleBounds) {
        var boundsCentre = visibleBounds.getCenter();
        var zoomLevel = map.getBoundsZoomLevel(visibleBounds);
        if(zoomLevel < 15 ) {
            map.setCenter(boundsCentre, zoomLevel);
        }
        else {
            map.setCenter(boundsCentre, 15);
        }
    }
},

getVisibleBounds: function() {
    if(mapUtil.maxLng) {
        var swLatLng = new GLatLng(mapUtil.minLat, mapUtil.minLng);
        var neLatLng = new GLatLng(mapUtil.maxLat, mapUtil.maxLng);
        var minBounds = new GLatLngBounds(swLatLng, neLatLng);
        return minBounds;
    }
        return null;
    }
}


//use the
//mapUtil.calculateBorders(lat, lng); for each marker
//then call the mapUtil.zoomToViewAll()

//the map is the variable containing GMap2


function getUICookie(name) {
    try {
        var dc = document.cookie;
        path = "/";
        var prefix = name + "=";
        var begin = dc.indexOf("; " + prefix);
        if (begin == -1) {
            begin = dc.indexOf(prefix);
            if (begin != 0) return null;
        } else {
            begin += 2;
        }
        var end = document.cookie.indexOf(";", begin);
        if (end == -1) {
            end = dc.length;
        }
        return unescape(dc.substring(begin + prefix.length, end));
    } catch (e) { }
}