﻿//****************************************************************************
var win = null;
var dmi_Err_generico = "No fue posible llevar a cabo la acción";
var dmi_Msg_NoHayPrepedidoTrabajoCrearNuevo = "No hay ningún PrePedido de trabajo, puede aceptar para crear uno nuevo o cancelar y seleccionar alguno de los existentes. ¿Desea crear un nuevo PrePedido?"
var url_actual;
function AbrirVentana(pagina, tipo, ancho, alto, nombre) {

    var str = "height=" + alto + ",innerHeight=" + alto;
    str += ",width=" + ancho + ",innerWidth=" + ancho;

    if (window.screen) {
        var ah = screen.availHeight - 30;
        var aw = screen.availWidth - 10;

        var xc = (aw - ancho) / 2;
        var yc = (ah - alto) / 2;

        str += ",left=" + xc + ",screenX=" + xc;
        str += ",top=" + yc + ",screenY=" + yc;
    }
    if (tipo == "I") {
        str += ",location=no,directories=no,resizable=yes,status=no,toolbar=yes,menubar=yes,scrollbars=yes"
        win = window.open(pagina, nombre, str);
    }
    else {
        if (tipo == "P") {
            str += ",location=no,directories=no,resizable=yes,status=no,toolbar=no,menubar=no,scrollbars=yes"
            win = window.open(pagina, nombre, str);
        }
        else {
            str += ",location=no,directories=no,resizable=no,status=no,toolbar=no,menubar=no,scrollbars=no"
            win = window.open(pagina, nombre, str);
        }
    }
    win.focus();
}


/**************************************************************************************
*  Function    : Adaptación de adjustInteger()                                       *
*  Description : onkeyup event handler to increment/decrement integer fields.        *
*                Adaptada para no permitir numeros menores de 1                      *
*               21/7/2009 B2B09-0005 Adaptada para limitar números menores y mayores *
*  Parameters  : aInputTextbox, html textbox containing the integer value to be      *
*                    incremented/decremented                                         *
*  ISD Feature : "Increment/Decrement Numerical Fields"                              *
*  Authors     : Samson Wong                                                         *
**************************************************************************************/
function adjustInteger1(aInputTextbox, aKeyCode, limite) {
    // if (justDoIt == true)
    // {
    // var lWhichCode = event.keyCode;
    var lWhichCode = aKeyCode;

    // if up arrow, or plus key...
    if ((lWhichCode == 38) || (lWhichCode == 107)) {
        // strip "+" character if it has been appended to integer value
        while ((lWhichCode == 107) && (aInputTextbox.value.charAt(aInputTextbox.value.length - 1) == "+")) {
            aInputTextbox.value = (aInputTextbox.value).substring(0, aInputTextbox.value.length - 1);
        }

        // if currency value not initialized or contains invalid characters...
        if ((aInputTextbox.value == "") || (isNaN(aInputTextbox.value))) {
            // set initial value
            aInputTextbox.value = "1";
        }
        else {
            if (parseInt(new Number(aInputTextbox.value) + 1) <= limite)
            {
            // myAlert("adjustInteger(aInputTextbox.value=" + aInputTextbox.value + ")");
               aInputTextbox.value = new Number(aInputTextbox.value) + 1;
            }
            else
            {
                alert(dmi_Msg_ConsultarComercial);
            }
        }
    }
    // if down arrow, or minus key...
    else if ((lWhichCode == 40) || (lWhichCode == 109)) {
        // strip "-" character if it has been appended to integer value
        while ((lWhichCode == 109) && (aInputTextbox.value.charAt(aInputTextbox.value.length - 1) == "-")) {
            aInputTextbox.value = (aInputTextbox.value).substring(0, aInputTextbox.value.length - 1);
        }

        // if currency value not initialized or contains invalid characters...
        if ((aInputTextbox.value == "") || (isNaN(aInputTextbox.value))) {
            // set initial value
            aInputTextbox.value = "1";
        }
        else {
            // myAlert("adjustInteger(aInputTextbox.value=" + aInputTextbox.value + ")");
            if (Number(aInputTextbox.value) > limite) {
                aInputTextbox.value = new Number(aInputTextbox.value) - 1;
            }
        }
    }
    // }
}

// redirect nos va a indicar si tras la creación debemos redirigir al usuario hasta él o no
// p.e. en el caso de añadir nota no redirigiremos
var cesta_pedido = 0;
var redirect_NuevoPedido = true;
var nueva_nota = false;
var _imgButton;
var _articulo;
var _atributo1;
var _atributo2;
var _atributo3;
var _atributo4;
var _atributo5;
var _descripcion_libre;
var _cajas_surtidas;
var _bultos;
var _serie;
var _unid_venta;
var _surtido;
var _observaciones;
function NuevoPedidoSeleccionarCliente() {
    AbrirVentana('../Clientes/wSearchClientes.aspx?Target=*&field=', 'P', '800', '600', 'SearchCliente');
}

