////////////////////////////////////// R E G U L A R     E X P   //////////////
RegExps = new Array();
RegExpsWords = new Array();

RegExps[1] = '^([a-zA-Z0-9_\.\-])+(\\@)+([a-zA-Z0-9_\.\-])+(\\.)+([a-zA-Z0-9_\.\-]{2,})$'
RegExpsWords[1] = 'must be a valid email.'

RegExps[2] = '^((\\+|0){1})+([0-9,\\s]{1,})$'
//RegExps[2] = '^([0-9]{1,})$'
RegExpsWords[2] = 'must be a valid phone number starting with + or 0.'

RegExps[3] = '^([0-9]{1,2})+\/+([0-9]{1,2})+\/+([0-9]{4})$'
RegExpsWords[3] = 'must be a date in format DD/MM/YYYY.'

RegExps[4] = '^([0-9]{1,2})+\:+([0-9]{1,2})+\:+([0-9]{1,2})$'
RegExpsWords[4] = 'must be a time in format HH:MM:SS.'

RegExps[5] = '^([0-9]{1,})$'
RegExpsWords[5] = 'must be a whole number.'

RegExps[6] = '^([0-9]{1,})+(\\.+([0-9]{1}))?$'
RegExpsWords[6] = 'must be a number with none or one decimal place.'

RegExps[7] = '^([0-9]{1,})+(\\.+([0-9]{2}))?$'
RegExpsWords[7] = 'must be a number with none or two decimal places.'

RegExps[8] = '^([[a-zA-Z0-9]{2,4})+\\s+([[a-zA-Z0-9]{2,3})$'
RegExpsWords[8] = 'must be a valid UK post code.'

//////////////////////////////////////////// T I M E    D A T E  ////////////
Now = new Date();
	NowDay = Now.getDate();
	NowMonth = Now.getMonth();
	NowYear = Now.getYear();
	NowHour = Now.getHours();
	NowMin = Now.getMinutes();
	
	if (NowYear < 2000) NowYear += 1900; //for Netscape

function WriteDayOptions()
	{
		line = "";
		for (i=1; i<31; i++)
		{
			var day = ""+i;
			if (day.length == 1) {
				day = "0"+day;
			}
			line += "<OPTION value='"+ day+"'";
			if (i == NowDay){
				line+=" selected='selected' " ;
				}
			line +=">"; //
			line += day;
		}
		return line;
	}
	

function WriteMonthOptions()
	{
		line = "";
		for (i=1; i<=12; i++)
		{
			var month = ""+i;
			if (month.length == 1) {
				month = "0"+month;
			}
			line += "<OPTION value='"+ month+"'";
			if (i == (NowMonth+1)){
				line+=" selected='selected' " ;
				}
			line +=">"; //
			line += month;
		}
		return line;
	}

function WriteYearOptions(YearsAhead)
	{
		line = "";
		
		for (i=-100; i<YearsAhead; i++)
		{
			var year = NowYear + i;
			
			line += "<OPTION value='"+ year+"'";
			if (i == 0){
				line+=" selected='selected' " ;
				}
			line +=">"; //
			line += year;
		}
		return line;
	}

function WriteMinOptions(){
	line = "";
	for (i=0; i<60; i++) {
	 var day = i;
	 	var str = ""+i;
		if (str.length == 1) {
			str = "0"+str;
		}
		line += "<OPTION value='"+ str+"'";
		if (i == NowMin){
			line+=" selected='selected' " ;
			}
		line +=">"; //
		line += str;
	}
	return line;
}
function WriteHourOptions(){
	line = "";
	for (i=0; i<24; i++) {
	 var day = i;
	 	var str = ""+i;
		if (str.length == 1) {
			str = "0"+str;
		}
		line += "<OPTION value='"+ str+"'";
		if (i == NowHour){
			line+=" selected='selected' " ;
			}
		line +=">"; //
		line += str;
	}
	return line;
}


/////////////////////////////////////////// S U B M I T    /////////////////////////////////////
function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
////alert("it exists");
	var radioLength; 
	radioLength= radioObj.length;
////alert("Length is "+ radioLength);
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {

		if(radioObj[i].checked) {

		return radioObj[i].value;
		}

	}
	return "";
}



var numChecked = 0;

