// ************************
// layer utility routines *
// ************************

var agent=navigator.userAgent.toLowerCase();
function moveObject(objectId, newXCoordinate, newYCoordinate) {
    // get a reference to the cross-browser style object and make sure the object exists
    var styleObject = getStyleObject(objectId);
    if(styleObject) {
  styleObject.left = newXCoordinate;
  styleObject.top = newYCoordinate;
  return true;
    } else {
  // we couldn't find the object, so we can't very well move it
  return false;
    }
} // moveObject

function switchIfDone(the_form, this_div, next_div) {

  var complete = true;
  for (var loop=0; loop < the_form.elements.length; loop++) {
    if (the_form.elements[loop].value == "") {
      complete = false;
    }
  }
  if ((complete == true) && (next_div == "finished")) {
    submitTheInfo();
  }
  else if (complete == true) {
    switchDiv(this_div, next_div);
  } else {
    alert('please complete the form before moving on');
  }
}

function switchDiv(this_div, next_div) {
  if (getStyleObject(this_div) && getStyleObject(next_div)) {
    setVisDisp(this_div, false);
    setVisDisp(next_div, true);
  }
}

function escapeChars(theString) {
   var regexp = /&/g ;
   var regexp2 = /#/g ;
   var regexp3 = /\r\n/g ;
   var regexp4 = /\n/g ;
   var regexp5 = /\"/g ;
   theString = theString.replace(regexp, "%^");
   theString = theString.replace(regexp2, "%*");
   theString = theString.replace(regexp3, "<br>");
   theString = theString.replace(regexp4, "<br>");
   theString = theString.replace(regexp5, "%)");
   return theString;
}

function chkFieldSelected(governingLoc, errorMge, nation)
{
   var check = true;

   if (nation == "canada")
   {
   if (getFormObject('powerattny', governingLoc).value == "Select the Province" || getFormObject('powerattny', governingLoc).value == " " || getFormObject('powerattny', governingLoc).value == "")
      {
         setVisDisp(errorMge, true);
         getObject("governingLawAnchor").focus();
         return false;
      }

      else
      {
         setVisDisp(errorMge, false);
         return true;
      }
   }


   else if (nation == "usa")
   {
    if (getFormObject('powerattny', governingLoc).value == "Select the State" || getFormObject('powerattny', governingLoc).value == " " || getFormObject('powerattny', governingLoc).value == "")
      {
         setVisDisp(errorMge, true);
         getObject("governingLawAnchor").focus();
         return false;
      }

      else
      {
         setVisDisp(errorMge, false);
         return true;
      }
   }

   else if (nation == 'australia')
   {
      if (getFormObject('powerattny', governingLoc).value == 'Select the State/Territory' || getFormObject('powerattny', governingLoc).value == " " || getFormObject('powerattny', governingLoc).value == "")
      {
         setVisDisp(errorMge, true);
         getObject("governingLawAnchor").focus();
         return false;
      }

      else
      {
         setVisDisp(errorMge, false);
         return true;
      }
   }

   else
   {
      if (getFormObject('powerattny', governingLoc).value == "Select the Country" || getFormObject('powerattny', governingLoc).value == " ")
      {
         setVisDisp(errorMge, true);
         getObject("governingLawAnchor").focus();
        return false;
      }

      else
      {
         setVisDisp(errorMge, false);
      return true;
    }
   }
}


