/*!
 * jQuery Vid5Player: HTML5 Video Player v1.1
 * http://ionwebdev.com/jquery-video-player/plugins
 *
 * Copyright 2010, Duane A. Comeaux
 * dacmeaux@gmail.com
 *
 * Released under the MIT, BSD, and GPL Licenses.
 *
 * Date: Sun Nov 14  23:00:00 2010 -0300
 *
 * Change Log v1.1
 *  -   Code totally re-written for better handling of events
 *  -   Fullscreen controls handled more smoothly and consistently
 *  -   The video element is now extended vs. the contianer for the video
 *      in version 1.01
*/

(function($){
    $.fn.html5video = function($options)
    {
        // set debugging
        if( $options.debug )
            $.fn.html5video.debug = true;

        var $settings = $.extend({}, $.fn.html5video.defaults, $options);
        $.fn.html5video.instid = Math.round(Math.random() * 1000000000);

        return this.each(function()
        {
            $this = this;
            var o = $.meta ? $.extend({}, $settings, $($this).data()) : $settings;
            $.fn.html5video.setupPlayer($this, o);


        });
    };

    $.fn.html5video.setupPlayer = function($obj, $attrs)
    {
        if( $obj.tagName.toLowerCase() == 'video' )
        {
            $($obj).attr({
                src         :   $attrs.src[0],
                poster      :   $attrs.poster[0],
                preload     :   $attrs.preload,
                controls    :   $attrs.controls,
                id          :   ($attrs.id != undefined
                                    ? $attrs.id +'-'+ $.fn.html5video.instid :
                                    'video-player-'+ $.fn.html5video.instid
                                ),
                type        :   $attrs.type,
                width       :   $attrs.width,
                height      :   $attrs.height
            })
            .bind('loadstart loadeddata canplaythrough playing seeked seeking played progress ended waiting timeupdate error abort stalled loadedmetadata pause loadedmetadata', function($event)
            {
                $.fn.html5video['handle'+ $event.type.ucwords()]($obj, $attrs, $event);
            })
            .parent().css({position: 'relative'});

            if( $attrs.loop != null )
                $($obj).attr('loop', $attrs.loop);
            if( $attrs.controls != null )
                $($obj).attr('controls', $attrs.controls);

            if( $attrs.usercontrols == 'yes' )
            {
                var user_agent = navigator.userAgent.toLowerCase();
                if( user_agent.indexOf('ipad') > -1
                    || user_agent.indexOf('ipod') > -1
                    || user_agent.indexOf('iphone') > -1
                    || user_agent.indexOf('mobile') > -1
                    || user_agent.indexOf('android') > -1
                    || ( user_agent.indexOf('blackberry') > -1 && user_agent.indexOf('version/6') > -1)
                    || user_agent.indexOf('iemobile/7') > -1)
                {
                    $($obj)
                    .attr({controls: 'controls'})
                    .removeAttr('autoplay');
                }
                else
                    $.fn.html5video.controls($obj, $attrs);
            }

            if( $attrs.autoplay != undefined )
            {
                $obj.load();
                $obj.play();
            }
        }
    };

    $.fn.html5video.controls = function($obj, $attrs)
    {
        $controls = $('<div id="video-player-controls-'+ $.fn.html5video.instid +'"></div>');
        $controls.addClass('controls');
        var parent = $($obj).parent();
        parent.append($controls);
        $buttons = $attrs.buttons;

        for( $y in $buttons )
        {
            if( $buttons[$y] == 'yes' )
            {
                if( $y != 'seekBar' )
                {
                    if( $y =='volume' )
                        $.fn.html5video.numButtons +=2;
                    else if( $y == 'time' )
                        $.fn.html5video.numButtons +=4;
                    else
                        $.fn.html5video.numButtons++;
                }
            }
        }

        for( $y in $buttons )
            if( $buttons[$y] == 'yes' )
                $.fn.html5video.buttons($y, $obj, $attrs, $controls);


        $controls.oneTime(3000, 'control', function()
        {
            $controls.fadeOut();
        });

        parent
        .bind('mouseenter mouseleave', function($event)
        {
            $controls.stopTime('control');
            if( $event.type == 'mouseenter' )
            {
                $('body').find('.bubble').remove();
                $controls.fadeIn();
            }
            else
                if( !$($event.relatedTarget).hasClass('controls') )
                    $controls.fadeOut();
        });

        return $controls;
    };

    $.fn.html5video.buttons =  function($btn, $obj, $attrs, $controls)
    {
        if( typeof($.fn.html5video.addButton[$btn]) == 'undefined' )
            $._debug('button '+ $btn +' is not valid', true);
        else
            $.fn.html5video.addButton[$btn]($obj, $attrs, $controls);
    };

     $.fn.html5video.addButton = {
        playPause : function($obj, $attrs, $controls)
        {
            $play_pause_btn = $('<a href="javascript:void(0);" id="play-pause-'+ $.fn.html5video.instid +'"></a>');
            $controls.append($play_pause_btn);

            $play_pause_btn
            .addClass('play-pause-btn btn')
            .css({
                background: '#666 url('+ $attrs.controlbtns_normal +') no-repeat 0px -'+ (16*10) +'px'
            })
            .mousedown(function($event)
            {
                if( $obj.paused )
                {
                    $bubble = $.fn.html5video.info('playing', $('body'), $event, true);

                    $(this)
                    .css({
                        background: '#666 url('+ $attrs.controlbtns_normal +') no-repeat -17px -'+ (16*10) +'px'
                    });

                    $obj.play();
                }
                else
                {
                    $bubble = $.fn.html5video.info('paused', $('body'), $event, true);

                    $(this)
                    .css({
                        background: '#666 url('+ $attrs.controlbtns_normal +') no-repeat 0px -'+ (16*10) +'px'
                    });

                    $obj.pause();
                }
            })
            .mouseup(function()
            {
                $bubble.fadeOut('slow', function(){$(this).remove();});
            })
            .mouseover(function()
            {
                if( $obj.paused )
                {
                    $(this)
                    .css({
                        background: '#666 url('+ $attrs.controlbtns_over +') no-repeat 0px -'+ (16*10) +'px'
                    });
                }
                else
                {
                    $(this)
                    .css({
                        background: '#666 url('+ $attrs.controlbtns_over +') no-repeat -17px -'+ (16*10) +'px'
                    });
                }
            })
            .mouseout(function()
            {
                if( $obj.paused )
                {
                    $(this)
                    .css({
                        background: '#666 url('+ $attrs.controlbtns_normal +') no-repeat 0px -'+ (16*10) +'px'
                    });
                }
                else
                {
                    $(this)
                    .css({
                        background: '#666 url('+ $attrs.controlbtns_normal +') no-repeat -17px -'+ (16*10) +'px'
                    });
                }
            });

            $($obj)
            .bind('playing', function()
            {
                $play_pause_btn
                .css({
                    background: '#666 url('+ $attrs.controlbtns_normal +') no-repeat -17px -'+ (16*10) +'px'
                });
            });

            return this;
        },

        seekBar : function($obj, $attrs, $controls)
        {
            $$bar_seek_bar = $('<div id="seek-bar-'+ $.fn.html5video.instid +'" class="seek-bar bar hor"></div>');
            $$track_seek_bar = $('<div id="seek-bar-track-'+ $.fn.html5video.instid +'"></div>').addClass('seek-bar-track');
            $$btn_seek_bar = $('<a href="javascript:void(0);" class="seek-btn btn" id="seek-btn-'+ $.fn.html5video.instid +'"></a>');
            $$progress_seek_bar = $('<div class="seek-bar-progress" id="seek-bar-progress-'+ $.fn.html5video.instid +'"></div>');
            $$loader_seek_bar = $('<div class="seek-bar-loader" id="seek-bar-loader-'+ $.fn.html5video.instid +'"></div>');

            $$bar_seek_bar
            .append($$btn_seek_bar)
            .append($$progress_seek_bar)
            .append($$track_seek_bar)
            .append($$loader_seek_bar);

            $controls.append($$bar_seek_bar);
            $.fn.html5video.seekBarWidth = $attrs.width - ($.fn.html5video.numButtons * 20); //$attrs.trackwidth;
            $.fn.html5video.oseekBarWidth = $.fn.html5video.seekBarWidth;
            $duration = 0;

            $$bar_seek_bar.css({width: $.fn.html5video.seekBarWidth - 15 +'px'});
            $$track_seek_bar.css({width: ($.fn.html5video.seekBarWidth) - 30 +'px'});

            $.fn.html5video.factor = ($.fn.html5video.seekBarWidth - 30) / $obj.duration;
            $.fn.html5video.ofactor = $.fn.html5video.factor;

            $$btn_seek_bar
            .draggable({axis: 'x', containment: $$btn_seek_bar.parent(), scroll: false})
            .mousedown(function($evt)
            {
                $bubble = $.fn.html5video.info('seeking', $('body'), $evt);
                $bubble.attr('id', 'seeking-'+ $.fn.html5video.instid);
                $paused = $obj.paused;
                $obj.pause();
                $(this)
                .bind('dragstart', function($event, ui)
                {
                    $obj.pause();
                })
                .bind('drag', function($event, ui)
                {
                    $($obj).stopTime('rm');
                    $$progress_seek_bar.css({width: ($(this).position().left) +'px'});
                    if( $obj.buffered != undefined )
                    {
                        $._debug('Can buffer', 'message');
                    	if( $$progress_seek_bar.width() / $.fn.html5video.factor <= $obj.buffered.end(0) * $.fn.html5video.factor )
                    		$obj.currentTime = $$progress_seek_bar.width() / $.fn.html5video.factor;
                        else
                            $obj.currentTime = $obj.buffered.end(0) * $.fn.html5video.factor;
                    }
                })
                .bind('dragstop', function($event, ui)
                {
                    $obj.currentTime = $$progress_seek_bar.width() / $.fn.html5video.factor;
                    if( !$paused )
                        $obj.play();
                });
            })
            .mouseup(function()
            {
                $(this).parent().find('.bubble').fadeOut(function(){$(this).remove();});
            })
            .mouseover(function()
            {
                $(this).css({background: '#000 url('+ $attrs.controlbtns_over +') -'+ (16*9+1) +'px -'+ (16*1+1) +'px no-repeat'});
            })
            .mouseout(function()
            {
                $(this).css({background: '#000 url('+ $attrs.controlbtns_normal +') -'+ (16*9+1) +'px -'+ (16*1+1) +'px no-repeat'});
            })
            .css({
                background: '#000 url('+ $attrs.controlbtns_normal +') -'+ (16*9+1) +'px -'+ (16*1+1) +'px no-repeat'
            });

            $$progress_seek_bar
            .bind('mousemove', function($event)
            {
                $.seekBar.time($event);
            })
            .click(function($event)
            {
               	$.seekBar.move($event, $obj);
            });

            $$track_seek_bar
            .bind('mousemove', function($event)
            {
                $.seekBar.time($event);
            })
            .click(function($event)
            {
                $.seekBar.move($event, $obj);
            });

            $$loader_seek_bar
            .bind('mousemove', function($event)
            {
                $.seekBar.time($event);
            })
            .click(function($event)
            {
                $.seekBar.move($event, $obj);
            });

            $$btn_seek_bar
            .bind('mousemove', function($event)
            {
                $.seekBar.time($event);
            })
            .click(function($event)
            {
                $.seekBar.move($event, $obj);
            });

            return this;
        },

        volume : function($obj, $attrs, $controls)
        {
            $$box_volume = $('<div id="volume-bar-'+ $.fn.html5video.instid +'"></div>');
            $$attrsp_volume = $('<a href="javascript:void(0);" id="volume-up-'+ $.fn.html5video.instid +'" class="volume-up btn"></a>');
            $$down_volume = $('<a href="javascript:void(0);" id="volume-down-'+ $.fn.html5video.instid +'" class=" volume-down btn"></a>');

            $controls.append($$box_volume);
            $$box_volume.addClass('volume bar').append($$down_volume).append($$attrsp_volume);

            var $bubble;

            $$attrsp_volume
            .css({
                background: '#666 url('+ $attrs.controlbtns_normal +') no-repeat -'+ (16*9) +'px -'+ (16*10) +'px'
            })
            .mouseover(function($event)
            {
                $bubble = $.fn.html5video.info('click and hold to raise volume', $('body'), $event, true);
                $(this).css({background: '#666 url('+ $attrs.controlbtns_over +') no-repeat -'+ (16*9) +'px -'+ (16*10) +'px'});
                $bubble.addClass('volume-bubble');
            })
            .mouseout(function()
            {
                $(document).find('.volume-bubble').fadeOut(function(){$(this).remove();});
                $(this).css({background: '#666 url('+ $attrs.controlbtns_normal +') no-repeat -'+ (16*9) +'px -'+ (16*10) +'px'});
            })
            .mousedown(function($event)
            {
                $(document).find('.volume-bubble').fadeOut(function(){$(this).remove();});
                var id = Math.round(Math.random() * 1000000000);
                $bubble = $.fn.html5video.info(Math.round($obj.volume*100) +'%', $('body'), $event, true);
                $bubble.addClass('volume-bubble');
                $(this)
                .everyTime(125, 'volup', function()
                {
                    if( $obj.volume <= 0.9 )
                        $obj.volume += 0.05;
                    else
                    {
                        $(this).stopTime('volup');
                        $obj.volume = 1;
                    }

                    $bubble.html(Math.round($obj.volume*100) +'%');
                }, 0);
            })
            .mouseup(function()
            {
                $(this).stopTime('volup');
                $(document).find('.volume-bubble').fadeOut(function(){$(this).remove();});
            });

            $$down_volume
            .css({
                background: '#666 url('+ $attrs.controlbtns_normal +') no-repeat -'+ (16*8) +'px -'+ (16*10) +'px'
            })
            .mouseover(function($event)
            {
                $bubble = $.fn.html5video.info('click and hold to lower volume', $('body'), $event, true);
                $(this).css({background: '#666 url('+ $attrs.controlbtns_over +') no-repeat -'+ (16*8) +'px -'+ (16*10) +'px'});
                $bubble.addClass('volume-bubble');
            })
            .mouseout(function()
            {
                $(document).find('.volume-bubble').fadeOut(function(){$(this).remove();});
                $(this).css({background: '#666 url('+ $attrs.controlbtns_normal +') no-repeat -'+ (16*8) +'px -'+ (16*10) +'px'});
            })
            .mousedown(function($event)
            {
                $(document).find('.volume-bubble').fadeOut(function(){$(this).remove();});
                $bubble = $.fn.html5video.info(Math.round($obj.volume*100) +'%', $('body'), $event, true);
                $bubble.addClass('volume-bubble');
                $(this)
                .everyTime(125, 'voldown', function()
                {
                    if( $obj.volume >= 0.1 )
                        $obj.volume -= 0.05;
                    else
                    {
                        $(this).stopTime('voldown');
                        $obj.volume = 0;
                    }

                    $bubble.html(Math.round($obj.volume*100) +'%');
                }, 0);
            })
            .mouseup(function()
            {
                $(this).stopTime('voldown');
                $(document).find('.volume-bubble').fadeOut(function(){$(this).remove();});
            });

            return this;
        },

        fullScreen : function($obj, $attrs, $controls)
        {
            $fullscreen_btn = $('<a href="javascript:void(0);" id="fullscreen-'+ $.fn.html5video.instid +'" class="fullscreen btn"></a>');
            $controls.append($fullscreen_btn);

            $fullscreen_btn
            .css({
                background: '#666 url('+ $attrs.controlbtns_normal +') no-repeat -'+ (16*10) +'px -'+ (16*7) +'px'
            })
            .mouseover(function($event)
            {
                var id = Math.round(Math.random() * 1000000000);
                $bubble = $.fn.html5video.info($attrs.zoomlevel +'X', $('body'), $event, true);

                $(this).css({background: '#666 url('+ $attrs.controlbtns_over +') no-repeat -'+ (16*10) +'px -'+ (16*7) +'px'});

                $bubble.attr('id', 'zoom-bubble-sm-'+ $.fn.html5video.instid).addClass('zoom-bubble');
            })
            .mouseout(function()
            {
                $('#zoom-bubble-sm-'+ $.fn.html5video.instid).fadeOut(500, function(){$(this).remove();});
                $(this).css({background: '#666 url('+ $attrs.controlbtns_normal +') no-repeat -'+ (16*10) +'px -'+ (16*7) +'px'});
            })
            .mousedown(function($event)
            {
                $('#zooming-bubble-'+ $.fn.html5video.instid).fadeOut(500, function(){$(this).remove();});
                var id = Math.round(Math.random() * 1000000000);
                $bubble = $.fn.html5video.info('zooming', $('body'), $event, true);
                $bubble.attr('id', 'zooming-bubble-'+ $.fn.html5video.instid);
				$$paused = $obj.paused;
                $$owidth = $($obj).width();
                $$oheight = $($obj).height();
                $$zwidth = $$owidth * $attrs.zoomlevel;
                $$zheight = $$oheight * $attrs.zoomlevel;
                $$wwidth = $(window).width();
                $$wheight = $(window).height();

                if( $$zwidth > $$wwidth )
                {
                    $ratio = $$zwidth/$$wwidth;
                    $$zwidth = $$wwidth;
                    $$zheight = Math.floor($$zheight/$ratio);
                   if( $$zheight > $$wheight )
                    {
                        $$zheight = $$wheight;
                        $ratio = $$zheight/$$wheight;
                        $$zwidth = $$zwidth/$ratio;
                    }
                }

                if( $$zheight > $$wheight )
                {
                    $ratio = $$zheight/$$wheight;
                    $$zheight = $$wheight;
                    $$zwidth = Math.floor($$zwidth/$ratio);
                    if( $$zwidth > $$wwidth )
                    {
                        $$zwidth = $$wwidth;
                        $ratio = $$zwidth/$$wwidth;
                        $$zheight = $$zheight/$ratio;
                    }
                }

                $overlay = $('<div class="overlay" id="overlay-'+ $.fn.html5video.instid +'"></div>');
                $('body').append($overlay);
                $overlay
                .css({
                    position: 'absolute',
                    zIndex: 49,
                    width: $(window).width() +'px',
                    height: $(document).height() +'px',
                    opacity: $attrs.overlayalpha,
                    background: '#000',
                    display: 'block',
                    top: '0px',
                    left: '0px'
                })
                .bind('click', function()
                {
                    $($obj).trigger('click');
                });

                $bubble = $.fn.html5video.info('click to zoom out', $('body'), $event);
                $bubble
                .attr('id', 'zoom-bubble')
                .css(
                {
                    fontSize: '30px',
                    fontWeight: 'bold',
                    zIndex: 100,
                    opacity: 0.4
                });

                $$oparent = $($obj).parent();
                $('<div id="videoplayer-temp"></div>').insertAfter($$oparent);
                $$nparent = $$oparent.parent();
                $$nparent.css({position: 'relative'});
                $$oparent.detach();

                $('body').append($$oparent);

                $$oparent.css({
                    position: 'absolute',
                    zIndex: 50
                })
                .css({
                    left: ($(window).width() - $$owidth)/2  +'px',
                    top: ($(window).height() - $$oheight)/2 + $(window).scrollTop() +'px'
                })
                .animate({
                    width: $$zwidth +'px',
                    height: $$zheight +'px',
                    left: ($(window).width() - $$zwidth)/2  +'px',
                    top: ($(window).height() - $$zheight)/2 + $(window).scrollTop() +'px'
                }, 500, function()
                {
                    $('#zoom-bubble-'+ $.fn.html5video.instid).fadeOut(500, function(){$(this).remove();});
                    if( $('#error-bubble'+ $.fn.html5video.instid).length )
                    {
                        var error_bubble = $('#error-bubble'+ $.fn.html5video.instid);
                        var percent_left = Math.floor(($(this).width() - error_bubble.width())/2 / $(this).width() * 100);
                        var percent_top = Math.floor(($(this).height() - error_bubble.height())/2 / $(this).height() * 100);
						error_bubble
						.animate({
                            left: percent_left +'%',
                            top: percent_top +'%'
						}, 500);
                    }

                    var zoom_percent_left = Math.floor(($(window).width() - $bubble.width())/2 / $(window).width() * 100);
                    var zoom_percent_top = Math.floor(($(window).height() + $(window).scrollTop() * 2 - $bubble.height())/2 / ($(window).height()) * 100);
                    $bubble
                    .css(
                    {
                        left: zoom_percent_left +'%',
                        top: zoom_percent_top +'%'
                    });

                    $(document).oneTime(3000, 'zoom_timer', function()
                    {
                        $bubble.fadeOut('slow', function(){$(this).find('.bubble').remove();});
                    });

                    $('.fullscreen').css({display: 'none'});
                    if( !$$paused )
                        $obj.play();

                    $('#zooming-bubble-'+ $.fn.html5video.instid +'#zoom-bubble-sm-'+ $.fn.html5video.instid).fadeOut(500, function(){$(this).remove();});
                });

                $$origianl_bar_width = $.fn.html5video.seekBarWidth;
                $factor = $.fn.html5video.factor;
                $.fn.html5video.seekBarWidth = $$zwidth - ($.fn.html5video.numButtons * 20);


                $.fn.html5video.factor = $.fn.html5video.seekBarWidth / $obj.duration;
                var seek_width = $('#seek-bar-'+ $.fn.html5video.instid).width();
                var track_width = $('#seek-bar-track-'+ $.fn.html5video.instid).width();
                var loader_width = $('#seek-bar-loader-'+ $.fn.html5video.instid).width();
                var progress_width = $('#seek-bar-progress-'+ $.fn.html5video.instid).width();
                var seek_btn_position = $('#seek-btn-'+ $.fn.html5video.instid).position().left;

                var seek_width_zoom = $.fn.html5video.seekBarWidth - 15; //($$zwidth - ($.fn.html5video.numButtons * 20) * $.fn.html5video.factor) - 15;
                var track_width_zoom = $.fn.html5video.seekBarWidth - 30; //($$zwidth - ($.fn.html5video.numButtons * 20) * $.fn.html5video.factor) - 30;
                var loader_width_zoom = loader_width / $.fn.html5video.factor;
                var progress_width_zoom = loader_width / $.fn.html5video.factor;
                var seek_btn_position_zoom = seek_btn_position / $.fn.html5video.factor;

                $($obj)
                .animate({
                    width: $$zwidth +'px',
                    height: $$zheight +'px'
                }, 500, function()
                {
                    $('#seek-bar-'+ $.fn.html5video.instid)
                    .animate({
                            width: seek_width_zoom +'px'
                    }, 500);
                    $('#seek-bar-track-'+ $.fn.html5video.instid)
                    .animate({
                            width: track_width_zoom +'px'
                    }, 500);

                    $('#seek-bar-loader-'+ $.fn.html5video.instid)
                    .animate({
                            width: loader_width_zoom +'px'
                    }, 500);
                    $('#seek-bar-progress-'+ $.fn.html5video.instid)
                    .animate({
                            width: progress_width_zoom +'px'
                    }, 500);
                    if( $$paused )
                    {
                            $('#seek-btn-'+ $.fn.html5video.instid)
                            .animate({
                                    left: seek_btn_position_zoom +'px'
                            }, 500);
                    }

                    $('#zooming-bubble-'+ $.fn.html5video.instid).fadeOut(500,function(){$(this).remove();});
                    $.fn.html5video.zoomedIn = true;
                })
                .bind('click', function()
                {
                    $(document).stopTime('zooom_timer');
					$(document).find('.bubble').fadeOut('fast', function(){$(this).remove();});
                    $$oparent
                    .animate({
                        width: $$owidth +'px',
                        height: $$oheight +'px',
                        left: ($(window).width() - $$owidth)/2  +'px',
                        top: ($(window).height() - $$oheight)/2 + $(window).scrollTop() +'px',
                        opacity: 0
                    }, 500, function()
                    {

                        $$paused = $obj.paused;
                        $$oparent.detach();
                        $$oparent
                        .insertAfter($('#videoplayer-temp'))
                        .css({
                            position: 'relative',
                            zIndex: 0,
                            left: '0px',
                            top: '0px',
                            opacity: 1
                        });
                        $('#videoplayer-temp')
                        .css({width: '0px', height: '0px'})
                        .oneTime(500, function(){$(this).remove();});
                         if( !$$paused )
                            $obj.play();

                        if( $('#error-bubble'+ $.fn.html5video.instid).length )
                        {
                            var error_bubble = $('#error-bubble'+ $.fn.html5video.instid);
                            var percent_left = Math.floor(($$oparent.width() - error_bubble.width())/2 / $$oparent.width() * 100);
                            var percent_top = Math.floor(($$oparent.height() - error_bubble.height())/2 / $$oparent.height() * 100);
                            error_bubble
                            .animate({
                                left: percent_left +'%',
                                top: percent_top +'%'
                            }, 500);
                        }

                        $.fn.html5video.zoomedIn = false;
                    });

                    $('.fullscreen').css({display: 'block'});

                    $.fn.html5video.seekBarWidth = $$origianl_bar_width;

                    $('#seek-bar-'+ $.fn.html5video.instid)
                    .animate({
                            width: seek_width +'px'
                    }, 500);
                    $('#seek-bar-track-'+ $.fn.html5video.instid)
                    .animate({
                            width: track_width +'px'
                    }, 500);
                    $('#seek-bar-loader-'+ $.fn.html5video.instid)
                    .animate({
                            width: loader_width +'px'
                    }, 500);
                    $('#seek-bar-progress-'+ $.fn.html5video.instid)
                    .animate({
                            width: progress_width +'px'
                    }, 500);

                    //if( $$paused )
                    //{
                            $('#seek-btn-'+ $.fn.html5video.instid)
                            .animate({
                                    left: '0px'
                            }, 500);
                    //}

                    $.fn.html5video.factor = $.fn.html5video.ofactor;

                    $($obj)
                    .animate({
                        width: $$owidth +'px',
                        height: $$oheight +'px'
                    }, 500)
                    .unbind('click');

                    $('.info').remove();
                    $overlay
                    .fadeOut(function()
                    {
                        $(this).remove();
                    });
                    $bubble.fadeOut('fast');
                });
            })
            .mouseup(function()
            {
            	$('#zooming-bubble-'+ $.fn.html5video.instid).fadeOut(500,function(){$(this).remove();});
                $(this).parent().find('.bubble').fadeOut(function(){$(this).remove();});
            });
            return this;
        },

        time : function($obj, $attrs, $controls)
        {
            $$tbox = $('<div class="time bar" id="time-bar-'+ $.fn.html5video.instid +'"></div>');
            $$time = $('<a class="timer btn" id="timer-'+ $.fn.html5video.instid +'" href="javascript:void(0);"></a>');
            $$ttext = $('<span class="time-text" id="time-text-'+ $.fn.html5video.instid +'"></span>');
            $$tbox.append($$time)
            .append($$ttext);

            $controls.append($$tbox);

            var $bubble;

            $$time
            .css({
                background: '#000 url('+ $attrs.controlbtns_normal +') no-repeat -'+ (16*5) +'px -'+ (16*7) +'px'
            })
            .mouseover(function($event)
            {
                $$duration = $obj.duration;
                $bubble = $.fn.html5video.info($.timeComponent($$duration, 'hours') +':'+ $.timeComponent($$duration, 'minutes') +':'+ $.timeComponent($$duration, 'seconds'), $('body'), $event, true);
                $bubble.attr('id', 'time-bubble-'+ $.fn.html5video.instid);
                $(this).css({background: '#000 url('+ $attrs.controlbtns_over +') no-repeat -'+ (16*5) +'px -'+ (16*7) +'px'});
            })
            .mouseout(function()
            {
                $('#time-bubble-'+ $.fn.html5video.instid).fadeOut(function(){$(this).remove();});
                $(this).css({background: '#000 url('+ $attrs.controlbtns_normal +') no-repeat -'+ (16*5) +'px -'+ (16*7) +'px'});
            });
            
            return this;
        }

    };

    $.seekBar = {
        move : function($evt, $obj)
        {
                $obj.currentTime = ($evt.pageX - $($evt.currentTarget).offset().left) / $.fn.html5video.factor;
                $$btn_seek_bar.css({left: $evt.pageX - $($evt.currentTarget).offset().left - $$btn_seek_bar.width()/2 +'px'});
                $$progress_seek_bar.css({width: (($obj.currentTime * $.fn.html5video.factor)) +'px'});
        },
        time : function($evt)
        {
            if( $($evt.currentTarget).hasClass('seek-btn') )
                $pos = $evt.pageX - $('#seek-bar-track-'+ $.fn.html5video.instid).offset().left;
            else
                $pos = $evt.pageX - $($evt.currentTarget).offset().left;
            $time = Math.round($pos / $.fn.html5video.factor);
            $('.time-bubble')
            .each(function()
            {
                    $(this).fadeOut(300, function(){$(this).remove();});
            });
            $$tbubble = $.fn.html5video.info($.timeComponent($time, 'hours') +':'+ $.timeComponent($time, 'minutes') +':'+ $.timeComponent($time, 'seconds'), $('body'), $evt, true);
            $$tbubble.addClass('time-bubble'); //.css({fontSize: '10px'});

            $$tbubble.css({top: $($evt.currentTarget).offset().top - $$tbubble.height() - 15 +'px'});

            $($evt.currentTarget).mouseleave(function(){$$tbubble.remove();});
        }
    };

    $.timeComponent = function($t, $c)
    {
        $x = 0;
        switch( $c )
            {
            case "seconds"  :$x = $.timeComponent.seconds($t);break;
            case "minutes"  :$x = $.timeComponent.minutes($t);break;
            case "hours"    :$x = $.timeComponent.hours($t);break;
            default         :$x = 0;
            }

        if( $x < 10 )
            return '0'+ $x;
        else
            return $x;
    };

    $.timeComponent.seconds = function($t)
    {
        $s = 0;
        if( Math.floor($t) % 60 == 0 )
            $s = 0;
        else
            $s = Math.floor($t) - Math.floor($t/60)*60;
        return $s;
    };

    $.timeComponent.minutes = function($t)
    {
        $m = 0;
        $m = Math.floor($t/60);
        return $m;
    };

    $.timeComponent.hours = function($t)
    {
        $h = 0;
        $h = Math.floor($t/4250);
        return $h;
    };

    $.fn.html5video.handleLoadstart     = function($obj, $attrs, $e)
    {
        $._debug('Load Start', 'message');
        $bubble = $.fn.html5video.info('Loading...', $('body'), $e, false);
        $bubble
        .css({
            fontSize: '20px'
        })
        .attr('id', 'loading-bubble-'+ $.fn.html5video.instid)
        .css({
            left: ($($obj).offset().left + ($($obj).width() - $bubble.width())/2) +'px',
            top: ($($obj).offset().top + ($($obj).height() - $bubble.height())/2) +'px'
        });
    };

    $.fn.html5video.handleLoadeddata    = function($obj, $attrs, $e)
    {
        $._debug('Loaded Data', 'message');
        $('#loading-bubble-'+ $.fn.html5video.instid).fadeOut(500, function()
        {
            $(this).remove();
        });
    };

    $.fn.html5video.handlePlaying       = function($obj, $attrs, $e)
    {
        $._debug('Playing', 'message');
        $.fn.html5video.factor = ($.fn.html5video.seekBarWidth - 30) / $obj.duration;
        $($obj).stopTime('rm');
        $($obj)
        .everyTime(100, 'rm', function()
        {
            if( $obj.paused )
            {
                $($obj).stopTime('rm');
            }
            else
            {
                if( $obj.readyState > 0 )
                {
                    $._debug($obj.duration, 'message');
                    $$progress_seek_bar.css({width: ($obj.currentTime * $.fn.html5video.factor) +'px'});
                    $$btn_seek_bar.css({left: ($obj.currentTime * $.fn.html5video.factor) +'px'});
                }
            }
        }, 0)
        .parent().find('.bubble').each(function()
        {
            $(this).fadeOut(500, function(){$(this).remove();});
        });

    };

    $.fn.html5video.handlePause       = function($obj, $attrs, $e)
    {
        $._debug('Paused', 'message');
        $($obj).stopTime('rm');
        $($obj).parent().find('.bubble').each(function()
        {
            $(this).fadeOut(500, function(){$(this).remove();});
        });
    };

    $.fn.html5video.handlePlayed        = function($obj, $attrs, $e)
    {
        //$($obj).stopTime('rm');
    };

    $.fn.html5video.handleWaiting       = function($obj, $attrs, $e)
    {
        $($obj).stopTime('rm');
        $._debug('Waiting', 'message');
        $bubble = $.fn.html5video.info('Buffering...', $('body'), $e, false);
        $bubble
        .css({
            fontSize: '20px'
        })
        .attr('id', 'waiting-bubble-'+ $.fn.html5video.instid)
        .css({
            left: ($($obj).offset().left + ($($obj).width() - $bubble.width())/2) +'px',
            top: ($($obj).offset().top + ($($obj).height() - $bubble.height())/2) +'px'
        });
    };

    $.fn.html5video.handleTimeupdate    = function($obj, $attrs, $e)
    {
        $._debug('Updating', 'message');
        $('#loading-bubble-'+ $.fn.html5video.instid +',#waiting-bubble-'+ $.fn.html5video.instid)
        .fadeOut(500, function()
        {
            $(this).remove();
        });

        $$etime = $obj.duration - $obj.currentTime;
        $('#time-text-'+ $.fn.html5video.instid)
        .html($.timeComponent($$etime, 'hours') +':'+ $.timeComponent($$etime, 'minutes') +':'+ $.timeComponent($$etime, 'seconds') );
    };

    $.fn.html5video.handleSeeked       = function($obj, $attrs, $e)
    {
        $._debug('Seeked', 'message');
        $('#seeking-'+ $.fn.html5video.instid).fadeOut(500, function(){$(this).remove();});
    };

    $.fn.html5video.handleSeeking       = function($obj, $attrs, $e)
    {
        $('#seeking-'+ $.fn.html5video.instid).fadeOut(500, function(){$(this).remove();});
        $._debug('Seeking', 'message');
    };

    $.fn.html5video.handleProgress      = function($obj, $attrs, $e)

    {
        // This event is not fully supported// by all major browsers
        $._debug('Progressing', 'message');
        if( $obj.buffered != undefined )
        {
            $('#seek-bar-loader-'+ $.fn.html5video.instid)
            .css({width: ($obj.buffered.end(0) * $.fn.html5video.factor) +'px' });
        }
    };

    $.fn.html5video.handleEnded         = function($obj, $attrs, $e)
    {
        $($obj).stopTime('rm');

        if( $obj.currentTime >= $obj.duration )
        {
            $.fn.html5video.nextVideo++;
            $._debug($attrs.src[$.fn.html5video.nextVideo], 'message');
            if( $attrs.src[$.fn.html5video.nextVideo] != undefined )
            {
                $($obj).attr({
                    src: $attrs.src[$.fn.html5video.nextVideo],
                    poster: $attrs.poster[$.fn.html5video.nextVideo]
                });
                $obj.load();
                $.fn.html5video.factor = ($.fn.html5video.seekBarWidth - 30) / $obj.duration;
                $obj.play();
            }
            else
            {
                $($obj).attr({
                    src: $attrs.src[0],
                    poster: $attrs.poster[0]
                });
                $obj.load();
                $.fn.html5video.factor = ($.fn.html5video.seekBarWidth - 30) / $obj.duration;
                $obj.pause();
                $.fn.html5video.nextVideo = 0;
            }
        }
    };

    $.fn.html5video.handleError         = function($obj, $attrs, $e)
    {
        $._debug('error', 'message');
        var $$error_text = 'Attempted to play:<br>'+ $($obj).attr('src') +'.<br><br>';
        if(  $e.target.error != undefined )
        {
            switch( $e.target.error.code )
            {
                case $e.target.error.MEDIA_ERR_ABORTED:
                    $$error_text += 'You aborted the video playback.';
                    break;
                case $e.target.error.MEDIA_ERR_NETWORK:
                    $$error_text += 'A network error caused the video download to fail part-way.';
                    break;
                case $e.target.error.MEDIA_ERR_DECODE:
                    $$error_text += 'The video playback was aborted due<br>to a corruption problem or because<br>the video used features your<br>browser did not support.';
                    break;
                case $e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:
                    $$error_text += 'The video could not be loaded,<br>either because the server or<br>network failed or<br>because the format is not supported.';
                    break;
                default:
                    $$error_text += 'An unknown error occurred.';
                    break;
            }

            $('.bubble').fadeOut(function(){$(this).remove();});
            $bubble = $.fn.html5video.info($$error_text, $($obj).parent(), $e, false);

            var percent_left = Math.floor(($($obj).width() - $bubble.width())/2 / $($obj).width() * 100);
            var percent_top = Math.floor(($($obj).height() - $bubble.height())/2 / $($obj).height() * 100);
            $bubble
            .attr('id', 'error-bubble-'+ $.fn.html5video.instid)
            .fadeIn('slow')
            .css({
                margin: '0 auto',
                left: percent_left +'%',
                top: percent_top +'%'
            });
        }
    };

    $.fn.html5video.handleCanplaythrough= function($obj, $attrs, $e)
    {

    };

    $.fn.html5video.handleAbort         = function($obj, $attrs, $e)
    {

    };

    $.fn.html5video.handleStalled       = function($obj, $attrs, $e)
    {

    };

    $.fn.html5video.handleLoadedmetadata= function($obj, $attrs, $e)
    {
        if( !$.fn.html5video.zoomedIn )
        {
            $.fn.html5video.oseekBarWidth = $attrs.width - ($.fn.html5video.numButtons * 20);
            $.fn.html5video.factor = ($.fn.html5video.oseekBarWidth - 30) / $obj.duration;
        }
        else
            $.fn.html5video.factor = ($.fn.html5video.seekBarWidth - 30) / $obj.duration;
    };

    $.fn.html5video.numButtons = 0;
    $.fn.html5video.seekBarWidth = 0;
    $.fn.html5video.oseekBarWidth = 0;
    $.fn.html5video.nextVideo = 0;
    $.fn.html5video.factor = 0;
    $.fn.html5video.ofactor = 0;
    $.fn.html5video.zoomedIn = false;

    $.fn.html5video.defaults =
    {
        src         :       ['video.m4v'],
        type        :       'video/x-m4v',
        poster      :       ['poster_1.jpg'],
        width       :       480,
        height      :       270,
        controls    :       'controls',
        preload     :       'auto',
        autoplay    :       'autoplay',
        loop        :       '',
        controlbtns_normal :'styles/images/ui-icons_ef8c08_256x240.png',
        controlbtns_over :  'styles/images/ui-icons_ffd27a_256x240.png',
        usercontrols:       'no',
        buttons     :       {playPause:'yes',seekBar:'no',time:'no',volume:'no',fullScreen:'no',mute:'no'},
        overlayalpha:       0.8,
        zoomlevel   :       4
    };

    $.fn.html5video.info = function($text, $obj, $event, $attrsse_default_position)
    {
        var id = Math.round(Math.random() * 1000000000);
        var $bubble = $('<div id="bubble-'+ id +'" class="bubble"></div>');
        $bubble.html($text);
        if( $($obj) == undefined )
            $('body').append($bubble);
        else
            $($obj).append($bubble);

        $(document).stopTime();
        if( $attrsse_default_position == true || $attrsse_default_position == undefined )
        {
            $bubble
            .css({
                left: $event.pageX - ($('#bubble-'+ id).width())/2 +'px',
                top: $($event.currentTarget).offset().top - $($event.currentTarget).height() - $('#bubble-'+ id).height() +'px'
            });
        }
        $._debug($($event.target).offset().left, 'message');

        return $bubble;
    };

    $._debug = function(obj, type)
    {
        if( window.console && window.console.log && $.fn.html5video.debug == true )
        {
            if( type != undefined )
                window.console.log(type +': '+ obj);
            else
                window.console.log('Affected Elements '+ $(obj).size());
        }
    };

})(jQuery);

String.prototype.ucwords = function(){
    return this.replace(/\w+/g, function(a){
        return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
    });
};
