<!--
// Standard Macromedia (MM_) functions
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);

function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}

function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location=\'"+selObj.options[selObj.selectedIndex].value+"\'");
  if (restore) selObj.selectedIndex=0;
}


function showLayer(layerName){
	if (document.getElementById){
		var targetElement = document.getElementById(layerName);
		targetElement.style.visibility = 'visible';
		targetElement.style.height = 'auto';
	}
}

function hideLayer(layerName){
	if (document.getElementById) {
		var targetElement = document.getElementById(layerName);
		targetElement.style.visibility = 'hidden';
		targetElement.style.height = '0px';
	}
}

function salesRepsShow(layerName,allLayers){
	var allLayersArray = allLayers.split(",");
	for(i=0; i<allLayersArray.length; i++){
		hideLayer(allLayersArray[i]);
	}
	showLayer(layerName);
}

function changePic(imgTarget, imgSrc){
	if(document.getElementById(imgTarget)){
		document.getElementById(imgTarget).src = imgSrc;
	}
}

// HREF VIA JAVASCRIPT EVENT
function redirect(url) {
	window.location = url;
}

// ONCHANGE REDIRECT
function doOnChange(form, box, prepend){
	if(box == "company") var s = document.forms[0].company;
	else if(box == "contractor") var s = document.forms[0].contractor;
	else if(box == "sales_rep") var s = document.forms[0].sales_rep;
        else if(box == "customer") var s = document.forms[0].customer;
	var d = s.options[s.selectedIndex].value;
	//alert(prepend);
	if(d) location.href = prepend + d;
}

function marginCommissionSwitch(showMargin, prepend){
    if (showMargin) {
        location.href = '?' + prepend + '&commission=1';
    }
    else {
        location.href = '?' + prepend + '&commission=0';
    }
    return false;
}

// new window popup used for opening up artwork and flash projects
function launchwin(uri,name,args)
{
	newwin = window.open(uri,name,args);
	newwin.focus();
}

// USER TYPES EMAIL INTO FORM AND USES THIS FUNCTION TO REDIRECT TO A 'SEND PASSWORD TO MY EMAIL' PAGE
function requestpass(){
	var e = document.forms[0].username.value;
	uri = "actions/forgot_password.php?username=" + e + "";
	top.location.replace(uri);
}

// WEB BASED 'BACK' BUTTON
function go_back(){
	history.back();
}
		

// FOR USE IN CMS... CONFIRM ACTION BEFORE SUBMITTING TO db_update PAGE
function confirmSubmit(conf)
{
	var agree=confirm(conf);
	if (agree){
		return true ;
	} else {
		return false ;
	}
}

// CONFIRM BEFORE CONTINUING
function confirmFirst(msg,url){
	var agree=confirm(msg);
	if (agree) top.location.replace(url);
}


// CHECK OR UNCHECK ALL CHECKBOXES ON THE FORM
var checkAll_status = "check";
function checkAll(){
	var msg = "";
	for(i=0; i<document.forms[0].elements.length; i++){
		if(document.forms[0].elements[i].type == "checkbox"){
			if(checkAll_status == "check") document.forms[0].elements[i].checked = false;
			else document.forms[0].elements[i].checked = true;
		}
	}
	
	if(checkAll_status == "check") checkAll_status = "uncheck";
	else checkAll_status = "check";
}

// CHECK ALL CHECKBOXES ON THE FORM
function checkAllCommission(form){
    for(i=0; i<document.getElementById(form).elements.length; i++){
        if(document.getElementById(form).elements[i].type == "checkbox") {
            var pattern = /commission_checkbox_(\d+)/;
            var result;
            result = pattern.exec(document.getElementById(form).elements[i].id);
            if (document.getElementById(form).elements[i].checked == false) {
                document.getElementById(form).elements[i].checked = true;
                //applyCommissionPayment(document.getElementById(form).elements[i].onclick())
                applyCommissionPayment(result[1]);
            }
        }
    }
}

function uncheckAllCommission(form){
    for(i=0; i<document.getElementById(form).elements.length; i++){
        if(document.getElementById(form).elements[i].type == "checkbox"){
            var pattern = /commission_checkbox_(\d+)/;
            var result;
            result = pattern.exec(document.getElementById(form).elements[i].id);
            if (document.getElementById(form).elements[i].checked == true) {
                document.getElementById(form).elements[i].checked = false;
                //applyCommissionPayment(document.getElementById(form).elements[i].onclick())
                applyCommissionPayment(result[1]);
            }
        }
    }

}

