dojo.require("esri.map");
dojo.require("esri.toolbars.navigation");
dojo.require("dijit.form.Button");
dojo.require("dijit.Dialog");
dojo.require("esri.tasks.locator");
dojo.require("esri.tasks.query");
dojo.require("esri.tasks.find");
dojo.require("esri.tasks.gp");

var map, symbol, locator, queryTask, query, featureSet, find, params, gp;

var secondDlg;

var startExtent = new esri.geometry.Extent(-9501963.4729, 5077426.8804,-9061074.6938, 5529934.0878, new esri.SpatialReference({wkid:102100}));
var defaultMode = 'NONE';
var mode = defaultMode;

var currentDate;

function Init() {

	//varible to keep track of when all layers have been loaded.
	var layersLoaded = 0;
	//loading image. id
    var loading = dojo.byId("loadingImg");

	// defining levels of detail
    var lods = [ 
		{"level" : 7, "resolution" : 1222.99245256249, "scale" : 4622324.434309},
		{"level" : 8, "resolution" : 611.49622628138, "scale" : 2311162.217155}, 
		{"level" : 9, "resolution" : 305.748113140558, "scale" : 1155581.108577}, 
		{"level" : 10, "resolution" : 152.874056570411, "scale" : 577790.554289}, 
		{"level" : 11, "resolution" : 76.4370282850732, "scale" : 288895.277144}, 
		{"level" : 12, "resolution" : 38.2185141425366, "scale" : 144447.638572}, 
		{"level" : 13, "resolution" : 19.1092570712683, "scale" : 72223.819286}, 
		{"level" : 14, "resolution" : 9.55462853563415, "scale" : 36111.909643}
          
	  ];
	
	//zoom slider configs
	esriConfig.defaults.map.slider = { left:"22px", top:"100px", width:null, height:"125px" };
    esriConfig.defaults.map.sliderLabel = null;

	//adding map
	map = new esri.Map("map",{
		extent:startExtent, lods:lods
	});	
	
	//resize listener
	dojo.connect(map, 'onLoad', function(map) {
		dojo.connect(dijit.byId('map'), 'resize', resizeMap);
    });
	
	//loading icon listeners
	dojo.connect(map, "onLoad", showLoading);
    dojo.connect(map, "onZoomStart", showLoading);
    dojo.connect(map, "onPanStart", showLoading);
	
	//Listen for infoWindow onHide event and clear map
    dojo.connect(map.infoWindow, "onHide", function() {map.graphics.clear();});
	
	//add locator service
	locator = new esri.tasks.Locator(LocatorURL);
    dojo.connect(locator, "onAddressToLocationsComplete", showResults);
	
	//add basemap service
	var streetMap = new esri.layers.ArcGISTiledMapServiceLayer(BasemapURL, {opacity:1});
	map.addLayer(streetMap);
	dojo.connect(streetMap, "onUpdate", hideLoading);
	
	//add operational layer service
	var DTE = new esri.layers.ArcGISTiledMapServiceLayer(dteURL, {id:"DTE", opacity:0.6});
	map.addLayer(DTE);
	dojo.connect(DTE, "onUpdate", hideLoading);
	
	//add geoprocessor service
	gp = new esri.tasks.Geoprocessor(gpURL);

	
	//query listener
    dojo.connect(map, "onClick", executeQueryTask); 
	//build query task
    queryTask = new esri.tasks.QueryTask(queryURL);
    //build query filter
    query = new esri.tasks.Query();
    query.returnGeometry = true;
    query.outFields = ["JOB_ID", "NUM_CUST", "EST_REP_DTTM", "CAUSE", "OFF_DTTM", "ADD_DTTM", "CIRCUIT_EST_DTTM", "CIRCUIT_EST_ENDDTTM", "EST_REP_ENDDTTM", "EST_REP_DTTM"];
	map.infoWindow.resize(325, 180);

	//Find parameters
    find = new esri.tasks.FindTask(findURL);
    params = new esri.tasks.FindParameters();
	params.contains = false;
    params.layerIds = [1];
    params.searchFields = ["ZIP"];
	
	//loading icon functions
	//show
	function showLoading() {
    esri.show(loading);
    map.hideZoomSlider();
    }
    //hide
	function hideLoading() {
    layersLoaded++;
		if (layersLoaded === map.layerIds.length) {
            esri.hide(loading);
            map.enableMapNavigation();
            map.showZoomSlider();
            layersLoaded = 0;
        }
    }
	
	//create error dialog box
	dojo.addOnLoad(function() {
            // create the dialog:
            secondDlg = new dijit.Dialog({
                title: "ZIP Code Error",
                style: "width: 300px"
            });
        });
}

	//error dialog box
	function showZipDialog() {
            // set the content of the dialog:
            secondDlg.attr("content", "Please enter a valid ZIP Code that is within the Detroit Edison Service Area. Example: 48197");
            secondDlg.show();
        }

	function getEstMode(results, messages) {
		mode = results[0].value;
		var tempDate = results[1].value;
		currentDate = tempDate.date;
	}

			
			
	//enter key fires search
	function processKey(e)
	{
		if (null == e)
			e = window.event ;
		if (e.keyCode == 13)  {
			locate();
			doFind(dojo.byId('address').value);
		}
	}
	
	//resize the map when the browser resizes
	function resizeMap() {
        var resizeTimer;
        clearTimeout(resizeTimer);
        resizeTimer = setTimeout(function() {
          map.resize();
          map.reposition();
        }, 500);
    }

    //Locator functions
    function locate() {
		esri.show(dojo.byId('loadingImg'));
		map.graphics.clear();
		map.infoWindow.hide();
        var add = dojo.byId("address").value.split(",");
        var address = {
          ZIP: add[0]
        };
        locator.addressToLocations(address);
    }

    function showResults(candidates) {
		esri.hide(dojo.byId('loadingImg'));
        var candidate;
        var symbol = new esri.symbol.SimpleMarkerSymbol();

        symbol.setStyle(esri.symbol.SimpleMarkerSymbol.STYLE_DIAMOND);
        symbol.setColor(new dojo.Color([0,0,0,0.8]));
		
        var points =  new esri.geometry.Multipoint(map.spatialReference);
		if (candidates.length > 0){
			for (var i=0, il=candidates.length; i<il; i++) {
				candidate = candidates[i];
				if (candidate.score == 100) {
					var attributes = { address:candidate.address, score:candidate.score, locatorName:candidate.attributes.Loc_name };
					var graphic = new esri.Graphic(candidate.location, symbol, attributes);
					map.graphics.add(graphic);
					map.graphics.add(new esri.Graphic(candidate.location, new esri.symbol.TextSymbol(attributes.address).setOffset(0, 10)));
					points.addPoint(candidate.location);
				}
			}			
	    map.setExtent(points.getExtent().expand(3));
		}
		else if (candidates.length <= 0){
			showZipDialog();
		}
	}

	//Query Functions
	function executeQueryTask(evt) {
		esri.show(dojo.byId('loadingImg'));
        map.infoWindow.hide();
        map.graphics.clear();
        featureSet = null;
		gp.execute({},getEstMode);
        //onClick event returns the evt point where the user clicked on the map.
        //This is contains the mapPoint (esri.geometry.point) and the screenPoint (pixel xy where the user clicked).
        //set query geometry = to evt.mapPoint Geometry
        query.geometry = evt.mapPoint;

        //Execute task and call showResults on completion
        queryTask.execute(query, function(fset) {
          if (fset.features.length === 1) {
            showFeature(fset.features[0],evt);
          } else if (fset.features.length !== 0) {
            showFeatureSet(fset,evt);
          } else 
			{
			esri.hide(dojo.byId('loadingImg'));
			map.graphics.clear();
			}
		  
        });
    }

	function doFind() {
        params.searchText = dojo.byId("address").value;
        find.execute(params, showResults2);
    }
	  
    function showResults2(results) {
        var result, attribs;
        var s = [""];
        for (var i=0, il=results.length; i<il; i++) {
          result = results[i];
          attribs = result.feature.attributes;
		  var cst = attribs.RPT_CUST_STILL_OUT
		  var a = "are"
		  var c = "customers"
			  if (cst == 1){
				c = "customer";
				a = "is"}
			  else if (cst == "Null"){
				cst = "0"}
          s.push("<br>There "+ a + " <b>" + cst + "</b> " + c + " affected in the <b>" + 
		  attribs.PO_NAME + "</b> ZIP Code <b>" + attribs.ZIP + "</b>.<br>");
        }
        dojo.byId("info").innerHTML = s.join("");
    }


    function showFeature(feature,evt) {
		esri.hide(dojo.byId('loadingImg'));
        map.graphics.clear();
		// need to get current date from server side, not from client machine!!  need to change this code.


        //set symbol
        var symbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([0,0,0]), 3), new dojo.Color([0,0,0,0.3]));
        feature.setSymbol(symbol);

        //construct infowindow title and content
        var attr = feature.attributes;
		
		var expiredCircuit = new Date(attr.CIRCUIT_EST_ENDDTTM);
		expiredCircuit.setMinutes(expiredCircuit.getMinutes() + expiredCircuit.getTimezoneOffset());  // for EST time zone		
		var expiredNormal = new Date(attr.EST_REP_ENDDTTM);		
		expiredNormal.setMinutes(expiredNormal.getMinutes() + expiredNormal.getTimezoneOffset());  // for EST time zone
		var startCircuit = new Date(attr.CIRCUIT_EST_DTTM);
		startCircuit.setMinutes(startCircuit.getMinutes() + startCircuit.getTimezoneOffset());  // for EST time zone
		var startNormal = new Date(attr.EST_REP_DTTM);
		startNormal.setMinutes(startNormal.getMinutes() + startNormal.getTimezoneOffset());  // for EST time zone
		var expiredTestCircuit = new Date(attr.CIRCUIT_EST_ENDDTTM);
		var expiredTestNormal = new Date(attr.EST_REP_ENDDTTM);

		
        var title = attr.NUM_CUST + "";
		if (attr.NUM_CUST == 1) 
		{
			title += " Customer Affected";
		}
		else
		{
			title += " Customers Affected"
		}
			
		var content = "<b>Job ID: </b>" + attr.JOB_ID;
		
		if (mode == 'CIRCUIT') {
			if (attr.CIRCUIT_EST_DTTM != '' && attr.CIRCUIT_EST_ENDDTTM != ''
				&& eval(currentDate < expiredTestCircuit)) {
				content += "<br /><br /><b>Estimated Restoration: </b> " + startCircuit.toDateString() + ", " + removeSeconds(startCircuit.toLocaleTimeString())
				+" - " + expiredCircuit.toDateString() + ", " + removeSeconds(expiredCircuit.toLocaleTimeString())
			}
			else {
				content += "<br /><br><b>Estimated Restoration: </b> Not Available";
			}
		}
		else if (mode == 'NORMAL') {
			if (attr.CIRCUIT_EST_DTTM != '' && attr.CIRCUIT_EST_ENDDTTM != ''
				&& eval(currentDate < expiredTestCircuit)) {
				content += "<br /><br /><b>Estimated Restoration: </b> " + startCircuit.toDateString() + ", " + removeSeconds(startCircuit.toLocaleTimeString()) 
				content += " - " + expiredCircuit.toDateString() + ", " + removeSeconds(expiredCircuit.toLocaleTimeString())
			}
			// expired circuit exists
			else if (attr.CIRCUIT_EST_DTTM != '' && attr.CIRCUIT_EST_ENDDTTM != ''
				&& eval(currentDate >= expiredCircuit)) {
				content += "<br /><br><b>Estimated Restoration: </b> Not Available";
			}
			else if (attr.EST_REP_DTTM != '' && attr.EST_REP_ENDDTTM != ''
				&& eval(currentDate < expiredTestNormal)) {
				content += "<br /><br /><b>Estimated Restoration: </b> " + startNormal.toDateString() + ", " + removeSeconds(startNormal.toLocaleTimeString())
				content += " - " + expiredNormal.toDateString() + ", " + removeSeconds(expiredNormal.toLocaleTimeString() )
			}
			else {
				content += "<br /><br><b>Estimated Restoration: </b> Not Available";
			}
		}
		else {
			content += "<br /><br><b>Estimated Restoration: </b> Not Available";
		}

		mode = defaultMode;
		var offDate = new Date(attr.OFF_DTTM);
		offDate.setMinutes(offDate.getMinutes() + offDate.getTimezoneOffset());  // for EST time zone
		
		var updateDate = new Date(attr.ADD_DTTM);
		updateDate.setMinutes(updateDate.getMinutes() + updateDate.getTimezoneOffset());  // for EST time zone
		
		content += "<br /><br><b>Off Since: </b>" + offDate.toDateString() + ", " + removeSeconds(offDate.toLocaleTimeString()) 
				+ "<br /><br><b>Last Update: </b>" + updateDate.toDateString() + ", " + removeSeconds(updateDate.toLocaleTimeString()) 
				+ "<br /><br><b>Cause: </b>" + attr.CAUSE;
					
		map.graphics.add(feature);
		map.infoWindow.setTitle(title);
        map.infoWindow.setContent(content);
		

        (evt) ? map.infoWindow.show(evt.screenPoint,map.getInfoWindowAnchor(evt.screenPoint)) : null;
    }

	// takes the seconds off the time 
	// expects format to be xx:xx:xx XM
	function removeSeconds(timeToChange) {
		var amPM = timeToChange.substring(timeToChange.length - 2);
		var result = timeToChange.substring(0, timeToChange.length -6) + " " + amPM;
		return result;
	}
	
    function showFeatureSet(fset,evt) {
		esri.hide(dojo.byId('loadingImg'));
		
        //remove all graphics on the maps graphics layer
        map.graphics.clear();
        var screenPoint = evt.screenPoint;

        featureSet = fset;

        var numFeatures = featureSet.features.length;

        //QueryTask returns a featureSet.  Loop through features in the featureSet and add them to the infowindow.
        var title = "You have selected " + numFeatures + " outages.";
        var content = "Please select desired outage from the list below.<br /><br/>";

        for (var i=0; i<numFeatures; i++) {
            var graphic = featureSet.features[i];
		    var TotalCust = graphic.attributes.NUM_CUST
		    if (TotalCust == 1){
				content = content + TotalCust + " Customer Affected (<A href='#' onClick='showFeature(featureSet.features[" + i + "]);'>show</A>)<br/>";
			}
		    else {
				content = content + TotalCust + " Customers Affected (<A href='#' onClick='showFeature(featureSet.features[" + i + "]);'>show</A>)<br/>";
			}
        }
        map.infoWindow.setTitle(title);
        map.infoWindow.setContent(content);
        map.infoWindow.show(screenPoint,map.getInfoWindowAnchor(evt.screenPoint));
		
    }
		
dojo.addOnLoad(Init);
