if(typeof(String.prototype.strip) === 'undefined') {
	String.prototype.strip = function() {
		return String(this).replace(/^\s+|\s+$/g, '');
	};
}

$(document).ready(function() {
	$('.user .options. input.option').click(function() {
		$('.user .options. input.option').removeClass('active');
		$(this).addClass('active');
	});
});

function unique(a) {
	tmp = new Array(0);
	
	for(i = 0; i < a.length; i++){
		if(!contains(tmp, a[i])) {
			tmp.length += 1;
			tmp[tmp.length -1 ] = a[i];
		}
	}
	
	return tmp;
}

function contains(a, e) {
	for(j = 0; j < a.length; j++) {
		if(a[j] == e) {
			return true;
		}
	}
	
	return false;
}

function chkValues(){

	if ($('.user .options. input.option.store').hasClass('active')) {
		if($('.storePickup .storeSelect').val() == '0'){
			alert('Bitte wählen Sie noch die Filiale an die Ihre Bestellung gesendet werden soll.');
			return false;
		}
	}


}

function hideShippingAddress() {
	$('name="oxaddressid"').val(-2);
	$('form[name="order"]').submit();
}

function User(errorArea) {
	this.errorArea = errorArea;
	this.registeredFields = {};
	this.errors = [];
	this.customErrorMessages = {
		tel: 'Wir benötigen Ihre Telefonnummer, um Sie bei Rückfragen erreichen zu können.',
		delPnr: 'Bitte geben Sie Ihre Postnummer (nur Zahlen!) an.',
		delPsNr: 'Bitte geben Sie Ihre Packstationsnummer (nur Zahlen!) an.'
	};
}

User.prototype.registerField = function(name, id, type, minLength, maxLength) {
	var field = {name: name, id: id, value: '', type: type, minLength: minLength, maxLength: maxLength};
	this.registeredFields[id] = field;
}

User.prototype.deleteField = function(id) {
	delete(this.registeredFields[id]);
}

User.prototype.checkEmailAddressContent = function(id, id2) {
	var email1 = $('#' + id).val().strip();
	var email2 = $('#' + id2).val().strip();
	
	if(email1 == email2) {
		return true;
	}
	
	return false;
}

User.prototype.checkFields = function(event) {
	var returnValue = true;
	
	if(event != null && typeof(event.originalEvent) != 'undefined') {
		var triggerName = $(event.originalEvent.explicitOriginalTarget).attr('name');
		
		if(typeof(triggerName) == 'undefined') {
			triggerName = $(document.activeElement).attr('name');
		}
		
		if(typeof(triggerName) == 'undefined') {
			triggerName = event.originalEvent;
		}
		
		this.log(triggerName);
		
		if(triggerName == 'blshowshipaddress' || triggerName == 'blshowPsAddress' || triggerName == 'blshowStoreAddress' ||
			triggerName == 'blhideshipaddress' || triggerName == 'blhidePsAddress' || triggerName == 'blhideStoreAddress') {
			return true;
		}
	}
	
	for(var i in this.registeredFields) {
		var field = this.registeredFields[i];
		field.value = $('#' + field.id).val();
		
		switch(field.type) {
			case 'email':
				$('#' + field.id).removeClass('error');
				$('#' + field.id).parents('tr').children('td').children('label').removeClass('error');
				
				if(!this.checkEmail(field.value)) {
					this.addError(field.id, 'Bitte geben Sie eine gültige E-Mail-Adresse an!');
					returnValue = false;
				}
				
				break;

			case 'notEmpty':
				$('#' + field.id).removeClass('error');
				$('#' + field.id).parents('tr').children('td').children('label').removeClass('error');
				
				if(!this.checkNotEmpty(field.value)) {
					if(typeof(this.customErrorMessages[field.id]) != 'undefined') {
						this.addError(field.id, this.customErrorMessages[field.id]);
					} else {
						this.addError(field.id, 'Bitte geben Sie ' + field.name + ' an!');
					}

					returnValue = false;
				}
				
				break;

			case 'zip':
				$('#' + field.id).removeClass('error');
				$('#' + field.id).parents('tr').children('td').children('label').removeClass('error');
				
				if(!this.checkZip(field.value)) {
					this.addError(field.id, 'Bitte geben Sie eine gültige PLZ an. Format: 11111/1111 oder D-1111/D-11111.');
					returnValue = false;
				}

				break;

			case 'date':
				$('#' + field.id).removeClass('error');
				$('#' + field.id).parents('tr').children('td').children('label').removeClass('error');
				
				if(!this.checkNumberRange(field.value, field.minLength, field.maxLength)) {
					this.addError(field.id, 'Bitte geben Sie ein gültiges Geburtsdatum an!');
					returnValue = false;
				}
				
				break;

			case 'phone':
				$('#' + field.id).removeClass('error');
				$('#' + field.id).parents('tr').children('td').children('label').removeClass('error');
				
				if(!this.checkPhone(field.value)) {
					if(typeof(this.customErrorMessages[field.id]) != 'undefined') {
						this.addError(field.id, this.customErrorMessages[field.id]);
					} else {
						this.addError(field.id, 'Bitte geben Sie ' + field.name + ' an!');
					}
				
					returnValue = false;
				}
				
				break;

			case 'number':
				$('#' + field.id).removeClass('error');
				$('#' + field.id).parents('tr').children('td').children('label').removeClass('error');
				
				if(!this.checkNumber(field.value)) {
					if(typeof(this.customErrorMessages[field.id]) != 'undefined') {
						this.addError(field.id, this.customErrorMessages[field.id]);
					} else {
						this.addError(field.id, 'Bitte geben Sie ' + field.name + ' an!');
					}
				
					returnValue = false;
				}
				
				break;
				
		}
	}
	
	if(event != null && returnValue == true) {
		if(!this.checkEmailAddressContent('email1', 'email2')) {
			this.addError('email1', 'Bitte geben Sie übereinstimmende E-Mail-Adressen an!');
			this.addError('email2', 'Bitte geben Sie übereinstimmende E-Mail-Adressen an!');
			returnValue = false;
		}
		
		if(!this.checkBirthDate('bDay', 'bMonth', 'bYear')) {
			this.addError('bDay', 'Sie müssen volljährig sein, um bestellen zu können!');
			this.addError('bMonth', 'Sie müssen volljährig sein, um bestellen zu können!');
			this.addError('bYear', 'Sie müssen volljährig sein, um bestellen zu können!');
			
			returnValue = false;
		}
	}
	
	this.showErrors();
	
	//this.log(returnValue);
	
	return returnValue;
}

