var today;//Variable to hold the date
var dateTag;//Variable to hold the string that goes to the page
var issDate;
var strDate;
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_anomaly"
var language;
var nbCMC;
var nbNCEP;
var nbCMC_NCEP;

/************************************************************************************
  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(){/*{{{*/
	var viewButton = document.getElementById("View");//Get a handle to the view button
	viewButton.disabled = "true";

	nbCMC = 22;
	nbNCEP = 21;
	nbCMC_NCEP = 43;
	//Get the language of the page
	language = (document.getElementsByTagName('body'))[0].getAttribute('lang');
	var incButton = document.getElementById("increment");
	var decButton = document.getElementById("decrement");
	var hourBox = document.getElementById('heure');
	registerEvents();

	hourBox.selectedIndex = 0;
	disableViewButton();//Because JS is on we take away the view button from the page
	if(window.location.search.substring(1)){
		getVariablesFromUrl();
	}else{
		issDate = zeroTheHours(new Date());
		strDate = zeroTheHours(new Date());
		strDate.setDate(strDate.getDate()+1);
	}
	changeDateTag();//Update the date tag on the web page
	changeForecastDateTag();
	checkButtons();
	updateImages();//Updates all the images on the page
}/*}}}*/
/************************************************************************************
	Function: registerEvents()
	Authour: Shayne Brioux
	Date: Mar 2009
	Purpose: This function simply attaches events using the traditional model to the 
				pages buttons.
 ************************************************************************************/
