 /* Checks Browser Compatibility */
  var agt = navigator.userAgent.toLowerCase();
  var is_op = (agt.indexOf("opera") != -1);
  var is_ie = (agt.indexOf("msie") != -1) && document.all && !is_op;
  var is_mac = (agt.indexOf("mac") != -1);
  var is_gk = (agt.indexOf("gecko") != -1);
  var is_sf = (agt.indexOf("safari") != -1);

  ratingMsgs = new Array(6);
  ratingMsgColors = new Array(6);
  barColors = new Array(6);

  ratingMsgs[0] = "Too short";
  ratingMsgs[1] = "Weak";
  ratingMsgs[2] = "Fair";
  ratingMsgs[3] = "Good";
  ratingMsgs[4] = "Strong";
  ratingMsgs[5] = "Not rated"; //If the password server is down

  ratingMsgColors[0] = "#676767";
  ratingMsgColors[1] = "#aa0033";
  ratingMsgColors[2] = "#f5ac00";
  ratingMsgColors[3] = "#6699cc";
  ratingMsgColors[4] = "#008000";
  ratingMsgColors[5] = "#676767";

  barColors[0] = "#dddddd";
  barColors[1] = "#aa0033";
  barColors[2] = "#ffcc33";
  barColors[3] = "#6699cc";
  barColors[4] = "#008000";
  barColors[5] = "#676767";


 var isBrowserCompatible = Compatible();
  
//
// general purpose functions
//

