//NOTICE:  This computer software was prepared by Battelle Energy Alliance, LLC and [Insert Author Name(s)], 
//hereinafter the Contractor, under Contract No. DE-AC07-05ID14517 with the United States (U.S.) Department of Energy (DOE).  
//All rights in the computer software are reserved by DOE on behalf of the United States Government and the Contractor as provided in the Contract. 
//You are authorized to use this computer software for Governmental purposes but it is not to be released or distributed to the public. 
//NEITHER THE GOVERNMENT NOR THE CONTRACTOR MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. 
//This notice including this sentence must appear on any copies of this computer software.
//
//create the Cross-browser chart script for skystream wind turbine
//author: Mark McKay © 2009

var myURL = 'http://wind-for-schools.caesenergy.org/phpCurrentWindData.php';
var globwind = [];
var globpower = [];
var globenergy = [];
var globrpm = [];
var globmyUTCdate = [];
var plot;
var overview;
var options;
var powerDataOptions;
var energyDataOptions;
var markings = [];
var windClick = 0;
var RPMClick = 0;
var engClick = 0;
//var ip = location.host;
//var ipStr = new java.lang.String(ip);
        
$(function (){
    
    getFile();
    
    
    var month=new Array(12);month[0]="January"; month[1]="February";    month[2]="March";
                            month[3]="April";   month[4]="May";         month[5]="June";
                            month[6]="July";    month[7]="August";      month[8]="September";
                            month[9]="October"; month[10]="November";   month[11]="December";
            var currentDate = new Date();
            var currentMonth = currentDate.getMonth();            
            var browserName = navigator.appName;
        
            if(currentMonth != 0) lastMonth = currentMonth -1;
            else lastMonth = 11;
                $("#month").text(month[currentMonth]);
                $("#lastmonth").text(month[lastMonth]);
            //}

    // helper for returning the weekends in a period

   
        options = {
        xaxis: { mode: 'time'}, selection: { mode: "xy" }, yaxis: { min: 0,tickFormatter: function (v, axis) { return v.toFixed(axis.tickDecimals) +"W" } }, legend: { position: 'nw' } ,
        selection: { mode: "xy" },
        grid: {
        color: "", backgroundColor: "#E7E7EF",tickColor: "silver", borderWidth: 1, clickable: true, hoverable: true,
        markings: weekendAreas
        }        
    };
    
    powerDataOptions = "lines: { show: true },points:{show: true, radius: 1}, label: 'Power' ";
    
    
     plot = $.plot($("#placeholder"), [{ data: globpower, lines: { show: true },points:{show: true, radius: 1}, label: "Power" }], options);
    
     overview = $.plot($("#overview"), [globpower], {
        lines: { show: true, lineWidth: 1 },
        shadowSize: 0,
        xaxis: { ticks: [], mode: "time" },
        yaxis: { ticks: [], min: 0, max: 3000 },
        selection: { mode: "x" }
        
    });

    // now connect the two
    
    $("#placeholder").bind("plotselected", function (event, ranges) {
        // do the zooming
        plot = $.plot($("#placeholder"), [{ data: globpower, lines: { show: true },points:{show: true, radius: 1}, label: "Power" }],
                      $.extend(true, {}, options, {
                          xaxis: { min: ranges.xaxis.from, max: ranges.xaxis.to },
                          yaxis: { min: ranges.yaxis.from, max: ranges.yaxis.to }
                      }));

        // don't fire event on the overview to prevent eternal loop
        overview.setSelection(ranges, true);
    });
    
    $("#overview").bind("plotselected", function (event, ranges) {
        plot.setSelection(ranges);
    });
    
    function showTooltip(x, y, contents) {
        $('<div id="tooltip">' + contents + '</div>').css( {
            position: 'absolute',
            display: 'none',
            top: y + 5,
            left: x + 5,
            border: '1px solid #fdd',
            padding: '2px',
            'background-color': '#fee',
            opacity: 0.80
        }).appendTo("body").fadeIn(200);
    }

    var previousPoint = null;
    $("#placeholder").bind("plothover", function (event, pos, item) {
    var d = new Date((pos.x)+25200000);//account for out time zone
    $("#x").text(d.getHours()+":"+d.getMinutes());
        $("#y").text(pos.y.toFixed(2));

        if (item) {
        var dd = new Date((item.datapoint[0])+25200000);//account for out time zone
             $("#plotPoint").text(item.series.label +": Data Pt->"+ item.dataIndex + 
             "@ Time:" +(dd.getHours())+"Hrs.:"+(dd.getMinutes())+ "Min"+
             ", Y axis:" +(item.datapoint[1]));
        } else {
            $("#testDate").text("item ...");
        }

        if ($("#enableTooltip:checked").length > 0) {
            if (item) {
                if (previousPoint != item.datapoint) {
                    previousPoint = item.datapoint;
                    
                    $("#tooltip").remove();
                    var x = item.datapoint[0].toFixed(2),
                        y = item.datapoint[1].toFixed(2);
                    
                    showTooltip(item.pageX, item.pageY,
                                item.series.label + " of " + x + " = " + y);
                }
            }
            else {
                $("#tooltip").remove();
                previousPoint = null;            
            }
        }
    });

    $("#placeholder").bind("plotclick", function (event, pos, item) {
        if (item) {
            plot.highlight(item.series, item.datapoint);
        }
    });


   $("#placeholder2").bind("plotclick", function (event, pos, item) {
        
            if(RPMClick == 0) {
                RPMClick = 1;
            if(windClick > 0) windClick = 0;
            if(engClick > 0) engClick = 0;
            } else {
                RPMClick = 0;
            }
            doPlot();
       
    });

   $("#placeholder3").bind("plotclick", function (event, pos, item) {
        
            if(windClick == 0) {
                windClick = 1;
            if(RPMClick > 0) RPMClick = 0;
            if(engClick > 0) engClick = 0;

            } else {
                windClick = 0;
            }
            doPlot();
    });
    
   $("#placeholder4").bind("plotclick", function (event, pos, item) {
        
            if(engClick == 0) {
                engClick = 1;
            if(RPMClick > 0) RPMClick = 0;
            if(windClick > 0) windClick = 0;

            } else {
                engClick = 0;
            }
            doPlot();
    });


//*********hover end
    
    
});


