﻿Utils = {};

/*
 *	Clase para el manejo de estilos
 */
Utils.Styles = function() {};

Utils.Styles.Add = function(urlStyle) {
    var headers = document.getElementsByTagName("head");
    if (headers !== undefined)
        if (headers.length > 0) {
            var link = document.createElement("link");
            link.rel = "stylesheet";
            link.type = "text/css";
            link.href = urlStyle;
            headers[0].appendChild(link);
        }
};

Utils.Styles._GetLinks = function() {
    var links = [];
    var headers = document.getElementsByTagName("head");
    if (headers !== undefined)
        if (headers.length > 0)
        links = headers[0].getElementsByTagName("link");

    return links;
};


Utils.Styles.Remove = function(urlStyle) {
    var headers = document.getElementsByTagName("head");
    if (headers !== undefined)
        if (headers.length > 0) {
            var links = headers[0].getElementsByTagName("link");
            for (var i = 0; i < links.length; i++) {
                if (links[i].href == urlStyle)
                    headers[0].removeChild(links[i]);
            
            }
        }
};


Utils.Styles.GetElementById = function(linkId) {
    var links = Utils.Styles._GetLinks();
    for (var i = 0; i < links.length; i++)
        if (links[i].id == linkId)
        return links[i];

    return null;
};

Utils.Styles.GetElementByAttrbute = function(attribute, value) {
    var links = Utils.Styles._GetLinks();
    for (var i = 0; i < links.length; i++)
        if (links[i].getAttribute(attribute) == value)
        return links[i];

    return null;
};

/*
 *	Otros
 */
Utils.CurrencyOnly = function(o) {
    var sValue = o.value;
    var sKey = String.fromCharCode(window.event.keyCode);
    if (document.selection.createRange().text == sValue) {
        sValue = sKey;
    }
    else {
        sValue = sValue + sKey;
    }

    var re = new RegExp("^\\d+(?:\\.\\d{0,2})?$");
    if (!sValue.match(re))
        window.event.returnValue = false;
};

Utils.Textboxes = null;

Utils.OnEnterPostBack = null;

Utils.DisableEnterPostBack = function() {
    Utils.Textboxes = $("input:text");

    if ($.browser.mozilla)
        $(Utils.Textboxes).keypress(function(event) { return Utils.CheckForEnter(this, { event: event }); });
    else
        $(Utils.Textboxes).keydown(function(event) { return Utils.CheckForEnter(this, { event: event }); });
};

Utils.CheckForEnter = function(sender, args) {
    var event = args.event || window.event;
    var key = event.charCode || event.keyCode;

    if (key == 13) {
        currentTextboxNumber = Utils.Textboxes.index(sender);

        if (Utils.Textboxes[currentTextboxNumber + 1] != null) {
            nextTextbox = Utils.Textboxes[currentTextboxNumber + 1];
            nextTextbox.select();
        }

        args.event.preventDefault();
        if (typeof (Utils.OnEnterPostBack) == "function")
            Utils.OnEnterPostBack(sender, args);

        return false;
    }
};

/*
 *	Clase para el manejo de mensajes
 */
Utils.MessageBox = {};

Utils.MessageBox.MessageBoxIcon = {
    Ok: 0,
    Warning: 1,
    Error: 2
};

Utils.MessageBox.Images = {    
    Ok : "",
    Warning : "",
    Error : ""
};

Utils.MessageBox.btnDetailsMsgBox_click = function(sender, args) {
    Utils.MessageBox.HideDetails();
};

Utils.MessageBox.btnOkMsgBox_click = function(sender, args) {
    $.unblockUI();
};

Utils.MessageBox.HideDetails = function(hide) {
    var detailsTrMsg = $("#detailsTrMsg");
    var btnDetailsMsgBox = $("#btnDetailsMsgBox");

    if (detailsTrMsg.length > 0) {
        if (hide === undefined)
            hide = detailsTrMsg[0].style.display != "none";

        if (!hide) {
            detailsTrMsg[0].style.display = "block";
            btnDetailsMsgBox[0].innerHTML = "Ocultar Detalles";
        }
        else {
            detailsTrMsg[0].style.display = "none";
            btnDetailsMsgBox[0].innerHTML = "Mostrar Detalles";
        }
    }
};

