/*
----------------------------------------------------------------------------------
Main JavaScript validation 
----------------------------------------------------------------------------------
   Version        Date        	Name      	Desc
      1.0	  24/06/2008  		AEK			Validation for form fields 
      					                    This file is the template for the 
      					                    JavaScript validation files that are 
      					                    written out for each form
      					                    in the format ValidateFormXXXXXXXXX.js
      					                    where XXXXXXXXX is the name of the 
      					                    GalleryTemplate having the associated 
      					                    form. The association is established 
      					                    in the TemplatesForSectionTypes table.
      					                    
      					                    WARNING!!!! DO NOT CHANGE THIS FILE!!! (please)
----------------------------------------------------------------------------------
*/

//Dynamic Code starts here >>>>>

//==================================
function validateFields(strMessage, strValidationFields) {
var el = document.getElementById("ItemTitle");
//var star = "*";
//var quote = "'";
//strValidationFields = strValidationFields.replace("*","'")
var strVF = strValidationFields.replace(/\*/g, "'");

var fieldValPairs = strVF.split("|");
var OK = false;
var fieldMsg = "";
var allMessages = "";
//alert ("strValidationFields = " + strValidationFields);
if (el.value == "") {
	allMessages = strMessage
	el.focus();
} 
//debugger;
if (strValidationFields != "") {
	for(var i = 0; i < fieldValPairs.length; i++) {
		fieldMsg = eval(fieldValPairs[i]);
		if ( fieldMsg == "") { //e.g. eval(      IsNumeric("i", "txtSize", "Size")      )
			//OK!
		} else {
			if (allMessages == "") {
				allMessages = fieldMsg;
			} else {	
				allMessages += "\n" + fieldMsg;
			}
		}
	}
}	

if (allMessages != "") {
	OK = false; 
    alert(allMessages);
} else {
		OK = true; 
}
return OK;
}   
//==========================

function IsNotEmpty(id, strLiteral)
	{
	var el = document.getElementById(id);
	var fieldMsg = "";
	var pos = 0;
	var cleanLiteral = strLiteral;
	pos = cleanLiteral.indexOf("(");
	if (pos != -1 )
		{
		cleanLiteral = trim(cleanLiteral.substr(0,pos-1)); //remove anything in brackets from the literal to give the field name
		}
	if (el.type=='select-one')
		{//it's a multiselect field, need more intelligent checking
		if (el.length==0)
			{
			fieldMsg = cleanLiteral + " cannot be empty";
			}
		}
	else
		{//not multiselect, default to simply checking the value
		if (el.value == "")
			{
			fieldMsg = cleanLiteral + " cannot be empty";	
			}
		}
	return fieldMsg
	}
//==========================

function IsValidDate(id, strLiteral) {
var el = document.getElementById(id);
var OK = true;
var posSlash1 = el.value.indexOf("/");
var posSlash2 = el.value.lastIndexOf("/");
var fieldMsg = "";
//debugger;
if (el.value == "") {
	OK = false;
} else if (posSlash1 != 2) {
	OK = false;
} else if (posSlash2 != 5) {
	OK = false;
} else if (el.value.length != 10) {
	OK = false;
} else if (!CheckIfNumeric(el.value.substr(0,2))) {
	OK = false;
} else if (!CheckIfNumeric(el.value.substr(3,2))) {
	OK = false;
} else if (!CheckIfNumeric(el.value.substr(6,4))) {
	OK = false;		
} else {
	var monthMinus1 = parseInt(el.value.substr(3,2) -1);
	if (!ValidDateIsOK(parseInt(el.value.substr(0,2)), monthMinus1, parseInt(el.value.substr(6,4)))) {
		OK = false;	
	}
}
var pos = 0;
var cleanLiteral = strLiteral;
pos = cleanLiteral.indexOf("(");
if (pos != -1 ) {
	cleanLiteral = trim(cleanLiteral.substr(0,pos-1)); //remove anything in brackets from the literal to give the field name
}
if (!OK) {
	fieldMsg = cleanLiteral + " must be a valid date in the format dd\/mm\/yyyy";	
}
return fieldMsg
}
//==========================
function trim(stringToTrim) { 
return stringToTrim.replace(/^\s+|\s+$/g,""); 
}
//==========================
function ValidDateIsOK(day,month,year){
/*
NOTE!! The month needs to be a 0 (zero) for Jan, upto 11 to Dec. (hence the wrapper function IsValidDate above)
Purpose: return true if the date is valid, false otherwise

Arguments: day integer representing day of month
month integer representing month of year
year integer representing year

Variables: dteDate - date object

*/
var dteDate;

//set up a Date object based on the day, month and year arguments
//javascript months start at 0 (0-11 instead of 1-12)
dteDate=new Date(year,month,day);

/*
Javascript Dates are a little too forgiving and will change the date to a reasonable guess if it's invalid. 
We'll use this to our advantage by creating the date object and then comparing it to the details we put it. 
If the Date object is different, then it must have been an invalid date to start with...
*/

return ((day==dteDate.getDate()) && (month==dteDate.getMonth()) && (year==dteDate.getFullYear()));
}

