// $Id: utils.js,v 1.21 2010/02/26 00:07:53 morciuch Exp $
//------------------------------------------------------------------------------------
// Browser recognition
//------------------------------------------------------------------------------------
var ns6=document.getElementById&&!document.all
var ie=document.all

//------------------------------------------------------------------------------------
// Show OR hide funtion depends on if element is shown or hidden
//------------------------------------------------------------------------------------
var imgout=new Image(9,9);
var imgin=new Image(9,9);
imgout.src="images/up.gif";
imgin.src="images/right.gif";
//------------------------------------------------------------------------------------
// Returns true if specific element is visible
//------------------------------------------------------------------------------------
function isVisible(id)
{
	if (document.getElementById)  // DOM3 = IE5, NS6
	{
		if (document.getElementById(id).style.display == "none") 
		{
			return false;		
		}
		else
		{
			return true;
		}
	}
	else
	{
		if (document.layers) 
		{	
			if (document.id.display == "none")
			{
				return false;
			} 
			else 
			{
				return true;
			}
		} 
		else 
		{
			if (document.all.id.style.visibility == "none")
			{
				return false;
			} 
			else 
			{
				return true;
			}
		}	
	}
}

//------------------------------------------------------------------------------------
// Toggles element visibility and alternating an image for the visibility state
//------------------------------------------------------------------------------------
function showOrHide(id, img_up, img_down) { 

	imgout.src=img_up;
	imgin.src=img_down;
	
	if (document.getElementById) // DOM3 = IE5, NS6
	{ 
		var div = document.getElementById(id);
		if (div.style.display == "none")
		{
			div.style.display = 'block';
			filter(id+'img','imgin');			
		} 
		else 
		{
			filter(id+'img','imgout');
			div.style.display = 'none';
		}	
	} 
	else 
	{ 
		if (document.layers) 
		{	
			if (document.id.display == "none")
			{
				document.id.display = 'block';
				filter(id,'imgin');
			} 
			else 
			{
				filter(id,'imgout');	
				document.id.display = 'none';
			}
		} 
		else 
		{
			if (document.all.id.style.visibility == "none")
			{
				document.all.id.style.display = 'block';
			} 
			else 
			{
				filter(id,'imgout');
				document.all.id.style.display = 'none';
			}
		}
	}
}

//------------------------------------------------------------------------------------
// This switches expand collapse icons
//------------------------------------------------------------------------------------
function filter(imagename,objectsrc){
	if (document.images){
		document.images[imagename].src=eval(objectsrc+".src");
	}
}

//------------------------------------------------------------------------------------
// Replaces text with by in string
//------------------------------------------------------------------------------------
function replace(fullString,text,by) {
    var strLength = fullString.length, txtLength = text.length;
    if ((strLength == 0) || (txtLength == 0)) return fullString;

    var i = fullString.indexOf(text);
    if ((!i) && (text != fullString.substring(0,txtLength))) return fullString;
    if (i == -1) return fullString;

    var newstr = fullString.substring(0,i) + by;

    if (i+txtLength < strLength)
        newstr += replace(fullString.substring(i+txtLength,strLength),text,by);

    return newstr;
}

//------------------------------------------------------------------------------------
// Validates email address
//------------------------------------------------------------------------------------
function checkEmail(myForm) {
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(myForm.emailAddr.value)){
		return (true)
	}
	alert("Invalid E-mail Address! Please re-enter.")
	return (false)
}

//------------------------------------------------------------------------------------
// Places focus on specific form element
//------------------------------------------------------------------------------------
function putFocus(formInst, elementInst) {
	if (document.forms.length > 0) {
		document.forms[formInst].elements[elementInst].focus();
	}
}

//------------------------------------------------------------------------------------
// Places forcus on first text, textarea or password input on the current form
//------------------------------------------------------------------------------------
function firstFocus()
{
   if (document.forms.length > 0)
   {
      var TForm = document.forms[0];
      for (i=0;i<TForm.length;i++)
      {
         if ((TForm.elements[i].type=="text")||
           (TForm.elements[i].type=="textarea")||
           (TForm.elements[i].type=="password"))
         {
            document.forms[0].elements[i].focus();
            break;
         }
      }
   }
}

//------------------------------------------------------------------------------------
// Locks all inputs and submits the form
//------------------------------------------------------------------------------------
function lockFormAndSubmit(form, fieldName, source) 
{
	lockFormAndSubmit(form, fieldName, source, 'Please wait...');
}

