$(document).ready(function ondocumentready(){
	config_login();
	config_home_gallery();
	config_form_calculo_empresas();
	config_form_calculo_usuarios();
	config_faq();
	
	if($(window).width()>600) load_social();
});


$(window).resize(function(){
	if($(window).width()>600) load_social();
});

var social_loaded = false;

function load_social()
{
	if (social_loaded) return;
	
	
	$update_list = $('#twitter_update_list');
	if ($update_list.length)
	{
		//$('body').append('<script type="text/javascript" src="/js/blogger.js"></script>');
		//$('body').append('<script type="text/javascript" src="http://twitter.com/statuses/user_timeline/menupass.json?callback=twitterCallback2&count=1"></script>');
		
		$.ajax({
		  url: '/tweet.php',
		  dataType: 'html',
		  method: 'get',
		  success: function(data) { $('#twitter_update_list').html(data); }
		});
	}
	
	$('#twitterFollow').append('<a href="http://twitter.com/menupass" class="twitter-follow-button" data-show-count="false" data-lang="es"></a>');
	$('#twitterFollow').append('<script src="http://platform.twitter.com/widgets.js" type="text/javascript"></script>');
				
	
	$('#facebookLike').append('<iframe src="http://www.facebook.com/plugins/like.php?app_id=214269061940634&amp;href=<?=urlencode(BFRequest::protocol_host().BFRequest::getCurrentUrl())?>'
							  +'&amp;send=false&amp;layout=button_count&amp;width=150&amp;show_faces=false&amp;action=like&amp;colorscheme=light&amp;font=trebuchet+ms&amp;height=21" '
							  +'scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:150px; height:21px;" allowTransparency="true"></iframe>');	
}




function config_faq()
{
	$(document).ready(function(){
		$('.faq_title ~ p').hide();
		$('.faq_title').css('cursor','pointer');
		$('.faq_title').click(function(){
			$(this).next('p').show();
			$(this).css('cursor','default');
		});
		$('.faq_title').each(function(){
			
			$(this).mouseover(function(){
				if ($(this).css('cursor')=='pointer')
					$(this).css('color','#e18000');
			});
			$(this).mouseout(function(){
				$(this).css('color','#4F4F4F');
			});
		});
	});
}


function config_login()
{
	$('#loginContent').hide();
	$('#loginContainer').removeClass('hidden');
	
	$('#accessContent a').click(function(){
		$('.form_login_tab').hide();
		if ($(this).hasClass('selected'))
		{
			$(this).removeClass('selected');
			$('#loginContent').slideUp('fast');
		}
		else
		{
			$('#accessContent a').removeClass('selected');
			$(this).addClass('selected');
			$('#'+$(this).attr('to')).show();
			$('#loginContent').slideDown('fast');
		}
		
		return false;
	});
	
	$('input[name=NroTar1]').keyup(function() { if($(this).val().length==4) $('input[name=NroTar2]').focus(); 	});
	$('input[name=NroTar2]').keyup(function() { if($(this).val().length==4) $('input[name=NroTar3]').focus(); 	});
	$('input[name=NroTar3]').keyup(function() { if($(this).val().length==4) $('input[name=NroTar4]').focus(); 	});
	$('input[name=NroTar4]').keyup(function() { if($(this).val().length==4) $('input[name=IDUSUARIO]').focus(); 	});
	
	$('#formUsuarios').submit(function(){
		if(
				$('input[name=NroTar1]',this).val()=='' || 
				$('input[name=NroTar2]',this).val()=='' || 
				$('input[name=NroTar3]',this).val()=='' || 
				$('input[name=NroTar4]',this).val()=='' 
		)
		{
			alert('Debes completar los 16 dígitos de la tarjeta');
			if($('input[name=NroTar4]',this).val()=='') $('input[name=NroTar4]',this).focus();
			if($('input[name=NroTar3]',this).val()=='') $('input[name=NroTar3]',this).focus();
			if($('input[name=NroTar2]',this).val()=='') $('input[name=NroTar2]',this).focus();
			if($('input[name=NroTar1]',this).val()=='') $('input[name=NroTar1]',this).focus();
			return false;
		}
		
		if(
				!$('input[name=NroTar1]',this).val().match(/^[0-9]{4,4}$/) ||
				!$('input[name=NroTar2]',this).val().match(/^[0-9]{4,4}$/) ||
				!$('input[name=NroTar3]',this).val().match(/^[0-9]{4,4}$/) ||
				!$('input[name=NroTar4]',this).val().match(/^[0-9]{4,4}$/)
		)
		{
			alert('El número de tarjeta no es válido (introduce sólamente los números, sin guiones ni espacios)');
			if(!$('input[name=NroTar4]',this).val().match(/^[0-9]{4,4}$/)) { $('input[name=NroTar4]',this).val(''); $('input[name=NroTar4]',this).focus(); }
			if(!$('input[name=NroTar3]',this).val().match(/^[0-9]{4,4}$/)) { $('input[name=NroTar3]',this).val(''); $('input[name=NroTar3]',this).focus(); }
			if(!$('input[name=NroTar2]',this).val().match(/^[0-9]{4,4}$/)) { $('input[name=NroTar2]',this).val(''); $('input[name=NroTar2]',this).focus(); }
			if(!$('input[name=NroTar1]',this).val().match(/^[0-9]{4,4}$/)) { $('input[name=NroTar1]',this).val(''); $('input[name=NroTar1]',this).focus(); }
			return false;
		}
		
		if($('input[name=IDUSUARIO]',this).val()=='')
		{
			alert('El NIF no puede estar vacío');
			$('input[name=IDUSUARIO]',this).focus();
			return false;
		}
		
		if(!$('input[name=IDUSUARIO]',this).val().match(/^([A-Za-z]{0,1}[0-9]{1,9}[A-Za-z]{0,1})$/))
		{
			alert('Introduce tu NIF con la letra');
			$('input[name=IDUSUARIO]',this).focus();
			return false;
		}
	});
	
	$('#formEmpresas').submit(function(){
		
		if($('input[name=IDUSUARIO]',this).val()=='')
		{
			alert('El usuario no puede estar vacío');
			$('input[name=IDUSUARIO]',this).focus();
			return false;
		}
		
		if($('input[name=PIN]',this).val()=='')
		{
			alert('La contraseña no puede estar vacía');
			$('input[name=PIN]',this).focus();
			return false;
		}
	});
}


