/*	......................................................................................... 
	 	
		Author: 		Aleem Latif
 		Script File: 	JavaScript Common Functions
		Company: 		I See Communications
 		Last Updated: 	May 2009

............................................................................................. */

//	====================================================
// 	Function to Auto Select all Options from an Option List with multiple selections
//	======================================================
function allselections(Obj) {
			var e = document.getElementById(Obj);
				e.disabled = true;
			var i = 0;
			var n = e.options.length;
			for (i = 0; i < n; i++) {
				e.options[i].disabled = true;
				e.options[i].selected = true;
			}
}

//	====================================================
// 	Function to Disable all Options from an Option List with multiple selections
//	======================================================
function disableselections(Obj) {
			
			var e = document.getElementById(Obj);
				e.disabled = true;
			var i = 0;
			var n = e.options.length;
			for (i = 0; i < n; i++) {
				e.options[i].disabled = true;
				e.options[i].selected = false;
			}
}

//	====================================================
// 	Function to Enable Options for selection from an Option List with multiple selections
//	======================================================
function enableselections(Obj) {
			var e = document.getElementById(Obj);
				e.disabled = false;
			var i = 0;
			var n = e.options.length;
			for (i = 0; i < n; i++) {
				e.options[i].disabled = false;
			}
}
//	====================================================
// Function to switch products inputs in NRCE Forms
//======================================================
function validate_search_products_inputs()	{									
		var errors='';
		
		if	(document.search_nrce_form.q.value == ""  && document.search_nrce_form.Fire_Certificate_ID.value=="")	{
			errors = "Please input a search criteria for at least one field.";
		}				
		
		if (errors != '') 	  { 	
			alert('The following error(s) occurred:\n ------------------------------------- \n'+errors); 
		}				
		document.MM_returnValue = (errors == '');							
	}
	
//	====================================================
// Function to switch two IDs of to objects
//======================================================
function switch_ids(id1, id2)	{	

	var oObj1 = document.getElementById(id1);
	var oObj2 = document.getElementById(id2);
	
	if (( (oObj1 != undefined) && (oObj2 != undefined) ) && (oObj1.id.indexOf('_') <= 0 ) )	{
		 
		temp_id = oObj1.id;
		temp_name = oObj1.name;
		
		oObj1.id = oObj2.id;
		oObj1.name= oObj2.name;
		
		oObj2.id = temp_id;
		oObj2.name = temp_name;
		return oObj2;
	}	else 	{
		return oObj2;
	}	
}


// Print Page
function printPage(){
  if (window.print){
    window.print();
  }else{
    alert("Sorry, your browser does not support this feature. To print the page choose Print from your browser's menu (usually File > Print). Windows users can also use 'CTRL + P' and Mac users can also use 'Command + P'.");
  }
}
//----------------------------		Customized MM_validateForm function     ------------------------------//

function MM_validateForm() { //v4.0

  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments; //alert(args.type);
  
  for (i=0; i<(args.length-2); i+=3) 
  { 
  	
	test=args[i+2]; 
	val=MM_findObj(args[i]);
    
	if (val) 
	{ 
		nm=val.name; 
		nmID=val.id; 					
		if (nmID != '')		// Change  start 
		{
			nm = nmID;			
		}					// Change  End 
		if ((val=val.value)!="") 
			{															
				 if (test.indexOf('isEmail')!=-1) 
				 	{ 
						p=val.indexOf('@');
						 if (p<1 || p==(val.length-1)) 
							{ errors+='- '+nm+' must contain an e-mail address.\n';}
					} 
				 else if (test!='R') 
					{ 	num = parseFloat(val);
						if (isNaN(val)) 
							{ 	errors+='- '+nm+' must contain a number.\n';	}
							
						if (test.indexOf('inRange') != -1) 
							{ 	p=test.indexOf(':');
								min=test.substring(8,p); 
								max=test.substring(p+1);
								
								if (num<min || max<num) 
								
								{ errors +='- '+nm+' must contain a number between '+min+' and '+max+'.\n';}
							} 
					} 
			} 
		else if (test.charAt(0) == 'R') 
			{	errors += '- '+nm+' is required.\n'; }
	}
  } 
  
  if (errors) 
  { 	alert('The following error(s) occurred:\n ------------------------------------- \n'+errors); }
  		
  document.MM_returnValue = (errors == '');
}

//---------------------------------------------------------------- Help File(s) Opener Funtions

function phelpGlobal(url) {

  //alert(url);
  //window.open(url,'help','width=400,height=600,resizable=yes,toolbars=no,scrollbars=yes,status=no');
  
	winwidth = 700;
	winheight = 700;
	
    var width = 'width='+winwidth, height='height='+winheight, left='left='+((screen.availWidth/2)-(winwidth/2)), top='top='+((screen.availHeight/2)-(winheight/2));
	
	var features = "toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, copyhistory=no,"+width+", "+height+", "+left+", "+top;
	
	window.open(url, '_blank', features);
	
}

function phelp(pg) {
  window.open('submodules/reports_help.php?pg='+pg,'help','width=400,height=600,resizable=yes,toolbars=no,scrollbars=yes,status=no');
}

