//<![CDATA[
/*This script is used to plot proposed, approved, and completed burns on google maps. 
Author: Matthew Mavko, Air Sciences Inc.
for the MT/ID Airshed Group

Acknowledgements:
Many techniques were learned from Jon Conolly's REQ2:
http://www.pnsn.org/req2/
*/

Event.observe(window, 'load', function(){
	loadMap();
	
	if(isAdmin == "visible"){
		$("Appr_Active").observe('click',toggleApprove);
		$("appr_confirm").observe('click',confirmApprovals);
		$("approve_all").observe('click',approveAll);
	}
	$("download").observe('click',downloadBurns);
	
	resetControl();
	initFilters();
	getBurns();

	$("burn3").observe('click', shide);
	$("burn2").observe('click', shide);
	$("burn1").observe('click', shide);

	for (var i = 0; i < overlayNames.length; i++){
		$(overlayNames[i]).observe('click', getOverlay);
	}
	
	$("layer").observe('change', toggleFilters);

	
	$("burnDate").observe('change', changeDate);
	$("burnEDate").observe('change', changeDate);
	$("mapDate").observe('change', changeDetects);
	$("burnDate").observe('change:cal', changeDate);
	$("burnEDate").observe('change:cal', changeDate);
	$("mapDate").observe('change:cal', changeDetects);
//	$("bckDate").observe('click', changeDate);
//	$("fwdDate").observe('click', changeDate);
	
	$("fil_prty").observe('change', changeFilter);
	$("fil_air").observe('change', changeFilter);
	$("fil_elev").observe('change', changeFilter);
	$("fil_acres").observe('change', changeFilter);
	$("fil_btype").observe('change', changeFilter);
	$("fil_state").observe('change', changeFilter);
	
	
	//reset map view
	$('reset').observe('click', function(){
		map.setCenter(new GLatLng(initCenterLat,initCenterLon), parseInt(initCenterZoom));
		map.setMapType(G_PHYSICAL_MAP);
		map.closeInfoWindow();
		for (var i = 0; i < overlayNames.length; i++){
			$(overlayNames[i]).checked = false;
		}
		map.removeOverlay(detectXML);
		map.removeOverlay(tribeXML);

		map.removeOverlay(class1XML);
		map.removeControl(controlCls1);

		map.removeOverlay(idXML);
		map.removeOverlay(mtXML);
		map.removeOverlay(impactXML);
		map.removeOverlay(airshedXML);
		map.removeOverlay(ashd_cntrdXML);
		
	});
	
	//scriptacolous effects
//	$('helpWebi').observe('click', function(){
//		new Effect.BlindDown('webiHelpBox');
//	});
	
//	$('webiHelpClose').observe('click', function(){
//		new Effect.BlindUp('webiHelpBox');
//	});
//	resetControl();
});



// unload handlers
window.unload = function(){
	GUnload();
};

//Global varaibles
var map;
var side_bar_html = "";
var gmarkers = [];
var count = 0;
var zIndex = 1000;
var eventArray = [];
var tdList = ['a','b','c','d','e','f','g','h','i','j','k'];
var browser = navigator.appVersion;
var displayType = "table-row";

var txt = new RegExp('MSIE');

if ( browser.match(txt) == "MSIE") {
	displayType = "block";
}

var burnNum = 0; //number of events shown on map


