/*
	www.i-weather.org JavaScript main file
	Copyright (c) 2010 fabric | ch
	Author Stephane Carion
	Version   2.1,  20.06.2010

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>
*/


//Init global variables
if (typeof(iweatherCss)!="number") iweatherCss=1;
if (typeof(iweatherTwinkle)!="number") iweatherTwinkle=1;
if (typeof(iweatherTwinkleCount)!="number") iweatherTwinkleCount=40;		// Number of 'blinks'
if (typeof(iweatherTwinkleDelay)!="number") iweatherTwinkleDelay=30;		// Delay (in sec.) between twinkles
	
var iweatherStartDate = new Date(Date.UTC(2001, 9, 26, 5, 0, 0)); 		// Month is 0-11 in JavaScript, iweather start time is 26-oct-2001, 11am at GMT+1, so 10am at UTC
var iweatherTime=new Array();
var iweatherValues=new Array();
iweatherValues['init']=false;
var iweatherTwinkleCountIntern=iweatherTwinkleCount;
iweatherTime.push(Array(js_getTimeValue("00:00:00"),255,215,0,102));
iweatherTime.push(Array(js_getTimeValue("00:30:00"),255,215,0,102));
iweatherTime.push(Array(js_getTimeValue("04:10:05"),255,255,0,102));
iweatherTime.push(Array(js_getTimeValue("05:10:05"),155,255,55,102));
iweatherTime.push(Array(js_getTimeValue("06:10:05"),0,255,255,102));
iweatherTime.push(Array(js_getTimeValue("12:03:50"),70,235,255,102));
iweatherTime.push(Array(js_getTimeValue("13:03:50"),70,235,255,102));
iweatherTime.push(Array(js_getTimeValue("18:57:35"),0,255,255,102));
iweatherTime.push(Array(js_getTimeValue("19:57:35"),155,255,55,102));
iweatherTime.push(Array(js_getTimeValue("20:57:35"),255,255,0,102));
iweatherTime.push(Array(js_getTimeValue("24:37:40"),255,215,0,102));
iweatherTime.push(Array(js_getTimeValue("25:07:40"),255,215,0,102));

js_addLoadEvent(function() {js_initIweather()});

function js_addLoadEvent(func) {
	var onload = window.onload;
	window.onload = function() {
		if (onload) {
			onload();
		}
		func();
	}
}

function js_initIweather() {
	js_setIweatherValues();
	js_setIweatherContents();
	if (iweatherCss) js_iweatherCss();
	if (iweatherTwinkle) setTimeout("js_iweatherTwinkle()",1000+Math.round(Math.random()*iweatherTwinkleDelay*1000));
}

function js_setIweatherValues() {
	// Initialize the iweatherValues array and repeat it every seconds
	iweatherValues=js_getIweatherValues();
	iweatherValues['init']=true;
	setTimeout("js_setIweatherValues()",1000);
}

