// Overwrite dom objects
String.prototype.lTrim = function(){
	return this.replace(/^\s+/,'');
}
String.prototype.rTrim = function(){
	return this.replace(/\s+$/,'');
}
String.prototype.trim = function(){
	return this.replace(/^\s+|\s+$/g,'');
}

function getInternetExplorerVersion()
//Returns the version of Internet Explorer or a -1
//(indicating the use of another browser).
{
var rv = -1; // Return value assumes failure.
if (navigator.appName == 'Microsoft Internet Explorer')
{
var ua = navigator.userAgent;
var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
 rv = parseFloat( RegExp.$1 );
}
return rv;
}

function messageobj(field, val, type){
	this.field = field;
	this.message = val;
	this.type = type;
}
var messagelist = function(){
	var list = [];
	var count = 0;
	return { 
		getCount : function(){
			return list.length;
		},
		push : function(field, val, type){
			var inArr = false;
			for(var i=0; i < list.length; i++){
				if(list[i].field == field){
					list[i] = new messageobj(field, val, type);
					inArr = true;
				}
			}
			if(!inArr){
				list.push(new messageobj(field, val, type));
			}
		},
		pop : function(field){
			for(var i=0; i < list.length; i++){
				if(list[i].field == field){
					list.splice(i, 1);
				}
			}
		},
		getMessage : function(field){
			for(var i=0; i < list.length; i++){
				if(list[i].field == field){
					return list[i];
				}
			}
			return "";
		},
		clearMessages : function(field){
			list = [];
		},
		getType : function(field){
			var message = this.getMessage(field);
			if(message != ""){
				return message.type;
			}
			return "";
		},
		getList : function(){
			return list;
		}
	};
}();

var browserName = navigator.appName;
var ieVersion = getInternetExplorerVersion();
var errorList = new Array();
var warningList = new Array();
var infoList = new Array();
var isAdmin = false;
var targetElem = "default";
var buttonClicked = false;

var addressHover = {
	tag : "div", id : "widgetAddress", innerHTML : [
			{ tag : "p", innerHTML : [
					{ tag : "strong", innerHTML : "Please choose one of these addresses. The address you entered is pre-selected." }
				]
			},
			{ tag : "div", className : "qasAddress", style: "overflow:auto;", id : "addressContainer" },
			{ tag : "div", align : "right", style : "margin:10px 50px 0 0;", innerHTML : [
					{ tag : "input", name : "close", type : "button", className : "btnBlue", value : "Cancel", title : "Cancel", onClick : function(){closeHover("widgetAddress");}, style : "cursor:pointer;" },
					{ tag : "span", className : "btnBlueEnd"},
					{ tag : "input", name : "Submit", type : "button", className : "btnBlue", style: "margin-left:8px;cursor:pointer;", value : "Use this address", onClick : function(event){ chooseAddress();closeHover("widgetAddress");} },
					{ tag : "span", className : "btnBlueEnd" }
				] 
			}
		]			
};
// definition for error/info/warning bubble messages
var messages = {
	error :   { color : "#DF0000", background : "#FFE3E3"} ,
	info  :   { color : "#9ed1c1", background : "#e7f3f0" },
	warning : { color : "#FFAE30", background : "#FFF3DF"}
	
};
// temporary definition used for migrating objects for future use. Eventually depricate the above one.
var messagescolors = {
		error :   { color : "#DF0000", background : "#FFE3E3"} ,
		info  :   { color : "#9ed1c1", background : "#e7f3f0" },
		warn : { color : "#FFAE30", background : "#FFF3DF"}
		
	};
var messageskin = {
	tag : "div", id : "messageContainer", innerHTML : [
		{ tag : "div", className : "bubbleInner", style:"position:relative;", innerHTML : [
			{ tag : "img", src : "/images/app/c3plus/btnCloseBubble.jpg", alt : "Close", className : "cursor", style : "position:absolute;top:5px;right:5px;cursor:pointer;", onclick : function (event){ document.getElementById("messageContainer").parentNode.removeChild(document.getElementById("messageContainer")); } },
			{ tag : "div", style: "top:5px;left:12px;width:153px;", id : "messageBody" }
		]}
	]
}
/* function to test for which browser we are using, currently 
 * only tests for IE, but can expand it for later use to detect FF and other browsers
 */
function browserDetect(){
	var temp = "";
	var version = 0;
	if (navigator.appVersion.indexOf("MSIE")!=-1){
		temp=navigator.appVersion.split("MSIE");
		version= "IE" + parseFloat(temp[1]);
	}
	return version;
}
/* 
 * returns the version of IE for use of rendering objects based on which version the user has.
 */
function getIEVersion(){
  var rv = -1; // Return value assumes failure.
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}
/*
 * createHTML(obj, parent)
 * created by : Chris Williams
 * purpose : Allows the user to pass in a JSON Formated HTML declaration and it will dynamically
 * create the elements given the proper formating.  It recursively adds items to the parent.
 * example of proper dom obj:
 * var domObj = { tag : "div", innerHTML : "Hello", className : "someClass", style : "margin-top:10px" }
 */
