
function verifyCoForm() {
	
				 if (document.form2.pass1.value != document.form2.pass2.value) {
				 		alert('Your passwords do not match.  Please re-type them.');
						return false;
				 }
				 if (document.form2.fname.value == '') {
				 		alert('Please enter your First Name.');
						document.form2.fname.focus();
						return false;
				 }
				 if (document.form2.lname.value == '') {
				 		alert('Please enter your Last Name.');
						document.form2.lname.focus();
						return false;
				 }
				 if (document.form2.email.value == '') {
				 		alert('Please enter your Email Address.');
						document.form2.email.focus();
						return false;
				 }
				 if(!validateEmail(document.form2.email)){
				 	return false;
				 				 	
				} 
				 		
				 	
				 if (document.form2.pass1.value == '') {
				 		alert('Please enter a Password.');
						document.form2.pass1.focus();
						return false;
				 }
				 document.form2.submit();
}
function validateEmail(vfld){
  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/
  var space=/\s+/
 
  if (!email.test(tfld)||tfld=='your@email.com') {
    alert ("ERROR: not a valid e-mail address");
    return false;
  }
  if(space.test(tfld)){
    alert ("Please Check your email for spaces");
    return false;
  }
  var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/
  if (!email2.test(tfld)) 
    alert("e-mail accepted, but it is an unusual e-mail address - please check if correct");
  
  return true;
};
function setAddr(addrfrm, iscardaddr) {

   var newaddress;
  /*
   var formnum
   if(document.form2)
      formnum=1; 
   else formnum=0;
     */
     var form2=document.getElementById('form2');
	if (form2 && form2.used_add.value){
	   document.getElementById('addnewaddress').style.display = "inline";
	   document.getElementById('deletethisaddress').style.display = "inline";
	   addrfrm.name.value = cust_name[form2.used_add.value];
		addrfrm.add1.value = cust_addr1[form2.used_add.value];
		addrfrm.add2.value = cust_addr2[form2.used_add.value];
		addrfrm.city.value = cust_city[form2.used_add.value];
      addrfrm.state.value = cust_state[form2.used_add.value].toUpperCase();
		addrfrm.zip.value = cust_zip[form2.used_add.value];
		addrfrm.nationid.value = cust_nationid[form2.used_add.value];
	   addrfrm.phone1.value = cust_phone1[form2.used_add.value];
      if(iscardaddr){
         addrfrm.cust_card_id.value = form2.used_add.value;
         addrfrm.cust_add_id.value = cust_add_id[form2.used_add.value];
      
      } else {
         addrfrm.cust_add_id.value = form2.used_add.value;
         addrfrm.phone2.value = cust_phone2[form2.used_add.value];
         addrfrm.phone3.value = cust_phone3[form2.used_add.value];
         if(showoffice(cust_res_ship[form2.used_add.value], addrfrm)){			   	  
            addrfrm.res_ship[1].checked=true;
            if(addrfrm.org.value)
               addrfrm.org.value = cust_org[form2.used_add.value];
         } else addrfrm.res_ship[0].checked=true;
      }
      
		showrow('province',addrfrm.province, addrfrm.nationid.value!=1,cust_province[form2.used_add.value]);
   	//fields that only depend on if military or not
   	//showrow('state',addrfrm.state, addrfrm.nationid.value==1 && !ismiladdr,cust_state[form2.used_add.value]);
		//showfield('milstate',addrfrm.milstate, ismiladdr,cust_state[form2.used_add.value]);
		document.getElementById('countrytext').innerHTML=cust_country[form2.used_add.value];
		
   }else { 
      
	   newaddress=true;
	   if(form2){
	   document.getElementById('addnewaddress').style.display = "none";
	   document.getElementById('deletethisaddress').style.display = "none";
	}

	   addrfrm.cust_add_id.value='new';
      addrfrm.city.value='';
      addrfrm.nationid.value=1;
		addrfrm.name.value = '';
		addrfrm.add1.value = '';
		addrfrm.add2.value = '';
		addrfrm.state.value='';
		addrfrm.zip.value = '';
		addrfrm.nationid.value=1;
		addrfrm.phone1.value = '';
      if(!iscardaddr){
	      addrfrm.res_ship[0].checked = true;
		   addrfrm.phone2.value = '';
		   addrfrm.phone3.value = ''; 
         document.getElementById('missingphone2').style.display='none'; 
		   document.getElementById('missingphone3').style.display='none';
		   showoffice(false, addrfrm);
      }
		
		showrow('province', addrfrm.province);
	   document.getElementById('missingcity').style.display='none';
      document.getElementById('missingmilcity').style.display='none';
	   document.getElementById('missingstate').style.display='none';
	   document.getElementById('missingname').style.display='none';
      document.getElementById('missingphone').style.display='none';
      document.getElementById('missingmessage').style.display='none';
      document.getElementById('missingadd1').style.display='none';
      document.getElementById('missingzip').style.display='none'; 
		document.getElementById('missingnationid').style.display='none';
		document.getElementById('missingphone1').style.display='none';
		  
	 } 
   
   if(iscardaddr)
      document.getElementById('nopobox').innerHTML="&nbsp;";
   else  
      document.getElementById('nopobox').innerHTML="(No PO Boxes)";
   showrow("state", null,addrfrm.nationid.value==1); 
   var ismiladdr=select_state(addrfrm);
   if(!newaddress)
      validateAddress(addrfrm);
}

function showoffice(office_ship, thisform){
   
   office_ship = typeof(office_ship) != 'undefined' ? office_ship : false; 
  
   if(office_ship==="N")
      office_ship=true;
   if(office_ship==="Y")
     office_ship=false;
     var custorg;
   if(office_ship){
      if(document.form2)
       custorg  = typeof(cust_org[document.form2.used_add.value]) != 'undefined' ? cust_org[document.form2.used_add.value] :''; 
       else custorg='';
      showrow('office', thisform.org, true, custorg);
      thisform.res_ship[1].checked=true;
   } else {
      showrow('office',thisform.org);
      thisform.res_ship[0].checked=true;
      
   }
   return office_ship;
}

