//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://69.20.174.50/';
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 filter = 1;
var displayMonth = 0;
var chartType = 1;
var browserInfo;

//var ip = location.host;
//var ipStr = new java.lang.String(ip);
        
$(function (){
    var monthlist=document.months.SelectMonth;
    browserInfo = navigator;
    
    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]);
                $("#month2").text(month[currentMonth]);
                $("#lastmonth2").text(month[lastMonth]);

            //}
    //monthlist.options.length=0;
    
    monthlist.options.length=currentMonth+1;
    monthlist.options[currentMonth+1] = new Option(month[currentMonth], currentMonth+1, false, true);
    // 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}, label: 'Power' ";
     plot = $.plot($("#placeholder"), [{ data: globpower, lines: { show: true },points:{show: true}, 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}, 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)+21600000);//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])+21600000);//account for out time zone
             $("#plotPoint").text(item.series.label +": pt->"+ item.dataIndex + 
             "@ x:" +(dd.getHours())+"Hrs.:"+(dd.getMinutes())+ "Min"+
             ", y:" +(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}, 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}, 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}, 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}, 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();
    doPlot();
    return;
};

function getFile() {
    
       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 = 'skystream.d261.k12.id.us';
        myURL = '';
        var myHostName = location.host;
        if(myHostName.length > 0){
         myURL = 'http://';
         myURL += location.host;
         myURL += '/';
        }

    }
    
    var d = new Date();
    var curMonth = d.getMonth();
    var curYear = d.getFullYear();
    displayMonth = curMonth+1;
    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=pURL;

var pFunc = 'parseData';
    if (window.XMLHttpRequest) { // code for Mozilla, Safari, etc 
        xmlhttp=new XMLHttpRequest();
        if(BrowserDetect.browser !="Safari"){
        try {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
        } catch (e) {
            alert("Permission could be denied for cross-browser scripting.");
        }
        }
        eval('xmlhttp.onreadystatechange='+pFunc+';');
        if(BrowserDetect.browser =="Safari") xmlhttp.open("GET", pURL, false); // leave true for Gecko
        else xmlhttp.open("GET", pURL,true); // leave true for Gecko
        //xmlhttp.setRequestHeader("User-Agent",navigator.userAgent);
        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();
        }
    }
    //XMLHttpRequestDemo(pURL);
	return;
}

//function XMLHttpRequestDemo(sURL) {
// var oRequest = new XMLHttpRequest();
   //var sURL  = "http://69.20.174.50/mostcurrentwindturbine.csv";
   //var sURL = "http://69.20.174.50/tenminaverage_ss2009_06.csv";

// oRequest.open("GET",sURL,false);
// oRequest.setRequestHeader("User-Agent",navigator.userAgent);
// oRequest.send(null)

// if (oRequest.status==200||oRequest.status==0) parseData(oRequest.responseText);
// else alert("Error executing XMLHttpRequest call!");}



//data format in tenminaverage_ss2009_MM.csv file = "Date, Power(watts), RPM, Wind(meters/sec), Total Energy(Watt-Hrs)"


