/**
	ajax code to load content from web service in xml format
	used to show  quake info and felt reports on the shaking map
	solo application hosted on apache
	
	two blocks of contents are copied across
	1. the quake info at the header part
	2. the felt reports table below the shaking map
	
	to be able to query quakeinfo and feltreports from web service, 
	the web service need be on the same host as this web app,
	or a proxy is needed (e.g. apache mod_rewrite)
	
	19/2/2008
	
*/	



var REPORTS_URL = "/services/mmreport?";
var MMDEF_URL = "http://www.geonet.org.nz/earthquake/geonet-modified-mercalli-intensity-scale.html#mm" ; 

var quakeHeader = "New Zealand Earthquake Report";
var reportsHeader = "The Modified Mercalli (MM) intensity levels, and the number of reports (where MM can be determined) from localities that experienced them, are shown below:";

var TAG_REPORT = "report";
var TAG_REPORTS = "felt-reports";
var TAG_MM = "mm";
var ATTR_VAL = "val";
var ATTR_DEF = "def";
var AATTR_PLACE = "plc";
var TAG_LOCAL_TIME = "local-time";
var TAG_MAGNITUDE = "mag";
var TAG_LOCATION = "location";

var tableID = "shakemap-table"; 
var TH_CLASSES = ["nameColumnHeader", "reportsColumnHeader", "reportsStringColumnHeader"];
var TH_HEADERS = ["Level", "Number", "Localities"];
var CELL_CLASSES = ["reportsColumnName", "reportsColumnValue", "reportsStringColumnValue"];
var TIME_FORMAT_NZ1 = "MMM d yyyy 'at' h:mm a";
var month_names = [ "January", "February", "March", "April", "May", "June", "July", "August",
					"September", "October", "November", "December"];
					
var day_names =[ "Sunday",  "Monday", "Tuesday", "Wednesday", "Thursday",  "Friday", "Saturday"];

var quakeInfoHolderID = "quakeinfo_header"; //the element id of the target page the holds the content to copy
var reportsHolderID = "quake-info"; //the element id of the target page the holds the content to copy
var	detailsDivID = "details";

var quakeInfoHolder;  //the element  of the target page the holds the content to copy
var reportsHolder;  //the element   of the target page the holds the content to copy
var detailsDiv ;//= document.createElement("div");
var reportTable; 

var sp;// = getQueryVariable("sp", "S11g");
var externalRef;
var agency;

var http_request_reports = false;
var http_request_quake = false;
var debug;

//we start here
window.onload = init;  
  
/** initialization */
function init() { 
	debug = document.getElementById("debug");
	quakeInfoHolder = document.getElementById(quakeInfoHolderID);
	reportsHolder = document.getElementById(reportsHolderID);
	//get query parameter
	sp = getQueryVariable("sp", "S11g");
	if((sp)&&(sp.length > 1)){ //S2620918g
		//check first char
		var first = sp.substring(0,1);
		if (isNaN(first*1)){
			sp = sp.substring(1); //remove the S
		}
	}
	
	//load quake info and populate the page head
	if(sp){//query xml externalRef=2684211&agency=g
		//queryQuakeInfo(QUAKE_INFO_URL +  sp);
	}
	//load felt reports and quake details, not needed for the perl template page!!!!
	loadFeltReports();
	//debug.innerHTML = "ref=" + ref + " last=" + last ; 
}


/*			   
*/
function loadFeltReports() {
	var ref; //external ref
	var last; //agency 
	ref = sp;
		
	//check last char, g
	last = ref.substring(ref.length -1,ref.length);
	//log("last =" + last + " type=" +   (isNaN(last*1))); 	
	if (isNaN(last*1)){
		ref = ref.substring(0, ref.length -1); //remove the g
	}else{//no request
		//last = "g";
		ref = null;
	}
	externalRef = ref;
	agency = last;
	
	if(ref){//query xml externalRef=2684211&agency=g
		queryFeltReports(REPORTS_URL + "externalRef=" + ref + "&agency=" + last);
	}
	
}

/*			   
*/
function createReportsTable() {
	reportTable = document.getElementById(tableID);
	if(!reportTable){
		reportTable = document.createElement("Table");
		reportTable.id = "shakemap-table";
		//add head row
		 addrow(TH_HEADERS, null, 0);
	}
}

