// ================================================================
function setGender(prefixField, genderField) {
	if ($(prefixField).value == 'Mr.') {
		$(genderField).value = 0;
	}
	else if ($(prefixField).value == 'Mrs.' || $(prefixField).value == 'Ms.') {
		$(genderField).value = 1;
	}
}

// ================================================================
function $RF(el, radioGroup) {
    if($(el).type && $(el).type.toLowerCase() == 'radio') {
        var radioGroup = $(el).name;
        var el = $(el).form;
    } else if ($(el).tagName.toLowerCase() != 'form') {
        return false;
    }
 
    var checked = $(el).getInputs('radio', radioGroup).find(
        function(re) {return re.checked;}
    );
    return (checked) ? $F(checked) : null;
}

// ================================================================
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));
	}
	
	if (!sign) {
		return '<span style="color: #FF0000;">($'+ num +'.'+ cents +')</span>';
	}else{
		return '$'+num+'.'+cents;
	}
	//return (((sign)?'':'-') + '$' + num + '.' + cents);
}

// ================================================================
function isValidCreditCard(type, ccnum) {
   // Remove all dashes for the checksum checks to eliminate negative numbers
   ccnum = ccnum.split("-").join("");
   ccnum = ccnum.split(" ").join("");
   
   if (type == "Visa") {
      // Visa: length 16, prefix 4, dashes optional.
      var re = /^4\d{3}-?\d{4}-?\d{4}-?\d{4}$/;
   } else if (type == "MasterCard") {
      // Mastercard: length 16, prefix 51-55, dashes optional.
      var re = /^5[1-5]\d{2}-?\d{4}-?\d{4}-?\d{4}$/;
   } else if (type == "Discover") {
      // Discover: length 16, prefix 6011, dashes optional.
      var re = /^6011-?\d{4}-?\d{4}-?\d{4}$/;
   } else if (type == "AmEx") {
      // American Express: length 15, prefix 34 or 37.
      var re = /^3[4,7]\d{13}$/;
   } else if (type == "Diners") {
      // Diners: length 14, prefix 30, 36, or 38.
      var re = /^3[0,6,8]\d{12}$/;
   }
   if (!re.test(ccnum)) return false;
   // Checksum ("Mod 10")
   // Add even digits in even length strings or odd digits in odd length strings.
   var checksum = 0;
   for (var i=(2-(ccnum.length % 2)); i<=ccnum.length; i+=2) {
      checksum += parseInt(ccnum.charAt(i-1));
   }
   // Analyze odd digits in even length strings or even digits in odd length strings.
   for (var i=(ccnum.length % 2) + 1; i<ccnum.length; i+=2) {
      var digit = parseInt(ccnum.charAt(i-1)) * 2;
      if (digit < 10) { checksum += digit; } else { checksum += (digit-9); }
   }
   if ((checksum % 10) == 0) return true; else return false;
}

// ================================================================
function isValidCreditCardCake(ccnum) {
	if (ccnum.match(/^3[4|7]\d{13}$/) || ccnum.match(/^(?:3(0[0-5]|[68]\d)\d{11})|(?:5[1-5]\d{14})$/) || ccnum.match(/^(?:6011|650\d)\d{12}$/) || ccnum.match(/^5[1-5]\d{14}$/) || ccnum.match(/^4\d{12}(\d{3})?$/)){
		return true;
	}
	else {
		return false;
	}
}

// ================================================================
function alltrim(str) {
	return str.replace(/^\s+|\s+$/g, '');
}

// ================================================================
// Only allows digits, a single decimal point, and 2 digits after the decimal.
// Run onKeyUp
//
function onlyFloat(i) 
{ 
	var str = new String($(i).value);
	str = alltrim(str);

	// Only allow nums and decimal point
	str = str.replace(/[^0-9.]/g, ''); 
	
	// Only allow 1 decimal
	var piecesArr = str.split('.');
	if (piecesArr.length > 2) {
		str = str.replace(/[.]$/g, '');
	}
	
	// Only allow 2 digits after the decimal
	if (piecesArr.length > 1) {
		if (/[0-9]{3,}$/.test(str)) {
			str = str.replace(/.$/g, '');
		}
	}

	if (str != $(i).value) {
		$(i).value = str;
	}
}

