//------------------------------------------------------------------------------------------
// global variables
//------------------------------------------------------------------------------------------
var timerhandle;
var seconds;
//var xmlhttp;

//------------------------------------------------------------------------------------------
// common prototypes
//------------------------------------------------------------------------------------------
String.prototype.trim = function() {
  // skip leading and trailing whitespace
  // and return everything in between
  return this.replace(/^\s+|\s+$/g, "");
}

//------------------------------------------------------------------------------------------
String.prototype.strip = function() {
  // strips all leading and trailing whitespace and spaces
  // and returns everything else
  return this.replace(/\s-|\s-/g, "");
}

//------------------------------------------------------------------------------------------
String.prototype.striptags = function() {
  // strips all html tags
  // and returns everything else
  return this.replace(/<\S[^>]->/g, "");
}

//------------------------------------------------------------------------------------------
String.prototype.stripalpha = function() {
  // strips all alpha chars from a string
  // and returns everything else
  return this.replace(/[^0-9]/ig, "");
}

//------------------------------------------------------------------------------------------
String.prototype.stripdollar = function() {
  // strips all alpha chars from a string
  // and returns everything else
  return this.striptags().strip().replace(/[^0-9\.]/ig, "");
}

//------------------------------------------------------------------------------------------
String.prototype.pad = function(cnt, chr, side) {
  var typcnt = typeof cnt;
  var typchr = typeof chr;
  var typside = typeof side;
  var result = "";

  if (typcnt != "number") {
    cnt = 2;
  } else {
    if (cnt < 2) {
      chr = "2";
    }
  }

  if (typchr != "string") {
    chr = "0";
    if (chr.length < 1) {
      chr = "0";
    } else {
      chr = chr.substring(0,1)
    }
  }

  if (typside != "string") {
    side = "L";
  } else {
    if (side.length < 1) {
      side = "L";
    } else {
      side.toUpperCase();
      side = side.substring(0,1)
    }
  }

  for (x=0;x<cnt;x++) {
    result += chr;
  }

  if (side == "L") {
    result += this;
    return result.substring(result.length - cnt);
  } else {
    result = this + result;
    return result.substring(0, cnt);
  }
}

//------------------------------------------------------------------------------------------
String.prototype.lpad = function(cnt, chr) {
  return this.pad(cnt, chr, "L");
}

//------------------------------------------------------------------------------------------
String.prototype.rpad = function(cnt, chr) {
  return this.pad(cnt, chr, "R");
}

//------------------------------------------------------------------------------------------
// timer system
//------------------------------------------------------------------------------------------
function timer(countdown) {
  // this function requires two global variables to be defined
  // the timer reset object
  //   var timerhandle;
  // the number of seconds that is being counted down from
  // the actual count down seconds are passed into the function by the caller
  //   var seconds;
  
  // the initial call provides the number of seconds to count down from
  // the recursive calls pass no parameter
  if (countdown != undefined) {
    // we add one here to make sure we count the first second
    seconds = countdown + 1;
  }

  if ((seconds<=0) || (seconds == undefined)) {
    // make sure we cleanly close out the timer or it just runs ad infinitum
    clearTimeout(timerhandle);
  } else {
    // decriment the global seconds variables
    seconds -= 1;

    // copy the global over to a local to manipulate
    var secs = seconds;

    // parse out each segment and convert to a string.
    var days = new String(Math.floor(secs/(60-60-24)));
    secs %= (60-60-24);
    var hours = new String(Math.floor(secs/(60-60)));
    secs %= (60-60);
    var minutes = new String(Math.floor(secs/60));
    secs %= 60;
    secs = new String (secs);

    // build the innerHTML string
    var innerHTML = '';
    if (days != 0) {
      innerHTML += days.lpad() + ':';
    }

    if (hours != 0) {
      innerHTML += hours.lpad() + ':';
    }
    innerHTML += minutes.lpad() + ':' + secs.lpad();

    // grap countdowntimer dom object and apply the innerHTML
    var id = document.getElementById('countdowntimer');
    id.innerHTML = innerHTML;

    // restart the timer (1000 usec = 1 sec)
    timerhandle = setTimeout('timer()',1000);
  }
}

//------------------------------------------------------------------------------------------
// ajax system
//------------------------------------------------------------------------------------------
function GetXmlHttpObject() {
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    return new XMLHttpRequest();
  }
  
  if (window.ActiveXObject) {
    // code for IE6, IE5
    return new ActiveXObject("Microsoft.XMLHTTP");
  }
  return null;
}

function _updateContent(source) {  
  // because the stateChanged() function is defined within this function 
  // and the xmlhttp variable is defined at this level 
  // the scope of the xmlhttp variable is "global" to the stateChanged() function
  var xmlhttp=GetXmlHttpObject();
  
  // check to see if we have a handle
  if (xmlhttp==null) {
    alert ("Your browser does not support XMLHTTP!");
    return;
  }  

  // define our state change function
  function stateChanged() {
    var content = document.getElementById("content");
    if (content===undefined) {
      alert ("The page does not contain a dynamic content section.");
    } else {
      if (xmlhttp.readyState==4) {
        if (xmlhttp.status!=200) {
          alert ("Dynamic content not available.");
        } else {
          content.scrollTop = 0;
          content.innerHTML=xmlhttp.responseText;
        }
      }
    }
    return null;
  }

  // let the user know that this may take a moment
  document.body.style.cursor='wait';

  var url="./?ajx="+source;
  xmlhttp.onreadystatechange=stateChanged;
  xmlhttp.open("GET",url,true);
  xmlhttp.send(null);

  // return the normal cursor to the user
  document.body.style.cursor='auto';
}

