// Original script by Ken True with mods by Ken Challis and others
// Modified for NexStorm updates by Henkka Roblom
// Some added functionality by Jim McMurry
// Version 1.0
//
// No need to change anything in this script
var nstotalupdates = 0;   
var nstotalupdates2 = 0;
nextmin = 0;
mapcheck = 0;
graphcheck = 0;
lasttrac = 0;


function set_ajax_obsL( name, value ) {               
		var element = document.getElementById(name);
		if (! element ) { return; }   
		var lastobs = element.getAttribute("lastobs");
		element.setAttribute("lastobs",value);
		if (unescape(value) != unescape(lastobs)) {
		  element.innerHTML =  value;
		}
}

function convertalign(rawalign) {

		align = Number(rawalign) + Number(alignment);
		if (align > 360) {
		align = Number(align) - Number(360);
		}
		return align;
}

function bearDir ($beardir)
// Take wind direction value, return the
// text label based upon 16 point compass -- function by beeker425
//  see http://www.weather-watch.com/smf/index.php/topic,20097.0.html
{
   $bearlabel = new Array("N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW");
   return $bearlabel[Math.floor(((parseInt($beardir) + 11) / 22.5) % 16 )];
}


// Functions for graphic display of TRACReport.txt


function makeRequest(url) {
        var httpRequest;

        if (window.XMLHttpRequest) { // Mozilla, Safari, ...
            httpRequest = new XMLHttpRequest();
            if (httpRequest.overrideMimeType) {
                httpRequest.overrideMimeType('text/xml');
                // See note below about this line
            }
        } 
        else if (window.ActiveXObject) { // IE
            try {
                httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
                } 
                catch (e) {
                           try {
                                httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                               } 
                             catch (e) {}
                          }
                                       }

        if (!httpRequest) {
            alert('Giving up :( Cannot create an XMLHTTP instance');
            return false;
        }
        httpRequest.onreadystatechange = function() { alertContents(httpRequest); };
        httpRequest.open('GET', url, true);
        httpRequest.send('');

    }

    function alertContents(httpRequest) {

        if (httpRequest.readyState == 4) {
            if (httpRequest.status == 200) {
		
		// Get the tracreport-data for AJAX
			if (! httpRequest.responseText.split('|')[0] == "") {
				document.getElementById("TRACHEAD").innerHTML = httpRequest.responseText.split('|')[0];
				document.getElementById("TRAC").innerHTML = httpRequest.responseText.split('|')[1];
				//document.getElementById("UPDATES").innerHTML = httpRequest.responseText.split('|')[3];
		   		lasttrac = httpRequest.responseText.split('|')[4];

			}
	       maptime = httpRequest.responseText.split('|')[2];
	       graphtime = httpRequest.responseText.split('|')[3];
	       
			if (! (maptime == mapcheck)) {
				
				
				//set_ajax_obsL("TIMEST", "Map Updated");
				document.getElementById("NEXMAP").src = path_to_image+"?"+ maptime;
			
				if (! showtime == "") {
			
					set_ajax_obsL("IMAGETIME", maptime);
				}
			}
			mapcheck = maptime; 


	if (graphtime*1 > graphcheck*1) {
	//set_ajax_obsL("TIMESTG", "<br/>Graph Updated");
        document.getElementById("NEXGRAPH").src = path_to_graph+"?"+graphtime;
	graphcheck = graphtime;
	} 




            } else {
                alert('No TRAC-data currently available.');
            }
        }

    }