Utils.MessageBox.Show = function(title, message, details, icon, timeout) {
    var titleMsg = $("#titleMsg");
    var imgMsg = $("#imgMsg");
    var textMsg = $("#textMsg");
    var detailsMsg = $("#detailsMsg");
    var btnDetailsMsgBox = $("#btnDetailsMsgBox");
    var btnOkMsgBox = $("#btnOkMsgBox");
    var btnContainerMsgBox = $("#btnContainerMsgBox");

    if (typeof (details) == "undefined" || details == null)
        details = "";

    if (typeof (timeout) == "undefined" || timeout == null)
        timeout = 0;

    Utils.MessageBox.HideDetails(true);

    var iconImagen = "";
    switch (icon) {
        case Utils.MessageBox.MessageBoxIcon.Ok:
            iconImagen = Utils.MessageBox.Images.Ok;
            break;
        case Utils.MessageBox.MessageBoxIcon.Warning:
            iconImagen = Utils.MessageBox.Images.Warning;
            break;
        case Utils.MessageBox.MessageBoxIcon.Error:
            iconImagen = Utils.MessageBox.Images.Error;
            break;
    }

    titleMsg[0].innerHTML = title;
    imgMsg[0].style.display = iconImagen != "" ? "block" : "none";
    imgMsg[0].src = iconImagen;
    textMsg[0].innerHTML = message;

    btnDetailsMsgBox[0].style.display = details != "" ? "block" : "none";
    //btnOkMsgBox[0].style.display = timeout > 0 ? "none" : "block";
    btnContainerMsgBox[0].style.display = timeout > 0 ? "none" : "block";
    detailsMsg[0].value = details;

    Utils.MessageBox._Show(timeout);
};

Utils.MessageBox._Show = function(timeout) {
    var css = {};
    css["width"] = '550px';
    css["left"] = ($(window).width() - 550) / 2 + 'px';
    css["border"] = 'solid';
    css["border-width"] = '1px';
    css["border-color"] = '#666666';
    css["padding"] = '5px';
    css["backgroundColor"] = '#77B4E0';
    css["color"] = '#fff';

    /*var css = {
        width: '550px',
        left: ($(window).width() - 550) / 2 + 'px',
        border: 'solid',
        'border-width': '1px',
        'border-color': '#666666',
        padding: '5px',
        backgroundColor: '#77B4E0',
        color: '#fff'
    };*/

    var overlayCSS = {
        backgroundColor: '#CCCCCC'
    };

    var parameters = {
        message: $("#messageBox"),
        fadeIn: 700,
        fadeOut: 700,
        css: css,
        overlayCSS: overlayCSS
    };

    if (typeof (timeout) == "number")
        if (timeout > 0)
        parameters.timeout = timeout;

    $.blockUI(parameters);
};

window.MessageBox = Utils.MessageBox;
window.MessageBoxIcon = Utils.MessageBox.MessageBoxIcon;


