Array.prototype.findIndex = function(value){
var ctr = "";
for (var i=0; i < this.length; i++) {
// use === to check for Matches. ie., identical (===), ;
if (this[i] == value) {
return i;
}
}
return ctr;
};


/* global variable for the edit / new invoice page; see formisdirty etc. functions */
var remindUser = "stay";

function sz(t,min) {
	a = t.value.split('\n');
	b=1;
	for (x=0;x < a.length; x++) {
		 if (a[x].length >= t.cols) b+= Math.floor(a[x].length/t.cols);
	 }
	b+= a.length;
	if (t.value=="") b=1;
	if (b<min) b = min;
	t.rows = b; 
}


function addRow(tableID) {

	var table = document.getElementById(tableID);
	var rowCount = table.rows.length;
	var row = table.insertRow(rowCount);
	//alert(rowCount);
	//row.className = 'invoiceRow';
	//row.style.height ='30px';
	row.className = 'invoiceDataHeadRow';
	var colCount = table.rows[1].cells.length;
	//alert(colCount);

	for(var i=0; i<colCount; i++) {

		var newcell	= row.insertCell(i);
		newcell.innerHTML = table.rows[1].cells[i].innerHTML;
		newcell.className = table.rows[1].cells[i].className;
		//alert(table.rows[1].cells[i].className);
		
		//alert(newcell.childNodes);
		/* sets the values of the input elements to default */
		//alert(newcell.childNodes.length);
		
		var inputNode = newcell.getElementsByTagName("input")[0];
		if (inputNode) { 
			if (i<7) inputNode.style.color ='silver';	
			inputNode.value = '0.00';
		}
		var selectNode = newcell.getElementsByTagName("select")[0];
		if (selectNode) { 
			selectNode.selectedIndex = 0;
		}
		var textareaNode = newcell.getElementsByTagName("textarea")[0];
		if (textareaNode) { 
			textareaNode.value='';
			textareaNode.rows=1;
		}
			
		/*		
		switch(newcell.childNodes[0].type) {
			case "text":
					newcell.childNodes[0].value = "3.00";
					if (i<6) newcell.childNodes[0].style.color = "blue";
					break;
			case "hidden":
					newcell.childNodes[0].value = "0.00";
					break;
			case "checkbox":
					newcell.childNodes[0].checked = false;
					break;
			case "select-one":
					newcell.childNodes[0].selectedIndex = 0;
					break;
			case "textarea":
					newcell.childNodes[0].value = "";
					newcell.childNodes[0].rows = 1;					
					break;
		}*/
	}
	
	/* if the tax column has been inserted, the cell background could be yellow... they have to be set to white when a new row is inserted */
	/* i=1 to skip headline row; rowCount+1 to include the last added row */
	for (i=1;i<(rowCount+1);i++) {
		var rowNode = table.rows[i];
		rowNode.cells[5].style.backgroundColor ='#FFFFFF';
		var inputNode = rowNode.cells[5].getElementsByTagName("input")[0];
		//alert(inputNode.tagName);						 	
		inputNode.style.backgroundColor ='#FFFFFF';				 	
		
		rowNode.cells[6].style.backgroundColor ='#FFFFFF';
		var inputNode = rowNode.cells[6].getElementsByTagName("input")[0];
		inputNode.style.backgroundColor ='#FFFFFF';				 	
	}
}



function reCalculateTax2(tableID) {
	
 	var sum_of_all_taxes		=	0*1;
	var table 					= document.getElementById(tableID);	
	var rowCount 				= table.rows.length;
	var discount 				= document.getElementById('sum_discount').value;
	var subtotal				= document.getElementById('sum_subtotal').value;
	if (subtotal>0) var discount_per_subtotal = discount/subtotal; else var discount_per_subtotal = 0;
	
	var taxPct = [];
	var taxSums = [];
	
	//starts on i=1 to skip the headline row
	for (rowNo=1; rowNo<rowCount; rowNo++) {
	 
		taxPctValue     = 	table.getElementsByTagName("tr")[rowNo].getElementsByTagName("td")[6].getElementsByTagName("input")[0].value; //the tax column is the 5th column in this table; must grab everything like this due to different chilenode counting in firefox and ie
		amountValue 	=   table.getElementsByTagName("tr")[rowNo].getElementsByTagName("td")[7].getElementsByTagName("input")[0].value;
	
		if ((taxPctValue>0)&&(amountValue>0)) { //both the tax percentage and the line amount must be over 0 
	 		
			var new_value = taxPct.findIndex(taxPctValue);
 			if (new_value==="") {
			
				taxPct.push(taxPctValue);
			
				/* calculates the tax per line after subtracting the discount proportionally */
				var line_total = table.getElementsByTagName("tr")[rowNo].getElementsByTagName("td")[7].getElementsByTagName("input")[0];			
				var line_total_after_discount = line_total.value - (line_total.value * discount_per_subtotal);
				var line_tax = line_total_after_discount * (taxPctValue/100);
				taxSums.push(line_tax)
			} 

			/* this line uses a tax percentage already in the array; must update the tax sums for that tax percentage */
			else {
		 
			 	var old_tax = taxSums[new_value];

				/* calculates the tax per line after subtracting the discount proportionally */
				var line_total = table.getElementsByTagName("tr")[rowNo].getElementsByTagName("td")[7].getElementsByTagName("input")[0];			
				var line_total_after_discount = line_total.value - (line_total.value * discount_per_subtotal);
				var line_tax = line_total_after_discount * (taxPctValue/100);

				taxSums.splice(new_value,1,line_tax+old_tax);
			}
		}
	}
	
	/* sorts the two arrays */
	if (taxPct.length>1) {
	 
	 	var tempPct = [];
	 	var tempSums = [];
	 	var taxPctLength = taxPct.length;
	 
		for (i=0; i<taxPctLength; i++) {
		 
		 	for (x=0; x<taxPct.length;x++) { //runs through the array and finds the highest value
		 	
				taxPct[x] = taxPct[x]*1; //multiplies with 1 to cast the value as a number to get numerical instead of alphabetical comparison		 		
		 	
		 		if (x==0) {
					highestValue = taxPct[0];
					highestPos = 0;
				}
		 	 
		 	 	if (taxPct[x]>highestValue) { 
					highestValue = taxPct[x];
					highestPos = x;
				}
			}
			
			tempPct.push(highestValue); //puts the highest value found in a new temp array
			taxPct.splice(highestPos,1); //removes the value placed in the temp array from the original array
			tempTax = taxSums[highestPos]*1;
			tempTax = tempTax.toFixed(2);
			tempTax = tempTax*1; //toFixed converts it back to a string so must cast it again
			tempSums.push(tempTax);
			sum_of_all_taxes = sum_of_all_taxes + tempTax;
			taxSums.splice(highestPos,1);
		}
		
		taxPct = tempPct;
		taxSums = tempSums;
	} 
	
	else {
		
		if (taxSums[0]*1>0) {
		 	taxSums[0] = taxSums[0]*1; //cast to numeric
		 	taxSums[0] = taxSums[0].toFixed(2);
		 	taxSums[0] = taxSums[0]*1; //cast back to numeric
			sum_of_all_taxes = taxSums[0]; 
		}
	}
	
	var taxSum_rows = document.getElementsByName("line_tax[]").length;

	if (taxPct.length>0) {
	 
	 	document.getElementById('sum_blankAfterDiscountOrTaxTR').style.display='none';
	 
	 	for (i=0; i<taxPct.length;i++) {
	 	 
	 	 	if (taxPct.length-i>1) var paddingBottom = '1px'; else paddingBottom = '7px';
	
			var tableSums 		= document.getElementById('table_sums');	
			var tableSums_rows	= tableSums.rows.length;
			var taxName = document.getElementById('customization_taxname2').value.replace(" ","&nbsp;");
	
			var taxPctOutput = taxPct[i]*1;
			var taxSumsOutput = taxSums[i]*1;
	
			var row = tableSums.insertRow(5+i);

			var newcell = row.insertCell(0);
			newcell.innerHTML = '<td></td>';
			newcell.style.width='0px';

			var newcell = row.insertCell(1);
			newcell.innerHTML = '<td>+&nbsp;'+taxName+'&nbsp;('+pad_zeros(taxPctOutput)+'%)</td>';
			newcell.style.width='200px';	
			newcell.style.fontSize='11px';
			newcell.style.fontFamily='verdana';	
			newcell.style.color='#3c3c3c';
			newcell.style.paddingLeft='10px';
			newcell.style.paddingBottom=paddingBottom;		
	
			var newcell = row.insertCell(2);
			newcell.innerHTML = '<td></td>';
			newcell.style.textAlign='right';		
			newcell.style.paddingRight='4px';
			newcell.style.paddingBottom=paddingBottom;
			newcell.style.borderRight='1px solid white';
			newcell.style.borderLeft='1px solid white';
	
			var newfield = document.createElement("input");
			newfield.name = 'line_tax[]';
			newfield.type = 'text';
			newfield.value = pad_zeros(taxSumsOutput);
			newfield.readOnly = 'true';	
			newfield.style.border='0px solid white';
			newfield.style.textAlign='right';
			newfield.style.width='100px';
			newfield.style.paddingRight='5px';	
			newfield.style.fontFamily='verdana';
			newfield.style.fontSize='13px';	
			newfield.style.color='#3c3c3c';				
			newcell.appendChild(newfield);
		}
	}

	return sum_of_all_taxes;
}

function reCalculateTax(tableID) {
	
 	var sum_of_all_taxes		=	0*1;
	var table 					= document.getElementById(tableID);	
	var rowCount 				= table.rows.length;
	var discount 				= document.getElementById('sum_discount').value;
	var subtotal				= document.getElementById('sum_subtotal').value;
	if (subtotal>0) var discount_per_subtotal = discount/subtotal; else var discount_per_subtotal = 0;
	
	var taxPct = [];
	var taxSums = [];
	
	//starts on i=1 to skip the headline row
	for (rowNo=1; rowNo<rowCount; rowNo++) {
	 
		taxPctValue     = 	table.getElementsByTagName("tr")[rowNo].getElementsByTagName("td")[5].getElementsByTagName("input")[0].value; //the tax column is the 5th column in this table; must grab everything like this due to different childnode counting in firefox and ie
		amountValue 	=   table.getElementsByTagName("tr")[rowNo].getElementsByTagName("td")[7].getElementsByTagName("input")[0].value;
	
		if ((taxPctValue>0)&&(amountValue>0)) { //both the tax percentage and the line amount must be over 0 
	 		
			var new_value = taxPct.findIndex(taxPctValue);
 			if (new_value==="") {
			
				taxPct.push(taxPctValue);
			
				/* calculates the tax per line after subtracting the discount proportionally */
				var line_total = table.getElementsByTagName("tr")[rowNo].getElementsByTagName("td")[7].getElementsByTagName("input")[0];			
				var line_total_after_discount = line_total.value - (line_total.value * discount_per_subtotal);
				var line_tax = line_total_after_discount * (taxPctValue/100);
				taxSums.push(line_tax)
			} 

			/* this line uses a tax percentage already in the array; must update the tax sums for that tax percentage */
			else {
		 
			 	var old_tax = taxSums[new_value];

				/* calculates the tax per line after subtracting the discount proportionally */
				var line_total = table.getElementsByTagName("tr")[rowNo].getElementsByTagName("td")[7].getElementsByTagName("input")[0];			
				var line_total_after_discount = line_total.value - (line_total.value * discount_per_subtotal);
				var line_tax = line_total_after_discount * (taxPctValue/100);

				taxSums.splice(new_value,1,line_tax+old_tax);
			}
		}
	}
	
	/* sorts the two arrays */
	if (taxPct.length>1) {
	 
	 	var tempPct = [];
	 	var tempSums = [];
	 	var taxPctLength = taxPct.length;
	 
		for (i=0; i<taxPctLength; i++) {
		 
		 	for (x=0; x<taxPct.length;x++) { //runs through the array and finds the highest value
		 	
				taxPct[x] = taxPct[x]*1; //multiplies with 1 to cast the value as a number to get numerical instead of alphabetical comparison		 		
		 	
		 		if (x==0) {
					highestValue = taxPct[0];
					highestPos = 0;
				}
		 	 
		 	 	if (taxPct[x]>highestValue) { 
					highestValue = taxPct[x];
					highestPos = x;
				}
			}
			
			tempPct.push(highestValue); //puts the highest value found in a new temp array
			taxPct.splice(highestPos,1); //removes the value placed in the temp array from the original array
			tempTax = taxSums[highestPos]*1;
			tempTax = tempTax.toFixed(2);
			tempTax = tempTax*1; //toFixed converts it back to a string so must cast it again
			tempSums.push(tempTax);
			sum_of_all_taxes = sum_of_all_taxes + tempTax;
			taxSums.splice(highestPos,1);
		}
		
		taxPct = tempPct;
		taxSums = tempSums;
	} 
	
	else {
		
		if (taxSums[0]*1>0) {
		 	taxSums[0] = taxSums[0]*1; //cast to numeric
		 	taxSums[0] = taxSums[0].toFixed(2);
		 	taxSums[0] = taxSums[0]*1; //cast back to numeric
			sum_of_all_taxes = taxSums[0]; 
		}
	}
	
	var taxSum_rows = $("input[name='line_tax[]']").size();
	/* remove all current tax rows */
	if (taxSum_rows>0) {
	
		var tableSums 		= document.getElementById('table_sums');	
		var tableSums_rows	= tableSums.rows.length;
		
		for (i=0; i<taxSum_rows; i++) tableSums.deleteRow(5);
		
	 	document.getElementById('sum_blankAfterDiscountOrTaxTR').style.display='';
	}
	
	/* recalculates tax 2; does this here before outputting the content of tax row one to ensure tax row 1 is on top */
	var sum_tax2 = reCalculateTax2(tableID, taxPct);
	
	if (taxPct.length>0) {
	 
	 	document.getElementById('sum_blankAfterDiscountOrTaxTR').style.display='none';
	 
	 	for (i=0; i<taxPct.length;i++) {
	 	 
	 	 	if (taxPct.length-i>1) var paddingBottom = '1px'; 
			else {
			 	if (sum_tax2==0) var paddingBottom = '7px';
			 	else var paddingBottom = '1px';
			}
	
			var tableSums 		= document.getElementById('table_sums');	
			var tableSums_rows	= tableSums.rows.length;
			var taxName = document.getElementById('customization_taxname').value.replace(" ","&nbsp;");
	
			var taxPctOutput = taxPct[i]*1;
			var taxSumsOutput = taxSums[i]*1;
	
			var row = tableSums.insertRow(5+i);

			var newcell = row.insertCell(0);
			newcell.innerHTML = '<td></td>';
			newcell.style.width='0px';

			var newcell = row.insertCell(1);
			newcell.innerHTML = '<td>+&nbsp;'+taxName+'&nbsp;('+pad_zeros(taxPctOutput)+'%)</td>';
			newcell.style.width='200px';	
			newcell.style.fontSize='11px';
			newcell.style.fontFamily='verdana';	
			newcell.style.color='#3c3c3c';
			newcell.style.paddingLeft='10px';
			newcell.style.paddingBottom=paddingBottom;		
	
			var newcell = row.insertCell(2);
			newcell.innerHTML = '<td></td>';
			newcell.style.textAlign='right';		
			newcell.style.paddingRight='4px';
			newcell.style.paddingBottom=paddingBottom;
			newcell.style.borderRight='1px solid white';
			newcell.style.borderLeft='1px solid white';
	
			var newfield = document.createElement("input");
			newfield.name = 'line_tax[]';
			newfield.type = 'text';
			newfield.value = pad_zeros(taxSumsOutput);
			newfield.readOnly = 'true';	
			newfield.style.border='0px solid white';
			newfield.style.textAlign='right';
			newfield.style.width='100px';
			newfield.style.paddingRight='5px';	
			newfield.style.fontFamily='verdana';
			newfield.style.fontSize='13px';	
			newfield.style.color='#3c3c3c';				
			newcell.appendChild(newfield);
		}
	}

	return sum_of_all_taxes+sum_tax2;
}

 
function reCalculate(obj, tableID, verdi) {
	
	//will use these variables if this function must run twice... i.e. when this function changes the value of the cell to 0 (when NaN input)
	var original_obj = obj;
	var original_tableID = tableID;
	var original_verdi = verdi;
	
	//will only calculate the values if it is a valid number, i.e. non-NaN	
	if(!isNaN(verdi)) {

		//declares the variables 
	 	var old_line_amount = 0;
 		var new_line_amount	= 0;
 
		//won't go through the lines if there's only a change in the discount
		if (obj.id!="sum_discount") {

			//declare more variables
		   	var table 		= document.getElementById(tableID);
	 		var rowCount 	= table.rows.length;
		 	var rowNumber	= 0;
 			var node 		= obj;
	
			//finds the line number the change happened at
		    while ( node != null )  {
    	    	if (node.tagName == "TR" ) { 
			 		rowNumber = node.rowIndex;
    	            break;
    		    }
        		node = node.parentNode;
		    }	
		
			var id = (rowNumber-1);

			/* recalculates: 
			(1) gets the old line_amount
			(2) calculates the new line amount
			(3) gets the old sums 
			(4) subtracts the old line_amount from the old sums
			(5) adds the new line_amount to the sums
			*/

			old_line_amount = document.getElementsByName("total[]")[id].value;
			new_line_amount = document.getElementsByName("unit_price[]")[id].value * document.getElementsByName("qty[]")[id].value;	
			document.getElementsByName("total[]")[id].value = new_line_amount.toFixed(2);
			
		}
		
		//calculate sums
		var old_sum_subtotal = document.getElementsByName("sum_subtotal")[0].value;
		var new_sum_subtotal = old_sum_subtotal - old_line_amount + new_line_amount;

		var discount = parseFloat(document.getElementsByName("sum_discount")[0].value); //multiplies with 1 to make toFixed work
        if (isNaN(discount)) discount=0;

		//must write these back into the form because they are used by the tax recalculation below
		document.getElementsByName("sum_subtotal")[0].value = new_sum_subtotal.toFixed(2);
		document.getElementsByName("sum_discount")[0].value = discount.toFixed(2);

		var new_sum_tax = reCalculateTax(tableID);

        var sum_total = new_sum_subtotal + new_sum_tax - discount;
		var amount_paid = parseFloat(document.getElementsByName("amount_paid")[0].value); //cast it to numeric
		if (amount_paid=="0.00") amount_paid = 0; //toFixed doesn't work on 0.00 so this is a fix for it...
		var balance_due = sum_total - amount_paid;
		
		//gets the currency from the invoice form
		var currency_symbol = get_currency_symbol(document.getElementsByName("currency_code")[0].value);

		//writes the rest back into the form
		document.getElementsByName("sum_total")[0].value = sum_total.toFixed(2);
		document.getElementsByName("amount_paid")[0].value = amount_paid.toFixed(2);
		document.getElementsByName("balance_due")[0].value = currency_symbol+balance_due.toFixed(2);

	} else {
		obj.style.color = 'silver';	

		if (obj.id!="sum_discount") {
			
			obj = obj.parentNode; 		//input -> td
			colNo = obj.cellIndex;
			obj = obj.parentNode;  		//td -> tr
			rowNo = obj.rowIndex;
			rowNo = rowNo-1;
			if (colNo==3) document.getElementsByName("unit_price[]")[rowNo].value = "0.00"; 
			else if (colNo==4) document.getElementsByName("qty[]")[rowNo].value = "0.00";
			else if (colNo==5) document.getElementsByName("tax[]")[rowNo].value = "0.00";			
		}
		else document.getElementsByName("sum_discount")[0].value = "0.00";		

		//recalculates everything after having set the NaN to 0.00
		reCalculate(original_obj, original_tableID, "0.00");

		alert(AynaxMessages.VALID_NUMBER);
	}
}

