var today;//Variable to hold the date
var year;//Variable to hold the current year
var month;//Variable to hold the current month
var day;//Variable to hold the current day
var dateTag;//Variable to hold the string that goes to the page
var issDate, strDate, finDate, startingYear, startingMonth, startingDay, startingDateTag;
var finishYear, finishMonth, finishDay, finishDateTag;
var selHourBox, dateTagBot, inday, inmonth, inyear, tag, tagBot, issuedDayLeft;
var issuedDayRight, issuedDayLeftBot, issuedDayRightBot, forcastStartLeft;
var forcastStartRight, forcastStartLeftBot, forcastStartRightBot, forcastFinishLeft;
var forcastFinishRight, forcastFinishLeftBot, forcastFinishRightBot;
var currIssDate, currForStrDate, currForFinDate, issDisableDateStr, issDisableDateFin;
var strDisableDateStr, strDisableDateFin, finDisableDateStr, finDisableDateFin, tempDate; 
var numOfMonths = 12;//Total number of months in a year
var february = 2;//Number to represent which month february
var prefix = "http://collaboration.cmc.ec.gc.ca/cmc/ensemble/naefs/semaine2/images/";
var part2Global = "_054@007_E1_global_I_NAEFS@TEMPERATURE_anomaly@probability@above@normal@week2_";
var part2North = "_054@007_E1_north@america_I_NAEFS@TEMPERATURE_anomalyi"
var language;
var selecHour;
var issuedDaysBack = 31;

/************************************************************************************
  Function: initialize()
  Author: Shayne Brioux 
  Date: Jan 2008
  Purpose:	This function is called by the body onload of the semaine2_e or f page
  				the function sets up the current date and makes calls to have the JS
				modify the page accordingly.
*************************************************************************************/
function initialize(){
	//Get the language of the page
	language = (document.getElementsByTagName('body'))[0].getAttribute('lang');
	var incButton = document.getElementById("increment");
	var decButton = document.getElementById("decrement");
	selHourBox = document.getElementById('heure');
	selHourBox.selectedIndex = 0;
	disableViewButton();//Because JS is on we take away the view button from the page
	today = new Date();//Get the current date and store it in the appropriate var
	issDate = zeroTheHours(new Date());
	strDate = zeroTheHours(new Date());
	finDate = zeroTheHours(new Date());
	finDate.setDate(finDate.getDate()+1);
	
	registerEvents();//Register events to the drop down boxes

	changeDateTag();//Update the date tag on the web page
	changeStartDateTag();
	changeFinishDateTag();
	checkButtons();
	changeTitle();
	//updateImages();//Updates all the images on the page
}
/************************************************************************************
	Function: registerEvents 
	Authour: Shayne Brioux
	Date: Feb 2009
	Purpose: This functions sole purpose is to register events to the drop down boxes
				on the page.  This was needed for the updated version of the page that
				now contains two sets of controls.			
 ************************************************************************************/
function registerEvents(){
	document.getElementById('heure').onchange = hourChange;
	document.getElementById('heure2').onchange = hourChange;

	document.getElementById('type').onchange = typeChange;
	document.getElementById('type2').onchange = typeChange;
}
/************************************************************************************
	Function:	typeChange 
	Authour: 	Shayne Brioux
	Date: 		Feb 2009
	Purpose: 	This function will check to see which type box was changed and then 
					change the opposite box to match the newly selected value, then update 
					the images
 ************************************************************************************/
function typeChange(e){
	var tBox;
	if(this.id == 'type'){
		tBox = document.getElementById('type2');
		tBox.selectedIndex = this.selectedIndex;
	} else {
		tBox = document.getElementById('type');
		tBox.selectedIndex = this.selectedIndex;
	}
	updateImages();
}
/************************************************************************************
	Function: hourChange
	Authour: Shayne Brioux
	Date: Feb 2009
	Purpose: This function will check to see which hour box was changed and then change
				the opposite box to match the newly selected value, then update the images
 ************************************************************************************/
