/*files:/home/digivotion/releases/3.5.1/digiself-core/application/modules/default/public/plugins/digibox/jquery.digibox.js*/
/*jquery.digibox.js*/
// DigiBox v0.1 - a lightbox variant jQuery 1.4.2+
// Copyright (c) 2011 Digivotion - info@digivotion.com
(function($, window, document){

    //Default settings 
    var defaultOptions = {
        initialWidth: 48,
        maxWidth: false,
        width: false,
        
        initialHeight: 48,
        maxHeight: false,
        height: false,

        fadeSpeed: 200,

        html: false,
        url: false,
        iframe: false,

        title: '',

        runInlineJavascript: false,
        runExternalJavascript: false
    };

    //Cached parameters
    var $window;
    var $document;
    var $wrapper;
    var $wrapperOpacity;
    var $container;
    var $content;
    var $title;
    var $result;
    var $loading;
    var $isLoading;
    var $passedOptions;
    var $currentOptions;
    var $forceReload;
    var $reloadElement;
    var $clickFunctionSet = false;

    //Other variables
    var imgRegExp = /\.(jpg|gif|png|bmp|jpeg)(.*)?$/i;

    // ****************
    // Private functions
    // ****************
    
    /**
     * Check the options
     */
    _checkOptions = function(obj, options){
        //Check if the options are valid
        options.fadeSpeed = (isNaN(options.fadeSpeed)) ? defaultOptions.fadeSpeed : options.fadeSpeed;
        options.initialWidth = (isNaN(options.initialWidth)) ? defaultOptions.initialWidth : options.initialWidth;
        options.initialHeight = (isNaN(options.initialHeight)) ? defaultOptions.initialHeight : options.initialHeight;

        //If this is a link and none of the input types are set use the href tag (if it is set)
        if (options.html === false && options.url === false && options.iframe === false && obj.tagName == 'A' && $.trim($(obj).attr('href')).length > 0){
            options.url = $(obj).attr('href');
        }

        if ($.trim(options.title).length == 0 && $.trim($(obj).attr('title')).length > 0){
            options.title = $(obj).attr('title');
        }

        //Return the fixxed options
        return options;
    }

    /**
     * Open the digibox
     */
    _open = function(obj, reloading){
        //Get the current options
        $currentOptions = _checkOptions(obj, $(obj).data('digibox'));
        $(obj).data('digibox', $currentOptions);
        reloading = reloading || false;

        //Remember that we're loading
        $isLoading = true;

        //If no content is to be loaded just quit and don't load
        if ($currentOptions.html === false && $currentOptions.url === false && $currentOptions.iframe === false){
            throw('Missing either html, url or iframe option');
        }

        //Display the digibox
        if (!reloading){
            var position = _centerPosition($currentOptions.initialWidth, $currentOptions.initialHeight);
            $container.css({
                width: $currentOptions.initialWidth +'px',
                height: $currentOptions.initialHeight +'px',
                top: position.top +'px',
                left: position.left +'px',
                display: 'block',
                opacity: 0 
            });
        }

        $content.hide();
        $loading.show();
       
        if (!reloading){
            $wrapper.css({display: 'block', opacity: 0});
            $wrapper.animate({opacity: $wrapperOpacity}, {duration: $currentOptions.fadeSpeed, queue: false});
            $container.animate({opacity: 1}, {duration: $currentOptions.fadeSpeed, queue: false});
        }

        //Handle the title if present
        if ($.trim($currentOptions.title).length > 0){
            $title.html($currentOptions.title);
            $title.show();
        } else {
            $title.hide();
        }

        //Get the type of content
        var type;
        if ($currentOptions.iframe !== false){
            type = 'iframe';
        } else if ($currentOptions.html){
            type = 'html';
        } else {
            if ($currentOptions.url.match(imgRegExp)){
                type = 'image';
            } else {
                type = 'ajax';
            }
        }

        //Handle the content by type
        switch (type){
            case 'html':
                $result[0].innerHTML = $currentOptions.html;
                _runScripts();
                _complete();
                break;

            case 'image':
                //Preload the image
                var preloader = new Image();
                
                preloader.onerror = function(){
                    _error();
                }

                preloader.onload = function(){
                    preloader.onerror = null;
                    preloader.onload = null;

                    var aspectRatio = preloader.width / preloader.height;
                    var width = preloader.width;
                    var height = preloader.height;

                    //Image size stuff
                    //Max width or height
                    if($currentOptions.maxWidth !== false || $currentOptions.maxHeight !== false){
                        if($currentOptions.maxWidth !== false && preloader.width > $currentOptions.maxWidth && $currentOptions.maxHeight !== false && preloader.height > $currentOptions.maxHeight){
                            if ((preloader.width / $currentOptions.maxWidth) < (preloader.height / $currentOptions.maxHeight)){
                                if ($currentOptions.width === false){
                                    width = $currentOptions.maxWidth;
                                }
                                if ($currentOptions.height === false){
                                    height = parseInt($currentOptions.maxWidth / aspectRatio);
                                }
                            } else {
                                if ($currentOptions.width === false){
                                    width = parseInt($currentOptions.maxHeight * aspectRatio);
                                }
                                if ($currentOptions.height === false){
                                    height = $currentOptions.maxHeight;
                                }
                            }
                        } else if($currentOptions.maxWidth !== false && preloader.width > $currentOptions.maxWidth){
                            if ($currentOptions.width === false){
                                width = $currentOptions.maxWidth;
                            }
                            if ($currentOptions.height === false){
                                height = parseInt($currentOptions.maxWidth / aspectRatio);
                            }
                        } else if($currentOptions.maxHeight !== false && preloader.height > $currentOptions.maxHeight){
                            if ($currentOptions.width === false){
                                width = parseInt($currentOptions.maxHeight * aspectRatio);
                            }
                            if ($currentOptions.height === false){
                                height = $currentOptions.maxHeight;
                            }
                        }
                    }

                    //Width or height
                    if ($currentOptions.width !== false || $currentOptions.height !== false){
                        if ($currentOptions.height === false){
                            width = $currentOptions.width;
                            height = parseInt($currentOptions.width / aspectRatio);
                        } else if ($currentOptions.width === false){
                            width = parseInt($currentOptions.height * aspectRatio);
                            height = $currentOptions.height;
                        } else {
                            width = $currentOptions.width;
                            height = $currentOptions.height;
                        }
                    }

                    $currentOptions.width = width;
                    $currentOptions.height = height;

                    $result.html(
                        $("<img />").attr({
                            'src' : preloader.src,
                            'alt' : $(obj).attr('title')
                        }).css({
                            display: 'block',
                            width: $currentOptions.width,
                            height: $currentOptions.height})
                    );

                    _complete();
                }

                preloader.src = $currentOptions.url;
                break;

            case 'iframe':

                if ($currentOptions.iframe.indexOf('?') > -1){
                    $currentOptions.iframe += '&' +new Date().getTime();
                } else {
                    $currentOptions.iframe += '?' +new Date().getTime();
                }

                var iframe = $('<iframe></iframe>').attr({
                    id: 'digiboxFrame',
                    scrolling: 'no',
                    frameborder: 0,
                    name: 'digiboxFrame' +new Date().getTime(),
                    src: $currentOptions.iframe
                });
                iframe[0].src = $currentOptions.iframe;

                $result.html(iframe);
                iframe[0].contentWindow.location.replace($currentOptions.iframe);

                iframe.bind('load', function(){
                    //Get the content size
                    var sizeContainer = $("<div></div>"); 
                    sizeContainer.attr('id', 'tempDigiboxSizeContainer');
                    sizeContainer.css({
                        left: '-99999px',
                        top: '-99999px',
                        position: 'absolute',
                        display: 'block'
                    });
                    
                    sizeContainer[0].appendChild(innerShiv($result.clone().html()));
                    $('iframe', sizeContainer)[0].id = 'tempDigiboxSizeIframe';
                    $('iframe', sizeContainer)[0].name = 'tempDigiboxSizeIframe' +new Date().getTime();
            
                    $document[0].body.appendChild(sizeContainer[0]);
                    
                    $('#tempDigiboxSizeIframe').bind('load', function(){
                        try {
                            var frameBody = $document[0].frames($('#tempDigiboxSizeIframe').attr('id')).document.body;
                        } catch (e){
                            var frameBody = $('#tempDigiboxSizeIframe')[0].contentDocument.body;
                        }

                        var height = 0;
                        var width = 0;
                        $(frameBody).children().filter(':visible').each(function(){
                            if ($(this).css('marginLeft') == 'auto'){
                                $(this).css('marginLeft', 0);
                            }
                            
                            if ($(this).css('marginRight') == 'auto'){
                                $(this).css('marginRight', 0);
                            }

                            if (!($.browser.msie && $.browser.version < 9) || $(this).css('display') == 'block'){
                                height += $(this).height();
                                width += $(this).width();
                            }

                            var top = parseInt($.curCSS(this, 'top'), 10);
                            if(isFinite(top)) {
                                height += top;
                            }
                            
                            var left = parseInt($.curCSS(this, 'left'), 10);
                            if(isFinite(left)) {
                                width += left;
                            }

                        });

                        _complete(width, height);
                    });
                })

                break;

            case 'ajax':
                $.ajax({
                    url: $currentOptions.url,
                    dataType: 'html',
                    success: function(data){
                        var result = data.substring(data.indexOf('<body'), (data.indexOf('</body>') +7)); //Dirty ugly fix becuase somehow jquery's load function can't take 'body' as a selector for the page fragment
                        $result[0].innerHTML = result;

                        //Correct the external links
                        $result.find('[src]').each(function(){
                            if (!/^(.*:)*\/\//ig.test($(this).attr('src'))){
                                
                                //If we have a base path use that
                                var baseBegin = data.indexOf('<base');
                                if (!/^\/[^\/]{1}.*/ig.test($(this).attr('src')) && baseBegin > 0){
                                    var base = $(data.substring(baseBegin, data.indexOf('>', baseBegin) + 1)).attr('href');
                                    $(this).attr('src', base + $(this).attr('src'));
                                }

                                //Otherwise try to deduce the path from the link
                                else {
                                    var tempAnchor = $('<a></a>');
                                    tempAnchor.attr('href', $currentOptions.url);
                                    if (/^\/[^\/]{1}.*/ig.test($(this).attr('src'))){
                                        $(this).attr('src', tempAnchor.attr('protocol') + '//' + tempAnchor.attr('hostname') + $(this).attr('src'));
                                    } else {
                                        $(this).attr('src', tempAnchor.attr('protocol') + '//' + tempAnchor.attr('hostname') + tempAnchor.attr('pathname') + '/' + $(this).attr('src'));
                                    }
                                }
                            }
                        });

                        _runScripts();
                        _complete();
                    },
                    error: function(){
                        _error();
                    }
                });
                break;
        }
    }
   
   /*
    * Handle the scripts in the HTML
    */
    _runScripts = function(){
        if ($currentOptions.runInlineJavascript || $currentOptions.runExternalJavascript){
            $result.find('script').each(function(){

                //Load external javascripts
                if ($(this).attr('src') !== undefined && $currentOptions.runExternalJavascript){
                    $.getScript($(this).attr('src'));
                }
                
                //Load inline javascript
                else if ($(this).attr('src') === undefined && $currentOptions.runInlineJavascript) {
                    $.globalEval(this.innerHTML.replace('<![CDATA[', '').replace(']]>', ''));
                }
            });
        }
    }

    /**
     * If an error occurs display it
     */
    _error = function(){
        $result.html('No content could be loaded');
        _complete();
    }

    /**
     * Once the content has finished loading show the content
     */
    _complete = function(realWidth, realHeight){

        //Get the new dimensions of the lightbox
        realHeight = realHeight || false;
        realWidth = realWidth || false;

        //Create a temporary container to get the contents size
        if (realWidth === false || realHeight === false){
            var sizeContainer = $("<div></div>"); 
            sizeContainer.attr('id', 'tempDigiboxSizeContainer');
            sizeContainer.css({
                left: '-99999px',
                top: '-99999px',
                position: 'absolute',
                display: 'block'
            });
            
            sizeContainer[0].appendChild(innerShiv($result.clone().html()));
            $document[0].body.appendChild(sizeContainer[0]);

            $('#tempDigiboxSizeContainer > *').each(function(){
                if ($(this).css('marginLeft') == 'auto'){
                    $(this).css('marginLeft', 0);
                }
                
                if ($(this).css('marginRight') == 'auto'){
                    $(this).css('marginRight', 0);
                }
            });

            realHeight = $('#tempDigiboxSizeContainer').height();
            realWidth = $('#tempDigiboxSizeContainer').width();
        }
        
        //Width
        if ($currentOptions.width !== false && !isNaN($currentOptions.width)){
            var width = $currentOptions.width;
        } else if ($currentOptions.maxWidth !== false && !isNaN($currentOptions.maxWidth)){
            var width = (realWidth > $currentOptions.maxWidth) ? $currentOptions.maxWidth : realWidth;
        } else {
            var width = realWidth;
        }

        //Height
        if ($currentOptions.height !== false && !isNaN($currentOptions.height)){
            var height = $currentOptions.height;
        } else if ($currentOptions.maxHeight !== false && !isNaN($currentOptions.width)){
            var height = (realHeight > $currentOptions.maxHeight) ? $currentOptions.maxHeight : realHeight;
        } else {
            var height = realHeight;
        }


        //Correct for scrollbar sizes
        if ($currentOptions.height === false && width < realWidth){
            if ($currentOptions.maxHeight === false || realHeight + $.scrollbarWidth() < $currentOptions.maxHeight){
                height = height + $.scrollbarWidth();
            }
        }

        if ($currentOptions.width === false && height < realHeight){
            if ($currentOptions.maxWidth === false || realWidth + $.scrollbarWidth() < $currentOptions.maxWidth){
                width = width + $.scrollbarWidth();
            }
        }
        
        if ($currentOptions.iframe !== false && (width < realWidth || height < realHeight)){
            $('#digiboxFrame').attr('scrolling', 'auto');
        } else if ($currentOptions.iframe !== false && $.browser.webkit) {
            $('#digiboxFrame').contents().find('html').css('overflow', 'hidden');
        }

        //Remove the temporary container
        $('#tempDigiboxSizeContainer').remove();
        
        //Left and top
        var left = $container.offset().left - parseInt((width - $container.width()) / 2);
        var top = $container.offset().top - parseInt((height - $container.height()) / 2); 

        left = (left < 0) ? 0 : left;
        top = (top < 0) ? 0 : top;

        //Resize the lightbox and show it's content
        $container.animate(
            {
                width: width, 
                height: height,
                left: left,
                top: top
            }, 
            {
                duration: 500,
                queue: false, 
                complete: function(){
                    //Show the contet
                    $content.css({display: 'block', opacity: 0});
                    $content.animate({opacity: 1}, {
                        duration: 500,
                        queue: false,
                        complete: function(){ 
                            $loading.hide(); 
                            $isLoading = false;
                        }
                    });
                }
            }
        );
    }
    
    /**
     * Center the digibox
     */
    _centerPosition = function(width, height){
        var left = parseInt((($(window).width() - width) / 2) +$(document).scrollLeft());
        var top = parseInt((($(window).height() - height) / 2) +$(document).scrollTop());
       
        left = (left < 0) ? 0 : left;
        top = (top < 0) ? 0 : top;
        
        return {left: left, top: top};
    }


    // ****************
    // Public functions
    // Usage: $.fn.digibox.<function>();
    // Usage from within an iframe: parent.$.fn.digibox.<function>();
    // ****************

    /**
     * The constructor of the digibox
     * Set the options here
     */
    $.fn.digibox = function(options) {
        //If no matches were given for the selector return
        if ($(this).selector && !$(this).length) {
            return this;
        }

        //Set the options
        $passedOptions = options || {};

        //Bind the click event to the selector
        if (!$clickFunctionSet){
            $(this).live('click', function(e){
                $clickFunctionSet = true;

                $(this).data('digibox', $.extend({}, ($(this).data('digibox') || defaultOptions), $passedOptions));
                if (!((e.button !== 0 && typeof e.button !== 'undefined') || e.ctrlKey || e.shiftKey || e.altKey)) {
                    e.preventDefault();
                    _open(this);
                }
            });
        }

        //For chaining methods
        return this;
    }

    /**
     * Initialize the digibox
     */
    $.fn.digibox.init = function(){
        $window = $(window);
        $document = $(document);
        $isLoading = false;

        //Create the content container
        $container = $('<div></div>');
        $container[0].id = 'digibox';
        $('body', $document).prepend($container);
        
        var defaultTemplate = 
            '<div class="close">Close</div>' +
            '<div class="prev">Previous</div>' +
            '<div class="next">Next</div>' +
            '<div class="title"></div>' +
            '<div class="result"></div>';
        $.fn.digibox.template = $.fn.digibox.template || defaultTemplate;
        
        $content = $('<div></div>');
        $content.html($.fn.digibox.template);
        $content.addClass('content');
        $container.append($content);

        $result = $('.result', $content);
        $title = $('.title', $content);
        
        $loading = $('<div></div>');
        $loading.addClass('loading');
        $container.append($loading);

        //Create the wrapper
        $wrapper = $('<div></div>');
        $wrapper[0].id = 'digiboxWrapper';
        $wrapper.bind('click', function(){
            $.fn.digibox.close();
        });
        $('body', $document).prepend($wrapper);
        if ($.browser.msie && $.browser.version < 9){
            $wrapperOpacity = $.curCSS($wrapper[0], 'filter').match(/alpha\(opacity=([0-9]*)\)/)[1] / 100;
        } else {
            $wrapperOpacity = $.curCSS($wrapper[0], 'opacity');
        }

        //Bind the close event to the esc key
        $document.bind('keydown', function(e) {
            if (e.keyCode == 27 && !$isLoading){
                e.preventDefault();
                $.fn.digibox.close();
            }
        });

        //Allow anything with the close class to close the digibox
        $('.close', $content).bind('click', function(){
            $.fn.digibox.close();
        });
    }

    /*
     * Reload the lightbox with the new settings
     */
    $.fn.digibox.reload = function(options){

        //Geto the options
        options = $.extend({}, defaultOptions, (options || {}));
        $reloadElement = $('<a></a>').data('digibox', options);

        //Resize the lightbox and hide it's content
        $isLoading = true;

        $content.animate({opacity: 0}, {
            duration: 500,
            queue: false,
            complete: function(){ 
                $content.hide();
                $loading.show(); 
                
                _open($($reloadElement)[0], true);
            }
        });
    }

    /**
     * Hide the digibox upon request from a iframe use parent.$.digibox.close();
     */
    $.fn.digibox.close = function(){
        $wrapper.animate({opacity: 0}, {
            duration: $currentOptions.fadeSpeed, 
            queue: false, 
            complete: function(){ $wrapper.hide(); }});
        
        $container.animate({opacity: 0}, {
            duration: $currentOptions.fadeSpeed, 
            queue: false, 
            complete: function(){ $container.hide(); }});
    }

    
    //Init the digibox when the dom is ready
    $(document).ready(function() {
        if (!$forceReload){
            //Hide the digibox
            $.fn.digibox.init();
        }
    });

})(jQuery, window, document);