/*
*	Clase para el manejo de cadenas Url
*/
Utils.Url = {

    // public method for url encoding
    encode: function(string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode: function(string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode: function(string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode: function(utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while (i < utftext.length) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }

        return string;
    }
};

/*
 *	Clase para el manejo de ventanas
 */
Utils.Window = function() {
    this.Object = null;
    this.Url = "";
    this.Width = "";
    this.Height = "";
    this.Name = "_blank";
    this.ShowToolbar = false;
    this.ShowMenuBar = false;
    this.ShowLocation = false;
    this.ShowStatus = false;
    this.Resizable = false;
    this.ShowTitlebar = false;
    this.ShowDirectories = false;
    this.ShowScrollBars = false;
    this.Center = false;
    this.Parameters = new Array();

    this.OnClose = null;
};

Utils.Window.prototype.SetUrl = function(value) {
    this.Url = value;
};

Utils.Window.prototype.SetWidth = function(value) {
    this.Width = value;
};

Utils.Window.prototype.SetHeight = function(value) {
    this.Height = value;
};

Utils.Window.prototype.SetName = function(value) {
    this.Name = value;
};

Utils.Window.prototype.SetShowToolbar = function(value) {
    this.ShowToolbar = value;
};

Utils.Window.prototype.SetShowMenuBar = function(value) {
    this.ShowMenuBar = value;
};

Utils.Window.prototype.SetShowLocation = function(value) {
    this.ShowLocation = value;
};

Utils.Window.prototype.SetShowStatus = function(value) {
    this.ShowStatus = value;
};

Utils.Window.prototype.SetResizable = function(value) {
    this.Resizable = value;
};

Utils.Window.prototype.SetShowTitlebar = function(value) {
    this.ShowTitlebar = value;
};

Utils.Window.prototype.SetShowDirectories = function(value) {
    this.ShowDirectories = value;
};

Utils.Window.prototype.SetShowScrollBars = function(value) {
    this.ShowScrollBars = value;
};

Utils.Window.prototype.SetCenter = function(value) {
    this.Center = value;
};

Utils.Window.prototype.GetUrl = function() {
    return this.Url;
};

Utils.Window.prototype.GetWidth = function() {
    return this.Width;
};

Utils.Window.prototype.GetHeight = function() {
    return this.Height;
};

Utils.Window.prototype.GetName = function() {
    return this.Name;
};

Utils.Window.prototype.GetShowToolbar = function() {
    return this.ShowToolbar;
};

Utils.Window.prototype.GetShowMenuBar = function() {
    return this.ShowMenuBar;
};

Utils.Window.prototype.GetShowLocation = function() {
    return this.ShowLocation;
};

Utils.Window.prototype.GetShowStatus = function() {
    return this.ShowStatus;
};

Utils.Window.prototype.GetResizable = function() {
    return this.Resizable;
};

Utils.Window.prototype.GetShowTitlebar = function() {
    return this.ShowTitlebar;
};

Utils.Window.prototype.GetShowDirectories = function() {
    return this.ShowDirectories;
};

Utils.Window.prototype.GetShowScrollBars = function() {
    return this.ShowScrollBars;
};

Utils.Window.prototype.GetCenter = function() {
    return this.Center;
};

Utils.Window.prototype.AddParameter = function(Name, Value) {
    this.Parameters.push({ Name: Name, Value: Value });
};

Utils.Window.prototype._IsEnabledModal = function() {
    return (typeof (window.showModalDialog) != "undefined" && window.showModalDialog != null);
};

Utils.Window.prototype._CreateUrl = function(modal) {
    var url = this.GetUrl();

    if (!modal) {
        var Parameters = "";
        for (var i = 0; i < this.Parameters; i++) {
            if (Parameters != "")
                Parameters += "&";

            Parameters += this.Parameters[i].Name + "=" + this.Parameters[i].Value;
        }

        if (Parameters != "")
            url += "?" + Parameters;
    }

    return url;
};

Utils.Window.prototype._CreateObjectParameter = function() {
    var objParameter = new Object();
    for (var i = 0; i < this.Parameters; i++) {
        eval("objParameter." + this.Parameters[i].Name + " = '" + this.Parameters[i].Value + "';");
    }

    return objParameter;
};

Utils.Window.prototype._CreateStringConditions = function(modal) {
    var Conditions = "";

    if (!modal) {
        if (this.GetHeight() > "")
            Conditions += "height=" + this._GetFixSize(this.GetHeight());

        if (this.GetWidth() > "")
            Conditions += ", width=" + this._GetFixSize(this.GetWidth());

        Conditions += ", toolbar=" + this._BooleanToString(this.GetShowToolbar());
        Conditions += ", menubar=" + this._BooleanToString(this.GetShowMenuBar());
        Conditions += ", location=" + this._BooleanToString(this.GetShowLocation());
        Conditions += ", status=" + this._BooleanToString(this.GetShowStatus());
        Conditions += ", resizable=" + this._BooleanToString(this.GetResizable());
        Conditions += ", titlebar=" + this._BooleanToString(this.GetShowTitlebar());
        Conditions += ", directories=" + this._BooleanToString(this.GetShowDirectories());
        Conditions += ", scrollbars=" + this._BooleanToString(this.GetShowScrollBars());

        if (this.GetCenter()) {
            var left = (screen.width - this.GetWidth()) / 2;
            var top = (screen.height - this.GetHeight()) / 2;

            Conditions += ", top =" + top;
            Conditions += ", left=" + left;
        }
    }
    else {
        Conditions += "status:" + this._BooleanToString(this.GetShowStatus());
        Conditions += "; resizable:" + this._BooleanToString(this.GetResizable());
        //Conditions += "; toolbar:" + this._BooleanToString(this.GetShowToolbar());
        //Conditions += "; menubar:" + this._BooleanToString(this.GetShowMenuBar());
        //Conditions += "; location:" + this._BooleanToString(this.GetShowLocation());
        //Conditions += "; titlebar:" + this._BooleanToString(this.GetShowTitlebar());
        //Conditions += "; directories:" + this._BooleanToString(this.GetShowDirectories());
        Conditions += "; scroll:" + this._BooleanToString(this.GetShowScrollBars());
        Conditions += "; center:" + this._BooleanToString(this.GetCenter());

        if (this.GetHeight() > "")
            Conditions += "; dialogHeight:" + this._GetFixSize(this.GetHeight());

        if (this.GetWidth() > "")
            Conditions += "; dialogWidth:" + this._GetFixSize(this.GetWidth());
    }

    //alert(Conditions);
    return Conditions;
};

Utils.Window.prototype._GetFixSize = function(value) {
    if (typeof (value) == "number")
        return value + "px";

    return value;
};

Utils.Window.prototype._BooleanToString = function(value) {
    return value ? "yes" : "no";
};

Utils.Window.prototype.Show = function() {
    this.Object = window.open(this._CreateUrl(false), this.GetName(), this._CreateStringConditions(false));
    this.Object.returnValue = null;

    var self = this;
    if (typeof (self.OnClose) == "function") {
        this.Object.onunload = function() {
            var args = { returnValue: self.returnValue };
            self.OnClose(this, args);
        }
    }
};

Utils.Window.prototype.ShowDialog = function() {
    var result = null;

    if (this._IsEnabledModal()) {
        var self = this;
        var tmrShowDialog = setTimeout(function() {
            result = window.showModalDialog(self._CreateUrl(true), self._CreateObjectParameter(), self._CreateStringConditions(true));
            if (typeof (self.OnClose) == "function") {
                var args = { returnValue: result };
                self.OnClose(this, args);
            }
        }, 100);
    }
    else
        this.Show();

    return result;
};

Utils.muestraDialogonc = function(url, ancho, alto) {
    $("#iDialognc").attr("src", url);

    var dialog = $("#dialognc");
    dialog.dialog('option', 'width', ancho);
    dialog.dialog('option', 'height', alto);
    dialog.dialog('open');
};

/*
*	Desglosa un mensaje de error Ajax para extraer el mensaje en si.
*/
Utils.GetErrorMessage = function(err) {
    var txt = err;
    var index = txt.indexOf(":");

    if (index != -1)
        txt = txt.substring(index + 1);

    return txt;
};

Utils.muestraDialogo = function(url, ancho, alto) {
    $("#iDialog").attr("src", url);

    var dialog = $("#dialog");
    dialog.dialog('option', 'width', ancho);
    dialog.dialog('option', 'height', alto);
    dialog.dialog('open');   
};

Utils.CloseDialog = function() {
    $("#dialog").dialog('close');
};

Utils.CloseDialogNC = function() {
    $("#dialognc").dialog('close');
};

Utils.BlockPanel = function(className) {
    var css = {};
    css["width"] = "300px";
    css["border"] = 'none';
    css["color"] = '#000000';
    css["padding"] = '15px';
    css["backgroundColor"] = '#FFFFFF';
    css["-webkit-border-radius"] = '10px';
    css["-moz-border-radius"] = '10px';
    css["-ms-border-radius"] = '10px';
    css['border-radius'] = '10px';
    css["opacity"] = .8;   

    $('div.' + className).block({
        message: $("#tallContent"),
        css: css,
        overlayCSS: {
            backgroundColor: '#CCCCCC'
        }
    });
};

Utils.UnBlockPanel = function(className) {
    $('div.' + className).unblock();
};

Utils.DateTimeConfig = {
    dateFormat: 'dd/mm/yy',
    changeMonth: true,
    changeYear: true,
    dayNamesMin: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sa'],
    monthNames: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo',
                    'Junio', 'Julio', 'Agosto', 'Septiembre',
                    'Octubre', 'Noviembre', 'Diciembre'],
    monthNamesShort: ['Ene', 'Feb', 'Mar', 'Abr',
                    'May', 'Jun', 'Jul', 'Ago',
                    'Sep', 'Oct', 'Nov', 'Dic']
};

Utils.FixIframeHeight = function(iframeID) {
    var iFrame = $("#" + iframeID);

    var nHeight = 0;
    if (iFrame[0].contentDocument)
        nHeight = iFrame[0].contentDocument.body.scrollHeight + 35;
    else
        nHeight = iFrame[0].contentWindow.document.body.scrollHeight;

    iFrame.height(nHeight);
};

Utils.CopyToClipboard = function(text) {
    if (window.clipboardData)
        window.clipboardData.setData('text', text);
    else {
        var clipboarddiv = document.getElementById('divclipboardswf');
        if (clipboarddiv == null) {
            clipboarddiv = document.createElement('div');
            clipboarddiv.setAttribute("name", "divclipboardswf");
            clipboarddiv.setAttribute("id", "divclipboardswf");
            document.body.appendChild(clipboarddiv);
        }
        clipboarddiv.innerHTML = '<embed src="clipboard.swf" FlashVars="clipboard=' + encodeURIComponent(text) + '" width="0" height="0" type="application/x-shockwave-flash"></embed>';
    }
};