function parseData() {
    try{if (xmlhttp.status==404) document.getElementById('theData').innerHTML="file does not exist";
    }catch(e){
    }
    if (xmlhttp.readyState==4) { 
        if (xmlhttp.status==200) { 
            var avgCounter=0;
            var tmpArr=xmlhttp.responseText.split('\n');
            var tempArray = new Array();
            var tempDateArray;
            var tempDate;
            var tempTime;
            var tempHrs;
            var tempMin;
            var tempSec;
            var power = [];
            var energy = [];
            var rpm = [];
            var wind = [];
            var myUTCdate = [];
            var tempdata = [];
            var out=tmpArr[0];
			var out="";
            var tempPower=0.0;
            var tempEnergy=0.0;
            var tempRPM=0.0;
            var tempWind=0.0;
            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('/');
                    
                    myUTCdate[idx]= Date.UTC(tempDate[2],(tempDate[0]-1),tempDate[1],tempHrs,tempMin,tempSec);
                    if((tempArray[2] == 0) && (tempArray[3] == 0)) tempArray[1] = 0;
                    
                    try{
                        tempPower += parseFloat(tempArray[1].valueOf());
                        tempEnergy += parseFloat(tempArray[4].valueOf())/1000;
                        tempRPM += parseFloat(tempArray[2].valueOf());
                        tempWind += parseFloat(tempArray[3].valueOf())*2.2369;
                        //alert(tempPower);
                    }catch (e){
                    //alert(tempWind+", "+idx);
                    //avgCounter = filter;
                    }
                    
                    
                    //document.getElementById('theData2').innerHTML=tempPower.toFixed(2);
                    
                    if(avgCounter >= filter){

                    //power.push([myUTCdate[idx],parseFloat(tempArray[1]).toFixed(2)]);
                    energy.push([myUTCdate[idx],tempArray[4]/1000]);
                    //rpm.push([myUTCdate[idx],tempArray[2]]);
                    //wind.push([myUTCdate[idx],(tempArray[3]*2.2369).toFixed(2)]);
                    
                    power.push([myUTCdate[idx],tempPower/avgCounter]);
                    //energy.push([myUTCdate[idx],tempEnergy/avgCounter]);
                    rpm.push([myUTCdate[idx],tempRPM/avgCounter]);
                    wind.push([myUTCdate[idx],tempWind/avgCounter]);
                    
                    
                    avgCounter = 0;
                    tempPower=0.0;
                    //tempEnergy=0.0;
                    tempRPM=0.0;
                    tempWind=0.0;
                
                    }
                    avgCounter += 1;
                   
                }
            }
            globwind = wind;
            globpower = power;
            globenergy = energy;
            globrpm = rpm;
            globmyUTCdate = myUTCdate;
            //alert(power);
            //document.getElementById('theData2').innerHTML=tempPower.toFixed(2)+", "+tempEnergy.toFixed(2)+", "+tempRPM.toFixed(2)+", "+tempWind.toFixed(2);                        
            doPlot();

        }
    }
    
	return;
}

function getData(month){
    displayMonth = month;
       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 = 'skystream.d261.k12.id.us';
        myURL = '';
        var myHostName = location.host;
        if(myHostName.length > 0){
         myURL = 'http://';
         myURL += location.host;
         myURL += '/';
        }

    }
    
    var d = new Date();
    var curMonth = d.getMonth();
    var curYear = d.getFullYear();
   
    if(month == "0"){
        curMonth += 1;
        curMonth = (curMonth < 10 ? "0" : "") + curMonth;
        var pURL = myURL+'tenminaverage_ss'+curYear+'_'+curMonth+'.csv';
    } else {
        curMonth = month;
        curMonth = (curMonth < 10 ? "0" : "") + curMonth;
        var pURL = myURL+'tenminaverage_ss'+curYear+'_'+curMonth+'.csv';
    }
    
    document.getElementById('theData').innerHTML=pURL;

var pFunc = 'parseData';
    if (window.XMLHttpRequest) { // code for Mozilla, Safari, etc 
        xmlhttp=new XMLHttpRequest();
        if(BrowserDetect.browser !="Safari"){
        try {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
        } catch (e) {
            alert("Permission could be denied for cross-browser scripting.");
        }
        }
        eval('xmlhttp.onreadystatechange='+pFunc+';');
        if(BrowserDetect.browser =="Safari") xmlhttp.open("GET", pURL, false); // leave true for Gecko
        else 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();
        }
    }

//alert(month+": worked");
return;
}

function setFilter(f){
filter = f;
//alert(displayMonth);
getData(displayMonth);
return;
}

function setPlotType(t){
chartType = t;
//alert(chartType);
getData(displayMonth);
return;

}


var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