function form_submit() {
		var oForm = document.form;
		numChecked = 0;
	//	//alert(InputInfo.length);
		for (i = 0; i < InputInfo.length; i++) {
			
			id = InputInfo[i].ID;
			FieldName = InputInfo[i].FieldName;
			Description = InputInfo[i].Description;		
			Type = InputInfo[i].Type;
			Mandatory = InputInfo[i].Mandatory;
			MaxChars = InputInfo[i].MaxChars;
			MinChars = InputInfo[i].MinChars;
			HintMessage = InputInfo[i].HintMessage;
			ErrorMessageMax = InputInfo[i].ErrorMessageMax;
			ErrorMessageMin = InputInfo[i].ErrorMessageMin;
			//NonSelectable = InputInfo[i].NonSelectable;
			RegExpId = InputInfo[i].RegExpId;
			AddId = InputInfo[i].AddId;
			
			//alert("Q"+i+": "+oForm[FieldName]);
			
			if (oForm[FieldName] != undefined) {
			
			switch(Type){
		  		
		    	case 'textbox': 
					
					ConvertDateTime(FieldName,AddId);
					if (!Validate_Text(oForm[FieldName].value , Mandatory, MaxChars, ErrorMessageMax, MinChars, ErrorMessageMin, Description,i,RegExpId)){
		                 return false;
					}
					
					if (!ValidateTextAgainstText(i)) {
						return false;
					}
					
				break;
		    	case 'radio':  
					////alert("field name: "+oForm);
					if (!Validate_Radio(oForm[FieldName], HintMessage, Mandatory, Description)){
	                    return false;
						}
				break
		    	case 'check':   
					if (!Validate_Check(oForm[FieldName] , HintMessage, Mandatory, Description,i)){
		                    return false;
							}
				break
		    	case 'list':   
					////alert('Found List Item');
					
					if (!Validate_List(oForm[FieldName].value, HintMessage, Mandatory, Description,i)){
	                    return false;
							}
				break;
				case 'textarea':
					ConvertDateTime(FieldName,AddId);
					if (!Validate_Text(oForm[FieldName].value , Mandatory, MaxChars, ErrorMessageMax, MinChars, ErrorMessageMin, Description,i)){
		                 return false;
					}
					if (!ValidateTextAgainstText(i)) {
						return false;
					}
				
				break;
		    	default:    
					////alert("Invalid input type");         
		    }
			} else {
				//alert("UNDEFINED");
				//return true;
			}
		} 
		//------------------------------------------ after validation convert all date values to YYYY-MM-DD
		for (i = 0; i < InputInfo.length; i++) {
			
			ConvertDateTimeForDB(i);
			
		}
}
//--------------------------------------------------------------------------------------------------------------
function ConvertDateTimeForDB (fieldId) {
	var addId = InputInfo[i].AddId;
	var fieldName = InputInfo[i].FieldName;
	//---------------- test if DATE drop downs used:
	if (addId == '1'){
			var dateTxt =  GetDateStrDB(fieldName);
	   		var realField = document.getElementById(fieldName);
			realField.value = dateTxt;
			//alert(dateTxt);
	   		//alert("NEW DATE:" + realField.value);
	//---------------- test if DATETIME drop downs used:
	} else  if (addId == '3'){ 
		
			var dateTxt =  GetDateStrDB(fieldName);
			var timeTxt =  GetTimeStr(fieldName);
			var realField = document.getElementById(fieldName);
			realField.value = dateTxt+" "+timeTxt;
	   		//alert(realField.value);
			//alert ("NEW DATE TIME: " + realField.value);
			
	} 
}

function GetDateStrDB(fieldName){
	var dayD = document.getElementById("IGNORE_"+fieldName+"_day");
	var dayTxt = dayD[dayD.selectedIndex].value;
		
	var monthD = document.getElementById("IGNORE_"+fieldName+"_month");
	var monthTxt = monthD[monthD.selectedIndex].value;
		
	var yearD = document.getElementById("IGNORE_"+fieldName+"_year");
	var yearTxt = yearD[yearD.selectedIndex].value;
    var dateStr  = yearTxt+"-"+monthTxt+"-"+dayTxt;
   // var dateStr  = dayTxt+"/"+monthTxt+"/"+yearTxt;
	return dateStr;
}

//---------------------------------------------------------------------------------------------------------



function Validate_Email(Emailfield,  MaxChar, HMessage){
		if (Emailfield.indexOf('@') == -1 || Emailfield.indexOf('.') == -1) {
				//alert(HMessage);
				return false;
			}
		return true;
}


////////////////////////////////////////////////////////////////////////////   D A T E    T I M E    //////////////////////////