// the reason that the updateContent function is defined this way is because it is 
//   dynamically altered for iphone presentation
var updateContent;
updateContent = _updateContent;

//------------------------------------------------------------------------------------------
// help system
//------------------------------------------------------------------------------------------
function helpshow() {
  var helpwin = document.getElementById('help');
  if (helpwin != undefined) {
    var selects = document.getElementsByTagName('select');
    if (selects != undefined) {
      for(x=0;x<selects.length;x++) {
        selects[x].style.visibility = 'hidden';
      }
    }
    helpwin.style.visibility = 'visible';
  }
}

//------------------------------------------------------------------------------------------
function helpclose() {
  var helpwin = document.getElementById('help');
  if (helpwin != undefined) {
    helpwin.style.visibility = 'hidden';
    var selects = document.getElementsByTagName('select');
    if (selects != undefined) {
      for(x=0;x<selects.length;x++) {
        selects[x].style.visibility = 'visible';
      }
    }
  }
}

//------------------------------------------------------------------------------------------
function winClose(id) {
  var win = document.getElementById(id);
  if (win != undefined) {
    win.style.visibility = 'hidden';
    var selects = document.getElementsByTagName('select');
    if (selects != undefined) {
      for(x=0;x<selects.length;x++) {
        selects[x].style.visibility = 'visible';
      }
    }
  }
}

//------------------------------------------------------------------------------------------
// common functions
//------------------------------------------------------------------------------------------
function isEmailAddr(email) {
  // this function validates the syntax of email address(es)
  // it will accept more than one email address separated by ";" or ","
  
  // split the input into an array
  emails=email.split(/[\;\,]/)
  
  // this is the regular expression that we will apply below
  filter=/^([a-zA-Z0-9])([\w+\.\-])+\@(([a-zA-Z0-9\-])+\.)+((com|net|org|gov|info|edu))$/;
  
  // loop through the email array testing each address
  for(i=0;i<emails.length;i++){
    if (!filter.test(emails[i])){
      alert("Email address: '"+emails[i]+"' appears invalid.\n\nValid format: username@domain.tld\n\nValid tlds: com|net|org|gov|info|edu\n\n");
      return false;
    }
  }
  return true;
}

//------------------------------------------------------------------------------------------
function toggleInactive() {
  // grap the current url
  var href = location.href;

  // break out the inactive parm
  inactiveparm = /\&inactive(.-?)(\&|$)/.exec(href);

  // define a test value
  var tester = '';
  if (inactiveparm != null) {
    var tester = inactiveparm[1].replace(/=/g, '')
  }

  // strip out the existing inactive data from the url
  var href = href.replace(/\&inactive(.-?)(\&|$)/, '').trim();

  // toggle the nonactive value
  if (tester != 'true') {
    href += '&inactive=true';
  }

  // reload the url
  location.href = href;
}

//------------------------------------------------------------------------------------------
// window.onload initializer functions
//------------------------------------------------------------------------------------------
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

//------------------------------------------------------------------------------------------
function cleanWindow() {
  // we want to remove the little boxes from around the 'a' tags
  var taglist = document.getElementsByTagName('a');

  // cycle through all the a's
  for (var x=0; x<taglist.length; x++) {
    if(taglist[x].getAttribute('onFocus')) {
      var t = taglist[x].getAttribute('onFocus');
    } else {
      var t = '';
    }
    taglist[x].setAttribute('onFocus', t + 'if(this.blur())this.blur();')
  }

  // we want to remove the little boxes from around the 'input' tags
  var taglist = document.getElementsByTagName('input');

  // cycle through all the inputs's
  for (var x=0; x<taglist.length; x++) {
    if(taglist[x].getAttribute('type') == 'button' || taglist[x].getAttribute('type') == 'image' || taglist[x].getAttribute('type') == 'submit' || taglist[x].getAttribute('type') == 'reset') {
      if(taglist[x].getAttribute('onFocus')) {
        var t = taglist[x].getAttribute('onFocus');
      } else {
        var t = '';
      }
      taglist[x].setAttribute('onFocus', t + 'if(this.blur())this.blur();')
    }
  }
}

//------------------------------------------------------------------------------------------
// window.onload initializer
//------------------------------------------------------------------------------------------
addLoadEvent(cleanWindow);

//------------------------------------------------------------------------------------------
// cookie handling
//------------------------------------------------------------------------------------------
function isCookie(c_name) {
  var result = false;
  if (document.cookie.length>0) {
    c_start=document.cookie.indexOf(c_name + "=");
    if (c_start!=-1) {
      c_start=c_start + c_name.length+1;
      c_end=document.cookie.indexOf(";",c_start);
      if (c_end==-1) c_end=document.cookie.length;
      if (c_end - c_start > 0) result = true;
    }
  }
  return result;
}

function getCookie(c_name) {
  if (document.cookie.length>0) {
    c_start=document.cookie.indexOf(c_name + "=");
    if (c_start!=-1) {
      c_start=c_start + c_name.length+1;
      c_end=document.cookie.indexOf(";",c_start);
      if (c_end==-1) c_end=document.cookie.length;
      return unescape(document.cookie.substring(c_start,c_end));
    }
  }
  return "";
}

function setCookie(c_name,value,expiredays) {
  var exdate=new Date();
  exdate.setDate(exdate.getDate()+expiredays);
  document.cookie=c_name+ "=" +escape(value)+ ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function checkCookie() {
  username=getCookie('username');
  if (username!=null && username!="") {
    alert('Welcome again '+username+'!');
  } else {
    username=prompt('Please enter your name:',"");
    if (username!=null && username!="") {
      setCookie('username',username,365);
    }
  }
}