function showrow(name, field, show,value, debug){
  
   if(show){
      document.getElementById(name+'row').style.display='block';
      
      if(field)
      field.value=value;
   } else {
      if(field)
      field.value='';
      document.getElementById(name+'row').style.display='none';
     
   }
  
}

function validateAddress(frm) { 
   
   //$(".missing").fadeOut(100);
   var nationid=frm.nationid.value;  
   var hasmissing=false;
   var hasinvalid=false;
   //trim() is in checkout.js
   frm.zip.value=trim(frm.zip.value);
   
   if(typeof(frm.fname)=='undefined'){
      if(showmissing('name', frm.name.value))
      hasmissing=true;
      
   }else {
      if(showmissing('fname', frm.fname.value))
      hasmissing=true;
      if(showmissing('lname', frm.lname.value))
      hasmissing=true;
}
   if(showmissing('add1',frm.add1.value))
   	hasmissing=true;
   if(frm.ismiladdr.value){	
      
   	myOption = -1;
   	for (i=frm.milcity.length-1; i > -1; i--) {
   		if (frm.milcity[i].checked) {
   			myOption = i;
   		}
   	}
   	
   	if(showmissing('milcity', myOption!=-1))
   	   hasmissing=true;
   
   	if(showmissing('state', frm.state.value))
   	   hasmissing=true;
   	
   } else {
   
      if(showmissing('city', frm.city.value))
      hasmissing=true;
      
      if(showmissing('nationid',nationid))
      hasmissing=true;
      
   	if(nationid == '1') {
   
         if(showmissing('state',frm.state.value))
   	      hasmissing=true;
   	   if(showmissing('zip',frm.zip.value)){
   	      hasmissing=true;
   	      showmissing('invalidzipcode',true);
   	   }  else 	if(!verifyzip(frm.zip.value)){
       	   hasinvalid=true;
       	   showmissing('invalidzipcode',null,'"'+frm.zip.value+'" is not a valid zip code!' );
       	} else {showmissing('invalidzipcode',true);}
      } 	   else showmissing('zip',true);
   }
   	var phonemessage=new Array();
   	var hasvalidphone=false;
      var phone1 =trim(frm.phone1.value); 
   	if(frm.phone1){        
         showmissing('phone1',true);
         if(phone1){
   	   if(!showmissing('phone1', validphone(phone1, nationid),'Not valid'))
   	      {hasvalidphone=true;}else {hasinvalid=true;}
   	   }
   	}
   	if(frm.phone2){
        var phone2 =trim(frm.phone2.value); 
         showmissing( 'phone2', true);
         if(phone2){
   	      if(!showmissing('phone2',validphone(phone2, nationid), 'Not Valid'))
   	         {hasvalidphone=true;}else {hasinvalid=true;}
   	      }
   	 }
       if(frm.phone3){
         var phone3 =trim(frm.phone3.value); 
         showmissing('phone3',true);
         if(phone3){
   	      if(!showmissing('phone3',validphone(phone3, nationid), 'Not Valid'))
   	         {hasvalidphone=true;}else {hasinvalid=true;}
   	      }
   	  }
      if(!hasvalidphone){
   	   phonemessage.unshift('Please submit at least 1 valid phone number');
   		hasmissing=true;
   	} 

   	if(frm.email){
         if(showmissing('email',frm.email.value))
            hasmissing=true;
         else if(emailmess=validemail(frm.email.value)){
            //showmissing('email',null,emailmess, true);
            showmissing('invalidemail',null,emailmess);
            hasinvalid=true;
         } else showmissing('invalidemail',true);

      }
      if(typeof(frm.pass1)!=='undefined'){
         var hasmissingpass;
         hasmissingpass=false;
         if(showmissing('pass1',frm.pass1.value))
            hasmissingpass=true;
         if(showmissing('pass2',frm.pass2.value))
            hasmissingpass=true;
         if(hasmissingpass){
            hasmissing=true;
            showmissing('invalidpass', true);
         } else if(showmissing('invalidpass', frm.pass1.value==frm.pass2.value, "Passwords do not match"))
            hasinvalid=true;
      

      }
   	showmissing('phone', !phonemessage.length,phonemessage.join('<br />',phonemessage), true);
   	 
   	/*
   	if(hasvalidphone && !phonemessage){
   	   document.getElementById('missingphone').innerHTML='';
   	   document.getElementById('missingphone').className='';
   	}
   	*/
  
   //alert('hasmissing:'+hasmissing);
   //alert('hasinvalid:'+hasinvalid);
   missingmessagearr=new Array();
   if(hasmissing)
      missingmessagearr.push('Some of your data is missing!');
   if(hasinvalid)
      missingmessagearr.push('Some of your data is not valid!');
      
   return !showmissing( 'message',!missingmessagearr.length, missingmessagearr.join('<br />',missingmessagearr), true);
   	
}

function showmissing(el, i, m, d, fm,db){

  // returns true if i is missing(or not true)
 //    alert(e+":"+display);
   oe=el;
   el='missing'+el; 
   
   if(db){ 
    alert('element:'+el+'\ninput value:'+i+'\ndisplay:'+d+'\nmessage:'+m);
   }
   if(i){	 
      if(fm)
      document.getElementById(el).style.display='none';
      else $("#"+el).fadeOut('normal');
   
      return false;
   } else {

     
      
   if(fm){
      if(d)var display='block';
         else var display='inline';
      document.getElementById(el).style.display=display;
   }else 
      $("#"+el).fadeIn('normal');
      
      m = typeof(m) != 'undefined' ? m : 'Missing';
      $("#"+el).html(m);
      
      return true;
   }
}

function submitShipping(){   
   var thisform;
   thisform=document.getElementById('form1');
   var thisform = typeof(thisform) != 'undefined' ? thisform : document.form1;
   if(validateAddress(thisform)){
      if (thisform.nationid.value != '1') 		   
		alert('We are now accepting international orders.  Orders shipping outside the U.S., with the exception of Canada, must be over $750.00 (US Dollars). We will email you with the shipping costs, for your confirmation. Please double check that your email address is correct.  The customer shall pay customs duties and taxes.  We do not have information regarding customs costs for your country.');
      thisform.submit();
   }
}
   
