﻿var info_carrito;
var info_reservas;
var total_plan;
var lista_colores;

function buscar_carrito(reserva) {
    $.ajax({
        type: "POST",
        url: "MiCarrito.aspx/buscarCarrito",
        data: "{reserva:'" + reserva + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
            data.d = data.d.replace(/\n/g, " ").replace(/\r/g, " ");
            info_carrito = $.evalJSON(data.d);
            if (reserva != "") {
                $("#div_reservaactual").html('<strong>RESERVA: ' + reserva + '</strong>');
            }
            procesar_template_carrito('#div_resultadocarrito', 'S');
        }
    });
}

function procesar_template_carrito(nombreDiv, edicion) {
    if (info_carrito.Carrito.FilaReservas[0] != null) {
        if (edicion == 'S') {
            $(nombreDiv).dialog('close');
            $(nombreDiv).dialog('destroy');
        }

        $(nombreDiv).setTemplateURL('templates/carrito/resultado_carrito.html', null, { filter_data: false });
        $(nombreDiv).setParam('Estado', info_carrito.Carrito.FilaReservas[0].Estado);
        $(nombreDiv).setParam('Edicion', edicion);
        $(nombreDiv).processTemplate(info_carrito);

        if (edicion == 'S') {
            mostrar_dialogo_carrito(nombreDiv);
        }
        else {
            $(nombreDiv).hide();
        }
    }
}

function mostrar_dialogo_carrito(nombreDiv) {
    $(nombreDiv).show();
    $(nombreDiv).dialog({
        bgiframe: true,
        resizable: false,
        modal: true,
        width: 750,
        zIndex: 0,
        buttons: { 'Cerrar': function() { $(this).dialog('close'); } }
    });
}

function llenar_listacolores() {
    WSCarrito.listaColores(listacolores_callback);
}

function listacolores_callback(resultado) {
    if (resultado != '') {
        var Json = eval('(' + resultado + ')');
        lista_colores = Json;
    }
}

function borrarReservaHotel(codigo) {
    confirmarBorrado(codigo, "borrarReservaHotel", "Hoteles");
}

function borrarReservaTransfer(codigo) {
    confirmarBorrado(codigo, "borrarReservaTransfer", "Transfers");
}

function borrarReservaTour(codigo) {
    confirmarBorrado(codigo, "borrarReservaTour", "Tours");
}

function borrarReservaPlan(codigo) {
    confirmarBorrado(codigo, "borrarReservaPlan", "Planes");
}

function confirmarBorrado(codigo, accion, tipo) {
    $("#dialogo_alerta").dialog('close');
    $("#dialogo_alerta").dialog('destroy');
    $("#dialogo_alerta").html("Quitar elemento de la reserva?");
    $("#dialogo_alerta").attr("title", "Reserva " + tipo);
    $("#dialogo_alerta").show();
    $("#dialogo_alerta").dialog({
        resizable: false,
        modal: true,
        width: 200,
        zIndex: 0,
        buttons: {
            'Cancelar': function() {
                $(this).dialog('close');
            },
            'Aceptar': function() {
                borrarReserva(codigo, accion, tipo);
                $(this).dialog('close');
            }
        }
    });
}

function borrarReserva(codigo, accion, tipo) {
    $.ajax({
        type: "POST",
        url: "MiCarrito.aspx/" + accion,
        data: "{codigo:'" + codigo + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
            data.d = data.d.replace(/\n/g, " ").replace(/\r/g, " ");
            var resultado = $.evalJSON(data.d);
            borrar_reserva_callback(resultado, tipo);
        }
    });
}

function borrar_reserva_callback(resultado, tipo) {
    if (resultado == 'ERROR')
        alerta('No se pudo quitar la reserva de ' + tipo);
    else
        buscar_carrito(resultado);
}

function rowspanRoomingList() {
    var elemento = info_carrito.Carrito.FilaReservas[0].RoomingList[0].FilaRoomingList;
    return (elemento.length + 1); //Inlcuir encabezados + pie
}

