$(document).ready(function() 
{

	// Inicializamos shadowbox para iframes en español
	Shadowbox.init({
	    language: 'es',
    	players:  ["iframe"],
		modal:    true		   				   
	});							 

	//Limpiamos input de search al hacer focus
	$("#buscar-text").focus( function(){
		$(this).val('');
	});
	
	$("#buscar-text").blur( function(){
		if ($(this).val() == ""){
			$(this).val( ((LANGUAGE == 'ca')? "Busca la teva oferta" : "Busca tu oferta") );
		}
	});
	
	$("#ventajas-search .submit").hover( function(){
		if( $('#buscar-text').val() == ((LANGUAGE == 'ca')? "Busca la teva oferta" : "Busca tu oferta") ){
			$('#buscar-text').val('');
		}
	}, function(){
		if ($('#buscar-text').val() == ""){
			$('#buscar-text').val( ((LANGUAGE == 'ca')? "Busca la teva oferta" : "Busca tu oferta") );
		}
	});
	
	//Comportamientos formularios de vacaciones. Pestañas y bloques que se muestran al hacer focus en un radio button //
	$("#particular").click( function(){
		$('#empresas').removeClass('activa');
		$('#particular').addClass('activa');
		$('#caja-empresas').hide();
		$('#caja-particular').show();
        $("#pestanas_formulario_form").val("part");
	});
	$("#empresas").click( function(){
		$('#particular').removeClass('activa');
		$('#empresas').addClass('activa');
		$('#caja-empresas').show();
		$('#caja-particular').hide();
        $("#pestanas_formulario_form").val("emp");
	});
	$("#r-solicitar").click( function(){
		$('#caja-desviar').hide();
		$('#caja-cambioDireccion').hide();
		$('#caja-solicitar').show();
        $('#opciones_servicio_form').val("solicitar");
	});
	$("#r-desviar").click( function(){
		$('#caja-solicitar').hide();
		$('#caja-cambioDireccion').hide();
		$('#caja-desviar').show();
        $('#opciones_servicio_form').val("desviar");
	});
	$("#r-cambioDireccion").click( function(){
		$('#caja-solicitar').hide();
		$('#caja-desviar').hide();
		$('#caja-cambioDireccion').show();
        $('#opciones_servicio_form').val("cambio");
	});

    //Visibilidad inicial de las pestañas particular y empresas
    if ($("#pestanas_formulario_form").val() == "emp") {
        $("#empresas").trigger("click");
    } 
    else {
        $("#particular").trigger("click");
    }

    //visibilidad incial de los radio buttons de desviar, cambio de direccion u soliticar
    switch ($("#opciones_servicio_form").val()) 
    {
        case "solicitar":
            $("#r-solicitar").trigger("click");
            break;
        case "desviar":
            $("#r-desviar").trigger("click");
            break;
        case "cambio":
            $("#r-cambioDireccion").trigger("click");
            break;
    }
        	
	//Si existe el parametro con ID == ficha-ventajas-interesa, le añadimos el evento clic
	var interesa = $("#ficha-ventajas-interesa");
	if (interesa.length > 0) 
	{
		interesa.click(function()
		{
			//comprovació de les cookies
			if ($.cookie("ventajas-interesa-votar") == "active") {
				message = (LANGUAGE == 'ca')? "Ja ha mostrat el seu interès per aquest esdeveniment avui." : "Ya ha mostrado su interes por este evento hoy.";
				alert(message);
				return false;
			}

			//creació de la ruta per fer la crida AJAX
			var dURI = $(document).context.URL;
			var URIA = dURI.split("/");
			var id = (URIA[URIA.length-2]);
			var url = URIA.slice(0,URIA.length-2).join("/")+"/votar/"+id;			
			//petició AJAX
			ajaxCall(url,false,ajaxVoteStatus,"html",this);
		});
	}

	//si existe el input s_poblacio, le añadimos el evento keyup para cuando se escriba texto en el.
	var poblacioInput = $("#s_poblacion");
	if (poblacioInput.length > 0) {
                var suggest = new carrerer();
	}

	//si estamos en el formulario de promociones, mirar que pais se selecciona para enseñar uno u otro texto.
	var paisSelect = $("#s_pais");
	if (paisSelect.length > 0) 
	{
        var esDiv = $(".s_pais_es");
        var anDiv = $(".s_pais_an");

        if (paisSelect.val() == "es") {
            esDiv.show();
            anDiv.hide();
        } 
        else {
            esDiv.hide();
            anDiv.show();
        }

        //listen the change event
        paisSelect.change(function() 
		{
            if (paisSelect.val() == "es") {
                esDiv.show();
                anDiv.hide();
            } 
            else {
                esDiv.hide();
                anDiv.show();
            }
        });
	}

    // si estamos en el formulario de cambio de domicilio temporal, iniciar todos los posibles callejeros
    var modificacionTemporal = $("#pestanas_formulario_form");
    if(modificacionTemporal.length > 0) 
    {
        // el de particulares
        var poblacioPartInput = $("#s_poblacion_part");
        if(poblacioPartInput.length > 0) 
        {
            var pbPart = new carrerer({
                provinciaInputId: "s_provincia_part",
                poblacioInputId: "s_poblacion_part",
                poblacioCheckId: "s_poblacion_check_part",
                poblacioResultsId: "s_poblacion_res_part",
                poblacioResultsULId: "s_poblacio_res_ul_part",
                carrererInputId: "s_nombre_via_part",
                carrererResultsId: "s_nombre_via_res_part",
                carrererResultsULId: "s_nombre_via_res_ul_part"
            });
        }
        
        // el de empresas
        var poblacioEmpInput = $("#s_poblacion_emp");
        if(poblacioEmpInput.length > 0) 
        {
            var pbEmp = new carrerer({
                provinciaInputId: "s_provincia_emp",
                poblacioInputId: "s_poblacion_emp",
                poblacioCheckId: "s_poblacion_check_emp",
                poblacioResultsId: "s_poblacion_res_emp",
                poblacioResultsULId: "s_poblacio_res_ul_emp",
                carrererInputId: "s_nombre_via_emp",
                carrererResultsId: "s_nombre_via_res_emp",
                carrererResultsULId: "s_nombre_via_res_ul_emp"
            });
        }

        // el de cambio de direccion
        var poblacioDirInput = $("#s_poblacion_dir");
        if(poblacioDirInput.length > 0) 
        {
            var pbDir = new carrerer({
                provinciaInputId: "s_provincia_dir",
                poblacioInputId: "s_poblacion_dir",
                poblacioCheckId: "s_poblacion_check_dir",
                poblacioResultsId: "s_poblacion_res_dir",
                poblacioResultsULId: "s_poblacio_res_ul_dir",
                carrererInputId: "s_nombre_via_dir",
                carrererResultsId: "s_nombre_via_res_dir",
                carrererResultsULId: "s_nombre_via_res_ul_dir"
            });
        }

        //el de desviar
        var poblacioDesvInput = $("#s_poblacion_desv");
        if(poblacioDesvInput.length > 0) 
        {
            var pbDesv = new carrerer({
                provinciaInputId: "s_provincia_desv",
                poblacioInputId: "s_poblacion_desv",
                poblacioCheckId: "s_poblacion_check_desv",
                poblacioResultsId: "s_poblacion_res_desv",
                poblacioResultsULId: "s_poblacio_res_ul_desv",
                carrererInputId: "s_nombre_via_desv",
                carrererResultsId: "s_nombre_via_res_desv",
                carrererResultsULId: "s_nombre_via_res_ul_desv"
            });
        }        
    }

    if($("#form-solicitud-tarjeta").length > 0 || 
       $("#form-suscripcion-datos").length > 0 ||
       $("#form-sorteo").length > 0 ||
       $("#form-promocion").length > 0)
    {
        $("#s_provincia").change(
            function()
            {
                $("#s_poblacion").val('');
                $("#s_poblacion_check").val(0);
                $("#s_tipo_via").val('');
                $("#s_nombre_via").val('');
                $("#s_nombre_via_check").val(0);
                $("#s_numero_via").val('');
                $("#s_piso").val('');
                $("#s_puerta").val('');
                $("#s_escalera").val('');
                $("#s_cp").val('');
            }
        );
        $("#s_poblacion").change(
            function()
            {
                $("#s_tipo_via").val('');
                $("#s_nombre_via").val('');
                $("#s_nombre_via_check").val(0);
                $("#s_numero_via").val('');
                $("#s_piso").val('');
                $("#s_puerta").val('');
                $("#s_escalera").val('');
                $("#s_cp").val('');
            }
        );
        $("#s_nombre_via").blur(
            function()
            {
                var nombre_via = $("#s_nombre_via").val();
                var dades_via  = nombre_via.split(", ");
                var nom        = dades_via[0];
                var via        = dades_via[1];
                
                $.post("/carrerer/getTipusVia", {'tipus_via': via}, 
                    function(data)
                    {
                        $("#s_tipo_via").val(data);
                        $("#s_nombre_via").val(nom);
                    }
                );
            }
        );
    }
    
    //en el formulario de confirmacion - pago
    // modo facturacion
	if(!$('#modo_facturacion_pago').attr('checked'))
		$('#div_modo_facturacion_pago').css('display', 'none');
	if(!$('#modo_facturacion_contactar').attr('checked'))
		$('#div_modo_facturacion_contactar').css('display', 'none');

	// tipo facturacion
	if(!$('#tipo_facturacion_tarjeta_credito').attr('checked'))
		$('#div_tipo_facturacion_tarjeta_credito').css('display', 'none');
	if(!$('#tipo_facturacion_cuenta_corriente').attr('checked'))
		$('#div_tipo_facturacion_cuenta_corriente').css('display', 'none');

	// datos_facturacion_tarjeta credito (mismos datos facturacion)
	if($('#datos_facturacion_iguales').attr('checked')){			
		$('#div_datos_facturacion .block-content input').each(function(){
			$(this).attr('disabled', 'disabled');
		});
		$('#div_datos_facturacion .block-content select').each(function(){
			$(this).attr('disabled', 'disabled');
		});
	}

    // "modo facturacion" Event
	$(":input[@name='modo_facturacion']").click(function(){
	    value = ($('#modo_facturacion_pago').attr('checked'))? 'block' : 'none';
		$('#div_modo_facturacion_pago').css('display', value);
		
	    value = ($('#modo_facturacion_contactar').attr('checked'))? 'block' : 'none';
		$('#div_modo_facturacion_contactar').css('display', value);
    });

	// "tipo facturacion" Event
	var facturation_data = $('#div_datos_facturacion');
	//facturation_data.hide();
	$(":input[@name='tipo_facturacion']").click(function(){
		value = ($('#tipo_facturacion_tarjeta_credito').attr('checked'))? 'block' : 'none';
		$('#div_tipo_facturacion_tarjeta_credito').css('display', value);
		//if (value == 'block') $('#div_tipo_facturacion_tarjeta_credito').after(facturation_data);
		
		value = ($('#tipo_facturacion_cuenta_corriente').attr('checked'))? 'block' : 'none';
		$('#div_tipo_facturacion_cuenta_corriente').css('display', value);
		//if (value == 'block') $('#div_tipo_facturacion_cuenta_corriente').after(facturation_data);
		
		//$('#div_datos_facturacion').show();
	});
	
	// datos_facturacion_tarjeta credito (mismos datos facturacion)
	$('#datos_facturacion_iguales').click(function(){
		value = ($('#datos_facturacion_iguales').attr('checked'))? 'disabled' : '';
		$('#div_datos_facturacion .block-content input').each(function(){
			$(this).attr('disabled', value);
		});
		$('#div_datos_facturacion .block-content select').each(function(){
			$(this).attr('disabled', value);
		});
	});
});

