/* ----------------------------------------------------------------
   ----------------------------------------------------------------
   ----------------------------------------------------------------
   
	LDTPlayer is created by http://www.iri.centrepompidou.fr
	2010-06-14 - version 0.07
	
	init By Samuel Huron < samuel.huron (at) cybunk (dot) com >
	
	
   ----------------------------------------------------------------
*/




/* ----------------------------------------------------------------
   ----------------------------------------------------------------
 INTERFACE : SLIDER ( CONTROL BAR ) | BUTTON ()   */


	function createInterface (width,height,duration){
		$jIRI(function() {
		
			$jIRI("#Annotations").width(width-(78*2));
			$jIRI("#ShowAnnotation").width(width-10);
			$jIRI("#controlerLdt").width(width);
			$jIRI("#Ldtplayer1").attr("z-index","100");
			
			 $jIRI("#ShowAnnotation").click(function () { 
				 $jIRI(this).slideUp(); 
			});

			var LdtpPlayerY = $jIRI("#ldtPlaceHolder").attr("top");
			var LdtpPlayerX = $jIRI("#ldtPlaceHolder").attr("left");
			
			//alert(LdtpPlayerY+" | "+LdtpPlayerX);
			//$jIRI("#ShowAnnotation").attr("position","absolute");
			/*$jIRI("#ShowAnnotation").attr("top",0);
			$jIRI("#ShowAnnotation").attr("left",0);*/
			
			//$jIRI("#slider-range-min").roll
			$jIRI("#slider-range-min").slider({ //range: "min",
				value: 0,
				min: 1,
				max: duration/1000,//1:54:52.66 = 3600+3240+
				step: 0.1,
				slide: function(event, ui) {
					
					//$jIRI("#amount").val(ui.value+" s");
					player.sendEvent('SEEK', ui.value)
					//player.sendEvent('PAUSE')
				}
			});
			$jIRI("#amount").val($jIRI("#slider-range-min").slider("value")+" s");
			
			$jIRI(".ldtControl1 button:first").button({
				icons: {
					primary: 'ui-icon-play'
				},
				text: false
			}).next().button({
				icons: {
					primary: 'ui-icon-seek-next'
				},
				 text: false
			});
			
			$jIRI(".ldtControl2 button:first").button({
				icons: {
					primary: 'ui-icon-newwin'//,
					//secondary: 'ui-icon-volume-off'
				},
				text: false
			}).next().button({
				icons: {
					primary: 'ui-icon-volume-on'
				},
				 text: false
			});
		
		});	
	}

/* ----------------------------------------------------------------
   ----------------------------------------------------------------
 CREER JW PLAYER  creation + listener */


	var currentPosition = 0; 
	var currentVolume   = 50; 
	var player 			= null;
	
	function playerReady(thePlayer) {
		//alert("ready");
		player = window.document[thePlayer.id];
		addListeners();	
	}

	function addListeners() {
		if (player) { 
			player.addModelListener("TIME", "positionListener");
			player.addControllerListener("VOLUME", "volumeListener");
			player.addPlayPauseListener("PLAY", "state");
		} else {
			setTimeout("addListeners()",100);
		}

		// et changer les boutons
	}
	
	//function 

	function addPlayPauseListener(obj) { 
		if(obj){
			$jIRI(".control1 button:first").button({
				icons: {
					primary: 'ui-icon-pause'
				},
				text: false
			});
		}else{
			$jIRI(".control1 button:first").button({
				icons: {
					primary: 'ui-icon-play'
				},
				text: false
			});
		}
	}
	
	function positionListener(obj) { 
		currentPosition = obj.position; 
		var tmp = document.getElementById("posit");
		if (tmp) { tmp.innerHTML = "position: " + currentPosition; }
		$jIRI("#slider-range-min").slider("value", obj.position);
		$jIRI("#amount").val(obj.position+" s");
		// afficher annotation 
		
		MyLdt.checkTime(currentPosition);
	}

	function volumeListener(obj) { 
		currentVolume = obj.percentage; 
		var tmp = document.getElementById("vol");
		if (tmp) { tmp.innerHTML = "volume: " + currentVolume; }
	}

	function createPlayer(width,height,url,duration,streamerPath,MySwfPath) {
	
		myUrlFragment = url.split(streamerPath);
		file = myUrlFragment[1];
		//alert(url+" = "+streamerPath+" + "+file);
		streamer = streamerPath;
		//alert(" StreamerPath : "+streamer+" - "+file);
		//alert(" SwfPath : "+MySwfPath);
		
		var flashvars = {
			streamer:streamer,
			file:file, 
			//live:"true",
			autostart:"true",
			controlbar:"none"
		}

		var params = {
			allowfullscreen:"true", 
			allowscriptaccess:"always",
			wmode:"transparent"
		}

		var attributes = {
			id:"Ldtplayer1",  
			name:"Ldtplayer1"
		}

		swfobject.embedSWF(MySwfPath, "ldtPlaceHolder", width, height, "9.0.115", false, flashvars, params, attributes);
	}
	





