/*
 * mv_embed version .3 
 * for details see: http://metavid.ucsc.edu/wiki/index.php/Mv_embed 
 * and or the README
 *
 * All Metavid Wiki code is Released under the GPL2
 * for more info visit http:/metavid.ucsc.edu/code
 * 
 * @url http://metavid.ucsc.edu
 * 
 * portions sampled from the vlc browser interface:
 * http://people.videolan.org/~damienf/plugin-0.8.6.html
 * and whenDOM ready function from: 
 * http://en.design-noir.de/webdev/JS/whenDOMReady
 * 
*/ 

//config values: 
//the location of mv_embed folder (set in the sample page via php look up)
//needs to be set for external embeding to load the cortado applet, 
//and interface images. 
if(!mv_embed_path){
	var mv_embed_path = 'http://localhost/mvWiki/extensions/MetavidWiki/skins/mv_embed/';
}

//set up cross browser event handling (for onDOMready event) 
if (window.addEventListener) { 
	function addEvent (o, type, fn) {
		o.addEventListener (type, fn, false);
	}
	function removeEvent (o, type, fn) {
		o.removeEventListener (type, fn, false);
	}
} else if (window.attachEvent) {
	function addEvent (o, type, fn) {
		if (!o._events) o._events = {};
		var queue = o._events[type];
		if (!queue) {
			o._events[type] = [fn];
			if (!o._events._callback)
				o._events._callback = function (e) { Event._callListeners (e, o) };
			o.attachEvent ('on' + type, o._events._callback);
		} else if (Event._fnIndex (o, type, fn) == -1)
			queue[queue.length] = fn;
		else return;
		Event._mem[Event._mem.length] = [o, type, fn];
	}
	function removeEvent (o, type, fn) {
		var i = Event._fnIndex (o, type, fn);
		if (i < 0) return;
		var queue = o._events[type];
		if (queue.calling) {
			delete queue[i];
			if (queue.removeListeners)
				queue.removeListeners[queue.removeListeners.length] = i;
			else
				queue.removeListeners = [i];
		} else
			if (queue.length == 1)
				Event._detach (o, type);
			else
				queue.splice (i, 1);
	}
	var Event = {
		AT_TARGET : 2,
		BUBBLING_PHASE : 3,
		stopPropagation : function() { this.cancelBubble = true },
		preventDefault : function() { this.returnValue = false },
		_mem : [],
		_callListeners : function (e, o) {
			e.stopPropagation = Event.stopPropagation;
			e.preventDefault = Event.preventDefault;
			e.currentTarget = o;
			e.target = e.srcElement;
			e.eventPhase = e.currentTarget == e.target ? Event.AT_TARGET : Event.BUBBLING_PHASE;
			switch (e.type) {
				case 'mouseover':
					e.relatedTarget = e.fromElement;
					break;
				case 'mouseout':
					e.relatedTarget = e.toElement;
			}
			var queue = o._events[e.type];
			queue.calling = true;
			for (var i=0, l = queue.length; i < l; i++)
				if (queue[i])
					queue[i].call(o,e);
			queue.calling = null;
			if (!queue.removeListeners)
				return;
			if (queue.length == queue.removeListeners.length) {
				Event._detach (o, e.type);
				return;
			}
			queue.removeListeners = queue.removeListeners.sort(function(a,b){return a-b});
			var i = queue.removeListeners.length;
			while (i--)
				queue.splice (queue.removeListeners[i], 1);
			if (queue.length == 0)
				Event._detach (o, e.type);
			else
				queue.removeListeners = null;
		},
		_detach : function (o, type) {
			o.detachEvent ('on' + type, o._events._callback);
			delete o._events[type];
		},
		_fnIndex : function (o, type, fn) {
			var queue = o._events[type];
			if (queue)
				for (var i=0, l = queue.length; i < l; i++)
					if (queue[i] == fn)
						return i;
			return -1;
		},
		_cleanup : function() {
			for (var m, i=0; m = Event._mem[i]; i++)
				if (m[1] != 'unload' || m[2] == Event._cleanup)
					removeEvent (m[0], m[1], m[2]);
		}
	};
	addEvent (window, 'unload', Event._cleanup);
}

//Set Up page reWrite Callback (once the page is done loading)
addLoadEvent(mv_embed);




//init the global client detect type:
var global_embed_type = null 
var oggList = new Array()

