/* ------------------------------------------------------------------------
Class: VideoLightbox
Use: Lightbox Video clone for jQuery
Author: Joaquin Zschuschen (http://www.knowledgeactivators.nl)
Version: 1.0.1
------------------------------------------------------------------------- */
(function ($) {
    $.VideoLightbox = { version: '1.0.1' };

    $.fn.VideoLightbox = function (settings) {
        settings = jQuery.extend({
            animationSpeed: 'normal', /* fast/slow/normal */
            opacity: 0.80, /* Value between 0 and 1 */
            showTitle: true, /* true/false */
            showStrVideoProblems: true, /* true/false */
            showStrInstallSilverLight: true, /* true/false */
            allowresize: true, /* true/false */
            default_width: 500,
            default_height: 344,
            background: 'White',
            default_layover: 'images/videolayover.png', //thumb.jpg
            counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
            theme: 'light_rounded', /* light_rounded / dark_rounded / light_square / dark_square / facebook */
            hideflash: false, /* Hides all the flash object on a page, set to TRUE if flash appears over VideoLightbox */
            wmode: 'opaque', /* Set the flash wmode attribute */
            autoplay: true, /* Automatically start videos: True/False */
            modal: false, /* If set to true, only the close button will close the window */
            changevideocallback: function () { }, /* Called everytime an item is shown/changed */
            callback: function () { }, /* Called when VideoLightbox is closed */
            markup: '<div class="vlb_video_holder"> \
						<div class="vlb_top"> \
							<div class="vlb_left"></div> \
							<div class="vlb_middle"></div> \
							<div class="vlb_right"></div> \
						</div> \
						<div class="vlb_content_container"> \
							<div class="vlb_left"> \
							<div class="vlb_right"> \
								<div class="vlb_content"> \
									<div class="vlb_loaderIcon"></div> \
									<div class="vlb_fade"> \
										<div class="vlb_hoverContainer"> \
											<a class="vlb_next" href="#">next</a> \
											<a class="vlb_previous" href="#">previous</a> \
										</div> \
										<div id="vlb_full_res"></div> \
										<div class="vlb_details clearfix"> \
											<a class="vlb_close" href="#">Close</a> \
											<p class="vlb_description"></p> \
											<div class="vlb_nav"> \
												<a href="#" class="vlb_arrow_previous">Previous</a> \
												<p class="currentTextHolder">0/0</p> \
												<a href="#" class="vlb_arrow_next">Next</a> \
											</div> \
										</div> \
									</div> \
								</div> \
							</div> \
							</div> \
						</div> \
						<div class="vlb_bottom"> \
							<div class="vlb_left"></div> \
							<div class="vlb_middle"></div> \
							<div class="vlb_right"></div> \
						</div>  \
					    <div class="vlb_extra"></div> \
					    <div class="vlb_SilverLight"></div> \
					    <div class="vlb_Statistics"></div> \
					</div> \
					<div class="vlb_overlay"></div> \
					<div class="ppt"></div> '
        }, settings);
        // Fallback to a supported theme for IE6
        if ($.browser.msie && parseInt($.browser.version) == 6) {
            settings.theme = "light_square";
        }
        if ($('.vlb_overlay').size() == 0) _buildOverlay(); // If the overlay is not there, inject it!
        // Global variables accessible only by VideoLightbox
        var doresize = true, percentBased = false, correctSizes,
        // Cached selectors
		$vlb_video_holder, $ppt, $vlb_extra, $vlb_SilverLight, $vlb_Statistics, $vlb_overlay,
        // VideoLightbox container specific
		vlb_contentHeight, vlb_contentWidth, vlb_containerHeight, vlb_containerWidth,
        // Window size
		windowHeight = $(window).height(), windowWidth = $(window).width(),
        //Gallery specific
		setPosition = 0,
        // Global elements
		scrollPos = _getScroll();
        // Window/Keyboard events
        $(window).scroll(function () { scrollPos = _getScroll(); _centerOverlay(); _resizeOverlay(); });

        $(window).resize(function () { _centerOverlay(); _resizeOverlay(); });

        $(document).keydown(function (e) {
            if ($vlb_video_holder.is(':visible'))
                switch (e.keyCode) {
                case 37:
                    $.VideoLightbox.changePage('previous');
                    break;
                case 39:
                    $.VideoLightbox.changePage('next');
                    break;
                case 27:
                    if (!settings.modal)
                        $.VideoLightbox.close();
                    break;
            };
        });
        // Bind the code to each links
        $(this).each(function (index) {
            $(this).bind('click', function () {
                _self = this; // Fix scoping

                // Find out if the picture is part of a set
                theRel = $(this).attr('class');
                galleryRegExp = /\[(?:.*)\]/;
                theGallery = galleryRegExp.exec(theRel);

                // Build the gallery array
                var videos = new Array();

                if (theGallery) {
                    $('a[class*=' + theGallery + ']').each(function (i) {
                        if ($(this)[0] === $(_self)[0]) setPosition = i; // Get the position in the set
                        videos.push(makeVideoObject(this));
                    });
                } else {
                    videos.push(makeVideoObject(this));
                }
                $.VideoLightbox.open(videos);
                return false;
            });
            var relFilename = $(this).attr('rel');
            if (relFilename == undefined) { relFilename = settings.default_layover.toString(); }

            $(this).empty()
            $(this).append('<img id="thumb' + index + '" src="' + relFilename + '"/>');

            var classname = $(this).attr('class');
            if (classname != undefined) {
                var rollover = classname.search(/ro/);
                if (rollover != -1) { $(this).children(":first").RollOver(); };
            }
        });
        /** Opens the VideoLightbox modal box.
        * @param image {String,Array} Full path to the image to be open, can also be an array containing full videos paths.
        * @param title {String,Array} The title to be displayed with the picture, can also be an array containing all the titles.
        * @param description {String,Array} The description to be displayed with the picture, can also be an array containing all the descriptions. */
        $.VideoLightbox.open = function (gallery_videos) {
            // To fix the bug with IE select boxes
            if ($.browser.msie && $.browser.version == 6) {
                $('select').css('visibility', 'hidden');
            };
            // Hide the flash
            if (settings.hideflash) $('object,embed').css('visibility', 'hidden');
            // Convert everything to an array in the case it's a single item

            image_set = ($(gallery_videos).size() > 0) ? true : false; // Find out if it's a set
            // Hide the next/previous links if on first or last videos.
            _checkPosition($(gallery_videos).size());
            $('.vlb_loaderIcon').show(); // Do I need to explain?
            // Fade the content in
            $vlb_overlay.show().fadeTo(settings.animationSpeed, settings.opacity);
            // Display the current position
            $vlb_video_holder.find('.currentTextHolder').text((setPosition + 1) + settings.counter_separator_label + $(gallery_videos).size());

            //set VideoObject
            var videoObject = gallery_videos[setPosition];
            // Set the description
            if (videoObject['altFilename']) {
                $vlb_video_holder.find('.vlb_description').show().html(unescape(videoObject['altFilename']));
            } else {
                $vlb_video_holder.find('.vlb_description').hide().text('');
            };
            // Set the title
            if (videoObject['title'] && settings.showTitle) {
                hasTitle = true;
                $ppt.html(unescape(videoObject['title']));
            } else {
                hasTitle = false;
            };
            // Set the extra's
            if (strVideoProblems && settings.showStrVideoProblems) {
                hasStrVideoProblems = true;
                $vlb_extra.html(unescape(strVideoProblems));
            } else {
                hasStrVideoProblems = false;
            };
            // Set the statistics
            if (addStatsVideo) {
                if (typeof MakeVideoStatsStr == 'function') {
                    var tempMakeVideoStatsStr = MakeVideoStatsStr(videoObject['hrefFilename']);
                    $vlb_Statistics.html(tempMakeVideoStatsStr);
                    var a = $vlb_Statistics;
                }
            };
            // Get the dimensions
            movie_width = videoObject['width'];
            movie_height = videoObject['height'];
            // If the size is % based, calculate according to window dimensions
            if (movie_width.indexOf('%') != -1 || movie_height.indexOf('%') != -1) {
                movie_height = parseFloat(($(window).height() * parseFloat(movie_height) / 100) - 100);
                movie_width = parseFloat(($(window).width() * parseFloat(movie_width) / 100) - 100);
                percentBased = true;
            }
            // Fade the holder
            $vlb_video_holder.fadeIn(function () {
                // Inject the proper content

                correctSizes = _fitToViewport(movie_width, movie_height); // Fit item to viewport
                //correctSizes['height'] += 15; correctSizes['contentHeight'] += 15; correctSizes['containerHeight'] += 15; // Add space for the control bar
                var toInject;
                if (Silverlight.isInstalled()) {
                    var retval;
                    if (getExtFromFilename(videoObject['hrefFilename']) == "ism") {
                        toInject = CreateSLVideoPlayerAdaptiveStreaming(setPosition, correctSizes['width'], correctSizes['height'], videoObject['background'], videoObject['hrefFilename'], videoObject['relFilename'], videoObject['title'], videoObject['autoplay']);
                    }
                    else {
                        toInject = CreateSLVideoPlayer(setPosition, correctSizes['width'], correctSizes['height'], videoObject['background'], videoObject['hrefFilename'], videoObject['relFilename'], videoObject['altFilename'], videoObject['autoplay']);
                    };
                    //$(this).empty()
                    //$(this).append
                    $vlb_video_holder.find('#vlb_full_res')[0].innerHTML = toInject;
                    hasStrInstallSilverLight = false;
                }
                else {
                    var newlink = $($vlb_video_holder).find('#vlb_full_res')[0]
                    $(newlink).append('<a href="' + videoObject['hrefFilename'] + '" />')
                    standardMediaWithOpt($('#vlb_full_res a:first'), videoObject['hrefFilename'], videoObject['width'], videoObject['height'], videoObject['background'], videoObject['title'], videoObject['autoplay']);
                    // Set the install Silverlight
                    if (strInstallSilverLight && settings.showStrInstallSilverLight) {
                        hasStrInstallSilverLight = true;
                        $vlb_SilverLight.html(unescape(strInstallSilverLight));
                    } else {
                        hasStrInstallSilverLight = false;
                    };
                }

                // Show content
                _showContent();
            });
        };
        /** Change page in the VideoLightbox modal box
        * @param direction {String} Direction of the paging, previous or next. */
        $.VideoLightbox.changePage = function (direction) {
            if (direction == 'previous') {
                setPosition--;
                if (setPosition < 0) {
                    setPosition = 0;
                    return;
                };
            } else {
                if ($('.vlb_arrow_next').is('.disabled')) return;
                setPosition++;
            };
            // Allow the resizing of the videos
            if (!doresize) doresize = true;

            _hideContent(function () { $.VideoLightbox.open(videos, titles, descriptions) });
        };
        /** Closes the VideoLightbox modal box. */
        $.VideoLightbox.close = function () {
            $vlb_video_holder.find('object,embed').css('visibility', 'hidden');

            $('div.vlb_video_holder,div.ppt,div.vlb_extra,div.vlb_SilverLight,.vlb_fade').fadeOut(settings.animationSpeed);

            $vlb_overlay.fadeOut(settings.animationSpeed, function () {
                // Kill the opened content
                $('#vlb_full_res').html('');
                // Reset the width and everything that has been set.
                $vlb_video_holder.attr('style', '').find('div:not(.vlb_hoverContainer)').attr('style', '');
                // Center it
                _centerOverlay();
                // To fix the bug with IE select boxes
                if ($.browser.msie && $.browser.version == 6) {
                    $('select').css('visibility', 'visible');
                };
                // Show the flash
                if (settings.hideflash) $('object,embed').css('visibility', 'visible');

                setPosition = 0;
                settings.callback();
            });
            doresize = true;
        };
        /* make the individual video objects*/
        function makeVideoObject(obj) {
            var hrefFilename = $(obj).attr('href');
            var data = $(obj).metadata({ type: 'style' });
            var width = settings.default_width.toString();
            var height = settings.default_height.toString();
            var background = settings.background.toString();
            var autoplay = settings.autoplay;
            if (data.width) { width = data.width; }
            if (data.height) { height = data.height; }
            if (data.background) { background = data.background; }
            if (data.autoplay) { autoplay = (data.autoplay === 'true'); }
            var relFilename = $(obj).attr('rel');
            if (relFilename == undefined) { relFilename = settings.default_layover.toString(); }
            var altFilename = $(obj).attr('alt');
            if (altFilename == undefined) { altFilename = ''; } //top/logo_klein.jpg
            var title = 'titel';
            if ($(obj).attr('title')) { title = $(obj).attr('title'); }
            return { hrefFilename: hrefFilename, width: width, height: height, background: background, autoplay: autoplay, relFilename: relFilename, altFilename: altFilename, title: title }
        }
        /* Set the proper sizes on the containers and animate the content in. */
        _showContent = function () {
            $('.vlb_loaderIcon').hide();
            // Calculate the opened top position of the pic holder
            projectedTop = scrollPos['scrollTop'] + ((windowHeight / 2) - (correctSizes['containerHeight'] / 2));
            if (projectedTop < 0) projectedTop = 0 + $ppt.height();
            // Resize the content holder
            $vlb_video_holder.find('.vlb_content').animate({ 'height': correctSizes['contentHeight'] }, settings.animationSpeed);
            // Resize picture the holder
            $vlb_video_holder.animate({
                'top': projectedTop,
                'left': (windowWidth / 2) - (correctSizes['containerWidth'] / 2),
                'width': correctSizes['containerWidth']
            }, settings.animationSpeed, function () {
                $vlb_video_holder.find('.vlb_hoverContainer,#fullResImage').height(correctSizes['height']).width(correctSizes['width']);
                // Fade the new image
                $vlb_video_holder.find('.vlb_fade').fadeIn(settings.animationSpeed);
                // Show the nav
                if (image_set) { $vlb_video_holder.find('.vlb_hoverContainer').show(); } else { $vlb_video_holder.find('.vlb_hoverContainer').hide(); }
                // Show the title
                if (settings.showTitle && hasTitle) {
                    $ppt.css({
                        'top': $vlb_video_holder.offset().top - 25,
                        'left': $vlb_video_holder.offset().left + 20,
                        'display': 'none'
                    });
                    $ppt.fadeIn(settings.animationSpeed);
                };
                var positionExtra = 0;
                if (settings.showStrVideoProblems && hasStrVideoProblems) {
                    $vlb_extra.css({
                        'top': vlb_containerHeight + 25,
                        'left': $vlb_video_holder.offset().left + 20,
                        'display': 'none'
                    });
                    positionExtra = 25;
                    $vlb_extra.fadeIn(settings.animationSpeed);
                };
                if (settings.showStrInstallSilverLight && hasStrInstallSilverLight) {
                    $vlb_SilverLight.css({
                        'top': vlb_containerHeight + (positionExtra + 25),
                        'left': $vlb_video_holder.offset().left + 20,
                        'display': 'none'
                    });
                    $vlb_SilverLight.fadeIn(settings.animationSpeed);
                };
                // Callback!
                settings.changevideocallback();
            });
        };
        /** Hide the content...DUH! */
        function _hideContent(callback) {
            // Fade out the current video
            $vlb_video_holder.find('#vlb_full_res object,#vlb_full_res embed').css('visibility', 'hidden');
            $vlb_video_holder.find('.vlb_fade').fadeOut(settings.animationSpeed, function () {
                $('.vlb_loaderIcon').show();
                if (callback) callback();
            });
            // Hide the title
            $ppt.fadeOut(settings.animationSpeed);
            // Hide the vlb_SilverLight
            $vlb_SilverLight.fadeOut(settings.animationSpeed);
            // Hide the vlb_extra
            $vlb_extra.fadeOut(settings.animationSpeed);
        }
        /** Check the item position in the gallery array, hide or show the navigation links
        * @param setCount {integer} The total number of items in the set */
        function _checkPosition(setCount) {
            // If at the end, hide the next link
            if (setPosition == setCount - 1) {
                $vlb_video_holder.find('a.vlb_next').css('visibility', 'hidden');
                $vlb_video_holder.find('a.vlb_arrow_next').addClass('disabled').unbind('click');
            } else {
                $vlb_video_holder.find('a.vlb_next').css('visibility', 'visible');
                $vlb_video_holder.find('a.vlb_arrow_next.disabled').removeClass('disabled').bind('click', function () {
                    $.VideoLightbox.changePage('next');
                    return false;
                });
            };
            // If at the beginning, hide the previous link
            if (setPosition == 0) {
                $vlb_video_holder.find('a.vlb_previous').css('visibility', 'hidden');
                $vlb_video_holder.find('a.vlb_arrow_previous').addClass('disabled').unbind('click');
            } else {
                $vlb_video_holder.find('a.vlb_previous').css('visibility', 'visible');
                $vlb_video_holder.find('a.vlb_arrow_previous.disabled').removeClass('disabled').bind('click', function () {
                    $.VideoLightbox.changePage('previous');
                    return false;
                });
            };
            // Hide the bottom nav if it's not a set.
            if (setCount > 1) {
                $('.vlb_nav').show();
            } else {
                $('.vlb_nav').hide();
            }
        };
        /** Resize the item dimensions if it's bigger than the viewport
        * @param width {integer} Width of the item to be opened
        * @param height {integer} Height of the item to be opened
        * @return An array containin the "fitted" dimensions */
        function _fitToViewport(width, height) {
            hasBeenResized = false;

            _getDimensions(width, height);
            // Define them in case there's no resize needed
            imageWidth = width;
            imageHeight = height;

            if (((vlb_containerWidth > windowWidth) || (vlb_containerHeight > windowHeight)) && doresize && settings.allowresize && !percentBased) {
                hasBeenResized = true;
                notFitting = true;

                while (notFitting) {
                    if ((vlb_containerWidth > windowWidth)) {
                        imageWidth = (windowWidth - 200);
                        imageHeight = (height / width) * imageWidth;
                    } else if ((vlb_containerHeight > windowHeight)) {
                        imageHeight = (windowHeight - 200);
                        imageWidth = (width / height) * imageHeight;
                    } else {
                        notFitting = false;
                    };
                    vlb_containerHeight = imageHeight;
                    vlb_containerWidth = imageWidth;
                };
                _getDimensions(imageWidth, imageHeight);
            };
            return {
                width: Math.floor(imageWidth),
                height: Math.floor(imageHeight),
                containerHeight: Math.floor(vlb_containerHeight),
                containerWidth: Math.floor(vlb_containerWidth) + 40,
                contentHeight: Math.floor(vlb_contentHeight),
                contentWidth: Math.floor(vlb_contentWidth),
                resized: hasBeenResized
            };
        };
        /** Get the containers dimensions according to the item size
        * @param width {integer} Width of the item to be opened
        * @param height {integer} Height of the item to be opened */
        function _getDimensions(width, height) {
            width = parseFloat(width);
            height = parseFloat(height);

            // Get the details height, to do so, I need to clone it since it's invisible
            $vlb_details = $vlb_video_holder.find('.vlb_details');
            $vlb_details.width(width);
            detailsHeight = parseFloat($vlb_details.css('marginTop')) + parseFloat($vlb_details.css('marginBottom'));
            $vlb_details = $vlb_details.clone().appendTo($('body')).css({
                'position': 'absolute',
                'top': -10000
            });
            detailsHeight += $vlb_details.height();
            detailsHeight = (detailsHeight <= 34) ? 36 : detailsHeight; // Min-height for the details
            if ($.browser.msie && $.browser.version == 7) detailsHeight += 8;
            $vlb_details.remove();

            // Get the container size, to resize the holder to the right dimensions
            vlb_contentHeight = height + detailsHeight;
            vlb_contentWidth = width;
            vlb_containerHeight = vlb_contentHeight + $ppt.height() + $vlb_video_holder.find('.vlb_top').height() + $vlb_video_holder.find('.vlb_bottom').height();
            vlb_containerWidth = width;
        }
        function _centerOverlay() {
            if (doresize) {
                titleHeight = $ppt.height();
                strVideoProblemsHeight = $vlb_extra.height();
                strInstallSilverLightHeight = $vlb_SilverLight.height();
                contentHeight = $vlb_video_holder.height();
                contentwidth = $vlb_video_holder.width();

                projectedTop = (windowHeight / 2) + scrollPos['scrollTop'] - ((contentHeight + titleHeight) / 2);

                $vlb_video_holder.css({
                    'top': projectedTop,
                    'left': (windowWidth / 2) + scrollPos['scrollLeft'] - (contentwidth / 2)
                });
                $ppt.css({
                    'top': projectedTop - titleHeight,
                    'left': (windowWidth / 2) + scrollPos['scrollLeft'] - (contentwidth / 2) + 20
                });
                $vlb_extra.css({
                    'top': projectedTop + contentHeight + strVideoProblemsHeight + 30,
                    'left': (windowWidth / 2) + scrollPos['scrollLeft'] - (contentwidth / 2) + 20
                });
                $vlb_SilverLight.css({
                    'top': projectedTop + contentHeight + strInstallSilverLightHeight + 50,
                    'left': (windowWidth / 2) + scrollPos['scrollLeft'] - (contentwidth / 2) + 20
                });
            };
        };
        function _getScroll() {
            if (self.pageYOffset) {
                return { scrollTop: self.pageYOffset, scrollLeft: self.pageXOffset };
            } else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
                return { scrollTop: document.documentElement.scrollTop, scrollLeft: document.documentElement.scrollLeft };
            } else if (document.body) {// all other Explorers
                return { scrollTop: document.body.scrollTop, scrollLeft: document.body.scrollLeft };
            };
        };
        function _resizeOverlay() {
            windowHeight = $(window).height();
            windowWidth = $(window).width();

            $vlb_overlay.css({
                'height': $(document).height()
            });
        };
        function _buildOverlay() {
            // Inject the markup
            $('body').append(settings.markup);

            // Set my global selectors
            $vlb_video_holder = $('.vlb_video_holder');
            $ppt = $('.ppt');
            $vlb_extra = $('.vlb_extra');
            $vlb_SilverLight = $('.vlb_SilverLight');
            $vlb_Statistics = $('.vlb_Statistics');
            $vlb_overlay = $('div.vlb_overlay');

            $vlb_video_holder.attr('class', 'vlb_video_holder ' + settings.theme); // Set the proper theme

            $vlb_overlay
				.css({ 'opacity': 0, 'height': $(document).height() })
				.bind('click', function () {
				    if (!settings.modal)
				        $.VideoLightbox.close();
				});
            $('a.vlb_close').bind('click', function () { $.VideoLightbox.close(); return false; });

            $vlb_video_holder.find('.vlb_previous, .vlb_arrow_previous').bind('click', function () {
                $.VideoLightbox.changePage('previous');
                return false;
            });
            $vlb_video_holder.find('.vlb_next, .vlb_arrow_next').bind('click', function () {
                $.VideoLightbox.changePage('next');
                return false;
            });
        };
        _centerOverlay(); // Center it
    };
    function grab_param(name, url) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexS = "[\\?&]" + name + "=([^&#]*)";
        var regex = new RegExp(regexS);
        var results = regex.exec(url);
        if (results == null)
            return "";
        else
            return results[1];
    }
})(jQuery);