function loadMap() {
	if (GBrowserIsCompatible()) {
		map = new GMap2($("map"));
		map.setCenter(new GLatLng(initCenterLat,initCenterLon), parseInt(initCenterZoom));
		map.addControl(new GOverviewMapControl()); 
		map.addControl(new GScaleControl());
		map.addControl(new GLargeMapControl());
	
		map.addMapType(G_PHYSICAL_MAP);

		var mapControl = new GHierarchicalMapTypeControl();
		mapControl.clearRelationships();

		mapControl.addRelationship(G_SATELLITE_MAP, G_HYBRID_MAP, "Labels", false);
		
		map.setMapType(G_PHYSICAL_MAP);

		map.addControl(mapControl);
		// map.enableScrollWheelZoom();
		var html='<div id="appr_control"><input id="Appr_Active" type="checkbox" /> Activate Approve <a href="javascript:popUp('+"'help.cfm#activateapprove'"+')" style="text-decoration:none;color=#FFFFFF" ><img src="images/help_icon.gif" alt="fd" width="12" height="11" title="Click to view help menu" style="border:none"/></a><br><div id="appr_confirm"><button>Confirm Selections</button></div><br><div id="approve_all"><button>Approve All</button></div></div>';	
		var Appr_control=new HtmlControl(html);
		if (isAdmin == "visible"){
			map.addControl(Appr_control, new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7,43)));
		}
		var html='<div id="class1key"><ul><li><img src="images/CLS1_fws.png" /> FWS</li><li><img src="images/CLS1_nps.png" /> NPS</li><li><img src="images/CLS1_usfs.png" /> USDA-FS</li><li><img src="images/CLS1_native.png" /> Native Am.</li></ul></div>';
		controlCls1 = new HtmlControl(html);


		GEvent.addListener(map,"singlerightclick", function(point,src,overlay) { 
			if (overlay) { 
		  		if (overlay instanceof GMarker) { 
					GEvent.trigger(overlay,"RightClick"); 
		  		} 
			} 
		}); 
	//$("burntitlerow").style.display = displayType;

	}else{
	alert("Javascript must be enabled in order for you to use the AMS Map Tool. To view, you must first enable JavaScript in your browser options and try again");
	}
}



function toggleApprove(){
	map.closeInfoWindow();
	if (this.checked){
		$('approveText').style.visibility = "visible";
		$('appr_confirm').style.display = "block";
		$('approve_all').style.display = "block";
		if(!$('burn2').checked){
			$('burn2').checked = true;
			killMarkers();
			getBurns();
		}
	}else{
		$('approveText').style.visibility = "hidden";
		$('appr_confirm').style.display = "none";
		$('approve_all').style.display = "none";
		killMarkers();
		getBurns();
	}
}

function approveAll(){
	var prop_cnt = 0;
	var appr_cnt = 0;
	for (var i=0; i< gmarkers.length; i++) {		
		var marker = gmarkers[i];
		if (marker.grp == "burn2"){
			appr_cnt++;
		}else if (marker.grp == "burn1"){
			prop_cnt++;
		}
	}
	if ($("Appr_Active").checked){
		for (var i=0; i< gmarkers.length; i++) {		
			var marker = gmarkers[i];
			if (prop_cnt == 0 && marker.grp == "burn2"){
				marker.setImage("images/burn_1.png");
				marker.grp = "burn1";
			}else if (marker.grp == "burn1"){
				marker.setImage("images/burn_2.png");
				marker.grp = "burn2";
			}
		}
	}
}

function confirmApprovals(){
	map.closeInfoWindow();
	$('loading').style.visibility = "visible";
	$('loadText').style.visibility = "visible";
	document.body.style.cursor="wait";
	var confirmParams = '?ApprovalIDs=';
	for (var i=0; i< gmarkers.length; i++) {		
		if (gmarkers[i].grp == "burn2"){
			confirmParams += eventArray[i].fid +',';
		}
	}
	confirmParams = confirmParams.substr(0,confirmParams.length-1);
	confirmParams +='&NotApproved=';
	for (var i=0; i< gmarkers.length; i++) {		
		if (gmarkers[i].grp == "burn1"){
			confirmParams += eventArray[i].fid +',';
		}
	}
	confirmParams = confirmParams.substr(0,confirmParams.length-1);
	//$("numberBurns").innerHTML = confirmParams;
	new Ajax.Request(
			'xml/setApprovals.cfm' + confirmParams,
		{
			method: "post",
			contentType: 'text/xml',
			onSuccess: parseApprove
		}
	);
}
function parseApprove(ajax){
	var xmlDoc = GXml.parse(ajax.responseText);
	$('loading').style.visibility = "hidden";
	$('loadText').style.visibility = "hidden";
	document.body.style.cursor="default";
}