function validphone(phone, nationid){
   var phonepattern;
   if(nationid==1)
      phonepattern=/^[ ]*[(]{0,1}[ ]*[0-9]{3,3}[ ]*[)]{0,1}[-]{0,1}[ ]*[0-9]{3,3}[ ]*[-]{0,1}[ ]*[0-9]{4,4}[ ]*$/;
   else 
      phonepattern=/^((\+?\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/;
   return phonepattern.test(phone);
}
      
function coDelAddr() {
	var ask = confirm('Are you sure you want to remove this address from your list? (this cannot be undone)');
	if (ask) {
	   var form2;
	   form2=document.getElementById("form2");
	   form2.submit();
	   
		//var url = 'checkout2.php?delete_addr=' + document.form2.used_add.value;
	//document.location.href = url;
	}
}
function chDelCC() {
	 var ask = confirm('Are you sure you want to remove this Credit Card from your list? (this cannot be undone)');
	 if (ask) {
	   var frm=document.getElementById('form2');
	   frm.submit();
	 	//	var url = 'checkout4.php?delete_cc=' + document.form2.used_card.value;
	  	//document.location.href = url;
	 }
}

function setCard() {
/*
   showmissing('cardnumber', true);
   showmissing('cardexp', true);
   showmissing('zip',true);
*/


var billfrm=document.getElementById('billingform');
var form2=document.getElementById('form2');
   setAddr(billfrm, true);
   if(billfrm.cvvIsValid.value){
      document.getElementById('cvvrow').style.display='none';
   }
var isnewcard=false;
   if(form2) {
      
   	if(!form2.used_add.value){
   	   isnewcard=true;
   	   document.getElementById("cvvrow").style.display="none";
         document.getElementById('editcardnumberrow').style.display='none';
   		billfrm.editcard.checked=true;	
   		billfrm.cardno.className='setText2en'; 
   		billfrm.cardno.value='';
   		//enable('cardno');
   		//disable('editcard', 'editcardlabel');
   	   document.getElementById('countrytext').innerHTML="United States";
         billfrm.nationid.value=1;
   
   		billfrm.cust_card_id.value='new';
   		billfrm.cardtype.value = '';
   		billfrm.cardexp1.value = '';
   		billfrm.cardexp2.value = '';
   		document.getElementById('cardmess').innerHTML="Add a new card";
   		billfrm.cust_card_id.value = 'new';
   		//billfrm.cardno.readOnly = false;
   						  
   	} else {
   
   	   
   		disable('cardno');
   		
         //verifyBilling(billfrm);
   		//enable('editcard', 'editcardlabel');
         document.getElementById('editcardnumberrow').style.display='block';
   		billfrm.editcard.checked=false;	
   		billfrm.cardtype.value = cardtype[form2.used_add.value];
   		
   		billfrm.cardno.value = cardno[form2.used_add.value];
   		billfrm.cardexp1.value = cardexp1[form2.used_add.value];
   		billfrm.cardexp2.value = cardexp2[form2.used_add.value];
   		billfrm.cust_card_id.value = form2.used_add.value;
   		//document.getElementById('cardmess').innerHTML="Choose a Card";
   				CheckCardNumber(billfrm);
   		if(!showmissing('cardmessage',cardno[form2.used_add.value], "This credit card number is missing", true))
   	      showmissing('cardmessage',ccisvalid[form2.used_add.value], "This credit card number is not valid", true);
   	 
      	if(document.getElementById("cardHasErrors").value){
      	   enable('cardno');
      	   billfrm.editcard.checked=true;	
      	}		
   	}
		} else {
				// new account					
			}
			
			validatecvv(billfrm, isnewcard);
		}
		
function addnewcard(){

	document.getElementById("form2").used_add.selectedIndex = 0;
	setCard(); 
}

function onaddnewaddress(){
   var form2=document.getElementById("form2");
   if(form2)
	   document.getElementById("form2").used_add.selectedIndex = 0;
   setAddr(document.getElementById('form1'));
}

function Monify(value){
 var str = "" + Math.round(value * 100);
 var len = str.length;

 return (str=="0")?"":(str.substring(0,len-2)+"."+str.substring(len-2,len));

}


function popup(pageurl,wheight,wwidth,wname,wleft,wtop,resizable)
{	
	wheight = typeof(wheight) != 'undefined' ? wheight : 200;
	wwidth = typeof(wwidth) != 'undefined' ? wwidth : 370;
   wleft = typeof(wleft) != 'undefined' ? wleft : 40;
   wtop = typeof(wtop) != 'undefined' ? wtop : 262;
   wname = typeof(wname) != 'undefined' ? wname : 'popup';
   resizable = typeof(resizable) != 'undefined' ? resizable :1;
   params='width='+wwidth+',height='+wheight+',left = '+wleft+',top ='+wtop+',scrollbars=yes, resizable='+resizable;
	newwindow=window.open(pageurl,wname,params);
	if (window.focus) newwindow.focus();
	return false;
}

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

function boolHolder(bool) {
      this.bool = bool;
   }
function bool(bool){
   return new boolHolder(bool);
}
function validate_email(vfld, defaultemail, isdefaulterror, dvd){
   
   // dvd=dont validate default
   //if dvd is true, validation will allow either empty field or default email
   var tfld = trim(document.getElementById(vfld).value);  // value of field with whitespace trimmed off
   var isdefault;
   if(tfld==defaultemail) 
      isdefault=true;
   else isdefault=false;
   if(typeof(isdefaulterror)!='undefined'){
     
      if(!tfld || isdefault)
         isdefaulterror.bool=true;
      else isdefaulterror.bool=false;
   } 
   if(!dvd)
   if(showmissing(vfld, tfld&&tfld!=defaultemail, "Please enter a valid e-mail address!", true)) 
      return false;
  
   if(tfld){
      var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/;
      if(showmissing(vfld, email.test(tfld), "\""+tfld+"\" is not a valid e-mail address!", true)) 
      return false;
   

   var space=/\s+/;
   if(showmissing(vfld, !space.test(tfld), "Please check this email address for spaces",true))
      return false;
  
   var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/;
   if(showmissing(vfld,email2.test(tfld), tfld+ "is accepted, but it is an unusual e-mail address - please check if correct",true))
      return true;
   }
   
  return true;
   
}
function validate_emails( emailinput){
   var frm=document.getElementById(emailinput).form;
   var allvalid=true;
   var isvalid;
   var isdefault;
   var numdefaults=0;
   var numberElements =  frm.elements.length;
   
   var isdefaulterror=bool(false);
   var debug='';
   for(var i = 0; i < numberElements; i++)  {
      debug=''
      if(frm.elements[i].id==emailinput)continue;
      isvalid=validate_email( frm.elements[i].id, 'freind@email.com', isdefaulterror, true);
      
      isdefault=isdefaulterror.bool;
      if(isdefault)numdefaults++;
      if(!isvalid && !isdefault)allvalid=false;
     
      debug+='allvalid:'+allvalid+'\n';
     
   }
   //debug+='numdefaults:'+numdefaults+'\n';
   //debug+='numberElements'+numberElements+'\n';
  //alert(debug);
  showmissing('emails', numdefaults!=numberElements-1, "Please add email addresses to recieve our specials!");
   if(allvalid&& numdefaults!=numberElements-1)
      frm.submit();
}
function validemail(vfld, defaultemail){

   var tfld = trim(vfld);  // value of field with whitespace trimmed off
   var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/;
   var space=/\s+/;
 
   if (!email.test(tfld)||email==defaultemail) {
     return "\""+tfld+"\" is not a valid e-mail address!";
     // return "Not Valid";
   }
   if(space.test(tfld)){
      return "Please Check "+tfld+" for spaces";
  }
  /*
  var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/;
  if (!email2.test(tfld)) 
    return tfld+ " is accepted, but it is an unusual e-mail address - please check if correct";
   */
}
function disable(fieldname, label, fieldvalue){
   var field=document.getElementById(fieldname);
	field.disabled=true;
	if(fieldvalue)
		field.value = fieldvalue;
	else field.value='';
	field.className='setText2';
	if(label)
	document.getElementById(label).style.visibility = "hidden";
	
	
}

function enable(fieldid ,label,fieldvalue){
	
	document.getElementById(fieldid).className='setText2en';
	if(fieldvalue)
		document.getElementById(fieldid).value = fieldvalue;
	
	
	document.getElementById(fieldid).disabled=false; 
	//document.getElementById(fieldid).focus();
	//if(label)
	//document.getElementById(label).style.visibility = "visible";
	
}

function editcardno(frm){
   
  // document.getElementById('missingcardmessage').innerHTML="";
  //document.getElementById('missingcardmessagerow').style.display="none";
	if(frm.editcard.checked){
		enable('cardno');
		frm.cardno.value='';
		frm.cardno.focus();
		// showmissing('cardnumber',true);
		
	}
	else {
	   form2=document.getElementById("form2");
      disable('cardno', null, cardno[form2.used_add.value]);
		frm.cardtype.value = cardtype[form2.used_add.value];
      showmissing('cardnumber',frm.cardno.value);
      showmissing('cardtype', frm.cardtype.value);
   }
   validatecvv(frm);
}

function selectDate(theelement){
   CheckCardNumber(theelement.form, 'date');
}

function select_state(thisform){ 
   
   if(thisform.state.value=="AA" || thisform.state.value=="AE"||thisform.state.value=="AP"){
      thisform.ismiladdr.value=true;
      if(thisform.city.value=="APO"){
         thisform.milcity[0].checked=true;
      	thisform.milcity[1].checked=false;
      } else if(thisform.city.value=="FPO"){
         thisform.milcity[0].checked=false;
      	thisform.milcity[1].checked=true;
      } else { 
         thisform.milcity[0].checked=false;
      	thisform.milcity[1].checked=false;
      }
      
      
      
showmissing('invalidzipcode',true);
      document.getElementById('cityrow').style.display='none'; 
      document.getElementById('milcityrow').style.display="block";
      document.getElementById('countryrow').style.display="none"; 
         
   }else {
      thisform.ismiladdr.value='';
     

      if(thisform.city.value=="FPO"||thisform.city.value=="APO"){
         thisform.city.value="";
      }
       thisform.milcity[0].checked=false;
      	thisform.milcity[1].checked=false;
      document.getElementById('cityrow').style.display="block"; 
      document.getElementById('milcityrow').style.display="none"; 
      document.getElementById('countryrow').style.display="block"; 

   if(thisform.custaddrform.value=='shipping'){

      document.getElementById('isofficerow').style.display="block";
      //document.getElementById('officerow').style.display="block";
   }
     
   } 
   /* this is bogus
   if(!thisform.state.value)
      thisform.nationid.value=1;
      */
//validateShipping(ismiladdr, iscardaddr);
   return thisform.ismiladdr.value;
}



function preload() { //v3.0
 var d=document; if(d.images){ 
   if(!d.MM_p) d.MM_p=new Array();
   var i,j=d.MM_p.length,a=preload.arguments; 
   for(i=0; i<a.length; i++){
      if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
   }
}

function verifyzip(zip){
	var tfld = trim(zip); 
	var zipcodepattern=/(^\d{5}$)|(^\d{5}-\d{4}$)/;
	if (!zipcodepattern.test(tfld)) {
		return false;
	}
	return true;	
}

function verifycatalog(){
	if (!document.form1.name.value) {
		alert('Please enter your First Name.');
		document.form1.name.focus();
		return false;
	}
	if (!document.form1.snail_address.value) {
		alert('Please enter your Address.');
		document.form1.snail_address.focus();
		return false;
	}
	if (!document.form1.city.value) {
		alert('Please enter your City.');
		document.form1.city.focus();
		return false;
	}
	if (!document.form1.state.value) {
		alert('Please enter your State.');
		document.form1.state.focus();
		return false;
	}
	if (!document.form1.zip.value) {
		alert('Please enter your Zip Code.');
		document.form1.snail_address.focus();
		return false;
	}
	
	if(!verifyzip(document.form1.zip.value)){
	   alert('Zip Code is not valid.');
    		return false;
  		}
  		
	document.form1.submit();
}

function saveValue(theelement){
   theelement.origValue=theelement.value;
}

function onchangeqty(theelement, itemid, limitamt){ 
   if(validnum(theelement, limitamt)){
      totalCart(1, null);
      // settotalcart('button_'+itemid, true, itemid);
      setAddToCart(itemid, theelement.value);
   }
   //setTimeout(" sendData('addtocart',null,null, "+itemid+")", 3000);
   if(parseInt(theelement.value))
      theelement.focus();
}

function setAddToCart(itemid, theqty){
   var cartform=document.getElementById('cartform');
   if(!document.getElementById('addtocart_'+itemid))
      return; 
   if(typeof(cartform.isupdated)=='undefined' ||!cartform.isupdated.value){
      //togglediv(buttonid+"adding");
      setTimeout("setAddToCart('"+itemid+"','"+theqty+"');", 150);
   } else { 
      var formaction=new Array;
    
   if(theqty)
      formaction[0]='qty_choice=1';
   if(document.getElementById('form_'+itemid).email_special_id.value)
    formaction[1]="email_special_id="+document.getElementById('form_'+itemid).email_special_id.value;
    sendData('addtocart',null,formaction.join("&"), itemid);
   
   
   
}
}

function validnum(theelement, limitamt){
   theelement.value=trim(theelement.value);
   if(theelement.value==='')
      return false;
   else if(isNaN(theelement.value)){
     
      theelement.value=theelement.origValue;
      return false;
   } 
   if(limitamt){
      if(theelement.value > limitamt)
      theelement.value=limitamt;
   }
   return true;
}

function emptyfield(inputid, origvalue){
   document.getElementById(inputid).style.color='black';
   if(document.getElementById(inputid).value==origvalue)
      document.getElementById(inputid).value=''; 
   document.getElementById(inputid).focus();
}

function registerform1(e)
{ 
	if (!e) e = window.event;
	if(e['keyCode']==13) 
	verifyCoForm2()
}

function registerform2(e)
{ 
	if (!e) e = window.event;
	if(e['keyCode']==13) 
	verifyCoForm()

}

function registerfields(){
   
   document.forms['retlogin'].pass.onkeydown=registerform1;	
   document.forms['retlogin'].cust_email.onkeydown=registerform1;	
   document.forms['newlogin'].fname.onkeydown=registerform2;
   document.forms['newlogin'].lname.onkeydown=registerform2;
   document.forms['newlogin'].email.onkeydown=registerform2;
   document.forms['newlogin'].pass1.onkeydown=registerform2;
   document.forms['newlogin'].pass2.onkeydown=registerform2;
}
function showcssmenu(remove){
   if(remove){
      document.getElementById('cssdropmenuhidden').style.display='none';
      document.getElementById('removecsslinkhidden').style.display="none";
      document.getElementById('showcsslink').style.display="inline";
   }else {
      
      document.getElementById('cssdropmenuhidden').style.display='block';
      document.getElementById('removecsslinkhidden').style.display="inline";
      document.getElementById('showcsslink').style.display="none";
   }
}

function additem(inputid, buttonid){
   
   var hasbutton;
   if(typeof(buttonid)=='undefined')
   // for some reason booleans dont work 
   hasbutton="falsestring"; else 
   hasbutton="truestring";
   var noslider=document.getElementById("noslider").value;
   var theelement=document.getElementById(inputid);
   
   var frm=theelement.form;
   
   var emspecid=frm.email_special_id.value;
   var formdata;
  if(emspecid){
      formdata="email_special_id="+emspecid;
   } 
   var qtytoadd=parseInt(frm.qty_to_add.value);
   var itemid=frm.itemid.value;
   if(typeof(frm.qty_choice)!='undefined' && document.getElementById('qty_choice_3').checked){
      document.getElementById('addtocart_'+itemid).innerHTML='';
      sendData('addtocart', null,'qty_choice=1',itemid);
      document.getElementById('addtocart_'+itemid).style.width='110px';
      if(document.getElementById('midcol_'+itemid))
         document.getElementById('midcol_'+itemid).style.width='26em';
      return;
   } 

   // most cartform elements may not exist yet!
   var cartform;
   cartform=document.getElementById('cartform');
   if(typeof(cartform.isupdated)!='undefined')
     cartform.isupdated.value='';
   if(!qtytoadd)
      return;

   if((frm.availid.value<3) &&(qtytoadd > frm.avail.value) && frm.origavailid.value>2){
      // we need backorders to fill this order, give customers choice
      sendData('addtocart', frm, 'jsline=816', itemid);
      document.getElementById('addtocart_'+itemid).innerHTML="<div class='loader'><img src='/images/ajax-loader-red-big.gif' height='66' width='66'></div>";
      document.getElementById('addtocart_'+itemid).style.width='18em';
      if(document.getElementById('midcol_'+itemid))
      document.getElementById('midcol_'+itemid).style.width='18em';
      return;
   } 
   if(!noslider && hasbutton=='truestring'){
      document.getElementById('toggle').style.visibility='visible';
      document.getElementById('checkout').style.visibility='visible';
      document.getElementById('slidewrapper').style.visibility='visible';
      toggleCart(); toggleCart(3000);
   } 
   sendData('shoppingcart', frm, "noslider="+noslider);
   document.getElementById('addtocart_'+itemid).style.width='110px';
   document.getElementById('addtocart_'+itemid).innerHTML="<div class='loader'>Adding to your cart...<br/><img src='/images/ajax-loader-green.gif' height='35' width='35'></div>";
     if(document.getElementById('midcol_'+itemid))
   document.getElementById('midcol_'+itemid).style.width='26em';
   /*
   if(noslider){
     updatetotals(buttonid);
   } else settotalcart(buttonid, hasbutton, itemid, emspecid);
   */
      settotalcart(buttonid, hasbutton, itemid, emspecid);
}

function updatetotals(buttonid){

   var cartform=document.getElementById("cartform");
   
   // if ajax reload just happened, cart may not exist
   if(typeof(cartform.isupdated)=='undefined' ||!cartform.isupdated.value){
      setTimeout("updatetotals('"+buttonid+"');", 150);
   } else { 

      var qty = cartform.qty;
      var qtytotal=0;    
      if (qty[1]){ 
         for (var i=0; i<qty.length; i++) {
            qtytotal+=parseInt(qty[i].value);
         } 
      } else qtytotal=parseInt(qty.value);
      var the_es='';     
      if(qtytotal!=1)
         the_es='s';
      //setTimeout("alert('isupdated2:'+cartform.isupdated.value)", 1000);
      document.getElementById('numitems').innerHTML=qtytotal+" item"+the_es;
      document.getElementById('totalcost').innerHTML="Total Cost:"+document.getElementById('total').innerHTML;
      
       document.getElementById("wrapper_"+buttonid).innerHTML=document.getElementById("wrapper_"+buttonid).origButton;
      document.getElementById(buttonid).value='Add Again';

   }
}

function settotalcart(buttonid, hasbutton, itemid, emspecid){
   
   var formdata;
   formdata='';
   if(emspecid){
      formdata="email_special_id="+emspecid;
   } 
   if(formdata)
      formdata+="&";
   formdata+="jsline=887";
   var cartform;
   cartform=document.getElementById('cartform');
   if(typeof(cartform.isupdated)=='undefined' ||!cartform.isupdated.value){
      //togglediv(buttonid+"adding");
      setTimeout("settotalcart('"+buttonid+"','"+hasbutton+"','"+itemid+"','"+emspecid+"');", 150);
   } else { 
      // dont bother passing the form, 
      // it has been temporarily replaced by the loader gif
      
      sendData('addtocart',null,formdata, itemid);
      totalCart('', 1);
   }
}

function isoldie(versionlimit){
   if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
         var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
      if (ieversion <= versionlimit)
      return true;
   }
}

function onchangeshipping(frm){
/*
  if(frm.stateselect.value=='NY'){
      toggleCart();toggleCart(1000);
   }
   */
  sendData('shoppingcart', frm, 'wantfaster=1');
  setTimeout("totalCart('', 1);", 1000);
}

function validatesearch(theform){
   var searchstr=theform.cigarname.value;
   if(searchstr.length<2||searchstr=="Search Keywords..."){
      document.getElementById('searchfeedback').innerHTML="Please add a search term that has at least 2 letters";
      return false;
   }
}

function resetadv(theelement, theform, dontsend){
   var frm;
   if(theform)
      frm=theform;
   else frm = theelement.form;
   var numberElements =  frm.elements.length;
   for(var i = 0; i < numberElements; i++)  {
       var el=frm.elements[i];
       if(el.type=="select-one")
      el.selectedIndex=0;
   }
   frm.search.value='';
   onadvsearch(null,null,frm, dontsend);
}

function onadvsearch(theelement, goback, theform, dontsend){
   document.getElementById('numresults').innerHTML='<form action="numresults.php" method="post" id="numresultsform"><div><input name="isdone" type="hidden" id="isdone" /></div></form>'+"<img src='/images/ajax-loader-circle.gif' width='100' height='100'>";
   if(theelement)
      var frm = theelement.form;
   else if(theform)
   frm=theform
   var numberElements =  frm.elements.length;
   
   //set selected and unselected classes for menus and menu items
   for(var i = 0; i < numberElements; i++)  {
      var el=frm.elements[i];
      if(el.type=="select-one"){
         if(el.selectedIndex) 
            el.className='ddselect';
         else el.className='ddunselect';
         
         var numberOptions=el.options.length;
         for(var j=0; j<numberOptions; j++){
            if(j==el.selectedIndex)
               el.options[j].className='ddselecto';
            else 
               el.options[j].className='ddunselecto'
         }
      }
   }
   
   //document.getElementById('numresults').innerHTML="";
   if(!dontsend){
      document.getElementById('numresults').style.display='block';
      sendData('numresults', frm, 'isnumresults=1');
   }
}



/*
function togglecellborders(tableid, show) {

if(!document.getElementById('carttablenb'))return;

    var stl;
    if (show) stl = '1px solid #B3CEF2'
    else         stl = '0';

    var tbl  = document.getElementById(tableid);
    var rows = tbl.getElementsByTagName('tr');

    for (var row=0; row<rows.length;row++) {
      if(rows[row].className=="toprow")continue;
      var cells = rows[row].getElementsByTagName('td');
      
      for (var cellno=0; cellno<cells.length;cellno++) {

         var cell = cells[cellno].getElementsByTagName('td');
         if(cells[cellno].className !="titlecol" && cells[cellno].id!="cartmessage")
         cells[cellno].style.border=stl;
      
      }
    }
  }
  */
function submitForm(theinput){
   if(theinput.value)
   theinput.form.submit();
}


function showHide(shows, hides, isinline){
   if(isinline)display='inline'; 
      else display='block';
   if(shows){
      shows=mkArray(shows);
      var slen=shows.length;
      for (var i = 0; i < slen; i++){
         document.getElementById(shows[i]).style.display=display;
      }
   }
   if(hides){
      hides=mkArray(hides);
      var hlen=hides.length;
      for (var i = 0; i < hlen; i++)
      document.getElementById(hides[i]).style.display="none";
   }
}


function mkArray(obj){ 
   if(isArray(obj))
      return obj;
   else 
      return [obj];
}

function isArray(obj) {
   if (obj.constructor.toString().indexOf("Array") == -1)
      return false;
   else
      return true;
}

function submitOrder(justValidate){
   var frm=document.getElementById('form2');
   var today=new Date();
   var mess;
   var missing=justValidate;
   var year_diff = today.getFullYear() - frm.DOBy.value;
   var month_diff = today.getMonth()+1 - frm.DOBm.value;
   var day_diff =today.getDate()  - frm.DOBd.value; 
    document.getElementById("DOBarea").style.background="";
    document.getElementById("DOBddarea").style.background="";
   if (month_diff < 0) 
      year_diff--;
   else if ((month_diff===0) && (day_diff < 0)) 
      year_diff--;
   if(showmissing("DOB", year_diff>18, "You must be 19 years of age or older to place your order. Please update your date of birth. ", true))
   {
      document.getElementById("DOBddarea").style.background="#E4D8B2";
     // document.getElementById("DOBarea").style.background="#E4D8B2";
      missing=true;
   }
   if(showmissing('DOBcheckbox', frm.DOBcheckbox.checked, "You must check the above box to place your order.", true)){
      document.getElementById("DOBarea").style.background="#E4D8B2";
   missing=true;
}
   if(!missing)frm.submit();
   
   
}

function showform(frm){
   var numel =  frm.elements.length;
   var formtext='';
   formtext+="Number of Elements:"+numel;
   for(var i = 0; i < numel; i++)  {
      formtext+="name:"+frm.elements[i].name+" -- value:"+frm.elements[i].value+"\n";
      
   }
   alert(formtext);
   
   
}




function Monifyif(num){
	if(num>0)
		return "$"+Monify(num);
	return '$0.00';	
}
var globalupdateurl;
function totalCart(changeqty, dontresend) {
   var cartform=document.getElementById('cartform');
   if(cartform.isempty.value)
      return;
   changeqty=typeof(changeqty) == 'undefined' ? '':1; 
	var isUS=cartform.isUS.value;
	var freeshipqualify=cartform.freeshipqualify.value;
	
	var freeshiplimit=cartform.freeshiplimit.value;
	var haskeycode=cartform.haskeycode;
	var isheavy=cartform.isheavy;
   var qty = cartform.qty;
   var isttax=cartform.isttax;
   var unit = cartform.unit;
   var isfreeship = cartform.isfreeship;
   var parentcartitemid=cartform.parentcartitemid;
   var cataddamt=cartform.cataddamt;
   var id = cartform.id;
   var sub = cartform.sub;
   var assy_total = cartform.assy_total;
   var istob_tax=cartform.istob_tax;
   var url2 = "";
   var total = 0;
   var subtotal = '';
   var qtyTotal = 0;
   var assyTotal=0;
   var freeshiptotal=0;
   var ship = 0;
   var tob_tax=0;
   var sales_tax=0;
   var ishasheavy=false;
   var isbizship=cartform.isbizship.value;
   var plusship='';
   var db='';
   var numitems=0;
   var the_es="s";
   //for debugging
   var before='';
   var after='';
   if (qty[1]){ 
      for (var i=0; i<qty.length; i++) {
         
         
         /*
       db+="id:"+id[i].value+"\n";
       db+='parentcartitemid:'+parentcartitemid[i].value+"\n";
       db+='cataddamt:'+cataddamt[i].value+"\n";
       db+="\n";
       */
       /*
       if(i==3){
         
         for (var j=0; j<qty.length; j++) {
            before+=qty[j].value+" ";
         }
         alert("before:"+before);
      }
       */
      if(parentcartitemid[i].value>-1){
         document.getElementById('input_'+id[i].value).value=qty[parentcartitemid[i].value].value*cataddamt[i].value; 
         //alert(document.getElementById('input_'+id[i].value).value);
      }
      /*
      if(i==3){
         for (var j=0; j<qty.length; j++) {
         after+=qty[j].value+" ";
         }
         alert("after:"+after);
      }
      */
      /*
      if(haskeycode[i].value && qty[i].value>1)
         qty[i].value=1;
      */
           
			qty[i].value = parseInt(qty[i].value,10);
			
			
			
			
         if(url2 != "")url2=url2+"&";
           url2 = url2 + "id[" + id[i].value + "]=" + qty[i].value;
         
         numitems+=parseInt(qty[i].value);
         subtotal = parseFloat(qty[i].value) * parseFloat(unit[i].value);
         if(isfreeship[i].value)freeshiptotal+=subtotal;
         if(isheavy[i].value && (qty[i].value>0)) 
            ishasheavy=true;
         if(isttax[i].value=='t')
            tob_tax+=subtotal*cartform.tob_tax_percentage.value;
         if(subtotal)
            sub[i].value = "$" + Monify(subtotal);
         else sub[i].value="$0.00";
         total = total + subtotal;
         qtyTotal = qtyTotal + parseInt(qty[i].value,10);
         
         
         
         
         //alert('isshipcharge:'+isshipcharge[i].value);
        if(parentcartitemid[i].value==-1){
         if(assy_total[i].value>0){
      		assyTotal = assyTotal + parseInt(assy_total[i].value*qty[i].value,10);
      	} else {
         	assyTotal=assyTotal + parseInt(qty[i].value);
         }
     
         
         } 
         
         
         }
        
         //alert(db);
	} else {
      if(haskeycode.value && qty.value>1)
         qty.value=1;
   	//qty.value = 0;
   	if(assy_total.value>0)
      	assyTotal = assyTotal + parseInt(assy_total.value*qty.value,10);
   	else assyTotal=assyTotal + parseInt(qty.value);
  	   qty.value = parseInt(qty.value,10);
      url2 = "id[" + id.value + "]=" + qty.value;
       numitems=qty.value;
      subtotal = parseFloat(qty.value) * parseFloat(unit.value);
      if(isfreeship.value)
         freeshiptotal+=subtotal;
      if(isheavy.value &&(qty.value>0))
         ishasheavy=true;
      sub.value = Monifyif(subtotal);
      if(isttax.value=='t')
         tob_tax+=subtotal*cartform.tob_tax_percentage.value;
      total = total + subtotal;
      qtyTotal = parseInt(qty.value,10);
	}
	
   if (qtyTotal == 1 && assyTotal==1) {
   	if (parseFloat(subtotal) >= parseFloat(cartform.bong_limit.value)) {
     	   ship = Monify(parseFloat(cartform.ship_base.value));
      } else {
   	   ship = Monify((parseFloat(cartform.ship_base.value)) + (parseFloat(cartform.bong.value)));
   	   //cartform.save.value = '(Find out how to save $5.00 on Shipping)';
   	   
   	   //ship = Monify(((assyTotal - 1) * (parseFloat(cartform.ship_add.value))) + (parseFloat(cartform.ship_base.value)));
      }
   } else {
      
	   if (qtyTotal == 0 ) {
	   
		   ship = '0';
	   } else { 
		   ship = ((assyTotal - 1) * (parseFloat(cartform.ship_add.value))) + (parseFloat(cartform.ship_base.value));
		   if(ship)
		      ship=ship;
		   
	   }
	   //cartform.save.value = '';
   }

   cartform.totqty.value = qtyTotal;
   /*
   alert('freeshipqualify:'+freeshipqualify);
   alert('freeshiptotal:'+freeshiptotal);
   alert('freeshiplimit:'+freeshiplimit);
   */
   
   if(freeshipqualify &&freeshiptotal>freeshiplimit)
      ship=0;
   if(isUS){   
      if(ishasheavy||isbizship){
         ship=0; 
         document.getElementById('shipping').innerHTML="Determined by Weight<br/><a href=\"/faq.php#weight\" class='small'>more info</a>";
         document.getElementById('shipping').className="red right";
      } else {
         document.getElementById('shipping').innerHTML= Monifyif(ship);
         document.getElementById('shipping').className="right";
      }
   }
   
   sales_tax=cartform.state_tax.value*(parseFloat(total) + parseFloat(ship)+tob_tax);
   if(isUS)
      finalTotal = total + sales_tax + tob_tax + parseFloat(ship);
   else finalTotal = total;
   if(ishasheavy||isbizship)
      plusship="<br />plus shipping";
   globalupdateurl="/catalog/shopcart.php?"+url2;
            document.getElementById('updateurl').value="?"+url2;
   document.getElementById('items_total').innerHTML= Monifyif(total);
	if(cartform.tob_tax_percentage.value>0){
      document.getElementById('tob_tax').innerHTML= Monifyif(tob_tax);
      document.getElementById('sales_tax').innerHTML= Monifyif(sales_tax);
   }
   if(numitems==1)
   the_es='';
   
   if(numitems==0){
      if(!cartform.noslider.value){
         
	      setTimeout("toggleCart();document.getElementById('toggle').style.visibility='hidden'; document.getElementById('checkout').style.visibility='hidden'", 1500); 
     }
   }
   
   document.getElementById('total_items').value=numitems;
   document.getElementById('total').innerHTML= Monifyif(finalTotal)+plusship;
   document.getElementById('totalcost').innerHTML= "Total Cost:"+Monifyif(finalTotal)+plusship;
   document.getElementById('numitems').innerHTML= numitems + " item"+the_es;
   cartform.isupdated.value='';
  
   if(!dontresend)
   sendData('shoppingcart', cartform, 'changeqty='+changeqty);  
  
   //setTimeout("ScaleToFit('shoppingcart')",300);
   //alert(globalupdateurl);
   
   
   
}
function verifyCoForm2() {
   
				 if (document.form1.cust_email.value == '') {
				 		alert('You must enter your email address to continue');
						return false;
				 }
				 if (document.form1.pass.value == '') {
				 		alert('You must enter your password to continue');
						return false;
				 }
				 document.form1.submit();
}

function explode( delimiter, string, limit ) {
       var emptyArray = { 0: '' };
    
    // third argument is not required
    if ( arguments.length < 2 ||
        typeof arguments[0] == 'undefined' ||
        typeof arguments[1] == 'undefined' )
    {
        return null;
    }
 
    if ( delimiter === '' ||
        delimiter === false ||
        delimiter === null )
    {
        return false;
    }
 
    if ( typeof delimiter == 'function' ||
        typeof delimiter == 'object' ||
        typeof string == 'function' ||
        typeof string == 'object' )
    {
        return emptyArray;
    }
 
    if ( delimiter === true ) {
        delimiter = '1';
    }
    
    if (!limit) {
        return string.toString().split(delimiter.toString());
    } else {
        // support for limit argument
        var splitted = string.toString().split(delimiter.toString());
        var partA = splitted.splice(0, limit - 1);
        var partB = splitted.join(delimiter.toString());
        partA.push(partB);
        return partA;
    }
}

function checkcontactdata(){
   
   havedata=true; 
   if(document.form1.name.value)
   document.getElementById('namewarning').style.display = 'none';
   else {
      document.getElementById('namewarning').style.display = 'block';
      havedata=false;
   }
   if(document.form1.submit_by.value){
      document.getElementById('emailwarning').style.display = 'none';
      if(!validateEmail(document.form1.submit_by))
      havedata=false;
   } else {
      document.getElementById('emailwarning').style.display = 'block';
   
      havedata=false;
   }
   if(havedata)
  document.form1.submit();
}
function toggledisplay(elementid, display){
   display = typeof(display) == 'undefined' ? 'block' : display; 
   var cdis=document.getElementById(elementid).style.display;

   if(!cdis)cdis='none';//yes its counterintuitive because no display usually means the default such as 'block' but getelementbyid does not detect 'none'
   var newdis;
   if(cdis==display)
      newdis='none';
   else newdis=display;
   document.getElementById(elementid).style.display=newdis;
}

function validateinfo(){
	
	if (document.form1.fname.value == '') {
		alert('Please enter your First Name.');
		document.form1.fname.focus();
		return false;
	}
	if (document.form1.lname.value == '') {
		alert('Please enter your Last Name.');
		document.form1.lname.focus();
		return false;
	}
	if (document.form1.email.value == '') {
		alert('Please enter your Email Address.');
		document.form1.email.focus();
		return false;
	}
	if(!validateEmail(document.form1.email)){
		document.form1.email.focus();
		return false;
	}
	document.form1.submit();
}

function isNumeric(strString)
   //  check for valid numeric strings	
   {
   var strValidChars = "0123456789.-";
   var strChar;
   var blnResult = true;

   if (strString.length == 0) return false;

   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         }
      }
   return blnResult;
   }