//------------------------------------------------------------------------------------
// Locks all inputs and submits the form with custom msg on locked inputs
//------------------------------------------------------------------------------------
function lockFormAndSubmit(form, fieldName, source, msg) 
{
		if (msg == null) msg = 'Please wait...';
		
		source.value = msg;
    	for (i = 0; i < form.length; i++) 
    	{
     		var tempobj = form.elements[i];
     		if (tempobj.type.toLowerCase() == 'submit' || 
				tempobj.type.toLowerCase() == 'button' || 
				tempobj.type.toLowerCase() == 'reset')
			{
       			tempobj.disabled = true;
       		}
		}

  if (document.getElementById) {
    var input = document.createElement('input');
    if (document.all) 
    { // what follows should work with NN6 but doesn't in M14
        input.type = 'hidden';
        input.name = fieldName;
        input.value = 'true';
    }
    else if (document.getElementById) { // so here is the
                                        // NN6 workaround
        input.setAttribute('type', 'hidden');
        input.setAttribute('name', fieldName);
        input.setAttribute('value', 'true');
    }
    form.appendChild(input);
  }
  
  form.submit();
}

//------------------------------------------------------------------------------------
// Validates credit card number
//------------------------------------------------------------------------------------
function isValidCreditCardNumber(formField, ccType, fieldLabel)
{
	var result = true;
 	var ccNum = formField.value;
 
  	if (result && (formField.value.length>0))
 	{ 
 		if (!allDigits(ccNum))
 		{
 			alert('Please enter only numbers (no dashes or spaces) for the "' + fieldLabel +'" field.');
			formField.focus();
			result = false;
		}

		if (result)
 		{ 
 			
 			if (!LuhnCheck(ccNum) || !validateCCNum(ccType,ccNum))
 			{
 				alert('Please enter a valid ' + ccType + ' card number');
				formField.focus();
				result = false;
			}	
		} 

	} 
	
	return result;
}

//------------------------------------------------------------------------------------
// Verifies if the string is all numeric
//------------------------------------------------------------------------------------
function allDigits(str)
{
	return inValidCharSet(str,"0123456789");
}

//------------------------------------------------------------------------------------
// Verifies that string only contains characters from specific set
//------------------------------------------------------------------------------------
function inValidCharSet(str,charset)
{
	var result = true;
	
	for (var i=0;i<str.length;i++)
		if (charset.indexOf(str.substr(i,1))<0)
		{
			result = false;
			break;
		}
	
	return result;
}

//------------------------------------------------------------------------------------
// Performs Luhn check on the string
//------------------------------------------------------------------------------------
function LuhnCheck(str) 
{
  var result = true;

  var sum = 0; 
  var mul = 1; 
  var strLen = str.length;
  
  for (i = 0; i < strLen; i++) 
  {
    var digit = str.substring(strLen-i-1,strLen-i);
    var 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)
    result = false;
    
  return result;
}

//------------------------------------------------------------------------------------
// Validates credit card number
//------------------------------------------------------------------------------------
function validateCCNum(cardType,cardNum)
{
	var result = false;
	cardType = cardType.toUpperCase();
	
	var cardLen = cardNum.length;
	var firstdig = cardNum.substring(0,1);
	var seconddig = cardNum.substring(1,2);
	var first4digs = cardNum.substring(0,4);

	switch (cardType)
	{
		case "VISA":
			result = ((cardLen == 16) || (cardLen == 13)) && (firstdig == "4");
			break;
		case "AMERICAN EXPRESS":
			var validNums = "47";
			result = (cardLen == 15) && (firstdig == "3") && (validNums.indexOf(seconddig)>=0);
			break;
		case "MASTER CARD":
			var validNums = "12345";
			result = (cardLen == 16) && (firstdig == "5") && (validNums.indexOf(seconddig)>=0);
			break;
		case "DISCOVER":
			result = (cardLen == 16) && (first4digs == "6011");
			break;
		case "DINERS":
			var validNums = "068";
			result = (cardLen == 14) && (firstdig == "3") && (validNums.indexOf(seconddig)>=0);
			break;
	}
	return result;
}

