var cal1, cal2;
var dateFrom = null;
var dateTo = null;
var maxTimeCookie = 10;
var detview = false;

/********************************************
 *COOKIES
 ********************************************/

/*Funcion que permite crear cookies*/
function createCookie(name,value,minutes) {
        var expires = "";
	if (minutes) {
		var date = new Date();
		date.setTime(date.getTime()+(minutes*60*1000));
		expires = "; expires="+date.toGMTString();
	}
	document.cookie = name+"="+value+expires+"; path=/";
}

/*Funcion que permite leer cookies*/
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

/*Funcion que permite borrar cookies*/
function eraseCookie(name) {
	createCookie(name,"",-1);
}

/*Funcion que permite limpiar todas las cookies que almacenan info en general*/
function clearInfoCookies(){
    eraseCookie("in_date");
    eraseCookie("out_date");
    eraseCookie("rooms");
    eraseCookie("peoplerooms");
    eraseCookie("peopleroomtypes");
    eraseCookie("_reservaRef");
}

/*Funcion que permite limpiar todas las cookies que almacenan info de la sesion*/
function clearInfoAuth(){
    eraseCookie("_sessionweb");
    eraseCookie("_location");
    eraseCookie("_ustype");
}

/*******************************************/



/********************************************
 *CALENDAR
 ********************************************/

/*Funcion para iniciarlizar las variables*/
function LoadCalendar() {
	cal1 = new dhtmlxCalendarObject('calendar1');
	cal1.setOnClickHandler(selectDate1);
	selectDate1(new Date());
	
	cal2 = new dhtmlxCalendarObject('calendar2');
	cal2.setOnClickHandler(selectDate2);
	selectDate2(new Date()+1);
	
	cal1.setYearsRange(2011,2500);
	cal1.draw();
	
	cal2.setYearsRange(2011,2500);
	cal2.draw();
}

/*Funcion para controlar un click outside del componente calendar*/
document.onclick = function (e) {
    e = e || event
    var target = e.target || e.srcElement

    if(target.id != "cal1" && target.id != "cal2"){
        try{
                document.getElementById('calendar1').style.display = 'none';
                document.getElementById('calendar2').style.display = 'none';
        }catch(er){}
    }
}

/*Funcion Handler del evento select date de un componente calendario (1)*/
function selectDate1(date) {
	try{
            document.getElementById('date_in').value = cal1.getFormatedDate("%d/%m/%Y",date);
            document.getElementById('calendar1').style.display = 'none';
            dateFrom = new Date(date);

            if(document.getElementById("num_rooms").selectedIndex != 0){
                    onSelectRooms();
            }
		
	}catch(er){}
	
	return true;
}

/*Funcion Handler del evento select date de un componente calendario (2)*/
function selectDate2(date) {
	try{
            document.getElementById('date_out').value = cal2.getFormatedDate("%d/%m/%Y",date);
            document.getElementById('calendar2').style.display = 'none';
            dateTo = new Date(date);

            if(document.getElementById("num_rooms").selectedIndex != 0){
                    onSelectRooms();
            }
		
	}catch(er){}
	
	return true;
}

/*Funcion que permite visualizar el componente calendario en cada uno de los campos*/
function showCalendar(k) {
	try{
            if(k == 1){
                if(document.getElementById('calendar1').style.display == "none"){
                        document.getElementById('calendar1').style.display = 'block';
                        document.getElementById('calendar2').style.display = 'none';
                }else{
                        document.getElementById('calendar1').style.display = 'none';
                        document.getElementById('calendar2').style.display = 'none';
                }
            }else if(k == 2){
                if(document.getElementById('calendar2').style.display == "none"){
                        document.getElementById('calendar2').style.display = 'block';
                        document.getElementById('calendar1').style.display = 'none';
                }else{
                        document.getElementById('calendar2').style.display = 'none';
                        document.getElementById('calendar1').style.display = 'none';
                }
            }
	}catch(er){}
}

/*Funcion Handler del evento change de el listbox numero de habitaciones*/
function onSelectRooms(){
        var cur_date = new Date(new Date().getFullYear()+"/"+(new Date().getMonth()+1)+"/"+new Date().getDate());
        var temp_in_date = document.getElementById("date_in").value.split('/');
        var temp_out_date = document.getElementById("date_out").value.split('/');

	var in_date = new Date(temp_in_date[2]+"/"+temp_in_date[1]+"/"+temp_in_date[0]).getTime();
	var out_date = new Date(temp_out_date[2]+"/"+temp_out_date[1]+"/"+temp_out_date[0]).getTime();
	var rooms = document.getElementById("num_rooms").selectedIndex;

        if(in_date < cur_date){
            RequestShowMessage("FECHA_MEN_CUR");
        }else if(in_date > out_date){
            RequestShowMessage("FECHA_MAYOR");
	}else if(in_date == out_date){
            RequestShowMessage("FECHA_MAYOR");
	}else if(rooms == 0){
            RequestShowMessage("NO_SELECT_ROOMS");
	}else{
            clearInfoCookies();
            
            createCookie("in_date",document.getElementById("date_in").value,maxTimeCookie);
            createCookie("out_date",document.getElementById("date_out").value,maxTimeCookie);
            createCookie("rooms",rooms,maxTimeCookie);

            window.document.location = "reserva.php?ref=xcf"+getVars(5);
	}
}