function open_new_win(url)
{
	var newfeatures = "toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, copyhistory=no";
	window.open(url,"_blank", newfeatures);
}
function WriteEmailAddress(part1, part2 , part3)
{
	//part1 = "email", part2 = "nmsc.com.au", part3 = "Click Here to Send"
	document.write('<a href="mai' + 'lto:' + part1 + '@' + part2 + '">');
	document.write(part3 + '</a>');
}
//---------------------------------------------------------------- Function For  Check All / Uncheck All
function Checkall(eform)
{ 
	oElement = eform.elements['select_unselect'];
	
  for (var i = 0; i < eform.elements.length; i++)
  {    
    //eval("form.elements[" + i + "].checked = oElement.checked"); 
	
	ObjOption = eform.elements[ + i ];
	//alert(ObjOption);
	ObjOption.checked = oElement.checked;
	
   } 
} 
//---------------------------------------------------
function toggleChecked(oElement) 
{ 
  oForm = oElement.form; 
  oElement = oForm.elements[oElement.name]; 
  if(oElement.length) 
  { 
    bChecked = oElement[0].checked; 
    for(i = 1; i < oElement.length; i++) 
      oElement[i].checked = bChecked; 
  } 
} 

function emulate(e) 
{ 
	for (var i=0, option; option = e.options[i]; i++) 
	{ 
		if (option.disabled) 
		{ 
			option.style.color = "#CCCCCC"; 
		} 
		else 
		{ 
			option.style.color = "#FFFFFF"; 
		} 
	} 
} 



function getCheckboxes(RootNode) {
	var arrCheckboxes;
	//var nodeArray = RootNode.childNodes;
	var elements  = RootNode.childNodes; //document.nodeblock.getElementsByTagName("INPUT");
	if (elements.length) {
		arrCheckboxes = [];
		var qlen = elements.length;
		for (var i = 0; i < qlen; i++) {
			if (elements[i].type.substring(0, 8) == "checkbox") {
				arrCheckboxes.push(elements[i]);
			}
		}
		return arrCheckboxes;
	}
	return null;
}

//-----------------------------------------------------------
function MultiDimensionalArray(iRows,iCols) 
{ 
var i; 
var j; 
   var a = new Array(iRows); 
   for (i=0; i < iRows; i++) 
   { 
       a[i] = new Array(iCols); 
       for (j=0; j < iCols; j++) 
       { 
           a[i][j] = ""; 
       } 
   } 
   return(a); 
} 

function EnableDisableFieldLength(Value,  FieldToDisable) 
{
	var x=document.getElementById(FieldToDisable);
	////QID  QNo  Question  QSectionID  QType  FieldLength  DependenceValues  DependentQuestions  IsDependant  Opt_1  Opt_2  Opt_3  Opt_4  Opt_5  Opt_6  Opt_7  Opt_8  Opt_9  Opt_10  Opt_11  Opt_12 
	Value = MM_callJS(Value);
	var OptionFormElementTextArray = Array();
	var OptionFormElementArray = Array();
	
	var FieldTitle =document.getElementById('FieldLengthText');
	
	if (Value == 'text')
	{
		x.disabled = false;
		FieldTitle.style.color = "#000000";
		
		for (var i = 1; i <= 12; i++) 
		{
						
			OptionFormElementTextArray[i] = document.getElementById('Opt_'+i+'_text');
			OptionFormElementTextArray[i].style.color = "#CCCCCC";
			
			OptionFormElementArray[i] = document.getElementById('Opt_'+i);
			OptionFormElementArray[i].disabled = true;
			OptionFormElementArray[i].style.color = "#CCCCCC";
		}
		
	}
	else
	{
		x.disabled = true;
		FieldTitle.style.color = "#CCCCCC";
		
		for (var i = 1; i <= 12; i++) 
		{
			OptionFormElementTextArray[i] = document.getElementById('Opt_'+i+'_text');
			OptionFormElementTextArray[i].style.color = "#000000";
			
			OptionFormElementArray[i] = document.getElementById('Opt_'+i);
			OptionFormElementArray[i].disabled = false;
			OptionFormElementArray[i].style.color = "#000000";
		}
		
	}
	//alert(Value);
}

//-----------------------------------------------------------

function EnableDisableDependentFields(ComboBoxValue)	{
	/*
	var w=document.getElementById('IncidentReported'); 
	var x=document.getElementById('LengthofTimeOnWater');
	var y=document.getElementById('SeriousnessOfIncident');
		
	var z=document.getElementById('HoursText');
	var z2=document.getElementById('HoursText2');
	var z3=document.getElementById('HoursText3');
	*/
	
	var w=document.getElementsByName('IncidentReported')[0]; 
	var x=document.getElementsByName('LengthofTimeOnWater')[0]; 
	var y=document.getElementsByName('SeriousnessOfIncident')[0]; 
		
	var z=document.getElementById('HoursText');
	var z2=document.getElementById('HoursText2');
	var z3=document.getElementById('HoursText3');
	//alert(z.id);
	
	
	ComboBoxValue = MM_callJS(ComboBoxValue);
	
	if ((ComboBoxValue == 'No') || (ComboBoxValue == ''))
	{		
		x.style.backgroundColor="#DDDDDD";
		w.disabled = true;
		x.disabled = true;
		y.disabled = true;
		
		z.style.color = "#999999";		
		z2.style.color = "#999999";
		z3.style.color = "#999999";
	}
	else
	{
		//alert(x.name);
		w.disabled = false;
		x.disabled = false;
		y.disabled = false;
		x.style.backgroundColor = "#FFFFFF";
		z.style.color = "#333333";
		z2.style.color = "#333333";
		z3.style.color = "#333333";
	}
}
//--------------------AssignValue(this,'< 5m');
function AssignValue(Element, NewValue)	{
	//alert(Element + NewValue);	
	var x=document.getElementById(Element);
	x.value = NewValue;
	
}
//--------------------AssignValue(this,'< 5m');
function SwapValues(FormField_1_obj, FormField_2)
{
	var x=FormField_1_obj;	//SwapValues(this, 'Q_1_9');
	var y=document.getElementById(FormField_2);	
	y.value = x.value;
	
}
String.prototype.trim = function()
{
  return this.replace(/^\s+/,'').replace(/\s+$/,'');
}