function emailCheck (emailStr) {

/* The following variable tells the rest of the function whether or not
to verify that the address ends in a two-letter country or well-known
TLD.  1 means check it, 0 means don't. */

var checkTLD=1;

/* The following is the list of known TLDs that an e-mail address must end with. */

var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;

/* The following pattern is used to check if the entered e-mail address
fits the user@domain format.  It also is used to separate the username
from the domain. */

var emailPat=/^(.+)@(.+)$/;

/* The following string represents the pattern for matching all special
characters.  We don't want to allow special characters in the address.
These characters include ( ) < > @ , ; : \ " . [ ] */

var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";

/* The following string represents the range of characters allowed in a
username or domainname.  It really states which chars aren't allowed.*/

var validChars="\[^\\s" + specialChars + "\]";

/* The following pattern applies if the "user" is a quoted string (in
which case, there are no rules about which characters are allowed
and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
is a legal e-mail address. */

var quotedUser="(\"[^\"]*\")";

/* The following pattern applies for domains that are IP addresses,
rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
e-mail address. NOTE: The square brackets are required. */

var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;

/* The following string represents an atom (basically a series of non-special characters.) */

var atom=validChars + '+';

/* The following string represents one word in the typical username.
For example, in john.doe@somewhere.com, john and doe are words.
Basically, a word is either an atom or quoted string. */

var word="(" + atom + "|" + quotedUser + ")";

// The following pattern describes the structure of the user

var userPat=new RegExp("^" + word + "(\\." + word + ")*$");

/* The following pattern describes the structure of a normal symbolic
domain, as opposed to ipDomainPat, shown above. */

var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");

/* Finally, let's start trying to figure out if the supplied address is valid. */

/* Begin with the coarse pattern to simply break up user@domain into
different pieces that are easy to analyze. */

var matchArray=emailStr.match(emailPat);

if (matchArray==null) {

/* Too many/few @'s or something; basically, this address doesn't
even fit the general mould of a valid e-mail address. */

alert("Email address seems incorrect (check @ and .'s)");
return false;
}
var user=matchArray[1];
var domain=matchArray[2];

// Start by checking that only basic ASCII characters are in the strings (0-127).

for (i=0; i<user.length; i++) {
if (user.charCodeAt(i)>127) {
alert("Ths username contains invalid characters.");
return false;
   }
}
for (i=0; i<domain.length; i++) {
if (domain.charCodeAt(i)>127) {
alert("Ths domain name contains invalid characters.");
return false;
   }
}

// See if "user" is valid

if (user.match(userPat)==null) {

// user is not valid

alert("The username doesn't seem to be valid.");
return false;
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
host name) make sure the IP address is valid. */

var IPArray=domain.match(ipDomainPat);
if (IPArray!=null) {

// this is an IP address

for (var i=1;i<=4;i++) {
if (IPArray[i]>255) {
alert("Destination IP address is invalid!");
return false;
   }
}
return true;
}

/* Domain is symbolic name.  Check if it's valid. */

var atomPat=new RegExp("^" + atom + "$");
var domArr=domain.split(".");
var len=domArr.length;
for (i=0;i<len;i++) {
if (domArr[i].search(atomPat)==-1) {
alert("The domain name does not seem to be valid.");
return false;
   }
}

/* domain name seems valid, but now make sure that it ends in a
known top-level domain (like com, edu, gov) or a two-letter word,
representing country (uk, nl), and that there's a hostname preceding
the domain or country. */

if (checkTLD && domArr[domArr.length-1].length!=2 &&
domArr[domArr.length-1].search(knownDomsPat)==-1) {
alert("The address must end in a well-known domain or two letter " + "country.");
return false;
}

/* Make sure there's a host name preceding the domain. */

if (len<2) {
alert("This address is missing a hostname!");
return false;
}

/* If we've gotten this far, everything's valid!*/
return true;
}