//The getscrollbarwidth library which digibox requires
(function($,b,a){$.scrollbarWidth=function(){var c,d;if(a===b){c=$('<div style="width:50px;height:50px;overflow:auto"><div/></div>').appendTo("body");d=c.children();a=d.innerWidth()-d.height(99).innerWidth();c.remove()}return a}})(jQuery);

//The innershiv library, for all the old IE browsers
window.innerShiv=function(){function h(c,e,b){return/^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i.test(b)?c:e+"></"+b+">"}var c,e=document,j,g="abbr article aside audio canvas datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video".split(" ");return function(d,i){if(!c&&(c=e.createElement("div"),c.innerHTML="<nav></nav>",j=c.childNodes.length!==1)){for(var b=e.createDocumentFragment(),f=g.length;f--;)b.createElement(g[f]);b.appendChild(c)}d=d.replace(/^\s\s*/,"").replace(/\s\s*$/,"").replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/(<([\w:]+)[^>]*?)\/>/g,h);c.innerHTML=(b=d.match(/^<(tbody|tr|td|col|colgroup|thead|tfoot)/i))?"<table>"+d+"</table>":d;b=b?c.getElementsByTagName(b[1])[0].parentNode:c;if(i===!1)return b.childNodes;for(var f=e.createDocumentFragment(),k=b.childNodes.length;k--;)f.appendChild(b.firstChild);return f}}();
