var White = "#ffffff";
var Black = "#000000";
var BadInput = "#ffffbb";
var SelectRequiredColor = "#fff7f7";

var digits = "0123456789";
var lowerCaseLetters = "abcdefghijklmnopqrstuvwxyz";
var upperCaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var alphaChars = lowerCaseLetters + upperCaseLetters + digits + " .-_&";
var stringChars = alphaChars + ",?/<>;:'[]!@#$%&*()+=";
var whiteSpace = " \t\n\r";
var defaultHelp = "Please move mouse onto one of the options to get additional help.";

var monthNames = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
var dayNames = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');

var IsIE = navigator.userAgent.search(/MSIE/g) > 0;

var ChildID = CalculateChildID();
eval("var childWindowLibraryDM_" + ChildID + ";");

/**** TEST AND VALIDATE FUNCTIONS ************************************/
// IsAmericanExpress(s)
// IsDecimal(s)
// IsDiscover(s)
// IsDate(s)
// IsEmail(s)
// IsEmpty(s)
// IsMajorCreditCard(s)
// IsMasterCard(s)
// IsUrl(s)
// IsValidCreditCard(s, clean)
// IsVisa(s)

/**** FORMATTING FUNCTIONS *******************************************/
// Caps(s, case)
// CutString (s, length, dots)
// FormatCurrency(num, dollar)
// NeatCharsInBag (s, bag, replaceChar)
// Reformat (s)
// StripCharsInBag (s, bag)
// StripCharsNotInBag (s, bag)
// ToggleImage (imageID, newSrc)
// Trim(s)

/**** USER INPUT FUNCTIONS **********************************/
// Blur(element)
// BlurForm(form)
// ValidateCreditCard(inputField, required)
// ValidateDate(inputField, required)
// ValidateEmail(inputField, required)
// ValidateForm(form)
// ValidateMonthYear(inputField, required)
// ValidateNumber(inputField, required, validChars, currency)
// ValidatePhone(inputField, required)
// ValidateRadio(inputField, required)
// ValidateSelection(inputField, required)
// ValidateSsn(inputField, required)
// ValidateString(inputField, required, validChars, case)
// ValidateText(inputField, required, list)
// ValidateTime(inputField, required)
// ValidateUrl(inputField, required)

/**** ADDITIONAL FUNCTIONS *******************************************/
// Ajax(script, seconds)
// ChildWindow(url, width, height, scrollbars, resizable)
// Property(objectName, propertyName, propertyValue, notString)
// ShowHelp(s)

