
var hoursPerFile = 24.0;
var filetime = new Date();    
var xmlhttp;

var timerID = 0;

function setTimer (mins, url) {
    if (timerID) {
	clearTimeout (timerID);
    }
    timerID = setTimeout ("updateTimer('" + mins + "','" + url + "')", 
			  mins * 60 * 1000);
}


function updateTimer (mins, url) {
    if (timerID) {
	clearTimeout (timerID);
    }

    refreshFilename(url);
    timerID = setTimeout ("updateTimer('" + mins + "','" + url + "')", 
			  mins * 60 * 1000);
}

function setWaitCursor () {
    document.body.style.cursor = "wait";
}

function setDefaultCursor () {
    document.body.style.cursor = "default";
}

function nextFileTime (noOfFiles) {
    var oneFile = 3600*hoursPerFile*1000;
    newtime = filetime.getTime ();
    newtime = filetime.getTime ()+ (oneFile*noOfFiles);
    filetime.setTime (newtime);
}

function displayNextFile (noOfFiles, url) {
    setWaitCursor();
    nextFileTime (noOfFiles);
    var filename = getFileName( filetime, url );
    include (filename);
    setDefaultCursor ();
}

function leadingZero (digit) {
    var val = digit + 0;
    if (val < 10) { val = "0" + val; }
    return val;
}

function displayNowFile (url) {
    setWaitCursor ();
    filetime = new Date();
    var filename = getFileName (filetime, url);
    include (filename);
    setDefaultCursor ();
}

function refreshFilename (url) {
    setWaitCursor ();
    var filename = getFileName (filetime, url);
    include (filename);
    setDefaultCursor ();
}

function getFileName (dateobj, url) {
    var year = dateobj.getFullYear ();
    var month = leadingZero (dateobj.getMonth () + 1);
    var date = leadingZero (dateobj.getDate ());
    var filename = url + "/" + year + month + date + ".csv";
    return filename;
}

function include(pURL) {
    // code for Mozilla, Safari, ** And Now IE 7 **, etc 
    if (window.XMLHttpRequest) { 
	xmlhttp = new XMLHttpRequest ();
    } else if (window.ActiveXObject) {
	xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
    }
    if (typeof (xmlhttp) == 'object') {
	xmlhttp.onreadystatechange = postFileReady;
	xmlhttp.open ('GET', pURL, true);
	xmlhttp.send (null);
    }
}

function postFileReady () {
    if (xmlhttp.readyState == 4) { 
	var textdump = xmlhttp.responseText;
	var textsplit = textdump.split ('\n');
	generateTable (textsplit);
	generateGraph ();
    }
}

function monthSelector (month) {
    var res = "Dec";
    if (1 == month) { res = "Jan"; }
    else if (2 == month) { res = "Feb"; }
    else if (3 == month) { res = "Mar"; }
    else if (4 == month) { res = "Apr"; }
    else if (5 == month) { res = "May"; }
    else if (6 == month) { res = "Jun"; }
    else if (7 == month) { res = "Jul"; }
    else if (8 == month) { res = "Aug"; }
    else if (9 == month) { res = "Sep"; }
    else if (10 == month) { res = "Oct"; }
    else if (11 == month) { res = "Nov"; }
    return res;
}