function checkInput()
{
  var govCheck = true;
  var donorGovCheck = true;
  var signGovCheck = true;
  var powerCheck = false;
  var signGovLaw;
  var donorGovLaw;
   var governLaw = getFormObject(ct,"governLaw").value;


  if ((governLaw == "canada") || (governLaw == "usa") || (governLaw == "uk" && getFormObject(ct, "ukPOASelection")[1].checked && getFormObject(ct, 'governingCountry').value != 'Scotland'))
  {
   donorGovLaw = getFormObject(ct,"donorGovernLaw").value;
   signGovLaw = getFormObject(ct,"signGovLaw").value;
  }
  if ((governLaw == "usa")||(governLaw == "canada"))
  {  
      if (governLaw == "usa")
      {
         powerCheck = (getFormObject(ct,"realFeature").checked == true ||
         getFormObject(ct,"chattelFeature").checked == true || 
         getFormObject(ct,"bankfullFeature").checked == true || 
         getFormObject(ct,"businessoperateFeature").checked == true || 
         getFormObject(ct,"insuranceFeature").checked == true || 
         getFormObject(ct,"estatetransFeature").checked == true || 
         getFormObject(ct,"livingtrustFeature").checked == true || 
         getFormObject(ct,"litigationFeature").checked == true || 
         getFormObject(ct,"govtbenefitsFeature").checked == true || 
         getFormObject(ct,"retirementplanFeature").checked == true || 
         getFormObject(ct,"familycareFeature").checked == true || 
         getFormObject(ct,"taxFeature").checked == true || 
         getFormObject(ct,"maintainassetsFeature").checked == true || 
         getFormObject(ct,"professionalsFeature").checked == true ||
         getFormObject(ct,"usgeneralFeature").checked == true ||
         getFormObject(ct,"managerealtyFeature").checked == true || 
         getFormObject(ct,"managebankFeature").checked == true);
      }
      if (document.forms[ct].giftsFeature)
         powerCheck = powerCheck || getFormObject(ct,"giftsFeature").checked == true;
      if (document.forms[ct].charityFeature)
         powerCheck = powerCheck || getFormObject(ct,"charityFeature").checked == true;
      if (governLaw == "canada")
      {
            powerCheck = ((getFormObject(ct, "specificClause2").checked == true) ||
            getFormObject(ct,"realFeature").checked == true ||
            getFormObject(ct,"stayhomeFeature").checked == true || 
            getFormObject(ct,"familycareFeature").checked == true || 
            getFormObject(ct,"taxFeature").checked == true || 
            getFormObject(ct,"giftsFeature").checked == true || 
            getFormObject(ct,"charityFeature").checked == true || 
            getFormObject(ct,"maintainassetsFeature").checked == true || 
            getFormObject(ct,"professionalsFeature").checked == true || 
            getFormObject(ct,"corporateshareFeature").checked == true || 
            getFormObject(ct,"sellrealtyFeature").checked == true || 
            getFormObject(ct,"buyrealtyFeature").checked == true || 
            getFormObject(ct,"managerealtyFeature").checked == true || 
            getFormObject(ct,"managebankFeature").checked == true);
      }

      if (getFormObject(ct,"otherPowers").value >= 1)
      {
         powerCheck = true;
      }
   }
   else
   {
      powerCheck = true;    
   }
   if (powerCheck == false)
   {
         setVisDisp('powersErrMge', true);
         getObject("powersErr").focus();
   }
   else
   {
            setVisDisp('powersErrMge', false);
   }

  //governing Law
  if (governLaw == "canada")
   govCheck = chkFieldSelected("governingProv", "canadaErrMge", "canada");

   else if (governLaw == "usa")
      govCheck = chkFieldSelected("governingState", "usaErrMge", "usa");

   else if (governLaw == 'australia')
      govCheck = chkFieldSelected('governingTerritory', 'australiaErrMge', 'australia');

   else
      govCheck = chkFieldSelected("governingCountry", "ukErrMge", "uk");

   if (govCheck && (governLaw == "canada" || governLaw == "usa" || (governLaw == "uk" && getFormObject(ct, "ukPOASelection")[1].checked && getFormObject(ct,'governingCountry').value != 'Scotland')))
   {
      //donor location
      if (donorGovLaw == "canada"){
         donorGovCheck = chkFieldSelected("donorGovProv", "canadaDonorErrMge", "canada");

}
      else if (donorGovLaw == "usa")
         donorGovCheck = chkFieldSelected("donorGovState", "usaDonorErrMge", "usa");

      else if (donorGovLaw == 'australia')
         donorGovCheck = chkFieldSelected('donorGovTerritory', 'australiaDonorErrMge', 'australia');

      else
         donorGovCheck = chkFieldSelected("donorGovCountry", "ukDonorErrMge", "uk");

      if (donorGovCheck)
      {
         //signing location
         if (signGovLaw == "canada")
            signGovCheck = chkFieldSelected("signGovProv", "canadaSignErrMge", "canada");

         else if (signGovLaw == "usa")
            signGovCheck = chkFieldSelected("signGovState", "usaSignErrMge", "usa");

         else if (signGovLaw == 'australia')
            signGovCheck = chkFieldSelected('signGovTerritory', 'australiaSignErrMge', 'australia');

         else
            signGovCheck = chkFieldSelected("signGovCountry", "ukSignErrMge", "uk");
      }
      if (signGovCheck == false)
      {
         getObject("signingLocationAnchor").focus();
      }
  }


      
 if (govCheck == false || donorGovCheck == false || signGovCheck == false || powerCheck == false)
   return false;

 else
   return true;

}

function checkTextEntry()
{
   var powerCheck=true;
   var propertyCheck=true;
   var restrictionCheck=true;

   if ((getFormObject(ct, "specificAttorneyPower").value).length > 708)
   {
      setVisDisp("specificAttorneyErrMsg", true);
      getFormObject(ct, "specificAttorneyPower").focus();
      powerCheck=false;
   }

   if (powerCheck)
   {
      if ((getFormObject(ct, "limitedProperty").value).length > 558)
      {
         setVisDisp("limitedPropertyErrMsg", true);
         getFormObject(ct, "limitedProperty").focus();
         propertyCheck=false;
      }

      if (propertyCheck)
      {
         if ((getFormObject(ct, "otherRestriction").value).length > 707)
         {
            setVisDisp("restrictionsErrMsg", true);
            getFormObject(ct, "otherRestriction").focus();
            restrictionCheck=false;
         }
      }
   }

   if (propertyCheck == false || powerCheck == false || restrictionCheck == false)
      return false;

   else
      return true;

   return check;
}