/*
* Coverts all occurrences of <video> tag into video object
* (if a native support is not found) 
*/
function mv_embed(){    
	js_log('mv_embed');
    global_embed_type = getEmbedType();  
    js_log('detected: '+ global_embed_type);
    video_elements = document.getElementsByTagName("video")
    if( video_elements.length> 0) {
        for(i = 0; i < video_elements.length; i++) {   
        	js_log('on video ' + i );        
            //grab id:
            vid_id = video_elements[i].getAttribute("id");             	                        	
            if(global_embed_type=='oggplay'){
                //theoretically we should be done.
            }else{                        	
                //swap the video element for our own embed video element                
                if( swapEmbedVideoElement(video_elements[i]) ){
	             	//decrement i cuz we have swaped out the current video element
	                i--;
	            }     
            }                                                          
        }
    }
}

/*
* the base video control JSON object with default attributes
*    for supported attribute details see README
*/
var video_attributes = {
    "id":null,
    "class":null,
    "style":null,
    "name":null,     
    "innerHTML":null,
    "width":"320",
    "height":"240",
    
    "src":null,      
    "autoplay":false,   
    "start":0,
    "end":null,
    "controls":false, 
    
    //custom attributes for mv_embed: 
    "thumbnail":null, 
    "linkback":null, 
    "embed_link":true };