User.prototype.showErrors = function() {
	$(this.errorArea + ' p').remove();
	
	this.log(this.errors);
	
	this.errors = unique(this.errors);
	
	if(this.errors.length > 0) {
		for(var i in this.errors) {
			$(this.errorArea).append('<p>' + this.errors[i] + '</p>');
		}
				
		$(this.errorArea).show();
		this.errors = [];
	} else {
		$(this.errorArea).hide();
	}
}

User.prototype.addError = function(id, value) {
	this.errors.push(value);
	$('#' + id).addClass('error');
	$('#' + id).parents('tr').children('td').children('label').addClass('error');
}

User.prototype.log = function(value) {
	if('console' in window) {
		console.log(value);
	}
}

User.prototype.checkBirthDate = function(dayId, monthId, yearId) {
	var day = parseInt($('#' + dayId).val());
	var month = parseInt($('#' + monthId).val());
	var year = parseInt($('#' + yearId).val());
	var currentDate = new Date();
	var birthDate = new Date(year, month - 1, day);
	var fullAgeTimestamp = ((86400 * 365 * 18) + (86400 * 4));
	var currentTimestamp = parseInt(currentDate.getTime() / 1000);
	var birthDateTimestamp = parseInt(birthDate.getTime() / 1000);
	var ageTimestamp = currentTimestamp - birthDateTimestamp;
	
	this.log('fullAgeTimestamp: ' + fullAgeTimestamp);
	this.log('currentTimestamp: ' + currentTimestamp);
	this.log('birthDateTimestamp: ' + birthDateTimestamp);
	this.log('ageTimestamp: ' + ageTimestamp);
	this.log(birthDate.toLocaleString());
	
	
	if(ageTimestamp >= fullAgeTimestamp) {
		return true;
	}
	
	return false;
}

User.prototype.checkEmail = function(email) {
	var emailRegExp = /^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)([_\.\-])?@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$/;
	
	if(emailRegExp.test(email) || email == 'admin') {
		return true;
	}
	
	return false;
}

User.prototype.checkPhone = function(phoneNr) {
	var phoneNrRegExp = /^[0-9\-\/\ \+\(\)]{7,}$/;
	
	if(phoneNrRegExp.test(phoneNr)) {
		return true;
	}
	
	return false;
}

User.prototype.checkZip = function(zip) {
	var zipRegExp = /^[A-Za-z]{0,2}[\-]?[0-9]{4,5}$/;
	
	if(zipRegExp.test(zip)) {
		return true;
	}
	
	return false;
}

User.prototype.checkNotEmpty = function(value) {
	if(value.strip().length > 0) {
		return true;
	}
	
	return false;
}

User.prototype.checkNumber = function(value) {
	if(value.strip().length > 0 && Number(value.strip())) {
		return true;
	}
	
	return false;
}

User.prototype.checkNumberRange = function(value, minValue, maxValue) {
	var returnValue = false;
		
	if(this.checkNumber(value)) {
		if(minValue > 0) {
			returnValue = this.checkMinValue(value, minValue);
		}
		
		if(maxValue > 0 && returnValue == true) {
			returnValue = this.checkMaxValue(value, maxValue);
		}
	} 
	
	return returnValue;
}

User.prototype.checkMinValue = function(value, minValue) {
	if(value.strip() >= minValue) {
		return true;
	}
	
	return false;
}

User.prototype.checkMaxValue = function(value, maxValue) {
	if(value.strip() <= maxValue) {
		return true;
	}
	
	return false;
}

User.prototype.checkLength = function(value, minLength, maxLength) {
	var returnValue = false;
		
	if(this.checkNumber(value)) {
		if(minLength > 0) {
			returnValue = this.checkMinLength(value, minLength);
		}
		
		if(maxLength > 0 && returnValue == true) {
			returnValue = this.checkMaxLength(value, maxLength);
		}
	} 
	
	return returnValue;
}

User.prototype.checkMinLength = function(value, minLength) {
	if(value.strip().length >= minLength) {
		return true;
	}
	
	return false;
}

User.prototype.checkMaxLength = function(value, maxLength) {
	if(value.strip().length <= maxLength) {
		return true;
	}
	
	return false;
}