function reCalculateDeleteRow(rowIndex) {
	//recalculates sum_subtotal, sum_total and balance_due when a row has been deleted. Does this by subtracting the line_total from the aforementioned variables.

	var id = (rowIndex-1);	

	//picks up the necessary variables
	var line_total = document.getElementsByName("total[]")[id].value;
	var sum_subtotal = document.getElementsByName('sum_subtotal')[0].value;

	//recalculates the sum_subtotal, tax and balance_due
	sum_subtotal = sum_subtotal - line_total;
	
	//puts the variables back into the form
	document.getElementsByName('sum_subtotal')[0].value = sum_subtotal.toFixed(2);
}

function zapthisrow(from, tableID) {
    var node = from;
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;
    //alert(rowCount);

    while ( node != null )    {
        if (node.tagName == "TR" ) 	{
            //alert("we could zap the TR with rowIndex " + node.rowIndex);
	        if(rowCount <= 2) { 
				//alert("Cannot delete all the rows.");
       		    break;
       		} else {
	            reCalculateDeleteRow(node.rowIndex);
   	    	    table.deleteRow(node.rowIndex);
   	    	    reCalculate(document.getElementById('sum_discount'),'dataTable','0.00');
       			return;
       		}
   		}
   		node = node.parentNode;
	}
}

function isNumberKey(sender, evt)
{
    // allows only numbers, decimal point, and comma
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46 && charCode != 44) return false;
}

function sanitizeInvoiceLineValues(obj) {

	/* used by:
	/* --------------------------------------------------------
	/* invoiceForm.inc
	/* -------------------------------------------------------- */

	if (obj.value.search(/[^0-9.-]/i)!=-1)  {
	 	var match = obj.value.match(/[^0-9.-]/i);
	 	if (match==" ") var space="Empty space"; else var space="";
		obj.value = obj.value.replace(/[^0-9.-]/i,'');
		alert(AynaxMessages.ILLEGAL_CHARACTER_REMOVE +match+space+AynaxMessages.ALLOW_INPUT);	
	}
}

function pad_zeros(value) {

 	//sets everything to at least two decimals; removes 3+ zero decimas, keeps non-zero decimals
	
 	var new_value = value*1; //removes trailing zeros
	new_value = new_value+''; //casts it to string

	pos = new_value.indexOf('.');
	
	if (pos==-1) new_value=new_value+'.00';
	else {
		
		var integer = new_value.substring(0,pos);
		var decimals = new_value.substring(pos+1);
		while(decimals.length<2) decimals=decimals+'0';
		new_value = integer+'.'+decimals;		
	}
	
	return new_value;
}

function checkIfEmpty(obj) {
 
 	var new_value = obj.value;
 	
 	if (new_value=='') {
		new_value = '0.00'; 
		new_color = 'silver'; 
	}
	
 	else {
 
 		new_value = pad_zeros(new_value);
		new_color = '#3c3c3c';
	}

	obj.value = new_value; 
	obj.style.color = new_color;
}

function resetInvoiceForm() {

	var now = new Date();

	var day = now.getDate()+""; //adds the quotes to convert the int->string
	if (day.length==1) day = '0'+day;

	var month = now.getMonth();
	month++; //in javascript january is month 0, feb month 1, etc. so has to increase by one
	month=month+"";
	if (month.length==1) month = '0'+month;	
	
	var today = month+"/"+day+"/"+now.getFullYear();






    document.getElementsByName("from_name")[0].value = AynaxMessages.YOUR_NAME;
	document.getElementsByName("from_name")[0].style.color = "silver";
	document.getElementsByName("from_street")[0].value = AynaxMessages.STREET;
	document.getElementsByName("from_street")[0].style.color = "silver";
		
	document.getElementsByName("from_street2")[0].value = AynaxMessages.STREET2;
	document.getElementsByName("from_street2")[0].style.color = "silver";
	document.getElementsByName("from_city")[0].value = AynaxMessages.CITY;
	document.getElementsByName("from_city")[0].style.color = "silver";
	document.getElementsByName("from_state")[0].value = "";	
	document.getElementsByName("from_zip")[0].value = AynaxMessages.ZIP;
	document.getElementsByName("from_zip")[0].style.color = "silver";

	if (document.getElementsByName("to_attention")[0]!=null) document.getElementsByName("to_attention")[0].value = AynaxMessages.ATTENTION;
	if (document.getElementsByName("to_attention")[0]!=null) document.getElementsByName("to_attention")[0].style.color = "silver";
	document.getElementsByName("to_name")[0].value = AynaxMessages.TO_NAME;
	document.getElementsByName("to_name")[0].style.color = "silver";
	document.getElementsByName("to_street")[0].value = AynaxMessages.STREET;
	document.getElementsByName("to_street")[0].style.color = "silver";
	document.getElementsByName("to_street2")[0].value = AynaxMessages.STREET2;
	document.getElementsByName("to_street2")[0].style.color = "silver";	
	document.getElementsByName("to_city")[0].value = AynaxMessages.CITY;
	document.getElementsByName("to_city")[0].style.color = "silver";	
	document.getElementsByName("to_state")[0].value = "";	
	document.getElementsByName("to_zip")[0].value = AynaxMessages.ZIP;
	document.getElementsByName("to_zip")[0].style.color = "silver";

	document.getElementsByName("invoice_number")[0].value = "0000001";
	document.getElementsByName("po_number")[0].value = "";
	document.getElementsByName("invoice_date")[0].value = today;
	document.getElementsByName("payment_due_date")[0].value = today;	
	
	var table = document.getElementById('dataTable');
	var rowCount 	= (table.rows.length-1);	
	
	for (i=0; i<rowCount; i++) {

		/* first two rows are 0 and 1 when using getElementsByName but 1 and 2 when using deleteRow (includes the headrow); therefore, row 3 and onwards should be deleted */

	 	if (i>1) table.deleteRow(3);
	 	else {
			document.getElementsByName("item[]")[i].value = "";	
			document.getElementsByName("description[]")[i].value = ""; 
			document.getElementsByName("description[]")[i].rows=1;
			document.getElementsByName("unit_price[]")[i].value = "0.00";
			document.getElementsByName("unit_price[]")[i].style.color = "silver";		
			document.getElementsByName("qty[]")[i].value = "0.00";
			document.getElementsByName("qty[]")[i].style.color = "silver";		
			document.getElementsByName("tax[]")[i].value = "0.00";
			document.getElementsByName("tax[]")[i].style.color = "silver";		
			document.getElementsByName("total[]")[i].value = "0.00";
		}		
	}
	
	document.getElementsByName("invoice_notes")[0].value = "";		
	document.getElementsByName("sum_subtotal")[0].value = "0.00";
	document.getElementsByName("sum_discount")[0].value = "0.00";	
	document.getElementsByName("sum_tax")[0].value = "0.00";	
	document.getElementsByName("sum_total")[0].value = "0.00";	
	document.getElementsByName("amount_paid")[0].value = "0.00";
	document.getElementsByName("balance_due")[0].value = "0.00";		
}		



function currentWindow() { 
 
 	/* only the print button should launch a different window; uses this to reset the window for the other buttons */	 	
	document.getElementById("invoice_form").target = "_self"; 
}