/*
* createEmbedVideoElement 
* takes a video element as input and swaps it out with 
* an embed video interface based on the video_elements attributes
*/
function swapEmbedVideoElement(video_element){
	embed_video = document.createElement('div');

	//create the video interface:
	videoInterface = new embedVideo(video_element);
	
	//inherit the video interface  
	for(method in  videoInterface){
		//js_log('set: ' + method);
		if(method=='style'){
			embed_video.setAttribute('style', videoInterface[method]);
		}else if(method=='class'){
			if(isIE())
				embed_video.setAttribute("className", videoInterface['class']);
			else
				embed_video.setAttribute("class", videoInterface['class']);
		}else{		
			//normal inherit: 
			embed_video[method]=videoInterface[method];
		}
	}
  	//now swap out the video element for the embed_video obj:
    var parent_elm = video_element.parentNode;
    parent_elm.removeChild(video_element);
    
    //append the object into the dom: 
    parent_elm.appendChild(embed_video);  
    
    //now run the getHTML on the new embedVideo Obj:
    embed_video.getHTML(); 
    
    js_log('html set:' + document.getElementById(embed_video.id).innerHTML);
    
    //store a reference to the id 
    //(for single instance plugins that need to keep track of other instances on the page)
    oggList.push(embed_video.id)
    
    js_log('append child: ' + embed_video.id);
 	return true;
}
/* 
*  The video object constructor 
*/
function embedVideo(element){          
    /*
    * set up embedVideo object detect browser plugin support 
    * and inherit appropriate functions 
    */         
    //process video element attributes:
    this.init(element);            
    return this;
}
embedVideo.prototype.init = function(element){      
    //inherit all the default video_attributes 
    for(var attr in video_attributes){       
        if(element.getAttribute(attr)){
            this[attr]=element.getAttribute(attr);
            //js_log('attr:' + attr + ' val: ' + video_attributes[attr] +" "+'elm_val:' + element.getAttribute(attr) + "\n (set by elm)");  
        }else{        
            this[attr]=video_attributes[attr];
            //js_log('attr:' + attr + ' val: ' + video_attributes[attr] +" "+ 'elm_val:' + element.getAttribute(attr) + "\n (set by attr)");  
        }
    }
    //if the thumbnail is null replace with default thumb:
    if(!this['thumbnail']){
	this['thumbnail'] = mv_embed_path + 'images/vid_default_thumb.jpg';
    }	

    //if style is set override width and height
    if(element.style.width)this.width = element.style.width;
    if(element.style.height)this.height = element.style.height;
    //set the plugin id
    this.pid = 'pid_' + this.id;
         
    //grab any innerHTML and set it to missing_plugin_html
    if(element.innerHTML!=''){
        this.user_missing_plugin_html=element.innerHTML;
    } 

    /*
    * override all relevant exported functions with the {embed_type} Object 
    * place the base functions in parent.{function name}
    */
    if(global_embed_type){           
        eval('embedObj = new ' +global_embed_type +'Embed();');
        for(method in embedObj){
            this[method]=embedObj[method];
        }
    }    
}
embedVideo.prototype.getHTML = function (){
    //returns the innerHTML based on auto play option and global_embed_type
    //if auto play==true directly embed the plugin
    if(this.autoplay){ 	   
	this.thumbnail_disp = false;
	this.innerHTML = this.getEmbedHTML();
    }else{
        //if autoplay=false or render out a thumbnail with link to embed html      
       this.thumbnail_disp = true;
       this.innerHTML = this.getThumbnailHTML();
    }
}
embedVideo.prototype.getThumbnailHTML = function (){
    var thumb_html = '';
    var class_atr='';
    var style_atr='';
    //if(this.class)class_atr = ' class="'+this.class+'"';
    //if(this.style)style_atr = ' style="'+this.style+'"';
    //    else style_atr = 'overflow:hidden;height:'+this.height+'px;width:'+this.width+'px;';   

    //put it all in the div container dc_id
    thumb_html+= '<div id="dc_'+this.id+'" style="position:relative;'+
    	' overflow:hidden; top:0px; left:0px; width:'+this.width+'px; height:'+this.height+'px; z-index:0;">'+
        '<img src="' + this.thumbnail + '">';
    
    //put in the center: 
    var play_btn_height = play_btn_width = 109;
    var top = Math.round(this.height/2)- (play_btn_height/2);
    var left = Math.round(this.width/2)- (play_btn_width/2);
    thumb_html+='<div style="position:absolute;top:'+top+'px;left:'+left+'px;z-index:1">'+
			     '<a title="Play Media" href="javascript:document.getElementById(\''+this.id+'\').play();">';	
			     
        //fix for IE<7 and its lack of PNG support:
	thumb_html+=getTransparentPng(new Object ({id:'play_'+this.id, width:play_btn_width, height:play_btn_height, border:"0", 
					src:mv_embed_path + 'images/mv_embed_play.png' }));
	/*if( isIE() ){
		thumb_html+='<span id="play_'+this.id+'" style="display:inline-block;cursor:hand;width:109px;height:109px;' +
    		'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader' +
    		'(src=\''+ mv_embed_path + 'images/mv_embed_play.png\', sizingMethod=\'scale\');"</span>';			
	}else{
              thumb_html+='<img id="play_'+this.id+'" width="109" height="109" border="0" src="'+
	       mv_embed_path + 'images/mv_embed_play.png">';
	}*/					
	thumb_html+='</a></div>';

    //add in embed link (if requested) 
    if(this.embed_link){	
	thumb_html+='<div style="position:absolute;bottom:0px;right:0px;z-index:1">'+
	     '<a title="Embed Code" href="javascript:document.getElementById(\''+this.id+'\').hideShowEmbedCode();">';

	thumb_html+=getTransparentPng(new Object ({id:'play_'+this.id, width:"27", height:"27", border:"0", 
					src:mv_embed_path + 'images/vid_embed_sm.png' }));
	thumb_html+='</a></div>';

	var embed_code_html = '&lt;script type=&quot;text/javascript&quot; src=&quot;'+mv_embed_path+'mv_embed.js&quot;&gt;&lt;/script>' + '&lt;video id=&quot;'+this.id+'&quot; src=&quot;'+this.src+'&quot; thumbnail=&quot;'+mv_embed_path + this.thumbnail+'&quot;/&gt;';

	//add the hidden embed code:
	thumb_html+='<div id="embed_code_'+this.id+'" style="border:solid;border-color:black;overflow:hidden;display:none;position:absolute;bottom:2px;right:30px;width:250px;z-index:1">'+
		'<input onClick="this.select();" type="text" size="40" length="1024" value="'+embed_code_html+'">'
		 '</div>';

    }    

    thumb_html+='</div>';

    return thumb_html;
}
//display the code to remotely embed this video:
//if scriptaculus is available animate its appearance. 
embedVideo.prototype.hideShowEmbedCode = function(){
	js_log('hideShowEmbedCode');
	if(typeof Scriptaculous=='undefined'){
		//flip display: 
		js_log('looking for: ' + document.getElementById('embed_code_'+this.id).style.display);
		if(document.getElementById('embed_code_'+this.id).style.display=='none'){
			document.getElementById('embed_code_'+this.id).style.display='block';
		}else{
			document.getElementById('embed_code_'+this.id).style.display='none';
		}
	}else{
		Effect.toggle('embed_code_'+this.id, 'appear');
		/*$('embed_code_'+this.id).toggle(400);
		if($('embed_code_'+this.id)){
		Effect.Appear('embed_code_'+this.id);*/
	}
}


