
var debug = true;
var mybrowser = "";
var ordersent = false;  

function libname(){
	alert ("hello from order.js");
	return true;
}

function help1(){
	alert 
	('Unable to print?\n\n'
	+'Printing requires opening a new window.\n'
	+'Some anti-spyware programs and popup\n'
	+'blocking programs may not allow new windows\n'
	+'to be opened. You may need to check your\n'
	+'settings if you are running that type of software.\n'
	+'You will also need Adobe Reader software.');
}

function testpopulate(frm) {

	if (debug) {
	  frm.cus_name.value = "Paul Hastings";
	  frm.cus_street.value = "15 Lyons St.";
	  frm.cus_town.value = "Newstead";
	  frm.cus_postcode.value = "3462";
	  frm.cus_delivery.value = "Front door opposite milk bar";
	  frm.cus_alternate.value = "Leave at milk bar";
	  frm.cus_phone.value ="61 3 54762076";
	  frm.cus_email.value ="paul.hastings@lizzy.com.au";
	}
}
function validmail(myform) {
	//alert ("debug validmail");
	if (myform.cus_sub.value == "") {
		myform.cus_sub.value = "Message had no subject";
	}
	if (myform.cus_name.value) {return true;}
	if (myform.cus_email.value) {return true;}
	if (myform.cus_msg.value) {return true;}
	alert ("You haven't typed anything.");
	return false;
}	

function validorder(myform, msg) {
	if (validcust(myform)){
		if (calc(myform, msg)){
			return true;
		}else {
			alert ("You haven't selected any wine!");
			return false;
		}
	}
	alert ("Your customer details are not complete!");
	return false;
}

/*
returns current date string in format: day date month year eg. Monday 15 Sep  2003
*/
function displayDate() {

     var d=new Date();
     var weekday=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
     var monthname=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
     var edate = "";

     edate=weekday[d.getDay()] + " ";
     edate+=d.getDate() + " ";
     edate+=monthname[d.getMonth()] + " ";
     edate+=d.getFullYear();
     return edate;
}


/*
Check that the input fields on the form are not blank.
Parameters:
	myform is the form name
	key is the field name prefix for fields to be checked
	firstpicx is the index of the first graphic to change
	different graphics are used to indicate that a field
	is valid or not.
*/	
		
function validcust(myform) {
//if (debug) alert("validcust");

	var postkey = "cus";
	var delkey = "cud";
	var firstpicx = 0;
  
	var obj; 
	var x = 0;
	var msg = "";
	var errs = 0;
	var ok = 1;
	var bitscnt = 0;
    var bits = new Array(0,0,0,0,0);

	var dt = displayDate();
	elementById('ldated', dt);
	myform.dated.value = dt;
	
	
	if  (myform.cus_state.selectedIndex == 0) { myform.cus_state.selectedIndex = 7;}
	if  (myform.cud_state.selectedIndex == 0) { myform.cud_state.selectedIndex = 9;}
	for (i=0;i < myform.length;i++) {
		obj=myform.elements[i];
		if (obj.name.substring(0,postkey.length) == postkey || obj.name.substring(0, delkey.length) == delkey) {
			msg =  msg + x + " "+ obj.name + " value " + obj.value + " length " + obj.value.length +"\n";
	        ok = true;
	        if (obj.name.substring(0, 3) == delkey){
				x += 1;
		    	deliveryaddress(delkey, obj, bits);
	    	}else {
		        if (obj.name.substring(0, 3) == postkey){
		    		x += 1;
					switch (obj.name) {
						case postkey +  "_postcode":
							if (isNaN(obj.value) || (obj.value.length != 4)) {ok = 0;}
							break;
						case postkey + "_delivery":
						case postkey + "_alternate":
							if (obj.value.length < 10){ok=0;}
							break;
						case postkey + "_state":
							break;
						case postkey + "_email":
							if (obj.value.length) {
								if (validate_email(obj.value) == false){ok = 0;}
							}else {
								ok = 2;	
							}
							break;
						default:
							if (obj.value.length < 4){ok = 0;}
							break;
					}//end switch
				}
				setImage(firstpicx + x, ok);
				if (ok == 0) {errs++};
			}
		}
	}
	bitscnt = (checkdelivery(firstpicx + 6, bits));	
	if (bitscnt != 0 && bitscnt != 5) {errs++;}

	if (errs == 0 ){
		calc(myform);
		return true;
	}
	else{
		return false;
	}
}  

