var gmap = null;
var geocoder = null;
var defaultLyr; //default dynamic service layer
var zoningLyr,zoningParam; //dynamic service layer for zoning
var redevLyr,redevParam; //dynamic service layer for redev
var GPLyr,GPParam; //dynamic service layer for GP
var mapExtension,identifyTask,layers,overlays,findTask,findParams,listOfOverlays,geom; //layers store layerId
var geomService,addrFeat;
var polygon,aMarker,aPoint;//geocode address
var reasons = []; //geocoding process codes
var idOvs = [];
var idEventListener,overlayInstance = null;
var defaultLyrLoaded,zoningLyrLoaded;
var qAddrTask,qAddr = null;
var addrGeom,addrAttr,parcelGeom,addrHtml;
var aPoints = [];
var mapVE = null;
var locator = null;
var aryPDFLink = new Array("http://www.cityoffullerton.com/civica/filebank/blobdload.asp?BlobID=4661#Page",
    "http://www.cityoffullerton.com/civica/filebank/blobdload.asp?BlobID=4662#Page",
    "http://www.cityoffullerton.com/civica/filebank/blobdload.asp?BlobID=4663#Page",
    "http://www.cityoffullerton.com/civica/filebank/blobdload.asp?BlobID=4664#Page",
    "http://www.cityoffullerton.com/civica/filebank/blobdload.asp?BlobID=4665#Page",
    "http://www.cityoffullerton.com/civica/filebank/blobdload.asp?BlobID=4666#Page",
    "http://www.cityoffullerton.com/civica/filebank/blobdload.asp?BlobID=4667#Page",
    "http://www.cityoffullerton.com/civica/filebank/blobdload.asp?BlobID=4668#Page",
    "http://www.cityoffullerton.com/civica/filebank/blobdload.asp?BlobID=4669#Page",
    "http://www.cityoffullerton.com/civica/filebank/blobdload.asp?BlobID=4670#Page");

var _lastAddress = "";
var _address = "";

//google geocoding process codes
reasons[G_GEO_SUCCESS]="Success";
reasons[G_GEO_MISSING_ADDRESS]="Missing Address: The address was either missing or had no value.";
reasons[G_GEO_UNKNOWN_ADDRESS]="Unknown Address:  No corresponding geographic location could be found for the specified address.";
reasons[G_GEO_UNAVAILABLE_ADDRESS]="Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
reasons[G_GEO_TOO_MANY_QUERIES]="Too Many Queries: The daily geocoding quota for this site has been exceeded.";
reasons[G_GEO_SERVER_ERROR]="Server error: The geocoding request could not be successfully processed.";

function initialize() {
  if (GBrowserIsCompatible())
  {
    //Load Google Maps
    gmap = new GMap2(document.getElementById("gmap"));
    var centerat = new GLatLng(33.887,-117.925);
    gmap.addControl(new GLargeMapControl3D(), new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,35)));
    gmap.addControl(new GMapTypeControl());
    gmap.setCenter(centerat, 13); //19 farthest in, 12 farthest out
    gmap.enableScrollWheelZoom();
    gmap.addControl(new GScaleControl());
    geocoder = new GClientGeocoder();
    /*//zoom control
    var boxStyleOpts={opacity:.2, border:"2px solid yellow"};
    var otherOpts={
        buttonHTML:"<img src='zoom-control-inactive.png' />",
        buttonZoomingHTML:"<img src='zoom-control-active.png' />",
        buttonStartingStyle:{width:'17px',height:'17px'},
        overlayRemoveTime:0};
    gmap.addControl(new DragZoomControl((boxStyleOpts,otherOpts),{}), new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(27,7)));*/
    //gmap.enableGoogleBar(); //extra
    var cpyrPos = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(1,12)); //custom copyright text
    cpyrPos.apply(document.getElementById("copyright"));
    gmap.getContainer().appendChild(document.getElementById("copyright"));
      
    // Overwrite the getMinimumResolution() and getMaximumResolution() methods
    var mt = gmap.getMapTypes();
    for (var i=0; i<mt.length; i++) 
    {
        mt[i].getMinimumResolution = function() {return 12;}
        mt[i].getMaximumResolution = function() {return 19;}
    }
    
    GEvent.addListener(gmap,"zoomend",changeMapType);
        
    mapExtension = new esri.arcgis.gmaps.MapExtension(gmap);    
    defaultLyr = new esri.arcgis.gmaps.DynamicMapServiceLayer("/ArcGIS/rest/services/CommDev/MapServer",null,1,defaultMapLoad);
            
    identifyTask = new esri.arcgis.gmaps.IdentifyTask("/ArcGIS/rest/services/CommDev/MapServer");
    //GEvent.addListener(gmap,"click",identify);
    idEventListener = GEvent.bind(gmap,"click",this,identify);
    
    findTask = new esri.arcgis.gmaps.FindTask("/ArcGIS/rest/services/CommDev/MapServer");
    findParams = new esri.arcgis.gmaps.FindParameters();
    findParams.layerIds = [8];  //parcel
    findParams.searchFields = ["APN"];
    //findParams.contains = false; //exact match
    
    locator = new esri.arcgis.gmaps.Locator("/ArcGIS/rest/services/Composite/GeocodeServer");
    
    geomService = new esri.arcgis.gmaps.Geometry("/ArcGIS/rest/services/Geometry/GeometryServer");
    esri.arcgis.gmaps.Config.proxyUrl = "/arcgisserver/apis/javascript/proxy/proxy.ashx"; //proxy url for large posts

    qAddrTask = new esri.arcgis.gmaps.QueryTask("/ArcGIS/rest/services/AddrLoc/MapServer/0");
    qAddr = new esri.arcgis.gmaps.Query();
    
    buffParams = new esri.arcgis.gmaps.BufferParameters();
    buffParams.unit = esri.arcgis.gmaps.SRUnitType.FOOT;            
  }//end of If (GBrowserIsCompatible)
        
  else
  {
    alert("Sorry, Google Map is not compatible with this browser");
  }
 }//end of function initialize()