//new calendar validation function
function IsCalendarDate(id, strLiteral) {
var el = document.getElementById(id);
var strText = el.value;
var tempText = "";
var dayText = "";
var monthText = "";
var dayNumText = "";
var yearText = "";
var msg = "";
var pos = 0;
var cleanLiteral = strLiteral;
pos = cleanLiteral.indexOf("(");
if (pos != -1 ) {
	cleanLiteral = trim(cleanLiteral.substr(0,pos-1)); //remove anything in brackets from the literal to give the field name
}

//check string is of length 16 or 17
if (strText.length!=16 && strText.length!=17) {
	msg = cleanLiteral + ' must be a valid date. Please use the datepicker.';
	return msg;
}

//check day string
tempText = strText.substr(0,3);
if (tempText!='Mon' && tempText!='Tue' && tempText!='Wed' && tempText!='Thu' && tempText!='Fri' && tempText!='Sat' && tempText!='Sun') {
	msg = cleanLiteral + ' must be a valid date. Please use the datepicker.';
	return msg;
}
dayText = tempText;

//check divider is ", "
if (strText.substr(3,2)!=', ') {
	msg = cleanLiteral + ' must be a valid date. Please use the datepicker.';
	return msg;
}

//remove day and divider
strText = strText.substr(5,strText.length - 5);

//check month string
tempText = strText.substr(0,3);
if (monthNumber(tempText)==-1) {
//if (tempText!='Jan' && tempText!='Feb' && tempText!='Mar' && tempText!='Apr' && tempText!='May' && tempText!='Jun' && tempText!='Jul' && tempText!='Aug' && tempText!='Sep' && tempText!='Oct' && tempText!='Nov' && tempText!='Dec') {
	msg = cleanLiteral + ' must be a valid date. Please use the datepicker.';
	return msg;
}
monthText = tempText;

//check divider is " "
if (strText.substr(3,1)!=' ') {
	msg = cleanLiteral + ' must be a valid date. Please use the datepicker.';
	return msg;
}

//remove month and divider
strText = strText.substr(4,strText.length - 4);

//search for ","
pos = strText.indexOf(',');
if (pos==-1) {	//not found
	msg = cleanLiteral + ' must be a valid date. Please use the datepicker.';
	return msg;
}
if (pos!=1 && pos!=2) {		//not in right place
	msg = cleanLiteral + ' must be a valid date. Please use the datepicker.';
	return msg;
}

//check divider is ", "
if (strText.substr(pos,2)!=', ') {
	msg = cleanLiteral + ' must be a valid date. Please use the datepicker.';
	return msg;
}

//check daynumber is a number
tempText = strText.substr(0,pos);
if (!CheckIfPurelyNumeric(tempText)) {
	msg = cleanLiteral + ' must be a valid date. Please use the datepicker.';
	return msg;
}
dayNumText = tempText;

//check year
strText = strText.substr(pos + 2,strText.length - pos - 2);
if (strText.length!=4) {
	msg = cleanLiteral + ' must be a valid date. Please use the datepicker.';
	return msg;
}
if (!CheckIfPurelyNumeric(strText)) {
	msg = cleanLiteral + ' must be a valid date. Please use the datepicker.';
	return msg;
}
yearText = strText;

var dayNumInt = parseInt(dayNumText);
var yearInt = parseInt(yearText);

//check date is actually real
if (dayNumInt < 1 || dayNumInt > 31) {	//impossible day number
	msg = cleanLiteral + ' must be a valid date. Please use the datepicker.';
	return msg;
}
if (dayNumInt==31 && (monthText=='Feb' || monthText=='Sep' || monthText=='Apr' || monthText=='Jun' || monthText=='Nov')) {
//too many days
	msg = cleanLiteral + ' must be a valid date. Please use the datepicker.';
	return msg;
}
if (dayNumInt==30 && monthText=='Feb') {	//too many for february
	msg = cleanLiteral + ' must be a valid date. Please use the datepicker.';
	return msg;
}
//check for leap year
var isLeap = false;
if (yearInt%4==0) {
	isLeap = true;
}
if (isLeap)	{
	if (yearInt%100==0 && yearInt%400!=0) {
	isLeap = false;
	}
}
if (dayNumInt==29 && monthText=='Feb' && !isLeap) {
//too many for feb in a non leap year
	msg = cleanLiteral + ' must be a valid date. Please use the datepicker.';
	return msg;
}

//check dayText is valid for date
var monthInt = monthNumber(monthText);
var myDate = new Date(yearInt,monthInt - 1,dayNumInt);
var dayNames = new Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat");
var proposedDayText = dayNames[myDate.getDay()];
if (proposedDayText!=dayText) {
	msg = cleanLiteral + ' must be a valid date. Please use the datepicker.';
	return msg;
}

return msg;

}