/*******************************************/



/********************************************
 *SECTION LOADERS AND VALIDATORS
 ********************************************/

/*Funcion de inicializacion de la reserva en el paso inicial*/
function LoadReserva0(){
    var in_date = readCookie("in_date");
    var out_date = readCookie("out_date");
    var rooms = readCookie("rooms");

    if(in_date != null && out_date != null && rooms != null){
        document.getElementById("in_date_txt").innerHTML += in_date;
	document.getElementById("out_date_txt").innerHTML += out_date;
	document.getElementById("rooms_txt").innerHTML += rooms;
    }else{
        window.document.location = "./";
    }
}

/*Funcion de inicializacion de la reserva en el paso 1*/
function LoadReserva1(){
    showLoader();
    var vars,url;
    var persons = readCookie("peoplerooms");
    var types = readCookie("peopleroomtypes");

    if(persons != null && types != null){
        vars = "rooms="+persons+getVars(5);
        url = "Fachada/PeopleRooms.php?";
        HttpRequest(url+vars,ShowRoomsPersons);

        vars = "types="+types+getVars(5);;
        url = "Fachada/PeopleRoomTyples.php?";
        HttpRequest(url+vars,ShowRoomsTypes);
    }else{
        window.document.location = "./";
    }
}

/*Funcion de inicializacion de la reserva en el paso 2*/
function LoadReserva2(){
    showLoader();
    var vars,url;
    var _webs = readCookie("_sessionweb");

    var _in = readCookie("in_date");
    var _out = readCookie("out_date");
    var _rooms = readCookie("rooms");
    var _prooms = readCookie("peoplerooms");
    var _proomst = readCookie("peopleroomtypes");

    if(_webs != null && _in != null && _out != null && _rooms != null && _prooms != null && _proomst != null){
        vars = "s=" + _webs.split("|")[0] + "&u=" + _webs.split("|")[2] + "&in=" + _in + "&out=" + _out + "&rnum=" + _rooms + "&pr=" + _prooms + "&prt=" + _proomst + getVars(5);
        url = "Fachada/UserInfo.php?";
        HttpRequest(url+vars,ShowUserInfo);
    }else{
        window.document.location = "./";
    }
}

/*Funcion de inicializacion de la reserva en el paso 3*/
function LoadReserva3(){
    showLoader();
    var vars,url;
    var _webs = readCookie("_sessionweb");
    var res = readCookie("_reservaRef");
    var trans_code = getUrlVars()["codigo_respuesta_pol"];
    var pol_code = getUrlVars()["ref_pol"];
    var pol_valor = getUrlVars()["valor"];

    if(_webs != null && _webs != "" && res != null && res != "" && trans_code != null && trans_code != "" && pol_code != null && pol_code != "" && pol_valor != null && pol_valor != ""){
        vars = "s=" + _webs.split("|")[0] + "&u=" + _webs.split("|")[2] + "&refres=" + res + "&refpol=" + pol_code +"&refcode="+ trans_code + "&totalprice=" + pol_valor + getVars(5);
        url = "Fachada/UserReserveComplete.php?";
        HttpRequest(url+vars,CompleteReserve);
    }else{
        window.document.location = "./";
    }
}

/*Funcion que permite visualizar los botones correctos deacuerdo al tipo de usuario para pagar o reservar*/
function LoadPayButtons(){
    var typeu = readCookie("_ustype");

    if(typeu != null){
        if(typeu == 1){
            jQuery(document).ready(function() {
                $("#goPay1").fadeIn(1000);
                $("#goPay2").fadeIn(1000);
            });
        }else if(typeu == 2){
            jQuery(document).ready(function() {
                $("#goReserve").fadeIn(1000);
            });
        }
    }else{
        window.document.location = "./";
    }
}

/*Funcion que permite hacer un llamado a consultar los tipos de habitacion*/
function LoadRooms(){
    showLoader();
    var vars,url;
    var rooms = readCookie("rooms");

    vars = "num="+rooms+getVars(5);
    url = "Fachada/Rooms.php?";
    HttpRequest(url+vars,ShowRooms);
}