function submitTheInfo()
{
   //if (getFormObject(ct, 'governLaw').value == 'uk' && getFormObject(ct, 'ukPOASelection')[0].checked && (getFormObject(ct, 'governingCountry').value == 'England' || getFormObject(ct, 'governingCountry').value == 'Wales'))
   //{
   // window.location = '#disclaimer';
   // return;
   //}
   
  //divdisplay();

  //var submission_string = "";

  if(!checkInput()) return;

  //Uncomment the next line to enable the lawdepot US contracts page. Adds State initials to end of url (i.e ...?loc=USAK)
   //getForm('hiddenform').action+=getFormObject("powerattny", 'governingState').value;

  var f = getForm('hiddenform');
  if (getFormObject(ct, "governLaw").value == "uk"  && getFormObject(ct, "ukPOASelection")[0].checked && getFormObject(ct, 'governingCountry').value != 'Scotland')
  {
   if (!checkTextEntry()) return;
   var action=f.action;
//   f.action=action.replace(/preview\.php/,"previewPDF.php");
  }
      saveReq=false;
    //alert(createVarString());// DEBUG

      getFormObject("hiddenform","variablestring").value = createVarString();

      f.submit();
}


function hideAll(hidden_div) {
  setVisDisp("hidden_div",false);
}


function checkboxcheck(entry,HiddenDiv) {
  if(entry) {
     if (entry.checked) {
       setVisDisp(HiddenDiv,true);
     }
     else {
       setVisDisp(HiddenDiv,false);
     }
  }
}


function isNumber(inputVal) {
  oneDecimal = false
  inputStr = inputVal.toString()
  for (var i=0; i<inputStr.length; i++) {
    var oneChar =inputStr.charAt(i)
    if (oneChar == "." && !oneDecimal) {
      oneDecimal = true
      continue
    }
    if (oneChar < "0" || oneChar > "9")  {
      if (oneChar != ",") {
        alert("Please make sure entries are numbers.")
        return false
      }
    }
  }
  return true
}

function checkIt(inputvar) {
   inputStr = inputvar.value
   if (isNumber(inputStr)) {
   } else {
     inputvar.focus()
     inputvar.select()
   }
}

function funcChangeDiv(inputvar,selectedvalue,HiddenDiv) {
   if(inputvar) {
      if (inputvar.selectedIndex == selectedvalue) {
         setVisDisp(HiddenDiv,true);
      } else {
         setVisDisp(HiddenDiv,false);
      }
   }
}

function funcradChangeDiv(selectedvalue,HiddenDiv) {
   if (selectedvalue == "true") {
      setVisDisp(HiddenDiv,true);
   } else {
      setVisDisp(HiddenDiv,false);
   }
}

function funcNotChangeDiv(inputvar,selectedvalue,HiddenDiv) {
   if(inputvar) {
      if (inputvar.selectedIndex != selectedvalue) {
        setVisDisp(HiddenDiv,true);
      } else {
        setVisDisp(HiddenDiv,false);
      }
   }
}

function redisplay(db,openingornot,divname) {
   for (var i=1; i<db.length; i++) {
      setVisDisp(db[i].divname, false);
   }
   if (openingornot == 'true') {
      setVisDisp(db[1].divname, true);
   }
   setVisDisp(divname, true);
}


function formatCurrency(num,dollarSign) {
   num = num.toString().replace(/\$|\,/g,'');
   if(isNaN(num)){
      num="0";
      //alert("Oops!  That does not appear to be a valid number.  Please try again.");
      return (num);
   } else {
      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));
      }
      if (dollarSign == true) {
        return (((sign)?'':'-') + '$' + num + '.' + cents);
      } else {
         return (((sign)?'':'-') + num + '.' + cents);
      }
   }
}
function setStatus(msg) {
  status = msg;
}
function bookmark(){
   /***** Compatibility? *********/
   window.external.AddFavorite(window.location.href,window.document.title);
}
function printDocument() {
   if(window.print) {
      window.print();
   } else if(agent.indexOf("mac") != -1) {
      alert("Press Cmd-p to print your document.");
   } else {
      alert("Press Ctrl-p to print your document.");
   }
   
   
}

function displayOtherPowers()
{
   var governLaw = getFormObject(ct,"governLaw").value;
   if ((governLaw == "usa")||(governLaw == "canada"))
   { 
      for(i=1;i<=3;i++) 
      {
         if(i <= document.getElementById("otherPowers").value)
            setVisDisp("otherPower"+i,true);

         else
            setVisDisp('otherPower'+i,false);
      }
   }
}
