function Dataset(the_form){
	this.messages = new Array;
	this.form_name = the_form.name;

	var inputs = the_form.getElementsByTagName('input');

	for(var i = 0; i < inputs.length; i++){ //get all but country (it's a select)
		switch(inputs[i].name){
			case 'firstname':
				this.firstname = inputs[i].value;
				break;
			case 'lastname':
				this.lastname = inputs[i].value;
				break;
			case 'street_address':
				this.street_address = inputs[i].value;
				break;
			case 'city':
				this.city = inputs[i].value;
				break;
			case 'state':
				this.state = inputs[i].value;
				break;
			case 'postcode':
				this.postcode = inputs[i].value;
				break;
			case 'country':
			  //nb - this is only for the hidden input on the account_edit form
				this.country_id = inputs[i].value;
			case 'email_address':
				this.email_address = inputs[i].value;
				break;
			case 'telephone':
				this.telephone = inputs[i].value;
				break;
			case 'taxid':
				this.taxid = inputs[i].value;
				break;
			case 'password':
				this.password = inputs[i].value;
				break;
			case 'confirmation':
				this.confirmation = inputs[i].value;
				break;
			case 'email':
				this.email = inputs[i].value;
				break;
		}
	}

	var selects = the_form.getElementsByTagName('select');
	for(i = 0; i < selects.length; i++){ //get country
		if(selects[i].name == "country"){
			this.country_id = selects[i].value;
		}
	}
}