function GetDateStr(fieldName){
	var dayD = document.getElementById("IGNORE_"+fieldName+"_day");
	var dayTxt = dayD[dayD.selectedIndex].value;
		
	var monthD = document.getElementById("IGNORE_"+fieldName+"_month");
	var monthTxt = monthD[monthD.selectedIndex].value;
		
	var yearD = document.getElementById("IGNORE_"+fieldName+"_year");
	var yearTxt = yearD[yearD.selectedIndex].value;
   // var dateStr  = yearTxt+"-"+monthTxt+"-"+dayTxt;
    var dateStr  = dayTxt+"/"+monthTxt+"/"+yearTxt;
	return dateStr;
}

function GetTimeStr(fieldName){
	var hourD = document.getElementById("IGNORE_"+fieldName+"_hour");
	var hourTxt = hourD[hourD.selectedIndex].value;
	
	if (hourTxt.length == 1) {
		hourTxt = "0"+hourTxt;
	}
	
	var minD = document.getElementById("IGNORE_"+fieldName+"_min");
	var minTxt = minD[minD.selectedIndex].value;
	if (minTxt.length == 1) {
		minTxt = "0"+minTxt;
	}
	
	var timeStr  = hourTxt+":"+minTxt+":00";
	
	return timeStr;	
	
}

//--------------------------------------------------------------------------------

function DateFilled(fieldId){
	var isFilled = false;
	var dayD = document.getElementById("IGNORE_"+InputInfo[fieldId].FieldName+"_day");
	var dayTxt = dayD[dayD.selectedIndex].value;
	if (dayTxt != NowDay){
		isFilled = true;
	}
	
	var monthD = document.getElementById("IGNORE_"+InputInfo[fieldId].FieldName+"_month");
	var monthTxt = monthD[monthD.selectedIndex].value;
	if (monthTxt != NowMonth + 1){
		isFilled = true;
	}
		
	var yearD = document.getElementById("IGNORE_"+InputInfo[fieldId].FieldName+"_year");
	var yearTxt = yearD[yearD.selectedIndex].value;
	if (yearTxt != NowYear){
		isFilled = true;
	}
	return isFilled;
}

function TimeFilled(fieldId){
	var isFilled = false;
	var hourD = document.getElementById("IGNORE_"+InputInfo[fieldId].FieldName+"_hour");
	var hourTxt = hourD[hourD.selectedIndex].value;
	if (hourTxt != NowHour){
		isFilled = true;
	}
	var minD = document.getElementById("IGNORE_"+InputInfo[fieldId].FieldName+"_min");
	var minTxt = minD[minD.selectedIndex].value;
	if (minTxt != NowMin){
		isFilled = true;
	}
	return isFilled;
}

//-------------------------------------------------------------

function ValidateTextAgainstText(fieldId) {
	//alert(InputInfo[fieldId].MatchWithField);
	if (InputInfo[fieldId].MatchWithField != '[]') {
		var oForm = document.form;
		//var thisField = document.getElementById(InputInfo[fieldId].FieldName);
		var thisField = oForm[InputInfo[fieldId].FieldName];
		//alert(thisField);
		var matchField = oForm[InputInfo[fieldId].MatchWithField]
		//-------------- test if the matchField first needs to be converted as date or time:
		if (InputInfo[fieldId].MatchWithAddId != '[]') {
			ConvertDateTime(InputInfo[fieldId].MatchWithField, InputInfo[fieldId].MatchWithAddId);
			//alert("CONVERTED ");
		}
													 
		//var matchField = document.getElementById(InputInfo[fieldId].MatchWithField);
	//	alert(matchField);
		//alert(thisField.value + "   "+matchField.value)
		if (thisField.value != matchField.value) {
			alert ("'" + InputInfo[fieldId].Description +"' and '"+InputInfo[fieldId].MatchWithFieldText+"' have to match");
			return false;
		}
	}
	return true;
		  
}
////////////////////////////////////////////////////////////////////////// V A L I D A T I O N   //////////////