function getOverlay(){
	map.closeInfoWindow();
	var id = this.id;
	if (this.checked){
		$('loading').style.visibility = "visible";
		$('loadText').style.visibility = "visible";
		document.body.style.cursor="wait";
		if (id == "detect"){
			map.addOverlay(detectXML);
		}
		if (id == "impact"){
			map.addOverlay(impactXML);
		}
		if (id == "airshed"){
			map.addOverlay(airshedXML);
			map.addOverlay(ashd_cntrdXML);
		}	
		if (id == "tribe"){
			map.addOverlay(tribeXML);
		}	
		if (id == "id_co"){
			map.addOverlay(idXML);
		}	
		if (id == "mt_co"){
			map.addOverlay(mtXML);
		}	
		if (id == "class1"){
			map.addOverlay(class1XML);
			map.addControl(controlCls1, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(145,3)));
		}	
			
		$('loading').style.visibility = "hidden";
		$("loadText").style.visibility = "hidden";
		document.body.style.cursor="default";

	}else{ 
		if (id == "detect"){
			map.removeOverlay(detectXML);
		}
		if (id == "impact"){
			map.removeOverlay(impactXML);
		}
		if (id == "airshed"){
			map.removeOverlay(airshedXML);
			map.removeOverlay(ashd_cntrdXML);
		}
		if (id == "tribe"){
			map.removeOverlay(tribeXML);
		}
		if (id == "class1"){
			map.removeOverlay(class1XML);
			map.removeControl(controlCls1);
		}
		if (id == "id_co"){
			map.removeOverlay(idXML);
		}	
		if (id == "mt_co"){
			map.removeOverlay(mtXML);
		}	
	}
}

//Ajax to retrieve xml file for burns
function getBurns(){
	$('loading').style.visibility = "visible";
	$('loadText').style.visibility = "visible";
	document.body.style.cursor = "wait";
	
	setFileParams();
	new Ajax.Request(
			eventXML + fileParams,
		{
			method: "post",
			contentType: 'text/xml',
			onSuccess: parseBurns
		}
	);
}


//parse burn xml
function parseBurns(ajax){

	//xmlDoc = ajax.responseText;
	var xmlDoc = GXml.parse(ajax.responseText);
	
	var eventTag = xmlDoc.documentElement.getElementsByTagName("event");
		for (var i = 0; i < eventTag.length; i++) {
			var param = eventTag[i].getElementsByTagName("param");
			var burnParam = new Hash();
			burnParam.set("fid", eventTag[i].getAttribute("fire_id"));
			burnParam.set("type", eventTag[i].getAttribute("type"));
			burnParam.set("member", eventTag[i].getAttribute("member"));
			burnParam.set("office", eventTag[i].getAttribute("office"));
			burnParam.set("unit", eventTag[i].getAttribute("unit"));
			for(var j = 0; j< param.length; j++){
            	var test = burnParam.get(param[j].getAttribute("name"));
                if (test == null){
					burnParam.set(param[j].getAttribute("name"), param[j].getAttribute("value"));
            	}
			}
			var burn = new Burn(burnParam);
			eventArray[count] = burn; 
			map.addOverlay(burn.plotBurn());
			if (!$(burn.marker.grp).checked) {
				burn.marker.hide();
			}else{
				burnNum++;
			}
			
			//count++;  
			burn.makeList();
		}
		//$("numberBurns").innerHTML= burnNum;
	$('loading').style.visibility = "hidden";
	$("loadText").style.visibility = "hidden";
	document.body.style.cursor="default";

}

function downloadBurns(){
	window.location = 'map_download_burns.cfm' + fileParams + '&layer=' + $("layer").value;
}

//add listener to sidebar list items
function myclick(count) {
		GEvent.trigger(gmarkers[count], "dblclick");
		}

//show or hide (shide) selected markers
function shide(){
	var grp = this.id;
	var checked = this.checked;
	//manageList(grp, checked);
	for (var i=0; i< gmarkers.length; i++) {		
		if (gmarkers[i].grp == grp){
			if(checked){
				gmarkers[i].show();
				$("tr"+i).style.display = displayType;
				burnNum++;
			}else{
				gmarkers[i].hide();
				$("tr"+i).style.display = 'none';
				burnNum--;
				map.closeInfoWindow();
			}	
		}
    }
	//$("numberBurns").innerHTML= burnNum;
}