function generateTable (lines) {

    var setTitle = false;
    var timerTitle = document.getElementById ("graphupdate");
    if (null != timerTitle) {
	var dateobj = new Date();
	timerTitle.innerHTML = leadingZero (dateobj.getHours()) + ":" + 
	    leadingZero (dateobj.getMinutes()) + ":" + leadingZero (dateobj.getSeconds());
    }
    
    var dataStore = document.getElementById ("datatable");
    if (null != dataStore.tBodies[0]) {
	dataStore.removeChild (dataStore.tBodies[0]);
    }
    
    var tbdy = document.createElement ('TBODY');
    dataStore.appendChild (tbdy);
    
    var row = null;	     
    var td = null;
    
    // first line - can ignore first line as header line.
    // date,time, back_twd, avg_twd, veer_twd, min_tws, avg_tws, 
    //    max_tws, sampleSize
    
    // declare variable here - so access last time set.
    var segments = null;

    // YYYY/MM/DD,hh:mm.ss,ddd,ddd,ddd,d.dd,d.dd,dd.dd,dd
    // last column ignored as checksum colunm
    for (var i = 1; i < lines.length; i++) {
	segments = lines[i].split(',');
	row = document.createElement ('TR');
	for (var j = 0; j < segments.length - 1; j++) {
	    td = document.createElement ('TD');
	    if (j == 0) {
		var tsplit = segments[j].split('/');
		var datetext = tsplit[2] + " " + monthSelector(tsplit[1]) + 
		    " " + tsplit[0];
		td.appendChild (document.createTextNode (datetext));

		if (true != setTitle) {
		    setTitle = true;
		    var graphTitle = document.getElementById ("graphtitle");
		    graphTitle.innerHTML = datetext;
		}
	    }
	    else if (j == 1) {
		var tsplit = segments[j].split(':');
		var msplit = tsplit[1].split('.');
		td.appendChild (document.createTextNode (tsplit[0] + ":" + 
							 msplit[0]));
		numberHours = 1 + eval(tsplit[0]);
	    }
	    else {
		td.appendChild (document.createTextNode (segments[j]));
	    }
	    td.setAttribute ("class", "wind");
	    row.appendChild (td);
	    if ((6 == j || 7 == j) && (segments[j] > maximumWind)) {
		while (segments[j] > maximumWind) {
		    maximumWind = maximumWind + 10;
		}
	    }
	    
	}
	tbdy.insertBefore (row, tbdy.firstChild);
    }
}

// data processing constants/variables
var maximumWind = 50;

// all graph drawing constants/variables
var jg = null;

var th = 450;
var tw = 550;

var gh = 135;
var gw = 400;

var spcr = 5;
var numberHours = 0;

var speedSteps = 10;
var timeSteps = 1;