function createRequest( ) {
   http_request = false;
   if (window.XMLHttpRequest) { // Mozilla, Safari,...
         http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/xml');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
   return http_request;
}

 
/*
* add reports table etc to the doc
*/ 
function showReportsContents() { 
	if(reportsHolder){
		reportsHolder.innerHTML = "" ;
		if(reportTable){
			detailsDiv = document.getElementById(detailsDivID);
			if(!detailsDiv){
				detailsDiv = document.createElement("div");
				detailsDiv.id = detailsDivID;
			}
			detailsDiv.innerHTML = "<p>" + reportsHeader + "</p>";	
			
				
		    reportsHolder.appendChild( detailsDiv);
			reportsHolder.appendChild( reportTable);
		}
	}
}

/*
*/
function parseQuakeInfo() {
    //alert(http_request_quake.readyState);
    var headText = quakeHeader;
    var time, location, mag;
    var hasInfo = false;
      if (http_request_quake.readyState == 4) {
         if (http_request_quake.status == 200) {
            var xmldoc;// = http_request_quake.responseXML;          
             // ie doesnt form the xml doc well so we load from text...
		    if (window.ActiveXObject) {
		        xmldoc = new ActiveXObject("Microsoft.XMLDOM")
		        xmldoc.async="false"
		        var response = (http_request_quake.responseText);
		        //remove all the staff in the report tag for ie to parse the xml
                //response = response.replace(/<report.*>/, "<report>");
		        xmldoc.loadXML(response)
		    } else{
		    	xmldoc = http_request_quake.responseXML;  
		    }
		              
            var root = xmldoc.getElementsByTagName(TAG_REPORT).item(0);
          
            if(root){
               //var text = root.tagName;
               //alert(text);
               for (var iNode = 0; iNode < root.childNodes.length; iNode++) {
	               var node = root.childNodes.item(iNode);
	              // alert (node.tagName);
	               var nodeTage = node.tagName;
	               if (nodeTage) {
	               		if(nodeTage == TAG_LOCAL_TIME){
	               			time = node.childNodes[0].nodeValue;
	               			//alert (nodeTage);
	               		}else if(nodeTage == TAG_MAGNITUDE){
	               			mag = node.childNodes.item(0).nodeValue;
	               			//alert (mag);
	               		}else if(nodeTage == TAG_LOCATION){
	               			location = node.childNodes.item(0).nodeValue;
	               			//alert (location);
	               		}
	                 }
	               //alert (nodeTage);
	              }
               //
               //alert(time);
               var nzTimes = parseTimeString(time);
               
               if(nzTimes){
              	  headText =  "<h1 class='documentFirstHeading'><br/>"  + headText + " - "  + nzTimes[0] + "</h1>";
              	  hasInfo = true;
              	   // <p class="documentDescription">Magnitude
	               if(mag && location){
	               		 headText +=  "<p class='documentDescription'>Magnitude " + mag
	               		 			+   ", " + nzTimes[1] 
	               		 			+ ", " + location; 
	               }
                }
            }
        }
    }
     if(!hasInfo){
     	headText =  "<h1 class='documentFirstHeading'><br/>"  + headText   + "</h1>";
     }
    //show head text
    if(quakeInfoHolder){
    	quakeInfoHolder.innerHTML = headText;
    }
 }
 
 /*
 //2007-01-18T16:34:14.178+13:00
  */
 function parseTimeString(timestr) {
 //alert(timestr);
 //2007-01-18T16:34:14.178+13:00
 //var stdt = "(NZST)"; 
 if(timestr){
 	var strArray  = timestr.split("+");
 	//alert(strArray.length);
 
 	//var  timestr0 = strArray[0];
 	var  date = parseDateTime(strArray[0]);    
    
 	//alert(dayofweek);
 	if(date){
 		 var stdt = getStDt(strArray[1]);
	    var timestr = formatTime(date);
	    var append = "";
	    if(timestr){
	    	append = " at " + timestr ;
	    }
	    
	    if(stdt){
	    	append =   append  + " (" + stdt + ")";
	    }
    
	 	var nzTimes = new Array();
	 	nzTimes[0] = formatDate(date, 0) + append ;//short
	 	nzTimes[1] = formatDate(date, 1)  + append ; //long
	 	return nzTimes;
 	}
 	//debug.innerHTML = nztime_long; //Thu Jan 18 2007
   }
   return null;
 
 }
 
 function formatTime(date ) {//
 	var ampm = "am";
 	var hr = date.getHours();
 	if(hr >= 12){
 		hr -= 12;
 		ampm = "pm";
 	}
 	return hr + ":" + date.getMinutes() + ":" + date.getSeconds() + " " + ampm
 }
 
 
 function getStDt(timeplus ) {//+13:00
 	if(timeplus){
 		if(timeplus.indexOf("13") == 0){
 			return "NZDT";
 		}else if(timeplus.indexOf("12") == 0){
 			return "NZST";
 		}
 	}
 	return null;
 }
 
 //short: Jan 18 2007 at 4:34 pm - (NZDT),
 //long: Thursday, January 18 2007 at 4:34 pm (NZDT)
 function formatDate(date, short_long) {//0--short, 1--long
	//var datelocal = date.toLocaleString(); //Thu 18 Jan 2007 04:34:14 PM NZDT		
		if(short_long ==0){//Jan 18 2007 at 4:34 pm - (NZDT),
			return month_names[date.getMonth()].substring(0,3) + " " 
				 +  date.getDate() + " "
				+ date.getFullYear()  ; //
				  
		}else{//Thursday, January 18 2007 at 4:34 pm (NZDT)
			return day_names[date.getDay()] + ", "
				+  month_names[date.getMonth()] + " "
				+  date.getDate() + " "
				+ date.getFullYear()  ; //
		}
	
	//return datelocal;
 }
 
 function parseDateTime(dateTimeStr) {
 ////2007-01-18T16:34:14.178+13:00
 var date = null;
	 if(dateTimeStr){
	 	var array = dateTimeStr.split("T");
	 	if(array.length > 1){
	 	var year, month, day, hour, minute, second;
	 		var dateArray = array[0].split("-");
	 		if(dateArray.length > 2){
	 			 year = parseInt(dateArray[0]);
	 			 month = parseInt(dateArray[1]);
	 			 day = parseInt(dateArray[2]);
	 			//alert(year);
	 		}
	 		var timeArray = array[1].split(":");
	 		if(timeArray.length > 2){
	 			 hour = parseInt(timeArray[0]);
	 			 minute = parseInt(timeArray[1]);
	 			 second = parseInt(timeArray[2]);
	 			//alert(hour);
	 		}
	 		//alert(year + ", " + month + ", " + day + ", " + hour + ", " + minute + ", " + second);
	 		date = new Date(1*year, 1*month -1, 1*day,1*hour, 1*minute, 1*second);
	 		//date.setYear(98);
	 	}
	 }
	 return date; 
 }

function parseReports() {
      if (http_request_reports.readyState == 4) {
         if (http_request_reports.status == 200) {

            var xmldoc = http_request_reports.responseXML;
            //reportsHolder.innerHTML = xmldoc.xml;
            //alert(http_request_reports.responseText);
            var root = xmldoc.getElementsByTagName(TAG_REPORTS).item(0);
            if(root && (root.childNodes.length > 0)){
            var total;// = root.attributes[0].nodeValue;
            
            if(root.attributes[0]) total = root.attributes[0].nodeValue;
           // alert(root.childNodes.length);
            //
              createReportsTable();
            //alert(total);
	          for (var iNode = 0; iNode < root.childNodes.length; iNode++) {
	               var node = root.childNodes.item(iNode);
	               var nodeTage = node.tagName;
	               //alert (nodeData);
	               //<mm val="5" def="Strong" count="4" plc="Mahora [1],Palmerston North [1],Springvale [1],Waipawa [1]"/>
	               if(nodeTage == TAG_MM){
	               //var def = node.attributes.getNamedItem(ATTR_DEF).nodeValue;
	               //var place = node.attributes.getNamedItem(ATTR_PLACE).nodeValue;
		             var len = parseInt(node.attributes.length);
	          		 var arr = new Array(len - 1); 
	                 var cnt = 0;
	                 for (x = 0; x < node.attributes.length; x++) {
	                 	if (x == 1){continue;}
	                 	 var val = node.attributes[x].nodeValue;
	                 	 if (x == 0){
	                 	 	val = "<a target='_blank' shape='rect' href='" + MMDEF_URL + " "  + val + "'>" + "MM" + val + "</a>";
	                 	 	val += " " + node.attributes[x+1].nodeValue;
	                 	 }
	                 	 if (x == node.attributes.length - 1){//the report string
	                 	    //alert(val);change space to &nbsp;
	                 		 val = escapeReportString(val);
	                 	 }
	                     arr[cnt] = val;   
	                     cnt++;
		              }
		              addrow(arr, "mm" + node.attributes[0].nodeValue, 1);
	               }
	            }
	            //add bottom row for total reports
	             addrow([ "Total", total, ""], null, 0);
	           //
	           //
              
            }
           
         } else {
            //alert('There was a problem with the request.');
         }
      }
       showReportsContents();
   }
   
function queryFeltReports(url, para) {
   	  //if(!para) para = "";
      //makeRequest(url, para, parseReports, http_request_reports);
       http_request_reports = false;
       http_request_reports = createRequest();
      if (!http_request_reports) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }
      http_request_reports.onreadystatechange = parseReports;
      http_request_reports.open('GET', url , true);
      http_request_reports.send(null);
}