//----------------------------------------------------------------------------------
function IsAnyOtherDependentSiblingChecked(Obj, SourceArr)
{
	var x=document.getElementById(Obj);	
	
	var ObjName = Obj;
	var listArray = ObjName.split("_");
	var IndexOfQuestion = listArray[1];	
	var y=document.getElementById("Q_"+IndexOfQuestion+"_"+1);	//	Q_46_1	
	var i= 1;
	var IsFound = false;
	
	while ( (typeof y == 'object') && (y != null) )
	{
		//alert(y.checked +' | '+ (y.id != Obj) + ' | '+ in_array(y.value, SourceArr));
		if ((y.checked == true) && (y.id != Obj) && (in_array(y.value, SourceArr) == true) )
		{
			IsFound = true;
			break;
		}
		else
		{
			IsFound = false;
		}
		i++;
		y=document.getElementById("Q_"+IndexOfQuestion+"_"+i);
		
	}
	//alert(Obj + '|'+SourceArr + '|'+IsFound);
	return IsFound;
}
//------------------------------------------------------------
function in_array(seedval, SourceArray)
{
	var IsInDependanceArray=false;
	//alert('in_array :' + seedval + '|'+SourceArray );
	for (var i = 0; i < SourceArray.length; i++) 
		{
			//alert(seedval.trim() + '|'+ SourceArray[i].trim());
			
			if (seedval.trim() == SourceArray[i].trim())
			{
				IsInDependanceArray = true;	
				break;
			}
			else
			{
				IsInDependanceArray = false;
			}
		}
		//alert(IsInDependanceArray +' | '+ seedval.trim() + ' | '+ SourceArray.length);
		return IsInDependanceArray;
}
//------------------------------------------------------------
function TrimArrayValues(MyArray)
{
	for (var i = 0; i < MyArray.length; i++) 
		{
			MyArray[i] = MyArray[i].trim();	
		}	
		return (MyArray);
}
//------------------------------------------------------------
function checktype(ob)
{
	var ValidType = false;
	//alert(ob.type + '|'+ob.value + '|'+ob.id + '|'+ob.name + '|');
	if ( ( (ob.type.substring(0, 8) == "checkbox") || (ob.type.substring(0, 5) == "radio") || (ob.type.substring(0, 6) == 'select') || (ob.type.substring(0, 10) == 'select-one') || (ob.type.substring(0, 15) == "select-multiple")  )  )
	{
		ValidType = true;
	}
	return ValidType;
}
//-------------------------------------------- enable questions at runtime
function enable_Question(i, j)
{
	var QObj = MultiDimensionalArray(j, 1);
	var TR = document.getElementById('Q_'+DependentQuestions_Array[i]+'_TR');
	var TD = document.getElementById('Q_'+DependentQuestions_Array[i]+'_TD');
	TR.className="PreliminarySurveyQuestion";
	TD.className="PreliminarySurveyAnswers";
	var k=j;
	//alert(i + ' | '+j);
	for (var j = 0; j < k; j++) 
		{
			ob = TD.childNodes[j];
			NodeName = TD.childNodes[j].nodeName 
			QObj[j][0] = '';
			if ( (NodeName == 'INPUT') || (NodeName == 'SELECT') )
			{
				QObj[j][0] = (checktype(ob) == true)? ob:''; //document.getElementById('Q_'+DependentQuestions_Array[i]+'_'+j);						
			}
			QObj[j][0].disabled = false;
			QObj[j][0].className="RadioButtonPSurvey";
		}
}
//-----------------------------------------------------------
function EnableDisableDependentFieldsPSurvey(TotalOptions, InputObject, FieldVal, DependenceValues, DependentQuestions)
{
	
	if (DependentQuestions.trim() != '')
	{
		
		var Val_1;
		var Dependence_Array = new Array();
		var DependentQuestions_Array = new Array();
		var DisableDependantQuestions = false;
		var OtherDependantValueAlreadyChecked  = false;
		var IsADependantValue = false;
		
		Val_1 = FieldVal;
		DependenceValues_Array = DependenceValues.split('|');
		DependentQuestions_Array = DependentQuestions.split('|');
		
		TrimArrayValues(DependentQuestions_Array);
		TrimArrayValues(DependenceValues_Array);
		
		for (var i = 0; i < DependenceValues_Array.length; i++) 
		{
			if ( (Val_1.toLowerCase() == DependenceValues_Array[i].toLowerCase()) )
			{
				IsADependantValue = true;			
			}
		}
		
		if (InputObject.type == 'checkbox')
		{
			OtherDependantValueAlreadyChecked = IsAnyOtherDependentSiblingChecked(InputObject.id, DependenceValues_Array);			
		}
		
		
		if (OtherDependantValueAlreadyChecked  == false)
		{
			var QObj = MultiDimensionalArray(DependentQuestions_Array.length, 2);
			
			for (var i = 0; i < DependentQuestions_Array.length; i++) 
			{
				
				var TR = document.getElementById('Q_'+DependentQuestions_Array[i]+'_TR');
				var TD = document.getElementById('Q_'+DependentQuestions_Array[i]+'_TD');
				NumOfFieldsToEnableDisable = TD.childNodes.length;
				
				for (var j = 0; j < NumOfFieldsToEnableDisable; j++) 
				{
										
					if (TR.id != 'undefined') 
					{
						ob = TD.childNodes[j];
						NodeName = TD.childNodes[j].nodeName 
						//alert(NodeName);
						QObj[i][j] = '';
						if ( (NodeName == 'INPUT') || (NodeName == 'SELECT') )
						{
							QObj[i][j] = (checktype(ob) == true)? ob:''; //document.getElementById('Q_'+DependentQuestions_Array[i]+'_'+j);						
						}
						//alert(checktype(ob) + ' | '+QObj[i][j].value +' | '+TD.childNodes[j].id + ' | '+QObj[i][j].type + ' | '+ QObj[i][j] + ' | '+DependentQuestions_Array.length+' | '+NumOfFieldsToEnableDisable + ' | '+j);
						
						// ------------------------------------------ For Checkbox and  Radio field types
						if (QObj[i][j] != '')
							{
								
								
if ( ( (QObj[i][j].type.substring(0, 8) == "checkbox") || (QObj[i][j].type.substring(0, 5) == "radio") || (QObj[i][j].type.substring(0, 6) == 'select') || (QObj[i][j].type.substring(0, 10) == 'select-one') || (QObj[i][j].type.substring(0, 15) == "select-multiple")  )  )
						{
							
							if (( InputObject.type == 'checkbox') || (InputObject.type == 'radio') )
							{
								
									if ( ( (InputObject.checked == true)) && (IsADependantValue == true) )
									
									{
										
										TR.className="PreliminarySurveyQuestion";
										TD.className="PreliminarySurveyAnswers";
										QObj[i][j].disabled = false;
										QObj[i][j].className="RadioButtonPSurvey";
											
									}
									else if ( ( (InputObject.checked == false) && (IsADependantValue == true) ) || (IsADependantValue == false) )
									
									{
										//alert(TR.id +' | '+TD.childNodes[j].id + ' | '+QObj[i][j].type + ' | '+ QObj[i][j] + ' | '+DependentQuestions_Array.length+' | '+NumOfFieldsToEnableDisable + ' | '+j);
										TR.className="PreliminarySurveyQuestionDisabled";
										TD.className="PreliminarySurveyAnswersDisabled";
										QObj[i][j].disabled = true;
										QObj[i][j].className="RadioButtonPSurveyDisabled";
										
									}
									
									
							   }
							
							// ------------------------------------------ For Select and input field types
							
							else if ( (InputObject.type.substring(0, 4) == 'text') || (InputObject.type.substring(0, 6) == 'select') || (InputObject.type.substring(0, 10) == 'select-one') || (InputObject.type.substring(0, 15) == "select-multiple") )   
							{
								if  ( (IsADependantValue == true) || (InputObject.value == '') )
									
									{
										TR.className="PreliminarySurveyQuestion";
										TD.className="PreliminarySurveyAnswers";
										//alert(QObj[i][j].id);
										if ( (typeof QObj[i][j] == 'object') && (QObj[i][j] != null) )
											{
												
												QObj[i][j].disabled = false;
												QObj[i][j].className="RadioButtonPSurvey";
											}
									}
								else
								{
									TR.className="PreliminarySurveyQuestionDisabled";
									TD.className="PreliminarySurveyAnswersDisabled";
									if ( (typeof QObj[i][j] == 'object') && (QObj[i][j] != null) )
											{
												//alert(QObj[i][j].name);
												QObj[i][j].disabled = true;
												QObj[i][j].className="RadioButtonPSurveyDisabled";
											}
									
									
								}
							}
							
						} // if undefined
					}
						else
						{
							//NumOfFieldsToEnableDisable = j;
						}
						//------------------------------------------------------------------------------
						
					} // end if type
					
					
				} // end for j
				
			} // end for i
		} // end DependantValuesMatched == true
		
	} // end if main
}