function hourChange(e){
	var hBox;
	if(this.id == 'heure'){
		hBox = document.getElementById('heure2');
		hBox.selectedIndex = this.selectedIndex;
	} else {
		hBox = document.getElementById('heure');
		hBox.selectedIndex = this.selectedIndex;
	}
	updateHour();
}
/************************************************************************************
	Function: decrementDay()
	Authour: Shayne Brioux
	Date: Jan 2008
	Purpose: This function will take the current issued day and then back up 1 day
 ************************************************************************************/
function decrementDay(){
	issDate.setDate(issDate.getDate()-1);
	changeDateTag();//Update the date tag on the page
	checkButtons();
	updateImages();//Update all the images on the pag
	return false;
}
/************************************************************************************
	Function: incrementDay
	Authour: Shayne Brioux
	Date: Jan 2008
	Purpose: This function will take the current issued day and then advance 1 day
 ************************************************************************************/
function incrementDay(){
	issDate.setDate(issDate.getDate()+1);
	changeDateTag();//Update the date tag on the web page
	checkButtons();
	updateImages();//Update all the images on the page
	return false;
}
/************************************************************************************
	Function: startDec
	Authour: Shayne Brioux
	Date: Jan 2008
	Purpose: This function will take the current forecast start date and then backup
				the date 1 day
 ************************************************************************************/
function startDec(){
	strDate.setDate(strDate.getDate()-1);
	changeStartDateTag();
	checkButtons();
	updateImages();
	return false;
}
/************************************************************************************
	Function: startInc
	Authour: Shayne Brioux
	Date: Jan 2008
	Purpose: This function will take the current forecast start date and then advance
				the date 1 day
 ************************************************************************************/
function startInc(){
	strDate.setDate(strDate.getDate()+1);
	changeStartDateTag();
	checkButtons();
	updateImages();
	return false;
}
/************************************************************************************
	Function: finishDec
	Authour: Shayne Brioux
	Date: Jan 2008
	Purpose: This function will take the current forecast end date and then backup
				the date 1 day
 ************************************************************************************/
function finishDec(){
	finDate.setDate(finDate.getDate()-1);
	changeFinishDateTag();
	checkButtons();
	updateImages();
	return false;
}
/************************************************************************************
	Function: finishInc
	Authour: Shayne Brioux
	Date: Jan 2008
	Purpose: This function will take the current forecast end date and then advance
				the date 1 day
 ************************************************************************************/
function finishInc(){
	finDate.setDate(finDate.getDate()+1);
	changeFinishDateTag();
	checkButtons();
	updateImages();
	return false;
}
/***************************************************************************************
	Function: formatDate
	Author: Shayne Brioux
	Date: Jan 2008
	Purpose: This function will take the current date and change the formatting to follow
				suit with the XXXX-XX-XX format.  This will keep it consistent.
***************************************************************************************/
function formatDate(inDate){
	inday = inDate.getDate();
	inmonth = inDate.getMonth()+1;
	inyear = inDate.getFullYear();
	if(inday < 10) inday = "0" + inday;
	if(inmonth < 10) inmonth = "0" + inmonth;
	return inyear + "-" + inmonth + "-" + inday;
}
/***************************************************************************************
	Function: changeDateTag
	Author: Shayne Brioux
	Date: Jan 2008
	Purpose: This function will get a handle to the issued date tag on the web page and then
				update the tag with the new date.
***************************************************************************************/
function changeDateTag(){
	dateTag = document.getElementById('datecour');//Gets a handle to the date element
	dateTagBot = document.getElementById('datecour2');//Gets a handle to the date element
	dateTag.value = formatDate(issDate);
	dateTagBot.value = formatDate(issDate);
}
/***************************************************************************************
	Function: changeStartDateTag
	Author: Shayne Brioux
	Date: Jan 2008
	Purpose: This function will get a handle to the forecast start date tag on the web 
				page and then update the tag with the new date.
***************************************************************************************/
function changeStartDateTag(){
	tag = document.getElementById('dateprev_deb');
	tagBot = document.getElementById('dateprev_deb2');
	tag.value = formatDate(strDate);
	tagBot.value = formatDate(strDate);
}
/***************************************************************************************
	Function: changeFinishDateTag
	Author: Shayne Brioux
	Date: Jan 2008
	Purpose: This function will get a handle to the forecast finish date tag on the 
				web page and then update the tag with the new date.
***************************************************************************************/
function changeFinishDateTag(){
	tag = document.getElementById('dateprev_fin');
	tagBot = document.getElementById('dateprev_fin2');
	tag.value = formatDate(finDate);
	tagBot.value = formatDate(finDate);
}