function weekendAreas(axes) {
        var d = new Date(axes.xaxis.min);
        // go to the first Saturday
        d.setUTCDate(d.getUTCDate() - ((d.getUTCDay() + 1) % 7))
        d.setUTCSeconds(0);
        d.setUTCMinutes(0);
        d.setUTCHours(0);
        var i = d.getTime();
        do {
            // when we don't set yaxis the rectangle automatically
            // extends to infinity upwards and downwards
            markings.push({ xaxis: { from: i, to: i + 2 * 24 * 60 * 60 * 1000 } });
            i += 7 * 24 * 60 * 60 * 1000;
        } while (i < axes.xaxis.max);

        return markings;
}



function doPlot(){
    if(engClick > 0){
		plot = $.plot($("#placeholder"), [ { data: globpower, lines: { show: true },points:{show: true, radius: 0.1}, label: "Power" },{ data: globenergy, label: "Energy", yaxis: 2, color:"green" }],{ xaxis: { mode: 'time'}, selection: { mode: "xy" }, yaxis: { min: 0,tickFormatter: function (v, axis) { return v.toFixed(axis.tickDecimals) +"W" } }, y2axis: { tickFormatter: function (v, axis) { return v.toFixed(axis.tickDecimals) +"KWH" }}, selection: { mode: "xy" }, grid: {color: "", backgroundColor: "#E7E7EF",tickColor: "silver", borderWidth: 1, clickable: true, hoverable: true, markings: weekendAreas}, legend: { position: 'nw' } });
     } else if(windClick > 0){
     plot = $.plot($("#placeholder"), [ { data: globpower, lines: { show: true },points:{show: true, radius: 0.1}, label: "Power" },{ data: globwind, label: "Wind", yaxis: 2, color:"blue" }],{ xaxis: { mode: 'time'}, selection: { mode: "xy" }, yaxis: { min: 0,tickFormatter: function (v, axis) { return v.toFixed(axis.tickDecimals) +"W" } }, y2axis: { tickFormatter: function (v, axis) { return v.toFixed(axis.tickDecimals) +"mph" }}, selection: { mode: "xy" }, grid: {color: "", backgroundColor: "#E7E7EF",tickColor: "silver", borderWidth: 1, clickable: true, hoverable: true, markings: weekendAreas}, legend: { position: 'nw' } });
     if($("#enableTotWind:checked").length > 0) $("#enableTotEnergy:checked").length = 0;
    } else if(RPMClick > 0){
     plot = $.plot($("#placeholder"), [ { data: globpower, lines: { show: true },points:{show: true, radius: 0.1}, label: "Power" },{ data: globrpm, label: "RPM", yaxis: 2, color:"purple" }],{ xaxis: { mode: 'time'}, selection: { mode: "xy" }, yaxis: { min: 0,tickFormatter: function (v, axis) { return v.toFixed(axis.tickDecimals) +"W" } }, y2axis: { tickFormatter: function (v, axis) { return v.toFixed(axis.tickDecimals) +"" }}, selection: { mode: "xy" }, grid: {color: "", backgroundColor: "#E7E7EF",tickColor: "silver", borderWidth: 1, clickable: true, hoverable: true, markings: weekendAreas}, legend: { position: 'nw' } });
    } else {
     plot = $.plot($("#placeholder"), [ { data: globpower, lines: { show: true },points:{show: true, radius: 0.1}, label: "Power" }], { xaxis: { mode: 'time'}, selection: { mode: "xy" }, yaxis: { min: 0,tickFormatter: function (v, axis) { return v.toFixed(axis.tickDecimals) +"W" } }, selection: { mode: "xy" }, grid: {color: "", backgroundColor: "#E7E7EF",tickColor: "silver", borderWidth: 1, clickable: true, hoverable: true, markings: weekendAreas}, legend: { position: 'nw' } });
    }
    $.plot($("#placeholder2"), [ {data: globrpm, lines: { show: true, lineWidth: 1 }, label: "RPM",color:"purple"} ], { shadowSize: 0, xaxis: { mode: 'time' },  grid: {color: "", backgroundColor: "#E7E7EF",tickColor: "silver", markings: weekendAreas, clickable: true}, legend: {position: 'nw',  backgroundOpacity: 0.8}});
    $.plot($("#placeholder3"), [ {data: globwind,lines: { show: true, lineWidth: 1 }, label: "Wind Speed (mph)",color:"blue"} ], { shadowSize: 0, xaxis: { mode: 'time' },grid: {color: "", backgroundColor: "#E7E7EF",tickColor: "silver", markings: weekendAreas, clickable: true}, legend: {position: 'nw',  backgroundOpacity: 0.8}});
    $.plot($("#placeholder4"), [ {data: globenergy,lines: { show: true, lineWidth: 1 }, label: "Energy KWH",color:"green"} ], { shadowSize: 0, xaxis: { mode: 'time' },grid: {color: "", backgroundColor: "#E7E7EF",tickColor: "silver", markings: weekendAreas, clickable: true}, legend: {position: 'nw',  backgroundOpacity: 0.8}});

     overview = $.plot($("#overview"), [globpower], {lines: { show: true, lineWidth: 1 }, shadowSize: 0, xaxis: { ticks: [], mode: "time" }, yaxis: { ticks: [], min: 0 }, selection: { mode: "x" } });


};