function changeMapType() //change map type according to zoom level
{    
    if (gmap.getZoom() > 17) {   //zoomed in     
        if (gmap.getCurrentMapType() != "G_HYBRID_MAP")
            gmap.setMapType(G_HYBRID_MAP);
    }
    else { 
        if (gmap.getCurrentMapType() != "G_NORMAL_MAP")
            gmap.setMapType(G_NORMAL_MAP);
    }
}

function identify(overlay,latLng) //identify tool by clicking on map
{
    if (overlay) return;
    //clearResults();
    var ptLat = latLng.lat();
    var ptLon = latLng.lng();    
    var idParams = new esri.arcgis.gmaps.IdentifyParameters();
    idParams.geometry = latLng; // location where the user clicked on the map
    idParams.tolerance = 3;
    idParams.layerIds = [8,9,10]; //parcel, zoning, redev
    idParams.layerOption = "all"; //identify all layers
    idParams.bounds = gmap.getBounds();
    var mapSize = gmap.getSize();
    idParams.width = mapSize.width;
    idParams.height = mapSize.height;

    identifyTask.execute(idParams, function(response, error) 
    { 
      if (hasErrorOccurred(error)) return;
      // note that the location where the user clicked on the map (latLng) is visible in this function through closure
      addResultToMap(response,latLng,ptLat,ptLon);
  });
}

//function pausecomp(millis)
//{
//    var date = new Date();
//    var curDate = null;

//    do { curDate = new Date(); }
//    while(curDate-date < millis);
//} 

