
// populate the weather form
function popform(table,sta,dat){
	var f;

	f = getElement('StationDataForm');
	f.innerHTML=getWxDescriptionHTML(table,sta,dat,true);
	return true;
}

function getDataOption(){
	var opts = "";
	var nam;
	var c;
	c = getElement('dataset');
	opts = c.options[c.selectedIndex].value;
	return opts;
}

/*function getWindOption(){
	var opts = "";
	var el;
	var nam;
	var windCtrlNames = Array('optWind0','optWind0Max','optWind60','optWind90','optWindNone');
	var c;
	
	for (el in windCtrlNames){
		nam = windCtrlNames[el];
		c = getElement(nam);
		if(c != null) { // not all will be present on the historic disp
			if(c.selected) {
				opts = c.value;
			}
		}
	}
	return opts;
}*/
function setOverlayOptions(dateTime){
	var oName='wxoverlay';
	
	o = getOverlayImage();
	str = o.src;
	//oName = (str.indexOf(historic) >= 0) ? historic : live;

	initOverlay(oName,dateTime);
	
}
function initOverlay(sName,dateTime){
	var c;
	var opts;
	
	opts = getOverlayOptions(dateTime);
	
	o = getOverlayImage();
	o.src = sName + '.phtml' + opts;
}
function getOverlayImage(){
	return getElement('wxoverlay');
}
function getOverlayOptions(dateTime){
	var opts;
	var o;
	var dataOpt;
	
	opts = '';
	
	dataOpt = getDataOption();
	if(dataOpt != '')	opts += "?" + dataOpt;

	opts += (opts == '' ? '?' : '&');
	opts += 'datetime=' + dateTime;
	//opts += '&sid=' + sid;

	return  opts;
	
}
function getWxDescriptionHTML(hist,sta,dat,showStation){
	var h;
	var hdr;
	var wunits;
	var skyStateDesc;
	var skyAtts,rainAtts;
	var skipIR,skipRain;
	var skyCell,rainCell;
	var skyImCell,rainImCell;
	var historic;
	var atts;
	var ct;
	
	historic = (hist == 'h');
	h = '<table class="wxdata"><tbody><tr><td>\n';  // outer table to make a column
	h += '<table class="wxdata" style="background-color: #FFFF80;"><tbody>';
	if(dat.wind_conf == undefined) { //i.e. data object invalid
		ct =  tag('h3','Sorry, no data is available for this station at this time');
	}else{
		ct = tag('h3','at ' + dat.collected + ' on ' + dat.today );
		wunits = (dat.wind_conf == '0') ? "mph" : "knots"; 
	}
	if(showStation) h += trow((tag('h2',sta.title)) + ct);
	//h += trow('&nbsp;');
	if(dat.wind_conf == undefined ) {
		// noop
	}else if(dat.data_skip == '1') {
		h += trow(taga('span','class="error"','Sorry this data is only available from ' + dat.data_start + 'am to ' + dat.data_finish + ' pm'));
	}else if(dat.status != null) {
      h += trow(taga('span','class="error"','Sorry this Station is off the air at present.'));
	  h += trow('We hope to have this station back again on ' + dat.returnday + ' at ' + dat.returntime 
          +'\nFor help, or information about restoration of service, please call our 0800 free helpline number, or email us.\n' 
		  +' The details are below.');
	/*}else if(Number(dat.data_age_mins) > 90 && ! historic){
      h += trow('Sorry, the last automatic data upload from the Wendy weather stations to this page was at ' + dat.collected + ' on ' + dat.today 
	    + '\nThere seems to have been a breakdown in the automatic data transmission, and the data is out of date.');*/
    }else{

		h += trow(taga('span','class="wxdhdr"','Winds:') + ' In the last 30 mins, the Wind was varying between ' + dat.wind_min30 
		  + ' and ' + dat.wind_max30 + ' ' + wunits + ' ave ' + dat.wind_avedirn + ' at ' 
		  + dat.wind_avespeed + ' ' + wunits + '.');
		if(dat.wind_avedirn30 != null || dat.wind_avedirn60 != null || dat.wind_avedirn90 != null){
			h += trow("30 mins ago, it was " + dat.wind_avedirn30 + " at " + dat.wind_avespeed30 + " " + wunits + '.' + '<br/>\n'
			 + "60 mins ago, it was " + dat.wind_avedirn60 + " at " + dat.wind_avespeed60 + " " + wunits + '.' + '<br/>\n'
			 + "90 mins ago, it was " + dat.wind_avedirn90 + " at " + dat.wind_avespeed90 + " " + wunits + '.');
		}
		h += trow('&nbsp;');
		
		// Table for sky & rain
				
		//sky cell contents
		
		hdr = taga('span','class="wxdhdr"','Skystate:') + ' ';
		skipRain = dat.rain_skip == '1';
		skipIR = dat.ir_skip == '1';
		if(skipIR) {
			skyCell = hdr + 'Sorry, no Sky State Report is Available.';
		}else{
			skyCell = hdr + 'In the last 30 mins, light varied from ' 
			 + dat.ir_min30 + '% to ' + dat.ir_max30 + '% average ' + dat.ir_ave30 + '%. ';
		 	skyStateDesc = skyState(dat.today,dat.collected,Number(dat.ir_min30),Number(dat.ir_max30),Number(dat.ir_ave30));
			skyCell += skyStateDesc;
		}
		
		
		// rain cell contents
		
		

		//h += trow('&nbsp;');
		//RAIN
		rainCell = taga('span','class="wxdhdr"','Rain:') + ' ';
		
		if (skipRain){
		   rainCell += 'Sorry, no Rainfall Data is Available.';    
		}else if (dat.rain_today == '0'){
	       rainCell += 'There has been NO RAIN Today.';
		}else{	
			rainCell += ' It last rained at ' + hhMM(dat.rain_last) + ' and ' + dat.rain_today + 'mm has fallen since midnight.';
		}
		
		skyAtts = 'src="images/wx/' + skyStateImageName(skipIR,skyStateDesc) 
		 + '" class="wxdata" width=150 height=80 alt="Sky representation"';
		skyImCell = '\n' + taga('image',skyAtts,'');
		
		rainAtts = 'src="images/wx/' + rainfallImageName(skipRain,dat.rain_today) 
		  + '" class="wxdata" width=70 height=80 alt="Rainfall representation"';
		rainImCell =   taga('image',rainAtts,'');
		
		h += trow(taga('table','class="wxdata"',
			tag('tr',tag('td',skyCell) + '\n' + tag('td',rainCell))
			+ taga('tr','align="center"',tag('td',skyImCell) + '\n' + tag('td',rainImCell))
			));
		
				
		//TEMP
		h += trow(taga('span','class="wxdhdr"','Temperatures:')) + ' ';
		if (dat.temp_skip == '1'){
			h += trow("Sorry, no Temperature or Cloudbase Height data is Available.");
		}else{
			h += trow('Lowest temperature overnight was ' + dat.temp_min + '°C' + '<br/>\n'
				+'Highest temperature today was  ' + dat.temp_max + '°C' + '<br/>\n'
				+'Current temperature is:  '+ dat.temp_current + '°C');
			
			h += trow('&nbsp;');
			h += trow(taga('span','class="wxdhdr"','Anticipated Cloudbase:'));
			h += trow('Cloudbase is ' + dat.cloudbase + ' feet above sea level.' + '<br/>\n'
			 + 'Cloudbase is ' + (Number(dat.cloudbase) - Number(sta.height)) + ' feet above the station.');
		}
		h += trow('The station is ' + sta.height +' feet above sea level.');
		
	}
	h +='</tbody></table>\n';
	
	
	 if ( dat.tide_high1 + dat.tide_high2 + dat.tide_low1 + dat.tide_low2 > 0){
	 	h +='</td></tr><tr><td>\n'; // outer tbl new row
	 	h += '<table class="wxdata"><tbody>\n';
		hdr = taga('span','class="wxdhdr"','Tide Times:')  + ' ';
		h += trow(hdr + '(Times are in GMT or BST as appropriate for time of year.)' );
		h += trow('High Tide is at ' + hhMM(dat.tide_high1 )+ ' and at ' + hhMM(dat.tide_high2) + '.' + '<br/>\n'
			+ 'Low Tide is at ' + hhMM(dat.tide_low1) + ' and at ' + hhMM(dat.tide_low2) + '.');
		h += '</tbody></table>';
		h +='</td></tr>\n'; // outer tbl end new row
   }
	if(showStation){
		atts = 'href="station.html?stationid=' + sta.id + '" title="Station details" target="_blank"';
		h += trowcenter(tag('p',taga('a',atts,'Station details...')));
	}
	h += '</tbody></table>\n'; // outer table end
   return h;
}
function trow(str){
	return '<tr><td>' + str + '</td></tr>\n';
}
function trowcenter(str){
	return '<tr><td align="center">' + str + '</td></tr>\n';
}
function tag(nm,cont){
 return '<' + nm + '>' + cont + '</' + nm + '>';
}
function taga(nm,atts,cont){
 return '<' + nm + ' ' + atts +'>' + cont + '</' + nm + '>';
}