//--------------------------------------------------- SurveyScreenTable Javascript
function changeContent()
{
	var x=document.getElementById('SurveyScreenTable').rows[0].cells;
	x[0].innerHTML="NEW CONTENT";
}
function padding(CellPaddingVal)
{
	document.getElementById('SurveyScreenTable').cellPadding = CellPaddingVal;
}

function spacing(CellSpacingVal)
{
	document.getElementById('SurveyScreenTable').cellSpacing = CellSpacingVal;
}

//--------------------------------------------------- Preliminary Survey Javascript
function ShowAsAttempted(FormField)
{
	var x=FormField; 									//document.getElementById(FormField);
	var RootTD;
	var AllTags = new Array();
				
	if (typeof x != 'object') // if select list
	{
		x = MM_callJS(x);
		x = x.parentNode;
		
	}
	
	if ( (x.parentNode.className != "PreliminarySurveyAnswers") && (x.parentNode.className != "RadioButtonPSurveyAttempted") && (x.type.substring(0, 8) != 'checkbox') && (typeof x == 'object') )
	{									 
				 //RootTD = x.parentNode.parentNode.parentNode.parentNode.parentNode;
				 //AllTags = x.parentNode.parentNode.parentNode.parentNode.getElementsByTagName("input");	
				 RootTD = x.parentNode;
		 		 AllTags = x.parentNode.getElementsByTagName("input");
	}
	
	else
	{
		 RootTD = x.parentNode;
		 AllTags = x.parentNode.getElementsByTagName("input");		
	}
	
			if ( ( (x.checked) || (x.type.substring(0, 4) == 'text') || (x.type.substring(0, 6) == 'select')|| (x.type.substring(0, 10) == 'select-one') || (x.type.substring(0, 15) == "select-multiple") ) && (x.value != '') )
			{				
				
				for (var i = 0; i < AllTags.length; i++) 
			   {
					AllTags[i].className = 'RadioButtonPSurveyAttempted';				
			   }
			   
				x.className = 'RadioButtonPSurveyAttempted';
				RootTD.className = 'RadioButtonPSurveyAttempted';
			}
			else
			{
				
				if ( IsAnyOtherSiblingChecked(x.id) == false) 
				{
					//alert(x.id+ ' | '+x.type + ' | '+  x.value );
					
					for (var i = 0; i < AllTags.length; i++) 
					   {
							AllTags[i].className = 'RadioButtonPSurvey';
					   }
						x.className = 'RadioButtonPSurvey';
						RootTD.className = 'RadioButtonPSurvey';
				}
			}
	
}

