/** constructor 
   
       @param duration integer seconds
       @param <optional> function to run while waiting.
       
    */
   function Pause(duration, busy){
      this.duration= duration * 1000;
      this.busywork = null; // function to call while waiting.
      this.runner = 0;

      if (arguments.length == 2) {
         this.busywork = busy;
      }

      this.pause(this.duration);

   } // Pause class

   Pause.prototype.pause = function(duration){
      if ( (duration == null) || (duration < 0)) {return;}
      var later = (new Date()).getTime() + duration;
      while(true){
         if ((new Date()).getTime() > later) {
            break;
         }
         this.runner++;
         if (this.busywork != null) {
            this.busywork(this.runner);
         }
      } // while
   } // pause method

var param_useSidebar = true;
var crunchedLayerManager = null;
var control;
function setValue() {
	window.overlay_count = 0;
	window.map_div = $('cm_map');
	window.map = new VEMap('cm_map');
	window.map_layer = null;
	window.overlayIndex = 1;
	window.overlayHash = [];
}
var layers = {
 "apartments":
 {"url": "http://maps.google.com/maps/ms?ie=UTF8&hl=en&msa=0&output=kml&msid=111732542869653245611.00045668cfb06589cf808",
  "name": "Campus Apartments"},
 "residence_halls":
 {"url": "http://maps.google.com/maps/ms?ie=UTF8&hl=en&msa=0&output=kml&msid=111732542869653245611.0004562ababad6f008b30",
  "name": "Residence Halls"},
 "dining_locations": 
 {"url": "http://maps.google.com/maps/ms?ie=UTF8&hl=en&msa=0&output=kml&msid=111732542869653245611.00045629cded35b7f94ac",
  "name": "Campus Dining Locations"},
 "markets": 
 {"url": "http://maps.google.com/maps/ms?ie=UTF8&hl=en&msa=0&output=kml&msid=111732542869653245611.0004562a11b7ac31665bd",
  "name": "Campus Markets"},
 "espresso": 
 {"url" : "http://maps.google.com/maps/ms?ie=UTF8&hl=en&msa=0&output=kml&msid=111732542869653245611.00045629f641d73bb2f1a",
   "name": "Campus Espresso Bars"},
 "admin_offices":
 {"url": "http://maps.google.com/maps/ms?ie=UTF8&hl=en&msa=0&output=kml&msid=111732542869653245611.0004562b56cdb97fb5c8e",
  "name": "Housing and Dining Administrative Offices"}
};
var startup_location = "residence_halls";
function loadMap() {
	var options = new VEMapOptions();
	options.EnableBirdseye = false;
	options.EnableDashboardLabels = false;
	var bounds = new VELatLong(46.731802,-117.160349)
	map.SetDashboardSize(VEDashboardSize.Small);
	map.LoadMap(bounds, 15 ,'h' ,false, null, null, null, options);
map.AddShapeLayer(new VEShapeLayer());
	map.SetMapMode(VEMapMode.Mode2D);
	map.SetMapStyle('h');
	if(param_useSidebar) {
		$('blankNav').innerHTML = "";
		var l=1;
		for(var layer in layers) {
			addTR(layer,l);
			l++;
		}
	}
	AddMyControl();

}

