var $frm=false;
var $pag=false;
var $org;
function is_canada(){
	var lst;
	if(ge('reg_diff_chk').checked){		
		lst=ge('i_sstate');
	}else{
		lst=ge('i_state');
	}
	var state=lst.options[lst.selectedIndex].value;
	var prov=['AB','BC','MB','NB','NL','NT','ON','PE','QC','SK','NS','YT','NU'];
	return (state in arraY(prov));	
}
function ui_redirect(place){
	if(place='cart'){
		window.location="http://"+$hs+"i.php?pg=shop&action=view";
	}
}
function ui_submit(act,v,frm,pag){
	$org=0;
	if(frm=='chk'){
		if($trg_org!=-1){
			if($trg_org){
				$org=$trg_org.getAttribute('oid');
			}else{
				//alerT("You have not selected a school/organization.",0,0,'OK');
				//return;
			}
		}					
		var cart=eval("("+$jcart+")");
		for(i in cart){
			if(cart[i].yoke==2){
				if(is_canada()){
					alerT("Our "+cart[i].nam+" is only available for shipping in the USA.  You may either change your billing/shipping information or edit your shopping cart to remove this product.",0,600,'stay and edit shipping info','go to cart',false,"ui_redirect('cart')");
					return;
				}
				break;
			}
		}
		
	}
	if(pag){$pag=pag;}
	if(!act || act=='verified'){
		var tbl=v.split(',');
		var tx='',typ,u,lbl,min,targ,xpdat='';
		var dat=[];
		for(var a=0;a<tbl.length;a++){
			var t=ge(tbl[a]);
			var xlb=t.getAttribute('xlb');xlb=xlb?xlb+' ':'';
			var use=t.getAttribute('use');
			var r=t.rows;
			var d=t.getElementsByTagName('DIV');
			for(i=0;i<d.length;i++){
				div=d[i];
				typ=div.getAttribute('typ');
				if(typ && typ!='lb'){
					u=typ.split('_');
					typ=u[0];
					cat=(u.length>1)?u[1]:false;
					ord=(u.length>2)?u[2]*1:-1;
					if(ord>-1){
						targ=ge('i_'+div.id);						
						if(targ){
							lbl=ge('l_'+ord).innerHTML.trim();							
							man=right(lbl,1)=='*';
							if(man){lbl=lbl.substring(0,lbl.length-2);}
							tx+=i+" - "+ ord+div.id+"<br>"
							dat[ord]={use:use*1,id:div.id,typ:typ,cat:cat,
												val:targ.value,div:div,min:div.getAttribute('min')*1,
												ctl:targ,lbl:'<b>&#9658; '+xlb+lbl+'</b>',label:lbl,man:man,msg:false};
						}						
					}
				}
			}			
		}
		var ret=ui_validate(dat,frm);
		if(ret){
			alerT(ret,false,400,'Ok');
		}else{
			var pvar='';
			var	prefix=(frm=='reg' || frm=='acc')?'wu_':'od_';
			for(i=0;i<dat.length;i++){
				if(dat[i].use){
					pvar+=pvar?'&':'';
					pvar+=prefix+dat[i].id+'='+escape(dat[i].val);
				}
			}
			if(frm=='cnf'){xpdat='&od_notes='+escape(ge('i_comments').value.replace(/[^#-:<-\[\]-~]/g, ' '))+'&vcr='+ge('vcr').value}; 
			$frm=frm;
			if(frm=='chk'){
				if(!act){
					var s=ge('reg_diff_chk').checked?'s':'';
					verify_address(false,s);			
				}else if(act=='verified'){
					qjax(0,pvar+xpdat,0,'&frm='+frm+'&org='+$org);
				}
			}else{
				qjax(0,pvar+xpdat,0,'&frm='+frm);
			}
		}
	}else if(act=='rsp'){ 
		if($frm=='cnf'){
			if(v.substring(0,2)=='id'){				
				var url="http://"+$hs+"i.php?pg=receipt&"+v;
				window.location=url;
			}else if(v=='err_1'){
				alerT("Your transaction could not be processed, possibly due to an incorrectly entered expiry date, credit card number or card type (MC/Visa). If you would like assistance, please contact us by email or telephone.",0,400,'OK');
			}else if(v.substring(0,8)=='cart_up!'){ // insufficient stock
				var msg='It appears you have made changes to your order on another tab. When you press OK, this page will reload with a revised cart.';
				alerT(msg,0,400,'OK',false,'page_reload()');
			}else if(v.substring(0,8)=='stock=0!'){ // insufficient stock
				v=v.substring(8,v.length);
				var msg='There was insuffcient stock to carry out your order as requested for the following items:<br><br>'+v+'<br><br>When you press OK, this page will reload with revised quantities.';
				alerT(msg,0,500,'OK',false,'page_reload()');
			}else{
				alerT("There was a problem saving your order, please contact us by phone at 1-800-332-9327"+v,0,0,'OK');		
			}
		}else{
			if(v==1){
				if($frm=='reg'){ //registered successfully
					if($pag=='ct'){
						window.location.href="http"+$s+"://"+$hs+"i.php?pg=shop&step=2";	
					}else{
						window.location.href="http"+$s+"://"+$hs+"i.php?pg=shop";
					}
				}else if ($frm=='chk'){  //checkout successful
					window.location.href="http"+$s+"://"+$hs+"i.php?pg=shop&step=2";					 
				}else if ($frm=='acc'){  //account update successful
					page_reload();
				}
			}else{ //error writing to db (send message back from ajax) or ...	
				if(v=='nolog'){return;}
				alerT(v);
			}
		}
	}
}
function ui_validate(v,frm){
	v=ui_clean(v);
	var ret='',badformat,dup,len;
	for(i=0;i<v.length;i++){
		if(v[i]){
			if(v[i].use==1){
				if(v[i].man && !v[i].val){ //check blank on mandatory
					ret+=v[i].lbl+' is a mandatory field<br>';
				}else{ //check formatting otherwise
					len=false;				
					if(v[i].min>0){ //check length
						len=v[i].val.length<v[i].min;
					}
					if(len){
						ret+=v[i].lbl+' must be at least '+v[i].min+' characters long.<br>';
					}else{ //regex validate
						badformat=false;
						switch(v[i].cat){
							case 't1':badformat=t1_validate(v[i].val);badformat=badformat?' may only contain the following characters: '+badformat:false;break;
							case 'uz':badformat=t1_validate(v[i].val);badformat=badformat?' may only contain the following characters: '+badformat:false;break;
							case 'zp':badformat=zip_validate(v[i].val);badformat=badformat?' is not of a valid format.':false;break;
							case 'a1':badformat=street_validate(v[i].val);badformat=badformat?' may only contain the following characters: '+badformat:false;break;
							case 'cy':badformat=city_validate(v[i].val);badformat=badformat?' may only contain the following characters: '+badformat:false;break;
							case 'ph':badformat=phone_validate(v[i].val)?' is not of a valid format.':false;break;
							case 'e1':badformat=email_validate(v[i].val)?' is not of a valid format.':false;break;
							case 'cc':badformat=cc_validate(v[i].val)?' is not valid.':false;break;
							case 'xd':badformat=cc_date_validate(v[i].val);break;
							case 'p1':badformat=pwd_validate(v[i].val)?' is not valid.<br> - <i>A valid password must have 6 to 12 characters and at least one letter and one number.</i>':false;break;
						}
						if(badformat){
							ret+=v[i].lbl+badformat+'<br>';
						}else{ //duplicate required
							dup=ge(v[i].id+'_dup');
							if(dup){
								ret+=(dup.firstChild.value!=v[i].val)?'<b>&#9658; Confirmation '+v[i].label+'</b> does not match original.<br>':'';
							}
						}
					}
				}
			}
		}else{
			//alert(i)
		}
	}
	return ret;
}
function ui_clean(v){
	var	rx,upper,lower;
	for(i=0;i<v.length;i++){
		if(v[i]){
			rx=false;upper=false;lower=false;
			switch(v[i].cat){
				case 't1':break;
				case 'uz':break;
				case 'zp':rx=/[^A-Za-z0-9]/g;upper=1;break;
				case 'a1':rx=/[^À-üa-zA-Z0-9 ,#\-'.]/g;upper=1;break;
				case 'cy':rx=/[^À-üa-zA-Z0-9 '.\-]/g;upper=1;break;
				case 'ph':rx=/[^0-9()-.]/g;break;
				case 'e1':rx=/[^a-zA-Z0-9@._%+\-]/g;lower=1;break;
				case 'cc':rx=/[^0-9]/g;break;
				case 'xd':break;
				case 'p1':break;
			}
			val=v[i].val;
			val=val.trim();
			if(rx){
				if(upper){val=val.toUpperCase();}else if(lower){val=val.toLowerCase();}
				val=val.replace(rx,'');
			}
			v[i].val=val;
			v[i].ctl.value=val;
		}
	}
	return v;
}
function t1_validate(tx){
	return tx.match(/^[a-zA-Z' \-]+$/)?false:' A to Z';
}
function uz_validate(tx){
	return tx.match(/^[a-zA-Z0-9' ]+$/)?false:' A to Z, 0 to 9';
}
function zip_validate(tx){
	return tx.toUpperCase().match(/(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$)/)?false:' A to Z, 0 to 9';
}
function street_validate(tx){
	return tx.match(/^[À-üa-zA-Z0-9 ,#\-'.]+$/)?false:' A to Z, 0 to 9 OR the symbols [ .,-#\' ]';
}
function city_validate(tx){
	return tx.match(/^[À-üa-zA-Z0-9 '.\-]+$/)?false:' A to Z, 0 to 9 OR the symbols [ .-\' ]';
}
function email_validate(email){
  return !email.toLowerCase().match(/\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}\b/);
}
function phone_validate(phone){
  return !phone.match(/^([\+][0-9]{1,3}([ \.\-])?)?([\(]{1}[0-9]{3}[\)])?([0-9A-Z \.\-]{1,32})((x|ext|extension)?[0-9]{1,4}?)$/);
}
function pwd_validate(pwd){
  return !pwd.match(/(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9!@#$%^&*]{6,12})$/);
}
function cc_validate(ccnum){
	//if(ccnum==1111111111111111){return false;}
	var type=ge('credit_card').value;
	if(!type){return false;}
	var rge='';
	if(type=='Visa'){      
    rge = /^4\d{3}-?\d{4}-?\d{4}-?\d{4}$/; // Visa: length 16, prefix 4, dashes optional.
  }else if(type =='MC') {
    rge = /^5[1-5]\d{2}-?\d{4}-?\d{4}-?\d{4}$/;// Mastercard: length 16, prefix 51-55, dashes optional.
  }else if(type =='AmEx'){      
    rge = /^3[4,7]\d{13}$/;// American Express: length 15, prefix 34 or 37.
  }
  ccnum=ccnum.split("-").join("");
	ccnum=ccnum.split(" ").join("");
	return !ccnum.match(rge); 

}
function cc_date_validate(date){	
	var ret=' is not valid.';
	if(date.length==4){
		ret=!date.match(/\(?[0-9]{4}\)?/);
	}
	if(!ret){
		var m=date.substring(0,2)*1;
		var y=date.substring(2,4)*1;
		if(y<$cc_y){
			ret=' past expiry.';
		}else if(y==$cc_y && m<$cc_m){
			ret=' past expiry.';
		}
	}
	return ret;
}