Dataset.prototype = {
	/**
	* Validates the name field in a form. Returns true if the length is larger than 1
	* @return boolean
	*/
	validateName:function(){
		if(!(this.firstname==undefined) && this.firstname.length < 1){// && this.firstname.length > 60){
			return false;
			//this.messages.push("Your First Name must contain at least one character.");
		}
		else{
			return true;
		}
	},
	
	
	/**
	* Validates the name field in a form. Returns true if the length is larger than 1
	* @return boolean
	*/
	validateLastName:function(){
		if(!(this.lastname==undefined) && this.lastname.length < 1){// && this.lastname.length > 60){
			return false;
			//this.messages.push("Your Last	Name must contain at least one character.");
		}
		else{
			return true;
		}
	},
	
	

	/**
	* Validates the street address field in a form. Returns true if the length is larger than 5
	* @return boolean
	*/
	validateStreetAddress:function(){
		if(this.street_address!=undefined && this.street_address.length < 5){// && this.street_address.length > 64){
			return false;
			//this.messages.push("Your Street Address must contain a minimum of 5 characters.");
		}
		else{
			return true;
		}
	},

	/**
	* Validates the city field in a form. Returns true if the length is larger than 3
	* @return boolean
	*/
	validateCity:function(){
		if(!(this.city==undefined) && this.city.length < 3){// && this.city.length > 50){
			return false;
			//this.messages.push(this.messages.push("Your City must contain a minimum of 3 characters.");
		}
		else{
			return true;
		}
	},

	/**
	* Updates the value of the country to the one that is currently selected. 
	* Intended for the pulldown.
	*/
	setCountryId:function(){
		this.country_id = document.getElementById("country").value;
	},
	
	/**
	* Shows the state dropdown menu or empty text field.
	*/
	showState:function(){
		var us_states_element;
		var canada_states_element;
		var spain_states_element;
		var other_states_element;
		var state_li_element;
	
		if (this.country_id == ""){
			document.getElementById("us_states").style.display="none";
			document.getElementById("canada_states").style.display="none";
			document.getElementById("spain_states").style.display="none";
			document.getElementById("state_li").style.display="none";
			document.getElementById("other_states").style.display="none";
			document.getElementById("postcode_wrapper").style.display="block";
			
		} else if(this.country_id == '166'){
			document.getElementById("us_states").style.display="inline";
			document.getElementById("state_li").style.display="inline";
		    document.getElementById("canada_states").style.display="none";
			document.getElementById("spain_states").style.display="none";
			document.getElementById("other_states").style.display="none";
			document.getElementById("postcode_wrapper").style.display="block";
			
			document.getElementById("us_states").name="state";
			document.getElementById("canada_states").name="";
			document.getElementById("spain_states").name="";
			document.getElementById("other_states").name="";
			
		} else if (this.country_id =='170'){
			document.getElementById("canada_states").style.display="inline";
			document.getElementById("state_li").style.display="inline";
		    document.getElementById("us_states").style.display="none";
			document.getElementById("spain_states").style.display="none";
			document.getElementById("other_states").style.display="none";
			document.getElementById("postcode_wrapper").style.display="block";
			
			document.getElementById("canada_states").name="state";
			document.getElementById("us_states").name="";
			document.getElementById("spain_states").name="";
			document.getElementById("other_states").name="";
		
		} else if (this.country_id == '130') {
			document.getElementById("postcode_wrapper").style.display='none';
			//document.getElementById("").style.display='none';
			
		 } else if (this.country_id == "111"){
			document.getElementById("spain_states").style.display="inline";
			document.getElementById("state_li").style.display="inline";
		    document.getElementById("canada_states").style.display="none";
			document.getElementById("us_states").style.display="none";
			document.getElementById("other_states").style.display="none";
			document.getElementById("postcode_wrapper").style.display="block";
			
			document.getElementById("spain_states").name="state";
			document.getElementById("canada_states").name="";
			document.getElementById("us_states").name="";
			document.getElementById("other_states").name="";
			
		 } else {
			/*document.getElementById("other_states").style.display="inline";*/
			document.getElementById("us_states").style.display="none";
			document.getElementById("canada_states").style.display="none";
			/*document.getElementById("state_li").style.display="inline";*/
			document.getElementById("state_li").style.display="none";
			document.getElementById("spain_states").style.display="none";
			
			/*document.getElementById("other_states").name="state";*/
			document.getElementById("canada_states").name="";
			document.getElementById("us_states").name="";
			document.getElementById("spain_states").name="";
			document.getElementById("postcode_wrapper").style.display="block";
		}
	},
	
	/**
	* Validates the country id field in a form. Returns true if the field is selected
	* @return boolean
	*/	
	validateCountryId:function(){
		if(this.country_id == ''){
			return false;
			//this.messages.push("You must select a country from the Countries pull down menu.");
		}
		else{
			return true;
		}
	},
	
  /**
  *  This function is modified from a JavaScript written by							  
  *  Sandeep V. Tamhankar (stamhankar@hotmail.com). The original JavaScript			  
  *  is available at http://javascript.internet.com. It should correspond exactly			  	
  *  with the validation in validations.php. Fehr 7/9/08
  *  @return boolean
  */
	validateEmailAddress:function(){
		emailStr = this.email_address;

		var checkTLD=1;

		/* The following is the list of known TLDs that an e-mail address must end with. */
		/* 11/14/08 JC: added .cat TLD. Not really a country TLD so fails two-letter country
		domain test later on in this function, so it needs to be added here. */
		var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum|cat)$/;

		/* The following pattern is used to check if the entered e-mail address
		fits the user@domain format.  It also is used to separate the username
		from the domain. */
		var emailPat=/^(.+)@(.+)$/;

		/* The following string represents the pattern for matching all special
		characters such as ( ) < > @ , ; : \ " . [ ] */
		var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";

		/* The following string represents the range of characters allowed in a 
		username or domainname.*/
		var validChars="\[^\\s" + specialChars + "\]";

		/* The following pattern applies if the "user" is a quoted string (in
		which case, there are no rules about which characters are allowed
		and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
		is a legal e-mail address. */
		var quotedUser="(\"[^\"]*\")";

		/* The following pattern applies for domains that are IP addresses,
		rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
		e-mail address. NOTE: The square brackets are required. */
		var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;

		/* The following string represents an atom */
		var atom=validChars + '+';

		/* The following string represents one word in the typical username.
		For example, in john.doe@somewhere.com, john and doe are words.*/
		var word="(" + atom + "|" + quotedUser + ")";

		// The following pattern describes the structure of the user
		var userPat=new RegExp("^" + word + "(\\." + word + ")*$");

		/* The following pattern describes the structure of a normal symbolic
		domain, as opposed to ipDomainPat, shown above. */
		var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");

		/* Begin with the coarse pattern to simply break up user@domain into
		different pieces that are easy to analyze. */
		var matchArray=emailStr.match(emailPat);

		if (matchArray==null) {
		/* Too many/few @'s or something; basically, this address doesn't
		even fit the general mould of a valid e-mail address. */
			return false;
		}
		var user=matchArray[1];
		var domain=matchArray[2];

		// Start by checking that only basic ASCII characters are in the strings (0-127).
		for (i=0; i<user.length; i++) {
			if (user.charCodeAt(i)>127) {
				return false;
			}
		}
		for (i=0; i<domain.length; i++) {
			if (domain.charCodeAt(i)>127) {
				return false;
			}
		}

		// See if "user" is valid 
		if (user.match(userPat)==null) {
			return false;
		}

		/* if the e-mail address is at an IP address (as opposed to a symbolic
		host name) make sure the IP address is valid. */
		var IPArray=domain.match(ipDomainPat);
		if (IPArray!=null) {
			for (var i=1;i<=4;i++) {
				if (IPArray[i]>255) {
					return false;
				}
			}
			return true;
		}

		// Domain is symbolic name.  Check if it's valid.
		var atomPat=new RegExp("^" + atom + "$");
		var domArr=domain.split(".");
		var len=domArr.length;
		for (i=0;i<len;i++) {
			if (domArr[i].search(atomPat)==-1) {
				return false;
			}
		}

		/* domain name seems valid, but now make sure that it ends in a
		known top-level domain (like com, edu, gov) or a two-letter word,
		representing country (uk, nl), and that there's a hostname preceding 
		the domain or country. */
		if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1) {
			return false;
		}

		// Make sure there's a host name preceding the domain.
		if (len<2) {
			return false;
		}

		return true;
	},

	/**
	* Validates the postal code field in a form. Returns true if the length is larger than 4
	* @return boolean
	*/
	validatePostcode:function(){
		if(!(this.postcode==undefined) && this.postcode.length < 4){// && this.postcode.length > 15){
			//this.messages.push('A valid post/ZIP code is required.');
			return false;
		} else if(!(this.postcode==undefined) && this.country_id == '166' && !/^\d{5}(\-\d{4})?$/.test(this.postcode)){
			//this.messages.push('A valid ZIP code has five digits.');
			return false;
		} else {
			return true;
		}
	},
	
	/**
	* Validates the Telephone field in a form. Returns true if the length is at least 10 digits
	* @return boolean
	*/
	validateTelephone:function(){
			this.telephone = this.telephone.replace(/\D/g, '');
			if (/\d{6}/.test(this.telephone)) {
				return true;
			} else {
				return false;
			}

	},
	
	/**
	* Validates the Tax ID field in a form. This code comes straight from the 
	* VAT.php class file @ rev 1193 11 aug 06 c.a.l
	* @return boolean
	*/
	validateTaxId:function(){
		// per Rudy @ fs.be, we'll always allow blank vat
		if(this.taxid==undefined || this.taxid == ''){
			return;
		}

		this.taxid = this.taxid.replace(/[^A-Za-z0-9]/g,'');

		var error = false;
		//first, see if we're in a VAT country
		switch(this.country_id){
		      //belgium unique
			case '93': //Belgium - BE123456789
				if(!this.taxid.match(/^([Bb][Ee])?[0-9]{9,10}$/)){
					error = true;
				}
				break;

		      // 8 digits only
			case '107': //Denmark
			case '112': //Finalnd
			case '129': //Hungary
			case '144': //Malta
			case '158': //Slovenia
			case '138': //Luxembourg
				if(!this.taxid.match(/^([A-Za-z]{2})?[0-9]{8}$/)){
					error = true;
				}
				break;

		      // 9 digits only
			case '106': //Germany
			case '110': //Estonia
			case '120': //Greece
			case '154': //Portugal
			  if(!this.taxid.match(/^([A-Za-z]{2})?[0-9]{9}$/)){
			    error = true;
			  }
			  break;

		      // 10 digits only
			case '152': //Poland
			case '159': //Slovakia
			  if(!this.taxid.match(/^([A-Za-z]{2})?[0-9]{10}$/)){
			    error = true;
			  }
			  break;

		      // 11 digits only
			case '133': //Italy
			case '139': //Latvia
			  if(!this.taxid.match(/^([A-Za-z]{2})?[0-9]{11}$/)){
			    error = true;
			  }
			  break;

		      //netherlands unique
			case '147': //Netherlands 123456789B01
				if(!this.taxid.match(/^([A-Za-z]{2})?[0-9]{9}[Bb][0-9]{2}$/)){
					error = true;
				}
				break;

		      //france unique
			case '171': //France 
			  if(!this.taxid.match(/^([A-Za-z]{2})?([0-9A-Za-z]{2}[0-9]{9})$/)){
			    error = true;
			  }
			  break;
		      
		      //ireland unique
			case '130': //ireland
			  if(!this.taxid.match(/^([A-Za-z]{2})?[0-9][0-9A-Za-z][0-9]{5}[A-Za-z]$/)){
			    error = true;
			  }
			  break;

		      //lithuania uni()que
			case '137': //lithuania
			  if(!this.taxid.match(/^([A-Za-z]{2})?[0-9]{9}([0-9]{3})?$/)){
			    error = true;
			  }
			  break;

		      //austria unique
			case '89': //austria
			  if(!this.taxid.match(/^([A-Za-z]{2})?[Uu][0-9]{8}$/)){
			    error = true;
			  }
			  break;

		      //sweeden unique
			case '172': //sweeden
			  if(!this.taxid.match(/^([A-Za-z]{2})?[0-9]{10}01$/)){
			    error = true;
			  }
			  break;

		      //spain unique
			case '111': //spain
			  if(!this.taxid.match(/^([A-Za-z]{2})?[0-9A-Za-z][0-9]{7}[0-9A-Za-z]$/)){
			    error = true;
			  }
			  break;

		      //czech unique
			case '105': //czech
			  if(!this.taxid.match(/^([A-Za-z]{2})?[0-9]{8,10}$/)){
			    error = true;
			  }
			  break;

		      //uk unique - this is a tricky one
			case '164': //uk
			  if(!this.taxid.match(/^([A-Za-z]{2})?[0-9]{9}([0-9]{3})?$/) && !this.taxid.match(/^([A-Za-z]{2})?(([Gg][Dd])|([Hh][Aa]))[0-9]{3}$/)){
			    error = true;
			  }
			  break;

		      //cyprus unique
			case '104': //cyprus
			  if(!this.taxid.match(/^([A-Za-z]{2})?[0-9A-Za-z]{8}[A-Za-z]$/)){
			    error = true;
			  }
			  break;

		}

		if(error){
			//this.messages.push('The VAT Number you entered is not valid.');
			return false;
		}
		else{
			return true;
		}

	},
	
	/**
	* Validates the Passsword length in a form. Returns true if the length is at least 5 digits
	* @return boolean
	*/
	validateLength:function(){
		if(!(this.password==undefined) && this.password.length > 4){
			//this.messages.push('Your Password must contain a minimum of 5 characters.');
			return true;
		}
		else{
			return false;
		}
	},
	
	/**
	* Validates the Passsword match in a form. Returns true if the two passwords match
	* @return boolean
	*/
	validatePassword:function(){
		if(this.password != this.confirmation || !this.password){
			//this.messages.push('The Password Confirmation must match your Password.')
			return false;
		}
		else{
			return true;
		}
	},

	VATCountry:function(){
	  switch (this.country_id){
			case '93': //Belgium - BE123456789
			case '107': //Denmark
			case '112': //Finalnd
			case '129': //Hungary
			case '144': //Malta
			case '158': //Slovenia
			case '138': //Luxembourg
			case '106': //Germany
			case '110': //Estonia
			case '120': //Greece
			case '154': //Portugal
			case '152': //Poland
			case '159': //Slovakia
			case '133': //Italy
			case '139': //Latvia
			case '147': //Netherlands 123456789B01
			case '171': //France 
			case '130': //ireland
			case '137': //lithuania
			case '89': //austria
			case '172': //sweeden
			case '111': //spain
			case '105': //czech
			case '164': //uk
			case '104': //cyprus
			  return true;
			  break;
			default:
			  return false;
			  break;
	  }
	},

	validate:function(){
		if(this.form_name == "checkout_address"){
			if((this.firstname == '' || this.lastname == '') && this.street_address == ''){
				/** the form is a checkout form, and the user didn't enter enough data to 
					suggest he wants to use this address **/

				return true;
			}
		}
	  try{
		this.validateFirstname();
		this.validateLastname();
		this.validateEmailAddress();
		this.validateTelephone();
		this.validateStreetAddress();
		this.validateCity();
		this.validateState();
		this.validateCountryId();
		this.validatePostcode();
		if(this.VATCountry){
		  this.validateTaxId();
		}
		this.validatePassword();
	  }
	  catch(e){
//	    alert(e);
	  }
		/*if(this.messages.length > 0){
			var alert_messages = 'Whoops! I had trouble processing your address:\n\n';
			for(i = 0; i < this.messages.length; i++){
				alert_messages += this.messages[i] + "\n";
			}

			alert(alert_messages);
			resetButton('save_address_button');

			return false;
		
		}
		else return true;*/

	}
}

