/*----------------------------------------------------------------
 * NAME : controle.js
 * FUNCTION : control validation
 * ORIGIN : GFI Informatique
 * PROJECT : multi-missions 3DView
 *----------------------------------------------------------------
 * HISTORY
 * VERSION : 20/01/2006 : GFI
 *	creation
 * END-HISTORY
 * ----------------------------------------------------------------*/

/* RCS $Id: controle.js,v 1.2 2009/11/10 16:43:14 lbeigbed Exp $ */



/************************** VARIABLES ***************************/
//memorize the plot type selected
plotType = 0;
listType = 0;

//memorize the start & stop time
//timeStart =  "2000/01/01 14:00:00"; /* the beginning of Rosetta mission */
//DM117
timeStart =  "null";
timeStop = initTime("stop");

//memorize the current help page
helppage = "home_help.html";

//begin of generic control DM078
/*************************** ARRAYS *****************************/
// This array contains the mapping between CGI Name and Fields which need light control
// !!! WARNING! The same unauthorized values are discribed on server side
//  DO NOT FORGET TO UPDATE SERVER SIZE IN CASE OF MODIFICATION !!!
var JSlstFieldsLight = new Array();
 JSlstFieldsLight[0]= new Array("cgi.exe", "field");




/************************** FONCTIONS ***************************/

/*----------------------------------------------------------------
 * FONCTION :  checks if a character belongs to the authorized characters set
 * PARAMETRES :
 * 	valeur - ascii value of character to check
 * 	type - control type : LIGHT or STANDARD
 * RETURN  (true) if unauthorized character
 *----------------------------------------------------------------*/
function unauthorizedChar(value, typeControl)
// !!! WARNING! The same unauthorized values are described on server side
//  DO NOT FORGET TO UPDATE SERVER SIZE IN CASE OF MODIFICATION !!!
{
	if (typeControl == "STANDARD") {
		/* standard control */
		/* characters authorized are :
		 * SPACE (code 32)
		 * ! (code 33) + (code 43) , (code 44) - (code 45) . (code 46)
		   / (code 47) 
		 * from 0 to 9 (code 48 to 57)
		 * : (code 58) = (code 61) ? (code 63) @ (code 64)
		 * from A to Z (code 65 to 90)
		 * [ (code 91) \ (code 92) ] (code 93) _ (code 95)
		 * from a to z (code 97 to 122)
		 * accentuate characters (from 192 to 255)
		 */
		return ((value<32) ||
		((value>33)&&(value<43)) ||
		((value>58)&&(value<61)) ||
		(value==62) ||
		(value==94) ||
		(value==96) ||
		((value>122)&&(value<160)) ||
		((value>160)&&(value<192)) ||
		(value>255));
	}
	else {
		/* "light control "*/
		/* the list of the standard control is completed with:
		 * RETURN --> NL (code 10) and CR (code 13)
		 * " (code 34) # (code 35) % (code 37) & (code 38) ' (code 39)
		 * ( (code 40) ) (code 41) * (code 42) < (code 60) > (code 62)
		 * ` (code 96) ~ (code 126) ° (code 176) µ (code 181) */
		return ((value<10) ||
		((value>10)&&(value<13)) ||
		((value>13)&&(value<32)) ||
		(value==36) ||
		(value==59) ||
		(value==94) ||
		((value>122)&&(value<126)) ||
		((value>126)&&(value<160)) ||
		((value>160)&&(value<176)) ||
		((value>176)&&(value<181)) ||
		((value>181)&&(value<192)) ||
		(value>255));
	}
}


/*--------------------------------------------------------------------------
* NAME : initTime
* FUNCTION: Init START & STOP Time in textbox relative to current days
* ORIGIN : GFI INFORMATIQUE
* PROJECT : multi-missions 3DView
* PARAMETERS:
*		param : 'start' ou 'stop'
* RETURN :
*    formated time
----------------------------------------------------------------------------*/