// ================================================================
function numberOfDecimals(x, dec_sep)
{
    var tmp=new String(x);
    if (tmp.indexOf(dec_sep)>-1){
        return tmp.length-tmp.indexOf(dec_sep)-1;
    }else{
        return 0;
	}
} 

// ================================================================
function disableDiv(elm) {
 
    /*
	while (elm.tagName !="DIV") {
		elm = elm.parentNode;
    }
	*/
 
	_width = elm.offsetWidth;
	_height = elm.offsetHeight;
	_top = elm.offsetTop;
	_left = elm.offsetLeft;
	 
	overlay = document.createElement("div");
	overlay.style.width = _width + "px";
	overlay.style.height = _height + "px";
	overlay.style.position = "absolute";
	overlay.style.background = "#dedede";
	overlay.style.top = _top + "px";
	overlay.style.left = _left + "px";
	 
	overlay.style.filter = "alpha(opacity=80)";
	overlay.style.opacity = "0.8";
	overlay.style.mozOpacity = "0.8";
	 
	document.getElementsByTagName("body")[0].appendChild(overlay);
}

// ================================================================
function validateEmail(txt) {
	
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	
	if(reg.test(txt) == false) {
		valid = false;
	}else{
		valid = true;
	}
	return valid;
}

/* ================================================================
 * Description: Since rows may have been removed from a table, we need to re-do the CSS classes/background colors of each row so they alternate
 * 
 * @param table_id = table where you want to reset the row classes
 * @param oddRowClass = CSS class for odd rows
 * @param evenRowClass = CSS class for even rows
 * @param titleSelector = only pull child rows with this title
 */ 
function resetRowClasses(table_id, oddRowClass, evenRowClass, titleSelector) 
{
	//tableRows = $$('#'+table_id+' tr');
	tableRows = $(table_id).select( 'tr[title="'+titleSelector+'"]');

	// We are only concerned with visible rows
	visibleRows = new Array();
	for(i=0; i<tableRows.length; i++) {
		if (tableRows[i].visible()) {
			visibleRows[visibleRows.length] = tableRows[i].id;
		}
	}

	for(i=0; i<visibleRows.length; i++) {
	  // remove classes
	  $(visibleRows[i]).removeClassName(oddRowClass);
	  $(visibleRows[i]).removeClassName(evenRowClass);
	  
	  // add new class based on whether it is odd or even
	  if ((i % 2) == 0) {
		cssVal = oddRowClass;
	  }else{
		cssVal = evenRowClass;
	  }
	  $(visibleRows[i]).addClassName(cssVal);
	}
}

// ================================================================
function countVisibleRows(table_id, skipHeader)
{
	tableRows = $$('#'+table_id+' tr');

	if (skipHeader) {
		// Remove first row with headers
		tableRows.splice(0,1);
	}
	
	rowCount = 0;
	for(i=0; i<tableRows.length; i++) {
		if (tableRows[i].visible()) {
			rowCount++;
		}
	}
	//alert(rowCount);
	return rowCount;
}

// ================================================================
function toggleCheckbox(elementId)
{
	if ($(elementId).checked){
		$(elementId).checked = false;
	}else{
		$(elementId).checked = true;
	}
}

// ================================================================
function getFloatVal(x) {
	aNumber = x;
	aNumber = aNumber.replace(/[^0-9.]/g, '');
	aNumber = aNumber * 1;
	return aNumber;
}

// ================================================================
function getElementPos(e)
{
	var element = e;
	var curleft = 0;

	return Element.cumulativeOffset(e);

/*
	if (element.offsetParent) {
		while (element.offsetParent) {
			curleft += element.offsetLeft;
			element = element.offsetParent;
		}
	}
	else if (element.x) {
		curleft += element.x;
	}

	var element = e;
	var curtop = 0;

	if (element.offsetParent) {
		while (element.offsetParent) {
			curtop += element.offsetTop;
			element = element.offsetParent;
		}
	}
	else if (element.y) {
		curtop += element.y;
	}

	return {left:curleft, top:curtop}
*/
}

// ================================================================
function showQuickActions()
{
	var element		= $('qa_nav_link');
	var pos			= getElementPos(element);
    var docheight	= getPageHeight();


	if($('quick_actions').visible() == false){
		$('quick_actions').style.top = parseInt(pos.top + 42) + 'px';
		$('quick_actions').style.left = pos.left + 'px';

		document.getElementById('overlay_modal').style.height = docheight + 'px';
		document.getElementById('overlay_modal').style.display = '';
		
		$('quick_actions').show();
	}
	else{
		hideQuickActions();
	}

	return false;
}