function updateHour(){
	checkButtons();
	updateImages();
}
/**********************************************************************************************
	Function: updateImage
	Author: Shayne Brioux
	Date: Jan 2008
	Puprose:	The purpose of this function is to itterate through the placeholders for images
				on the page and then when called will update the holders src attribute to 
				conincide with the proper image.
**********************************************************************************************/
function updateImages(){
	var datecourVal = document.getElementById('datecour').value;
	var stripDatecour = datecourVal.replace(/-/g,'');
	var imageTag = document.getElementById('graphiques');
	var extension = ".gif";//The file type extension
	//var urlPrefix = 'http://collaboration.cmc.ec.gc.ca/cmc/ensemble/produits/data/produits/';
	var urlPrefix = 'http://collaboration.cmc.ec.gc.ca/cmc/ensemble/produits/data/produits/';
	var typeSelectBox = document.getElementById('type');
	var selectedType = typeSelectBox[typeSelectBox.selectedIndex].value;
	var hourSelectBox = document.getElementById('heure');
	var selectedHour = hourSelectBox[hourSelectBox.selectedIndex].value;
	var diff1 = withdrawDates(issDate.getFullYear(),issDate.getMonth(),issDate.getDate(),strDate.getFullYear(),strDate.getMonth(),strDate.getDate());
	var diff2 = withdrawDates(issDate.getFullYear(),issDate.getMonth(),issDate.getDate(),finDate.getFullYear(),finDate.getMonth(),finDate.getDate());
	imageTag.style.display = "block";
	imageTag.src = urlPrefix + selectedType + "/CMC_NCEP/" + stripDatecour + selectedHour +"_" + diff1 + "_" + diff2 + extension;
	divChildNodes = imageTag.parentNode.childNodes;
	for(var counter = 0; counter < divChildNodes.length; counter++){
		if(divChildNodes[counter].tagName == "P"){
			divChildNodes[counter].style.display = "none";
		}
	}
	imageTag.onerror = noImageToDisplay;
	changeTitle();
}
/************************************************************************************
	Function: noImageToDisplay
	Author: Shayne Brioux
	Date: Jan 2008
	Purpose:	The purpose of this function is to handle when an HTML error happens
				if there is no image at the src url.  The function will then replace
				the src image with the text of no image to display.
 ************************************************************************************/
