$(document).ready(function(){
	init();
});

function init(){
	var current_section = $("body").attr("id");
	
	switch (current_section) {
		case "portfolio":
			$(".item_image").hover(function(){
				doHighlight($(this),true);
			}, function(){
				doHighlight($(this),false);
			});
			break;
	}
	switch (current_section) {
		case "contact":
			$("form").submit(function(){
			return validateForm($(this));
		});
		break;
	}
}


function doHighlight(handler,highlight){
	var parent = handler.parents(".portfolio_item");
	var data = $(".item_data", parent);
	if(highlight){
		parent.fadeOut("fast").css("background-color","#e1e1e1").fadeIn("slow");
	}
	else{
		parent.css("background-color","transparent");
		//data.css("color","#333");
	}
}

function validateForm(form){
	var errors = "";
	var errors_num = 0;
	var error_msg = "El formulario contiene ";
	var error_empty = false;
	var error_whitespaces = false;
	var error_email = false;
	var error_rules = false;
	var error_file_format = false;
	
	$(":text,:password,select,textarea",form).not($(".tabbed :input")).each(function(){
		$(this).removeClass("error_focused");
		
		var this_id =  $(this).attr("id");
		var this_value = $(this).val();
		
		// Remove whitespaces from the beginning and end of value
		$.trim(this_value);
		
		// Test if value is empty
		if(this_value.length == 0){
			error_empty = true;
			errors_num++;
			if($(this).attr("class") != "error_focused"){
				$(this).addClass("error_focused");
			}
		}
		else{
			// Test if value is just whitespaces
			var whitespaces = 0;
			for ( i = 0; i < this_value.length; i++ ) {
				if (this_value.charAt(i) == " ") {
					whitespaces++;		
				}
			}
			if(this_value.length == whitespaces){
				error_whitespaces = true;
				errors_num++;
				if($(this).attr("class") != "error_focused"){
					$(this).addClass("error_focused");
				}
			}
			// Email
			if(this_id.match("email")){
				if(!this_value.match(/^(.+\@.+\..+)$/)){
					error_email = true;
					errors_num++;
					if($(this).attr("class") != "error_focused"){
						$(this).addClass("error_focused");
					}
				}
			}
			// User and password rules
			if(this_id.match("user_name") || this_id.match("password")){
				if(!this_value.match(/^[a-z\d]{4,12}$/i) && this_value.length > 0){
					error_rules = true;
					errors_num++;
					if($(this).attr("class") != "error_focused"){
						$(this).addClass("error_focused");
					}
				}
			}
		}
		
	});
	
	if(errors_num > 0){
		error_msg += (errors_num > 1)? "los siguientes errores:\n" : "el siguiente error:\n";
		if(error_empty || error_whitespaces){
			errors += " - Los campos marcados no puede dejarse vacíos.\n";
		}
		if(error_email){
			errors += " - El email introducido no es válido.\n";
		}
		if(error_rules){
			errors += " - Los campos de usuario y contraseña deben tener entre 4 y 12 caracteres y estos sólo pueden ser letras y/o números.\n";
		}
		
		alert(error_msg + errors);
		return false;
	}
	else{
		return true;
	}
}