/* ----------------------------------------------------------------
   ----------------------------------------------------------------

LOAD JSON AND PARSE IT
*/
	

	var MyLdt;
	var Durration;
	var playerLdtWidth;
	var playerLdtHeight;
	
	function loadJson (width,height,urlJson,MySwfPath){
		
		playerLdtWidth=width;
		playerLdtHeight=height;
		
		$jIRI.ajax({
					  dataType: 'jsonp',
					  url:urlJson,//+"?callback=callbackLdts",
					  //jsonpCallback:callbackLdts,
					  success: function(json){
						
						//eval(json);
						//alert("callback LDTS");
						/* START PARSING ----------------------- */
						/* metas , medias , annotation-types , annotations , lists , tags , views */
						/* # fonction avec 1 seul  media et 1 seul annotation type  code a cleaner */
						/* # créer le player 				   */
						//$jIRI.each(json.medias, function(i,item) {
						//});
						$jIRI("<div></div>").appendTo("#output");
						MyMedia = new  Media(json.medias[0].id,json.medias[0].href,json.medias[0]["meta"]["dc:duration"],json.medias[0]['dc:title'],json.medias[0]['dc:description']);
						//alert(" MySwfPath : "+MySwfPath);
						MyMedia.createPlayer(playerLdtWidth,playerLdtHeight,json.medias[0]["meta"]["item"]["value"],MySwfPath);
						//alert("success loading ! "+json.medias[0]["meta"]["dc:duration"]+ " | " +json.medias[0]["meta"]["item"]["value"]);
						
						/* # créer lignes 				   */
						/*$jIRI.each(json['annotation-types'], function(i,item) {
						});*/	
						MyLdt = new Ligne (json['annotation-types'][0].id,json['annotation-types'][0]['dc:title'],json['annotation-types'][0]['dc:description'],json.medias[0]["meta"]["dc:duration"]);
						//alert("duration : "+json.medias[0]["dc:duration"]);
						
						/* # créer les annotations 				   */
						$jIRI.each(json.annotations, function(i,item) {

							MyLdt.addAnnotation(
										item.id,
										item.begin,
										item.end,
										item.media,
										item.content.title,
										item.content.description,
										item.content.color);
						
						});	
						$jIRI.each(json.lists, function(i,item) {
							trace("lists","");
						});		
						$jIRI.each(json.tags, function(i,item) {
							trace("tags","");
						});	
						$jIRI.each(json.views, function(i,item) {
							trace("views","");
						});	
						/* END PARSING ----------------------- */
						
										
					}
					,error: function(data){
						  alert("ERROR : "+data);
					}		
				  });	
	}

	function callbackLdts(json){
		
	}
	
	function trace (msg,value){
		$jIRI("<div>"+msg+" : "+value+"</div>").appendTo("#output");
	}


	
	
/* ----------------------------------------------------------------
   ----------------------------------------------------------------
INIT player LDT  
*/

	function playerLdt (width,height,file,divId,MySwfPath){
		
			$jIRI("#"+divId).append("<div id=\"ldtShow\">\n	<div id=\"ShowAnnotation\" class=\"demo\" >\n			<div id=\"ldtSaTitle\"></div>\n			<div id=\"ldtSaDescription\"></div>\n		</div>		<div id=\"ldtPlaceHolder\">\n			<a href=\"http://www.adobe.com/go/getflashplayer\">Get flash</a> to see this player	\n		</div>\n	</div>\n	<div id=\"controlerLdt\" class=\"demo\">\n		<div class=\"ldtControl1\" >\n			<button id=\"ldtCtrlPlay\" onclick=\"player.sendEvent('PLAY')\">Play</button>\n			<button id=\"ldtCtrlNext\" onclick=\"player.sendEvent('SEEK', currentPosition+10)\">next</button>\n		</div>\n		<div id=\"Annotations\" class=\"ui-slider\">\n			<div id=\"slider-range-min\"></div>\n		</div>\n		<div class=\"ldtControl2\">\n			<button id=\"ldtCtrlScreen\" onclick=\"player.fullscreen('true')\">Enlarge</button>\n			<button id=\"ldtCtrlSound\" onclick=\"player.sendEvent('MUTE')\">Sound</button>\n		</div>\n	</div><div class='cleaner'>&nbsp;</div>");
			loadJson(width,height,file,MySwfPath);
	}
	
	
	