function addTR(layer,layer_index) {
var nav = $('blankNav')
nav.setStyle('cursor','pointer');
	var locationUL = document.createElement("ul");
	var locationLI=document.createElement("li");
	locationLI.id = "subLayer"+layer;
	var markerN = document.createElement("a");
	markerN.onclick = function() { showHideLayer(layer) };
	markerN.id = "navLink"+layer;
//	markerN.href ="#";
	var name = document.createTextNode(layers[layer].name); 
	markerN.appendChild(name);       
	locationLI.appendChild(markerN);
	locationUL.appendChild(locationLI);
	nav.appendChild(locationLI);
}
function showHideLayer(layer) {
	if(!layers[layer].loaded) {
		map.GetShapeLayerByIndex(1).DeleteAllShapes();
$('loading').childNodes[0].innerHTML = "loading "+layers[layer].name+"...";
//showPopWin('/hdrl/javascript/submodal/loading.html', 'Please Wait', 100, 100, null,true,true,false,"");
showPopWin('/hdrl/javascript/submodal/loading.html', 400, 100, null);
		map_layer = "layer" + layer;
		map_layer = new VEShapeLayer();
		map_layer.SetTitle=layers[layer].name;
		var url = layers[layer].url;
		var sourceSpec = new VEShapeSourceSpecification(VEDataType.ImportXML,url,map_layer);
		curLayer = layer;
		map.ImportShapeLayerData(sourceSpec,setTimeout("buildSideBar(map_layer,curLayer)",1000),true);
		layers[layer].loaded = true;
		overlayHash.push(layer); 

	} else {
		map.GetShapeLayerByIndex(1).DeleteAllShapes();
		map_layer = map.GetShapeLayerByIndex(removeLayer(layer));
		map.DeleteShapeLayer(map_layer);
		clearSideBar(layer);
		layers[layer].loaded = false;
		layers[layer].submenu = false;
	}

}
function buildSideBar(map_layer,layer) {
	var tmpArray = [];
	for(var i=0;i<map_layer.GetShapeCount();++i) {
		var currentShape=map_layer.GetShapeByIndex(i);
		currentShape.SetTitle(regexReplace(currentShape.GetTitle()));
		currentShape.SetDescription(regexReplace(currentShape.GetDescription()));
		tmpArray[i] = currentShape.GetTitle()+"|"+currentShape.GetID();
	}
	tmpArray.sort();
	if(tmpArray.length>0)layers[layer].submenu = true;
	if(layers[layer].submenu) {
		var ul = document.createElement("ul");
		ul.id = "sbUL"+layer;
		for(var i=0;i<tmpArray.length;++i) {
			var _shape = tmpArray[i].split('|');
			var li = document.createElement("li");
			var markerA = document.createElement("a");
			//markerA.setAttribute("onmouseover","mouseOverSidebarItem('"+_shape[1]+"');")
			//markerA.setAttribute("onmouseout","mouseOutSidebarItem('"+_shape[1]+"');")
			markerA.href = "javascript:mouseOverSidebarItem('"+_shape[1]+"');";
			//this regex replacement fixes an error in IE when interpreting the é character
			var _title = regexReplace(_shape[0]);
			markerA.appendChild(document.createTextNode(_title));
			li.appendChild(markerA);
			ul.appendChild(li);
		}
		$('subLayer'+layer).appendChild(ul);
		$('navLink'+layer).setProperty('class', 'navcurrentpage');
		setTimeout("hidePopWin(false)",1000)
	} else {
		buildSideBar(map_layer,layer)
	}
}
function clearSideBar(layer) {
	$('subLayer'+layer).removeChild($("sbUL"+layer));
	$('navLink'+layer).setProperty('class', '');
}
function WSU(action) {
	var btnShow = $('showWSU');
	var btnHide = $('hideWSU');
	switch(action){
	case "show":
	//	map.ShowMessage("The campus map does not perfectly fit with the Virtual Earth aerial map. The points have been optimized to display on the aerial map.");
		var tileSourceSpec = new VETileSourceSpecification("wsu", "http://www.livingat.wsu.edu/hdrl/campus_map/map_images/Layer_NewLayer/%4.png");
		tileSourceSpec.NumServers = 1;
		tileSourceSpec.MinZoomLevel = 15;
		tileSourceSpec.MaxZoomLevel = 17;
		tileSourceSpec.Opacity = 0.9;
		tileSourceSpec.ZIndex = 100;
		map.AddTileLayer(tileSourceSpec, true);
		btnHide.setStyle('background','#D7EDF4');
		btnShow.setStyle('display','none');
		btnHide.setStyle('display','block');
		checkCustomZoom('wsu');
		break;
	case "hide":
		map.DeleteTileLayer('wsu');
		btnHide.setStyle('display','none');
		btnShow.setStyle('display','block');
		break;
	}
}
function controlOver(id,color) {
	$(id).setStyle('background','#'+color);
}
function checkCustomZoom(tileLayerID) {
	if(map.GetTileLayerByID(tileLayerID)) {
		if(map.GetZoomLevel()<15) map.SetCenterAndZoom(new VELatLong(46.731802,-117.160349),15) //centers over martin stadium
	}
}
//this function iterates through the overlayHash array and removes the indicated layer and shifts all remaining layers left
function removeLayer(layer) {
	var _index;
	for(var i=0;i<overlayHash.length; i++) {
		if(overlayHash[i] == layer) {
			_index=i+2;
			if(i==0) overlayHash.shift();
			else overlayHash.splice(i,1);
			break;
		} else { _index = "fail"; }
	}
	return _index;
}
function AddMyControl() {
	if (control==null) {
		control = $('wsuMap');
		if(!(/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent))) { //this checks for IE
			control.style.top ="14px"; 
			control.style.left = "246px"; 
		} else {
			control.style.top ="16px"; 
			control.style.left = "248px"; 
		}
		
		map.AddControl(control);
		addShim(control);
		control.setStyle('display','block');
	}
 }
function addShim(el) {
	var shim = document.createElement("iframe");
	shim.id = "myShim";
	shim.frameBorder = "0";
	shim.style.position = "absolute";
	shim.style.zIndex = "1";
	shim.style.top  = el.offsetTop;
	shim.style.left = el.offsetLeft;
	shim.width  = el.offsetWidth;
	shim.height = el.offsetHeight;
	el.shimElement = shim;
	el.parentNode.insertBefore(shim, el);
}
function mouseOverSidebarItem(markerID){
	map.GetShapeLayerByIndex(1).DeleteAllShapes();	
	currentShape = map.GetShapeByID(markerID);
	currentIcon = currentShape.GetCustomIcon();
	//currentShape.SetCustomIcon("map_images/resHall_selected.png");
	var pts = currentShape.GetPoints();
	var _lat = pts[0].Latitude;
	var x = new VEShape(VEShapeType.Pushpin, new VELatLong(pts[0].Latitude+.00023,pts[0].Longitude));
	//x.SetTitle("pin02");
	x.SetCustomIcon("selected.png");
	map.GetShapeLayerByIndex(1).AddShape(x);
	map.SetCenterAndZoom(new VELatLong(pts[0].Latitude,pts[0].Longitude),17);
	//setTimeout("map.ShowInfoBox(currentShape);",1000);
}
		
function mouseOutSidebarItem(markerID){
	//currentShape = map.GetShapeByID(markerID);
	//currentShape.SetCustomIcon("map_images/resHall_selected.png");
	map.HideInfoBox(currentShape);
}

function regexReplace(inputStr) {
	inputStr=inputStr.replace(new RegExp("Â","g"),"");
	inputStr = inputStr.replace(new RegExp("Cafe","g"),"Café");
	inputStr = inputStr.replace(new RegExp("CafÃ©","g"),"Café");
	return inputStr;
}