﻿var gdes = {};
gdes.item = {};
gdes.padre = {}


gdes.nivel = {};
gdes.itemData = {};
gdes.itemSelect = {};
gdes.granpa = '0';
gdes.httpreferer = function (modo, url) {
    $.ajax({
        type: "POST",
        url: "Valida/httpreferer.ashx",
        data: 'modo=' + modo + "&url=" + url + '&uid=' + gdes.uid(),
        async: false,
        success: function (data) {
            if (modo != 'set') {
                if (data == '')
                    self.location.href = 'default.aspx';
                else
                    self.location.href = unescape(data);
            }
        }
    });
}

gdes.init = function (item, child, ubicacion, volver) {
    if (volver != null && volver != undefined && volver != '') {
        gdes.httpreferer('set', escape(volver));
    }

    //titulo de categorias
    if (child != 0)
        $('h1[id$=titulo_pagina]').html('CATEGORIA DE ' + $('#item_' + item).find('a').html());
    else
        if (ubicacion == 'p' || ubicacion == 'pVer')
            $('h1[id$=titulo_pagina]').html('PRODUCTO');
        else
            if (ubicacion == 'search')
                $('h1[id$=titulo_pagina]').html('BUSQUEDA RAPIDA');
            else
                $('h1[id$=titulo_pagina]').html('LISTADO DE PRODUCTOS DE ' + $('#item_' + item).find('a').html());

    try {
        $('h1[id$=titulo_pagina]').html($('h1[id$=titulo_pagina]').html().replace(":", "").replace(":", ""));
    } catch (ex) { }
    //$('#item_' + item).find('a').attr('style', 'font-weight:bold;');

    if (item == '' || item == undefined)
        item = '2';

    if (ubicacion == 'c')
        item = '2';

    //Default main zona marqueting

    $('div[class=centro_home]').html("<img src=\"Adjuntar/MuestraImagenxItem.aspx?id=" + item + "&modo=IMGZ\" alt=\"Tienda Vanzuli\" width='580px' height='162px' />");

    //Zona Marketing items con Imagen
    if (child != 0) {
        $('div[id$=zona_marketing_imagen]').html("<img src=\"Adjuntar/MuestraImagenxItem.aspx?id=" + item + "&modo=IMGZ\" alt=\"Tienda Vanzuli\" width='577px' height='107px'/>");
        $('div[id$="zona_marketing"]').attr("style", "display:;");
    } else {
        if (gdes.granpa != null && gdes.granpa != undefined)
            if (gdes.granpa == '1') {
                $('div[id$=zona_marketing_imagen]').html("<img src=\"Adjuntar/MuestraImagenxItem.aspx?id=" + item + "&modo=IMGZ\" alt=\"Tienda Vanzuli\" width='577px' height='107px'/>");
                $('div[id$="zona_marketing"]').attr("style", "display:;");
            } else {
                $('div[id$="zona_marketing"]').attr("style", "display:none;");
            }
    }



    //breadcrub
    if ($('a#_item_' + item).attr('path') != null && $('a#_item_' + item).attr('path') != undefined)
        $('div[id$=breadcrub]').html('Usted se encuentra en: > <a href="default.aspx">Inicio</a> > ' + $('a#_item_' + item).attr('path'));
    else
        $('div[id$=breadcrub]').html('Usted se encuentra en: > <a href="default.aspx">Inicio</a> > ');

    if (ubicacion == 'pVer')
        $('div[id$=breadcrub]').html('Usted se encuentra en: > <a href="default.aspx">Inicio</a> > <a href="carro.aspx">Carro</a> ');

    if (ubicacion == 'search')
        $('div[id$=breadcrub]').html('Usted se encuentra en: > <a href="default.aspx">Inicio</a> > Busqueda Rapida');

    $("a[id$='stock']").cluetip({ activation: 'click', width: 150, sticky: true, closePosition: 'bottom' });

};

gdes.uid = function () {
    return (new Date()).valueOf();
};

gdes.addCarro = function (idProducto) {
    self.location.href = "addcarro.aspx?id=" + idProducto + "&cantidad=1";
};
gdes.verStock = function (idProducto) {
    $.ajax({
        type: "POST",
        url: "Valida/verStockVendedor.ashx",
        data: 'VZ=' + idProducto + '&uid=' + gdes.uid(),
        async: false,
        success: function (data) {

            $('a[id$="stock"]').attr("title", data);


        }
    });
};

gdes.ingresarClienteVendedor = function () {

    $.ajax({
        type: "POST",
        url: "Valida/ingresaCliente.ashx",
        data: 'user=' + $('select[id$="cliente"]').val() + "&MODO=1"+ '&vendedor=1&uid=' + gdes.uid(),
        async: false,
        success: function (data) {
            if (data != 'N') {
                self.location.href = 'default.aspx';
            }
            else { alert("Ocurrio un problema, vuelva a intentar"); }
        }
    });
};