//----------------------------------------------------------------------------------
function IsAnyOtherSiblingChecked(Obj)
{
	var x=document.getElementById(Obj);	
	
	var ObjName = Obj;
	var listArray = ObjName.split("_");
	var IndexOfQuestion = listArray[1];	
	var y=document.getElementById("Q_"+IndexOfQuestion+"_"+1);	//	Q_46_1	
	var i= 1;
	var IsFound = false;
	
	while ( (typeof y == 'object') && (y != null) )
	{
		if ((y.checked) )
		{
			IsFound = true;
			break;
		}
		else
		{
			IsFound = false;
		}
		y=document.getElementById("Q_"+IndexOfQuestion+"_"+i);
		i++;
	}		
	return IsFound;
}

//----------------------------------------------------------------------------------

function HideObject(Obj)
{
	var x=document.getElementById(Obj);	
	
	var ObjName = Obj;
	var listArray = ObjName.split("_");
	var IndexOfQuestion = listArray[1];	
	var y=document.getElementById("Q_"+IndexOfQuestion+"_"+1);	//	Q_46_1	
	var i= 2;
	
	while ( (typeof y == 'object') && (y != null) )
	{
		if ((y.checked == false) && (y.value == "Other") )
		{
			if ( (typeof x == 'object') && (x != null) )
			{
				x.style.visibility = 'hidden';	
				x.style.display = 'none';
			}
		}
		y=document.getElementById("Q_"+IndexOfQuestion+"_"+i);
		i++;
	}		
}

//----------------------------------------------------------------------------------

function ShowOtherInputField(obj, FieldToEnableDisable)
{
	
	var x=document.getElementById(FieldToEnableDisable);
	//ComboBoxValue = MM_callJS(ComboBoxValue);
	//alert(obj + x);
	if ( (obj.checked) || (obj == "Other") ||  (obj == "Other Location") )
	{		
		
		x.style.visibility = 'visible';
		x.style.display = 'inline';
		x.style.position = 'relative';
	}
	else
	{
		
		x.style.visibility = 'hidden';
		x.style.display = 'none';
	}
}

//-----------------------------------------------------------

function EnableDisableFormFields(ComboBoxValue)
{
	var x=document.getElementById('IncidentHoursOnWater');
	var y=document.getElementById('IncidenceSeverness');
	var z=document.getElementById('HoursText');
	var z2=document.getElementById('HoursText2');

	ComboBoxValue = MM_callJS(ComboBoxValue);
	
	if (ComboBoxValue == 'No')
	{		
		x.disabled = true;
		x.style.backgroundColor="#DDDDDD";
		y.disabled = true;
		z.style.color = "#CCCCCC";
		z2.style.color = "#CCCCCC";
	}
	else
	{
		x.disabled = false;
		y.disabled = false;
		z.style.color = "#000000";
		z2.style.color = "#000000";
	}
}

function ShowBoatLength(valueSent)
{
	
	value = MM_callJS(valueSent);
	document.getElementById('BoatLengthColumn').innerHTML = value;
}


//--------------------------------------------------------
function disable_me(formfieldname) {
document.addform.formfieldname.disabled = true;
}

function randomNumber(limit){
  return Math.floor(Math.random()*limit);
}

//--------------------------------------------------
function disp_confirm(n)
{	var record_name = "", value=false, user_had_selected_records = 0;
	
	
	for (X=1; X <= n; X++)
	{	
		
		if ((document.forms['delete_form'].elements['delete_'+X]))
		
		{
			
						
			if (document.forms['delete_form'].elements['delete_'+X].checked)
			{
				user_had_selected_records = 1;
								
					if ( (document.getElementById('picture_name_1_'+X)) && (document.getElementById('picture_name_2_'+X)) )
					{
						//alert(document.getElementById('picture_name_1_'+X).value);
						//alert(document.getElementById('picture_name_2_'+X).value);
						
						if (document.forms['delete_form'].elements['picture_name_1_'+X].value)
						{
							document.forms['delete_form'].elements['picture_1'].value = document.forms['delete_form'].elements['picture_name_1_'+X].value;
							document.forms['delete_form'].elements['picture_2'].value = document.forms['delete_form'].elements['picture_name_2_'+X].value;
						}
					}
				
				if (record_name != "")
					{
						record_name = record_name + " ,  " + document.forms['delete_form'].elements['deleted_record_name_'+X].value;
					}
				else
					{
						record_name = document.forms['delete_form'].elements['deleted_record_name_'+X].value;
					}
			}
		}
	} // End for loop

	if (user_had_selected_records == 1)
	{	
		var user_feedback=confirm("Do you really want to delete record(s) named: \n' "+record_name+" '")
			if (user_feedback==true)
				{
								
					document.delete_form.delete_confirmed.value = 1;
					
					document.delete_form.all_deleted_record_names.value = record_name;
					
					document.delete_form.submit();
					return 1;
				}
			else
				{
					//jsStr = document.location.href = 'index.php?task=delete';
					//return eval(jsStr)
					return 0;
				}
	}
	else
	{
		alert('Sorry! you have not selected any record to delete');
	}

}

