//*****************************************************************
//  function Calculate_Net()
//*****************************************************************
function Calculate_Net(UnitPrice, Quantity, NumDays, Discount, NetPrice, bQtyDropdown){
  var tempQuantity;
  var tempDiscount;
  var tempNumDays   = parseInt(NumDays.value);
  var tempUnitPrice = parseFloat(UnitPrice.value.replace('$','').replace(',',''));
  
  if (bQtyDropdown == "true") {
    tempQuantity = parseFloat(Quantity.options[Quantity.selectedIndex].value);
  } else {
    tempQuantity = parseInt(Quantity.value);
  }
  if (Discount.value.indexOf('%') != -1) {
    tempDiscount  = parseFloat(Discount.value.replace('$',''));
    tempDiscount  = tempUnitPrice*(tempDiscount/100);        
  } else {
    tempDiscount  = parseFloat(Discount.value.replace('$',''));
    Discount.value = formatCurrency(tempDiscount);
  }
  UnitPrice.value = formatCurrency(tempUnitPrice);
  NetPrice.value= formatCurrency((tempUnitPrice-tempDiscount)*tempQuantity*tempNumDays);
  return false;
}

//*****************************************************************
//  function CheckNumericInput()
//*****************************************************************
function CheckNumericInput(AllowNegative, AllowDecimal)
  {
  // Numbers are allowed
  if ((this.event.keyCode >= 48) && (this.event.keyCode <= 57))
    {
    return (true);
    }
  // Only one period(decimal) is allowed if flag is set
  else if ((this.event.keyCode == 46) && (this.event.srcElement.value.indexOf(".") == -1) && AllowDecimal)
    {
    return (true);
    }
  // Only one dash(negative) is allowed if flag is set
  else if ((this.event.keyCode == 45) && (this.event.srcElement.value.indexOf("-") == -1) && AllowNegative)
    {
    return (true);
    }
  // Ignore any other characters entered
  else
    {
    this.event.returnValue=false;
    return (false);
    }
  }

function CheckInputKeyStroke(allowedChr){
	// Check that current character is number.
	if (allowedChr.indexOf(String.fromCharCode(this.event.keyCode)) == -1){
	  this.event.returnValue=false;
	  return false;
	}	else {
	  return true;
	}
}



//*****************************************************************
//  function formatCurrency()
//*****************************************************************
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: Tool Tip
// PURPOSE:		Mousover tooltips
// ****************************************************************
function ToolTip(what, horizontaloffset, verticaloffset){
         what=eval(what);
         what.style.display='block';
         what.style.left=event.x+ horizontaloffset +document.body.scrollLeft;
         what.style.top=event.y+ verticaloffset +document.body.scrollTop;
}
function UnToolTip(what){
         what=eval(what);
         what.style.display='none';
}  

// ****************************************************************
// FUNCTIONS: PopupWindow
// PURPOSE:		Popup Window
// **************************************************************** 
function PopupWindow(sURL, sMessageWindow, sScrollbars, sWidth, sHeight, sMenubar,sStatusbar, sResizable){
	window1=window.open(sURL,sMessageWindow,"scrollbars="+sScrollbars+",width="+sWidth+",height="+sHeight+",menubar="+sMenubar+",status="+sStatusbar+",resizable="+sResizable)
}

// ****************************************************************
// FUNCTIONS: checkEmailForm
// PURPOSE:		Email form Validation
// **************************************************************** 
function checkEmailForm(frmName,session){
  var valid = true;
  var svalid = '';
  frmName.FromName.style.backgroundColor	= 'white';
  frmName.FromEmail.style.backgroundColor	= 'white';
  frmName.Comment.style.backgroundColor		= 'white';
  frmName.verCode.style.backgroundColor     = 'white';
  if (frmName.FromName.value.length < 2){
    svalid = svalid + '-Please Enter a Name\n'
    frmName.FromName.style.backgroundColor='#DEE4F4';
    valid = false;
  }
	if (!isEmailAddr(frmName.FromEmail.value)){
    svalid = svalid + '-Please Enter valid Email\n'
    frmName.FromEmail.style.backgroundColor='#DEE4F4';
    valid = false;
  }
  if (frmName.Comment.value.length < 3){
    svalid = svalid + '-Please enter valid text\n' 
    frmName.Comment.style.backgroundColor='#DEE4F4';
    valid = false;
  }
  if (frmName.verCode.value != session)
  {
    svalid = svalid + '-Incorrect image verification\n' 
    frmName.verCode.style.backgroundColor='#DEE4F4';
    valid = false;
  }
  if (valid){
    var randomnumber=Math.floor(Math.random()*9999);
    var randomReturn=prompt("Please retype the four digit number to ensure you are an authentic user (" + randomnumber.toString() + ").","")
    if (randomnumber.toString() == randomReturn.toString())
    {
        frmName.submit();
		return true;
	}
	else
	{
	    alert("Error processing request.  Please try again.");
	    //return false;
	}
  }
  else{
    alert("The following fields are not valid.\n" + svalid)
    //return false;
  }
}