/*Funcion que permite hacer un llamado a validar la sesion*/
function ValidSession(){
    showLoader();
    var _webs = readCookie("_sessionweb");
    if(!isNull(_webs) && !isBlank(_webs)){
        var vars,url;
        vars = "s="+_webs.split("|")[0]+"&u="+_webs.split("|")[2]+getVars(5);
        url = "Fachada/ValidOAuth.php?";
        HttpRequest(url+vars,ResponseGetSession);
    }else{
        hideLoader();
    }
}

/*Funcion que permite hacer un llamado a validar la sesion*/
function ValidSessionorClose(){
    showLoader();
    var _webs = readCookie("_sessionweb");
    if(!isNull(_webs) && !isBlank(_webs)){
        var vars,url;
        vars = "s="+_webs.split("|")[0]+"&u="+_webs.split("|")[2]+getVars(5);
        url = "Fachada/ValidOAuth.php?";
        HttpRequest(url+vars,ResponseGetSessionAlternative);
    }else{
        hideLoader();
        window.document.location = "./";
    }
}

/*Funcion que permite hacer el llamado al estado de cuenta del usuario*/
function LoadUserInfo(){
    showLoader();
    var vars,url;
    var _webs = readCookie("_sessionweb");

    if(!isNull(_webs) && !isBlank(_webs)){
        vars = "s="+_webs.split("|")[0]+"&u="+_webs.split("|")[2]+getVars(5);
        url = "Fachada/UserAlterInfo.php?";
        HttpRequest(url+vars,ShowUserAccountInfo);
    }else{
        window.document.location = "./";
    }
}

/*Funcion handler del evento de seleccionar la cantidad de personas de una habitacion*/
function onSelectPersonRooms(row){
    showLoader();
    var vars,url;

    var ob = document.getElementById("list_room"+row);
    var index = ob.selectedIndex;
    var num = ob.options[index].value;

    vars = "num="+num+"&row="+row+getVars(5);
    url = "Fachada/RoomTypes.php?";
    HttpRequest(url+vars,ShowTypeRooms,null,row);
}

/*Funcion general de segmentacion para las validaciones*/
function validateReserve(step){
    if(step == 1){
        Reserve0();
    }
}

/*Funcion que permite validar los campos del formulario de registro*/
function validateRegister(){
    window.addEvent('domready', function() {
        MooTools.lang.setLanguage("es-ES");
        validate = new Form.Validator.Inline("myform");

        validate.add('isDiferent', {
            errorMsg: 'Las contraseñas no son iguales',
            test: function(element){
                if (element.value != element.ownerDocument.getElementById("passtxt").value){
                    return false;
                }else{
                    return true;
                }
            }
        });

        validate.add('isNotPhone', {
            errorMsg: 'Número telefonico invalido',
            test: function(element){
                if (element.value.length < 7){
                    return false;
                }else{
                    return true;
                }
            }
        });


        if(validate.validate()){
            var vars,url;
            
            var name = document.getElementById("nametxt").value;
            var docum = document.getElementById("documenttxt").value;
            var password = MD5(document.getElementById("passtxt").value);
            var country = document.getElementById("countrytxt").value;
            var city = document.getElementById("citytxt").value;
            var address = document.getElementById("addtxt").value;
            var phone = document.getElementById("phonetxt").value;
            var mail = document.getElementById("mailtxt").value;
            var job = document.getElementById("companytxt").value;
            var labor = document.getElementById("labortxt").value;
            var time = MD5(new Date().getTime().toString());

            showLoader();

            vars = "na="+name+"&do="+docum+"&pa="+password+"&co="+country+"&cy="+city+"&ad="+address+"&ph="+phone+"&ma="+mail+"&jo="+job+"&la="+labor+"&r="+time+getVars(10);
            url = "Fachada/ORegisterAuth.php?";
            HttpRequest(url+vars,GetORegisterAuth);
        }
    });
}

/*Funcion que permite limpiar los campos del formulario de registro*/
function cleanRegister(){
    document.getElementById("myform").reset();
}

/*Funcion que permite validar los campos del formulario de autenticacion*/
function validateLogin(){
    window.addEvent('domready', function() {
        MooTools.lang.setLanguage("es-ES");
        validate = new Form.Validator.Inline("myform2");
        if(validate.validate()){
            var vars,url;

            var us = document.getElementById("user_auth_txt").value;
            var pass = MD5(document.getElementById("pass_auth_txt").value);
            var time = MD5(new Date().getTime().toString());

            showLoader();

            vars = "u="+us+"&p="+pass+"&r="+time+getVars(10);
            url = "Fachada/OAuth.php?";
            HttpRequest(url+vars,GetOAuth);
        }
    });
}

/*Funcion que permite limpiar los campos del formulario de autenticacion*/
function cleanLogin(){
    document.getElementById("myform2").reset();
}