function addResultToMap(response, point, ptLat, ptLon) //process and display identify result
{    
    // aggregate the result per map service layer
    var idResults = response.identifyResults;
    var pointForZoom = idResults.geometry;    
    layers = { "8": [], "9": [], "10": []};
    
    for (var i = 0; i < idResults.length; i++) 
    {
        var result = idResults[i];
        layers[result.layerId].push(result);
    }
    // create and show the info-window with tabs, one for each map service layer
    var tabs = [];
    for (var layerId in layers) 
    {
        var results = layers[layerId];
        var count = results.length;
        var label = "", content = "",contentZoom;
        switch(layerId) 
        {
            case "8":
                label = "Parcel";
                //content = "Total features returned: <b>" + count + "</b>";
                content = "Parcel information not available";
                if (count == 0) break;

                for (var j = 0; j < count; j++) {
                    var attributes = results[j].feature.attributes;
                    parcelGeom = results[j].feature.geometry;

                    if (attributes["ADDRESS"] == 'Null' || attributes["ADDRESS"] == undefined || attributes["ADDRESS"] == '')
                    { addr = ''; }
                    else
                    { addr = " <b>Address:</b> " + attributes["ADDRESS"]; }
                    //                    var qAddr = queryAddr(parcelGeom);
                    //                    qAddr = addr + qAddr;
                    //                    var testAddr = "";
                    //                    testAddr = "<div id=\"divAddress\"><b>Address:</b> ";
                    //                    if (_address != _lastAddress) {
                    //                        testAddr += _address;
                    //                    }
                    //                    testAddr += "</div>";
                    var area = attributes["AREA_SF"];
                    var acre = area * 0.0000229568;
                    var roundAcre = Math.round(acre * 100) / 100;
                    var streetvwSm = "<table border='0'><tr><td height='200'><div id='svSmall' style='height: 220px; width: 350px;'></div></td></tr>";
                    var streetvwLg = "<table border='0' align='center'><tr><td><div id='svLarge' style='height: 400px; width: 550px;'></div></td></tr>";
                    //var birdVW = '<a href="#" onclick="javascript:getBirdsview()">Birds view</a>';
                    var birdVW = '<a href="#" onclick="javascript:getBirdsview('+ptLat+','+ptLon+')">Bird\'s Eye View</a>';

                    if (gmap.getZoom() < 18) //zoomed out
                    {
                        contentZoom = '<div class="text"><img src="/images/toolbar/extranet/tools_zoom_in.gif" alt="" /><a href="#" class="iw" onclick="javascript:zoomIn(' + pointForZoom + ')">Zoom In</a> </div>';
                        content = "<b>APN: </b>" + attributes["APN"] + "<br>" + addr +
                        "<br><b>Lot area:</b> " + area + " sf / " +
                        roundAcre + " acre" + "&nbsp;&nbsp;" +
                        createPDFLink(attributes["GRID"]) + "&nbsp;&nbsp;" +
                        birdVW + contentZoom + streetvwSm; //'<div style="width:264px;"></div>' + 

                    }
                    else //zoomed in
                    {
                        content = "<div><b>APN: </b>" + attributes["APN"] + "</div>" + addr +
                        "<br><b>Lot area:</b> " + area + " sf / " +
                        roundAcre + " acre" + "&nbsp;&nbsp;" + //'<div style="width:264px;"></div>'
                        createPDFLink(attributes["GRID"]) + "&nbsp;&nbsp;" +
                        birdVW + streetvwSm;
                    }
                    setTimeout(function() { updatePanoSm(point) }, 100); //activate streetview
                    showFeature(layerId, j); //highlights feature when clicked
                }
                break;

            case "9":
            label = "Land Use";
            //content = "Total features returned: <b>" + count + "</b>";
            content = "Zoning information not available";
            if (count == 0) break;
                        
            var ov1,ov2,ov3,ov4,ov5,info1,info2,info3,info4,info5; //zoning fields
                    
            for (var j = 0; j < count; j++) //displays/hides fields that have (no) info
            {
                var attributes = results[j].feature.attributes;
                
                if(attributes["OVERLAY1"]=='Null'|| attributes["OVERLAY2"]==undefined || attributes["OVERLAY2"]=='')
                    {ov1 = '';}
                    else
                    //{ ov1 = "<br/>Overlay1: " + attributes["OVERLAY1"]; }
                    { ov1 = "<br/>Overlay1: <a href=http://www.cityoffullerton.com/depts/dev_serv/planning_/zoning_key.asp target=_blank;'>" + attributes["OVERLAY1"]+"</a>"; }
                if(attributes["OVERLAY2"]=='Null' || attributes["OVERLAY2"]==undefined || attributes["OVERLAY2"]=='')
                    {ov2 = '';}
                    else
                    { ov2 = "<br/>Overlay2: <a href=http://www.cityoffullerton.com/depts/dev_serv/planning_/zoning_key.asp target=_blank;'>" + attributes["OVERLAY2"] + "</a>"; }
                if(attributes["OVERLAY3"]=='Null' || attributes["OVERLAY3"]==undefined || attributes["OVERLAY3"]=='')
                    {ov3 = '';}
                    else
                    { ov3 = "<br/>Overlay3: <a href=http://www.cityoffullerton.com/depts/dev_serv/planning_/zoning_key.asp target=_blank;'>" + attributes["OVERLAY3"] + "</a>"; }
                if(attributes["OVERLAY4"]=='Null' || attributes["OVERLAY4"]==undefined || attributes["OVERLAY4"]=='')
                    {ov4 = '';}
                    else
                    { ov4 = "<br/>Overlay4: <a href=http://www.cityoffullerton.com/depts/dev_serv/planning_/zoning_key.asp target=_blank;'>" + attributes["OVERLAY4"] + "</a>"; }
                if(attributes["OVERLAY5"]=='Null' || attributes["OVERLAY5"]==undefined || attributes["OVERLAY5"]=='')
                    {ov5 = '';}
                    else
                    { ov5 = "<br/>Overlay5: <a href=http://www.cityoffullerton.com/depts/dev_serv/planning_/zoning_key.asp target=_blank;'>" + attributes["OVERLAY5"] + "</a>"; }
                if(attributes["INFO1"]=='Null' || attributes["INFO1"]==undefined || attributes["INFO1"]=='')
                    {info1 = '';}
                    else
                    { info1 = "<br/>Info1: <a href=http://www.cityoffullerton.com/depts/dev_serv/planning_/zoning_key.asp target=_blank;'>" + attributes["INFO1"] + "</a>"; }
                if(attributes["INFO2"]=='Null' || attributes["INFO2"]==undefined || attributes["INFO2"]=='')
                    {info2 = '';}
                    else
                    { info2 = "<br/>Info2: <a href=http://www.cityoffullerton.com/depts/dev_serv/planning_/zoning_key.asp target=_blank;'>" + attributes["INFO2"] + "</a>"; }
                if(attributes["INFO3"]=='Null' || attributes["INFO3"]==undefined || attributes["INFO3"]=='')
                    {info3 = '';}
                    else
                    { info3 = "<br/>Info3: <a href=http://www.cityoffullerton.com/depts/dev_serv/planning_/zoning_key.asp target=_blank;'>" + attributes["INFO3"] + "</a>"; }
                if(attributes["INFO4"]=='Null' || attributes["INFO4"]==undefined || attributes["INFO4"]=='')
                    {info4 = '';}
                    else
                    { info4 = "<br/>Info4: <a href=http://www.cityoffullerton.com/depts/dev_serv/planning_/zoning_key.asp target=_blank;'>" + attributes["INFO4"] + "</a>"; }
                if(attributes["INFO5"]=='Null' || attributes["INFO5"]==undefined || attributes["INFO5"]=='')
                    {info5 = '';}
                    else
                    { info5 = "<br/>Info5: <a href=http://www.cityoffullerton.com/depts/dev_serv/planning_/zoning_key.asp target=_blank;'>" + attributes["INFO5"] + "</a>"; }   
                
                content = "<b>Zoning:</b> " + attributes["ZONE_DSC"] + 
                "<br/><b>General Plan:</b> " + attributes["GPLAN_DSC"] +                 
                ov1 + ov2 + ov3 + ov4 + ov5 + info1 + info2 + info3 + info4 + info5;                    
            }
            break;

        case "10":
            label = "Redev";
            //content = "Total features returned: <b>" + count + "</b>";
            content = "Non Redevelopment project area";
            if (count == 0) break;
            for (var j = 0; j < count; j++) {
                var attributes = results[j].feature.attributes;
                content = "<b>Redevelopment project area:</b> " + '<a href="' + attributes["URL"] + '">' +
                    attributes["PROJ_AREA"] + '</a>';
            }
            break;
        
//        case "12":
//            label = "Bird's View";
//            content = "<div style='position: relative;'><div id='veMap2' style='position: absolute; top: 0; left: 0; height: 300px; width: 400px;'></div></div>";
//            content = "<div style='position: relative;'><iframe id='ifBirds' src='" + getBirdsview(ptLat, ptLon) + "' width='400px' height='300px'></iframe></div>";
//            setTimeout(function(){getBirdsview(ptLat,ptLon)},500);
//            break;        
            
        } //end switch
        tabs.push(new GInfoWindowTab(label, content));
        if (idResults.length <= 0) { return; }
    }//end for loop layers
    //gmap.openInfoWindowTabsHtml(point, tabs);
    gmap.openInfoWindowTabs(point, tabs,{maxContent:streetvwLg, maxTitle:"Expanded Street View"});
}//end function addResultToMap