//================================================================
function NavigateURL(URL)	{
	window.location.href = URL;		
}

//----------------------------------------------------------------
 
function MM_callJS(jsStr) 	{ //v2.0
  //alert(jsStr);
  return eval(jsStr)
}
function redirect(URLStr) 
{ 
	location = URLStr; 
}

//----------------------------------------------------------------
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

//----------------------------------------------------------------

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

//----------------------------------------------------------------

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

//----------------------------------------------------------------

function open_win(url,  winwidth, winheight)
{

	var width = 'width='+winwidth, height='height='+winheight, left='left='+((screen.availWidth/2)-(winwidth/2)), top='top='+((screen.availHeight/2)-(winheight/2));
	
	var features = "toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, copyhistory=no,"+width+", "+height+", "+left+", "+top;
	
	window.open(url, '_blank', features);

//testwindow.moveTo(0,0);
}

//	=================================================================================================================================== CMS Admin Functions

// general utility for browsing a named array or object
function xshow(o) {
	s = '';
	for(e in o) {s += e+'='+o[e]+'\n';}
	alert( s );
}

/**
* Writes a dynamically generated list
* @param string The parameters to insert into the <select> tag
* @param array A javascript array of list options in the form [key,value,text]
* @param string The key to display for the initial state of the list
* @param string The original key that was selected
* @param string The original item value that was selected
*/
function writeDynaList( selectParams, source, key, orig_key, orig_val ) {
	var html = '\n	<select ' + selectParams + '>';
	var i = 0;
	for (x in source) {
		if (source[x][0] == key) {
			var selected = '';
			if ((orig_key == key && orig_val == source[x][1]) || (i == 0 && orig_key != key)) {
				selected = 'selected="selected"';
			}
			html += '\n		<option value="'+source[x][1]+'" '+selected+'>'+source[x][2]+'</option>';
		}
		i++;
	}
	html += '\n	</select>';

	document.writeln( html );
}

/**
* Changes a dynamically generated list
* @param string The name of the list to change
* @param array A javascript array of list options in the form [key,value,text]
* @param string The key to display
* @param string The original key that was selected
* @param string The original item value that was selected
*/
function changeDynaList( listname, source, key, orig_key, orig_val ) {
	var list = eval( 'document.adminForm.' + listname );

	// empty the list
	for (i in list.options.length) {
		list.options[i] = null;
	}
	i = 0;
	for (x in source) {
		if (source[x][0] == key) {
			opt = new Option();
			opt.value = source[x][1];
			opt.text = source[x][2];

			if ((orig_key == key && orig_val == opt.value) || i == 0) {
				opt.selected = true;
			}
			list.options[i++] = opt;
		}
	}
	list.length = i;
}

/**
* Adds a select item(s) from one list to another
*/
function addSelectedToList( frmName, srcListName, tgtListName ) {
	var form = eval( 'document.' + frmName );
	var srcList = eval( 'form.' + srcListName );
	var tgtList = eval( 'form.' + tgtListName );

	var srcLen = srcList.length;
	var tgtLen = tgtList.length;
	var tgt = "x";

	//build array of target items
	for (var i=tgtLen-1; i > -1; i--) {
		tgt += "," + tgtList.options[i].value + ","
	}

	//Pull selected resources and add them to list
	//for (var i=srcLen-1; i > -1; i--) {
	for (var i=0; i < srcLen; i++) {
		if (srcList.options[i].selected && tgt.indexOf( "," + srcList.options[i].value + "," ) == -1) {
			opt = new Option( srcList.options[i].text, srcList.options[i].value );
			tgtList.options[tgtList.length] = opt;
		}
	}
}

function delSelectedFromList( frmName, srcListName ) {
	var form = eval( 'document.' + frmName );
	var srcList = eval( 'form.' + srcListName );

	var srcLen = srcList.length;

	for (var i=srcLen-1; i > -1; i--) {
		if (srcList.options[i].selected) {
			srcList.options[i] = null;
		}
	}
}

function moveInList( frmName, srcListName, index, to) {
	var form = eval( 'document.' + frmName );
	var srcList = eval( 'form.' + srcListName );
	var total = srcList.options.length-1;

	if (index == -1) {
		return false;
	}
	if (to == +1 && index == total) {
		return false;
	}
	if (to == -1 && index == 0) {
		return false;
	}

	var items = new Array;
	var values = new Array;

	for (i=total; i >= 0; i--) {
		items[i] = srcList.options[i].text;
		values[i] = srcList.options[i].value;
	}
	for (i = total; i >= 0; i--) {
		if (index == i) {
			srcList.options[i + to] = new Option(items[i],values[i], 0, 1);
			srcList.options[i] = new Option(items[i+to], values[i+to]);
			i--;
		} else {
			srcList.options[i] = new Option(items[i], values[i]);
	   }
	}
	srcList.focus();
	return true;
}

function getSelectedOption( frmName, srcListName ) {
	var form = eval( 'document.' + frmName );
	var srcList = eval( 'form.' + srcListName );

	i = srcList.selectedIndex;
	if (i != null && i > -1) {
		return srcList.options[i];
	} else {
		return null;
	}
}