function isEmailAddr(email){
  var result = false
  var theStr = new String(email)
  var index = theStr.indexOf("@");
  if (index > 0){
    var pindex = theStr.indexOf(".",index);
    if ((pindex > index+1) && (theStr.length > pindex+1))
			result = true;
  }
  return result;
}

function isInteger(s){
	var i;
	for (i = 0; i < s.length; i++){   
		// Check that current character is number.
		var c = s.charAt(i);
		if (((c < "0") || (c > "9"))) return false;
	}
	// All characters are numbers.
	return true;
}

function stripCharsInBag(s, bag){
	var i;
	var returnString = "";
		// Search through string's characters one by one.
		// If character is not in bag, append to returnString.
		for (i = 0; i < s.length; i++)
		{   
				// Check that current character isn't whitespace.
				var c = s.charAt(i);
				if (bag.indexOf(c) == -1) returnString += c;
		}
		return returnString;
}

function checkPhone(strPhone){
	s = stripCharsInBag(strPhone, '()- ');
	return (isInteger(s) && s.length == 10); // phone number must be 10 digits long
}
function checkZipCode(strZipCode){
	s = stripCharsInBag(strZipCode, '-');
	return (isInteger(s) && s.length <= 10 && s.length >= 5); // zip code must be 5-10 digits long
}
function checkHexCode(strHexCode){
	var theStr = new String(strHexCode);
	var index = theStr.indexOf("#");
	if ( index == 0){
		theStr = stripCharsInBag(theStr, '#');
	} else {
		return (false);
	}
	s = stripCharsInBag(theStr, 'abcdefABCDEF0123456789');
	return (theStr.length == 6 && s.length < 1); // hex code must be 7 characters long (# plus 6 other characters)
}
function checkRequired(strRequired){
	return (strRequired.length >= 1); // Greater Than One Character
}

// ****************************************************************
// FUNCTIONS: checkLogin
// PURPOSE:		Email form Validation
// **************************************************************** 
function checkLogin(frmName){
  var valid = 'true';
  var svalid = '';
  frmName.UserName.style.backgroundColor			='white';
  frmName.Password.style.backgroundColor			='white';
  
  if (frmName.UserName.value.length < 1){
    svalid = svalid + '-Please Enter a valid user name \n'
    frmName.UserName.style.backgroundColor='#ccdaeb';
    valid = 'false';
  }
  if (frmName.Password.value.length < 1){
    svalid = svalid + '-Please enter a valid password \n' 
    frmName.Password.style.backgroundColor='#ccdaeb';
    valid = 'false';
  }
  
  if (valid == 'true'){
    frmName.submit();
  }
  else{
    alert("The following fields are not valid.\n" + svalid)
  }
}

// ****************************************************************
// FUNCTIONS: fun_Today
// PURPOSE:		Build Date
// **************************************************************** 
function fun_Today(){
	d = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
	m = new Array("January","February","March","April","May","June","July","August","September","October","November","December");

	today = new Date();
	day = today.getDate();
	year = today.getYear();

	if (year < 2000)    
	year = year + 1900; 

	end = "th";
	if (day==1 || day==21 || day==31) end="st";
	if (day==2 || day==22) end="nd";
	if (day==3 || day==23) end="rd";
	day+=end;

	document.write("Today is " + d[today.getDay()]+"<br>"+m[today.getMonth()]+" ");
	document.write(day+" " + year);
}
//*****************************************************************
//  function OpenCloseGroup()
//*****************************************************************
function OpenCloseGroup(ThisGroup){
  // Grab the image object reference
  var ThisGroupImage = event.srcElement;

  // If Layer is Closed
  if (ThisGroup.style.display=="none") {
    // Change Image and Open Layer
    ThisGroupImage.src="/common/images/minus.gif";
    ThisGroupImage.alt="Close";
    ThisGroup.style.display = "";
  }
  // Layer is Open
  else {
    // Change Image and Close Layer
    ThisGroupImage.src="/common/images/plus.gif";
    ThisGroupImage.alt="Open";
    ThisGroup.style.display = "none";
  }
}