function createPDFLink(grid) //zoning pdf map link
{
    var link;
           
    if(grid=="1A" || grid>=1 && grid<=10)
    {
        link = "<a href=" + aryPDFLink[0] + grid + ">" + "Zoning PDF map" + "</a>";
    }
    if(grid>10 && grid<=20)
    {
        link = "<a href=" + aryPDFLink[1] + grid + ">" + "Zoning PDF map" + "</a>";
    }
    if(grid>20 && grid<=30)
    {
        link = "<a href=" + aryPDFLink[2] + grid + ">" + "Zoning PDF map" + "</a>";
    }
    if(grid>30 && grid<=40)
    {
        link = "<a href=" + aryPDFLink[3] + grid + ">" + "Zoning PDF map" + "</a>";
    }
    if(grid>40 && grid<=50)
    {
        link = "<a href=" + aryPDFLink[4] + grid + ">" + "Zoning PDF map" + "</a>";
    }
    if(grid>50 && grid<=60)
    {
        link = "<a href=" + aryPDFLink[5] + grid + ">" + "Zoning PDF map" + "</a>";
    }
    if(grid>60 && grid<=70)
    {
        link = "<a href=" + aryPDFLink[6] + grid + ">" + "Zoning PDF map" + "</a>";
    }
    if(grid>70 && grid<=80)
    {
        link = "<a href=" + aryPDFLink[7] + grid + ">" + "Zoning PDF map" + "</a>";
    }
    if(grid>80 && grid<=90)
    {
        link = "<a href=" + aryPDFLink[8] + grid + ">" + "Zoning PDF map" + "</a>";
    }
    if(grid>90 && grid<=105)
    {
        link = "<a href=" + aryPDFLink[9] + grid + ">" + "Zoning PDF map" + "</a>";
    }
    if(grid==undefined || grid=='Null' || grid=='')
    {
        link = '';
    }
    return link;
}