function filasRoomingList() {
    if (info_carrito.Carrito.FilaReservas[0].RoomingList[0].FilaRoomingList[0] != undefined)
        return info_carrito.Carrito.FilaReservas[0].RoomingList[0].FilaRoomingList.length;
    else
        return 0;
}

function actualizarDatos() {
    var formParamsRoomingList = $('#frm_roominglistcarrito').serialize();
    if (formParamsRoomingList != '') {
        var JSONRoomingList = params2json(formParamsRoomingList);
        actualizarRoomingList(JSONRoomingList);
    } else {
        var formParamsDatosReserva = $('#frm_datosreservacarrito').serialize();
        if (formParamsDatosReserva != '') {
            var JSONDatosReserva = params2json(formParamsDatosReserva);
            actualizarDatosReserva(JSONDatosReserva);
        }
    }
}

function actualizarRoomingList(JSON) {
    $.ajax({
        type: "POST",
        url: "MiCarrito.aspx/actualizarRoomingList",
        data: "{datos:'" + JSON + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
            data.d = data.d.replace(/\n/g, " ").replace(/\r/g, " ");
            var resultado = $.evalJSON(data.d);
            roominglist_callback(resultado);
        }
    });
}

function actualizarDatosReserva(JSON) {
    $.ajax({
        type: "POST",
        url: "MiCarrito.aspx/actualizarDatosReserva",
        data: "{datos:'" + JSON + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
            data.d = data.d.replace(/\n/g, " ").replace(/\r/g, " ");
            var resultado = $.evalJSON(data.d);
            actualizardatos_callback(resultado);
        }
    });
}

function roominglist_callback(resultado) {
    if (resultado == 'ERROR')
        alerta('No se pudo actualizar la informaci&oacute;n del rooming list.');
    else {
        var formParamsDatosReserva = $('#frm_datosreservacarrito').serialize();
        var JSONDatosReserva = params2json(formParamsDatosReserva);
        actualizarDatosReserva(JSONDatosReserva);
    }
}

function actualizardatos_callback(resultado) {
    if (resultado.status == "OK") {
        alerta('Los datos fueron actualizados');
        buscar_ultimasreservas();
    }
    else {
        alerta(resultado.mensaje);
    }
}

function mostrarOcutarDiv(nombre) {
    $("#" + nombre).toggle();
}

function buscar_seguimiento(reserva) {
    $.ajax({
        type: "POST",
        url: "MiCarrito.aspx/buscarSeguimiento",
        data: "{reserva:'" + reserva + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
            data.d = data.d.replace(/\n/g, " ").replace(/\r/g, " ");
            var resultado = $.evalJSON(data.d);
            seguimiento_callback(resultado);
        }
    });
}

function seguimiento_callback(resultado) {
    $("#div_seguimiento").dialog('destroy');
    if (resultado != '') {
        if (resultado.Reservas != null) {
            $("#div_seguimiento").setTemplateURL('templates/carrito/seguimiento_reserva.html', null, { filter_data: false });
            $("#div_seguimiento").processTemplate(resultado);
            $("#div_seguimiento").corner();
            $("#div_seguimiento").show();
            new AjaxUpload('#href_files_seguimiento', {
                action: 'utilidades/upload.ashx',
                name: 'myfile',
                onComplete: function(file) {
                    $('<li></li>').appendTo($('#ol_lista_archivos')).text(file);
                },
                onSubmit: function() {
                    // allow only 1 upload
                    this.disable();
                }

            });
        }
    }

    $("#div_seguimiento").dialog({
        bgiframe: true,
        resizable: false,
        modal: true,
        width: 520,
        zIndex: 0,
        buttons: {
            'Cancelar': function() {
                $(this).dialog('close');
            },
            'Aceptar': function() {
                agregarSeguimiento();
                $(this).dialog('close');
            }
        }
    });
}