function registerEvents(){
	var incButton = document.getElementById("increment");
	var decButton = document.getElementById("decrement");

	var hourBox = document.getElementById('heure');
	var hourBoxBott = document.getElementById('heureBott');

	var typeBoxTop = document.getElementById('type');
	var typeBoxBott = document.getElementById('typeBott');

	hourBox.onchange = hourChange;
	hourBoxBott.onchange = hourChange;

	typeBoxTop.onchange = typeChange;
	typeBoxBott.onchange = typeChange;

	//If the script is being used on the individual images version of the page.
	if(hasThreeControls()){
		var hourBoxMidd = document.getElementById('heureMidd');
		var typeBoxMidd = document.getElementById('typeMidd');
		hourBoxMidd.onchange = hourChange;
		typeBoxMidd.onchange = typeChange;
	}
	

}
/************************************************************************************
	Function: decrementDay()
	Authour: Shayne Brioux
	Date: Jan 2008
	Purpose: This function will take the current 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 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 forecastDec(){/*{{{*/
	strDate.setDate(strDate.getDate()-1);
	changeForecastDateTag();
	checkButtons();
	updateImages();
	return false;
}/*}}}*/
function forecastInc(){/*{{{*/
	strDate.setDate(strDate.getDate()+1);
	changeForecastDateTag();
	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){/*{{{*/
	var inday = inDate.getDate();
	var inmonth = inDate.getMonth()+1;
	var 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 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
	var dateTagBott = document.getElementById('datecourBott');//Gets a handle to the date element
	dateTag.value = formatDate(issDate);
	dateTagBott.value = formatDate(issDate);
	if(hasThreeControls()){
		var dateTagMidd = document.getElementById('datecourMidd');//Gets a handle to the date element
		dateTagMidd.value = formatDate(issDate);
	}
}/*}}}*/
/***************************************************************************************
	Function: changeForecastDateTag
	Author: Shayne Brioux
	Date: Jan 2008
	Purpose: This function will get a handle to the forecast tag on the web page and then
				update the tag with the new date.
***************************************************************************************/
function changeForecastDateTag(){/*{{{*/
	var tag = document.getElementById('dateprev');
	var tagBott = document.getElementById('dateprevBott');
	tag.value = formatDate(strDate);//makes sure that the date has been formated properly
	tagBott.value = formatDate(strDate);//makes sure that the date has been formated properly
	if(hasThreeControls()){
		var tagMidd = document.getElementById('dateprevMidd');
		tagMidd.value = formatDate(strDate);//makes sure that the date has been formated properly
	}
}/*}}}*/
/*********************************************************************************************
	Function: hourChange
	Author: 	Shayne Brioux
	Date:		Feb 2009
	Purpose:	A second control was added to the bottom of the page. Now if the bottom control
				is changed we need to make sure the drop down box in the top is changed.  Same
				with the opposite.
*********************************************************************************************/
function hourChange(){/*{{{*/
	var hBox;
	var hBox2;
	if(this.id == 'heure'){//If the top hour box changed
		hBox = document.getElementById('heureBott');
		hBox.selectedIndex = this.selectedIndex;	
		if(hasThreeControls()){
			hBox2 = document.getElementById('heureMidd');
			hBox2.selectedIndex = this.selectedIndex;	
		}
	} else if (this.id == 'heureBott'){//If the bottom hour box changed
		hBox = document.getElementById('heure');
		hBox.selectedIndex = this.selectedIndex;	
		if(hasThreeControls()){
			hBox2 = document.getElementById('heureMidd');
			hBox2.selectedIndex = this.selectedIndex;	
		}
	} else { //If this is the middle hour box
		hBox = document.getElementById('heure');
		hBox2 = document.getElementById('heureBott');
		hBox.selectedIndex = this.selectedIndex;	
		hBox2.selectedIndex = this.selectedIndex;	
	}
	updateImages();
}/*}}}*/
/**********************************************************************************************
Function: typeChange
Author:	Shayne Brioux
Date:		Feb 2009
Purpose:	A second control was added to the bottom of the page.  Now if the bottom control is
			changed we need to make sure that the drop down box in the top is changed as well.
**********************************************************************************************/
function typeChange(){/*{{{*/
	var tBox;
	var tBox2;

	if(this.id == 'type'){//If the top type drop down box is changed
		tBox = document.getElementById('typeBott');
		tBox.selectedIndex = this.selectedIndex;
		if(hasThreeControls()){
			tBox2 = document.getElementById('typeMidd');
			tBox2.selectedIndex = this.selectedIndex;
		}
	} else if (this.id == 'typeBott'){//If the bottom type drop down box is changed
		tBox = document.getElementById('type');
		tBox.selectedIndex = this.selectedIndex;
		if(hasThreeControls()){
			tBox2 = document.getElementById('typeMidd');
			tBox2.selectedIndex = this.selectedIndex;
		}
	} else { // If the middle drop down box is changed
		tBox = document.getElementById('type');
		tBox2 = document.getElementById('typeBott');
		tBox.selectedIndex = this.selectedIndex;
		tBox2.selectedIndex = this.selectedIndex;
	}
	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 lang;
	if(language == "en"){
		lang = 'e';
	} else {
		lang = 'f';
	}
	var datecourVal = document.getElementById('datecour').value;
	var dateCourValStripped = datecourVal.replace(/-/g,'');
	var dateprevVal = document.getElementById('dateprev').value;
	var imageTag = document.getElementById('graphic');
	var extension = ".gif";//The file type extension
	//the common part of the url to all the required images
	var urlPrefix = 'http://collaboration.cmc.ec.gc.ca/cmc/ensemble/cartes/data/cartes/';
	var typeSelectBox = document.getElementById('type');//Get a handle to the type
	var selectedType = typeSelectBox[typeSelectBox.selectedIndex].value;//Get the selected index of type
	var typeHourBox = document.getElementById('heure');//get a handle to the hour 
	var selectedHour = typeHourBox[typeHourBox.selectedIndex].value;//Get the selected hour
	//Calculate the diff, identical to the old JS
	var diff = getHoursDiff(issDate.getFullYear(),issDate.getMonth()+1,issDate.getDate(),strDate.getFullYear(),strDate.getMonth()+1,strDate.getDate());
	if(imageTag){//The next portion will only work on the cartes_ page
		imageTag.style.display = "block";//Make sure the image is displayed
		imageTag.src = urlPrefix + selectedType + "/CMC_NCEP/" + dateCourValStripped + selectedHour + "_" +diff + extension;
		var divChildNodes = imageTag.parentNode.childNodes;//Get the parents elements child nodes
		for(var counter = 0; counter < divChildNodes.length; counter++){//loop through the nodes
			if(divChildNodes[counter].nodeName == "P"){//If the node is a p element
				divChildNodes[counter].style.display = "none";//Hide it
			}
		}
		imageTag.onerror = noImageToDisplay;//Setup what to do if no image available
		document.getElementById('jumperLink').href = 'cartes_small_' + lang + '.html?datecour=' + datecourVal + '&dateprev=' + dateprevVal + '&heure=' + selectedHour + '&type=' + selectedType;
	}
	var numOfCols = 3;//Max number of columns
	var numOfRows = 16;//Man number of rows
	var smallImage;//Vaiable to hold the image
	var centre = "CMC";//the center the images come from
	var tmp_center = new Array(3);//an array to make the next steps easier
	tmp_center[0] = nbNCEP;//Maximum number of NCEP images
	tmp_center[1] = nbCMC;//Max number of CMC images
	tmp_center[2] = nbNCEP;//Max number of both CMC and NCEP images
	var maximum = numOfRows * numOfCols; //The maximum number of image holders
	var legendImages = new Array(3);
	legendImages[0] = document.getElementById("legend1");
	legendImages[1] = document.getElementById("legend2");
	legendImages[2] = document.getElementById("legend3");
	for (var counter = 0; counter < legendImages.length;counter++){
		var legendKey;
		if(legendImages[counter]){
			if(selectedType == "UV200"){legendKey = "UVknots";}
			else if (selectedType == "UV12000"){legendKey = "UV";}
			else {legendKey = selectedType.substr(0,2);}
			legendImages[counter].src = "./images/echelle"+legendKey+".png";
		}
	}
	
	for(var i = 0; i < numOfRows; i ++){//Loop through all the rows
		if(i > 8){//If we are at the 9th row the NCEP images start
			centre = "NCEP";//Change the center that the images are comming from
		}
		for(var j = 0; j < numOfCols; j++){//Loop through all the colomns
			smallImage = document.getElementById('graph'+i+'_'+j);//Get a handle to the IMG tag
			if (smallImage){
				var total = (i)*numOfCols + j;//Keep track of the amount of images already done
				if (total >= 0 && total < 2){//If it's the first two images
					//The first two images have different urls
					smallImage.src = urlPrefix + selectedType + "/" + centre + "/" + dateCourValStripped + selectedHour + "_" + tmp_center[j] + "_" + diff + extension;
				} else if (total == 2){//If it's the third image
					//The Third image has a different url then the first two and all the rest
					smallImage.src = urlPrefix + selectedType + "/NCEP/" + dateCourValStripped + selectedHour + "_" + tmp_center[j] + "_" + diff + extension;
				} else {//If we are at any image after the third one.
					//Becuase there are only 21 images we need to skip the last two posible place holders
					//and start on a new row
					if(total >= (nbCMC+3) && centre == "CMC"){
						j = numOfCols;	//set j to the numOfCOls to cause the inner loop to end
					}else {
						var tmpTotal = total;//Store the current total number of images
						if(centre == "NCEP"){//If we are onto the NCEP images
							tmpTotal = total - (nbCMC + 2);//Need to restart a count so we get the right image
						}
						var tmp_modele = getTempModele(tmpTotal, numOfCols, centre);//Get the tmp modele, copied from the old JS file
						if(total < maximum){//As long as we are under the max number of images
							//output the url to the source of the img tag
							smallImage.src = urlPrefix + selectedType + "/"+centre+"/" + dateCourValStripped + selectedHour + "_" + tmp_modele +"_"+diff + extension;
						}
					}
				}//end of else
				//as long as smallImage has a handle to an IMage tag
					smallImage.style.display = "block";
					//Get the image tag's parent node, and then access all the child nodes
					var divChildNodes = smallImage.parentNode.childNodes;
					//Itterate through all the child nodes
					for(var counter = 0; counter < divChildNodes.length; counter++){
						if(divChildNodes[counter].nodeName == "P"){//If the child node is a p tag
							divChildNodes[counter].style.display = "none";//hide the tag
						}
					}
					smallImage.onerror = noImageToDisplay;//Setup the onerror for when there is no image.
					document.getElementById('jumperLink').href = 'cartes_' + lang + '.html?datecour=' + datecourVal + '&dateprev=' + dateprevVal + '&heure=' + selectedHour + '&type=' + selectedType;
			}//End if(smallImage)
		}//End for j loop
	}//End for i loop
}//End of function/*}}}*/
/*
	This function was taken from the cartes.js file from the origional version of the page.
	*/