function updatePanoSm(latLon)
{    
    var panoSmall = new GStreetviewPanorama(document.getElementById("svSmall"));
    panoSmall.setLocationAndPOV(latLon);
    GEvent.addListener(panoSmall,"error",function(errorCode){
        document.getElementById("svSmall").innerHTML = "No Street View available";        
        if(errorCode==603)
        {document.getElementById("svSmall").innerHTML = "Error: Flash doesn't appear to be supported by your browser";}
    });

    var iw = gmap.getInfoWindow();

    GEvent.addListener(iw, "maximizeend", function() {
        document.getElementById("divZone").style.display = "none"; //hide
        document.getElementById("divRedev").style.display = "none";
        document.getElementById("divGP").style.display = "none";
        setTimeout(function() { updatePanoLg(latLon) }, 100);
    });
    GEvent.addListener(iw,"infowindowbeforeclose",function()
    {
        panoSmall.remove();
    });    
}

function updatePanoLg(latLon) 
{
    var panoLarge = new GStreetviewPanorama(document.getElementById("svLarge"));
    panoLarge.setLocationAndPOV(latLon);
    var iw = gmap.getInfoWindow();
    GEvent.addListener(iw,"restoreclick",function()
    {
        panoLarge.remove();
    });
    GEvent.addListener(iw,"infowindowclose",function()
    {
        panoLarge.remove();
    });
    GEvent.addListener(iw,"infowindowbeforeclose",function()
    {
        panoLarge.remove();
    });
    GEvent.addListener(iw,"restoreend",function()
    {
        document.getElementById("divZone").style.display = "block"; //show
        document.getElementById("divRedev").style.display = "block";
        document.getElementById("divGP").style.display = "block";
        panoLarge.remove();        
    });
    GEvent.addListener(iw,"closeclick",function()
    {
        document.getElementById("divZone").style.display = "block"; //show
        document.getElementById("divRedev").style.display = "block";
        document.getElementById("divGP").style.display = "block";
        panoLarge.remove();        
    });
}
//var addrTest = "";
//function queryAddr(parcelGeom) //query address for display in infowindow
//{
//    _lastAddress = _address;
//    //addrAttr = "";
//    qAddr.queryGeometry = parcelGeom;
//    qAddr.outFields = ["ADDR_ALL"];
//    qAddrTask.execute(qAddr, false, function(fSet) {
//        addrFeat = fSet.features;
//        addrAttr = addrFeat[0].attributes.ADDR_ALL;
//        _address = addrAttr;
//        addrHtml = addrAttr;
//        //_address = addrAttr;
//        //alert("_address = " + _address);
//        //if (_address.length > 0) 
//        //{
//        document.getElementById("divAddress").innerHTML = "<b>Address: </b>" + addrAttr;
//        //}
//        //"<br/><b>Address:</b> " +
//        //        overlays = mapExtension.addToMap(fSet,html);
//    });        
//    //addrHtml = addrTest;
//    //alert(addrHtml);
//    return addrHtml;
//}

function queryAddr(addr) 
{
//    var qBounds = gmap.getBounds();
//    qAddr.queryGeometry = qBounds;
    qAddr.outFields = ["ADDR_ALL"];
    qAddr.where = "ADDR_ALL like '" + addr + "*'";
    
    qAddrTask.execute(qAddr, false, function(fSet) {
        //addrFeat = fSet.features, geometry, attributes;
        addrFeat = fSet.features;
        
        var _addr, feature, attr, y, x;
        var _str = "";
        for (var i = 0; i < addrFeat.length; i++) {
            feature = addrFeat[i];
            //attr = addrFeat.attributes;
            _addr = feature.attributes.ADDR_ALL;
            //y = feature.attributes.Y_COORD;
            //x = feature.attributes.X_COORD;
            
            _str += "<div style=\"padding-bottom: 4px;\">" + (i + 1) + ": <a href='javascript:searchAddress(" + "\"" + _addr + "\"" + ")'>" + _addr + "<\/a></div>";            
        }
        fncMultipleResults();
        document.getElementById("divData").innerHTML = _str;
    });
    fncEnableSubmit();
}

function redevMapLoad(layer)
{
    gmap.addOverlay(layer);
}