function initTime(param){


	var millisec = parseInt(Date.parse(new Date().toString()),10);
	var millisec48h=172800000; //48h*60*60*1000

	if (param == "start") {
		var tmpTime = new Date(millisec-millisec48h);
	}
	else {
		var tmpTime = new Date(millisec);
	}

	var sDate = tmpTime.getDate();


	//init month
	if ((tmpTime.getMonth()+1) < 10)
		month = "0"+ (tmpTime.getMonth()+1);
	else
		month = (tmpTime.getMonth()+1);
	//init day
	if (sDate < 10)
		day = "0"+ sDate;
	else
		day = sDate;
	//init hours
	if (tmpTime.getHours() < 10)
		hours = "0"+ (tmpTime.getHours());
	else
		hours = (tmpTime.getHours());
	//init minutes
	if (tmpTime.getMinutes() < 10)
		minutes = "0"+ (tmpTime.getMinutes());
	else
		minutes = (tmpTime.getMinutes());
	//init seconds
	if (tmpTime.getSeconds() < 10)
		seconds = "0"+ (tmpTime.getSeconds());
	else
		seconds = (tmpTime.getSeconds());

	var sTime = y2k(tmpTime.getYear()) + "/" + month + "/" + day + " "
					  + hours + ":" + minutes + ":" + seconds;

	return sTime;
}


function y2k(number) { return (number < 1000) ? number + 1900 : number; }




/*--------------------------------------------------------------------------
 * NAME : selectAll
 * FUNCTION : selects all the check boxes in the list
 * ORIGIN : GFI INFORMATIQUE
 * PROJECT : multi-missions 3DView
 * PARAMETERS :
 *    frmList : current form
 * RETURN :
 * ------------------------------------------------------------------------*/

function selectAll(frmList){
	var len;
	var i=0;
	var totalsize=parseFloat('0.00');

	if (frmList.nbLines.value == 1) {
	    frmList.chkSelect.checked = true;
  	    totalsize = parseFloat(frmList.hidData.value);
        }
	else {
	  len = frmList.chkSelect.length;
	  for (i=0;i<len;i++) {
		frmList.chkSelect[i].checked = true;
		totalsize = totalsize + parseFloat(frmList.hidData[i].value);
	  }
	}

	frmList.txtfilesize.value=totalsize;
}


/*--------------------------------------------------------------------------
 * NAME : deselectAll
 * FUNCTION : Unselects all the check boxes of the list
 * ORIGIN : GFI INFORMATIQUE
 * PROJECT : multi-missions 3DView
 * PARAMETERS :
 *    frmList : current form
 * RETURN :
 * ------------------------------------------------------------------------*/

function deselectAll(frmList) {
	var len;
	var i=0;

	if (frmList.nbLines.value == 1){
	    frmList.chkSelect.checked = false;
        }
	else {
	  len = frmList.chkSelect.length;
	  for (i=0;i<len;i++){
		frmList.chkSelect[i].checked = false;
	  }
	}

	frmList.txtfilesize.value = parseFloat('0.00');
}


function checkingResults(formFiche) {
	var len;
	var i;
	var msg="No checkbox selected";

        if(formFiche.nbLines.value == 1) {
		if(formFiche.chkSelect.checked) {
			msg ="";
		}
	}
	else {
		len = formFiche.nbLines.value;
		for(i=0;i<len;i++) if (formFiche.chkSelect[i].checked) msg="";
        }

	// If NOK, we display alert message
	if (msg != "") {
		alert(msg);
		msg="";
	}
	else {	// If OK, we submit the form
	  //formFiche.submit();
	  genericControl (formFiche);
	}
}



/*--------------------------------------------------------------------------
 * NAME : isValidDate
 * FUNCTION :   Checks the validity of a date
 * ORIGIN : GFI INFORMATIQUE
 * PROJECT : multi-missions 3DView
 * PARAMETERS :
 *    myDate : date (textbox) to check
 * RETURN :
 * ------------------------------------------------------------------------*/