function createHTML(obj, parent){
	// string node
	if(obj.constructor == String)
		return document.createTextNode(obj);	
	// has tag defined so create an element
	if(obj.tag){
		var tag = document.createElement(obj.tag);
		for (var key in obj){
			if(key != "tag"){
				if(key == "innerHTML"){
					var newobj = createHTML(obj[key], tag);
					if(newobj != tag)
						tag.appendChild(newobj);
				}else if(key == "style"){
					tag.style.cssText = obj[key];
				}else if(key == "value"){
					tag.setAttribute("value", obj.value);
				}else if(key == "onClick"){
					tag.onclick = obj[key];
				}else if(key == "onchange"){
					tag.onchange = obj[key];
				}else if(key == "onblur"){
					tag.onblur = obj[key];
				}else if(key == "onfocus"){
					tag.onfocus = obj[key];
				}else if(key == "onkeypress"){
					tag.onkeypress = obj[key];
				}else if(key == "readonly"){
					tag.setAttribute("readonly", obj[key]);
				}else{
					tag[key] = obj[key];
				}
			}
		}
		return tag;
	} else { 
		for (var x = 0; x < obj.length; x++)
			parent.appendChild(createHTML(obj[x], parent));	
		
		return parent;
	}
}
function selectDataRow(parent, tagname, obj, classname){
	resetClassVals(parent, tagname);
	obj.className = classname; 
	obj.style.backgroundColor = "#E6E6E6";
	selectedIndex = obj.index;
}
function resetClassVals(obj, tagname){
	var tags = obj.getElementsByTagName(tagname);
	for(var i =0; i < tags.length;i++){
		tags[i].style.backgroundColor = "#FFFFFF";
		tags[i].className = "";
	}
}
function handleQasResult(resultobj){
	
	if(resultobj.result.qasResult){
		var qasResult = resultobj.result.qasResult;
		var userContact = resultobj.result.userContact;
		rowObj.addresses = addresses;
		rowObj.monikers = qasResult.monikers;
		var cur_address = userContact.address + ", " + userContact.city + " " + userContact.stateName + " " +  userContact.zip;
	}else{
		var qasResult = resultobj.result;
		var userContact = qasResult.inputAddress;
		if(qasResult.addressTexts){
			monikers = qasResult.monikers;
		}
		var cur_address = userContact.addressLine + ", " + userContact.city + " " + userContact.stateName + " " +  userContact.postalCode;
	}		
	
	if(!qasResult.addressTexts){
		isEmptyQAS = true;
		chooseAddress(qasResult);
		return false;
	}else{
		showHover(null, "address");
		var obj = $get("addressContainer");
		obj.innerHTML = "";
	}
		
	var addresses = qasResult.addressTexts;
	var postalcodes = qasResult.postalCodes;

	var p = document.createElement("p");
	p.innerHTML = cur_address;
	p.className = "selectAddress";
	p.index = 0;
	p.onclick = function() { selectDataRow(this.parentNode, "p", this, "selectAddress"); }
	p.onmouseover = function() { this.style.backgroundColor = "#E6E6E6"; };
	p.onmouseout = function() { if(this.className != "selectAddress") { this.style.backgroundColor = "#FFFFFF";} };
		
	obj.appendChild(p)
	for(var x = 0; x < addresses.length; x++){
		var p = document.createElement("p");
		p.innerHTML = addresses[x] + " " + postalcodes[x];
		obj.appendChild(p);
		p.index = x + 1;
		p.onmouseover = function() { this.style.backgroundColor = "#E6E6E6"; };
		p.onmouseout = function() { if(this.className != "selectAddress") { this.style.backgroundColor = "#FFFFFF";} };
		p.onclick = function() { selectDataRow(this.parentNode, "p", this, "selectAddress");}
	}
	return true;
}
// functionName is the function to be called when the page counter is clicked
function getPageCounter(page,total,formattedTotal,perPage, functionName) {
  if( total == 0 ) return "";
  // figure out which elements are displayed
  var start = (page-1) * perPage + 1;
  var end = start + perPage-1;
  if( total - start < perPage )
    end = total;
//alert(page + "::" + start + "::" + end + "::" + total);
  // figure out how many pages and which ones
  var totalPages = parseInt((total-1) / perPage + 1);
  var numPages = totalPages;
  if( numPages > 5 )
	numPages = 5;
  var startPage = 1;
  var endPage = 5;
  if( page <= 3) {
    endPage = numPages;
  } else {
    startPage = page - 2;
    endPage = page + 2;
    if( startPage < 1 ) {
      startPage = 1;
      endPage = startPage + numPages - 1;
    }
    if( endPage >= totalPages) {
      endPage = totalPages;
      startPage = endPage - numPages + 1;
      if( startPage < 1 )
        startPage = 1;
    }
  }
  // Create the << and < arrows
  var result = "<strong>" + start + " - " + end + " of " + formattedTotal + "</strong>&nbsp;&nbsp;";
  if( page > 1 )
    result += "<a href='javascript:" + functionName +"(" + (page-1) + ")'>&lt;Previous</a>&nbsp;&nbsp;";
  else
    result += "<strong>Page&nbsp;</font></strong>";

  if( startPage > 1 )
    result += "<a href='javascript:"+ functionName +"(1)'>1</a>&nbsp;...&nbsp;";

  // Create the page numbers
  for (i = startPage; i <= endPage; i++) {
    if( i==page) result += "<font color='black'><strong>" + i + "</strong></font>";
    else
	  result += "<a href='javascript:" + functionName + "(" + i + ")'>" + i + "</a>";
    result += "&nbsp;";
    if( i < endPage )
      result += "|&nbsp;";
  }
//alert(page + "::" + startPage + "::" + endPage );

  // Create the > and >> arrows
  if( page < totalPages-2 )
    result += "...&nbsp;<a href='javascript:" + functionName + "(" + totalPages + ")'>" + totalPages + "</a>";
  if( page < totalPages ) {
      result += "<a href='javascript:" + functionName + "(" + (page+1) + ")'>&nbsp;Next></a>";
  }
  result += "</strong>";
  return result;
}

// Global functions to be put into a global library later.

function statusToString(status) {
  if( status == 0 ) return "";
  if( status == 1 ) return "15 Points - New Company";
  if( status == 2 ) return "5 Points";
  if( status == 4 ) return "In Jigsaw";
  if( status == 10 ) return "Banned";

  return "hello";
}

function countChecked(frmname, elemname){
	return getChecked(frmname, elemname).length;
}

function getChecked(frmname, elemname){
	var frm = document.forms[frmname];
	var elems = frm.elements;
	var len = frm.elements.length;
	var ids = [];
	for(var x=0; x<len; x++){
		if(elems[x].type == "checkbox"){
			if((elems[x].checked) && (elems[x].name != "deleteAll")){
				if(elemname != undefined){ // more accurate list
					if(elems[x].value.trim() != "" && (elems[x].name == elemname))
						ids.push(elems[x].value);
				}else{  // blanket list for all checkboxes
					if(elems[x].value.trim() != "")
						ids.push(elems[x].value);
				}
			}	
		}
	}
	return ids;
}

function checkAll(frmname, obj, ignoreChecked, elemname){
	var checkall = true;
	if(typeof obj != "undefined"){
		if(!obj.checked)
			checkall = false;
	}
	var frm = document.forms[frmname];
	var elems = frm.elements;
	var len = frm.elements.length;
	for(var x=0; x < len; x++){
		if(elems[x].type == "checkbox"){
			if(elemname != undefined){
				if(ignoreChecked){
					if(!checkall && (elemname == elems[x].name))
						elems[x].checked = checkall;
				}else{
					if(elemname == elems[x].name)
						elems[x].checked = checkall;	
				}
			}else{
				if(ignoreChecked){
					if(!checkall)
						elems[x].checked = checkall;
				}else{
					elems[x].checked = checkall;				
				}
			}
		}
	}
}
function checkAllBySection(id, obj){
	var checkall = true;
	if(typeof obj != "undefined"){
		if(!obj.checked)
			checkall = false;
	}
	var inputs = $get(id).getElementsByTagName("input");
	var len = inputs.length;
	for(var x=0; x < len; x++){
		if(inputs[x].type == "checkbox"){
			inputs[x].checked = checkall;
		}
	}
}
function checkAllBySectionLink(id, checkall){
	var inputs = $get(id).getElementsByTagName("input");
	var len = inputs.length;
	for(var x=0; x < len; x++){
		if(inputs[x].type == "checkbox" && inputs[x].disabled == false){
			inputs[x].checked = checkall;
		}
	}
}
/* function to get the checked value of the radio group
 *  TODO: Chris W. - Make a form Object to do all of these functions.
 */
 function getCheckedObj(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i];
		}
	}
	return "";
}
function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	
	return getCheckedObj(radioObj).value;
}

/* 
 * Fixes the length of any string provide the string and max length
 */
function fixLength(str, maxLimit){
  if( str == null || str.trim() == "")
	return "&nbsp;";
  if (str.length > maxLimit) {
    return str.substring(0, maxLimit) + "&hellip;";
  }
  return str;
}

function getStatusIcon(status, ready, locked, statusId) {
  if(statusId && statusId == "SUPPRESSED")
  	return "<div class='suppressedIcon fRight' style='width:15px;' title='This Contact can not be added to Jigsaw at this time.'></div>"
  if(locked)
  	return "<img src='/images/app/lock.gif' alt='This Contact can not be added to Jigsaw at this time.' />";
  if( status == 10 )
    return("<img src='/images/app/c3plus/icon-banned.gif'/>");
  else if( (status == 4) && (ready == 1))
    return "<img src='/images/app/c3plus/green_check.gif'/>&nbsp; <img src='/images/app/c3plus/icon-in.gif'/> ";
  else if( status == 4)
    return "<img src='/images/app/c3plus/icon-in.gif'/>    ";  
  else if( (status == 2) && (ready == 1))
    return " <img src='/images/app/c3plus/green_check.gif'/>&nbsp; <img src='/images/app/c3plus/icon-5.gif'/>";              
  else if( status == 2)
    return "<img src='/images/app/c3plus/icon-5.gif'/>   ";
  else if ( (status == 1) && (ready == 1))
    return " <img src='/images/app/c3plus/green_check.gif'/>&nbsp; <img src='/images/app/c3plus/icon-10.gif'/>";  
  else if( status == 1)
    return "<img src='/images/app/c3plus/icon-10.gif'/>   ";    
  else
    return "&nbsp;";
}
function checkSessionTimeout(sessionInfo,targetURL) {
  if(sessionInfo.sessionCode == 0)
	return false; 

  window.location = serverURL + "/Login.xhtml?targetURL=" + targetURL; 
  return true;
}

