/**
 * Set the selectedIndex property on the form.
 */
function setSelectedIndex(formName, index) {
  var cnt = 0;
  //alert('setSelectedIndex('+formName+','+index+') - start');

  // check for multiple hidden fields - for the selectedIndex field
  for (i=0;i<document.forms[formName].elements.length;i++) {
     if( document.forms[formName].elements[i].name=='selectedIndex' ){
        cnt++;
     }
  }
  // only set first hidden field - we only use the first occurance of the selected index.
  if(cnt > 1) {
    document.forms[formName].elements['selectedIndex'][0].value = index;
  } else {
    document.forms[formName].elements['selectedIndex'].value = index;
  }

  //alert('setSelectedIndex('+formName+','+index+') - end');
  return true;
}

function submitWebForm(formName) {
    //alert("SUBMIT");
    actionWebForm(formName,'userAction','submit');
}

// Generic submit function
// - should not be called directly
//
var actioned = false;
function actionWebForm(formName, fieldName, fieldValue) {
    //avoid from people clicking the button twice...
    if(actioned)
    {
        alert("Your first action is still processing, please wait.");
        return;
    }
    var cnt=0;
    var hiddenElement;
    for(i=0; i<document.forms[formName].elements.length; i++) {
	hiddenElement = document.forms[formName].elements[i];
        if(hiddenElement.name==fieldName && hiddenElement.type=="hidden") {
            hiddenElement.value = fieldValue;
            break;
    }
    }
    actioned = true;
    document.forms[formName].submit();
}

// Generic submit function for objects that are indexed on the page.
// - should not be called directly
//
function actionIndexedWebForm(formName, fieldName, fieldValue, index){
  var cnt = 0;
  // (1) Set the selected index.
  setSelectedIndex(formName, index);

  // (2) Action the form.
  actionWebForm(formName, fieldName, fieldValue);
}

//===========================================================
// NAVIGATION TAG (ONLY)
//===========================================================
// DEPRECATED - USE actionWebForm INSTEAD - KEPT HERE FOR NAVIGATION TAG SUPPORT
function submitAction(formName, fieldName, fieldValue){
  // check for multiple hidden fields
  var cnt = 0;
  var submitForm = true;
  var funcCall = "";
  for (i=0;i<document.forms[formName].elements.length;i++) {
     if( document.forms[formName].elements[i].name==fieldName ){
        cnt++;
     }
  }
  // only set first hidden field
  if( cnt > 1 ){
      document.forms[formName].elements[fieldName][0].value = fieldValue;
   } else {
      document.forms[formName].elements[fieldName].value = fieldValue;
   }
   if( submitForm == true ){
     document.forms[formName].submit()
   }
}

function checkSubmit(event,formName) {
    if( getKey(event)) {
          document.forms[formName].submit();
          event.returnValue=false;
    }
}

function getKey(evt){
   if(navigator.appName=="Netscape"){theKey=evt.which}
   if(navigator.appName.indexOf("Microsoft")!=-1){theKey=window.event.keyCode}
   if(theKey==13){
      return true;
   }
   return false;
}
//===========================================================
// POPUP WINDOWS
//===========================================================
function popupWindow(url,winName,w,h) {
    //alert('popup');
    leftPos=(screen.width-w)/2;
    topPos=(screen.height-h)/2;

    // If the window is null or closed then it will be opened here.
    window.open(url,winName,"toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no,width="+w+",height="+h+",left="+leftPos+",top="+topPos);
}

function popupScrollableWindow(url,winName,w,h) {
    leftPos=(screen.width-w)/2;
    topPos=(screen.height-h)/2;

    // If the window is null or closed then it will be opened here.
    window.open(url,winName,"toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,copyhistory=no,width="+w+",height="+h+",left="+leftPos+",top="+topPos);
}

// provides a handle to the opened window so the caller has some control over it.
function popupHandleableWindow(url,winName,w,h) {
    //alert('popup');
    leftPos=(screen.width-w)/2;
    topPos=(screen.height-h)/2;

    // If the window is null or closed then it will be opened here.
    return window.open(url,winName,"toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no,width="+w+",height="+h+",left="+leftPos+",top="+topPos);
}

function notInDemo(msg) {
    alert("Not implemented in demo:\n - "+msg);
}

//===========================================================
// DIV HANDLING - hide & show of html divs making up form
//===========================================================

// Show specified div
//
function showFormPart(div) {
    document.getElementById(div).style.display='';
}

// Hide specified div
//
function hideFormPart(div) {
    document.getElementById(div).style.display='none';
}

