﻿//heavily modified by bryan migliorisi
var ___sbE=null;

jQuery.fn.extend({
    openStagaBox: function(params) {
        return this.each(function() {
            ___sbE = this;
            $e = $(this);
            var ___sbHTML = $e.html();
            $e.find('*').each(function(i, e) {
                if (typeof $(e).attr('id') != 'undefined' && $(e).attr('id') != '') {
                    if (!$(e).hasClass('sbIdChanged')) {
                        $(e)
                            .attr('id', '___sb' + $(e).attr('id'))
                            .addClass('sbIdChanged');
                    }
                }
            });
            params.message = ___sbHTML;

            staga.UI.displayMessage(params);
        });
    },
    closeStagaBox: function() {
        $(document).trigger('close.stagaBox');
    },
    processcloseStagaBox: function() {
        return this.each(function() {
            $e = $(this);
            $e.find('*.sbIdChanged').each(function(i, e) {
                $(e).attr('id', $(e).attr('id').substr(5)).removeClass('sbIdChanged');
            });
            if (typeof $.stagaBox.settings.params.onClose == 'function') { $.stagaBox.settings.params.onClose.call($); }             // @EXTENDED 
        });
    },
    loadImageBox: function(reload) {
        if (typeof $.stagaBox.settings.imageBoxList == 'undefined') { $.stagaBox.settings.imageBoxList = []; }
        delete $.stagaBox.settings.preloadList;
        
        return this.each(function(i, e) {
            var rel = $(this).attr('rel').replace(' ', '_');
            if (rel == '') { rel = 'default'; }
            if (reload) {
                $.stagaBox.settings.imageBoxList[rel] = [];
                reload = false;
            } else {
                if (typeof $.stagaBox.settings.imageBoxList[rel] == 'undefined') { $.stagaBox.settings.imageBoxList[rel] = []; }
            }
            $.stagaBox.settings.imageBoxList[rel].push({
                imageId: i,
                imageUrl: this.href
            });
            $(this).unbind('click').click(function() {
                try {
                    $.stagaBox.displayImage(rel, i);
                }
                catch (ex) {
                    staga.log(ex)
                }
                return false;
            });

        });

    }
});


