//<![CDATA[
/*This script is used to plot earthquakes on google maps. 
Author: Jon Connolly
*/

//firstChild.nodeValue is used in place of textContent so that IE will display properly

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

//Global varaibles
var map;
var side_bar_html = "";
var gmarkers = [];
var count = 0;


function loadMap() {
	if (GBrowserIsCompatible()) {
		map = new GMap2($("map"));
		map.setCenter(new GLatLng(45.07, -120.95), 11);
		map.setMapType(G_PHYSICAL_MAP);
		map.addMapType(G_HYBRID_MAP); //puts Satellite and Map in tool bar
		map.addMapType(G_PHYSICAL_MAP);//this allows the terrain map to appear in the toolbar
		map.addControl(new GOverviewMapControl()); //adds map overview map in bottom left corner.
		map.addControl(new GSmallMapControl()); //adds lefthand slider bar thingy
		map.addControl(new GHierarchicalMapTypeControl());//right-top nav bar
		map.addControl(new GScaleControl());//adds scale
		}
}

//Ajax for station xml file
function getSites(){
	new Ajax.Request(
			"xml/station.xml",
		{
			method: "post",
			contentType: 'text/xml',
			onSuccess: parseSites
		}
	);
}

//parse the station xml
function parseSites(ajax){
	if(window.ActiveXObject){ // If IE
	var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
	xmlDoc.loadXML(ajax.responseText);
	} else {
	var xmlDoc = ajax.responseXML;
	}
	
	var staTag = xmlDoc.getElementsByTagName("station");
	var stas =[];
	for (var i = 0; i < staTag.length ; i++) { 
		var param = staTag[i].getElementsByTagName("param");
		stas[0] = param[0].firstChild.nodeValue;
		stas[1] = param[1].firstChild.nodeValue;
		stas[2] = param[2].firstChild.nodeValue;
		var point = new GLatLng(stas[1], stas[2]);
		map.addOverlay(plotStations(point, stas[0]));
	
	}
}

//plot the stations xml file
function plotStations(point, text){
	var staIcon = new GIcon();
	staIcon.image = "images/sta.png";
	staIcon.iconSize = new GSize(100, 100);
	staIcon.iconAnchor = new GPoint(50, 50);
	staIcon.infoWindowAnchor = new GPoint(50, 50);
	markerOptions = { icon:staIcon };
	var marker = (new GMarker(point, markerOptions));
	GEvent.addListener(marker, "click", function() {
	    marker.openInfoWindowHtml(text);
	  });
	
	 return marker;
}


//Ajax to retrieve xml file for eqs
function getEqs(){
	$('loading').style.visibility = "visible";
	$('loadText').style.visibility = "visible";
	document.body.style.cursor="wait";
	if(this.id){
		var file = "xml/" + this.id + ".xml";	
	}else{
		var file = "xml/mergeAcard.xml";
	}
	new Ajax.Request(
			file,
		{
			method: "get",
			contentType: 'text/xml',
			onSuccess: parseEqs
		}
	);
}


//parse quake xml
function parseEqs(ajax){
	$('loading').style.visibility = "hidden";
	$("loadText").style.visibility = "hidden";
	document.body.style.cursor="default";
	
	if(window.ActiveXObject){ // If IE
	var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
	xmlDoc.loadXML(ajax.responseText);
	} else {
	var xmlDoc = ajax.responseXML;
	}
	
	var eventTag = xmlDoc.getElementsByTagName("event");
		for (var i = 0; i < eventTag.length; i++) { 
			var param = eventTag[i].getElementsByTagName("param");
			var eq = new Hash();
			for(var j = 0; j< param.length; j++){
				eq.set(param[j].getAttribute("name"), param[j].getAttribute("value"));
			}
			var time = eq.get('year') + "/" + eq.get('month') + "/" + eq.get('day')
				+ " " + eq.get('hour') + ":" + eq.get('minute') + ":" + eq.get('second').substr(0,2);
			var depth = eq.get('depth');
			var point = new GLatLng(eq.get('latitude'), eq.get('longitude'));
			map.addOverlay(plotEqs(point, eq.get('magnitude'), time, depth));
			makeList(eq.get('magnitude'), time, depth);
		}
}