// aunque en esta página no tienen uso razon_social y nom_tienda, se implementan por
// compatibilidad
function CrearPedidoClienteBuscado(field, cliente, razon_social, delegacion, nom_tienda) {
    if (delegacion == '') {
        delegacion = '0';
    }
    NuevoPedido(cliente, delegacion);
}

function NuevoPedido(cliente, delegacion) {
    B2C.wsGeneral.CrearPrepedido(cliente, delegacion, NuevoPedidoCallBack, ErrorHandlerGenerico, TimeOutHandlerGenerico);
}

function NuevoPedidoCallBack(result) {
    var datos = eval("(" + result + ")");
    if (datos.pedido > 0) {    
        if (nueva_nota == true) {
            NuevaNota(_imgButton, _articulo, _atributo1, _atributo2, _atributo3, _atributo4, _atributo5, _descripcion_libre, _cajas_surtidas, _bultos, _serie, _unid_venta, _surtido, _observaciones);
        }
        if (redirect_NuevoPedido == true) {
            window.location.href = "../Prepedidos/EditB2BfhipecPage.aspx?prepedido=" + datos.pedido;
        }
        else {  
            if (nueva_nota == false) {
                // refrescar información que se está mostrando de la cesta
               B2C.wsGeneral.GetHTMLInfoCesta(GetHTMLInfoCestaCallBack, ErrorHandlerGenerico, TimeOutHandlerGenerico);
            }
            if (datos.ClienteTrabajoVaria == true) {
                // se ha establecido un cliente de trabajo distinto, hay que recargar página:
                window.location.reload();
            }
        }
        cesta_pedido = datos.pedido;
    }
    else {
        alert(dmi_Err_generico + ": " + datos.error);
    }
    redirect_NuevoPedido = true;
    nueva_nota = false;
}

// función para el caso de que se haya seleccionado añadir artículo a cesta y no haya un
// prepedido de trabajo
function NuevoPedidoNuevaNota(imgButton, articulo, atributo1, atributo2, atributo3, atributo4, atributo5, descripcion_libre, cajas_surtidas, bultos, serie, unid_venta, surtido, observaciones, cliente, delegacion) {
    // no obstante podría darse el caso de que hayamos creado el prepedido en una acción anterior de esta función
    // pero al no haberse refrescado página el onclick de pedir sigue llamando a este código, por lo que nos basamos en el valor de cesta_pedido
    if (cesta_pedido == 0) {
        if (confirm(dmi_Msg_NoHayPrepedidoTrabajoCrearNuevo)) {
            _imgButton = imgButton;
            _articulo = articulo;
            _atributo1 = atributo1;
            _atributo2 = atributo2;
            _atributo3 = atributo3;
            _atributo4 = atributo4;
            _atributo5 = atributo5;
            _descripcion_libre = descripcion_libre;
            _cajas_surtidas = cajas_surtidas;
            _bultos = bultos;
            _serie = serie;
            _unid_venta = unid_venta;
            _surtido = surtido;
            _observaciones = observaciones;
            redirect_NuevoPedido = false;
            nueva_nota = true;
            if (cliente == 0) {
                NuevoPedidoSeleccionarCliente();
            }
            else {
                NuevoPedido(cliente, delegacion);
            }
        }
    }
    else {
        NuevaNota(imgButton, articulo, atributo1, atributo2, atributo3, atributo4, atributo5, descripcion_libre, cajas_surtidas, bultos, serie, unid_venta, surtido, observaciones);
    }
}

function NuevaNota(imgButton, articulo, atributo1, atributo2, atributo3, atributo4, atributo5, descripcion_libre, cajas_surtidas, bultos, serie, unid_venta, surtido, observaciones) {
    _imgButton = imgButton;
    B2C.wsGeneral.InsertCesta(articulo, atributo1, atributo2, atributo3, atributo4, atributo5, descripcion_libre, cajas_surtidas, bultos, serie, unid_venta, surtido, observaciones, NuevaNotaCallBack, ErrorHandlerGenerico, TimeOutHandlerGenerico);
}

function NuevaNotaCallBack(result) {
    var datos = eval("(" + result + ")");
    if (datos.nota > 0) {
        // nota insertada: refrescar información que se está mostrando de la cesta
        $get(_imgButton).src = "../Imagenes/cesta_incluido.gif";
        B2C.wsGeneral.GetHTMLInfoCesta(GetHTMLInfoCestaCallBack, ErrorHandlerGenerico, TimeOutHandlerGenerico);
    }
    else {
        alert(dmi_Err_generico + ": " + datos.error);
    }
}

