/**
 * jQuery lightBox plugin
 * This jQuery plugin was inspired and based on Lightbox 2 by Lokesh Dhakar (http://www.huddletogether.com/projects/lightbox2/)
 * and adapted to me for use like a plugin from jQuery.
 * @name jquery-lightbox-0.5.js
 * @author Leandro Vieira Pinho - http://leandrovieira.com
 * @version 0.5
 * @date April 11, 2008
 * @category jQuery plugin
 * @copyright (c) 2008 Leandro Vieira Pinho (leandrovieira.com)
 * @license CC Attribution-No Derivative Works 2.5 Brazil - http://creativecommons.org/licenses/by-nd/2.5/br/deed.en_US
 * @example Visit http://leandrovieira.com/projects/jquery/lightbox/ for more informations about this jQuery plugin
 */

// Offering a Custom Alias suport - More info: http://docs.jquery.com/Plugins/Authoring#Custom_Alias
(function($) {
    /**
    * $ is an alias to jQuery object
    *
    */
    $.fn.videoBox = function(settings) {
        // Settings to configure the jQuery lightBox plugin how you like
        settings = jQuery.extend({
            // Configuration related to overlay
            overlayBgColor: '#000',                         // (string) Background color to overlay; inform a hexadecimal value like: #RRGGBB. Where RR, GG, and BB are the hexadecimal values for the red, green, and blue values of the color.
            overlayOpacity: 0.7,                            // (integer) Opacity value to overlay; inform: 0.X. Where X are number from 0 to 9
            // Configuration related to navigation
            fixedNavigation: true,                           // (boolean) Boolean that informs if the navigation (next and prev button) will be fixed or not in the interface.
            // Configuration related to images
            videoLoading: '/images/ajax-loader-video.gif',      // (string) Path and the name of the loading icon
            videoBtnPrev: '/images/pagination-prev.png',  // (string) Path and the name of the prev button video
            videoBtnNext: '/images/pagination-next.png',  // (string) Path and the name of the next button image
            videoBtnClose: '/images/bttn-img-close.png',   // (string) Path and the name of the close btn
            imageBlank: '/images/lightbox-blank.gif',   // (string) Path and the name of a blank image (one pixel)
            // Configuration related to container video box
            containerBorderSize: 20,                              // (integer) If you adjust the padding in the CSS for the container, #lightbox-container-video-box, you will need to update this value
            containerResizeSpeed: 400,                            // (integer) Specify the resize duration of container video. These number are miliseconds. 400 is default.
            // Configuration related to texts in caption. For example: video 2 of 8. You can alter either "video" and "of" texts.
            txtVideo: 'Video',                        // (string) Specify text "video"
            txtOf: 'of',                           // (string) Specify text "of"
            // Configuration related to keyboard navigation
            keyToClose: 'c',                            // (string) (c = close) Letter to close the jQuery lightBox interface. Beyond this letter, the letter X and the SCAPE key is used to.
            keyToPrev: 'p',                            // (string) (p = previous) Letter to show the previous video
            keyToNext: 'n',                            // (string) (n = next) Letter to show the next video.
            // Don�t alter these variables in any way
            videoArray: [],
            activeVideo: 0,
            audio: 0
        }, settings);
        // Caching the jQuery object with all elements matched
        var jQueryMatchedObj = this; // This, in this context, refer to jQuery object
        /**
        * Initializing the plugin calling the start function
        *
        * @return boolean false
        */
        function _initialize() {
            _start(this, jQueryMatchedObj); // This, in this context, refer to object (link) which the user have clicked
            return false; // Avoid the browser following the link
        }
        /**
        * Start the jQuery lightBox plugin
        *
        * @param object objClicked The object (link) whick the user have clicked
        * @param object jQueryMatchedObj The jQuery object with all elements matched
        */
        function _start(objClicked, jQueryMatchedObj) {
            // Hime some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
            $('select').css({
                'visibility': 'hidden'
            });
            // Call the function to create the markup structure; style some elements; assign events in some elements.
            _set_interface();
            // Unset total videos in videoArray
            settings.videoArray.length = 0;
            // Unset video active information
            settings.activeVideo = 0;
            // We have an video set? Or just an video? Let�s see it.
            if (jQueryMatchedObj.length == 1) {
                if (settings.audio)
                    settings.videoArray.push(new Array(objClicked.getAttribute('href'), objClicked.getAttribute('title'), null));
                else
                    settings.videoArray.push(new Array(objClicked.getAttribute('href'), objClicked.getAttribute('title'), objClicked.children('img')));
            } else {
                // Add an Array (as many as we have), with href and title atributes, inside the Array that storage the videos references
            for (var i = 0; i < jQueryMatchedObj.length; i++) {
                if (settings.audio)
                    settings.videoArray.push(new Array(jQueryMatchedObj[i].getAttribute('href'), jQueryMatchedObj[i].getAttribute('title'), null));
                else
                    settings.videoArray.push(new Array(jQueryMatchedObj[i].getAttribute('href'), jQueryMatchedObj[i].getAttribute('title'), jQuery(jQueryMatchedObj[i]).find('img').attr('src')));
                }
            }
            while (settings.videoArray[settings.activeVideo][0] != objClicked.getAttribute('href')) {
                settings.activeVideo++;
            }
            // Call the function that prepares video exibition
            _set_video_to_view();
        }
        /**
        * Create the jQuery lightBox plugin interface
        *
        * The HTML markup will be like that:
        <div id="jquery-overlay" style="background-color: rgb(0, 0, 0); opacity: 0.5; width: 1425px; height: 1083px;"></div>
        <div id="jquery-lightbox" style="top: 112.9px; left: 0pt;">
        <div id="lightbox-container-video-box" style="width: 356px; display: block; height: 394px;">
        <div id="lightbox-container-video">
        <a href="#" id="lightbox-secNav-btnClose"><img src="/images/bttn-img-close.png"></a>
        <span id="lightbox-video-details-caption" style="display: block;">Video Title</span>
        <div id="lightbox-video" style="display: block;">
        <object id="lightbox-video_api" data="/flash/flowplayer-3.1.1.swf?0.6704585746969197" type="application/x-shockwave-flash" height="100%" width="100%"><param name="allowfullscreen" value="true"><param name="allowscriptaccess" value="always"><param name="quality" value="high"><param name="bgcolor" value="#000000"><param name="flashvars" value="config={&quot;clip&quot;:{&quot;autoPlay&quot;:true,&quot;autoBuffering&quot;:true,&quot;src&quot;:&quot;../videos/flowplayer.flv&quot;},&quot;plugins&quot;:{&quot;controls&quot;:null},&quot;playerId&quot;:&quot;lightbox-video&quot;,&quot;playlist&quot;:[{&quot;autoPlay&quot;:true,&quot;autoBuffering&quot;:true,&quot;src&quot;:&quot;../videos/flowplayer.flv&quot;}]}"></object>
        </div>
        <div id="lightbox-loading" style="display: none;">
        <a href="#" id="lightbox-loading-link"><img src="/images/ajax-loader.gif"></a>
        </div>
        </div>

                        <div id="lightbox-container-video-data-box" style="display: block;">
        <div id="lightbox-container-video-data">
        <div id="lightbox-video-controls" style="display: block;"><a class="play">play</a><div class="track"><div class="buffer"></div><div class="progress"></div><div class="playhead"></div></div><div class="time"><span>00:00</span> <strong>00:00</strong></div><a class="mute">mute</a></div>
        <div id="lightbox-video-details">
        <span id="lightbox-video-details-currentNumber" style="display: none;"></span>
        <div style="" id="lightbox-other-videos">
        <div id="lightbox-nav" style="width: 73px;">
        <a style="background: transparent url(/images/pagination-next.png) no-repeat scroll right 10px; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;" href="#" class="next" id="lightbox-nav-btnNext">&nbsp;</a>
        <a style="background: transparent url(/images/lightbox-blank.gif) no-repeat scroll 0% 0%; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous;" href="#" class="prev" id="lightbox-nav-btnPrev">&nbsp;</a>
        <div id="lightbox-nav-pages" style="width: 48px;" class="pages"><span class="set"></span><span></span><span></span><span></span><span></span><span></span></div>
        </div>
        <div style="width:1000px" id="lightbox-other-videos-liner">
        <div class="videoThumb">Video Title</div>
        <div class="videoThumb">Video Title2</div>
        <div class="videoThumb">Video Title3</div>
        <div class="videoThumb">Video Title4</div>
        <div class="videoThumb">Video Title5</div>
        <div class="videoThumb">Video Title6</div>
        </div>
        </div>

                                </div>
        <div id="lightbox-secNav"></div>
        </div>
        </div>
        </div>
        </div>
        *
        */
        function _set_interface() {
            // Apply the HTML markup into body tag
            $('body').append('\
                <div id="jquery-overlay" ></div>\n\
                <div id="jquery-lightbox">\n\
                    <div id="lightbox-container-video-box">\n\
                        <div id="lightbox-container-video">\n\
                            <a href="#" id="lightbox-secNav-btnClose"><img src="' + settings.videoBtnClose + '"></a>\n\
                            <span id="lightbox-video-details-caption">Video Title</span>\n\
                            <a id="lightbox-video" href=""></a>\n\
                            <div id="lightbox-loading">\n\
                                <a href="#" id="lightbox-loading-link"><img src="' + settings.videoLoading + '"></a>\n\
                            </div>\n\
                        </div>\n\
                        <div id="lightbox-container-video-data-box">\n\
                            <div id="lightbox-container-video-data">\n\
                                <div id="lightbox-video-controls"></div>\n\
                                <div id="lightbox-video-details">\n\
                                    <span id="lightbox-video-details-currentNumber"></span>\n\
                                    <div id="lightbox-nav">\n\
                                        <a href="#" class="next" id="lightbox-nav-btnNext"><img src="' + settings.videoBtnNext + '"></a>\n\
                                        <a href="#" class="prev" id="lightbox-nav-btnPrev"><img src="' + settings.videoBtnPrev + '"></a>\n\
                                        <div id="lightbox-other-videos-pages" class="pages"></div>\n\
                                    </div>\n\
                                    <div style="" id="lightbox-other-videos">\n\
                                        <div id="lightbox-other-videos-liner"></div>\n\
                                    </div>\n\
                                </div>\n\
                                <div id="lightbox-secNav"></div>\n\
                            </div>\n\
                        </div>\n\
                    </div>\n\
                </div>\n\
            ');
            // Get page sizes
            var arrPageSizes = ___getPageSize();
            // Style overlay and show it
            $('#jquery-overlay').css({
                backgroundColor: settings.overlayBgColor,
                opacity: settings.overlayOpacity,
                width: arrPageSizes[0],
                height: arrPageSizes[1]
            }).fadeIn();
            // Get page scroll
            var arrPageScroll = ___getPageScroll();
            // Calculate top and left offset for the jquery-lightbox div object and show it
            $('#jquery-lightbox').css({
                top: arrPageScroll[1] + (arrPageSizes[3] / 10),
                left: arrPageScroll[0]
            }).show();
            // Assigning click events in elements to close overlay
            $('#jquery-overlay').click(function() { //#jquery-lightbox
                _finish();
            });
            // Assign the _finish function to lightbox-loading-link and lightbox-secNav-btnClose objects
            $('#lightbox-loading-link,#lightbox-secNav-btnClose').click(function() {
                _finish();
                return false;
            });
            // If window was resized, calculate the new overlay dimensions
            $(window).resize(function() {
                // Get page sizes
                var arrPageSizes = ___getPageSize();
                // Style overlay and show it
                $('#jquery-overlay').css({
                    width: arrPageSizes[0],
                    height: arrPageSizes[1]
                });
                // Get page scroll
                var arrPageScroll = ___getPageScroll();
                // Calculate top and left offset for the jquery-lightbox div object and show it
                $('#jquery-lightbox').css({
                    top: arrPageScroll[1] + (arrPageSizes[3] / 10),
                    left: arrPageScroll[0]
                });
            });
        }
        /**
        * Prepares video exibition; doing a video�s preloader to calculate it�s size
        *
        */
        function _set_video_to_view() { // show the loading
            // Show the loading
            $('#lightbox-loading').show();
            if (settings.fixedNavigation) {
                $('#lightbox-video,#lightbox-container-video-data-box,#lightbox-video-details-currentNumber').hide();
            } else {
                // Hide some elements
                $('#lightbox-video,#lightbox-nav,#lightbox-nav-btnPrev,#lightbox-nav-btnNext,#lightbox-container-video-data-box,#lightbox-video-details-currentNumber').hide();
            }

            jQuery('#lightbox-video-controls').css("opacity", 0);

            var modalWindowHeight = jQuery("#lightbox-container-video").outerHeight() + parseInt(jQuery("#lightbox-container-video").parent().css('padding-top')) + jQuery("#lightbox-container-video-data-box").outerHeight();
            _resize_container_video_box(jQuery("#lightbox-video").width(), modalWindowHeight);
        };

        function _embedMedia(src) {
            $("#lightbox-video").empty();
            $("#lightbox-video-controls").empty();
            $("#lightbox-video").attr('href', src);
            // Embed video
            if (settings.audio) {
                jQuery('.videoThumb').addClass('audioThumb');
                $f("lightbox-video", {
                    src: "/flash/flowplayer-3.1.1.swf",
                    wmode: "transparent"
                }, {
                    playlist: [
                        '/images/icon-video-large.png',
                        {
                            url: '/media/08-Lonely-As-You.mp3'
                        }
                    ],
                    plugins: {
                        controls: {
                            backgroundColor: '#363535',
                            backgroundGradient: 'none',
                            height: 30,
                            fullscreen: false,
                            time: false,
                            playlist: false,
                            volume: false,
                            fullscreen: false,
                            border: 0,
                            progressColor: "#a3cc85",
                            progressGradient: 'none',
                            bufferColor: "#686868",
                            bufferGradient: 'none',
                            buttonColor: '#444444',
                            buttonOverColor: '#444444'
                        },
                        audio: {
                            url: '/flash/flowplayer.audio-3.1.0.swf'
                        }
                    }
                });
            } else {
                $f("lightbox-video", {
                    src: src,
                    wmode: "transparent"
                }, {
                    clip: {
                        autoPlay: true,
                        autoBuffering: true
                    },
                    plugins: { controls: null }
                }).controls("lightbox-video-controls");
                jQuery('#lightbox-video-controls').css("display", "none");
            }
        }
        /**
        * Perfomance an effect in the video container resizing it
        *
        * @param integer intVideoWidth The video�s width that will be showed
        * @param integer intVideoHeight The video�s height that will be showed
        */
        function _resize_container_video_box(intVideoWidth, intVideoHeight) {
            // Get current width and height
            var intCurrentWidth = $('#lightbox-container-video-box').width();
            var intCurrentHeight = $('#lightbox-container-video-box').height();
            // Get the width and height of the selected video plus the padding
            var intWidth = (intVideoWidth + (settings.containerBorderSize * 2)); // Plus the video�s width and the left and right padding value
            //var intHeight = (intVideoHeight + (settings.containerBorderSize * 2)); // Plus the video�s height and the left and right padding value
            // Diferences
            var intDiffW = intCurrentWidth - intWidth;
            //var intDiffH = intCurrentHeight - intHeight;
            // Perfomance the effect
            $('#lightbox-container-video-box').animate({
                width: intWidth//,
                //height: intHeight
            }, settings.containerResizeSpeed, function() {
                _show_video();
            });
            if ((intDiffW == 0)) {//&& ( intDiffH == 0 ) ) {
                if ($.browser.msie) {
                    ___pause(250);
                } else {
                    ___pause(100);
                }
            }
        };
        /**
        * Show the prepared video
        *
        */
        function _show_video() {
            $('#lightbox-loading').hide();
            $('#lightbox-video').fadeIn(function() {
                _show_video_data();
                _embedMedia(settings.videoArray[settings.activeVideo][0]);
                _set_navigation();
            });
        };
        /**
        * Show the video information
        *
        */
        function _show_video_data() {
            $('#lightbox-container-video-data-box').fadeIn(1000, function() {
                $('#lightbox-video-controls').animate({ opacity: 1 }, 1000);
            });
            $('#lightbox-video-details-caption').hide();
            if (settings.videoArray[settings.activeVideo][1]) {
                $('#lightbox-video-details-caption').html(settings.videoArray[settings.activeVideo][1]).show();
            }
            // If we have a video set, display 'Video X of X'
            if (settings.showTxt) {
                if (settings.videoArray.length > 1) {
                    $('#lightbox-video-details-currentNumber').html(settings.txtVideo + ' ' + (settings.activeVideo + 1) + ' ' + settings.txtOf + ' ' + settings.videoArray.length).show();
                }
            }

            var thumbs = new Array();
            for (i = 0; i < settings.videoArray.length; i++) {
                thumbs[i] = jQuery("<div></div>").addClass('videoThumb');
            }
            jQuery(thumbs).each(function(i) {
                $('#lightbox-other-videos-liner').append(
                    jQuery(this).append(
                        jQuery('<a></a>').append(
                            jQuery("<img/>").attr('src', settings.videoArray[i][2])
                        ).append(
                            jQuery("<span><span/>").html(settings.videoArray[i][1])
                        ).attr({
                            'href': settings.videoArray[i][0],
                            'class': (i == settings.activeImage) ? "set" : null
                        })
                    )
                );
            });

            var slider = new SlideNews("lightbox-other-videos", "videoThumb", "lightbox-nav-btnPrev", "lightbox-nav-btnNext", 3, true);

        }
        /**
        * Display the button navigations
        *
        */
        function _set_navigation() {
            $('#lightbox-nav').show();
            // Enable keyboard navigation
            _enable_keyboard_navigation();

            jQuery(".videoThumb a").each(function(i) {
                jQuery(this).click(function(event) {
                    event.preventDefault();

                    jQuery(".videoThumb a").each(function(j) {
                        if (i == j) {
                            jQuery(this).addClass('set');
                        } else {
                            jQuery(this).removeClass('set');
                        }
                    });
                    jQuery('#lightbox-video-details-caption').html(settings.videoArray[i][1]);
                    _embedMedia(settings.videoArray[i][0]);
                });
            });

        }
        /**
        * Enable a support to keyboard navigation
        *
        */
        function _enable_keyboard_navigation() {
            $(document).keydown(function(objEvent) {
                _keyboard_action(objEvent);
            });
        }
        /**
        * Disable the support to keyboard navigation
        *
        */
        function _disable_keyboard_navigation() {
            $(document).unbind();
        }
        /**
        * Perform the keyboard actions
        *
        */
        function _keyboard_action(objEvent) {
            // To ie
            if (objEvent == null) {
                keycode = event.keyCode;
                escapeKey = 27;
                // To Mozilla
            } else {
                keycode = objEvent.keyCode;
                escapeKey = objEvent.DOM_VK_ESCAPE;
            }
            // Get the key in lower case form
            key = String.fromCharCode(keycode).toLowerCase();
            // Verify the keys to close the ligthBox
            if ((key == settings.keyToClose) || (key == 'x') || (keycode == escapeKey)) {
                _finish();
            }
            // Verify the key to show the previous video
            if ((key == settings.keyToPrev) || (keycode == 37)) {
                // If we�re not showing the first video, call the previous
                if (settings.activeVideo != 0) {
                    settings.activeVideo = settings.activeVideo - 1;
                    _set_video_to_view();
                    _disable_keyboard_navigation();
                }
            }
            // Verify the key to show the next video
            if ((key == settings.keyToNext) || (keycode == 39)) {
                // If we�re not showing the last video, call the next
                if (settings.activeVideo != (settings.videoArray.length - 1)) {
                    settings.activeVideo = settings.activeVideo + 1;
                    _set_video_to_view();
                    _disable_keyboard_navigation();
                }
            }
        }

        function _finish() {
            $('#jquery-lightbox').remove();
            $('#jquery-overlay').fadeOut(function() {
                $('#jquery-overlay').remove();
            });
            // Show some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
            $('embed, object, select').css({
                'visibility': 'visible'
            });
        }
        /**
        / THIRD FUNCTION
        * getPageSize() by quirksmode.com
        *
        * @return Array Return an array with page width, height and window width, height
        */
        function ___getPageSize() {
            var xScroll, yScroll;
            if (window.innerHeight && window.scrollMaxY) {
                xScroll = window.innerWidth + window.scrollMaxX;
                yScroll = window.innerHeight + window.scrollMaxY;
            } else if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
                xScroll = document.body.scrollWidth;
                yScroll = document.body.scrollHeight;
            } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
                xScroll = document.body.offsetWidth;
                yScroll = document.body.offsetHeight;
            }
            var windowWidth, windowHeight;
            if (self.innerHeight) {	// all except Explorer
                if (document.documentElement.clientWidth) {
                    windowWidth = document.documentElement.clientWidth;
                } else {
                    windowWidth = self.innerWidth;
                }
                windowHeight = self.innerHeight;
            } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
                windowWidth = document.documentElement.clientWidth;
                windowHeight = document.documentElement.clientHeight;
            } else if (document.body) { // other Explorers
                windowWidth = document.body.clientWidth;
                windowHeight = document.body.clientHeight;
            }
            // for small pages with total height less then height of the viewport
            if (yScroll < windowHeight) {
                pageHeight = windowHeight;
            } else {
                pageHeight = yScroll;
            }
            // for small pages with total width less then width of the viewport
            if (xScroll < windowWidth) {
                pageWidth = xScroll;
            } else {
                pageWidth = windowWidth;
            }
            arrayPageSize = new Array(pageWidth, pageHeight, windowWidth, windowHeight);
            return arrayPageSize;
        };
        /**
        / THIRD FUNCTION
        * getPageScroll() by quirksmode.com
        *
        * @return Array Return an array with x,y page scroll values.
        */
        function ___getPageScroll() {
            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;
            }
            arrayPageScroll = new Array(xScroll, yScroll);
            return arrayPageScroll;
        };
        /**
        * Stop the code execution from a escified time in milisecond
        *
        */
        function ___pause(ms) {
            var date = new Date();
            curDate = null;
            do {
                var curDate = new Date();
            }
            while (curDate - date < ms);
        };
        // Return the jQuery object for chaining. The unbind method is used to avoid click conflict when the plugin is called more than once
        return this.unbind('click').click(_initialize);
    };
})(jQuery);     // Call and execute the function immediately passing the jQuery object
