﻿//cosgis namespace
var cosgis = {};

//Google maps
cosgis.map = null;
cosgis.polyline = null;
cosgis.geocoder = null;
cosgis.marker;
//
cosgis.query = null;
cosgis.qtask = null;
//Map servers
cosgis.map_server = "198.1.35.115";
//Dynamic map
cosgis.dynamic_map_overaly = null;
cosgis.dynamic_map = null;
cosgis.dynamic_map_name = "COS_SnowPlow_WM";
cosgis.dynamic_url = "http://" + cosgis.map_server + "/ArcGIS/rest/services/" + cosgis.dynamic_map_name + "/MapServer";
cosgis.dynamic_service_url = "http://" + cosgis.map_server + "/arcgis/services/" + cosgis.dynamic_map_name + "/MapServer";
cosgis.dynamic_opacity = 0.55;
//Tiled maps
cosgis.tile_url_base = "http://198.1.35.115/ArcGIS/rest/services/COS_BasemapStreet_WM_Cache/MapServer";
//Ajax
cosgis.ajax_req = null;
//Map Start Coords
cosgis.LAT = 47.676;
cosgis.LNG = -117.424;
//Zoom level
cosgis.zoom_level = 12;
//
cosgis.reload_timer = null;
cosgis.reload_ms = 600000;

//Overlays
cosgis.map_extension = null;

function load() {
    if (GBrowserIsCompatible()) {
        //
        resizeApp();

        //Gmap object
        var gmap_opts = { backgroundColor: '#FFFFFF' };
        cosgis.map = new GMap2(document.getElementById("map"), gmap_opts);
        //G_NORMAL_MAP.getMaximumResolution = function() { return 17 } 

        //Create MapExtension utility class
        cosgis.map_extension = new esri.arcgis.gmaps.MapExtension(cosgis.map);

        //Add dynamic maps
        addDynamicMap(cosgis.dynamic_url);

        //Add tiled maps
        var mapOptions = { opacity: 1.0, minResolution: 11, maxResolution: 18 };
        var tiledmap = new esri.arcgis.gmaps.TiledMapServiceLayer(cosgis.tile_url_base, mapOptions, addTiledMap);

        //Update TOC scale dependent rendering
        GEvent.addListener(cosgis.map, "moveend", function () {
            //get database last updated
            queryLastUpdate();
            //set up auto map refresh
            clearInterval(cosgis.reload_timer);
            cosgis.reload_timer = setInterval('reloadMap()', cosgis.reload_ms);
        });

        //Set up Identify
        GEvent.addListener(cosgis.map, 'click', mapClick);


        //Geocoder
        cosgis.geocoder = new GClientGeocoder();
        
    }
}

function reloadMap() {
    queryLastUpdate();
    cosgis.dynamic_map.refresh();
}


//Handle single click vs double click 
var clckTimeOut = null;
var isDoubleClick = false;

function mapClick(ol, latlon) {
    if (clckTimeOut) {
        window.clearTimeout(clckTimeOut);
        clckTimeOut = null;
        doubleClick(ol, latlon);
    }
    else {
        clckTimeOut = window.setTimeout(function() { singleClick(ol, latlon) }, 500);
    }
}

function singleClick(ol, latlon) {
    window.clearTimeout(clckTimeOut);
    clckTimeOut = null;
    doIdentify(ol, latlon); //run identify if single click
}

function doubleClick(ol, latlon) {

}

//------------------------------------------------------------//
//--ESRI REST API--//
//------------------------------------------------------------//
//Dynamic layer opacity
function setOp() {
    var val = parseFloat(document.getElementById("divHorizontalSlider").value);
    val = val / 100;
    cosgis.dynamic_map.setOpacity(val);
}

//Dynamic map
function addDynamicMap(service) {
    var imageParams = new esri.arcgis.gmaps.ImageParameters();
    imageParams.format = "png32";
    imageParams.layerOption = "include";
    cosgis.dynamic_map = new esri.arcgis.gmaps.DynamicMapServiceLayer(service, imageParams, cosgis.dynamic_opacity, dynMapCallBack);
}

function dynMapCallBack(groundov) {
    cosgis.map.addOverlay(groundov);
    cosgis.dynamic_map_overaly = groundov;
}