/* returns html for a transparent png (for ie<7)*/
function getTransparentPng(image){
	if( isIE() ){
		return '<span id="'+image.id+'" style="display:inline-block;cursor:hand;width:'+image.width+'px;height:'+image.height+'px;' +
    		'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader' +
    		'(src=\''+image.src+'\', sizingMethod=\'scale\');"</span>';	
	}else{
		return '<img id="'+image['id']+'" width="'+image.width+'" height="'+image.height+'" border="0" src="'+
		image.src + '">';
	}
}

/*
*  base embed controls 
*	the play button calls 
*/
embedVideo.prototype.play = function(){
	//check if thumbnail is being displayed and embed html
	if(this.thumbnail_disp){
		js_log('rewrite embed');
		this.innerHTML = this.getEmbedHTML();
		this.thumbnail_disp=false;
	}else{
		//(when overwritten we put the javascript play call here:
	}
}
/*
 * base embed pause
 * 	there is no general way to pause the video 
 *  must be overwritten by embed object to support this functionality. 
 */
embedVideo.prototype.pause = function(){
	return null
}

/*
 * base embed stop (should be overwritten by the plugin) 
 */
embedVideo.prototype.stop = function(){
	//check if thumbnail is being displayed in which case do nothing
	if(this.thumbnail_disp){
		//already in stooped state
		//js_log('already in stopped state');
	}else{
		//rewrite the html to thumbnail disp 
		this.innerHTML = this.getThumbnailHTML();
		this.thumbnail_disp=true;
	}
}
/* the basic controls interface */
embedVideo.prototype.basic_controls = function(){
	return '<a title="play" href="javascript:document.getElementById(\''+this.id+'\').play();">'+
'	<img border="0" style="float:left"  src="'+mv_embed_path+'images/vid_play_sm.png" width="27" height="27" />'+
'</a>'+
'<a title="pause" href="javascript:document.getElementById(\''+this.id+'\').pause();">'+
'	<img border="0" style="float:left"  src="'+mv_embed_path+'images/vid_pause_sm.png" width="27" height="27" />'+
'</a> '+
'<a title="stop" href="javascript:document.getElementById(\''+this.id+'\').stop();">'+
'	<img border="0" style="float:left"  src="'+mv_embed_path+'images/vid_stop_sm.png" width="27" height="27" />'+
'</a>';
}
/*
*
* EMBED OBJECTS:
*
* all the embed objects that implement plugin specific code:
* (inheritance its all very hackish in JS)
*/
function javaEmbed(){
    //load cortado in an iframe (to better handle cross site java permission issues)
    this.getEmbedHTML = function (){       
       	iframe_src = mv_embed_path + 'cortado_iframe.php';
       	iframe_src+= "?media_url=" + this.src + '&id=' + this.pid;
	iframe_src+= "&width=" + this.width + "&height=" + this.height;
	iframe_src+= "&duration=" + this.duration;	
	return '<iframe width="'+this.width+'" height="'+this.height+'" '+
                   'frameborder=0  scrolling=no marginwidth=0 marginheight=0 ' +
                   'src = "'+ iframe_src + '"/>';
    }
    this.play = function(){
   		//check if thumbnail is being displayed and embed html
		if(this.thumbnail_disp){
		    //only one instance of cortado per page (stop others)
			for(var i in oggList){
				id = oggList[i];
				if(id!=this.id){
					if(typeof id=='string' ){						
						document.getElementById(id).stop();
					}
				}
			}    	    
			//now update inner html 
			this.innerHTML = this.getEmbedHTML();
			this.thumbnail_disp=false;
		}else{
			//cortado is already playing 
		}
    }
}

/*
* vlc embed based on: http://people.videolan.org/~damienf/plugin-0.8.6.html
*/

