$(document).ready(function(){

	// *************************
	// COOKIE DE LA HOME FLASH, 
	// detectamos si ha entrado en ela web o no
	// la cookie se destruye cuando cierra el navegador
	// *************************
	
	// miramos a ver si está la cookie
	// y ponemos un flash u otro
	
	if($('#home_container').length){
		if(ReadCookie('dentro')){
			$('#home_container').flash({
				swf:	'/assets/flash/test_inicio_short.swf',
				height: 1300,
				width:	1386,
				wmode: "transparent",
				params: {base_url:'http://' + window.location.host + '/'}
			});
		} else {
			document.cookie = "dentro=home";
			$('#home_container').flash({
				swf:	'/assets/flash/test_inicio.swf',
				height: 1300,
				width:	1386,
				wmode: "transparent",
				params: {base_url:'http://' + window.location.host + '/'}
			});
		}
	}
	
	function ReadCookie(cookieName) {
	 var theCookie=""+document.cookie;
	 var ind=theCookie.indexOf(cookieName);
	 if (ind==-1 || cookieName=="") return ""; 
	 var ind1=theCookie.indexOf(';',ind);
	 if (ind1==-1) ind1=theCookie.length; 
	 return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
	}
	
	// *****************
	// CAMPOS DE LOGIN
	// *****************
	
	$('#login_form input').attr('value','');	
	$('#login_form input').live('focus',function(){
		$(this).parent('label').find('span').hide();
	}).live('blur',function(){
		if ($(this).attr('value') == '') {
			$(this).parent('label').find('span').show();
		}
	});
	
	
	
	
	// ****************
	// EFECTO PARALLAX
	// ****************
	
//	$('body').parallax({
//		ratio	: 1.1
//	});
//	
//	if($('#wrapper.home').length){
//		$('#home_container').parallax({
//			ratio	: 0.2,
//			bg		: false		
//		});
//		$('#wrapper').parallax({
//			ratio	: 0.2		
//		});
//
//	}else{
//		$('#wrapper').parallax({
//			ratio	: 0.2		
//		});
//	}
//	
//	$('#logo').parallax({
//		ratio	: 0.8,
//		bg		: false
//	});
	
	// *************************
	// NOTIFICACIONES AL USUARIO
	// *************************
	
	// si alguna notificación al usuario se lo mostramos
	
	if($('#message').length){
		var txt 			= $('#message').html();
		var messageclass	= $('#message').attr('class');
		$.gritter.add({
			title: ' ',
			text: txt,
			sticky: true,
			time: '',
			class_name: messageclass
		});		
	}

	// prevenimos la baja del usuario
	
	$('a.baja').click(function(e){
		e.preventDefault();
		var link = $(this).attr('href');
		$.gritter.add({
			title: '¿Quieres darte de baja?',
			text: 'Recuerda que si te das de baja perderás todas tus participaciones en las promociones de Grefusateam. Si aún así quieres darte de baja, pincha <a href="'+link+'" title="darme de baja definitivamente">aquí</a>',
			sticky: true,
			time: '',
			class_name: 'warning'
		});		
	});
	
	
	
	
	// *****************************
	// INSERCIÓN DE CONTENIDO FLASH
	// *****************************
	
	// Carrusel de productos
	
	if($('#productsCar').length){
		$('#productsCar').flash({
			swf:	'/assets/flash/sabores.swf',
			height: 580,
			width:	553
		});
	}

	// Carrusel de premios
	
	if($('#premiosCar').length){
		$('#premiosCar').flash({
			swf:	'/assets/flash/premios.swf',
			height: 370,
			width:	553
		});
	}	
	
	
	/* =================== */
	/* = TABS GENÉRICOS = */
	/* =================== */

	$('div.tab_container > div').not(':first-child').hide();
	$('div.tab_container > div:first-child').addClass('on');
	$('ul.tabs li:first-child').addClass('on');
	$('ul.tabs li a').live('click', function(e){
		e.preventDefault();
		var destinoTab = $(this).attr('href');
		if (!$(this).parent('li').hasClass('on')){
			$(this).closest('ul').next('div.tab_container').find('div.on').slideToggle(300).removeClass('on');
			$(destinoTab).slideToggle(300).addClass('on');		
			$(this).closest('ul').find('li.on').removeClass('on');
			$(this).parent('li').addClass('on');

			// esto habría que solucionarlo porque 
			// da mucha guerra, el hover
			if($.browser.msie){
				//Cufon.refresh(replaces_hover);
			}else{
				Cufon.refresh('ul.tabs li a', {
					fontFamily: 'grCnd',
					hover: 'true'
				});
			 }
		}
		else {
			return false; 
		}

	});


	/* ========= */
	/* = POPUP = */
	/* ========= */

	$(".popup").click(function(e){
			e.preventDefault();
			if($('body').hasClass('open'))
			{
				return false;
			}
			else
			{
				$('body').addClass('open');
				$('body').append('<div id="overlay"></div><div id="cargador"><div id="loader"></div></div>');
				$('#cargador').hide();

				var toLoad = $(this).attr('href')+'#content';
				alert(toLoad);
				$('#loader').load(toLoad, {}, function(){
					// $('#cargador').append('<p class="close">Cerrar</p>');
					$('#cargador').slideToggle();
				});
				$('#overlay').show();
				$('#overlay').css({
					'height' : $(document).height()
				});		
			}
		});


		// $('#cargador p.close').live('click',function(){
		// 	$("body").removeClass('open');
		// 	$('#cargador').slideToggle(function(){
		// 		$(this).remove();
		// 	});
		// 	$('#overlay').remove();
		// });	
		$('#overlay').live('click',function(){
			$("body").removeClass('open');
			$('#cargador').slideToggle(function(){
				$(this).remove();
			});
			$('#overlay').remove();
		});
		
		
		$('#redencion').live('submit', function(){
			return false;
		});
		
		/* ========================== */
		/* = FORMULARIO DE REGISTRO = */
		/* ========================== */

		$("#reg_form").validate({
			errorLabelContainer: $("div.errores"),
			errorElement: "p",
			rules: {
				nombre: "required",
				apellidos: {
					required: true,
					minlength: 5
				},
				telefono: {
					required: true,
					number: true,
					minlength: 9,
					maxlength: 9
				},
				dia_nacimiento: "required",
				mes_nacimiento: "required",
				ano_nacimiento: "required",
				sex: "required",
				email: {
					required: true,
					email: true
				},
				email_c: {
					required: true,
					email: true,
					equalTo: "#email"
				},
				contrasena: {
					required: true,
					minlength: 6
				},
				contrasena_c: {
					required: true,
					minlength: 6,
					equalTo: "#contrasena"
				},
				tipo_via: "required",
				via: "required",
				numero: "required",
				cp: {
					required: true,
					number: true,
					minlength: 5,
					maxlength: 5
				},
				localidad: "required",
				provincia: "required",
				mailtutor: {
					required: "#mayor:unchecked",
					email: true
				}
			},
			messages: {
				nombre: "Por favor, escribe tu nombre",
				apellidos: {
					required: "Por favor, escribe tu apellido",
					minlength: "Tu apellido debe tener por los menos 5 caracteres"
				},
				telefono: {
					required: "Por favor, escribe tu teléfono",
					number: "El formato del teléfono debe ser numérico",
					minlength: "El teléfono deber tener 9 dígitos",
					maxlength: "El teléfono deber tener 9 dígitos"
				},
				dia_nacimiento: "Por favor, selecciona tu dia de nacimiento",
				mes_nacimiento: "Por favor, selecciona tu mes de nacimiento",
				ano_nacimiento: "Por favor, selecciona tu año de nacimiento",
				sexo: "Por favor, selecciona tu sexo",
				email: {
					required: "Por favor, escribe tu email",
					email: "Tu email debe ser válido"
				},
				email_c: {
					required: "Por favor, escribe tu email",
					email: "Tu email debe ser válido",
					equalTo: "Verifica que los emails coinciden"
				},
				contrasena: {
					required: "El campo contraseña es obligatorio",
					minlength: "La contraseña debe tener un minimo de 6 caracteres"
				},
				contrasena_c: {
					required: "El campo contraseña es obligatorio",
					minlength: "La contraseña debe tener un minimo de 6 caracteres",
					equalTo: "Las contraseñas deben coincidir"
				},
				tipo_via: "Por favor, selecciona tu tipo de via",
				via: "Por favor, introduce tu via",
				numero: "Por favor, introduce tu numero de domicilio",
				cp: {
					required: "Por favor, introduce tu código postal",
					number: "El formato del código postal debe ser numérico",
					minlength: "El código postal deber tener 5 dígitos",
					maxlength: "El código postal deber tener 5 dígitos"
				},
				localidad: "Por favor, introduce tu población",
				provincia: "Por favor, introduce tu provincia",
				mailtutor: {
					required: "Debes ser mayor de 14 años o introducir el email de tu padre/madre o tutor",
					email: "El email de tu padre/tutor debe ser válido"
				}
			}
		});
		
		if ($("#reg_form").hasClass('modificar')) {
			$("#contrasena").rules("remove", "required");
			$("#contrasena_c").rules("remove", "required");
		}

		$('#mayor').live('click',function(){
			if ($(this).is(':checked')){
				$(this).attr('checked', true);
				$('#reg_form fieldset.padre').slideUp();
			}
			else {
				$(this).attr('checked', false);
				$('#reg_form fieldset.padre').slideDown();
			}
		});


	
});