function ajaxVoteStatus(msg,scope,data) {
	if (msg == "OK") 
	{
		message = (LANGUAGE == 'ca')? "Votació realitzada amb èxit" : "Votación realizada con exito";
		alert(message);
		//inscriu la cookie per que no es pugui tornar a votar
		$.cookie("ventajas-interesa-votar","active", { expires: 1 })	
	} 
	else {
		message = (LANGUAGE == 'ca')? "Hi ha hagut un problema en realitzar la votació, si us plau proveu-ho més tard." : "Ha habido un problema al realizar la votación, por favor intentelo más tarde.";
		alert(message);
	}
}

function ajaxCall(url,params,callback,dataType,scope) {
	$.ajax({
		url: url,
		global: false,
		type: "POST",
		data: params,
		dataType:dataType,
		success: function(msg){
			callback(msg,scope,params);
		}
	});
}

function validate_promo_confirm(form, message)
{
	if(document.getElementById('check-condiciones').checked)
	{
		return true;
	}
	else
	{
        if( message == undefined || !message.length){
            var message = (LANGUAGE == 'ca')? "Per realitzar la comanda ha de llegir i acceptar les condicions de reserva." : "Para realizar el pedido debe de leer y aceptar las condiciones de reserva.";
        }
		alert( message );
		document.getElementById('submitbotton').style.visibility = "visible";
		return false;
	}
}

