/*Script developed by Hennepin County GIS division copyright 2009.  This file is meant to support the mapping component
 of the mandated American Recovery and Reinvestment Act tracking within Hennepin County.  Geographic locations of items are
 approximate.
 */
dojo.require("esri.map");
dojo.require("esri.tasks.query");
var layer, map, qLayer, visible = [];
var cat, prj, baseLayer, factor = 0.01125;
var queryTask, clickQ, options, infoX = 275, infoY = 150;
var errorString = "An error occured with the map service, please try again.\nContact us if the issue persists.";
var HCmapService = "http://gis.co.hennepin.mn.us/ArcGIS/rest/services/Maps/HENN_DYNAMIC_STIMULUS/MapServer";
var baseService = "http://gis.co.hennepin.mn.us/ArcGIS/rest/services/Maps/HENN_CACHE_BASEMAP/MapServer";
function init(){
    cat = dojo.byId("prjType").value.toLowerCase(); //get the category
    try { //figure out if mapping a project page
        prj = dojo.byId("prjNum").value.toString();
    } 
    catch (e) {
        prj = "none";
    }
    switch (cat) {//switch for setting qLayer
        case "transportation":
            qLayer = 0;
            break;
        case "environment":
            qLayer = 4;
            break;
        case "health":
            qLayer = 3;
            break;
        case "housing":
            qLayer = 2;
            break;
        case "justice":
            qLayer = 1;
            break;
        case "all":
            qLayer = -99;
            break;
    }
    if (dojo.isIE && dojo.isIE < 7) {
        esriConfig.defaults.map.zoomDuration = 0;
    }
    clickQ = new esri.tasks.Query(); //have to define the query in initialization.
    clickQ.returnGeometry = true;
    clickQ.outFields = ["NEW_LOCATION_NAME_TXT", "NEW_WEBSITE_WEBTITLE", "NEW_WEBSITE_CATEGORY", "NEW_WEBSITE_DESCRIPT_SHORT", "AWARD_AMOUNT", "NEW_WEBSITE_WEBSITE"];
    map = new esri.Map("myMap");
    if (prj != "none") {
        dojo.connect(map, "onLoad", function(){
            map.disableMapNavigation();
        });
    }
    layer = new esri.layers.ArcGISDynamicMapServiceLayer(HCmapService);
    baseLayer = new esri.layers.ArcGISTiledMapServiceLayer(baseService);
    map.addLayer(baseLayer);
	if (layer.loaded) {
        buildLayerList(layer);
    }
    else {
        dojo.connect(layer, "onLoad", buildLayerList);
    }
    if ((cat != "all") && (prj == "none")) {
        dojo.connect(map, "onClick", executeQuery);
        queryTask = new esri.tasks.QueryTask(HCmapService + "/" + qLayer);
    } /*set the map to query the points on map click.  if adding identify task to this script, configure here.*/
    dojo.connect(window, "onResize", resizeMap); //make sure the map always covers the desired area.   
}

function buildLayerList(layer){ //loop through the layers of the stimulus service and get the correct layer to be visible
	var infos = layer.layerInfos, info, items = [];
    for (var i = 0, il = infos.length; i < il; i++) {
        info = infos[i];
        if (info.defaultVisibility) {
            if (info.name.toLowerCase() == cat) {
                visible.push(info.id); //only get the category to be visible              
            }
            else 
                if (cat == "all") {
                    visible.push(info.id); //set all layers to visible
                }
        }
        if ((cat == "all") && (info.id != 5)) { // for all project map, create the TOC to switch layers on/off
            items[i] = "<input type='checkbox' class='list_item' checked='" + (info.defaultVisibility ? "checked" : "") + "' id='" + info.id + "' onclick='updateLayerVisibility();' /><label for='" + info.id + "'>" + info.name + "</label>";
        }
    }
    if (cat == "all") { //if all project map, add the TOC to the map
        var str = items.join().toString();
        var str2 = str.replace(/,/g, " ");
        dojo.byId("layer_list").innerHTML = "<strong>Layers:</strong> " + str2;
    }
    //    map.setLevel(0);
    // if (prj != "none") {//zoom to the extent of all points within the visible array 
    //     setZoom(visible);
    // } 
    layer.setVisibleLayers(visible);
    map.addLayer(layer);
}

function updateLayerVisibility(){ //handles switching of layer visiblity in all project map.
    var inputs = dojo.query(".list_item"), input;
    visible = [];
    for (var i = 0, il = inputs.length; i < il; i++) {
        if (inputs[i].checked) {
            visible.push(inputs[i].id);
        }
    }
    layer.setVisibleLayers(visible);
}

