/*
* NSDisplay goes jQuery, showing data from Boltek Stormtracker together with Nexstorm & NSLog softwares.
* v. 1.0
* Created by Henkka, nordicweather.net, Feb 2010
*/

$(function () {

	// DON'T TOUCH!!!
   var data = ''; 
	 var alreadyFetched = {};
   var ns = '';
   var iteration = 0;
   var nextmin = 0;
   
  update();
  $("#continuespan").html(txtPaus);
  $("#continuespan").hide();
 
  
   
   function update() {
   
          //Reset data
          alreadyFetched = {};
            
       function onDataReceived(series) {
          iteration++;
                
          // split NSRealtime
          var ns = series.split(',');
          
          // clock
          if(date == 1) {
          var cu = ns[2]+'.'+ns[1]+'.'+ns[0]+' '+ns[3]+':'+ns[4]+':'+ns[5];
          } else if (date == 2) {
          var cu = ns[1]+'/'+ns[2]+'/'+ns[0]+' '+ns[3]+':'+ns[4]+':'+ns[5];
          } else {
          var cu = ns[2]+'/'+ns[1]+'/'+ns[0]+' '+ns[3]+':'+ns[4]+':'+ns[5];
          }
          var ca = ns[0]+ns[1]+ns[2]+ns[3]+ns[4];
          $("#clock").html(cu);
          $("#SHOWTIME").html(ns[50]+' min');
          $("#SHOWTIME2").html(ns[50]+' min');
          var mea = ns[51];
          if(mea == "1"){var kmhmph = "mi";var measure = "mi";}
          else{var kmhmph = "km";var measure = "km";}        
          var offset = ns[51];
          
          // Rates
          var rate = ns[24];
          var clrate = ns[26];
          if(rate < 30) {
          $("#RATE").html(rate);
          } else {
          $("#RATE").html("<font color=\"#EE2C2C\">" + rate + "</font>");
          }
          if(clrate < 30) {
          $("#CLOSERATE").html(clrate);
          } else {
          $("#CLOSERATE").html("<font color=\"#EE2C2C\">" + clrate + "</font>");
          }
          
          //Since midnight
          $("#MIDNIGHT").html(ns[15]);

          //Total since X minute
          $("#LMINTOTAL").html(ns[32]);

          //Peakrates
          $("#PEAKRATE").html("" + ns[22] + "/min");
          $("#PEAKBURSTRATE").html("" + ns[48] + "/sec");

          //Peaktimes
          $("#PEAKTIME").html(ns[23]);
          $("#PEAKBURSTTIME").html(ns[49]);
 
          //Last striketime
          $("#LASTSTRTIME").html(ns[41]); 

          //Last striketype
          $("#LASTSTRTYPE").html(ns[10]); 

          //Last strikedist
          $("#LASTSTRDIS").html(ns[7]+' '+kmhmph); 

          //Last strikedirec
          bear = (ns[6]*100/100).toFixed(0) +"°";
          $("#LASTSTRDIREC").html(bear);	
          
          p2_lon = 0;
          p2_lat = 0;
          userlat = $.cookie("nsd2lat");
          userlon = $.cookie("nsd2lon");
          
          if (measure == "mi") {                             
          ns[7] = ns[7] * 0.62;
          }
          
          getpoint(ns[6], ns[7], centerlat, centerlon, measure);
          dista = distance(userlat, userlon, p2_lat, p2_lon, measure);
          $("#DEBUG").html("Debug: "+ns[6]+"||"+ns[7]+"||"+centerlat+","+centerlon+"||"+userlat+","+userlon+"||"+p2_lat+","+p2_lon+"="+dista);
          $("#USERDIST").html(dista.toFixed(0)+' '+measure);
          
          /* For plotting directly - not in use, maybe in future ;)
          heightofimagedistance = 2000;
          widthofimagedistance = 2000;
          if (measure == "km") {
          heightofimagelatitude = heightofimagedistance / 111.322;      // 1 degree latitude in km x height
          widthofimagelongitude = widthofimagedistance / (cos(deg2rad(centerlat)) * 111.322); // latitude in km x width
          } else {
          heightofimagelatitude = heightofimagedistance / 69.172;        // 1 degree latitude in miles times height of image in miles
          widthofimagelongitude = widthofimagedistance / (cos(deg2rad(centerlat)) * 69.172); // latitude in miles x width
          }
          pt = getlocationcoords(p2_lat, p2_lon, 691, 691); // mapspoints x, y
          */

          midnight = ns[15];
          cgptod = ns[18];
       if(cgptod == 0) { cgptof = "0%"; } else { cgptof = "" + ((cgptod/midnight)*100).toFixed(0) + "%"; }
          $("#CGPTODPREC").html(cgptof);

          cgmtod = ns[19];
			if(cgmtod == 0) { cgmtof = "0%"; } else { cgmtof = "" + ((cgmtod/midnight)*100).toFixed(0) + "%"; }
          $("#CG-TODPREC").html(cgmtof);

          ccptod = ns[20];
			if(ccptod == 0) { ccptof = "0%"; } else { ccptof = "" + ((ccptod/midnight)*100).toFixed(0) + "%"; }
          $("#CCPTODPREC").html(ccptof);

          ccmtod = ns[21];
			if(ccmtod == 0) { ccmtof = "0%"; } else { ccmtof = "" + ((ccmtod/midnight)*100).toFixed(0) + "%"; }
          $("#CC-TODPREC").html(ccmtof);

          //Uptime
          len = ns[40].length;
          $("#UPTIME").html(ns[40].substr(0,len-3));

        // Update the map, trac and graph each minute
        var thismin = ca;	
        if (thismin*1 != nextmin*1) {
        var range = $.cookie("nsd2");
        $("#NEXMAP").attr('src', path_to_map+'?range='+range+'&' + ca);
        
        $.getJSON(path_to_nsjson, function (data) {
        
        $.plot($("#GRAPH"),
        [{data:data[0].a1, lines: { show: true, fill: false, lineWidth: 2 }, points:
        { show: false },legend: {show: false}, color: "#00FF00"}],
       // {yaxis: { min: 0, minTickSize:1,tickDecimals:0 }, xaxis: { mode: "time",timeformat: "%H:%M",  tickSize: [20, "minute"] },
       {yaxis: { min: 0, minTickSize:1,tickDecimals:0 }, xaxis: {mode: "time", ticks: [[2, "60"], [22, "40"], [42, "20"], [62, "0"]] },
        grid: {tickColor: "#424242", color:"#CCCCCC",  borderWidth: 1, borderColor: "#424242",      backgroundColor: { colors: ["#000", "#424242"] }}
        });
        
        $.plot($("#TOTCHART"),
        [{data:data[1].a2, lines: { show: true, fill: false, lineWidth: 2 }, points:
        { show: false },legend: {show: false}, color: "#00FF00"}],
        {yaxis: { min: 0, minTickSize:1,tickDecimals:0}, xaxis: { mode: "time",timeformat: "%H:%M",  tickSize: [1, "hour"] },
        grid: {tickColor: "#424242", color:"#CCCCCC",  borderWidth: 1, borderColor: "#424242",      backgroundColor: { colors: ["#000", "#424242"] },hoverable: true, autoHighlight: true}
        });

        
        
        });
        
        $.get(path_to_trac, function (trac) {
        check = trac.split("\n");
        if(check.length*1 == 1) {
        $("#STORMS").html("<font color=\"#00FF00\">" + txtNost + "</font>");
        $("#NEARBY").html("<font color=\"#00FF00\">" + txtInac + "</font>");
        $("#STORM").html("");
        } else {
        var howmany = (check.length-1*100/100).toFixed(0);
        $("#STORMS").html("<font color=\"#EE2C2C\">" + txtTrac + " " + howmany + " " + txtStor + "</font>");
        tracreport(trac,userlat,userlon,centerlat,centerlon,measure);
        } 
        });
        
        $.get(path_to_oldtrac, function (trac) {
        check = trac.split("\n");
        if(check.length*1 > 1) {
        oldstorms(trac,userlat,userlon,centerlat,centerlon,measure); 
        }
        });
        
        nextmin = thismin;
        }
        
        if (iteration == updates) {
        $("#continuespan").show();
        return;
        }
          
        ns = '';
        ns = false;
                  
        } // EOF onDataReceived

        $.ajax({
            url: dataurl,
            method: 'GET',
            dataType: 'text',
            cache: false,
            success: onDataReceived,
            error: function(msg){}
        });
          
            
        if (iteration < updates) {
        setTimeout(update, timeout*1000);
        }
        
           
      }; // EOF update
      
      
      function showTooltip(x, y, contents) {
        $('<div id="tooltip">' + contents + '</div>').css( {
            position: 'absolute',
            display: 'none',
            top: y - 35,
            left: x + 5,
            border: '1px solid #eee',
            padding: '2px',
            'background-color': '#fff',
            opacity: 0.80
        }).appendTo("body").fadeIn(200);
     }
       
     var previousPoint = null;
     $("#TOTCHART").bind("plothover", function (event, pos, item) {
        $("#x").text(pos.x.toFixed(2));
        $("#y").text(pos.y.toFixed(2));

            if (item) {
                if (previousPoint != item.datapoint) {
                    previousPoint = item.datapoint;
                    
                    $("#tooltip").remove();
                    var x = item.datapoint[0].toFixed(3),
                        y = item.datapoint[1].toFixed(0);
                    var hy = new Date(x*1);
                    var hour = hy.getHours();
                    var minu = hy.getMinutes();
                    if(minu < 10) var minu = '0'+minu;
                    //var os = new Date.getMonth(x);
                    //showTooltip(item.pageX, item.pageY, hour + ":"+minu+": " + y);
                    showTooltip(item.pageX, item.pageY, y);
                }
            }
            else {
                $("#tooltip").remove();
                previousPoint = null;            
            }
     });
     
    function windDir ($winddir){$windlabel = new Array("N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW");  
    return $windlabel[Math.floor(((parseInt($winddir) + 11) / 22.5) % 16 )];
    }  
    bgcolor = new Array("#61C770", "#CED156", "#D2A055", "#C45539");
     
// CUrrent storms

    function tracreport(trac,userlat,userlon,centerlat,centerlon,measure) {
    // Reading the storms
    parts = '';
		var parts = trac.split("\n");

		// Process the each storm
		var se = '';
		var table=new Array();
		var nearby = 'off';

		var trends = new Array("No", "Weakening", "Intensifying", "Undetermined");
		var intensitys = Array("Weak", "Moderate", "Strong", "Severe");

		table+= se + '<div style="color:#3299CC; font-size: 12px;padding-top:6px;text-align: center;"><b>'+txtStorms+'</b></div><br/><table width="99%" border= "0" cellspacing="0" cellpadding="0" style="padding-bottom:0px; border: 1px solid #424242; background: #000;"><tr style="background-color:#424242; height: 18px; color:#3299CC; font-size:11px;"><td width="63"><div align="center" class="nexstyle11">ID</div></td><td width="63"><div align="center" class="nexstyle11">' + txtDete + '</div></td><td width="63"><div align="center" class="nexstyle11">' + txtBear + '</div></td><td width="63"><div align="right" class="nexstyle11"style="padding-right:5px;">' + txtDist + '</div></td><td width="92"><div align="center" class="nexstyle11">' + txtInte + '</div></td><td width="93"><div align="center" class="nexstyle11">' + txtTren+ '</div></td><td width="63"><div align="right" class="nexstyle11" style="padding-right:5px;">' + txtRate + '</div></td><td width="60"><div align="right" class="nexstyle11" style="padding-right:5px;">' + txtPeak + '</div></td><td width="60"><div align="right" class="nexstyle11" style="padding-right:5px;">CG</div></td><td width="60"><div align="right" class="nexstyle11" style="padding-right:5px;">CC</div></td><td width="60"><div align="right" class="nexstyle11" style="padding-right:5px;">' + txtTota + '</div></td><td width="75"><div align="center" class="nexstyle11"></div></td><td width="60"><div align="center" class="nexstyle11">' + txtAge + '</div></td></tr>';


		for (var i = 0; i <= parts.length-2; i++) {

		part = parts[i];

		id = part.split(',')[0];
		detec = part.split(',')[2];
		bear = windDir(part.split(',')[8]);
		disti = part.split(',')[9];
		age = part.split(',')[32];
		curate = part.split(',')[12];
		prate = part.split(',')[13];
		totst = part.split(',')[21]*1;
		
		cga = part.split(',')[22]*1;
		cga+= part.split(',')[23]*1;
		cg = (cga/totst*100).toFixed(0);

		cca = part.split(',')[24]*1;
		cca+= part.split(',')[25]*1;
		cc = (cca/totst*100).toFixed(0);

		tt = trendtxt[part.split(',')[20]];

		jj = intensitytxt[part.split(',')[18]];
		jcolor = bgcolor[part.split(',')[18]];
		
		p2_lat = 0;
		p2_lon = 0;
		getpoint(part.split(',')[8], disti, centerlat, centerlon, measure);
    dista = distance(userlat, userlon, p2_lat, p2_lon, measure);

		if(disti < 50) {
		nearby = 'on';
		}

		if(i%2 != 1) { var tblbg = "#2B2B2B"; } else { var tblbg = "#000" }

		table+= se + '<tr style="font-size:11px;color:#fff;line-height: 20px;background-color:'+tblbg+';"><td width="63"><div align="left" style="padding-left:7px;">' + id + '</span></td><td width="63"><div align="center">' + detec + '</div></td><td width="63"><div align="center">' + bear + '</div></td><td width="63"><div align="right" style="padding-right:5px;">' + disti + ' '+ measure +'</div></td><td width="92"><div align="center"><font color="' + jcolor + '">' + jj + '</font></div></td><td width="93"><div align="center">' + tt + '</div></td><td width="60"><div align="right" style="padding-right:5px;">' + curate + '</div></td><td width="60"><div align="right" style="padding-right:5px;">' + prate + '</div></td><td width="60"><div align="right">' + cg + '%</div></td><td width="66"><div align="right">' + cc + '%</div></td><td width="60"><div align="right" style="padding-right:10px;">' + totst + '</div></td><td width="75"><div align="right" style="padding-right:15px;"></div></td><td width="60"><div align="center">' + age + '</div></td></tr>';
		} // EOF each

		table+= se + "</table><br/>";

    $("#STORM").html(table);
		if(nearby == "on") {
		$("#NEARBY").html("<font color=\"#EE2C2C\">" + txtActi + "</font>");
		} else {
		$("#NEARBY").html("<font color=\"#00FF00\">" + txtInac + "</font>");
		}

  }  // EOF function

// OLD STORMS

    function oldstorms(trac,userlat,userlon,centerlat,centerlon,measure) {
    // Reading the storms
    parts = '';
		var parts = trac.split("\n");

		// Process the each storm
		var se = '';
		var table=new Array();
		var nearby = 'off';

		var trends = new Array("No", "Weakening", "Intensifying", "Undetermined");
		var intensitys = Array("Weak", "Moderate", "Strong", "Severe");

		table+= se + '<div style="color:#3299CC; font-size: 12px;padding-top:6px;text-align: center;"><b>'+txtOldStorms+'</b></div><br/><table width="99%" border= "0" cellspacing="0" cellpadding="0" style="padding-bottom:0px; border: 1px solid #424242; background: #000;"><tr style="background-color:#424242; height: 18px; color:#3299CC; font-size:11px;"><td width="75"><div align="center" class="nexstyle11">ID</div></td><td width="75"><div align="center" class="nexstyle11">' + txtDete + '</div></td><td width="63"><div align="center" class="nexstyle11">' + txtLast + '</div></td><td width="63"><div align="center" class="nexstyle11">' + txtClBear + '</div><td width="63"><div align="center" class="nexstyle11">' + txtClDist + '</div></td><td width="92"><div align="center"class="nexstyle11">' + txtClDistt + '</div></td><td width="63"><div align="center" class="nexstyle11">' + txtMaxInte + '</div></td><td width="60"><div align="right" class="nexstyle11" style="padding-right:5px;">' + txtPeak + '</div></td><td width="60"><div align="right" class="nexstyle11" style="padding-right:5px;">CG</div></td><td width="60"><div align="right" class="nexstyle11" style="padding-right:5px;">CC</div></td><td width="60"><div align="right" class="nexstyle11" style="padding-right:5px;">' + txtTota + '</div></td><td width="75"><div align="center" class="nexstyle11"></div></td><td width="60"><div align="center" class="nexstyle11">' + txtDura + '</div></td></tr>';


		for (var i = 0; i <= parts.length-2; i++) {

		part = parts[i];

		id = part.split(',')[0];
		detec = part.split(',')[2];
		bear = windDir(part.split(',')[15]);
		disti = part.split(',')[16];
		disttime = part.split(',')[17];
		lastact = part.split(',')[7];
		age = part.split(',')[32];
		curate = part.split(',')[12];
		prate = part.split(',')[13];
		totst = part.split(',')[21]*1;
		
		cga = part.split(',')[22]*1;
		cga+= part.split(',')[23]*1;
		cg = (cga/totst*100).toFixed(0);

		cca = part.split(',')[24]*1;
		cca+= part.split(',')[25]*1;
		cc = (cca/totst*100).toFixed(0);

		tt = trendtxt[part.split(',')[20]];

		jj = intensitytxt[part.split(',')[19]];
		jcolor = bgcolor[part.split(',')[19]];
		
		p2_lat = 0;
		p2_lon = 0;
		getpoint(part.split(',')[15], disti, centerlat, centerlon, measure);
    dista = distance(userlat, userlon, p2_lat, p2_lon, measure);

		if(i%2 != 1) { var tblbg = "#2B2B2B"; } else { var tblbg = "#000" }

		table+= se + '<tr style="font-size:11px;color:#fff;line-height: 20px;background-color:'+tblbg+';"><td width="63"><div align="left" style="padding-left:7px;">' + id + '</span></td><td width="75"><div align="center">' + detec + '</div></td><td width="75"><div align="center">' + lastact + '</div></td><td width="63"><div align="center">' + bear +'</div></td><td width="63"><div align="right" style="padding-right:5px;">' + disti + ' '+ measure +'</div></td><td width="92"><div align="center">' + disttime + '</div></td><td width="63"><div align="center"><font color="' + jcolor + '">' + jj + '</font></div></td><td width="60"><div align="right" style="padding-right:5px;">' + prate + '</div></td><td width="60"><div align="right">' + cg + '%</div></td><td width="60"><div align="right">' + cc + '%</div></td><td width="60"><div align="right" style="padding-right:10px;">' + totst + '</div></td><td width="75"><div align="right" style="padding-right:15px;"></div></td><td width="60"><div align="center">' + age + '</div></td></tr>';
		} // EOF each

		table+= se + "</table><br/>";
		$("#OLDSTORM").html(table);

  }  // EOF function
  
// Distance & getpoint-functions
  
function distance(lat1, lon1, lat2, lon2, unit) { 
  var R = 6371; // earth's mean radius in km
  var dLat = deg2rad((lat2-lat1));
  var dLon = deg2rad((lon2-lon1));
  lat1 = deg2rad(lat1), lat2 = deg2rad(lat2);
  
  var a = Math.sin(dLat/2) * Math.sin(dLat/2) +

          Math.cos(lat1) * Math.cos(lat2) * 

          Math.sin(dLon/2) * Math.sin(dLon/2);

  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));

  var d = R * c;

  return d;

}


 // This and the next function compliments of Tom Chaplin, carterlake.org