function go_paso(paso)
{
	$form_with_errors = false;

	if(paso == 'save')
	{
	  	if($('#modo_facturacion_pago').attr('checked'))
	  	{
			// CUENTA CORRIENTE        	
	    	if($('#tipo_facturacion_cuenta_corriente').attr('checked'))
	    	{
	    		var entidad = $('#cc_entidad');
	    		var oficina = $('#cc_oficina');
	    		var dc = $('#cc_dc');
	    		var cuenta = $('#cc_cuenta');
	    	
				if(!validate_cuenta_corriente( entidad.val(), oficina.val(), dc.val(), cuenta.val() ))
				{
					// not valid
					message = (LANGUAGE == 'ca')? "El número del compte corrent no és vàlid" : "El número de la cuenta corriente no es válido";
					alert(message);
					entidad.addClass('item-error');
					oficina.addClass('item-error');
					dc.addClass('item-error');
					cuenta.addClass('item-error');
					
					$form_with_errors = true;
				}
				else{
					// valid
					entidad.removeClass('item-error');
					oficina.removeClass('item-error');
					dc.removeClass('item-error');
					cuenta.removeClass('item-error');
					
					$form_with_errors = false;
				}
	    	}
	    	// TARJETA CREDITO
	    	else if($('#tipo_facturacion_tarjeta_credito').attr('checked'))
	    	{
				var tarjeta_credito = $('#num_tarjeta_credito');
				
				if(!validate_tarjeta_credito( tarjeta_credito.val() ))
				{
					// not valid
					message = (LANGUAGE == 'ca')? "El número de la targeta de crèdit no és vàlid" : "El número de la tarjeta de crédito no es válido";
					alert(message);
					tarjeta_credito.addClass('item-error');			
					
					$form_with_errors = true;
				}
				else{
					// valid
					tarjeta_credito.removeClass('item-error');
					
					$form_with_errors = false;			
				}
	    	}
	  	}		
	}

	if( !$form_with_errors ){
    	//Submit
    	$("#form-suscripcion-datos").attr("action" , paso+".html");
    	$("#form-suscripcion-datos").submit();
	}
}