//plot the eqs
function plotEqs(point, mag, date, depth){
	side_bar_html = "";
	var image = getDepth(depth);
	var siz = getMag(mag);
	var grp = "eq" + mag.charAt(0);//sets up marker groups
	if(mag.charAt(0) > 3){
		grp = "eq" + 3;
	}
	eqIcon = new GIcon();
	eqIcon.image = "images/" + image + ".png";
	eqIcon.iconSize = new GSize(siz, siz);
	eqIcon.iconAnchor = new GPoint(siz/2, siz/2);
	eqIcon.infoWindowAnchor = new GPoint(siz/2, siz/2);
	var markerOptions = { icon:eqIcon };
	var marker = (new GMarker(point, markerOptions));
	var listId = "listId" + count; //give each a unique id so an open window will highlight the list-item
	GEvent.addListener(marker, "click", function() {
	    marker.openInfoWindowHtml("<strong> Mag "+ mag + "</strong><br/>" + date);
		$(listId).style.backgroundColor = "yellow";
	  });
	
	GEvent.addListener(map,"infowindowclose", function() { //resores list-item to un-highlighted
		$(listId).style.backgroundColor="#ffffff";
	});
	marker.grp = grp; //add group id to each marker
	
	//the following is to set up the sidebar list
	gmarkers[count] = marker;
	
	side_bar_html = "javascript:myclick(" + count + ")";

	return marker;
}

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


//create the side bar
function makeList(mag, time, depth){
	var z = depth.split(".")[0];
	//if (z < 10){
	//	z = "0" + z;
	//}
	z +=" Km"
	
	var grp = "eq" + mag.charAt(0);//sets up marker classes based on mag
	if(mag.charAt(0) > 3){
		grp = "eq" + 3;
	}
	var li  = document.createElement("li");
	Element.extend(li); //IE
	li.id = "listId" + count;
	li.addClassName(grp);
	var a = document.createElement("a");
	a.href = side_bar_html;
	if(mag >=3){//give mag 3 and greater red type
		Element.addClassName(a, "m3");
	}else{
		Element.addClassName(a, "msmall");
	}
	a.innerHTML= mag + " " + time + " " + z; //works in ie
	li.appendChild(a);
	$("eqlist").appendChild(li);
	count ++;
}

//check depth of event to assign proper colored icon
function getDepth(z){
	if (z < 10){
		return "shallowest";
	}
	if (z < 15){
		return "shallower";
	}
	if (z < 20){
		return "med";	
	}
	if (z < 25){
		return "deeper";
	}
	if (z > 25){
		return "deepest"
	}
}
//determine magnitude to size icons
function getMag(mag){
	var scale = 5; //these allow for fine tuning the size of icons
	var base =5;
	return size = mag * scale + base;
}
//////the following three functions are to manage the user checkbox clicks////////////

//show or hide (shide) selected markers
function shide(){
	var grp = this.id;
	var checked = this.checked;
	checkBoxes(grp);
	manageList(grp, checked);
	for (var i=0; i<gmarkers.length; i++) {
		if (grp == "eqAll"){ //if 'eqall' button is clicked(shows all or hides all)
			if(checked){
				gmarkers[i].show();
			}else{
				gmarkers[i].hide();
				map.closeInfoWindow();	
			}
		}else{
      		if (gmarkers[i].grp == grp){//individual button clicked
				if(checked){
        			gmarkers[i].show();
				}else{
					gmarkers[i].hide();
					map.closeInfoWindow();
				}	
			}
      	}
    }
}

//manages checkboxes, markers and list for case when 'eqAll' is checked or another button is checked when
//eqAll is already checked
function checkBoxes(grp){
	var listAll = $('eqlist').childElements();
	if (grp == "eqAll"){//uncheck all boxes when 'eqall is clicked
		for(var i =0; i < 4; i++){
			$('eq' + i).checked = false;
		}
		for(var i= 0; i < listAll.length; i ++){
			if($('eqAll').checked){
				listAll[i].show();
			}else{
				listAll[i].hide();
			}
		}
	}else{ //remove all icons/list-items if all is checked when another button is checked
		if($('eqAll').checked){
			for (var i=0; i<gmarkers.length; i++){
				gmarkers[i].hide();
			}
			for(var i= 0; i < listAll.length; i ++){
				listAll[i].hide();
			}
		}
		$('eqAll').checked = false;
	}
}

function manageList(grp,checked){
	var list = $$("."+ grp);
	for(var i = 0; i < list.length; i++){
		if(checked){
			list[i].show();
		}else{
			list[i].hide();
		}
	}
}
////////end of click functions/////////
/*function showPacTime(){
	id = this.id;
	$$(id "div").style.display = "block";
		
}
function showUTC(){
	id = this.id;
	$$(id "div").style.display = "none";
}*/
//]]>