function vlcEmbed(){ 
	//init vars: 
	this.monitorTimerId = 0;
	this.prevState = 0;		
    this.getEmbedHTML = function(){   
	//setup the interface controls if requested		
	if(this.controls){
		/*for the vlc playhead we need scriptaculus/prototype
		 only the slider uses scriptaculous/prototype code so 
		as long as you don't set controls to "true" the extra files won't load. */			
		//try and get the interface 
		if( this.get_interface_lib() ){
			js_log('interface loaded');
			
			controls_html = '<div id="track_'+this.id+'" class="mv_track">'+
				'<div id="playhead_'+this.id+'" class="mv_playhead"></div>'+
			'</div>';
			
			//controls_html = '<div id="track_'+this.id+'"></div>';
			controls_html += this.basic_controls() + this.extended_vlc_controls();		
		}else{
			//if not present, it's loading
			return 'loading interface <blink>...</blink>';
		}
		
	}else{	    	        	
		controls_html ='';
	}
	//give VLC 150ms to initialize before we start playback 
	//@@todo should be able to do this as an event
	setTimeout('document.getElementById(\''+this.id+'\').postEmbedJS()', 150);
        return '<object classid="clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921" '+
		'codebase="http://downloads.videolan.org/pub/videolan/vlc/latest/win32/axvlc.cab#Version=0,8,6,0" '+
		'id="'+this.pid+'" events="True" height="'+this.height+'" width="'+this.width+'">'+
            '<param name="MRL" value="">'+
            '<param name="ShowDisplay" value="True">'+
            '<param name="AutoLoop" value="False">'+
            '<param name="AutoPlay" value="False">'+
            '<param name="Volume" value="50">'+
            '<param name="StartTime" value="0">'+
            '<embed pluginspage="http://www.videolan.org" type="application/x-vlc-plugin" '+
            'progid="VideoLAN.VLCPlugin.2" name="'+this.pid+'" height="'+this.height+'" width="'+this.width+'">'+
        '</object>' + controls_html;
    }
    //loads in the css and js for the interface
    this.get_interface_lib = function(doLoad){				
		var doLoad = (doLoad==null)? true:doLoad;
		//js_log('get interface:' + doLoad);
		var loading_interface =false;

		//scriptaculous version: 
		if(typeof Prototype=='undefined'){
			if(doLoad) loadExternalJs(mv_embed_path + 'scriptaculous/lib/prototype.js');
			//js_log('Prototype und');
			loading_interface = true;
		}
		if(typeof Scriptaculous=='undefined'){
			if(doLoad) loadExternalJs(mv_embed_path + 'scriptaculous/src/scriptaculous.js');
			//js_log('Scriptaculousmv_track und');
			loading_interface=true;
		}
				
		//grab the css file: 
		if(!styleSheetPresent(mv_embed_path+'mv_embed.css')){	
			if(doLoad) loadExternalCss(mv_embed_path+'mv_embed.css');
			js_log('css und');
			loading_interface=true;
		}

		if(loading_interface){
			//call get_interface_lib (without requests) until interface is done loading: 
			setTimeout('document.getElementById(\''+this.id+'\').get_interface_lib(false)', 50);
			//if loading interface is not yet available 
			return false;			
		}else{
			//js_log('loading_interface = false');
			//if it was a load request and it was already loaded return true
			if(doLoad){
				return true;
			}else{
				//non loading request means time has passed so we need to update the innerHTML
				this.innerHTML = this.getEmbedHTML();
			}
		}
    }
    /*
    * some java script to start vlc playback after the embed:
    */
    this.userSlide=false;
    this.postEmbedJS = function(){
        //load a pointer to the vlc into the object (this.vlc)
    	this.getVLC();
    	//manipulate the dom object to make sure vlc has the correct size: 
    	this.vlc.style.width=this.width;
    	this.vlc.style.height=this.height;       
    	this.vlc.playlist.items.clear();
    	js_log('play:' + this.src);   
    	var itemId = this.vlc.playlist.add(this.src);
    	if( itemId != -1 ){
    		//play
    		this.vlc.playlist.playItem(itemId);
    	}else{
    		js_log("error:cannot play at the moment !");
    	}
    	//if controls enabled start up javascript interface and monitor:
		if(this.controls){
				//get a pointer to this id (as this in onSlide context is not "this") 
		    	var parent_id = this.id;		    
		    	js_log('parent id: '+ parent_id + ' id: ' + this.id);
				//activate the slider: scriptaculus based)
				this.slider = new Control.Slider('playhead_'+this.id, 'track_'+this.id,{
					sliderValue:0,
					onSlide:function(v){
						thisVid = document.getElementById(parent_id);
						if(! thisVid.userSlide){
							//user slide clip:
							thisVid.userSlide=true;
							js_log('user slide: ' + thisVid.userSlide);
						}										
					},
					onChange:function(v){ 
						thisVid = document.getElementById(parent_id);
						if(thisVid.userSlide==true){						
							//seek to a given position:
							js_log('this.userSlide seek to: ' + v);	
							thisVid.doSeek(v);	
							thisVid.userSlide=false;
						}
					}
				});
		  
			//start doing status updates every 1/10th of a second
		    setTimeout('document.getElementById(\''+this.id+'\').monitor()',500);		    		
		}
    }   
	this.doSeek = function(value){
		//if( ! this.inputTrackerIgnoreChange ){
			if( (this.vlc.input.state == 3) && (this.vlc.input.position != value) )
	        {
        	    this.vlc.input.position = value;
            	document.getElementById("info_" + this.id ).innerHTML = 'seeking'
	        }				
		//}
	}

    /* 
    * updates the status time
    */
    this.monitor = function(){
		//js_log( 'state:' + this.vlc.input.state);
		//js_log('time: ' + this.vlc.input.time);
		if( this.vlc.log.messages.count > 0 ){
        	// there is one or more messages in the log
        	var iter = this.vlc.log.messages.iterator();
        	while( iter.hasNext ){
 	           var msg = iter.next();
        	   var msgtype = msg.type.toString();
	           if( (msg.severity == 1) && (msgtype == "input") )
        	   {
                	js_log( msg.message );
            	}
        	}
	        // clear the log once finished to avoid clogging
        	this.vlc.log.messages.clear();
    	}
    	var newState = this.vlc.input.state;
    	if( this.prevState != newState ){
       		if( newState == 0 )
	        {
        	    // current media has stopped 
	            this.onStop();
        	}
	        else if( newState == 1 )
        	{
	            // current media is opening/connecting
        	    this.onOpen();
	        }
	        else if( newState == 2 )
        	{
	            // current media is buffering data
        	    this.onBuffer();
	        }
	        else if( newState == 3 )
        	{
	           // current media is now playing
        	   this.onPlay();
	        }
       		else if( this.vlc.input.state == 4 )
	        {
        	    // current media is now paused
	            this.onPause();
        	}
        	this.prevState = newState;
	    }
	    else if( newState == 3 ){
	        // current media is playing
	        this.onPlaying();
	    }
	    if( ! this.monitorTimerId ){
	        this.monitorTimerId = setInterval('document.getElementById(\''+this.id+'\').monitor()', 250);
	    }
    }

/* events */

    this.onOpen = function(){
    	document.getElementById("info_"+this.id).innerHTML = "Opening...";
		//document.getElementById("PlayOrPause").disabled = true;
    	//document.getElementById("Stop").disabled = false;
    };
    this.onBuffer = function(){
    	document.getElementById("info_"+this.id).innerHTML = "Buffering...";
    	//document.getElementById("PlayOrPause").disabled = true;
    	//document.getElementById("Stop").disabled = false;
    };

    this.onPlay = function(){
    	//document.getElementById("PlayOrPause").value = "Pause";
		//document.getElementById("PlayOrPause").disabled = false;
		//document.getElementById("Stop").disabled = false;
		this.onPlaying();
    };
   
    this.liveFeedRoll = 0;
    this.onPlaying = function(){
        var info = document.getElementById("info_"+this.id);
        var mediaLen = this.vlc.input.length;
        if( mediaLen > 0 )
        {
          // seekable media
           //as long as the user is not interacting with the playhead update:
           if(! this.userSlide){
	            //js_log('user slide is false' + this.userSlide + '(update)');
	            this.slider.setValue(this.vlc.input.position);
	            info.innerHTML = this.getTimeInfo();
           }else{
           		//update info to seek to: 
	           info.innerHTML = 'seek to: '	+ seconds2ntp(Math.round( (this.slider.value*mediaLen)/1000) );
           }
        }else{
        	//@@todo hide playhead remove the slider (its a live stream)     
            info.innerHTML = 'live';
        }
    }
   this.onPause = function()
   {
   	//document.getElementById("PlayOrPause").value = " Play ";
   };
   this.onStop = function(){	
	    // disable logging
	    this.vlc.log.verbosity = -1;
	    //document.getElementById("Stop").disabled = true;
		if(this.controls){
		    this.slider.setValue(0);
		    document.getElementById("info_"+this.id).innerHTML = "-:--:--/-:--:--";
		}		
	    //document.getElementById("PlayOrPause").value = " Play ";
	    //document.getElementById("PlayOrPause").disabled = false;
    };
	

   /* js hooks/controls */
    this.play = function(){
		if(this.thumbnail_disp){	
			this.thumbnail_disp=false;
			this.innerHTML = this.getEmbedHTML();
		}else{		
			// clear the message log and enable error logging
	        this.vlc.log.verbosity = 1;
    	    this.vlc.log.messages.clear();
			this.vlc.playlist.play();
			this.monitor();
		}
    }
    this.stop = function(){
    	this.vlc.playlist.stop();
    	if( this.monitorTimerId != 0 )
	    {
	        clearInterval(this.monitorTimerId);
	        this.monitorTimerId = 0;
	    }
	    this.onStop();
    }
    this.pause = function(){
		this.vlc.playlist.togglePause();
    }
    this.fullscreen = function(){
		this.vlc.video.toggleFullscreen();
    }
    this.currentTime = function(seek_val){
	//if we did not get a seek value then return the current timestamp: 
	if(!seek_val){
		return this.vlc.input.time;
	}
    }

    // get the embed vlc object 
    this.getVLC = function getVLC(){
   		if (window.document[this.pid]){
        	this.vlc = window.document[this.pid];
		}
		if (navigator.appName.indexOf("Microsoft Internet")==-1){
            if (document.embeds && document.embeds[this.pid])
            	this.vlc =  document.embeds[this.pid]; 
		}else{
        	this.vlc = document.getElementById(this.pid );
		}
    }
    /*
     * returns current time /
     */
    this.getTimeInfo = function(){
		return  seconds2ntp(Math.round(this.vlc.input.time / 1000) )+ 
            	"/" + seconds2ntp(Math.round(this.vlc.input.length / 1000) );
    }
    this.extended_vlc_controls = function(){ 
		return '<a title="fullscreen" href="javascript:document.getElementById(\''+this.id+'\').fullscreen();">'+
	'	<img border="0" style="float:left" src="'+mv_embed_path+'images/vid_full_screen_sm.png" width="27" height="27" />'+
	'</a>'+
	'<span id="info_'+this.id+'" class="mv_status" style="float:left">--</span>';
    }
}