function upDate(){
    getFile();
    return;
};

function getFile() {
    params = getUrlVars();
	var myParams = "?"+params[0]+"="+params[params[0]]+"&"+params[1]+"="+params[params[1]]+"&"+params[2]+"="+params[params[2]];

       var tempElement = document.getElementById('enableURL').value;
    if(tempElement.length > 0){
        myURL = 'http://';
        myURL += document.getElementById('enableURL').value;
        myURL += '/';
    } else {
        //myURL = 'http://69.20.174.50/';
        myURL = '';
        var myHostName = location.host;
        if(myHostName.length > 0){
         myURL = 'http://';
         myURL += location.host;
         myURL += '/';
        }

    }
    
	var urlShort = 'http://wind-for-schools.caesenergy.org/phpCurrentWindData.php';
	var pURL = urlShort+myParams;
	var displayShortURL = urlShort.split('/');

	
    var d = new Date();
    var curMonth = d.getMonth();
    var curYear = d.getFullYear();
	
   
    if($("#enableMonth:checked").length > 0){
        curMonth = (curMonth < 10 ? "0" : "") + curMonth;
        //var pURL = myURL+'tenminaverage_ss'+curYear+'_'+curMonth+'.csv';
    } else {
        curMonth += 1;
        curMonth = (curMonth < 10 ? "0" : "") + curMonth;
        //var pURL = myURL+'tenminaverage_ss'+curYear+'_'+curMonth+'.csv';
    }
    
    //document.getElementById('theData').innerHTML=displayShortURL[2];
	document.getElementById('currentTurbine').innerHTML=params[params[0]];

var pFunc = 'parseData';
    if (window.XMLHttpRequest) { // code for Mozilla, Safari, etc 
        xmlhttp=new XMLHttpRequest();
        eval('xmlhttp.onreadystatechange='+pFunc+';');
        xmlhttp.open("GET", pURL, true); // leave true for Gecko
        xmlhttp.send(null);
    } else if (window.ActiveXObject) { //IE 
        xmlhttp=new ActiveXObject('Microsoft.XMLHTTP'); 
        if (xmlhttp) {
            eval('xmlhttp.onreadystatechange='+pFunc+';');
            xmlhttp.open('GET', pURL, false);
            xmlhttp.send();
        }
    }

	return;
}

