// General javascript code for DeKroyft-Metz & Co., Inc. corporate website
//
//  Copyright (C) 2005 John L. Lawler and Incode Systems, Inc.
//    (except where credit is otherwise given)
//
// =============================================================================
// general functions
//
// 2005-03-04 Quick and dirty string padding function
// 2005-08-03 Added prtFriendlyBtnOnclick() function for handling simple
//            printer friendly mode on some pages.
//
function StrPadLeft(orig_str, pad_char, pad_to_len) {
  if (orig_str.length >= pad_to_len)
    return orig_str;

  while (orig_str.length < pad_to_len) {
    orig_str = pad_char + orig_str;
  }

  return orig_str;
}

// 2005-03-05 jll; snagged from random website
function sleep(sleepms) {
  var then,now;
  then = new Date().getTime();
  now = then;
  while((now - then) < sleepms) {
    now = new Date().getTime();
  }
}

// 2005-03-09 jll; also from random site on web
function trim(sInString) {
  sInString = sInString.replace( /^\s+/g, "" ); // strip leading
  return sInString.replace( /\s+$/g, "" );      // strip trailing
}

// source: SmartWebby.com
function isInteger(s) {
  var i;
  for (i = 0; i < s.length; i++) {   
    // Check that current character is number.
    var c = s.charAt(i);
    if ((c < "0") || (c > "9"))
      return false;
  }

  return true;
}

function RoundNumber(n,d) {
  var factor = Math.pow(10,d);
  return (Math.round(n * factor) / factor);
}

function FormatNumber(n,d) {
  var n1 = n;

  try {
    n1 = n1.toFixed(d);
  }
  catch(e) {
    n1 = RoundNumber(n,d);
    var i = String(n1).indexOf(".");

    if (d <= 0) {
      if (i > 0) n1 = n1.substr(0, i-1);
    }
    else {
      if (i < 0) {
	n1 = n1 + ".";
	for (var j = 0; j < d; j++)
          n1 = n1 + "0";  
      }
      else {
        var l = Number(i) + 1 + Number(d);
        var len = String(n1).length;

        if (l < len)
          n1 = n1.substr(0, l);
        else
          for (var j = len; j < l; j++)
            n1 = n1 + "0";
      }
    }
  }
  return n1;
}

// 2005-08-03 jll; Helper function to be called from a "Printer Friendly" btn
//   on a DMC webpage; see map1.php for an example of usage.
function prtFriendlyBtnOnclick(btn) {
  var sidebarDiv = document.getElementById('sidebar');
  var headerDiv = document.getElementById('header');
  var mainDiv = document.getElementById('main');
  sidebarDiv.parentNode.removeChild(sidebarDiv);
  headerDiv.parentNode.removeChild(headerDiv);
  mainDiv.style.left = mainDiv.style.top = '0px';

  // remove the Printer Friendly button and replace with link to original page
  var link = document.createElement('a');
  link.setAttribute('href', document.URL);
  link.appendChild(document.createTextNode('return to original page'));
  var linkRoot = document.createElement('a');
  linkRoot.setAttribute('href', '/');
  linkRoot.appendChild(document.createTextNode('return to homepage'));

  btn.parentNode.insertBefore(link, btn);
  btn.parentNode.insertBefore(document.createTextNode(' | '), btn);
  btn.parentNode.insertBefore(linkRoot, btn);
  btn.parentNode.insertBefore(document.createElement('br'), btn);
  btn.parentNode.insertBefore(document.createElement('br'), btn);
  // this joyous method works well in FF, but (naturally) not at all in IE6
  //btn.parentNode.style.setProperty("float", "none", "");
  btn.parentNode.removeChild(btn);
}

// =============================================================================
// validating functions
function non_neg_money(Field) {
  if (isNaN(parseFloat(Field.value)) ||
      parseFloat(Field.value) != Field.value ||
      Field.value < 0) {
    alert("this money field must be a non-blank, non-negative decimal!");
    Field.focus();
    if (Field.type == "text" ||
        Field.type == "textarea")
      Field.select();
    return false;
  }
  //Field.value = parseFloat(Field.value);
  return true;
}

function non_neg_decimal(Field) {
  if (isNaN(parseFloat(Field.value)) ||
      parseFloat(Field.value) != Field.value ||
      Field.value < 0) {
    alert("this field must be a non-blank, non-negative decimal!");
    Field.focus();
    if (Field.type == "text" ||
        Field.type == "textarea")
      Field.select();
    return false;
  }
  //Field.value = parseFloat(Field.value);
  return true;
}