function initAddressForm(){
	var forms = document.getElementsByTagName('form');

	for(var i = 0; i < forms.length; i++){
		if(forms[i].name == "addressbook" || forms[i].name == "checkout_address" || forms[i].name == 'account_edit'){
			forms[i].onsubmit = function(e){
				var ok = validateForm(this);
				if(e && e.explicitOriginalTarget){
				  resetButtonNoId(e.explicitOriginalTarget);
				}
				else{
				  //find element
				  var inputs = this.getElementsByTagName('input');
				  var cur_element = null;
				  for(var i = inputs.length -1; i >= 0; i--){
				    //probably fastest to go backwards
				    cur_element = inputs[i];
				    if(cur_element.type == 'image'){
				      //it's a button
				      resetButtonNoId(cur_element);
				      break;
				    }
				  }
				}
				return ok;
			}
			break;
		} else if (forms[i].name == 'create_account' ){
			forms[i].onsubmit = LOGIN_FORM.checkLoginForm();
		
		}
	}

}

function validateForm(the_form){
	var d = new Dataset(the_form);
	return d.validate();
}

function initCountry(){
	var input_country = document.getElementById('country');
	input_country.onchange = function(){updateState(this.value);updateVAT(this.value);}
}

function updateVAT(country_id){
  try{
    var vat_item = document.getElementById('vat');
  }
  catch(e){
    //no idea if will throw exception if VAT isn't an option, so we'll just do this anyway
    var vat_item=null;
  }

  if(vat_item){
    if(country_id == 89 || //austria
       country_id == 93 || //belgium
       country_id == 94 || //bulgaria - member in 2007
       country_id == 126 || //croatia - candidate
       country_id == 104 || //cyprus
       country_id == 105 || //czech
       country_id == 107 || //denmark
       country_id == 110 || //estonia
       country_id == 112 || //finland
       country_id == 171 || //france
       country_id == 116 || //french guiana
       country_id == 106 || //germany
       country_id == 120 || //greece
       country_id == 127 || //holy see
       country_id == 129 || //hungary
       country_id == 130 || //ireland
       country_id == 133 || //italy
       country_id == 139 || //latvia
       country_id == 137 || //lithuania
       country_id == 138 || //luxembourg
       country_id == 142 || //macedonia - candidate
       country_id == 144 || //malta
       country_id == 131 || //man, isle of
       country_id == 147 || //netherlands
       country_id == 152 || //poland
       country_id == 154 || //portugal
       country_id == 156 || //romania - member in 2007
       country_id == 159 || //slovakia
       country_id == 158 || //slovenia
       country_id == 111 || //spain
       country_id == 172 || //sweeden
       country_id == 162 || //turkey - candidate
       country_id == 165 //uk
       ){
	vat_item.style.display = "block";
       }
       else{
	vat_item.style.display = "none";
	var tax_input = document.getElementById('taxid');
	tax_input.value = '';
       }

  }
}

function updateState(country_id){
	var USA_COUNTRY_ID = 166;
	var CA_COUNTRY_ID = 170;
	var state_li = document.getElementById('state_li');
	if(state_li){
	  var state_class = state_li.className;

	  if(country_id == USA_COUNTRY_ID || country_id == CA_COUNTRY_ID){
		if(state_class.indexOf('required') == -1){
		  if(state_class.indexOf('optional') != -1){
		    state_class = state_class.replace(/optional/i,'required');
		  }
		  else{
		    state_class = state_class + ' required';
		  }
		}
	  }
	  else{
		state_class = state_class.replace(/required/i,'');
	  }

	  state_li.className = state_class;
	}

}

try{
	var country_id = document.getElementById('country').value;
	if(document.getElementById('country')) { //if the form didn't render (address book is full) we don't want to create errors
		initAddressForm();
		initCountry();
		updateVAT(country_id);
		updateState(country_id);
	}
}
catch(e){
//	alert(e); //comment this out when not debugging;
}


