var showAutos = false;
var showCommCenters = false;
var showGardens = false;
var showBikeRoutes = false;
var showPools = false;
var minx = new Array();
var miny = new Array();
var maxx = new Array();
var maxy = new Array();
var theStartpos = 0;
var visibleLayerArr = new Array();
var layerGoRound = 0;
var resultSet = new Array();
var countSet = new Array();
var theActiveLayerID = 0;
var mheight = "650";
var mwidth = "800";
var weAreGeoCoding = false;
var theFullAddress = "";
var marker;
var theLatitudeIE = 0;
var theLongitudeIE = 0;
var theZoomIE = 0;
var map;
var point = new Array();
var glbCount = 0;
var marker = new Array();
var infoTabs = new Array();
//var geocoder = new GClientGeocoder();
//var map = new GMap2(document.getElementById("map"));

function getServiceInfo() {
    var axl = '<?xml version="1.0" encoding="UTF-8"?><ARCXML version="1.1">\n<REQUEST>\n<GET_SERVICE_INFO renderer="false" extensions="false" fields="false" />\n</REQUEST>\n</ARCXML>\n';
    http = getHTTPObject();
    //if ((http != null) && (!isWorking)) {
    if ((http != null)) {

        http.open("POST", url, true);
        http.onreadystatechange = parseLayers;
        isWorking = true;

        http.send(axl);
    }
}


function parseLayers() {
    if (http.readyState == 4) {

        if (http.status == 200) {

            var result = http.responseText;

        } else alert("Error retreiving data");

    }

}

function getTheLayers(i) {
    //alert("weAreGeoCoding = " + weAreGeoCoding);
    //if (visibleLayers > 0){
    var axl = cqBuildQuery(i);
    theActiveLayerID = i;
    var queryUrl = url + "&CustomService=Query";

    http = getHTTPObject();
    http.open("POST", queryUrl, true);
    //if ((isIE) && (weAreGeoCoding)){
    //http.onreadystatechange = buildMapIE;
    //}else{
    http.onreadystatechange = buildMap;
    //}
    isWorking = true;
    http.send(axl);
    //getMapWithCurrentExtent()
    //}else{
    //clearMap();
    //}
}

function cqBuildQuery(i) {

    var fieldName = "ACTIVITY_TYPE";
    var theValue = "";
    var queryString = "";
    var theString = '<?xml version="1.0" encoding="UTF-8"?>';
    theString += '<ARCXML version="1.1">\n<REQUEST>\n<GET_FEATURES featurelimit="200" outputmode="xml" geometry="false" envelope="true">';
    theString += '<LAYER id="99" />';
    theString += '<SPATIALQUERY subfields ="#ID# #SHAPE# BUILDING ADDRESS LINK WIRELESS WIRELESSLOCATION2 WIRELESSLOCATION1 WIRELESSLOCATION3 WIRELESSLOCATION4 WIRELESSLOCATION5" where="" >';
    theString += '</SPATIALQUERY>';
    theString += '</GET_FEATURES>';
    theString += '</REQUEST>';
    theString += '</ARCXML>';

    return theString;



}



function getMapWithCurrentExtent() {
    var env = '<ENVELOPE minx="' + southWest.lng() + '" miny="' + southWest.lat() + '" maxx="' + northEast.lng() + '" maxy="' + northEast.lat() + '" />';

    return env;
}

function getMapRequest(envelope) {
    var axl = '<?xml version="1.0" encoding="UTF-8"?>';
    axl += '<ARCXML version="1.1">';
    axl += ' <REQUEST>';
    axl += '    <GET_IMAGE>';
    axl += '    <PROPERTIES>';
    axl += envelope;
    axl += '<IMAGESIZE height="' + mheight + '" width="' + mwidth + '" />';
    /*axl += '<LAYERLIST >\n';
    for (var i=0;i<layerCount;i++) {
    if (LayerVisible[i]==1) {
    axl += '<LAYERDEF id="' + LayerID[i] + '" visible="true" />\n';
    }else {
    axl += '<LAYERDEF id="' + LayerID[i] + '" visible="false" />\n';
    }
    }
	
	axl += '</LAYERLIST>\n';*/
    axl += ' </PROPERTIES>';
    /*if (addAcetate){
		
		 axl += '<LAYER type="acetate" name="acetate1" id="acetate1">';
    axl += '<OBJECT units="database">';
    axl += '<TEXT coords="' +theenvelope[0] + ' '+theenvelope[1] +'" label="'+theElecResultsArr[9]+'" >';
    axl += '<TEXTMARKERSYMBOL glowing="255,255,0" interval="3" fontstyle="bold" halignment="center" overlap="false" font="Arial" fontcolor="0,0,0" fontsize="12" valignment="top" />';
    axl += '</TEXT>';
    axl += '</OBJECT>';
    axl += '</LAYER>';
	
	 axl += '<LAYER type="acetate" name="acetate" id="acetate">';
    axl += '<OBJECT units="database">';
    axl += '<POINT coords="' +theenvelope[0] + ' '+theenvelope[1] +'" >';
    axl += '<SIMPLEMARKERSYMBOL color="255,255,0" type="star" width="16" outline="0,0,0" />';
    axl += '</POINT>';
    axl += '</OBJECT>';
    axl += '</LAYER>';
	
	}*/
    axl += '    </GET_IMAGE> </REQUEST></ARCXML>';

    return axl;

}