function agregarSeguimiento() {
    if ($('#segr_observacion').val() != '') {
        var paramsFormSeguimiento = $('#frm_seguimiento').serialize();
        var JSONDatosSeguimiento = params2json(paramsFormSeguimiento);
        $.ajax({
            type: "POST",
            url: "MiCarrito.aspx/agregarSeguimiento",
            data: "{data:'" + JSONDatosSeguimiento + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data) {
                data.d = data.d.replace(/\n/g, " ").replace(/\r/g, " ");
                var resultado = $.evalJSON(data.d);
                agregarseguimiento_callback(resultado);
            }
        });
    }
}

function agregarseguimiento_callback(resultado) {
    if (resultado.status == "OK") {
        buscar_ultimasreservas();
    }
    else {
        alerta(res.mensaje);
    }
}

function cambiarEstado(reserva, estado, nombre) {
    $("#div_segcambioestado").dialog('destroy');
    $("#div_segcambioestado").setTemplateURL('templates/carrito/cambio_estado_reserva.html', null, { filter_data: false });
    $("#div_segcambioestado").setParam('Reserva', reserva);
    $("#div_segcambioestado").setParam('Estado', estado);
    $("#div_segcambioestado").setParam('Nombre', nombre);
    $("#div_segcambioestado").processTemplate();
    $("#div_segcambioestado").corner();
    $("#div_segcambioestado").show();
    $("#div_segcambioestado").dialog({
        bgiframe: true,
        resizable: false,
        modal: true,
        width: 520,
        zIndex: 0,
        buttons: {
            'Cancelar': function() {
                $(this).dialog('close');
            },
            'Aceptar': function() {
                cambiarEstadoReserva();
                $(this).dialog('close');
            }
        }
    });
}

function cambiarEstadoReserva() {
    var paramsFormCambioEstado = $('#frm_segcambioestado').serialize();
    var JSONDatosCambioEstado = params2json(paramsFormCambioEstado);
    $.ajax({
        type: "POST",
        url: "MiCarrito.aspx/cambiarEstado",
        data: "{data:'" + JSONDatosCambioEstado + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
            data.d = data.d.replace(/\n/g, " ").replace(/\r/g, " ");
            var resultado = $.evalJSON(data.d);
            cambioestado_callback(resultado);
        }
    });
}

function cambioestado_callback(resultado) {
    if (resultado.status == "OK") {
        alerta('Cambio de estado realizado con exito.');
        buscar_ultimasreservas();
    }
    else if (resultado.status == "ERROR") {
        alerta(resultado.mensaje);
    }
}

function inputEditable(estado) {
    if ((estado == 'C') || (estado == 'S') || (estado == 'T') || (estado == 'K'))
        return '';
    else
        return 'readonly';
}

function mostrar_carrito() {
    $('#div_cargandocarrito').jqm();
    $('#span_mensajecarrito').html('Cargando carrito');
    buscar_carrito('');
}

function imprimir_carrito(titulo) {
    procesar_template_carrito('#div_templatecarrito', 'N');
    $("#div_imprcarrito_N").printArea({ mode: "popup", popHt: 500, popWd: 750, popTitle: titulo });
}

function mail_carrito() {
    var paramsFrmMailCarrito = $('#frm_mailcarito').serialize();
    var JSONDatosMailCarrito = params2json(paramsFrmMailCarrito).replace(/}/g, "").replace(/\"/g, "'");
    procesar_template_carrito('#div_templatecarrito', 'N');
    
    var mail_body = $("#div_imprcarrito_N").html().replace(/\n/g, "").replace(/\r/g, "");
    JSONDatosMailCarrito = JSONDatosMailCarrito + ",'mail_body':'" + escape(mail_body) + "'}";
    $('#div_mailcarrito').hide();

    $.ajax({
        type: "POST",
        url: "MiCarrito.aspx/enviarMailCarrito",
        data: "{data:\"" + JSONDatosMailCarrito + "\"}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
            data.d = data.d.replace(/\n/g, " ").replace(/\r/g, " ");
            var resultado = $.evalJSON(data.d);
            mail_callback(resultado);
        }
    });
}

function mail_callback(resultado) {
    if (resultado.status == "OK") {
        alerta(resultado.mensaje);
    }
    else if (resultado.status == "ERROR") {
        alerta(resultado.mensaje);
    }
}