gdes.ingresarCliente = function () {
    $.ajax({
        type: "POST",
        url: "Valida/ValidaClienteIngreso.ashx",
        data: 'user=' + $('input[id$="login_username"]').val() + '&pass=' + $('input[id$=login_password]').val() + '&uid=' + gdes.uid(),
        async: false,
        success: function (data) {

            if (data.split('|')[1] != '3') {
                alert(data.split('|')[2]);
            }
            else {
                $.ajax({
                    type: "POST",
                    url: "Valida/ingresaCliente.ashx",
                    data: 'user=' + $('input[id$="login_username"]').val() + "&MODO=" + data.split('|')[0] + '&uid=' + gdes.uid(),
                    async: false,
                    success: function (data) {
                        if (data != 'N') {

                            self.location.href = 'default.aspx';


                        }
                        else { alert("Ocurrio un problema, vuelva a intentar"); }
                    }
                });
            }
        }
    });

};

gdes.ingresarCliente2 = function () {
    $.ajax({
        type: "POST",
        url: "Valida/ValidaClienteIngreso.ashx",
        data: 'user=' + $('input[id$="login_username2"]').val() + '&pass=' + $('input[id$=login_password2]').val() + '&uid=' + gdes.uid(),
        async: false,
        success: function (data) {

            if (data.split('|')[1] != '3') {
                alert(data.split('|')[2]);
            }
            else {
                $.ajax({
                    type: "POST",
                    url: "Valida/ingresaCliente.ashx",
                    data: 'user=' + $('input[id$="login_username2"]').val() + "&MODO=" + data.split('|')[0] + '&uid=' + gdes.uid(),
                    async: false,
                    success: function (data) {
                        if (data != 'N') {

                            self.location.href = 'default.aspx';


                        }
                        else { alert("Ocurrio un problema, vuelva a intentar"); }
                    }
                });
            }
        }
    });

};

gdes.addCarroCodigo = function () {
    if ($('input[id$="CodigoValido"]').val() == "1") {

        $.ajax({
            type: "POST",
            url: "Valida/addCarro.ashx",
            data: 'id=' + $('input[id$="iIdProducto"]').val() + '&cantidad=' + $('input[id$="buscar_cantidad"]').val() + '&uid=' + gdes.uid(),
            async: false,
            success: function (data) {
                if (data != 'N')
                    self.location.href = 'carro.aspx';
                else {

                    self.location.href = 'iniciarsession.aspx';
                }

            }
        });
    }
    else {
        alert("el código del producto no es valido, favor ingrese un valor valido")
    }
};

gdes.ValidaProductoCarro = function (codigo) {
    $('#detalleProducto').html('<img src="images/ajax-loading.gif"/>');
    $.ajax({
        type: "POST",
        url: "Valida/ValidaProductoBusqueda.ashx",
        data: 'codigo=' + codigo + '&uid=' + gdes.uid(),
        async: false,
        success: function (data) {
            if (data.split("|")[0] == '1') {
                $('#detalleProducto').html("Producto: " + data.split("|")[1] + ", $" + data.split("|")[2]);
                $('input[id$="CodigoValido"]').val(data.split("|")[0]);
                $('input[id$="iIdProducto"]').val(data.split("|")[3]);

            } else {
                if (data.split("|")[0] == '0') {
                    $('#detalleProducto').html(data.split("|")[1]);
                    $('input[id$="CodigoValido"]').val(data.split("|")[0]);
                    $('input[id$="iIdProducto"]').val('');
                }
            }
        }
    });
};



gdes.ValidaRut = function (codigo, objeto) {

    $.ajax({
        type: "POST",
        url: "Valida/ValidaRut.ashx",
        data: 'rut=' + codigo + '&uid=' + gdes.uid(),
        async: false,
        success: function (data) {
            if (data.split("|")[0] == '1') {
                alert(data.split("|")[1]);
                $("input[id$=" + objeto + "]").val('');
                return false;
            }
        }
    });

};

gdes.CambioCantidad = function (value, idLinea, idCarro) {

    $.ajax({
        type: "POST",
        url: "Valida/UpdateCatidadCarro.ashx",
        data: 'Cantidad=' + value + '&idLinea=' + idLinea + '&idCarro=' + idCarro + '&uid=' + gdes.uid(),
        async: false,
        success: function (data) {
            if (data != 'N') {
                eo_Callback("CallDetalleCarro", "");
            }
            else {
                alert("Verifique la información ingresada, esta provocando conflictos");
            }

        }
    });
};

gdes.ConfirmaBorrar = function () {
    if (confirm('¿Eliminar productos seleccionados?')) {

        $('input[type=checkbox][id$="_prductoelimina"]').each(function () {
            if ($(this).is(':checked')) {

                $.ajax({
                    type: "POST",
                    url: "Valida/DeleteProductoCarro.ashx",
                    data: 'idLinea=' + $(this).attr('linea') + '&idCarro=' + $(this).attr('carro') + '&uid=' + gdes.uid(),
                    async: false,
                    success: function (data) {
                        if (data == 'N')
                            return false;
                    }
                });
            }
        });

        eo_Callback("CallDetalleCarro", "");
    }
};