// SHADOW POPOVER
function popOver(){
	var b = document.getElementById("overlay_background");
	var f = document.getElementById("overlay_feature");
	var ifr = document.getElementById("iFrame_buyNow");
	
	if(b.style.visibility == "visible"){
		b.style.visibility = "hidden";
		f.style.visibility = "hidden";
		ifr.style.visibility = "visible";
	} else {
		b.style.visibility = "visible";
		f.style.visibility = "visible";
		ifr.style.visibility = "hidden";
	}
}


// COMPANY PAYMENTS TAB FUNCTION(S)
function calculateInvoiceTotal(){
	var tempTotal = 0;
	if(document.getElementById("recipient").selectedIndex == 1){
		// loop through all OHL Invoice Amounts and add up everything selected
		var numInvoices = document.getElementById("numInvoices");
		for(i=0; i<numInvoices.value; i++){
			if(document.getElementById("ohlInvoices_"+i)){
				thisCheckbox = document.getElementById("ohlInvoices_"+i);
				if(thisCheckbox.checked == true){
					invamt = document.getElementById("ohlInvoiceAmt_"+i);
					tempTotal = parseFloat(tempTotal) + parseFloat(invamt.value);
				}
			}
		}
		
		tempTotal = tempTotal.toFixed(2);
		document.getElementById("amount").value = tempTotal;
		document.getElementById("showAmount").innerHTML = "$" + tempTotal;
		
	} else if(document.getElementById("recipient").selectedIndex == 2){
		// loop through all BSB Invoice Amounts and add up everything selected
		var numInvoices = document.getElementById("numInvoices");
		for(i=0; i<numInvoices.value; i++){
			if(document.getElementById("bsbInvoices_"+i)){
				thisCheckbox = document.getElementById("bsbInvoices_"+i);
				if(thisCheckbox.checked == true){
					invamt = document.getElementById("bsbInvoiceAmt_"+i);
					tempTotal = parseFloat(tempTotal) + parseFloat(invamt.value);
				}
			}
		}
		
		tempTotal = tempTotal.toFixed(2);
		document.getElementById("amount").value = tempTotal;
		document.getElementById("showAmount").innerHTML = "$" + tempTotal;
		
	} else {
		alert("Please select who this payment will be for before checking invoices.");	
	}
}


// POPUP MULTIPLE INVOICES
function printAllInvoices(invoices_to_print,customer){
	var invoices = new Array();
	invoices = invoices_to_print.split(",");
	if(invoices.length > 0){
		for(i=0; i<invoices.length; i++){
			launchwin("invoice.php?id=" + invoices[i] + "&customer=" + customer + "","invoice" + invoices[i] + "","width=800,height=800,scrollbars=yes");	
		}
	}
}


// POPUP MULTIPLE INVOICES IN A SINGLE POPUP
function printAllInvoicesAtOnce(invoices_to_print){
	launchwin("invoice_mult.php?invoices=" + invoices_to_print,"invoice_all","width=800,height=800,scrollbars=yes");	
}

// POPUP MULTIPLE INVOICES IN A SINGLE POPUP
function printAllInvoicesAtOnce_v3(invoices_to_print){
	launchwin("invoice_mult_v3.php?invoices=" + invoices_to_print,"invoice_all","width=800,height=800,scrollbars=yes");	
}

// POPUP MULTIPLE INVOICES IN A SINGLE POPUP
function printAllInvoicesAtOnce_dhl(invoices_to_print){
	launchwin("invoice_mult_dhl.php?invoices=" + invoices_to_print,"invoice_all","width=800,height=800,scrollbars=yes");	
}

// POPUP MULTIPLE INVOICES IN A SINGLE POPUP
function printAllInvoicesAtOnce_ups(invoices_to_print){
	launchwin("invoice_mult_ups.php?invoices=" + invoices_to_print,"invoice_all","width=800,height=800,scrollbars=yes");	
}

function printAllInvoicesAtOnce_fedexedi(invoices_to_print){
	launchwin("invoice_mult_fedexedi.php?invoices=" + invoices_to_print,"invoice_all","width=800,height=800,scrollbars=yes");	
}

// FUNCTIONS BELOW USED IN invoice.php ONLY
function makeVisible(n){
	document.getElementById(n).style.visibility = "visible";
}