/* ----------------------------------------------------------------
   ----------------------------------------------------------------
 API player */


	function APIplayer (){

	}
	


/* ----------------------------------------------------------------
   ----------------------------------------------------------------
	Class Media


		"http://advene.liris.cnrs.fr/ns/frame_of_reference/ms":"o=0",
		"id":"kia_closeup",
		"url":"D:/Thibaut/Outils_techno/IRI-LignesDeTemps/media/video/kia_closeup_BQ.flv",
		"dc:creator":"tcavalie",
		"dc:created":"2010-05-04T00:00:00",
		"dc:contributor":"tcavalie",
		"dc:modified":"2010-05-04T00:00:00",
		"dc:creator.contents":"Abbas Kiarostami",
		"dc:created.contents":"1990",
		"dc:title":"Close Up is a very very long title",
		"dc:description":"Analyse de Close Up",
		"dc:duration":"689266"
	*/
	function Media (id,url,duration,title,description){
		this.id 		 = id;
		this.url 		 = url;
		this.title 		 = title;
		this.description = description;
		this.duration 	 = duration;

		this.lignes = new Array();
		this.updatePlayer = updatePlayerMedia;
		this.getDuration = getMediaDuration;
		this.createPlayer = createPlayerMedia;
		
		trace("Media ID :",id);
		trace("Media URL :",this.url);
		trace("- content : color",url);
		trace("- content : audio",title);
	}
	function createPlayerMedia(width,height,MyStreamer,MySwfPath){
		//alert("create swfpath : "+MySwfPath+" my streame : "+MyStreamer);
		createPlayer(width,height,this.url,this.duration,MyStreamer,MySwfPath);
		createInterface(width,height,this.duration);
	}
	function updatePlayerMedia(){
		
	}
	function getMediaDuration(){
		return (this.duration);
	}
	function getMediaTitle(){
		return (this.title);
	}
	

/* ----------------------------------------------------------------
   ----------------------------------------------------------------
 Class Ligne (annotationType) 
	
		"id":"dp_1",
		"dc:creator":"tcavalie",
		"dc:created":"2010-04-04T19:09:44",
		"dc:contributor":"perso",
		"dc:modified":"15/2/2008",
		"dc:title":"dqsdkljfh qklsdhf very very very long",
		"dc:description":"sdfg sdfg sdfg sdfg"
	*/
	function Ligne (){
		this.id 			= id;
		this.title 			= title;
		this.description 	= description;
		this.annotations 	= new Array();
		this.addAnnotation  = addAnnotationligne;
		this.clickAnnotation= onClickLigneAnnotation;
		this.checkTime 		= checkTimeLigne;
	}
	
	function Ligne (id,title,description,duration){
		this.id 		 = id;
		this.title 		 = title;
		this.description = description;
		//
		this.annotations = new Array();
		this.addAnnotation = addLigneAnnotation;
		this.checkTime 	= checkTimeLigne;
		this.duration = duration;
		trace("LIGNE  ","créer ");
	}
	
	function addLigneAnnotation(id,begin,end,media,title,description,color){
		var myAnnotation = new Annotation(id,begin,end,media,title,description,color,this.duration);
		this.annotations.push(myAnnotation);
		trace("LIGNE  ","add annotation ");
	}
	
	function onClickLigneAnnotation(id){
		player.sendEvent('SEEK', this.start);
	}
	
	function searchLigneAnnotation(id){
		/*for (){
		}*/
	}
	
	function listAnnotations(){
	
	}
	
	function checkTimeLigne(time){
		var annotationTempo;
		for (var i=0; i < this.annotations.length; ++i){
			var annotationTempo = this.annotations[i];
			//trace("check... ",time+" = "+annotationTempo.begin+" -- "+annotationTempo.end);
			//if (time>annotationTempo.begin){
			if (time>annotationTempo.begin/1000 && time<annotationTempo.end/1000){
				//trace("check ",annotationTempo.begin+" "+annotationTempo.end +" "+annotationTempo.title);
				$jIRI("#ldtSaTitle").text(annotationTempo.title);
				$jIRI("#ldtSaDescription").text(annotationTempo.description);
				break;
			} 
		}
	}
	


