var gmap = null;
//var gpolys = [];
var findTask = null;
var findParams = null;
var mapExtension = null;
//var gOverlays = null;
var identifyTask, layers, overlays, dynamicMap;
var aryAttributeDB = new Array("ACTIVITY_B", "ACTIVITY_S", "BARBECUE", "BASEBALL", "BASKETBALL", "BENCHES", "BLEACHER_S", "FIRE_RINGS", "GAZEBO", "GYM", "HANDICAP", "HORSESHOE", "PAR_COURSE", "PARKING", "PICNIC_TAB", "PLAYGROUND", "RACQUETBAL", "TRAIL", "RESTROOM", "SEATING", "SHUFFLEBOA", "SKATE_PARK", "SNACK_BAR", "SOCCER", "SOFTBALL", "SWIMMING", "TENNIS", "VOLLEYBALL", "WADING_POO","DOG_BAG","PIC_SHELTER","DRINK_FOUNTAIN","FOUNTAIN","SPRAY_POOL","CREEK","LAKE","FISHING","SCHOOL_ADJ");
var aryAttributeName = new Array("Activity Building", "Activity Slab", "Bar-B-Qs", "Baseball", "Basketball", "Benches", "Bleacher Seating", "Fire Rings", "Gazebo Seating", "Gymnasium", "Handicap Facility", "Horse Shoe", "Par Course", "Parking Lot", "Picnic Tables", "Playground", "Racquetball", "Trail(s)", "Restroom", "Seating", "Shuffle Board", "Skate Park", "Snack Bar", "Soccer", "Softball", "Swimming Pool", "Tennis", "Volleyball", "Wading Pool","Doggie Bag Dispensers","Picnic Shelter","Drinking Fountain","Fountain","Spray Pool","Creek","Lake","Fishing","School Adjacent");

function initialize() {
  if (GBrowserIsCompatible())
  {
    //Load Google Maps
    gmap = new GMap2(document.getElementById("gmap"));
    var centerat = new GLatLng(33.887, -117.925); //33.873, -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, 13 farthest out
    gmap.enableScrollWheelZoom();
    gmap.addControl(new GScaleControl());
    geocoder = new GClientGeocoder();
    //gmap.enableGoogleBar(); //extra
    
    // 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;}
    }
    
    mapExtension = new esri.arcgis.gmaps.MapExtension(gmap);
    findTask = new esri.arcgis.gmaps.FindTask("/arcgis/rest/services/Parks/MapServer");
    findParams = new esri.arcgis.gmaps.FindParameters();
    findParams.layerIds = [0,1];
    findParams.searchFields = ["NAME","ADDRESS","URL","TRAIL_NAME","DIFF_LVL","TRAIL_TYPE","LENGTH"];
    findParams.contains = false;
    
    dynamicMap = new esri.arcgis.gmaps.DynamicMapServiceLayer("/ArcGIS/rest/services/Parks/MapServer", null, 0.75, dynmapCallback);
    identifyTask = new esri.arcgis.gmaps.IdentifyTask("/ArcGIS/rest/services/Parks/MapServer");
    GEvent.addListener(gmap, "click", identify);   
            
  }//end of If (GBrowserIsCompatible)
        
  else
  {
    alert("Sorry, Google Map is not compatible with this browser");
  }
 }//end of function initialize()

function find(obj) //dropdown list search
{
    //mapExtension.removeFromMap(gOverlays);
    if(obj.selectedIndex != 0)
    {
        gmap.closeInfoWindow();
        fncClearFormExcept(obj);
        clearMap();
        if(obj.id.indexOf("Park") > 0)
        {
            findParams.searchText = obj.options[obj.selectedIndex].text;
            findTask.execute(findParams,findParkCompleteCallback);
        }
        else
        {
            findParams.searchText = obj.options[obj.selectedIndex].text;
            findTask.execute(findParams,findTrailCompleteCallback);
        }
    }
}

function dynmapCallback(mapOverlay) //add dynamic map
{
    gmap.addOverlay(mapOverlay);
}

