

/*
 * Si se quiere agregar un pop se debe colocar un div con la clase "popUp-cnt".
 *
 * Ejemplo 1 (más de un popup):
 * <div id="popUp1" class="popUp-cnt"></div>
 * Para abrirlo:
 * popup.show('popUp1');
 * popup.show('popUp1',true); <-- Click en el fondo cierra el popup.
 *
 *
 * Ejemplo 2 (popup único):
 * <div class="popUp-cnt"></div>
 * Para abrirlo:
 * popup.show();
 *
 * ****************************************************************************/



// Referencia global para acceder al popup.
var popup;
function Popup(){
    var self = this;
    var div = $('<div id="popUp"></div>');
    var bg = $('<div class="popUp-bg"></div>');
    var cnts = {};
    var cnt;
    var w,h;

    // Agrego el div que tiene los popups.
    div.hide().prependTo($('body'));
    
    // Obtengo los popups.
    $('div.popUp-cnt').each(function(){
        var c = $(this);
        c.hide().appendTo(div);
        var id = c.attr('id');
        if(id==''){
            id= 'popUpNoId';
        }
        cnts[id] = c;
    });
    
    // Agrego fondo.
    bg.prependTo(div).css('opacity',0.8);

    /**
     * Posiciona el popup en la pantalla.
     */
    var setPosition = function(){
        if(cnt!=undefined){
            w = $('body').width();        
            var puw = (cnt.width()+parseInt(cnt.css('padding-left'))+parseInt(cnt.css('padding-right')));
            var puh = (cnt.height()+parseInt(cnt.css('padding-top'))+parseInt(cnt.css('padding-bottom')));
            var top = (($(window).height()-puh)/4);
            var left = ((w-puw)/2);
            if(top<0){
                top=20;
            }else{
                /*  Alinea con la grilla de 5px */
                top = Math.round(top/5)*5;
            }
            if(left<0){
                left=20;
            }
            top+=$(document).scrollTop();

            cnt.css('left',left+'px');
            cnt.css('top',top+'px');
        }
    };
    var setSizes = function(){
        w = $(document).width();
        h = $(document).height();
        bg.width(w);
        bg.height(h);
        setPosition();
    };

    /**
     * Agregar nuevos popup.
     * 
     * @param string id Identificador del popup.
     * @param string html Contenido del popup.
     * @param bool show Indica si se debe mostrar el popup después de agregarlo.
     * @param bool bgClickClose Indica si al hacer click en el fondo lo cierra.
     */
    this.add = function(id,html,show,bgClickClose){
        if(cnts[id]!=undefined){
            cnts[id].remove();
        }
        var newCnt = $('<div id="'+id+'" class="popUp-cnt"></div>');
        cnts[id] = newCnt;
        newCnt.html(html).hide().appendTo(div);
        if(show!=undefined&&show==true){
            self.show(id,bgClickClose);
        }
    }

    /**
     * Muestra el popup correspondient al id indicado.
     *
     * @param string id Identificador del popup.
     * @param bool bgClickClose Indica si al hacer click en el fondo lo cierra.
     */
    this.show = function(id, bgClickClose){
        if(id==undefined){
            id = 'popUpNoId';
        }
        if(bgClickClose!==undefined&&bgClickClose==true){
            if(!bg.hasClass('close')){
                bg.addClass('close').bind('click',self.close);
            }
        }else{
            bg.removeClass('close').unbind('click');
        }
        // Controlo que el popup solicitado exista.
        if(cnts[id]!=undefined){
            // Si hay un popup activo oculto el contenido y muestro el
            // solicitado.
            if(cnt!=undefined){
                cnt.fadeOut('fast',function(){
                    cnt=undefined;
                    self.show(id,bgClickClose);
                });
            }else{
                // Obtengo el popup a mostrar.
                cnt = cnts[id];                
                // Verifico si el popup esta activo.
                var visible = div.css('display')!='block';
                // Si el popup esta activo no hago nada con el fondo.
                if(visible){
                    div.css({
                        'visibilty':'hidden',
                        'display':'block'
                    });
                }
                // Oculto el contenido(visiblity) que voy a mostrar y le activo
                // display:block para que calcule el ancho y posisionarlo.
                cnt.css({
                    'visibilty':'hidden',
                    'display':'block'
                });
                // Posiciono el contenido.
                setSizes();
                // Si ya esta activo no hago nada con el fondo.
                if(visible){
                    div.css({
                        'visibilty':'visible',
                        'display':'none'
                    });
                }
                // Oculto el contenido para mostrarlo con el fade.
                cnt.css({
                    'display':'none'
                });
                // Si esta activo no hago el fade del fondo.
                if(visible){
                    div.fadeIn('fast');
                }
                // Muestro el contenido.
                cnt.fadeIn();
            }
        }
    };
    
    /**
     * Cierra el popup activo.
     */
    this.close = function(){
        var aux = cnt;
        cnt=undefined;
        aux.fadeOut('fast');
        div.fadeOut();
    };
    /*  Cualquier elemento que tenga la clase close cierra el popup. */
    $('.close',div).click(function(){
        self.close();
        return false;
    });
    /*  Activo que si se redimenciona la ventana se ajuste el tamaño.   */
    $(window).resize(setSizes);
}