function GetHTMLInfoCestaCallBack(result) {
    $get("PageHeader_InfoCestaUpdatePanel").innerHTML = result;
    
}

function ErrorHandlerGenerico(result) {
    var msg = result.get_exceptionType() + "\r\n";
    msg += result.get_message() + "\r\n";
    msg += result.get_stackTrace();
    alert(msg);
}

function TimeOutHandlerGenerico(result) {
    alert("Timeout :" + result);
}

function FormatoNum(numero, decimales) {
    var num = numero.toFixed(decimales);
    return num.replace(".", ",");
}

function ResetUsuarioTrabajo() {
    B2C.wsGeneral.ResetUsuarioTrabajo(ResetUsuarioTrabajoCallBack, ErrorHandlerGenerico, TimeOutHandlerGenerico);
}

function ResetUsuarioTrabajoCallBack(result) {
    window.location.reload();
}

function trim(cadena) {
    for (i = 0; i < cadena.length; ) {
        if (cadena.charAt(i) == " ")
            cadena = cadena.substring(i + 1, cadena.length);
        else
            break;
    }

    for (i = cadena.length - 1; i >= 0; i = cadena.length - 1) {
        if (cadena.charAt(i) == " ")
            cadena = cadena.substring(0, i);
        else
            break;
    }

    return cadena;
}

/* funciones utilizadas por el control CustomerSelect */
function CustomerSelectCancel() {
}

function EstablecerCliente(CodCli, EsPreCliente, NomCli) {
    B2C.wsGeneral.EstablecerCliente(CodCli, EsPreCliente, EstablecerClienteCallBack, ErrorHandlerGenerico, TimeOutHandlerGenerico);
}

function EstablecerClienteCallBack(result) {
    var datos = eval('(' + result + ')');
    if (datos.ok == true) {
        var modalPopupBehavior = $find('programmaticMPESearchBehavior');
        modalPopupBehavior.hide();
        window.location = url_actual;
    }
    else {
        alert(datos.errMessage);
    }
}