function newWindow() {
 
 	/* launches a new window for the print version of the invoice */

	/* if inside the application */
 	if (document.getElementById("print_form")!=null) document.getElementById("print_form").target = "fenster";
 	
 	/* if using the free invoice */	
	else if (document.getElementById("invoice_form")!=null) document.getElementById("invoice_form").target = "fenster";
	
 	
	printWindow = window.open('','fenster','width=760,height=800,top=0; left=0; scrollbars=yes, menubar=yes, toolbar=no');	

	/* must do an extra test for Chrome since focus() doesn't work on an already opened window */
	var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
	if (is_chrome) {
		if(typeof(printWindow)!='undefined' && !printWindow.closed) {
			printWindow.blur();
		}
		else {
			printWindow = window.open('','fenster','width=740,height=800,top=0; left=0; scrollbars=yes, menubar=yes, toolbar=no');	
		}
	}
	printWindow.focus();
}

		function showOrHideCustomizationLink(newStatus) {
			
			if (newStatus=="show") {
				document.getElementById('customization_options').value='on';
				document.getElementById('showCustomization').style.display='none';
				document.getElementById('hideCustomization').style.display='';
				document.getElementById('divWithCustomization').style.display='';				
			}
			else {
				document.getElementById('customization_options').value='off';
				document.getElementById('hideCustomization').style.display='none';
				document.getElementById('showCustomization').style.display='';
				document.getElementById('divWithCustomization').style.display='none';				
			}			
		}


		function toggleCustomization(newStatus) {

			//document.getElementById('fpi_showCustomization').value=newStatus;

			if (newStatus == "on") {
			 	
				document.getElementById('customization_options').value="on"; 			 	
				document.getElementById('toggleCustomizationOn').style.display="none";
				document.getElementById('toggleCustomizationOff').style.display="";				
				document.getElementById('divWithCustomization').style.display="block";				
			}
			else {
				document.getElementById('customization_options').value="off"; 			 				 
				document.getElementById('toggleCustomizationOn').style.display="";
				document.getElementById('toggleCustomizationOff').style.display="none";
				document.getElementById('divWithCustomization').style.display="none";									
				
			}
		}

		function setTaxNodeToZero() {
			
			/* sets the tax node to zero here, in a separate function;  */
			/* this is to make it possible to use settimeout to call this function, */
			/* to avoid firefox from shaking when the values are set to 0.00 */
			
			var table = document.getElementById('dataTable');
			var rowCount = table.rows.length;					
					
			for (i=0;i<rowCount;i++) {
				var rowNode = table.rows[i];
					
				//changes the classes of description, unit price, quantity and amount; i>0 because don't need the headline
				if (i>0) {

					//grabs the input elements in this row and resets values (tax) and class names (unit price, quantity and amount)
					var node = rowNode.cells[5].getElementsByTagName("input")[0];
					node.value = '0.00';
				}
			}
		}
		
		
		function setTaxNode2ToZero() {
			
			/* sets the tax node to zero here, in a separate function;  */
			/* this is to make it possible to use settimeout to call this function, */
			/* to avoid firefox from shaking when the values are set to 0.00 */
			
			var table = document.getElementById('dataTable');
			var rowCount = table.rows.length;					
					
			for (i=0;i<rowCount;i++) {
				var rowNode = table.rows[i];
					
				//changes the classes of description, unit price, quantity and amount; i>0 because don't need the headline
				if (i>0) {

					//grabs the input elements in this row and resets values (tax) and class names (unit price, quantity and amount)
					var node = rowNode.cells[6].getElementsByTagName("input")[0];
					node.value = '0.00';
				}
			}
		}		
		
		function get_currency_symbol(currency_code) {
            if (currency_code=="USD") return '$';
            else if (currency_code=="CAD") return '$';
            else if (currency_code=="EUR") return decodeURI('\u20ac');
            else if (currency_code=="GBP") return decodeURI('\xa3');
            else if (currency_code=="AUD") return '$';
            else if (currency_code=="AED") return 'DH';
            else if (currency_code=="AFN") return 'Af ';
            else if (currency_code=="ALL") return 'Lek ';
            else if (currency_code=="AMD") return 'Ad ';
            else if (currency_code=="ANG") return 'f ';
            else if (currency_code=="AOA") return 'Kz ';
            else if (currency_code=="ARS") return '$';
            else if (currency_code=="AWG") return 'f ';
            else if (currency_code=="AZN") return 'm ';
            else if (currency_code=="BAM") return 'KM ';
            else if (currency_code=="BBD") return '$';
            else if (currency_code=="BDT") return 'Tk ';
            else if (currency_code=="BGN") return 'lev ';
            else if (currency_code=="BHD") return 'BD ';
            else if (currency_code=="BIF") return 'Fr ';
            else if (currency_code=="BMD") return '$';
            else if (currency_code=="BND") return '$';
            else if (currency_code=="BOB") return '$b ';
            else if (currency_code=="BRL") return 'R$ ';
            else if (currency_code=="BSD") return '$';
            else if (currency_code=="BTN") return '$';
            else if (currency_code=="BWP") return 'P ';
            else if (currency_code=="BZD") return 'BZ ';
            else if (currency_code=="CDF") return 'Fr ';
            else if (currency_code=="CHF") return 'Fr ';
            else if (currency_code=="CLP") return '$';
            else if (currency_code=="CNY") return decodeURI('\xa5');
            else if (currency_code=="COP") return '$';
            else if (currency_code=="CRC") return 'c ';
            else if (currency_code=="CUP") return '$';
            else if (currency_code=="CVE") return 'Esc ';
            else if (currency_code=="CZK") return 'Kc ';
            else if (currency_code=="DJF") return 'Fr ';
            else if (currency_code=="DKK") return 'Kr ';
            else if (currency_code=="DOP") return 'P';
            else if (currency_code=="DZD") return 'DA ';
            else if (currency_code=="EEK") return 'kr ';
            else if (currency_code=="EGP") return decodeURI('\xa3');
            else if (currency_code=="ERN") return 'Nfk ';
            else if (currency_code=="ETB") return 'BR ';
            else if (currency_code=="FJD") return '$';
            else if (currency_code=="FKP") return decodeURI('\xa3');
            else if (currency_code=="GEL") return 'GL ';
            else if (currency_code=="GHS") return 'Ghc ';
            else if (currency_code=="GIP") return decodeURI('\xa3');
            else if (currency_code=="GMD") return 'D';
            else if (currency_code=="GNF") return 'Fr ';
            else if (currency_code=="GTQ") return 'Q ';
            else if (currency_code=="GYD") return '$';
            else if (currency_code=="HKD") return '$';
            else if (currency_code=="HNL") return 'L ';
            else if (currency_code=="HRK") return 'kn ';
            else if (currency_code=="HTG") return 'G';
            else if (currency_code=="HUF") return 'Ft ';
            else if (currency_code=="IDR") return 'Rp ';
            else if (currency_code=="ILS") return 'NIS ';
            else if (currency_code=="INR") return 'R ';
            else if (currency_code=="IQD") return 'ID';
            else if (currency_code=="IRR") return 'IR ';
            else if (currency_code=="ISK") return 'kr ';
            else if (currency_code=="JMD") return 'J$ ';
            else if (currency_code=="JOD") return 'JD ';
            else if (currency_code=="JPY") return decodeURI('\xa5');
            else if (currency_code=="KES") return decodeURI('Sh ');
            else if (currency_code=="KGS") return 'som ';
            else if (currency_code=="KHR") return 'R ';
            else if (currency_code=="KMF") return decodeURI('Fr ');
            else if (currency_code=="KPW") return 'W ';
            else if (currency_code=="KRW") return 'W ';
            else if (currency_code=="KWD") return 'K.D. ';
            else if (currency_code=="KYD") return '$';
            else if (currency_code=="KZT") return 'T ';
            else if (currency_code=="LAK") return 'KN ';
            else if (currency_code=="LBP") return decodeURI('\xa3');
            else if (currency_code=="LKR") return 'Rs ';
            else if (currency_code=="LRD") return '$';
            else if (currency_code=="LSL") return 'L';
            else if (currency_code=="LTL") return 'Lt ';
            else if (currency_code=="LVL") return 'Ls ';
            else if (currency_code=="LYD") return 'LD ';
            else if (currency_code=="MAD") return 'D';
            else if (currency_code=="MDL") return 'L';
            else if (currency_code=="MGA") return 'Ar ';
            else if (currency_code=="MKD") return 'D ';
            else if (currency_code=="MNT") return 'T ';
            else if (currency_code=="MOP") return 'P';
            else if (currency_code=="MRO") return 'UM ';
            else if (currency_code=="MUR") return 'Rs ';
            else if (currency_code=="MVR") return 'Rf ';
            else if (currency_code=="MWK") return 'MK ';
            else if (currency_code=="MXN") return '$';
            else if (currency_code=="MYR") return 'RM ';
            else if (currency_code=="MZN") return 'MT ';
            else if (currency_code=="NAD") return '$';
            else if (currency_code=="NGN") return 'N ';
            else if (currency_code=="NIO") return 'C$ ';
            else if (currency_code=="NOK") return 'kr ';
            else if (currency_code=="NPR") return 'Rs ';
            else if (currency_code=="NZD") return '$';
            else if (currency_code=="OMR") return 'R ';
            else if (currency_code=="PAB") return 'B/. ';
            else if (currency_code=="PEN") return 'S/. ';
            else if (currency_code=="PGK") return 'K';
            else if (currency_code=="PHP") return 'P ';
            else if (currency_code=="PKR") return 'Rs ';
            else if (currency_code=="PLN") return 'zl ';
            else if (currency_code=="PYG") return 'Gs ';
            else if (currency_code=="QAR") return 'QR ';
            else if (currency_code=="RON") return 'L';
            else if (currency_code=="RSD") return 'D ';
            else if (currency_code=="RUB") return 'p. ';
            else if (currency_code=="RWF") return decodeURI('Fr ');
            else if (currency_code=="SAR") return 'R ';
            else if (currency_code=="SBD") return '$';
            else if (currency_code=="SCR") return 'Rs ';
            else if (currency_code=="SDG") return '$';
            else if (currency_code=="SEK") return 'Kr';
            else if (currency_code=="SGD") return '$';
            else if (currency_code=="SHP") return decodeURI('\xa3');
            else if (currency_code=="SKK") return 'Sk ';
            else if (currency_code=="SLL") return 'Le ';
            else if (currency_code=="SRD") return '$';
            else if (currency_code=="SSP") return decodeURI('\xa3');
            else if (currency_code=="STD") return 'Db ';
            else if (currency_code=="SYP") return decodeURI('\xa3');
            else if (currency_code=="SZL") return 'L';
            else if (currency_code=="THB") return 'B ';
            else if (currency_code=="TJS") return 'SM ';
            else if (currency_code=="TMM") return 'm';
            else if (currency_code=="TND") return 'D ';
            else if (currency_code=="TOP") return 'T$ ';
            else if (currency_code=="TRY") return 'TR ';
            else if (currency_code=="TTD") return 't ';
            else if (currency_code=="TWD") return '$';
            else if (currency_code=="TZS") return 'Sh ';
            else if (currency_code=="UAH") return 'UH ';
            else if (currency_code=="UGX") return 'Sh ';
            else if (currency_code=="UYU") return '$U ';
            else if (currency_code=="UZS") return 'som ';
            else if (currency_code=="VEF") return 'Bs ';
            else if (currency_code=="VND") return 'd ';
            else if (currency_code=="VUV") return 'Vt ';
            else if (currency_code=="WST") return 'T';
            else if (currency_code=="XAF") return 'Fr ';
            else if (currency_code=="XCD") return '$';
            else if (currency_code=="XOF") return 'Fr ';
            else if (currency_code=="XPF") return 'Fr ';
            else if (currency_code=="YER") return 'R ';
            else if (currency_code=="ZAR") return 'R ';
            else if (currency_code=="ZMK") return 'ZK ';

            /*
            if (currency_code=="USD") return '$';
            else if (currency_code=="CAD") return '$';
            else if (currency_code=="EUR") return decodeURI('\u20ac');
            else if (currency_code=="GBP") return decodeURI('\xa3');
            else if (currency_code=="AUD") return '$';
            else if (currency_code=="AED") return '';
            else if (currency_code=="AFN") return decodeURI('\u060b');
            else if (currency_code=="ALL") return decodeURI('\x4c\x65\x6b ');
            else if (currency_code=="AMD") return decodeURI('DH ');
            else if (currency_code=="ANG") return decodeURI('\u0192');
            else if (currency_code=="AOA") return decodeURI('Kz ');
            else if (currency_code=="ARS") return '$';
            else if (currency_code=="AWG") return decodeURI('\u0192');
            else if (currency_code=="AZN") return decodeURI('\u043c\u0430\u043d ');
            else if (currency_code=="BAM") return decodeURI('\x4b\x4d ');
            else if (currency_code=="BBD") return '$';
            else if (currency_code=="BDT") return decodeURI('\u09F3');
            else if (currency_code=="BGN") return decodeURI('\u043b\u0432 ');
            else if (currency_code=="BHD") return decodeURI('\u0628\u002E\u062F');
            else if (currency_code=="BIF") return 'Fr ';
            else if (currency_code=="BMD") return '$';
            else if (currency_code=="BND") return '$';
            else if (currency_code=="BOB") return decodeURI('\x24\x62 ');
            else if (currency_code=="BRL") return decodeURI('\x52\x24 ');
            else if (currency_code=="BSD") return '$';
            else if (currency_code=="BTN") return '$';
            else if (currency_code=="BWP") return decodeURI('\x50');
            else if (currency_code=="BZD") return decodeURI('\x42\x5a\x24');
            else if (currency_code=="CDF") return 'Fr ';
            else if (currency_code=="CHF") return 'Fr ';
            else if (currency_code=="CLP") return '$';
            else if (currency_code=="CNY") return decodeURI('\xa5');
            else if (currency_code=="COP") return '$';
            else if (currency_code=="CRC") return decodeURI('\u20a1');
            else if (currency_code=="CUP") return decodeURI('\u20b1');
            else if (currency_code=="CVE") return 'Esc ';
            else if (currency_code=="CZK") return decodeURI('\x4b\u010d ');
            else if (currency_code=="DJF") return 'Fr ';
            else if (currency_code=="DKK") return decodeURI('\x6b\x72 ');
            else if (currency_code=="DOP") return decodeURI('\x52\x44\x24');
            else if (currency_code=="DZD") return decodeURI('\u062F\u002E\u062C');
            else if (currency_code=="EEK") return decodeURI('\x6b\x72 ');
            else if (currency_code=="EGP") return decodeURI('\xa3');
            else if (currency_code=="ERN") return 'Nfk ';
            else if (currency_code=="ETB") return 'KR ';
            else if (currency_code=="FJD") return '$';
            else if (currency_code=="FKP") return decodeURI('\xa3');
            else if (currency_code=="GEL") return decodeURI('\u10DA');
            else if (currency_code=="GHS") return 'Ghc ';
            else if (currency_code=="GIP") return decodeURI('\xa3');
            else if (currency_code=="GMD") return 'D';
            else if (currency_code=="GNF") return 'Fr ';
            else if (currency_code=="GTQ") return decodeURI('\x51');
            else if (currency_code=="GYD") return '$';
            else if (currency_code=="HKD") return '$';
            else if (currency_code=="HNL") return decodeURI('\x4c');
            else if (currency_code=="HRK") return decodeURI('\x6b\x6e ');
            else if (currency_code=="HTG") return 'G';
            else if (currency_code=="HUF") return decodeURI('\x46\x74 ');
            else if (currency_code=="IDR") return decodeURI('\x52\x70 ');
            else if (currency_code=="ILS") return decodeURI('\u20aa');
            else if (currency_code=="INR") return decodeURI('\u20b9');
            else if (currency_code=="IQD") return decodeURI('\u0639\u002E\u062F');
            else if (currency_code=="IRR") return decodeURI('\ufdfc');
            else if (currency_code=="ISK") return decodeURI('\x6b\x72 ');
            else if (currency_code=="JMD") return decodeURI('\x4a\x24');
            else if (currency_code=="JOD") return decodeURI('\u062F\u002E\u0627');
            else if (currency_code=="JPY") return decodeURI('\xa5');
            else if (currency_code=="KES") return decodeURI('Sh ');
            else if (currency_code=="KGS") return decodeURI('\u043b\u0432 ');
            else if (currency_code=="KHR") return decodeURI('\u17db');
            else if (currency_code=="KMF") return decodeURI('Fr ');
            else if (currency_code=="KPW") return decodeURI('\u20a9');
            else if (currency_code=="KRW") return decodeURI('\u20a9');
            else if (currency_code=="KWD") return decodeURI('\u062F\u002E\u0643');
            else if (currency_code=="KYD") return '$';
            else if (currency_code=="KZT") return decodeURI('\u043b\u0432 ');
            else if (currency_code=="LAK") return decodeURI('\u20ad');
            else if (currency_code=="LBP") return decodeURI('\xa3');
            else if (currency_code=="LKR") return decodeURI('\u20a8 ');
            else if (currency_code=="LRD") return '$';
            else if (currency_code=="LSL") return 'L';
            else if (currency_code=="LTL") return decodeURI('\x4c\x74 ');
            else if (currency_code=="LVL") return decodeURI('\x4c\x74 ');
            else if (currency_code=="LYD") return decodeURI('\u0644\u002E\u062F');
            else if (currency_code=="MAD") return decodeURI('\u062F\u002E\u0645\u002E');
            else if (currency_code=="MDL") return 'L';
            else if (currency_code=="MGA") return 'Ar ';
            else if (currency_code=="MKD") return decodeURI('\u0434\u0435\u043d ');
            else if (currency_code=="MNT") return decodeURI('\u20ae');
            else if (currency_code=="MOP") return 'P';
            else if (currency_code=="MRO") return 'UM ';
            else if (currency_code=="MUR") return decodeURI('\u20a8');
            else if (currency_code=="MVR") return decodeURI('\xDE\x83\x2E');
            else if (currency_code=="MWK") return 'MK ';
            else if (currency_code=="MXN") return '$';
            else if (currency_code=="MYR") return decodeURI('\x52\x4d ');
            else if (currency_code=="MZN") return decodeURI('\x4d\x54 ');
            else if (currency_code=="NAD") return '$';
            else if (currency_code=="NGN") return decodeURI('\u20a6');
            else if (currency_code=="NIO") return decodeURI('\x43\x24');
            else if (currency_code=="NOK") return decodeURI('\x6b\x72 ');
            else if (currency_code=="NPR") return decodeURI('\u20a8');
            else if (currency_code=="NZD") return '$';
            else if (currency_code=="OMR") return decodeURI('\ufdfc');
            else if (currency_code=="PAB") return decodeURI('\x42\x2f\x2e');
            else if (currency_code=="PEN") return decodeURI('\x53\x2f\x2e');
            else if (currency_code=="PGK") return 'K';
            else if (currency_code=="PHP") return decodeURI('\u20b1');
            else if (currency_code=="PKR") return decodeURI('\u20a8');
            else if (currency_code=="PLN") return decodeURI('\x7a\u0142 ');
            else if (currency_code=="PYG") return decodeURI('\x47\x73 ');
            else if (currency_code=="QAR") return decodeURI('\ufdfc');
            else if (currency_code=="RON") return 'L';
            else if (currency_code=="RSD") return decodeURI('\u0414\u0438\u043d\x2e');
            else if (currency_code=="RUB") return 'p. ';
            else if (currency_code=="RWF") return decodeURI('Fr ');
            else if (currency_code=="SAR") return decodeURI('\ufdfc');
            else if (currency_code=="SBD") return '$';
            else if (currency_code=="SCR") return decodeURI('\u20a8');
            else if (currency_code=="SDG") return '$';
            else if (currency_code=="SEK") return decodeURI('\x6b\x72 ');
            else if (currency_code=="SGD") return '$';
            else if (currency_code=="SHP") return decodeURI('\xa3');
            else if (currency_code=="SKK") return 'Sk ';
            else if (currency_code=="SLL") return 'Le ';
            else if (currency_code=="SRD") return '$';
            else if (currency_code=="SSP") return decodeURI('\xa3');
            else if (currency_code=="STD") return 'Db ';
            else if (currency_code=="SYP") return decodeURI('\xa3');
            else if (currency_code=="SZL") return 'L';
            else if (currency_code=="THB") return decodeURI('\u0e3f');
            else if (currency_code=="TJS") return 'SM ';
            else if (currency_code=="TMM") return 'm';
            else if (currency_code=="TND") return decodeURI('\u062F\u002E\u062A');
            else if (currency_code=="TOP") return 'T$';
            else if (currency_code=="TRY") return 'TL ';
            else if (currency_code=="TTD") return decodeURI('\x54\x54\x24');
            else if (currency_code=="TWD") return '$';
            else if (currency_code=="TZS") return 'Sh ';
            else if (currency_code=="UAH") return decodeURI('\u20b4');
            else if (currency_code=="UGX") return 'Sh ';
            else if (currency_code=="UYU") return decodeURI('\x24\x55 ');
            else if (currency_code=="UZS") return decodeURI('\u043b\u0432 ');
            else if (currency_code=="VEF") return decodeURI('\x42\x73 ');
            else if (currency_code=="VND") return decodeURI('\u20ab');
            else if (currency_code=="VUV") return 'Vt ';
            else if (currency_code=="WST") return 'T';
            else if (currency_code=="XAF") return 'Fr ';
            else if (currency_code=="XCD") return '$';
            else if (currency_code=="XOF") return 'Fr ';
            else if (currency_code=="XPF") return 'Fr ';
            else if (currency_code=="YER") return decodeURI('\ufdfc');
            else if (currency_code=="ZAR") return decodeURI('\x52');
            else if (currency_code=="ZMK") return 'ZK ';
            
            
            
            */
		} 
		
		function customization_toggleTaxName(obj) {
		 
		 	if (obj.value=="") obj.value = AynaxMessages.TAX;

			/* save the value in the invoice form */			
			if (document.getElementById('taxname')!=null) document.getElementById('taxname').value=obj.value;

			/* update invoice form; does this by recalculating the tax */
			reCalculateTax('dataTable');		
						
		}		


		function customization_toggleTaxName2(obj) {
		 
		 	if (obj.value=="") obj.value = AynaxMessages.TAX;

			/* save the value in the invoice form */			
			if (document.getElementById('taxname2')!=null) document.getElementById('taxname2').value=obj.value;

			/* update invoice form; does this by recalculating the tax */
			reCalculateTax('dataTable');		
						
		}		


		function customization_showSecondTax() {
		 
			document.getElementById('tax2_TR1').style.display="";
			document.getElementById('tax2_TR2').style.display="";
			document.getElementById('second_tax_link').innerHTML='<a onclick="customization_hideSecondTax();" style="color:#1869B8;font-size:10px;cursor:pointer;">' + AynaxMessages.HIDE_SECOND_TAX +'</a>';
		}		



		function customization_hideSecondTax() {
		 
			document.getElementById('tax2_TR1').style.display="none";
			document.getElementById('tax2_TR2').style.display="none";
			document.getElementById('second_tax_link').innerHTML='<a onclick="customization_showSecondTax();" style="color:#1869B8;font-size:10px;cursor:pointer;">' + AynaxMessages.ADD_SECOND_TAX +'</a>';
		}		


		
		function customization_toggleCurrency(obj) {

			/* save the value in the invoice form */			
			if (document.getElementById('save_currency_code')!=null) document.getElementById('save_currency_code').value=obj.value;

			/* recalculates the balance */
			var balance_due = document.getElementById('sum_total').value-document.getElementById('amount_paid').value;
			balance_due = balance_due.toFixed(2);

			/* update invoice form */			
			document.getElementById('balance_due').value = get_currency_symbol(obj.value)+balance_due;
			
			/* check if currency_code should be shown */
			customization_toggleShowCurrencyCode(document.getElementById('show_currency_code'));

		}
		
		function customization_toggleShowCurrencyCode(obj) {

			if (obj.checked) {

				/* save the value in the invoice form */			
				if (document.getElementById('save_show_currency_code')!=null) document.getElementById('save_show_currency_code').value=obj.value;

				/* get the currency code from the currency_code drop down */
				var currency_code = document.getElementById("currency_code").options[document.getElementById("currency_code").selectedIndex].value;
			
				/* update invoice form */			
				document.getElementById('currency_code_output').innerHTML = '('+currency_code+')';
			}

			else {

				/* save the value in the invoice form */			
				if (document.getElementById('save_show_currency_code')!=null) document.getElementById('save_show_currency_code').value='';

				/* update invoice form */			
				document.getElementById('currency_code_output').innerHTML = '';
			}
		}		


		function customization_toggleDateFormat(obj) {

			/* only needs to save the value in the invoice form; the updating is done by jquery */			
			if (document.getElementById('customization_save_date_format')!=null) document.getElementById('customization_save_date_format').value=obj.value;
			
		}


		function customization_toggleLanguage(obj) {

			/* only needs to save the value in the invoice form; the updating is done by jquery */			
			if (document.getElementById('language')!=null) document.getElementById('language').value=obj.value;
			
			//updates the heading in the invoice template			
			document.getElementById('invoice_heading').value=document.getElementById("translation_"+obj.value).value;
			document.getElementById('invoice_heading_copy').value=document.getElementById('invoice_heading').value
		}

		
		function enableTax1(obj) {
			
			if (obj.checked) {
			 
			 	//if tax2 is enabled, automatically enable tax1
				if (!document.getElementById('customization_tax').checked) {
					document.getElementById('customization_tax').checked = true;
					customization_toggleFields(document.getElementById('customization_tax'));
				}
			}
		}


		function disableTax2(obj) {
			
			if (!obj.checked) {
			 
			 	//if tax1 is turned off, automatically remove tax2
				if (document.getElementById('customization_tax2').checked) {
					document.getElementById('customization_tax2').checked = false;
					customization_toggleFields(document.getElementById('customization_tax2'));
				}
			}
		}


		function customization_toggleFields(obj) {
			
			//alert(obj.checked+' '+obj.id);
			
			/* If the field has been checked */ 
			if (obj.checked) {
				
				/* show the right field depending on the object's id */
				
				if (obj.id=="customization_logo") { 
				 
					/* save value inside the invoice form */				 
				 	if (document.getElementById('customization_save_logo')!=null) document.getElementById('customization_save_logo').value='on';

					/* removes the regular headline; another will be placed below the logo */
				 	document.getElementById('invoiceHeadlineNoLogo').style.display='none';
			 	
				 	/* if there is already a logo in the session variable, show this logo; if not, show the upload form */
					if ((document.getElementById('customization_logoFilename_session')!=null)&&(document.getElementById('customization_logoFilename_session').value!="")) {
							document.getElementById('customization_uploadDelete').style.display="";
							document.getElementById('upload_area').className="invoiceForm_uploadArea_done";
							document.getElementById('customization_logoFilename').value=document.getElementById('customization_logoFilename_session').value;
							document.getElementById('upload_area').innerHTML='<img border=0 src="'+document.getElementById('customization_logoFilename').value+'">';						
						} 
					
					/* no logo in the session; show upload form */					
					else {
					 				 
						var class_name = 'invoiceForm_uploadArea';
						if (document.getElementById('upload_area_reload')) {
							if (document.getElementById('upload_area_reload').value=='white') {
								var class_name = 'invoiceForm_uploadAreaNoBg';
							}
						}

						document.getElementById('upload_area').className=class_name;
						document.getElementById('upload_area').innerHTML='<img border=0 src="images'+aynaxImageLanguagePath+'/your_logo_here2.png"><!-- <p style="vertical-align:top;color:silver;font-size:12px;font-family:verdana;text-align:right;margin-right:10px;margin-top:-5px;font-style:italic;">('+ AynaxMessages.DIMENSIONS_MAX +')</p> -->';						
						customization_uploadCreateForm();
					
					}
				 	
				 	/* shows the invoice headline beneath the logo */
					document.getElementById('invoiceHeadlineWhenLogo').style.display='';					
					
				}
				
				else if (obj.id=="customization_street2") { 
				 
					/* save value inside the invoice form */				 
					if (document.getElementById('customization_save_street2')!=null) document.getElementById('customization_save_street2').value='on';
				 
					document.getElementById('from_street2TR').style.display=''; 
					document.getElementById('from_street2BlankTR').style.display='';
					document.getElementById('from_street2TD').className='invoiceForm_fromNameTD_onFocus';
					document.getElementById('from_street2').style.backgroundColor='#FFFADC';					
					
					document.getElementById('to_street2TR').style.display=''; 
					document.getElementById('to_street2BlankTR').style.display='';
					document.getElementById('to_street2TD').className='invoiceForm_fromNameTD_onFocus';
					document.getElementById('to_street2').style.backgroundColor='#FFFADC';					
					
				}
				
				else if (obj.id=="customization_attention") { 
				 
					/* save value inside the invoice form */				 
					if (document.getElementById('customization_save_attention')!=null) document.getElementById('customization_save_attention').value='on';
				 
					document.getElementById('to_attentionTR').style.display=''; 
					document.getElementById('to_attentionBlankTR').style.display='';
					document.getElementById('to_attentionTD').className='invoiceForm_fromNameTD_onFocus';
					document.getElementById('to_attention').style.backgroundColor='#FFFADC';					
					
				}

				else if (obj.id=="customization_taxid1") { 
				 
					/* save value inside the invoice form */				 
					if (document.getElementById('customization_save_taxid1')!=null) document.getElementById('customization_save_taxid1').value='on';
				 
					document.getElementById('taxid1TR').style.display=''; 
					document.getElementById('taxid1BlankTR').style.display='';
					document.getElementById('taxid1TD').className='invoiceForm_fromNameTD_onFocus';
					document.getElementById('taxid1').style.backgroundColor='#FFFADC';					
					
				}
				
				else if (obj.id=="customization_taxid3") { 
				 
					/* save value inside the invoice form */				 
					if (document.getElementById('customization_save_taxid3')!=null) document.getElementById('customization_save_taxid3').value='on';
				 
					document.getElementById('taxid3TR').style.display=''; 
					document.getElementById('taxid3BlankTR').style.display='';
					document.getElementById('taxid3TD').className='invoiceForm_fromNameTD_onFocus';
					document.getElementById('taxid3').style.backgroundColor='#FFFADC';					
					
				}
				
			
				else if (obj.id=="customization_poNumber") { 
				 
					/* save value inside the invoice form */				 
					if (document.getElementById('customization_save_poNumber')!=null) document.getElementById('customization_save_poNumber').value='on';
				 
					document.getElementById('po_numberTR').style.display=''; 
					document.getElementById('po_numberBlankTR').style.display='';
					document.getElementById('po_numberTD').className='invoiceForm_fromNameTD_onFocus';
					document.getElementById('po_number').style.backgroundColor='#FFFADC';					
					
				}
				
				else if (obj.id=="customization_tax") { 
				 
					/* save value inside the invoice form */
					if (document.getElementById('customization_save_tax')!=null) document.getElementById('customization_save_tax').value='on';

					/* grabs the table, goes through each row and changes the style of cell 5 = tax */
					var table = document.getElementById('dataTable');
					var rowCount = table.rows.length;					
					
					for (i=0;i<rowCount;i++) {
						var rowNode = table.rows[i];
						rowNode.cells[5].style.display ='';
						
						//changes the classes of description, unit price, quantity and amount; i>0 because don't need the headline
						if (i>0) {

			
							rowNode.cells[5].className = 'invoiceDataTax_visible';							
	
							//changes background in the tax cells	
							rowNode.cells[5].style.backgroundColor = '#FFFADC';	
							
							var node = rowNode.cells[5].getElementsByTagName("input")[0];						 	
						 	node.value = '0.00';
						 	node.style.color = 'silver';
						 	node.style.backgroundColor = '#FFFADC';
							
							//grabs the various elements in this row and either changes background color (tax) or class (unit price, quantity, amount)
							var node = rowNode.cells[3].getElementsByTagName("input")[0];						 	
						 	node.className = 'inputInvoiceDataPriceOrQty_wTAX';
						 	
							var node = rowNode.cells[4].getElementsByTagName("input")[0];						 	
						 	node.className = 'inputInvoiceDataPriceOrQty_wTAX';
						 	
							var node = rowNode.cells[7].getElementsByTagName("input")[0];						 	
						 	node.className = 'inputInvoiceDataAmount_wTAX';

							
						}
					}
					
					/* sets new classes for the description, unit price & quantity and amount fields */

					//tax sum bottom
					//document.getElementById('sum_taxTR').style.display=''; 
					//document.getElementById('sum_discountTD').className='invoiceForm_fromNameTD_onFocus';
					//document.getElementById('sum_discount').style.backgroundColor='#FFFADC';					
					//document.getElementById('sum_blankSubtotalTR').style.display='none';
					//if (document.getElementById('customization_discount').checked==true) document.getElementById('sum_blankAfterDiscountOrTaxTR').style.display='none';					
				
				}
				
				
				else if (obj.id=="customization_tax2") { 
				 
					/* save value inside the invoice form */
					if (document.getElementById('customization_save_tax2')!=null) document.getElementById('customization_save_tax2').value='on';

					/* grabs the table, goes through each row and changes the style of cell 5 = tax */
					var table = document.getElementById('dataTable');
					var rowCount = table.rows.length;					
					
					for (i=0;i<rowCount;i++) {
						var rowNode = table.rows[i];
						rowNode.cells[6].style.display ='';
						
						//changes the classes of description, unit price, quantity and amount; i>0 because don't need the headline
						if (i>0) {

							rowNode.cells[6].className = 'invoiceDataTax_visible';							
	
							//changes background in the tax cells	
							rowNode.cells[6].style.backgroundColor = '#FFFADC';	
							
							var node = rowNode.cells[6].getElementsByTagName("input")[0];						 	
						 	node.value = '0.00';
						 	node.style.color = 'silver';
						 	node.style.backgroundColor = '#FFFADC';
							
							//grabs the various elements in this row and either changes background color (tax) or class (unit price, quantity, amount)
							var node = rowNode.cells[2].getElementsByTagName("textarea")[0];						 	
						 	node.className = 'inputInvoiceDataDescription_wTAX2';
						}
					}
				}				
				
				
				else if (obj.id=="customization_discount") { 
				 
					/* save value inside the invoice form */
					if (document.getElementById('customization_save_discount')!=null) document.getElementById('customization_save_discount').value='on';
				 
					document.getElementById('sum_discountTR').style.display=''; 
					document.getElementById('sum_discountTD').className='invoiceForm_fromNameTD_onFocus';
					document.getElementById('sum_discount').style.backgroundColor='#FFFADC';					
					document.getElementById('sum_blankSubtotalTR').style.display='none';
					if (document.getElementById('customization_tax').checked==false) document.getElementById('sum_blankAfterDiscountOrTaxTR').style.display='';					
				}
				
				
				
			/* if the field is empty */ 
			} else {
				
				
				if (obj.id=="customization_logo") { 
				 
					/* save value inside the invoice form */				 
				 	if (document.getElementById('customization_save_logo')!=null) { 
				 	
					  	//var old_value = document.getElementById('customization_save_logo').value;
						document.getElementById('customization_save_logo').value='';
						//document.getElementById('customization_save_logo').defaultValue=old_value;						
					}
					
				 	document.getElementById('customization_logoFilename').value='';				 	
				 
				 	document.getElementById('invoiceHeadlineNoLogo').style.display='';
				 
					document.getElementById('upload_area').innerHTML='';
					document.getElementById('upload_area').className="invoiceForm_uploadArea_hidden";
					document.getElementById('customization_uploadField').innerHTML="";					
					document.getElementById('customization_uploadField').className="invoiceForm_uploadField_hidden";			
					document.getElementById('customization_uploadDelete').style.display="none";	
					
					if (document.getElementById('upload_area_reload')) document.getElementById('upload_area_reload').value='';
				 	document.getElementById('invoiceHeadlineWhenLogo').style.display='none';
					

														
				}
				
				
				else if (obj.id=="customization_street2") { 
				 
				 	//save value inside the invoice form
					if (document.getElementById('customization_save_street2')!=null) document.getElementById('customization_save_street2').value='';
					
					//hide elements
					document.getElementById('from_street2TR').style.display='none'; 
					document.getElementById('from_street2BlankTR').style.display='none';
					document.getElementById('to_street2TR').style.display='none'; 
					document.getElementById('to_street2BlankTR').style.display='none';
					
					//reset values
					document.getElementById('from_street2').value= AynaxMessages.STREET2; 					
					document.getElementById('to_street2').value=AynaxMessages.STREET2; 					
					
					//reset colors
					document.getElementById('from_street2').style.color='silver'; 															
					document.getElementById('to_street2').style.color='silver'; 															
					
				}

				else if (obj.id=="customization_attention") { 
				 
				 	//save value inside the invoice form
					if (document.getElementById('customization_save_attention')!=null) document.getElementById('customization_save_attention').value='';
					
					//hide elements
					document.getElementById('to_attentionTR').style.display='none'; 
					document.getElementById('to_attentionBlankTR').style.display='none';
					
					//reset values
					document.getElementById('to_attention').value=AynaxMessages.ATTENTION; 					
					
					//reset colors
					document.getElementById('to_attention').style.color='silver'; 															
					
				}

				else if (obj.id=="customization_taxid1") { 
				 
				 	//save value inside the invoice form
					if (document.getElementById('customization_save_taxid1')!=null) document.getElementById('customization_save_taxid1').value='';
					
					//hide elements
					document.getElementById('taxid1TR').style.display='none'; 
					document.getElementById('taxid1BlankTR').style.display='none';
					
					//reset values
					document.getElementById('taxid1').value=AynaxMessages.TAX_NAME_ID_NUMBER; 					
					
					//reset colors
					document.getElementById('taxid1').style.color='silver'; 															
					
				}

				else if (obj.id=="customization_taxid3") { 
				 
				 	//save value inside the invoice form
					if (document.getElementById('customization_save_taxid3')!=null) document.getElementById('customization_save_taxid3').value='';
					
					//hide elements
					document.getElementById('taxid3TR').style.display='none'; 
					document.getElementById('taxid3BlankTR').style.display='none';
					
					//reset values
					document.getElementById('taxid3').value=AynaxMessages.TAX_NAME_ID_NUMBER; 					
					
					//reset colors
					document.getElementById('taxid3').style.color='silver'; 															
					
				}

				else if (obj.id=="customization_poNumber") { 
				 	
					//save value inside the invoice form
					if (document.getElementById('customization_save_poNumber')!=null) document.getElementById('customization_save_poNumber').value='';
				 
				 	//hide elements
					document.getElementById('po_numberTR').style.display='none'; 
					document.getElementById('po_numberBlankTR').style.display='none';
					
					//reset values
					document.getElementById('po_number').value=''; 	
					
				}

				else if (obj.id=="customization_tax") { 
				 
					/* save value inside the invoice form */
					if (document.getElementById('customization_save_tax')!=null) document.getElementById('customization_save_tax').value='';				 
				 
					/* grabs the table, goes through each row and changes the style of cell 5 = tax */
					var table = document.getElementById('dataTable');
					var rowCount = table.rows.length;					
					
					for (i=0;i<rowCount;i++) {
						var rowNode = table.rows[i];
						rowNode.cells[5].style.display ='none';
						
						
						//changes the classes of description, unit price, quantity and amount; i>0 because don't need the headline
						if (i>0) {

							//grabs the input elements in this row and resets values (tax) and class names (unit price, quantity and amount)
							/* uses settimeout to stop firefox from shaking */
							//var node = rowNode.cells[5].getElementsByTagName("input")[0];
							setTimeout("setTaxNodeToZero();",300); //impossible to send an object
						 	//node.value = '0.00';
						 	//node.style.color = 'silver';

							//changes the class of the td
							rowNode.cells[5].className = 'invoiceDataTax_hidden';
							
							var node = rowNode.cells[3].getElementsByTagName("input")[0];						 	
						 	node.className = 'inputInvoiceDataPriceOrQty';
						 	
							var node = rowNode.cells[4].getElementsByTagName("input")[0];						 	
						 	node.className = 'inputInvoiceDataPriceOrQty';
						 	
							var node = rowNode.cells[7].getElementsByTagName("input")[0];						 	
						 	node.className = 'inputInvoiceDataAmount';
							
							//resets values
							//var node = rowNode.cells[7].getElementsByTagName("input")[0];						 	
						 	//node.value = '0.00';
						 	
							//document.getElementById('sum_tax').value='0.00';
							//document.getElementById('sum_tax_woDiscount').value='0.00';
							
							//recalculate the form -> faking a change in the discount to force a sum only recalculation
							//reCalculate(document.getElementById('sum_discount'),'dataTable',document.getElementById('sum_discount').value);
							setTimeout("reCalculate(document.getElementById('sum_discount'),'dataTable','0.00');",300);

						}
					}
				 
					//document.getElementById('sum_taxTR').style.display='none'; 
					if (document.getElementById('customization_discount').checked==false) document.getElementById('sum_blankSubtotalTR').style.display='';
					if (document.getElementById('customization_discount').checked==true) document.getElementById('sum_blankAfterDiscountOrTaxTR').style.display='';					
				}


				else if (obj.id=="customization_tax2") { 
				 
					/* save value inside the invoice form */
					if (document.getElementById('customization_save_tax2')!=null) document.getElementById('customization_save_tax2').value='';				 
				 
					/* grabs the table, goes through each row and changes the style of cell 5 = tax */
					var table = document.getElementById('dataTable');
					var rowCount = table.rows.length;					
					
					for (i=0;i<rowCount;i++) {
						var rowNode = table.rows[i];
						rowNode.cells[6].style.display ='none';
						
						
						//changes the classes of description, unit price, quantity and amount; i>0 because don't need the headline
						if (i>0) {

							//grabs the input elements in this row and resets values (tax) and class names (unit price, quantity and amount)
							/* uses settimeout to stop firefox from shaking */
							setTimeout("setTaxNode2ToZero();",300); //impossible to send an object

							//changes the class of the td
							rowNode.cells[6].className = 'invoiceDataTax_hidden';
							
							var node = rowNode.cells[2].getElementsByTagName("textarea")[0];						 	
						 	node.className = 'inputInvoiceDataDescription ';
							
							//recalculate the form -> faking a change in the discount to force a sum only recalculation
							setTimeout("reCalculate(document.getElementById('sum_discount'),'dataTable','0.00');",300);

						}
					}
				 
					//document.getElementById('sum_taxTR').style.display='none'; 
					if (document.getElementById('customization_discount').checked==false) document.getElementById('sum_blankSubtotalTR').style.display='';
					if (document.getElementById('customization_discount').checked==true) document.getElementById('sum_blankAfterDiscountOrTaxTR').style.display='';					
				}

				else if (obj.id=="customization_discount") { 
				 
					/* save value inside the invoice form */
					if (document.getElementById('customization_save_discount')!=null) document.getElementById('customization_save_discount').value='';
			 
				 	//hide, position and style elements
					document.getElementById('sum_discountTR').style.display='none'; 
					if (document.getElementById('customization_tax').checked==false) document.getElementById('sum_blankSubtotalTR').style.display='';
					document.getElementById('sum_blankAfterDiscountOrTaxTR').style.display='none';
					document.getElementById('sum_discount').style.color='silver'; 															
					
					//reset values
					document.getElementById('sum_discount').value='0.00';
					
					//recalculate the form
					reCalculate(document.getElementById('sum_discount'),'dataTable','0.00');
				}
				
			}
			
		}

		String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }		
		
		function customization_uploadCreateForm() {

			var d=document;

			/* creates the upload button */
			var newElement = d.createElement("INPUT");					    
			newElement.type = "image";			
			newElement.src = "images/browse.png";			
			d.getElementById('customization_uploadField').appendChild(newElement);
			
			/* creates the file browser */						
			var newElement = d.createElement("INPUT");
			newElement.name ="filename";
			newElement.type = "file";
			newElement.size = "5";
			newElement.className = "invoiceForm_logoBrowse";
			newElement.onchange = function ()  {  ajaxUpload(this.form,'ajaxupload.php?filename=name&amp;maxSize=9999999999&amp;maxW=300&amp;fullPath=http://'+location.host+'/upload/&amp;relPath=upload/&amp;colorR=255&amp;colorG=255&amp;colorB=255&amp;maxH=125','upload_area','<p style="padding-right:15px;vertical-align:top;">'+ AynaxMessages.FILE_UPLOAD +'...<b><img src='+"'images/loader_light_blue.gif' width='128' height='15' border='0'></p>","<img src='images/error.gif' width='16' height='16' border='0'> " + AynaxMessages.FILE_ERROR_UPLOAD); return false; };  			
			d.getElementById('customization_uploadField').appendChild(newElement);

			/* changes the class of the div to make it visible */
			document.getElementById('customization_uploadField').className="invoiceForm_uploadField";
		
		}
		

		function customization_uploadDelete() {
			
			/* shows the your logo here img, the browse button and hides the delete logo button */
			document.getElementById('upload_area').innerHTML='<img src="images'+aynaxImageLanguagePath+'/your_logo_here2.png">';
			document.getElementById('upload_area').className="invoiceForm_uploadAreaNoBg";						
			customization_uploadCreateForm();			
			document.getElementById('customization_uploadDelete').style.display="none";
			document.getElementById('customization_logoFilename').value="";			
			document.getElementById('customization_logoFilename_session').value="";			
			
		}
		
		
		function findRowNumber(node) {
			/* function to return the row index */ 
			/* loops backwards/upwards through the nodes until a TR is found; then simply grabs the rowIndex of the TR */ 
			
			var rowNumber = 0;
			
		    while ( node != null )  {
	    	    if (node.tagName == "TR" ) { 
				 	rowNumber = node.rowIndex;
		            break;
    		    }
        		node = node.parentNode;
	    	}	
	    	
	    	return rowNumber;
		}
		
		function findCellNumber(node) {
			/* function to return the cell index */
			/* loops backwards/upwards through the nodes until a TD is found; then simply grabs the cellIndex of the TD */
			
			var cellNumber = 0;
			
		    while ( node != null )  {
	    	    if (node.tagName == "TD" ) { 
				 	cellNumber = node.cellIndex;
		            break;
    		    }
        		node = node.parentNode;
	    	}	
	    	
	    	return cellNumber;
		}
		
		
		function invoiceForm_changeBackground(obj,color) {

			/* find the row number */
			var rowNumber = findRowNumber(obj);
			
			/* find the column or cell number */
			var cellNumber = findCellNumber(obj);
			
			/* fetches the table and changes the background of this cell */
			var table = document.getElementById('dataTable');
			var rowNode = table.rows[rowNumber];
			var node = rowNode.cells[cellNumber];
			node.style.backgroundColor = color;
			
			/* goes through the different cells to change the input elements */
			
			/* item */ 			
			if (cellNumber==1) {
				document.getElementsByName('item[]')[(rowNumber-1)].style.backgroundColor = color;	
				node = rowNode.cells[0];
				node.style.backgroundColor = color;
			}
		
			/* description */
			else if (cellNumber==2) {
				document.getElementsByName('description[]')[(rowNumber-1)].style.backgroundColor = color;					
  			}
		
			/* unit price */
			else if (cellNumber==3) {
				document.getElementsByName('unit_price[]')[(rowNumber-1)].style.backgroundColor = color;					
			}
		
			/* quantity */
			else if (cellNumber==4) {
				document.getElementsByName('qty[]')[(rowNumber-1)].style.backgroundColor = color;					
			}
			
			/* tax */
			else if (cellNumber==5) {
				document.getElementsByName('tax[]')[(rowNumber-1)].style.backgroundColor = color;					
			}
			
			/* tax 2 */
			else if (cellNumber==6) {
				document.getElementsByName('tax2[]')[(rowNumber-1)].style.backgroundColor = color;					
			}
		}

		function recordPayment_deletePayment(paymentId,paymentAmount) {
		 	document.getElementById('recordPayment_deletePaymentId').value=paymentId;
		 	document.getElementById('recordPayment_deletePaymentAmount').value=paymentAmount;		 	
			document.getElementById("recordPayment_paymentHistory").submit();
		}


	/* showInvoices.php */
	
		function invoiceFilter_paginator(value) {
		 	document.getElementById('invoiceFilter_pageCurrent').value=value;
			document.forms["invoice_filter"].submit();
		}
		
		function invoiceFilter_deleteInvoice(id, invoice_number) {
		 	document.getElementById('invoiceFilter_deleteId').value=id;
		 	document.getElementById('invoiceFilter_deleteInvoiceNo').value=invoice_number;		 	
			document.forms["invoice_filter"].submit();
		}

		function invoiceFilter_restoreInvoice(id, invoice_number) {
		 	document.getElementById('invoiceFilter_restoreId').value=id;
		 	document.getElementById('invoiceFilter_restoreInvoiceNo').value=invoice_number;		 	
			document.forms["invoice_filter"].submit();
		}

		
		function setStatus(newStatus) {
		 	document.getElementById('status').value=newStatus;
			invoiceFilter_resetPageCurrent();		 	
			document.forms["invoice_filter"].submit();
		}
		
		function invoiceFilter_changeSort(column) {

			/* gets new and old columns */
		 	var newColumn = column;
			var oldColumn = document.getElementById('invoiceFilter_sortColumn').value;

			//alert(newColumn);
			//alert(oldColumn);
			
			/* gets current sort order */
			var sortOrder = document.getElementById('invoiceFilter_sortOrder').value;
		 
		 	/* if same column, only change order by */
		 	if (newColumn == oldColumn) {
		 	 	
				if (sortOrder=="DESC") sortOrder = "ASC"; else sortOrder = "DESC";
				document.getElementById('invoiceFilter_sortOrder').value=sortOrder;
				
				//alert(sortOrder);
			
			/* changes column; sets the sort order to the default for that column */
			} else {

				document.getElementById('invoiceFilter_sortColumn').value = newColumn;
				
				if (newColumn=="invoice_number") sortOrder = "ASC";
				else if (newColumn=="to_name") sortOrder = "ASC";				
				else if (newColumn=="invoice_date") sortOrder = "DESC";					
				else if (newColumn=="sum_total") sortOrder = "DESC";					
				else if (newColumn=="amount_paid") sortOrder = "DESC";									
				else if (newColumn=="balance_due") sortOrder = "DESC";
				else if (newColumn=="status") sortOrder = "ASC";
				
				else if (newColumn=="address") sortOrder = "ASC";
				else if (newColumn=="vendor_name") sortOrder = "ASC";				
													
				document.getElementById('invoiceFilter_sortOrder').value=sortOrder;				
			}
			
			document.forms["invoice_filter"].submit();			

		}
		
		function toggleInvoiceFilter(newStatus) {

			document.getElementById('invoiceFilter_showFilter').value=newStatus;

			if (newStatus == "On") {
			 	
				document.getElementById('toggleFilterOn').style.display="none";
				document.getElementById('toggleFilterOff').style.display="block";				
				document.getElementById('divWithInvoiceFilter').style.display="block";				
			}
			else {
				document.getElementById('toggleFilterOn').style.display="block";
				document.getElementById('toggleFilterOff').style.display="none";
				document.getElementById('divWithInvoiceFilter').style.display="none";									
				
			}
		}
		
		function lastDayOfMonth(Year, Month) {
	        return(new Date((new Date(Year, Month+1,1))-1)).getDate();
		}		
		
		function formatMonthToScreen(theMonth) {
			//increases the value with 1 
			//adds a "" to make it a string
			//adds a preceding 0 if the length is only 1
			
			theMonth++
			theMonth=theMonth+"";
			if (theMonth.length==1) theMonth = '0'+theMonth;			
			
			return theMonth;
		}
		
		function findQuarter(theMonth) {
			//finds which of the four quarters a month belongs to
			//returns the number as an integer
			
			if ((theMonth>=0)&&(theMonth<3)) return 1; /* Q1 */
			if ((theMonth>=3)&&(theMonth<6)) return 2; /* Q2 */
			if ((theMonth>=6)&&(theMonth<9)) return 3; /* Q3 */
			if ((theMonth>=9)&&(theMonth<12)) return 1; /* Q1 */									

		}
		
		function invoiceFilter_updateFromTime() {
		 
		 	var date_format = document.getElementById('date_format').value;

			var time_frame = document.getElementById('invoiceFilter_timeFrame').value;

			var now = new Date();
			
			/* TEST */
			//now.setFullYear(2010,0,15);

			if (time_frame=="all_time") {
				document.getElementById('invoiceFilter_fromDate').value = document.getElementById('invoiceFilter_minDate').value;
				document.getElementById('invoiceFilter_toDate').value = document.getElementById('invoiceFilter_maxDate').value;
			}
			
			else if (time_frame=="this_month") {
			
			 	var lastDay = lastDayOfMonth(now.getFullYear(), now.getMonth());
				
				if (date_format=="dd/mm/yy") document.getElementById('invoiceFilter_fromDate').value = '01/'+formatMonthToScreen(now.getMonth())+'/'+now.getFullYear();
				else if (date_format=="dd.mm.yy") document.getElementById('invoiceFilter_fromDate').value = '01.'+formatMonthToScreen(now.getMonth())+'.'+now.getFullYear();
				else if (date_format=="yy-mm-dd") document.getElementById('invoiceFilter_fromDate').value = now.getFullYear()+'-'+formatMonthToScreen(now.getMonth())+'-01';
				else document.getElementById('invoiceFilter_fromDate').value = formatMonthToScreen(now.getMonth())+'/01/'+now.getFullYear();

				if (date_format=="dd/mm/yy") document.getElementById('invoiceFilter_toDate').value = lastDay+'/'+formatMonthToScreen(now.getMonth())+'/'+now.getFullYear();
				else if (date_format=="dd.mm.yy") document.getElementById('invoiceFilter_toDate').value = lastDay+'.'+formatMonthToScreen(now.getMonth())+'.'+now.getFullYear();
				else if (date_format=="yy-mm-dd") document.getElementById('invoiceFilter_toDate').value = now.getFullYear()+'-'+formatMonthToScreen(now.getMonth())+'-'+lastDay;
				else document.getElementById('invoiceFilter_toDate').value = formatMonthToScreen(now.getMonth())+'/'+lastDay+'/'+now.getFullYear();
			}
			
			else if (time_frame=="last_month") {

				var lastMonth=(now.getMonth()-1); //in javascript january is month 0, feb month 1, etc. so to find last month we just don't add 1'
				if (lastMonth==-1) { lastMonth=11; var theYear = (now.getFullYear()-1); } else var theYear = now.getFullYear();
				var lastDay = lastDayOfMonth(theYear, lastMonth);
			
				if (date_format=="dd/mm/yy") document.getElementById('invoiceFilter_fromDate').value = '01/'+formatMonthToScreen(lastMonth)+'/'+theYear;
				else if (date_format=="dd.mm.yy") document.getElementById('invoiceFilter_fromDate').value = '01.'+formatMonthToScreen(lastMonth)+'.'+theYear;
				else if (date_format=="yy-mm-dd") document.getElementById('invoiceFilter_fromDate').value = theYear+'-'+formatMonthToScreen(lastMonth)+'-01';
				else document.getElementById('invoiceFilter_fromDate').value = formatMonthToScreen(lastMonth)+'/01/'+theYear;

				if (date_format=="dd/mm/yy") document.getElementById('invoiceFilter_toDate').value = lastDay+'/'+formatMonthToScreen(lastMonth)+'/'+theYear;
				else if (date_format=="dd.mm.yy") document.getElementById('invoiceFilter_toDate').value = lastDay+'.'+formatMonthToScreen(lastMonth)+'.'+theYear;
				else if (date_format=="yy-mm-dd") document.getElementById('invoiceFilter_toDate').value = theYear+'-'+formatMonthToScreen(lastMonth)+'-'+lastDay;
				else document.getElementById('invoiceFilter_toDate').value = formatMonthToScreen(lastMonth)+'/'+lastDay+'/'+theYear;
			}
			
			else if (time_frame=="this_quarter") {

				var currentMonth=now.getMonth();
				var currentQuarter = findQuarter(currentMonth);
	
				if 		(currentQuarter==1) { var startMonth = 0; var endMonth = 2; }
				else if (currentQuarter==2) { var startMonth = 3; var endMonth = 5; }
				else if (currentQuarter==3) { var startMonth = 6; var endMonth = 8; }
				else if (currentQuarter==4) { var startMonth = 9; var endMonth = 11; }
				
				var lastDay = lastDayOfMonth(now.getFullYear(), endMonth);				
				
				if (date_format=="dd/mm/yy") document.getElementById('invoiceFilter_fromDate').value = '01/'+formatMonthToScreen(startMonth)+'/'+now.getFullYear();
				else if (date_format=="dd.mm.yy") document.getElementById('invoiceFilter_fromDate').value = '01.'+formatMonthToScreen(startMonth)+'.'+now.getFullYear();
				else if (date_format=="yy-mm-dd") document.getElementById('invoiceFilter_fromDate').value = now.getFullYear()+'-'+formatMonthToScreen(startMonth)+'-01';
				else document.getElementById('invoiceFilter_fromDate').value = formatMonthToScreen(startMonth)+'/01/'+now.getFullYear();

				if (date_format=="dd/mm/yy") document.getElementById('invoiceFilter_toDate').value = lastDay+'/'+formatMonthToScreen(endMonth)+'/'+now.getFullYear();
				else if (date_format=="dd.mm.yy") document.getElementById('invoiceFilter_toDate').value = lastDay+'.'+formatMonthToScreen(endMonth)+'.'+now.getFullYear();
				else if (date_format=="yy-mm-dd") document.getElementById('invoiceFilter_toDate').value = now.getFullYear()+'-'+formatMonthToScreen(endMonth)+'-'+lastDay;
				else document.getElementById('invoiceFilter_toDate').value = formatMonthToScreen(endMonth)+'/'+lastDay+'/'+now.getFullYear();
			}
			
			else if (time_frame=="last_quarter") {

				var currentMonth=now.getMonth();
				var currentQuarter = findQuarter(currentMonth);
				
				var lastQuarter = (currentQuarter-1);
				if (lastQuarter==0) { lastQuarter=4; var theYear = (now.getFullYear()-1); } else var theYear = now.getFullYear();
	
				if 		(lastQuarter==1) { var startMonth = 0; var endMonth = 2; }
				else if (lastQuarter==2) { var startMonth = 3; var endMonth = 5; }
				else if (lastQuarter==3) { var startMonth = 6; var endMonth = 8; }
				else if (lastQuarter==4) { var startMonth = 9; var endMonth = 11; }
				
				var lastDay = lastDayOfMonth(theYear, endMonth);				
				
				if (date_format=="dd/mm/yy") document.getElementById('invoiceFilter_fromDate').value = '01/'+formatMonthToScreen(startMonth)+'/'+theYear;
				else if (date_format=="dd.mm.yy") document.getElementById('invoiceFilter_fromDate').value = '01.'+formatMonthToScreen(startMonth)+'.'+theYear;
				else if (date_format=="yy-mm-dd") document.getElementById('invoiceFilter_fromDate').value = theYear+'-'+formatMonthToScreen(startMonth)+'-01';
				else document.getElementById('invoiceFilter_fromDate').value = formatMonthToScreen(startMonth)+'/01/'+theYear;
				
				if (date_format=="dd/mm/yy") document.getElementById('invoiceFilter_toDate').value = lastDay+'/'+formatMonthToScreen(endMonth)+'/'+theYear;
				else if (date_format=="dd.mm.yy") document.getElementById('invoiceFilter_toDate').value = lastDay+'.'+formatMonthToScreen(endMonth)+'.'+theYear;
				else if (date_format=="yy-mm-dd") document.getElementById('invoiceFilter_toDate').value = theYear+'-'+formatMonthToScreen(endMonth)+'-'+lastDay;
				else document.getElementById('invoiceFilter_toDate').value = formatMonthToScreen(endMonth)+'/'+lastDay+'/'+theYear;
				
			}
			
			else if (time_frame=="this_year") {

				if (date_format=="dd/mm/yy") document.getElementById('invoiceFilter_fromDate').value = '01/01/'+now.getFullYear();
				else if (date_format=="dd.mm.yy") document.getElementById('invoiceFilter_fromDate').value = '01.01.'+now.getFullYear();
				else if (date_format=="yy-mm-dd") document.getElementById('invoiceFilter_fromDate').value = now.getFullYear()+'-01-01';
				else  document.getElementById('invoiceFilter_fromDate').value = '01/01/'+now.getFullYear();
				
				
				if (date_format=="dd/mm/yy") document.getElementById('invoiceFilter_toDate').value = '31/12/'+now.getFullYear();
				else if (date_format=="dd.mm.yy") document.getElementById('invoiceFilter_toDate').value = '31.12.'+now.getFullYear();
				else if (date_format=="yy-mm-dd") document.getElementById('invoiceFilter_toDate').value = now.getFullYear()+'-12-31';
				else document.getElementById('invoiceFilter_toDate').value = '12/31/'+now.getFullYear();
			}
			
			else if (time_frame=="last_year") {

				if (date_format=="dd/mm/yy") document.getElementById('invoiceFilter_fromDate').value = '01/01/'+(now.getFullYear()-1);
				else if (date_format=="dd.mm.yy") document.getElementById('invoiceFilter_fromDate').value = '01.01.'+(now.getFullYear()-1);
				else if (date_format=="yy-mm-dd") document.getElementById('invoiceFilter_fromDate').value = (now.getFullYear()-1)+'-01-01';
				else document.getElementById('invoiceFilter_fromDate').value = '01/01/'+(now.getFullYear()-1);
				
				if (date_format=="dd/mm/yy") document.getElementById('invoiceFilter_toDate').value = '31/12/'+(now.getFullYear()-1);
				else if (date_format=="dd.mm.yy") document.getElementById('invoiceFilter_toDate').value = '31.12.'+(now.getFullYear()-1);
				else if (date_format=="yy-mm-dd") document.getElementById('invoiceFilter_toDate').value = (now.getFullYear()-1)+'-12-31';
				else document.getElementById('invoiceFilter_toDate').value = '12/31/'+(now.getFullYear()-1);
			}
			
			else if (time_frame=="custom") {

				document.getElementById('invoiceFilter_fromDate').value = '';
				document.getElementById('invoiceFilter_toDate').value = '';
				
			}
					
			
		}	

		function invoiceFilter_resetPageCurrent() {
			document.getElementById('invoiceFilter_pageCurrent').value=1;			
		}

	
