$(document).ready(function (){
	//Prepare images for modal window
	initGalleries();
	//Tooltips
	$('#sec-nav *').tooltip();
	//Instantiate social networks tabs.
	initSocialTab();
	//initFormElements
	initContactForm();
});

function initGalleries(){
	//get all images that are children of .item-images
	$('.item-images a, .item-images-wide a').each(function(){
		//get the original href attr
		var ref = $(this).attr('href');
		//split the href value
		var parts = ref.split('&');
		//slice the value
		var rel = parts[1].slice(3);
		//add the rel attr to the anchor
		$(this).attr('rel', rel);
		//get the src attr from each image.
		var currImg = $(this).children().attr('src');
		//separate the path.
		var pathArray = currImg.split('thumbs');
		//point to large img path
		var path = pathArray[0] + 'large' + pathArray[1];
		//attach the new path to the img.
		$(this).attr('href', path);
	});
	//set up color box calling methods
	$('.item-images, .item-images-wide').each(function(){
		//get the rel attr of the first child
		var rel = $(this).children().eq(0).attr('rel');
		//setup calling method
		$("a[rel='" + rel + "']").colorbox();
	});
}/*End initGalleries Method*/

function initSocialTab(){
	// UL that holds the icons
	var siList = $('#social-icons');
	// Social Button
	var siButton = $('#social-button');
	//Prepare social tab
	siButton.attr('src', 'images/special/social-down.png');
	siButton.attr('title', "Mostrar Redes Sociales");
	siButton.toggle(function(){
		//hide it
		siList.slideUp('slow', function(){
			//the arrow should point down and on hover should say hide tab
			siButton.attr('src', 'images/special/social-up.png').attr('title', "Mostrar Redes Sociales");
		})
	}, function(){
		//show it
		siList.slideDown('slow', function(){
			//the arrow should point down and on hover should say show tab
			siButton.attr('src', 'images/special/social-down.png').attr('title', "Esconder Redes Sociales");
		})
	});
}/*End initSocialTab Method*/

function initContactForm(){
	//Create notice fields for required fields
	var nameNotice		= $('#cf-nombre').parent().append('<p id="nombre-notice" class="error"></p>');
	var lastnameNotice	= $('#cf-apellido').parent().append('<p id="apellido-notice" class="error"></p>');
	var emailNotice		= $('#cf-correo').parent().append('<p id="correo-notice" class="error"></p>');
	var messageNotice	= $('#cf-mensaje').parent().append('<p id="mensaje-notice" class="error"></p>');
	var generalNotice	= $('#cf-submit').parent().prepend('<p id="general-notice"></p>');
	//Insert notification images
	$('#cf-nombre').parent().children().eq(0).append('<img id="name-img" src="images/special/form-cross.png" />');
	$('#cf-apellido').parent().children().eq(0).append('<img id="apellido-img" src="images/special/form-cross.png" />');
	$('#cf-correo').parent().children().eq(0).append('<img id="correo-img" src="images/special/form-cross.png" />');
	$('#cf-mensaje').parent().children().eq(0).append('<img id="mensaje-img" src="images/special/form-cross.png" />');
	//hide all images
	$('fieldset label img').hide();
	//select all p with class notice and hide them
	$('fieldset p').hide();
	//Remove the action attribute from the form
	$('#contact-form').removeAttr('action');
	//Replace submit button with regulat button
	$('#cf-submit').replaceWith('<input type="button" value="Enviar" id="cf-submit-bt" />');
	//Setup Listeners
	$('#cf-submit-bt').bind('click',contactSubmit);
	$('#cf-nombre').bind('change',validateName);
	$('#cf-apellido').bind('change',validateApellido);
	$('#cf-correo').bind('change',validateCorreo);
	$('#cf-mensaje').bind('change',validateMensaje);
	
}/*End initContactForm Method*/

/*
Event Handlers
*/

function validateName(){
	//Name Notification
	var nameNotify = $('#nombre-notice');
	//get value
	var nombre = $('#cf-nombre').val();
	//img
	var img = $('#name-img');
	//validate
	var valid = validateEmpty(nombre,3,25);
	switch (valid){
		case 1001:
			nameNotify.show('fast');
			nameNotify.html('Por favor ingrese su nombre.');
			img.attr('src','images/special/form-cross.png');
			img.show();
			return false;
			break;
		case 1002:
			nameNotify.show('fast');
			nameNotify.html('Su nombre debe superar los 3 caracteres.');
			img.attr('src','images/special/form-cross.png');
			img.show();
			return false;
			break;
		case 1003:
			nameNotify.show('fast');
			nameNotify.html('Su nombre no debe superar los 25 caracteres.');
			img.attr('src','images/special/form-cross.png');
			img.show();
			return false;
			break;
		case 1000:
			nameNotify.html('');
			nameNotify.hide('fast');
			img.attr('src','images/special/form-ticket.png');
			img.show();
			return true;
			break;
	}
}

function validateApellido(){
	//Name Notification
	var apNotify = $('#apellido-notice');
	//get value
	var apellido = $('#cf-apellido').val();
	//img
	var img = $('#apellido-img');
	//validate
	var valid = validateEmpty(apellido,3,25);
	switch (valid){
		case 1001:
			apNotify.show('fast');
			apNotify.html('Por favor ingrese su apellido.');
			img.attr('src','images/special/form-cross.png');
			img.show();
			return false;
			break;
		case 1002:
			apNotify.show('fast');
			apNotify.html('Su apellido debe superar los 3 caracteres.');
			img.attr('src','images/special/form-cross.png');
			img.show();
			return false;
			break;
		case 1003:
			apNotify.show('fast');
			apNotify.html('Su apellido no debe superar los 25 caracteres.');
			img.attr('src','images/special/form-cross.png');
			img.show();
			return false;
			break;
		case 1000:
			apNotify.html('');
			apNotify.hide('fast');
			img.attr('src','images/special/form-ticket.png');
			img.show();
			return true;
			break;
	}
}