function noImageToDisplay(e){
	if(!e) e = window.event;//Get a handle to the event
	var target;//a variable to track the target
	if(e.target){//for FF
		target = e.target;//Save the target
	} else {//Otherwise it's a IE rendering engine
		target = e.srcElement;//Save the target
	}
	this.style.display = "none";//Hide the image
	var parentsChilds = this.parentNode.childNodes;//Get all the child nodes of the parent
	for (var counter = 0; counter < parentsChilds.length; counter++){//Iterate through teh child nodes
		if (parentsChilds[counter].tagName == "P"){//If the tag is a P tag
			if(language == "en"){
				parentsChilds[counter].innerHTML = "Image Not Available"; //Insert the error message
			} else {
				parentsChilds[counter].innerHTML = "Image Non Disponible";//Inser the error message
			}
			parentsChilds[counter].style.display = "block";//Display the hidden P tag
		}
	}
}
/*********************************************************************************************
Function:	checkButtons
Author:		Shayne Brioux
Date:			Jan 2008
Purpose:		This function will get a handle to all the buttons on the page. The function
				will then check the current issued date, forecast start date and forecast
				finish date. Once these dates are found boundry dates that the buttons are
				to stay within are setup.  If the date is at the boundry buttons on the page
				are disabled.  If one button causes another button to fall outside the boundries
				then the button is moved back into within the boundry by calling the appropriate
				increment or decrement function for that button.
**********************************************************************************************/
function checkButtons(){

	issuedDayLeft = document.getElementById('decrement');
	issuedDayRight = document.getElementById('increment');
	issuedDayLeftBot = document.getElementById('decrement2');
	issuedDayRightBot = document.getElementById('increment2');
	
	forcastStartLeft = document.getElementById('left_button2');
	forcastStartRight = document.getElementById('right_button2');
	forcastStartLeftBot = document.getElementById('left_button2b');
	forcastStartRightBot = document.getElementById('right_button2b');
	
	forcastFinishLeft = document.getElementById('left_button3');
	forcastFinishRight = document.getElementById('right_button3');
	forcastFinishLeftBot = document.getElementById('left_button3b');
	forcastFinishRightBot = document.getElementById('right_button3b');
	
	currIssDate = zeroTheHours(issDate);
	currForStrDate = zeroTheHours(strDate);
	currForFinDate = zeroTheHours(finDate);

	issDisableDateStr = zeroTheHours(new Date());
	issDisableDateStr.setDate(issDisableDateStr.getDate() - issuedDaysBack);
	issDisableDateFin = zeroTheHours(new Date());
	strDisableDateStr = currIssDate;
	strDisableDateFin = new Date();
	strDisableDateFin.setFullYear(issDate.getFullYear(),issDate.getMonth(),issDate.getDate());
	strDisableDateFin.setDate(strDisableDateFin.getDate() + 13);
	finDisableDateStr = new Date();
	finDisableDateStr.setFullYear(strDate.getFullYear(),strDate.getMonth(),strDate.getDate());
	finDisableDateStr.setDate(finDisableDateStr.getDate() + 1);
	finDisableDateFin = new Date();
	finDisableDateFin.setFullYear(issDate.getFullYear(),issDate.getMonth(),issDate.getDate());
	finDisableDateFin.setDate(finDisableDateFin.getDate() + 14);

	if(Date.parse(currIssDate) >= Date.parse(issDisableDateFin)){
		issuedDayRight.disabled="disabled";
		issuedDayRightBot.disabled="disabled";
	} else {
		issuedDayRight.disabled = "";
		issuedDayRightBot.disabled = "";
	}
	if(Date.parse(currIssDate)<= Date.parse(issDisableDateStr)){
		issuedDayLeft.disabled = "disabled";
		issuedDayLeftBot.disabled = "disabled";
	} else {
		issuedDayLeft.disabled = "";
		issuedDayLeftBot.disabled = "";
	}
	if(Date.parse(currForStrDate) <= Date.parse(strDisableDateStr)){
		forcastStartLeft.disabled = "disabled";
		forcastStartLeftBot.disabled = "disabled";
	} else {
		forcastStartLeft.disabled = "";
		forcastStartLeftBot.disabled = "";
	}
	if(Date.parse(currForStrDate) >= Date.parse(strDisableDateFin)){
		forcastStartRight.disabled = "disabled";
		forcastStartRightBot.disabled = "disabled";
	} else {
		forcastStartRight.disabled = "";
		forcastStartRightBot.disabled = "";
	}
	if(Date.parse(currForFinDate) <= Date.parse(finDisableDateStr)){
		forcastFinishLeft.disabled = "disabled";
		forcastFinishLeftBot.disabled = "disabled";
	} else {
		forcastFinishLeft.disabled = "";
		forcastFinishLeftBot.disabled = "";
	}
	if(Date.parse(currForFinDate) >= Date.parse(finDisableDateFin)){
		forcastFinishRight.disabled = "disabled";
		forcastFinishRightBot.disabled = "disabled";
	} else {
		forcastFinishRight.disabled ="";
		forcastFinishRightBot.disabled ="";
	}
	var hourBox = document.getElementById('heure');
	var selHour = hourBox[hourBox.selectedIndex].value;
	tempDate = zeroTheHours(new Date());
	tempDate.setFullYear(issDate.getFullYear(),issDate.getMonth(),issDate.getDate());
	tempDate.setDate(tempDate.getDate() + 1);
	if(selHour == "12" && Date.parse(tempDate) == Date.parse(currForStrDate)){
		forcastStartLeft.disabled = "disabled";
		forcastStartLeftBot.disabled = "disabled";
	}

	strDisableDateFin.setDate(strDisableDateFin.getDate() + 1);
	finDisableDateFin.setDate(finDisableDateFin.getDate() + 1);
	//Start of date adjustments
	if(Date.parse(currForStrDate) > Date.parse(strDisableDateFin)){
		startDec();
	}
	if(Date.parse(currForStrDate) < Date.parse(currIssDate)){
		startInc();
	}
	if(Date.parse(currForFinDate) > Date.parse(finDisableDateFin)){
		finishDec();
	}
	if(Date.parse(currForFinDate) <= Date.parse(currForStrDate)){
		finishInc();
	}
	if(Date.parse(currIssDate) == Date.parse(currForStrDate) && selHour == "12"){
		startInc();
	}
	//end of date adjustments
}
function zeroTheHours(date){
	date.setHours(0);
	date.setMinutes(0);
	date.setSeconds(0);
	date.setMilliseconds(0);
	return date;
}