function getlocationcoords(lat, lon, width, height) {   
    x = (lon + (abs(centerlon) + (widthofimagelongitude / 2))) * (width / widthofimagelongitude); 
    y = (((lat * -1) + (abs(centerlat) + (heightofimagelatitude / 2))) * (height / heightofimagelatitude));
    var my=new Array();
    my['x']=x.toFixed(0);
    my['y']=y.toFixed(0);
    return my; 
} 

function getpoint(angle, distance, lat, lon, measure) {

if (measure == "nm") {
	R = 3444; // earth's mean radius in nautical miles
} else if (measure == "km") {
	R = 6372.797; // earth's mean radius in kilometers
} else {
	R = 3956; // earth's mean radius in miles (default)
}

 var lat1 = deg2rad(lat), lon1 = deg2rad(lon);
 brng = deg2rad(angle);
 d = distance;

 var lat2 = Math.asin( Math.sin(lat1)*Math.cos(d/R) + 
                        Math.cos(lat1)*Math.sin(d/R)*Math.cos(brng) );

 var lon2 = lon1 + Math.atan2(Math.sin(brng)*Math.sin(d/R)*Math.cos(lat1), 
                               Math.cos(d/R)-Math.sin(lat1)*Math.sin(lat2));

 lon2 = (lon2+Math.PI)%(2*Math.PI) - Math.PI;  // normalise to -180...+180

 if (isNaN(lat2) || isNaN(lon2)) return null;
 
p2_lat = rad2deg(lat2);
p2_lon = rad2deg(lon2);
return;
}

function abs (mixed_number) {
    return Math.abs(mixed_number) || 0;
}

function atan2(y, x) {
    return Math.atan2(y, x);
}

function asin(arg) {
    return Math.asin(arg);
}

function sin(arg) {
    return Math.sin(arg);
}

function deg2rad(angle) {
    return (angle / 180) * Math.PI;
}

function cos(arg) {
    return Math.cos(arg);
}

function acos(arg) {
    return Math.acos(arg);
}

function rad2deg (angle) {
    return (angle / Math.PI) * 180;
}

});