/* sendInvoice.php */

    function isSameString( s1, s2 )
      {
        alert( "s1: " + s1.toString() );
        alert( "s2: " + s2.toString() );

      	if ( s1.toString() == s2.toString() )
        {
      	  return true;
        }
        else
        {
          return false;
        }
      }
	
function sendInvoice_changePDFtextInMail(obj, name, amount, subdomain, invoice, email) 	{

	/* updates the message; content depends on whether the pdf is attached or not */
	if (obj.checked) { var originalMessage = document.getElementById('sendInvoice_noPDFmsg').value; var newMessage = document.getElementById('sendInvoice_PDFmsg').value; }
	else { var originalMessage = document.getElementById('sendInvoice_PDFmsg').value; var newMessage = document.getElementById('sendInvoice_noPDFmsg').value; }

	/* compare the current message with the original message */
	var currentMessage = document.getElementById('sendInvoice_message').value;
	
	//alert(currentMessage.length+' '+originalMessage.length);	
	
	if (currentMessage.trim()==originalMessage.trim()) var different = false;  else var different = true; 

	/* if the user has changed the original message, must ask him whether he wants it overwritten with our new message */
	if (different) {

		var userReply = confirm(AynaxMessages.PDF_SETTINGS_CHANGE);
		if (userReply) 	document.getElementById('sendInvoice_message').value = newMessage;		

	} else {

		/* updates the form with the new message */
		document.getElementById('sendInvoice_message').value = newMessage;
	}
	
}

