// Bone simple and frankly somewhat nasty hackaround
// for the current chaos surrounding the HTML5 video
// element (AND an attempt to provide a standard,
// lightweight reusable player)
//
// Based on http://pipwerks.com/2010/03/19/html5-video-minus-ogg/
//
// Requires Prototype and swfobject


// params - {
//      // REQUIRED
//      flv: URL of flv video,
//      mp4: URL of mp4 video,
//      width: width of video in px,
//      height: height of video in px
//
//      // OPTIONAL
//      oncomplete: a JS function to be called, with NO args, on video complete
//          (will also accept the string name of a global js function. But don't be that guy.)
// }


var _gaq = _gaq || [];

VideoManager = function(params) {


    var tracking_id = params.flv || params.mp4;

    // all of this nasty by-name stuff is an outgrowth of our
    // bone-simple flash integration.
    var complete_handler_name = '_video_complete_';
    while(window[complete_handler_name]) {
        var digit = Math.floor(Math.random() * 10);
        complete_handler_name += ('' + digit);
    }

    window[complete_handler_name] = function() {
        _gaq.push(['_trackEvent', 'Videos', 'Video Completed', tracking_id ]);

        if("function" == typeof params['oncomplete']) {
            params['oncomplete']();
        }
        else if("undefined" != typeof params['oncomplete']) {
            // LEGACY. DON'T DO THIS.
            window[ params['oncomplete'] ]();
        }
    };

    // old id -> { new_id: new id, old_content: old content }
    var replaced = {};

    var embed_flv = function(id_to_replace, new_id) {
        // TODO these need to be configurable defaults with a params {} arg.

        var swfVersionStr = "10.0.0";
        var expressInstall = "/media/swf/expressInstall.swf";

        // TODO the paths to these assets need to be generalized.
        var flvPlayer = "/media/video/platform/player/FLV_JS_player.swf";
        var skin = "/media/video/platform/player/assets/SkinOverAllNoFullNoCaption.swf"; 
        var element_id = "Video_Player_id";
        var flashvars = {
            vidsrc : params.flv,
            skin : skin,
            autoplay : 'true'
        };

        flashvars.oncomplete = complete_handler_name;

        var objectparameters = {};
        objectparameters.quality = "high";
        objectparameters.bgcolor = "#ffffff";
        objectparameters.allowscriptaccess = "sameDomain";
        objectparameters.allowfullscreen = "true";        

        var attributes = {};
        attributes.id = new_id;
        attributes.name = "FLV_JS_player";
        attributes.align = "middle";

        swfobject.embedSWF(
            flvPlayer, id_to_replace, params.width, params.height,
            swfVersionStr, expressInstall,
            flashvars, objectparameters, attributes
        );        
    };

    var embed_video = function(id_to_replace, new_id) {
        var videotag = '' +
            '<video id="' + new_id + '" width="' + params.width + '" height="'+ params.height + '" controls autobuffer="autobuffer" >' +
            '<source src="' + params.mp4 + '"  type="video/mp4" >' +
            '</video>';

        Element.replace(id_to_replace, videotag);
        Event.observe(new_id, 'ended', window[ complete_handler_name ]);

        $(new_id).play();
    };
    
    var no_flash_installed = function(id_to_replace, new_id) {
	var htmltag = ''+
	    '<div id="'+new_id+'">'+
	    '<a href="http://www.adobe.com/go/getflashplayer">'+
	    '<img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a>'+
	    '</div>';
	Element.replace(id_to_replace, htmltag);
	Event.observe(new_id, 'ended', window[ complete_handler_name ]);
    }

    // Returns a function that, when called, creates a new element containing the right
    // kind of video and uses it to replace the element identified by id_to_replace
    //
    var show_player = function (id_to_replace, new_id) {

        var detect = document.createElement('video') || false;

        var use_html5 = false;
        var use_flash = false;
        
        if(detect && typeof detect.canPlayType !== "undefined") {
            if(detect.canPlayType("video/mp4") === "maybe" || detect.canPlayType("video/mp4") === "probably") {
                use_html5 = true;  
            }
            
        } 
        if (!use_html5) { 
    	    var getVer = swfobject.getFlashPlayerVersion();
    	    if (getVer.major != "0") {
    		use_flash = true; 
    	    }
        }

        if(use_html5) {
            embed_video(id_to_replace, new_id);
            _gaq.push(['_trackEvent', 'Videos', 'Video Opened (as HTML5)', tracking_id ]);

        }
        else if (use_flash) { 
            embed_flv(id_to_replace, new_id);
            _gaq.push(['_trackEvent', 'Videos', 'Video Opened (as FLV)', tracking_id ]);
        }
        else{
    	    no_flash_installed(id_to_replace, new_id);    	
        }
    };

    return {
        insertVideo : function(replace_id) {

            var new_id = replace_id + "_video";
            while($(new_id)) {
                new_id = new_id + "_video";
            }

            replaced[replace_id] = {
                old_content: $(replace_id).cloneNode(true),
                new_id: new_id
            }

            show_player(replace_id, new_id);

            return new_id;
        },

        uninsertVideo : function(restore_id) {
            var replaced_stuff = replaced[restore_id];
            Element.replace(replaced_stuff.new_id,
                            replaced_stuff.old_content);

            delete replaced[restore_id];

            _gaq.push(['_trackEvent', 'Videos', 'Video Hidden', tracking_id ]);
        },

        isInserted : function(replaced_id) {
            return ("undefined" != typeof replaced[replaced_id]);
        }

        
    };
}