//data format in tenminaverage_ss2009_MM.csv file = "Date, Power(watts), RPM, Wind(meters/sec), Total Energy(Watt-Hrs)"


function parseData() {
	
	var d = new Date();
    
	var myTimeZone = d.getTimezoneOffset() * 60000;
	
	
    if (xmlhttp.readyState==4) { 
        if (xmlhttp.status==200) { 
            var tmpArr=xmlhttp.responseText.split('<br>');
            var tempArray;
            var tempDateArray;
            var tempDate;
            var tempTime;
            var tempHrs;
            var tempMin;
            var tempSec;
			var tmpWind = 0;
			var tmpRPM = 0;
			var tmpPower = 0;
			var tmpUTCdate = 0;
            var power = [];
            var energy = [];
            var rpm = [];
            var wind = [];
            var myUTCdate = [];
            var tempdata = [];
            var out=tmpArr[0];
			var out="";
            var count = 0;
			var myAvgValue = 20;
			var myDataCount = tmpArr.length;
			
			if(myDataCount < 200)myAvgValue = 2;
			else if (myDataCount < 1000) myAvgValue = 10;
			else if (myDataCount < 20000) myAvgValue = 20;
			else if (myDataCount < 50000) myAvgValue = 40;
			else myAvgValue = 50;
			
            for (var idx=0;idx<tmpArr.length;idx++) {
				
                out += '<span style="color:#FF9900; font-weight:bold"> , </span>'+idx +' - '+tmpArr[idx]+'<br>';
                tempArray = tmpArr[idx].split(',');
                //power.push([tempArray[0],tempArray[1]]);
                if(idx >=0){
                    var temp = tempArray[0].split(' ');
                    var temp2 = tempArray[0].split(':');
                    tempTime = temp2[0].split(' ');
                    tempHrs = tempTime[1];
                    tempMin = temp2[1];
                    tempSec = temp2[2];
                    tempDate = temp[0].split('/');
                    count++;
					tmpWind+= (tempArray[7]*2.2369);
					tmpRPM+= (tempArray[6]*1);
					tmpPower+=(tempArray[3]*1);
					
					tmpUTCdate+= (tempArray[1]*1000);
					
                    if((tempArray[2] == 0) && (tempArray[3] == 0)) tempArray[1] = 0;
					
                    if(count > myAvgValue){
						
						tmpWind /= count;
						tmpRPM /= count;
						tmpPower /= count;
						tmpUTCdate /= count;
						count = 0;
                    
						//myUTCdate[idx]=  tmpUTCdate;
						myUTCdate[idx]=  (tempArray[1]*1000);
						power.push([myUTCdate[idx],tmpPower.toFixed(2)]);
						energy.push([myUTCdate[idx],tempArray[5]/1000]);
						rpm.push([myUTCdate[idx],tmpRPM.toFixed(2)]);
						wind.push([myUTCdate[idx],(tmpWind).toFixed(2)]);
						
						//document.getElementById('theData2').innerHTML=tmpArr.length;
						
                    /*
                    myUTCdate[idx]=  (tempArray[1]*1000);
                    power.push([myUTCdate[idx],tempArray[3]]);
                    energy.push([myUTCdate[idx],tempArray[5]/1000]);
                    rpm.push([myUTCdate[idx],tempArray[6]]);
                    wind.push([myUTCdate[idx],(tempArray[7]*2.2369).toFixed(2)]);
					 */
                   }
                }
            }
            globwind = wind;
            globpower = power;
            globenergy = energy;
            globrpm = rpm;
            globmyUTCdate = myUTCdate;
            
			//document.getElementById('theData2').innerHTML=tmpWind;
			
            doPlot();
			document.getElementById('theData').innerHTML="Done";
        }
    }
    
	return;
}


// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
	
    return vars;
}