function addTiledMap(gTileLayer) {
    //Set Map Center
    var center = new GLatLng(cosgis.LAT, cosgis.LNG);
    cosgis.map.setCenter(center, cosgis.zoom_level);

    //Customize gmap object
    var customUI = cosgis.map.getDefaultUI();
    customUI.controls.scalecontrol = true; //Scale
    customUI.controls.largemapcontrol3d = true; //Zoom
    customUI.controls.maptypecontrol = false; //Default map type control
    customUI.controls.menumaptypecontrol = false; //Menu map type control
    customUI.zoom.scrollwheel = true;  //Scroll zoom
    cosgis.map.setUI(customUI);

    //
    var opts = { errorMessage: "No data available", minResolution: 11, maxResolution: 18 };
    var tilelayers = [gTileLayer];
    var gMapType = new GMapType(tilelayers, new GMercatorProjection(19), "Spokane", opts);
    cosgis.map.addMapType(gMapType);

    //Map type control
    var mapControl = new GHierarchicalMapTypeControl();
    cosgis.map.addControl(mapControl);
    //cosgis.map.setMapType(G_PHYSICAL_MAP);
    //cosgis.map.setMapType(gMapType);
}

//------------------------------------------------------------//
//--GEOCODE--//
//------------------------------------------------------------//

//Find address
function findAddress(address) {
    //alert("here");
    if (cosgis.geocoder) {
        address = address + " Spokane, WA";
        cosgis.geocoder.getLocations(address, addAddressToMap);
    }
}

//Add to map
function addAddressToMap(response) {
    //cosgis.map.clearOverlays();
    if (!response || response.Status.code != 200) {
        alert("Address not found");
        cosgis.search_new = false;
    } else {
        var place = response.Placemark[0];
        var addr = place.address.split(",");
        var point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);

        //Write html
        var html = "<div id=\"divResultsWindow\" ><h3>Address:</h3><p style='font-size:1.3em; margin-top:0px;'>" + addr[0] + "<br>" + addr[1] + ", " + addr[2] + "</p></div>";
        html += "<p style='color:#696969; font-style:italic;'>Click on a route for more info...</p>"

        //Add points to map
        addMarker(point, html);

        //Write to results div
        e('txtSearch').value = addr[0];
    }
}

//Add point and info window to map
function addMarker(pnt, html) {
    //Remove other markers
    removeMarker();
    //Set zoom
    if (cosgis.map.getZoom() < 17)
        cosgis.map.setZoom(17);
    //Center
    cosgis.map.setCenter(pnt);
    //Create marker and add to map
    cosgis.marker = new GMarker(pnt);
    cosgis.map.addOverlay(cosgis.marker);
    //Info windows options
    var opts = { maxWidth: 250 };
    //Open info window
    cosgis.marker.openInfoWindowHtml(html, opts);
    //Open onclick
    GEvent.addListener(cosgis.marker, "click", function() {
        cosgis.marker.openInfoWindowHtml(html, opts);
    });
}

function removeMarker() {
    if (typeof (cosgis.marker) != 'undefined')
        cosgis.map.removeOverlay(cosgis.marker);
}

//------------------------------------------------------------//
//--IDENTIFY--//
//------------------------------------------------------------//
function doIdentify(overlay, point) {
    if (overlay) {
        return;
    }
    //var layerid = cosgis.identify_layer_id;
    cosgis.id_task = new esri.arcgis.gmaps.IdentifyTask(cosgis.dynamic_url);
    cosgis.id_point = point;
    var dim = cosgis.map.getSize();

    var idparams = new esri.arcgis.gmaps.IdentifyParameters();
    idparams.geometry = point;
    idparams.tolerance = 5;
    idparams.bounds = cosgis.map.getBounds();
    idparams.width = dim.width;
    idparams.height = dim.height;
    idparams.layerIds = [1, 2, 3, 4, 5, 12];
    idparams.layerOption = "all";
    idparams.returnGeometry = false;

    cosgis.id_task.execute(idparams, idCallBack);
}