/*********************************************************************/
/**** TEST AND VALIDATE FUNCTIONS ************************************/
/*********************************************************************/
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function IsAmericanExpress(s) {
  s = StripCharsNotInBag(s, digits);

  firstdig = s.substring(0, 1);
  seconddig = s.substring(1, 2);
  if (s.length == 15 && firstdig == 3 && (seconddig == 4 || seconddig == 7)) return IsValidCreditCard(s, 1);
  return false;
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function IsDate(inputDate){
	return !isNaN(new Date(inputDate));
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function IsDiscover(s) {
  s = StripCharsNotInBag(s, digits);

  first4digs = s.substring(0, 4);

  if (s.length == 16 && first4digs == "6011") return IsValidCreditCard(s, 1);
  return false;
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function IsEmail(s) {
  if (IsEmpty(s)) return false;
  return s.match(/^[A-Za-z0-9_]+([_\-\.]\w+)*\@[A-Za-z0-9_]+([_\-\.]\w+)*\.[A-Za-z0-9]+$/) ? true : false;
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function IsEmpty(s) {
  return ((s == null) || (s.length == 0));
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function IsMajorCreditCard(s) {
  if (IsVisa(s) == 1) ccType = "Visa";
  else if (IsMasterCard(s)) ccType = "MasterCard";
  else if (IsAmericanExpress(s)) ccType = "American Express";
  else if (IsDiscover(s)) ccType = "Discover";
  else ccType = "";

  return ccType
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function IsMasterCard(s) {
  s = StripCharsNotInBag(s, digits);

  firstdig = s.substring(0, 1);
  seconddig = s.substring(1, 2);

  if (s.length == 16 && firstdig == 5 && (seconddig >= 1 && seconddig <= 5)) return IsValidCreditCard(s, 1);
  return false;
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function IsUrl(s) {
  if (IsEmpty(s)) return false;

  return s.match(/^(https:\/\/)?[A-Za-z0-9]+([\-\.\?\^\|\+\/~#&=,;]\w+)*(:[0-9]+)?$/) ? true : false;
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function IsValidCreditCard(s, clean) {
  if (!clean) s = StripCharsNotInBag(s, digits);
  if (s.length > 16 || s.length < 13) return (false);

  sum = 0; mul = 1; l = s.length;
  for (var i = 0; i < l; i++) {
    digit = s.substring(l - i - 1, l - i);
    tproduct = parseInt(digit, 10) * mul;

    if (tproduct >= 10) sum += (tproduct % 10) + 1;
    else sum += tproduct;

    if (mul == 1) mul++;
    else mul--;
  }

  if ((sum % 10) == 0) return true;
  else return false;
} 

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function IsVisa(s) {
  s = StripCharsNotInBag(s, digits);
  if ((s.length == 16 || s.length == 13) && s.substring(0, 1) == 4) return IsValidCreditCard(s, 1);
  return false;
}

/*********************************************************************/
/**** FORMATTING FUNCTIONS *******************************************/
/*********************************************************************/
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function Caps(s, textCase) {
  if (IsEmpty(s)) return "";
  if (s) {
  	s = NeatCharsInBag(s, whiteSpace);
    if (textCase == "upper") s = s.toUpperCase();
    else if (textCase == "lower") s = s.toLowerCase();
    else if(textCase != "none") {
      splitStr = s.split(" ");
      for(var i = 0; i < splitStr.length; i++) splitStr[i] = splitStr[i].substring(0, 1).toUpperCase() + splitStr[i].substring(1);
      s = splitStr.join(" ");
    }
	}
	return s;
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function CutString (s, length, dots) {
  if (length == null) length = 0

  if (s.length > length) return s.substr(0, length) + dots;
  else return s;
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function FormatCurrency(num, dollar) {
  if (num == null || (num == "" && num != 0)) return "";
  
  num = num.toString().replace(/\$|\,/g, '');
  if (isNaN(num)) num = "0";
  sign = (num == (num = Math.abs(num)));
  num = Math.floor(num * 100 + 0.50000000001);
  cents = num % 100;
  num = Math.floor(num / 100).toString();
  if (cents < 10) cents = "0" + cents;
  for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
    num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
  return (((sign) ? '' : '-') + (dollar ? dollar : '') + num + '.' + cents);
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function NeatCharsInBag (s, bag, replaceChar) {
var i, j;
var returnString = "";

  if (IsEmpty(s)) return "";
  if (IsEmpty(bag)) bag = " ";
  if (IsEmpty(replaceChar)) replaceChar = " ";
  for (i = 0; i < s.length; i++) {
    if (bag.indexOf(s.charAt(i)) == -1) break;
  }
  for (j = i; j < s.length; j++) {   
    if (bag.indexOf(s.charAt(j)) == -1) returnString += s.charAt(j);
	  else if (j > 0 && bag.indexOf(s.charAt(j - 1)) == -1) returnString += replaceChar;
  }

  return returnString;
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function Reformat (s) {
var arg;
var sPos = 0;
var resultString = "";

  if (IsEmpty(s)) return "";
  for (var i = 1; i < Reformat.arguments.length; i++) {
    arg = Reformat.arguments[i];
    if (i % 2 == 1) resultString += arg;
    else {
      resultString += s.substring(sPos, sPos + arg);
      sPos += arg;
    }
  }
  return resultString + s.substring(sPos);
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function StripCharsInBag (s, bag) {
var returnString = "";

  if (IsEmpty(s)) return "";
  if (IsEmpty(bag)) bag = "";
 
  for (var i = 0; i < s.length; i++) {   
    var c = s.charAt(i);
    if (bag.indexOf(c) == -1) returnString += c;
  }

  return returnString;
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function StripCharsNotInBag (s, bag) {
var returnString = "";
var c;

  if (IsEmpty(s)) return "";
  if (IsEmpty(bag)) bag = "";
  for (var i = 0; i < s.length; i++) {   
    c = s.charAt(i);
    if (bag.indexOf(c) != -1) returnString += c;
  }
 
  return returnString;
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function ToggleImage (imageID, newSrc) {
var image = document.getElementById(imageID);

  if (image && newSrc) image.src = newSrc;
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function Trim(s) { 
  if (IsEmpty(s)) return "";
  while (s.substring(0, 1) == ' ' || s.substring(0, 1) == '\t' || s.substring(0, 1) == '\n' || s.substring(0, 1) == '\r') 
    s = s.substring(1, s.length);
  while (s.substring(s.length - 1, s.length) == ' ' || s.substring(s.length - 1, s.length) == '\t' || 
         s.substring(s.length - 1, s.length) == '\n' || s.substring(s.length - 1, s.length) == '\r') 
    s = s.substring(0, s.length - 1);
  return s;
} 

/*********************************************************************/
/**** USER INPUT FUNCTIONS *******************************************/
/*********************************************************************/
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function Blur(element) {
var required = 0, kind, returnValue = false;

  if (!element) return true;
  kind = "" + element.getAttribute("kind");
  if (kind != null) {
    if (element.className && element.className.match(/required/i)) required = 1;
    switch (kind) {
      case "alpha": returnValue = ValidateString(element, required, alphaChars, element.getAttribute("case")); break;
      case "amount": returnValue = ValidateNumber(element, required, digits + '.-', 1); break;
      case "credit": returnValue = ValidateCreditCard(element, required); break;
      case "date": returnValue = ValidateDate(element, required); break;
      case "decimal": returnValue = ValidateNumber(element, required, digits + '.-'); break;
      case "email": returnValue = ValidateEmail(element, required); break;
      case "monthyear": returnValue = ValidateMonthYear(element, required); break;
      case "number": returnValue = ValidateNumber(element, required, digits + '-'); break;
      case "password": returnValue = ValidateString(element, required, stringChars, "none"); break;
      case "phone": returnValue = ValidatePhone(element, required); break;
      case "ukphone": returnValue = ValidateUKPhone(element, required); break;
      case "ukmobile": returnValue = ValidateUKMobile(element, required); break;
      case "radio": returnValue = ValidateRadio(element, required); break;
      case "select": returnValue = ValidateSelection(element, required); break;
      case "ssn": returnValue = ValidateSsn(element, required); break;
      case "string": returnValue = ValidateString(element, required, stringChars, element.getAttribute("case")); break;
      case "text": returnValue = ValidateText(element, required); break;
      case "textlist": returnValue = ValidateText(element, required, 1); break;
      case "time": returnValue = ValidateTime(element, required); break;
      case "username": returnValue = ValidateString(element, required, upperCaseLetters + digits + '.-_', "none"); break;
      case "url": returnValue = ValidateUrl(element, required); break;
      case "zip": returnValue = ValidateString(element, required, digits + ' -', "upper"); break;
      case "postcode": returnValue = ValidatePostCode(element, required, lowerCaseLetters + upperCaseLetters + digits + whiteSpace, "upper"); break;
      case "height": returnValue = ValidateHeight(element, required, digits + "',m,.","none"); break;
      default: returnValue = true;
    }
  }
  eval("if (window." + element.name.replace(/:/g, "_") + "Blur) " + element.name.replace(/:/g, "_") + "Blur()");
  return returnValue;
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function BlurForm(form) {
  for (i = 0; i < form.elements.length; i++) {
    if (form.elements[i].type == "text" && form.elements[i].value)
      Blur (form.elements[i]);
  }
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
var oldSearchType1 = "", oldSearchType2 = "";
PopupCalendar("Initiate");
var oldSearchType1 = "", oldSearchType2 = "";
function ListSearch(searchForm, same) {
  var alphaSearchOperators = Array("=", "=", "Not = ", "<>", "Exact = ", "==", "Starts", "~", "Between", "BETWEEN")
  //var alphaSearchOperators = Array("=", "=")
  var numberSearchOperators = Array("=", "=", ">=", ">=", "<=", "<=", "Between", "BETWEEN")
  var searchBy = searchForm.searchBy;
  var searchOperator = searchForm.searchOperator;
  var searchOperatorValue = searchOperator.value ? searchOperator.value : "=";

  splitValue = searchBy.value.split(/\^/);
  if (splitValue.length == 2) {
	if (same) {
	  if ((splitValue[1] == "alpha" || splitValue[1] == "email") && (searchOperator.options.length < 2 || (searchOperator.options.length >= 2 && searchOperator.options[2].value != "=="))) {
	for (i = searchOperator.options.length - 1; i >= 0 ; i--) searchOperator.options[i] = null;
	for (i = 0; i < alphaSearchOperators.length; i += 2)
	  searchOperator.options[i / 2] = new Option(alphaSearchOperators[i], alphaSearchOperators[i + 1], false, false);
	  }
	  else if ((splitValue[1] != "alpha" || splitValue[1] != "email")  && (searchOperator.options.length < 2 || (searchOperator.options.length >= 2 && searchOperator.options[2].value != ">="))) {
	for (i = searchOperator.options.length - 1; i >= 0 ; i--) searchOperator.options[i] = null;
	for (i = 0; i < numberSearchOperators.length; i += 2)
	  searchOperator.options[i / 2] = new Option(numberSearchOperators[i], numberSearchOperators[i + 1], false, false);
	  }
	}
	searchOperator.value = searchOperatorValue;
	newInnerHTML2 = ""
	if (splitValue[1] == "date") {
	  newInnerHTML1 = "<input kind='date' id='dbSearchValue1' class='small requiredNone' name=dbSearchValue1 type=text size=10 maxlength=64 onblur='Blur(this);' accesskey='S'>&nbsp;<a href=\"javascript:PopupCalendar('dbSearchValue1', GetX('icondbSearchValue1'), GetY('icondbSearchValue1') + 17);\"><img id='icondbSearchValue1' src='image/icon_calendar.gif' align=absmiddle width=20 height=16 title='Click here to select a Date'></a>";
	  if (searchOperator.value == "BETWEEN") {
	newInnerHTML2 = "&nbsp;and&nbsp;<input kind='date' id='dbSearchValue2' class='small requiredNone' name=dbSearchValue2 type=text size=10 maxlength=64 onblur='Blur(this);' accesskey='S'>&nbsp;<a href=\"javascript:PopupCalendar('dbSearchValue2', GetX('icondbSearchValue2'), GetY('icondbSearchValue2') + 17);\"><img id='icondbSearchValue2' src='image/icon_calendar.gif' align=absmiddle width=20 height=16 title='Click here to select a Date'></a>";
	  }
	  else oldSearchType2 = "";
	}
	else{
	newInnerHTML1 = "<input kind='" + splitValue[1] + "' id='dbSearchValue1' class='small requiredNone' name=dbSearchValue1 type=text size=12 maxlength=32 onblur='Blur(this);' accesskey='S'>";
	if (searchOperator.value == "BETWEEN") {
	  newInnerHTML2 = "&nbsp;and&nbsp;<input kind='" + splitValue[1] + "' id='dbSearchValue2' class='small requiredNone' name=dbSearchValue2 type=text size=12 maxlength=32 onblur='Blur(this);' accesskey='S'>";
	}
	else oldSearchType2 = "";
	}
	if (splitValue[1] != oldSearchType1) {
	  document.getElementById("tdSearchValue1").innerHTML = newInnerHTML1;
	  oldSearchType1 = splitValue[1];
	}
	if (splitValue[1] != oldSearchType2) {
	  document.getElementById("tdSearchValue2").innerHTML = newInnerHTML2;
	  oldSearchType2 = (newInnerHTML2 != "") ? splitValue[1] : "";
	}
  }
}
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function ValidateCreditCard(inputField, required) {
  if (!inputField) return false;

  ValidateString(inputField, required, digits, "none");
  newValue = inputField.value;
  if (newValue == "") return (required ? false : true);

  ccTypeValue = IsMajorCreditCard(newValue);
  if (ccTypeValue == "") inputField.style.background = BadInput, returnValue = false;
  else inputField.style.background = White, returnValue = true;

  ccTypeLabelName = inputField.getAttribute("label");
  if (ccTypeLabelName) {
    if (ccTypeLabelName.match(/label/gi))
      document.getElementById(ccTypeLabelName).innerHTML = ccTypeValue;
    else 
      document.getElementByName(ccTypeLabelName).value = ccTypeValue;
  }

  if (newValue.length == 15)
    inputField.value = Reformat(newValue, "", 4, "-", 6, "-", 5);
  else if (newValue.length > 12)
    inputField.value = Reformat(newValue, "", 4, "-", 4, "-", 4, "-", 4);
  else if (newValue.length > 8)
    inputField.value = Reformat(newValue, "", 4, "-", 4, "-", 4);
  else if (newValue.length > 4)
    inputField.value = Reformat(newValue, "", 4, "-", 4);

  return returnValue;
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function ValidateDate(inputField, required) {
var daysInMonth = Array(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
var month, day, year;
var goodInput = false;

  if (!inputField) return false;

  inputField.value = StripCharsNotInBag(inputField.value, digits + " /-");
  if (!required && inputField.value == "") {
    inputField.style.background = White;
    return true;
  }

  inputText = inputField.value.replace(/[- ]/g, "/");
  splitInput = inputText.split("/");
  if (splitInput.length == 1 && (inputText.length == 8 || inputText.length == 6)) {
    inputText = inputText.substring(0, 2) + "/" + inputText.substring(2, 4) + "/" + inputText.substring(4, inputText.length);
    splitInput = inputText.split("/");
  }
  if(splitInput.length == 3) {
    month = parseInt(splitInput[1], 10);
    day = parseInt(splitInput[0], 10);
    year = parseInt(splitInput[2], 10);
    if (!isNaN(month) && !isNaN(day) && !isNaN(year)) {
      year = (year > 25 && year < 100) ? 1900 + year : (year > 0 && year <= 25) ? 2000 + year : year;
      goodInput = (month >= 1 && month <= 12) & (day >= 1 && day <= daysInMonth[month - 1]) &&
                  (month == 2 && day <= ((!(year % 100) && (year % 400)) || (year % 4)) ? 28 : 29);
    }
  }
  if (!goodInput) {
    inputField.style.background = BadInput;
    return false;
  }
  else {
    inputField.style.background = White;
    inputField.value = splitInput[0] + "/" + splitInput[1] + "/" + year;
    return true;
  }
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function ValidateEmail(inputField, required) {
  if (!inputField) return false;

  ValidateString(inputField, required, lowerCaseLetters + upperCaseLetters + digits + '.-_@', "none");
  newValue = inputField.value;
  if (newValue == "") return (required ? false : true);

  if (!IsEmail(newValue)) {
    inputField.style.background = BadInput;
    return false;
  }
  else {
    inputField.style.background = White;
    return true;
  }
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function ValidateForm(form) {
  if (form.elements.length == null) return false;
  //if (form.submitButton) form.submitButton.disabled = true;
  var invalidinputs = '' ;
  var curID = '';
  var FocusID;
  for (var i = 0, n = 0, validInputs = 0; i < form.elements.length; i++) 
  {
    if (form.elements[i].type.search(/text|password|textarea|select-one|select-multiple|radio/) > -1)
     {
        validInputs += Blur(form.elements[i]), n++; 
        if(!Blur(form.elements[i]))
        {
            curID = form.elements[i].id;
            if(document.getElementById(curID + 'Label') != null)
            {
                invalidinputs += document.getElementById(curID + 'Label').innerHTML  ;
                invalidinputs = invalidinputs.replace(':',', ');
             }
             getParent(curID, 'div')
        }
     }              
  }
  
  //alert(invalidinputs);
  //alert(validInputs)
  //alert(n)
  
  if (validInputs != n) 
  {
    invalidinputs = invalidinputs.substring(0,invalidinputs.length-2);
   // alert(FocusID)
   //alert(getParent(FocusID,'div'));
    
    //alert('All fields marked in yellow are invalid.\nPlease check and retry.\n\nAlso please make sure all the required fields are filled.');
    //if (form.submitButton) form.submitButton.disabled = false;
    alert( 'Below fields are invalid.\n'+ invalidinputs +'.\n\nPlease check and retry. Also please make sure all the required fields are filled.')
    return false;
  }
  
  if (window.AdditionalValidation && !AdditionalValidation(form)) {//alert(3);
    //if (form.submitButton) form.submitButton.disabled = false;
    return false;
  }
  //alert(2);
  return true;
}

function ValidateForm1(form) {
  if (form.elements.length == null) return false;
  //if (form.submitButton) form.submitButton.disabled = true;
  var invalidinputs = '' ;
  var curID = '';
  var FocusID;
  for (var i = 0, n = 0, validInputs = 0; i < form.elements.length; i++) 
  {
    if (form.elements[i].type.search(/text|password|textarea|select-one|select-multiple|radio/) > -1)
     {
        validInputs += Blur(form.elements[i]), n++; 
        if(!Blur(form.elements[i]))
        {
            curID = form.elements[i].id;
            if(curID == 'dbpassword')
            {
                invalidinputs = invalidinputs + 'Password, ';
            }
            else
            {
                if(document.getElementById(curID + 'Label') != null)
                {
                    invalidinputs += document.getElementById(curID + 'Label').innerHTML  ;
                    invalidinputs = invalidinputs + ', ';
                }
             }
        }
     }              
  }
  if (validInputs != n) 
  {
    invalidinputs = invalidinputs.substring(0,invalidinputs.length-2);
   // alert(FocusID)
   //alert(getParent(FocusID,'div'));
    
    //alert('All fields marked in yellow are invalid.\nPlease check and retry.\n\nAlso please make sure all the required fields are filled.');
    //if (form.submitButton) form.submitButton.disabled = false;
    alert( 'Below fields are invalid.\n'+ invalidinputs +'.\n\nPlease check and retry. Also please make sure all the required fields are filled.')
    return false;
  }
  
  if (window.AdditionalValidation && !AdditionalValidation(form)) {//alert(3);
    //if (form.submitButton) form.submitButton.disabled = false;
    return false;
  }
  //alert(2);
  return true;
}

function ValidateForm2(form) {
  if (form.elements.length == null) return false;
  //if (form.submitButton) form.submitButton.disabled = true;
  var invalidinputs = '' ;
  var curID = '';
  var FocusID;
  for (var i = 0, n = 0, validInputs = 0; i < form.elements.length; i++) 
  {
    if (form.elements[i].type.search(/text|password|textarea|select-one|select-multiple|radio/) > -1)
     {
        validInputs += Blur(form.elements[i]), n++; 
//        if(!Blur(form.elements[i]))
//        {
//          invalidinputs = invalidinputs + ', ';
//        }
     }              
  }
  if (validInputs != n) 
  {
    
    //invalidinputs = invalidinputs.substring(0,invalidinputs.length-2);
   // alert(FocusID)
   //alert(getParent(FocusID,'div'));
    
    alert('All fields marked in yellow are invalid.\nPlease check and retry.\n\nAlso please make sure all the required fields are filled.');
    //if (form.submitButton) form.submitButton.disabled = false;
    //alert( 'Below fields are invalid.\n'+ invalidinputs +'.\n\nPlease check and retry. Also please make sure all the required fields are filled.')
    return false;
  }
  
  if (window.AdditionalValidation && !AdditionalValidation(form)) {//alert(3);
    //if (form.submitButton) form.submitButton.disabled = false;
    return false;
  }
  //alert(2);
  return true;
}

function getParent(element, parent){
if(typeof element=="string"){element=document.getElementById(element);};
if(!element){return null;};
var elements=[];

if(typeof parent!="string"){/*no parent: gets all parents till #document*/
	while(element.parentNode)
	{
	    element=element.parentNode;
	    elements.unshift(element);
		if(element==parent){return elements;};
	}
}
else{/*string, presumes you want to locate the first parent node that is such TAG*/
parent=parent.toUpperCase();
	while(element.parentNode)
	{
	element=element.parentNode;
	if(!element){return null;};
	if(element.parentNode.id != '')
	{
	    //alert(element.parentNode.id);
	   if(!element.parentNode.id){return null;};
	    if(document.getElementById(element.parentNode.id + '1') != null)
	        {
	            document.getElementById(element.parentNode.id + '1').className = 'select'; 
	        }
	     else
	        {
	            document.getElementById(element.parentNode.id + '1').className = ''; 
	        } 
	}
	elements.unshift(element);
		if(element.nodeName && element.nodeName.toUpperCase()==parent){return elements;};
	}
};
//return elements;
//alert(elements)
/* keep this comment to reuse freely:
http://www.fullposter.com/?1 */}
//}
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function ValidateMonthYear(inputField, required) {
var goodInput = false;
var today = new Date();
var curMonth = today.getMonth() + 1;
var curYear  = today.getFullYear();

  if (!inputField) return false;

  inputField.value = StripCharsNotInBag(inputField.value, digits + "/-");
  if (!required && inputField.value == "") return true;

  inputText = inputField.value.replace(/-/g, "/");
  inputText = inputText.replace(/ /g, "/");
  splitInput = inputText.split("/");
  if (splitInput.length == 1) {
    if (inputText.length == 6) {
      inputText = inputText.substring(0, 2) + "/" + inputText.substring(2, 6);
      splitInput = inputText.split("/");
    }
    else if (inputText.length == 4) {
      inputText = inputText.substring(0, 2) + "/" + (2000 + parseInt(inputText.substring(2, 4), 10));
      splitInput = inputText.split("/");
    }
  }
  if(splitInput.length == 2) {
    month = parseInt(splitInput[0], 10);
    year = parseInt(splitInput[1], 10);
    year = (year >= 0 && year <= 99) ? 2000 + year : year;
    goodInput = !isNaN(month) && !isNaN(year) && ((year == curYear && month > curMonth && month <= 12) || (month > 0 && month <= 12 && year > curYear && year <= curYear + 25));
    if (!isNaN(month) && !isNaN(year) && month >= 1 && month <= 12)
      inputField.value = (month < 10 ? "0" + month : month) + "/" + year;
  }
  if (!goodInput) {
    inputField.style.background = BadInput;
    return false;
  }
  else {
    inputField.style.background = White;
    return true;
  }
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function ValidateNumber(inputField, required, validChars, currency) {
var minimum = '', maximum = '';
var isDecimal;

  if (!inputField) return false;
  if (!validChars) validChars = "";

  ValidateString(inputField, required, validChars, "none");
  newValue = inputField.value;
  if (newValue == "") return (required ? false : true);

  isDecimal = (validChars.search(/\./g) > 0);
  newValue = (newValue.substring(0, 1) == "-") ? "-" + StripCharsInBag(newValue.substring(1), "-") : StripCharsInBag(newValue, "-");

  if (isDecimal) {
    newValue = parseFloat(newValue);
    minimum = parseFloat(inputField.getAttribute('minimum'));
    maximum = parseFloat(inputField.getAttribute('maximum'));
    if (!isNaN(minimum) && newValue < minimum) newValue = minimum;
    if (!isNaN(maximum) && newValue > maximum) newValue = maximum;
  }
  else {
    newValue = parseInt(newValue, 10);
    minimum = parseInt(inputField.getAttribute('minimum'), 10);
    maximum = parseInt(inputField.getAttribute('maximum'), 10);
    if (!isNaN(minimum) && newValue < minimum) newValue = minimum;
    if (!isNaN(maximum) && newValue > maximum) newValue = maximum;
  }
  inputField.style.background = White;
  inputField.value = currency ? FormatCurrency(newValue) : newValue;
  return true;
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function ValidatePhone(inputField, required) {
  if (!inputField) return false;

  ValidateString(inputField, required, digits, "none");
  newValue = inputField.value;
  if (newValue == "") return (required ? false : true);

  if (newValue.length == 11 && newValue.substring(0, 1) == "1") newValue = newValue.substring(1);

  if (newValue.length > 5)
    inputField.value = (newValue.length <= 7) ? Reformat(newValue, "", 3, "-", 4) : Reformat(newValue, "", 3, "-", 3, "-", 4);

  if (newValue.length != 7 && newValue.length != 10) {
    inputField.style.background = BadInput;
    return false;
  }
  else {
    inputField.style.background = White;
    return true;
  }
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function ValidateUKPhone(inputField, required) {
  if (!inputField) return false;

  ValidateString(inputField, required, digits, "none");
  newValue = inputField.value;
  if (newValue == "") return (required ? false : true);

   if (newValue.length = 11)
    inputField.value =  Reformat(newValue, "", 3, "", 4, "", 4);

  if (newValue.length != 11) {
    inputField.style.background = BadInput;
    return false;
  }
  else {
    inputField.style.background = White;
    return true;
  }
}
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function ValidateUKMobile(inputField, required) {
  if (!inputField) return false;

  ValidateString(inputField, required, digits, "none");
  newValue = inputField.value;
  if (newValue == "") return (required ? false : true);

   //if (newValue.length = 11)
    //inputField.value =  Reformat(newValue, "", 5, "", 6);

  if (newValue.length > 15) {
    inputField.style.background = BadInput;
    return false;
  }
  else {
    inputField.style.background = White;
    return true;
  }
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////

function ValidateRadio(inputField, required) {
var i, radioArray;

  radioArray = (eval("inputField.form." + inputField.name));
  if (required) {
    for (i = 0; i < radioArray.length; i++)
      if (radioArray[i].checked) break;
    if (i == radioArray.length) {
      for (i = 0; i < radioArray.length; i++)
        radioArray[i].className = 'bgBadInput required';
      return false;
    }
    else {
      for (i = 0; i < radioArray.length; i++)
        radioArray[i].className = 'bgRequired';
      return true;
    }
  }
  else
    return true;
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function ValidateSelection(inputField, required) {
  if (!required) {
    inputField.style.background = White;
    return true;
  }
  else if (inputField.value == "" || inputField.value == "0") {
    inputField.style.background = BadInput;
    return false;
  }
  else {
    inputField.style.background = SelectRequiredColor;
    return true;
  }
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function ValidateSsn(inputField, required) {
  if (!inputField) return false;

  ValidateString(inputField, required, digits, "none");
  newValue = inputField.value;
  if (newValue == "") return (required ? false : true);

  inputField.value = Reformat(newValue, "", 3, "-", 2, "-", 4);
  if (newValue.length != 9) {
    inputField.style.background = BadInput;
    return false;
  }
  else {
    inputField.style.background = White;
    return true;
  }
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function ValidateString(inputField, required, validChars, textCase) {
  if (!inputField) return false;
  if (!validChars) validChars = "";

  newValue = Trim(inputField.value);
  inputField.value = (newValue) ? Caps(StripCharsNotInBag(NeatCharsInBag(newValue, whiteSpace), validChars), textCase) : "";
  
  if (required && inputField.value == "") {
    inputField.style.background = BadInput;
    return false;
  }
  else {
    inputField.style.background = White;
    return true;
  }
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function ValidateHeight(inputField, required, validChars, textCase) {
  if (!inputField) return false;
  if (!validChars) validChars = "";

  newValue = Trim(inputField.value);
  inputField.value = (newValue) ? Caps(StripCharsNotInBag(NeatCharsInBag(newValue, whiteSpace), validChars), textCase) : "";
  if (inputField.value.indexOf("m") != -1)
  {
    if(inputField.value.indexOf("m") != inputField.value.length-1)
    {
        inputField.style.background = BadInput;
        return false;
    }
  }
  
  if (inputField.value.indexOf("'") != -1)
  {
    if(inputField.value.indexOf("'") != inputField.value.length - 1)
    {
            if(inputField.value.indexOf("'") == 0)
            {
                inputField.style.background = BadInput;
                return false;
            }
            if (inputField.value.indexOf("''") != -1)
            {
                 if(inputField.value.indexOf("''") != inputField.value.length - 2)
                    {
                         inputField.style.background = BadInput;
                         return false;
                    }
            }
            else
            {
                inputField.style.background = BadInput;
                return false;
            }
     }     
  }
  if (required && inputField.value == "") {  
    inputField.style.background = BadInput;
    return false;
  }
  else {
    inputField.style.background = White;
    return true;
  }
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function ValidatePostCode(inputField, required, validChars, textCase) {
  if (!inputField) return false;
  if (!validChars) validChars = "";

  newValue = Trim(inputField.value);
  inputField.value = (newValue) ? Caps(StripCharsNotInBag(NeatCharsInBag(newValue, whiteSpace), validChars), textCase) : "";
  if (required && inputField.value == "") {
    inputField.style.background = BadInput;
    return false;
  }
  else {
    inputField.style.background = White;
    return true;
  }
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////

function ValidateText(inputField, required, list) {
  if (!inputField) return false;
  validChars = stringChars + "\n";

  newValue = Trim(inputField.value);
  if (list) newValue = NeatCharsInBag(NeatCharsInBag(newValue, " \t"), "\n\r", "\n");
  inputField.value = (newValue) ? StripCharsNotInBag(newValue, validChars) : "";
  if (required && inputField.value == "") {
    inputField.style.background = BadInput;
    return false;
  }
  else {
    inputField.style.background = White;
    return true;
  }
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function ValidateTime(inputField, required) {
var hours = -1, mins = 0, amPm;

  if (!inputField) return false;
  
   
  inputField.value = StripCharsNotInBag(inputField.value.toUpperCase(), digits + "APM-:");
  
  if (!required && inputField.value == "") return true;
  inputText = inputField.value;
   
  
  if (inputText.substr(inputText.length - 2, 2) == "AM" || inputText.substr(inputText.length - 2, 2) == "PM") {
    amPm = inputText.substr(inputText.length - 2, 2);
    inputText = inputText.substr(0, inputText.length - 2);
  }
  
  else if (inputText.substr(inputText.length - 1, 1) == "A" || inputText.substr(inputText.length - 1, 1) == "P") {
    amPm = inputText.substr(inputText.length - 1, 1) + "M";
    inputText = inputText.substr(0, inputText.length - 1);
  }
 
  inputText = inputText.replace(/[- ]/g, ":");
  splitInput = inputText.split(":");
  if (splitInput.length == 2) {
    hours = parseInt(splitInput[0], 10);
    mins = parseInt(splitInput[1], 10);
  }
  else {
    if (inputText.length <= 2) hours = parseInt(inputText, 10);
    else if (inputText.length <= 4) {
      hours = parseInt(inputText.substr(0, inputText.length - 2), 10);
      mins = parseInt(inputText.substr(inputText.length - 2, 2), 10);
    }
  }
 
  if (hours > 0 && hours < 24 && mins < 60) {
    if (hours < 12) inputText = hours + ":" + (mins < 10 ? "0" + mins : mins);
    else inputText = (hours) + ":" + (mins < 10 ? "0" + mins : mins);

    inputField.style.background = White;
    inputField.value = inputText;
    return true;
  }
  else {
    inputField.style.background = BadInput;
    return false;
  }
  alert("6" + inputField.value);
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function ValidateUrl(inputField, required) {
  if (!inputField) return false;

  newValue = inputField.value;
  if (newValue.substr(0, 7) == "http://") newValue = newValue.substr(7);
  else if (newValue.substr(0, 6) == "http:/") newValue = newValue.substr(6);
  else if (newValue.substr(0, 5) == "http:") newValue = newValue.substr(5);
  inputField.value = newValue;

  ValidateString(inputField, required, lowerCaseLetters + upperCaseLetters + digits + '.,;-_~/#^?&=+|:', "none");
  newValue = inputField.value;
  if (newValue == "") return (required ? false : true);

  if (!IsUrl(newValue)) {
    inputField.style.background = BadInput;
    return false;
  }
  else {
    inputField.style.background = White;
    return true;
  }
}

/*********************************************************************/
/**** ADDITIONAL FUNCTIONS *******************************************/
/*********************************************************************/
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
var ajaxHttp;
function Ajax(script, seconds) {
  if (!window.AjaxProcess) return;
  try { ajaxHttp = new ActiveXObject("Msxml2.XMLHTTP"); }
  catch(e) {
    try{ ajaxHttp = new ActiveXObject("Microsoft.XMLHTTP");}
    catch(oc){ ajaxHttp = null;}
  }
  if(!ajaxHttp && typeof XMLHttpRequest != "undefined") ajaxHttp = new XMLHttpRequest();

  if(ajaxHttp != null) {
    ajaxHttp.onreadystatechange = AjaxResponse;
    ajaxHttp.open("GET", script + (script.indexOf("?") > 0 ? "&" : "?") + "ms=" + new Date().getTime(), true);
    ajaxHttp.send(null);
  }

  if (seconds && parseInt(seconds, 10) > 0) setTimeout("Ajax()", parseInt(seconds, 10) * 1000)
}

function AjaxResponse() {
  if (ajaxHttp && (ajaxHttp.readyState == 4 && ajaxHttp.responseText) && (ajaxHttp.status > 100 && ajaxHttp.status < 500)) eval(ajaxHttp.responseText);
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function CalculateChildID() {
  var url, subIndex;
  var returnInt;
  
  url = location.host + location.pathname;
  subIndex = url.indexOf('/');
  if (url.indexOf('/', subIndex + 1) > -1) subIndex = url.indexOf('/', subIndex + 1);
  url = url.substring(0, subIndex);
  for (i = 0, returnInt = 0; i < url.length; i++ ) returnInt += url.charCodeAt(i);
  return '' + returnInt + url.charCodeAt(url.length - 2) + url.charCodeAt(url.length - 1);
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function ChildWindow(url, width, height, scrollbars, resizable) {
  var childWindow;

  if (width < 200) width = 200;
  if (height < 180) height = 180;
  wLeft = parseInt(screen.width / 2 - width / 2, 10);
  wTop = parseInt(screen.height / 2 - height / 2, 10);
  scrollbars = (!scrollbars || scrollbars != '1') ? 0 : 1;
  resizable = (!resizable || resizable != '1') ? 0 : 1;
  eval("childWindow = childWindowLibraryDM_" + ChildID);
  if (childWindow && childWindow.open) childWindow.close();
  eval("childWindowLibraryDM_" + ChildID + " = window.open(url, 'childWindowLibraryDM_" + ChildID + "', 'location=0,toolbar=0,menubar=0,resizable=" + resizable + ",status=0,scrollbars=" + scrollbars + ",width=" + width + ",height=" + height + ",left=" + wLeft + ",top=" + wTop + "')");
  eval("childWindowLibraryDM_" + ChildID + ".focus()");
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function CloseChildWindow() {
var childWindowObject;

  eval("childWindowObject = childWindowLibraryDM_" + ChildID);
  if (childWindowObject && childWindowObject.open) childWindowObject.close();
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function CloseHelpBar() {
  if (document.getElementById('helpBar')) document.getElementById('helpBar').style.visibility = 'hidden';
  location.href = location.href;
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function DateAdd(interval, number, inputDate){
	if(!IsDate(inputDate)) return "";
	if(isNaN(number)) return "";

	number = new Number(number);
	var dt = new Date(inputDate);
	
  switch(interval.toLowerCase()) {
		case "yyyy":
			dt.setFullYear(dt.getFullYear() + number);
			break;
		case "q":
			dt.setMonth(dt.getMonth() + (number * 3));
			break;
		case "m":
			dt.setMonth(dt.getMonth() + number);
			break;
		case "y":
		case "d":
		case "w":
			dt.setDate(dt.getDate() + number);
			break;
		case "ww":
			dt.setDate(dt.getDate() + (number * 7));
			break;
		case "h":
			dt.setHours(dt.getHours() + number);
			break;
		case "n":
			dt.setMinutes(dt.getMinutes() + number);
			break;
		case "s":
			dt.setSeconds(dt.getSeconds() + number);
			break;
		case "ms":
			dt.setMilliseconds(dt.getMilliseconds() + number);
			break;
		default:
			return "";
  }
	return dt;
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function DateDiff(interval, inputDate1, inputDate2, firstDayOfWeek, firstWeekOfYear){
	if(!IsDate(inputDate1)) return -1;
	if(!IsDate(inputDate2)) return -1;
	var dt1 = new Date(inputDate1);
	var dt2 = new Date(inputDate2);

	var iDiffMS = dt2.valueOf() - dt1.valueOf();
	var dtDiff = new Date(iDiffMS);

	var nYears  = dt2.getUTCFullYear() - dt1.getUTCFullYear();
	var nMonths = dt2.getUTCMonth() - dt1.getUTCMonth() + (nYears != 0 ? nYears * 12 : 0);
	var nQuarters = parseInt(nMonths / 3);
	
	var nMilliseconds = iDiffMS;
	var nSeconds = parseInt(iDiffMS / 1000);
	var nMinutes = parseInt(nSeconds / 60);
	var nHours = parseInt(nMinutes / 60);
	var nDays  = parseInt(nHours / 24);
	var nWeeks = parseInt(nDays / 7);

	var iDiff = 0;		
	switch(interval.toLowerCase()){
		case "yyyy": return nYears;
		case "q": return nQuarters;
		case "m": return nMonths;
		case "y": 
		case "d": return nDays;
		case "w": return nDays;
		case "ww":return nWeeks;
		case "h": return nHours;
		case "n": return nMinutes;
		case "s": return nSeconds;
		case "ms":return nMilliseconds;
		default: return -1;
	}
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function LeadingZero (x) { return (x < 0 || x > 9 ? "" : "0") + x; }

function FormatDateTime (inputDate, format) {
  var formatTokens = new Array('yyyy', 'yy', 'y', 'hh', 'h', 'HH', 'H', 'mm', 'm', 'ss', 's', 'tt', 't', 'TT', 'T', 'XXXX', 'XXX', 'XX', 'X', 'zzzz', 'zzz', 'zz', 'z');

  if(!IsDate(inputDate)) return "";
  var dt = new Date(inputDate);

	var y = dt.getFullYear();
  var M = dt.getMonth() + 1;
	var d = dt.getDate();
	var w = dt.getDay();
	var H = dt.getHours();
	var m = dt.getMinutes();
	var s = dt.getSeconds();
  var token;

	var value = new Object();
	if (y.length < 4) y = "" + (y - 0 + 1900);

  value["yyyy"] = y;
	value["yy"] = LeadingZero(y % 100);
	value["y"] = y % 100;
	value["h"] = (H == 0 ? 12 : (H > 12 ? H - 12 : H));
	value["hh"] = LeadingZero(value["h"]);
	value["HH"] = LeadingZero(H);
	value["H"] = H;
	value["mm"] = LeadingZero(m);
	value["m"] = m;
	value["ss"] = LeadingZero(s);
	value["s"] = s;
	value["t"] = (H > 11 ? "P" : "A");
  value["tt"] = value["t"] + "M";
  value["TT"] = value["tt"].toLowerCase();
  value["T"] = value["t"].toLowerCase();
	value["XXXX"] = monthNames[M - 1];
	value["XXX"] = monthNames[M - 1].substring(0, 3);
	value["XX"] = LeadingZero(M);
	value["X"] = M;
	value["zzzz"] = dayNames[w];
	value["zzz"] = dayNames[w].substring(0, 3);
	value["zz"] = LeadingZero(d);
	value["z"] = d;
 
  format = format.replace(/M/g, "X");
  format = format.replace(/d/g, "z");
	for (token in formatTokens) format = format.replace(new RegExp(formatTokens[token], 'g'), value[formatTokens[token]]);
  
  return format;
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function Property(objectName, propertyName, propertyValue, notString) {
var object;

  if (IsEmpty(objectName) || IsEmpty(propertyName)) return null;

  object = document.getElementById(objectName);
  if (!object) return null;
  if (propertyValue != null) eval("object." + propertyName + (notString ? " = " + propertyValue : " = \"" + propertyValue + "\""));
  
  return eval("object." + propertyName);
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function ShowHelp(element, focus) {
var kind, helpObject, finalHelp;
var elementHelp = "", elementDefaultHelp = "", requiredHelp = "";

  helpObject = document.getElementById('dmHelpPane');
  if (!helpObject) return false;

  if (element) {
    elementHelp = element.getAttribute("help");
    if (elementHelp == null) elementHelp = "";
    if (element.className && element.className.match(/required/i)) requiredHelp = "<p class='red bold bottomSpace'>Required Field.<br></p>";
    kind = "" + element.getAttribute("kind");
    switch (kind) {
      case "alpha": elementDefaultHelp = ""; break;
      case "amount": elementDefaultHelp = ""; break;
      case "credit": elementDefaultHelp = ""; break;
      case "date": elementDefaultHelp = ""; break;
      case "decimal": elementDefaultHelp = ""; break;
      case "email": elementDefaultHelp = ""; break;
      case "monthyear": elementDefaultHelp = ""; break;
      case "number": elementDefaultHelp = ""; break;
      case "password": elementDefaultHelp = ""; break;
      case "phone": elementDefaultHelp = ""; break;
      case "radio": elementDefaultHelp = ""; break;
      case "select": elementDefaultHelp = ""; break;
      case "ssn": elementDefaultHelp = ""; break;
      case "string": elementDefaultHelp = ""; break;
      case "text": elementDefaultHelp = ""; break;
      case "textlist": elementDefaultHelp = ""; break;
      case "time": elementDefaultHelp = ""; break;
      case "url": elementDefaultHelp = ""; break;
      case "username": elementDefaultHelp = ""; break;
      case "zip": elementDefaultHelp = ""; break;
      default: break;
    }
  }
  elementDefaultHelp = "";
  if (!focus) finalHelp = defaultHelp;
  else {
    if (elementHelp) finalHelp = requiredHelp + elementHelp + (elementDefaultHelp ? '<br><br>' + elementDefaultHelp : "");
    else {
      if (elementDefaultHelp) finalHelp = requiredHelp + elementDefaultHelp;
      else finalHelp = requiredHelp;
    }
  }
  finalHelp = finalHelp.replace(/<BR>/g, "<p class='topSpace'></p>");
  finalHelp = finalHelp.replace(/<HR>/g, "<p class='borderTop borderDark bottomSpace'><img src='LibraryDM/empty.gif' width=100% height=1></p>");
  helpObject.innerHTML = finalHelp;
}


/*********************************************************************/
/**** CALENDAR FUNCTIONS *********************************************/
/*********************************************************************/
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
var closePopupCalendar;

function PopupCalendar(formElementName, x, y, parameter, cMonth, cYear) {
var showType, tagName;
//alert(x);
//alert(y);
  if (formElementName == "Initiate") {
    if (IsIE) document.write ("<iframe id='calendarBackLayer' frameborder=0 scrolling=no style='visibility:hidden; position:absolute; z-index:100'></iframe>");
    document.write ("<div id='calendarLayer' kind='calendarLayer' style='visiblity:hidden; position:absolute; top:0px; left:0px; z-index=101;'></div>");
    return;
  }
  if (!document.getElementById('calendarLayer')) return;
  if (y < 0) y = 0;
  showType = (parameter == "noDay") ? "Year" : "Month";
  tagName = document.getElementById(formElementName).tagName;
  if (tagName == "SELECT") {
    prefix = formElementName.substring(0, formElementName.search(/Month/g));
    if (prefix != "") {
      cMonth = document.getElementById(prefix + "Month").value;
      cYear = document.getElementById(prefix + "Year").value;
      PopupCalendarShow(formElementName, showType, cMonth, cYear, x, y, parameter);
    }
  }
  else if (tagName == "INPUT") {
    inputField = document.getElementById(formElementName);
    ValidateDate(inputField);
    if (inputField && !IsEmpty(inputField.value) && inputField.style.background != BadInput) {
      splitInput = inputField.value.split("/");
      PopupCalendarShow(formElementName, showType, splitInput[1], splitInput[2], x, y, parameter);
    }
    else PopupCalendarShow(formElementName, showType, (new Date().getMonth()) + 1, new Date().getFullYear(), x, y, parameter);
  }
  else if (tagName == "A") {
    if (cMonth && cYear)
      PopupCalendarShow(formElementName, showType, cMonth, cYear, x, y, parameter);
    else
      PopupCalendarShow(formElementName, showType, (new Date().getMonth()) + 1, new Date().getFullYear(), x, y, parameter);
  }
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function PopupCalendarHide() {
  cObj = document.getElementById('calendarLayer');
  cbObj = document.getElementById('calendarBackLayer');
  if (cObj && cObj.style.visibility == "visible") {
    if (!closePopupCalendar) { closePopupCalendar = true; return; }
    cObj.style.left = 0;
    cObj.style.top = 0;
    cObj.style.visibility = 'hidden';
    if (cbObj) {
      cbObj.style.left = 0;
      cbObj.style.top = 0;
      cbObj.style.visibility = 'hidden';
    }
    cObj.innerHTML = "";
    document.onmousedown = null;
  }
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function PopupCalendarReturn(formElementName, cMonth, cDay, cYear) {
var tagName;

  tagName = document.getElementById(formElementName).tagName;
  if (tagName == "SELECT") {
    prefix = formElementName.substring(0, formElementName.search(/Month/g));
    if (prefix != "") {
      if (document.getElementById(prefix + "Month")) document.getElementById(prefix + "Month").value = cMonth;
      if (document.getElementById(prefix + "Day")) document.getElementById(prefix + "Day").value = cDay;
      if (document.getElementById(prefix + "Year")) document.getElementById(prefix + "Year").value = cYear;
    }
  }
  else if (tagName == "INPUT") {
    inputField = document.getElementById(formElementName);
    if (inputField) inputField.value = cDay + "/" + cMonth  + "/" + cYear;
    inputField.focus();
    Blur(inputField);
  }
  else if (tagName == "A") {
    anchorElement = document.getElementById(formElementName);
    if (anchorElement && anchorElement.getAttribute('url')) {
      url = anchorElement.getAttribute('url');
      document.location.href = url + ((url.search(/\?/g) > -1) ? "&" : "?") + "date=" + cDay  + "/" + cMonth + "/" + cYear;
    }
  }
  closePopupCalendar = true;
  PopupCalendarHide();
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function PopupCalendarShow(formElementName, type, cMonth, cYear, x, y, parameter) {
  var daysOfMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
  var monthName = ["January","February","March","April","May","June","July","August","September","October","November","December"];
  var weekDay = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
  var minYear = 1920;
  var maxYear = 2125;

  cMonth = parseInt(cMonth, 10) - 1;
  cYear = parseInt(cYear);
  if (cYear == "") cYear = minYear;
  if (cYear < minYear || cYear > maxYear) return;
  if (type != "Year" && type != "Years") type = "Month";
  parameterStr = (parameter) ? ", '" + parameter + "'" : "";

  function GetHTML(cMonth, cYear, type) {
    var today = new Date();

    if (type == "Month") {
      var vDate = new Date();
      vDate.setDate(1);
      vDate.setMonth(cMonth);
      vDate.setFullYear(cYear);
      var vFirstDay = vDate.getDay();
      var vDay = 1;
      var vLastDay = LastDay(cMonth, cYear);

      if (cMonth == 0) var pLastDay = 31;
      else var pLastDay = LastDay(cMonth - 1, cYear);

      var vOnLastDay = 0;
      var pDays = pLastDay - vFirstDay;
      var vCode = "";

      for (i = 0; i < vFirstDay; i++, pDays++) vCode += (vCode ? "|" : "") + pDays;
      for (i = vFirstDay; i < 7; i++, vDay++) vCode += (vCode ? "|" : "") + vDay;
      vCode += "\n";
      for (i = 2; i < 7; i++) {
        for (j = 0; j < 7; j++) {
          vCode += (j != 0 ? "|" : "") + vDay;
          vDay ++;
          if (vDay > vLastDay) { vOnLastDay = 1; break; }
        }
        if (j == 7) vCode = vCode + "\n";
        if (vOnLastDay == 1) break;
      }
      for (i = 1; i < (7 - j); i++) vCode += "|" + i;

      pMonth = (cMonth + 11) % 12;
      pYear = (pMonth == 11) ? cYear - 1 : cYear;
      nMonth = (cMonth + 1) % 12;
      nYear = (nMonth == 0) ? (cYear + 1) : cYear;
    }
    else if (type == "Years") {
      cYear = minYear + parseInt((cYear - minYear) / 9) * 9;
    }

    code  = "<table class='border borderDark bgWhite' width=172 onMouseDown='javascript:closePopupCalendar=false;' style='position:absolute;z-index:1000;'>";
    code += "<tr>";
    code += "  <td align=center>";
    code += "    <table align=center width=152>";
    code += "    <tr height=25>";
    code += "      <td class=bold width=136>";
    if (type == "Month") {
      code += "        <a href=\"javascript:PopupCalendarShow('" + formElementName + "', 'Month', " + (pMonth + 1) + ", " + pYear + ", " + x + ", " + y + parameterStr + ");\" title='Previous Month'><img src='image/arrows_left.gif'></a>&nbsp;&nbsp;&nbsp;";
      code += "<a class=under href=\"javascript:PopupCalendarShow('" + formElementName + "', 'Year', 0, " + cYear + ", " + x + ", " + y + parameterStr + ");\" title='Show Full Year'>" + monthName[cMonth].substr(0, 3) + " " + cYear + "</a>&nbsp;&nbsp;&nbsp;";
      code += "<a href=\"javascript:PopupCalendarShow('" + formElementName + "', 'Month', " + (nMonth + 1) + ", " + nYear + ", " + x + ", " + y + parameterStr + ");\" title='Next Month'><img src='image/arrows_right.gif'></a>";
    }
    else if (type == "Year") {
      code += "        <a href=\"javascript:PopupCalendarShow('" + formElementName + "', 'Year', 0, " + (cYear - 1) + ", " + x + ", " + y + parameterStr + ");\" title='Previous Year'><img src='image/arrows_left.gif'></a>&nbsp;&nbsp;&nbsp;";
      code += "<a class=under href=\"javascript:PopupCalendarShow('" + formElementName + "', 'Years', 0, " + cYear + ", " + x + ", " + y + parameterStr + ");\" title='Show All Years'>Year " + cYear + "</a>&nbsp;&nbsp;&nbsp;";
      code += "<a href=\"javascript:PopupCalendarShow('" + formElementName + "', 'Year', 0, " + (cYear + 1) + ", " + x + ", " + y + parameterStr + ");\" title='Next Year');\"><img src='image/arrows_right.gif'></a>";
    }
    else if (type == "Years") {
      code += "        <a href=\"javascript:PopupCalendarShow('" + formElementName + "', 'Years', 0, " + (cYear - 9) + ", " + x + ", " + y + parameterStr + ");\" title='Previous 9 years'><img src='image/arrows_left.gif'></a>&nbsp;&nbsp;";
      code += cYear + " - " + (cYear + 8) + "&nbsp;&nbsp;";
      code += "<a href=\"javascript:PopupCalendarShow('" + formElementName + "', 'Years', 0, " + (cYear + 9) + ", " + x + ", " + y + parameterStr + ");\" title='Next 9 years'><img src='image/arrows_right.gif'></a>";
    }
    code += "      </td>";
    code += "      <td align=right><a href='javascript:closePopupCalendar=true; PopupCalendarHide();' title='Click here to close'><img src='image/icon_close.gif' width=14 height=13></a><img src='image/empty.gif' width=1 height=1></td>";
    code += "    </tr>";
    code += "    <tr>";
    code += "      <td colspan=3 align=center class=box>";
    code += "        <table class='border borderMedium bgWhite' width=152>";
                      if (type == "Month") {
                        code += "        <tr>";
                        code += "          <td class=pad width=15% align=center>S</td>";
                        code += "          <td class=pad width=14% align=center>M</td>";
                        code += "          <td class=pad width=14% align=center>T</td>";
                        code += "          <td class=pad width=14% align=center>W</td>";
                        code += "          <td class=pad width=14% align=center>T</td>";
                        code += "          <td class=pad width=14% align=center>F</td>";
                        code += "          <td class=pad width=15% align=center>S</td>";
                        code += "        </tr>";
                        code += "        <tr height=1>";
                        code += "          <td style='padding:0px 2px 0px 2px;' colspan=7><img src='image/dot_medium.gif' width=100% height=1></td>";
                        code += "        </tr>";
                        weeks = vCode.split("\n");
                        for (i = 0; i < weeks.length; i++) {
                          days = weeks[i].split("|");
                          code += "        <tr>";
                          for (j = 0; j < days.length; j++) {
                            var iDay = parseInt(days[j], 10)
                            if ((i == 0 && iDay > 7) || (i == weeks.length - 1 && iDay < 7)) {
                              code += "          <td class='border borderLight pad medium small' align=center>" + iDay + "</td>";
                            }
                            else {
                              if (cMonth == today.getMonth() && iDay == today.getDate() && cYear == today.getFullYear())
                                code += "          <td class='border borderLight small' align=center bgcolor=#fffae0>";
                              else
                                code += "          <td class='border borderLight pad small' align=center>";
                              code += "            <a href=\"javascript:PopupCalendarReturn('" + formElementName + "', " + (cMonth + 1) + ", " + iDay + ", " + cYear + ");\">" + iDay + "</a>";
                              code += "          </td>";
                            }
                          }
                          code += "        </tr>";
                        }
                      }
                      else if (type == "Year") {
                        for (i = 0; i < 4; i++) {
                          code += "        <tr>";
                          for (j = 0; j < 3; j++) {
                            code += "          <td class='pad small border borderLight' align=center height=27>";
                            if (parameter == "noDay")
                              code += "            <a href=\"javascript:PopupCalendarReturn('" + formElementName + "', " + (i * 3 + j + 1) + ", 1, " + cYear + ");\">" + monthName[i * 3 + j].substr(0, 3) + "</a>"
                            else
                              code += "            <a href=\"javascript:PopupCalendarShow('" + formElementName + "', 'Month', " + (i * 3 + j + 1) + ", " + cYear + ", " + x + ", " + y + parameterStr + ");\">" + monthName[i * 3 + j].substr(0, 3) + "</a>";
                            code += "          </td>";
                          }
                          code += "        </tr>";
                        }
                      }
                      else if (type == "Years") {
                        for (i = 0; i < 3; i++) {
                          code += "        <tr>";
                          for (j = 0; j < 3; j++) {
                            if ((cYear + i * 3 + j) > maxYear) {
                              code += "          <td class='pad medium small' align=center>" + (cYear + i * 3 + j) + "</td>";
                            }
                            else {
                              code += "          <td class='pad small border borderLight' align=center height=36>";
                              code += "            <a href=\"javascript:PopupCalendarShow('" + formElementName + "', 'Year', 0, " + (cYear + i * 3 + j) + ", " + x + ", " + y + parameterStr + ");\">" + (cYear + i * 3 + j) + "</a>";
                              code += "          </td>";
                            }
                          }
                          code += "        </tr>";
                        }
                      }
    code += "        </table>";
    code += "      </td>";
    code += "    </tr>";
    code += "    <tr><td class=pad colspan=3 align=center>Today:<a class=under href=\"javascript:PopupCalendarReturn('" + formElementName + "', " + (today.getMonth() + 1) + ", " + today.getDate() + ", " + today.getFullYear() + ");\">" + weekDay[today.getDay()] + ", " + monthName[today.getMonth()].substr(0, 3) + " " + today.getDate() + "</a></td></tr>";
    code += "    </table>";
    code += "    <img src='image/empty.gif' width=1 height=2><br>";
    code += "  </td>";
    code += "</tr>";
    code += "</table>";
    return code;
  }

  function LastDay(cMonth, cYear) {
    if (cMonth == 1 && !(cYear % 4) && ((cYear % 100) || !(cYear % 400))) return daysOfMonth[cMonth] + 1;
    return daysOfMonth[cMonth];
  }

  var code = GetHTML (cMonth, cYear, type);
  var cObj = document.getElementById('calendarLayer');
  var cbObj = document.getElementById('calendarBackLayer');
  cObj.style.left = x;
  cObj.style.top = y;
  cObj.style.width = 172;
  cObj.style.visibility = 'visible';
  if (cbObj) {
    cbObj.style.left = x;
    cbObj.style.top = y;
    cbObj.style.width = 172;
    cbObj.style.height = 74 + (weeks.length * 21);
    cbObj.style.visibility = 'visible';
  }

  cObj.innerHTML = code;
  document.onmousedown = PopupCalendarHide;
  closePopupCalendar = true;
}

//////////////////// 
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function GetX(objName) {
var object = typeof objName == "object" ? objName : document.getElementById(objName);

	for (var sumLeft = 0; object != document.body; sumLeft += object.offsetLeft, object = object.offsetParent);
	return sumLeft;
}

///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
function GetY(objName) {
var object = typeof objName == "object" ? objName : document.getElementById(objName);
  for (var sumTop = 0; object != document.body; sumTop += object.offsetTop, object = object.offsetParent);
	return sumTop;
}

//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
 function allownumbers(e)
   {
    var key = window.event ? e.keyCode : e.which;
    var keychar = String.fromCharCode(key);
    var reg = new RegExp("[0-9?.]")
    var reg1 = new RegExp("[0-9]")
   
    if (key == 8)
    {
     keychar = String.fromCharCode(key);
    }
    if (key == 13)
    {
     key=8;
     keychar = String.fromCharCode(key);     
    }
    if( this.value.indexOf(".") == -1)
    {
    return reg.test(keychar);
    }
    else
    {
    return reg1.test(keychar);
    }
   } 
   
function CheckCheckAll(fmobj) {
  for (var i=0;i<fmobj.elements.length;i++) {
    var e = fmobj.elements[i];
    if ( (e.name != 'allbox') && (e.type=='checkbox') && (!e.disabled) ) {
      e.checked = fmobj.allbox.checked;
    }
  }
}



//////////////////////////////////////////////////////////////////////////////////
//Ajax core functions/
//////////////////////////////////////////////////////////////////////////////////

function InvokeAjax(url) 
{
	//alert(url);
	http = GetHttpObject();
	if(http != null)
	{ 
		http.onreadystatechange = Process;
		http.open("GET", url, true);
		http.send(null);
	}
}
	

////////**************************************************//////////
var http;
function GetHttpObject() 
{
	var localHttp;
	try { localHttp = new ActiveXObject("Msxml2.XMLHTTP"); }
	catch(e) {
		try{ localHttp = new ActiveXObject("Microsoft.XMLHTTP");}
		catch(oc){ localHttp = null;}
		}
		if(!localHttp && typeof XMLHttpRequest != "undefined") localHttp = new XMLHttpRequest();
		return localHttp;
}

function SendQuery(str, status) 
{
	http = GetHttpObject();
	if(http != null){ 
		http.onreadystatechange = Process;
		//alert("listOrdersInGrid.aspx?type="+ status +"&IDs=" + str + "&ms=" + new Date().getTime())
		http.open("GET", str + "&ms=" + new Date().getTime(), true);
		http.send(null);
	}
}

function Process() 
{ 
	if (http && (http.readyState == 4 && http.responseText) && (http.status > 100 && http.status < 500)){
	    //alert(http.responseText);
		eval(http.responseText);
	}	
}

function LoadPage (url, q) 
{
    //alert("load" + url);
    parent.document.getElementById('loadingDiv').style.visibility= "visible";
    if (url.indexOf("javascript:") == 0) eval(url.substring(11).replace(/#/g, "'"));
    parent.document.getElementById('frameContent').src = url + (q ? '?' + q + '&' : '?') + 'ms=' + new Date().getTime();
 }
 
 function LoadPage1 (url, q) 
{
    //alert("load" + url);
    parent.document.getElementById('loadingDiv').style.visibility= "visible";
    if (url.indexOf("javascript:") == 0) eval(url.substring(11).replace(/#/g, "'"));
    parent.document.getElementById('frameContent').src = url;
 }

 function LoadUserPage (url, q) 
{
    //alert("load" + url);
    parent.document.getElementById('loadingDiv').style.visibility= "visible";
    if (url.indexOf("javascript:") == 0) eval(url.substring(11).replace(/#/g, "'"));
    parent.document.getElementById('frameContent').src = url + (q ? '?' + q + '&' : '?') + 'ms=' + new Date().getTime();
 }
 
 
 /* ----------- Reminder Functions ----------------------*/  
 
 function CollectSelection(form, Typerow, Numbersub)
{
  if (form == null) return false;
    var retStr
    var isFirst = true
    for (var i = 0, n = 0, validInputs = 0; i < form.elements.length; i++){
      if (form.elements[i].name.substring(0, Numbersub) == Typerow ){
              if(form.elements[i].checked){
			    if (isFirst){
				    retStr = form.elements[i].name.substring(Numbersub);
					isFirst = false;					
				}
			    else{
				    retStr = retStr + "," + form.elements[i].name.substring(Numbersub);				    
			    }
		    }
	    }
    }
 
     if (!retStr){
       return false;      
    }    
    return retStr;
 }
 
 function HandleSelectAll(form)
{
 //alert(document.AdminForm1.dbSelect1Flag.value);
    if (form == null) return false;
  if (AdminForm1.dbSelect1Flag.value == "false"){ chkVal = true; AdminForm1.dbSelect1Flag.value = "true";}
  else {chkVal = false; AdminForm1.dbSelect1Flag.value = "false";}

  for (var i = 0, n = 0, validInputs = 0; i < form.elements.length; i++) 
	if (form.elements[i].name.substring(0, 5) == "Event" || form.elements[i].name.substring(0, 4) == "Task") form.elements[i].checked = chkVal
}

var EventData = "";
var taskData = "";
var userid;
function callAjaxReminders(str)
{
    var isvalid = IsValidReminders(str);
    if (isvalid)
    {
        var ajaxUrl="listReminders.aspx?UserId=" + userid + "&Taskids=" + taskData + "&EventIds=" + EventData + "";
        if(str == "snooze")
        {
            ajaxUrl = ajaxUrl + "&Type=Snooze" + "&Time=" + Form1.dbSnoozeTime.value;
        }
        if(str == "dismiss")
        { 
            ajaxUrl = ajaxUrl + "&Type=Dismiss" ;
        }
        if(str == "dismissAll")
        {
            ajaxUrl = ajaxUrl + "&Type=DismissAll";
        }
        
       // InvokeAjax(ajaxUrl);
    }
    else
    {
        return false;
    }
}
function IsValidReminders(type)
{
    if(type == "snooze")
    {
        if (Form1.dbSnoozeTime.value == "") {alert("Snooze time cannot be empty"); return false;}
    }
    GetIDs();
    if(EventData == false && taskData == false)
   {
        alert("You need to select atleast one to proceed further.");
        return false;
   }
    userid=AdminForm1.Userid.value;
    return true;
}
function GetIDs()
{
EventData = CollectSelection(AdminForm1, "Event", 5);
taskData = CollectSelection(AdminForm1, "Task" , 4);
//alert("eve: " + EventData + "taskdata: " + taskData);
}

// user written functions//


function CollectSelection(form)
{
    if (form == null) return false;
    var retStr
    var isFirst = true
   //alert(form.elements.length);
    for (var i = 0, n = 0, validInputs = 0; i < form.elements.length; i++){
	    if (form.elements[i].id.substring(0, 6) == "dbRow_"){
		    if(form.elements[i].checked){
			    if (isFirst){
				    retStr = form.elements[i].id.substring(6);
					isFirst = false;
					//alert(retStr);
				}
			    else{
				    retStr = retStr + "," + form.elements[i].id.substring(6);
				    //alert("els" + retStr);
			    }
		    }
	    }
    }
    
//    if (!retStr){
//        //alert("You need to select atleast one applicant to proceed further.");
//        return false;
//    }
    form.dbCollection.value = retStr;
    return true;
}

function HandleSelect(obj)
{
var form =  document.getElementById("f1");
 for (var i = 0; i < form.elements.length; i++) 
	if (form.elements[i].id.substring(0, 6) == "dbRow_") form.elements[i].checked = obj.checked;
	CollectSelection(form);
}

