/**
 * Common objects and functions.
 * 
 * @author Tomas
 */
var common = new function($) {

/*
 * Document ready.
 */
$(function() {
	$("#language").change(onLanguageChange);
	$("form.validate").submit(onFormSubmit);
});

/**
 * On language change.
 */
function onLanguageChange() {
	var locale = $(this).val();
	var href = window.location.href;
	if (href.indexOf("?") < 0) {
	href += "?";
	}
	if (href.indexOf("locale=") < 0) {
	href += "&";
	}
	if (href.indexOf("locale=") < 0) {
	window.location.href = href + "locale=" + escape(locale);
	}
	else {
	var pos = href.indexOf("&locale");
	var lang = href.substr(0,pos);
	window.location.href = lang + "&locale=" + escape(locale);
	}
}

/**
 * On form submit.
 */
function onFormSubmit() {
	var submit = true;
	$(this).find(".required").each(function() {
		var $this   = $(this);
		var value   = $this.val();
		var type    = null;
		var invalid = false;
		if (value == "") {
			invalid = true;
		} else if (this.type == "checkbox") {
			invalid = !this.checked;
		} else if ($this.hasClass("name")) {
			type = "name";
		} else if ($this.hasClass("email")) {
			type = "email";
		} else if ($this.hasClass("phone")) {
			type = "phone";
		} else if ($this.hasClass("url")) {
			type = "url";
		}
		if (type != null && !isValid(type, value)) {
			invalid = true;
		}
		if (invalid) {
			$this.addClass("invalid");
			if (submit) {
				this.focus();
				submit = false;
			}
		} else {
			$this.removeClass("invalid");
		}
	});
	return submit;
}

/*
 * Valid patterns.
 */
var validPatterns = {
	"name"  : /^[\w ]+$/,
	"email" : /^[\w\.\-]+@\w+\.\w+$/,
	"phone" : /^\d{2,}\-?\d{2,}$/,
	"url"   : /^\S+/
};

/**
 * Is valid.
 * 
 * @param type string
 * @param value string
 * @return boolean
 */
function isValid(type, value) {
	return (value.search(validPatterns[type]) == 0);
}

/*
 * Public.
 */
this.isValid = isValid;

}(jQuery);