/*Funcion que valida la reserva inicial*/
function Reserve0(){
    var close = false;
    var list_persons = new Array();
    var list_types = new Array();

    var rooms = readCookie("rooms");

    for(var i = 1; i <= rooms; i++){

        var ob = document.getElementById("list_room"+i);

        if(ob != null){
            var index = ob.selectedIndex;
            var value = ob.options[index].value;

            if(index == 0){
                RequestShowMessage("ALL_ROOMS_SELECT");
                close = true;
                break;
            }else{
                list_persons.push(value);
                close = false;
            }
        }else{
            close = true;
        }
    }

    if(!close){
        for(i = 1; i <= rooms; i++){
            var cant = document.getElementById("types"+i).childNodes[0].childNodes[0].childNodes.length;
            var selectall = false;
            var inputValue = "";
            for(var j = 0; j < cant; j+=2){
                if(document.getElementById("types"+i).childNodes[0].childNodes[0].childNodes[j].checked){
                    selectall = true;
                    inputValue = document.getElementById("types"+i).childNodes[0].childNodes[0].childNodes[j].value;
                }
            }

            if(!selectall){
                RequestShowMessage("ALL_ROOMSTYPES_SELECT");
                close = true;
                break;
            }else{
                list_types.push(inputValue);
            }
        }
    }

    if(!close){
        createCookie("peoplerooms",list_persons,maxTimeCookie);
        createCookie("peopleroomtypes",list_types,maxTimeCookie);

        window.document.location = "reserva1.php?cf=xvf"+getVars(5);
    }
}

/*Funcion que permite validar los campos del formulario de registro*/
function validateUpdate(){
    window.addEvent('domready', function() {
        MooTools.lang.setLanguage("es-ES");
        validate = new Form.Validator.Inline("myform3");

        validate.add('isDiferent', {
            errorMsg: 'Las contraseñas no son iguales',
            test: function(element){
                if (element.value != element.ownerDocument.getElementById("passtxt").value){
                    return false;
                }else{
                    return true;
                }
            }
        });

        validate.add('isNotPhone', {
            errorMsg: 'Número telefonico invalido',
            test: function(element){
                if (element.value.length < 7){
                    return false;
                }else{
                    return true;
                }
            }
        });


        if(validate.validate()){
            var vars,url;

            var name = document.getElementById("nametxt").value;
            var docum = document.getElementById("documenttxt").value;
            var password_old = MD5(document.getElementById("oldpasstxt").value);
            var password = MD5(document.getElementById("passtxt").value);
            var country = document.getElementById("countrytxt").value;
            var city = document.getElementById("citytxt").value;
            var address = document.getElementById("addtxt").value;
            var phone = document.getElementById("phonetxt").value;
            var mail = document.getElementById("mailtxt").value;
            var job = document.getElementById("companytxt").value;
            var labor = document.getElementById("labortxt").value;
            var time = MD5(new Date().getTime().toString());

            showLoader();

            vars = "na="+name+"&do="+docum+"&pao="+password_old+"&pa="+password+"&co="+country+"&cy="+city+"&ad="+address+"&ph="+phone+"&ma="+mail+"&jo="+job+"&la="+labor+"&r="+time+getVars(10);
            url = "Fachada/OUpdateProfile.php?";
            HttpRequest(url+vars,GetUpdateProfile);
        }
    });
}

/*Funcion que permite limpiar los campos del formulario de actualizacion*/
function cleanUpdater(){
    document.getElementById("myform3").reset();
}

/*Funcion que permite validar los campos del formulario de recuperar clave*/
function passRecovery(){
     window.addEvent('domready', function() {
        MooTools.lang.setLanguage("es-ES");
        validate = new Form.Validator.Inline("recovery");

        if(validate.validate()){
            var vars,url;

            var docum = document.getElementById("document_rec_txt").value;
            var time = MD5(new Date().getTime().toString());
            showLoader();

            vars = "&do="+docum+"&r="+time+getVars(10);
            url = "Fachada/ORecoverPassword.php?";
            HttpRequest(url+vars,GetRecoveryStatus);
        }
    });
}

/*Funcion que permite limpiar los campos del formulario de recuperacion de clave*/
function cleanRecover(){
    document.getElementById("recovery").reset();
}