function goToExtent(features){ //creates an extent based on the points within a layer.
    var f, extent;
    if (features[0].geometry.type == "point") {
        for (var i = 0, il = features.length; i < il; i++) {
            f = features[i];
            if (extent) {
                extent = extent.union(new esri.geometry.Extent(f.geometry.x - factor, f.geometry.y - factor, f.geometry.x + factor, f.geometry.y + factor, new esri.SpatialReference({
                    wkid: 4326
                })));
            }
            else {
                extent = new esri.geometry.Extent(f.geometry.x - factor, f.geometry.y - factor, f.geometry.x + factor, f.geometry.y + factor, new esri.SpatialReference({
                    wkid: 4326
                }));
            }
        }
    } //handle other geometry if needed
    map.setExtent(extent);
}

function setZoom(visLayers){ //query all features of a category
    var zLayer;
    if (visLayers.length == 1) {
        for (var i = 0, il = visLayers.length; i < il; i++) {
            zLayer = visLayers[i];
            if (zLayer != 5) {
                var qT = new esri.tasks.QueryTask(HCmapService + "/" + zLayer);
                var q = new esri.tasks.Query();
                q.returnGeometry = true;
                q.outFields = ["NEW_WEBSITE_UNIQUE_NO"];
                if (prj == "none") {
                    q.where = "1=1"; //get all from layer
                }
                else {
                    q.where = "NEW_WEBSITE_UNIQUE_NO='" + prj + "'";
                }
                qT.execute(q, function(results){
                    goToExtent(results.features);
                });
            }
        }
    }
    else {
        //map.setExtent(extentAndSR.expand(1.1));
        map.setLevel(0)
        return;
    }
}

function resizeMap(){//used for resizing of map
    var timer;
    clearTimeout(timer);
    timer = setTimeout(function(){
        map.resize();
        map.reposition;
    }, 500);
    map.reposition();
}

function executeQuery(evt){ //query the project points layers on map click.
    var fact;
    switch (map.getLevel()) { //change the "buffer" of the click depending on the zoom level, larger when zoomed out
        case 0: fact = 1220; break;
        case 1: fact = 610; break;
        case 2: fact = 305; break;
        case 3: fact = 122; break;
        case 4: fact = 76; break;
        case 5: fact = 46; break;
        case 6: fact = 23; break;
        case 7: fact = 15; break;
        default: fact = 8; break;
    }
    var newPoint, qEnv;
    qEnv = new esri.geometry.Extent(evt.mapPoint.x - fact, evt.mapPoint.y - fact, evt.mapPoint.x + fact, evt.mapPoint.y + fact, new esri.SpatialReference({
        wkid: 26915
    }));
    //alert((evt.mapPoint.x + fact) - (evt.mapPoint.x - fact));
    clickQ.geometry = qEnv;
    queryTask.execute(clickQ, function(featureSet2){
        map.infoWindow.hide();
        var infoCont = "_";
        var fCOunt = featureSet2.features.length;
        if (featureSet2.features.length < 1) {
            return;
        }
        for (var i = 0, il = featureSet2.features.length; i < il; i++) {
            var graphic = featureSet2.features[i]; //Get the current feature from the featureSet.
            var scrPt = map.toScreen(graphic.geometry); //convert the selected point location to screen location
            var atts = graphic.attributes;
            var title = atts.NEW_LOCATION_NAME_TXT; //only for testing data., must change back to NEW_LOCATION_NAME_TEXT
            var proj = atts.NEW_WEBSITE_WEBTITLE;
            var category = atts.NEW_WEBSITE_CATEGORY;
            var money = atts.AWARD_AMOUNT;
            var link = atts.NEW_WEBSITE_WEBSITE;
            if (infoCont == "_") {
                infoCont = "<i>" + proj + "</i><br /><b>Category: </b>" + category + "<br />";
                if (money != null) {
                    infoCont += "<b>Funds: </b>" + money + "<br />";
                }
                infoCont += "<b>Link: </b><a href='" + cat + "/" + link + "'>More Info</a> ";
            }
            else {
                infoCont += "<hr /><i>" + proj + "</i><br /><b>Category: </b>" + category + "<br />";
                if (money != null) {
                    infoCont += "<b>Funds: </b>" + money + "<br />";
                }
                infoCont += "<b>Link: </b><a href='" + cat + "/" + link + "'>More Info</a> ";
            }
        }
        if (fCOunt > 1) {
            infoCont += "<br/><br />";
            if (dojo.isIE && dojo.isIE < 7) {
                infoCont += "<br />";
            }
        }
        map.infoWindow.setTitle(title);
        map.infoWindow.setContent(infoCont);
        map.infoWindow.resize(infoX, infoY);
        map.infoWindow.show(scrPt, map.getInfoWindowAnchor(scrPt));
    });
}

dojo.addOnLoad(init);

