dojo.require("dijit.layout.BorderContainer");
dojo.require("dijit.layout.ContentPane");
dojo.require("esri.map");
dojo.require("dojo.data.ItemFileReadStore");

var map, mapLevel, regionStore, regionGraphicLayer, zipLookUp, iTip;
var streetMap, imagery, boundary;
var outline = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([255, 255, 255, 1]), 1);
var roSym = new esri.symbol.SimpleMarkerSymbol(esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE, 14, outline, new dojo.Color([255, 102, 0, 1]));
var soSym = new esri.symbol.SimpleMarkerSymbol(esri.symbol.SimpleMarkerSymbol.STYLE_CIRCLE, 8, outline, new dojo.Color([255, 102, 0, 1]));
var regionLookUp = {
	'philadelphia': 'Philadelphia', 'denver': 'Denver', 'sanantonio': 'San Antonio', 
	'boston': 'Boston', 'stlouis': 'St. Louis', 'olympia': 'Olympia', 'redlands': 'California',
	'california': 'California',	'charlotte': 'Charlotte', 'minneapolis': 'Minneapolis', 
	'washingtondc': 'Washington D.C.', 'headquarters': 'Esri Headquarters'
};
function init() {
	// find out which RO we want by looking at the URL
	var urlPieces = window.location.href.split('/');
	var roOfInterest = urlPieces[urlPieces.length-1].split('.')[0];
	var roCity = regionLookUp[roOfInterest];
	
	regionStore = new dojo.data.ItemFileReadStore({
		url: "/about-esri/regions/regions_with_satellites_web_merc.json",
		//url: "regions_with_satellites_web_merc.json",
		typeMap: { 'Polygon': esri.geometry.Polygon, 'Point': esri.geometry.Point, 'Extent': esri.geometry.Extent }
	});

	var startExtent = new esri.geometry.Extent({"xmin":-15380353.083429763,"ymin":1340374.1949893543,"xmax":-6574807.424977609,"ymax":9526534.916407976,"spatialReference":{"wkid":102113}});
	map = new esri.Map("regionsMap", {extent: startExtent, nav: false, slider: false, displayGraphicsOnPan: true});
	dojo.connect(map, "onLoad", function(theMap) {
		// graphics layer for the region graphic
		regionGraphicLayer = new esri.layers.GraphicsLayer({'id': 'region'});
		map.addLayer(regionGraphicLayer);

		// get the RO geometry
		if (roCity) {
    		regionStore.fetchItemByIdentity({identity: roCity, onItem: displayRegion, onError: oops});
    	} else { 
    		consle.log('unknown RO city ... make sure the html file name is one of the following: sanantonio'); 
    	}
		
		// show or hide the region graphic based on the zoom level
		// IE grinds to a half if you're zoomed in a lot and try to pan with a large graphic on the map
		mapLevel = theMap.getLevel();
		dojo.connect(theMap, "onExtentChange", function() {
			if (map.getLevel() > mapLevel+3) {
				regionGraphicLayer.hide();
			} else if (map.getLevel() <= mapLevel+3) {
				regionGraphicLayer.show();
			}
		});
		
		iTip = new infoTip("iTip", "infoTip roundcorner", map.position, false);
		dojo.connect(map.graphics, "onMouseOver", g_onMouseOverHandler);
		dojo.connect(map.graphics, "onMouseOut", g_onMouseOutHandler);
	});
	
	streetMap = new esri.layers.ArcGISTiledMapServiceLayer("http://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer");
	map.addLayer(streetMap);

	imagery = new esri.layers.ArcGISTiledMapServiceLayer("http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer", {visible: false});
	map.addLayer(imagery);

	boundary = new esri.layers.ArcGISTiledMapServiceLayer("http://server.arcgisonline.com/ArcGIS/rest/services/Reference/World_Boundaries_and_Places/MapServer", {visible: false});
	map.addLayer(boundary);

	dojo.connect(dojo.byId('zIn'), 'onclick', function() { map.setLevel(map.getLevel()+1); });
	dojo.connect(dojo.byId('zOut'), 'onclick', function() { map.setLevel(map.getLevel()-1); });
	
	dojo.connect(dojo.byId('basemapToggleImagery'), 'onclick', function(){
		if(dojo.byId('basemapToggleImagery').className.indexOf('imageryOff') != -1){
			streetMap.hide();
			imagery.show();
			boundary.show();
			dojo.byId('basemapToggleImagery').className = "imageryOn";
			dojo.byId('basemapToggleStreets').className = "streetsOff";
		}
	});
	
	dojo.connect(dojo.byId('basemapToggleStreets'), 'onclick', function(){
		if(dojo.byId('basemapToggleStreets').className.indexOf('streetsOff') != -1){
			streetMap.show();
			imagery.hide();
			boundary.hide();
			dojo.byId('basemapToggleStreets').className = "streetsOn";
			dojo.byId('basemapToggleImagery').className = "imageryOff";
		} 
	});	
}

