var choices = null;
var products = null;
var touched = 0;
var origyear = null;
var origmonth = null;
var origday = null;

var prodnum1=5;
function addnewline1(){
	if(prodnum1>=50){
		alert('You add too many lines , please add to another invoice');
		return;
	}
	var p1=prodnum1;
	str+="</select>";
	var x=document.getElementById('productarea1');
	cat0ops=document.forms.overland.cat0.innerHTML;
	var newrow=x.insertRow();
	var newcell=newrow.insertCell();
	var str="<select name=cat"+p1+" id=cat"+p1+" onchange='touched="+p1+";cleanAndRenew("+p1+", 1);tally()'><option value=0 selected>"+cat0ops;
	newcell.innerHTML=str;
	newcell=newrow.insertCell();
	str="<input name=qty"+p1+" type='text' id=qty"+p1+" size='5' onkeyup='multiply([String(this.name), this.form.unit"+p1+".name], this.form.total"+p1+".name);tally()' onBlur='tally()'>";
	newcell.innerHTML=str;

	newcell=newrow.insertCell();
	str="<select name='type"+p1+"' id='type"+p1+"' onchange='addUnit(this)'><option value='dummy'>---Product Type---</option></select>";
	newcell.innerHTML=str;

	newcell=newrow.insertCell();
	str="<strong>@</strong>";
	newcell.innerHTML=str;

	newcell=newrow.insertCell();
	str="<input name='unit"+p1+"' type='text' id='unit"+p1+"' size='8' onkeyup='multiply([String(this.name), this.form.qty"+p1+".name], this.form.total"+p1+".name);tally()' onBlur='reformat(this);tally()'>";
	newcell.innerHTML=str;

	newcell=newrow.insertCell();
	str="$<input name='total"+p1+"' type='text' id='total"+p1+"' size='8' onkeyup='tally()' onBlur='reformat(this);tally()'>";
	newcell.innerHTML=str;


	prodnum1++;

}


function fillProducts(what) {
	products = what;
}

function fillChoices(what) {
	choices = what;
}

function remember() {
	origyear = document.overland.year.selectedIndex;
	origmonth = document.overland.month.selectedIndex;
	origday = document.overland.day.selectedIndex;
}
function setTodaysDate() {
	if(document.overland.year) {
		document.overland.year.selectedIndex = origyear;
		document.overland.month.selectedIndex = origmonth;
		document.overland.day.selectedIndex = origday;
	}
}
function findMySpot(needle, haystack) {
	var overstack = eval("document.overland."+String(haystack));
	for(var i=0;i<overstack.length;i++) {
		var mylabel = overstack.options[i].text;
		mylabel = String(mylabel.toLowerCase());
		needle = String(needle.toLowerCase());
		if(mylabel == needle) {
			return i;
		}
	}
	return -1;
}


function fillForm(what) {
	var pos = what.selectedIndex;
	if(pos == 0) {
		var template = choices[1];
		for(var x=0;x<template.length;x++) {
			var box = template[x][0];
			var loc = eval("document.overland."+box);
			if(loc) {
				if(loc.type == "text" || loc.type == "textarea" || loc.type == "hidden") {
					loc.value = "";
				} else {
					if(loc.type == "select-one") {
						loc.selectedIndex = 0;
					}
				}
			}
		}
		setTodaysDate();
	} else {
		var stats = choices[pos];
		for(var x=0;x<stats.length;x++) {
			var box = String(stats[x][0]);
			var loc = eval("document.overland."+box);
			if(box == "date") {
				var calandar = stats[x][1];
				calandar = calandar.split("-");
				var order = ["year","month","day"];
				for(j=0;j<order.length;j++) {
					target = order[j];
					newvalue = calandar[j];
					var howFarDown = findMySpot(newvalue, target);
					target = eval("document.overland."+target);
					if(howFarDown > 0) {
						target.selectedIndex = howFarDown;
					} else {
						target.selectedIndex = 0;
					}
				}
			} else {
				if(loc) {
					if(loc.type == "text" || loc.type == "textarea" || loc.type == "hidden") {
						loc.value = stats[x][1];
					} else {
						if(loc.type == "select-one") {
							var position = findMySpot(String(stats[x][1]), box);
							if(position > 0) {
								loc.selectedIndex = position;
							} else {
								loc.selectedIndex = 0;
							}
						}
					}
				}
			}
		}
	}
	fillInvoiceNo();
}