function parseEnvelope(theString, startpos, count, layID) {
    theString = theString.toUpperCase();
    var tempString = "";
    var dQuote = "\"";
    var pos = theString.indexOf("ENVELOPE", startpos);
    if (pos != -1) {
        pos = pos + 8;
        startpos = theString.indexOf("MINX=", pos);
        startpos += 6;
        var endpos = theString.indexOf(dQuote, startpos);
        tempString = theString.substring(startpos, endpos);
        minx[count + "" + layID] = parseFloat(tempString);
        startpos = theString.indexOf("MINY=", pos);
        startpos += 6;
        endpos = theString.indexOf(dQuote, startpos);
        tempString = theString.substring(startpos, endpos);
        miny[count + "" + layID] = parseFloat(tempString);
        startpos = theString.indexOf("MAXX=", pos);
        startpos += 6;
        endpos = theString.indexOf(dQuote, startpos);
        tempString = theString.substring(startpos, endpos);
        maxx[count + "" + layID] = parseFloat(tempString);
        startpos = theString.indexOf("MAXY=", pos);
        startpos += 6;
        endpos = theString.indexOf(dQuote, startpos);
        tempString = theString.substring(startpos, endpos);
        maxy[count + "" + layID] = parseFloat(tempString);
        theStartpos = endpos;

    }

}






function buildMap() {
    if (http.readyState == 4) {

        if (http.status == 200) {


            var result = http.responseText;

            var glbCount = getCount(result);


            map = new GMap2(document.getElementById("map"));
            map.addControl(new GLargeMapControl());
            map.addControl(new GScaleControl());
            map.addControl(new GOverviewMapControl());
            map.addControl(new GMapTypeControl());
            GEvent.addListener(map, "moveend", function() {
                var center = map.getCenter();
                theLatitude = center.lat();
                theLongitude = center.lng();
                var bounds = map.getBounds();
                southWest = bounds.getSouthWest();
                northEast = bounds.getNorthEast();


            });
            GEvent.addListener(map, "zoomend", function() {
                theZoom = map.getZoom();
            });

            //trial
            GEvent.addListener(map, "wheelup", function() {
                map.centerAndZoom(map.getZoomLevel() - 1);

            });



            map.setCenter(new GLatLng(42.2773, -83.7598), 10);



            var theLat = 0;
            var theLong = 0;
            var visibleLayers = 0;
            theStartpos = 0;
            processResult3(result, glbCount)
            processResult4(result, glbCount)
            processResult5(result, glbCount)
            processResult6(result, glbCount)
            processResult7(result, glbCount)
            processResult8(result, glbCount)
            processResult9(result, glbCount)
            processResult10(result, glbCount)
            for (var i = 0; i < glbCount; i++) {
                visibleLayers = i + 1;
                parseEnvelope(result, theStartpos, i, visibleLayerArr[visibleLayers]);
                processResult2(result, glbCount, drillIDsName[theActiveLayerID]);

                theLat = (maxy[i + "" + visibleLayerArr[visibleLayers]] + miny[i + "" + visibleLayerArr[visibleLayers]]) / 2;
                theLong = (maxx[i + "" + visibleLayerArr[visibleLayers]] + minx[i + "" + visibleLayerArr[visibleLayers]]) / 2;
                point[i] = new GLatLng(theLat, theLong);

                if (cvtResults3[i] == "YES") {
                    map.addOverlay(createMarker(point[i], createIcon("Swimming"), i));
                } else {
                    map.addOverlay(createMarker(point[i], createIcon(0), i));
                }
            }


            displayBuildNames(glbCount);

        }
    }

}


