//HTML5 Video JQuery Plugin
//version 1.1
//dependencies: jquery, swfobject 2
//Ben Pritchard - New Perspective 2011

(function ($) {
    $.fn.npHTML5Video = function (args) {
        return this.each(function () {
            var $this = $(this);
            var videoElem = $(this);
            var flashStr = "";
            var sourceStr = "";
            var downloadStr = "";
            var mp4Codec = "";
            var autoplay;
            var manualSeek;
            var touchDevice;

            //source for videos
            //Android browser will not display an h264 video when the source element supplys a type attribute
            //Check for Android and apply the type attribute if it is a non-Android device
            if (!isAndroid()) {
                mp4Codec = 'type=\'video/mp4; codecs="avc1.42E01E, mp4a.40.2"\'';
            }
            var vidSource;

            if (isIOS()) {
                sourceStr = '<source src="' + args.appleStream + '"/>';
            } else {
                sourceStr = '<source src="' + args.mp4 + '" ' + mp4Codec + ' />';
            }

            if (isIPhoneIOS5()) {
                mp4Codec = 'type=\'video/mp4\'';
                sourceStr = '<source src="' + args.mp4 + '" ' + mp4Codec + ' />';
            }

            //fall back for browsers that support the video element but fail
            downloadStr = '<p>Download video as <a href="' + args.mp4 + '">MP4</a>.</p>';
            //check if the browser can handle playback via the video element

            //check if this device supports touch events
            touchDevice = isTouchDevice();

            autoplay = args.autoplay;
            if (autoplay != true || autoplay == undefined) {
                if ($this.attr("autoplay") != undefined) {
                    autoplay = args.autoplay;
                } else {
                    autoplay = false;
                }
            }

            //flash version
            if (isAndroid()) {
                flashVersionStr = "20.0.0"; //Android will not use flash so set the version high
            } else {
                flashVersionStr = "10.0.0";
            }

            if (args.flashVer) {
                flashVersionStr = args.flashVer;
            }

            if (!isIOS() && swfobject.hasFlashPlayerVersion(flashVersionStr)) {
            verlicon('***');
                //ie 6 is angry when not provided with an id, attempt to get it from the video tag, default it to a random string otherwise
                var _id;
                if ($this.attr('id').length > 0) {
                    _id = $this.attr('id');
                } else {
                    _id = ("videoPlayer_" + Math.random() * 999).toString();
                }
                //ie 6 thinks the video tag is invalid, width() and height() will throw errors, use attr() instead to get width and height
                var cntrlHeight = 40;
                if (args.controlHeight) {
                    cntrlHeight = args.controlHeight;
                }

                var posterFrame = $this.attr("poster");
                if (posterFrame == undefined) {
                    posterFrame = "/images/blackPoster.jpg";
                }

                //ie mis-adds control height so parseInt the addition
                //alert(posterFrame);
                swfobject.embedSWF(args.swf, _id, $this.attr('width'), parseInt(parseInt($this.attr('height')) + cntrlHeight), flashVersionStr, args.swfExpressInstall, {
                    mp4: args.mp4,
                    posterFrame: posterFrame,
                    color: args.color,
                    autoPlay: autoplay,
                    rtmp: args.rtmp,
                    streamList: args.streamList
                }, {
                    menu: "false",
                    allowFullScreen: "true"
                }, {
                    base: args.swfBase,
                    id: _id,
                    name: _id
                });
            } else {
                //browser supports the video element, write the source elements
                if (!document.createElement('video').canPlayType != true) {
                    var videoPlayerHTML = '<div id="' + $this.attr("id") + '_player" rel="' + $this.attr("id") + '" class="player">' +
								   '<div id="' + $this.attr("id") + '_playtoggle" class="playtoggle"></div>' +
								   '<div class="divider"></div>' +
								   '<div id="' + $this.attr("id") + '_gutter" class="gutter">' +
								   '<div id="' + $this.attr("id") + '_progress" class="progress"><img src="/audioController/progress.png" width="100%" height="18" /></div>' +
								   '</div>' +
								   '<div id="' + $this.attr("id") + '_timeleft" class="timeleft">00:00/00:00</div>' +
								   '<div class="clear"></div>' +
								   '</div>'
                    $this.html(sourceStr);
                    $this.after(videoPlayerHTML);

                    //hide the real controls
                    $this.attr("controls", "");
                    //skinned element references
                    var playtoggleRef = $("#" + $this.attr("id") + "_playtoggle");
                    var gutterRef = $("#" + $this.attr("id") + "_gutter");
                    var progressRef = $("#" + $this.attr("id") + "_progress");
                    var timeleftRef = $("#" + $this.attr("id") + "_timeleft");
                    var audiomuteRef = $("#" + $this.attr("id") + "_audiomute");


                    //bind complete event
                    $(this).bind("ended", function () {
                        $this.attr("currentTime", 0);
                        $this.trigger("pause");
                        playtoggleRef.css({ backgroundPosition: '0px 0px' });
                    });


                    //poster frame click capability
                    if (!isIOS()) {
                        $(this).bind("click", function () { playToggleEvent(playtoggleRef, $this) });
                    }

                    //apply some color
                    var progColor = "#b71234";
                    if (args.color) {
                        progColor = "#" + args.color.split("x")[1];
                    }
                    progressRef.css("backgroundColor", progColor);
                    //jquery ui slider
                    gutterRef.slider({
                        value: 0,
                        step: 0.01,
                        orientation: "horizontal",
                        range: "min",
                        max: $this.duration,
                        animate: true,
                        slide: function (e, ui) {
                            manualSeek = true;
                            progressRef.width(gutterRef.width() * (ui.value / 100));
                        },
                        stop: function (e, ui) {
                            manualSeek = false;
                            $this.attr("currentTime", videoElem.attr("duration") * (ui.value / 100));
                        }
                    });
                    //on playhead update event
                    $(this).bind('timeupdate', function () {
                        var cTime = videoElem.attr("currentTime");
                        var tTime = videoElem.attr("duration");
                        pos = (cTime / tTime) * 100;
                        timeleftRef.text(cmtss(cTime) + "/" + cmtss(tTime));
                        if (!manualSeek) {
                            gutterRef.slider("option", "value", pos);
                            progressRef.width(pos + '%')
                        }
                    });
                    //play pause control
                    playtoggleRef.click(function () { playToggleEvent(playtoggleRef, $this) });


                    if (touchDevice != true) {
                        playtoggleRef.mouseover(function () { onPlayPauseOver(playtoggleRef, $this) });
                        playtoggleRef.mouseout(function () { onPlayPauseOut(playtoggleRef, $this) })
                    }
                    //audio mute control binding
                    audiomuteRef.click(function () { mute(audiomuteRef, $this) });
                    if (touchDevice != true) {
                        audiomuteRef.mouseover(function () { onAudioOver(audiomuteRef, $this) });
                        audiomuteRef.mouseout(function () { onAudioOut(audiomuteRef, $this) });
                    }
                } else {
                    $this.replaceWith("Your browser does not support Flash or the HTML5 Video Tag");
                }
            }
            if (args.debug == true) {
                $("body").append("<br />HTML5 Video JQuery Plugin DEBUG:<br />");
                jQuery.each(jQuery.browser, function (i, val) {
                    $("<div>" + i + " : <span>" + val + "</span>")
			.appendTo(document.body);
                });
            }
        });
    };
})(jQuery);
function playToggleEvent(playtoggleRef, videoElem) {
    if (videoElem.attr("paused")) {
        if (!isIPhoneIPod()) {
            if (isTouchDevice() != true) {
                playtoggleRef.css({ backgroundPosition: '-117px 0px' });
            } else {
                playtoggleRef.css({ backgroundPosition: '-78px 0px' });
            }
        }
        videoElem.trigger("play", "");
    } else {
        if (!isIPhoneIPod()) {
            if (isTouchDevice() != true) {
                playtoggleRef.css({ backgroundPosition: '-78px 0px' });
            } else {
                playtoggleRef.css({ backgroundPosition: '0px 0px' });
            }
        }
        videoElem.trigger("pause");
    }
}
//check if this device supports touch events
function isTouchDevice() {
    if (typeof document.body.ontouchstart != "undefined") {
        return true;
    } else {
        return false;
    }
}
function onPlayPauseOver(playtoggleRef, videoElem) {
    if (!videoElem.attr("paused")) {
        playtoggleRef.css({ backgroundPosition: '-117px 0px' });
    } else {
        playtoggleRef.css({ backgroundPosition: '-39px 0px' });
    }
}
function onPlayPauseOut(playtoggleRef, videoElem) {
    if (!videoElem.attr("paused")) {
        playtoggleRef.css({ backgroundPosition: '-78px 0px' });
    } else {
        playtoggleRef.css({ backgroundPosition: '0px 0px' });
    }
}