// Toggle form divs
// - displaying one & hiding another
//
function toggleFormPart(displayDiv, hideDiv) {
    //alert("Hide ["+hideDiv+"], Display ["+displayDiv+"]");
    hideFormPart(hideDiv);
    showFormPart(displayDiv);
}

// Toggle a specific individual div - on or off.
//
function toggleDiv(div) {
    var divObject = document.getElementById(div);
    if(divObject.style.display=='none') divObject.style.display='';
    else divObject.style.display='none';
}

// Toggle a specific individual img - replaces the img src depending on the current src.
//
function toggleImg(name,src1,src2) {
    //alert('toggleImg() name['+name+'] src1['+src1+'] src2['+src2+'] existing src['+document.images[name].src+']');
    var image = document.getElementById(name);
    var imgsrc=image.src;
    if(imgsrc.indexOf(src1) > -1) {
        document.images[name].src=src2;
    } else {
        document.images[name].src=src1;
    }
}

// Return next part unless option is TRUE then return optional part
//
function nextFormPart(formName, option, optionalPart, nextPart) {
    var returnPart=nextPart;
    //'yes' radio button for option is first in array
    //alert('nextFormPart-formName='+formName+',option='+option+',optionalPart='+optionalPart+',nextPart='+nextPart+'.');
    if(option.length>0) {
        if(document.forms[formName].elements[option][0].checked) returnPart=optionalPart;
    }
    return returnPart;
}

//===========================================================
// IMAGE HANDLING - set images (for mouseover etc...)
//===========================================================

function setImage(imageName,imageSrc) {
    if(document.images) {
        document[imageName].src=imageSrc;
    }
}

//===========================================================
// MULTI PART FORM HANDLING - validation & submiting of forms
//===========================================================

// Store active parts in form
//
function setPartFields(formName,activePart,previousPart) {
    document.forms[formName].elements['activePart'].value=activePart;
    document.forms[formName].elements['previousPart'].value=previousPart;
}
function setTaskFields(formName,formMethod,ruleSet,save) {
    document.forms[formName].elements['formMethod'].value=formMethod;
    document.forms[formName].elements['ruleSet'].value=ruleSet;
    document.forms[formName].elements['save'].value=save;
}

// Display next form part
// - navigation handled locally by javascript - no server call
//
function navigateMultiPartWebForm(formName, currentPart, nextPart) {
    setPartFields(formName,nextPart,currentPart);
    toggleFormPart(nextPart,currentPart);
}
function navigateMultiPartWebFormOptional(formName, currentPart, option, optionalPart, nextPart) {
    //alert(selectName+" is checked ["+document.forms[formName].elements[option][0].checked+"]");
    navigateMultiPartWebForm(formName, currentPart, nextFormPart(formName,option,optionalPart,nextPart));
}

function actionMultiPartWebForm(userAction,formName,currentPart,nextPart,formMethod,ruleSet,save) {
    setPartFields(formName,nextPart,currentPart);
    setTaskFields(formName,formMethod,ruleSet,save);
    actionWebForm(formName,'userAction',userAction);
}

function actionMultiPartWebFormOptional(userAction,formName,currentPart,nextPart,formMethod,ruleSet,save,option,optionalPart) {
    actionMultiPartWebForm(userAction,formName,currentPart,nextFormPart(formName,option,optionalPart,nextPart),formMethod,ruleSet,save);
}

function getFormContextPath(formName)
{
    var formInstance = document.forms[formName];
    var formContextPathObject = formInstance.contextPath;
    var fromContextPathValue = null;
    if(formContextPathObject.value)
    {
        formContextPathValue = formContextPathObject.value;
    }
    else
    {
        formContextPathValue = formContextPathObject[0].value;
    }

    return formContextPathValue;
}

//================
//==Trim Methods==
//================
function lTrim(str){
	if (str==null){return null;}
	for(var i=0;str.charAt(i)==" ";i++);
	return str.substring(i,str.length);
}
function rTrim(str){
	if (str==null){return null;}
	for(var i=str.length-1;str.charAt(i)==" ";i--);
	return str.substring(0,i+1);
}
function trim(str){return lTrim(rTrim(str));}
function trimMulti(str) {
    //Trims mutli spaces (into a single space).
    var buff=str;
    while(true) {
        i=buff.indexOf("  ");
        if(i<0) break;
        //alert('substring first['+str.substring(0,i)+'] second['+str.substring(i+2,str.length)+']');
        buff=buff.substring(0,i) + buff.substring(i+1,buff.length);
    }

    return buff;
}