function GPMapLoad(layer)
{
    gmap.addOverlay(layer);
}

function defaultMapLoad(layer)
{
    defaultLyrLoaded = true;
    dynmapcallback();    
}

function zoningMapLoad(layer)
{
    zoningLyrLoaded = true;
    dynmapcallback();
}

function dynmapcallback()
{
    if(defaultLyrLoaded && zoningLyrLoaded)
    {
        gmap.addOverlay(zoningLyr);
        gmap.addOverlay(defaultLyr);
    }    
    else
    {
        gmap.addOverlay(defaultLyr);
    }
}

function find(searchStr) //find APN
{
    if(listOfOverlays)//remove result overlay
    {
        for(var i=0; i<listOfOverlays.length; i++)
        {
            gmap.removeOverlay(listOfOverlays[i].overlay);
        }     
    }    
    mapExtension.removeFromMap(overlays);
    gmap.closeInfoWindow();    

    findParams.searchText = searchStr;
    findTask.execute(findParams, findCompleteCallback);
}

function sortByFoundFieldName(a, b) {
    if (a.feature.attributes[a.foundFieldName] > b.feature.attributes[b.foundFieldName]) return 1;
    if (a.feature.attributes[a.foundFieldName] < b.feature.attributes[b.foundFieldName]) return -1;
    return 0;
}

function findCompleteCallback(response) //find result
{
    var findResults = response.findResults, findResult, geometry, attributes, geom, i,j, name, foundField;
    var uniqueId = 0;
    var resultList = "<table width='150px'><tr><td>APN</td></tr>"; //display results list
    listOfOverlays=[];//added

    if (findResults.length <= 0){ return; }

    //var APNAry = new Array();
    findResults.sort(sortByFoundFieldName);
    
    for (i = 0; i < findResults.length; i++)
    {
        fncMultipleResults();
        findResult = findResults[i];        
        geometry = findResult.feature.geometry;
        attributes = findResult.feature.attributes;
        name = findResult.layerName;
        foundField = findResult.foundFieldName;
        //APNAry[i] = attributes[foundField];

        resultList = resultList + "<tr><td>" + "<a href='#' onclick='zoom(" + uniqueId + "," + attributes[foundField] + ")'>" + attributes[foundField] + "</a></td></tr>";
                
        for(j=0; j<geometry.length; j++)
        {
            geom = geometry[j];
            var func = getClickFunc(attributes,findResult.layerId,name,foundField);
            listOfOverlays[uniqueId++]={"overlay":geom,"func":func};
        }
    }
       
    resultList += "</table>";
    
    if(findResults.length<=1)
    {
        document.getElementById('divData').innerHTML = "";
        fncHideResults();
        var bounds = geom.getBounds();
        var center = bounds.getCenter();
        var zoomLevel = gmap.getBoundsZoomLevel(bounds);
        gmap.setCenter(center,zoomLevel);
        var html = foundField + ": " + attributes[foundField];
        //gmap.openInfoWindowHtml(center,html);
        identify(null,center);
    }
    else if (findResults.length > 1) 
    {
        document.getElementById('divData').innerHTML = resultList;
    }
    fncEnableSubmit();
}

function getClickFunc(attributes,layerId,layerName,foundFieldName)
{
    var html = "APN: " + attributes["APN"];
    return function(latlng)
    {
        //gmap.openInfoWindowHtml(latlng,html);
        identify(null,latlng);
    }    
}

function zoom(uniqueId,fieldValue) //zoom function for find results list
{
    var polygon = listOfOverlays[uniqueId].overlay;
    var func = listOfOverlays[uniqueId].func;
    var bounds = polygon.getBounds();
    var center = bounds.getCenter();
    var zoomLevel = gmap.getBoundsZoomLevel(bounds);
    gmap.setCenter(center,zoomLevel);
    //var html = "APN: " +  fieldValue;
    //gmap.openInfoWindowHtml(center,html);
    func(center);
}

function showFeature(layerId, index) //highlights feature when clicked
{
    mapExtension.removeFromMap(overlays);
    var idResult = layers[layerId][index];
    overlays = mapExtension.addToMap(idResult, {polygonOptions: { clickable: false}});
    //for buffer
    for(var x=0; x<overlays.length; x++)
    {
        idOvs.push(overlays[x]);
    }   
}

function zoomIn(pt) //zoom to address visible level in infowindow
{
    gmap.setCenter(pt,18); 
}