function mail_voucher() {

    var paramsFrmMailVoucher = $('#frm_mailvoucher').serialize();
    var JSONDatosMailVoucher = params2json(paramsFrmMailVoucher);
    $('#div_mailvoucher').hide();

    $.ajax({
        type: "POST",
        url: "MiCarrito.aspx/enviarMailVoucher",
        data: "{data:'" + JSONDatosMailVoucher + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
            data.d = data.d.replace(/\n/g, " ").replace(/\r/g, " ");
            var resultado = $.evalJSON(data.d);
            mail_callback(resultado);
        }
    });
}

function verVouchers(reserva, localizador, mailCliente) {
    var JSON = "{'reserva':'" + reserva + "','localizador':'" + localizador + "','mailcliente':'" + escape(mailCliente) + "'}";
    $.ajax({
        type: "POST",
        url: "MiCarrito.aspx/urlVouchers",
        data: "{data:\"" + JSON + "\"}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
            data.d = data.d.replace(/\n/g, " ").replace(/\r/g, " ");
            if (data.d != "") {
                vouchers_callback($.evalJSON(data.d));
            } else {
                alerta("No se han generado los voucher.", "Vouchers");
            }
        }
    });
}

function vouchers_callback(resultado) {

    $("#div_vouchers").dialog('destroy');
    if (resultado != '') {
        if (resultado.Vouchers.UrlsVoucher[0] != null) {
            $("#div_vouchers").setTemplateURL('templates/carrito/resultado_vouchers.html', null, { filter_data: false });
            $("#div_vouchers").processTemplate(resultado);
            $("#div_vouchers").corner();
            $("#div_vouchers").show();
        }
    }

    $("#div_vouchers").dialog({
        bgiframe: true,
        resizable: false,
        modal: true,
        width: 300,
        zIndex: 0,
        buttons: {
            'Cerrar': function() {
                $(this).dialog('close');
            }
        }
    });
}

function verOrdenServicio(reserva, localizador) {
    var JSON = "{'reserva':'" + reserva + "','localizador':'" + localizador + "'}";
    $.ajax({
        type: "POST",
        url: "MiCarrito.aspx/urlOrdenServicio",
        data: "{data:\"" + JSON + "\"}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {

            data.d = data.d.replace(/\n/g, " ").replace(/\r/g, " ");

            if (data.d != "") {
                var ordenes_servicio = $.evalJSON(data.d);
                ordenes_callback(ordenes_servicio);
                //document.location = ordenes_servicio.Ordenes.UrlsOrdenes[0].UrlOrden;
            }
            else {
                alerta('No se ha generado la orden de servicio.', 'Orden de servicio');
            }
        }
    });
}

function ordenes_callback(resultado) {

    $("#div_ordenes").dialog('destroy');
    if (resultado != '') {
        if (resultado.Ordenes.UrlsOrdenes[0] != null) {
            $("#div_ordenes").setTemplateURL('templates/carrito/resultado_orden_servicio.html', null, { filter_data: false });
            $("#div_ordenes").processTemplate(resultado);
            $("#div_ordenes").corner();
            $("#div_ordenes").show();
        }
    }

    $("#div_ordenes").dialog({
        bgiframe: true,
        resizable: false,
        modal: true,
        width: 300,
        zIndex: 0,
        buttons: {
            'Cerrar': function() {
                $(this).dialog('close');
            }
        }
    });
}


function mail_orden() {

    var paramsFrmMailOrden = $('#frm_mailorden').serialize();
    var JSONDatosMailOrden = params2json(paramsFrmMailOrden);
    $('#div_mailorden').hide();

    $.ajax({
        type: "POST",
        url: "MiCarrito.aspx/enviarMailOrden",
        data: "{data:'" + JSONDatosMailOrden + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
            data.d = data.d.replace(/\n/g, " ").replace(/\r/g, " ");
            var resultado = $.evalJSON(data.d);
            mail_callback(resultado);
        }
    });
}