function identify(overlay,latLng)
{
    if (overlay) return; //
    
    // set the identify parameters
    var identifyParams = new esri.arcgis.gmaps.IdentifyParameters();
    identifyParams.geometry = latLng;
    identifyParams.tolerance = 3;
    identifyParams.layerIds = [0,1]; //0-Trail, 1-Parks
    identifyParams.layerOption = "all";
    identifyParams.bounds = gmap.getBounds();
    var mapSize = gmap.getSize();
    identifyParams.width = mapSize.width;
    identifyParams.height = mapSize.height;
    
    identifyTask.execute(identifyParams, function(response, error)
    {
        if (hasErrorOccurred(error)) return;
        addResultToMap(response,latLng);
    }); 
}

function addResultToMap(response, point) //show infowindow by identify
{
    var idResults = response.identifyResults;
    var info = "";
    if (response.identifyResults.length <= 0) { return; }//added
    for(var i=0; i<idResults.length; i++)
    {
        var feature = idResults[i].feature;
        var lyrId = idResults[i].layerId; //added
        var geometry = feature.geometry;
        var attributes = feature.attributes;
        var content;
        
        if(lyrId=="0") //trail
        {
            //content = fncAdjustImage(attributes["IMAGE"]) + "<b>Name: </b>" + fncAdjustHref(attributes["URL"], attributes["TRAIL_NAME"]) + "<br/><b>Type:</b> " + attributes["TRAIL_TYPE"] + "<br/><b>Difficulty level:</b> " + attributes["DIFF_LVL"]+ "<br/><b>Length:</b> " + attributes["LENGTH"] + " mi";
            content = fncCreateTrailsBubble(attributes["IMAGE"], attributes["URL"], attributes["TRAIL_NAME"], attributes["TRAIL_TYPE"], attributes["DIFF_LVL"], attributes["LENGTH"]);
        }
        else if(lyrId=="1") //park
        {
            //content = fncAdjustImage(attributes["IMAGE"]) + "<b>Name: </b>" + fncAdjustHref(attributes["URL"], attributes["NAME"]) + "<br/><b>Address:</b> " + attributes["ADDRESS"] + "<br>" ;//+ fncAdjustFacilities(attributes);
            content = fncCreateParksBubble(attributes["IMAGE"], attributes["URL"], attributes["NAME"], attributes["ADDRESS"], attributes);
        }
  
    }//for loop idResults.length
    gmap.openInfoWindowHtml(point,content,{Width: 350});
}

function hasErrorOccurred(error) 
{
    if (error) {
      alert("Error " + error.code + ": " + (error.message || (error.details && error.details.join(" ")) || "Unknown error" ));
      return true;
    }
    return false;
}

function findParkCompleteCallback(response) //park
{
    var findResults = response.findResults, findResult, geometry, attributes, geom, i,j, name, foundField;
    var uniqueId = 0;
    
    for(i=0; i<findResults.length; i++)
    {
        findResult = findResults[i];
        geometry = findResult.feature.geometry;
        attributes = findResult.feature.attributes;
        
        
        name = findResult.layerName;
        foundField = findResult.foundFieldName;
        
        for(j=0; j<geometry.length; j++)
        {
            geom = geometry[j];
            //gmap.addOverlay(geom);
        }
        
    }
    var bounds = geom.getBounds();
    var center = bounds.getCenter();
    var zoomLevel = gmap.getBoundsZoomLevel(bounds);
    gmap.setCenter(center,zoomLevel);
    /*
    picnic shelter (adlena) 
    fountain (downtown)
    spray pool (adlena, lemon)
    Creek (Hiltscher)
    Doggie Bag Dispensers (Hiltscher)
    */
    //var html2 = attributes["ACTIVITY_B"] + attributes["ACTIVITY_S"] + attributes["BARBECUE"] + attributes["BASEBALL"] + attributes["BASKETBALL"] + attributes["BENCHES"] + attributes["BLEACHER_S"] + attributes["FIRE_RINGS"] + attributes["GAZEBO"] + attributes["GYM"] + attributes["HANDICAP"] + attributes["HORSESHOE"] + attributes["PAR_COURSE"] + attributes["PARKING"] + attributes["PICNIC_TAB"] + attributes["PLAYGROUND"] + attributes["RACQUETBAL"] + attributes["TRAIL"] + attributes["RESTROOM"] + attributes["SEATING"] + attributes["SHUFFLEBOA"] + attributes["SKATE_PARK"] + attributes["SNACK_BAR"] + attributes["SOCCER"] + attributes["SOFTBALL"] + attributes["SWIMMING"] + attributes["TENNIS"] + attributes["VOLLEYBALL"] + attributes["WADING_POO"];
    //var html = fncAdjustImage(attributes["IMAGE"]) + "<b>Name: </b>" + fncAdjustHref(attributes["URL"], attributes["NAME"]) + "<br/><b>Address:</b> " + attributes["ADDRESS"] + "<br>" + fncAdjustFacilities(attributes); //width=101 height=100
    var html = fncCreateParksBubble(attributes["IMAGE"], attributes["URL"], attributes["NAME"], attributes["ADDRESS"], attributes);
    //gmap.openInfoWindowHtml(polygon.getBounds().getCenter(),html,{maxWidth:70, maxHeight:100, autoScroll:true});
    gmap.openInfoWindowHtml(center,html,{Width: 350});
}