function printInvoice(invoice_date, due_date, invoice, customer, late_fee, invoice_type){
        var late_fee_str = "0";
	if(document.getElementById("printButton")){
		var n = document.getElementById("printButton");
		n.style.visibility = "hidden";
	}

        if (late_fee) {
           late_fee_str = "0";
        }
        else {
           late_fee_str = "1";
        }
	
	var url = "actions/print_invoice.php";
	var qs  = "invoice_date=" + invoice_date + "&due_date=" + due_date + "&id=" + invoice + "&customer=" + customer + "&apply_late_fee=" + late_fee_str + "&invoice_type=" + invoice_type;
	makeRequest(url+"?"+qs);
        //history.go();
}

var http_request = false;
function printAndClose(){
	if(http_request.readyState == 4) {
		if(http_request.responseText == 'print'){
			hasPrinted = true;
			window.print();
			window.close();
		}
	}
}

// AJAX FUNCTIONS
function makeRequest(url) {
	//var http_request = false;
	
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
			// See note below about this line
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
			http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	
	if (!http_request) {
		alert('Giving up :( Cannot create an XMLHTTP instance');
		return false;
	}
	
	http_request.onreadystatechange = printAndClose;
	http_request.open('GET', url, true);
	http_request.send(null);
	
}
	
// (not using right now)
function alertContents(http_request) {
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			alert(http_request.responseText);
		} else {
			alert('There was a problem with the request.');
		}
	}
	
}

function toggleLayer(whichLayer)
{
   if (document.getElementById)
   {
      // this is the way the standards work
      var style2 = document.getElementById(whichLayer).style;
      style2.display = style2.display? "":"block";
   }
   else if (document.all)
   {
      // this is the way old msie versions work
      var style2 = document.all[whichLayer].style;
      style2.display = style2.display? "":"block";
   }
   else if (document.layers)
   {
      // this is the way nn4 works
      var style2 = document.layers[whichLayer].style;
      style2.display = style2.display? "":"block";
   }
}

function showHideOHLBSB() {
   if (document.getElementById('recipient').selectedIndex == 1) {
      document.getElementById('bsbInvoices').style.display = '';
      document.getElementById('ohlInvoices').style.display = 'block';
      document.getElementById('start_i').value = 0;
   }
   else {
      document.getElementById('bsbInvoices').style.display = 'block';
      document.getElementById('ohlInvoices').style.display = '';
      document.getElementById('start_i').value = 1000;
   }
   document.getElementById('amount').disabled = false;
   document.getElementById('check_num').disabled = false;
   document.getElementById('notes').disabled = false;
}


function arrowSwap(img_name)
{
   if (document.images[img_name].src.search(/right_arrow.gif/) > 0)
   {
      document.images[img_name].src = 'images/down_arrow.gif';
   }
   else
   {
      document.images[img_name].src = 'images/right_arrow.gif';
   }
}

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);
}

function stripCurrencyFormat(num) {
   num = num.toString().replace(/\$|\,/g,'');
   if (isNaN(num))
      num = "0";
   return num;
}

function calcAmountDue(invoice) {
   current = document.getElementById('total_'+invoice);
   fee  = document.getElementById('fee_'+invoice);
   fee_chk = document.getElementById('fee_checkbox_'+invoice);
   
   if (fee_chk.checked == true) {
      new_total = parseFloat(stripCurrencyFormat(current.innerHTML)) + parseFloat(stripCurrencyFormat(fee.innerHTML));
      document.getElementById('total_'+invoice).innerHTML = formatCurrency(new_total);
   }
   else {
      new_total = parseFloat(stripCurrencyFormat(current.innerHTML)) - parseFloat(stripCurrencyFormat(fee.innerHTML));
      document.getElementById('total_'+invoice).innerHTML = formatCurrency(new_total);
   }

   return true;
}

function applyExactAmount(amount, start_i) {
   var i = start_i;
   while (true) {
      if (document.getElementById('total_'+i)) {
         var total_due = stripCurrencyFormat(document.getElementById('total_'+i).innerHTML);
         if (amount == total_due) {
            applyToId(i, amount);
            return true;
         }
      }
      else {
         break;
      }
      i++;
   }
   return false;
}