function deliveryaddress(key, obj, bits){

	switch (obj.name) {
	case key + "_name":
		if (obj.value.length > 3){bits[0] = 1;}
		break;
	case key + "_street":
		if (obj.value.length > 3){bits[1] = 1;}
		break;
	case key + "_town":
		if (obj.value.length > 3){bits[2] = 1;}
		break;
	case key + "_state":
		if (obj.value != " "){bits[3] = 1;}
		break;
	case key + "_postcode":	
		if (isNaN(obj.value) == false){
			if (obj.value.length == 4)
			{bits[4] = 1;}
		}
		break;
	}
}
/*
returns 0 if there are no delivery address elements or they are all complete
else returns 1
*/
function checkdelivery(ix, bits){
	
	var bx;
	var ok=0;
	
	for (bx=0; bx < bits.length; bx++) {ok += bits[bx];}
	if (ok == bits.length  || ok == 0){
		return ok;
	}else {
		for (bx=0; bx < bits.length; bx++) {
			setImage(ix + bx, bits[bx]);
		}
		return 1;		
	}
}

function setImage(ix, ok){
//alert("setImage " + ix + " ok " +ok);

	if (ok == 1) {
		document.images[ix].src = "images/correct.gif";
	}else {
		if (ok == 0){
	    	document.images[ix].src = "images/incorrect.gif";
    	}else {
	    	document.images[ix].src = "images/blank.gif";
    	}	    	
    }	
}

/*
email the current order
*/

function sendorder(obj){
		
	if (ordersent==false){
		if (validorder(obj, 1)){
			var msg=buildorder(obj);
			alert ("sendorder1");
			sm = new SendMail();
			alert ("sendorder2");
			sm.To = "paul@gcom.net.au";
			sm.From = "me@myco.com";
			sm.Cc = "jaym@hisco.com";
			sm.Subject = "Order";
			sm.Body = msg;
			alert (sm.send());
			alert (sm.errorMessage);
			if (sm.errorCode() == 0 ){
				ordersent=true;
			}else {
				orderSent=false;
			}
		}
	}else{
		alert ("You have already sent this order!");
	}
}


/*
Popup a window and print the current order.
*/ 
function printorder(obj) {

	if (validorder(obj, 1)){
		var msg=buildorder(obj);
		wprint(msg);
	}
}