function clearResults() //clear identify highlight,infowindow & result list
{
    //gmap.clearOverlays(); //clear all overlays, including dynamic layers
    if(listOfOverlays)
    {
        for(var i=0; i<listOfOverlays.length; i++)
        {
            gmap.removeOverlay(listOfOverlays[i].overlay);
        }
    }   
    mapExtension.removeFromMap(overlays);
    gmap.closeInfoWindow();
    document.getElementById('divData').innerHTML = "";
    clearAddr();
}

function toggleSV() //turn on/off streetview overlay
{
	if(!overlayInstance)
	{
		overlayInstance = new GStreetviewOverlay();
		gmap.addOverlay(overlayInstance);
	}
	else
	{
		gmap.removeOverlay(overlayInstance);
		overlayInstance = null;
	}
}

function show(mapLayer) //turn on layers
{
    if (mapLayer == "Zoning") {
        zoningParam = new esri.arcgis.gmaps.ImageParameters();
        zoningParam.layerIds = [9, 7];
        zoningLyr = new esri.arcgis.gmaps.DynamicMapServiceLayer("/ArcGIS/rest/services/CommDev/MapServer", zoningParam, 0.75, zoningMapLoad);

        //      GEvent.addListener(zoningLyr,"update",function()
        //        {
        //            // hide "Loading..." message
        //            document.getElementById("status").style.display = "none";
        //        }
        //      );
        //      GEvent.addListener(gmap, "moveend", function() {
        //          // show "Loading..." message
        //          document.getElementById("status").style.display = "block";
        //        }); 
    }
    else if (mapLayer == "Redev") {
        redevParam = new esri.arcgis.gmaps.ImageParameters();
        redevParam.layerIds = [10];
        redevLyr = new esri.arcgis.gmaps.DynamicMapServiceLayer("/ArcGIS/rest/services/CommDev/MapServer", redevParam, 0.60, redevMapLoad);
    }
    else if (mapLayer == "GP")
    {
        GPParam = new esri.arcgis.gmaps.ImageParameters();
        GPParam.layerIds=[0];
        GPLyr = new esri.arcgis.gmaps.DynamicMapServiceLayer("/ArcGIS/rest/services/GPlan/MapServer", GPParam, 0.60, GPMapLoad);    
    }
}

function hide(mapLayer) //turn off layers
{
    if(mapLayer=="Zoning")
    {
        zoningLyr.hide();
    }
    if(mapLayer=="Redev")
    {
        redevLyr.hide();
    }
    if(mapLayer=="GP")
    {
        GPLyr.hide();
    }
}

function boxClick(box,mapLayer) //check/uncheck layers
{
    if(box.checked)
    {
        show(mapLayer);
    }
    else
    {
        hide(mapLayer);
    }
}

function hasErrorOccurred(error) 
{
    if (error) 
    {
      alert("Error " + error.code + ": " + (error.message || (error.details && error.details.join(" ")) || "Unknown error" ));
      return true;
    }
    return false;
}

//function searchAddressGoogle(address) //google geocoding service
//{
//	var search = address + " fullerton";
//	geocoder.getLocations(search, function(result) {
//	    //gmap.clearOverlays();		
//	    if (result.Status.code == G_GEO_SUCCESS) {
//	        if (result.Placemark.length > 1) {
//	            document.getElementById("divData").innerHTML = "Did you mean:";
//	            for (var i = 0; i < result.Placemark.length; i++) {
//	                var p = result.Placemark[i].Point.coordinates;
//	                //document.getElementById("divData").innerHTML += "<br>"+(i+1)+": <a href='javascript:place(" +p[1]+","+p[0]+")'>"+ result.Placemark[i].address+"<\/a>";
//	                var gcAddr = result.Placemark[i].address;
//	                document.getElementById("divData").innerHTML += "<br>" + (i + 1) + ": <a href='javascript:place(" + p[1] + "," + p[0] + ",\"" + gcAddr + "\")'>" + result.Placemark[i].address + "<\/a>";
//	                fncMultipleResults();
//	            }
//	        }
//	        else {
//	            document.getElementById("divData").innerHTML = "";
//	            var p = result.Placemark[0].Point.coordinates;
//	            var addr = result.Placemark[0].address;
//	            place(p[1], p[0], addr);
//	        }
//	    }
//	    else {
//	        var reason = "Code " + result.Status.code;
//	        if (reasons[result.Status.code]) {
//	            reason = reasons[result.Status.code]
//	        }
//	        //alert('Could not find "'+search+ '" ' + reason);
//	        alert("Could not find " + search + " " + reason);
//	    }
//	});	
//}

function searchAddress(address)
{
    
    var inputAddr = {Street:address};       
    var outFields = ["Score", "Match_addr", "Loc_name", "X", "Y"];
    locator.addressToLocations(inputAddr, outFields, false, addrCallback);
}

