/*  Module itdFrm.js - JavaScript 1.5

IDWD JavaScript Form Functions
  - Requires global JavaScript module itd.js

©2004- InnoTech Dynamics Web Design®
 http://idwd.vantonder.net/
 E-mail: itdwd at vantonder dot net

  2004-05-30
 Updates:
  2008-04-09
  2008-05-08
  2009-06-21
*/

var empty_fields;
var errors;
var ffSs = 'font-family:Microsoft Sans Serif, Arial, Helvetica, sans-serif;';
var ffMs = 'font-family:Consolas, Andale Mono, Lucida Console, Courier New, Courier, monospace;';

function format(num)
{ /*
  A simple utility function to format decimal numbers to 2 places.
  Decimal point used for js compatability.
  2007-05-21
 Updates:
  2007-05-25
*/
  if (num === 0) {
    return "0.00";
  } else {
    var tmp = Math.round(num * 100) + "";
    return tmp.substr(0, tmp.length - 2) + "." + tmp.substr(tmp.length - 2, 2);
  }
}


function lstElm(frm)
{ /*
  A utility function that lists all named elements in a form an their types and values.
  (Temporarily) requires a 10x60 textarea named elmtxtarea in the form to contain the list.
  Eg. <td>Form elements:<br /><textarea name="elmtxtarea" rows="50" cols="80"></textarea></td>
    lstElm(document.formName); in a script on the page after the form
  2007-05-20
 Updates:
  2009-06-18
*/
  var elmTxt = frm.elmtxtarea;
  elmTxt.value = '  Type  |  Name  | Descriptor | Value  \n';
  var dscr;
  var elm;
  var vlu;

  for (var i = 0; i < frm.elements.length; i++) {
    elm = frm.elements[i];
    if (elm.name != "elmtxtarea") {
      dscr = elm.value;
      vlu = "";
      if (elm.type == "checkbox") {
        if (elm.checked) vlu = "checked";
        dscr = "";
      } else if (elm.type == "radio") {
        if (elm.checked) vlu = "checked";
      } else if (elm.type == "select-one") {
      }
      if (vlu != "") vlu = ' | ' + vlu;
      elmTxt.value += elm.type + ' | ' + elm.name + ' | ' + dscr + vlu + '\n';
    }
  }
}


function formValues(frm)
{ /*
  A utility function that creates an html table containing
   named elements in a form and thier assigned values.
  2009-06-19
 Updates:
  2009-06-20
*/
  var elmTxt = frm.elmtxtarea;

  var htTblFrm = '<table align="center" border="1" cellpadding="4" cellspacing="0">\n';
  var dscr;
  var dspl;
  var elm;
  var vlu;
  var htTblFrm = '';
  var frmEmail;

  htTblFrm += '<form name="frmSmry" action="" method="get" enctype="text/html">\n';
  htTblFrm += '<table align="center" border="1" cellpadding="3" cellspacing="0">\n';

  for (var i = 0; i < frm.elements.length; i++) {
    elm = frm.elements[i];
    if (elm.name != "elmtxtarea" && elm.name != "Kamer_tariewe" && elm.type != "submit" &&
        elm.type != "reset" && elm.type != "button" && elm.type != "hidden") {
      dscr = elm.value;
      if (elm.name == "Email") frmEmail = dscr;
      vlu = "";
      dspl = "";
      if (elm.type == "checkbox") {
        if (elm.checked) dspl = dscr;
      } else if (elm.type == "radio") {
        if (elm.checked) dspl = dscr;
      } else if (elm.type == "select-one") {
        dspl = dscr;
      } else {
        dspl = dscr;
      }
      if (dspl != "" && dspl != "0" && dspl != "0.00") {
        htTblFrm += '<tr><td>' + elm.name + '</td><td>' + dspl + '</td></tr>\n';
      }
    }
  }
  htTblFrm += '</table>\n';
  htTblFrm += '</form>\n';
  //elmTxt.value = htTblFrm;
  return htTblFrm;
}