function toggleSendForm(status) {
	
	/* the status is how it was before the link was clicked... */
	
	if (status=="On") {
		document.getElementById('toggleSendFormOn').style.display='none';
		document.getElementById('toggleSendFormOff').style.display='';
		document.getElementById('sendInvoice_sendForm').style.display='';		
	} 
	
	else {
		document.getElementById('toggleSendFormOn').style.display='';
		document.getElementById('toggleSendFormOff').style.display='none';
		document.getElementById('sendInvoice_sendForm').style.display='none';
	}
}


function setDefaultValues(option) {
 
	document.getElementById('to_name').defaultValue = document.getElementById('to_name').value;

	//the original selectedIndex=0 becuase the field is by default empty; must be set to false
	document.getElementById('to_name').options[0].selected=false;
	document.getElementById('to_name').options[0].defaultSelected=false;
	
	document.getElementById('to_name').options[document.getElementById('to_name').selectedIndex].selected=true;
	document.getElementById('to_name').options[document.getElementById('to_name').selectedIndex].defaultSelected=true;
  
 	if (option=="1") document.getElementById('to_address').defaultValue = document.getElementById('to_address').value;
 	
	else {
	
		document.getElementById('to_attention').defaultValue = document.getElementById('to_attention').value;	
		document.getElementById('to_street').defaultValue = document.getElementById('to_street').value;	
		document.getElementById('to_street2').defaultValue = document.getElementById('to_street2').value;	
		document.getElementById('to_city').defaultValue = document.getElementById('to_city').value;	

		document.getElementById('to_state').options[0].selected=false;
		document.getElementById('to_state').options[0].defaultSelected=false;

		document.getElementById('to_state').defaultValue = document.getElementById('to_state').value;
		document.getElementById("to_state").defaultSelectedIndex = document.getElementById("to_state").selectedIndex;

		document.getElementById('to_state').options[document.getElementById('to_state').selectedIndex].selected=true;
		document.getElementById('to_state').options[document.getElementById('to_state').selectedIndex].defaultSelected=true;
		
		document.getElementById('to_zip').defaultValue = document.getElementById('to_zip').value;	
		document.getElementById('taxid3').defaultValue = document.getElementById('taxid3').value;
			
	}
}