//*****************************************************************
//  function OpenGroup()
//*****************************************************************
function OpenGroup(ThisGroup,ThisImage){
  ThisImage.src="/common/images/minus.gif";
  ThisImage.alt="Close";
  ThisGroup.style.display = "";
}
//*****************************************************************
//  function CloseGroup()
//*****************************************************************
function CloseGroup(ThisGroup,ThisImage){
  ThisImage.src="/common/images/plus.gif";
  ThisImage.alt="Open";
  ThisGroup.style.display = "none";
}   
function IFHide(sIframe, sWidth, sHeight){
  if (sIframe.style.display == 'none'){
	  sIframe.style.display = '';
		sIframe.style.width = sWidth;
		sIframe.style.height= sHeight;	
		
	} else {
		sIframe.style.display = 'none';
	}
}

function openTool(sURL){
	window.open(sURL,"newwin","scrollbars=no, toolbar=no, directories=no, menu bar=no, resizable=YES, status=yes, width=750, height=665");
	window.close;
}
function openTool(sURL, CompanyId){
	window.open(sURL,"tool_"+CompanyId,"scrollbars=no, toolbar=no, directories=no, menu bar=no, resizable=YES, status=yes, width=750, height=665");
	window.close;
}

// ****************************************************************
// ****************************************************************
//Credit Card Validation
// ****************************************************************
// ****************************************************************
function validateCard(cardNumber,cardType,cardMonth,cardYear) {
   	if( cardNumber.length == 0 ) {						//most of these checks are self explanitory
 		alert("Please enter a valid card number.");
   		return false;				
   	}
  	for( var i = 0; i < cardNumber.length; ++i ) {		// make sure the number is all digits.. (by design)
   		var c = cardNumber.charAt(i);
   		if( c < '0' || c > '9' ) {
   			alert("Please enter a valid card number. Use only digits. do not use spaces or hyphens.");
  			return false;
   		}
   	}
   	var length = cardNumber.length;			//perform card specific length and prefix tests
   	switch( cardType ) {
   		case '156':
			if( length != 15 ) {
				alert("Please enter a valid American Express Card number.");
				return false;
			}
			var prefix = parseInt( cardNumber.substring(0,2));
  			if( prefix != 34 && prefix != 37 ) {
				alert("Please enter a valid American Express Card number.");
   				return false;
   			}
			break;
   		case '157':
			if( length != 16 ) {
   				alert("Please enter a valid Discover Card number.");
				return false;
			}
  			var prefix = parseInt( cardNumber.substring(0,4));
   			if( prefix != 6011 ) {
   				alert("Please enter a valid Discover Card number.");
   				return false;
  			}
   			break;
   		case '158':
			if( length != 16 ) {
   				alert("Please enter a valid MasterCard number.");
  				return false;
  			}
   			var prefix = parseInt( cardNumber.substring(0,2));
  			if( prefix < 51 || prefix > 55) {
  				alert("Please enter a valid MasterCard Card number.");
 				return false;
			}
			break;
   		case '159':
			if( length != 16 && length != 13 ) {
				alert("Please enter a valid Visa Card number.");
				return false;
 			}
   			var prefix = parseInt( cardNumber.substring(0,1));
			if( prefix != 4 ) {
 				alert("Please enter a valid Visa Card number.");
   				return false;
   			}
  			break;
  	}
   	if( !mod10( cardNumber ) ) { 		// run the check digit algorithm
   		alert("Sorry! this is not a valid credit card number.");
   		return false;
	}
	if( expired( cardMonth, cardYear ) ) {							// check if entered date is already expired.
   		alert("Sorry! The expiration date you have entered would make this card invalid.");
  		return false;
	}
	return true; // at this point card has not been proven to be invalid
}
function mod10( cardNumber ) { // LUHN Formula for validation of credit card numbers.
	var ar = new Array( cardNumber.length );
	var i = 0,sum = 0;

   	for( i = 0; i < cardNumber.length; ++i ) {
   		ar[i] = parseInt(cardNumber.charAt(i));
   	}
   	for( i = ar.length -2; i >= 0; i-=2 ) { // you have to start from the right, and work back.
   		ar[i] *= 2;							 // every second digit starting with the right most (check digit)
   		if( ar[i] > 9 ) ar[i]-=9;			 // will be doubled, and summed with the skipped digits.
   	}										 // if the double digit is > 9, ADD those individual digits together 
   	for( i = 0; i < ar.length; ++i ) {
   		sum += ar[i];						 // if the sum is divisible by 10 mod10 succeeds
   	}
   	return (((sum%10)==0)?true:false);	 	
}