/*Funcion que me permite inicializar la solicitud de reserva o de pago*/
function sendToPay(op){
    showLoader();
    var vars,url;
    var _webs = readCookie("_sessionweb");

    var _in = readCookie("in_date");
    var _out = readCookie("out_date");
    var _rooms = readCookie("rooms");
    var _prooms = readCookie("peoplerooms");
    var _proomst = readCookie("peopleroomtypes");

    if(_webs != null && _in != null && _out != null && _rooms != null && _prooms != null && _proomst != null){

        if(op == 1){
            var listus = document.getElementById("namestxt");

            if(listus != null){
                vars = "s=" + _webs.split("|")[0] + "&u=" + _webs.split("|")[2] + "&in=" + _in + "&out=" + _out + "&rnum=" + _rooms + "&pr=" + _prooms + "&action=" + op + "&list=" + listus.value + "&prt=" + _proomst + getVars(5);
            }
        }else{
            vars = "s=" + _webs.split("|")[0] + "&u=" + _webs.split("|")[2] + "&in=" + _in + "&out=" + _out + "&rnum=" + _rooms + "&pr=" + _prooms + "&action=" + op + "&prt=" + _proomst + getVars(5);
        }
        url = "Fachada/OpenReserve.php?";
        HttpRequest(url+vars,CallBackReserve);
    }else{
        window.document.location = "./";
    }
}

/*Funcion que permite validar los nombres de los usuariospara plan millas*/
function validUsersPreReserve(){
    var listus = document.getElementById("namestxt");

    if(listus.value.length < 5){
        alert("Debes ingresar el o los nombres de usuario");
    }else{
        sendToPay("1");
    }
}

/*******************************************/




/********************************************
 *AJAX CALL HTTP REQUEST AND CALLBACK METHODS
 ********************************************/

/*Funcion que permite hacer la instancia de un objeto HTTP request por disponibilidad del navegador*/
function makeHttpObject() {
	try {return new XMLHttpRequest();}
	catch (error) {}
	try {return new ActiveXObject("Msxml2.XMLHTTP");}
	catch (error) {}
	try {return new ActiveXObject("Microsoft.XMLHTTP");}
	catch (error) {}

	throw new Error("Could not create HTTP request object.");
}

/*Funcion que permite hacer un llamado HTTP request*/
function HttpRequest(url, success, failure, ref) {
    var request = makeHttpObject();
    request.open("GET", url, true);
    request.send(null);
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            if (request.status == 200){
                if(ref == null || ref == ""){
                    success(request.responseText);
                }else{
                    success(request.responseText,ref);
                }
            }else if (failure){
                failure(request.status, request.statusText);
            }
        }
    }
}

/*Funcion que permite visualizar las alertas con contenido dinamico*/
function ShowAlert(json){
    if(json != ""){
        var item = JSON.decode(json);
        if(item.error){
            alert(item.error);
        }
    }
}

/*Funcion que permite insertar dinamicamente las personas por habitacion por cantidad de habitaciones seleccionadas*/
function ShowRooms(html){
    hideLoader();
    if(html != ""){
        if(html[0] == "{"){
            var item = JSON.decode(html);

            if(item.error){
                alert(item.error);
            }
        }else{
            document.getElementById("conenido").innerHTML = html;

            jQuery(document).ready(function() {
                $("#conenido").fadeOut(0).fadeIn(1000);
            });
        }
    }
}

/*Funcion que permite insertar dinamicamente los tipos de habitacion disponible por cantidar de personas por habitacion*/
function ShowTypeRooms(html, ref){
    hideLoader();
    if(html != ""){
        if(html[0] == "{"){
            var item = JSON.decode(html);

            if(item.error){
                alert(item.error);
            }
        }else{
            document.getElementById("types"+ref).innerHTML = html;

            jQuery(document).ready(function() {
                $("#types"+ref).fadeOut(0).fadeIn(1000);
            });
        }
    }

}

/*Funcion que permite insertar dinamicamente el numero de personas de acuerdo a la cantidad de habitaciones*/
function ShowRoomsPersons(json){
    hideLoader();
    if(json != ""){
        var item = JSON.decode(json);

        if(item.error){
            alert(item.error);
        }else{
            document.getElementById("persons_txt").innerHTML += item.types;
        }
    }
}

/*Funcion que permite insertar dinamicamente los tipos de habitacion de acuerdo a la cantidar de habitaciones*/
function ShowRoomsTypes(json){
    hideLoader();
    if(json != ""){
        var item = JSON.decode(json);

        if(item.error){
            alert(item.error);
        }else{
            document.getElementById("types_txt").innerHTML += item.types;
        }
    }
}