function isblank(str)
{ /* A utility function that returns true if a string contains only whitespace characters.
   2008-04-09
 Updates:
*/
/*
  for(var i = 0; i < str.length; i++) {
    var chr = str.charAt(i);
    if ((chr != ' ') && (chr != '\n') && (chr != '\t')) {return false;}
  }
  return true;
*/

  return !/[^\s]/.test(str);

}
//** End isblank


function isempty(elm)
{ /*  A utility function that returns true if a form field is empty or contains only whitespace characters.
  2007-05-21
 Updates:
*/
  if ((elm === null) || (elm === "") || isblank(elm)) {
    return true;
  } else {
    return false;
  }
}
//** End isblank


function trim(str)
{ /*  Remove leading and trailing whitespace characters,
     consolidate multiple space and tab characters into single spaces,
     remove spaces after newlines
  2008-04-09
Updates:

*/
  if (str != undefined) {
    // leading or trailing
    str = str.replace(/(^\s*)|(\s*$)/gi,"");
    // consolidate into single spaces
    str = str.replace(/[ \t\0]{1,}/gi," ");
    // remove spaces after newline
    str = str.replace(/\n /,"\n");
    return str;
  }
}
//** end trim()


function frmVerify(frm, lang)
{ /*  Function that performs form verification.
  It is invoked from the onsubmit event handler.
  The handler should return whatever value this function returns.
  2004-05-30
 Updates:
  2007-05-27
  2007-06-01
  2009-06-20
*/
  empty_fields = "";
  mty_optFields = "";
  errors = "";
  var len;
  var msg;
  var dlgTtl;
  var radChk;
  var v;

  // Loop through the elements of the form, looking for all
  //   text and textarea elements that don't have an "optional" property
  //   defined. Then, check for fields that are empty and make a list of them.
  // If any of these elements have a "min" or a "max" property defined,
  //   verify that they are numbers and in the right range.
  // If the element has a "numeric" property defined, verify that
  //   it is a number, but don't check its range.
  // Put together error messages for fields that are wrong.

  for (var i = 0; i < frm.length; i++) {
    var elm = frm.elements[i];
    var elmTxt;
    if (elm.text) {
      elmTxt = elm.text;
    } else {
      elmTxt = elm.name;
    }

    //if (elm.name == "vfaks") alert(i);  //temp to determine index of element
    //if (elm.name == "Rollovr_Btns") alert(elm.optional);

    if (elm.filter && !isempty(elm.value)) {
      if (!elm.filter.test(elm.value)) {
        if (elm.fltmsg) {
          errors += "    " + elm.fltmsg + " in ";
        } else {
          errors += "    Invalid field ";
        }
        errors += "`" + elmTxt + "`: |" + elm.value + "| \n";
      }
    }

    if (!elm.optional) {
      if (((elm.type == "text") || (elm.type == "textarea"))) {
        // first check if the field is empty
        if (isempty(elm.value)) {
          empty_fields += "\n    " + elmTxt;
          continue;  // next iteration of loop
        }

        // Check for fields that are supposed to be numeric.
        if (elm.numeric) {
          v = parseFloat(elm.value);
          if (isNaN(v) ||
              ((elm.min !== null) && (v < elm.min)) ||
              ((elm.max !== null) && (v > elm.max))) {
            errors += "    The field `" + elmTxt + "` must be a number";
            if (elm.min !== null) {
              errors += " not less than " + elm.min;
            }
            if (elm.max !== null && elm.min !== null) {
              errors += " and not more than " + elm.max;
            } else {
              if (elm.max !== null) {
                errors += " that is less than " + elm.max;
              }
            }
            errors += ".\n";
          }
        } else {
          len = elm.value.length;
          if (elm.min !== null && len < elm.min) {
            errors += "    The field `" + elmTxt + "`: |" + elm.value + "| must be at least " + elm.min + " characters long.\n";
          } else {
            if (elm.max !== null && len > elm.max) {
              errors += "    The field `" + elmTxt + "`: |" + elm.value+ "| must be no longer than " + elm.max + " characters.\n";
            }
          }
        }
      } else if (elm.type == "radio") {
        radChk = false;
        var elmnm = elm.name;
        var elmln = frm[elmnm].length;
        var k = elmln - 1;
        if (elm.value == (frm[elmnm][k].value)) {
          for (var j = 0; j < elmln; j++) {
            if (frm[elmnm][j].checked === true) {
              radChk = true;
              break;
            }
          }
          if (!radChk) {empty_fields += "\n    " + elmTxt;}
        }
      } else if (elm.type == "select-one") {
        if (elm.selectedIndex === 0) {
          empty_fields += "\n    " + elmTxt;
        }
      }
    } else {  // optional
      if (((elm.type == "text") || (elm.type == "textarea"))) {
        // first check if the field is empty
        if (isempty(elm.value) && !elm.noprompt) {
          mty_optFields += "    " + elmTxt + "\n";
          continue;
        }

        // Check for fields that are supposed to be numeric.
        if (elm.numeric) {
          v = parseFloat(elm.value);
          if (isNaN(v) ||
              ((elm.min !== null) && (v < elm.min)) ||
              ((elm.max !== null) && (v > elm.max))) {
            errors += "    The field `" + elmTxt + "` must be a number";
            if (elm.min !== null) {
              errors += " not less than " + elm.min;
            }
            if (elm.max !== null && elm.min !== null) {
              errors += " and not more than " + elm.max;
            } else {
              if (elm.max !== null) {
                errors += " that is less than " + elm.max;
              }
            }
            errors += ".\n";
          }
        } else {
          len = elm.length;
          if (elm.min !== null && len < elm.min) {
            errors += "    The field `" + elmTxt + "`: |" + elm.value + "| must be at least" + elm.min + "characters long.\n";
          } else {
            if (elm.max !== null && len > elm.max) {
              errors += "    The field `" + elmTxt + "`: |" + elm.value + "| must be no longer than" + elm.max + "characters.\n";
            }
          }
        }
      }
    }
  }

  //specific tests for this form
  errors +=  vrfySpcf(frm);

  // If there were any errors, display the messages, and
  //   return false to prevent the form from being submitted.
  // Otherwise return true.
  if (mty_optFields) {
    var rtrn = fnFldsMty(mty_optFields);
    if (!rtrn) {
      return false;
    }
  }

  if (!errors && !empty_fields) {
    wrtFrmSmry(frm, lang);
    return true;
  }
  //wrtFrmSmry(frm);  //test
  fnFldsErr(errors, empty_fields);
  return false;
}
//** End frmVerify


