﻿(function ($) {
    $.fn.youTubeEmbed = function (settings) {
        // Settings can be either a URL string,
        // or an object
        if (typeof settings == 'string') {
            settings = { 'video': settings }
        }
        // Default values
        var def = {
            width: 552, //640
            progressBar: true,
            height: 323
        };
        settings = $.extend(def, settings);
        //$(".browseHolder").hide();
        var elements = {
            originalDIV: this, // The "this" of the plugin
            container: null, // A container div, inserted by the plugin
            control: null, // The control play/pause button
            player: null, // The flash player
            progress: null, // Progress bar
            customControls: null, //ian
            customPause: null, //ian
            customPlay: null, //ian
            customStop: null, //ian
            //customStopButton: null, //ian
            customSoundOn: null, //ian
            customSoundOff: null, //ian
            elapsed: null // The light blue elapsed bar
        };
        try {
            settings.videoID = settings.video.match(/v=(\w+)/)[1];
            // safeID is a stripped version of videoID,
            // ready for use as a JavaScript function name
            settings.safeID = settings.videoID.replace(/[^a-z0-9]/ig, '');
        } catch (e) {
            // If the url was invalid, just return the "this"
            return elements.originalDIV;
        }
        // Fetch data about the video from YouTube's API
        var youtubeAPI = 'http://gdata.youtube.com/feeds/api/videos?v=2&alt=jsonc';
        $.get(youtubeAPI, { 'q': settings.videoID }, function (response) {
            var data = response.data;
            if (!data.totalItems || data.items[0].accessControl.embed != "allowed") {
                // If the video was not found, or embedding is not allowed;
                return elements.originalDIV;
            }
            // data holds API info about the video:
            data = data.items[0];
            settings.ratio = 3 / 4;
            if (data.aspectRatio == "widescreen") {
                settings.ratio = 9 / 16;
            }

            //IW 02-09-2010 - take height from passed in settings value
            //settings.height = Math.round(settings.width * settings.ratio);
            //settings.height = 323; //ian testing

            // Creating a container inside the original div, which will
            // hold the object/embed code of the video
            elements.container = $('<div>', { className: 'flashContainer', css: {
                width: settings.width,
                height: settings.height
            }
            }).appendTo(elements.originalDIV);
            //alert(elements.originalDIV.id);
            // Embedding the YouTube chromeless player
            // and loading the video inside it:
            //alert(settings.height);
            elements.container.flash({
                swf: 'http://www.youtube.com/apiplayer?enablejsapi=1&version=3',
                id: 'video_' + settings.safeID,
                height: settings.height,
                width: settings.width,
                allowScriptAccess: 'always',
                allowFullScreen: 'true',
                wmode: 'transparent',
                flashvars: {
                    "video_id": settings.videoID,
                    "playerapiid": settings.safeID,
                    "autoplay": 1
                }
            });
            //alert(settings.safeID);
            // We use get, because we need the DOM element
            // itself, and not a jquery object:
            elements.player = elements.container.flash().get(0);
            //alert(elements.player.id);
            // alert(settings.progressBar);
            // Creating the control Div. It will act as a ply/pause button
            //elements.control = $('<div>', { className: 'controlDiv' })
            //	               .appendTo(elements.container);
            // If the user wants to show the progress bar:
            //elements.player.seekTo(50);
            if (settings.progressBar) {
                elements.customControls = $('<div>', { className: 'customControls' }).appendTo(elements.container);
                elements.customPause = $('<span>', { className: 'customPause', style: 'float:left;' }).appendTo(elements.customControls);
                elements.customPlay = $('<span>', { className: 'customPlay', style: 'float:left;' }).appendTo(elements.customControls);
                elements.customStop = $('<span>', { className: 'customStop', style: 'float:left;' }).appendTo(elements.customControls);
                //elements.customStopButton = $('<a href="#" id="customStopButton" class=".sbCallToActionLink">test</a>')
                //                            .appendTo(elements.customControls);
                elements.customSoundOn = $('<span>', { className: 'customSoundOn', style: 'float:left;' }).appendTo(elements.customControls);
                elements.customSoundOff = $('<span>', { className: 'customSoundOff', style: 'float:left;' }).appendTo(elements.customControls);
                elements.progress = $('<div>', { className: 'progressBar' }).appendTo(elements.container);
                elements.elapsed = $('<div>', { className: 'elapsed' }).appendTo(elements.progress);
                elements.customPause.click(function (e) {
                    elements.player.pauseVideo();
                    $(elements.customPause).hide();
                    $(elements.customPlay).show();
                    $(elements.customStop).show();

                    return false;
                });
                elements.customPlay.click(function (e) {
                    elements.player.playVideo();
                    $(elements.customPause).show();
                    $(elements.customPlay).hide();
                    $(elements.customStop).show();
                    stopped = false;
                    return false;
                });
                elements.customStop.click(function (e) {
                    elements.player.stopVideo();
                    elements.player.clearVideo();
                    try {
                        api.seekTo(settings.frameNo);
                        api.stop();
                    }
                    catch (e) { }
                    try {
                        reloadGallery(settings.frameNo);
                    }
                    catch (e1) { }
                    $(elements.customPause).hide();
                    $(elements.customPlay).show();
                    $(elements.customStop).hide();
                    $('#player_' + settings.customId).hide();
                    $('#sbImage_' + settings.customId).show();
                    //$(".browseHolder").show();
                    jQuery('.box').show();

                    return false;
                });
                elements.customSoundOn.click(function (e) {
                    elements.player.unMute();
                    $(elements.customSoundOn).hide();
                    $(elements.customSoundOff).show();

                    return false;
                });
                elements.customSoundOff.click(function (e) {
                    elements.player.mute();
                    $(elements.customSoundOn).show();
                    $(elements.customSoundOff).hide();
                    return false;
                });
                elements.progress.click(function (e) {
                    // When a click occurs on the progress bar, seek to the
                    // appropriate moment of the video.
                    var ratio = (e.pageX - elements.progress.offset().left) / elements.progress.outerWidth();
                    elements.elapsed.width(ratio * 100 + '%');
                    elements.player.seekTo(Math.round(data.duration * ratio), true);
                    return false;
                });
            }
            var initialized = false;
            // Creating a global event listening function for the video
            // (required by YouTube's player API):

            window['eventListener_' + settings.safeID] = function (status) {
                var interval;
                if (status == -1)	// video is loaded
                {
                    if (!initialized) {
                        elements.container.addClass('playing');
                        //elements.player.playVideo();
                        if (settings.progressBar) {
                            interval = window.setInterval(function () {
                                try {
                                    elements.elapsed.width(((elements.player.getCurrentTime() / data.duration) * 100) + '%');
                                }
                                catch (e) {
                                }
                            }, 1000);
                        }
                        $(elements.customPause).show();
                        $(elements.customPlay).hide();
                        $(elements.customStop).show();
                        
                        if (elements.player.isMuted()) {
                            $(elements.customSoundOn).show();
                            $(elements.customSoundOff).hide();
                        }
                        else {
                            $(elements.customSoundOn).hide();
                            $(elements.customSoundOff).show();
                        }
                        // Listen for a click on the control button:
                        elements.control.click(function () {
                            //alert(elements.container.hasClass('playing'));
                            if (!elements.container.hasClass('playing')) {
                                // If the video is not currently playing, start it:
                                //ian - original
                                //elements.control.removeClass('play replay').addClass('pause');
                                //elements.control.removeClass('play');
                                elements.control.removeClass('replay');
                                elements.container.addClass('playing');
                                elements.player.playVideo();

                                if (settings.progressBar) {
                                    try {
                                        interval = window.setInterval(function () {
                                            elements.elapsed.width(((elements.player.getCurrentTime() / data.duration) * 100) + '%');
                                        }, 1000);
                                    }
                                    catch (e) {
                                    }
                                }
                                $(elements.customPause).show();
                                $(elements.customPlay).hide();
                                $(elements.customStop).show();
                                if (elements.player.isMuted()) {
                                    $(elements.customSoundOn).show();
                                    $(elements.customSoundOff).hide();
                                }
                                else {
                                    $(elements.customSoundOn).hide();
                                    $(elements.customSoundOff).show();
                                }
                            } else {
                                // If the video is currently playing, pause it:
                                //alert(elements.container.hasClass('playing'));
                                $(elements.customPause).hide();
                                $(elements.customPlay).show();
                                $(elements.customStop).show();

                                elements.control.removeClass('pause').addClass('play');
                                elements.container.removeClass('playing');
                                elements.control.removeClass('replay');
                                elements.player.pauseVideo();
                                if (elements.player.isMuted()) {
                                    $(elements.customSoundOn).show();
                                    $(elements.customSoundOff).hide();
                                }
                                else {
                                    $(elements.customSoundOn).hide();
                                    $(elements.customSoundOff).show();
                                }
                                if (settings.progressBar) {
                                    window.clearInterval(interval);
                                }
                            }
                        });
                        initialized = true;
                    }
                    else {
                        // This will happen if the user has clicked on the
                        // YouTube logo and has been redirected to youtube.com
                        if (elements.container.hasClass('playing')) {
                            elements.control.click();
                        }
                    }
                }
                if (status == 0) { // video has ended
                    //elements.control.removeClass('pause').addClass('replay');
                    elements.control.addClass('replay')
                    elements.container.removeClass('playing');
                }
            }
            // This global function is called when the player is loaded.
            // It is shared by all the videos on the page:
            if (!window.onYouTubePlayerReady) {
                window.onYouTubePlayerReady = function (playerID) {
                    document.getElementById('video_' + playerID).addEventListener('onStateChange', 'eventListener_' + playerID);
                }
            }
        }, 'jsonp');
        return elements.originalDIV;
    }
})(jQuery);