function queryQuakeInfo(url, para) {
   	  //if(!para) para = "";
      //makeRequest(url, para, parseQuakeInfo, http_request_quake);
        http_request_quake = false;
       http_request_quake = createRequest();
      if (!http_request_quake) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }
      http_request_quake.onreadystatechange = parseQuakeInfo;
      http_request_quake.open('GET', url , true);
      http_request_quake.send(null);
}


function addrow(arr, rowclass, th_td) {
  // var tbl = reportTable;//document.getElementById(tableID);
   var lastRow = reportTable.rows.length;
   //alert(lastRow);
   var row = reportTable.insertRow(lastRow);
   if(rowclass && (th_td != 0) ){//th
      row.className = rowclass; 
   }
    for (var r = 0; r < arr.length; r++) { 
        var cell ;
    	if(th_td == 0 ){//th 
      	 cell = document.createElement("th");
	     //cell.innerHTML = TH_HEADERS[r];
	     cell.className = TH_CLASSES[r]; 
	     row.appendChild(cell);
       }else{//td
       	 cell = row.insertCell(r);
         cell.className = CELL_CLASSES[r]; 
       }
       cell.innerHTML = arr[r];
    }
}


//replace space to bnsp etc
 function escapeReportString(reportStr) {
	if (reportStr){
		reportStr = reportStr.replace(new RegExp( " ", "g" ), "&nbsp;");
		reportStr = reportStr.replace(new RegExp( ",", "g" ), ", ");
	}
	return reportStr;
}  
   