/* ----------------------------------------------------------------
   ----------------------------------------------------------------
  CLASSE Annotation 


		"begin":"767",
		"end":"785",
		"id":"dp_1_sp_3",
		"media":"kia_closeup",
		"content": {
						"mimetype":"application/x-ldt-structured",
						"title":"mon titre",
						"description":"ma description en &lt;b&gt;gras&lt;/b&gt; .",
						"color":"16763904",
						"audio":{"src":"","mimetype":"audio/mp3","href":""}
					},
		"meta":
				{
					"id-ref":"dp_1",
					"dc:creator":"tcavalie",
					"dc:created":"2010-04-04T19:09:44",
					"dc:contributor":"perso",
					"dc:modified":"9/10/2007"
				}
	*/
	
	function Annotation (){
		this.id 			= null;
		this.begin 			= null;
		this.end 			= null;
		this.media 			= null;
		this.description	= null;
		this.title 			= null;
		this.color 			= null;
		this.onRollOver 	= onRollOverAnnotation;
		this.onClick 		= onClickAnnotation;
		this.toolTip 		= rollOverAnnotation;
		this.draw 			= drawAnnotation;
		trace("annotation ","réussi")
	}
	
	function Annotation (id,begin,end,media,title,description,color,duration){
		this.id 			= id;
		this.begin 			= begin;
		this.end 			= end;
		this.media 			= media;
		this.description 	= description;
		this.title 			= title;
		this.color 			= title;
		this.duration		= duration;
		//
		this.onRollOver 	= onRollOverAnnotation;
		//this.onClick 		= onClickAnnotation;
		this.toolTip 		= tootTipAnnotation;
		this.draw 			= drawAnnotation;
		//this.show 			= showAnnotationNotice;
		// draw it 
		this.draw();
		
		//
		trace("Annotation created : ",id);
	}
	
	function drawAnnotation (){
		//alert (this.duration);
		startPourcent = timeToPourcent(this.begin,this.duration); // temps du média 
		endPourcent = timeToPourcent(this.end,this.duration)-startPourcent;
				
		$AnnotationTemplate = "<div title='"+this.title+"' id='"+this.id+"'  class='ui-slider-range ui-slider-range-min ui-widget-header iri-chapter' width='100%' style='left:"+startPourcent+"%; width:"+endPourcent+"%; padding-top:15px; border-left:solid 1px #aaaaaa; border-right:solid 1px #aaaaaa;' onclick=\"player.sendEvent('SEEK', '"+Math.round(this.begin/1000)+"');$jIRI('#ShowAnnotation').slideDown().delay(5000).slideUp();\"  ></div> ";
		

		
		$toolTipTemplate = "<div class='tooltip'>"
							+"<div class='title'>"+this.title+"</div>"
							+"<div class='time'>"+this.begin+" : "+this.end+"</div>"
							+"<div class='description'>"+this.description+"</div>"
							+"</div>";
		
		
		$jIRI("<div>"+$AnnotationTemplate+"</div>").appendTo("#Annotations");
		$jIRI("#"+this.id).tooltip({ effect: 'slide'});

		trace(" ### ","ADD ANOTATION : "+this.begin+" "+this.end+" "+this.title+" | "+startPourcent+" | "+endPourcent+" | duration = "+this.duration);
	}
	
	function tootTipAnnotation() {
		// 1 chercher le div correspondant
		// 2 y mettre les information
		return this.color + ' ' + this.type + ' apple';
	}
	
	function onRollOverAnnotation(){
		this.tootTip();
	}
		
	function timeToPourcent(time,timetotal){
		return (parseInt(Math.round(time/timetotal*100)));
	}
		
		
/* ----------------------------------------------------------------
   ----------------------------------------------------------------
	Class tracess */
	
	function Tracer (){
		
	}
	
	function addTrace(){
		
	}
	
	
	