
// starting the script on page load
$(document).ready(function(){
	tooltip();
	showMessageAlert();
	showMessageNewsletter();
	showBannerSlideshow();
	showLoginForm();
	ie6TransparentPNG();
});

function ie6TransparentPNG() {
	//PNG's en IE6
	$('body').supersleight({shim: '/js/supersleight/x.gif'});
}

function showBannerSlideshow() {
	$("#destacados").scrollable({size: 1, loop: true, clickable: false, speed: 400 }).autoscroll({autoplay: true, interval : 10000});
}

function showMessageAlert() {
	if ($("#messageAlert").length) { //if exists
		$("#messageAlert").overlay({  
		    top: 'center',  
		    expose: {  
		        color: '#fff',  
		        loadSpeed: 200,  
		        opacity: 0.5 
		    },
		    // disable this for modal dialog-type of overlays 
		    closeOnClick: false, 
		    // we want to use the programming API 
		    api: true
		}).load();
	}
}

function showMessageNewsletter() {
	if ($("#messageNewsletter").length) { //if exists
		$("#messageNewsletter").overlay({  
		    top: 'center',  
		    expose: {  
		        color: '#fff',  
		        loadSpeed: 200,  
		        opacity: 0.5 
		    },
		    // disable this for modal dialog-type of overlays 
		    closeOnClick: false, 
		    // we want to use the programming API 
		    api: true
		}).load();
	}
}
function showMessageRegister() {
	if ($("#messageRegister").length) { //if exists
		$("#messageRegister").overlay({  
		    top: 'center',  
		    expose: {  
		        color: '#fff',  
		        loadSpeed: 200,  
		        opacity: 0.5,
			    onClose: function() {
			    	showLoginForm();
			    }
		    },
		    // disable this for modal dialog-type of overlays 
		    closeOnClick: false, 
		    // we want to use the programming API 
		    api: true
		}).load();
	}
}

var showLoginFormObj = null;
function showLoginForm() {
	if (!showLoginFormObj) {
		showLoginFormObj = $("#accesobutton").tooltip({
			tip: '#box_acceso',
			position: 'bottom left',
			offset: [12, 120],
			events: {
				tooltip: 'mouseover'
			},
			effect: 'slide',
			 api: true
		});
		
		$(document).click(function(e) {
			var el = $(e.target)
			if ($("#box_acceso:visible").length && !el.is("#box_acceso") && !el.parents("#box_acceso").length && !el.is("#accesobutton, #accesobutton a")) {
				hideLoginForm();
			}
		});

	} else showLoginFormObj.show();
}
function hideLoginForm() {
	$("#box_acceso").slideUp();
}

function contactSubmit(f) {
	
	if (validateContactForm(f)) {
		$("#enviar").attr("disabled", "disabled"); 
		$("#loading").show();
	    $.ajax({ 
	        url: '/info/enviar_email.php',
	        type: 'POST',
	        cache: false,
	        dataType: "json",
	        data: $(f).serialize(),
	        success: function(data) { 
	    		if (data.success) {
	    			f.reset();
	    			showMessage("mensaje_newsletter_ok");
	    		} else {
	    			alert(data.error);
	    		}
	        },
	        error: function(){
	        	alert("Se ha producido un error");
	        },
	        complete: function() {
	        	$("#enviar").removeAttr("disabled");
	        	$("#loading").hide();
	        }
	    });
	} else {
		showMessage("mensaje_newsletter_error1");
	}
	return true;
}

function validateContactForm(f) {

	if (f.Nombre.value=="") return false;
	if (f.Apellidos.value=="") return false;
	if (f.Email.value=="") return false;
	if (!isValidEmail(f.Email.value)) return false;
	return true;
}
///
function registroSubmit(f) {
	
	if (validateRegistroForm(f)) {
		$("#enviar").attr("disabled", "disabled"); 
		$("#loading").show();
	    $.ajax({ 
	        url: '/usuarios/suscribe.php',
	        type: 'POST',
	        cache: false,
	        dataType: "json",
	        data: $(f).serialize(),
	        success: function(data) { 
	    		if (data.success) {
	    			f.reset();
	    			$('.jquery_passStrengthener').remove();
	    			hideMessages();
	    			showMessageRegister();
	    		} else {
	    			alert(data.error);
	    		}
	        },
	        error: function(){
	        	alert("Se ha producido un error");
	        },
	        complete: function() {
	        	$("#enviar").removeAttr("disabled");
	        	$("#loading").hide();
	        }
	    });
	} else {
		showMessage("mensaje_newsletter_error1");
	}
	return true;
}

var passStrengthenerPassed = false;
function validateRegistroForm(f) {

	if (f.nombre.value=="") return false;
	if (f.apellidos.value=="") return false;
	if (f.email.value=="") return false;
	if (f.psw.value=="") return false;
	if (!passStrengthenerPassed) {
		alert('Atención, debe entrar una contraseña válida');
		return false;
	}
	if (!isValidEmail(f.email.value)) {
		alert('Atención, el correo electrónico no tiene un formato válido');
		return false;
	}
	
	if (f.federado.checked && f.licencia.value=="") {
		alert('Atención, debe entrar el número de licencia de federado');
		return false;
	}
	
	if (!f.newsletter.checked) {
		alert('Atención, debe seleccionar la casilla de verificación por la cual autoriza el envio de comunicaciones');
		return false;
	}

	
	return true;
}
///
function showMessage(id) {
	$(".message").hide();
	$("#"+id).show();
}
function hideMessages() {
	$(".message").hide();
}
function isValidEmail(str) {
	var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; // not valid
	var reg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/; // valid
	return (!reg1.test(str) && reg2.test(str)); // if syntax is valid
}

function inscribeOferta(id,urlparam) {
    $.ajax({ 
        url: '/ofertas/inscribe_oferta.php',
        type: 'POST',
        cache: false,
        dataType: "json",
        data: '&id='+id,
        success: function(data) {
    		if (data.success) {
    			if (urlparam.length == 0)
    				//alert('Acabas de ser inscrito a la oferta. Muchas gracias.');
    				window.location.href = "/";
    			else
    				window.location.href = urlparam;
    		} else {
    			var typeError = (data.type || null);
    			if (typeError != 'already_inserted')
    				alert(data.error);
    			else {
    				if (urlparam.length > 0)
    					window.location.href = urlparam;
    				else
    					//alert(data.error);
    					window.location.href = "/";
    			}
    		}
        },
        error: function(){
        	alert("Se ha producido un error");
        },
        complete: function() {
        	
        }
    });
}