function ConvertDateTime(fieldName, addId) {
	//---------------- test if DATE drop downs used:
	if (addId == '1'){
		
			var dateTxt =  GetDateStr(fieldName);
	   		var realField = document.getElementById(fieldName);
			realField.value = dateTxt;
			//alert(dateTxt);
	   		//alert("DATE:" + realField.value);
			
			
		
	//---------------- test if TIME drop downs used:
	} else if (addId == '2'){ 
		
			var timeTxt =  GetTimeStr(fieldName);
	   		var realField = document.getElementById(fieldName);
			realField.value = timeTxt;
	   		//alert(realField.value);
			
		
	//---------------- test if DATETIME drop downs used:
	} else  if (addId == '3'){ 
		
			var dateTxt =  GetDateStr(fieldName);
			var timeTxt =  GetTimeStr(fieldName);
			var realField = document.getElementById(fieldName);
			realField.value = dateTxt+" "+timeTxt;
	   		//alert(realField.value);
			
	} 
}


function Validate_Text(Textfield, Mandatory, MaxChar, EMMax, MinChar, EMMin, Descript, fieldId, RegExpId){
	//alert(Textfield);
	
		
	
		if (Textfield != InputInfo[fieldId].OriginalContent && Textfield.length > 0){
			//------------ reg exp:
			
			if (RegExpId != '0' && RegExpId != 'undefined' && RegExpId != undefined && RegExpId != ''){
				//alert(RegExpId);
				var pattern=new RegExp(RegExps[RegExpId], "gi") ;
				var correct = pattern.test(Textfield);
				
				//alert("HI" + correct);
				if (correct == true){
				} else {
					alert("Content of '"+Descript+"' "+RegExpsWords[RegExpId]);
					return false;
				}
			}
			//------------- no of characters:
			if (Textfield.length > MaxChar){
				alert (Descript+" - \n"+EMMax)
				return false;
			}
			if (Textfield.length < MinChar){
				alert (Descript+" - \n"+EMMin)
				return false;
			}	
		} else {
			
			if (Mandatory == "Yes"){
				alert (InputInfo[fieldId].HintMessage);
				return false;
			}
		} 
		return true;
			
		
	
	
	
}


function Validate_Radio(RadioField, HMessage, Mand, Descript){
		if (Mand == "Yes"){
			var radio_choice = false;
			for (counter = 0; counter < RadioField.length; counter++){
				if (RadioField[counter].checked)
				radio_choice = true; 
			}
			if (!radio_choice){
				alert (HMessage)
			return false;
			}
		}
		return true;
}


function Validate_Check(CheckField, HMessage, Mand, Descript, fieldId){
	
		if (Mand == "Yes"){
			var check_choice = false;
			if (CheckField.checked){
				check_choice = true; 
			}
			if (!check_choice){
				alert (HMessage)
			return false;
			}
		}
		
		if (CheckField.checked){
			numChecked++;
		}
	
		
		//----------- last check box of an object, test the min/max and reset count 
		if (InputInfo[fieldId].LastInObject == "1") {
			//---------- tst min / max allowed to be checked:
			if (numChecked < InputInfo[fieldId].MinChecked) {
				alert("Please check at least "+InputInfo[fieldId].MinChecked+" check boxes in '"+InputInfo[fieldId].TopQuestionText+"'");
				numChecked = 0;
				return false;
			}
			if (numChecked > InputInfo[fieldId].MaxChecked) {
				alert("Please check a maximum of "+InputInfo[fieldId].MaxChecked+" check boxes in '"+InputInfo[fieldId].TopQuestionText+"'");
				numChecked = 0;
				return false;
			}
			numChecked = 0;
		}
		//alert(numChecked);
		return true;
}



function Validate_List(ListField, HMessage, Mand, Descript,fieldId){
	if (Mand == "Yes"){
			//alert(' Passed the value *'+ListField+'*');
			//alert(fieldId);
			numOfItems = InputInfo[fieldId].NonSelectable[0];
			for (q=1;q<=numOfItems;q++){
			if (ListField == InputInfo[fieldId].NonSelectable[q]){
				alert (HMessage);
				return false;
			}
			}
	}
	return true;
}

function NCSSFix() {
	    document.location = document.location;
	    }
	if (!document.getElementById) {
	window.onresize = NCSSFix;
}


function OpenWindow( url, width, height, options, name )
	{
	  if ( ! width ) width = 475;
	  if ( ! height ) height = 250;
	  if ( ! options ) options =
	"scrollbars=yes,menubar=yes,toolbar=yes,location=yes,status=yes,resizable=yes";
	  if ( ! name ) name = "outsideSiteWindow";
	  var newWin = window.open( url, name, "width=" + width + ",height=" +
	height + "," + options );
}

function urlMenu(that) {
		theURL = that.options[that.selectedIndex].value; 
		if (theURL) {
			window.location = theURL;
		}
}