function PopupFoto(imagen) {
    var w = window.open(imagen, 'Foto', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,width=800,height=650');
    w.focus;
}


var BrowserDetect = {
        init: function() {
            this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
            this.version = this.searchVersion(navigator.userAgent)
		|| this.searchVersion(navigator.appVersion)
		|| "an unknown version";
            this.OS = this.searchString(this.dataOS) || "an unknown OS";
        },
        searchString: function(data) {
            for (var i = 0; i < data.length; i++) {
                var dataString = data[i].string;
                var dataProp = data[i].prop;
                this.versionSearchString = data[i].versionSearch || data[i].identity;
                if (dataString) {
                    if (dataString.indexOf(data[i].subString) != -1)
                        return data[i].identity;
                }
                else if (dataProp)
                    return data[i].identity;
            }
        },
        searchVersion: function(dataString) {
            var index = dataString.indexOf(this.versionSearchString);
            if (index == -1) return;
            return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
        },
        dataBrowser: [
	{
	    string: navigator.userAgent,
	    subString: "Chrome",
	    identity: "Chrome"
	},
	{ string: navigator.userAgent,
	    subString: "OmniWeb",
	    versionSearch: "OmniWeb/",
	    identity: "OmniWeb"
	},
	{
	    string: navigator.vendor,
	    subString: "Apple",
	    identity: "Safari",
	    versionSearch: "Version"
	},
	{
	    prop: window.opera,
	    identity: "Opera"
	},
	{
	    string: navigator.vendor,
	    subString: "iCab",
	    identity: "iCab"
	},
	{
	    string: navigator.vendor,
	    subString: "KDE",
	    identity: "Konqueror"
	},
	{
	    string: navigator.userAgent,
	    subString: "Firefox",
	    identity: "Firefox"
	},
	{
	    string: navigator.vendor,
	    subString: "Camino",
	    identity: "Camino"
	},
	{		// for newer Netscapes (6+)
	    string: navigator.userAgent,
	    subString: "Netscape",
	    identity: "Netscape"
	},
	{
	    string: navigator.userAgent,
	    subString: "MSIE",
	    identity: "Explorer",
	    versionSearch: "MSIE"
	},
	{
	    string: navigator.userAgent,
	    subString: "Gecko",
	    identity: "Mozilla",
	    versionSearch: "rv"
	},
	{ 		// for older Netscapes (4-)
	    string: navigator.userAgent,
	    subString: "Mozilla",
	    identity: "Netscape",
	    versionSearch: "Mozilla"
	}
],
        dataOS: [
	{
	    string: navigator.platform,
	    subString: "Win",
	    identity: "Windows"
	},
	{
	    string: navigator.platform,
	    subString: "Mac",
	    identity: "Mac"
	},
	{
	    string: navigator.userAgent,
	    subString: "iPhone",
	    identity: "iPhone/iPod"
	},
	{
	    string: navigator.platform,
	    subString: "Linux",
	    identity: "Linux"
	}
]

};
    
function Mostrar (objeto) { 
if (ns4)
{
 objeto.visibility = "show";
}
else
{
 if (ie4) 
 {
    objeto.visibility = "visible";
 } 
}
}

function Ocultar(objeto) {
    if (ns4) {
        objeto.visibility = "hide";
    }
    else {
        if (ie4) {
            objeto.visibility = "hidden";
        }
    }
}

// requiere jquery-ui-1.8.5.custom.min
function showAlert(text) {
    $alert = $(document.createElement("div"));
    $alert.html(text);
    $("body").append($alert);
    $alert.dialog({
        height: 155,
        modal: true,
        draggable: false,
        title: "Atención",
        buttons: {
        "Cerrar": function() {
                $(this).dialog("close");
            }
        }
    });
}

function GetShoppingCartTotales() {
    B2C.wsGeneral.GetShoppingCartTotales(GetShoppingCartTotales_CallBack)
}

function GetShoppingCartTotales_CallBack(response) {
    //valores devueltos: ItemsCount | SubTotal | ShippingAmount | PaymentAdditionalFee | TaxAmount | Total
    if (response != '') {
        var datos = eval('(' + response + ')');
        $("#ItemCountValue").html(datos.ItemsCount);
        $("#SubTotalValue").html(datos.SubTotal);
        $("#ShippingAmountValue").html(datos.ShippingAmount);
        if (datos.ItemsCount == 0) {
            // mostrar mensaje de Cesta vacía:
            $("#no-items-basket").html(dmi_CartIsEmpty);
        }
        else {
            $("#no-items-basket").html("");
        }
        UpdateHeaderCartItemCount(datos.ItemsCount);
    }
}


// actualizar Cart Items count cabecera
function UpdateHeaderCartItemCount(HeaderCartItemCountValue) {
    $("#HeaderCartItemCountValue").html(HeaderCartItemCountValue);
}

var CodigoValeUsos;
function GetHTMLUsosVale(Admon, eValeGUID, eValeContador, CodigoVale, event) {
    SaveMousePosition(event);
    CodigoValeUsos = CodigoVale;
    B2C.wsGeneral.GetHTMLUsosVale(Admon, eValeGUID, eValeContador, GetHTMLUsosValeCallBack);
}

function GetHTMLUsosValeCallBack(result) {    
    detailRolloverPopup(CodigoValeUsos, result, false);
}

var HelpTitle;
function GetHTMLHelp(TopicName, event) {
    SaveMousePosition(event);
    HelpTitle = "Ayuda";
    B2C.wsGeneral.GetHTMLHelp(TopicName, GetHTMLHelpCallBack);
}

function GetHTMLHelpCallBack(result) {
    detailRolloverPopup(HelpTitle, result, false);
}

function EditConfiguracion_eVales(id, apartado) {
    AbrirVentana('../eVales/wEditConfiguracion' + apartado + '.aspx?id=' + id, 'P', '800', '600', apartado);
}

var idMsg_ClientID;
var imgMsg_ClientID;
function SendVale_Notification(eVale_GUID, idMensajeGenerado_ClientID, imgMensajeGenerado_ClientID) {
    idMsg_ClientID = idMensajeGenerado_ClientID;
    imgMsg_ClientID = imgMensajeGenerado_ClientID;
    B2C.wsGeneral.SendVale_Notification(eVale_GUID, SendVale_NotificationCallBack);
}

function SendVale_NotificationCallBack(response) {
    var img = $get(imgMsg_ClientID);
    // valores devueltos: idMensaje | idMensajeText | PopupTitulo | PopupBody | imgMensaje
    if (response != '') {
        var datos = eval('(' + response + ')');
        if (datos.idMensaje != 0) {
            var span = $get(idMsg_ClientID);
            var text = document.createTextNode('' + datos.idMensajeText);
            /*no consigo que la etiqueta span muestre interpretado el código html del link: dejo sólo el nº idMensaje
            span.innerHTML = ''; // clear existing
            span.appendChild(text); */
            span.innerHTML = datos.idMensaje;
            if (datos.imgMensaje != '') {
                img.src = datos.imgMensaje;
                img.alt = "";
            }
            if ((datos.PopupTitulo != '') || (datos.PopupBody != '')) {
                img.onmouseout = function() { detailRolloverPopupClose(); };
                img.onmouseover = function() {
                    SaveMousePosition(event);
                    detailRolloverPopup(datos.PopupTitulo, datos.PopupBody, false);
                }
            }
        }
        else {
            img.style.visibility = "hide";
        }
    }
    else {

    }
}