function changeDate(){
	map.closeInfoWindow();
	setFilter($("layer").value,this.id);
	
	var direction = 1;
	var NewStartDate=new Date(SDate);
	
	if (this.id == "burnDate" || this.id == "burnEDate") {
		NewStartDate=new Date(this.value);
	}else{
		if (this.id == "bckDate") {
			direction = -1;
		}
		NewStartDate.setDate(NewStartDate.getDate()+direction);
	}
	
//The following ugly statement fixes IE6,7 incompatibility with CFML
	SDate = String("0" +(NewStartDate.getMonth() + 1)).slice(-2) + "/" + String("0" +NewStartDate.getDate()).slice(-2) + "/" + NewStartDate.getFullYear();
	vSDate = NewStartDate.getFullYear() + "-" + String("0" +(NewStartDate.getMonth() + 1)).slice(-2) + "-" + String("0" +NewStartDate.getDate()).slice(-2);
//	mapDate = NewStartDate.getFullYear() + "" + String("0" +(NewStartDate.getMonth() + 1)).slice(-2) + "" + String("0" +NewStartDate.getDate()).slice(-2);
	if (this.id != "burnDate" && this.id != "burnEDate"){
		$("burnDate").value = SDate;
	}
	
	killMarkers();
	getBurns();
	//resetControl();
}
function changeDetects(){
	//$("banner").innerHTML += detectXMLpath + "fireDetectsFETS" + mapDate + ".kml";
	var NewStartDate=new Date(this.value);
	mapDate = NewStartDate.getFullYear() + "" + String("0" +(NewStartDate.getMonth() + 1)).slice(-2) + "" + String("0" +NewStartDate.getDate()).slice(-2);
	if ($("detect").checked){
		//$("key").innerHTML += geoXMLpath + "fireDetectsFETS" + mapDate + ".kml";
		map.removeOverlay(detectXML);
	}
	detectXML = new GGeoXml(detectXMLpath + "fireDetectsFETS" + mapDate + ".kml");
	if ($("detect").checked){
		map.addOverlay(detectXML);
	}
}

function changeFilter(){
	map.closeInfoWindow();
	setFilter($("layer").value,this.id);
	
//	if (this.id != "fil_elev" && this.id != "fil_acres"){
//		var idx = this.selectedIndex;
//		var val = this.options[idx].value;
//		
//		if (this.id == "fil_prty"){
//			priority = val;
//		}else if (this.id == "fil_air"){
//			airshed = val;
//		}
//	}
	killMarkers();
	getBurns();
	//resetControl();
}

//kill all markers and re-plot burnAll when when plot by time/depth is clicked
function killMarkers(){
	for(var i = 0; i< gmarkers.length; i++){
		gmarkers[i].remove();
		for (var j = 0; j < tdList.length; j++){
			$("td"+i+tdList[j]).innerHTML = "";
		}
		$("tr"+i).style.display = 'none';
	}
	GEvent.clearListeners(map,"infowindowclose");
	gmarkers = [];
	eventArray = [];
	burnNum = 0;
	count = 0;
}
//resets buttons on plot change and refresh
function resetControl(){
	if(isAdmin == "visible"){
		$("burn1").checked = true; 
		$("burn2").checked = false; 
		$("burn3").checked = false; 
	}else{
		$("burn1").checked = false; 
		$("burn2").checked = true; 
		$("burn3").checked = false; 
	}
	$("airshed").checked = false;
	$("impact").checked = false;
	$("detect").checked = false;
}