function buildorder(obj) {
	
	var i=0;
	var msg=obj.title.value;
	msg=msg+'<br><br>'+displayDate();
	msg=msg+'<br><br><table>';
	msg=msg+'<tr valign="top"><td width="300"><b>Postal address</b><br>'+obj.cus_name.value;
	msg=msg+'<br>'+obj.cus_street.value;
	msg=msg+'<br>'+obj.cus_town.value+" "+obj.cus_state.value+" "+obj.cus_postcode.value;
	msg=msg+'</td>';
	msg=msg+'<td width="300"><b>Delivery address</b><br>'+obj.cud_name.value;
	msg=msg+'<br>'+obj.cud_street.value;
	msg=msg+'<br>'+obj.cud_town.value+' '+obj.cud_state.value+' '+obj.cud_postcode.value;
	msg=msg+'<td></tr></table>';

	msg=msg+"<br><b>Delivery instructions</b><br>"+obj.cus_delivery.value;
	msg=msg+"<br><br><b>Alternate delivery instructions</b><br>"+obj.cus_alternate.value;
	msg=msg+"<br><br><b>Phone </b>"+obj.cus_phone.value+"<b> email </b>"+obj.cus_email.value;
	
	msg=msg+"<br><br><table>";
	msg=msg+'<tr><td><b>Cases of 12 x 750ml bottles</b> (prices inc GST)&nbsp\;&nbsp\&nbsp\;&nbsp\;</td>';
	msg=msg+'<td><b>Price</b></td>';
	msg=msg+'<td align="right">&nbsp\;&nbsp\;&nbsp\;&nbsp\;<b>Cases</b></td>';
	msg=msg+'<td align="right">&nbsp\;&nbsp\;&nbsp\;&nbsp\;<b>Amount</b></td></tr>';
	
	var x=0;
	for (i=0;i < obj.length;i++) {
		el=obj.elements[i];
        if (el.name.substring(0, 'qty'.length) == 'qty') {
			//msg=msg+"<br>"+obj.win+i.value;
	        qty=eval("obj.qty"+x+".value");
	        if (qty){
		        product=eval("obj.win"+x+".value");
		        price=eval("obj.pri"+x+".value");
		        ext=eval("obj.ext"+x+".value");
				msg=msg+'<tr><td>'+product+'</td>';
				msg=msg+'<td align="right">'+price+'</td>';
				msg=msg+'<td align="right">'+qty+'</td>';
				msg=msg+'<td align="right">&nbsp\;&nbsp\;'+ext+'</td></tr>';
			}
			x++;
		}
	}
	
	msg=msg+'<tr><td align="right">Sub total&nbsp\;&nbsp\;</td>';
	msg=msg+'<td>&nbsp\;</td>';	
	msg=msg+'<td>&nbsp\;</td>';	
	msg=msg+'<td align="right">'+obj.Subtotal.value+'</td></tr>';
	
	msg=msg+'<tr><td align="right">Freight&nbsp\;&nbsp\;</td>';
	msg=msg+'<td>'+obj.Frt.value+'</td>';	
	msg=msg+'<td align="right">'+obj.Cases.value+'</td>';	
	msg=msg+'<td align="right">'+obj.Freight.value+'</td></tr>';
	
	msg=msg+'<tr><td align="right"><b>Total&nbsp\;&nbsp\;</b></td>';
	msg=msg+'<td>&nbsp\;</td>';	
	msg=msg+'<td>&nbsp\;</td>';	
	msg=msg+'<td align="right"><b>'+obj.Total.value+'</b></td></tr>';
	
	msg=msg+"</table>";	
	return msg;
}

/*
This is supposed to display, print and close a window.
it generally works but in NS 4.7 it does not close the window after printing.
*/
function wprint(msg) {

     var id=popUpID("","printWindow");
     id.document.open();
     id.document.write(msg);
     id.document.close();
     id.window.print();
     id.window.close(); //  doesnt work in ns 4.7, is okay in ie 5  opera 7 ns 7
}

/*
This one returns the window handle
*/
function popUpID(URL, winname) {
     var id=window.open(URL, winname, 
     "toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=600,height=600");
     id.window.focus();
     return id;
}

function popUp(URL, winname) {
     var id=window.open(URL, winname, 
     "toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=600,height=600");
     id.window.focus();
}


/*
returns current date string in format: day date month year eg. Monday 15 Sep  2003
*/
function displayDate() {

     var d=new Date();
     var weekday=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
     var monthname=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
     var edate = "";

     edate=weekday[d.getDay()] + " ";
     edate+=d.getDate() + " ";
     edate+=monthname[d.getMonth()] + " ";
     edate+=d.getFullYear();
     return edate;
}

function elementById(id, val){
	
	if (val){ //set value property
		try
		{
			var el = document.getElementById(id);
			if (ActiveXObject){	el.innerHTML = val;}
		}
		catch(e)
		{
			try
			{
				document.getElementById(id).firstChild.nodeValue=val;
			}
			catch(f)
			{	
				document.getElementById(id, val);
			}
		}
	}else{ //get value property
	
		try
		{
			var el = document.getElementById(id);
			if (ActiveXObject){	val = el.innerHTML;}
		}
		catch(e)
		{
			try
			{
				val = document.getElementById(id).firstChild.nodeValue;
			}
			catch(f)
			{	
				val = document.getElementById(id);
			}
		}
	}
	return val;
}