//------------------------------------------------------------------------------------
// Checks specific radio button based on its id
//------------------------------------------------------------------------------------
function selectRadioButton(id)
{ 
	if (document.getElementById) { // DOM3 = IE5, NS6
		document.getElementById(id).checked = true;
	} else { 
		if (document.layers) {	
			document.id.checked = true;
		} else {
			document.all.id.checked = true;
		}
	}
}

//------------------------------------------------------------------------------------
// Escapes out forward slashes
//------------------------------------------------------------------------------------
function simpleEscape(text) {
    return text.replace(/\//g, "%2F");
}

//------------------------------------------------------------------------------------
// simple encoding of a given URL.
// Any "/" character in the parameters of the given URL will be replaced by "%2F".
//------------------------------------------------------------------------------------
function encodeUrl(url) {
    encodedurl = url
    asteriskIdx = url.indexOf("?");
    if(asteriskIdx > -1 && asteriskIdx < (url.length-1)) {
        encodedurl = url.substring(0, asteriskIdx) + "?" + simpleEscape(url.substring(asteriskIdx + 1));
    }
    return encodedurl;
}

//------------------------------------------------------------------------------------
// Opens a new window with parameter URL, Windowname, width and height
//------------------------------------------------------------------------------------
var smallwindow;
function opensmallwin(url, name, w, h)
{
    encodedurl = encodeUrl(url);
    smallwindow = window.open(encodedurl, name, 'toolbar=no,location=no,directories=no,status=no,menubar=0,scrollbars=yes,resizable=yes,top=150,left=660,width='+w+',height='+h);
    if(smallwindow != null)
       {
          if (smallwindow.opener == null)
          {
             smallwindow.opener = self;
          }
        }
    //smallwindow.focus();
    return smallwindow;
}

//------------------------------------------------------------------------------------
// Dynamically adds form element
//------------------------------------------------------------------------------------
function addelementtoform(field,fieldType,fieldName,fieldValue)
{
	var input = document.createElement(field);
	input.type = fieldType;
	input.name = fieldName;
	input.value = fieldValue;
	document.resourceForm.appendChild(input);
}

//------------------------------------------------------------------------------------
// Opens new windows with a message
//------------------------------------------------------------------------------------
function openExtWindow(url,w,h) 
{
	w = typeof(w) != 'undefined' ? w : '1024';
  	h = typeof(h) != 'undefined' ? h : '768';
	alert('You are about to open a link in a new window. To return to the current page, close the new window.');
	var load = window.open(url,'','scrollbars=yes,menubar=no,height='+h+',width='+w+',resizable=yes,toolbar=no,location=no,status=no');
	load.focus();
}

/***********************************************
* Highlight Table Cells Script- Dynamic Drive DHTML code library (www.dynamicdrive.com)
* Visit http://www.dynamicDrive.com for hundreds of DHTML scripts
* This notice must stay intact for legal use
***********************************************/

//Specify highlight behavior. "TD" to highlight table cells, "TR" to highlight the entire row:
var highlightbehavior="TR"

function changeto(e,highlightcolor)
{
	source=ie? event.srcElement : e.target
	if (source.tagName=="TABLE") 
		return
	while(source.tagName!=highlightbehavior && source.tagName!="HTML")
		source=ns6? source.parentNode : source.parentElement
	if (source.style.backgroundColor!=highlightcolor&&source.id!="ignore")
		source.style.backgroundColor=highlightcolor
}

function contains_ns6(master, slave) 
{ //check if slave is contained by master
	while (slave.parentNode)
		if ((slave = slave.parentNode) == master)
			return true;
	return false;
}

function changeback(e,originalcolor)
{
	if (ie&&(event.fromElement.contains(event.toElement)||source.contains(event.toElement)||source.id=="ignore")||source.tagName=="TABLE")
		return
	else if (ns6&&(contains_ns6(source, e.relatedTarget)||source.id=="ignore"))
		return
	if (ie&&event.toElement!=source||ns6&&e.relatedTarget!=source)
		source.style.backgroundColor=originalcolor
}
// ----------------------------------------------------------------------

// Javascript form validation routines.
// Author: Stephen Poley
//
// Simple routines to quickly pick up obvious typos.
// All validation routines return true if executed by an older browser:
// in this case validation must be left to the server.
//
// Update Jun 2005: discovered that reason IE wasn't setting focus was
// due to an IE timing bug. Added 0.1 sec delay to fix.
//
// Update Oct 2005: minor tidy-up: unused parameter removed
//
// Update Jun 2006: minor improvements to variable names and layout
// ----------------------------------------------------------------------

var nbsp = 160;		// non-breaking space char
var node_text = 3;	// DOM text node-type
var emptyString = /^\s*$/ ;
var global_valfield;	// retain valfield for timer thread

// --------------------------------------------
//                  trim
// Trim leading/trailing whitespace off string
// --------------------------------------------

function trim(str)
{
  return str.replace(/^\s+|\s+$/g, '');
}

// --------------------------------------------
//                  setfocus
// Delayed focus setting to get around IE bug
// --------------------------------------------

function setFocusDelayed()
{
  global_valfield.focus();
}

function setfocus(valfield)
{
  // save valfield in global variable so value retained when routine exits
  global_valfield = valfield;
  setTimeout( 'setFocusDelayed()', 100 );
}

// --------------------------------------------
//                  msg
// Display warn/error message in HTML element.
// commonCheck routine must have previously been called
// --------------------------------------------

function msg(fld,     // id of element to display message in
             msgtype, // class to give element ("warn" or "error")
             message) // string to display
{
  // setting an empty string can give problems if later set to a 
  // non-empty string, so ensure a space present. (For Mozilla and Opera one could 
  // simply use a space, but IE demands something more, like a non-breaking space.)
  var dispmessage;

  if (emptyString.test(message)) 
    dispmessage = String.fromCharCode(nbsp);    
  else  
    dispmessage = message;

  var elem = document.getElementById(fld);
  elem.firstChild.nodeValue = dispmessage;  
  elem.className = msgtype;   // set the CSS class to adjust appearance of message
}

// --------------------------------------------
//            commonCheck
// Common code for all validation routines to:
// (a) check for older / less-equipped browsers
// (b) check if empty fields are required
// Returns true (validation passed), 
//         false (validation failed) or 
//         proceed (don't know yet)
// --------------------------------------------

var proceed = 2;  

function commonCheck    (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required)   // true if required
{
  if (!document.getElementById) 
    return true;  // not available on this browser - leave validation to the server

  var elem = document.getElementById(infofield);

  if(elem == null) return true; //alert('Element [' + infofield + '] is not defined');

  if (!elem.firstChild) return true;  // not available on this browser 

  if (elem.firstChild.nodeType != node_text) return true;  // infofield is wrong type of node  
  
  if (valfield.length > 1)
  { 
   	if (valfield.selectedIndex != null)
   	{
   		valid = (valfield.selectedIndex > 0);
   	}
   	else
   	{
		for (var x = 0; x < valfield.length; x++)
		{
			valid = valfield[x].checked
			if (valid) {break}
		}
	}
	if(!valid)
	{
      msg (infofield, "error", "ERROR: required");  
      setfocus(valfield);
      return false;
	}	
  }
  else if (emptyString.test(valfield.value)) 
  {
    if (required) {
      msg (infofield, "error", "ERROR: required");  
      setfocus(valfield);
      return false;
    }
    else {
      msg (infofield, "warn", "");   // OK
      return true;  
    }
  }
  
  return proceed;
}

// --------------------------------------------
//            validatePresent
// Validate if something has been entered
// Returns true if so 
// --------------------------------------------

function validatePresent(valfield,   // element to be validated
                         infofield ) // id of element to receive info/error msg
{
  var stat = commonCheck (valfield, infofield, true);

  if (stat != proceed) return stat;

  msg (infofield, "warn", "");  

  return true;
}

// --------------------------------------------
//               validateEmail
// Validate if e-mail address
// Returns true if so (and also if could not be executed because of old browser)
// --------------------------------------------

function validateEmail  (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required)   // true if required
{
  var stat = commonCheck (valfield, infofield, required);

  if (stat != proceed) return stat;

  var tfld = trim(valfield.value);  // value of field with whitespace trimmed off
  var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/  ;

  if (!email.test(tfld)) {
    msg (infofield, "error", "ERROR: not a valid e-mail address");
    setfocus(valfield);
    return false;
  }

  var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/  ;

  if (!email2.test(tfld)) 
    msg (infofield, "warn", "Unusual e-mail address - check if correct");
  else
    msg (infofield, "warn", "");

  return true;
}

// --------------------------------------------
//            validateTelnr
// Validate telephone number
// Returns true if so (and also if could not be executed because of old browser)
// Permits spaces, hyphens, brackets and leading +
// --------------------------------------------

function validateTelnr  (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required)   // true if required
{
  var stat = commonCheck (valfield, infofield, required);

  if (stat != proceed) return stat;

  var tfld = trim(valfield.value);  // value of field with whitespace trimmed off
  var telnr = /^\+?[0-9 ()-]+[0-9]$/  ;

  if (!telnr.test(tfld)) {
    msg (infofield, "error", "ERROR: not a valid telephone number. Characters permitted are digits, space ()- and leading +");
    setfocus(valfield);
    return false;
  }

  var numdigits = 0;

  for (var j=0; j<tfld.length; j++)
    if (tfld.charAt(j)>='0' && tfld.charAt(j)<='9') numdigits++;

  if (numdigits<6) {
    msg (infofield, "error", "ERROR: " + numdigits + " digits - too short");
    setfocus(valfield);

    return false;
  }

  if (numdigits>14)
    msg (infofield, "warn", numdigits + " digits - check if correct");
  else { 
    if (numdigits<10)
      msg (infofield, "warn", "Only " + numdigits + " digits - check if correct");
    else
      msg (infofield, "warn", "");
  }

  return true;
}

// --------------------------------------------
//             validateAge
// Validate person's age
// Returns true if OK 
// --------------------------------------------

function validateAge    (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required)   // true if required
{
  var stat = commonCheck (valfield, infofield, required);

  if (stat != proceed) return stat;

  var tfld = trim(valfield.value);
  var ageRE = /^[0-9]{1,3}$/

  if (!ageRE.test(tfld)) {
    msg (infofield, "error", "ERROR: not a valid age");
    setfocus(valfield);

    return false;
  }

  if (tfld>=200) {
    msg (infofield, "error", "ERROR: not a valid age");
    setfocus(valfield);

    return false;
  }

  if (tfld>110) msg (infofield, "warn", "Older than 110: check correct");
  else {
    if (tfld<7) msg (infofield, "warn", "Bit young for this, aren't you?");
    else        msg (infofield, "warn", "");
  }

  return true;
}

	/************************************************************************************************************
	(C) www.dhtmlgoodies.com, November 2005
	
	This is a script from www.dhtmlgoodies.com. You will find this and a lot of other scripts at our website.	
	
	Terms of use:
	You are free to use this script as long as the copyright message is kept intact. However, you may not
	redistribute, sell or repost it without our permission.
	
	Thank you!
	
	www.dhtmlgoodies.com
	Alf Magne Kalleland
	
	************************************************************************************************************/	
	var arrayOfRolloverClasses = new Array();
	var arrayOfClickClasses = new Array();
	var activeRow = false;
	var activeRowClickArray = new Array();
	
	function highlightTableRow()
	{
		var tableObj = this.parentNode;
		if(tableObj.tagName!='TABLE')tableObj = tableObj.parentNode;

		if(this!=activeRow){
			this.setAttribute('origCl',this.className);
			this.origCl = this.className;
		}
		this.className = arrayOfRolloverClasses[tableObj.id];
		
		activeRow = this;
		
	}
	
	function clickOnTableRow()
	{
		var tableObj = this.parentNode;
		if(tableObj.tagName!='TABLE')tableObj = tableObj.parentNode;		
		
		if(activeRowClickArray[tableObj.id] && this!=activeRowClickArray[tableObj.id]){
			activeRowClickArray[tableObj.id].className='';
		}
		this.className = arrayOfClickClasses[tableObj.id];
		
		activeRowClickArray[tableObj.id] = this;
				
	}
	
	function resetRowStyle()
	{
		var tableObj = this.parentNode;
		if(tableObj.tagName!='TABLE')tableObj = tableObj.parentNode;

		if(activeRowClickArray[tableObj.id] && this==activeRowClickArray[tableObj.id]){
			this.className = arrayOfClickClasses[tableObj.id];
			return;	
		}
		
		var origCl = this.getAttribute('origCl');
		if(!origCl)origCl = this.origCl;
		this.className=origCl;
		
	}
		
	function addTableRolloverEffect(tableId,whichClass,whichClassOnClick)
	{
		arrayOfRolloverClasses[tableId] = whichClass;
		arrayOfClickClasses[tableId] = whichClassOnClick;
		
		var tableObj = document.getElementById(tableId);
		var tBody = tableObj.getElementsByTagName('TBODY');
		if(tBody){
			var rows = tBody[0].getElementsByTagName('TR');
		}else{
			var rows = tableObj.getElementsByTagName('TR');
		}
		for(var no=0;no<rows.length;no++){
			rows[no].onmouseover = highlightTableRow;
			rows[no].onmouseout = resetRowStyle;
			
			if(whichClassOnClick){
				rows[no].onclick = clickOnTableRow;	
			}
		}	
	}

// copyright 1999 Idocs, Inc. http://www.idocs.com
// Distribute this script freely but keep this notice in place
function numbersonly(myfield, e, dec)
{
	var key;
	var keychar;

	if (window.event)
   		key = window.event.keyCode;
	else if (e)
   		key = e.which;
	else
   		return true;
	keychar = String.fromCharCode(key);

	// control keys
	if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27)) return true;
	// numbers
	else if ((("0123456789").indexOf(keychar) > -1)) return true;

	// decimal point jump
	else if (dec && (keychar == "."))
   	{
   		myfield.form.elements[dec].focus();
   		return false;
   	}
	else
   		return false;
}