function initFilters(){
	var initDate = new Date();
	if(isAdmin == "visible"){
		initDate.setDate(initDate.getDate() + 1);
	}
	var date = String("0" +(initDate.getMonth() + 1)).slice(-2) + "/" + String("0" +initDate.getDate()).slice(-2) + "/" + initDate.getFullYear();
	//var vDate = initDate.getFullYear() + "-" + String("0" +(initDate.getMonth() + 1)).slice(-2) + "-" + String("0" +initDate.getDate()).slice(-2);
	$("burnDate").value = date;
	$("burnEDate").value = date;
	$("fil_elev").value = 0;
	$("fil_acres").value = 100000;
	$("fil_prty").selectedIndex = 0;
	$("fil_air").selectedIndex = 0;
	$("fil_btype").selectedIndex = 0;
	$("fil_state").selectedIndex = 0;
	var layers = $("layer").options;
	for (var i=0;i < layers.length; i++){
		filter_settings[layers[i].value] = new Array();
		filter_settings[layers[i].value]['burnDate'] = date;
		filter_settings[layers[i].value]['burnEDate'] = date;
		filter_settings[layers[i].value]['fil_elev'] = 0;
		filter_settings[layers[i].value]['fil_acres'] = 100000;
		filter_settings[layers[i].value]['fil_btype'] = "all";
		filter_settings[layers[i].value]['fil_state'] = "all";
		filter_settings[layers[i].value]['fil_prty'] = "all";
		filter_settings[layers[i].value]['fil_air'] = "all";
	}
}
function setFilter(layer,filter){
	var val = $(filter).value
	if (filter == 'burnDate' || filter == 'burnEDate'){
		var NewStartDate=new Date($(filter).value);
		val = String("0" +(NewStartDate.getMonth() + 1)).slice(-2) + "/" + String("0" +NewStartDate.getDate()).slice(-2) + "/" + NewStartDate.getFullYear();
	}
	filter_settings[layer][filter] = val;
}
	
function toggleFilters(){
	
	$("burnDate").value = filter_settings[this.value]['burnDate'];
	$("burnEDate").value = filter_settings[this.value]['burnEDate'];
	$("fil_elev").value = filter_settings[this.value]['fil_elev'];
	$("fil_acres").value = filter_settings[this.value]['fil_acres'];
	$("fil_prty").value = filter_settings[this.value]['fil_prty'];
	$("fil_air").value = filter_settings[this.value]['fil_air'];
	$("fil_btype").value = filter_settings[this.value]['fil_btype'];
	$("fil_state").value = filter_settings[this.value]['fil_state'];

}
	
	
////////////////////////////////begin Earthquake class//////////////////////////////////