function validateCorreo(){
	//Name Notification
	var correoNotify = $('#correo-notice');
	//get value
	var correo = $('#cf-correo').val();
	//img
	var img = $('#correo-img');
	//validate
	var valid = validateEmail(correo);
	switch (valid){
		case 1001:
			correoNotify.show('fast');
			correoNotify.html('El correo ingresado no es v&aacute;lido.');
			img.attr('src','images/special/form-cross.png');
			img.show();
			return false;
			break;
		case 1000:
			correoNotify.html('');
			correoNotify.hide('fast');
			img.attr('src','images/special/form-ticket.png');
			img.show();
			return true;
			break;
	}
}

function validateMensaje(){
	//Name Notification
	var msgNotify = $('#mensaje-notice');
	//get value
	var mensaje = $('#cf-mensaje').val();
	//img
	var img = $('#mensaje-img');
	//validate
	var valid = validateEmpty(mensaje,3,255);
	switch (valid){
		case 1001:
			msgNotify.show('fast');
			msgNotify.html('Por favor ingrese su mensaje.');
			img.attr('src','images/special/form-cross.png');
			img.show();
			return false;
			break;
		case 1002:
			msgNotify.show('fast');
			msgNotify.html('Su mensaje debe superar los 3 caracteres.');
			img.attr('src','images/special/form-cross.png');
			img.show();
			return false;
			break;
		case 1003:
			msgNotify.show('fast');
			msgNotify.html('Su mensaje no debe superar los 255 caracteres.');
			img.attr('src','images/special/form-cross.png');
			img.show();
			return false;
			break;
		case 1000:
			msgNotify.html('');
			msgNotify.hide('fast');
			img.attr('src','images/special/form-ticket.png');
			img.show();
			return true;
			break;
	}
}

function contactSubmit(){
	var notice = $('#general-notice');
	
	if (validateName() && validateApellido() && validateCorreo() && validateMensaje()){
		sendForm();
	} else {
		notice.addClass('error');
		notice.show('fast').delay(3000).hide('slow');
		notice.html('Hay campos con error en el formulario, por favor rectifique e int&eacute;ntelo de nuevo.');
		return false;
	}
}

function sendForm(){
	//show preloader
	$('#cf-submit-bt').parent().append('<img id="cf-preloader" src="images/special/form-preloader.gif" />');
	
	//get the values of the form
	var nombre = $('#cf-nombre').val();
	var apellido = $('#cf-apellido').val();
	var correo = $('#cf-correo').val();
	var telPais = $('#cf-tel-pais').val();
	var telCiudad = $('#cf-tel-ciudad').val();
	var telNumero = $('#cf-numero').val();
	var mensaje = $('#cf-mensaje').val();
	
	//set resources
	var page = "scripts/ajaxMail.php";
	var parameters = 'nombre=' + nombre + '&apellido=' + apellido + '&correo=' + correo + '&pais=' + telPais + '&ciudad=' + telCiudad + '&numero=' + telNumero + '&mensaje=' + mensaje;
	
	sendMail(page,parameters);

}

function sendMail(serverPage, params){
	var notice = $('#general-notice');

	var xmlhttp = xmlHttpRequest();
	
	xmlhttp.open("POST", serverPage, true);

	//Send the proper header information along with the request
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.setRequestHeader("Content-length", params.length);
	xmlhttp.setRequestHeader("Connection", "close");

	xmlhttp.onreadystatechange = function(){
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
			var response = xmlhttp.responseText;
			if (response == 101){
				$('#cf-preloader').remove();
				notice.addClass('success');
				notice.show('fast').delay(5000).hide('slow');
				notice.html('Gracias por su mensaje, responder&eacute; a la brevedad.');
				cleanUpForm();
			} else {
				$('cf-preloader').remove();
				notice.addClass('error');
				notice.show('fast');
				notice.html('Lo siento, hubo un error y su mensaje no pudo enviarse. Por favor utilice una de las opciones de la derecha.');
			}
		}
	}
	xmlhttp.send(params);
}

/*
Validation Methods
*/
function validateEmpty( textValue, minLength, maxLength ){
	var str = jQuery.trim(textValue);
	if ( str == ''){
		return 1001;//field is empty
	} else if (minLength != null || maxLength != null){
		if (str.length < minLength){
			return 1002; // Too short
		}
		if (str.length > maxLength){
			return 1003; //too long
		}
	}
	return 1000; //Success
}

function validateEmail(textValue){
	var str = jQuery.trim(textValue);
	var reg = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/;
   	if(reg.test(str) == false) {
		return 1001; // Invalid Email
   	}
	return 1000;
}


function xmlHttpRequest(){
	//Create a boolean variable to check for a valid Internet Explorer instance.
	var xmlhttp = false;
	var articleID = null;
	var output = '';
	//Check if we are using IE.
	try{
		//If the javascript version is greater than 5.
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch(e){
		//If not, then use the older active x object.
		try {
			//If we are using Internet Explorer.
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (E){
			//Else we must be using other browser
			xmlhttp = false;
		}
	}
	// If we are using a non-IE browser, create a javascript instance of the object.
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined'){
		xmlhttp = new XMLHttpRequest();
	}
	return xmlhttp;
}

function cleanUpForm(){
	$('#contact-form input[type="text"]').val('');
	$('#contact-form input[type="email"]').val('');
	$('#contact-form textarea').val('');
}