function config_home_gallery()
{
	if ($('#homeSlideshowThumbs').length==0) return;
	
	var duration = 800;
	
	if ($('#homeSlideshowContainer').css('position')=='relative') duration = 0;
	
	$('#homeSlideshowContainer').css('overflow','hidden');
	
    $('#homeSlideshowThumbs').galleriffic({
    	imageContainerSel:         '#homeSlideshow', // The CSS selector for the element within which the main slideshow image should be rendered
    	autoStart:                 true, // Specifies whether the slideshow should be playing or paused when the page first loads
    	defaultTransitionDuration: duration, // If using the default transitions, specifies the duration of the transitions
    	syncTransitions:           true, // Specifies whether the out and in transitions occur simultaneously or distinctly
    	delay:                     6000, // in milliseconds
    	captionContainerSel:       '#homeSlideshowCaption', // The CSS selector for the element within which the captions should be rendered
    	controlsContainerSel:      '#homeSlideshowControls', // The CSS selector for the element within which the slideshow controls should be rendered
    	preloadAhead:              -1, // Set to -1 to preload all images
    	enableKeyboardNavigation:  false, // Specifies whether keyboard navigation is enabled
    	enableHistory:             false, // Specifies whether the url's hash and the browser's history cache should update when the current slideshow image changes
    	enableTopPager:            false,
        enableBottomPager:         false,
        renderSSControls:          false, // Specifies whether the slideshow's Play and Pause links should be rendered
        renderNavControls:         true, // Specifies whether the slideshow's Next and Previous links should be rendered
        prevLinkText:              '',
        nextLinkText:              ''
       
        /*
        ,onSlideChange: function(prevIndex, nextIndex) {
        	// 'this' refers to the gallery, which is an extension of $('#thumbs')
        	//this.find('ul.thumbs').children().eq(prevIndex).fadeOut();
        	//this.find('ul.thumbs').children().eq(nextIndex).fadeIn();
    	}
    	//*/
    
    	,onTransitionOut:  function(slide, caption, isSync, callback) {
    		
    		if(slide.width()<900)
    		{
    			slide.hide();
    			return;
    		}
    		
    		// desde la izda
    		//slide.animate({left:slide.width()+'px'},1500,callback);
    		
    		// desde la dcha
    		slide.animate({left:-slide.width()+'px'},500,callback);
    	}
    	,onTransitionIn:   function(slide, caption, isSync) {
    		slide.show();
    		slide.css('opacity',1);
    		slide.css('overflow','hidden');
    		
    		if(slide.width()<900)
    		{
    			slide.show();
    			return;
    		}
    		
    		/*
    		// desde la izda
    		slide.css('left',-slide.width()+'px');
    		slide.animate({left:'0px'},1500);
    		//*/
    		
    		// desde la dcha
    		slide.css('left',slide.width()+'px');
    		slide.animate({left:'0px'},500);
    	}

    });
    
	$('#homeSlideshowCaption').hide();
	$('#homeSlideshowControls').hide();
	
	$('#homeSlideshowThumbs a').click(function(e){e.preventDefault();});
}


