// www.itelligent.com.mx, Agosto 2010

$(function () {
    if(typeof(purchase) != 'undefined')
        $('#busqueda').append(
            $('<div id="lightbox" style="width: 165px; height: 35px; position: absolute; bottom: 230px; right: 0px; "></div>')
        );

    $('#menu_light').click(function () {
        lightbox.start();

        return false;
    });
})

var lightbox = {
    __interno: {
        close: null,
        empty: null,
        logo: null,
        foot: null,
        wait: null
    },

    __target: function (url, extra) {
        var res = {
            id: url.indexOf('&id') != -1 ? url.match(/&id=(\d*)/)[1] : '',
            p: url.indexOf('&p') != -1 ? url.match(/&p=(\d+)/)[1] : '',
            com_buscar: url.indexOf('&com_buscar') != -1 ? url.match(/&com_buscar=([^&]*)/)[1] : ''
        }

        if(extra)
            for(e in extra)
                res[e] = extra[e];

        return res;
    },

    __dim: function () {
        return {
            width: parseInt($('body').width(), 10),
            height: Math.max(
                Math.max(document.body.scrollHeight, document.documentElement.scrollHeight),
                Math.max(document.body.offsetHeight, document.documentElement.offsetHeight),
                Math.max(document.body.clientHeight, document.documentElement.clientHeight)
            )
        }
    },

    // operaciones sobre el boton
    show: function (propiedades, url) {
        $('#lightbox')
            .html(
                $('<div style="display: none; cursor: pointer; " class="' + (!propiedades.lightbox ? 'no_encontrado' : 'encontrado') + '">' + (!propiedades.lightbox? 'ADD TO LIGHTBOX' : 'VIEW LIGHTBOX') + '</div>')
                    .click((function (lightbox) { return function () {
                        if($('#lightbox').data('activo'))
                            return;

                        if($(this).hasClass('no_encontrado'))
                            lightbox.add(url);
                        else
                            lightbox.start();

                        return;
                    }})(this))
            )
            .data('target', url)
            .find('div')
                .fadeIn('fast');
    },
    hide: function () {
        $('#lightbox')
            .find('div')
                .fadeOut('fast', function () {
                    $(this).remove();
                });
    },


    // visualizacion del componente
    start: function () {
        if($('#lightbox').data('activo'))
            return;

        $('#lightbox').data('activo', true)

        // bloquea los botones
        $('#menu_light, #lightbox').css('opacity', .4)

        // bloquea la pagina (si ya esta activo bpage se cancela la carga)
        bpage.show({
            opacity: 1
        });

        // agrega el manejador para la tecla 'esc'
        $(document)
            .keyup((function (lightbox) { return function (e) {
                if((document.all ? window.event.keyCode : e.which) != 27)
                    return false;

                // ventana de compra activa es cancelada y la galeria sigue activa
                if(purchase.isActive()) {
                    purchase.stop(function () {
                        galeriebox.unblock();

                        // desbloquea elementos propios
                        for(a in lightbox.__interno)
                            if(lightbox.__interno[a])
                                lightbox.__interno[a].css('z-index', 102);
                    });

                    return false;
                }

                lightbox.stop();

                return false;
            }})(this))

        // agrega el indicador de trabajo
        this.__interno.wait = $('<div style="background: url(scripts/loadingb.gif) no-repeat center center; width: 31px; height: 31px; z-index: 102; line-height: 31px; text-align: center; color: #fff; font-weight: 800; font-size: 15px; "></div>')
            .css({
                'position' : document.all ? 'absolute' : 'fixed',
                'top' : '10px',
                'right': '10px',
                'display' : 'none'
            })

        $('body').append(this.__interno.wait);

        // agrega el boton de cerrar
        this.__interno.close = $('<div style=" color: #fff; text-align: right; background: transparent; z-index: 102; ">\
                                    <a href="#" style="color: #fff; text-decoration: underline; background: transparent; ">close</a> or Esc Key \
                                  </div> \
            ')
            .css({
                'position' : document.all ? 'absolute' : 'fixed',
                'top' : '10px',
                'right': '10%',
                'display' : 'none'
            })
            .find('a')
                .click((function(lightbox) { return function (e) {
                    lightbox.stop();
                    return false;
                }})(lightbox))
                .end()

        $('body').append(this.__interno.close);

        // agrega el boton de vaciar
        this.__interno.empty = $('<div style=" color: #fff; text-align: right; background: transparent; z-index: 102; "> \
                                    <a href="#" style="color: #fff; text-decoration: underline; background: transparent; ">empty lightbox</a>  \
                                  </div> \
            ')
            .css({
                'position' : document.all ? 'absolute' : 'fixed',
                'top' : '10px',
                'right': '20%',
                'display' : 'none'
            })
            .find('a')
                .click((function(lightbox) { return function () {
                    // bloquea terceros
                    galeriebox.block();

                    // bloquea elementos propios
                    for(a in lightbox.__interno)
                        if(lightbox.__interno[a])
                            lightbox.__interno[a].css('z-index', 1);

                    // solicita borrar todos los componentes
                    modTT780(
                        'lightbox_c.reiniciar',
                        {},
                        function (data) {
                            try {
                                data = eval('(' + data.responseText + ')');
                            }
                            catch(exc) {
                                alert('Operation fail');
                                return false;
                            }

                            // actualiza el boton
                            if($('#lightbox').data('target'))
                                lightbox.show({lightbox: false}, $('#lightbox').data('target'));

                            // actualiza el menu
                            $('#menu_light').find('span').remove();

                            lightbox.stop();

                            return true
                        }
                    )

                    return false;
                }})(lightbox))
                .end()

        $('body').append(this.__interno.empty);

        // agrega el logotipo
        this.__interno.logo = $('<a href="#" style="background: url(\'styles/general/logob.gif\') no-repeat 0px 0px; width: 157px; height: 50px; overflow: hidden; display: block; text-align: left; text-decoration: none; text-indent: -10000px; z-index: 102; ">Moises Levy :: Lightbox</a>')
            .css({
                'position' : document.all ? 'absolute' : 'fixed',
                'top' : '10px',
                'left': '10%',
                'display' : 'none'
            })
            .click((function(lightbox) { return function (e) {
                lightbox.stop();
                return false;
            }})(lightbox))

        $('body').append(this.__interno.logo);

        // agrega el pie
        this.__interno.foot = $('<div style="width: 100%; text-align: center; color: #6B6B6B; font-size: 13px; z-index: 102; background: transparent; "><p style="padding: 20px 50px; margin: 0px; background: transparent;  ">You can access to this screen at any time by selecting “Lightbox” in the left menu on the main screen</p></div>')
            .css({
                'position' : document.all ? 'absolute' : 'fixed',
                'bottom': '0px',
                'left': '0px'
            })

        $('body').append(this.__interno.foot);

        // solicita el listado
        modTT780(
            'lightbox_c.listado',
            {},
            (function (lightbox) { return function (data) {
                try {
                    data = eval('(' + data.responseText + ')');
                }
                catch(e) {
                    if(confirm('Operation fail. Try again?')) {
                        $('#lightbox').data('activo', false)

                        return lightbox.start();
                    }

                    return false;
                }

                // remueve el mensaje de carga
                bpage.hideMessage();

                // revisa el listado
                var content = $(data);

                if(content.length == 0) {
                    alert('No items to display\n\nPlease choose and add images to the lightbox first');

                    // desbloquea los botones
                    $('#lightbox').data('activo', false)
                    $('#menu_light, #lightbox').css('opacity', 1)

                    // desbloquea la pagina
                    bpage.hide();

                    return false;
                }

                // dimensiones de la matriz
                var cuadro = content.length < 4 ? content.length : Math.ceil(Math.sqrt(content.length));

                // manda llamar la galeria
                galeriebox.show(
                    content,
                    {
                        cols: cuadro,
                        rows: cuadro,
                        render: function (target, i) {
                            var width = '96%';
                            var height = 'auto';

                            var top = '0%';
                            var left = '0%';

                            var zona = {
                                width : $(target).width(),
                                height: $(target).height()
                            }

                            var zos = $(target).offset();

                            var dim = lightbox.__dim();

                            // pedido
                            var pedido = this.src.match(/pedido=(\d{8}-\d{2})/);

                            // area
                            var area = this.src.match(/area=([\d\.]+)x([\d\.]+)/)

                            // aspecto
                            var aspecto = this.src.match(/aspecto=(\d+)x(\d+)/)

                            if(area) {
                                width  = (100 * (area[1] * dim.width / 100) / zona['width']) + '%';
                                height = (100 * (area[2] * dim.height / 100) / zona['height']) + '%';
                            }
                            // tamanno en pixeles
                            else if(aspecto) {
                                aspecto['width'] = aspecto[1];
                                aspecto['height'] = aspecto[2];

                                var referencia_1 = aspecto['width'] / aspecto['height'] < zona['width'] / zona['height'] ? 'height' : 'width';
                                var referencia_2 = referencia_1 == 'height' ? 'width' : 'height';

                                aspecto[referencia_2] = aspecto[referencia_2] * zona[referencia_1] / aspecto[referencia_1];

                                eval(referencia_2 + " = (96 * (aspecto[referencia_2] / zona[referencia_2])) + '%'");
                                eval(referencia_1 + " = '96%'");
 
                                left = ((100 - width.replace('%', '')) / 2) + '%';
                                top = ((100 - height.replace('%', '')) / 2) + '%';
                            }

                            // coord
                            var coord = this.src.match(/coord=([\d\.]+)x([\d\.]+)/)
                            if(coord) {
                                left = (100 * (coord[1] * dim.width / 100 - zos.left) / zona['width']) + '%';
                                top  = (100 * (coord[2] * dim.height / 100 - zos.top) / zona['height']) + '%';
                            }

                            return $('<div style="background: url(scripts/loading.gif) center center no-repeat #fff; text-align: center; border: 3px solid #fff; width: ' + width + '; height: ' + height + '; position: absolute; top: ' + top + '; left: ' + left + '; "> \
                                        <img src="' + this.src + '" style="width: 100%; height: 100%; background: transparent; display: none; "> \
                                      </div> \
                                    ')
                                        .find('img')
                                            .load(function () {
                                                    if($(this).data('marca'))
                                                        return;

                                                    $(this).data('marca', true)

                                                    $(this).fadeIn('fast');
                                            })
                                            .each(function () {
                                                if(this.complete && !$(this).data('marca'))
                                                    $(this).load();
                                            })
                                            .end()
                                        .append(
                                            $('<div style="color: #fff; font-size: 11px; position: absolute; top: 0px; right: 0px; width: 15px; height: 15px; text-align: center; vertical-align: middle; background: url(scripts/mini_cerrar.gif) no-repeat center center #000; border: 1px solid #fff;" title="Drop"></div>')
                                                .click((function (lightbox, src) { return function (e) {
                                                    e.stopPropagation();
                                                    
                                                    if(!confirm('Sure you want drop the item?'))
                                                        return false;
                                                    
                                                    // elimina manejadores
                                                    $(this).unbind('click');

                                                    lightbox.remove(src, this.parentNode)

                                                    return false;
                                                }})(lightbox, this.src))
                                        )
                                        .append(
                                            $('<div style="color: #fff; font-size: 11px; position: absolute; top: 0px; right: 25px; width: 15px; height: 15px; text-align: center; vertical-align: middle; background: url(scripts/' + (pedido ? 'mini_carrito_quitar.gif' : 'mini_carrito_agregar.gif') + ') no-repeat center center #000; border: 1px solid #fff; " title="' + (pedido ? 'Unpurchase' : 'Purchase') + '"></div>')
                                                .click((function (lightbox, src) { return function (e) {
                                                    e.stopPropagation();

                                                    // bloquea terceros
                                                    galeriebox.block();

                                                    // bloquea elementos propios
                                                    for(a in lightbox.__interno)
                                                        if(lightbox.__interno[a])
                                                            lightbox.__interno[a].css('z-index', 1);

                                                    bpage.showMessage();


                                                    purchase.profile(
                                                        {
                                                            width: aspecto[1],
                                                            height: aspecto[2],
                                                            pedido: pedido ? pedido[1] : ''
                                                        },
                                                        '?mod=portafolio.perfil&p=' + src.match(/p=(\d+)/)[1] + '&id=' + (src.match(/id=(\d+)/) ? src.match(/id=(\d+)/)[1] : '') + '&com_buscar=' + (src.match(/com_buscar=([^&]*)/) ? src.match(/com_buscar=([^&]*)/)[1] : ''),
                                                        (function (lightbox) { return function () {
                                                            // desbloquea terceros
                                                            galeriebox.unblock();

                                                            // desbloquea elementos propios
                                                            for(a in lightbox.__interno)
                                                                if(lightbox.__interno[a])
                                                                    lightbox.__interno[a].css('z-index', 102);

                                                        }})(lightbox),
                                                        (function (lightbox, button) { return function (agregado) {
                                                            $(button)
                                                                .css('background-image', 'url(scripts/' + (agregado ? 'mini_carrito_quitar.gif' : 'mini_carrito_agregar.gif') + ')')
                                                                .css('title', agregado ? 'Unpurchase' : 'Purchase')

                                                            purchase.show('', data, src)
                                                            purchase.stop(function () {
                                                                // desbloquea terceros
                                                                galeriebox.unblock();

                                                                // desbloquea elementos propios
                                                                for(a in lightbox.__interno) {
                                                                    
                                                                    if(lightbox.__interno[a])
                                                                        lightbox.__interno[a].css('z-index', 102);
                                                                }

                                                                return;
                                                            });

                                                        }})(lightbox, this)
                                                    );

                                                    return false;
                                                }})(lightbox, this.src))
                                        )
                                        .square({
                                            onChange: function (medidas) {
                                                if($(this).data('activo'))
                                                    return ;

                                                lightbox.tareaNueva();

                                                $(this).data('activo', true);

                                                var os = $(this).offset();

                                                var __onChange = function (url) {
                                                    var dim = lightbox.__dim();
                                                    
                                                    modTT780(
                                                        'lightbox_c.modificar',
                                                        lightbox.__target(
                                                            url,
                                                            {
                                                                area: (100 * medidas.width / dim.width).toFixed(2) + 'x' + (100 * medidas.height / dim.height).toFixed(2),
                                                                coord: (100 * os.left / dim.width).toFixed(2) + 'x' + (100 * os.top / dim.height).toFixed(2)
                                                            }
                                                        ),
                                                        (function (square) { return function (data) {
                                                            try {
                                                                data = eval('(' + data.responseText + ')');
                                                            }
                                                            catch(e) {
                                                                if(confirm('Operation fail. Try again?')) {
                                                                    $(square).data('activo', false)

                                                                    __onChange(url);
                                                                }

                                                                return;
                                                            }

                                                            lightbox.tareaTerminada();

                                                            $(square).data('activo', false)

                                                            return;
                                                        }})(this)
                                                    );
                                                }

                                                __onChange.apply(this, [$(this).find('img').attr('src')]);
                                            }
                                        })

                        }
                    }
                );

                for(a in lightbox.__interno)
                    if(a != 'wait')
                        lightbox.__interno[a].css('display', 'block')

                return false;
            }})(this)
        );
    },
    stop: function () {
        // remueve manejadores de la tecla 'esc'
        $(document).unbind('keyup');

        // remueve elementos propios
        for(a in this.__interno)
            if(this.__interno[a])
                this.__interno[a].remove();

        // remueve terceros
        galeriebox.hide();
        bpage.hide();

        // desbloquea botones
        $('#menu_light, #lightbox').css('opacity', 1)

        $('#lightbox').data('activo', false)
    },


    // operaciones del componente
    add: function (url) {
        // bloquea la pantalla
        bpage.show({
            message: $('<div style="background: url(scripts/loadingb.gif) center 20px no-repeat #000; border: 1px solid #888; width: 150px; height: 100px; text-align: center; color: #fff; font-size: 10px; "><div style="position: absolute; bottom: 10px; left: 0px; width: 100%; background: transparent; ">ADDING TO LIGHTBOX...</a></div>')
        });

        modTT780(
            'lightbox_c.agregar',
            this.__target(url),
            (function (lightbox) { return function (data) {
                try {
                    data = eval('(' + data.responseText + ')');
                }
                catch(e) {
                    alert('Failed operation');
                    data = true;
                }

                if(data === false)
                    alert('Error adding image ');
                else {
                    // actualiza el boton
                    lightbox.show({lightbox: data > 0}, url);

                    // actualiza el menu
                    var sp = $('#menu_light').find('span')
    
                    if(sp.length == 0)
                        $('#menu_light a').append(' <span>(1)</span>')
                    else
                        sp.html('(' + data + ')')
                }

                bpage.hide();
                lightbox.start();

            }})(this)
        )
    },
    remove: function (url, objImagen) {
        // agrega indicador de trabajo sobre el objeto
        this.tareaNueva(objImagen);

        modTT780(
            'lightbox_c.quitar',
            this.__target(url),
            (function (lightbox) { return function (data) {
                try {
                    data = eval('(' + data.responseText + ')');
                }
                catch(e) {
                    alert('Failed operation');
                    data = true;
                }

                if(data === false)
                    alert('Error removing image ');
                else {
                    var t1 = lightbox.__target($('#lightbox').data('target'))
                    var t2 = lightbox.__target(url)

                    var e = true;
                    for(a in t1)
                        if(t1[a] != t2[a]) {
                            e = false;
                            break;
                        }

                    // actualiza el boton si es necesario
                    if(e)
                        lightbox.show({lightbox: false}, url);
    
                    // actualiza el menu
                    var sp = $('#menu_light').find('span')
    
                    if(data == 0) {
                        sp.remove();
                        lightbox.stop();
                    }
                    else {
                        sp.html('(' + data + ')')
                        $(objImagen).remove()
                    }
                }

                // remueve el indicador de trabajo sobre el objeto
                lightbox.tareaTerminada(objImagen);

            }})(this)
        );
    },


    tareaNueva: function (objImagen) {
        $(objImagen).css('opacity', .7);

        if(this.__interno.wait.css('display') != 'block')
            return this.__interno.wait
                    .css('display', 'block')
                    .html(1)

        return this.__interno.wait.html(parseInt(this.__interno.wait.html(), 10) + 1)
    },
    tareaTerminada: function (objImagen) {
        $(objImagen).css('opacity', 1);

        if(parseInt(this.__interno.wait.html(), 10) == 1)
            return this.__interno.wait
                    .html('')
                    .css('display', 'none')

        return this.__interno.wait.html(parseInt(this.__interno.wait.html(), 10) - 1)
    }
}

