﻿/* contact form validation */
ContactValidator = function(config) {
	$.extend(this, config);
	$(document).ready(function() { this.init(); } .createDelegate(this));
}

d = function(){}// console.debug;

ContactValidator.prototype = {
	formId: null
	, emptyFirstName: "Der Vorname ist nicht gefüllt"
	, emptyLastName: "Der Nachname ist nicht gefüllt"
	, emptyMailingPostalCode: "Die PLZ ist gefüllt"
	//	, emptyMailingStreet: "Die Strasse ist nicht gefüllt"
	//	, emptyMailingCity: "Das Ort ist nicht gefüllt"
	, emptyPhone: "Das Telefon ist nicht gefüllt"
	, invalidEmail: "Die Email-Adresse ist ungültig"
	, invalidMailingPostalCode: "Die PLZ ist ungültig"
	, invalidPhone: "Das Telefon ist ungültig"
	, zipCityConfig: null
	, country: null
	, defaults: {}
	, init: function() {
		this.mandatory = $(this.formId + ' .mandatory input');
		
		if (typeof ZipCityHint != "undefined" && this.zipCityConfig)
			this.zipCityHint = new ZipCityHint(this.zipCityConfig);
		this.phoneInput = this.mandatory.filter('#Phone');
		this.phoneInput.keypress(this.phoneInputKeypress.createDelegate(this));
		this.errors = $(); //this.errors = $(this.formId + ' .mandatory .alert');
		
		this.initDefaults();
	}
	, initDefaults: function() {
		$.each(this.defaults, function(index, el) {
			//console.debug('#'+index)
			var input = $('#'+index);
			if(input.val() == "") {
				input.val(el);
			}
			input.focus(
				function() {
					if($(this).val() == el) {
						$(this).val(""); 
					}
				}
			).blur(
				function() {
					if($(this).val() == "") {
						$(this).val(el); 
					}
				}
			);
			//.createDelegate(this));
		});
	}
	, isEmpty: function(field, value) { return value.length == 0 || value == null; }
	, setError: function(input, msg) {
		//d(input)
		var err = $('#err' + input);
		if(err) try {err.html(msg).show();}catch(e){}
		if (!this.errors.is('#err' + input))
			this.errors = this.errors.add(err);
		this.hasErrors = true;
	}
	, hasErrors: false
	, validate: function() {
		var that = this;
		this.errors.hide();
		this.hasErrors = false;
		this.mandatory.each(function(index, el) {
			var name = el.name;
			var value = el.value;
			//d(this.defaults)
			if(this.defaults && this.defaults[el.name] && this.defaults[el.name] == value) {
				value = "";
			}
			
			if (that.isEmpty(el, value)) {				
				that.setError(name, that['empty' + name]);
			}
			else {
				switch (name) {
					case "Email":
						if (!that.isValidEmail(value)) {
							that.setError(name, that.invalidEmail);
						}
						break;
					case "MailingPostalCode":
						if (that.zipCityHint && !that.zipCityHint.validate())
							that.setError(name, that.invalidMailingPostalCode);
						break;
					case "Phone":
						var phone = that.phoneInput.val();
						var phoneOK = true;
						var temp;
						switch (that.country) {
							case 'F':
								if ((temp = phone.match(/^[+]33(.*)$/))) // prepeare if +33 format
									phone = "0" + temp[1];
								if ((temp = phone.match(/^0033(.*)$/))) // prepeare if 0033 format
									phone = "0" + temp[1];
								phone = phone.replace(/\D/g, ''); //extract numbers
								if (!phone.match(/^0[12345689][\d]{8}$/) || phone.match(/^089/)) // check 01 23 45 67 89 format and exclude numbers starting with 089
									phoneOK = false;
								break;
							case 'D':
								if ((temp = phone.match(/^[+]49(.*)$/)))
									phone = "0" + temp[1];
								if ((temp = phone.match(/^0049(.*)$/)))
									phone = "0" + temp[1];
								phone = phone.replace(/\D/g, '');
								if (phone.length < 5)
									phoneOK = false;
								break;
							case 'CH':
								if ((temp = phone.match(/^\s*(?:[+]|00)41(.*)$/)))
									phone = "0" + temp[1];
								phone = phone.replace(/\D/g, '');
								if (!phone.match(/^0(1|2[12467]|3[1234]|4[134]|5[256]|6[12]|7[1689]|81|91)[\d]{7}$/))
									phoneOK = false;
								break;
							default:
								alert('Unkonwn country ' + that.country);
						}
						if (!phoneOK)
							that.setError(name, that.invalidPhone);
						break;
				}
			}
		}.createDelegate(this));
		return !this.hasErrors;
	}
	, urlRegex: /(.*)\/car\/([\d\w]+)(?:\/Options|\/AltCars|)(.*)/i
	, submit: function(event) {
		if (!this.validate())
			return false;
		var action = window.location.pathname.replace(this.urlRegex, '$1/quote$3');
		$("form#main").attr('action', action);
	}
	, emailRegex: /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/i
	, isValidEmail: function(str) {
		return this.emailRegex.test(str); //(str.indexOf(".") > 2) && (str.indexOf("@") > 0);
	}
	, phoneInputKeypress: function(e) {
		var key = (e.which) ? e.which : e.keyCode;
		if (key > 57) // not a digit or cmd
			e.preventDefault();
	}
};

Function.prototype.createDelegate = function(scope) {
	var fn = this;
	return function() {
		return fn.apply(scope, arguments);
	}
}

String.prototype.format = function() {
	var pattern = /\{\d+\}/g;
	var args = arguments;
	return this.replace(pattern, function(capture) { return args[capture.match(/\d+/)]; });
}	