/**
* Validar una cuenta corriente con javascript
* http://www.develovers.net/validar-cuenta-corriente-javascript-224163
*
* VALIDACIÓN DE CUALQUIER LIBRETA DE CUALQUIER ENTIDAD BANCARIA.
* Funcion recibe como parámetro la entidad, la oficina,
* el digito (concatenación del de control entidad-oficina y del de control entidad)
* y la cuenta. Espera los valores con 0's a la izquierda.
* Devuelve true o false.
* NOTAS:
* Formato deseado de los parámetros:
* - i_entidad (4)
* - i_oficina (4)
* - i_digito (2)
* - i_cuenta (10)
*/
function validate_cuenta_corriente(i_entidad, i_oficina, i_digito, i_cuenta)
{
	var wtotal,wcociente, wresto;
	if (i_entidad.length != 4){
		return false;
	}
	if (i_oficina.length != 4){
		return false;
	}
	if (i_digito.length != 2){
		return false;
	}
	if (i_cuenta.length != 10){
		return false;
	}
	wtotal = i_entidad.charAt(0) * 4;
	wtotal += i_entidad.charAt(1) * 8;
	wtotal += i_entidad.charAt(2) * 5;
	wtotal += i_entidad.charAt(3) * 10;
	wtotal += i_oficina.charAt(0) * 9;
	wtotal += i_oficina.charAt(1) * 7;
	wtotal += i_oficina.charAt(2) * 3;
	wtotal += i_oficina.charAt(3) * 6;
	// busco el resto de dividir wtotal entre 11
	wcociente = Math.floor(wtotal / 11);
	wresto = wtotal - (wcociente * 11);
	//
	wtotal = 11 - wresto;
	if (wtotal == 11){
		wtotal=0;
	}
	if (wtotal == 10){
		wtotal=1;
	}
	if (wtotal != i_digito.charAt(0)){
		return false;
	}
	//hemos validado la entidad y oficina
	//-----------------------------------
	wtotal = i_cuenta.charAt(0) * 1;
	wtotal += i_cuenta.charAt(1) * 2;
	wtotal += i_cuenta.charAt(2) * 4;
	wtotal += i_cuenta.charAt(3) * 8;
	wtotal += i_cuenta.charAt(4) * 5;
	wtotal += i_cuenta.charAt(5) * 10;
	wtotal += i_cuenta.charAt(6) * 9;
	wtotal += i_cuenta.charAt(7) * 7;
	wtotal += i_cuenta.charAt(8) * 3;
	wtotal += i_cuenta.charAt(9) * 6;

	// busco el resto de dividir wtotal entre 11
	wcociente = Math.floor(wtotal / 11);
	wresto = wtotal - (wcociente * 11);
	//
	wtotal = 11 - wresto;
	if (wtotal == 11){wtotal=0;}
	if (wtotal == 10){wtotal=1;}

	if (wtotal != i_digito.charAt(1)){
		//alert(wtotal+' y no '+i_digito.charAt(1));
		return false;
	}

	// hemos validado la cuenta corriente
	return true;
}