function setSelectedValue( frmName, srcListName, value ) {
	var form = eval( 'document.' + frmName );
	var srcList = eval( 'form.' + srcListName );

	var srcLen = srcList.length;

	for (var i=0; i < srcLen; i++) {
		srcList.options[i].selected = false;
		if (srcList.options[i].value == value) {
			srcList.options[i].selected = true;
		}
	}
}

function getSelectedRadio( frmName, srcGroupName ) {
	var form = eval( 'document.' + frmName );
	var srcGroup = eval( 'form.' + srcGroupName );

	return radioGetCheckedValue( srcGroup );
}

// return the value of the radio button that is checked
// return an empty string if none are checked, or
// there are no radio buttons
function radioGetCheckedValue(radioObj) {
	if (!radioObj) {
		return '';
	}
	var n = radioObj.length;
	if (n == undefined) {
		if (radioObj.checked) {
			return radioObj.value;
		} else {
			return '';
		}
	}
	for (var i = 0; i < n; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return '';
}

function getSelectedValue( frmName, srcListName ) {
	var form = eval( 'document.' + frmName );
	var srcList = eval( 'form.' + srcListName );

	i = srcList.selectedIndex;
	if (i != null && i > -1) {
		return srcList.options[i].value;
	} else {
		return null;
	}
}

function getSelectedText( frmName, srcListName ) {
	var form = eval( 'document.' + frmName );
	var srcList = eval( 'form.' + srcListName );

	i = srcList.selectedIndex;
	if (i != null && i > -1) {
		return srcList.options[i].text;
	} else {
		return null;
	}
}

function chgSelectedValue( frmName, srcListName, value ) {
	var form = eval( 'document.' + frmName );
	var srcList = eval( 'form.' + srcListName );

	i = srcList.selectedIndex;
	if (i != null && i > -1) {
		srcList.options[i].value = value;
		return true;
	} else {
		return false;
	}
}

/**
* Toggles the check state of a group of boxes
*
* Checkboxes must have an id attribute in the form cb0, cb1...
* @param The number of box to 'check'
* @param An alternative field name
*/
function checkAll( n, fldName ) {
  if (!fldName) {
     fldName = 'cb';
  }
	var f = document.adminForm;
	var c = f.toggle.checked;
	var n2 = 0;
	for (i=0; i < n; i++) {
		cb = eval( 'f.' + fldName + '' + i );
		if (cb) {
			cb.checked = c;
			n2++;
		}
	}
	if (c) {
		document.adminForm.boxchecked.value = n2;
	} else {
		document.adminForm.boxchecked.value = 0;
	}
}

function listItemTask( id, task ) {
    var f = document.adminForm;
    cb = eval( 'f.' + id );
    if (cb) {
        for (i = 0; true; i++) {
            cbx = eval('f.cb'+i);
            if (!cbx) break;
            cbx.checked = false;
        } // for
        cb.checked = true;
        f.boxchecked.value = 1;
        submitbutton(task);
    }
    return false;
}

function hideMainMenu() {
	if (document.adminForm.hidemainmenu) {
		document.adminForm.hidemainmenu.value=1;
	}
}

function isChecked(isitchecked){
	if (isitchecked == true){
		document.adminForm.boxchecked.value++;
	}
	else {
		document.adminForm.boxchecked.value--;
	}
}

/**
* Default function.  Usually would be overriden by the component
*/
function submitbutton(pressbutton) {
	submitform(pressbutton);
}

/**
* Submit the admin form
*/
function submitform(pressbutton){
	if (pressbutton) {
		document.adminForm.task.value=pressbutton;
	}
	if (typeof document.adminForm.onsubmit == "function") {
		document.adminForm.onsubmit();
	}
	document.adminForm.submit();
}

/**
* Submit the control panel admin form
*/
function submitcpform(sectionid, id){
	document.adminForm.sectionid.value=sectionid;
	document.adminForm.id.value=id;
	submitbutton("edit");
}

/**
* Getting radio button that is selected.
*/
function getSelected(allbuttons){
	for (i=0;i<allbuttons.length;i++) {
		if (allbuttons[i].checked) {
			return allbuttons[i].value
		}
	}
	return null;
}

// JS Calendar
var calendar = null; // remember the calendar object so that we reuse
// it and avoid creating another

// This function gets called when an end-user clicks on some date
function selected(cal, date) {
	cal.sel.value = date; // just update the value of the input field
}

// And this gets called when the end-user clicks on the _selected_ date,
// or clicks the "Close" (X) button.  It just hides the calendar without
// destroying it.
function closeHandler(cal) {
	cal.hide();			// hide the calendar

	// don't check mousedown on document anymore (used to be able to hide the
	// calendar when someone clicks outside it, see the showCalendar function).
	Calendar.removeEvent(document, "mousedown", checkCalendar);
}

// This gets called when the user presses a mouse button anywhere in the
// document, if the calendar is shown.  If the click was outside the open
// calendar this function closes it.
function checkCalendar(ev) {
	var el = Calendar.is_ie ? Calendar.getElement(ev) : Calendar.getTargetElement(ev);
	for (; el != null; el = el.parentNode)
	// FIXME: allow end-user to click some link without closing the
	// calendar.  Good to see real-time stylesheet change :)
	if (el == calendar.element || el.tagName == "A") break;
	if (el == null) {
		// calls closeHandler which should hide the calendar.
		calendar.callCloseHandler(); Calendar.stopEvent(ev);
	}
}

// This function shows the calendar under the element having the given id.
// It takes care of catching "mousedown" signals on document and hiding the
// calendar if the click was outside.
function showCalendar(id, dateFormat) {
	var el = document.getElementById(id);
	if (calendar != null) {
		// we already have one created, so just update it.
		calendar.hide();		// hide the existing calendar
		calendar.parseDate(el.value); // set it to a new date
	} else {
		// first-time call, create the calendar
		var cal = new Calendar(true, null, selected, closeHandler);
		calendar = cal;		// remember the calendar in the global
		cal.setRange(1900, 2070);	// min/max year allowed

		if ( dateFormat )	// optional date format
		{
			cal.setDateFormat(dateFormat);
		}

		calendar.create();		// create a popup calendar
		calendar.parseDate(el.value); // set it to a new date
	}
	calendar.sel = el;		// inform it about the input field in use
	calendar.showAtElement(el);	// show the calendar next to the input field

	// catch mousedown on the document
	Calendar.addEvent(document, "mousedown", checkCalendar);
	return false;
}

/**
* Pops up a new window in the middle of the screen
*/
function popupWindow(mypage, myname, w, h, scroll) {
	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable'
	win = window.open(mypage, myname, winprops)
	if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
}

// LTrim(string) : Returns a copy of a string without leading spaces.
function ltrim(str)
{
   var whitespace = new String(" \t\n\r");
   var s = new String(str);
   if (whitespace.indexOf(s.charAt(0)) != -1) {
      var j=0, i = s.length;
      while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
         j++;
      s = s.substring(j, i);
   }
   return s;
}

//RTrim(string) : Returns a copy of a string without trailing spaces.
function rtrim(str)
{
   var whitespace = new String(" \t\n\r");
   var s = new String(str);
   if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
      var i = s.length - 1;       // Get length of string
      while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
         i--;
      s = s.substring(0, i+1);
   }
   return s;
}