function fnFldsMty(mty_optFields)
{ /*
  Empty optional fields
  2007-06-01
 Updates:
  2007-06-02
*/
  dlgTtl = "Empty optional fields";
  msg  = "<ul style=\"margin-top: 0; margin-bottom: 0;\">\n";
  mty_optFields = mty_optFields.replace(/\n/g , "</li>\n");
  mty_optFields = mty_optFields.replace(/ {4}/g , "<li>");
  msg += mty_optFields + "</ul>\n";
  msg += "<p style=\"color: #c04000; margin: 0;\">Please supply all applicable items.</p>\n";
  fnWrtSlider(dlgTtl, msg);
  fnShowSliderBox();
  msg = "- Click 'Cancel' to go back to the form to add or change information.\n";
  msg += "- Click 'OK' to continue and submit the information as entered.\n";
  if (confirm(msg)) {
    fnHideSliderBox();
    return true;
  } else {
    return false;
  }
}
//** End fnFldsMty


function fnFldsErr(errors, empty_fields)
{ /* Empty compulsory fields and fields with errors
  2007-06-01
 Updates:
  2007-06-02
*/
  var tblWdthEm;
  var msg;

  dlgTtl = "Fields with errors";
  err  = "";
  if (empty_fields) {
    empty_fields = empty_fields.replace(/\n/g , "</li>\n");
    empty_fields = empty_fields.replace(/ {4}/g , "<li>");
    err += "<p style=\"color: #e00000; margin: 0;\">The following required field(s) are empty:</p>\n";
    err += "<ul style=\"margin-top: 0; margin-bottom: 0;\">\n" + empty_fields + "</ul>";
  }
  if (errors) {
    errors = errors.replace(/\n/g , "</li>\n");
    errors = errors.replace(/ {4}/g , "<li>");
    err += "<p style=\"color: #e00000; margin: 0;\">The following required field(s) are in error:</p>\n";
    err += "<ul style=\"margin-top: 0; margin-bottom: 0;\">\n" + errors + "</ul>\n";
    tblWdthEm = 35;
  }
  fnWrtSlider(dlgTtl, err, tblWdthEm);
  fnShowSliderBox();
  msg = "- Click 'Cancel' to go back to the form to add or change information.\n";
  msg += "- Click 'OK' to continue and submit the information as entered.\n";
// ??
  msg = "The form was not submitted because of the error(s) listed.\n";
  msg += "  - Please correct the error(s) and re-submit.\n";
  alert(msg);
}
//** End fnFldsErr



