  var IE4 = document.all;
  var NN4 = document.layers;
  var NN6 = (navigator.appName == "Netscape" && parseInt(navigator.appVersion) >= 5);
  
  // Global variable to stop prevent submit to be click multiple time
  var gSubmitClicked = false;
  
  function getSpanObject(obj) {
	return (IE4?eval("document.all." + "span_"+obj):(NN6?document.getElementById("span_"+obj):false));
  }

  function highlightText(obj,e) {

    if (NN4) {
        e.focus();
    } else {
    	var theObj = getSpanObject(obj);
        if (theObj)
	    	theObj.style.backgroundColor = "#FF0000";
    }
  }

  function unHighlightText(obj) {
	var theObj = getSpanObject(obj);
	if (theObj)
		theObj.style.backgroundColor = "";
  }
  
  badchars = ["  ","!","\"","?","^","*","(",")","{","}","`","|","\\",":",";","~","#","<",",",">","?","/",".","@","[","]"];  

  function verifyEmail(email) {
    if (email.indexOf("@") < 1 || email.indexOf("@") > email.length - 5 || email.length < 6 || email.indexOf(".") < 1)
        return false;
    for (var i = 0; i < badchars.length-4; i++) {
        if (email.indexOf(badchars[i]) != -1) {
            return false;
        }
    }
    return true;
  }

  function setSubject() {
    if(document.survey.sel_subject.value=='Other') {
       document.survey.subject.value=document.survey.other_subject.value;
    } else {
       document.survey.subject.value = document.survey.sel_subject.value;
    }
  }
  
  /* This function uses Ajax to verify Captra before calling form submit */
  function Captcha_verify(oForm, verify_func)
  {
  	// Do nothing if gSubmitClicked is set
  	if(gSubmitClicked == true)
  	{
  		alert("Please wait while the system verify your information.");
  		return;
  	}
  	else
  	{
  		// Set it to true to prevent another submit click until verification completed
  		gSubmitClicked = true;
  	}
  
  	var oShowProgress = false;
  	var sProgressMessage = "";
  	
  	var params = "captcha=" + document.getElementById("captcha").value + "&captcha-hash=" + document.getElementById("captcha-hash").value + "&encrypt=" + document.getElementById("encrypt").value;
  	var url = "/vnu/actions/captraverify?" + params;
  	var oMessageText = document.getElementById("id_captcha_errorMessage");
  	
  	// Show progress while it is retrieving data from server
  	function showProgress()
  	{
  		sOriginalProgressMessage = sProgressMessage;
  		
  		function displayMessage()
  		{
  			if(oShowProgress)
  			{
  				if(oMessageText != null)
  				{
  					oMessageText.innerHTML = sProgressMessage + " . . . . .";
  				}
  			}
  		}
  		
  		window.setTimeout(displayMessage, 3000);
  		if(oMessageText != null)
  		{
  			oMessageText.innerHTML = sProgressMessage;
  		}
  			
  		if(oShowProgress)
  		{
  			window.setTimeout(showProgress, 5000);
  		}
  	}
  		
    // Ajax callback function
  	function callback(responseText) 
  	{   
  		// If it successfully validated, then submit form
  		if(responseText.indexOf("<Status>SUCCESSFUL</Status>") >= 0)
  		{
  			gSubmitClicked = false;
  			oForm.submit();
  		}
  		// Otherwise, if CapcthaCode returns, then get a new image and set captcha-hash
  		else if(responseText.match(".*<CaptchaCode>.*</CaptchaCode>.*"))
  		{
  			var sCaptchaCode = responseText.substring(responseText.indexOf("<CaptchaCode>")+13, responseText.indexOf("</CaptchaCode>"));
  			
  			var oCaptchaImage =  document.getElementById("captcha-hash_img");
  			
  			if(oCaptchaImage != null)
  			{
  				sProgressMessage = "Verfication code not matched, retrieving new code";
  				
  				oCaptchaImage.src = "/remoteload/captcha/" + sCaptchaCode + ".jpg";
  				var oCaptcha_hashInput =  document.getElementById("captcha-hash");
  				
  				if(oCaptcha_hashInput != null)
  				{
  					oCaptcha_hashInput.value = sCaptchaCode;
  				}
  			}
  			
  			oShowProgress = false;
  			sProgressMessage = "<b>Please enter code as shown above and resubmit again.</b>";
  			showProgress();
  		}
  		// use the old method, but shouldn't really be here unless problem with Ajax call.
  		else
  		{
  			// Should never really be here
  			window.history.back();
  		}
  		
  		gSubmitClicked = false;
  	}
  	
  	if(verify_func)
  	{
  		if(oMessageText != null)
  		{
  			oMessageText.style.display = "";
  			oShowProgress = true;
  			sProgressMessage = "Validating verification code, please wait";
  			showProgress();
  		}
  			
  		var ajax = new Ajax_call(url, callback);
  		ajax.doGet(); 
  	}
  	else
  	{
  		gSubmitClicked = false;
  	}
  }
  
  /*
    This function verifies html forms. It's designed for feedback but it can also
    be used for other forms. The fields table specifies mandatory fields.
    NOTE: If you want text to be un/highlighted use 'span_<field>' naming to indicate
    spans corresponding to fields in your html document, i.e.
    <form onsubmit="verify(document.form, ['comments'])">
      <span id="span_comments">Your comments </span>
      <textarea name="comments"> </textarea>
    </form>
  */
  function verify(f, fields) {
   
    var status = 'OK';

    for (var i = 0; i < fields.length; i++) {
         var element = eval('f.'+fields[i]);
         /*Check multiple elements (checkboxes radio and drop-down lists) for at least option checked*/
         if(element != null && element.length) {
            var allUnchecked = true;
            for(var j=0;j<element.length;j++) {
                var sub = element[j];
                if(sub.type=='checkbox' || sub.type=='radio') {
                   if(sub.checked) {
                      allUnchecked = false;
                      break;
                   }
                //drop-down
                } else if(element.type=='select-one') {
                  if(sub.selected && sub.value!='') {
                     allUnchecked = false;
                      break;
                  }
                } else if(element.type=='select-multiple') {
                  if(sub.selected && sub.value!='') {
                     allUnchecked = false;
                     break;
                  }
                }
            }
            if(allUnchecked) {
               highlightText(fields[i]);
               status = 'FAILED';
            }

         }
         
         if(element && element.value=='') {
            highlightText(fields[i]);
            status = 'FAILED';
         }
    }

    if(f.sel_subject) {
      if( (f.sel_subject.value=='Other') 
         && ( (f.other_subject.value=='If other, please specify...')
         || (f.other_subject.value=='') ) ) {
         f.other_subject.style.backgroundColor = 'RED';
         status = 'FAILED';
      }
    }

    if(status=='FAILED') {
       alert('Please fill in all the required fields.');
       return false;
    }

    if(f.email) {
       if( (!f.email.value=='') && (!verifyEmail(f.email.value)) ) {
          alert('The email address you typed does not appear to be valid.');
          highlightText('email'); 
          return false;
       }
    }
    
    if(f.to) {
       if( (!f.to.value=='') && (!verifyEmail(f.to.value)) ) {
          alert('The email address of recipient you typed does not appear to be valid.');
          highlightText('to'); 
          return false;
       }
    }

    if(f.email_retype) {
       if( (!f.email.value=='') && (f.email.value!=f.email_retype.value) ) {
          alert('\'Email\' and \'Confirm Email\' must match.');
          highlightText('email');
          highlightText('email_retype');
          return false;
       }
    }


    if(f.from) {
       if( (!f.from.value=='') && (!verifyEmail(f.from.value)) ) {
          alert('The email address you typed does not appear to be valid.');
          highlightText('from'); 
          return false;
       }
    }
    
    if(f.sel_subject) {
       setSubject();
    }
    
    return true;
  }