function withdrawDates(year1,month1,day1,year2,month2,day2){
	date1 = new Date(year1,month1,day1);
	date2 = new Date(year2,month2,day2);
	diff = (Date.UTC(date2.getUTCFullYear(), date2.getUTCMonth(),date2.getUTCDate(),0,0,0) - Date.UTC(date1.getUTCFullYear(),date1.getUTCMonth(),date1.getUTCDate(),0,0,0))/1000/60/60;
	var selectBoxHour = document.getElementById("heure");
	var currHour = selectBoxHour[selectBoxHour.selectedIndex].value;
	if(currHour == "12"){
		diff = diff - 12;
	}
	if (diff < 0) diff = 0;
	if(diff < 10)
		return "00"+diff;
	else if (diff < 100)
		return "0"+diff;
	else return diff;
}
function changeTitle(){
	var subTitle = document.getElementById('subTitle');
	var typeSelectBox = document.getElementById('type');
	var selectedType = typeSelectBox[typeSelectBox.selectedIndex].value;
	var englishTitle = new Array();
	var frenchTitle = new Array();
	englishTitle[0] = "Probability of precipitation over 0.2 mm everyday ";
	englishTitle[1] = "Probability of precipitation over 2 mm at least one day";
	englishTitle[2] = "Probability of precipitation over 5 mm at least one day";
	englishTitle[3] = "Probability of precipitation over 10 mm at least one day";
	englishTitle[4] = "Probability of precipitation over 25 mm at least one day";
	englishTitle[5] = "Probability of precipitation accumulation over 0.2 mm for the whole period";
	englishTitle[6] = "Probability of precipitation accumulation over 2 mm for the whole period";
	englishTitle[7] = "Probability of precipitation accumulation over 5 mm for the whole period";
	englishTitle[8] = "Probability of precipitation accumulation over 10 mm for the whole period";
	englishTitle[9] = "Probability of precipitation accumulation over 25 mm for the whole period";
	englishTitle[10] = "Probability of precipitation accumulation over 50 mm for the whole period";
	englishTitle[11] = "Probability of wind speed over 15 km/h at least one day";
	englishTitle[12] = "Probability of wind speed over 50 km/h at least one day";
	englishTitle[13] = "Probability of wind speed over 90 km/h at least one day";
	englishTitle[14] = "Probability of minimum temperature under 0&deg;C at least one day";
	englishTitle[15] = "Probability of minimum temperature under -5&deg;C at least one day";
	englishTitle[16] = "Probability of minimum temperature under -15&deg;C at least one day";
	englishTitle[17] = "Probability of minimum temperature under -30&deg;C at least one day";
	englishTitle[18] = "Probability of maximum temperature over 0&deg;C at least one day";
	englishTitle[19] = "Probability of maximum temperature over 15&deg;C at least one day";
	englishTitle[20] = "Probability of maximum temperature over 30&deg;C at least one day";
	englishTitle[21] = "Probability of windchill under -15 at least one day";
	englishTitle[22] = "Probability of windchill under -30 at least one day";
	englishTitle[23] = "Probability of windchill under -40 at least one day";
	englishTitle[24] = "Probability of windchill under -55 at least one day";
	
	frenchTitle[0] = 'Probabilit&eacute; de pr&eacute;cipitations sup&eacute;rieures &agrave; 0.2 mm tous les jours';
	frenchTitle[1] = 'Probabilit&eacute; de pr&eacute;cipitations sup&eacute;rieures &agrave; 2 mm au moins une journ&eacute;e';
	frenchTitle[2] = 'Probabilit&eacute; de pr&eacute;cipitations sup&eacute;rieures &agrave; 5 mm au moins une journ&eacute;e';
	frenchTitle[3] = 'Probabilit&eacute; de pr&eacute;cipitations sup&eacute;rieures &agrave; 10 mm au moins une journ&eacute;e';
	frenchTitle[4] = 'Probabilit&eacute; de pr&eacute;cipitations sup&eacute;rieures &agrave; 25 mm au moins une journ&eacute;e';
	frenchTitle[5] = 'Probabilit&eacute; d\'accumulation de pr&eacute;cipitations sup&eacute;rieures &agrave; 0.2 mm pour la p&eacute;riode';
	frenchTitle[6] = 'Probabilit&eacute; d\'accumulation de pr&eacute;cipitations sup&eacute;rieures &agrave; 2 mm pour la p&eacute;riode';
	frenchTitle[7] ='Probabilit&eacute; d\'accumulation de pr&eacute;cipitations sup&eacute;rieures &agrave; 5 mm pour la p&eacute;riode';
	frenchTitle[8] ='Probabilit&eacute; d\'accumulation de pr&eacute;cipitations sup&eacute;rieures &agrave; 10 mm pour la p&eacute;riode';
	frenchTitle[9] ='Probabilit&eacute; d\'accumulation de pr&eacute;cipitations sup&eacute;rieures &agrave; 25 mm pour la p&eacute;riode';
	frenchTitle[10] ='Probabilit&eacute; d\'accumulation de pr&eacute;cipitations sup&eacute;rieures &agrave; 50 mm pour la p&eacute;riode';
	frenchTitle[11] = 'Probabilit&eacute; de vents sup&eacute;rieurs &agrave; 15 km/h au moins une journ&eacute;e';
	frenchTitle[12] = 'Probabilit&eacute; de vents sup&eacute;rieurs &agrave; 50 km/h au moins une journ&eacute;e';
	frenchTitle[13] = 'Probabilit&eacute; de vents sup&eacute;rieurs &agrave; 90 km/h au moins une journ&eacute;e';
	frenchTitle[14] = 'Probabilit&eacute; de temp&eacute;rature minimale inf&eacute;rieure &agrave; 0&deg;C au moins une journ&eacute;e';
	frenchTitle[15] = 'Probabilit&eacute; de temp&eacute;rature minimale inf&eacute;rieure &agrave; -5&deg;C au moins une journ&eacute;e';
	frenchTitle[16] = 'Probabilit&eacute; de temp&eacute;rature minimale inf&eacute;rieure &agrave; -15&deg;C au moins une journ&eacute;e';
	frenchTitle[17] = 'Probabilit&eacute; de temp&eacute;rature minimale inf&eacute;rieure &agrave; -30&deg;C au moins une journ&eacute;e';
	frenchTitle[18] = 'Probabilit&eacute; de temp&eacute;rature maximale sup&eacute;rieure &agrave; 0&deg;C au moins une journ&eacute;e';
	frenchTitle[19] = 'Probabilit&eacute; de temp&eacute;rature maximale sup&eacute;rieure &agrave; 15&deg;C au moins une journ&eacute;e';
	frenchTitle[20] = 'Probabilit&eacute; de temp&eacute;rature maximale sup&eacute;rieure &agrave; 30&deg;C au moins une journ&eacute;e';
	frenchTitle[21] = 'Probabilit&eacute; de refroidissement &eacute;olien inf&eacute;rieur &agrave; -15 au moins une journ&eacute;e';
	frenchTitle[22] =  'Probabilit&eacute; de refroidissement &eacute;olien inf&eacute;rieur &agrave; -30 au moins une journ&eacute;e';
	frenchTitle[23] = 'Probabilit&eacute; de refroidissement &eacute;olien inf&eacute;rieur &agrave; -40 au moins une journ&eacute;e';
	frenchTitle[24] = 'Probabilit&eacute; de refroidissement &eacute;olien inf&eacute;rieur &agrave; -55 au moins une journ&eacute;e';
	if(language == "en"){
	subTitle.innerHTML = englishTitle[typeSelectBox.selectedIndex];
	} else {
		subTitle.innerHTML = frenchTitle[typeSelectBox.selectedIndex];
	}
}