function non_neg_int(Field) {
  if (isNaN(parseInt(Field.value)) ||
      parseInt(Field.value) != Field.value ||
      Field.value < 0) {
    alert("this field must be a non-negative integer!");
    Field.focus();
    if (Field.type == "text" ||
        Field.type == "textarea")
      Field.select();
    return false;
  }
  return true;
}

function gt_zero_int(Field) {
  if (isNaN(parseInt(Field.value)) ||
      parseInt(Field.value) != Field.value ||
      Field.value <= 0) {
    alert("this field must be an integer greater than 0!");
    Field.focus();
    if (Field.type == "text" ||
        Field.type == "textarea")
      Field.select();
    return false;
  }
  return true;
}

function non_null_char(Field) {
  if (trim(Field.value) == "") {
    alert("this field cannot be blank!");
    Field.focus();
    if (Field.type == "text" ||
        Field.type == "textarea")
      Field.select();
    return false;
  }
  return true;
}

// =============================================================================
// date validating functions, portions excerpted from SmartWebby.com

// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=2000;
var maxYear=2100;

function stripCharsInBag(s, bag) {
  var i;
  var returnString = "";
  // Search through string's characters one by one.
  // If character is not in bag, append to returnString.
  for (i = 0; i < s.length; i++) {   
    var c = s.charAt(i);
    if (bag.indexOf(c) == -1)
      returnString += c;
  }
  return returnString;
}

function daysInFebruary (year) {
  // February has 29 days in any year evenly divisible by four,
  //   EXCEPT for centurial years which are not also divisible by 400.
  return ((year % 4 == 0) &&
          (!(year % 100 == 0) || (year % 400 == 0))) ? 29 : 28;
}

function GetDaysInMonth(m) {
  days = 31;

  if (m == 4 || m == 6 || m == 9 || m == 11)
    days = 30;
  if (m == 2)
    days = 29;

  return days;
}

function is_non_null_date(Field) {
  var dtStr = Field.value;
  var pos1 = dtStr.indexOf(dtCh);
  var pos2 = dtStr.indexOf(dtCh, pos1 + 1);
  var strMonth = dtStr.substring(0, pos1);
  var strDay;
  var strYear = dtStr.substring(pos2 + 1);
  var errorMsg = '';

  // allow date w/o year to be specified
  if (pos2 != -1)
    strDay = dtStr.substring(pos1 + 1, pos2);
  else
    strDay = dtStr.substring(pos1 + 1);

  strYr = strYear;

  if (strDay.charAt(0) == "0" && strDay.length > 1)
    strDay = strDay.substring(1);
  if (strMonth.charAt(0) == "0" && strMonth.length > 1)
    strMonth=strMonth.substring(1);

  for (var i = 1; i <= 3; i++) {
    if (strYr.charAt(0) == "0" && strYr.length > 1)
      strYr=strYr.substring(1)
  }

  month = parseInt(strMonth);
  day = parseInt(strDay);
  year = parseInt(strYr);

  if (pos1 == -1) {
    errorMsg = "The date format should be: mm/dd/yyyy\n" +
                 "(or mm/dd, current year assumed)";
  }

  if (strMonth.length < 1 || month < 1 || month > 12) {
    errorMsg = "Please enter a valid month";
  }

  if (strDay.length < 1 || day < 1 || day > 31 ||
      (month == 2 && day > daysInFebruary(year)) ||
      day > GetDaysInMonth(month)) {
    errorMsg = "Please enter a valid day";
  }

  if (pos2 != -1 &&  // allow date w/o year to be specified
      (strYear.length != 4 ||
       year == 0 ||
       year < minYear ||
       year > maxYear)) {
    errorMsg = "Please enter a valid 4 digit year between " + minYear +
                 " and " + maxYear;
  }

  if ((pos2 != -1 && dtStr.indexOf(dtCh, pos2 + 1) != -1) ||
      isInteger(stripCharsInBag(dtStr, dtCh)) == false) {
    errorMsg = "Please enter a valid date";
  }

  // if the year was not present, we'll add it for completeness
  if (errorMsg == '' && pos2 == -1) {
    var now = new Date();
    Field.value += '/' + now.getFullYear();
  }

  if (errorMsg > '') {
    alert(errorMsg);
    Field.focus();
    if (Field.type == "text" ||
        Field.type == "textarea")
      Field.select();
    return false;
  }
  else
    return true;
}

// this one accepts null strings
function is_date(Field) {
  if (trim(Field.value) > "")
    return is_non_null_date(Field);
  else
    return true;
}