function findTrailCompleteCallback(response) //trail
{
    var findResults = response.findResults, findResult, geometry, attributes, geom, i,j, name, foundField;
    var uniqueId = 0;
        
    for(i=0; i<findResults.length; i++)
    {
        findResult = findResults[i];
        geometry = findResult.feature.geometry;
        
        attributes = findResult.feature.attributes;
        name = findResult.layerName;
        foundField = findResult.foundFieldName;
        
        for(j=0; j<geometry.length; j++)
        {
            geom = geometry[j];
            //gmap.addOverlay(geom);
        }
    }
    var bounds = geom.getBounds();
    var center = bounds.getCenter();
    var zoomLevel = gmap.getBoundsZoomLevel(bounds);
    gmap.setCenter(center,zoomLevel);
    //var html = fncAdjustImage(attributes["IMAGE"]) + "<b>Name: </b>" + fncAdjustHref(attributes["URL"], attributes["TRAIL_NAME"]) + "<br/><b>Type:</b> " + attributes["TRAIL_TYPE"] + "<br/><b>Difficulty level:</b> " + attributes["DIFF_LVL"]+ "<br/><b>Length:</b> " + attributes["LENGTH"] + " mi";
    var html = fncCreateTrailsBubble(attributes["IMAGE"], attributes["URL"], attributes["TRAIL_NAME"], attributes["TRAIL_TYPE"], attributes["DIFF_LVL"], attributes["LENGTH"]);
    gmap.openInfoWindowHtml(center,html,{Width: 350});
}
    
function createPoly(geom,layer,attributes)
{
    poly = new GPolygon(geom);
    //poly.mylayer = layer;
    if(layer=="Trail")
    {
        GEvent.addListener(geom, "click", GEvent.callbackArgs(geom, onClickTrailFunc, attributes));
        GEvent.addListener(geom, "mouseout", onMouseOutTrailFunc);
    }
    else
    {
        GEvent.addListener(geom, "mouseover", GEvent.callbackArgs(geom, onMouseOverParkFunc, attributes));
    }
    //gpolys.push(poly);
    //gmap.addOverlay(poly);
    return poly;
}

function onMouseOverParkFunc(attributes)
{
    var polygon = this;
//    polygon.setFillStyle({color: "#FF6666"},{weight: 4},{opacity: 0.4}); //color, weight, opacity(0-1)
//    polygon.setStrokeStyle({color: "#FF6666"});
    //var html = fncAdjustImage(attributes["IMAGE"]) + "<b>Name: </b>" + fncAdjustHref(attributes["URL"], attributes["NAME"]) + "<br/><b>Address:</b> " + attributes["ADDRESS"] + "<br>" + fncAdjustFacilities(attributes); //+ "<br/><img src='rollhls3.jpg'/>";
    var html = fncCreateParksBubble(attributes["IMAGE"], attributes["URL"], attributes["NAME"], attributes["ADDRESS"], attributes);
    gmap.openInfoWindowHtml(polygon.getBounds().getCenter(),html,{Width: 350});
}

function onClickTrailFunc(attributes)
{
    var poly = this;
    //polygon.setFillStyle({color: "#FF6666"},{weight: 4},{opacity: 0.4}); //color, weight, opacity(0-1)
    //polygon.setStrokeStyle({color: "#FF6666"});
    //var html = fncAdjustImage(attributes["IMAGE"]) + "<b>Name: </b>" + fncAdjustHref(attributes["URL"], attributes["TRAIL_NAME"]) + "<br /><b>Type:</b> " + attributes["TRAIL_TYPE"] + "<br/><b>Level:</b> " + attributes["DIFF_LVL"]+ "<br/><b>Length:</b> " + attributes["LENGTH"] + " mi";
    var html = fncCreateTrailsBubble(attributes["IMAGE"], attributes["URL"], attributes["TRAIL_NAME"], attributes["TRAIL_TYPE"], attributes["DIFF_LVL"], attributes["LENGTH"]);
    //gmap.openInfoWindowHtml(poly.getBounds().getCenter(),html);
    gmap.openInfoWindowHtml(getPolylineCenter(poly),html,{Width: 350});
}

