/****************************************************************************
 * <PRE>
 * Filename  : inquiry_valid_param.js
 * Class     : 
 * Function  : inquiry validation
 * Comment   : 
 * History   : 24/07/2006, Created by Eric Chen Kong Hin 
 * </PRE>
 * @version  : v1.0
 * @author   : Copyright (c) 2006 by pureworks enterprise. All Rights Reserved.
 ****************************************************************************/

/***
Validation: empty field(s)
			***/
function pic(img_name,img_src){
		document[img_name].src=img_src;
}
			
function insrtInquiry()
{
	var form = document.ENQUIRIES_FORM;
	if ( form.fname.value == "")
    {
	alert("please fill in Full Name");
   	form.fname.focus();	
	}
	else if(form.cname.value =="")
	{
	alert("please fill in Company Name");
	form.cname.focus();
	}
	else if(form.cbusiness.value =="")
	{
	alert("please fill in Company Business");
	form.cbusiness.focus();
	}
	else if(form.email.value =="")
	{
	alert("please fill in Contact Email");
	form.email.focus();
	}
	else if(form.contel.value =="")
	{
	alert("please fill in Contact Number");
	form.contel.focus();
	}
	else if(form.city.value =="")
	{
	alert("please fill in City");
	form.city.focus();
	}
	else if(form.state.value =="")
	{
	alert("please fill in State");
	form.state.focus();
	}
	else if(form.country.value =="0")
	{
	alert("please fill in Country");
	form.country.focus();
	}
	else if(form.address.value =="")
	{
	alert("please fill in Company Address");
	form.address.focus();
	}
	else if(form.feedback.value =="")
	{
	alert("please fill in Inquiry or Feedback");
	form.feedback.focus();
	}
	else if(form.project_period.value =="0")
	{
	alert("please select a duration");
	form.project_period.focus();
	}
  	else
   	{
    form.action="pureworks_enquiries.php"
    form.submit(); 
   }
 
}

function resetInquiry()
{
	var form = document.ENQUIRIES_FORM;
	form.fname.value="";
	form.cname.value="";
	form.cbusiness.value="";
	form.email.value="";
	form.contel.value="";
	form.city.value="";
	form.state.value="";
	form.country.value="0";
	form.address.value="";
	form.feedback.value="";
	form.project_period.value="0";
}

