/*
    Simple proof of concept example that shows how one could impliment
    the HTML 5 video spec using JavaScript and Flash.
    
    Mike Chambers
    http://www.mikechambers.com
    
    Uses SWFObject
    http://code.google.com/p/swfobject/
*/

//create a simple name space
var mesh;
if(!mesh)
{
    mesh = {};
}

mesh.HTML5Player = function()
{
}

/*
    Method that uses SWFObject API to load and display a Flash based video
    player based on the attributes specified in the video element.
*/
mesh.HTML5Player.prototype.writePlayer = function(element, ob)
{
	if (swfobject.hasFlashPlayerVersion("9.0.115"))
	{
		var fn = function()
		{
			var att = { data:"/player.swf", 
						width:ob.width, 
						height:ob.height,
						allowFullScreen:true };

			var par = { flashvars:"videoURL=" + escape(ob.src) +
			 			"&autoplay=" + ob.autoplay + 
			 			"&controls=" + ob.controls +
						"&poster=" + ob.poster +
						"&playcount=" + ob.playcount
					};
			
			var e_id = element.id;
			
			//check to see if the element has an ID
			if(e_id == "")
			{
			    //if not, generate an id for it
			    e_id = new Date().getTime();
			    element.id = e_id;
			    
			    //todo: look into modifying swfobject to take an element
			    //and not an id
			}

			var myObject = swfobject.createSWF(att, par, e_id);
		};
		swfobject.addDomLoadEvent(fn);
		fn()
	}
}	


/*
    Utility method that grabs the value of an attribute.
    
    If the attribute doesnt exists, it returns an empty string
*/
mesh.HTML5Player.prototype.getAttributeValue = function(node)
{
	if(node == null)
	{
		return ""
	}
	else
	{  
        return node.value;
	}
}

/*
    Parses the DOM for video elements and creates a Flash based player in
    their place.
*/
mesh.HTML5Player.prototype.parse = function()
{
    //grab all of the video elements
	var ve = document.getElementsByTagName("video");
	
	var len = ve.length;

	//loop through them and parse the attributes
	for(var i = len; i > 0; i--)
	{
		var vo = {};
		v = ve[i - 1];

		var atts = v.attributes;
		
		vo.controls = (atts["controls"])?true:false;
		vo.src = this.getAttributeValue(atts["src"])
		vo.poster = this.getAttributeValue(atts["poster"]);
		vo.height = this.getAttributeValue(atts["height"]);
		vo.width = this.getAttributeValue(atts["width"]);
		vo.poster = this.getAttributeValue(atts["poster"]);
		vo.playcount = this.getAttributeValue(atts["playcount"]);
		vo.autoplay = (this.getAttributeValue(atts["autoplay"]) == "true")?true:false;
                vo.className = 'video';
		
		//create a player for each element
		this.writePlayer(v, vo)
	}
}

//onload function
var init = function()
{
	var p = new mesh.HTML5Player();
	p.parse();
};

swfobject.addDomLoadEvent(init)