function ajax_get(url, passedFunction) {

    if (window.XMLHttpRequest)   {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }

    else {
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=passedFunction;
    xmlhttp.open("GET",url,true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send(null);
}


function ajax(url,data,passedFunction) {
	
	if (window.XMLHttpRequest)   {
  		// code for IE7+, Firefox, Chrome, Opera, Safari
  		xmlhttp=new XMLHttpRequest();
	}
	
	else {
		// code for IE6, IE5
  		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  	}

	xmlhttp.onreadystatechange=passedFunction;  	
	xmlhttp.open("POST",url,true);
	xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	xmlhttp.send(data);  	
  	
}


function edit_customer_name() {
	
	var customer_name = document.getElementById('to_name').options[document.getElementById('to_name').selectedIndex].text;		
	var customer_id = document.getElementById('to_name').options[document.getElementById('to_name').selectedIndex].value;		
	document.getElementById('to_name').style.display='none';
	document.getElementById('edit_customer_name').style.display='none';	
	document.getElementById('edit_customer_msg_save').style.display='';
	
	document.getElementById('customer_name').style.display='';
	document.getElementById('customer_name').focus();
	document.getElementById('customer_name').value=customer_name;
	document.getElementById('customer_id').value=customer_id;
	
}


function customer_name_update() {

	var customer_id = document.getElementById('customer_id').value;
	
	var customer_name = document.getElementById('customer_name').value;
	if (customer_name!="") {
		if (customer_name!=document.getElementById('to_name').options[document.getElementById('to_name').selectedIndex].text) {
			var data = "c_id="+customer_id+"&c_name="+customer_name;
			ajax("../updateCustomerName.inc.php", data, function() {});
		}
		document.getElementById('to_name').options[document.getElementById('to_name').selectedIndex].text=customer_name;			
	}
	
	document.getElementById('customer_name').style.display='none';
	document.getElementById('to_name').style.display='';
	document.getElementById('edit_customer_name').style.display='';	
	document.getElementById('edit_customer_msg_save').style.display='none';
	
	field_onblur(document.getElementById('to_name'),AynaxMessages.YOUR_NAME);
	
}

function vendor_name_update() {

	var customer_id = document.getElementById('customer_id').value;
	
	var customer_name = document.getElementById('customer_name').value;
	if (customer_name!="") {
		if (customer_name!=document.getElementById('to_name').options[document.getElementById('to_name').selectedIndex].text) {
			
			var data = { id : customer_id, name : customer_name };
			$.ajax({
				url: 'updateVendorName.inc.php',
				data : data,
				type: 'POST',
            	cache: false,
            	async: true,
            	success:function(response){},
				error: function(){}
				
			});
			
		}
		document.getElementById('to_name').options[document.getElementById('to_name').selectedIndex].text=customer_name;			
	}
	
	document.getElementById('customer_name').style.display='none';
	document.getElementById('to_name').style.display='';
	document.getElementById('edit_customer_name').style.display='';	
	document.getElementById('edit_customer_msg_save').style.display='none';
	
	field_onblur(document.getElementById('to_name'),AynaxMessages.YOUR_NAME);
	
}


function edit_default_notes(type) {
 		var type_label = type == 'po' ? AynaxMessages.PURCHASE_ORDER : type.charAt(0).toUpperCase()+type.slice(1);
 		
 		var add_default_notes = '';
 		if (type == 'invoice'){
 			add_default_notes = AynaxMessages.ADD_DEFAULT_NOTES_INVOICE;	
 		}else if (type =='estimate'){
 			add_default_notes = AynaxMessages.ADD_DEFAULT_NOTES_ESTIMATE; 	
 		}else if(type == 'po'){
 			add_default_notes = AynaxMessages.ADD_DEFAULT_NOTES_PO; 		
 		}
 		
 		
 		var divTag2 = document.createElement("div");
        divTag2.id = "div2";
        divTag2.setAttribute("align","left");
        divTag2.style.position = "relative";
        divTag2.style.left = "400px";
        divTag2.style.top = "-560px";
        divTag2.style.backgroundColor = "#FFFFFF";
        divTag2.style.border = "3px solid silver";
        divTag2.style.height = "250px";
        divTag2.style.width = "500px";
        divTag2.style.padding = "10px";
        divTag2.style.zIndex = 21;
	    divTag2.innerHTML = ""+
		
		"<table border=0 cellpadding=0 cellspacing=0 style=\"width:100%;\"><tr><td colspan=2 style=\"text-align:center;\">"+
		
		"<b>"+AynaxMessages.EDIT_DEFAULT_NOTES+"</b><br><br>"+
		
		"</td></tr><tr><td colspan=2 style=\"text-align:left;padding-left:25px;\">"+
		
		"<textarea id=\"default_notes_textarea\" name=\"invoice_notes\" class=\"invoiceForm_fromNameTD\" onfocus=\"this.className='invoiceForm_fromNameTD_onFocus';\" onblur=\"this.className='invoiceForm_fromNameTD';\" rows=6 cols=60 style=\"width:430px; overflow:auto; outline:none; padding:5px; font-weight:normal; font-family:verdana;font-size:13px;color:#3c3c3c;\">"+
		
		"</textarea><br><br>"+
		
		"</td></tr><tr><td style=\"text-align:left;padding-left:25px;width:5px;\">"+
		
		"<input type=\"checkbox\" id=\"copy_to_current_invoice\">"+
		
		"</td><td style=\"text-align:left;padding-left:5px;\">"+
		
		"<font style=\"font-size:12px;\">"+ add_default_notes +
		
		"</td></tr><tr><td colspan=2 style=\"text-align:right;padding-top:20px;\">"+

		"<input type=submit style=\"height:32px;width:120px;\" onclick=\"element1=document.getElementById('div1');element1.parentNode.removeChild(element1);element2=document.getElementById('div2');element2.parentNode.removeChild(element2);\"  value=\""+ AynaxMessages.CANCEL +"\">"+
		
		"&nbsp;&nbsp;&nbsp;"+

		"<input type=submit onclick=\"saveDefaultNotes('"+type+"');\" style=\"height:32px;width:120px;\"  value=\""+ AynaxMessages.SAVE +"\">"+
		
		"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td></tr></table>";
		
		"";

        document.body.appendChild(divTag2);
 
 		var data = "type="+type;
		ajax("../getDefaultNotes.inc.php", data, function() {

			if (xmlhttp.readyState==4 && xmlhttp.status==200) document.getElementById('default_notes_textarea').value = xmlhttp.responseText;
			
		});

 
 	 	var h = document.body.clientHeight + 20 + "px";
 	 	var w = document.body.clientWidth + "px";
		var divTag = document.createElement("div");
        divTag.id = "div1";
        divTag.setAttribute("align","center");
        divTag.style.position = "absolute";
        divTag.style.left = "0px";
        divTag.style.top = "0px";
        divTag.style.backgroundColor = "#000000";
        divTag.style.height = h;
        divTag.style.width = w;
        divTag.style.zIndex = 20;
        divTag.style.opacity = 0.6;
	    divTag.innerHTML = "";
	    
        document.body.appendChild(divTag);

      	document.getElementById('default_notes_textarea').onfocus();
     	document.getElementById('default_notes_textarea').select();
}


function saveDefaultNotes(type) {
    var label_type = type == 'po' ? 'purchase order' : type;
    
 	var notes = document.getElementById('default_notes_textarea').value;
 
 	if (document.getElementById('copy_to_current_invoice').checked) document.getElementById('invoice_notes').value = notes;
 	
 	var data = "type="+type+"&notes="+encodeURIComponent(notes);
	ajax("../updateDefaultNotes.inc.php", data, function() {});
	
	document.getElementById('div2').style.height = "150px";
	document.getElementById('div2').innerHTML = ""+
	
	"<br><div style=\"text-align:center;\">"+
	
	"<table cellpadding=0 cellspacing=0 style=\"width:100%; margin:0px; margin-bottom:0px; margin-top:0px;padding:0px;background-color:#FFFADC;border-top:2px solid #FCF5CD; border-bottom:2px solid #FCF5CD;padding:5px;padding-left:12px;\">"+
	"<tr><td style=\"width:40px;vertical-align:top;\">"+
	"<img style=\"margin:0px;padding:0px;\" src=\"images/green_check_25-5.gif\">"+
	"</td><td>"+
	"<font style=\"font-size:13px;font-family:verdana;color:#3c3c3c;\">"+AynaxMessages.MESSAGE_LABEL+"</font>"+
	"</td></tr></table>"+

	"<br><br>"+

	"<input type=submit onclick=\"removeDefaultNotesPopup();\" style=\"height:32px;width:120px;\"  value=\""+ AynaxMessages.OK +"\">"+
	
	"</div><br><br>";
	

	
}

function removeDefaultNotesPopup() {
	
	element1=document.getElementById('div1');
	element1.parentNode.removeChild(element1);
	element2=document.getElementById('div2');
	element2.parentNode.removeChild(element2);	
	
}


function edit_emailaddress(node,id) {
 
	var emailaddress = node.innerHTML;
 	node = node.parentNode;
 	node.innerHTML='<input autocomplete=off id="emailaddress" style="outline:none;border:0px solid white;width:320px; padding:0px; font-weight:normal; font-family:verdana;font-size:13px;color:#3c3c3c;" type=text onkeyup="sanitizeEmailAddress(this);" onfocus="this.value=this.value;" onblur="emailaddress_update(this,'+id+',\''+emailaddress+'\');"><span id="edit_emailaddress_msg_save" style="display:none;font-size:11px;padding:7px; position:absolute;width:140px;background:#EFF7FA; border:1px solid #cccccc; color:black; font-weight:normal;font-family:verdana;">'+ AynaxMessages.CLICK_OUTSIDE_FIELDS +'</span>';
	//alert(node.innerHTML);
	document.getElementById('emailaddress').focus();
	document.getElementById('emailaddress').value=emailaddress;
	document.getElementById('edit_emailaddress_msg_save').style.display='';
	//alert(id);
 	
}

function emailaddress_update(node,id,old_e) {

 	var emailaddress = node.value;
 
 	if (emailaddress!=old_e) {
		ajax_get("../updateContactEmail.inc.php?c_id="+id+"&e_addr="+emailaddress, function() {});
	}	
	document.getElementById('edit_emailaddress_msg_save').style.display='none';
 	node = node.parentNode;
	node.innerHTML='<a title="'+AynaxMessages.CLICK_SAVE_EMAIL+'" onclick="edit_emailaddress(this,'+id+');" style="width:300px;font-family:verdana;font-size:13px;text-decoration:underline;cursor:pointer;">'+emailaddress+'</a>';
 	node = node.parentNode;
	node.cells[0].innerHTML='<input name="toContact[]" type=checkbox value="'+emailaddress+'">';


	//alert(emailaddress);
	//alert(node.tagName);		
	
}

function rec(type) {
 
 	var data = "type="+type;
	ajax("../rec.inc.php", data, function() {});

}

function re(error_code, error_msg) {
  
 	var data = "error_code="+error_code+"&error_msg="+error_msg;
	ajax("../re.inc.php", data, function() {});

}


function getVendorAddress(cust_id) {

	var vendorId = cust_id; 
	
 	/* means 'New Vendor' is selected */
 	if (vendorId==0) {
		
		document.getElementById('edit_customer_name').style.display='none';	
		document.getElementById('to_name').style.width='100%';		
		document.getElementById('to_new_customerTR').style.display='';		
		document.getElementById('to_new_customerBlankTR').style.display='';	
		document.getElementById('to_new_customer').value= AynaxMessages.VENDOR_NAME;
		document.getElementById('to_new_customer').style.color='silver';		
		document.getElementById('to_address').value= AynaxMessages.VENDOR_ADDRESS;
		document.getElementById('to_address').style.color='silver';		
				
	}
		
	else {
	 
	 	/* tries to fetch the id again in case it is empty */
	 	if (vendorId=='') {
			if (document.getElementById('to_name')!=null) vendorId = document.getElementById("to_name").options[document.getElementById("to_name").selectedIndex].value;
		}
		document.getElementById('edit_customer_name').style.display='';	
		document.getElementById('to_name').style.width='90%';		
	 	document.getElementById('to_new_customerTR').style.display='none';		 		
		document.getElementById('to_new_customerBlankTR').style.display='none';	
		 
 		//var data = "customer="+vendorId;
 		$.ajax({
 			url: '/getVendorAddress.inc.php?v=' + vendorId,
            type: 'GET',
            cache: false,
            async: true,
            success:function(response){
            	var address = response;

				if (address=='') address = AynaxMessages.VENDOR_ADDRESS;
				if (address==AynaxMessages.VENDOR_ADDRESS) var address_color = "silver";
				else address_color = "#3c3c3c";
				
				document.getElementById("to_address").value	= address;
				document.getElementById("to_address").style.color=address_color;
				sz(document.getElementById("to_address"),4);
            },
            error: function(){
            
            }
 		});
		
	}		
}

function getCustomerAddress(customerId) {

    /* means 'New Customer' is selected */
    if (customerId==0) {

        document.getElementById('edit_customer_name').style.display='none';
        document.getElementById('to_name').style.width='100%';
        document.getElementById('to_new_customerTR').style.display='';
        document.getElementById('to_new_customerBlankTR').style.display='';
        document.getElementById('to_new_customer').value= AynaxMessages.CUSTOMER_NAME;
        document.getElementById('to_new_customer').style.color='silver';
        document.getElementById('to_address').value= AynaxMessages.CUSTOMER_ADDRESS;
        document.getElementById('to_address').style.color='silver';

    }

    /* means existing customer is selected and an address must be fetched and inserted */
    else {

        /* tries to fetch the id again in case it is empty */
        /*
         if (isEmpty(customerId)||isBlank(customerId)) {
         if (document.getElementById('to_name')!=null) customerId = document.getElementById("to_name").options[document.getElementById("to_name").selectedIndex].value;
         else customerId="isNull";
         if (isEmpty(customerId)||isBlank(customerId)) customerId="wasEmptyStillEmpty";
         }
         */

        document.getElementById('edit_customer_name').style.display='';
        document.getElementById('to_name').style.width='90%';
        document.getElementById('to_new_customerTR').style.display='none';
        document.getElementById('to_new_customerBlankTR').style.display='none';

        //var data = "customer="+customerId;

        ajax_get("../getCustomerAddress.inc.php?customer="+customerId, function() {

            //alert(xmlhttp.responseText);

            if (xmlhttp.readyState==4 && xmlhttp.status==200) {

                /* get the whole address record */
                var node=xmlhttp.responseXML.documentElement.getElementsByTagName("address");

                /* to_address */
                var to_address = node[0].getElementsByTagName("to_address")[0];
                if (to_address.hasChildNodes()) var address = to_address.firstChild.nodeValue; else var address='';

                if (address=='') address = "Customer address";
                if (address=="Customer address") var address_color = "silver";
                else address_color = "#3c3c3c";

                document.getElementById("to_address").value     = address;
                document.getElementById("to_address").style.color=address_color;
                sz(document.getElementById("to_address"),4);

            }
        });
    }
}

function getNewCustomerData(cust_id) {
 
	var customerId = cust_id; //declares so that it can be re-assigned in case it is empty, bug...
 
 	/* means New Customer is selected */
 	if (customerId==0) {
 	 
 		document.getElementById('to_new_customerTR').style.display='';		
		document.getElementById('to_new_customerBlankTR').style.display='';	
		document.getElementById('to_new_customer').value=AynaxMessages.CUSTOMER_NAME;
		document.getElementById('to_new_customer').style.color='silver';		
		document.getElementById('to_attention').value=AynaxMessages.ATTENTION;	
		document.getElementById('to_attention').style.color='silver';			
		document.getElementById('to_street').value=AynaxMessages.STREET
		document.getElementById('to_street').style.color='silver';			
		document.getElementById('to_street2').value=AynaxMessages.STREET2;	
		document.getElementById('to_street2').style.color='silver';	
		document.getElementById('to_city').value=AynaxMessages.CITY;			
		document.getElementById('to_city').style.color='silver';							
		document.getElementById('to_state').selectedIndex=0;			
		document.getElementById('to_zip').value=AynaxMessages.ZIP;			
		document.getElementById('to_zip').style.color='silver';							
		
	} else {

	 	/* tries to fetch the id again in case it is empty */	 
	 	if (customerId=='') {
			if (document.getElementById('to_name')!=null) customerId = document.getElementById("to_name").options[document.getElementById("to_name").selectedIndex].value;
		}
 
 		//document.getElementById('to_name').style.fontWeight='normal';
		document.getElementById('to_new_customerTR').style.display='none';		 		
		document.getElementById('to_new_customerBlankTR').style.display='none';	
		 
 		var data = "customer="+customerId;
 
		ajax("../getCustomer.inc.php", data, function() {
			if (xmlhttp.readyState==4 && xmlhttp.status==200) {

				/* get the whole address record */
				var node=xmlhttp.responseXML.documentElement.getElementsByTagName("address");
		
				/* to_attention */		 
				var to_attention = node[0].getElementsByTagName("to_attention")[0];
				if (to_attention.hasChildNodes()) {
					document.getElementById("to_attention").value	= to_attention.firstChild.nodeValue;
					document.getElementById("to_attention").style.color="#3c3c3c";					
				} 
				else  {
					document.getElementById("to_attention").value	= AynaxMessages.ATTENTION;
					document.getElementById("to_attention").style.color="silver";
				}
		
				/* to_street */		 
				var to_street = node[0].getElementsByTagName("to_street")[0];
				if (to_street.hasChildNodes()) {
					document.getElementById("to_street").value	= to_street.firstChild.nodeValue;
					document.getElementById("to_street").style.color="#3c3c3c";					
				} 
				else  {
					document.getElementById("to_street").value	= AynaxMessages.STREET;
					document.getElementById("to_street").style.color="silver";
				}

				/* to_street2 */		 
				var to_street2 = node[0].getElementsByTagName("to_street2")[0];
				if (to_street2.hasChildNodes()) {
					document.getElementById("to_street2").value	= to_street2.firstChild.nodeValue;
					document.getElementById("to_street2").style.color="#3c3c3c";					
				} 
				else  {
					document.getElementById("to_street2").value	= AynaxMessages.STREET2;
					document.getElementById("to_street2").style.color="silver";
				}

				/* to_city */		 
				var to_city = node[0].getElementsByTagName("to_city")[0];
				if (to_city.hasChildNodes()) {
					document.getElementById("to_city").value	= to_city.firstChild.nodeValue;
					document.getElementById("to_city").style.color="#3c3c3c";					
				} 
				else  {
					document.getElementById("to_city").value	= AynaxMessages.CITY;
					document.getElementById("to_city").style.color="silver";
				}

				/* to_state */		 
				var to_state = node[0].getElementsByTagName("to_state")[0];
				if (to_state.hasChildNodes()) {
			 
				 	/* figure out which selectedIndex the to_state has */
		   			var states = new Array('AL','AK','AZ','AR','CA','CO','CT','DE','DC','FL','GA','HI','ID','IL','IN','IA','KS','KY','LA','ME','MD','MA','MI','MN','MS','MO','MT','NE','NV','NH','NJ','NM','NY','NC','ND','OH','OK','OR','PA','RI','SC','SD','TN','TX','UT','VT','VA','WA','WV','WI','WY');
				 	var newPos = states.findIndex(to_state.firstChild.nodeValue);
					document.getElementById("to_state").selectedIndex	= (newPos+1);
				} 
				else  {
					document.getElementById("to_state").selectedIndex	= 0;
				}

				/* to_zip */		 
				var to_zip = node[0].getElementsByTagName("to_zip")[0];
				if (to_zip.hasChildNodes()) {
					document.getElementById("to_zip").value	= to_zip.firstChild.nodeValue;
					document.getElementById("to_zip").style.color="#3c3c3c";					
				} 
				else  {
					document.getElementById("to_zip").value	= AynaxMessages.ZIP;
					document.getElementById("to_zip").style.color="silver";
				}
	    	}
  		});
	}
}


var confirmExitIfModified = (function()
{
 
/**
 * Determines if a form is dirty by comparing the current value of each element
 * with its default value.
 *
 * @param {Form} form the form to be checked.
 * @return {Boolean} <code>true</code> if the form is dirty, <code>false</code>
 *                   otherwise.
 */ 
 
 
function formIsDirty(form)
{
 
 /* for all actions except the print button; print button is handled below in formIsDirty2 */
 
    for (var i = 0; i < form.elements.length; i++)
    {
        var element = form.elements[i];
        var type = element.type;
        if (type == "checkbox" || type == "radio")
        {
            if (element.checked != element.defaultChecked)
            {
             	//alert(element.name);
                return true;
            }
        }
        else if (type == "hidden" || type == "password" || type == "text" ||
                 type == "textarea")
        {
		
    		element.defaultValue = element.defaultValue.replace(/\u00a0/g, " ");
      
            if (element.value != element.defaultValue)
            {
             
             	//alert(element.name+':'+element.value+':'+element.defaultValue+':'+element.value.length+':'+element.defaultValue.length);
             
              	/* excludes these values; not enough to just click a customization box, must do somehting with it too... this only applies to IE, firefox doesn't have a separate defaultvalue for hidden fields */
              	if (element.name=="customization_options") {}
              	else if (element.name=="customization_logo") {}
              	else if (element.name=="customization_street2") {}
              	else if (element.name=="customization_poNumber") {}
              	else if (element.name=="customization_tax") {}
              	else if (element.name=="customization_tax2") {}              	
              	else if (element.name=="customization_discount") {}
                  else if (element.name=="balance_due") {}
            	else if (element.name=="line_tax[]") {}						  			  				  				                	
				else return true;
            }
        }
        
        else if (type == "select-one" || type == "select-multiple")
        {
            for (var j = 0; j < element.options.length; j++)
            {
                if (element.options[j].selected !=
                    element.options[j].defaultSelected)
                    
                    
                {
                //alert(element.name+':'+element.options[j].selected+':'+element.options[j].defaultSelected+': J:'+j);
                    return true;
                }
            }
        } 
    }
    return false;
}

    return function(form, message)
    {
        window.onbeforeunload = function(e)
        {
            e = e || window.event;
            if (formIsDirty(document.forms[form]))
            {
             
            	if (remindUser=="stay") {
                	// For IE and Firefox
	   	            if (e)
    	   	        {
        		       e.returnValue = message;
            	   	}
                	// For Safari
	   	            return message;
   		        }
   		        
   		        else if (remindUser=="inform") {
					
					remindUser = "stay";
					alert(message);
						
					
				}

            }
        };
    };
    
})();


function formIsDirty2(form)
{
 
/* only for the print button; all other actions are handled above in formIsDirty */
  
    for (var i = 0; i < form.elements.length; i++)
    {
        var element = form.elements[i];
        var type = element.type;
        if (type == "checkbox" || type == "radio")
        {
            if (element.checked != element.defaultChecked)
            {
             	//alert('hei1');
                return true;
            }
        }
        else if (type == "hidden" || type == "password" || type == "text" ||
                 type == "textarea")
        {
         
         	//document.writeln(element.name+':'+element.value+':'+element.defaultValue+"<br>");
         
            if (element.value != element.defaultValue)
            {
             	//alert('hei2');
              	//alert(element.name+':'+element.value+':'+element.defaultValue);
              	/* excludes these values; not enough to just click a customization box, must do somehting with it too... this only applies to IE, firefox doesn't have a separate defaultvalue for hidden fields */
              	if (element.name=="customization_options") {}
              	else if (element.name=="customization_logo") {}
              	else if (element.name=="customization_street2") {}
              	else if (element.name=="customization_poNumber") {}
              	else if (element.name=="customization_tax") {}
              	else if (element.name=="customization_tax2") {}              	
              	else if (element.name=="customization_discount") {}	
            	else if (element.name=="line_tax[]") {}
                  else if (element.name=="balance_due") {}
				else {
              		//alert('caught:'+element.name+':'+element.value+':'+element.defaultValue);
				 	return true;
				}
            }
        }
        else if (type == "select-one" || type == "select-multiple")
        {
            for (var j = 0; j < element.options.length; j++)
            {
                if (element.options[j].selected !=
                    element.options[j].defaultSelected)
                {
             	//alert('hei3');
             	//alert(element.options[j].selectedIndex);
             	//alert(element.name);
             	//alert(element.options[j].selected);
             	//alert(element.options[j].defaultSelected);             	
                  
                    return true;
                }
            }
        }
    }
    return false;
}

/* editCustomer.php */

function deleteContact(node) {
 
	/* function to delete a contact */ 
	/* loops backwards/upwards through the nodes until a TABLE is found; then finds the TR and rowIndex of the TR */ 
		
	var table = document.getElementById('contactTable');			
	var rowCount = table.rows.length;
	
	var originalCount = document.getElementById('originalCount').value;
		
    while ( node != null )  {
	     
     	/* first finds the inner table */
   	    if (node.tagName == "TABLE" ) { 
    		while ( node != null )  {
    		 	/* then goes for the tr */
     			if (node.tagName == "TR" ) { 
     			 
					/* if only three rows, means there is only one contact left... deletes the content, not the row; the original count stuff is to ensure that the function that detects changes fires if an original contact is deleted, but not when a new contact is deleted */
					if (rowCount>3) {  if ((node.rowIndex-1)<=originalCount) document.getElementById('formChange').value = 'changed'; table.deleteRow(node.rowIndex);  }
					else {
						var newcell = table.rows[node.rowIndex];
						var inputNode = newcell.getElementsByTagName("input")[0];
						if (inputNode) { 
							inputNode.value=AynaxMessages.FIRST_NAME; 
							inputNode.style.color='silver';
						}
						var inputNode = newcell.getElementsByTagName("input")[1];
						if (inputNode) { 
							inputNode.value=AynaxMessages.LAST_NAME; 
							inputNode.style.color='silver';
						}
						var inputNode = newcell.getElementsByTagName("input")[2];
						if (inputNode) { 
							inputNode.value=AynaxMessages.EMAIL_ADDRESS; 
							inputNode.style.color='silver';
						}
						var inputNode = newcell.getElementsByTagName("input")[3];
						if (inputNode) { 
							inputNode.value=AynaxMessages.PHONE_NUM_LABEL; 
							inputNode.style.color='silver';
						}
					}
	           		break;
	           	}
	           	node = node.parentNode;
	        }
	        break;
   	    }
    	node = node.parentNode;
    }	
}


function newContact() {

	var table = document.getElementById('contactTable');
	var rowCount = table.rows.length;
	
	/* grabs the last row and copies it */
	var row = table.insertRow(rowCount);
	var newcell = row.insertCell(0);
	newcell.innerHTML = table.rows[(rowCount-1)].cells[0].innerHTML;
	
	/* resets the input fields */
	var inputNode = newcell.getElementsByTagName("input")[0];
	if (inputNode) { 
		inputNode.value=AynaxMessages.FIRST_NAME; 
		inputNode.style.color='silver';
	}
	var inputNode = newcell.getElementsByTagName("input")[1];
	if (inputNode) { 
		inputNode.value=AynaxMessages.LAST_NAME; 
		inputNode.style.color='silver';
	}
	var inputNode = newcell.getElementsByTagName("input")[2];
	if (inputNode) { 
		inputNode.value=AynaxMessages.EMAIL_ADDRESS; 
		inputNode.style.color='silver';
	}
	var inputNode = newcell.getElementsByTagName("input")[3];
	if (inputNode) { 
		inputNode.value=AynaxMessages.PHONE_NUM_LABEL; 
		inputNode.style.color='silver';
	}
	
}

function field_onfocus(obj,text) {

 	if ((obj.type=='text')||(obj.type=='select-one')) {
		var node = obj.parentNode; 
		node.className='invoiceForm_fromNameTD_onFocus';
	} 
	else if (obj.type=='textarea')  obj.className='invoiceForm_fromNameTD_onFocus';

	obj.style.backgroundColor='#FFFADC';	
	
	if (text!=null) {
		if (obj.value==text) {
			obj.value = '';
			obj.style.color = '#3c3c3c';
		}	
	}
}

function field_onblur(obj,text) {
 
 	if ((obj.type=='text')||(obj.type=='select-one')) {
		var node = obj.parentNode; 
		node.className='invoiceForm_fromNameTD';
	}
	else if (obj.type=='textarea') obj.className='invoiceForm_fromNameTD';
	
	obj.style.backgroundColor='#FFFFFF';

	if (text!=null) {
		if (obj.value=='') {
			obj.value = text;
			obj.style.color = 'silver';
		} else obj.style.color= '#3c3c3c';
	}
		
}

function nextPage() {
	var regex = new RegExp("[^"+AynaxMessages.REGEX_ALPHA+"_@.]", "i");
	
	/* check the input values on the first page of the form  */
	var emailaddress = document.getElementById('emailaddress').value;
	var password = document.getElementById('password').value;

	if (emailaddress=="") {
		document.getElementById('email_error').style.display="";
		document.getElementById('email_errormsg').innerHTML=AynaxMessages.VALID_EMAIL_ADDRESS;
	}

	else if (emailaddress.search(regex)!=-1) {
		document.getElementById('email_error').style.display="";
		document.getElementById('email_errormsg').innerHTML=AynaxMessages.ILLEGAL_CHARACTER_ADDRESS ;
	}


	else if (emailaddress.indexOf('@')==-1) {
		document.getElementById('email_error').style.display="";
		document.getElementById('email_errormsg').innerHTML=AynaxMessages.INCORRECTLY_FORMATTED_EMAIL;
	}

	
	else if (emailaddress.indexOf('.')==-1) {
		document.getElementById('email_error').style.display="";
		document.getElementById('email_errormsg').innerHTML=AynaxMessages.INCORRECTLY_FORMATTED_EMAIL_PERIOD;
	}
	

	else if (emailaddress.indexOf('www.')!=-1) {
		document.getElementById('email_error').style.display="";
		document.getElementById('email_errormsg').innerHTML=AynaxMessages.EMAIL_WWW_MISSING;
	}

	
	else if (password=="") {
		document.getElementById('email_error').style.display="";
		document.getElementById('email_errormsg').innerHTML=AynaxMessages.MISSING_PASSWORD;
	}
	
	else if (password.length<4) {
		document.getElementById('email_error').style.display="";
		document.getElementById('email_errormsg').innerHTML=AynaxMessages.PASSWORD_TOO_SHORT;
	}
	

	else {

		document.getElementById('headline').innerHTML='<h1 style="font-size:20px;font-weight:bold;font-family:verdana;color:#3c3c3c;margin:0px; padding:0px;">'+AynaxMessages.SAVE_INVOICE_CREATE_ACCOUNT+'<font style="font-size:20px;"> '+ AynaxMessages.STEP2 +'</font></h1>';		
		document.getElementById('email_intro').style.display='none';
		document.getElementById('email_blankTR').style.display='none';
		document.getElementById('email_input').style.display='none';
		document.getElementById('password_blankTR').style.display='none';
		document.getElementById('password_input').style.display='none';
		if (document.getElementById('email_error')!=null) document.getElementById('email_error').style.display='none';

		document.getElementById('webaddress_intro').style.display='';
		document.getElementById('webaddress_blankTR').style.display='';
		document.getElementById('webaddress_input').style.display='';
	
		document.getElementById('firstSubmit').style.display='none';
		document.getElementById('submitButton').style.display='';
		
		$.post("../recordRegistrationFormViewInDB.inc.php", {emailaddress:emailaddress});
	}	
}

/* lp-freePrintableInvoice.php */
function nextPage2() {
	var regex = new RegExp("[^"+AynaxMessages.REGEX_ALPHA+"0-9_@.]", "i");
	
	/* check the input values on the first page of the form  */
	var emailaddress = document.getElementById('emailaddress').value;
	var password = document.getElementById('password').value;

	if (emailaddress=="") {
		document.getElementById('email_error').style.display="";
		document.getElementById('email_errormsg').innerHTML=AynaxMessages.VALID_EMAIL_ADDRESS;
	}

	else if (emailaddress.search(regex)!=-1) {
		document.getElementById('email_error').style.display="";
		document.getElementById('email_errormsg').innerHTML=AynaxMessages.ILLEGAL_CHARACTER_ADDRESS;
	}


	else if (emailaddress.indexOf('@')==-1) {
		document.getElementById('email_error').style.display="";
		document.getElementById('email_errormsg').innerHTML=AynaxMessages.INCORRECTLY_FORMATTED_EMAIL;
	}

	
	else if (emailaddress.indexOf('.')==-1) {
		document.getElementById('email_error').style.display="";
		document.getElementById('email_errormsg').innerHTML=AynaxMessages.INCORRECTLY_FORMATTED_EMAIL_PERIOD;
	}
	

	else if (emailaddress.indexOf('www.')!=-1) {
		document.getElementById('email_error').style.display="";
		document.getElementById('email_errormsg').innerHTML=AynaxMessages.EMAIL_WWW_MISSING;
	}

	
	else if (password=="") {
		document.getElementById('email_error').style.display="";
		document.getElementById('email_errormsg').innerHTML=AynaxMessages.MISSING_PASSWORD;
	}
	
	else if (password.length<4) {
		document.getElementById('email_error').style.display="";
		document.getElementById('email_errormsg').innerHTML=AynaxMessages.PASSWORD_TOO_SHORT;
	}
	

	else {

		document.getElementById('headline').innerHTML=AynaxMessages.FREE_TRIAL_ACCOUNT; ' <font style="font-size:16px;">'+AynaxMessages.STEP2+'</font>';		
		document.getElementById('email_intro').style.display='none';
		document.getElementById('email_blankTR').style.display='none';
		document.getElementById('email_input').style.display='none';
		document.getElementById('password_blankTR').style.display='none';
		document.getElementById('password_input').style.display='none';
		if (document.getElementById('email_error')!=null) document.getElementById('email_error').style.display='none';

		document.getElementById('webaddress_intro').style.display='';
		document.getElementById('webaddress_blankTR').style.display='';
		document.getElementById('webaddress_input').style.display='';
	
		document.getElementById('firstSubmit').style.display='none';
		document.getElementById('submitButton').style.display='';
	}	
}


function sanitizeNames(obj) {

	/* used by:
	/* --------------------------------------------------------
	/* customerForm.inc
	/* invoiceForm.inc
	/* editProfile.php
	/* -------------------------------------------------------- */
	var regex = new RegExp("[^"+AynaxMessages.REGEX_ALPHA+"0-9_.,' ()&-]", "i");
	
	if (obj.value.search(regex)!=-1)  {
	 	var match = obj.value.match(regex);
	 	if (match==" ") var space="Empty space"; else var space="";
		obj.value = obj.value.replace(regex,'');
		alert(AynaxMessages.ILLEGAL_CHARACTER_REMOVE+match+space+AynaxMessages.ALLOW_INPUT_HYPHEN);	
	}
}

function sanitizeAccountId(obj) {

	/* used by:
	/* --------------------------------------------------------
	/* lp-freePrintableInvoice.php
	/* signup.php
	/* freeInvoiceTemplate.php
	/* -------------------------------------------------------- */
	var regex = new RegExp("[^"+AynaxMessages.REGEX_ALPHA+"0-9]", "i");
	
	if (obj.value.search(regex)!=-1)  {
	 	var match = obj.value.match(regex);
	 	if (match==" ") var space="Empty space"; else var space="";
		obj.value = obj.value.replace(regex,'');
		alert(AynaxMessages.ILLEGAL_CHARACTER_REMOVE+match+space+AynaxMessages.ALLOW_INPUT_LETTER);	
	}
}

function sanitizeEmailAddress(obj) {

	/* used by:
	/* --------------------------------------------------------
	/* lp-freePrintableInvoice.php
	/* signup.php
	/* freeInvoiceTemplate.php
	/* sendInvoice.php
	/* customerForm.inc
	/* -------------------------------------------------------- */
	var regex = new RegExp("[^"+AynaxMessages.REGEX_ALPHA+"0-9_@.-]", "i");
	
	if (obj.value.search(regex)!=-1)  {
	 	var match = obj.value.match(regex);
	 	if (match==" ") var space="Empty space"; else var space="";
		obj.value = obj.value.replace(regex,'');
		alert(AynaxMessages.ILLEGAL_CHARACTER_REMOVE+match+space+AynaxMessages.ALLOW_INPUT_SYMBOL);	
	}
}

function sanitizePassword(obj) {

	/* used by:
	/* --------------------------------------------------------
	/* freeInvoiceTemplate.php
	/* 
	/* -------------------------------------------------------- */
	var regex = new RegExp("[^"+AynaxMessages.REGEX_ALPHA+"0-9_@.-]", "i");
	
	if (obj.value.search(regex)!=-1)  {
	 	var match = obj.value.match(regex);
	 	if (match==" ") var space="Empty space"; else var space="";
		obj.value = obj.value.replace(regex,'');
		alert(AynaxMessages.ILLEGAL_CHARACTER_REMOVE+match+space+AynaxMessages.ALLOW_INPUT_NUMBER);	
	}
}

function lookup(obj) {

	/* looks up the account id */
	if (obj.value.length==0) {	
		document.getElementById('error_tr').style.display="none";	 
	}
	
	else if (obj.value.length<4) {
	 
	 	/* show immediately a message stating that the account name must be at least 4 chars long */
		document.getElementById('error_tr').style.display="";	 
		document.getElementById('error_td_img').innerHTML='<img style="margin:0px;padding:0px;" src="images/grey_error_25b.gif">';
		document.getElementById('error_td_txt').innerHTML=AynaxMessages.ACCOUNT_SHORT;


	} else {
	 
	 	/* check if the 4+char account name is available */
		
		$.post("../lookupAccountName.inc.php", {'ai':obj.value}, function(data){
		 
			if (data==0) {
				document.getElementById('error_tr').style.display="";	 
				document.getElementById('error_td_img').innerHTML='<img style="margin:0px;padding:0px;" src="images/grey_checkmark_25.gif">';
				document.getElementById('error_td_txt').innerHTML=AynaxMessages.ACCOUNT_NAME_AVAILABLE;

   			} else {
				document.getElementById('error_tr').style.display="";	 
				document.getElementById('error_td_img').innerHTML='<img style="margin:0px;padding:0px;" src="images/grey_error_25b.gif">';
				document.getElementById('error_td_txt').innerHTML=AynaxMessages.ACCOUNT_NAME_NOT_AVAILABLE;
				
			}
   			
		});
	 
	}
}





/* invoiceNumbers.php */

function onlyNumbers(obj) {
	var regex = new RegExp("[^0-9]", "i");
	
	if (obj.value.search(regex)!=-1)  {
		obj.value = obj.value.replace(regex,'');
		alert(AynaxMessages.ONLY_NUMBERS);	
	}
}

function onlyNumbersLettersOrDashes(obj) {
	var regex = new RegExp("[^"+AynaxMessages.REGEX_ALPHA+"0-9-]", "i");
	if (obj.value.search(regex)!=-1)  {
		obj.value = obj.value.replace(regex,'');
		alert(AynaxMessages.ONLY_LETTERS);	
	}
}

function createInvoiceNumbers() {
	
	var prefix = document.getElementById('prefix').value;
	var start = document.getElementById('start').value;
	var increment = (document.getElementById('increment').value * 1);
	var postfix = document.getElementById('postfix').value;
	
	/* first invoice number */
	var first = prefix+start+postfix;

	/* second invoice number */
	var start_w_zeros_length = start.length;
	start = start * 1;
	start = start+'';
	var start_wo_zeros_length = start.length;
	var zero_count = start_w_zeros_length - start_wo_zeros_length;

	var second_number = (start*1) + increment;
	var diff = (second_number+'').length-start_wo_zeros_length;
	zero_count = zero_count - diff;
	
	var zeros='';
	for (i=0; i<zero_count; i++) {
		zeros=zeros+'0'; 
	}
	
	var second = prefix+zeros+second_number+postfix;

	/* third invoice number */
	var second_w_zeros_length = (second_number+zeros).length;
	var second_wo_zeros_length = (second_number+'').length;
	var zero_count = second_w_zeros_length - second_wo_zeros_length;

	var third_number = second_number + increment;
	var diff = (third_number+'').length-second_wo_zeros_length;
	zero_count = zero_count - diff;
	
	var zeros='';
	for (i=0; i<zero_count; i++) {
		zeros=zeros+'0'; 
	}
	
	var third = prefix+zeros+third_number+postfix;
	
	
	document.getElementById('nextThree').value = first+', '+second+', '+third;
	
	
}

/* sendInvoice.php */

function addRecipient() {

	var copyTable = document.getElementById('javascript_copy');

	var table = document.getElementById('innerSendForm');
	var rowCount = table.rows.length;
	
	/* grabs the first row and copies it */
	var row = table.insertRow(rowCount-8);

	var newcell = row.insertCell(0);
	newcell.innerHTML = "<td></td>";

	var newcell = row.insertCell(1);
	newcell.innerHTML = "<td></td>";

	var newcell = row.insertCell(2);
	newcell.innerHTML = copyTable.rows[0].cells[0].innerHTML;
	newcell.className = copyTable.rows[0].cells[0].className;

	/* resets the input fields */
	var inputNode = newcell.getElementsByTagName("input")[0];
	if (inputNode) { 
		inputNode.value=AynaxMessages.CONTACT_EMAIL_ADDRESS; 
		inputNode.style.color='silver';
	}

	var newcell = row.insertCell(3);
	newcell.innerHTML = '<a title="'+AynaxMessages.REMOVE_RECIPIENT+'" style="cursor:pointer;" onclick="removeRecipient(this);"><img border=0 src="images/delete_item.gif"></a>';
	newcell.style.paddingLeft = '5px';

	var row = table.insertRow(rowCount-8);
	var newcell = row.insertCell(0);
	newcell.innerHTML = '<td></td>';
	newcell.style.height = '5px';	
}


function removeRecipient(node) {

	var table = document.getElementById('innerSendForm');			
	var rowCount = table.rows.length;
	
   	while ( node != null )    {
        if (node.tagName == "TR" ) 	{
         		prevNode = node.previousSibling;
				table.deleteRow(node.rowIndex);
				table.deleteRow(prevNode.rowIndex);
      			return;
   		}
   		node = node.parentNode;
	}
}

function hideshowvariantssendinvoice(){
curent = document.getElementById('variantsSendInvoice').style.display;
if(curent == 'none'){
   document.getElementById('variantsSendInvoice').style.display = 'block';    
}else{
   document.getElementById('variantsSendInvoice').style.display = 'none';
}
}

function checkpayform(){
    form = document.getElementById('buyStampFrom')
    if(form.elements['quantity'].value.length == 0){
        alert(AynaxMessages.NUMBER_STAMPS);        
        form.elements['quantity'].focus();         
      return false;
    }
    myreg = new RegExp("^\\d+$");
    res = myreg.test(form.elements['quantity'].value);
    if (!res) {
        alert(AynaxMessages.NUMBER_STAMPS_DIGIT);
        form.elements['quantity'].focus(); 
        return false;
    }
    
    
    return true;
}

function hideElement(element_id_name){
  document.getElementById(element_id_name).style.display = 'none';        
}

function hideshowelement(element_id_name){

document.getElementById('explain_div_ie').style.display = 'none';    
document.getElementById('explain_div_ff').style.display = 'none';    
document.getElementById('explain_div_chrome').style.display = 'none';    
document.getElementById('explain_div_safari').style.display = 'none';    

curent = document.getElementById(element_id_name).style.display;
if(curent == 'none'){
   document.getElementById(element_id_name).style.display = 'block';    
}else{
   document.getElementById(element_id_name).style.display = 'none';
}        
document.getElementById('TB_window').style.marginTop=(0 - parseInt(document.getElementById('TB_window').offsetHeight / 2) + (TBWindowMargin = document.documentElement && document.documentElement.scrollTop || document.body.scrollTop)) + 'px'

}

function strip(html)
{
   var tmp = document.createElement("DIV");
   tmp.innerHTML = html;
   return tmp.textContent||tmp.innerText;
}

function recordPDFblock() {
	
	//var stripped = htstring.replace(/(<([^>]+)>)/ig,""); 

	var message = document.getElementById('pdf_message_content').innerHTML;
	message = strip(message);
	message = escape(message);
	
	/* registers that the pdf-block has been shown */
	var data = "error="+message;
	ajax("../noPDFblock.inc.php", data, function() { 
		if (xmlhttp.readyState==4 && xmlhttp.status==200) {
	}
	 
	});
	
	
 }

function recordPrint(ai) {
 
	/* registers the number of times this invoice has been printed */
	$.post("../recordPrintInDB.inc.php", {ai:ai});
	
 }

function recordPDF(ai) {

	/* registers the number of times a PDF has been generated from this invoice */
	$.post("../recordPDFInDB.inc.php", {ai:ai});

}

function recordLocalTime(ai) {
	
	now = new Date();
		
	day = now.getDate();
	day = day+'';
	if (day.length==1) day='0'+day;

	month = now.getMonth()+1;
	month=month+'';
	if (month.length==1) month='0'+month;

	year = now.getFullYear();

  	hour = now.getHours();
	hour = hour+'';
	if (hour.length==1) hour='0'+hour;
  	
  	min = now.getMinutes();
	min = min+'';
	if (min.length==1) min='0'+min;
  	
 	var lt = year+'-'+month+'-'+day+' '+hour+':'+min;
	//alert(lt);
	
	/* registers the number of times a PDF has been generated from this invoice */
	$.post("../recordLocalTimeInvoiceViewed.inc.php", {'ai':ai, 'lt':lt});
}

function showLoader() {
	
	document.getElementById('save_box').style.display='none';
	document.getElementById('loading_box').style.display='';
	document.getElementById('loader_td').innerHTML='<img src="images/loader4.gif">';	
	
	
	
}

function passwordEmailErrors(email, password){
    var errors = null;

    if (!email){
        errors = {"error_counter":2, "errorMsg":AynaxMessages.VALID_EMAIL_ADDRESS};
    } else if (!password){
        errors = {"error_counter":2, "errorMsg":AynaxMessages.ENTER_VALID_PASSWORD};
    }else if (password.length < 4){
        errors = {"error_counter":2, "errorMsg":AynaxMessages.PASSWORD_TOO_SHORT};
    }


    return errors;
}

function displayErrorMessageInvoice(message){
    $('#email_error').show();
    $('#email_errormsg').html(message);
}


var ErrorCodeHash = {
    '300' : AynaxMessages.ERROR_300,
    '302' : AynaxMessages.ERROR_302,
    '303' : AynaxMessages.ERROR_303,
    '304' : AynaxMessages.ERROR_304
};

function stripslashes(str){
    return str.replace(/\//g,'');
}

function replaceAll(haystack, needle, replace){
	var pattern = new RegExp(needle,'g');
	return haystack.replace(pattern, replace);
	
}

function checkErrorsInvoice(invoiceValues){
     var errors = null;
     
     var regex = new RegExp("[^"+AynaxMessages.REGEX_ALPHA+"0-9_.,' &()-]", "i");
     
     var matchFromName = regex.exec(  stripslashes(invoiceValues["from_name"])  );

     if ((invoiceValues["from_name"]=="")||(invoiceValues["from_name"]==AynaxMessages.YOUR_NAME))
         errors = {"error_code":300, "errorMsg":ErrorCodeHash['300']};

     else if (matchFromName){
         errors = {"error_code":301, "errorMsg": AynaxMessages.SPECIAL_CHARACTER_NOT_ALLOWED+ " [" + matchFromName +"]"};
     }

     if (invoiceValues["to_id"]=="")
         errors = {"error_code":302, "errorMsg":ErrorCodeHash['302']};

     else if (invoiceValues["invoice_number"]=="")
         errors = {"error_code":303, "errorMsg":ErrorCodeHash['303']};

     
     var matchNewCustomer = regex.exec(  stripslashes(invoiceValues["to_new_customer"])  );
     //if to_id = 0 the user is creating a new customer; this name cannot be blank
     if ((invoiceValues["to_id"]==0)&&((invoiceValues["to_new_customer"]=="")||(invoiceValues["to_new_customer"]=="Customer name")))
         errors = {"error_code":304, "errorMsg":ErrorCodeHash['304']};

     else if (matchNewCustomer ){
         errors = {"error_code":305, "errorMsg":AynaxMessages.SPECIAL_CHARACTER_NOT_ALLOWED_CUSTOMER+" ["+matchNewCustomer+"]"};
     }

     return errors;
}

function getInvoiceValues(){
    var invoiceValues = {
        'from_name' : $('#from_name').val(),
        'to_id'     : $('#to_name').val(),
        'invoice_number' : $('#invoice_number').val(),
        'to_new_customer' : $('#to_new_customer').val()
    };

    return invoiceValues;

}

function displayErrorMessageAjax( errors, invoice_values){
    if (errors){

        var msg = (errors && errors.errorMsg) ? errors.errorMsg : '';

        invoice_values['error_code'] = errors.error_code;
        invoice_values['msg'] = msg;

        $.ajax({
            url: 'validateInvoiceFormDisplayError.php',
            type: 'POST',
            data: { invoice_values : invoice_values },
            cache: false,
            async: false,
            success: function(response){

                var prevElement = $('#infoMessage');
                if (prevElement){
                    prevElement.remove();
                }

                $('#divWithCustomization').after(response);
            },
            error: function(){
                var prevElement = $('#infoMessage');
                if (prevElement){
                    prevElement.remove();
                }

                $('#divWithCustomization').after(AynaxMessages.ERROR_TRY_AGAIN);
            }
        })



    }
}

function validateInvoiceForm(type, page, callback){

    var invoice_values = getInvoiceValues();
    var errors = checkErrorsInvoice( invoice_values );
    var id = $('input[name=c]:first').val()
    if (!errors){
        $.ajax({
            url: 'validateInvoiceForm.php',
            type: 'POST',
            cache: false,
            dataType : 'json',
            async: false,
            data: {invoice_values : invoice_values, page: page, c:id, type:type},
            success: function(request){
                if (request && request.success){

                    callback();

                }else if(request && request.errors){
                    errors = request.errors;
                    displayErrorMessageAjax(errors, invoice_values);

                }else{
                    var prevElement = $('#infoMessage');
                    if (prevElement){
                        prevElement.remove();
                    }

                    $('#divWithCustomization').after(AynaxMessages.ERROR_TRY_AGAIN);
                }

            },
            error: function(){
                var prevElement = $('#infoMessage');
                if (prevElement){
                    prevElement.remove();
                }

                $('#divWithCustomization').after(AynaxMessages.ERROR_TRY_AGAIN);
            }

        });


    }else{
        displayErrorMessageAjax(errors, invoice_values);
    }

}


function validateInvoiceSaveFormEmail(saveMessage){

    var email = $('#emailaddress').val();
    var password = $('#password').val();

    var errors = passwordEmailErrors(email, password);

    if ( !errors ){
        $.ajax({
            url: 'validateEmailAccount.php',
            type: 'POST',
            cache: false,
            dataType : 'json',
            async: false,
            data: {email : email},
            success: function(request){
                if (request && request.success){
                    showLoader();
                    $('#submitButtonHidden').val(saveMessage);
                    $('#invoice_form').submit();

                }else if(request && request.errors){
                    errors = request.errors;
                    var msg = (errors && errors.errorMsg) ? errors.errorMsg : AynaxMessages.ERROR_TRY_AGAIN;
                    displayErrorMessageInvoice(msg);

                }else{
		    $('#email_error').show();
                displayErrorMessageInvoice(AynaxMessages.ERROR_TRY_AGAIN);
		}

            },
            error: function(){
                $('#email_error').show();
                displayErrorMessageInvoice(AynaxMessages.ERROR_TRY_AGAIN);

            }

        });

    }else{
        var msg = (errors && errors.errorMsg) ? errors.errorMsg : AynaxMessages.ERROR_TRY_AGAIN;
        displayErrorMessageInvoice(msg);

    }


}

function printOverlay(src, title){
	var url = 'showExpenses.php?action=printOverlay&src=' + src + '&title=' + title;
	var win = window.open(url,null,'width=760,height=800,top=0; left=0; scrollbars=yes, menubar=yes, toolbar=no');
}

function setSizeImage(width, height){
        var maxWidth = 400;
        var maxHeight = 300;
        var size = {width : width , height : height};


        var ratio = (width/height);

        if (width >= maxWidth && (width >= height)){
            size.width = maxWidth;
            size.height = Math.round( maxWidth / ratio );

        }else if (height >= maxHeight && (height >= width)){
            size.height = maxHeight;
            size.width = Math.round( maxHeight * ratio );

        }else if (width >= maxWidth && (width <= height)){
            size.height = maxHeight;
            size.width = Math.round( maxHeight * ratio );

        }else if (height >= maxHeight && (height <= width)){
            size.width = maxWidth;
            size.height = Math.round( maxWidth / ratio );
        }

        return size;
}

function fullSize(triggerId,oid,imgId){
	//$('#' + triggerId).overlay().close();
	
	var imgObj = $('#' + imgId);
	//get size from src string
	var src = imgObj.attr('src');
	
	var width = 0;
	var height = 0;
	
	if (src){
		var arr= src.split('-');
		width = arr[1];
		height = arr[2];
	}
	
	$('#' + oid).css('width', width);
    $('#' + oid).css('height', height);
    
    imgObj.attr('width', width);
	imgObj.attr('height',height);
	
	$('span.fullsizeSpan').hide();
	$('span.regularsizeSpan').show();
	$('#' + triggerId).overlay().load();
	
}

function regularSize(triggerId,oid,imgId){
	//$('#' + triggerId).overlay().close();
	
	var imgObj = $('#' + imgId);
	//get size from src string
	var src = imgObj.attr('src');
	
	var width = 0;
	var height = 0;
	
	if (src){
		var arr= src.split('-');
		width = arr[1];
		height = arr[2];
	}
	
	var size = setSizeImage(width, height);
	
	$('#' + oid).css('width', size.width);
    $('#' + oid).css('height', size.height);
    
    imgObj.attr('width', size.width);
	imgObj.attr('height',size.height);
	
	$('span.fullsizeSpan').show();
	$('span.regularsizeSpan').hide();
	$('#' + triggerId).overlay().load();
}

function clearImageLink(id){
	var imgObj = $('#uploader_view_receipt_image' + id);
	var src = imgObj.attr('src');
	
	imgObj.attr('src', '');
	
	$('#uploader_view_receipt_layer' + id).hide();
	$('#upload_loader_receipt' + id).hide();
	$('#upload_loader_layer' + id).hide();
	$('#upload_loader_controller' + id).show();

	$('#new_expense_url' + id).val( '' );
	$('#new_expense_name' + id).val( '' );	
}

function deleteImage(triggerId, id, removeRecord){

	$('#' + triggerId).overlay().close();
	
	clearImageLink(id);
	
	if (removeRecord){
		updateExpense(id);
	}
	
	
}

function downloadPDF(image_id, expense_id){
	document.location = 'showExpenses.php?action=downloadImageAttachment&expense_id='+expense_id+'&file=' + $('#' + image_id).attr('url');		
}
function downloadImage(image_id, expense_id){
	document.location = 'showExpenses.php?action=downloadImageAttachment&expense_id='+expense_id+'&file=' + $('#' + image_id).attr('src');	
}

function setOverlayDisplayEvent(id, width, height, receipt_url, view_receipt_layer, view_receipt_image, view_receipt){
	//default for pdf icon
	var size = {width : 192 , height : 192}; 
	var src_url = receipt_url;
	
	var type = "image";
	
	if (src_url && src_url.toLowerCase().indexOf(".pdf") !==-1){
		//PDF
		type = "pdf"; 
		src_url = "/images/pdficon.png";
	}else{
		//Image
		size = setSizeImage(width, height);
	
	}

	$("#" + view_receipt_layer+id).css("width", size.width);
	$("#" + view_receipt_layer+id).css("height", size.height);
	
	var imgObj = $("#" + view_receipt_image + id);
	
	//center loader
	var left = Math.round( (size.width - 32) / 2 );
	var top = Math.round( (size.height - 32) / 2 );
	
	imgObj.css("left", left);
	imgObj.css("top", top);
	
	
	if (type == 'pdf'){
		var imgObj = $("#" + view_receipt_image + id);
		imgObj.css("left", 0);
		imgObj.css("top", 0);
		imgObj.attr("src",src_url);
		imgObj.attr("width",size.width);
		imgObj.attr("height",size.height);
		imgObj.attr("url",receipt_url);
		imgObj.attr("rtype",type);
		
		$("#" + view_receipt_layer+id + ' div.details.image_details').hide();
		$("#" + view_receipt_layer+id + ' div.details.pdf_details').show();
		
		
		$("#" + view_receipt+id).overlay();
	
	}else{
		$("#" + view_receipt_layer+id + ' div.details.image_details').show();
		$("#" + view_receipt_layer+id + ' div.details.pdf_details').hide();
	
		$("#" + view_receipt+id).overlay({
			onLoad:function(){
				var obj = $("#image_temp_placeholder");
				obj.unbind("load");
				obj.attr("src",src_url);
				obj.load(function(){
		
					var imgObj = $("#" + view_receipt_image + id);
					imgObj.css("left", 0);
					imgObj.css("top", 0);
					imgObj.attr("src",obj.attr("src"));
					imgObj.attr("width",size.width);
					imgObj.attr("height",size.height);
					imgObj.attr("url",receipt_url);
					imgObj.attr("rtype",type);
				})
		
		
			}
		});

	
	}
	
}

function payment_check_customer(id){
	var chkPaymentInvoice = document.getElementById("payment_check_invoice" + id);

	if (document.getElementById("payment_check_custormer" + id).checked){
		$('#payment_customer_table_parent'+id).show();
		$('.payment_customer_table'+id).show();
		$('#payment_customer_headline' + id).show();
		$('#payment_customer_form' + id).show();
		
		if (!chkPaymentInvoice.checked){
			$('#payment_invoice_headline' + id).hide();
			$('#payment_invoice_form' + id).hide();
			chkPaymentInvoice.checked = false;

		}
		
		
	}else{
		$('#payment_customer_table_parent'+id).hide();
		$('#payment_customer_form' + id).hide();
		$('#payment_customer_headline' + id).hide();

		if (chkPaymentInvoice.checked){
			$('#payment_invoice_headline' + id).hide();
			$('#payment_invoice_form' + id).hide();
			chkPaymentInvoice.checked = false;

		}

		$('.payment_customer_table'+id).hide();

	}

} 


function payment_check_invoice(id){
	var chkPaymentInvoice = document.getElementById("payment_check_custormer" + id);

	if (document.getElementById("payment_check_invoice" + id).checked){

		$('.payment_customer_table' + id).show();
		$('#payment_invoice_headline' + id).show();
		$('.payment_invoice_form' + id).show();

		if (!chkPaymentInvoice.checked){
			chkPaymentInvoice.checked = true;
			$('#payment_check_custormer' + id).click();
			chkPaymentInvoice.checked = true;
		}
	}else{

		$('#payment_invoice_headline' + id).hide();
		$('#payment_invoice_form' + id).hide();

		if (!chkPaymentInvoice.checked){ $('.payment_customer_table' + id).hide();  }
	}
}

function editVendorForm(overlayId){
	if (overlayId){
		$('#' + overlayId + 'trigger').overlay().close();
		setTimeout(function(){  
			$('#group_by_vendor_opt').click();
			window.location.hash='#main-title_anchor';
		}, 500);
	}
	else{
		$('#group_by_vendor_opt').click();
		window.location.hash='#main-title_anchor';
	}
	
	
}

//Presumes selectObj to be alphabetically order
function indexInsertNewOptionSortOrder(selectObj,value,text){
	var options = selectObj.options
	var size = options.length;
	var index = -1;
	var newOptions= new Array();
	
	for( var i=0; i < size; i ++ ){
	
		if (text.toLowerCase() < options[i].text.toLowerCase()){
			var opt = new Option(value, text);
		
			newOptions.push( opt );
		} 	
		newOptions.push(options[i]);
	}
	
	return newOptions;	
}

function isValidEmail(email) { 
	if (!email){
		return false;
	}else{
		var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
		return re.test(email);
	}
}
	
Number.prototype.formatAynaxCurrency = function(c, d, t){
var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
   return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
 };