// utility function to retrieve a future expiration date in proper format;
// pass three integer parameters for the number of days, hours,
// and minutes from now you want the cookie to expire; all three
// parameters required, so use zeros where appropriate
function getExpDate(days, hours, minutes) {
    var expDate = new Date();
    if (typeof days == "number" && typeof hours == "number" && typeof hours == "number") {
        expDate.setDate(expDate.getDate() + parseInt(days));
        expDate.setHours(expDate.getHours() + parseInt(hours));
        expDate.setMinutes(expDate.getMinutes() + parseInt(minutes));
        return expDate.toGMTString();
    }
}

// utility function called by getCookie()
function getCookieVal(offset) {
    var endstr = document.cookie.indexOf (";", offset);
    if (endstr == -1) {
        endstr = document.cookie.length;
    }
    return unescape(document.cookie.substring(offset, endstr));
}

// primary function to retrieve cookie by name
function getCookie(name) {
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while (i < clen) {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg) {
            return getCookieVal(j);
        }
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break; 
    }
    return null;
}

// store cookie value with optional details as needed
function setCookie(name, value, expires, path, domain, secure) {
    document.cookie = name + "=" + escape (value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

// remove the cookie by setting ancient expiration date
function deleteCookie(name,path,domain) {
    if (getCookie(name)) {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

// emulate c printf function
printf = function() 
{ 
  var num = arguments.length; 
  var oStr = arguments[0];   
  for (var i = 1; i < num; i++) 
  { 
    var pattern = "\\{" + (i-1) + "\\}"; 
    var re = new RegExp(pattern, "g"); 
    oStr = oStr.replace(re, arguments[i]); 
  } 
  return oStr; 
} 

// return true if string is empty
function isEmpty( inputStr ) 
{ 
	return ( null == inputStr || 0 == inputStr.length ) 
}

function isNotEmpty( inputStr ) 
{ 
	return ( !isEmpty(inputStr) ) 
}

// String.trim() emulation
String.prototype.trim = function()
{
	return (this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, ""))
}

// String.startsWith() emulation
String.prototype.startsWith = function(str)
{
	return (this.match("^"+str)==str)
}

// String.endsWith() emulation
String.prototype.endsWith = function(str)
{
	return (this.match(str+"$")==str)
}

/*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 * http://blog.stevenlevithan.com/archives/date-time-format 
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */
var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};

//helper function to create the form
function getNewSubmitForm(action)
{
	var submitForm = document.createElement("FORM");
	document.body.appendChild(submitForm);
	submitForm.method = "POST";
	submitForm.action = action;
	
	return submitForm;
}

//helper function to add elements to the form
function createNewFormElement(inputForm, elementName, elementValue)
{
	var newElement = document.createElement("input");
	newElement.type = "hidden";
	newElement.name = elementName;
	inputForm.appendChild(newElement);
	newElement.value = elementValue;
	
	return newElement;
}

function submitLink(href)
{
	var lex1 = href.split('?');
	var action = lex1[0];
	var qstr = lex1[1];
	var params = qstr.split('&');

	var submitForm = getNewSubmitForm(action);
	
	for (var i = 0; i < params.length; i++) 
	{
		var keyValue = params[i].split('=');
		var name = keyValue[0];
		var value = keyValue[1]; 
	
 		createNewFormElement(submitForm, name, value);
	}
 	
 	submitForm.submit();
}