function genericEmbed(){
    this.getEmbedHTML = function(){
        return '<object type="application/ogg" '+
        'width="'+this.width+'" height="'+this.height+'" ' +
        'data="' + this.src + '"></object>';
    }
}
/*
* set the missing plugin html (check for user included code)
*/ 
embedVideo.getPluginMissingHTML=function(){		
    if(this.user_missing_plugin_html){
        return this.user_missing_plugin_html;
    }else{
	  return '<div style="margin:6px"><p>The '+
		' <a href="http://www.videolan.org/doc/play-howto/en/ch04.html#id293992">vlc mozilla plugin</a> or '+
		' <a href="http://java.com/en/download/index.jsp">java plug-in</a> is required to play this clip '+
		' <br>for more info <i>see metavid <a href="http://metavid.ucsc.edu/wiki/index.php/MetavidFAQ#How_can_I_play_back_Metavid_video">playback help</a></i>'+
		'<p><b>alternatively</b> you can <a href="'+this.src +'">'+
		'download this clip</a> to be viewed outside the web browser with video application such as '+
			'<a href="http://www.videolan.org/vlc/">VLC</a>'+
		'</div>';
	}
}


/*
* Returns embed type:
    oggplay: oggplay/native video plugin support
    vlc:    vlc browser plugin detected
    generic: mime type application/ogg found (generic via xine, totem or some other plugin)
    java:   java detected
    null:   no playback support system found
*/
function getEmbedType(){
    var oggPlugin=false;
    var vlcPlugin=false;
    var javaPlugin=false;
    
    //check for native/oggplay support:
    if(document.getElementsByTagName("video").length > 0) {
      var myvideo = document.getElementsByTagName("video")[0];      
      if(myvideo.play) {
        return 'oggplay';
      }
    }

    //check if we can do a direct lookup via navigator plugins:
    if(navigator.mimeTypes && navigator.mimeTypes.length > 0) {               
       for (var i = 0; i < navigator.mimeTypes.length; i++) {
            if(navigator.mimeTypes[i].type.indexOf("application/ogg") > -1) {
                oggPlugin = true;
            }
            if(navigator.mimeTypes[i].type.indexOf("application/x-vlc-plugin") > -1) {
                vlcPlugin = true;
            }	
            if(navigator.mimeTypes[i].type.indexOf("application/x-java-applet") > -1) {
               javaPlugin = true;
            }
        }
        //preference order: necessary as vlc plugin will show up as both generic and its x-name-plugin
        //(because we have no js hooks for generic we prefer java over the generic plugins such as mplayer
        // and Totem...we should add in support for others over time)
        if(vlcPlugin)return 'vlc';     
        if(javaPlugin)return 'java';
        if(oggPlugin)return 'generic';
    }
    //if IE check for vlc ActiveX object: 
    if(isIE()){
		var p;
		try {
			p = new ActiveXObject('VideoLAN.VLCPlugin.2');
		}
		catch (e) {
			//alert('vlc not found');
		}
		if (p){
			return 'vlc';
		}	
	}	
    //general way to check for java in IE and others: 
    if(navigator.javaEnabled() == 1){
		return 'java';	
	}
	//exhausted all detection return null 
	return null;
}