/*
calculate order value
*/
function calc(myform, msg) {
//if (debug){alert("calc " + myform );}
	
	var obj; 
	var px=0;
	var fx=0;
	var pcode=0;
	var myqty=0;
	var mysubtot=0;
	var mytot=0;
	var myamt=0;
	var myextn=0;
	var myrate=0;
	var myfreight=0;

	pcode=myform.cud_postcode.value;
	if (pcode==""){pcode=myform.cus_postcode.value;}
	fx = pcode.substring(0, 1);
	
	if (!pcode){
		//if (msg){alert ("Your customer details are not complete.");}
		return false;
	}
	
	for (i=0;i < myform.length;i++) {
		obj=myform.elements[i];
        if (obj.name.substring(0, 'qty'.length) == 'qty') {
	        if (isNaN(obj.value) || obj.value.length == 0 || (obj.value.indexOf(".") != -1)) {
		    	obj.value = "";   
	    	}
	    	if (obj.value == 0){
		    	obj.value = "";
		    }else {
	        	myqty = myqty + parseInt(obj.value);
        	}
	        myextn = obj.value * document.getElementById('hpri' + px).value;
	        
	        if (myextn == 0){
		        myextn = "";
				document.getElementById('hext' + px).value="";  
				elementById('amt' + px, " ");
	        }else {
	        	myextn = formatCurrency(myextn);
				document.getElementById('hext' + px).value=myextn;  
				elementById('amt' + px, myextn);
        	}
			mysubtot = mysubtot + toCents(myextn);
			px++;
		}
	}
	
	if (myqty){
		myrate = document.getElementById('rateid' + fx).value;
		myfreight = myqty*myrate;
		mysubtot = mysubtot/100;
		mytot = mysubtot + myqty*myrate
		mytot = formatCurrency(mytot);
		myrate = formatCurrency(myrate);
		myfreight = formatCurrency(myfreight);
		mysubtot = formatCurrency(mysubtot);
		elementById('colhead', 'Amount');
		elementById('lsub', 'Sub total');
		elementById('lfrt', 'Freight');
		elementById('ltot', 'Total');
		elementById('cases', myqty);
		elementById('subtot', mysubtot);
		elementById('freightrate', myrate);
		elementById('freight', myfreight);
		elementById('total', mytot);
		myform.Cases.value=myqty;
		myform.Subtotal.value=mysubtot;
		myform.Frt.value=myrate;
		myform.Freight.value=myfreight;
		myform.Total.value=mytot;
		return true;
	}else {
		elementById('colhead', ' ');
		elementById('lsub', ' ');
		elementById('lfrt', ' ');
		elementById('ltot', ' ');
		elementById('cases', ' ');
		elementById('subtot', ' ');
		elementById('freightrate', ' ');
		elementById('freight', ' ');
		elementById('total', ' ');
		elementById('colhead', ' ');
		myform.Cases.value=' ';
		myform.Subtotal.value=' ';
		myform.Frt.value=' ';
		myform.Freight.value=' ';
		myform.Total.value=' ';
		return false;
	}
	
}

/*
<!-- Original:  Cyanide_7 (leo7278@hotmail.com) -->
<!-- Web Site:  http://www7.ewebcity.com/cyanide7 -->
<!-- This script and many more are available free online at -->
<!-- The JavaScript Source!! http://javascript.internet.com -->
*/
function formatCurrency(num) {
//if (debug){alert("formatCurrency");}
	
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num)) num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10) cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+
		num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}

/*
Unformat a currency string returning whole nbr of cents
*/

function toCents(num) {
//if (debug) alert("tocents");
	
	val = num.toString().replace(/\$|\,/g,'');
	val = val*100;
	if(isNaN(val)) val = 0;
	val = parseInt(val);
	return val;

}
      
/*
give focus to the first input field in the first form on the current page
*/
function setfocus() {
//if (debug) alert("setfocus");

	if (document.forms.length > 0) {
		var field = document.forms[0];	
		for (i = 0; i < field.length; i++) {
			if ((field.elements[i].type == "text") 
			|| (field.elements[i].type == "textarea") 
			|| (field.elements[i].type.toString().charAt(0) == "s")) {
				document.forms[0].elements[i].focus();
				break;
			}
		}
	}
}