function NSajaxLoader(url) {
  if (document.getElementById) {
    var x = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest(url);
  }
	if (x && ( nstotalupdates <= nsmaxupdates || nsmaxupdates > 0  )) { // got something back
    x.onreadystatechange = function() {
    try { if (x.readyState == 4 && x.status == 200) { 
		if (nsmaxupdates > 0 ) {nstotalupdates++; } // increment counter if needed   
		
		//Date
		set_ajax_obsL("DATE", x.responseText.split(delim)[dateOff*1]);

		//Since midnight
		set_ajax_obsL("MIDNIGHT", x.responseText.split('|')[midnightOff*1]);
	
               //Rate
               light = x.responseText.split(delim)[countOff*1];
               dist =  Math.round(x.responseText.split(delim)[distOff*1] * distfactor);
               if (dist == 0) dist = 1000;
               if ((light < strikecaution) && (dist >= distcaution)) {
                       light = "<font color=#FFFFFF size=6><b>" + light + "</b></font>";
                       graphpath = path_to_graph;
               } else if ((light >= strikecaution) || (dist <= distcaution)) {
                       light = "<font color=" + cautioncolor + " size=6><b>" + light + "</b></font>";
                       graphpath = path_to_graph2;
               } else {
                       light = "<font color=" + warningcolor + " size=6><b>" + light + "</b></font>";
                       graphpath = path_to_graph2;
               }

		set_ajax_obsL("RATE", light);
	
		//Since midnight
		//set_ajax_obsL("MIDNIGHT", x.responseText.split(delim)[midnightOff*1]);
	
		//Last strikedist
		set_ajax_obsL("LASTSTRDIS", Math.round(x.responseText.split(delim)[distOff*1] * distfactor));      
		
		//Last strikedirec
		bear = convertalign(x.responseText.split(delim)[direcOff*1]);
		if(showbearing == 1) bearing = bearDir(bear);
		if(showbearing == 2) bearing = "" + bear + "" + bearword +" (" + bearDir(bear) +")";
		if(showbearing == 0) bearing = "" + bear + "" + bearword +"";
		set_ajax_obsL("LASTSTRDIREC", bearing);		
	
		//Last striketime
		set_ajax_obsL("LASTSTRTIME", x.responseText.split(delim)[lasttimeOff*1].substr(0,8));
			//set_ajax_obsL("UPDATES", "<br>Debug: Script updates:" + path_to_tracajax + "");
            	//thismin = x.responseText.split(delim)[dateOff*1];
		thismin = x.responseText.split(delim)[30].replace(/^\s\s*/, '').replace(/\s\s*$/, '');
		//thismin = thismin.substr(thismin.length - 5, 2);
		
		if (thismin*1 >= nextmin*1) {

			//Calling the tracreportshort
			humm = makeRequest(path_to_tracajax + "?tractime=" + lasttrac + "&lang=" + lang);

			nextmin = Number(thismin) + 1;
			if (nextmin >= 60) {
					nextmin = nextmin - 60;
			}
		}

		//humm = makeRequest(path_to_tracajax + "?tractime=" + lasttrac + "&lang=" + lang);

		// Show the pausemessage instead of TRACheader if needed
		if (nsmaxupdates > 0 && nstotalupdates > nsmaxupdates-1) { /* chg indicator to pause message */
		set_ajax_obsL("TRACHEAD", langPauseMsg);
		}

		// For debugging
		//You can enable one of theese at time for checking updates. Appears in the topsection of Nexstormdisplay
		debupdates = "" + nstotalupdates + "/" + nsmaxupdates + "";
		//set_ajax_obsL("TIMEST", "<br>Debug:<br/>" + nstotalupdates + "/ " + nsmaxupdates + "");



    } // END if (x.readyState == 4 && x.status == 200)
	} // END try
	catch(e){}  // Mike Challis added fix to fix random error: NS_ERROR_NOT_AVAILABLE
    } // x.onreadystatechange = function()
    x.open("GET", url, true);
    x.send(null);
	if ( (nsmaxupdates == 0) || (nstotalupdates < nsmaxupdates-1)) {
      setTimeout("NSajaxLoader(path_to_data + '?' + new Date().getTime())", 1000); // get new data 
    }
  }  // end of 'got something back'
} // end NSajaxLoader function