function print(item){
	var printThis = document.getElementById(item).value;
	var win=null;
    win = window.open();
    self.focus();
    win.document.open();
    win.document.write('<html><head>');
    
    win.document.write('<style>p.breakhere{page-break-after : always}</style>');
    
    win.document.write('</head><body style="font-size:8px">');
    win.document.write(printThis);
    win.document.write('</body></html>');
    win.document.close();
    //win.print();
    //win.close();
}
function trim(str, chars) 
{
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) 
{
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) 
{
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

var helpWindow;
function openHelp(pageName)
{
	helpWindow = window.open("help/" + pageName, 'help',
		'left=40,top=40,width=400,height=300,toolbar=1,resizable=0,scrollbars=1');
}

function waitDiv(showHide)
{
	if (showHide == 1)
		document.getElementById("pleasewaitScreen").style.visibility = "";
	else
		document.getElementById("pleasewaitScreen").style.visibility = "hidden";
}

function writeXMLtoFields(xmlHttpThis)
{
	var response  = xmlHttpThis.responseXML.documentElement;
	var items = response.getElementsByTagName("User")[0].childNodes;
	for (var i = 0 ; i < items.length ; i++) 
	{
		var item = items[i];
		var id = item.nodeName;
		if (id != "#text" && item.firstChild != null)
		{
			var value = item.firstChild.nodeValue;
			var field = document.getElementById(id);
			if (id == "type")   // checkbox
			{
				if ((field = document.getElementById(value)) != null)
				field.checked = true;
			}
			else if (field != null)
				field.value = value;
		}
	}
}
function checkFieldsNoCompany()
{
	return checkFieldsWithExceptions(['fax', 'mobile', 'companyName', 'workPhone']);
}
function checkFields()
{
	return checkFieldsWithExceptions(['fax', 'mobile']);
}
function checkFieldsWithExceptions(optionalFields)
{
	var arrayOfElements = document.getElementsByTagName("input");
	for (i = 0; i < arrayOfElements.length; i++)
		if (arrayOfElements[i].type == "text")
			if (arrayOfElements[i].value == "")
			{
				var mandatory = true;
				for (j = 0; j < optionalFields.length; j++)
					if (arrayOfElements[i].name == optionalFields[j])
						mandatory = false;
				if (mandatory)
				{
					alert("Please enter a value for '" + arrayOfElements[i].name + "'");
					return false;
				}
			}
	var password = document.getElementById("password");
	var passwordConfirm = document.getElementById("passwordConfirm");
	
	return checkPasswordFields(password, passwordConfirm);
}
function checkPasswordFields(password, passwordConfirm)
{
	if (password != null)
	{
		if (password.value == "")
		{
			alert("Please enter a Password value");
			return false;
		}
		if (passwordConfirm != null)
		{
			if (passwordConfirm.value == "")
			{
				alert("Please enter a Password confirmation value");
				return false;
			}
				
			if (password.value != passwordConfirm.value)
			{
				alert("Password does not match confirmation.");
				return false;
			}
		}
	}
	return true;
}
//
// functions for reports.jsp
//


function checkEmail(){
	var email = document.getElementById("email").value;
	if(email != "" && email.indexOf("@") > -1 && email.indexOf(".") > -1){
		return true;
	}
	alert("Email format problem");
	return false;
}

//
// functions for billing.jsp
//
function formatCurrency(num) 
{
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
		num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
		cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}

//
// functions for index.jsp
//

function checkCapsLock(e) 
{
	var capslock = document.getElementById("capslock");
	capslock.style.visibility = "hidden";
	var myKeyCode = 0;
	var myShiftKey = false;

	if (document.all)  // Internet Explorer 4+
	{
		myKeyCode = e.keyCode;
		myShiftKey = e.shiftKey;
	}
	else if (document.layers || document.getElementById)	// Mozilla
	{
		myKeyCode = e.which;
		myShiftKey = myKeyCode == 16;
	}
	
	// Upper case letters are seen without depressing the Shift key, therefore Caps Lock is on
	if (myKeyCode >= 65 && myKeyCode <= 90 && !myShiftKey)
		capslock.style.visibility = "";
	else if (myKeyCode >= 97 && myKeyCode <= 122 && myShiftKey)
		capslock.style.visibility = "";
}

//
// functions for mainMenu.jsp
//


function getXPos(cellName){
	var obj = document.getElementById(cellName);
	var curtop = 0;
	if (obj.offsetParent) {
		do {
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}

	return curtop + 20;	
}
function getYPos(cellName){
	var obj = document.getElementById(cellName);
	var curLeft = 0;
	if (obj.offsetParent) {
		do {
			curLeft += obj.offsetLeft;
		} while (obj = obj.offsetParent);
	}

	return curLeft -250;	
}

function closeAllOthersFirst(elementName){
	for(y = 0; y < divBoxes.length; y++){
		if(elementName != divBoxes[y]){
			document.getElementById(divBoxes[y]).style.visibility = "hidden";
		}
	}
}

function showSheet(elementName, cellName){
	closeAllOthersFirst(elementName);
	document.getElementById(elementName).style.top = getXPos(cellName);
	document.getElementById(elementName).style.left = getYPos(cellName);
	if(document.getElementById(elementName).style.visibility == "hidden"){
		document.getElementById(elementName).style.visibility = "";
	}
	else{
		document.getElementById(elementName).style.visibility = "hidden";
	}
}

//
// functions for createCompany.jsp
//

//
// functions for userAssociation.jsp
//

function openTools(){
	window.location = "userTools.jsp";
}

function deleteConfirm(){
	document.getElementById("warn").style.visibility = "hidden";
	document.getElementById("yes").style.visibility = "";
}

function deleteCancel(){
	//document.getElementById("userTools").value = ""
	document.getElementById("reason").value = ""
	document.getElementById("warn").style.visibility = "hidden";
	document.getElementById("yes").style.visibility = "hidden";
}

function deleteUser(theId){
	document.getElementById("theUser").value = theId;
	document.getElementById("warn").style.visibility = "";
}

function editEntry(usersId)
{
	window.location="userEditor.jsp?userToEdit=" + usersId;
}

var n = 0;
var found;
function findInPage(str) 
{
	var	txt, i;
	if (str == "") 
		return false;

	if (document.all) 
	{
		txt = window.document.body.createTextRange();
		// Find the nth match from the top of the page.
		for (i = 0; i <= n &&(found = txt.findText(str)) != false; i++) 
		{
			txt.moveStart("character",1);
			txt.moveEnd("textedit");
		}
		if (found) 
		{
			txt.moveStart("character", -1); txt.findText(str);
			txt.select(); txt.scrollIntoView(); n++;
		}
		else 
		{
			if (n > 0)
			{
				n = 0; 
				findInPage(str);
			}
			else
				alert("Not found.");
		}
	}
	else if ((document.layers && !found) || (document.getElementById && !found))
	{
		if (!window.find(str))
			while(window.find(str, false, true))
				n++; 
		else 
			n++;
		if (n == 0)
			alert("Not found.");
	}
	return false;
}

//
// functions for userEditor.jsp
//

function userDataHandler()
{
	if (xmlhttp.readyState==4)
	{
		waitDiv(0);
		if (xmlhttp.status == 200)
			writeXMLtoFields(xmlhttp);
		else if(xmlhttp.status == 404)
			alert("Page Not Found");
		else
			alert("Server Status is: " + xmlhttp.status);
	}
}
function pickUser(id)
{
	waitDiv(1);
	XmlHttpPOST(userDataHandler, "ajaxStuff/loadUserEditor.jsp", "usersIdToChange=" + id);
}

//
// functions for 'addUserToCompany.jsp
//

function companyDataHandler()
{
	if (xmlhttp.readyState==4)
	{
		waitDiv(0);
		if (xmlhttp.status == 200)
			writeXMLtoFields(xmlhttp);
		else if(xmlhttp.status == 404)
			alert("Page Not Found");
		else
			alert("Server Status is: " + xmlhttp.status);
	}
}

function getCompanyData(select)
{
	getCompanyDataByName(select.value);
}
function getCompanyDataByName(name)
{
	if (name != "No Companies Exist")
	{
		var allText = document.getElementsByTagName("input");
		for (i = 0; i < allText.length; i++)
			if (allText[i].type == "text" && allText[i].name.indexOf("activationDate") < 0)
				allText[i].value = "";
	}
	waitDiv(1);
	XmlHttpPOST(companyDataHandler, "ajaxStuff/loadCompInfo.jsp", "companyName=" + escape(name));
}

function createNewCompany(button)
{
	var select = document.theform.companyCmb;
	var companyName = document.theform.companyName;
	var addUser = document.theform.addUser;
	if (button.value.indexOf("Create") >= 0)
	{
		select.selectedIndex = select.options.length-1;
		select.disabled = true;
		if (addUser != null)
			addUser.disabled = true;
		companyName.disabled = false;
		var allText = document.getElementsByTagName("input");
		for (i = 0; i < allText.length; i++)
			if (allText[i].type == "text")
				allText[i].value = "";
		document.theform.companyName.focus();
	}
	else
	{
		select.selectedIndex = 0;
		select.disabled = false;
		companyName.disabled = true;
		if (addUser != null)
			addUser.disabled = false;
		document.theform.address.focus();
	}
}

function setVisibleConfirm(component, show)
{
	setVisible(component, show);
	var whole = document.getElementById("whole");
	if (show)
	{
		if (whole.filters != null)
			whole.filters.item("DXImageTransform.Microsoft.Alpha").Opacity=25;
		else
			whole.style.MozOpacity = 0.4;
	}
	else
	{
		if (whole.filters != null)
			whole.filters.item("DXImageTransform.Microsoft.Alpha").Opacity=100;
		else
			whole.style.MozOpacity = 1;
	}
}

function setVisible(component, show)
{
	if (show)
		document.getElementById(component).style.visibility = "";
	else
		document.getElementById(component).style.visibility = "hidden";
}

function setVisibleSubmit(component, form)
{
	setVisibleConfirm(component, true);
	setTimeout("form.submit();", 100);
}

function rateHandler() 
{
	// Can't check status since safari doesn't support it
   	if (xmlhttp.readyState == 4)
   	{
		var rating = parseInt(xmlhttp.responseText);
   		DrawBar(rating);
   	}
} 

function CreateRatePasswdReq(theForm) 
{
    if (!isBrowserCompatible)
 		return;

    var passwd = theForm["password"].value;
    var min_passwd_len = 6;
    var email = "";
    var firstname = "";
    var lastname = "";
  
    if (theForm["email"])
    	 email = getUserName(theForm["email"].value);

   	// If Last name exists, It has to be Caribou Sign up.  We'll have
   	// all the functions defined in CaribouSignUpBox.gxp
  	if (theForm["lastname"])
    	lastname = escape(theForm["lastname"].value);

   	if (theForm["firstname"])
      	firstname = escape(theForm["firstname"].value);

    if (passwd.length < min_passwd_len)  
    {
      	if (passwd.length > 0)
 			DrawBar(0);
      	else
        	ResetBar();
    } 
    else 
    {
  	  	//We need to escape the password now so it won't mess up with length test
      	var params = "Passwd=" + escape(passwd)
                   + "&Email=" + email
                   + "&FirstName=" + firstname
                   + "&LastName=" + lastname;
 
      	XmlHttpGET(rateHandler, "includes/ratePassword.jsp?" + params);
    }
  }

  function getElement(name) 
  {
    if (document.all)
      return document.all(name);

    return document.getElementById(name);
  }

  function getUserName(s) 
  {
	  var parts = s.split("@");
	  return parts[0];
  }

  function DrawBar(rating) 
  {
    var posbar = getElement('posBar');
    var negbar = getElement('negBar');
    var passwdRating = getElement('passwdRating');
    var barLength = getElement('passwdBar').width;

    if (rating >= 0 && rating <= 4) 
    {  //We successfully got a rating
      posbar.style.width = barLength / 4 * rating + "px";
      negbar.style.width = barLength / 4 * (4 - rating) + "px";
    } 
    else 
    {
      posbar.style.width = "0px";
      negbar.style.width = barLength + "px";
      rating = 5; // Not rated Rating
    }
    posbar.style.background = barColors[rating];
    passwdRating.innerHTML = "<font color='" + ratingMsgColors[rating] +
                             "'>" + ratingMsgs[rating] + "</font>";
  }
  	
  //Resets the password strength bar back to its initial state without any message showing.
  function ResetBar() 
  {
    var posbar = getElement('posBar');
    var negbar = getElement('negBar');
    var passwdRating = getElement('passwdRating');
    var barLength = getElement('passwdBar').width;

    posbar.style.width = "0px";
    negbar.style.width = barLength + "px";
    passwdRating.innerHTML = "";
  }

  function gff(str, pfx) 
  {
    var i = str.indexOf(pfx);
    if (i != -1) 
    {
      var v = parseFloat(str.substring(i + pfx.length));
      if (!isNaN(v)) 
 	     return v;
    }
    return null;
  }
  function Compatible() 
  {
    if (is_ie && !is_op && !is_mac) 
    {
      var v = gff(agt, "msie ");
      if (v != null)
        return (v >= 6.0);
    }

    if (is_gk && !is_sf) 
    {
      var v = gff(agt, "rv:");
      if (v != null)
         return (v >= 1.4);
      else 
      {
         v = gff(agt, "galeon/");
         if (v != null)
           return (v >= 1.3);
      }
    }

    if (is_sf) 
    {
      var v = gff(agt, "applewebkit/");
      if (v != null)
        return (v >= 124);
    }

    return false;
  }

function CreateXmlHttpReq(handler) 
{
  var xmlhttp = null;
  if (is_ie) 
  {
		try 
		{
			try
			{
				xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
				if (!xmlhttp)
					xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e)
			{
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
		  xmlhttp.onreadystatechange = handler;
		} 
		catch (ex) 
		{
		  // TODO: better help message
		  alert("You need to enable active scripting and activeX controls");  
		}
  } 
  else 
  {
    // Mozilla
    xmlhttp = new XMLHttpRequest();
    xmlhttp.onload = handler;
    xmlhttp.onerror = handler;

  }
  return xmlhttp;
}

var xmlhttp;
// XMLHttp send POST request
function XmlHttpPOST(handler, url, data) 
{
  try 
  {
  	xmlhttp = CreateXmlHttpReq(handler);
    xmlhttp.open("POST", url, true);
    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    xmlhttp.send(data);
  } 
  catch (ex) 
  {
//    alert(ex);
  }
}
// XMLHttp send GEt request
function XmlHttpGET(handler, url) 
{
  try 
  {
 	xmlhttp = CreateXmlHttpReq(handler);
    xmlhttp.open("GET", url, true);	
    xmlhttp.send(null);
  } 
  catch (ex) 
  {
    alert(ex);
  }
}

//Bug Testing
function getPermission(form){
   if(confirm("ARE YOU SURE??")){
      form.submit();
   }
}