//=======================
// ==Validation Helpers==
//=======================
function isNumeric(valueToCheck) {
  //Numerics may not have spaces.
  if(valueToCheck.length != trimSpace(valueToCheck).length) return false;
  //Numerics must be a number.
  return isNaN(valueToCheck,10) ? false : true ;
}
function isEmpty(inputValue) {
    if(inputValue==null) return true;
    if(trimSpace(inputValue).length==0) return true;
    return false ;
}
function isObjEmpty(obj) {
    if(obj.value==null) return true;
    if(trimSpace(obj.value).length==0) return true;
    return false ;
}
//====================
// ==Date Validation==
//====================
function validateDateInput(obj) {
   //alert(obj.value);
   var date=new String(obj.value);

   //field is not mandatory
   if(date.length==0) return true;

   //check length and forward slashes
   if(date.length!=10 || date.charAt(2)!='/' || date.charAt(5)!='/') {
       return invalidDate(obj);
   }

   //check numerics
   if(!isNumeric(date.substr(0,2)) ||
      !isNumeric(date.substr(3,2)) ||
      !isNumeric(date.substr(6,4))) {
       return invalidDate(obj);
   }

   return true;
}

function invalidDate(obj) {
    alert("The value " + obj.value + " is not in a vaild date format.\n\r" +
          "Please enter date in the format dd/mm/yyyy.");
    obj.focus();
    obj.select();
    return false;
}

//======================
// ==Number Validation==
//======================
function validateNumberInput(obj) {
   //alert(obj.value);
   var number=new String(obj.value);

   //field is not mandatory
   if(number.length==0) return true;

   //check numerics
   if(!isNumeric(number)) {
       return invalidNumber(obj);
   }

   return true;
}

var minInteger=new Number(-2147483648);
var maxInteger=new Number(2147483647);
function validateIntegerInput(obj) {

    if(!validateNumberInput(obj)) return true;

    // Check integer range.
    var o = new Number(obj.value);
    if(o.valueOf() < minInteger.valueOf() || o.valueOf() > maxInteger.valueOf()) invalidIntegerNumber(obj);
    //alert('o='+o.valueOf()+', minInteger='+minInteger.valueOf()+', maxInteger='+maxInteger.valueOf());
}

function invalidNumber(obj) {
    alert("The value '" + obj.value + "' is not in a vaild number.\n\r" +
          "Please enter the number only with numeric characters - alphabetic characters and/or spaces are not allowed.");
    obj.focus();
    obj.select();
    return false;
}

function invalidIntegerNumber(obj) {
    alert("The value " + obj.value + " is not in a vaild number.\n\r" +
          "This field can only accept numbers in the range "+minInteger+" to "+maxInteger+".");
    obj.focus();
    obj.select();
    return false;
}

//===============================
// ==Mandatory Field Validation==
//===============================
function validateMandatoryField(obj) {
    if(isObjEmpty(obj)) {
        alert("Field is mandatory, it must contain text.");
        obj.focus();
        obj.select();
        return false;
    }
    return true;
}

//=================
// ==Number Utils==
//=================
function zeroPadNumber(obj,finalLength) {
    var number=new String(obj.value);

    //field is not mandatory
    if(number.length==0) return true;

    //identify number of zero's required
    var padNumber=finalLength-(number.length);

    //pad with zero's
    var finalNumber='';
    for(var i=0;i<padNumber;i++) {
        finalNumber = finalNumber + '0';
    }

    //assign new number
    obj.value=finalNumber+number;;

    return true;
}

//===============
//==Array Utils==
//===============
function convertArrayToString(obj,delimiter){
	if (typeof(delimiter)=="undefined" || delimiter==null) {
		delimiter = "";
	}
	var s="";
	if(obj==null||obj.length<=0){return s;}
	for(var i=0;i<obj.length;i++){
		s=s+((s=="")?"":delimiter)+obj[i].toString();
	}
	return s;
}

/* *****************************************************************************************************************
 * function that returns the input value after trimming the leading and lagging spaces if any
 * there is no trim() function in javascript
 *
 *@author ramiahb
 *@version 1.1 14/11/2001
 *@usages - isEmpty, validateMFLApplicableAdaptationModify, validateAdaptationAgreementSearch
 *Moved to common - 10/01/2002
 ******************************************************************************************************************/