/*
give focus to formx elementx on the current page
*/
function shiftfocus(formx, elementx){
//if (debug) alert("shiftfocus");
	var msg = "";

	if (document.forms.length > 0) {
		if (formx < document.forms.length) {
			if (elementx < document.forms[formx].elements.length) {
				//for (i=0;i < document.forms[formx].elements.length;i++) {
				//	msg = msg + "\n" + "shiftfocus() to " + document.forms[formx].elements[i].name + " i " + i;
				//}
				//alert (msg);
				document.forms[formx].elements[elementx].focus();
			}
		}
	}
}


// Written by Joseph Carter
// Vulcan Microsystems

function validate_email(input_str){

var input_len1=input_str.length;
var iserror=0;

    input_len1=input_str.length;

    if (input_len1<=5) {
        //alert("You must enter a Valid Email Address!\n");
        iserror=1;
    }

    var lastdot=-1;
    var lastat=-1;
    var numberat=0
    for (var j = 0; j < input_len1; j++) {
         var ch2 = input_str.substring(j, j + 1);
         if (((ch2 < "a") ||  (ch2 > "z")) && ((ch2 < "A") || (ch2 > "Z")) && ((ch2 < "0") ||  (ch2 > "9")) && (ch2 != "@" ) && (ch2 != ".") && (ch2 != "_") && (ch2 != "-")){
             //alert("Please input a valid email address!\nValid characters include A-Z, a-z, 0-9, -, _, . and @");
             iserror=1;
         }
         if (ch2==".") {
             if ( j == lastdot + 1) {
                 //alert("Please input a valid email address!\nYou can't have two dots next to\neach other'..'.");
                 iserror=1;
             }
             lastdot=j;
         }
         if (ch2=="@") {
             lastat=j;
             numberat=numberat+1
         }
         if (ch2==" ") {
             //alert("Please input a valid email address!\nYou can't have any spaces in the address.");
             iserror=1;
         }
    }
    if (lastat == -1) {
         //alert("Please input a valid email address!\nYou don't have an '@'.");
         iserror=1;
    }
    if (lastat == 0) {
         //alert("Please input a valid email address!\nYou don't have a name before the '@'.");
         iserror=1;
    }
    if (numberat > 1) {
         //alert("Please input a valid email address!\nYou may have only one '@'.");
         iserror=1;
    }
    if ((lastdot <= lastat) || (lastdot > input_len1 - 3 ) || (input_len1 - lastdot > 4)) {
         //alert("Please input a valid email address!\nYou don't have a proper domain name!\nUse .com, .org, .net, .cc, etc");
         iserror=1;
    }
    if (lastdot == lastat + 1) {
         //alert("Please input a valid email address!\nYou don't have a proper organization name!\nUse name@organization.domain");
         iserror=1;
    }
    if (iserror==1) {
         //document.forms[0].email_address.focus();
         return false;
    }

    return true;
}
/*
		function AddValues()	{
			var input1 = document.frmFormAdd.txtInput1.value;
			var input2 = document.frmFormAdd.txtInput2.value;		
			document.frmFormAdd.txtResult.value = parseFloat(input1) + parseFloat(input2);
		}
		function ConcatenateValues()	{
			var input1 = document.frmFormAdd.txtInput1.value;
			var input2 = document.frmFormAdd.txtInput2.value;		
			document.frmFormAdd.txtResult.value = input1 + input2	
		}
		function AddTruncateValues()	{
			var input1 = document.frmFormAdd.txtInput1.value;
			var input2 = document.frmFormAdd.txtInput2.value;		
			document.frmFormAdd.txtResult.value = parseInt(input1) + parseInt(input2);
		}
		function ClearValues()	{
			document.frmFormAdd.txtInput1.value = "";
			document.frmFormAdd.txtInput2.value = "";
			document.frmFormAdd.txtResult.value = "";
		}
*/