(function($) {
    $.stagaBox = function(params) {
        params = $.extend({}, staga.UI.stagaBoxDefaults, params);
        $.stagaBox.init({}, params);
        $.stagaBox.loading();
        $.stagaBox.reveal(params.message, params.title, params.css, params);
    };

    $.stagaBox.settings = {
        loading_image: '/style/themes/common/loading.gif',
        close_image: '/style/themes/common/closelabel.gif',
        image_types: ['png', 'jpg', 'jpeg', 'gif'],
        //stagaBox_html: '<div id="stagaBox" style="display:none;"> <div class="popup"> <table> <tbody> <tr> <td class="tl"/><td class="b"/><td class="tr"/> </tr> <tr> <td class="b"/><td class="body"><div class="header"></div> <div class="content"> </div> <div class="footer"> <a href="#" class="close"> <img src="/style/themes/common/closelabel.gif" title="close" class="close_image" /> </a> </div> </td> <td class="b"/> </tr> <tr> <td class="bl"/><td class="b"/><td class="br"/> </tr> </tbody> </table> </div> </div>',
        stagaBox_html: '<div id="stagaBox" style="display:none;"> <div class="popup"> <table> <tbody> <tr> <td class="tl"/><td class="b"/><td class="tr"/> </tr> <tr> <td class="b"/><td class="body"><div class="header"></div> <div class="content"> </div> <div class="footer" style="border:none; padding:0;"> </div> </td> <td class="b"/> </tr> <tr> <td class="bl"/><td class="b"/><td class="br"/> </tr> </tbody> </table> </div> </div>'
    };

    $.stagaBox.loading = function(params) {
        if ($('#stagaBox .loading').length == 1) return true;
        $('#stagaBox .content').empty();
        $('#stagaBox .body')
            .children().hide().end()
            .append('<div class="loading"><img src="' + $.stagaBox.settings.loading_image + '"/></div>');
        var pageScroll = $.stagaBox.getPageScroll();
        
        $('#stagaBox').css({
            top: pageScroll[1] + ($.stagaBox.getPageHeight() / 10),
            left: pageScroll[0]
        }).show();
        
        $(document).unbind('keydown.stagaBox').bind('keydown.stagaBox', function(e) {
            if (e.keyCode == 27) {
                $.stagaBox.close();
            }
            if ($.stagaBox.settings.params.imageBox) {
                if (e.keyCode == 37) {
                    // left
                    $.stagaBox.switchImage($.stagaBox.settings.params.imageIndex - 1);
                }
                if (e.keyCode == 39) {
                    // right
                    $.stagaBox.switchImage($.stagaBox.settings.params.imageIndex + 1);
                }
            }
        });
    };

    $.stagaBox.imageBox = function() {
        $('.post-gallery-item a.post-image-enlarge').each(function(i, e) {
            $(e).unbind().click(function() {
                staga.UI.displayMessage({
                    message: '<img src="' + this.href + '" alt="" />',
                    title: "Uploaded Image",
                    imageBox: true,
                    imageList: postImages,
                    imageIndex: i
                });
                return false;
            });
        });
    };

    $.stagaBox.displayImage = function(rel, index) {
        $.stagaBox.settings.currentImageList = rel;
        $.stagaBox.preloadImages(rel, function() {
            staga.UI.displayMessage({
                message: '<img src="' + $.stagaBox.settings.imageBoxList[rel][index].imageUrl + '" alt="" />',
                title: "Uploaded Image",
                imageBox: true,
                imageIndex: index,
                onLoad: function() {
                    var $sbContent = $('#stagaBox .content');
                    $sbContent
                        .width($sbContent.find('img').width())
                        .height($sbContent.find('img').height())
                        .addClass('content-loading');
                }
            });
        });
    };

    $.stagaBox.preloadImages = function(rel, callback) {
        if (typeof $.stagaBox.settings.preloadList == 'undefined') { $.stagaBox.settings.preloadList = {}; }
        if (typeof $.stagaBox.settings.preloadList[rel] != 'undefined') {
            // already preloaded, exit
            callback();
            return false;
        }
        var $sbContent = $('body');
        var imageList = $.stagaBox.settings.imageBoxList[rel];
        $.stagaBox.settings.preloadList[rel] = true;
        for (var i = 0, len = imageList.length; i < len; i++) {
            var id = "_stagaBox-" + rel + i
            if ($('#' + id).length == 0) {
                $('<img />')
                .attr('id', id)
                .attr('rel', rel)
                .attr('src', imageList[i].imageUrl)
                .addClass('stagaBoxImage')
                .load(function() { callback() })
                .appendTo($sbContent)
                .hide();
            }
        }
        //callback();
    };



    $.stagaBox.switchImage = function(newImageIndex) {

        var imageList = $.stagaBox.settings.imageBoxList[$.stagaBox.settings.currentImageList]
        var nextImage = imageList[newImageIndex];

        if (typeof nextImage != 'undefined') {
            $.stagaBox.settings.params.imageIndex = newImageIndex;
            var $sbContent = $('#stagaBox .content');
            var $originalImage = $('img#_stagaBox-' + $.stagaBox.settings.currentImageList + newImageIndex);
            var $newImage;
            if ($originalImage.length != 0) {
                $newImage = $originalImage.clone().appendTo($sbContent);
            } else {
                //we must have some images that arent pre-loaded so lets do that now
                staga.log('img#_stagaBox-' + $.stagaBox.settings.currentImageList + newImageIndex, "does not exist");
                return;
            }
            var $curImage = $('#stagaBox .content img:visible');

            $curImage.animate({ opacity: 0 }, 200, function() {
                $sbContent.animate({
                    height: $newImage.height(),
                    width: $newImage.width()
                }, 500, function() {
                    $newImage.fadeIn(300);
                });
            }).remove();
        }
    };

    $.stagaBox.reveal = function(data, header, klass, params) {
        header = header ? header : "";
        var formattedHeader;
        if ($.stagaBox.settings.params.closeButton) {
            formattedHeader = "<span class='text'>{0}</span><span class='close' onclick='$.stagaBox.close();'>X</span>".format(header);
        } else {
            formattedHeader = header;
        }
        $('#stagaBox .header').removeAttr('class').addClass('header').html(formattedHeader).addClass(klass ? klass : "");

        if (typeof params.formatData != 'undefined') { data = data.format.apply(data, params.formatData); }
        if (typeof params.height == 'number') { $('#stagaBox .content').css('height', params.height); }
        if (typeof params.width == 'number') { $('#stagaBox .content').css('width', params.width); }
        $('#stagaBox .loading').remove();
        $('#stagaBox .content').removeAttr('style').append(data);
        $('#stagaBox .body').children().fadeIn('normal');
        if (typeof params.onLoad == 'function') { params.onLoad(data); } // @EXTENDED
        if (params.keepCentered) {
            $(document).scroll(function() {
                clearTimeout(params.timer)
                params.timer = setTimeout(function() {
                    var x = $(window).scrollTop() + 30;
                    $('#stagaBox').animate({ top: x }, 350)
                }, 200);
            });
        }
    };

    $.stagaBox.center = function() { }

    $.stagaBox.close = function() {
        $(document).trigger('close.stagaBox');
        return false;
    };

    $(document).bind('close.stagaBox', function() {
        $(document).unbind('keydown.stagaBox');
        $('#stagaBox').fadeOut(function() {
            $('#stagaBox .content').removeClass().addClass('content');
            staga.UI.dimScreenStop();
        });

        if (typeof ___sbE != null) { $(___sbE).processcloseStagaBox(); }

    })

    $.fn.stagaBox = function(settings) {
        $.stagaBox.init(settings);

        var image_types = $.stagaBox.settings.image_types.join('|');
        image_types = new RegExp('\.' + image_types + '$', 'i');

        function click_handler() {
            $.stagaBox.loading(true);

            var klass = this.rel.match(/stagaBox\[\.(\w+)\]/);
            if (klass) klass = klass[1];

            if (this.href.match(/#/)) {
                var url = window.location.href.split('#')[0];
                var target = this.href.replace(url, '');
                $.stagaBox.reveal($(target).clone().show(), klass);

            } else if (this.href.match(image_types)) {
                var image = new Image();
                image.onload = function() {
                    $.stagaBox.reveal('<div class="image"><img src="' + image.src + '" /></div>', klass);
                };
                image.src = this.href;

            } else {
                $.get(this.href, function(data) { $.stagaBox.reveal(data, klass) });
            };

            return false;
        };

        this.click(click_handler);
        return this;
    };

    $.stagaBox.init = function(settings, params) {
        $('#stagaBox .close').show();
        $('#stagaBox').remove();

        $.stagaBox.settings.inited = true;
        $.stagaBox.settings.params = params;

        if (settings) $.extend($.stagaBox.settings, settings);

        //        if (params.closeButton) {
        //            $('body').append($.stagaBox.settings.stagaBox_html);
        //        } else {
        //            $('body').append($.stagaBox.settings.stagaBoxNoClose_html);
        //        }
        $('body').append($.stagaBox.settings.stagaBox_html);

        var preload = [new Image(), new Image()];
        preload[0].src = $.stagaBox.settings.close_image;
        preload[1].src = $.stagaBox.settings.loading_image;

        $('#stagaBox').find('.b:first, .bl, .br, .tl, .tr').each(function() {
            preload.push(new Image());
            preload.slice(-1).src = $(this).css('background-image').replace(/url\((.+)\)/, '$1');
        });

        $('#stagaBox .close').click(function() {
            $(this).hide();
            $.stagaBox.close();
            return false;
        });

        $('#stagaBox .close_image').attr('src', $.stagaBox.settings.close_image);
    };

    $.stagaBox.getPageScroll = function() {
        var xScroll, yScroll;
        if (self.pageYOffset) {
            yScroll = self.pageYOffset;
            xScroll = self.pageXOffset;
        } else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
            yScroll = document.documentElement.scrollTop;
            xScroll = document.documentElement.scrollLeft;
        } else if (document.body) {// all other Explorers
            yScroll = document.body.scrollTop;
            xScroll = document.body.scrollLeft;
        };
        return new Array(xScroll, yScroll);
    };

    $.stagaBox.getPageHeight = function() {
        var windowHeight;
        if (self.innerHeight) {	// all except Explorer
            windowHeight = self.innerHeight;
        } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
            windowHeight = document.documentElement.clientHeight;
        } else if (document.body) { // other Explorers
            windowHeight = document.body.clientHeight;
        }
        return windowHeight;
    };
})(jQuery);