/**
* Validar tarjetas de crédito con Javascript
* http://www.bitacoradewebmaster.com/2007/06/04/validar-tarjetas-de-credito-con-javascript/
*/
function validate_tarjeta_credito( numero ) {
	//Limpiamos el número de tarjeta  de posibles espacios en blanco...
	var expReg = /\W/gi;
	var numero = numero.replace(expReg, "");

	// Chequeamos que el numero entrado tenga formato numérico...
	if(isNaN(numero)) {
		//alert("El número de la tarjeta de crédito no tiene formato numérico.");
		//campo.focus();
		return false;
	}

	// Chequeamos que el numero tenga 16 o 18 dígitos...
	if((numero.length!=16) && (numero.length!=18)) {
		//alert("El número de dígitos en la tarjeta de crédito es incorrecto.");
		//campo.focus();
		return false;
	}

	var suma = 0;
	for(i = numero.length; i > 0; i--) {
		// Si la posición es impar
		if(i % 2 == 1) {
			var doble = "" + (parseInt(numero.substring(i - 1, i)) * 2);
			//Si el doble tiene más dos cifras (o sea es mayor que 9)
			if(doble.length == 2) {
				doble = parseInt(doble.substring(0,1)) + parseInt(doble.substring(1,2));
			}
			suma += parseInt(doble);
		}
		// Si la posición es par
		else {
			suma += parseInt(numero.substring(i - 1, i));
		}
	}

	// Si la suma total no es divisible por 10 entonces el número no es válido
	if(suma % 10 != 0) {
		//alert("El número de la tarjeta de crédito no es válido.");
		//campo.focus();
		return false;
	}

	// En cualquier otro caso el número es válido
	return true;
}