function js_iweatherCss() {
	if (iweatherValues['init']) {
		var nodes=document.getElementsByTagName('style');
		var found=-1;
		for (var n=0;(n<nodes.length && found==-1);n++) if(nodes[n].getAttribute('title')=='i-weather') found=n;
		if (found==-1) {
			var style=document.createElement('style');
			style.setAttribute('type','text/css');
			style.setAttribute('title','i-weather');
		} else {
			var style=nodes[found];
		}
		var content='';
		content+='body {background-color: '+iweatherValues['iweatherColorHex']+'; color: '+iweatherValues['greyColorHex']+';}\n';
		content+='a {color: '+iweatherValues['greyColorHex']+';}\n';
		content+='.iweatherColor { color: '+iweatherValues['iweatherColorHex']+';}\n';
		content+='.iweatherGreyColor { color: '+iweatherValues['greyColorHex']+';}\n';
		content+='.iweatherBgColor { background-color: '+iweatherValues['iweatherColorHex']+';}\n';
		if (style.styleSheet) {
			style.styleSheet.cssText=content;							// IE
		} else {
			style.textContent=content;									// FireFox
		}
		if (found==-1) document.getElementsByTagName('head')[0].appendChild(style);
		setTimeout("js_iweatherCss()",10000);							// Changing the CSS every 10 seconds
	}
}
function js_setIweatherContents() {
	if (iweatherValues['init']) {
		if (node=document.getElementById('iweather_Days')) {
			node.innerHTML=""+iweatherValues['days'];
		}
		if (node=document.getElementById('iweather_Time')) {
			node.innerHTML=""+iweatherValues['time'];
		}
		if (node=document.getElementById('iweather_LocalDate')) {
			node.innerHTML=""+iweatherValues['localDate'];
		}
		if (node=document.getElementById('iweather_LocalTime')) {
			node.innerHTML=""+iweatherValues['localTime'];
		}
		if (node=document.getElementById('iweather_Nanometers')) {
			node.innerHTML=""+iweatherValues['nanometers'];
		}
	}
	setTimeout("js_setIweatherContents()",1000)
}
function js_iweatherTwinkle() {
	if (iweatherValues['init']) {
		iweatherTwinkleCountIntern=iweatherTwinkleCount;
		js_startIweatherTwinkle();
		setTimeout("js_iweatherTwinkle()",1000+Math.round(Math.random()*iweatherTwinkleDelay*1000));
	}
}
function js_startIweatherTwinkle() {
	if (iweatherTwinkleCountIntern>0) {
		iweatherTwinkleCountIntern--;
		if (iweatherTwinkleCountIntern%2) { 
			color="#"+js_DecToHex(iweatherValues['iweatherColorArray'][0]+iweatherTwinkleCountIntern)+js_DecToHex(iweatherValues['iweatherColorArray'][1]+iweatherTwinkleCountIntern)+js_DecToHex(iweatherValues['iweatherColorArray'][2]+iweatherTwinkleCountIntern);
		} else {
			color="#"+js_DecToHex(iweatherValues['iweatherColorArray'][0]-iweatherTwinkleCountIntern)+js_DecToHex(iweatherValues['iweatherColorArray'][1]-iweatherTwinkleCountIntern)+js_DecToHex(iweatherValues['iweatherColorArray'][2]-iweatherTwinkleCountIntern);
		}
		document.getElementsByTagName('body')[0].style.backgroundColor=color;
		setTimeout("js_startIweatherTwinkle()",8);
	}
}
function js_getIweatherValues() {
	// Returns an array with iweather values
	var result=new Array();
	var todayDate = new Date();
	result['todayDate']=todayDate;
	var diffSeconds=(todayDate.getTime()-iweatherStartDate.getTime())/1000;		//Difference in seconds
	result['diffSeconds']=diffSeconds;
	var days=parseInt( diffSeconds / iweatherTime[iweatherTime.length-1][0] );
	result['days']=days;
	var percent=parseFloat( (diffSeconds % iweatherTime[iweatherTime.length-1][0]) / iweatherTime[iweatherTime.length-1][0] * 100 );
	result['percent']=percent;
	var hours=parseInt( (diffSeconds % iweatherTime[iweatherTime.length-1][0]) /60/60 );
	result['hours']=hours;
	var minutes=parseInt( (diffSeconds % iweatherTime[iweatherTime.length-1][0]) /60 );
	result['minutes']=minutes%60;
	var seconds=parseInt( (diffSeconds % iweatherTime[iweatherTime.length-1][0]) );
	result['seconds']=seconds%60;
	
	// Other usefull values
	result['time']=js_leadingZero(result['hours'],2)+":"+js_leadingZero(result['minutes'],2)+":"+js_leadingZero(result['seconds'],2);		//Like: 09:34:56
	result['localDate']=js_leadingZero(result['todayDate'].getDate(),2)+"."+js_leadingZero(result['todayDate'].getMonth()+1,2)+"."+result['todayDate'].getFullYear();		//Like: 25.12.1970
	result['localTime']=js_leadingZero(result['todayDate'].getHours(),2)+":"+js_leadingZero(result['todayDate'].getMinutes(),2)+":"+js_leadingZero(result['todayDate'].getSeconds(),2)		//Like 23:59:00
	
	var index=-1;	
	for ( var i=1;i<iweatherTime.length;i++ ) {
		if (seconds>=iweatherTime[i-1][0] && seconds<iweatherTime[i][0]) {
			index=i;
			var coef=(seconds-iweatherTime[i-1][0])/(iweatherTime[i][0]-iweatherTime[i-1][0]);
			var RGBA=new Array();
			for (var j=0;j<4;j++) RGBA[j]=parseInt(iweatherTime[i-1][j+1]+coef*(iweatherTime[i][j+1]-iweatherTime[i-1][j+1]));
		}
	}
	result['index']=index;
	if (index>0) {
		result['iweatherColorHex']="#"+js_DecToHex(RGBA[0])+js_DecToHex(RGBA[1])+js_DecToHex(RGBA[2]);
		result['inColorHex']="#"+js_DecToHex(256-RGBA[0])+js_DecToHex(256-RGBA[1])+js_DecToHex(256-RGBA[2]);
		result['greyColorHex']="#"+js_DecToHex(RGBA[3])+js_DecToHex(RGBA[3])+js_DecToHex(RGBA[3]);
		result['iweatherColorArray']=Array(RGBA[0],RGBA[1],RGBA[2]);
		result['coef']=coef;
		result['secondsTotal']=seconds;
		result['previous']=Array(iweatherTime[index-1][1],iweatherTime[index-1][2],iweatherTime[index-1][3]);
		result['next']=Array(iweatherTime[index][1],iweatherTime[index][2],iweatherTime[index][3]);
		//nanometers: 597nm at 0%, 460 at 50%, 597 at 100% ->
		if (percent<50) result['nanometers']=parseInt((460-597)*2*percent/100+597); else result['nanometers']=parseInt((597-460)*2*(percent-50)/100+460);
	} 
	return result;
}
function js_getIweatherTable(id) {
	if (iweatherValues['init'] && (node=document.getElementById(id))) {
		node.innerHTML="";
		var content="";
		var table=document.createElement("table");
		table.setAttribute("style","width:100%;height:20px;border:1px solid #000000;border-collapse:collapse;margin-bottom:5px;");
		var tr=document.createElement("tr");
		for (i=0;i<iweatherTime.length-1;i++) {
			td=document.createElement("td")
			var RGBA=new Array();
			for (var j=0;j<4;j++) RGBA[j]=parseInt(iweatherTime[i][j+1]);
			iweatherColor="#"+js_DecToHex(RGBA[0])+js_DecToHex(RGBA[1])+js_DecToHex(RGBA[2])
			content+="width:"+(iweatherTime[i+1][0]-iweatherTime[i][0])/iweatherTime[iweatherTime.length-1][0]*100+"%;background:"+iweatherColor+" "
			td.setAttribute("style","border:1px solid #000000;width:"+(iweatherTime[i+1][0]-iweatherTime[i][0])/iweatherTime[iweatherTime.length-1][0]*100+"%;background:"+iweatherColor);
			tr.appendChild(td)
		}
		table.appendChild(tr)
		node.appendChild(table)
		percent=iweatherValues['percent'];
		table=document.createElement("table")
		table.setAttribute("style","width:100%;height:20px;border:1px solid #000000;border-collapse:collapse");
		var tr=document.createElement("tr");
		td=document.createElement("td");
		td.setAttribute("style","border:1px solid #000000;width:"+percent+"%;");
		tr.appendChild(td);
		td=document.createElement("td")
		tr.appendChild(td);
		table.appendChild(tr)
		node.appendChild(table)
	}
	setTimeout("js_getIweatherTable('"+id+"')",1000)
}		
	
function js_getTimeValue(s) {
	// Transforms i-weather time (00:00:00 -> 25:07:40) to number of seconds
	s=s+":00:00:00";		// Simple way to be sure to have at least an array of 3 (without error)
	var arr=s.split(":");
	return parseInt(arr[0])*60*60 + parseInt(arr[1])*60 + parseInt(arr[2]);
}
function js_leadingZero(s,count) {
	// Returns a string with 'count' leading zero(s)
	var sLeadingZero=s+"";
	while(sLeadingZero.length<count) sLeadingZero="0"+sLeadingZero;
	return sLeadingZero;
}
function js_DecToHex(number) {
	var hexbase="0123456789ABCDEF";
	if(number>255) number=255;
	if(number<0) number=0;
	return hexbase.charAt((number>> 4)& 0xf)+ hexbase.charAt(number& 0xf);
}
function js_HexToDec(hex) {
	return parseInt(hex.substr(0,1),16)*16 + parseInt(hex.substr(1,1),16); 
}
function js_debug(t) {
	if (div=document.getElementById('debug')) div.innerHTML+=t+"<br />";
}