function expired( month, year ) {
   	var now = new Date();							// this function is designed to be Y2K compliant.
   	var expiresIn = new Date(year,month,0,0,0);		// create an expired on date object with valid thru expiration date
   	expiresIn.setMonth(expiresIn.getMonth()+1);		// adjust the month, to first day, hour, minute & second of expired month
   	if( now.getTime() < expiresIn.getTime() ) return false;
       	return true;									// then we get the miliseconds, and do a long integer comparison
}

/********************************************************************
Trim(string) : Returns a copy of a string without leading or trailing spaces
********************************************************************/
function Trim(str){
   return RTrim(LTrim(str));
}
/********************************************************************
LTrim(string) : Returns a copy of a string without leading spaces.
********************************************************************/
function LTrim(str){
	var whitespace = new String(" \t\n\r");

	var s = new String(str);

	if (whitespace.indexOf(s.charAt(0)) != -1) {
		var j=0, i = s.length;
		// Iterate from the far left of string until we
		// don't have any more whitespace...
		while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
				j++;
		// Get the substring from the first non-whitespace
		// character to the end of the string...
		s = s.substring(j, i);
	}
	return s;
}

/*******************************************************************
RTrim(string) : Returns a copy of a string without trailing spaces.
********************************************************************/
function RTrim(str){
	// We don't want to trip JUST spaces, but also tabs,
	// line feeds, etc.  Add anything else you want to
	// "trim" here in Whitespace
	var whitespace = new String(" \t\n\r");

	var s = new String(str);

	if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
		var i = s.length - 1;       // Get length of string
		// Iterate from the far right of string until we
		// don't have any more whitespace...
		while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
				i--;
		// Get the substring from the front of the string to
		// where the last non-whitespace character is...
		s = s.substring(0, i+1);
	}
	return s;
}

//*****************************************************************
//  function ValidDateRange()
//*****************************************************************
function ValidDateRange(StartDate, EndDate, MaxDays, DefaultMaxDays, AllowEmptyDates){
  var sError = "";
  
  if ( AllowEmptyDates == 'TRUE' ){
    var bAllowEmptyDates = true;
  } else {
    var bAllowEmptyDates = false;
  }

  StartDate = Trim(StartDate);
  EndDate = Trim(EndDate);
  
  sError = sError + IsDate(StartDate);
  sError = sError + IsDate(EndDate);
  
  if (!bAllowEmptyDates && sError.length > 0) {
    alert(sError);
  }
  
  if ((sError.length == 0)) {
    var dStartDate = new Date(StartDate);
    var dEndDate = new Date(EndDate);
    
    if ( dEndDate.getTime()-dStartDate.getTime() < 0 ) {
      alert('The "Start Date" field can not be greater than the "End Date" field');
      return false;
    }

    var dDateDiff = new Date();
    dDateDiff.setTime(Math.abs(dStartDate.getTime() - dEndDate.getTime()));

    if (isNumeric(MaxDays)) {
      if (Math.floor(dDateDiff.getTime() / (1000 * 60 * 60 * 24))>MaxDays) {
        alert('The maximum days allowed between the "Start" and "End" dates is '+MaxDays+' days');
        return false;
      }
    } else {
      if (isNumeric(DefaultMaxDays)) {
        if (Math.floor(dDateDiff.getTime() / (1000 * 60 * 60 * 24))>DefaultMaxDays) {
          alert('The maximum days allowed between the "Start" and "End" dates is '+DefaultMaxDays+' days');
          return false;
        }
      }
    }
  }

  return true;
}

/*******************************************************************
IsDate(dateStr) : Returns true/false if the string passed is a date
********************************************************************/
var dtCh= "/";
var minYear=1990;
var maxYear=2100;

function IsDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	var sError = ""
	var bError = false
	strYr=strYear
	
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1 || dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		sError = sError + "\n - Format must be: mm/dd/yyyy";
		bError = true;
	}
	if (strMonth.length<1 || month<1 || month>12){
		sError = sError + "\n - Invalid Month";
		bError = true;
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		sError = sError + "\n - Invalid Day";
		bError = true;
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		sError = sError + "\n - Must enter a four digit year between "+minYear+" and "+maxYear;
		bError = true;
	}
  return sError;
}