function config_form_calculo_empresas()
{
	if ($('#empresa_ahorro_dias').length==0) return;
		
	$('#empresa_ahorro_dias').ForceNumericOnly();
	$('#empresa_ahorro_importe').ForceNumericOnlyFloat();
	$('#empresa_ahorro_calcular').click(empresas_calcular);
	
	empresas_calcular();
}

function empresas_calcular()
{
	var dias = parseInt($('#empresa_ahorro_dias').val());
	var importe = parseFloat($('#empresa_ahorro_importe').val());
	if (isNaN(dias)) dias = 0;
	if (isNaN(importe)) importe = 0;
	
	var capital = dias*importe;
	var resultado = capital*0.31;
	
	$('#empresa_ahorro_dias').val(dias);
	$('#empresa_ahorro_importe').val(fix_float(importe));
	$('#empresa_ahorro_capital').html(''+fix_float(capital));
	$('#empresa_ahorro_resultado').html(''+fix_float(resultado));
}


function config_form_calculo_usuarios()
{
	if ($('#empleado_ahorro_dias').length==0) return;
	
	$('#empleado_ahorro_dias').ForceNumericOnly();
	$('#empleado_ahorro_importe').ForceNumericOnlyFloat();
	$('#empleado_ahorro_irpf').ForceNumericOnly();
	$('#empleado_ahorro_calcular').click(usuarios_calcular);
	
	usuarios_calcular();
}

function usuarios_calcular()
{
	var dias = parseInt($('#empleado_ahorro_dias').val());
	var importe = parseFloat($('#empleado_ahorro_importe').val());
	var irpf = parseFloat($('#empleado_ahorro_irpf').val());
	if (isNaN(dias)) dias = 0;
	if (isNaN(importe)) importe = 0;
	if (isNaN(irpf)) irpf = 0;
	
	var resultado_capital = dias*importe;
	var resultado_irpf = resultado_capital*irpf/100;
	var resultado_ss = resultado_capital*6.4/100;
	
	
	$('#empleado_ahorro_dias').val(dias);
	$('#empleado_ahorro_importe').val(fix_float(importe));
	$('#empleado_ahorro_irpf').val(irpf);
	
	$('#empleado_ahorro_otras_1').html(''+fix_float(resultado_capital));
	$('#empleado_ahorro_menup_1').html(''+fix_float(resultado_capital));
	
	$('#empleado_ahorro_otras_2').html(''+fix_float(resultado_ss));
	$('#empleado_ahorro_menup_2').html('exento');
	
	$('#empleado_ahorro_otras_3').html(''+fix_float(resultado_irpf));
	$('#empleado_ahorro_menup_3').html('exento');
	
	$('#empleado_ahorro_otras_4').html(''+fix_float(resultado_capital-resultado_ss-resultado_irpf));
	$('#empleado_ahorro_menup_4').html(''+fix_float(resultado_capital));

	
	var total_ahorro = resultado_ss+resultado_irpf;
	
	if (total_ahorro)
	{
		if($('#total_ahorro_fila').length==0)
			$('#result_calculadora').append('<tr id="total_ahorro_fila"><td colspan="2">Total Ahorro</td><td class="right" id="empleado_ahorro_total"></td></tr>');
	
		$('#empleado_ahorro_total').html(''+fix_float(total_ahorro));
	}
	else
	{
		$('#total_ahorro_fila').remove();
	}
}


function fix_float(num) {
	 string = "" + num;
	 if (string.indexOf('.') == -1)
	  return string + '.00';
	 seperation = string.length - string.indexOf('.');
	 if (seperation > 3)
	  return string.substring(0,string.length-seperation+3);
	 else if (seperation == 2)
	  return string + '0';
	 return string;
	}



jQuery.fn.ForceNumericOnly =
	function()
	{
	return this.each(function()
			{
		$(this).keydown(function(e)
				{
			var key = e.charCode || e.keyCode || 0;
			// allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
			return (
					key == 8 || 
					key == 9 ||
					key == 46 ||
					(key >= 37 && key <= 40) ||
					(key >= 48 && key <= 57) ||
					(key >= 96 && key <= 105));
				});
			});
	};


jQuery.fn.ForceNumericOnlyFloat =
function()
{
    return this.each(function()
    {
        $(this).keydown(function(e)
        {
        	var key = e.charCode || e.keyCode || 0;
            var oElement = e.target;
            
        	// allow backspace, tab, delete, arrows
        	if (key == 8 || key == 9 || key == 46 || (key >= 37 && key <= 40) ) return true;
            
            if (key==110 || key==190)
            {
            	if ($(oElement).val()=='')
            	{
            		$(oElement).val('0.');
            		return false;
            	}
            	
            	return true;
            }
            
            // numbers and keypad numbers
            
            if ((key >= 48 && key <= 57) || (key >= 96 && key <= 105)) 
           		return true;
            
           return false;
        });
    });
};