/*
  2007-05-29
 Updates:
  2007-05-31
  2007-06-03
*/
var xOfstDflt = 80;
var yOfstDflt = 10;
var xOfstIncr = xOfstDflt / 4;
var sliderXOffset = xOfstDflt;
var sliderYOffset = yOfstDflt;
var flgNxt;
var tmotId;
var sldrElmTbl;
var sldrElmTtl;
var sldrElmMsg;
var sldrElmBtn1;
var sldrElmBtn2;

function fnWrtSlider(sldrTtl, sldrMsg, msgWdth, sldrBtn1, sldrBtn2)
{ /* Write slider table at end of document
  2007-05-29
 Updates:
  2007-06-03
*/

  var tblWdth = emSzPx * 16;

  if (msgWdth) {
    tblWdth = emSzPx * msgWdth;
  }

  if (!sldrTtl) {
    sldrTtl = "";
  }

  if (!sldrMsg) {
    sldrMsg = "";
  }

  if (!sldrBtn1) {
    sldrBtn1 = "";
  }

  if (!sldrBtn2) {
    sldrBtn2 = "";
  }

  if (sldrElmTbl) {
    sldrElmTbl.setAttribute("width", tblWdth);
    sldrElmTtl.innerHTML = sldrTtl;
    sldrElmMsg.innerHTML = sldrMsg;
  } else {
    sliderTable = "\n<table id=\"sldrTbl\" border=\"0\" cellspacing=\"0\" cellpadding=\"1\" width=\"" + tblWdth + "\" style=\"display: none; position: absolute; top: 10px; left: 10px; empty-cells: hide\">\n" +
      "<tr>\n" +
        "<td>\n" +
          "<div style=\"width: 20px; cursor: pointer;\" onclick=\"javascript: fnHideSliderBox();\">&nbsp;</div>\n" +
          "<table cellspacing=\"0\" cellpadding=\"0\" bgcolor=\"#ffffff\" border=\"1\" bordercolor=\"#999999\">\n" +
            "<tr>\n" +
              "<td>\n" +
                "<table cellspacing=\"0\" cellpadding=\"0\" width=\"100%\" bgcolor=\"#0033ff\" border=\"0\">\n" +
                  "<tr>\n" +
                    "<td id=\"sldrTtl\" style=\"font-weight: bold; padding: 0.2em; color: #ffffff; cursor: default;\">" + sldrTtl + "</td>\n" +
                    "<td style=\"width: 1em; padding: 0.25em 0; color: #000000; background-color: #cccccc; cursor: pointer;\" onclick=\"javascript: fnHideSliderBox(); return false;\">&nbsp;X&nbsp;</td>\n" +
                  "</tr>\n" +
                "</table>\n" +
              "</td>\n" +
            "</tr>\n" +
            "<tr>\n" +
              "<td id=\"sldrMsg\" valign=\"top\" style=\"padding: 0.5em;\">" + sldrMsg + "</td>\n" +
            "</tr>\n" +
/*
            "<tr>\n" +
              "<td align=\"center\" valign=\"top\" style=\"padding: 0.25em 0.25em;\">\n" +
               "<span id=\"sldrBtn1\" class=\"btn\" style=\"cursor: pointer;\" onclick=\"javascript: flgNxt = false;\">" + sldrBtn1 + "<\/span>\n" +
               "<span id=\"sldrBtn2\" class=\"btn\" style=\"cursor: pointer;\" onclick=\"javascript: fnHideSliderBox(); flgNxt = true;\">" + sldrBtn2 + "<\/span>\n" +
               "</td>\n" +
            "</tr>\n" +
*/
          "</table>\n" +
        "</td>\n" +
      "</tr>\n" +
    "</table>";
    document.write(sliderTable);
    if (document.getElementById) {
      sldrElmTbl = document.getElementById ("sldrTbl");
      sldrElmTtl = document.getElementById ("sldrTtl");
      sldrElmMsg = document.getElementById ("sldrMsg");
/*
      sldrElmBtn1 = document.getElementById ("sldrBtn1");
      sldrElmBtn2 = document.getElementById ("sldrBtn2");
*/
    } else {
      sldrElmTbl = document.all.sldrTbl;
      sldrElmTtl = document.all.sldrTtl;
      sldrElmMsg = document.all.sldrMsg;
/*
      sldrElmBtn1 = document.all["sldrBtn1"];
      sldrElmBtn2 = document.all["sldrBtn2"];
*/
    }
    sldrElmTtl.onmousedown = fnMouseClickHandler;
  }
/*
  if (sldrBtn1 === "") sldrElmBtn1.style.display = "none";
  else sldrElmBtn1.style.display = "inline";
  if (sldrBtn2 === "") sldrElmBtn2.style.display = "none";
  else sldrElmBtn2.style.display = "inline";
*/
}