function getURL(theReply) {
    var theURL = "";
    var startpos = 0;
    var endpos = 0;

    var pos = theReply.indexOf("OUTPUT");
    var pos1 = theReply.indexOf("url", pos);
    pos1 += 5;
    var pos2 = theReply.indexOf("\"", pos1);
    theURL = theReply.substring(pos1, pos2);


    return theURL;

}



function CustomGetTileURl() {
    http = getHTTPObject();
    var axl = getMapRequest(getMapWithCurrentExtent())
    if ((http != null)) {

        http.open("POST", url, true);
        http.onreadystatechange = addToGoogle;
        isWorking = true;

        http.send(axl);
    }


}



function addToGoogle() {
    if (http.readyState == 4) {

        if (http.status == 200) {


            var result = http.responseText;

            CustomTileUrl = getURL(result);


        }

    }


}

function createIcon(id) {
    // Create our "tiny" marker icon
    var icon = new GIcon();
    switch (id) {

        case "Gardening":
            icon.image = "http://labs.google.com/ridefinder/images/mm_20_green.png";
            break;

        case "Exercise":
            icon.image = "http://labs.google.com/ridefinder/images/mm_20_brown.png";
            break;

        case "Swimming":
            icon.image = "http://labs.google.com/ridefinder/images/mm_20_blue.png";
            break;

        default:
            icon.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
            break;

    }
    //icon.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
    icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
    icon.iconSize = new GSize(12, 20);
    icon.shadowSize = new GSize(22, 20);
    icon.iconAnchor = new GPoint(6, 20);
    icon.infoWindowAnchor = new GPoint(5, 1);

    return icon


}
//<br><a target=_blank href=http://gisweb.ewashtenaw.org/website/county_buildings/pdfs/"+cvtResults2[s]+">More info on the building</a></p>"),<br><a target=_blank href=http://gisweb.ewashtenaw.org/website/county_buildings/pdfs/"+cvtResults2[s]+">More info on the building</a>
//<br><a target=_blank href=http://gisweb.ewashtenaw.org/website/county_buildings/pdfs/"+cvtResults2[s]+">More info on the building</a></p>")<br><a target=_blank href=http://gisweb.ewashtenaw.org/website/county_buildings/pdfs/"+cvtResults2[s]+">More info on the building</a>
function createMarker(point, icon, s) {
    // Our info window content
    if (!isIE) {
        if (cvtResults3[s] == "YES") {
            infoTabs[s] = [
  new GInfoWindowTab("Building Info", "<p>" + multiResults[s] + "<br> - <i>Secure Wireless Available Here</i> -<br>" + cvtResults[s] + "<br>Directions " + buildGoogleMapsURL(cvtResults[s], 0) + " or " + buildGoogleMapsURL(cvtResults[s], 1) + "<br>" + diplayBuildingURL(cvtResults2[s]) + "</p>"),
  new GInfoWindowTab("Wireless", "<p>Wireless locations:<br>" + concatWirelessLocations(s) + "</p>")
];
        } else {
            infoTabs[s] = [
  new GInfoWindowTab("What's Here", "<p>" + multiResults[s] + "<br>" + cvtResults[s] + "<br>Directions " + buildGoogleMapsURL(cvtResults[s], 0) + " or " + buildGoogleMapsURL(cvtResults[s], 1) + "<br>" + diplayBuildingURL(cvtResults2[s]) + "</p>"),
];
        }
        marker[s] = new GMarker(point, icon);
        GEvent.addListener(marker[s], "click", function() {
            marker[s].openInfoWindowTabsHtml(infoTabs[s]);
        });
    } else {
        if (cvtResults3[s] == "YES") {
            infoTabs[s] = [
  new GInfoWindowTab("Building Info", "<p>" + multiResults[s] + "<br> - <i>Secure Wireless Available Here</i> -<br>" + cvtResults[s] + "<br>Directions " + buildGoogleMapsURL(cvtResults[s], 0) + " or " + buildGoogleMapsURL(cvtResults[s], 1) + "<br>" + diplayBuildingURL(cvtResults2[s]) + "</p>"),
  new GInfoWindowTab("Wireless", "<p>Wireless locations:<br>" + concatWirelessLocations(s) + "</p>")
];
        } else {
            infoTabs[s] = [
  new GInfoWindowTab("What's Here", "<p>" + multiResults[s] + "<br>" + cvtResults[s] + "<br>Directions " + buildGoogleMapsURL(cvtResults[s], 0) + " or " + buildGoogleMapsURL(cvtResults[s], 1) + "<br>" + diplayBuildingURL(cvtResults2[s]) + "</p>")
];
        }
        marker[s] = new GMarker(point, icon);
        GEvent.addListener(marker[s], "click", function() {
            try {
                marker[s].openInfoWindowTabsHtml(infoTabs[s]);
            } catch (e) {
                alert("error" + e);
            }
        });
    }
    /* var marker = new GMarker(point, icon);
    GEvent.addListener(marker, 'click', function() {
    marker.openInfoWindowTabsHtml(infoTabs);
    });*/
    return marker[s];
}