function displayRegion(aoi) {
    //console.log(aoi);
	var outline = new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([16, 103, 152]), 2);
	var symbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, outline, new dojo.Color([229, 239, 247, 0.2]));
	var infoTemplate = new esri.InfoTemplate({"title": "${name}", "content": "Phone: ${phone}"});
	
	var regionGraphic = new esri.Graphic(aoi.geometry[0], symbol);
	var rgLayer = map.getLayer('region');
	rgLayer.add(regionGraphic);
	
	var roAttrs = { "name": aoi.name[0], "address": aoi.address[0], "phone": aoi.phone[0], "fax": aoi.fax[0] }
	// uncomment the line below for a graphic with an info window
	//var roPointGraphic = new esri.Graphic(aoi.location[0], roSym, roAttrs, infoTemplate);
	var roPointGraphic = new esri.Graphic(aoi.location[0], roSym, roAttrs);
	map.graphics.add(roPointGraphic);
	//map.setExtent(esri.graphicsExtent(map.getLayer('region').graphics), true);

	if (aoi.focusExtent) {
		map.setExtent(aoi.focusExtent[0]);
	} else if (aoi.focusPoint) { // no focus point for DC, just use the extent of the region poly since it's so small
		map.setExtent(esri.graphicsExtent(map.getLayer('region').graphics), true);
		map.centerAt(aoi.focusPoint[0]);
	}
	
	if (aoi.satellites.length > 0) {
    	dojo.forEach(aoi.satellites, function(sat) {
    	   var satAttrs = { "name": sat.name[0], "address": sat.address[0], "phone": sat.phone[0], "fax": sat.fax[0] }
    	   // uncomment the line below for a graphic with an info window
		   //var roGraphic = new esri.Graphic(sat.location[0], soSym, satAttrs, infoTemplate);
		   var roGraphic = new esri.Graphic(sat.location[0], soSym, satAttrs);
    	   map.graphics.add(roGraphic);
    	});	    
	} else {
		//console.log('no satellites');
	}
}

function g_onMouseOutHandler(evt) {
	iTip.hide();
}

function g_onMouseOverHandler(evt) {
	//var img = '<img src="images/i_flag.png"/ style="height:20px;width20px;border:0;">';
	iTip.setContent(evt.graphic.attributes.name);
	//iTip.setContent(img + "&nbsp;" + evt.graphic.attributes.name + "<br/><a href='" + evt.graphic.attributes.url + "'>" + evt.graphic.attributes.url + "</a>");
	//console.log(evt.screenPoint);
	iTip.show(evt.screenPoint);
}

function oops(error){
	console.log('boooooo...', error);
}

dojo.addOnLoad(init);

// code for info tips:
function infoTip(e,b,d,c){this.LOCATION={left:"left",right:"right",top:"top",bottom:"bottom"};this._isShowing=false;this._coords=null;this._height=0;this._width=0;this._location="top";this._padding=15;this._xOffset=d.x;this._yOffset=d.y;this._id=e;this._animationRef=null;this._animation=c;var a=dojo.doc.createElement("div");dojo.attr(a,{id:e,"class":b,style:"display:none"});dojo.doc.body.appendChild(a);this.getId=function(){return this._id};this.setPadding=function(f){this._padding=f};this.setLocation=function(f){this._location=f};this.setSize=function(f,g){dojo.style(this._id,{height:g+"px",width:f+"px"})};this.setContent=function(f){dojo.byId(this._id).innerHTML=f;dojo.style(this._id,"display","")};this.setClass=function(f){dojo.byId(this._id).className=f};this.show=function(g){this._coords=dojo.coords(this._id);this._height=this._coords.h;this._width=this._coords.w;var h,f;switch(this._location){case"left":h=g.y+this._yOffset-(this._height/2)+"px";f=g.x+this._xOffset-this._width-this._padding+"px";break;case"right":h=g.y+this._yOffset-(this._height/2)+"px";f=g.x+this._xOffset+this._padding+"px";break;case"bottom":h=g.y+this._yOffset+this._padding+"px";f=g.x+this._xOffset-(this._width/2)+"px";break;case"top":h=g.y+this._yOffset-this._height-this._padding+"px";f=g.x+this._xOffset-(this._width/2)+"px";break}dojo.style(this._id,{left:f,top:h,display:""});if(this._animation){if(this._animationRef!=null){this._animationRef.stop()}this._animationRef=dojo.fadeIn({node:this._id,duration:1000}).play()}this._isShowing=true};this.hide=function(){if(!this._isShowing){return}if(this._animation){this._animationRef=dojo.fadeOut({node:this._id,duration:800,onEnd:function(){this.node.style.display="none"}}).play()}else{dojo.style(this._id,"display","none")}this._isShowing=false};this.isShowing=function(){return this._isShowing}};