function idCallBack(idresults) {
    if (typeof (idresults.identifyResults[0]) != 'undefined') {
        var layer_name = idresults.identifyResults[0].layerName;
        if (layer_name.indexOf("Snow") != -1) {
            //Get street address
            var street_address = "";
            for (var i = 0; i < idresults.identifyResults.length; i++) {
                var result = idresults.identifyResults[i];
                if (result.layerName == "Street") {
                    var att = result.feature.attributes;
                    street_address = att.BlockNumber + " " + att.StreetDirection + " " + att.StreetName + " " + att.StreetType;
                    break;
                }
            }

            //Attributes for record 0
            var attributes = idresults.identifyResults[0].feature.attributes;
            //Info window
            var html = "<h3>Snow Plow Status</h3>";
            html += "<table border=\"0\" cellspacing=\"2\">";

            if (layer_name.indexOf("SnowRes") != -1) {
                html += "<tr class=\"tabCell1\"><td>Route:</td><td>" + attributes.Route + "</td></tr>";
                html += "<tr class=\"tabCell2\"><td>Type:</td><td>Residential or Local Street</td></tr>";
            } else {
                html += "<tr class=\"tabCell1\"><td>Type:</td><td>Arterial Street</td></tr>";
            }
            html += "<tr class=\"tabCell1\"><td>Status:</td><td><strong>" + attributes.Status + "</strong></td></tr>";
            html += "<tr class=\"tabCell2\"><td>Last Updated:</td><td>" + attributes.LastUpdate + "</td></tr>";
            if (street_address != "") {
                html += "<tr class=\"tabCell1\"><td>Block:</td><td>" + street_address + "</td></tr>";
            }
            html += "</table>";

            //Add to map
            cosgis.map.openInfoWindow(cosgis.id_point, html, { maxWidth: 250 });
        }
    }
}

//------------------------------------------------------------//
//--GENERAL PAGE FUNCTIONS--//
//------------------------------------------------------------//
//Resizes map
function resizeApp() {
    var offsetTop = 0;
    var mapElem = e("map");
    //var leftElem = e("divLeftColumn");
    var offsetBottom = 10;

    for (var elem = mapElem; elem != null; elem = elem.offsetParent) {
        offsetTop += elem.offsetTop;
    }

    var height = getWindowHeight() - offsetTop - offsetBottom;
    if (height >= 0) {
        mapElem.style.height = height - 0 + "px";
    }

    if (cosgis.map) {
        cosgis.map.checkResize();
        cosgis.dynamic_map.refresh();
    }

}

//Get Height
function getWindowHeight() {
    if (window.self && self.innerHeight) {
        return self.innerHeight;
    }
    if (document.documentElement && document.documentElement.clientHeight) {
        return document.documentElement.clientHeight;
    }
    return 0;
}

//Get Element ID
function e(id) { return document.getElementById(id); }

//Save Key Value Pairs
function saveFormData(key, val) {
    cosgis.form_data[key] = val;
}
function getFormData(key) {
    var val = cosgis.form_data[key];
    if (typeof (val) == 'undefined') { val = ''; }
    return val;
}

//------------------------------------------------------------//
//---AJAX---//
//------------------------------------------------------------//
function getXmlHttpRequestObject() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        return new ActiveXObject("Microsoft.XMLHTTP");
    } else {
        alert("This function is not supported by your browser");
    }
}

//------------------------------------------------------------//
//---Last Update---//
//------------------------------------------------------------//

function getLastUpdate() {
    cosgis.ajax_req = getXmlHttpRequestObject();
    if (cosgis.ajax_req.readyState == 4 || cosgis.ajax_req.readyState == 0) {
        cosgis.ajax_req.open("GET", 'callback.ashx?get=dt', true);
        cosgis.ajax_req.onreadystatechange = parseLastUpdate;
        cosgis.ajax_req.send(null);
    }
}

//Build the toc
function parseLastUpdate() {
    if (cosgis.ajax_req.readyState == 4) {
        if (cosgis.ajax_req.responseText.length > 0) {
            //alert(cosgis.ajax_req.responseText);
            e("pDate").innerHTML = "<strong>Updated:</strong>&nbsp;" + cosgis.ajax_req.responseText;
        }
        cosgis.ajax_req = null;
    }
}

function queryLastUpdate() {
    var qtask = new esri.arcgis.gmaps.QueryTask("http://198.1.35.115/ArcGIS/rest/services/COS_SnowPlow_WM/MapServer/14");
    cosgis.query = new esri.arcgis.gmaps.Query();
    cosgis.query.outFields = ["LastUpdate"];
    cosgis.query.where = "ID = 1";
    qtask.execute(cosgis.query, false, queryLastUpdateComplete);
}

function queryLastUpdateComplete(fset) {
    var lastUpdate = fset.features[0].attributes.LastUpdate;
    var dt = new Date(lastUpdate);
    var dtLocal = dojo.date.add(dt, "hour", 8);
    var dtDisplay = dojo.date.locale.format(dtLocal, { datePattern: "M/dd/yyyy h:mm a", selector: "date" });
    e("pDate").innerHTML = "<strong>Updated:</strong>&nbsp;" + dtDisplay;
}