function isValidDate (myDate) {

	/* Separators */
	var sepDate = "/";
	var sepTime = ":";
	var sepDT = " ";

	/* Bad items into strings */
	var expo = "e";
	var virg = ".";


	/* Format : 'YYYY/MM/DD HH24:MI:SS' */

	/* Check if separators are ok */
	if ( (myDate.value.length != 19)
		|| (myDate.value.indexOf(sepDate) != 4)
		|| (myDate.value.lastIndexOf(sepDate) != 7)
		|| (myDate.value.indexOf(sepDT) != 10)
		|| (myDate.value.indexOf(sepTime) != 13)
		|| (myDate.value.lastIndexOf(sepTime) != 16)) {

		return false;
	}

	/* Get the fields */
	var year = myDate.value.substring(0,4);
	var month = myDate.value.substring(5,7);
	var day = myDate.value.substring(8,10);

	var hours = myDate.value.substring(11,13);
	var minutes = myDate.value.substring(14,16);
	var seconds = myDate.value.substring(17);


	/* Is it a number ? */
	if (isNaN(year)) return false;
	if (isNaN(month)) return false;
	if (isNaN(day)) return false;
	if (isNaN(hours)) return false;
	if (isNaN(minutes)) return false;
	if (isNaN(seconds)) return false;


	/* Is there bad characters ? */
	if ((year.indexOf(expo) >= 0) || (year.indexOf(virg) >= 0)) return false;
	if ((month.indexOf(expo) >= 0) || (month.indexOf(virg) >= 0)) return false;
	if ((day.indexOf(expo) >= 0) || (day.indexOf(virg) >= 0)) return false;
	if ((hours.indexOf(expo) >= 0) || (hours.indexOf(virg) >= 0)) return false;
	if ((minutes.indexOf(expo) >= 0) || (minutes.indexOf(virg) >= 0)) return false;
	if ((seconds.indexOf(expo) >= 0) || (seconds.indexOf(virg) >= 0)) return false;


	/* Is it in the range ? */
	if (parseInt(year, 10) < 0) return false;
	if ((parseInt(month, 10) < 1) || (parseInt(month, 10) > 12)) return false;
	if ((parseInt(day, 10) < 1) || (parseInt(day, 10) > 31)) return false;
	if ((parseInt(hours, 10) < 0) || (parseInt(hours, 10) > 23)) return false;
	if ((parseInt(minutes, 10) < 0) || (parseInt(minutes, 10) > 59)) return false;
	if ((parseInt(seconds, 10) < 0) || (parseInt(seconds, 10) > 59)) return false;


	/* It's fine !! */
	return true;
}


/*--------------------------------------------------------------------------
 * NAME : openPopup
 * FUNCTION :   displays a page in a popup window
 * ORIGIN : GFI INFORMATIQUE
 * PROJECT : 3DView Multimission
 * PARAMETERS :
 *    urlpage : page url to display
 * RETURN :
 * ------------------------------------------------------------------------*/
function openPopup(urlpage) {
	return openPopup(urlpage,600,600);
}

/*--------------------------------------------------------------------------
 * NAME : openPopup
 * FUNCTION :   displays a page in a popup window with defined width and height
 * ORIGIN : GFI INFORMATIQUE
 * PROJECT : 3DView Multimission
 * PARAMETERS :
 *    urlpage : page url to display
 *    xsize : popup width
 *    ysize : popup height
 * RETURN :
 * ------------------------------------------------------------------------*/
function openPopup(urlpage, xsize, ysize) {

	if (!top.popup || top.popup.closed) {
		top.popup = window.open("", "popupTarget","width="+xsize+",height="+ysize+",status=yes,menubar=no,resizable=yes,scrollbars=yes" );
		top.popup.location.href= urlpage;
	}else{
		top.popup.location.href= urlpage;
		top.popup.focus();
	}
	return true;
}