function sortByAddrMatch(a, b) 
{
    return (parseFloat(b.attributes.Score) - parseFloat(a.attributes.Score));
}

function addrCallback(addressResults) 
{
    clearResults();
    var candidates = addressResults.addressCandidates, score, location, attributes, candidate;        
    if(candidates.length<=0)
    {
        document.getElementById("divData").innerHTML = "No address found";
        fncMultipleResults();
    }
    var hasMatch = false;
    var _str = "";
    
    candidates.sort(sortByAddrMatch);
    
    for(var i=0; i<candidates.length; i++)
    {
        candidate = candidates[i];
        //alert(candidate.location+" "+candidate.address+" "+candidate.score);
        var x = candidate.attributes.X;
        var y = candidate.attributes.Y;
        var matchAddr = candidate.attributes.Match_addr;
        var score = candidate.attributes.Score;
        
        if(candidate.attributes.Score==100 && candidate.attributes.Loc_name=="AddrPt")
        {
            _str = "";
            hasMatch = true;
            place(y, x, matchAddr);
        }
        else
        {
            //document.getElementById("divData").innerHTML = "Did you mean:";
            _str += "<div style=\"padding-bottom: 4px;\">" + (i + 1) + ": <a href='javascript:place(" + y + "," + x + ",\"" + matchAddr + "\")'>" + matchAddr + "<\/a> " + score + "%</div>";
	    }
	}
	
	if (hasMatch) 
	{
	    document.getElementById("divData").innerHTML = "";
	    fncHideResults();
	}
	else 
	{
	    fncMultipleResults();
	    document.getElementById("divData").innerHTML = _str;
	}
	fncEnableSubmit();
    //overlays = mapExtension.addToMap(addressResults);    
}

function place(lat,lng,addr) //create address marker
{   //  removeOverlay doesn't remove an array, only single objects.
    //	to remove the entire collection, loop through the array and remove them individually
    for(var i=0; i<aPoints.length; i++) 
    {
        if(aPoints[i])
        {
            gmap.removeOverlay(aPoints[i]);
            aPoints[i]=false;
        }
    }    
    aPoint = new GLatLng(lat,lng);
    gmap.setCenter(aPoint,18);
    var marker = new GMarker(aPoint);
    aPoints[i] = marker;
    gmap.addOverlay(aPoints[i]);    
    //marker.openInfoWindowHtml(addr);
    identify(null,aPoint);
    GEvent.addListener(marker,"click",function()
    {
        marker.openInfoWindowHtml(addr);
    });
    //gmap.addOverlay(new GMarker(aPoint));
    document.getElementById("divData").innerHtml = "";    
}

function clearAddr() //remove address marker
{
    //gmap.removeOverlay(aPoint);
    for(var i=0; i<aPoints.length; i++) //loop through array to remove point markers
    {
        if(aPoints[i])
        {
            gmap.removeOverlay(aPoints[i]);
            aPoints[i]=false;
        }        
    }    
}

function fncPopWindow(strUrl, strWindowName, strFeatures, blnReplace) {
    
}

function getBirdsview(lat,lon) //open Virtual Earth oblique image
{
    //window.open('http://bing.com/maps/default.aspx?cp=' + lat + '~' + lon + '&style=b','_bird');
    var _url = 'BirdsView.aspx?lat=' + lat + '&lon=' + lon;
    var _wndName = 'birdsview';
    var _features = 'width=500,height=500,resizable=yes';
    
    var wndPop = window.open(_url, _wndName, _features);
    //wndPop.document.close();
    wndPop.focus();
}


//function print()
//{
//    var baseURL = "http://maps.google.com/staticmap?";
//    var params = [];
//    params.push("center=" + gmap.getCenter().lat().toFixed(6) + "," + gmap.getCenter().lng().toFixed(6));
//    if (gmap.getCurrentMapType()==G_SATELLITE_MAP)
//    {
//        params.push("maptype=satellite");
//    }
//    if (gmap.getCurrentMapType()==G_HYBRID_MAP)
//    {
//        params.push("maptype=hybrid");
//    }
//    if (gmap.getCurrentMapType()==G_PHYSICAL_MAP)
//    {
//        params.push("maptype=terrain");
//    }
//    
//    params.push("zoom=" + gmap.getZoom());
//    params.push("size=450x400");
//    var img = document.createElement("img");
//    img.src = baseURL + params.join("&") + "&key=ABQIAAAA4PzXLddDHgsLIAfgLIaGrhQLj0r_jF9VdpNe7HE67ZPy_HVY9hQv6zq6LCk5F_E6QYeK-IxZgtYGGQ";
//    document.getElementById("staticMap").innerHTML="";
//    document.getElementById("staticMap").appendChild(img);    
//}
