this.imagePreview = function(){
	/* CONFIG */

        xOffset = 10;
        yOffset = 30;

	/* END CONFIG */
	$("a.preview").hover(function(e){
		this.t = this.title;
		this.title = "";
		var c = (this.t != "") ? "<br/>" + this.t : "";
		$("body").append("<p id='tooltipPreview'><img src='"+ this.href +"' alt='Image preview' />"+ c +"</p>");
		$("#tooltipPreview")
			.css("top",(e.pageY - xOffset - $("#tooltipPreview").height()) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");

                $("#tooltipPreview img").load(function(){
                    $("#tooltipPreview")
			.css("top",(e.pageY - xOffset - $("#tooltipPreview").height()) + "px")
			.css("left",(e.pageX - yOffset - $("#tooltipPreview").width()) + "px");
                });
        },
	function(){
            this.title = this.t;
            $("#tooltipPreview").remove();
        });
	$("a.preview").mousemove(function(e){
            $("#tooltipPreview")
                .css("top",(e.pageY - xOffset - $("#tooltipPreview").height()) + "px")
                .css("left",(e.pageX - yOffset - $("#tooltipPreview").width()) + "px");
	});
};


function calculaPrecoReserva(){

    if($("#precoReserva").length>0){
        var precoIni = Number($("#precoReserva").attr("rel"));

        var precoCama = Number($("#precoCama").val());
        var precoPequeno = Number($("#precoPequeno").val());
        var precoFinal = precoIni;

        $(".listaQuartos select.adutosCombo").each(function(){

            //se o pequeno almoço estiver seleccionado
            if($(".pequenoEscolha:checked",$(this).parent().parent().parent()).length == 1){
                //preço pequeno almoço
                precoFinal += (precoPequeno*Number($(this).val()));
            }

            //se o pequeno almoço estiver seleccionado
            if($(".camaEscolha:checked",$(this).parent().parent().parent()).length == 1){
                //preço pequeno almoço
                precoFinal += precoCama;
            }

        });

        $("#precoReserva").text(precoFinal.toFixed(2))

    }
}


$(document).ready(function(){					

    $(".listaQuartos select.adutosCombo, .listaQuartos .pequenoEscolha, .listaQuartos .camaEscolha").change(function(){
        calculaPrecoReserva();
    });

    $.datepicker.setDefaults( $.datepicker.regional[ "pt-BR" ] );


    var dates = $("#dateIn, #dateOut").datepicker({
            showOn: "both",
            buttonImage: "imagens/calendar_sprite.gif",
            buttonImageOnly: true,
            minDate: new Date(),
            maxDate: new Date($("#dateIn").attr("rel")),
            defaultDate: new Date(),
            dateFormat: "yy-mm-dd",
            changeMonth: true,
            numberOfMonths: 2,
            onSelect: function( selectedDate ) {
                var option = this.id == "dateIn" ? "minDate" : "maxDate",
                instance = $(this).data("datepicker");
                date = $.datepicker.parseDate(
                        instance.settings.dateFormat ||
                        $.datepicker._defaults.dateFormat,
                        selectedDate, instance.settings );
                dates.not(this).datepicker("option",option,date);
            }
    });

    imagePreview();

    $(".detalheQuarto").click(function(){

        $(this).parent().parent().next().children("td").toggle();

        return false;
    });


     //cria validação para todos os formulários
    $("form").each(function(index){
        var temp = new appValidaForm();
        temp.initCampoTexto($(this));
    });

});


var appValidaForm = function(){

    /*if (this.__proto__.constructor !== appValidaForm) {
        return new appValidaForm();
    }*/

    //atributos
    this.erroInitValue = "";
    this.campoErro = "";

    //metodos
    this.initCampoTexto = function(form){

        var iThis = this;//referencia a esta intância

        this.campoErro = $(".erroForm",form);

        if(this.campoErro.attr("title")){
            this.erroInitValue = this.campoErro.attr("title");
        }

        //para cada campo no form
        $("input:text, input:password",form).each(function(){

            //se for para ignorar o placeholder
            if(!form.hasClass("ignoreTitle")){

                //valores por defeito
                iThis.colocaPlaceholder($(this));

                $(this).focus(function(){
                    iThis.limpaPlaceholder($(this));
                    iThis.campoErro.html(iThis.erroInitValue);
                })
                $(this).blur(function(){
                    iThis.colocaPlaceholder($(this));
                })
            }
        });

        //limpar o campo erro
        $("input, textarea, select",form).focus(function(){
            iThis.campoErro.html(iThis.erroInitValue);
        });


        //carrega numa tecla
        $("input.nOnly",form).keypress(function(e){
            if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)){
                return false;
            }
            return true;
        });


        //a submeter o form
        form.submit(function(){
            return iThis.validaForm(form, iThis.campoErro);
        })

    }

    this.limpaPlaceholder = function(txtCampo){
        if(txtCampo.attr("title")){
            if(txtCampo.val() == txtCampo.attr("title")){
                txtCampo.val("");
            }
        }
    }

    this.colocaPlaceholder = function(txtCampo){
        if(txtCampo.attr("title")){
            if(txtCampo.val() == ""){
                txtCampo.val(txtCampo.attr("title"));
            }
        }
    }

    this.validaEmail=function(texto){
        var pEmail  =/^.+@.+\..{2,3}$/
        return pEmail.test(texto);
    }

    this.validaForm=function(form,campoErro){

        var iThis = this;//referencia a esta intância
        var id = form.attr("id");

        var retorno = true;
        var sErro = "";

        //todos os campos obrigatorios
        $("#" + id + " input.require, #" + id + "  textarea.require, #" + id + "  select.require").each(function(){
            //se for para ignorar o placeholder
            if(!form.hasClass("ignoreTitle")){
                iThis.limpaPlaceholder($(this));
            }

            //se estiver visivel
            if($(this).is(":visible")){

                if($(this).is(":checkbox")){
                    if(!$(this).is(":checked")){
                        if(retorno){
                            sErro = "Tem que preencher o campo: " + $(this).attr("title");
                            retorno = false;
                        }
                    }
                }else if($(this).val() == null || $(this).val() == ""){
                    if(retorno){
                        sErro = "Tem que preencher o campo: " + $(this).attr("title");
                        retorno = false;
                    }
                }
                /*else if($(this).is("[maxlength]")){
                    if(String($(this).val()).length != $(this).attr("maxlength")){
                        sErro = "O campo: " + $(this).attr("title") + " tem que ter " + $(this).attr("maxlength") + " caracteres!";
                        retorno = false;
                    }
                }*/
            }
            //se for para ignorar o placeholder
            if(!form.hasClass("ignoreTitle")){
                iThis.colocaPlaceholder($(this));
            }
        });

        //para as checkbox que têm que ter pelo menos um seleccionado
        var checkOldName = "";
        $("#" + id + " input:checkbox.require1").each(function(){
            var name = $(this).attr("name");

            //se estiver visivel
            if($(this).is(":visible")){
                if(checkOldName != name){
                    if($("#" + id + " input[name^='" + name + "']:checked").length == 0){
                        sErro = "Tem que seleccionar pelo menos uma opção do campo: " + $(this).attr("title");
                        retorno = false;
                    }
                    checkOldName = name;
                }
            }

        });

        var passwordOld = "";
        var passwordLista = "";
        //para verificar se os campos de password estão ok
        $("#" + id + " input:password").each(function(index){
            if(index == 0){
                passwordOld = $(this).val();
                passwordLista = $(this).attr("title");
            }else{
                if(passwordOld != $(this).val()){
                    if(retorno){
                        passwordLista += ", " + $(this).attr("title");
                        sErro = "Os valores dos seguintes campos têm que ser iguais: " + passwordLista;
                        retorno = false;
                    }
                }
            }
        });

        if(retorno){
            //campos de email
            $("#" + id + " input.email").each(function(){
                //se for para ignorar o placeholder
                if(!form.hasClass("ignoreTitle")){
                    iThis.limpaPlaceholder($(this));
                }
                //se estiver visivel
                if($(this).is(":visible")){
                    if(!iThis.validaEmail($(this).val())){
                        sErro = "Formato do campo inválido: " + $(this).attr("title");
                        retorno = false;
                    }
                }
                //se for para ignorar o placeholder
                if(!form.hasClass("ignoreTitle")){
                    iThis.colocaPlaceholder($(this));
                }
            });
        }

        if(sErro == ""){
            campoErro.html(iThis.erroInitValue);
        }else{
            campoErro.html(sErro);
        }

        return retorno;

    }

}
