var xmlHttp;  // for ajax support

// for ajax support
function setupXmlHttpObject() {
	var r = false;
	try
	  {
	  // Firefox, Opera 8.0+, Safari
	  xmlHttp=new XMLHttpRequest();
	  r = true;
	  }
	catch (e)
	  {
	  // Internet Explorer
	  try
	    {
	    	xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
	    	r = true;
	    }
	  catch (e)
	    {
	    try
	      {
	      	xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
	      	r = true;
	      }
	    catch (e)
	      {
	      	alert("Your browser does not support AJAX!");
	      	r = false;
	      }
	    }
	  }
	return r;
}

// for ajax support
function setupHttpPostHeaders(paramLength) {
	//Send the proper header information along with the request
	xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlHttp.setRequestHeader("Content-length", paramLength);
	xmlHttp.setRequestHeader("Connection", "close");
}

// for ajax support - building url or post param string 
// to avoid &param=&param2=value problems
function safeGetParamString(p, v) {
	var r = "";
	if ( v ) {
		v = v + ""; 
		if ( v.length > 0 ) 
			r = "&" + p + "=" + encodeURIComponent(v);
	}
	return r;  
}

// JavaScript Document
function hideElement(id) {
	var bReturn = false;
	var show_hide_area = document.getElementById(id); 
	if ( show_hide_area ) {
		show_hide_area.style.display = "none";
		show_hide_area.style.visibility = "hidden";
	}
	return bReturn;
}

function calcAndUpdateTotal(meetingId) {
	var costElement = document.getElementById("itemCost_" + meetingId);
	var durElement = document.getElementById("durationMin_" + meetingId );
	// var unitsElement = document.getElementById("itemUnits_" + meetingId );
	var totalElement = document.getElementById("invoiceTotalUSD_" + meetingId);

	if ( costElement ) {
		if ( durElement ) {
			//if ( unitsElement ) {
				if ( totalElement ) {

					moneyFormat(costElement);

					var unitsElement_value = durElement.value / 60.0 ;

					var theTotal = costElement.value * unitsElement_value ;

					setText(totalElement, theTotal);

					moneyFormat(totalElement);
	
				} else {
					errorAlert("cannot update total, total element not found!");
				}				
			/* } else {
				errorAlert("cannot update total, units element not found!");
			}	*/	
		} else {
			errorAlert("cannot update total, duration element not found!");
		}
	} else {
		errorAlert("cannot update total, cost element not found!");
	}
}

function formatTIN(theString, isIndividual) {
	var theCount = 0;
	var newString = "";
	var myString = theString;
	var theLen = myString.length;
	for ( var i = 0 ; i < theLen ; i++ ) {
		if ( newString.length >= 9 ) 
			break;
	
		// Character codes for ints 1 - 9 are 48 - 57
		if ( (myString.charCodeAt(i) >= 48 ) && (myString.charCodeAt(i) <= 57) )
			newString = newString + myString.charAt(i);
	}
	// Now the string has been stripped of other chars it can be reformatted to ###-##-#### 
	var newLen = newString.length;
	var newSSN = "";
	if ( newLen >= 9 ) {
		for ( var i = 0 ; i < newLen ; i++ ) {
		     if ( (isIndividual == 1 && (( i == 2 ) || ( i == 4 ))) || (isIndividual == 0 && i == 1 ) ) {
				newSSN = newSSN + newString.charAt(i) + "-";
		     } else {
				newSSN = newSSN + newString.charAt(i);
		     }
		}
		return newSSN;
	} else {
		return newString; // digits only
	}
}

function reformatTIN() {
	if ( !isNonUs() ) {
		var tinInputElementId = "taxIdDisp";
		var tinInputElement = document.getElementById(tinInputElementId);
		if ( tinInputElement ) {
			var doFormat = true;
			var origTinElem = document.getElementById("originalTaxId");
			if ( origTinElem ) {
				if ( origTinElem.value == tinInputElement.value )
					doFormat = false;
			}
			if ( doFormat )
				tinInputElement.value = formatTIN(tinInputElement.value, isIndividual());
		} else {
			alert("could not find taxId input element");
		}
	}
}

function isIndividual() {
	var isIndividual = 1;
	var chkIsIndividual = document.getElementById("isIndividual");
	if ( chkIsIndividual ) {
		if ( chkIsIndividual.checked )
			isIndividual = 1;
		else
			isIndividual = 0;
	}
	return isIndividual;
}

function isNonUs() {
	var isNonUs = 0;
	var chkisNonUs = document.getElementById("isNonUs");
	if ( chkisNonUs ) {
		if ( chkisNonUs.checked )
			isNonUs = 1;
		else
			isNonUs = 0;
	}
	return isNonUs;
}

function isIndividual_onclick(me) {
	if ( me.checked ) {
		var chkisNonUs = document.getElementById("isNonUs");
		if ( chkisNonUs ) 
			chkisNonUs.checked = false;
			var eTaxID = document.getElementById("taxIdDisp");
			if ( eTaxID.value == "Non-U.S." )
				eTaxID.value = "";
			
			eTaxID.disabled = false;
	}
}

function nonUS_onclick(me) {
	var eTaxID = document.getElementById("taxIdDisp");
	if ( eTaxID ) {
		if ( me.checked ) {
			//alert('checked');
			eTaxID.value = "Non-U.S.";
			eTaxID.disabled = true;
			var chkIsIndividual = document.getElementById("isIndividual");
			if ( chkIsIndividual )
				chkIsIndividual.checked = false;
		} else {
			//alert('not checked');
			if ( eTaxID.value == "Non-U.S." )
				eTaxID.value = "";

			eTaxID.disabled = false;
		}
	} else {
		alert("TaxID Field not found!");
	}
}