var tempobj = new Object();
function findPos(obj) {
	tempobj = obj;
	var curleft = 0;
	var curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while ((obj = obj.offsetParent) && (obj.style.position != "relative")) {	
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}
var __isFireFox = navigator.userAgent.match(/gecko/i);
//returns the absolute position of some element within document
function GetElementAbsolutePos(element) {
	var res = new Object();
	res.x = 0; res.y = 0;
	if (element !== null) {
		res.x = element.offsetLeft; 
		res.y = element.offsetTop; 
    	
		var offsetParent = element.offsetParent;
		var parentNode = element.parentNode;

		while (offsetParent !== null) {
			res.x += offsetParent.offsetLeft;
			res.y += offsetParent.offsetTop;

			if (offsetParent != document.body && offsetParent != document.documentElement) {
				res.x -= offsetParent.scrollLeft;
				res.y -= offsetParent.scrollTop;
			}
			//next lines are necessary to support FireFox problem with offsetParent
			if (__isFireFox) {
				while (offsetParent != parentNode && parentNode !== null) {
					res.x -= parentNode.scrollLeft;
					res.y -= parentNode.scrollTop;
					
					parentNode = parentNode.parentNode;
				}    
			}
			parentNode = offsetParent.parentNode;
			offsetParent = offsetParent.offsetParent;
		}
	}
    return res;
}

function getTopLeft(e){
	var posx=0,posy=0;
	if(e==null) e=window.event;
	if(e.pageX || e.pageY){
	 	posx=e.pageX; posy=e.pageY;
 	}
	else if(e.clientX || e.clientY){
 		if(document.documentElement.scrollTop){
 			posx=e.clientX+document.documentElement.scrollLeft;
 			posy=e.clientY+document.documentElement.scrollTop;
 		}
 		else{
 			posx=e.clientX+document.body.scrollLeft;
 			posy=e.clientY+document.body.scrollTop;
 		}
 	}
	return { top : posy, left : posx }
	// document.getElementById("btc").style.top=(posy+10)+"px";
	// document.getElementById("btc").style.left=(posx-20)+"px";
}
// Dom functions
function getElement(event){
	if (!event) var event = window.event;
	if (event.target) var elem = event.target;
	else if (event.srcElement) var elem = event.srcElement;
	if (elem.nodeType == 3) // defeat Safari bug
		elem = elem.parentNode;
	return elem;
}
function getNextSibling(obj){
	var sibling = obj;
	while(sibling.nextSibling){
		sibling = sibling.nextSibling;
		if(sibling.nodeType != 3)
			return sibling;			
	}	
	return sibling;
}
function getPrevSibling(obj){
	var sibling = obj;
	while(sibling.prevSibling){
		sibling = sibling.prevSibling;
		if(sibling.nodeType != 3)
			return sibling;			
	}	
	return sibling;
}
function getParent(obj){
	var parent = obj;
	while(parent.parentNode){
		parent = parent.parentNode;
		if(parent.nodeType != 3)
			return parent;
	}
	return parent;
}
function updateMeritBadge() {
  UserAPI.getMeritBadge(uid, handleUpdateMeritBadge);
}

function handleUpdateMeritBadge(AjaxResult) {
  if( checkSessionTimeout(AjaxResult,targetURL)) return;
  if( AjaxResult.statusCode == RESULT_FAILURE) return;
  var meritbadge = document.getElementById("meritbadge");
  meritbadge.innerHTML = AjaxResult.result;
}

function getFieldByName(parent, name, tagname){
	var tags = parent.getElementsByTagName(tagname);
	for(var i = 0; i < tags.length; i++)
		if(tags[i].name == name)
			return tags[i];
	
	return false;
}
function $get(id){
	return document.getElementById(id);
}

function showSelects(obj){
	if(obj){
		var selects = obj.getElementsByTagName("select");
		for(var i = 0; i < selects.length; i++){
			selects[i].style.visibility = "visible";
		}
	}
}
function hideSelects(obj){
	if(obj){
		var selects = obj.getElementsByTagName("select");
		for(var i = 0; i < selects.length; i++){
			selects[i].style.visibility = "hidden";
		}
	}
}
function hideFlashObjects(obj){
	if(obj){
		var objects = obj.getElementsByTagName("object");
		for(var i = 0; i < objects.length; i++){
			objects[i].style.visibility = "hidden";
		}
	}
}
function showFlashObjects(obj){
	if(obj){
		var objects = obj.getElementsByTagName("object");
		for(var i = 0; i < objects.length; i++){
			objects[i].style.visibility = "visible";
		}
	}
}
function addStatusBox(){
	var div = document.createElement("div");
	div.id = "jigsaw_status";
	var div_content = document.createElement("div");
	div_content.id = "jigsaw_status_message";
	div.appendChild(div_content);
	if(document.body)
		document.body.appendChild(div);
	else if(document.documentElement)
		document.documentElement.appendChild(div);
}
// fading functions
var jigsaw_status_shown = false;
function opacity(id, opacStart, opacEnd, millisec) {
    //speed for each frame
    var speed = Math.round(millisec / 100);
    var timer = 0;

    //determine the direction for the blending, if start and end are the same nothing happens
    if(opacStart > opacEnd) {
        for(i = opacStart; i >= opacEnd; i--) {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
        $get("jigsaw_status").style.display = "none";
    } else if(opacStart < opacEnd) {
    	$get("jigsaw_status").style.display = "block";
        for(i = opacStart; i <= opacEnd; i++)
            {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    }
}

//change the opacity for different browsers
function changeOpac(opacity, id) {
    var object = $get(id).style;
    object.opacity = (opacity / 100);
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
    object.filter = "alpha(opacity=" + opacity + ")";
} 
function hideStatus(){
	opacity("jigsaw_status", 100, 0, 800);
	jigsaw_status_shown = false;
}

// login hover code
function showLoginHover(){
	showMaskedHover("signIn");
	getFormElement("LoginForm", "email").focus();
}
// get form by name or id
function getForm(name) {
	if($get(name)){
		return $get(name);
	}else{
		return document.forms[name];
	}
}
function getFormElement(formName, formElement){
	if(getForm(formName).elements[formElement])
		return getForm(formName).elements[formElement];
	else
		return null;
}
/* Universal form submission function
 * Function : subForm(args)
 * Description: Allows for multiple objects passed as args that if submitting a form the values can be
 * passed to change them before form submission.
 * Also gets the form needed to submit by passing either form name or id referencing form
 * Usage: subform(["formname", {name : fieldname, value : value}, {object same as last}]);
 * Expects: args[0] must equal the form name or id to the form.  args listed after that are optional, 
 * but must be in the format {name : fieldname, value : fieldvalue }, where fieldname is of type string and
 * fieldvalue can be a string or number.
 */
function subForm(args){
	if(typeof(args) == "string"){
		var form = getForm(args);
	}else{
		var form = getForm(args[0]);
		
		for(var i=1;i<args.length;i++){
			form.elements[args[i].name].value = args[i].value; 
		}
	}
	form.submit();
}
/*
 * Used for buttons across the site where we only want the user to click once
 */
function safeSubForm(args){
	if(!buttonClicked){
		buttonClicked = true;
		subForm(args);
	}
}
/*
 * Convert form dom object to Json object
 */
function convertForm(form){
	var tempform = new Object();
	var inputs = form.getElementsByTagName("input");
	var selects = form.getElementsByTagName("select");
	var textareas = form.getElementsByTagName("textarea");
	var jsonString = "";
	for(var i = 0; i < inputs.length; i++){
		if(inputs[i].value == "null")
			inputs[i].value = "";
		
		if(inputs[i].type == "text" || inputs[i].type == "hidden"){
			if(inputs[i].name != ""){
				jsonString += "\"" + inputs[i].name + "\" : \"" + inputs[i].value + "\"";
				if(i < (inputs.length - 1))
					jsonString += ", ";
			}
		}
		if(inputs[i].type == "checkbox") {
			// define when its needed
		}
	}
	for(var i = 0; i < textareas.length; i++){
		if(textareas[i].value == "null")
			textareas[i].value = "";
		
		if(textareas[i].name){
			jsonString += "\"" + textareas[i].name + "\" : \"" + textareas[i].value + "\"";
			if(i < (textareas.length - 1))
				jsonString += ", ";
		}
	}
	for(var i = 0; i < selects.length; i++){
		if(selects[i].name && selects[i].selectedIndex != -1){
			if(!(jsonString.substring(jsonString.length -2) == ", "))
				if(jsonString != "")
					jsonString += ", ";
		
			jsonString += "\"" + selects[i].name + "\" : \"" + selects[i].options[selects[i].selectedIndex].value + "\"";
			if(i < (selects.length - 1))
				jsonString += ", ";
		}
	}
	if(jsonString.substring(jsonString.length -2) == ", ")
		jsonString = jsonString.substring(0, jsonString.length -2);
	
	return eval( "({"+ jsonString + "})");
	// return tempform;
}
function disableForm(id){
	var formcontainer = $get(id);
	var inputs = formcontainer.getElementsByTagName("input");
	var selects = formcontainer.getElementsByTagName("select");
	var textarea = formcontainer.getElementsByTagName("textarea");
	
	for(var i=0;i< inputs.length;i++){
		inputs[i].disabled=true;
	}
	for(var i=0;i<selects.length;i++){
		selects[i].disabled=true;
	}
	for(var i=0;i<textarea.length;i++){
		textarea[i].disabled=true;
	}
}
function enableForm(id){
	var formcontainer = $get(id);
	var inputs = formcontainer.getElementsByTagName("input");
	var selects = formcontainer.getElementsByTagName("select");
	var textarea = formcontainer.getElementsByTagName("textarea");

	for(var i=0;i< inputs.length;i++){
		if(inputs[i].name != "email" && inputs[i].name != "website")
			inputs[i].disabled=false;

	}
	for(var i=0;i<selects.length;i++){
		selects[i].disabled=false;
	}
	for(var i=0;i<textarea.length;i++){
		textarea[i].disabled=false;
	}
}
/* 
 * Function to do the same as safeSubForm, but for forms without a form name
 */
function clickOnce(obj){
	if(buttonClicked == false){
		buttonClicked = true;
		obj.form.submit();
	}else{
		return false;
	}
}
/* expand and collpase text blocks with clickable icon
The expander div is assigned two classes, one for styles and the other as a display state
The states are "open" and "closed"
example: <div class="expander open">, <div class="expander closed">
This allows the same code to be used if the block is displayed open or closed by default
*/

function expander(obj) {
//determine if the block is open or closed
var displayState = obj.parentNode.className.slice(9); 
//identify the icon to change
var icon = obj.parentNode.getElementsByTagName("a")[0];
//identify the text to display
var displayBlock = obj.parentNode.getElementsByTagName("div")[0];
if (displayState == "open") {
	displayBlock.style.display = "none";
	icon.style.backgroundPosition = "0 0";
	obj.parentNode.className = "expander closed";
	}
else if (displayState == "closed") {
	displayBlock.style.display = "block";
	icon.style.backgroundPosition = "0 -17px";
	obj.parentNode.className = "expander open";
	}
}
function gotoURL(url){
	document.location.href = url;
}
// deprecated use the cssCenterObject function.
function centerObjectInWindow(obj, override_top){
	var w_height = getViewportHeight();
	var w_width = getViewportWidth();
	w_width = w_width - 200; // adjustment to fix css issues
	var mid_h = w_height / 2;
	var mid_w = w_width / 2;
	var obj_off_w = obj.offsetWidth;
	var obj_off_h = obj.offsetHeight;
	
	if(override_top)
		obj.style.top = override_top + "px";
	else
		obj.style.top = (mid_h - (obj_off_h/2)) + "px";
		
	obj.style.left = (mid_w - (obj_off_w/2)) + "px";
}
function hideObject(id){
	$get(id).style.display = "none";
}
function disableFields(obj){
	var inputs = obj.getElementsByTagName("input");
	var selects = obj.getElementsByTagName("select");
	for(var i=0;i<inputs.length;i++){
		inputs[i].disabled = true;
	}
	for(var x=0;x<selects.length;x++){
		selects[x].disabled = true;
	}
}
function enableFields(obj){
	var inputs = obj.getElementsByTagName("input");
	var selects = obj.getElementsByTagName("select");
	for(var i=0;i<inputs.length;i++){
		inputs[i].disabled = false;
	}
	for(var x=0;x<selects.length;x++){
		selects[x].disabled = false;
	}
}
/*
 * This function allows you to clone an object and make it its own object not a reference to the object.
 * usage: var obj = new ClonedObject( Object, newid);
 */
ClonedObject = function( obj, id) {
  var that = obj.cloneNode(true); // clone the div, it'll be our new object
  that.id = id;
  return(that);
}
/*
 * Function : setObjBorder
 * Description : Takes a resultobj from an Ajax object and sets the border based on its error/warning's being set;
 * It takes 2 parameters the id of the form field to manipulate and the obj of the data to look through
*/
function setObjBorder(id, resultobj, formName){
	if(id == "" || typeof(id) == "undefined")
		return false;
	if(formName)  // code change to make it modular for all forms
		var obj = getFormElement(formName, id);
	else
		var obj = $get(id);
		
	var target = obj;
	if(obj.tagName.toLowerCase() == "select"){
		target = obj.parentNode;
	}	
	if(resultobj.errors != undefined)
		var err_len = resultobj.errors.length;
	else
		var err_len = 0;
	
	if(resultobj.warnings != undefined)
		var warn_len = resultobj.warnings.length;
	else
		var warn_len = 0;
	
	var type = "";
	for(var x = 0; x < warn_len; x++){
		if(obj.name.replace("Code", "") == resultobj.warnings[x].field && resultobj.warnings[x].message != ""){
			type = "warning";
		}
	}
	for(var x = 0; x < err_len; x++){
		if(obj.name.replace("Code", "") == resultobj.errors[x].field && resultobj.errors[x].message != ""){
			type = "error";
		}
	}
	if(type == ""){
		if(obj.tagName.toLowerCase() == "select"){
			target.style.borderColor = "#FFFFFF";
			target.style.borderStyle = "solid";
			target.style.borderWidth = "2px";
		}else{
			target.style.borderColor = "";
			target.style.borderStyle = "";
			target.style.borderWidth = "";
		}
		return false;
	}
	target.style.borderColor = messages[type].color;
	target.style.borderStyle = "solid";
	target.style.borderWidth = "2px";
	return type;
}
/*
 * Function : setObjBorder
 * Description : Takes a resultobj from an Ajax object and sets the border based on its error/warning's being set;
 * It takes 2 parameters the id of the form field to manipulate and the obj of the data to look through
*/
function setMessagingBorder(id, messagelist, formName){
	if(id == "" || typeof(id) == "undefined")
		return false;
	if(formName)  // code change to make it modular for all forms
		var obj = getFormElement(formName, id);
	else
		var obj = $get(id);
		
	var target = obj;
	var field = obj.name.replace("Code","");
	if(obj.tagName.toLowerCase() == "select"){
		target = obj.parentNode;
	}	
	type = messagelist.getType(field);
	if(type == ""){
		if(obj.tagName.toLowerCase() == "select"){
			target.style.borderColor = "#FFFFFF";
			target.style.borderStyle = "solid";
			target.style.borderWidth = "2px";
		}else{
			target.style.borderColor = "";
			target.style.borderStyle = "";
			target.style.borderWidth = "";
		}
		return false;
	}
	target.style.borderColor = messagescolors[type].color;
	target.style.borderStyle = "solid";
	target.style.borderWidth = "2px";
	return type;
}
function getViewportHeight() {
	if (window.innerHeight!=window.undefined) return window.innerHeight;
	if (document.compatMode=='CSS1Compat') return document.documentElement.clientHeight;
	if (document.body) return document.body.clientHeight; 
	return window.undefined; 
}
function getViewportWidth() {
	if (window.innerWidth!=window.undefined) return window.innerWidth; 
	if (document.compatMode=='CSS1Compat') return document.documentElement.clientWidth; 
	if (document.body) return document.body.clientWidth; 
	return window.undefined; 
}
/*
 * function to make sure a text area doesn't exceed the max amount of chars allowed.
 */
function checkMaxChars(obj, max){
	if(obj.textLength > max){
		obj.value = obj.value.substring(0,max);
	}
}
function hideHover(id){
	var body = getDocumentBody();
	if($get(id).style.display == "none")
		return;
	
	$get(id).style.display="none";

	if($get("overlay"))
		$get("overlay").style.display="none";
		
	body.style.overflow = "auto";
	
	if($get('jigsawBody')){
		showSelects($get('jigsawBody'));
		showFlashObjects($get('jigsawBody'));
	}
}
function hideMessage(type){
	switch(type){
	case "error":
		if($get("msgError")){
			$get("msgError").style.display = "none";
			return true;
		}
		break;
	case "confirm":
		if($get("msgConfirm")){
			$get("msgConfirm").style.display = "none";
			return true;
		}
		break;
	case "info":
		if($get("msgInformation")){
			$get("msgInformation").style.display = "none";
			return true;
		}
		break;
	case "warn":
		if($get("msgWarning")){
			$get("msgWarning").style.display = "none";
			return true;
		}
		break;
	}
}
function createMessage(type, message){
	hideMessage("error");
	hideMessage("confirm");
	hideMessage("warn");
	hideMessage("info");
	var displaystyle = "table";
	if(ieVersion == 7){
		displaystyle = "block";
	}
	var messageContainer = $get("jigsawMessaging");
	var div ={};
	var div2 = {};
	switch(type){
	case "error":
		if($get("errorContainer")){
			$get("errorContainer").innerHTML = message;
			$get("msgError").style.display = displaystyle;
			return true;
		}
		div = document.createElement("div");
		div.id="msgError";
		div2 = document.createElement("div");
		div2.id="errorContainer";
		break;
	case "confirm":
		if($get("msgConfirm")){
			$get("confirmContainer").innerHTML = message;
			$get("msgConfirm").style.display = displaystyle;
			return true;
		}
		div = document.createElement("div");
		div.id="msgConfirm";
		div2 = document.createElement("div");
		div2.id="confirmContainer";
		break;
	case "info":
		if($get("msgInformation")){
			$get("informationContainer").innerHTML = message;
			$get("msgInformation").style.display = displaystyle;
			return true;
		}
		div = document.createElement("div");
		div.id="msgInformation";
		div2 = document.createElement("div");
		div2.id="informationContainer";
		break;
	case "warn":
		if($get("msgWarning")){
			$get("warningContainer").innerHTML = message;
			$get("msgWarning").style.display = displaystyle;
			return true;
		}
		div = document.createElement("div");
		div.id="msgWarning";
		div2 = document.createElement("div");
		div2.id="warningContainer";
		break;
	}
	if(div){
		div2.innerHTML = message;
		div.appendChild(div2);
		messageContainer.appendChild(div);
	}
}
/* new updated modular message function replace showErrorWarnBubble in businessCard.js 
 * when we have time.
 */
IEoffsetTop = -10;
adjustmentLeft = 333;
var defaultPlacement = "main";
var adjustmentTopSide = 15;
function showBubbleMessage(obj, message, placement, type, left, top){
	var position = findPos(obj);
	
	if(left){
		position[0] = left;
	}
	if(top){
		position[1] = top;
	}
	if(!$get("messageContainer"))
		var msgObj = createHTML(messageskin);
	else 
		var msgObj = $get("messageContainer");
	
	var btype = type;
	if(type == "warn"){
		btype = "warning";
	}
	msgObj.className = btype + placement + " bubble"; 
	msgObj.style.position = "absolute";
	$get(defaultPlacement).appendChild(msgObj);
	$get("messageBody").innerHTML = message;
	
	if(placement == "Bottom"){
		msgObj.style.top = (position[1] + 25) + "px";
		msgObj.style.left = (position[0]) + adjustmentLeft + "px";
	}else if(placement == "Side"){
		msgObj.style.top = (position[1] + adjustmentTopSide) + "px";
		if(!left)
			msgObj.style.left = (position[0] - msgObj.offsetWidth) + adjustmentLeft + "px";
		else
			msgObj.style.left = (position[0]) + "px";
	}else{
		msgObj.style.left = (position[0]) + adjustmentLeft + "px";
	}
	msgObj.style.zIndex = "5000";
	
	
	if(placement == "Top"){
		if(IE)
			position[1] = position[1] + IEoffsetTop;
			
		msgObj.style.top = (position[1] - msgObj.offsetHeight) + "px";
				
	}
}
function getMessageType(obj){
	for(i in errorList){
		if(errorList[i].field == obj.name && errorList[i].message != "")
		return "error";
	}
	for(i in warningList){
		if(warningList[i].field == obj.name && warningList[i].message != "")
		return "warning";
	}
	for(i in infoList){
		if(infoList[i].field == obj.name && infoList[i].message != "")
		return "info";
	}
	return "";
}
function showMessage(obj, left, top, align){
	hideBubble();
	var type = getMessageType(obj);  //obj.className.replace(/Top/i, "").replace(/Bottom/i, "").replace(/Side/i, "");
	if(type == "")
		return;
		
	var message = "";
	if(type == "info"){
		for(i in infoList){
			if(infoList[i].field == obj.name)
				message = infoList[i].message;
		}
	}
	if(type == "warning"){
		for(i in warningList){
			if(warningList[i].field == obj.name)
				message = warningList[i].message;
		}
	}
	if(type == "error"){
		for(i in errorList){
			if(errorList[i].field == obj.name)
				message = errorList[i].message;
		}
	}
	if(align == null)
		var alignment = "Top";
	else 
		var alignment = align;
	if((type == "warning" || type == "error" || type == "info") && message != "")
		showBubbleMessage(obj, message , alignment, type, left, top);
}
/* End new bubble message functions */
function isFunction(fn) {
  if(typeof fn != "function") return false;
  if(typeof fn.constructor != "function") return false;
  return fn.constructor.prototype.hasOwnProperty( "call" );
}
function getElementWidth(elem){
	return elem.offsetWidth;
}
/* function to write a flash object to the page and not cause that IE double click issue for flash objects. */
function flashObject(url,id,height,width,wmode,color,eid){
	this.url=url;
	this.id=id;
	this.eid=eid;
	this.height=height;
	this.width=width;
	this.color=color;
	this.wmode=wmode;
	this.type="application/x-shockwave-flash";
	this.variables=new Array();
	this.params=new Array();
	flashObject.prototype.addVariable=function(name,value){
		this.variables.push({"name":name,"value":value})};
	flashObject.prototype.addParam=function(name,value){
		this.params.push({"name":name,"value":value})};
	flashObject.prototype.writeobj=function(id){
		str='<object id="'+this.id+'" width="'+this.width+'" height="'+this.height+'" >';
		for(j in this.params){
			str+='<param name="'+this.params[j].name+'" value="'+this.params[j].value+'" ></param>'
		}
		str+='<embed src="'+this.url+'" id="'+this.eid+'" width="'+this.width+'" height="'+this.height+'" wmode="'+this.wmode+'" type="application/x-shockwave-flash" ></embed>';
		str+="</object>";
		document.write(str)
	}
	flashObject.prototype.returnobj=function(id){
		str='<object id="'+this.id+'" width="'+this.width+'" height="'+this.height+'" >';
		for(j in this.params){
			str+='<param name="'+this.params[j].name+'" value="'+this.params[j].value+'" ></param>'
		}
		str+='<embed src="'+this.url+'" id="'+this.eid+'" width="'+this.width+'" height="'+this.height+'" wmode="'+this.wmode+'" type="application/x-shockwave-flash" ></embed>';
		str+="</object>";
		return str;
	}
}
function hideBubble(){
	if(document.getElementById("messageContainer")){
		var msgContainer = $get("messageContainer");
		var par_msgContainer = msgContainer.parentNode;
		par_msgContainer.removeChild(msgContainer);
	}
}
function fixMultiSelect(obj){
	var numSelected = 0;
	for (i=0; i < obj.length; i++){
		if(obj.options[i].selected){
		numSelected++;
		}
	}
	if(numSelected > 1)
		obj.options[0].selected = false;
		
}
function showWebsite(url) {
    if (url.indexOf("http://") == -1) url = "http://" + url;
    window.open (url);
}

function showExtHelp (url, width, height, top, left, windowname) {
    
    if (windowname == null) windowname = "Help";
    var pWidth = width == null ? 810 : width;
    var pHeight = height == null ? 800 : height;
    if (left == null) left =  (screen.width - pWidth) / 2;
    if (top == null) top =  (screen.height - pHeight) / 2;
    var args = "width=" + pWidth + ",height=" + pHeight + ",top=" + top + ",left=" + left + ",scrollbars=yes" + ",resizable=yes";
    pWindow = window.open(url, windowname, args);
}

function showHelp (fileName) {
	var slashHelp = "/";
	if(serverURL.lastIndexOf("/") == (serverURL.length - 1))
		slashHelp = "";
    if (fileName == null || fileName == "") fileName = "Help.html";
    helpWindow = window.open (serverURL + slashHelp + "help/" + fileName, 'Help', "left=400,top=0,toolbar=yes,scrollbars=yes,menubar=yes,resizable=yes,location=yes,status=yes,height=575,width=700");
    try {
        helpWindow.focus();
    } catch (e) {
    
    }  
}

function showHelpPage (fileName) {
	var slashHelp = "/";
	if(serverURL.lastIndexOf("/") == (serverURL.length - 1))
		slashHelp = "";
    if (fileName == null || fileName == "") fileName = "Help.html";
    helpWindow = window.open (serverURL + slashHelp + fileName, 'Help', "left=400,top=0,toolbar=yes,scrollbars=yes,menubar=yes,resizable=yes,location=yes,status=yes,height=575,width=720");
    try {
        helpWindow.focus();
    } catch (e) {
    
    }  
}

function showHelpPopup(url, width, height) {
    url = serverURL + url;
    if (width == null) width = 500;
    if (height == null) height = 400;
    window.open (url, 'Help', "left=400,top=0,toolbar=no,scrollbars=yes,menubar=no,resizable=yes,location=no,status=yes,height="+height+",width="+width);
}
// jigsaw_03_01.js functions

var IE = navigator.appName.indexOf("Microsoft") != -1;
var DOM = document.getElementById;
var is_mac = navigator.userAgent.toLowerCase().indexOf("mac") != -1;
var jigsawWindow = true;
var helpWindow;
var pWindow;
var timeoutId = null;
var darkblue = "#002D60";
//var darkblue = "#666666";

var lightblue = "#DFEAF4";

function setPopupTimeout() {
    setTimeout("testPopup()",700);
}

function testPopup () {
    timeoutId = null;
    if ((pWindow==null) ||(typeof(pWindow)=="undefined") || (typeof(pWindow.location.hash)!="string"))
        alert("You must disable your popup killer to use this feature of Jigsaw.");
}

function makeLink (innerText, href) {
	var link = document.createElement("a");
	var textNode = document.createTextNode(innerText);
	link.style.whiteSpace = "nowrap";
	if (href != null && trim(href) != "")
	    link.href = href;
	
	link.appendChild (textNode);
	return link;	
}

function removeChildren (elem) {
    if (elem == null || elem.childNodes == null || !elem.childNodes.length) return;
    var len = elem.childNodes.length - 1;
    for (var i = len; i >= 0; i--) {
        elem.removeChild(elem.childNodes[i]);
    }
}

function showObject (object, show, visibilityOnly) {
	if (object == null) return;
	if (visibilityOnly == null) visibilityOnly = false;
	if (show) {
		object.style.visibility = "visible";
		if (!visibilityOnly) object.style.display = "block";
	} else {
		object.style.visibility = "hidden";
		if (!visibilityOnly) object.style.display = "none";
	}
}

function getInnerText (elem) {
	if (IE) return elem.innerText;
	var children = elem.childNodes;
	for (var i = 0; i < children.length; i++) {
		var child = children[i];
		if (child.nodeType == 3) return child.data;
	}
		
}

function setInnerText (elem, text) {
	if (elem == null) return;
	if (IE) elem.innerText = text;
	else {
	    var hasTextNode = false;
		var children = elem.childNodes;
		for (var i = 0; i < children.length; i++) {
			var child = children[i];
			if (child.nodeType == 3) {
			    child.data = text;
			    hasTextNode = true;
			    break;
			}
		}
		if (!hasTextNode) {
		    var textNode = document.createTextNode(text);
		    elem.appendChild (textNode);  
		}
	}	
}

function $get (id) {
    var elem = null
    if (DOM) {
           elem = document.getElementById (id);
    } else if (IE) {
        elem = document.all[id];
    }
    return elem;
}

function addEventHandler (obj, ev, handler) {
	if (IE) 
		obj.attachEvent (ev, handler);
	else {
		obj.addEventListener (ev, handler, false);
	}
}

function getArgs() {
	var args = new Object();
	var query = location.search.substring(1);
	var pairs = query.split("&");
	for (var i = 0; i < pairs.length; i++) {
		var pos = pairs[i].indexOf('=');
		if (pos == -1) continue;
		var argname = pairs[i].substring (0,pos);
		var value = pairs[i].substring (pos+1);
		args[argname] = unescape(value);
	}
	return args;
}

//override this within a page to show context-sensitive help
var helpAnchor = 'top';
var problemWindow;

function reportCompanyProblem (url, id) {
    url = url + (url.indexOf('?') == -1 ? "?" : "&" ) + "id=" + id;
    var args = "toolbar=no,scrollbars=yes,menubar=no,resizable=yes,location=no,status=no,height=800,width=800";
    var left =  150;
    var top = 150;
    args += ",top=" + top + ",left=" + left;
    problemWindow = window.open (url, 'Problem', args);
    try {
        problemWindow.focus();
    } catch (e) {
    
    }  
}

function reportContactProblem (url, id) {
    url = url + (url.indexOf('?') == -1 ? "?" : "&" ) + "id=" + id;
    var args = "toolbar=no,scrollbars=no,menubar=no,resizable=yes,location=no,status=no,height=475,width=575";
    var left =  (screen.width - 475) / 2;
    var top =  (screen.height - 575) / 2;
    args += ",top=" + top + ",left=" + left;
    problemWindow = window.open (url, 'Problem', args);
    try {
        problemWindow.focus();
    } catch (e) {
    
    }  
}


function showUploadHelp (anchor) {
    helpWindow = window.open ("help/UploadHelp.html#" + anchor, 'Help', "toolbar=yes,scrollbars=yes,menubar=yes,resizable=yes,location=yes,status=yes,height=500,width=700");
    try {
        helpWindow.focus();
    } catch (e) {
    
    }    
}

function doClear (form) {
    if (form == null) form = document.forms[0];
    if (form == null) return;
    for (var i = 0; i < form.elements.length; i++) {
        var field = form.elements[i];
        if (field.type != 'hidden') {
            if (field.type == 'select-one') {
                field.selectedIndex = 0;
            } else if (field.type == 'text') {
                field.value = "";
            } else if (field.type == 'checkbox') {
                field.checked = false;
            }
        }
    }
}

function validateField (field, fieldname) {
    var msg = "";
    if (field.value == null || trim(field.value) == "") {
        firstField = firstField == null ? field : firstField;
        msg += "\n-" + fieldname;
    }
    return msg;
}

function trim(s) {
    if (s == null || s == "") return "";
    return ltrim(rtrim(s));
}

function ltrim(s) {
	var re = /^\s */;
	return s.replace(re, '');
}

function rtrim(s) {
	var re = /\s *$/;
	return s.replace(re, '');
}

function setSelectValue(select, value) {
    if (select == null) return;
    if (!is_mac) {
        select.value = value;
        return;
    }
    for (var i = 0; i < select.options.length; i++) {
        if (select.options[i].value == value)
              select.options[i].selected = true;
    }
    
}
function isValid (s) {
    if (s != null && trim(s) != "")
        return true;
}

function js_encodeURIComponent (s) {
    if (typeof encodeURIComponent == "function") {
		return encodeURIComponent(s);
	}
	else {
		return escape(s);
	}
}

function isValidDate(s) {
    if (s == "") return true;
    var datearr = s.split("/");
    if( datearr.length != 3 ) {
    	return false;
    }
    var month = datearr[0];
    var day = datearr[1];
    var year = datearr[2];
    if( !isValidDay(day,month,year)) {
    	return false;
    }
    return true; 
}

function dayExists (s) {
    if (s == "") return true;
    var nums = s.split('/');
    if (nums.length != 3) return false;
    var month = nums[0] * 1;
    if (month < 1 || month > 12) return false;
    var year = nums[2] * 1;
    var day = nums[1] * 1;
    if (!isValidDay (day, month, year)) return false;
    return true;
}

function isValidDay (day, month, year) {
	if( month < 1 || month > 12) return false;
	if( year < 1970 || year > 2030) return false;
    if (day < 1) return false;
    var numDays = 31;
    if (month == 2) {
        numDays = isLeapYear(year) ? 29 :28;
    }
    if (month == 4 || month == 6 || month == 9 || month == 11) {
        numDays = 30;
    }
    return day <= numDays;
}

function isLeapYear(year) {
    return (year - 2000) % 4 == 0;
}

function isAfter(d1, d2) {
    //returns true if day 1 comes after day 2
    var nums1 = d1.split('/');
    if (nums1.length != 3) return false;
    var nums2 = d2.split('/');
    if (nums2.length != 3) return false;
    var month1 = nums1[0] * 1;
    var year1 = nums1[2] * 1;
    var day1 = nums1[1] * 1;
    
    var month2 = nums2[0] * 1;
    var year2 = nums2[2] * 1;
    var day2 = nums2[1] * 1;
    
    if (year1 > year2) {
        return true;
    } else if (year1 < year2) {
        return false;
    } else if (month1 > month2) {
       return true;
    } else if (month1 < month2) {
        return false;
    } else if (day1 > day2) {
        return true;
    } else return false;
    
}
function goURL(newUrl){
	document.location.href = newUrl;
}
function changeImage(obj, keyword1, keyword2, func){
	var src = obj.src;
	if(src.search(keyword1) != -1){
		src = src.replace(keyword1, keyword2);
	}else{
		src = src.replace(keyword2, keyword1);
	}
	obj.src = src;
}
var defaultText = "Example: cisco.com";
function searchText(obj, isFocus, specialText) {
	var text = defaultText;
	
	if(specialText)
		text = specialText;
  
  	if(obj.value != text)
  		obj.style.color="#000000";obj.style.fontStyle="normal";
  		
  	if((obj.value == text) || (isFocus && obj.value.trim() == "")) {
   		obj.style.color="#000000";obj.style.fontStyle="normal";obj.value='';
  	}else if(obj.value==''){
   		obj.style.color="#CCC";obj.style.fontStyle="italic";obj.value=text;
  	}
}

function searchMessage(){
	$get("srchDisp").style.display="block";
	$get("main").style.display="none";
	$get("jigsawHeader").style.visibility="hidden";
	$get("jigsawFooter").style.visibility="hidden";
}

// Popup window function
function removeChars(str, pattern) {
    while (str.indexOf(pattern) != -1) {
        str = str.substring(0, str.indexOf(pattern)) + str.substring(str.indexOf(pattern) + 1, str.length);
    }
    return str;
}
function newWin(url, winName, width, height, toolbars, locations, scrollbar, menus, resizable, Horiz, Vert, server, defaultvals) {
    var settings;
    if (defaultvals == null) {
        defaultvals = true;
    }
    winName = defaultvals ? winName ? winName : "jigsawWin" : winName ? winName : "_blank";
    settings =    (defaultvals ? "width=" + (width ? width : 700) + "," : width ? "width=" + width + "," : "") 
    			+ (defaultvals ? "height=" + (height ? height : 700) + "," : height ? "height=" + height + "," : "") 
    			+ (defaultvals ? "toolbar=" + (toolbars ? toolbars : 1) + "," : toolbars ? "toolbar=" + toolbars + "," : "") 
    			+ (defaultvals ? "location=" + (locations ? locations : 1) + "," : locations ? "location=" + locations + "," : "") 
    			+ (defaultvals ? "scrollbars=" + (scrollbar ? scrollbar : 1) + "," : scrollbar ? "scrollbars=" + scrollbar + "," : "") 
    			+ (defaultvals ? "menubar=" + (menus ? menus : 1) + "," : menus ? "menubar=" + menus + "," : "") 
    			+ (defaultvals ? "resizable=" + (resizable ? resizable : 1) + "," : resizable ? "resizable=" + resizable + "," : "") 
    			+ (defaultvals ? "top=" + (Vert ? Vert : 20) + "," : Vert ? "top=" + Vert + "," : "") 
    			+ (defaultvals ? "left=" + (Horiz ? Horiz : 20) + "," : Horiz ? "left=" + Horiz + "," : "") + "fullscreen=no";
    			
    if (!server || url.substr(0, 4) == "http") {
        server = "";
    }
    winName = removeChars(winName, "*");
    winName = removeChars(winName, " ");

    if (winName == "_blank") {
        settings = "toolbar=1,menubar=1,location=1,scrollbars=1,resizable=1";
    }
    jigsawWin = settings ? window.open(server + url, winName, settings) : window.open(server + url, winName);
    if (winName == "_blank") {
        if (window.screen) {
            var availWidth = screen.availWidth;
            var availHeight = screen.availHeight;
            jigsawWin.moveTo(0, 0);
            jigsawWin.resizeTo(availWidth, availHeight);
        }
    }
    if (window.focus) {
        jigsawWin.focus();
    }
}
// function to show the listhover for dropdowns.
function toggleDropDown(id){
	if(targetElem != null){	
		var obj = $get(id);
		if(obj.style.display == "block")
			obj.style.display = "none";
		else
			obj.style.display = "block";
	}
}
//Generic Hover Function
function showConfirm(obj, id, isTop, leftAdjustment, topAdjust){
	var left = 0;
	if(leftAdjustment)
		left = leftAdjustment;
		
	var top = 0;
	if(topAdjust)
		top = topAdjust;
		
	var position = findPos(obj);
	var hover = $get(id);

	hover.style.zIndex = 10000000;	
	hover.style.position = "absolute";
	
	hover.style.left = position[0] + left + "px";
	hover.style.display = "block";
	if(isTop){
		hover.style.top = position[1] - hover.offsetHeight + (obj.offsetHeight / 2) + top + "px";
	}else{
		hover.style.top = position[1] + top + "px";
	}
	return true;
}
// Display Pop out hover
function showArrowHover(obj, id, placement, adjustTop){
	var position = GetElementAbsolutePos(obj);
	var hover = $get(id);
	var topdefault = 25;
	hover.style.zIndex = 10000000;	
	hover.style.position = "absolute";
	if(hover.style.display == "block"){
		hover.style.display = "none";
	}else{
		hover.style.display = "block";
	}
	switch(placement){
		case "top" :
		break;
		case "bottom" :
			hover.style.left = (position.x - hover.offsetWidth + obj.offsetWidth - 5) + "px";
			hover.style.top = (position.y + topdefault) + "px";
		break;
		case "right" :
		break;
		case "bottomleft" :
			if(adjustTop)
				topdefault = topdefault - adjustTop;
				
			hover.style.left = (position.x - 5) + "px";
			hover.style.top = (position.y + topdefault) + "px";
		break;
		default :
		break;
	}
	/*
	if(isTop){
		hover.style.top = position[1] - hover.offsetHeight + (obj.offsetHeight / 2) + "px";
	}else{
		hover.style.top = position[1] +  "px";
	}*/
	return true;

}

// updated to add overlay code to the page.
function showMaskedHover(id){
	var body = getDocumentBody();

	if($get("overlay")){
		var mask = $get("overlay");
	}
	if(browserName == "Microsoft Internet Explorer" && ieVersion == 6){
		mask.style.position = "absolute";
		mask.style.height = "10000px";
		mask.style.width = "10000px";
	}
	window.scrollTo(0,0);
	mask.style.display="block";
	mask.style.visibility="visible";
	changeOpac(50, "overlay");
	mask.style.zIndex = 10;
	
	var hover = $get(id);
		hover.style.display = "block";
		hover.style.zIndex = 10000000;	
							
	cssCenterObject(id);
	hideSelects($get('jigsawBody'));
	hideFlashObjects($get('jigsawBody'));
	body.style.overflow = "hidden";
}
// Specifically for processing time consuming requests
function showProcessingHover(){
	 $get("processingText").style.visibility="hidden";
	 showMaskedHover("processing");
}
// Using CSS to center objects, makes code much cleaner.  
function cssCenterObject(id){
	var obj = $get(id);
	if(browserName == "Microsoft Internet Explorer"){
		obj.style.left = "50%";
		obj.style.top = getViewportHeight() / 2;
		obj.style.position = "absolute";
	}else{
		obj.style.left="50%";
		obj.style.top="50%";
		obj.style.position = "fixed";
	}
	obj.style.zIndex = 1000000;
	
	var width = obj.offsetWidth;
	var height = obj.offsetHeight;
	obj.style.marginTop = -1 * (height/2) + "px";
	obj.style.marginLeft = -1 * (width/2) + "px";
}
// Get the document body
function getDocumentBody(){
	if (document.documentElement)
		return document.documentElement;
	else if (document.body && document.body.scrollTop)
		return document.body;
	else
		return document.getElementsByTagName("body")[0];
				
}
// comma formating numbers
function commaFormatted(amount){
	var delimiter = ","; 
	var a = amount;
	var i = parseInt(a);
	if(isNaN(i)) { return ''; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	var n = new String(i);
	var a = [];
	while(n.length > 3)
	{
		var nn = n.substr(n.length-3);
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	if(n.length > 0) { a.unshift(n); }
	n = a.join(delimiter);
	amount = n;
	amount = minus + amount;
	return amount;
}
function showElement(id){
	var obj = $get(id);
	if(obj.tagName == "SPAN")
		obj.style.display = "inline";
	else
		obj.style.display = "block";
}
function hideElement(id){
	$get(id).style.display = "none";
}

// functionName is the function to be called when the page counter is clicked
// actionName format:/XXX
// prefixUrl format:/XXX
function getPageCounterForSEO(page,total,formattedTotal,perPage, actionName,prefixUrl) {
  if( total == 0 ) return "";
  // figure out which elements are displayed
  var start = (page-1) * perPage + 1;
  var end = start + perPage-1;
  if( total - start < perPage )
    end = total;
//alert(page + "::" + start + "::" + end + "::" + total);
  // figure out how many pages and which ones
  var totalPages = parseInt((total-1) / perPage + 1);
  var numPages = totalPages;
  if( numPages > 10 )
	numPages = 10;
  var startPage = 1;
  var endPage = 10;
  if( page <= 9) {
    endPage = numPages;
  } else {
    startPage = page - 4;
    endPage = page + 5;
    if( startPage < 1 ) {
      startPage = 1;
      endPage = startPage + numPages - 1;
    }
    if( endPage >= totalPages) {
      endPage = totalPages;
      startPage = endPage - numPages + 1;
      if( startPage < 1 )
        startPage = 1;
    }
  }
  // Create the << and < arrows
  var result = "<strong>" + start + " - " + end + " of " + formattedTotal + "</strong>&nbsp;&nbsp;";
  if( page > 1 )
    //result += "<a href='javascript:" + functionName +"(" + (page-1) + ")'>&lt;Previous</a>&nbsp;&nbsp;";
    result += "<a href='"+prefixUrl+"/"+ (page-1) +actionName+"'>&lt;Previous</a>&nbsp;&nbsp;";
  else
    result += "<strong>Page&nbsp;</font></strong>";

  if( startPage > 1 )
    //result += "<a href='javascript:"+ functionName +"(1)'>1</a>&nbsp;...&nbsp;";
	result += "<a href='"+prefixUrl+"/1"+ actionName +"'>1</a>&nbsp;...&nbsp;";
  // Create the page numbers
  for (i = startPage; i <= endPage; i++) {
    if( i==page) result += "<font color='black'><strong>" + i + "</strong></font>";
    else
	  //result += "<a href='javascript:" + functionName + "(" + i + ")'>" + i + "</a>";
	  result += "<a href='"+prefixUrl+"/"+ i + actionName +"'>" + i + "</a>";
    result += "&nbsp;";
    if( i < endPage )
      result += "|&nbsp;";
  }
//alert(page + "::" + startPage + "::" + endPage );

  // Create the > and >> arrows
  if( page < totalPages-2 )
    //result += "...&nbsp;<a href='javascript:" + functionName + "(" + totalPages + ")'>" + totalPages + "</a>";
    result += "...&nbsp;<a href='" + prefixUrl + "/" + totalPages + actionName +"'>" + totalPages + "</a>";
  if( page < totalPages ) {
      //result += "<a href='javascript:" + functionName + "(" + (page+1) + ")'>&nbsp;Next></a>";
      result += "<a href='"+prefixUrl + "/" + (page+1) + actionName + "'>&nbsp;Next></a>";
  }
  result += "</strong>";
  return result;
}