/**
 * jQuery videoBox plugin
 * This jQuery plugin was inspired and based on Lightbox 2 by Lokesh Dhakar (http://www.huddletogether.com/projects/lightbox2/)
 * @name jquery-videobox-0.1.js
 * @author Preben Friis - http://nsaka.com
 * @version 0.1
 * @date September 1, 2010
 * @category jQuery plugin
 * @copyright (c) 2010 Nsaka ApS. (nsaka.com)
 */

var context;
 
(function($) {
    /**
    * $ is an alias to jQuery object
    */
    $.fn.videoBox = function(settings) {
        // Settings to configure the jQuery videoBox 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.6, 	// (integer) Opacity value to overlay; inform: 0.X. Where X are number from 0 to 9
            // Configuration related to images
            imageLoading: '/images/Loading.gif', 	// (string) Path and the name of the loading icon
            imageBtnPrev: '/images/Previous.png', 		// (string) Path and the name of the prev button image
            imageBtnNext: '/images/Next.png', 		// (string) Path and the name of the next button image
            imageBtnClose: '/images/Close.png', 		// (string) Path and the name of the close btn
            imageBlank: '/images/Blank.gif', 			// (string) Path and the name of a blank video (one pixel)
            // Configuration related to container video box
            containerBorderSize: 5, 		// (integer) If you adjust the padding in the CSS for the container, #videobox-container-box, you will need to update this value
            containerResizeSpeed: 500, 	// (integer) Specify the resize duration of container image. These number are miliseconds. 400 is default.
            // Configuration related to texts in caption. For example: Image 2 of 8. You can alter either "Image" and "of" texts.
            txtImage: 'Video', // (string) Specify text "Image"
            txtOf: 'of', 	// (string) Specify text "of"
            // Configuration related to keyboard navigation
            keyToClose: 'c', 	// (string) (c = close) Letter to close the jQuery videoBox interface. Beyond this letter, the letter X and the ESCAPE key is used too.
            keyToPrev: 'p', 	// (string) (p = previous) Letter to show the previous image
            keyToNext: 'n', 	// (string) (n = next) Letter to show the next image.
            // Don't alter these variables in any way
            videoArray: [],
            activeVideo: 0,
            maxWidth: 1200
        }, 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 videoBox 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) {
            // Hide some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
            $('embed, object, select').css({ 'visibility': 'hidden' });

            // Unset total images in videoArray
            settings.videoArray.length = 0;
            // Unset video active information
            settings.activeVideo = 0;
            // We have an video set? Or just an image? Let's see it.
            if (jQueryMatchedObj.length == 1) {
                settings.videoArray.push(new Array(objClicked.getAttribute('href'), objClicked.getAttribute('title')));
            } else {
                // Add an Array (as many as we have), with href and title atributes, inside the Array that storage the images references		
                for (var i = 0; i < jQueryMatchedObj.length; i++) {
                    settings.videoArray.push(new Array(jQueryMatchedObj[i].getAttribute('href'), jQueryMatchedObj[i].getAttribute('title')));
                }
            }
            while (settings.videoArray[settings.activeVideo][0] != objClicked.getAttribute('href')) {
                settings.activeVideo++;
            }
            // Call the function to create the markup structure; style some elements; assign events in some elements.
            _set_interface();

            // Call the function that prepares video exibition
            _set_image_to_view();
        }
        /**
        * Create the jQuery videoBox plugin interface
        */
        function _set_interface() {
            // Apply the HTML markup into body tag
            var videoSrc = settings.videoArray[settings.activeVideo][0];
            //$('body').append('<div id="jquery-overlay"></div><div id="jquery-videobox"><div id="videobox-container-box"><div id="videobox-container"><video id="video5" width="768" height="432" controls><source type="video/mp4" /><source type="video/ogg" /><object id="player" width="768" height="456" type="application/x-shockwave-flash" data="/media/player.swf"><param name="movie" value="/media/player.swf" /><param name="flashvars" value="file=' + videoSrc + '&autostart=true&playerReady=playerReady" /></object></video><div style="" id="videobox-nav"><a href="#" id="videobox-nav-btnPrev"></a><a href="#" id="videobox-nav-btnNext"></a></div></div></div><div id="videobox-container-data-box"><div id="videobox-container-data"><div id="videobox-image-details"><span id="videobox-image-details-caption"></span><span id="videobox-image-details-currentNumber"></span></div><div id="videobox-secNav"><a href="#" id="videobox-secNav-btnClose"><img src="' + settings.imageBtnClose + '"></a></div></div></div></div>');
            $('body').append('<div id="jquery-overlay"></div><div id="jquery-videobox"><div id="videobox-container-box"><div id="videobox-container"><video id="video5" width="768" height="432" controls><source type="video/ogg" /><source type="video/mp4" /><object id="player" width="768" height="456" type="application/x-shockwave-flash" data="/media/player.swf"><param name="movie" value="/media/player.swf" /><param name="flashvars" value="file=' + videoSrc + '&autostart=true&playerReady=playerReady" /></object></video><div style="" id="videobox-nav"><a href="#" id="videobox-nav-btnPrev"></a><a href="#" id="videobox-nav-btnNext"></a></div></div></div><div id="videobox-container-data-box"><div id="videobox-container-data"><div id="videobox-image-details"><span id="videobox-image-details-caption"></span><span id="videobox-image-details-currentNumber"></span></div><div id="videobox-secNav"><a href="#" id="videobox-secNav-btnClose"><img src="' + settings.imageBtnClose + '"></a></div></div></div></div>');

            // Get page sizes
            var arrPageSizes = _get_page_size();

            settings.maxWidth = arrPageSizes[0] - (settings.containerBorderSize * 4);

            // 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-videobox div object and show it
            $('#jquery-videobox').css({
                top: arrPageScroll[1] + (arrPageSizes[3] / 10),
                left: arrPageScroll[0]
            }).show();
            // Assigning click events in elements to close overlay
            /*$('#jquery-overlay, #jquery-videobox').click(function() {
                _finish();
                return false;
            });*/
            $('#jquery-overlay, #videobox-secNav-btnClose').click(function() {
                _finish();
                return false;
            });
            /*$('#video5').click(function() {
                //alert("Don't click me. It tickles!");
                doClose = false;
                return true;
            });*/

            // If window was resized, calculate the new overlay dimensions
            $(window).resize(function() {
                // Get page sizes
                var arrPageSizes = _get_page_size();

                settings.maxWidth = arrPageSizes[0] - (settings.containerBorderSize * 4);

                // 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-videobox div object and show it
                $('#jquery-videobox').css({
                    top: arrPageScroll[1] + (arrPageSizes[3] / 10),
                    left: arrPageScroll[0]
                });
            });
        }
        /**
        * Prepares video exibition; doing a image's preloader to calculate it's size
        */
        function _set_image_to_view() {
            _resize_container_image_box(768, 448);
        };
        /**
        * Perfome an effect in the video container resizing it
        *
        * @param integer intImageWidth The image's width that will be shown
        * @param integer intImageHeight The image's height that will be shown
        */
        function _resize_container_image_box(intImageWidth, intImageHeight) {
            // Get current width and height
            var intCurrentWidth = $('#videobox-container-box').width();
            var intCurrentHeight = $('#videobox-container-box').height();

            if (intImageWidth > settings.maxWidth) {
                intImageHeight = intImageHeight * settings.maxWidth / intImageWidth;
                intImageWidth = settings.maxWidth;
            }

            // Get the width and height of the selected video plus the padding
            var intWidth = (intImageWidth + (settings.containerBorderSize * 2)); // Plus the image's width and the left and right padding value
            var intHeight = (intImageHeight + (settings.containerBorderSize * 2)); // Plus the image's height and the left and right padding value

            // Diferences
            var intDiffW = intCurrentWidth - intWidth;
            var intDiffH = intCurrentHeight - intHeight;
            // Perfomance the effect
            $('#videobox-container-box').animate({ width: intWidth, height: intHeight }, settings.containerResizeSpeed, function() { _show_video(); });
            if ((intDiffW == 0) && (intDiffH == 0)) {
                if ($.browser.msie) {
                    ___pause(100);
                } else {
                    ___pause(100);
                }
            }
            $('#videobox-container-data-box').css({ width: intImageWidth });
            $('#videobox-nav-btnPrev, #videobox-nav-btnNext').css({ height: intImageHeight / 2 + (settings.containerBorderSize * 2), opacity: 0.3 });

        };
        /**
        * Show the video
        */
        function _show_video() {
            //$('#videobox-loading').hide();
            $('#videobox-container').fadeIn(function() {
                _show_image_data();
                _set_navigation();
            });
            //_preload_neighbor_images();

            try {
                var video = $('#video5');
                var videoSrc = settings.videoArray[settings.activeVideo][0];

                if (video[0].canPlayType('video/ogg; codecs="theora, vorbis"'))
                    videoSrc = videoSrc.substr(0, videoSrc.lastIndexOf(".")) + ".ogg";

                video[0].src = videoSrc;
                video[0].load();
                video[0].play();

                video.bind("ended", function() {
                    _finish();
                });
            }
            catch (err) { };

            context = this; // used by swf player
        };
        /**
        * Show the video information
        *
        */
        function _show_image_data() {
            $('#videobox-container-data-box').slideDown('fast');
            $('#videobox-image-details-caption').hide();
            if (settings.videoArray[settings.activeVideo][1]) {
                $('#videobox-image-details-caption').html(settings.videoArray[settings.activeVideo][1]).show();
            }
            // If we have a video set, display 'Image X of X'
            if (settings.videoArray.length > 1) {
                //$('#videobox-image-details-currentNumber').html(settings.txtImage + ' ' + (settings.activeVideo + 1) + ' ' + settings.txtOf + ' ' + settings.videoArray.length).show();

                //$('#videobox-image-details-currentNumber').html("Source: " + settings.videoArray[settings.activeVideo][0]).show();
                //var video = $('#video5');
                //$('#videobox-image-details-currentNumber').html("Source: " + video.currentSrc).show();
                var video = $('#video5');
                var videoSrc = settings.videoArray[settings.activeVideo][0];
                try {
                    if (video[0].canPlayType('video/ogg; codecs="theora, vorbis"')) {
                        //alert("Ogg!");
                        videoSrc = videoSrc.substr(0, videoSrc.lastIndexOf(".")) + '.ogg';
                    }
                }
                catch (err) { };

                $('#videobox-image-details-currentNumber').html("Source: " + videoSrc).show();
            }
        }
        /**
        * Display the button navigations
        *
        */
        function _set_navigation() {
            $('#videobox-nav').show();

            // Instead to define this configuration in CSS file, we define here. And it's needed to IE. Just.
            $('#videobox-nav-btnPrev, #videobox-nav-btnNext').css({ 'background': 'transparent url(' + settings.imageBlank + ') no-repeat' });

            // Show the prev button, if not the first video in set
            if (settings.activeVideo != 0) {
                // Show the images button for Prev button
                $('#videobox-nav-btnPrev').css({ 'background': 'url(' + settings.imageBtnPrev + ') left 15% no-repeat', 'opacity': 0.3 }).
                    unbind().hover(function() {
                        $(this).stop().animate({ opacity: 0.8 }, 500);
                    }, function() {
                        $(this).stop().animate({ opacity: 0.3 }, 300);
                    }).show().bind('click', function() {
                        settings.activeVideo = settings.activeVideo - 1;
                        _set_image_to_view();
                        return false;
                    });
            }

            // Show the next button, if not the last video in set
            if (settings.activeVideo != (settings.videoArray.length - 1)) {
                // Show the images button for Next button
                $('#videobox-nav-btnNext').css({ 'background': 'url(' + settings.imageBtnNext + ') right 15% no-repeat', 'opacity': 0.3 }).
                    unbind().hover(function() {
                        $(this).stop().animate({ opacity: 0.8 }, 500);
                    }, function() {
                        $(this).stop().animate({ opacity: 0.3 }, 300);
                    }).show().bind('click', function() {
                        settings.activeVideo = settings.activeVideo + 1;
                        _set_image_to_view();
                        return false;
                    });
            }
            // Enable keyboard navigation
            _enable_keyboard_navigation();
        }
        /**
        * 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 image
            if ((key == settings.keyToPrev) || (keycode == 37)) {
                // If we're not showing the first image, call the previous
                if (settings.activeVideo != 0) {
                    settings.activeVideo = settings.activeVideo - 1;
                    _set_image_to_view();
                    _disable_keyboard_navigation();
                }
            }
            // Verify the key to show the next image
            if ((key == settings.keyToNext) || (keycode == 39)) {
                // If we're not showing the last image, call the next
                if (settings.activeVideo != (settings.videoArray.length - 1)) {
                    settings.activeVideo = settings.activeVideo + 1;
                    _set_image_to_view();
                    _disable_keyboard_navigation();
                }
            }
        }
        /**
        * Preload prev and next images being showed
        *
        */
        function _preload_neighbor_images() {
            if ((settings.videoArray.length - 1) > settings.activeVideo) {
                objNext = new Image();
                objNext.src = settings.videoArray[settings.activeVideo + 1][0];
            }
            if (settings.activeVideo > 0) {
                objPrev = new Image();
                objPrev.src = settings.videoArray[settings.activeVideo - 1][0];
            }
        }
        /**
        * Remove jQuery videoBox plugin HTML markup
        *
        */
        function _finish() {
            $('#jquery-videobox').fadeOut(function() { $('#jquery-videobox').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' });
        }
        /**
        *
        * @return Array Return an array with page width, height and window width, height
        */
        function _get_page_size() {
            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 - 18) {
                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

function playerReady(object) {
    //alert('the player is ready');
    var swfplayer;    
    swfplayer = document.getElementById(object.id);
    swfplayer.addModelListener("STATE", "swfstate");
};

function swfstate(obj) {
    if (obj.newstate == "COMPLETED") {
        //alert(obj.newstate);
        //context._finish();
        $('#jquery-videobox').fadeOut(function() { $('#jquery-videobox').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' });
    }
}

