var costsub=0;
//to hinder the enter button from submitting form, to force them to click submit
var submitclicked=false;

function trim(str){
return str.replace(/^\s+|\s+$/g,'');
}

function calccost(num){
	var unitprice=0,total=0;
	//if updating price, update calccost algorith in the php
	total=unitprice*num;
	
	costsub=total.toFixed(2);
}

//keith on the web wrote this, thanks dude
function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function validateall(){
	var ret=true;
	//goes till validate returns false if all statements are like 
	r=validate(document.f1.num);
	ret=r&&ret;
	r=validate(document.f1.shippinginus[(document.f1.shippinginus[0].checked?0:1)]);
	ret=r&&ret;
	if(ret){
		r=validate(document.f1.shipadd);
		ret=r&&ret;
	}
	
	//ret needs help so that the form will interpret the false correctly
	if (ret) {
		ret=true; 
	} else {
		ret=false;
		if (submitclicked==true) { 
			document.getElementById('update_msg').innerHTML='<span class=error>Information is not complete or correct.  Please correct the items in pink.</span>';
			submitclicked=false;
		}
	}
	return ret;
}

//check field value against a rule, a max length and anything else special
//all in order to provide an appropriate error message
var rules = new Array;
rules['num']=/^[1-9]$/
rules['shippinginus']=/^1$/
rules['shipadd']=/^(?!Name\W+Address\W+City, State Zip).+/
//
function validate(field){
	//rules - regexpresion, maxlength
	var ret,ret1=true,ret2=true,ret3=true;

	//check against regular expression
	ret1=(field.value.search(rules[field.name])!=-1);
	if (!ret1) {
		switch (field.name){
			case 'num':
				document.getElementById('num_r').innerHTML=0;
			break;
			case 'shipadd':
				document.getElementById('shipadd_r').innerHTML='';
		}
	}

	//color text if error for any of the checks
	if (!ret1||!ret2||!ret3) {
		style='error';
	}else {
		style='';
	}
	document.getElementById(field.name+'_t').className=style;

	ret=ret1&&ret2&&ret3;
	//POST VALIDATE updates
	//update review display at bottom of page
	if (ret) {
		switch(field.name){
		case 'shipadd':
			document.getElementById('shipadd_r').innerHTML=field.value.replace(/\n/g," <br>");
		break;
		case 'num':
			document.getElementById('num_r').innerHTML=field.value;
		}
	}

	return ret;
}

function submitready(){
	var ret=false;
	if (submitclicked==true)
		if (validateall()==true){
			ret=true;
		}
	return ret;
}
