
function format_money(val){
	var money_value = "$" + val;
	var point = money_value.indexOf(".");
	var strlen = money_value.length;

	if (point == -1){
		money_value = money_value + ".00";
	} else {
		if (strlen - point > 3){
			trunc = point + 3;
			money_value = money_value.substring(0, trunc);
		}
		if (money_value.length - point == 2)
			money_value = money_value + "0";
	}
	return(money_value);
}

function add_money(val1, val2){
	re = /^\$|,/g;
	val1 = val1.replace(re, "");
	val2 = val2.replace(re, "");	
	return(format_money(parseFloat(val1) + parseFloat(val2)));
}


function calc_freight(qty){
	freight = 0;
	if (qty){
		freight = 20;
		if (qty >= 6 && qty <=15){
			freight = 10;
		}
		if (qty < 6){
			freight = 6.5;
		}
	}
	return(freight);
}

function grand_total(){

	itemqty = 0;
	tv = "$0.00";
	for (c=0; c<atotalqty.length;c++){
		f = atotalqty[c];
		if (document.ShoppingCartForm[f].value)	itemqty = itemqty + parseInt(document.ShoppingCartForm[f].value);
	}

	for (c=0; c<atotal.length;c++){
		f = atotal[c];
		v = document.ShoppingCartForm[f].value;
		tv = add_money(tv, v);
	}


	if (document.ShoppingCartForm["Freight"]){
	
	}
	freight = format_money(calc_freight(itemqty));
	gst_total = format_money(add_gst(tv));
	gtv = add_money(gst_total, freight);
	
	document.ShoppingCartForm["Gst"].value = format_money(gst_component(gst_total));	
	document.ShoppingCartForm["TotalQty"].value = itemqty;	
	document.ShoppingCartForm["Freight"].value = freight;
	document.ShoppingCartForm["TotalValue"].value = gtv;	
}


function add_gst(value){
	re = /^\$|,/g;
	value = value.replace(re, "");
	value = parseFloat(value) * 1.125;
	return(value);
}
function remove_gst(value){
	re = /^\$|,/g;
	value = value.replace(re, "");
	value = parseFloat(value) / 1.125;
	return(value);
}

function gst_component(value){
	ev = remove_gst(value);
	re = /^\$|,/g;
	value = value.replace(re, "");
	value = parseFloat(value);
	sv = value;

	gst = sv - ev;
	return(gst);
	
}

// Start of Credit Card Number Validation 

function verify_ccard(inNumber, type)
{// returns 0 if valid, positive number if invalid.
        total = 1*0;
        tmp = 1*0;

        number = "";

        // make sure there are only numbers in the string...
        for(i = 0; i < inNumber.length; i++)
        {
                if(inNumber.charAt(i) >= "0" && inNumber.charAt(i) <= "9")
                {
                        number = number + inNumber.charAt(i);
                }
        }

        if(number.length < 13) return 10; // too short for anything

        first = "" + number.charAt(0);
        second = "" + number.charAt(1);
        third = "" + number.charAt(2);
        firstTwo = first + second;
        firstFour = firstTwo + third + number.charAt(3);

        if(type == "MASTERCARD")
        {
                if(first != "5" || second < "1" || second > "5")
                        return 11;// invalid Mastercard prefix
                if(number.length != 16)
                        return 21;
        }
        else if(type == "VISA")
        {
                if(first != "4")
                        return 12;// invalid Visa prefix
                if(number.length != 13 && number.length != 16)
                        return 22;
        }
        else if(type == "AMEX")
        {
                if(first != "3" || (second != "4" && second != "7"))
                        return 13;// invalid American Express Prefix
                if(number.length != 15) 
                        return 23;
        }
        else if(type == "DINERS")
        {
                if(firstTwo != "36"
                        && firstTwo != "38"
                        && (firstTwo != "30" ||
                                (third < "0" || third > "5")))
                {
                        return 15;
                }
                if(number.length != 14)
                        return 25;
        }
         // now check the credit card suffix and length vs. the type

    
         // do the check sum
        for(loc = number.length - 2; loc >= 0; loc -= 2)
        {
                total += 1 * number.charAt(loc +1);
                tmp = number.charAt(loc) * 2;
                if(tmp > 9) total += 1;
                total += tmp%10;
        }
        if(number.length % 2 > 0)
        total += 1 * number.charAt(0);


        return (total % 10);
}