function getElement(id){
	var element = null;
	if (document.all) {
    	element =  document.all(id);
  	}else if (document.getElementById) {
	   element= document.getElementById(id);
  	}
	return element;
}

function rainfallImageName(skipRain,rain){
			var ret;
			var ext = '.gif';
			if(skipRain) {
				ret = 'rainna';
			}else if(rain <= 0) {
				ret = 'rainnone';
			}else if(rain <= 5) {
				ret = 'rain1to5mm';
			}else if(rain <= 10) {
				ret = 'rain6to10mm';
			}else if (rain <= 20) {
				ret = 'rain11to20mm';
			}else{
				ret = 'rain20mmplus';
			}
			ret += ext;
			return ret;

}
function skyStateImageName(skip,desc){
	var iName;
	var ext = '.jpg';
	var sny,snyorclear,soca,hoca,oca,loca;
	var hc,mhc,mc,lmc,lc;
	var cld;
	var scattered;
	
	sny = snyorclear =  hoca = oca = loca = false;
	hc = mhc = mc = lmc = lc = false;
	
	if(skip) {
		iName = 'noskystate';
	}else{
		if(desc.indexOf('sunny') >= 0) {
			if(desc.indexOf('or clear') >= 0){
				snyorclear = true;
			}else{
				sny = true;
			}
		}else if(desc.indexOf('overcast') >= 0) {
			if(desc.indexOf('lightly') >= 0) {
				loca = true;
			}else if(desc.indexOf('heaviliy') >= 0) {
				hoca = true;
			}else{
				oca = true;
			}
		}
		if(desc.indexOf('heavy cloud') >=0) {
			if(desc.indexOf('moderate to') >= 0){
				mhc = true;
			}else{
				hc = true;
			}
	   }else if(desc.indexOf('light to moderate cloud') >=0) {
		   lmc = true;
		}else if(desc.indexOf('moderate cloud') >=0) {
			mc = true;
		}else if(desc.indexOf('light cloud') >=0) {
			lc = true;
		}
		cld = hc || mhc || mc || lmc || lc;
		scattered = (cld &&  desc.indexOf('scattered') >= 0);
	
		if(sny) {
				iName = 'sunny';
		}else if(snyorclear){
				iName = 'brightmilky';
		}else if(loca){
				iName = 'lightovercast';
		}else if(hoca){
				iName = 'heavilyovercast';
		}else if(oca){
				iName = 'overcast';
		}else{
			iName = "black";
		}
	 
	 	// If it's sunny, we can add cloud descs
			
		if (sny) {
			if(scattered)	iName += 'scattered';
			if(hc) {
				iName += 'heavycloud';
			}else if(mhc) {
				iName += 'mod2heavycloud';
			}else if(mc) {
				iName += 'modcloud';
			}else if(lmc){
				iName += 'light2modcloud';
			}else if(lc){
				iName += 'lightcloud';
			}
		}
	}
	
	
	return iName + ext;
}
function skyState(pDate,pTime,minLight,maxLight,avLight){
	var desc;
	var monthNo;
	var monTimes;
	var t,t1,t2;
	var t1Str,t2Str;
	var lightDiff;
	var meanLight;
	var scaTrigger;
	monTValid = Array(
	{t1:'09:30',t2:'15:00'},
	{t1:'09:00',t2:'15:30'},
	{t1:'08:30',t2:'16:30'},
	{t1:'07:30',t2:'18:30'},
	{t1:'06:30',t2:'20:00'},
	{t1:'06:00',t2:'20:30'},
	{t1:'06:00',t2:'20:30'},
	{t1:'07:00',t2:'20:00'},
	{t1:'07:30',t2:'07:00'},
	{t1:'08:30',t2:'17:00'},
	{t1:'08:00',t2:'16:00'},
	{t1:'09:30',t2:'15:00'});

	desc = '';

	monthNo = monthNumber(pDate);
	monTimes = monTValid[monthNo - 1];
	t1 = minuteOfDay(monTimes.t1);
	t2 = minuteOfDay(monTimes.t2);
	t = minuteOfDay(pTime);
	if(false){ // &&  t < t1 ||t >  t2){
		desc =  'The Sky Report is available Between ' + monTimes.t1 + ' and ' + monTimes.t2;
    }else{
	    lightDiff = maxLight - minLight;
	    meanLight = lightDiff /3.0;
	    scaTrigger= maxLight- meanLight;
	
	//  scaTrigger% = value 1/3 of way down between maxLight% and minLight%
	// note: scaTrigger is NOT 66% of maxLight%, it is 66% of range  between min and max light.
		
		desc += "The sky is ";
	
	// set basic sky state from max figure
	// if not much difference between max & min print 1st parameter &    quit.
	
		if (minLight < (maxLight - 15) && maxLight > 39) desc += "mainly ";
		if (maxLight > 90) desc +=  "sunny";
		if (maxLight > 80 && maxLight < 91) desc +=  "sunny or clear";
		if (maxLight > 69 &&  maxLight < 81) desc += "lightly overcast";
		if (maxLight > 39 &&  maxLight < 70) desc += "overcast";
		if (maxLight < 40) {
			desc += "heavily overcast.";
		}else if (minLight > (maxLight - 15)){
		//    if min and max nearly the same, then quit
			desc += '.';
		}else{
	
	//if bigger difference than that, then say cloud state
	//first work out how much of sky covered:
	
			desc += " with some ";
	
	//    if ave light >3/4 of max light, then add "scattered"
	//    (this means more sky, less cloud)
	
			if (maxLight > 39 && avLight >= scaTrigger)  desc += "scattered ";
			
			if (minLight < 30) desc += "heavy cloud.";
			if (minLight > 29 && minLight < 46) desc +=  "moderate to heavy cloud.";
			if (minLight > 45 && minLight < 60) desc +=  "moderate cloud.";
			if (minLight > 59 && minLight < 70) desc +=  "light to moderate cloud.";
			if (minLight > 69 && minLight < 86) desc +=  "light cloud.";
		}
	}
	return desc;
}
// converts '745' to 07:45
function hhMM(numStr){
	var str;
	str = padStr(String(numStr),4);
	return str.substr(0,2) + ':' + str.substr(2,2);
	
}
function padStr(pStr,length) {
    var str = pStr;
    while (str.length < length)
        str = '0' + str;
    return str;
}

function minuteOfDay(timeStr){
	var c;
	var hr;
	var mn;
	c = timeStr.split(':');
	if(c.length < 2) {
		throw ('minuteOfDay: Bad time formst - hh:mm[:ss] expected');
	}
	hr = Number(c[0]);
	mn = Number(c[1]);
	return hr * 60 + mn;
}
function monthNumber(datStr) {
	var c;
	var mon;
	var dStr;
	dStr = new String(datStr);
	c = dStr.slice(3,5);
	
	mon = Number(c);
	return mon;
}