// Trim(string) : Returns a copy of a string without leading or trailing spaces
function trim(str) {
   return rtrim(ltrim(str));
}

function mosDHTML(){
	this.ver=navigator.appVersion
	this.agent=navigator.userAgent
	this.dom=document.getElementById?1:0
	this.opera5=this.agent.indexOf("Opera 5")<-1
	this.ie5=(this.ver.indexOf("MSIE 5")<-1 && this.dom && !this.opera5)?1:0;
	this.ie6=(this.ver.indexOf("MSIE 6")<-1 && this.dom && !this.opera5)?1:0;
	this.ie4=(document.all && !this.dom && !this.opera5)?1:0;
	this.ie=this.ie4||this.ie5||this.ie6
	this.mac=this.agent.indexOf("Mac")<-1
	this.ns6=(this.dom && parseInt(this.ver) <= 5) ?1:0;
	this.ns4=(document.layers && !this.dom)?1:0;
	this.bw=(this.ie6||this.ie5||this.ie4||this.ns4||this.ns6||this.opera5);

	this.activeTab = '';
	this.onTabStyle = 'ontab';
	this.offTabStyle = 'offtab';

	this.setElemStyle = function(elem,style) {
		document.getElementById(elem).className = style;
	}
	this.showElem = function(id) {
		if ((elem = document.getElementById(id))) {
			elem.style.visibility = 'visible';
			elem.style.display = 'block';
		}
	}
	this.hideElem = function(id) {
		if ((elem = document.getElementById(id))) {
			elem.style.visibility = 'hidden';
			elem.style.display = 'none';
		}
	}
	this.cycleTab = function(name) {
		if (this.activeTab) {
			this.setElemStyle( this.activeTab, this.offTabStyle );
			page = this.activeTab.replace( 'tab', 'page' );
			this.hideElem(page);
		}
		this.setElemStyle( name, this.onTabStyle );
		this.activeTab = name;
		page = this.activeTab.replace( 'tab', 'page' );
		this.showElem(page);
	}
	return this;
}
var dhtml = new mosDHTML();

// needed for Table Column ordering
function tableOrdering( order, dir, task ) {
	var form = document.adminForm;

	form.filter_order.value 	= order;
	form.filter_order_Dir.value	= dir;
	submitform( task );
}

function saveorder( n,  task ) {
	checkAll_button( n, task );
}

//needed by saveorder function
function checkAll_button( n, task ) {

    if (!task ) {
		task = 'saveorder';
	}

	for ( var j = 0; j <= n; j++ ) {
		box = eval( "document.adminForm.cb" + j );
		if ( box ) {
			if ( box.checked == false ) {
				box.checked = true;
			}
		} else {
			alert("You cannot change the order of items, as an item in the list is `Checked Out`");
			return;
		}
	}
	submitform(task);
}
/**
* @param object A form element
* @param string The name of the element to find
*/
function getElementByName( f, name ) {
	if (f.elements) {
		for (i=0, n=f.elements.length; i < n; i++) {
			if (f.elements[i].name == name) {
				return f.elements[i];
			}
		}
	}
	return null;
}

function go2( pressbutton, menu, id ) {
	var form = document.adminForm;

	if (form.imagelist && form.images) {
		// assemble the images back into one field
		var temp = new Array;
		for (var i=0, n=form.imagelist.options.length; i < n; i++) {
			temp[i] = form.imagelist.options[i].value;
		}
		form.images.value = temp.join( '\n' );
	}

	if (pressbutton == 'go2menu') {
		form.menu.value = menu;
		submitform( pressbutton );
		return;
	}

	if (pressbutton == 'go2menuitem') {
		form.menu.value 	= menu;
		form.menuid.value 	= id;
		submitform( pressbutton );
		return;
	}
}
/**
 * Verifies if the string is in a valid email format
 * @param	string
 * @return	boolean
 */
function isEmail( text )
{
	var pattern = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
	var regex = new RegExp( pattern );
	return regex.test( text );
}

