    jQuery.noConflict();

    function listaHabitaciones() {
            var lista = 'hab=';
            jQuery("._numeroHabitaciones").each(function(){
                var a=jQuery(this);
                var id = a.attr('id');
                var t = id.split('-');
                var idHab = t[1];
                if (parseInt(jQuery("#"+id).html()) > 0) {
                    lista += [idHab]+','+jQuery("#"+id).html()+';';
                }
            });
            return lista;
    }

    function valida() {
        var rango = jQuery("#dateRange").val();
        var periodo = rango.split(" - ");
        if (periodo.length == 2) {
            // Hacer la grabación y pasar al siguiente paso a recojer los datos del cliente f2r ¿como le cambio el idioma?
            var data = listaHabitaciones();
            if (data == 'hab=') {
                // No se ha seleccionado ninguna habitacion
                alert(jQuery("#trad0001").html());
            } else {
                if (jQuery("#diasEstancia").html() != '') {
                    if (confirm(jQuery("#trad0002").html())) {
                        /*
                        * Grabacion de la reserva a espensas de que se introduzcan los datos del cliente
                        *
                        */
                        data += '&extras=';
                        for (var item in aExtras) {
                            if (aExtras[item][1] > 0) {
                                data += [item]+','+aExtras[item][1]+';';
                            }
                        }
                        data += '&total='+jQuery("#precioTotal").html();

                        var url= sitio+'/step0/reserva/'+jQuery("#Step0PaquetesId").val()+'/'+jQuery("#Step0RegimenId").val()+'/'+periodo[0]+'/'+periodo[1];
                        //var url= 'http://localhost/t3/step0/reserva/'+jQuery("#Step0PaquetesId").val()+'/'+jQuery("#Step0RegimenId").val()+'/'+periodo[0]+'/'+periodo[1];
                        jQuery.ajax({
                            url: url,
                            data: data,
                            dataType: "json",
                            async: false,
                            success: function(idReserva){
                                if (idReserva != "") {
                                    // Se ha grabado la reserva temporal, submit al siguiente paso, captura de datos del cliente
                                    document.forms.siguiente.id.value = idReserva;
                                   document.forms.siguiente.submit();
                                }
                            }
                        });
                    }
                } else {
                    alert(jQuery("#trad0010").html());
                }
            }
        }
        return false;
    }


    function validaStep2() {
        var aviso = "";
        if (jQuery("#Nombre").val() == "") {
            aviso += jQuery("#trad0006").html()+"<br>";
        }
        if (jQuery("#Apellidos").val() == "") {
            aviso += jQuery("#trad0007").html()+"<br>";
        }
        if (jQuery("#Telefono1").val() == "") {
            aviso += jQuery("#trad0008").html()+"<br>";
        }
        if (!emailValido(jQuery("#Email").val())) {
            aviso += jQuery("#trad0009").html()+"<br>";
        }
        if (aviso != "") {
            jQuery.prompt(aviso,{
                buttons:{Ok:true},
                opacity: 0.6
            });
            return false;
        }
        return true;


    }


    function calculaCalendario() {
        // Verificar que se hayan seleccionado todos los datos
        // Tiene que haber un rango de fechas de al menos 1 día
        var rango = jQuery("#dateRange").val();
        var periodo = rango.split(" - ");
        if (periodo.length != 2) {
            alert(jQuery("#trad0003").html());
        } else {
            var tmp = primerDia.split('-');
            var hoy = new Date(tmp[2],(tmp[1]-1));
            // Calculo por ajax del array en funci�n de la nueva fecha - f2r
            var url = sitio+'/step0/calendario/'+jQuery("#Step0PaquetesId").val()+'/'+jQuery("#Step0RegimenId").val()+'/'+primerDia;
            var data = listaHabitaciones();
			// we will use the "async: false" because if we use async call, the datapickr will wait for the data to be loaded
			jQuery.ajax({
					url: url,
					data: data,
					dataType: "json",
					async: false,
				    success: function(data){
                        var j = 0;
					    jQuery.each(data, function(i, day){
					     	scheduledDays[j] = day;
                            j++;
				    	});
                        if (j == 0) {
                            scheduledDays = new Array();
                        }
				    }
			});

            jQuery("#fromCalendar").datepicker("change",{beforeShowDay:
                    function (date) {
                            var isScheduled = false;
                            var scheduleStatus = "ui-datepicker-unselectable";
                            //this._unselectableClass = 'ui-datepicker-unselectable'

                            // Check for scheduled day
                            for (i = 0; i < scheduledDays.length; i++) {
                              if (date.getMonth() == (scheduledDays[i][1]-1) && date.getDate() == scheduledDays[i][2] && date.getFullYear() == scheduledDays[i][0])
                              {
                                isScheduled = true;
                                scheduleStatus = scheduledDays[i][3];
                                break;
                              }
                            }
                            if (isScheduled) {
						        var titulo = (scheduledDays[i][4] ? scheduledDays[i][4] : '');
						        if (scheduledDays[i][3] != '') {
                                    var n = new Number(scheduledDays[i][3]);
						        	return [true, scheduleStatus,titulo,inicioPrecio+n.toFixed(2)+finalPrecio];
						        } else {
						        	return [true, 'ui-datepicker-unselectable','',titulo];
						        }
                            } else {
                              	return [true, 'ui-datepicker-unselectable'];
                            }
                    }
            });
            jQuery("#fromCalendar").datepicker( 'setDate' , hoy );
            var rango = jQuery("#dateRange").val();
        	var periodo = rango.split(" - ");
        }
        fechaSeleccionada();
    }

	function fechaSeleccionada() {
		var rango = jQuery("#dateRange").val();
		var periodo = rango.split(" - ");
	    var tmp = periodo[0].split('-');
	    var inicio= new Date(tmp[2],(tmp[1]-1),tmp[0]);
	    var tmp = periodo[1].split('-');
	    var fechaFinal = new Date(tmp[2],(tmp[1]-1),tmp[0]);

            // The number of milliseconds in one day
        var ONE_DAY = 1000 * 60 * 60 * 24

        // Convert both dates to milliseconds
        var date1_ms = inicio.getTime()
        var date2_ms = fechaFinal.getTime()

        // Calculate the difference in milliseconds
        var difference_ms = date2_ms - date1_ms;
        if (difference_ms < 0) {
            var diasEstancia =  0;
        } else {
            difference_ms = Math.abs(difference_ms);
            var diasEstancia =  Math.round(difference_ms/ONE_DAY);
        }

	    var precio = 0;
	    var fecha = inicio;
	    while (fecha < fechaFinal) {
            var isScheduled = false;
		    for (i = 0; i < scheduledDays.length; i++) {
		      if (fecha.getMonth() == parseInt(scheduledDays[i][1]-1) && fecha.getDate() == scheduledDays[i][2] && fecha.getFullYear() == scheduledDays[i][0])
		      {
		        isScheduled = true;
		        break;
		      }
		    }
		    if (isScheduled && !isNaN(scheduledDays[i][3])) {
		    	precio += parseInt(scheduledDays[i][3]);
		    }
		    fecha.setTime(fecha.getTime()+24*60*60*1000); // a�adimos 1 d�a
	    }
        var totalPax = 0;
        var html = '';
        jQuery("._numeroHabitaciones").each(function(){  
            var a=jQuery(this);
            var id = a.attr('id');
            var t = id.split('-');
            var idHab = t[1];
            totalPax = parseInt(totalPax+(pax[idHab]*jQuery("#"+id).html()));
            if (parseInt(jQuery("#"+id).html()) > 0) {
                html += '<tr><td>'+jQuery("#"+id).html()+'</td><td>'+hab[jQuery("#Step0HotelId").val()][idHab]+'</td></tr>';
            }
        });
        // Actualizacion del resumen
        jQuery("#resumenRegimen").html(regimenes[jQuery("#Step0RegimenId").val()]);
        jQuery("#hotelSeleccionado").html(hoteles[jQuery("#Step0HotelId").val()]);
        jQuery("#resumenInicio").html(periodo[0]);
        jQuery("#resumenFinal").html(periodo[1]);
        jQuery("#totalPax").html(totalPax);
        if (diasEstancia > 0) jQuery("#diasEstancia").html(diasEstancia);
        var tdp = (precio+importeExtras);
        if (totalPax > 0) {
            tdp = (tdp/totalPax);
        }
        if (diasEstancia > 0) {
            tdp = (tdp/diasEstancia);
        }
        var t = new Number(tdp);
        jQuery("#subtotalPorPax").html(t.toFixed(2));
        jQuery("#totalPorPax").html(t.toFixed(2));
	    var t = new Number(precio+importeExtras);
	    jQuery("#precioTotal").html(t.toFixed(2));
        jQuery("#precioSubTotal").html(t.toFixed(2));

        var seleccion =jQuery("#Step0PaquetesId").selectedTexts()+" \n"+jQuery("#Step0HabitacionId").selectedTexts();
        jQuery("#habSeleccionadas").html(html);
	}

	function ponerPreciosCalendario(date,elemento) {
	    var isScheduled = false;
	    var scheduleStatus = "";
	    // Check for scheduled day

	    for (i = 0; i < scheduledDays.length; i++) {
	      if (date.getMonth() == parseInt(scheduledDays[i][1]-1) && date.getDate() == scheduledDays[i][2] && date.getFullYear() == scheduledDays[i][0])
	      {
	        isScheduled = true;
	        scheduleStatus = 'ui-datepicker-event-day';
	        break;
	      }
	    }
	    if (isScheduled) {
	        var titulo = (scheduledDays[i][4] ? scheduledDays[i][4] : '');
	        if (scheduledDays[i][3] != '') {
                return [true, scheduleStatus,titulo,inicioPrecio+scheduledDays[i][3]+finalPrecio];
	        } else {
	        	return [false, '','',titulo];
	        }
	    } else {
	      return [false, ''];
	    }
	}


    function cambioDivHabitaciones() {
        /* Genera el div de las habitaciones donde van las cantidades seleccionadas
         * Existe un boton para añadir y otro para restar por cada tipo de habitacion
         * El total de la suma de las habitaciones tiene que ser mayor que cero
         */
        var pvez = true;
        var html = '';
        var filas = 0;
        var totalPax = 0;

        for (var idHabitacion in hab[jQuery("#Step0HotelId").val()] ) {
            filas++;
        }
        for (var idHabitacion in hab[jQuery("#Step0HotelId").val()] ) {
            html += '<tr><td class="tablaHabitacionesBotones"><div id="habit'+idHabitacion+'" ><button  class="botonCantidadHabitaciones" id="bMenosNumHab-'+idHabitacion+'" type="button" onclick=_buttonSR("-","'+idHabitacion+'")>&minus;</button><span id="numHab-'+idHabitacion+'" class="_numeroHabitaciones" style="font-size: 22px; padding: 3px;">';
            if (pvez) {
                  pvez = false;
                  //html += '1';
                  html += '0';
            } else {
                  html += '0';
            }
            html += '</span><button  class="botonCantidadHabitaciones" id="bMasNumHab'+idHabitacion+'" type="button"  onclick=_buttonSR("+","'+idHabitacion+'")>+</button></div></td><td class="tablaHabitacionesNombre">';
            html += '<h6>'+hab[jQuery("#Step0HotelId").val()][idHabitacion]+'</h6></td></tr>';
        }
       jQuery("#tablaHabitaciones").html(html);
       jQuery("#totalPax").html(totalPax);
    }





    function _buttonSR(accion,idHab) {
        
        var nh = jQuery("#numHab-"+idHab).html();
        
        switch (accion) {
            case '-':   if (nh > 0) {
                            nh--;
                        }
                        break;
            case '+':   nh++;
                        break;
        }
        jQuery("#numHab-"+idHab).html(nh);
        // Si no hay ninguna habitacion => desactivar las fechas
        var data = listaHabitaciones();
        if (data == 'hab=') {
            // NO se han seleccionado habitaciones
            alert(jQuery("#trad0001").html());
        }
        calculaCalendario();
    };


    function muestraEnlacePaquete() {
        jQuery("#enlacePaquete").hide();
        jQuery("#enlacePaquete").html("");
        for (idPaquete in descPaquetes) {
            if (idPaquete == jQuery("#Step0PaquetesId").val() && descPaquetes[idPaquete] != null) {
                jQuery("#enlacePaquete").html(descPaquetes[idPaquete]);
                
                break;
            } else {
                jQuery("#enlacePaquete").hide();
            }
        }
        jQuery("#enlacePaquete").show();
        switch (jQuery("#Step0PaquetesId").val()) {
            case "11":
            case "12": var idH = 1;break;
            case "10":
            case "9": var idH = 2;break;
            case "8":
            case "7":
            case "6": var idH = 3;break;
            case "5":
            case "4": var idH = 4;break;
            default : var idH = 5;
        }
        jQuery(".logoPaquete").hide();
        jQuery("#paqueteLogo-"+idioma+"-"+idH).show();

    }

        function muestraEnlaceHotel() {
        jQuery("#enlaceHotel").hide();
        jQuery("#enlaceHotel").html("");
        for (idHotel in descHoteles) {
            if (idHotel == jQuery("#Step0HotelId").val() && descHoteles[idHotel] != null) {
                jQuery("#enlaceHotel").html(descHoteles[idHotel]);
                
                break;
            } else {
                jQuery("#enlaceHotel").hide();
            }
        }
        jQuery("#enlaceHotel").show();
        jQuery(".logoHotel").hide();
        jQuery("#hotelLogo-"+jQuery("#Step0HotelId").val()).show();

    }


     fmtMoney = function(n, c, d, t){ //v1.0
        var m = (c = Math.abs(c) + 1 ? c : 2, d = d || ",", t = t || ".",
        /(\d+)(?:(\.\d+)|)/.exec(n + "")), x = m[1].length > 3 ? m[1].length % 3 : 0;
        return (x ? m[1].substr(0, x) + t : "") + m[1].substr(x).replace(/(\d{3})(?=\d)/g,
        "$1" + t) + (c ? d + (+m[2] || 0).toFixed(c).substr(2) : "");
    };

    function actualizaPrecioExtra(id, precioBase){
        var combo = document.getElementById("extra" + id);
        var adus = jQuery("#extra" + id).val();
        var price = precioBase * adus;
        jQuery("#extraTxt" + id).html(fmtMoney(price,2,"."));
    }

    function addExtra(id) {
        for (var item in aExtras) {
            if (item == id) {
                aExtras[item][1] = parseInt(parseInt(aExtras[item][1]) + parseInt(jQuery("#extra"+id).val()));
                break;
            }
        }
        mostrarExtras();
     }

     function delExtra(id) {
         for (var item in aExtras) {
            if (item == id) {
                aExtras[item][1] = 0;
                break;
            }
        }
        mostrarExtras();
     }

    function mostrarExtras() {
        // Generar el resumen de extras
        importeExtras = 0;
        html = '';
        for (var item in aExtras) {
            if (aExtras[item][1] > 0) {
                html +='<tr><td>'+aExtras[item][2]+'</td><td>'+aExtras[item][1]+'</td><td style="text-align: right;"><b>';
                var n = new Number(aExtras[item][0]);
                html += n.toFixed(2);
                var n = new Number(parseFloat(aExtras[item][0]*aExtras[item][1]));
                html += '</b>&nbsp;&euro;</td><td style="text-align: right;"><b>'+n.toFixed(2)+'</b>&nbsp;&euro;</td><td class="tablaSinBorder"><img onclick="delExtra(\''+item+'\')" src="'+sitio+'/app/webroot/img/imgusuario/b_drop.png" style="cursor: pointer;" /></td></tr>';
                importeExtras +=parseFloat(aExtras[item][0]*aExtras[item][1]);
            }
        }
        if (html != null) {
            var n = new Number(importeExtras);
            html +='<tr><td colspan="2" class="tablaSinBorder"></td><th>'+jQuery("#trad0004").html()+'</th><td class="tablaBorder"  style="text-align: center;"><b>'+n.toFixed(2)+'</b>&nbsp;&euro;</td></tr>';
            jQuery("#extrasSeleccionados").html(html);
            fechaSeleccionada();
        }
    }

    function emailValido(s) {
        var filter=/^[A-Za-z][A-Za-z0-9_-]*@[A-Za-z0-9_-]+\.[A-Za-z0-9_.]+[A-za-z]$/;
        if (s.length == 0 ) return false;
        if (filter.test(s))
            return true;
        else
            return false;
    }

    function hideMotor(idioma, value){
    	if ((idioma=='de')&&((value==4) ||(value==5))){
    		jQuery(".step0titulo").hide();
    		jQuery("#step0hotel").hide();
    		jQuery("#step0habitacion").hide();
    		jQuery("#step0form").hide();
    		jQuery("#step0preview").hide();
    		jQuery("#step0extras").hide();
    		jQuery("#step0resumen").hide(); 	
    		jQuery("#step0continuar").hide();
    		jQuery(".step0tituloMail").show();
    		jQuery("#step0MailReserva").show();
    	}else{
    		jQuery(".step0titulo").show();
    		jQuery("#step0hotel").show();
    		jQuery("#step0habitacion").show();
    		jQuery("#step0form").show();
    		jQuery("#step0preview").show();
    		jQuery("#step0extras").show();
    		jQuery("#step0resumen").show();
    		jQuery("#step0continuar").show(); 
    		jQuery(".step0tituloMail").hide();
    		jQuery("#step0MailReserva").hide();
    	}
    }