/*Funcion que permite recibir los datos del usuario despues de iniciar sesion*/
function ShowUserInfo(json){
    var item = JSON.decode(json);

    if(item.error){
        alert(item.error);
    }else{
        if(document.getElementById("name_txt")){
            document.getElementById("name_txt").innerHTML += item.nombre;
        }

        if(document.getElementById("docum_txt")){
            document.getElementById("docum_txt").innerHTML += item.documento;
        }

        if(document.getElementById("country_txt")){
            document.getElementById("country_txt").innerHTML += item.pais;
        }

        if(document.getElementById("city_txt")){
            document.getElementById("city_txt").innerHTML += item.ciudad;
        }

        if(document.getElementById("address_txt")){
            document.getElementById("address_txt").innerHTML += item.direccion;
        }

        if(document.getElementById("phone_txt")){
            document.getElementById("phone_txt").innerHTML += item.telefono;
        }

        if(document.getElementById("mail_txt")){
            document.getElementById("mail_txt").innerHTML += item.correo;
        }

        if(document.getElementById("pass_txt")){
            document.getElementById("pass_txt").innerHTML += item.password;
        }

        if(document.getElementById("job_txt")){
            document.getElementById("job_txt").innerHTML += item.empresa;
        }

        if(document.getElementById("labor_txt")){
            document.getElementById("labor_txt").innerHTML += item.cargo;
        }

        if(document.getElementById("total_value")){
            document.getElementById("total_value").innerHTML = "Valor a pagar<br />" + formatCurrency(item.total);
            jQuery(document).ready(function() {
                $("#total_value").fadeOut(0).fadeIn(1000);
                $("#pagainfo").fadeOut(0).fadeIn(500);
            });
        }

        var tu = readCookie("_ustype");

        if(document.getElementById("total_price_txt") && tu == "2"){
            document.getElementById("total_price_txt").innerHTML += formatCurrency(item.total);
        }

        if(document.getElementById("new_score_txt") && tu == "2"){
            document.getElementById("new_score_txt").innerHTML += item.stepscore;
        }

        if(document.getElementById("updated_score_txt") && tu == "2"){
            document.getElementById("updated_score_txt").innerHTML += item.puntos;
        }

        if(document.getElementById("reserve_code_txt") && tu == "2"){
            var res = readCookie("_reservaRef");
            if(res != null && res != ""){
                document.getElementById("reserve_code_txt").innerHTML = "Código de pre-reserva<br /># "+res;
                document.getElementById("result_transaction").innerHTML = "Gracias por realizar su pre-reserva<br /><span class='txt4'>Su pre-reserva ha sido recibida exitosamente </span><br />";
                document.getElementById("result_transaction").parentNode.innerHTML += "<p style='line-height: 20px; margin-top: -47px;'><span style='font-size:10px'>*Sujeto a Disponibilidad</span></p>";
            }
        }

        if(document.getElementById("detalle")){
            var html = "";
            
            html += "<p><strong>Cliente "+item.tipo+"</strong> "+item.puntos+" Puntos</p>";

            if(item.comming != null || item.comming != null){
                html += " <p><strong>Siguiente premio a obtener:</strong> "+item.comming+"</p>";
            }
            
            html += "<p><strong>Precio Base: </strong>"+formatCurrency(item.base)+"</p>";
            html += "<p><strong>Iva: </strong>"+formatCurrency(item.iva)+"</p>";
            html += "<p><strong>Precio Primer Noche: </strong>"+formatCurrency(item.dia)+"</p>";
            if(item.descuento){
                html += "<p><strong>Descuento: </strong>"+item.descuento+"</p>";
            }
            html += "<p><strong>Precio Total: </strong>"+formatCurrency(item.total)+"</p>";
            html += "<a href='javascript:ShowDetail();'><p><strong>Detalle [+]</strong></p></a>";
            html += "<div id='detail_info'><p>"+item.detalle+"</p></div>";

            if(document.getElementById("detalle")){
                document.getElementById("detalle").innerHTML += html;
            }

            jQuery(document).ready(function() {
                $("#detail_info").slideUp(0);
                $("#detalle").fadeOut(0).fadeIn(1000, function(){
                    hideLoader();
                    LoadPayButtons();
                });
            });
        }
    }
}

/*Funcion que permite visualizar o ocultar los detalles de una reserva*/
function ShowDetail(){
    jQuery(document).ready(function() {
        if(detview){
            $("#detail_info").slideUp("slow");
            detview = false;
        }else{
            $("#detail_info").slideDown("slow");
            detview = true;
        }
    });
}

/*Funcion que permite recibir si la autenticacion es correcta*/
function GetOAuth(json){
    hideLoader();
    if(json != ""){

        var item = JSON.decode(json);

        if(item.error){
            alert(item.error);
        }else{
            var ses = item.session.split("|");

            clearInfoAuth();

            createCookie("_sessionweb",ses.join("|"),maxTimeCookie);
            createCookie("_location",window.location.href,maxTimeCookie);
            createCookie("_ustype",item.tu,maxTimeCookie);

            if(window.location.href.indexOf("reserva") != -1){
                window.document.location = "reserva2.php?ref=xcf"+getVars(5);
            }else if(window.location.href.indexOf("zona") != -1){
                window.document.location = "zona1.php?ref=xcf"+getVars(5);
            }else if(window.location.href.indexOf("millas") != -1){
                window.document.location = "millas1.php?ref=xcf"+getVars(5);
            }else{
                window.document.location = "./";
            }
        }
    }else{
        RequestShowMessage("USER_NO_VALID");
    }
}