function generateGraph () {
    
    if (null == jg) {
	var canvas = document.getElementById ("chart");
	jg = new jsGraphics ("div_canvas");
    }
    
    jg.clear ();
    jg.setColor ("black");
    jg.setStroke (1);
    
    // draws entire canvas area ....
    //jg.drawLine (0, 0, tw, 0);
    //jg.drawLine (0, th, tw, th);
    //jg.drawLine (0, 0, 0, th);
    //jg.drawLine (tw, 0, tw, th);

    // create image object which is used extensive for image gathering 
    // information like heights widths etc.
    var img = new Image ();

    // draw title for wind speed graph.
    img.src = "img/windspeed.gif";
    jg.drawImage ("img/windspeed.gif", 
		  tw/2-(img.width/2), 0,
		  img.width, img.height, null);

    // defines the top height location of wind speed box.
    var wsHeight = img.height + spcr;

    // defines the X locations for box left and right
    var boxLeft = (tw/2)-(gw/2);
    var boxRight = (tw/2)+(gw/2);

    // draws wind speed box.
    jg.drawLine (boxLeft, wsHeight, boxRight, wsHeight);
    jg.drawLine (boxLeft, wsHeight + gh, boxRight, wsHeight + gh);
    jg.drawLine (boxLeft, wsHeight, boxLeft, wsHeight + gh);
    jg.drawLine (boxRight, wsHeight, boxRight, wsHeight + gh);

    // draws the Y axis - knots.
    jg.setStroke (Stroke.DOTTED);

    // calculates speed step for 1 knot. (sStep)
    var sSteps = gh/maximumWind;

    for (var i = 0; i <= maximumWind; i=i+10) {
	img.src = 'img/' + i + 'k.gif';
	jg.drawImage (img.src, boxLeft - img.width - spcr, 
		      (wsHeight + gh) - (sSteps*i) - (img.height/2),
		      img.width, img.height, null);
	jg.drawLine (boxLeft, (wsHeight + gh) - (sSteps*i), boxRight, 
		     (wsHeight + gh) - (sSteps*i));
    }
    jg.setStroke (1);

    // works out the maximum width of largest knot image.
    var addition = img.width;

    // writes the Y axis label
    img.src = 'img/knots.gif';
    jg.drawImage (img.src, boxLeft - img.width - addition - (spcr*2), 
		  wsHeight + ((gh/2) - (img.height/2)),
		  img.width, img.height, null);

    // draws the X axis - hours
    var hourImg = new Image ();

    // calculates the step for 1 hour (gStep)
    var gStep = gw / numberHours;

    jg.setStroke (Stroke.DOTTED)
    for (var i = 0; i <= numberHours; i++) {
	hourImg.src = 'img/' + i + '.gif';
	jg.drawImage (hourImg.src, boxLeft + gStep*i - hourImg.width/2, 
		      wsHeight + gh + spcr, 
		      hourImg.width, hourImg.height, null);
	jg.drawLine (boxLeft + gStep*i, wsHeight, boxLeft + gStep*i, 
		     wsHeight + gh);
    }
    jg.setStroke (1);

    // writes the X axis label
    img.src = 'img/hours.gif';
    jg.drawImage ('img/hours.gif', (tw/2)-(img.width/2), 
		  wsHeight + gh + hourImg.height + spcr*2, 
		  img.width, img.height, null);

    // draws the title of the wind direction graph
    img.src = "img/winddirection.gif";
    var wdHeight = wsHeight + gh + img.height + spcr*10;
    jg.drawImage (img.src, tw/2-(img.width/2), wdHeight, 
		  img.width, img.height, null);

    // defines the top height location of wind direction box.
    wdHeight = wdHeight + img.height + spcr;

    // draws the boundary of the wind direction box.
    jg.drawLine (boxLeft, wdHeight, boxRight, wdHeight);
    jg.drawLine (boxLeft, wdHeight + gh, boxRight, wdHeight + gh);
    jg.drawLine (boxLeft, wdHeight, boxLeft, wdHeight + gh);   
    jg.drawLine (boxRight, wdHeight, boxRight, wdHeight + gh);

    // draws the X axis - hours
    jg.setStroke (Stroke.DOTTED);
    for (var i = 0; i <= numberHours; i++) {
	hourImg.src = 'img/' + i + '.gif';
	jg.drawImage (hourImg.src, boxLeft + gStep*i - hourImg.width/2, 
		      wdHeight + gh + spcr, 
		      hourImg.width, hourImg.height, null);
	jg.drawLine (boxLeft + gStep*i, wdHeight, boxLeft + gStep*i, 
		     wdHeight + gh);
    }
    jg.setStroke (1);

    // draws the X axis label
    img.src = "img/hours.gif";
    jg.drawImage (img.src, (tw/2)-(img.width/2), 
		  wdHeight + gh + hourImg.height + spcr*2, 
		  img.width, img.height, null);

    // draws the Y axis
    jg.setStroke (Stroke.DOTTED);
    for (var i = 0; i <= 360; i=i+90) {
	img.src = 'img/' + i + 'd.gif';
	jg.drawImage (img.src, 
		      boxLeft - img.width - spcr, 
		      wdHeight + gh - ((gh/(360/90))*(i/90)) - (img.height/2), 
		      img.width, img.height, null);

	jg.drawLine (boxLeft, wdHeight + gh - ((gh/(360/90))*(i/90)), 
		     boxRight, wdHeight + gh - ((gh/(360/90))*(i/90)));

	// works out the maximum width of largest image left
	addition = img.width;

	if (i == 0 || i == 360) { img.src = 'img/n.gif'; }
	else if (i == 90) { img.src = 'img/e.gif'; }
	else if (i == 180) { img.src = 'img/s.gif'; }
	else if (i == 270) { img.src = 'img/w.gif'; }
	jg.drawImage (img.src, boxRight + spcr, 
		      wdHeight + gh - ((gh/(360/90))*(i/90)) - (img.height/2), 
		      img.width, img.height, null);
    }
    jg.setStroke (1);

    // work out maximum width of largest image right.
    var addition1 = img.width;

    // writes the Y axis label - left
    img.src = 'img/degrees.gif';
    jg.drawImage (img.src, boxLeft - img.width - addition - (spcr*2), 
		  wdHeight + ((gh/2) - (img.height/2)),
		  img.width, img.height, null);

    // writes the Y axis label - right
    img.src = 'img/bearings.gif';
    jg.drawImage (img.src, boxRight + addition + spcr, 
		  wdHeight + ((gh/2) - (img.height/2)),
		  img.width, img.height, null);

    // define arrays
    // this will be the only instance of speed X points as only expect 
    // linear changes.
    var speedXPoints = [];
    // could be many instances due to bearing fluxing around 360/0
    var directionXPoints = [];

    // this two array for collecting avg and max wind speeds.
    var avgWindPoints = [];
    var maxWindPoints = [];

    // again could be many instances due to bearing fluxing around 360/0
    var dirWindPoints = [];
    
    data = document.getElementById ("datatable");

    jg.setStroke (Stroke.DOTTED);
    jg.setColor ("green");
    
    var rowcount = 0;
    var lastpoint = null;
    var dRowCount = 0;

    for (var r = 0; r < data.tBodies[0].rows.length; r++) {
	var row = data.rows[r];
	
	if (row.cells[1] != null && row.cells[1].innerHTML != "Time") {
	    // col: 0 - data
	    
	    // col:1 - calculates the X Position (Time) (FORMAT: HH:MM.SS)
	    var timecol = row.cells[1].innerHTML.split (':');		
	    var hour = timecol[0];
	    var min = timecol[1].split('.')[0];
	    // hour calculation   minuate calculation       offset calculation
	    speedXPoints[rowcount] = (gStep*hour) + ((gStep/60)*min) + boxLeft;
	    
	    // col:2 - backing
	    
	    // col:3 - average bearing
	    var val = row.cells[3].innerHTML;	   
	    // if fluxing around 360/0 then draw line and reset arrays.
	    if (null != lastpoint && ((lastpoint < 45 && val > 315) 
				      || (lastpoint > 315 && val < 45))) {

		directionXPoints[dRowCount] = speedXPoints[rowcount];
		// so if last point was 0+ then create last point on o line
		if (lastpoint < 45 && val > 315) { 
		    dirWindPoints[dRowCount] = wdHeight + gh; 
		}
		// si if last point was 360- then create last point on 360 line
		else { dirWindPoints[dRowCount] = wdHeight; }

		jg.drawPolyline (directionXPoints, dirWindPoints);
		directionXPoints = null; dirWindPoints = null;
		directionXPoints = []; dirWindPoints = [];
		dRowCount = 0;

		directionXPoints[dRowCount] = speedXPoints[rowcount];
		// so if last point was 0+ then create first point on 360 line
		if (lastpoint < 45 && val > 315) { 
		    dirWindPoints[dRowCount++] = wdHeight; 
		}
		// so if last point was 360- then create first point on 0 line
		else { dirWindPoints[dRowCount++] = wdHeight + gh; }

		lastpoint = null;
		
	    }

	    directionXPoints[dRowCount] = speedXPoints[rowcount];
	    dirWindPoints[dRowCount++] = wdHeight + gh - ((gh/360)*val);
	    lastpoint = val;
	    
	    // col:4 - veering
	    
	    // col:5 - min wind strength
	    
	    // col:6 - average wind strength
	    avgWindPoints[rowcount] = (wsHeight + gh) - 
		(sSteps * (row.cells[6].innerHTML));
	    
	    // col:7 - maximum wind strength
	    maxWindPoints[rowcount++] = (wsHeight + gh) - 
		(sSteps * (row.cells[7].innerHTML));
	}
    }

    // draw final direction lines.
    jg.drawPolyline (directionXPoints, dirWindPoints);

    // check checkbox then draw max wind points.
    var toggle = document.getElementById ("ckbMaxWind");
    if (true == toggle.checked) {
	jg.setColor ("red");
	jg.drawPolyline (speedXPoints, maxWindPoints);
    }

    // check checkbox then draw avg wind points.
    toggle = document.getElementById ("ckbAvgWind");
    if (true == toggle.checked) {
	jg.setColor ("blue");
	jg.drawPolyline (speedXPoints, avgWindPoints);
    }

    // render - hopefully.
    jg.paint ();
}