function formCheck(formobj){
	// dialog message
	var alertMsg = "Please complete the following fields:\n";
	
	var l_Msg = alertMsg.length;

	for (var i = 0; i < fieldRequired.length; i++){
		var obj = formobj.elements[fieldRequired[i]];
		if (obj){
			switch(obj.type){
			case "select-one":
				if (obj.selectedIndex == -1 || obj.options[obj.selectedIndex].text == ""){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
				break;
			case "select-multiple":
				/*if (obj.selectedIndex == -1){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}*/
				if (obj.length == 0){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
				break;
			case "text":
			case "textarea":
			case "password":
			case "radio":
			case "hidden":
				/*if (obj.value != 1)
					obj.value = trim(obj.value);*/
				if (Trim(obj.value) == "" || obj.value == null){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
				break;
			default:
			}
			if (obj.type == undefined){
				var blnchecked = false;
				for (var j = 0; j < obj.length; j++){
					if (obj[j].checked){
						blnchecked = true;
					}
				}
				if (!blnchecked){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
			}
		}
	}
	if (alertMsg.length == l_Msg)
		formobj.submit();
	else
		alert(alertMsg);
}

/***
Validation: empty field(s) without submitting the form
						***/
			
function formCheckNoSubmit(formobj){
	// dialog message
	var alertMsg = "Please complete the following fields:\n";
	var proceed = false;
	var l_Msg = alertMsg.length;
	
	for (var i = 0; i < fieldRequired.length; i++){
		var obj = formobj.elements[fieldRequired[i]];
		if (obj){
			switch(obj.type){
			case "select-one":
				if (obj.selectedIndex == -1 || obj.options[obj.selectedIndex].text == ""){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
				break;
			case "select-multiple":
				/*if (obj.selectedIndex == -1){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}*/
				if (obj.length == 0){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
				break;
			case "text":
			case "textarea":
			case "password":
			case "radio":
			case "hidden":
				/*if (obj.value != 1)
					obj.value = trim(obj.value);*/
				if (Trim(obj.value) == "" || obj.value == null){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
				break;
			default:
			}
			if (obj.type == undefined){
				var blnchecked = false;
				for (var j = 0; j < obj.length; j++){
					if (obj[j].checked){
						blnchecked = true;
					}
				}
				if (!blnchecked){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
			}
		}
	}

	if (alertMsg.length == l_Msg)
		proceed = true;
	else
		alert(alertMsg);
		
	return proceed;
}


function ltrim ( s )
{
	return s.replace( /^\s*/, "" );
}

function rtrim ( s )
{
	return s.replace( /\s*$/, "" );
}

function trim ( s )
{
	return rtrim(ltrim(s));
}

/***
Validation: textarea maxlength
			***/
			
function checkTAreaLength(elem, maxlength) {
     if (elem.value.length >= maxlength) {
          alert('Please enter '+maxlength+' characters or less.');
          elem.focus();
          return false;
     } else {
          return true;
     }
}

/***
Format: amount field
			***/
			
function checkDecimals(obj) 
{
	var fieldName = obj.name;
	var fieldValue = obj.value;
	var blnResult = true;
	decallowed = 2;  // how many decimals are allowed?

	if (isNaN(fieldValue) || fieldValue == "") {
		alert("Please enter a valid decimal value.");
		var blnResult = false;
	} else {
		if (fieldValue.indexOf('.') == -1) fieldValue += ".";
			dectext = fieldValue.substring(fieldValue.indexOf('.')+1, fieldValue.length);

		if (dectext.length > decallowed) {
			alert ("Please enter a number with up to " + decallowed + " decimal places.");
			var blnResult = false;
      		} else {
			var blnResult = true;
      		}
   	}
   	return blnResult;
}

/***
Validation: numeric field
			***/
			
function checkNumeric(obj) 
{
   var strString = obj.value;
   var blnResult = true;
   if (strString.length != 0) {
   	if (IsNumeric(strString) == false) {
   		alert("Please enter a valid numeric value.");
   		obj.value = "0";
   		obj.select();
   		blnResult = false;
   	}	
   }
   return blnResult;
}			

function IsNumeric(strString)
{
   var strValidChars = "0123456789";
   var strChar;
   var blnResult = true;

   if (strString.length == 0) return false;

   for (i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         }
      }
   return blnResult;
}

/***
Validation: character/number field
			***/
			
function checkCN(elem) {
	var valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
	var ok = "yes";
	var temp;
	
	for (var i=0; i<elem.value.length; i++) {
		temp = "" + elem.value.substring(i, i+1);
		if (valid.indexOf(temp) == "-1") ok = "no";
	}
	
	if (ok == "no") {
		alert("Please enter characters and/or numbers only.");
		elem.focus();
		elem.select();
		return false;
  	 }
  	 return true;
}

/***
Validation: phone / fax number field
			***/
			
function checkPhone(elem) {
	var valid = "-0123456789"
	var ok = "yes";
	var temp;
	
	for (var i=0; i<elem.value.length; i++) {
		temp = "" + elem.value.substring(i, i+1);
		if (valid.indexOf(temp) == "-1") ok = "no";
	}
	
	if (ok == "no") {
		alert("Please enter numbers and/or dash (-) only.");
		elem.focus();
		elem.select();
		return false;
  	 }
  	 return true;
}

/***
Validation: file type (file upload)
			***/
			
var validExt = Array("doc", "xls", "ppt", "pdf", "txt", "jpg", "gif", "zip", "csv");
			
function checkExt(elem){
     	var filename = elem.value;
     	var filelength = parseInt(filename.length) - 3;
     	var fileext = filename.substring(filelength,filelength + 3);

      	// Check file extenstion
        if (validateExt(fileext)) {
     		alert ("Only doc, xls, ppt, pdf, txt, jpg, gif, zip or csv file is allowed to be uploaded.");
     		elem.focus();
                return false;
        } 
	return true;
}

function validateExt(fileext) {
	for (var i=0; i<validExt.length; i++) {
		if (MatchIgnoreCase(fileext, validExt[i]))
			return false;
	}
	return true;
}

function checkCsv(elem){
     	var filename = elem.value;
     	var filelength = parseInt(filename.length) - 3;
     	var fileext = filename.substring(filelength,filelength + 3);

      	// Check file extenstion
        if (!MatchIgnoreCase(fileext, "csv")) {
     		alert ("Only csv file is allowed to be uploaded for Statement of Compliance.");
     		elem.focus();
                return false;
        } 
	return true;
}

/***
Validation: Others
	type 1 - Comma (,) and double quotes (") are not allowed
	type 2 - Symbols (^) are not allowed (File upload)
			***/
			
function checkOther(elem, type) {
	var ok = "yes";
	var temp;
	
	if (type == 1) {
		var valid = ',"'
		for (var i=0; i<elem.value.length; i++) {
			temp = "" + elem.value.substring(i, i+1);
			if (valid.indexOf(temp) != "-1") ok = "no";
		}
	
		if (ok == "no") {
			alert('Comma (,) and double quotes (") are not allowed.');
			elem.focus();
			elem.select();
			return false;
  		}
  	 } else if (type == 2) {
		var valid = '^'
		for (var i=0; i<elem.value.length; i++) {
			temp = "" + elem.value.substring(i, i+1);
			if (valid.indexOf(temp) != "-1") ok = "no";
		}
	
		if (ok == "no") {
			alert('File name with symbols (^) is not allowed.');
			elem.focus();
			elem.select();
			return false;
  		}
  	 }
  	 return true;
}

/***
Validation: email field
			***/

function checkEmail(elem) 
{
   var str = Trim(elem.value);

   if (str.length == 0) {
   	return (true);
   }
   
   if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(elem.value))
	return (true);
   
   alert("Please enter a valid email value.");
   elem.focus();
   elem.select();
   return (false);
}

/***
Validation: time field
			***/

function IsValidTime(timeStr) {
// Checks if time is in HH:MM:SS AM/PM format.
// The seconds and AM/PM are optional.

   var str = Trim(timeStr);

   if (str.length == 0) {
   	return true;
   }

  var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;

  var matchArray = timeStr.match(timePat);
  if (matchArray == null) {
	alert("Time is not in a valid format.");
	return false;
  }
  
  hour = matchArray[1];
  minute = matchArray[2];
  second = matchArray[4];
  ampm = matchArray[6];

  if (second=="") { second = null; }
  if (ampm=="") { ampm = null }

  if (hour < 0  || hour > 23) {
	alert("Hour must be between 1 and 12. (or 0 and 23 for military time)");
	return false;
  }
  if (hour <= 12 && ampm == null) {
	if (confirm("Please indicate which time format you are using.  OK = Standard Time, CANCEL = Military Time")) {
	  alert("You must specify AM or PM.");
	  return false;
   	}
  }
  if  (hour > 12 && ampm != null) {
	alert("You can't specify AM or PM for military time.");
	return false;
  }
  if (minute<0 || minute > 59) {
	alert ("Minute must be between 0 and 59.");
	return false;
  }
  if (second != null && (second < 0 || second > 59)) {
	alert ("Second must be between 0 and 59.");
	return false;
  }
  return true;
}

/***
Match ignore case
			***/
			
function MatchIgnoreCase(a, b){
	if (a.toLowerCase() == b.toLowerCase())
		return true;
	else
		return false;
}

/***
Trim field (left & right)
			***/

function Trim(TRIM_VALUE)
{
  if(TRIM_VALUE.length < 1)
  	return"";

  TRIM_VALUE = RTrim(TRIM_VALUE);
  TRIM_VALUE = LTrim(TRIM_VALUE);
  
  if(TRIM_VALUE=="") {
	return "";
  } else {
	return TRIM_VALUE;
  }
}

function RTrim(VALUE)
{
  var w_space = String.fromCharCode(32);
  var v_length = VALUE.length;
  var strTemp = "";

  if(v_length < 0)
	return"";

  var iTemp = v_length -1;

  while(iTemp > -1)
  {
	if(VALUE.charAt(iTemp) == w_space) {
	} else {
	  strTemp = VALUE.substring(0,iTemp +1);
	  break;
	}
	iTemp = iTemp-1;
  }
  
  return strTemp;
}

function LTrim(VALUE)
{
  var w_space = String.fromCharCode(32);
  
  if(v_length < 1)
	return"";

  var v_length = VALUE.length;
  var strTemp = "";
  var iTemp = 0;

  while(iTemp < v_length)
  {
	if(VALUE.charAt(iTemp) == w_space) {
	} else {
	  strTemp = VALUE.substring(iTemp,v_length);
	  break;
	}
	iTemp = iTemp + 1;
  } 

  return strTemp;
}

/***
Place focus on the 1st field of the form
					***/

function placeFocus() {
   if (document.forms.length > 0) 
   {
   	var field = document.forms[0];
	for (i = 0; i < field.length; i++) 
	{
	   if ((field.elements[i].type == "text") || (field.elements[i].type == "textarea") || (field.elements[i].type.toString().charAt(0) == "s")) 
	   {
		document.forms[0].elements[i].focus();
		break;
           }
      	}
   }
}

/***
Replace substring
		***/

function replaceSubstring(inputString, fromString, toString) {
   // Goes through the inputString and replaces every occurrence of fromString with toString
   var temp = inputString;
   if (fromString == "") {
      return inputString;
   }
   if (toString.indexOf(fromString) == -1) { // If the string being replaced is not a part of the replacement string (normal situation)
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } else { // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
      var midStrings = new Array("~", "`", "_", "^", "#");
      var midStringLen = 1;
      var midString = "";
      // Find a string that doesn't exist in the inputString to be used
      // as an "inbetween" string
      while (midString == "") {
         for (var i=0; i < midStrings.length; i++) {
            var tempMidString = "";
            for (var j=0; j < midStringLen; j++) { tempMidString += midStrings[i]; }
            if (fromString.indexOf(tempMidString) == -1) {
               midString = tempMidString;
               i = midStrings.length + 1;
            }
         }
      } // Keep on going until we build an "inbetween" string that doesn't exist
      // Now go through and do two replaces - first, replace the "fromString" with the "inbetween" string
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + midString + toTheRight;
      }
      // Next, replace the "inbetween" string with the "toString"
      while (temp.indexOf(midString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(midString));
         var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } // Ends the check to see if the string being replaced is part of the replacement string or not
   return temp; // Send the updated string back to the user
} // Ends the "replaceSubstring" function

/***
Check caps lock on/off
		***/
		
function checkCapsLock( e ) { // e.g. onKeyPress="checkCapsLock(event)"
	var myKeyCode=0;
	var myShiftKey=false;
	var myMsg='Caps Lock is On.\n\nTo prevent entering your password incorrectly,\nyou should press Caps Lock to turn it off.';

	// Internet Explorer 4+
	if ( document.all ) {
		myKeyCode=e.keyCode;
		myShiftKey=e.shiftKey;

	// Netscape 4
	} else if ( document.layers ) {
		myKeyCode=e.which;
		myShiftKey=( myKeyCode == 16 ) ? true : false;

	// Netscape 6
	} else if ( document.getElementById ) {
		myKeyCode=e.which;
		myShiftKey=( myKeyCode == 16 ) ? true : false;

	}

	// Upper case letters are seen without depressing the Shift key, therefore Caps Lock is on
	if ( ( myKeyCode >= 65 && myKeyCode <= 90 ) && !myShiftKey ) {
		alert( myMsg );

	// Lower case letters are seen while depressing the Shift key, therefore Caps Lock is on
	} else if ( ( myKeyCode >= 97 && myKeyCode <= 122 ) && myShiftKey ) {
		alert( myMsg );

	}
}

/***
Toggle field background between normal and readonly
						***/
		
function toggleColor(objElement, turn)
{
  	if (turn == false)
    		objElement.className='readonly';
  	else
    		objElement.className='normal';
}

/***
URL encoding
	***/
						
function URLencode(sStr) {
    return escape(sStr).replace(/\+/g, '%2C').replace(/\"/g,'%22').replace(/\'/g, '%27');
}

/***
check phone, fax , mobile in format of country code + area code + tel no
	***/
	
function checkTel(obj1, obj2, obj3, fieldname)
{
	if (obj1.value == "" && obj2.value == "" && obj3.value == "")
	{
		return null;	
	}
	else if (obj1.value != "" && obj2.value != "" && obj3.value != "")
	{
		if (checkNumeric(obj1) && checkNumeric(obj2) && checkNumeric(obj3))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	else
	{
		alert("Please complete " + fieldname + ".");
		return false;
	}
}