function getTempModele(total, maximum, centre){/*{{{*/
	eval('var max = nb'+centre);
	if(centre == "CMC" || centre == "NCEP" && max>maximum)
		if(total == 1) return maximum-1;
		else if (total == 2) return maximum;
		else return total-2;
	else if (centre == "NCEP")
		if (total == 1) return maximum-2;
		else if (total == 2) return maximum-1;
		else if (total == 3) return maximum;
		else return total-3;
	//Should not reach this return.. put in to get rid of strict JS warning
	return false;
}/*}}}*/
/************************************************************************************
	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) var 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].nodeName == "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: openInNewWindow
	Author: Shayne Brioux
	Date: Jan 2008
	Purpose:	The purpose of this function is to open the requested image into a new
				window when the image is clicked on.
**************************************************************************************/
function openInNewWindow(e){/*{{{*/
	if(!e) e = window.event;//Get a handle to the called event
		if(e.target){//For FF
			window.open(e.target.src);//Open the src of the img in the new window
		} else {//For other rendering engines.. IE for example
			window.open(e.srcElement.src);//Open the src of the img in the new window
		}
}/*}}}*/
/***************************************************************************************
	Function: checkButtons
	Authour: Shayne Brioux
	Date: Jan 2008
	Purpose:	The purpose of this function is to check all the current dates on the web 
				page and then either display or hide any of the buttons according to the 
				spec of the page.
***************************************************************************************/
function checkButtons(){/*{{{*/
	var issuedDaysBack = 31;//Number issued days you are allowed to go backwards

	//Get handles to the issued date buttons
	var issuedDayLeft = document.getElementById('decrement');
	var issuedDayLeftBott = document.getElementById('decrementBott');
	var issuedDayRight = document.getElementById('increment');
	var issuedDayRightBott = document.getElementById('incrementBott');
	//Get a handle to the forcast Date buttons
	var forcastStartLeft = document.getElementById('left_button2');
	var forcastStartLeftBott = document.getElementById('left_button2Bott');
	var forcastStartRight = document.getElementById('right_button2');
	var forcastStartRightBott = document.getElementById('right_button2Bott');
	
	if(hasThreeControls()){
		var issuedDayLeftMidd = document.getElementById('decrementMidd');
		var issuedDayRightMidd = document.getElementById('incrementMidd');
		var forcastStartLeftMidd = document.getElementById('left_button2Midd');
		var forcastStartRightMidd = document.getElementById('right_button2Midd');
	}


	var currIssDate = zeroTheHours(issDate);//Zero out the hours
	var currForStrDate = zeroTheHours(strDate);//Zero out the hours

	//Setup all the dates that the buttons should be disabled on for comparison
	var issDisableDateStr = zeroTheHours(new Date());
	issDisableDateStr.setDate(issDisableDateStr.getDate() - issuedDaysBack);
	var issDisableDateFin = zeroTheHours(new Date());
	var strDisableDateStr = zeroTheHours(new Date());
	strDisableDateStr.setFullYear(issDate.getFullYear(),issDate.getMonth(),issDate.getDate()+1);
	var strDisableDateFin = zeroTheHours(new Date());
	strDisableDateFin.setFullYear(issDate.getFullYear(),issDate.getMonth(),issDate.getDate()+14);
	
	if(Date.parse(currIssDate) >= Date.parse(issDisableDateFin)){
		issuedDayRight.disabled="disabled";
		(hasThreeControls())? issuedDayRightMidd.disabled="disabled" :false;
		issuedDayRightBott.disabled="disabled";
	} else {
		issuedDayRight.disabled = "";
		(hasThreeControls())? issuedDayRightMidd.disabled = "" : false;
		issuedDayRightBott.disabled = "";
	}
	if(Date.parse(currIssDate) <= Date.parse(issDisableDateStr)){
		issuedDayLeft.disabled = "disabled";
		(hasThreeControls())? issuedDayLeftMidd.disabled = "disabled" : true;
		issuedDayLeftBott.disabled = "disabled";
	} else {
		issuedDayLeft.disabled = "";
		(hasThreeControls())? issuedDayLeftMidd.disabled = "" : false;
		issuedDayLeftBott.disabled = "";
	}
	if(Date.parse(currForStrDate) > Date.parse(strDisableDateStr)){
		forcastStartLeft.disabled = "";
		(hasThreeControls())? forcastStartLeftMidd.disabled = "" : false;
		forcastStartLeftBott.disabled = "";
	} else {
		forcastStartLeft.disabled = "disabled";
		(hasThreeControls())? forcastStartLeftMidd.disabled = "disabled" : false;
		forcastStartLeftBott.disabled = "disabled";
	}
	if(Date.parse(currForStrDate) > Date.parse(strDisableDateFin)){
		forcastStartRight.disabled = "disabled";
		(hasThreeControls())? forcastStartRightMidd.disabled = "disabled" : false;
		forcastStartRightBott.disabled = "disabled";
	} else {
		forcastStartRight.disabled = "";
		(hasThreeControls())? forcastStartRightMidd.disabled = "" : false;
		forcastStartRightBott.disabled = "";
	}

	strDisableDateFin.setDate(strDisableDateFin.getDate() + 1);
	//Start of date adjustments
	if(currForStrDate > strDisableDateFin){
		forecastDec();
	}
	if(currForStrDate <= currIssDate){
		forecastInc();
	}
	//end of date adjustments
}/*}}}*/
/*************************************************************************************
	Function:	zeroTheHours(Date)
	Authour:		Shayne Brioux
	Date: 		Jan 2008
	Purpose:		The purpose of this function is to set the hour,minute,seconds and
					milliseconds within the date variable to 0 for easier comparison
					later
	reutrn:		The newly zero'd out date
	variables:	date - a Date() variable
*************************************************************************************/
function zeroTheHours(date){/*{{{*/
	date.setHours(0);
	date.setMinutes(0);
	date.setSeconds(0);
	date.setMilliseconds(0);
	return date;
}/*}}}*/
/***********************************************************************************
Function:	getHoursDiff(year1,month1,day1,year2,month2,day2)
Authour: 	unknown
Date:			unknown
Purpose:		From what I can tell this function will calculate the number of hours
				difference between the first and the second date.  Then the function
				will return the number of hours calculated.  Again this function was
				taken from the origional version of the JS for the cartes page.
*************************************************************************************/
function getHoursDiff(year1,month1,day1,year2,month2,day2){/*{{{*/
	var date1 = new Date(year1,month1-1,day1);
	var date2 = new Date(year2,month2-1,day2);
	var 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 typeHourBox = document.getElementById('heure');
	var selectedHour = typeHourBox[typeHourBox.selectedIndex].value;
	if(selectedHour == "12") diff = diff - parseInt(selectedHour);
	if(diff < 10)
		return "00"+diff
	else if (diff < 100)
		return "0"+diff
	else return diff;
}/*}}}*/
function getVariablesFromUrl(){/*{{{*/
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	var newVariables = new Array();
	for(var i = 0; i < vars.length; i++){
		var pair = vars[i].split("=");
		newVariables[pair[0]] = pair[1];
	}
	var issuedDate = newVariables['datecour'].split("-");
	var forecastStartDate = newVariables['dateprev'].split("-");
	issDate = new Date(issuedDate[0],issuedDate[1]-1,issuedDate[2]);
	strDate = new Date(forecastStartDate[0], forecastStartDate[1]-1,forecastStartDate[2]);
	
	var hourBox = document.getElementById('heure');
	hourBox.selectedIndex = (newVariables['heure'] == "12")? 1 : 0;

	var typeBox = document.getElementById('type');
	for(var count = 0; count < typeBox.length; count++){
		if(typeBox[count].value == newVariables['type']){
			typeBox.selectedIndex = count;
		}
	}
}/*}}}*/

