$(document).ready(function() 
{

	// Cufon texto a reemplazar
	Cufon.replace('#nav-servicios li a')('#nav-web li a')('.destacado')('h2')('h3')('#servicios-portada li h3')('#servicios-interior li h3')('blockquote');

	//('#slide-portada .content p',{ hover: true })
	
		$('#slide').cycle({
			fx:      'fade',
	   		speed:   3000,
			timeout: 2000,
    		pause:   1,
			next:   '#siguiente',
			prev:   '#anterior'
		});
	


	// Formulario de contacto desplegable
	function contact() {
		if ($("#form-contacto").is(":hidden")){
			$("#form-contacto").slideDown("slow");
			$("#background-pop").css({"opacity": "0.7"});
			$("#background-pop").fadeIn("normal"); 
		}
		else{
			$("#form-contacto").slideUp("slow");
			$("#background-pop").fadeOut("normal");  
		}
	}
	 
	
	$(".contacto").click(function(){contact()});
	
	
	$('a[href*=#]').each(function() {
		if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
		&& location.hostname == this.hostname
		&& this.hash.replace(/#/,'') ) {
		  var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) +']');
		  var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false;
			if ($(this.hash).length) {
				$(this).click(function(event) {
					var targetOffset = $(this.hash).offset().top;
					var target = this.hash;
					event.preventDefault();			   
					$('html, body').animate({scrollTop: targetOffset}, 500);
					return false;
				});
			}
		}
	});



  $('.form-contacto').submit( function(){
		var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		var email = document.getElementById('e-mail');
		if (!filter.test(email.value)) {
			$('.email-aviso').show();
		} else {$('.email-aviso').hide();}
		
		if (document.cform.nombre.value == "") {
			$('.nombre-aviso').show();
		} else {$('.nombre-aviso').hide();}	
		
		if (document.cform.consulta.value == "") {
			$('.consulta-aviso').show();
		} else {$('.consulta-aviso').hide();}
		
		if ((document.cform.nombre.value == "") || (!filter.test(email.value)) || (document.cform.consulta.value == "")){
			return false;
		} 
		
		if ((document.cform.nombre.value != "") && (filter.test(email.value)) && (document.cform.consulta.value != "")) {

			$('.form-contacto').hide();
		
			$('.loader').append($('.bar'));
			$('.bar').css({display:'block'});
		
			$.post('mail.aspx',{nombre:$('#nombre').val(),
							  email:$('#e-mail').val(),
							  consulta:$('#consulta').val()},
		
			function(data){
			  $('.bar').css({display:'none'});
			  $('.loader').append(data);
			});
			
			setTimeout('$("#background-pop").fadeOut("slow"); $("#form-contacto").slideUp("slow")', 5000);
			
			return false;
		} 
  });
	//IE6  
	$("#background-pop").css({  
		"height": document.documentElement.clientHeight 
	});  
});






function IsNumeric(n) {
    return !isNaN(n);
} 

function CleanNumber(value) {

    // Assumes string input, removes all commas, dollar signs, and spaces      
    newValue = value.replace(".","");
    newValue = newValue.replace("€","");
    newValue = newValue.replace(/ /g,'');
    return newValue;
    
}

function CommaFormatted(amount) {
    
	var delimiter = "."; 
	var i = parseInt(amount);
	
	if(isNaN(i)) { return ''; }
	
	i = Math.abs(i);
	
	var minus = '';
	if (i < 0) { minus = '-'; }
	
	var n = new String(i);
	var a = [];
	
	while(n.length > 3)
	{
		var nn = n.substr(n.length-3);
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	
	if (n.length > 0) { a.unshift(n); }
	
	n = a.join(delimiter);
	
	amount =  minus + n + "€";
	
	return amount;
	
}




// form presupuesto

function applyName(klass, numPallets) {

    var toAdd = $("td." + klass).text();
    
    var actualClass = $("td." + klass).attr("rel");
    
    $("input." + actualClass).attr("value", numPallets + " pallets");
    
}

function removeName(klass) {
    
    var actualClass = $("td." + klass).attr("rel");
    
    $("input." + actualClass).attr("value", "");
    
}

function calcTotalPallets() {

    var totalPallets = 0;

    $(".cantidad-input").each(function() {
    
        var thisValue = $(this).val();
    
        if ( (IsNumeric(thisValue)) && (thisValue != '') && (thisValue > 0)) {
            totalPallets += parseInt(thisValue);
        };
    
    });
    
    $("#total-cantidad-input").val(totalPallets);

}

function calcProdSubTotal() {
    
    var prodSubTotal = 0;

    $(".fila-total-input").each(function() {
    
        var valString = $(this).val() || 0;
        
        prodSubTotal += parseInt(valString);
                    
    });
        
    $("#servicios-subtotal").val(CommaFormatted(prodSubTotal));
    $("#fc-precio").attr("value", prodSubTotal);
}



// DOM READY
$(function() {

    var inc = 1;

    $(".nombre-servicio").each(function() {
        
        $(this).addClass("servicio-" + inc).attr("rel", "servicio-" + inc);
    
        var prodTitle = $(this).text();       
        $("#enviar-form-presupuesto").append("<input type='hidden' name='" + prodTitle + "' value='' class='servicio-" + inc + "' />");
        
        inc++;
    
    });

    // Reset form on page load, optional
    $("#tabla-presupuesto input[type=text]:not('#servicios-subtotal')").val("");
    $("#servicios-subtotal").val("0€");
    $("#fc-precio").val("0€");
    $("#total-cantidad-input").val("0");
    
    // "The Math" is performed pretty much whenever anything happens in the quanity inputs
    $('.cantidad-input').bind("focus blur change keyup", function(){
    
        // Caching the selector for efficiency 
        var $el = $(this);
    
        // Grab the new quantity the user entered
        var numPallets = CleanNumber($el.val());
                
        // Find the pricing
        var multiplier = $el
            .parent().parent()
            .find("td.precio-servicio span")
            .text();
        
        // If the quantity is empty, reset everything back to empty
        if ( (numPallets == '') ) {
        
            $el
                .removeClass("aviso")
                .parent().parent()
                .find("td.fila-total input")
                .val("");
                
            var titleClass = $el.parent().parent().find("td.nombre-servicio").attr("rel");
            
            removeName(titleClass);
        
        // If the quantity is valid, calculate the row total
        } else if ( (IsNumeric(numPallets)) && (numPallets != '') && (numPallets >= 0) ) {
            
            var rowTotal = numPallets * multiplier;
            
            $el
                .removeClass("aviso")
                .parent().parent()
                .find("td.fila-total input")
                .val(rowTotal);
                
            var titleClass = $el.parent().parent().find("td.nombre-servicio").attr("rel");
                    
            applyName(titleClass, numPallets);
        
        // If the quantity is invalid, let the user know with UI change                                    
        } else {
        
            $el
                .addClass("aviso")
                .parent().parent()
                .find("td.fila-total input")
                .val("");
            
            var titleClass = $el.parent().parent().find("td.nombre-servicio").attr("rel");
            
            removeName(titleClass);
                                          
        };
        
        // Calcuate the overal totals
        calcProdSubTotal();
        calcTotalPallets();
    
    });

});