function trimSpace(inputValue)
{
    //if incoming value is of zero length, no need to process
    if(inputValue == null || inputValue.length==0)
    {
        return inputValue;
    }
    var leadSpaceCount=0;
    var lagSpaceCount=0;
    //loop through the string
    for(loopCounter=0;loopCounter< inputValue.length;loopCounter++)
    {
        //check whether the ascii code of the character is 32 - empty space
        if(parseInt(inputValue.charCodeAt(loopCounter)) == 32)
        {
            //gives the lead space count
            leadSpaceCount+=1;
        }
        else
        {
            //if we encounter a non-space char, break
            break;
        }

    }

    //if leadSpaceCount is equal to the length of the string, then the string is full of empty spaces.
    //no need to do this
    if (leadSpaceCount != inputValue.length)
    {
        //loop through the string in reverse to find the lagging spaces
        for(loopCounter=inputValue.length-1;loopCounter>=0;loopCounter--)
        {
                if(parseInt(inputValue.charCodeAt(loopCounter)) == 32)
                {
                    lagSpaceCount+=1;
                }
                else
                {
                    break;
                }
       }
    }// if

    // do we have to trim any leading space?
    if(leadSpaceCount > 0)
    {
        inputValue = inputValue.substring(leadSpaceCount,inputValue.length);
    }
    // do we have to trim any lagging space?
    if(lagSpaceCount>0)
    {
        inputValue= inputValue.substring(0,inputValue.length-lagSpaceCount);
    }
    return(inputValue);

}

//====================
// ==Processing Page==
//====================
function launchProcessingPage() {if(top) top.launchProcessingPage();}
function closeProcessingPage() {if(top && top.processingPageHandle) top.closeProcessingPage();}
function closeProcessingPageFromPopup(popupHandle) {
    if(popupHandle && popupHandle.opener && popupHandle.opener.top && popupHandle.opener.top.processingPageHandle) {
        popupHandle.opener.top.closeProcessingPage();
        popupHandle.focus();
     }
}

/* *****************************************************************************************************************
 * function that checks passwords entered are the same and submits form.
 *
 * *****************************************************************************************************************/

function checkPasswd()
{
        if  ( document.registrationForm.password1.value == null || document.registrationForm.password1.value == " ")
        {
             alert('Invalid Passwords. Please try again.');
        }
        else if (document.registrationForm.password1.value == document.registrationForm.password2.value  )
        {

            document.registrationForm.confirmPassword.value = document.registrationForm.password1.value;

            //validation complete... let's submit
            submitWebForm('registrationForm');
        }
        else
        {
            alert('The passwords do not match. Please try again.');
        }
}

/* *****************************************************************************************************************
 * function that validates content of a data field to ensure it is alpha and/or numeric (A-Z, a-z, 0-9)
 *
 * *****************************************************************************************************************/
function validateAlphaNumericInput(obj){
    //content can be all numbers, all characters A-Z or a combination of both
    //alert(obj.value)
    var inputValue =new String(obj.value);
    //field is not mandatory
    if(inputValue.length==0) return true;

     //if all numeric then ok
     if(isNumeric(inputValue)) {
        //alert("valid numeric");
        return true;
     }
     else{
        //not entirely numeric so need to check that a valid combo of A-Z, a-z and 0-9 ONLY
        if (!isAlphaNumeric(inputValue)) {
            //alert("Invalid");
            obj.focus();

            //trim before putting back
            inputValue = trimSpace(inputValue);
            obj.value = inputValue;

            return false;
        }
        //alert("valid");
        return true;
     }
}

//Helper to determine if Alpha-Numeric
function isAlphaNumeric(inputValue){
    var valid="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

        for (var i=0; i<inputValue.length; i++) {
            if (valid.indexOf(inputValue.charAt(i)) < 0) {
                 alert("The value '" + inputValue + "' is not valid.\n\r" +
                    "Please enter only numeric and/or alphabetic characters. Spaces are not allowed.");
                return false;
            }
        }

        return true;
}
//Convert non numeric characters to spaces and trim blanks from start and end.
function convertPhoneNumber(obj) {
    var number=new String(obj.value);
    //alert('original number['+number+']');
    var numberArray=number.split('');

    //Convert non numeric characters to a space.
    for(var i=0;i<number.length;i++) {
        if(!isNumeric(number.charAt(i))) numberArray[i]=" ";
    }
    number=convertArrayToString(numberArray);
    //alert('number after conversion of non numeric characters to spaces['+number+']');

    //Remove spaces from start and end.
    number=trim(number);
    number=trimMulti(number);
    //alert('final number['+number+']');

    //Reassign to the original object.
    obj.value=number;
}