// ================================================================
function hideQuickActions(){
	$('quick_actions').hide();

	document.getElementById('overlay_modal').style.display = 'none';


	return false;
}

// ============================================
function confirmPWC_close(txt, base, url)
{
	var con = confirm(txt);
	if (con){
	  if (typeof(url) != 'undefined') {
		parent.reloadParent(base, url);
	  }else{
		parent.reloadParent(base);
	  }
	  return true;
	}else{
	  return false;
	}
}

// ============================================
function formatPhone(tb)
{
	var rawPhone = tb.value.replace(/[^0-9]/g, '');
	var formattedPhone = '';

	for (i = 0; i < rawPhone.length; i++) {
		formattedPhone += rawPhone.charAt(i);

		if (formattedPhone.length == 3 || formattedPhone.length == 7) {
			formattedPhone += '-';
		}
		else if (formattedPhone.length == 12) {
			break;
		}
	}

	tb.value = formattedPhone;

	return;
}

// ============================================
function stopBubble(e)
{
	if (window.event) {
		window.event.cancelBubble = true;
	}
	else if (e){
		e.stopPropagation();
	}

	return;
}

// turn autocomplete off for all fields with a class of number_field
document.observe('dom:loaded', function() {
	$$('.number_field').each(function(i){ i.setAttribute('autocomplete', 'off');});
});



// Adding on to prototype to allow us to abort ajax calls
Ajax.Request.prototype.abort = function() {
	// prevent and state change callbacks from being issued
	this.transport.onreadystatechange = Prototype.emptyFunction;
	
	// abort the XHR
	this.transport.abort();
	
	// update the request counter
	Ajax.activeRequestCount--;
	
	if (Ajax.activeRequestCount < 0) {
		Ajax.activeRequestCount = 0;
	}

};

// Adding on to prototype to allow us to abort ajax calls
function openRemoteWindow(width, height, url, title) 
{
  var docheight = getPageHeight();

  document.getElementById('overlay_modal').style.height = docheight + 'px';
  document.getElementById('overlay_modal').style.display = '';

  PWC = new Window({
    className: 'alphacube',
    title: title,
    width: width,
    height: height,
    url: url,
    recenterAuto: false,
	resizable: true,
	closable: true,
	minimizable: true,
	maximizable: true,
	draggable: true,
	showEffectOptions: { duration:0.25 }
  });
  
  PWC.showCenter();
 
  return;
}

// ============================================
function isValidUSZip(sZip) {
   return /^\d{5}(-\d{4})?$/.test(sZip);
}

// ============================================
function isValidCanadaZip(sZip) {
   return /^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} {0,1}\d{1}[A-Z]{1}\d{1}$/.test(sZip);
}

function currencyFormat(value, includeCommas)
{
	value *= 100;
	value = Math.round(value);
	value /= 100;

	var wholeValue = new String;
	var decimalValue = new String;

	splitValue = new String(value).split('.');

	if (splitValue.length == 1) {
		wholeValue = new String(value);
		decimalValue = '00';
	}
	else if (splitValue.length == 2) {
		if (splitValue[1].length == 1) {
			wholeValue = splitValue[0];
			decimalValue = splitValue[1] + '0';
		}
		else if (splitValue[1].length == 2) {
			wholeValue = splitValue[0];
			decimalValue = splitValue[1];
		}
		else if (splitValue[1].length > 2) {
			wholeValue = splitValue[0];
			decimalValue = splitValue[1].substr(0,2);
		}
	}

	var currencyValue = new String;

	if (includeCommas) {
		var i;
		var j = 0;

		for (i = (wholeValue.length - 1); i >= 0; i--) {
			currencyValue = wholeValue.charAt(i) + currencyValue;

			if (j == 2 && i > 0) {
				currencyValue = ',' + currencyValue;

				j = 0;
			}
			else {
				j++;
			}
		}

		currencyValue += '.' + decimalValue;
	}
	else {
		currencyValue = wholeValue + '.' + decimalValue;
	}

	return currencyValue;
}

// ============================================
function ifImageExists(id) {
	$(id).show();
}

// ============================================
function missingImage(id, missingImage) {
	$(id).src = missingImage;
	$(id).show();

}