function fnHideSliderBox()
{
  sldrElmTbl.style.display = "none";
}


function fnCheckCookieData()
{
  var cookieExpireTimeDate = new Date();

  // 4 days * 24 hours * 3600 seconds/hr * 1000 seconds/millisecond
  var cookieExpireTime = cookieExpireTimeDate.getTime() + (4 * 24 * 3600 * 1000);

  cookieExpireTimeDate.setTime (cookieExpireTime);

  document.cookie = "zdSlider=;path=/;expires=" + cookieExpireTimeDate.toGMTString();

  setTimeout ("fnShowSliderBox();", 200);

  //sldrElmTbl.onmousedown = fnMouseClickHandler;
}


function fnExpireForOneYear()
{
  var cookieExpireTimeDate = new Date();

  // 4 days * 24 hours * 3600 seconds/hr * 1000 seconds/millisecond
  var cookieExpireTime = cookieExpireTimeDate.getTime() + (365 * 24 * 3600 * 1000);

  cookieExpireTimeDate.setTime (cookieExpireTime);

  document.cookie = "zdSlider=;path=/;expires=" + cookieExpireTimeDate.toGMTString();
  return true;
}


function fnGetSliderLeftLocation()
{
  return ((window.pageXOffset) ? window.pageXOffset : document.documentElement.scrollLeft) + sliderXOffset + "px";
}


function fnGetSliderTopLocation()
{
  return ((window.pageYOffset) ? window.pageYOffset : document.documentElement.scrollTop) + sliderYOffset + "px";
}


function fnCheckSliderLocationAndSleep()
{
  sldrElmTbl.style.top = fnGetSliderTopLocation();
  sldrElmTbl.style.left = fnGetSliderLeftLocation();
    if (parseInt(sldrElmTbl.style.left, 10) < 0) {
      sliderXOffset = 0;
    }
    if (parseInt(sldrElmTbl.style.top, 10) < 0) {
      sliderYOffset = 0;
    }

  if (sldrElmTbl.style.display === "") {
    setTimeout ("fnCheckSliderLocationAndSleep();", 1000);
  }
}