// End of Credit Card Validation
function changeval(formfield){
	form = formfield.form;
	num = parseFloat(formfield.value);
	var sizeref = formfield.name.replace(/qty/,'ipp'); 
	var packamountref = formfield.name.replace(/qty/,'packamount'); 

	if (num){
		scol = form[sizeref];
		if (scol.length){			
			for (var c=0; c < scol.length; c++){
				if (scol[c].checked){
					var ipp = scol[c].value.split(':');
				}
			}	
		} else {
			if (scol.checked){
				var ipp = scol.value.split(':');
			}		
		}
		var price = ipp[1];
		
		document.orderform[packamountref].value = format_money(parseInt(num) * parseFloat(price));
	} else {
		document.orderform[packamountref].value = '';
	}
/*
	ce = sel_fields.length;
	sel_fields[ce] = packamountref;
	sel_prices[ce] = Pprice;
*/
	total_fields(); 
}
function changeipp(formfield){
	re = /^\$|,/g;
	price = formfield.value;
	form = formfield.form;	
	price = parseFloat(price);
	var packamountref = formfield.name.replace(/giftamount/,'packamount'); 
	var ippref = formfield.name.replace(/giftamount/,'ipp'); 
	var qtyref = formfield.name.replace(/giftamount/,'qty'); 
	var qty = document.orderform[qtyref].value;

	if (price && qty){
		scol = form[ippref];
		if (scol.length){			
			for (var c=0; c < scol.length; c++){
				if (scol[c].checked){
					scol[c].value = 'normal:' + price + ':1';
				}
			}	
		} else {
			if (scol.checked){
				scol.value = 'normal:' + price + ':1';
			}		
		}
		document.orderform[packamountref].value = format_money(parseInt(qty) * parseFloat(price));
	} else {
		document.orderform[packamountref].value = '';
	}
	total_fields(); 
}


function changesize(formfield){
	form = formfield.form;
	var qtyref = formfield.name.replace(/ipp/,'qty'); 
	if (form[qtyref].value){
		changeval(form[qtyref]);
	}
	
}

total_fields.field_count = 20;
total_fields.used_fields = 0;

function total_fields(){
	re = /^\$|,/g;
	form = document.orderform;
	var sub_total = 0;
	total_fields.used_fields = 0;
var msg = "";
	for (c=1;c<=total_fields.field_count;c++){
		var pf = 'packamount' + c;
msg = msg + pf + ' ' + form[pf] + ", ";
		if (form[pf] && form[pf].value){
			total_fields.used_fields += 1;
			var val = parseFloat(form[pf].value.replace(re, ""));
			sub_total = sub_total + val;
		}
	}
	if (document.orderform.SubTotal){
		document.orderform.SubTotal.value = format_money(sub_total);
	} else {
		document.orderform.OrderTotal.value = format_money(sub_total);	
	}
	if (document.orderform.freight){
		for(c=0;c<document.orderform.freight.length; c++){
			if(document.orderform.freight[c].checked)
			freight = document.orderform.freight[c].value;
		}
		
		
		grand_total = sub_total + parseFloat(freight);
	} else {
		grand_total = sub_total;
	}
	document.orderform.OrderTotal.value = format_money(grand_total);
	if (total_fields.field_count <= total_fields.used_fields) {
		addRow();
	}
}

function addRow(){

	total_fields.field_count += 1;	
	var Stub = "Rcode" + total_fields.field_count;	
 	document.getElementById(Stub).style.display="";
}


function set_code(aval,formfield){
	formfield.value = aval.Alt;	
	var occref = formfield.name.replace(/occupation/,'occ'); 
	formfield.form[occref].value = aval.Id;

}

var code_array = new Array();