gdes.ConfirmaBorrarCarros = function () {
    if (confirm('¿Eliminar carros seleccionados?')) {

        $('input[type=checkbox][id$="_carroelimina"]').each(function () {
            if ($(this).is(':checked')) {

                $.ajax({
                    type: "POST",
                    url: "Valida/DeleteCarro.ashx",
                    data: 'idCarro=' + $(this).attr('carro') + '&uid=' + gdes.uid(),
                    async: false,
                    success: function (data) {
                        if (data == 'N')
                            return false;
                    }
                });
            }
        });

        eo_Callback("CallCarro", "");
    }
};

gdes.EnviarPedido = function (idCarro, lineasPedido) {

    if (lineasPedido > 0) {
        $.ajax({
            type: "POST",
            url: "Valida/CarroUpdate.ashx",
            data: 'estado=1&idCarro=' + idCarro + '&Comentarios=' + $('textarea[id$="ComentariosCarro"]').val() + '&direccion=' + $("select[id$='direcciondespacho'] option:selected").text() + '&uid=' + gdes.uid(),
            async: false,
            success: function (data) {
                if (data.split('|')[0] != 'N') {
                    if (data.split('|')[1] == "correcto") {
                        alert("Su pedido ha sido enviado correctamente"); self.location.href = 'mispedidos.aspx';
                    } else
                        alert(data.split('|')[1])

                }
                else
                    alert("Ocurrio un problema, volver a intentar");
            }
        });
    } else {
        alert("El pedido no contiene lineas");
    }

};



gdes.EnviarPedidoMail = function (idCarro) {

    if ($('input[id$="MailTO"]').val() != "") {
        $.ajax({
            type: "POST",
            url: "Valida/CarroMail.ashx",
            data: 'estado=1&idCarro=' + idCarro + '&Comentarios=' + $('textarea[id$="ComentariosCarro"]').val() + '&Asunto=' + $('input[id$="Asunto"]').val() + '&TO=' + $('input[id$="MailTO"]').val() + '&uid=' + gdes.uid(),
            async: false,
            success: function (data) {
                if (data.split('|')[0] != 'N') {

                    alert("El carro ha sido enviado por mail exitosamente"); self.location.href = 'carro.aspx';

                }
                else
                    alert("Ocurrio un problema, volver a intentar");
            }
        });
    } else {
        alert("Debe ingresar destinatarios");
    }

};

gdes.LlenaData = function (id, modo) {
    var option = "";
    $.ajax({
        type: "POST",
        url: "Valida/llenFiltros.ashx",
        data: 'item=' + id + '&modo=' + modo + '&uid=' + gdes.uid(),
        async: false,
        success: function (data) {
            option = data;
        }
    });
    return option;
};

gdes.verCarro = function (idCarro) {
    self.location.href = 'carro.aspx?idCarro=' + idCarro;
};

gdes.ClientesUsuario = function (Accion, Rut, Nombre, Mail, Password) {
    var resultado = "";
    $.ajax({
        type: "POST",
        url: "Valida/ClienteUsuario.ashx",
        data: 'Accion=' + Accion + '&Rut=' + Rut + '&Nombre=' + Nombre + "&Mail=" + Mail + "&Password=" + Password + '&uid=' + gdes.uid(),
        async: false,
        success: function (data) {
            resultado = data;
        }
    });
    return resultado;
};

gdes.DireccionUsuario = function (Accion, Direccion, idCLienteDir, region, comuna) {
    var resultado = "";
    $.ajax({
        type: "POST",
        url: "Valida/DireccionUsuario.ashx",
        data: 'Accion=' + Accion + '&Direccion=' + Direccion + '&idCLienteDir=' + idCLienteDir + '&region=' + region + '&comuna=' + comuna + '&uid=' + gdes.uid(),
        async: false,
        success: function (data) {
            resultado = data;
        }
    });
    return resultado;
};


gdes.DireccionUsuarioback = function (Accion, Direccion, idCLienteDir, region, comuna, id) {
    alert('Accion=' + Accion + '&Direccion=' + Direccion + '&idCLienteDir=' + idCLienteDir + '&region=' + region + '&comuna=' + comuna + '&idcliente=' + id + '&uid=' + gdes.uid())
    var resultado = "";
    $.ajax({
        type: "POST",
        url: "../Valida/DireccionUsuario.ashx",
        data: 'Accion=' + Accion + '&Direccion=' + Direccion + '&idCLienteDir=' + idCLienteDir + '&region=' + region + '&comuna=' + comuna + '&idcliente=' + id + '&uid=' + gdes.uid(),
        async: false,
        success: function (data) {
            resultado = data;
        }
    });
    return resultado;
};

gdes.ReutilizaPedido = function (idCarro) {

    if (confirm("esta opcion agregara los productos del pedido en carro activo, desea continuar")) {
        $.ajax({
            type: "POST",
            url: "Valida/reutilizarPedido.ashx",
            data: 'idCarro=' + idCarro + '&uid=' + gdes.uid(),
            async: false,
            success: function (data) {
                if (data != 'N')
                    self.location.href = 'carro.aspx';
            }
        });

    }
}