function monthNumber(monthString) {
var monthNames = new Array ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
for (i=0;i<=11;i++) {
	if (monthNames[i]==monthString) {
	var monthInt = i + 1
	return monthInt
	}
}
return -1;
}

//==========================
function IsNumeric(strMode, id, strLiteral) {
var el = document.getElementById(id);
var strText = el.value;
var ValidChars = "0123456789";
var IsNum=true;
var validationMsg = "";
var char = "";
var msg = "";
var pos = 0;
var cleanLiteral = strLiteral;
pos = cleanLiteral.indexOf("(");
if (pos != -1 ) {
	cleanLiteral = trim(cleanLiteral.substr(0,pos-1)); //remove anything in brackets from the literal to give the field name
}

//alert("here we go strMode = " + strMode + "  id = " +id);
if (strMode == "i") { //any +ve integer
   ValidChars = "0123456789";
   msg = cleanLiteral + " must be a positive whole number ";
} else if (strMode == "d") {  //any +ve decimal
	ValidChars = "0123456789.";
	msg = cleanLiteral + " must be a positive number ";
} else if (strMode == "-") {  //any number
	ValidChars = "0123456789.-";	
	msg = cleanLiteral + " must be a number ";
} else if (strMode == "z") {  //cannot be 0
	ValidChars = "0123456789.";	//must be > 0	
	msg = cleanLiteral + " must be greater than 0 ";
} else if (strMode == "-i") {  //any  integer
	ValidChars = "0123456789-";	
	msg = cleanLiteral + " must be a whole number ";
}

if (el.value == "") {
	fieldMsg = cleanLiteral + " cannot be a zero length string";	
	IsNum = false;
} else {
		for (i = 0; i < strText.length && IsNum == true; i++) { 
		   Char = strText.charAt(i); 
		   if (ValidChars.indexOf(Char) == -1) {
		      IsNum = false;
		   }
		}
		if (IsNum) {
			if (isNaN(strText))   {
				IsNum = false;
				msg = cleanLiteral + " must be numeric";
			} 		
		}		
}

if (!IsNum) {
	validationMsg = msg;
}
   
return validationMsg;

}   
//==================================
function CheckIfNumeric(strString)
   //  check for valid numeric strings	
   {
   var strValidChars = "0123456789.-";
   var strChar;
   var blnResult = true;

   if (strString.length == 0) return false;

   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         }
      }
   return blnResult;
   }

function CheckIfPurelyNumeric(strString)
   //  check for valid numeric strings	
   {
   var strValidChars = "0123456789";
   var strChar;
   var blnResult = true;

   if (strString.length == 0) return false;

   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         }
      }
   return blnResult;
   }

function checkStringOnlyIncludes(strString,strIncludes)	{
	var blnResult = true;
	var strChar;
	if (strIncludes.length==0)
		{blnResult = false;}
	else
		{
		for (i = 0; i < strString.length && blnResult == true; i++)
			{
			strChar = strString.charAt(i);
			if (strIncludes.indexOf(strChar) == -1)
				{
				blnResult = false;
				}
			}
		}
	return blnResult;
	}

//==================================
function validateName(strMessage) {
var el = document.getElementById("ItemTitle");
var OK = true;
//alert ("In!");
if (el.value == "") {
	alert (strMessage);
	el.focus();
	OK = false;
}
	
return OK;
}   
//==========================
//Dynamic Code ends here <<<<<