function get_codes(xmldoc, formfield)
{
	var id = 'TEST';
	var results = document.getElementById(id);
	results.innerHTML = "";

	var form = formfield.form;
	var xmllists = xmldoc.getElementsByTagName("bulblist");
	var text;

	var listtext="";
	
	for (var r=0; r < xmllists.length; r++){
		var xmllist = xmllists[r];
		var bulbs = xmllist.getElementsByTagName("bulb");			

		for (var c = 0; c < bulbs.length; c++){
			var bulb = bulbs[c];
			var code = bulb.getAttribute("code");

			var xmlcat = bulb.getElementsByTagName("category")[0];
			var category = xmlcat.firstChild.data;

			var xmlname = bulb.getElementsByTagName("name")[0];
			var name = xmlname.firstChild.data;

			var xmlvart = bulb.getElementsByTagName("variety")[0];
			var variety = xmlvart.firstChild.data;
			
			if (variety == '-') variety = ' ' ;

			var current = 'y';
			var sold_out = 'n';
			var on_sale = 'n';

			var xmlcurrent = bulb.getElementsByTagName("current")[0];
			var current = xmlcurrent.firstChild.data;
			var xmlsold_out = bulb.getElementsByTagName("sold_out")[0];
			var sold_out = xmlsold_out.firstChild.data;
			var xmlon_sale = bulb.getElementsByTagName("on_sale")[0];
			var on_sale = xmlon_sale.firstChild.data;

			var list = document.createElement("li");				
			anchor = document.createElement("a");
			anchor.setAttribute("href","#");
			anchor.appendChild(document.createTextNode(name));			
			anchor.setAttribute("alt", name);
			anchor.Alt = name;

			code_array[c] = name;

			anchor.onclick = function (){
				set_code(this, formfield);
				return false;
			};
			list.appendChild(anchor);

			if (bulbs.length > 1){
				document.getElementById(id).appendChild(list);
			} else {	
				var fullname = category + ' ' + name;
				if (variety != '-'){
					fullname = fullname + ' ' + variety;
				}
				if (on_sale == 'y'){
					fullname = fullname + ' (on sale)';
				}
				if (code == -1){
					alert(name);
					formfield.value = '';
				} else if (current == 'n') {			
					alert(fullname + ' is not a currently stocked bulb');	
					formfield.value = '';
				} else if (sold_out == 'y') {				
					alert(fullname + " SOLD OUT.\n" + "Unfortunately we have sold out of this bulb");	
					formfield.value = '';
				} else {
					if (1==1){
						var nameref = formfield.name.replace(/code/,'name'); 

						formfield.form[nameref].value = fullname;

						var sizeref = formfield.name.replace(/code/,'ipp'); 
						var giftamountref = formfield.name.replace(/code/,'giftamount'); 

						var sizecell = document.getElementById(sizeref);
						sizecell.innerHTML = "";
						var priceref = formfield.name.replace(/code/,'price'); 
						var pricecell = document.getElementById(priceref);
						pricecell.innerHTML = "";
						var qtyref = formfield.name.replace(/code/,'qty'); 
						var paref = formfield.name.replace(/code/,'packamount'); 

	
	
						var itemrows = bulb.getElementsByTagName("item");			
				// alert(dayrows.length);
						var itag = 'normal';
						var chk = ' selected';
						for (var c = 0; c < itemrows.length; c++){
							var itemrow = itemrows[c];
//				alert(itemrow);
							var xmltypename = itemrow.getElementsByTagName("item_type")[0];
							var item_type = xmltypename.firstChild.data;
							var xmlitemsname = itemrow.getElementsByTagName("num_items")[0];
							var num_items = xmlitemsname.firstChild.data;
							var xmlpricename = itemrow.getElementsByTagName("price")[0];
							var price = xmlpricename.firstChild.data;
//							alert(item_type + ' ' + num_items + ' ' + itag + ':' + price);
							sizecell.innerHTML += '<input type="radio" name="'+sizeref+'" value="'+itag+':' + price + ':' + num_items + '" onClick="changesize(this)">'+num_items+'<br>';
	
							if (code == '999'){							
								pricecell.innerHTML += '$<input type="text" name="' + giftamountref + '" size="4" onChange="changeipp(this)"><br>';
							} else {
								pricecell.innerHTML += '$' + price + '<br>';
							
							}

						}
						var col = form[sizeref];
						if (itemrows.length > 1){
							col[0].checked = 1;
						} else {
							col.checked = 1;							
						}
						form[qtyref].value = 1;


						if (code == '999'){ // Gift voucher exception
							form[giftamountref].focus();
						} else {					
							changeval(form[qtyref]);
							form[qtyref].focus();
						}
						
						
					} else {
						var coderef = formfield.name.replace(/name/,'code'); 
						formfield.form[coderef].value = code;				
					}
				}
				
			
			}

		}


	}
//	results.innerHTML = listtext;

}


function isnumeric(englishname, formfield){

var ValidChars = "0123456789.-+,";
var IsNumber=true;
var Char;
var rv = formfield.value;
	for (i = 0; i < rv.length && IsNumber == true; i++) 
	{ 
		Char = rv.charAt(i); 
		if (ValidChars.indexOf(Char) == -1) {
			IsNumber = false;
		}
	}
	if (!IsNumber){
		alert(englishname + " must be a number please.");	
		formfield.focus();
		return(false);
	}

	return(true);
}

function check_rd(rdno, rfchecked){
	var ret = true;
	
	if (rfchecked && !rdno){
		alert("You have selected Rural Delivery, please enter a Rural Delivery No:");
		ret = false;
	}
	if (!rfchecked && rdno){
		alert("You have entered a Rural Delivery No:, please also select the Rural Delivery freight option");
		ret = false;
	}
	return(ret);
}

function emailcheck(str) {

var at="@"
var dot="."
var lat=str.indexOf(at)
var lstr=str.length
var ldot=str.indexOf(dot)
var valid = true;

	if (str.indexOf(at)==-1){
		valid = false;
	}
	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		valid = false;
	}
	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		valid = false;
	}
	if (str.indexOf(at,(lat+1))!=-1){
		valid = false;
	}
	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		valid = false;
	}
	if (str.indexOf(dot,(lat+2))==-1){
		valid = false;
	}		
	if (str.indexOf(" ")!=-1){
		valid = false;
	}
	
	return(valid);
}


function checkcode(formfield){
	var name = formfield.name;
	var code = formfield.value.toString();
	
	d = new Date();
	ms = d.getTime();
	if (code.length >= 3 && code.length <= 4){
		url = 'xbulb.php?code=' + code + '&ms=' + ms;
		var request = HTTP.newRequest();
		request.onreadystatechange = function() {
			if (request.readyState==4) { 
				if (request.status == 200){
					get_codes(request.responseXML, formfield);
				}
			}
		}
		request.open("GET", url, true);
		request.setRequestHeader("User-Agent", "XMLHttpRequest");
		request.send(null);
	}
}