/*** global functions ***/

var _hasInnerText = null;
function hasInnerText() {
	if ( _hasInnerText == null ) _hasInnerText = (document.getElementsByTagName("body")[0].innerText != undefined) ? true : false;
	return _hasInnerText;
}

function setTextById(elementId,changeVal){
    var elem = document.getElementById(elementId);
	return setText(elem, changeVal);
}

function setText(elem, changeVal) {
	if ( elem ) {
	    if(!hasInnerText()){
			elem.textContent = changeVal;
	    }else{
			elem.innerText = changeVal;
	    }
	    if ( getText(elem)  == changeVal )
	    	return true;
	    else
	    	return false; // failed to change value	    
	} else {
		return false; // element undefined or not found
	}
}

function getTextById(elementId, aDefault) {
    var elem = document.getElementById(elementId);
    if ( aDefault )
    	return getText(elem, aDefault);
    else
    	return getText(elem);
}

function getText(elem) {
	return getText(elem, "{undefined}");
}

function getText(elem, aDefault) {
	if ( elem ) {
		if(!hasInnerText()){
			return elem.textContent.replace(/^\s+|\s+$/g, ''); // trim;
		}else{
			return elem.innerText;
		}
	} else {
		return aDefault;  // element undefined or not found
	}
}

function isNumeric(strString) {
	//if (value == null || !value.toString().match(/^[-]?\d*\.?\d*$/)) return false;
  	//  check for valid numeric strings 
	var strValidChars = "0123456789"; // .-
	var strChar;
	var blnResult = true;
	
	if (strString.length == 0) return false;
	
	//  test strString consists of valid characters listed above
	for (i = 0; i < strString.length && blnResult == true; i++)
	{
		strChar = strString.charAt(i);
		if (strValidChars.indexOf(strChar) == -1)
			{
			blnResult = false;
			}
	}
	return blnResult;
}

function rrTrim(value) {
	return value.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}


/*
JavaScript Unleashed, Third Edition
by Richard Wagner and R. Allen Wyke 

ISBN: 067231763X
Publisher Sams CopyRight 2000

*/
function moneyFormat(textObj) {
	var newValue = 0.0;

	if ( textObj.value ) {
		newValue = textObj.value;	
	} else {
		newValue = getText(textObj)
	}

   var decAmount = "";
   var dolAmount = "";
   var decFlag = false;
   var aChar = "";
   
   var result = "0.00";
   
   // ignore all but digits and decimal points.
   for(i=0; i < newValue.length; i++) {
      aChar = newValue.substring(i,i+1);
      if(aChar >= "0" && aChar <= "9") {
         if(decFlag) {
            decAmount = "" + decAmount + aChar;
         }
         else {
            dolAmount = "" + dolAmount + aChar;
         }
      }
      if(aChar == ".") {
         if(decFlag) {
            dolAmount = "";
            break;
         }
         decFlag=true;
      }
   }
   
   // Ensure that at least a zero appears for the dollar amount.

   if(dolAmount == "") {
      dolAmount = "0";
   }
   // Strip leading zeros.
   if(dolAmount.length > 1) {
      while(dolAmount.length > 1 && dolAmount.substring(0,1) == "0") {
         dolAmount = dolAmount.substring(1,dolAmount.length);
      }
   }
   
   // Round the decimal amount.
   if(decAmount.length > 2) {
      if(decAmount.substring(2,3) > "4") {
         decAmount = parseInt(decAmount.substring(0,2)) + 1;
         if(decAmount < 10) {
            decAmount = "0" + decAmount;
         }
         else {
            decAmount = "" + decAmount;
         }
      }
      else {
         decAmount = decAmount.substring(0,2);
      }
      if (decAmount == 100) {
         decAmount = "00";
         dolAmount = parseInt(dolAmount) + 1;
      }
   }
   
   // Pad right side of decAmount
   if(decAmount.length == 1) {
      decAmount = decAmount + "0";
   }
   if(decAmount.length == 0) {
      decAmount = decAmount + "00";
   }
   
   // Check for negative values and reset textObj
   if(newValue.substring(0,1) != '-' ||
         (dolAmount == "0" && decAmount == "00")) {
      result = dolAmount + "." + decAmount;

   }
   else{
      result = '-' + dolAmount + "." + decAmount;
   }
   
   if ( textObj.value ) {
   		textObj.value = result;
   	} else {
   		setText(textObj, result);
   	} 
}


/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

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++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

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)
	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){
		alert("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date")
		return false
	}
	return true
}

function validateDateInput(input) {
	if ( input ) {
		var val = input.value;
		val = val.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
		if (isDate(val)==false){
			input.focus();
			return false;
		}
	} else {
		return false;
	}
    return true;
}

/*** end date validation ***/


/*** validate email address (http://homepage.ntlworld.com/kayseycarvey/jss3p7.html) */ 
function CheckEmail(email) {
	//var email = document.f1.Email.value
	var AtPos = email.indexOf("@")
	var StopPos = email.lastIndexOf(".")
	//var Message = ""
	var valid = true
	
	if ( email ) {
		if (email == "") {
			//Message = "Not a valid Email address" + "\n"
			valid = false;
		}
		
		if (AtPos == -1 || StopPos == -1) {
			//Message = "Not a valid email address"
			valid = false;
		}
		
		if (StopPos < AtPos) {
			// Message = "Not a valid email address"
			valid = false;
		}
		
		if (StopPos - AtPos == 1) {
			//Message = "Not a valid email address"
			valid = false;
		}
	} else {
		valid = false;
	}	
	return valid; //Message
}
/*** end email validation ***/