/*Funcion que permite recibir la notificacion de si el registro ha sido correcta*/
function GetORegisterAuth(json){
   hideLoader();
   if(json != ""){

        var item = JSON.decode(json);

        if(item.error){
            alert(item.error);
        }else{
            var ses = item.session.split("|");

            clearInfoAuth();

            createCookie("_sessionweb",ses.join("|"),maxTimeCookie);
            createCookie("_location",window.location.href,maxTimeCookie);
            createCookie("_ustype",item.tu,maxTimeCookie);

            if(window.location.href.indexOf("reserva") != -1){
                window.document.location = "reserva2.php?ref=xcf"+getVars(5);
            }else if(window.location.href.indexOf("zona") != -1){
                window.document.location = "zona1.php?ref=xcf"+getVars(5);
            }else if(window.location.href.indexOf("millas") != -1){
                window.document.location = "millas1.php?ref=xcf"+getVars(5);
            }else{
                window.document.location = "./";
            }
        }
    }else{
        RequestShowMessage("NO_SAVE_USER");
    }
}

/*Funcion que permite recibir la notificacion de validar la sesion*/
function ResponseGetSession(json){
    hideLoader();
    if(json != ""){

        var item = JSON.decode(json);

        if(item.error){
            alert(item.error);
        }else{
            var loc = readCookie("_location");
            var tu = readCookie("_ustype");

            if(loc != null && tu != null){
                if(window.location.href.indexOf("reserva") != -1){
                    window.document.location = "reserva2.php?ref=xcf"+getVars(5);
                }else if(window.location.href.indexOf("zona") != -1 && (loc.indexOf("zona") != -1 || tu == 1)){
                    window.document.location = "zona1.php?ref=xcf"+getVars(5);
                }else if(window.location.href.indexOf("millas") != -1 && (loc.indexOf("millas") != -1 || tu == 2)){
                    window.document.location = "millas1.php?ref=xcf"+getVars(5);
                }
            }else{
                window.document.location = "./";
            }
        }
    }else{
        RequestShowMessage("USER_NO_VALID");
    }
}

/*Funcion que permite recibir la notificacion de validar la sesion*/
function ResponseGetSessionAlternative(json){
    hideLoader();
    if(json != ""){

        var item = JSON.decode(json);

        if(item.error){
            alert(item.error);
        }else{
            var loc = readCookie("_location");
            var tu = readCookie("_ustype");

            if(loc != null && tu != null){
                
            }else{
                window.document.location = "./";
            }
        }
    }else{
        RequestShowMessage("USER_NO_VALID");
    }
}

/*Funcion que permite recibir la notificacion e informacion de la cuenta del usuario*/
function ShowUserAccountInfo(json){
    hideLoader();
    if(json != ""){
        var item = JSON.decode(json);

        if(item.error){
            alert(item.error);
        }else{

            var profileM = document.getElementById("profileM");
            if(profileM != null){
                profileM.innerHTML = "<label>"+item.userName+"</label> "+profileM.innerHTML;
                jQuery(document).ready(function() {
                        $("#profileM").fadeIn(1000);
                });
            }

            var profile = document.getElementById("profile"+item.userProfile);
            if(profile != null){
                jQuery(document).ready(function() {
                        $("#profile"+item.userProfile).fadeIn(1000);
                });
            }

            var actual = document.getElementById("actual");
            if(actual != null){
                if(item.score > 0){
                    actual.innerHTML += "<p class='txt5'>"+item.score+" Puntos</p>";
                }else{
                    actual.innerHTML += "<p class='txt5'>0 Puntos</p>";
                }

                jQuery(document).ready(function() {
                        $("#actual").slideDown(1000);
                });
            }

            var adquiridos = document.getElementById("adquiridos");
            if(adquiridos != null){

                if(item.currentAwards.length > 0){
                    for(var i = 0;i < item.currentAwards.length; i++){
                        adquiridos.innerHTML += "<p><strong>"+item.currentAwards[i].nombre+"</strong> "+item.currentAwards[i].puntaje+" Puntos</p>";
                    }
                }else{
                     adquiridos.innerHTML += "<p><strong>Ninguno</strong></p>";
                }

                jQuery(document).ready(function() {
                        $("#adquiridos").slideDown(1000);
                });
            }

            var proximos = document.getElementById("proximos");
            if(proximos != null){
                if(item.comingAwards.length > 0){
                    for(var j = 0;j < item.comingAwards.length; j++){
                        proximos.innerHTML += "<p><strong>"+item.comingAwards[j].nombre+"</strong> "+item.comingAwards[j].puntaje+" Puntos</p>";
                    }
                }else{
                    proximos.innerHTML += "<p><strong>Ninguno</strong></p>";
                }

                jQuery(document).ready(function() {
                        $("#proximos").slideDown(1000);
                });
            }
        }
    }else{
        RequestShowMessage("USER_NO_VALID");
    }
}