function moveListItem(lbSourceID,lbTargetID,txtHiddenToStoreIn,blnAdd)
	{
	var isIE = true;
	if (navigator.userAgent.indexOf('Firefox') != -1)
		{
		isIE = false;
		}
		
	var lbSource = document.getElementById(lbSourceID);
	var lbTarget = document.getElementById(lbTargetID);
	var realSource;
	var realTarget;
	//"real" means the actual source/target. i.e. the real source is where the item is going from, the real target is where the target is going to
	//the basic lbSource/lbTarget variables represent the left/right listboxes respectively.
	if (blnAdd)
		{
		realSource = lbSource;
		realTarget = lbTarget;
		}
	else
		{
		realSource = lbTarget;
		realTarget = lbSource;
		}
	if (realSource.selectedIndex==-1)
		{//no item selected in source
		return false;}

	//get current value of the hidden string - always blank on pageload
	var inputHidden = document.getElementById(txtHiddenToStoreIn);
	var txtHidden = inputHidden.value;
	var txtNewHidden = '';
	
	//setup the array of current values being sent as hidden, i.e. if a multiselect has already been changed
	var strHiddenArray = new Array();
	if (txtHidden.length==0)
		{//blank string
		strHiddenArray[0] = '';
		}
	else if (txtHidden.indexOf(";")==-1)
		{//one entry
		strHiddenArray[0] = txtHidden;
		}
	else
		{//split the string into the array
		strHiddenArray = txtHidden.split(";");
		}
	
	//loop through array and if start of string is the targetID then set that element to blank
	for (i=0;i<strHiddenArray.length;i++)
		{
		var curElement = strHiddenArray[i];
		if (curElement.length > lbTargetID.length)
			{
			if (curElement.indexOf(lbTargetID)!=-1)
				{//found the string that passes this multiselect's value to the postback function, set it to blank, we'll add the new value later
				strHiddenArray[i] = '';
				}
			}
		}
	//we now have a set of elements of the strings we're NOT currently changing. We'll use it later to rebuild the hidden string.
	//they may all be blank
			
	//move the listitem
	var itemValue = realSource.options[realSource.selectedIndex].value;
	var itemText = realSource.options[realSource.selectedIndex].text;
	realSource.remove(realSource.selectedIndex);
	var optNew = document.createElement("OPTION");
	newOpt = new Option(itemText,itemValue);
	//find the position for new option
	//loop through items in realTarget and check itemValue against value of item
	var nItemsInTarget = realTarget.length;
	var indexOfItemAfter = -1;
	for (k=0;k<nItemsInTarget;k++)
		{
		var targetItemValue = realTarget.options[k].value;
		if (parseInt(itemValue) < parseInt(targetItemValue))
			{//new value has lower value than this item, put new item before this item and exit loop
			indexOfItemAfter = k;
			break;
			}
		}
	if (indexOfItemAfter==-1)
		{//put item at the end
		if (isIE)
			{realTarget.add(newOpt,realTarget.length);}
		else
			{realTarget.add(newOpt,null);}
		}
	else
		{//put the item before the item indexOfItemAfter
		if (isIE)
			{realTarget.add(newOpt,indexOfItemAfter);}
		else
			{
			var subsequentItem = realTarget.options[indexOfItemAfter];
			realTarget.add(newOpt,subsequentItem);
			}
		}
		
	//build the Target concatenated string
	var strTargetSum = '';
	var intItems = lbTarget.length;
	for (i=1;i<=intItems;i++)
		{
		strTargetSum += lbTarget.options[i-1].text;
		//add comma if not the last item
		if (i!=intItems) {strTargetSum += ',';}
		}
	
	//rebuild the whole hidden string
	for (i=0;i<strHiddenArray.length;i++)
		{
		var curElement2 = strHiddenArray[i];
		if (curElement2!='')
			{//not a blank element, write it to the string with a comma
			txtNewHidden += curElement2 + ';';
			}
		}
	txtNewHidden += lbTargetID + ':' + strTargetSum
	
	//set hidden input value to the new string
	inputHidden.value = txtNewHidden;
		
	return false;	//always return false so button doesn't submit to cause postback
	}

function moveAllListItems(lbSourceID,lbTargetID,txtHiddenToStoreIn,blnAdd)
	{//set source variable to the listbox that the items are being moved FROM
	if (blnAdd)
		{
		var lbRealSource = document.getElementById(lbSourceID);
		}
	else
		{
		var lbRealSource = document.getElementById(lbTargetID);
		}
	var nItems = lbRealSource.length;
	for (j=0;j<nItems;j++)
		{//loop from last item to first, moving each one in turn
		lbRealSource.selectedIndex = 0;
		moveListItem(lbSourceID,lbTargetID,txtHiddenToStoreIn,blnAdd);
		}
	
	return false;	//always return false so button doesn't submit to cause postback
	}
	

