var globalEventRegistry = [];
(function($j){

    $j.fn.youTubeEmbed = function(settings, screen_width, screen_height){

        // Settings can be either a URL string,
        // or an object

        if(typeof settings == 'string'){
            settings = {'video' : settings}
        }

        // Default values
        var jtE = this;
        var globalEventListener;

        //var screen_width = $j(window).width();
        //var screen_height = $j(window).height();

        var def = {
            width        : screen_width,
            height        : screen_height,
            progress_bar    : true
        };

        // List of available YT qualities

        var qualities = {
            'hd1080'       : "1080p",
            'hd720'        : "720p",
            'large'        : "480p",
            'medium'       : "360p",
            'small'        : "240p"
        };

        settings = $j.extend(def,settings);

        var elements = {
            originalDIV     : this,    // The "this" of the plugin
            container     : null,    // A container div, inserted by the plugin
            error_box : null,    // error box
            error_box_close : null,    // error box close
            player_control_wrap : null,    // temporary plyer control wrap (for yt button handle)
            control_wrap : null,    // Buttons wrap
            control         : null,    // The control play/pause button
            volume : null, //The volume control wrap
            player         : null,    // The flash player
            progress_wrap : null,    // Progress bar wrap
            progress     : null,    // Progress bar
            elapsed         : null,        // The elapsed bar
            time_wrap : null,    // Progress time wrap
            time_duration     : null,    // Duration time
            time_current     : null,    // Current time
            quality_box     : null,    // Quality box
            qualities_wrap     : null,    // Qualities wrap box
            quality_hd1080     : null,    // Quality hd1080
            quality_hd720     : null,    // Quality hd720
            quality_large    : null,    // Quality large
            quality_medium     : null,    // Quality medium
            quality_small     : null,    // Quality small
            fullscreen     : null    // Fullscreen
        };


        try{

            settings.videoID = settings.video.match(/v=(.{11})/)[1];

            // The safeID is a stripped version of the
            // videoID, ready for use as a function name

            settings.safeID = settings.videoID.replace(/[^a-z0-9]/ig,'');

        } catch (e){
            // If the url was invalid, just return the "this"
            return false;
        }

        // Fetch data about the video from YouTube's API
        var youtubeAPI = 'http://gdata.youtube.com/feeds/api/videos?v=2&alt=jsonc';

        $j.get(youtubeAPI,{'q':settings.videoID},function(response){

            var data = response.data;

            // Creating a container inside the original div, which will
            // hold the object/embed code of the video

            elements.container = $j('<div>',{className:'flashContainer',css:{
                width    : settings.width,
                height    : settings.height
            }}).appendTo(elements.originalDIV);

            // Embedding the YouTube chromeless player
            // and loading the video inside it:

            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',
                wmode        : 'transparent',
                flashvars    : {
                    "video_id"        : settings.videoID,
                    "playerapiid"    : settings.safeID
                }
            });

            // We use get, because we need the DOM element
            // itself, and not a jquery object:

            elements.player = elements.container.flash().get(0);

            // Creating the control Div wrap panel

            elements.player_control_wrap = $j('<div>',{className:'player_control_wrap'})
                               .appendTo(elements.container);

            // Creating error box

            elements.error_box = $j('<div>',{className:'errorBox'})
                               .appendTo(elements.container);

            elements.error_box_close = $j('<div>',{className:'errorBoxClose'})
                               .appendTo(elements.container);

            elements.error_box_close.html('X');

            // Creating the control Div wrap panel

            elements.control_wrap = $j('<div>',{className:'control_div_wrap'})
                               .appendTo(elements.container);

            // Creating the control Div. It will act as a play/pause button

            elements.control = $j('<div>',{className:'control_div play'})
                               .appendTo(elements.control_wrap);

            // Creating the volume Div. It will act as a mute/volume buttons

            elements.volume = $j('<div>',{className:'volumeDiv'})
                               .appendTo(elements.control_wrap);

            elements.volume0 = $j('<div>',{className:'volumebar volumebar_dark volume0'})
                               .appendTo(elements.volume);
            elements.volume20 = $j('<div>',{className:'volumebar volumebar_bright volume20 active'})
                               .appendTo(elements.volume);
            elements.volume40 = $j('<div>',{className:'volumebar volumebar_dark volume40'})
                               .appendTo(elements.volume);
            elements.volume60 = $j('<div>',{className:'volumebar volumebar_dark volume60'})
                               .appendTo(elements.volume);
            elements.volume80 = $j('<div>',{className:'volumebar volumebar_dark volume80'})
                               .appendTo(elements.volume);
            elements.volume100 = $j('<div>',{className:'volumebar volumebar_dark volume100'})
                               .appendTo(elements.volume);
            /*
            elements.fullscreen = $j('<div>',{className:'fullscreen'})
                               .appendTo(elements.control_wrap);
            */

            // Append quality boxes

            elements.quality_box = $j('<div>',{className:'quality_box'})
                               .appendTo(elements.control_wrap);

            elements.qualities_box = $j('<div>',{className:'qualities_box'})
                               .appendTo(elements.container);



            /*
            if(!data.totalItems || data.items[0].accessControl.embed!="allowed"){

                // If the video was not found, or embedding is not allowed;

                return elements.originalDIV;
            }
            */


            if(!data.totalItems || data.totalItems=="0"){
                // If the video was not found;
                //elements.error_box_close.show();
                elements.error_box.show();
                elements.error_box.html('Video incorrecto');
                return false;
            }

            if(data.totalItems=="0"){
                // If the video was not found;
                //elements.error_box_close.show();
                elements.error_box.show();
                elements.error_box.html('Video incorrecto');
                return false;
            }

            if(data.items[0].accessControl.embed!="allowed"){
                // If the video embedding is not allowed;
                //elements.error_box_close.show();
                elements.error_box.show();
                elements.error_box.html('Video incorrecto');
                return false;
            }

            // data holds API info about the video:

            data = data.items[0];

            settings.ratio = 3/4;
            if(data.aspectRatio == "widescreen"){
                settings.ratio = 9/16;
            }

            //settings.height = Math.round(settings.width*settings.ratio);




            // If the user wants to show the progress bar:

            if(settings.progress_bar){

                elements.progress_wrap = $j('<div>',{className:'progress_bar_wrap'})
                                    .appendTo(elements.control_wrap);

                elements.progress_wrap.css('width', screen_width-115+"px");

                elements.progress =    $j('<div>',{className:'progress_bar'})
                                    .appendTo(elements.progress_wrap);

                elements.progress.css('width', screen_width-120+"px");

                elements.elapsed =    $j('<div>',{className:'elapsed'})
                                    .appendTo(elements.progress);

                elements.time_wrap = $j('<div>',{className:'progress_time_wrap'})
                                    .appendTo(elements.control_wrap);

                elements.time_duration = $j('<div>',{className:'progress_time_duration'})
                                    .appendTo(elements.time_wrap);

                elements.time_current = $j('<div>',{className:'progress_time_current'})
                                    .appendTo(elements.time_wrap);

                minutes = Math.floor(data.duration/60);
                seconds = data.duration-(minutes*60);
                if(seconds<10){
                    seconds = "0"+seconds;
                }
                elements.time_duration.html("&nbsp;/&nbsp;"+minutes+":"+seconds);

                elements.time_current.html("0:00");

                elements.progress.click(function(e){

                    // When a click occurs on the progress bar, seek to the
                    // appropriate moment of the video.

                    elements.player.pauseVideo();

                    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);

                    elements.player.playVideo();
                });

            }

            var initialized = false;
            var custom_quality = "";

            // Creating a global event listening function for the video
            // (required by YouTube's player API):

            window['eventListener_'+settings.safeID] = function(status){

                var interval;
                var interval2;
                var interval3;
                var interval4;
                var interval5;

                var current_quality = elements.player.getPlaybackQuality();
                var video_qualities = new Array();

                //elements.quality_box.html(qualities[current_quality]);

                if(status==-1)    // video is loaded
                {
                    if(!initialized)
                    {
                        interval3 = window.setInterval(function(){
                            if(current_quality!=elements.player.getPlaybackQuality())
                            {
                                current_quality = elements.player.getPlaybackQuality();
                                elements.quality_box.html(qualities[current_quality]);
                            }
                        }, 3000);

                        interval4 = window.setInterval(function(){
                            // Check if qualities are available
                            if(video_qualities.length=="0")
                            {
                                video_qualities = elements.player.getAvailableQualityLevels();

                                for (var i=0; i<video_qualities.length; i++) {

                                    elements.quality_box.addClass('quality_box_high');
                                    if(video_qualities[i]=="hd1080")
                                    {
                                        elements.quality_hd1080 = $j('<div>',{className:'qualityhd1080'})
                                                           .appendTo(elements.qualities_box);
                                        elements.quality_hd1080.html(qualities['hd1080']);

                                        elements.quality_hd1080.bind('click', function() {
                                            elements.player.setPlaybackQuality('hd1080');
                                            elements.quality_box.removeClass('quality_box_high2');
                                            elements.qualities_box.hide();
                                        });
                                    }
                                    else if(video_qualities[i]=="hd720")
                                    {
                                        elements.quality_hd720 = $j('<div>',{className:'qualityhd720'})
                                                           .appendTo(elements.qualities_box);
                                        elements.quality_hd720.html(qualities['hd720']);

                                        elements.quality_hd720.bind('click', function() {
                                            elements.player.setPlaybackQuality('hd720');
                                            elements.quality_box.removeClass('quality_box_high2');
                                            elements.qualities_box.hide();
                                        });
                                    }
                                    else if(video_qualities[i]=="large")
                                    {
                                        elements.quality_large = $j('<div>',{className:'qualitylarge'})
                                                           .appendTo(elements.qualities_box);
                                        elements.quality_large.html(qualities['large']);

                                        elements.quality_large.bind('click', function() {
                                            elements.player.setPlaybackQuality('large');
                                            elements.quality_box.removeClass('quality_box_high2');
                                            elements.qualities_box.hide();
                                        });
                                    }
                                    else if(video_qualities[i]=="medium")
                                    {
                                        elements.quality_medium = $j('<div>',{className:'qualitymedium'})
                                                          .appendTo(elements.qualities_box);
                                        elements.quality_medium.html(qualities['medium']);

                                        elements.quality_medium.bind('click', function() {
                                            elements.player.setPlaybackQuality('medium');
                                            elements.quality_box.removeClass('quality_box_high2');
                                            elements.qualities_box.hide();
                                        });
                                    }
                                    else if(video_qualities[i]=="small")
                                    {
                                        elements.quality_small = $j('<div>',{className:'qualitysmall'})
                                                           .appendTo(elements.qualities_box);
                                        elements.quality_small.html(qualities['small']);

                                        elements.quality_small.bind('click', function() {
                                            elements.player.setPlaybackQuality('small');
                                            elements.quality_box.removeClass('quality_box_high2');
                                            elements.qualities_box.hide();
                                        });
                                    }

                                }
                            }
                        }, 3000);

                        interval5 = window.setInterval(function(){
                            if(custom_quality=="")
                            {
                                elements.player.setPlaybackQuality('medium');
                                custom_quality = "medium";
                            }
                        }, 1000);

                        elements.quality_box.click(function(){
                            // Show list only when non empty
                            if(elements.qualities_box.children().size() > 0)
                            {
                                if(elements.qualities_box.css('display')=='none')
                                {
                                    elements.quality_box.addClass('quality_box_high2');
                                    elements.qualities_box.show();
                                }
                                else
                                {
                                    elements.quality_box.removeClass('quality_box_high2');
                                    elements.qualities_box.hide();
                                }
                            }
                        });

                        // Listen for a click on the control button:

                        elements.control.click(function(){

                            if(!elements.container.hasClass('playing')){

                                // If the video is not currently playing, start it:

                                elements.control.removeClass('play replay').addClass('pause');
                                elements.container.addClass('playing');
                                elements.player.playVideo();

                                if(settings.progress_bar){
                                    interval = window.setInterval(function(){
                                        elements.elapsed.width(
                                            ((elements.player.getCurrentTime()/data.duration)*100)+'%'
                                        );
                                    },1000);
                                    interval2 = window.setInterval(function(){

                                    minutes_tmp = Math.floor(elements.player.getCurrentTime()/60);
                                    seconds_tmp = Math.floor(elements.player.getCurrentTime()-(minutes_tmp*60));
                                    if(seconds_tmp<10){
                                        seconds_tmp = "0"+seconds_tmp;
                                    }
                                    elements.time_current.html(minutes_tmp+":"+seconds_tmp);

                                    },1000);

                                    //DZ . added a global var to catch intervals;
                                    globalEventRegistry.push(interval);
                                    globalEventRegistry.push(interval2);
                                }

                            } else {

                                // If the video is currently playing, pause it:

                                elements.control.removeClass('pause').addClass('play');
                                elements.container.removeClass('playing');
                                elements.player.pauseVideo();

                                if(settings.progress_bar){
                                    window.clearInterval(interval);
                                    window.clearInterval(interval2);
                                }
                            }

                        });

                        // Listen for a click on the temporary play button:

                        elements.player_control_wrap.click(function(){

                            if(!elements.container.hasClass('playing')){

                                // If the video is not currently playing, start it:

                                elements.control.removeClass('play replay').addClass('pause');
                                elements.container.addClass('playing');
                                elements.player.playVideo();

                                if(settings.progress_bar){
                                    interval = window.setInterval(function(){
                                        elements.elapsed.width(
                                            ((elements.player.getCurrentTime()/data.duration)*100)+'%'
                                        );
                                    },1000);
                                    interval2 = window.setInterval(function(){

                                    minutes_tmp = Math.floor(elements.player.getCurrentTime()/60);
                                    seconds_tmp = Math.floor(elements.player.getCurrentTime()-(minutes_tmp*60));
                                    if(seconds_tmp<10){
                                        seconds_tmp = "0"+seconds_tmp;
                                    }
                                    elements.time_current.html(minutes_tmp+":"+seconds_tmp);

                                    },1000);

                                    //alert(window.globalEventRegistry);
                        // Listen for volume control click
                                }

                            } else {

                                // If the video is currently playing, pause it:

                                elements.control.removeClass('pause').addClass('play');
                                elements.container.removeClass('playing');
                                elements.player.pauseVideo();

                                if(settings.progress_bar){
                                    window.clearInterval(interval);
                                    window.clearInterval(interval2);
                                }
                            }

                        });

                        //DZ . added a global var to catch intervals;
                        window.globalEventRegistry.push(interval3);
                        window.globalEventRegistry.push(interval4);



                        $j(".volumebar").click(function()
                        {
                            if($j(this).hasClass('active')==false)
                            {
                                if($j(this).hasClass('volume0'))
                                {
                                    elements.player.setVolume("0");
                                }
                                else if($j(this).hasClass('volume20'))
                                {
                                    elements.player.setVolume("20");
                                }
                                else if($j(this).hasClass('volume40'))
                                {
                                    elements.player.setVolume("40");
                                }
                                else if($j(this).hasClass('volume60'))
                                {
                                    elements.player.setVolume("60");
                                }
                                else if($j(this).hasClass('volume80'))
                                {
                                    elements.player.setVolume("80");
                                }
                                else if($j(this).hasClass('volume100'))
                                {
                                    elements.player.setVolume("100");
                                }

                                $j(".volumebar").removeClass('active');
                                $j(".volumebar").removeClass('volumebar_bright');
                                $j(".volumebar").addClass('volumebar_dark');

                                $j(this).addClass('active');
                                $j(this).removeClass('volumebar_dark');
                                $j(this).addClass('volumebar_bright');
                            }

                        });

                        // Listen for volume control mouse over

                        $j(".volumebar").mouseover(function()
                        {
                            if($j(this).hasClass('active')==false)
                            {
                                $j(this).removeClass('volumebar_dark');
                                $j(this).addClass('volumebar_bright');
                            }
                        });

                        // Listen for volume control mouse over

                        $j(".volumebar").mouseout(function()
                        {
                            if($j(this).hasClass('active')==false)
                            {
                                $j(this).removeClass('volumebar_bright');
                                $j(this).addClass('volumebar_dark');
                            }
                        });

                        // Listen for fulscreen control click
                        /*
                        $j(".fullscreen").click(function()
                        {
                            elements.error_box_close.show();
                            elements.error_box.show();
                            elements.error_box.html('Option available soon');
                        });
                        */


                        // Hide errorbox

                        $j(".errorBoxClose").click(function()
                        {
                            elements.error_box.hide();
                            elements.error_box_close.hide();
                        });

                        initialized = true;

                        elements.player.setVolume("20");

                        // Auto play movie

                        //elements.control.removeClass('play replay').addClass('pause');
                        //elements.container.addClass('playing');
                        //elements.player.playVideo();

                        elements.control.click();
                    }
                    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.container.removeClass('playing');

                    elements.time_duration.html("&nbsp;/&nbsp;"+minutes+":"+seconds);
                }

            }

            // 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');



    }

})(jQuery);