/*Funcion que permite recibir la notificacion e informacion de la actualizacion de datos*/
function GetUpdateProfile(json){
   hideLoader();
   if(json != ""){

        var item = JSON.decode(json);

        if(item.error){
            alert(item.error);
        }else if(item.success){
            alert(item.success);
            cleanUpdater();
        }
    }else{
        RequestShowMessage("NO_UPDATE_USER");
    }
}

/*Funcion que permite recibir la notificacion e informacion de la recuperacion de la contraseña*/
function GetRecoveryStatus(json){
    hideLoader();
    if(json != ""){

        var item = JSON.decode(json);

        if(item.error){
            alert(item.error);
        }else if(item.success){
            alert(item.success);
            cleanRecover();
        }
    }else{
        RequestShowMessage("NO_RECOVER_PASSWORD");
    }
}

/*Funcion que permite recibir la notificacion e informacion de iniciar una reserva o reserva y pago*/
function CallBackReserve(json){
    hideLoader();
    var item = JSON.decode(json);

    if(item.error){
        alert(item.error);
    }else{
        $_type = readCookie("_ustype");
        if($_type != null){
            createCookie("_reservaRef", item.reserva, maxTimeCookie)
            if($_type == 1){
                if(document.getElementById("pay")){
                    document.getElementById("pay").innerHTML = item.form;
                    document.forms["gotopay"].submit() ;
                }
            }else if($_type == 2){
                if(item.url){
                    window.document.location = item.url;
                }
            }
        }else{
            window.document.location = "./";
        }
    }
}

/*Funcion que permite recibir la notificacion e informacion una reserva o reserva y pago exitoso*/
function CompleteReserve(json){
    hideLoader();
    var item = JSON.decode(json);

    if(item.error){
        alert(item.error);
    }else{
        if(document.getElementById("total_price_txt")){
            document.getElementById("total_price_txt").innerHTML += formatCurrency(item.price);
        }

        if(document.getElementById("new_score_txt")){
            document.getElementById("new_score_txt").innerHTML += item.scorestep;
        }

        if(document.getElementById("updated_score_txt")){
            document.getElementById("updated_score_txt").innerHTML += item.score;
        }

        if(document.getElementById("result_transaction")){
            document.getElementById("result_transaction").innerHTML = item.status;
        }

        if(document.getElementById("result_award")){
            document.getElementById("result_award").innerHTML = item.award;
        }

        if(document.getElementById("reserve_code_txt")){
            document.getElementById("reserve_code_txt").innerHTML += "# "+item.reserve_cod;
        }

        if(document.getElementById("pol_code_txt")){
            document.getElementById("pol_code_txt").innerHTML += "# "+item.pol_code;
        }

        jQuery(document).ready(function() {
            $("#reserve_info").fadeOut(0).fadeIn(1000);
        });

        clearInfoCookies();
        
    }
}

/*******************************************/




/********************************************
 *GENERAL FUNCTIONS
 ********************************************/

/*Function que permite visualizar el ajax animator*/
function showLoader(){
    $(document).ready(function() {
        $.fancybox.showActivity();
    });
}

/*Function que permite ocultar el ajax animator*/
function hideLoader(){
    $(document).ready(function() {
        $.fancybox.hideActivity();
    });
}

/*Function que permite generar las variables de consulta*/
function getVars(num){
    var v="";
    for(var i=0;i < num ; i++){
        v += "&p"+i+"sdasd3"+i+"="+MD5(new Date().getTime().toString());
    }
    return v;
}

/*Function que permite realizar un llamado de mensaje*/
function RequestShowMessage(tag){
    var vars,url;
    vars = "tag="+tag+getVars(5);
    url = "Fachada/Message.php?";
    HttpRequest(url+vars,ShowAlert);
}

/*Funcion que permite realizar la conversion de un numero en formato moneda*/
function formatCurrency(num){
    num = num.toString().replace(/\$|\,/g,'');

    if (isNaN(num))
    num = 0;

    var signo = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    centavos = num % 100;
    num = Math.floor(num / 100).toString();

    if (centavos < 10)
    centavos = '0' + centavos;

    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
    num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));

    return (((signo) ? '' : '-') + '$' + num + '.' + centavos);
}

/*Funcion que permite obtener los parametros de la URL*/
function getUrlVars() {
	var vars = {};
	var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
		vars[key] = value;
	});
	return vars;
}


/*******************************************/