function applyToOldest(amount, start_i) {
   var running_total = parseFloat(amount);

   var i = start_i;
   while (running_total > 0) {

      if (! document.getElementById('total_'+i)) {
         var confirmation = confirm("Payment is for $" + formatCurrency(running_total) + " more than owed. Would you like to apply a credit to this account? (Ok for Yes or Cancel to re-enter the payment amount or to not apply this credit)");
         if (confirmation == true) {
            // set the hidden field value
            document.getElementById('overpay').value = running_total;
         }
      }

      invoice_total = parseFloat(stripCurrencyFormat(document.getElementById('total_'+i).innerHTML)).toFixed(2);
      if (parseFloat(running_total) >= parseFloat(invoice_total)) {
         applyToId(i, invoice_total);
         running_total = parseFloat(running_total - invoice_total).toFixed(2);
      }
      else {
         var bad_debt = confirm("Applying the left over amount of $" + formatCurrency(running_total) + " to the invoice with a total due of $" + formatCurrency(invoice_total) + ". Would you like to mark the remaining amount as a bad debt (Ok), or short pay the invoice and leave it open (Cancel)?");
         if (bad_debt == true) {
            // Keep track of bad debt and close the invoice
            // Set a hidden field for this invoice
            document.getElementById('bad_debt_'+i).value = invoice_total - running_total;
            enableAndCheck(i, 'bad');
         }
         else {
            enableAndCheck(i, 'short');
         }

         applyToId(i, parseFloat(stripCurrencyFormat(running_total)).toFixed(2));
         running_total = 0;
      }

      i++;
   }

}

function applyPayment(amount, start_i) {
   if (! applyExactAmount(amount, parseInt(start_i))) {
      applyToOldest(amount, parseInt(start_i));
   }
   return true;
}

function applyToId(id, amount) {
   document.getElementById('apply_checkbox_'+id).checked = true;
   document.getElementById('payment_'+id).value = amount;
}

function applyCheckbox(id) {
    var due = parseFloat(stripCurrencyFormat(document.getElementById('total_'+id).innerHTML));
    if (document.getElementById('apply_checkbox_'+id).checked) {
        applyToId(id, due);
        setTotalPaymentAmount( getTotalPaymentAmount() + due );
    }
    else {
        document.getElementById('apply_checkbox_'+id).checked = false;
        document.getElementById('payment_'+id).value = '';
        setTotalPaymentAmount( getTotalPaymentAmount() - due );
    }
    
    return true;
}

function applyCommissionPayment(id) {

    var due = parseFloat(stripCurrencyFormat(document.getElementById('commission_'+id).innerHTML));
    var total = parseFloat(stripCurrencyFormat(document.getElementById('total_commission').innerHTML));
    if (document.getElementById('commission_checkbox_'+id).checked) {
        document.getElementById('total_commission').innerHTML = Math.round((total + due)*100)/100;
    }
    else {
        document.getElementById('commission_checkbox_'+id).checked = false;
        document.getElementById('total_commission').innerHTML = Math.round((total - due)*100)/100;
    }
    
    //alert(due);
    //alert(total);
    
    return true;
}

function setTotalPaymentAmount(amount) {
    //alert(amount);
    amount = Number(amount);
    document.getElementById('amount').value = Math.round(amount*100)/100;
    return true;
}

function getTotalPaymentAmount() {
    return Number(document.getElementById('amount').value);
}

function checkPayment(id) {
   due = parseFloat(stripCurrencyFormat(document.getElementById('total_'+id).innerHTML));
   payment_amount = parseFloat(document.getElementById('payment_'+id).value);

   if (payment_amount < due) {
      enableAndCheck(id, 'short');
   }
}

function enableAndCheck(id, type) {
   document.getElementById('short_'+id).disabled = false;
   document.getElementById('bad_'+id).disabled = false;

   if (type == 'short') {
      document.getElementById('short_'+id).checked = true;
   }
   else {
      document.getElementById('bad_'+id).checked = true;
   }
}

function validatePhone(id) {
   var pattern = /^\d{10}$/;
   if (pattern.test( document.getElementById(id).value )) {
      return true;
   }
   else {
      alert('Number must be in the format: 1231231234');
      return false;
   }
}

function stripDashes(id) {
   var string = document.getElementById(id).value;
   document.getElementById(id).value = string.replace(/-/g, '');
}

function refresh() {
   location.reload(true);
}

function flipBackground(id) {
    var text_box = document.getElementById(id).style.backgroundColor;
    if (text_box != 'red') {
        document.getElementById(id).style.backgroundColor = 'red';
    }
    else {
        document.getElementById(id).style.backgroundColor = 'white';
    }

}

//-->