/*
IE specific functions:  
*/
//check if we are an IE browser
function isIE(){
    return navigator.appName.indexOf("Microsoft") != -1;
    //return !(navigator.plugins && navigator.plugins.length);
}

/*
* utility functions: 
*/
function seconds2ntp(sec){
	hours = Math.floor(sec/ 3600);
	minutes = Math.floor((sec/60) % 60);
	seconds = sec % 60;
	if ( hours < 10 ) hours = "0" + hours;
	if ( minutes < 10 ) minutes = "0" + minutes;
	if ( seconds < 10 ) seconds = "0" + seconds;
	return hours+":"+minutes+":"+seconds;
}

//addLoadEvent for adding functions to be run when the page DOM is done loading
function addLoadEvent(func) {
	//check if the mediaWiki addOnloadHook is present else do our own: 
	if(window.addOnloadHook){
		addOnloadHook(func);			
	}else{
	    //add it in ourselves	
	    whenDOMReady(func);
	    /*var oldonload = window.onload;
	    if (typeof window.onload != 'function') {
	        window.onloadonload = func;
	    } else {
	        window.onload = function() {
	            if (oldonload) {
	                oldonload();
	            }
	            func();
	        }
	    }*/
	}
}

/*add event & when dom ready script 
from: design-noir.de (GPL 2)
http://en.design-noir.de/webdev/JS/whenDOMReady
*/
function whenDOMReady(fn) {
	var f = arguments.callee;
	if ("listeners" in f) {
		if (f.listeners)
			f.listeners.push(fn);
		else
			fn();
		return;
	}
	f.listeners = [fn];
	var callback = function() {
		/*@if (@_win32) f.script.onreadystatechange = null; @end @*/
		removeEvent(window, "load", callback);
		if (document.removeEventListener)
			document.removeEventListener("DOMContentLoaded", callback, false);
		while (f.listeners.length)
			f.listeners.shift()();
		f.listeners = null;
	};
	if (document.addEventListener)
		document.addEventListener("DOMContentLoaded", callback, false);
	/*@if (@_win32) else {
		document.write("<script id=__ie_scriptdummy defer src=javascript:void(0)><\/script>");
		f.script = document.getElementById("__ie_scriptdummy");
		f.script.onreadystatechange = function() {
			if (this.readyState == "complete")
				callback();
		};
	} @end @*/
	addEvent(window, "load", callback);
}