/*-----------------------------------------------------
* FONCTION : genericControl
* BUT: 	controle les caractères saisis dans les zones
*		de texte (type text ou textarea)
* PARAMETRES: form
-------------------------------------------------------*/
function genericControl(currForm){

	//retrieve the action value (cgi name)
	var lastslash = (currForm.action).lastIndexOf("/");
	if (lastslash >= 0) {
		var actionValue = (currForm.action).substr(lastslash + 1);
	}
	else {
		var actionValue = currForm.action;
	}

	var unauthorized=false;

	// detection of text fields an texarea fields in the form
	for (var i = 0; i < currForm.elements.length; i++)
	{
		var isLight = false;

		if ((currForm.elements[i].type =='textarea') || (currForm.elements[i].type =='text')) {

			if (actionValue == "")
				{
				// we are in a popup
				actionValue = "popup";
				}

			// check if the field is in the JSlstFieldsLight array (light controls)
			for (var j = 0; j < JSlstFieldsLight.length; j++) {
				if ((JSlstFieldsLight[j][0]==actionValue) && (JSlstFieldsLight[j][1]==currForm.elements[i].name)) {
					isLight = true;
				}
			}

			// check the characters in the field
			for (var k = 0; k < currForm.elements[i].value.length; k++) {

				value = currForm.elements[i].value.charCodeAt(k);

				if (isLight == true) {
					if (unauthorizedChar(value, "LIGHT")==true){
						unauthorized=true;
					}
				}
				else {
					if (unauthorizedChar(value, "STANDARD")==true){
						unauthorized=true;
					}
				}
			}
			if (unauthorized == true) {
				currForm.elements[i].focus();
				//alert("The field " + currForm.elements[i].name + " contains unauthorized characters !");
				alert("The field " + currForm.elements[i].name + " contains unauthorized characters !");
				break;
			}

		}
	}
	 // submit the form in all characters are authorized
	if (unauthorized == false) {
		return true;
	}
	else{
		return false;
	}

}

//end of generic control

/*--------------------------------------------------------------------------
 * NAME : controleAuxiOA3DData
 * FUNCTION :   Check mandatory fields on topframe
 * ORIGIN : GFI INFORMATIQUE
 * PROJECT : multi-missions 3DView
 * PARAMETERS :
 *    form : current form
 * RETURN :
 * ------------------------------------------------------------------------*/

function topframeControl(form){

		// Check of the start date
		if (isValidDate(form.txtStart) == false) {
			alert("Invalid UT Start Time format !");
			return;
		}

		// Check of the stop date
		if (isValidDate(form.txtStop) == false) {
			alert("Invalid UT Stop Time format !");
			return;
		}

		// Check of the scheduling of the date
		if (form.txtStop.value < form.txtStart.value) {
			alert("The UT Start Time cannot be greater than the UT Stop Time !");
			return false;
		}

		timeStart = form.txtStart.value;
		timeStop = form.txtStop.value;



	return genericControl (form);

}

/*--------------------------------------------------------------------------
 * NAME : resultFrameControl
 * FUNCTION :   Check mandatory fields on resultframe
 * ORIGIN : GFI INFORMATIQUE
 * PROJECT : multi-missions 3DView
 * PARAMETERS :
 *    form : current form
 * RETURN :
 * ------------------------------------------------------------------------*/

function resultframeControl(form){

	if ((form.txtStep.value == "") || (isNaN(form.txtStep.value)) ) {
		alert("time step is mandatory and must be numeric !");
		return false;
	}

	if(form.txtStep.value!=0){
		nbMaxValues = (form.dtEnd.value-form.dtBeg.value)/(form.txtStep.value/86400);
		if(nbMaxValues>form.maxPlotSamples.value){
			if(!confirm('If you choose to plot with this time step, visualisation may not work properly. Please, increase time step value.\nContinue plotting?'))
				return false;
		}
	}

	return genericControl (form);

}