Burn = Class.create({
	initialize: function(burn){
		this.fid = burn.get('fid');
		this.type = burn.get('type');
		this.mem = burn.get('member');
		this.off = burn.get('office');
		this.uni = burn.get('unit');
		this.loc = burn.get('location');
		this.cat = burn.get('category');
		this.shd = burn.get('airshed');
		this.btyp = burn.get('burntype');
		this.zone = burn.get('zone');
		this.yr = burn.get('year');
		this.mon = burn.get('month');
		this.day = burn.get('day');
		this.lat = burn.get('latitude');
		this.lon = burn.get('longitude');
		this.pacres = burn.get('proj_acres');
		this.acres = burn.get('acres');
		this.tons = burn.get('tonsacre');
		this.elev = burn.get('elevation');
		this.pri = burn.get('priority');
		this.listId;
		this.marker;
		this.point = new GLatLng(this.lat, this.lon);
	},
	//create a date string
	getDate: function(){
		return 	(this.yr + "/" + this.mon + "/" + this.day
				+ " " + "00:00:00");
	},
	
	plotBurn: function(){
		side_bar_html = "";
		var siz = 15;
		var grp = "burn" + this.type; //sets up marker groups
		var burnIcon = new GIcon();
		burnIcon.image = "images/burn_" + this.type + ".png";
		burnIcon.iconSize = new GSize(siz, siz);
		burnIcon.iconAnchor = new GPoint(siz/2, siz/2);
		burnIcon.infoWindowAnchor = new GPoint(siz/2, siz/2);	
		var markerOptions = {icon:burnIcon};
		this.marker = (new GMarker(this.point, markerOptions));
		this.listId = "tr" + count; //give each a unique id so an open window will highlight the list-item
		this.updateWindow();
		this.marker.grp = grp; //add group id to each marker
		var listId = this.listId;
		var marker = this.marker;
		GEvent.addListener(map,"infowindowclose", function() { //restores list-item to un-highlighted
			if (marker.grp == 'burn3'){
				$(listId).style.backgroundColor="#DDDDDD";
			}else if (marker.grp == 'burn2'){
				$(listId).style.backgroundColor="#00FF00";
			}else{
				$(listId).style.backgroundColor="#FFFFFF";
			}
		});

		//the following is to set up the sidebar list
		gmarkers[count] = this.marker;

		side_bar_html = "javascript:myclick(" + count + ")";

		return this.marker;
	},
	
	
	
	//create the side bar
	makeList: function(){
		var grp = "burn" + this.type;//sets up marker classes based on mag
		var listId = "tr"+count;
		var a = document.createElement("a");
		Element.extend(a); //IE
		a.href = side_bar_html;
		a.id = "atr" + count;
		if(this.pri == "A"){
			Element.addClassName(a, "pa");
		}else{
			Element.addClassName(a, "pb");
		}
		a.innerHTML= this.mem + " " + this.off;
		$("td"+count+"a").appendChild(a);
		$("td"+count+"a").style.textAlign = 'left';
		var elList = [this.uni,this.loc,this.shd,this.zone,this.elev,this.btyp,this.tons,this.pacres,this.acres,this.pri ]; 

		if (this.zone != 'None'){
			$("td"+count+"e").style.color = "#FF0000";
			$("td"+count+"e").style.fontWeight = "bold";
			//alert(this.zone);
		}else{
			$("td"+count+"e").style.color = "#000000";
			$("td"+count+"e").style.fontWeight = "normal";	
		}
		for (var i=1; i <= elList.length; i++){
			$("td"+count+tdList[i]).innerHTML = elList[i-1];
			if (i < 3){
				$("td"+count+tdList[i]).style.textAlign = 'left';
			}
		}
		
		if ($(grp).checked) {
			$(listId).style.display = displayType;
		}
		
		if (grp == 'burn3'){
			$(listId).style.backgroundColor="#DDDDDD";
		}else if (grp == 'burn2'){
			$(listId).style.backgroundColor="#00FF00";
		}else{
			$(listId).style.backgroundColor="#FFFFFF";
		}
		count ++;
	},
	
	//plots most recent on top
	order: function(){
		return zIndex --;
	},
	
	//creates and updates window. This function also creates a list
	//of  the event's webicorders sorted by distance from event
	updateWindow: function(){
		var marker = this.marker;
		GEvent.addListener(marker, "click", function() { //Toggle Approved/Proposed
			 if ($("Appr_Active").checked){
				 if (marker.grp == "burn2"){
					marker.setImage("images/burn_1.png");
					marker.grp = "burn1";
				 }else if (marker.grp == "burn1"){
					marker.setImage("images/burn_2.png");
					marker.grp = "burn2";
				 }
			 }
		});

		var windowHtml = this.getHtml();
		var listId = this.listId;
		var point = this.point;
		var time = this.yr + this.mon + this.day + this.hr;
		//add listeners and html to windows
		GEvent.addListener(marker, "RightClick", function() {
		    marker.openInfoWindowHtml(windowHtml);
			$("a"+listId).focus();
			$(listId).style.backgroundColor = "yellow";
		});
		GEvent.addListener(marker, "dblclick", function() {
		    marker.openInfoWindowHtml(windowHtml);
	
			$(listId).style.backgroundColor = "yellow";
		});
	},
	
	//html for info window
	getHtml: function(){
		var name = ["Date:","Unit Name:","Airshed/Impact Zone:","Elevation (ft):","Burn Type:","Loading (t/ac):","Project Acres:","Acres this Date:","Priority:" ];
		var param = [this.mon+"/"+this.day+"/"+this.yr,this.uni,this.shd+"/"+this.zone,this.elev,this.btyp,this.tons,this.pacres,this.acres,this.pri ];
		var html = "<div class = 'burnWin'> \n";
		html += "<strong>" + this.mem + ", " + this.off + "</strong>";	
		html += "<ul> \n";
			for (var i = 0; i < name.length; i++){
				html += "<li>" + name[i]  + "<span>" + param[i] + "</span> </li> \n";
			}
		html += "</ul>";
		return html; 
	}
});