function add(addthis, answer) {
	var sum = 0;
	var blemish = 0;
	for(var i=0;i<addthis.length;i++) {
		if(eval("document.overland."+addthis[i])){
			var addon = parseFloat(eval("document.overland."+addthis[i]+".value"));
			if(!isNaN(addon)) {
				sum += addon;
			}
		}
	}
	var destination = eval("document.overland."+answer);
	destination.value = getCurrency(sum);
}

function reformat(what) {
	var target = what.value;
	if(!isNaN(target) && target.length > 0) {
		var changeOver = getCurrency(target);
		what.value = changeOver;
	}
}

function getCurrency(initprice) {
	initprice = String(initprice);
	var decimal = initprice.indexOf(".");
	if(decimal == -1) {
		var dollars = initprice;
		var cents = "00";
	} else {
		var dollars = initprice.substr(0, decimal);
		var cents = initprice.substr(decimal+1);
		if(parseInt(cents) < 10) {
			cents += "0";
		}
		if(cents.length > 2) {
			cents = cents.substr(0, 2);
		}
	}
	price = dollars+"."+cents;
	return(price);
}

function gutThat(what, isprice) {
	what = String(what);
	if(what == 0) {
		var initprice = what;
	} else {
		var startpoint = what.indexOf("|");
		if(startpoint != -1) {
			var initprice = what.substr(startpoint + 1);
		} else {
			intiprice = what;
		}
	}
	if(isprice) {
		initprice = getCurrency(initprice);
	}
	return(initprice);
}
function multiply(byThis, answer) {
	var multthis = parseFloat(eval("document.overland."+byThis[0]+".value"));
	var bythat = parseFloat(eval("document.overland."+byThis[1]+".value"));
	if(!isNaN(multthis) && !isNaN(bythat)) {
		var result = multthis * bythat;
	} else {
		var result = "";
	}
	var destination = eval("document.overland."+answer);
	if(result != 0) {
		destination.value = getCurrency(result);
	}
}
function tally() {
	var totality = new Array();
	for(var f=0;f<100;f++) {
		totality[f] = "total"+f;
	}
	totality[totality.length] = "subtotal";
	add(totality, "finalsubtotal");
	getPercent("gst","finalsubtotal","netprofit");
	getPercent("pst","finalsubtotal","netprofit");
	getTaxes();
}
function fillInvoiceNo() {
	if(document.overland.invoiceno) {
		var suffix = choices[0];
		var surname = document.overland.company.value;
		if(surname != "") {
			var threeletters = surname.substr(0, 3);
			var prefix = threeletters.toUpperCase();
			var invoiceno = prefix+suffix;
			document.overland.invoiceno.value = invoiceno;
			document.overland.who.value = prefix;
		} else {
			document.overland.invoiceno.value = "";
			document.overland.who.value = "";
		}
	}
}
function getPercent(percent, ofWhat, destination) {
	var percentbox = eval("document.overland."+percent);
	var percent = percentbox.value;
	var ofThis = eval("document.overland."+ofWhat+".value");
	var onePercent = parseInt(ofThis) / 100;
	var percentage = onePercent * percent;
	var finalRestingPlace = eval("document.overland."+destination);
	var newValue = parseFloat(ofThis) + percentage;
	finalRestingPlace.value = getCurrency(newValue);
	getTaxes();
}
function getSupplyTaxes() {
	var originalValue = document.getElementById("unitprice").value;
	var pst = document.getElementById("processing").value;
	var gst = document.getElementById("fee").value;
	var onepercent = originalValue / 100;
	var daltonsTax = onepercent * pst;
	var paulsTax = onepercent * gst;
	var taxtotal = parseFloat(daltonsTax + paulsTax);
	var grandtotal = parseFloat(originalValue) + taxtotal;
	var grandtotal = getCurrency(grandtotal);
	document.getElementById("totalprice").value = grandtotal;
}
function twocents(that) {
	var chopup = String(that);
	if(chopup.indexOf(".") != -1) {
		var decimal = chopup.indexOf(".");
		var endpoint = chopup.length;
		var cents = decimal + 3;
		if(endpoint > cents) {
			chopup = chopup.substr(0, cents);
		}
	}
	return parseFloat(chopup);
}
function getTaxes() {
	if(document.overland.taxes.value == "") {
		var taxbefore = 0;
	} else {
		var taxbefore = document.overland.taxes.value;
	}
	if(document.overland.finalsubtotal.value == "") {
		var original = 0;
	} else {
		var original = document.overland.finalsubtotal.value;
	}
	if(document.overland.pst.value == "") {
		var pst = 0;
	} else {
		var pst = document.overland.pst.value;
	}
	if(document.overland.gst.value == "") {
		var gst = 0;
	} else {
		var gst = document.overland.gst.value;
	}
	var onePercent = original / 100;
	var daltonsTax  = onePercent * pst;
	var paulsTax = onePercent * gst;
	var totaltaxes = paulsTax + daltonsTax;
	document.overland.taxes.value = getCurrency(totaltaxes);
	var grandtotal = parseFloat(original) + parseFloat(totaltaxes);
	document.overland.netprofit.value = getCurrency(grandtotal);
}
function revealSupportPrices(who, that) {
	if(navigator.appName.indexOf("Netscape") != -1) {
		var origin = that;
	} else {
		if(event.srcElement) { var origin = window.event.srcElement }
		if(event.currentTarget) { var origin = window.event.currentTarget }
	}
	var init = origin.value;
	var stuff = init.split(",");
	var mainbit = eval("document.overland.cat"+who);
	var desc = eval("document.overland.item"+who);
	var unitprice = eval("document.overland.total"+who);
	if(mainbit.selectedIndex != 0) {
		desc.value = stuff[0];
		unitprice.value = getCurrency(stuff[1]);
	} else {
		desc.value = "";
		unitprice.value = "";
	}
}
function display(that) {
	if(navigator.appName.indexOf("Netscape") != -1) {
		var origin = that;
	} else {
		if(event.srcElement) { var origin = window.event.srcElement }
		if(event.currentTarget) { var origin = window.event.currentTarget }
	}
	if(document.overland.category) {
		document.overland.category.value = document.overland.cat0.options[document.overland.cat0.selectedIndex].text;
	}
	var init = origin.value;
	if(origin.type == "select-one") {
		var sel = origin.selectedIndex;
	} else {
		var sel = 0;
	}
	var stuff = init.split(",");
	var positions = ["itemname","unitprice","servicecode","vendor","vendorpartno","buyer","processing","fee","format","description","supporttype","colour","id","size"];
	if(sel != 0) {
		for(var x=0;x<positions.length;x++) {
			var target = eval("document.overland."+positions[x]);
			if(target) {
				var species = target.type;
				switch(species) {
					case "select-one":
					target.selectedIndex = parseInt(stuff[x]);
					break;
					default:
					if(positions[x] == "processing" || positions[x] == "fee") {
						var pigeonhole = parseInt(stuff[x]);
					} else {
						var pigeonhole = stuff[x];
					}
					target.value = pigeonhole;
				}
			}
		}
	} else {
		clearText("overland");
	}
	if(document.overland.totalprice && sel != 0) {
		getSupplyTaxes();
	}
}
function evaluate(who, where, status, msgbox) {
	if(formcheck(who)) {
		var overform = eval("document."+who);
		var propername = overform.billto[overform.billto.selectedIndex].text;
		var client = overform.company.value;
		var email = overform.email.value;
		status = parseInt(status);
		switch(status) {
			case 0:
			var type = "a quote";
			break;
			case 1:
			var type = "an estimate";
			break;
			default:
			var type = "an invoice";
		}
		if(msgbox) {
			var question = "You are about to send "+type+" to "+propername+" of "+client+" at "+email+". Press OK to submit the invoice, Cancel to cancel it";
			if(confirm(question)) {
				overform.action = where;
			//var pquestion = "Would you like to print current document";
			//if(confirm(pquestion)) {
			//            window.print();
			//			}

				overform.submit();
			}
		} else {
			overform.action = where;
			overform.submit();
		}
	}
}
function submitWithQ(what, where) {
	var overform = eval("document."+what);
	if(productformGood(what)) {
		var question = "If you are sure you want to save the changes, click OK. if not, choose Cancel";
		if(confirm(question)) {
			overform.action = where;
			overform.submit();
		}
	}
}
function already(needle, haystack) {
	for(j=0;j<haystack.length;j++) {
		if(needle == haystack[j] || needle.indexOf(haystack[j]) != -1) {
			return true;
		}
	}
	return false;
}
function formcheck(who) {
	var formID = "document."+who;
	var thatForm = eval(formID);
	var thatformskids = thatForm.elements;
	var howmany = thatformskids.length;
	for(var h=0;h<howmany;h++) {
		var species = thatformskids[h].type;
		var me = thatformskids[h].name;
		var mandselect = ["billto","month","day","year"];
		switch(species) {
			case "select-one":
			var myIt = me.indexOf("type");
			if(myIt != -1) {
				var mynumber = me.substr(myIt + 4);
				var mother = eval(formID+".cat"+mynumber);
				if(mother.selectedIndex != 0) {
					var mycat = mother.options[mother.selectedIndex].text;
					var I = eval(formID+".type"+mynumber);
					if(I.selectedIndex == 0) {
						alert("You have not selected a product for the "+mycat+" category");
						return false;
					}
				}
			} else {
				for(var t=0;t<mandselect.length;t++) {
					currString = formID+"."+mandselect[t];
					var currelement = eval(currString);
					if(currelement.selectedIndex == 0) {
						alert("You have not selected an option for the "+mandselect[t]+" menu");
						return false;
					}
				}
			}
			break;
			case "text":
			var opttext = ["unit","qty","day","total","fax"];
			if(already(me, opttext)) {
				if(me.indexOf("qty") != -1) {
					var mynumber = me.substr(3);
					var mother = eval(formID+".cat"+mynumber);
					var brother = eval(formID+".type"+mynumber);
					var I = eval(formID+".qty"+mynumber);
					var mycat = mother.options[mother.selectedIndex].text;
					if(mother.selectedIndex != 0 && brother.selectedIndex != 0 && I.value == "") {
						alert("You have not filled in a quantity for "+mycat);
						return false;
					}
				}
			} else {
				for(var l=0;l<opttext.length;l++) {
					var myIt = me.indexOf(opttext[l]);
					currString = formID+"."+me;
					var currelement = eval(currString);
					if(myIt != -1) {
						if(currelement.value == "") {
							alert("You have not filled in a value for the "+me+" field");
							return false;
						}
					}
				}
			}
			break;
		}
	}
	return true;
}
function myID(who) {
	for(f=0;f<document.overland.length;f++) {
		var needle = document.overland.elements[f].id;
		if(needle == who) {
			return f;
		}
	}
	return "dodo";
}
function clearText(overThere) {
	var theform = eval("document."+overThere);
	var bagOfShit = theform.elements;
	for(var t=0;t<bagOfShit.length;t++) {
		var moi = bagOfShit[t];
		var species = moi.type;
		if(species == "text" || species == "textarea" || species == "hidden") {
			moi.value = "";
		}
	}
}
function productformGood(overThere) {
	var theform = eval("document."+overThere);
	var bagOfShit = theform.elements;
	for(var t=0;t<bagOfShit.length;t++) {
		var moi = bagOfShit[t];
		var species = moi.type;
		if(species == "text" || species == "textarea") {
			if(moi.value == "" && moi.name != "addsupporttype") {
				alert("You have not filled in a value for "+moi.name);
				return false;
			}
		}
	}
	return true;
}
function cleanAndRenew(who, frominvoice) {
	var myel = eval("document.overland.cat"+who);
	var myover = eval("document.overland.type"+who);
	myover.selectedIndex = 0;
	var uplimit = myel.length - 1;
	for(var t=uplimit;t>=0;t--) {
		myover.options[t] = null;
	}
	var pos = myel.selectedIndex;
	if(pos != 0) {
		myover.options[0] = new Option("---Choose Product Type---", 0);
	} else {
		myover.options[0] = new Option("---Product Type---", 0);
	}
	var mylist = products[pos];
	if(pos > 0 && mylist.length > 1) {
		for (var i=1;i<mylist.length;i++) {
			if(frominvoice) {
				var crap = String(mylist[i]);
				var slash = crap.indexOf("|");
				var itemname = crap.substr(0, slash);
				myover.options[i] = new Option(itemname, crap);
			} else {
				var bigchunkoshit = String(mylist[i]);
				var otherlist = bigchunkoshit.split(",");
				myover.options[i] = new Option(otherlist[0], mylist[i]);
			}
		}
	}
}
function drawproducts(who, augunit) {
	var myel = eval("document.overland.cat"+who);
	var myover = eval("document.overland.type"+who);
	var pos = myel.selectedIndex;
	if(myover) {
		if(pos == 0) {
			var y = myID("type"+who);
			var el = document.getElementById("overland").elements;
			var doofus = el[y].parentNode;
			doofus.removeChild(el[y]);
			var cp = document.createElement("select");
			cp.setAttribute("id", "type"+who);
			doofus.appendChild(cp);
			document.getElementById("type"+who).name = "type"+who;
			document.getElementById("type"+who).id = "type"+who;
			document.getElementById("type"+who).options[0] = new Option("<-- Choose A Category --<", 0);
		} else {
			var y = myID("type"+who);
			var el = document.getElementById("overland").elements;
			var doofus = el[y].parentNode;
			doofus.removeChild(el[y]);
			var cp = document.createElement("select");
			cp.setAttribute("id", "type"+who);
			doofus.appendChild(cp);
			document.getElementById("type"+who).name = "type"+who;
			document.getElementById("type"+who).id = "type"+who;
			if(augunit) {
				if(navigator.appName.indexOf("Netscape") == -1) {
					document.getElementById("type"+who).setAttribute("onchange", addUnit);
				} else {
					document.getElementById("type"+who).setAttribute("onchange", "addUnit(this)");
				}
			} else {
				if(navigator.appName.indexOf("Netscape") == -1) {
					document.getElementById("type"+who).setAttribute("onchange", display);
				} else {
					document.getElementById("type"+who).setAttribute("onchange", "display(this)");
				}
			}
			document.getElementById("type"+who).options[0] = new Option("--- Choose A Product ---", 0);
			var mylist = products[pos];
			if(augunit) {
				for (i=1;i<mylist.length;i++) {
					var crap = String(mylist[i]);
					var slash = crap.indexOf("|");
					var itemname = crap.substr(0, slash);
					document.getElementById("type"+who).options[i] = new Option(itemname, crap);
				}
			} else {
				for (i=1;i<mylist.length;i++) {
					var crap = String(mylist[i][0]);
					var menu = String(mylist[i]);
					document.getElementById("type"+who).options[i] = new Option(crap, menu);
				}
			}
		}
	}
}
function addUnit(who) {
	if(navigator.appName.indexOf("Netscape") != -1) {
		var origin = who;
	} else {
		if(event.srcElement) { var origin = window.event.srcElement }
		if(event.currentTarget) { var origin = window.event.currentTarget }
	}
	var moniker = origin.name;
	var mynumber = parseInt(moniker.substr(4));
	touched = mynumber;
	var myquan = eval("document.overland.qty"+touched);
	var myunit = eval("document.overland.unit"+touched);
	var mytotal = eval("document.overland.total"+touched);
	myunit.value = gutThat(origin.options[origin.selectedIndex].value, true);
	multiply([myquan.name, myunit.name], mytotal.name);
	tally();
}

function formGood() {
	var whattocheck = ["itemname","unitprice","category"];
	for(var y=0;y<whattocheck.length;y++) {
		var mystring = String(whattocheck[y]);
		var locale = eval("document.overland."+mystring);
		var contents = locale.value;
		if(contents.length < 1) {
			alert("You have not filled in a value for the "+whattocheck[y]+" field");
			locale.focus();
			return false;
		}
	}
	var notnumberlist = ["unitprice","processing","fee","totalprice"];
	for(var e=0;e<notnumberlist.length;e++) {
		var mystring = String(whattocheck[e]);
		var locale = eval("document.overland."+notnumberlist[e]);
		var contents = locale.value;
		if(contents.length > 0) {
			if(isNaN(contents)) {
				switch(notnumberlist[e]) {
					case "processing":
					var label = "PST";
					break;
					case "fee":
					var label = "GST";
					break;
					default:
					var label = notnumberlist[e];
				}
				alert("You have not entered a number in the "+label+" field");
				locale.focus();
				return false;
			}
		}
	}
	return true;
}
function okIt(where) {
	if(formGood()) {
		document.overland.action = where;
		document.overland.submit();
	}
}