function getQueryVariable(variable, defval) {
  var query = window.location.search.substring(1);
  if(query){  	
  	var vars = query.split("&");
	  for (var i=0;i<vars.length;i++) {
	    var pair = vars[i].split("=");
	    if (pair[0] == variable) {
	      return pair[1];
	    }
  	} 
  }else{//for perl template where parameter is in the file name
  //http://camden.gns.cri.nz/test/2702325g-shaking.html
  	query = window.location.pathname;
  	 //alert (url);	
  	var vars = query.split('/');
  	// alert (vars.length);	
  	if(vars.length > 1){
  	   var last = vars[vars.length - 1];//2702325g-shaking.html
  	   //alert (last);
  	   var lastbreaks = last.split('-');
  	   if(lastbreaks.length > 1){
  	   	  var spval = lastbreaks[0];
  	   	  //alert(spval);
  	   	  return spval; //2702325g
  	   }
  	}
  }  
  return defval;
}


function navigateWithSp(url, append) { 
if(sp){
	url += sp;
	if(append){
		url += append;
	}
	window.location = url  ;
}
}

//ognl:("/felt/app?service=external/Felt&sp=S" + externalRef + "&sp=S" + agency.toUpperCase())
function navigateWithExternalRefAgency(url, secondParam) { 
if(externalRef && agency){
	url += externalRef + secondParam + agency;
	window.location = url  ;
}
}


      