function onMouseOutTrailFunc()
{
    var polygon = this;
    //polygon.setStrokeStyle({color: "#CC6600",weight: 3,opacity: 0.6});
    //gmap.closeInfoWindow();
}

function getPolylineCenter(poly)
{
    var n = poly.getVertexCount(), index;
    if(n % 2==0)
    {
        index = n/2;
    }
    else
    {
        index = (n+1)/2;
    }
    var vert=poly.getVertex(index);
    var lat=vert.lat();
    var lng=vert.lng();
    return new GLatLng(lat,lng);
}


//CC Added
function fncAdjustHref(strURL, strTitle)
{
    var strHref = strTitle;
    var itemHrefStart = '';
    var itemHrefEnd = '';
    if(strURL == '' || strURL == null || strURL == 'Null' || strURL == undefined)
    {
        strHref = strTitle;
    }
    else if((strURL.indexOf("http") > 0 || strURL.indexOf("www.") > 0) && strURL.indexOf("www.cityoffullerton.com") < 0)
    {
        strHref = '<a href="' + strURL + '" target="_blank">' + strTitle + '</a>';
    }
    else
    {
        strHref = '<a href="' + strURL + '">' + strTitle + '</a>';
    }
    
    return strHref;
}

function fncAdjustImage(strImage)
{
    var str = '';
    var itemStart = '';
    var itemEnd = '';
    if(strImage == undefined || strImage == '' || strImage == null || strImage == 'Null')
    {
        str = '';
    }
    else
    {
        strImage = strImage.toLowerCase();
        if(strImage.indexOf(".jpg") > -1 || strImage.indexOf(".gif") > -1 || strImage.indexOf(".jpeg") > -1 || strImage.indexOf(".png") > -1)
        {
            str = "<img src='" + strImage + "' align='right' style='padding-left: 3px;'>";
        }
    }
    return str;
}

function fncAdjustFacilities(aryAttributes)
{
    var cntAmenities = 0;
    var trackAmenities = 0;
    var strAmenities = "";
    var lenHalfAmenities = 10;
    
    for(var x = 0; x < aryAttributeDB.length; x++)
    {
        if(aryAttributes[aryAttributeDB[x]] == "Y")
        {
            cntAmenities++;
        }
    }
    
    lenHalfAmenities = Math.ceil(cntAmenities/2);
    strAmenities += "<b>Facilities: </b>";
    strAmenities += "<div style='padding-left: 5px;'>";
    for(var y = 0; y < aryAttributeDB.length; y++)
    {
        if(aryAttributes[aryAttributeDB[y]] == "Y")
        {
            if(trackAmenities == lenHalfAmenities)
            {
                //strAmenities += "</td>";
                //strAmenities += "<td width=47% valign=top>";
            }
            strAmenities += aryAttributeName[y] + "<br />";
            trackAmenities++;
        }
    }
    strAmenities += "</div>";
        return strAmenities;
}

function fncCreateParksBubble(image, url, name, address, attributes)
{
    var html = "<div style='width: 300px; height: 150px; overflow: auto;'>" + 
                "<b>Name: </b>" + fncAdjustHref(url, name) + 
                "<br /><b>Address:</b> " + address + 
                fncAdjustImage(image) + 
                "<br>" + fncAdjustFacilities(attributes) + 
                "</div>"; 
    
    return html;
}

function fncCreateTrailsBubble(image, url, name, type, difficulty, length)
{
    var html = "<div style='width: 250px; height: 150px; overflow: auto;'>" + 
                fncAdjustImage(image) + 
                "<b>Name: </b>" + fncAdjustHref(url, name) + 
                "<br /><b>Type:</b> " + type + 
                "<br/><b>Level:</b> " + difficulty + 
                "<br/><b>Length:</b> " + length + " mi" + 
                "</div>"; 
    
    return html;
}