function mute(audiomuteRef, videoElem) {
    if (videoElem.attr("volume") != 0) {
        videoElem.attr("volume", 0);
        audiomuteRef.css({ backgroundPosition: '-117px 0px' });
    } else {
        videoElem.attr("volume", 1);
        audiomuteRef.css({ backgroundPosition: '-39px 0px' });
    }
}
function onAudioOver(audiomuteRef, videoElem) {
    if (videoElem.attr("volume") == 0) {
        audiomuteRef.css({ backgroundPosition: '-117px 0px' });
    } else {
        audiomuteRef.css({ backgroundPosition: '-39px 0px' });
    }
}
function onAudioOut(audiomuteRef, videoElem) {
    if (videoElem.attr("volume") == 0) {
        audiomuteRef.css({ backgroundPosition: '-78px 0px' });
    } else {
        audiomuteRef.css({ backgroundPosition: '0px 0px' });
    }
}
function cmtss(s) {//returns mins:seconds
    inputTime = s;
    //Number of Hours
    NoH = Math.floor(inputTime / 3600);
    remaining = inputTime - (NoH * 3600);
    //Number of Minutes
    NoM = Math.floor(remaining / 60);
    remaining = remaining - (NoM * 60);
    //Number of Seconds
    NoS = Math.floor(remaining);
    //Check if value is a single digit, if so concatinate with '0' else display value.
    if (NoH < 10) {
        hours = "0" + NoH.toString();
    } else {
        hours = NoH.toString();
    }
    if (NoM < 10) {
        minutes = "0" + NoM.toString();
    } else {
        minutes = NoM.toString();
    }
    if (NoS < 10) {
        seconds = "0" + NoS.toString();
    } else {
        seconds = NoS.toString();
    }
    if (isNaN(minutes)) {
        minutes = "00";
    }
    if (isNaN(seconds)) {
        seconds = "00";
    }
    return minutes + ":" + seconds;
}

function isIPad() {
    if (navigator.userAgent.toLowerCase().indexOf("ipad") > -1) {
        return true;
    } else {
        return false;
    }
}
function isIPhoneIPod() {
    if (navigator.userAgent.toLowerCase().indexOf("iphone") > -1 || navigator.userAgent.toLowerCase().indexOf("ipod") > -1) {
        return true;
    } else {
        return false;
    }
}
function isIPhoneIOS5() {
    if (navigator.userAgent.toLowerCase().indexOf("iphone") > -1 && navigator.userAgent.toLowerCase().indexOf("os 5") > -1) {
        return true;
    } else {
        return false;
    }
}
function isIOS() {
    if (isIPad() || isIPhoneIPod()) {
        return true;
    } else {
        return false;
    }
}
function isAndroid() {
    if (navigator.userAgent.toLowerCase().indexOf("android") != -1) {
        return true;
    } else {
        return false;
    }
}
function isIE() {
    if ($.browser.msie) {
        return true;
    } else {
        return false;
    }
}