function concatWirelessLocations(i) {
    var wirelessLocations = "";

    if (cvtResults6[i] != "&nbsp;") {
        wirelessLocations = cvtResults6[i];
    }
    if (cvtResults7[i] != "&nbsp;") {
        wirelessLocations += ", " + cvtResults7[i];
    }
    if (cvtResults8[i] != "&nbsp;") {
        wirelessLocations += ", " + cvtResults8[i];
    }
    if (cvtResults9[i] != "&nbsp;") {
        wirelessLocations += ", " + cvtResults9[i];
    }
    if (cvtResults10[i] != "&nbsp;") {
        wirelessLocations += ", " + cvtResults10[i];
    }

    return wirelessLocations;

}

function diplayBuildingURL(theString) {
    var theReturn = "";
    if (theString != "0") {
        //theString.replace(/ /g,"%20");
        theString = escape(theString);
        if (theString == "LLRC.pdf") {
            theReturn += '<a target=_blank href=http://gisweb.ewashtenaw.org/website/county_buildings/pdfs/' + theString + '>More info on the building</a>';
            theReturn += '<br>';
            theReturn += '<a target=_blank href=http://www.ewashtenaw.org/government/departments/library/llrc_index.html>Link to the LLRC/LBPD</a>';
        } else {
            theReturn += '<a target=_blank href=http://gisweb.ewashtenaw.org/website/county_buildings/pdfs/' + theString + '>More info on the building</a>';
        }
    }


    return theReturn;


}

function displayBuildNames(i) {
    var theString = '<table>';
    multiResults.sort();
    for (var z = 0; z < i; z++) {
        theString += '<tr>';
        theString += '<td>';
        theString += '<a href=javascript:movemap(';

        theString += z;

        theString += ')>' + multiResults[z] + '</a>';
        theString += '</td>';
        theString += '</tr>';

    }
    theString += '</table>';
    var g = document.getElementById("outBuildName");
    g.innerHTML = theString;

}

function addPlus(word) {
    //var ww = "";
    //ww = "\'" + word + "\'";
    //alert(ww);
    //var w = word.split(" ");
    var ww = "";
    //for (var i=0;i < w.length;i++){
    //ww = ww + w[i] + "+";

    //}
    ww = word.replace(/ /g, "&nbsp;");
    ww = "'" + ww + "'";
    return ww;
}

function buildGoogleMapsURL(address, o) {
    var card = "";
    var toFrom = "";
    if (o == 0) {
        card = "To";
        toFrom = "q";
    } else {
        card = "From";
        toFrom = "saddr";
    }
    address = address.replace(/,/g, "");
    var pL = address.split(" ");
    var thePl = "";
    for (var i = 0; i < pL.length; i++) {
        thePl = thePl + pL[i] + "+";

    }
    thePl = "<a target=_blank href=http://maps.google.com/maps?f=d&hl=en&" + toFrom + "=" + thePl + ">" + card + "</a>";
    return thePl;
}

function movemap(i) {
    var name = multiResults[i];
    var g = lookUp.findIndex(name);
    //alert(g);
    marker[g].openInfoWindowTabsHtml(infoTabs[g])

}

Array.prototype.findIndex = function(value) {

    var ctr = "";
    var a = "";
    var b = "";
    //alert(value);
    for (var i = 0; i < this.length; i++) {
        //alert("this" +" " + this[i] + " " + value);
        a = this[i].replace(/ /g, "");
        b = value.replace(/ /g, "");
        //alert(a + " " + b);
        if (a == b) {
            return i;
        }
    }
    return ctr;
};