function loadExternalJs(url){
   js_log('load js: ' + url);
   var e = document.createElement("script");
   e.src = url;
   e.type="text/javascript";
   document.getElementsByTagName("head")[0].appendChild(e);  
}

function styleSheetPresent(url){
    style_elements = document.getElementsByTagName('link');  
    if( style_elements.length > 0) {
        for(i = 0; i < style_elements.length; i++) {   
		if(style_elements[i].href==url)
			return true;
	}
    }
    return false;
}
function loadExternalCss(url){
   //js_log('load css: ' + url);
   var e = document.createElement("link");
   e.href = url;
   e.type = "text/css";
   e.rel = 'stylesheet';
   document.getElementsByTagName("head")[0].appendChild(e);
}

/*
* Debug functions (can be removed once stable)
*/
function js_log(string){
   if( window.console ){
        console.log(string); 
   }else{
   	 //disable alerts
     //   alert(string);          
   }
}
function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects
	 for(var item in arr) {
	  var value = arr[item];
	 
	  if(typeof(value) == 'object') { //If it is an array,
	   dumped_text += level_padding + "'" + item + "' ...\n";
	   dumped_text += dump(value,level+1);
	  } else {
	   dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
	  }
	 }
	} else { //Stings/Chars/Numbers etc.
	 dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
} 

