﻿/// <reference path="./jquery-1.4.4-vsdoc.js">

/*
    Lista:
    
    * jQuery.getElement(id)
    * jQuery.getQuery()
    
    * jQuery(el).replaceText(sFind, sReplace)
    * jQuery(el).alphanumeric()
    * jQuery(el).numeric()
    * jQuery(el).alpha()
    
    Importante:
    
    Si queremos que la funcion del Plugin sea para un elemento es:
        $.fn.funcionx(...){
            ...
        }
    Donde al elemento lo referenciamos con "this"
    
    Si queremos que sea una funcion que cuelgue de jQuery:
        $.funcionx(...){
        }
    En este tipo de funciones no tenemos una referencia a nungun elemento
    porque no existe alguno.
*/

/*
    Extenciones/Plugins/Funciones para jQuery
    Este formato mantiene la compatibilidad con otros frameworks
    
    http://www.cristalab.com/tutoriales/251/crear-plugins-para-jquery.html
*/
(function ($) {
    /*
    Idem "Helper.getElement", pero para el entorno de jQuery
    Uso:
    var valorUsuario = jQuery.getElement("txtUsuario").val();
    */
    $.getElement = function (idElemento) {
        return jQuery(Helper.getElement(idElemento));
    };

    $.fn.replaceText = function (f, r) {
        if (this.tagName == "input" || this.tagName == "textarea") {
            this.val(this.val().replace(f, r));
        }
        else {
            this.html(this.html().replace(f, r));
        }
    };

    $.consola = function (mensaje, limpiar) {

        limpiar = limpiar == undefined ? true : limpiar;

        var consolaContenedor = $("#consola-contenedor");

        if (consolaContenedor.length == 0) {
            consolaContenedor = jQuery('<div id="consola-contenedor"></div>');

            consolaContenedor
                .css("position", "absolute")
                .css("top", 6)
                .css("left", 7)
                .css("border", "1px solid #000000")
                .appendTo("body");
        }

        if (limpiar)
            consolaContenedor.empty();
        else
            consolaContenedor.append("<br />");

        consolaContenedor.append("<span>&nbsp;" + mensaje + "&nbsp;</span>");
    }

    $.browserInfo = function () {

        var einfo = {
            browserType: "",
            browserVersion: "",
            screenWidth: "",
            screenHeight: "",
            error: false
        };

        try {

            if (jQuery.browser.webkit)
                einfo.browserType = "webkit";
            else if (jQuery.browser.safari == true)
                einfo.browserType = "safari";
            else if (jQuery.browser.opera)
                einfo.browserType = "opera";
            else if (jQuery.browser.msie)
                einfo.browserType = "msie";
            else if (jQuery.browser.mozilla)
                einfo.browserType = "mozilla";

            einfo.browserVersion = $.browser.version;
            einfo.screenWidth = window.screen.width;
            einfo.screenHeight = window.screen.height;
        }
        catch (ex) {
            einfo.error = true;
        }

        return einfo;
    };

    // http://itgroup.com.ph/alphanumeric/
    $.fn.alphanumeric = function (p) {

        p = $.extend({
            ichars: "!@#$%^&*()+=[]\\\';,/{}|\":<>?~`.- ",
            nchars: "",
            allow: ""
        }, p);

        return this.each
			(
				function () {
				    if (p.nocaps) p.nchars += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
				    if (p.allcaps) p.nchars += "abcdefghijklmnopqrstuvwxyz";

				    s = p.allow.split('');
				    for (i = 0; i < s.length; i++) if (p.ichars.indexOf(s[i]) != -1) s[i] = "\\" + s[i];
				    p.allow = s.join('|');

				    var reg = new RegExp(p.allow, 'gi');
				    var ch = p.ichars + p.nchars;
				    ch = ch.replace(reg, '');

				    jQuery(this).keypress
						(
							function (e) {
							    if (!e.charCode) k = String.fromCharCode(e.which);
							    else k = String.fromCharCode(e.charCode);

							    if (ch.indexOf(k) != -1) e.preventDefault();
							    if (e.ctrlKey && k == 'v') e.preventDefault();
							}
						);
				    jQuery(this).bind('contextmenu', function () { return false });
				}
			);
    };

    $.fn.numeric = function (p) {

        var az = "abcdefghijklmnopqrstuvwxyz";
        az += az.toUpperCase();

        p = $.extend({
            nchars: az
        }, p);

        return this.each(function () {
            jQuery(this).alphanumeric(p);
        }
		);
    };

    $.fn.alpha = function (p) {

        var nm = "1234567890";

        p = $.extend({
            nchars: nm
        }, p);

        return this.each(function () {
            jQuery(this).alphanumeric(p);
        }
		);
    };

    /*
    Retorna un array con los datos pasados por GET
    En el caso de que no existan datos devuelve null
    */
    $.getQuery = function () {

        var wlGetQuery = new String(window.location.search);
        var retorno = null;

        if (wlGetQuery.indexOf("?") > -1) {
            var qsget = wlGetQuery.substr(wlGetQuery.indexOf("?") + 1);
            jQuery.each(qsget.split("&"), function () {
                if (retorno == null)
                    retorno = new Array();

                var claveValor = this.split("=");
                retorno[claveValor[0]] = claveValor[1];
            });
        }
        return retorno;
    }

    /*
    Retorna el host completo(true)/solo host(false:default)
    */
    $.host = function (completo) {
        if (typeof (completo) == "undefined")
            completo = false;

        var host = window.location.host;
        var protocol = window.location.protocol;
        var port = window.location.port;
        var retorno = "";

        if (port != "") {
            if (host.indexOf(port) == -1) {
                if (protocol == "http" && port != "80")
                    port = ":" + port;
                else if (protocol == "https" && port != "443")
                    port = ":" + port;
                else if (protocol == "ftp" && port != "21")
                    port = ":" + port;
                else if (port != "")
                    port = ":" + port;
            }
            else {
                port = "";
            }
        }

        if (completo)
            retorno = protocol + "//" + host + port + "/";
        else
            retorno = host;

        return retorno;
    };

    $.bindAbrirEnNuevaVentana = function () {
        jQuery(".abrir-en-nueva-ventana").live("click", function (ev) {
            ev.stopPropagation();

            var url = '';

            if ($(this).hasClass('tiene-nombre'))
                url = $(this).attr("winname");
            else
                url = $(this).attr("href");

            Helper.window.open(url, MD5(url));
            return false;
        });
    };

    $.fn.tagName = function () {
        return $(this).get(0).tagName.toLowerCase();
    };

    $.fn.runClick = function () {

        $.each(this, function () {

            var element = $(this).get(0);

            if ($.browser.msie) { // IE
                element.click();
            }
            else {

                try {

                    var evt = document.createEvent("MouseEvents");
                    evt.initMouseEvent("click", true, true, window, 1, 1, 1, 1, 1, false, false, false, false, 0, element);
                    element.dispatchEvent(evt);

                    if ($.browser.mozilla) {
                        if (element.tagName == "A" && element.href != "") {
                            if (element.target == "_blank") { window.open(element.href, element.target); }
                            else { document.location = element.href; }
                        }
                    }

                } catch (e) {
                    window.open(element.href, element.target);
                }

            }

        });

        return this;
    };

    $.fn.selectText = function (start, end) {
        this.setSelection(start, end);

        return this;
    };



})(jQuery);