function fnSliderBoxMover()
{ /*
  2007-05-29
 Updates:
  2007-05-31
*/
  if (sliderXOffset != xOfstDflt || sliderYOffset != yOfstDflt)
  {
    if (sliderXOffset != xOfstDflt) {
      if (Math.abs(sliderXOffset - xOfstDflt) <= xOfstIncr) {
        sliderXOffset = xOfstDflt;
      } else if (sliderXOffset < xOfstDflt) {
        sliderXOffset += xOfstIncr;
      } else {
        sliderXOffset -= xOfstIncr;
      }
    }

    if (sliderYOffset != yOfstDflt) {
      if (Math.abs(sliderYOffset - yOfstDflt) <= xOfstIncr) {
        sliderYOffset = yOfstDflt;
      } else if (sliderYOffset < yOfstDflt) {
        sliderYOffset += xOfstIncr;
      } else {
        sliderYOffset -= xOfstIncr;
      }
    }
    sldrElmTbl.style.top = fnGetSliderTopLocation();
    sldrElmTbl.style.left = fnGetSliderLeftLocation();
    setTimeout("fnSliderBoxMover();", 20);
  } else {
    fnCheckSliderLocationAndSleep();
  }
}


function fnShowSliderBox()
{ /*
  2007-05-29
 Updates:
  2007-05-31
  2007-06-02
*/
  sliderYOffset = yOfstDflt;

  sliderXOffset = -xOfstDflt / 3;

  sldrElmTbl.style.top  = fnGetSliderTopLocation();
  sldrElmTbl.style.left = fnGetSliderLeftLocation();
  sldrElmTbl.style.display = "";
  fnSliderBoxMover();
}


function fnGetExpiresFromCookie (cookieVarName)
{
  var cookieEnabled = false;

// Best way to check for a cookie is to set it and get it.  Catch any errors
  try {
    document.cookie="testcookie";
    cookieEnabled = (document.cookie.indexOf("testcookie")!=-1)? true : false;
  }
  catch (strError){
    // no cookie code functionality on this browser...
    cookieEnabled = false;
  }
  if (!cookieEnabled) {
//    alert("no cookies allowed");
    return "no cookies allowed";
  }
//  alert("cookies allowed");


  var cookieVarNameLen = cookieVarName.length;
  var cookieVal = document.cookie;
  var cookieLen = cookieVal.length;
  var cookieSearchPos, cookieSearchPosEnd;


  cookieSearchPos = 0;
  while (cookieSearchPos < cookieLen) {
    cookieSearchPosEnd = cookieSearchPos + cookieVarNameLen;
    if (cookieVal.substring (cookieSearchPos, cookieSearchPosEnd) == cookieVarName) {
      cookieValSemicolonPos = cookieVal.indexOf (";", cookieSearchPosEnd);
      if (cookieValSemicolonPos == -1) {
        cookieValSemicolonPos = cookieLen;
      }
      return unescape (cookieVal.substring (cookieSearchPosEnd + 1, cookieValSemicolonPos));
    }
    cookieSearchPos++;
  }
  return null;
}

var mouseInitialClickXLocation, mouseInitialClickYLocation;


function fnMouseClickMoveHandler (e)
{
  mouseClickX = (document.all) ? event.clientX : e.clientX;
  mouseClickY = (document.all) ? event.clientY : e.clientY;

  sliderXOffset += mouseClickX - mouseInitialClickXLocation;
  sliderYOffset += mouseClickY - mouseInitialClickYLocation;
  mouseInitialClickXLocation = mouseClickX;
  mouseInitialClickYLocation = mouseClickY;
  sldrElmTbl.style.top = fnGetSliderTopLocation();
  sldrElmTbl.style.left = fnGetSliderLeftLocation();
}


function fnDoNothing()
{
}


function fnClearMouseClickActions()
{
  document.onmousemove = fnDoNothing;
  document.onmouseup  = fnDoNothing;
}


function fnMouseClickHandler (evt)
{
  mouseInitialClickXLocation = (document.all) ? event.clientX : evt.clientX;
  mouseInitialClickYLocation = (document.all) ? event.clientY : evt.clientY;
  document.onmousemove = fnMouseClickMoveHandler;
  document.onmouseup   = fnClearMouseClickActions;
}
