/**
 * Colibri
 **/

Colibri = function(initOptions) {
  this.init(initOptions);
};
   
$.extend(Colibri.prototype, {
  components:  {},
  XMLPresentation: null,
  XMLDocuments: null,
  vPosition:  0,
  vDuration:  0,
  isPlaying:  false,
  relativeURL: '',

  init: function(initOptions) {
	
    if(arguments[0].relativeURL != 'undefined')
      this.relativeURL = arguments[0].relativeURL + '/';
    
    var obj = this;
    var XMLPresentationURL = this.relativeURL + "watch/getXMLData";
    var XMLDocumentsURL = this.relativeURL + "watch/getXMLData";
    var noCache = Math.random(); // fix AJAX cache problems in IE
    var component = null;

    this.isPlaying = true;
      
    $.ajax({type: "GET", async:false, url: XMLPresentationURL, data: ({presentationId: document.getElementById('presentationId').value, file: 'presentation', actualizeIe: noCache}), dataType: "json", success:function(data, textStatus){obj.XMLPresentation = data;}});
    $.ajax({type: "GET", async:false, url: XMLDocumentsURL, data: ({presentationId: document.getElementById('presentationId').value, file: 'documents', actualizeIe: noCache}), dataType: "json", success:function(data, textStatus){obj.XMLDocuments = data;}});
    $.extend(this.components, {player: null, plan: null, documents: null, annexes: null, sidebar: null});
    for (component in this.components) {  // create and add components to Colibri
      this.components[component] = eval("new " + component + "(this.XMLPresentation, this.XMLDocuments);");
    }
  },
  
  sync: function() {
	var component = null;
	
    if (this.isPlaying == true) {
      for (component in this.components) { // call components sync functions
        this.components[component].sync(this.vPosition);
      }
    }
    setTimeout("theColibri.sync();", 1000);
  }
});


/**
 * Colibri Component : player
 **/

player = function(XMLPresentation, XMLDocuments) {
  this.init(XMLPresentation, XMLDocuments);
};

$.extend(player.prototype, {
  init: function(XMLPresentation, XMLDocuments) {
  },

  setTimecode: function(timecode) {
    setCurrentTime(Math.floor(timecode/1000));
    playPause('play');
  },
  
  sync: function(timecode) {
  }
});


/**
 * Colibri Component : plan
 */

plan = function(XMLPresentation, XMLDocuments) {
  this.init(XMLPresentation, XMLDocuments);
};

$.extend(plan.prototype, {
  chapters: {length: 0, currentChapter: 0},

  init: function(XMLPresentation, XMLDocuments) {
	$('.ulevel0').empty();
	if (!XMLPresentation.speech.content.outline[0]) { // if there is only one root tag 'outline', replace it with an array containing just one outline. God it's ugly.
		var tmp = XMLPresentation.speech.content.outline;
		delete XMLPresentation.speech.content.outline;
		XMLPresentation.speech.content.outline = Array();
		XMLPresentation.speech.content.outline[0] = tmp;
	}
	this.getChapter(this, -1, XMLPresentation.speech.content.outline);
  },
  
  getChapter: function (obj, i, data) {
	++i;
    $.each(data, function() {
    	if (this.outline && this.attributes && this.attributes.title && this.attributes.timecode) {
			$(".ulevel" + (i).toString() + ":last").append("<li class=\"ilevel" + (i).toString() + "\"><a href=\"javascript:theColibri.components.player.setTimecode(" + this.attributes.timecode + ");\" title=\"" + goToTime + obj.formatTime(Math.floor(this.attributes.timecode / 1000)) + ofTheVideo + " - " + this.attributes.title + "\"><span class=\"chapterTitle\">" + this.attributes.title + "</span></a><ul class=\"ulevel" + (i + 1).toString() + "\"></ul></li>");
			obj.chapters[obj.chapters.length++] = {
				timecode: this.attributes.timecode,
				title: this.attributes.title
			};
			obj.getChapter(obj, i, this.outline);
    	} else if (this.attributes && this.attributes.title && this.attributes.timecode && this.attributes.id != -1) {
    		$(".ulevel" + (i).toString() + ":last").append("<li class=\"ilevel" + (i).toString() + "\"><a href=\"javascript:theColibri.components.player.setTimecode(" + this.attributes.timecode + ");\" title=\"" + goToTime + obj.formatTime(Math.floor(this.attributes.timecode / 1000)) + ofTheVideo + " - " + this.attributes.title + "\"><span class=\"chapterTitle\">" + this.attributes.title + "</span></a></li>");
    		obj.chapters[obj.chapters.length++] = {
				timecode: this.attributes.timecode,
				title: this.attributes.title
			};
    	} else if (this.timecode && this.title) {
    		$(".ulevel" + (i).toString() + ":last").append("<li class=\"ilevel" + (i).toString() + "\"><a href=\"javascript:theColibri.components.player.setTimecode(" + this.timecode + ");\" title=\"" + goToTime + obj.formatTime(Math.floor(this.timecode / 1000)) + ofTheVideo + " - " + this.title + "\"><span class=\"chapterTitle\">" + this.title + "</span></a></li>");
    		obj.chapters[obj.chapters.length++] = {
				timecode: this.timecode,
				title: this.title
			};		
		} else if (this.outline) {
			$(".ulevel" + (i).toString() + ":last").append("<li class=\"ilevel" + (i).toString() + "\"><ul class=\"ulevel" + (i + 1).toString() + "\"></ul></li>");
			obj.getChapter(obj, i, this.outline);
		}
    });
  },

  sync: function(vPosition) { // set currentChapter
	var min = 0;
	var max = this.chapters.length;
	var mid = parseInt((min + max) / 2);

	while (mid != min) {
		if (this.chapters[mid].timecode > Math.floor(vPosition * 1000)) {
			max = mid;
		} else {
			min = mid;
		}
		mid = parseInt((min + max) / 2);
	}

	if (min != this.chapters.currentChapter || !this.chapters.currentChapter) {
		$('#plan li:has(a.currentChapter):last').removeClass('currentChapter');
		$("#plan a:eq(" + this.chapters.currentChapter + ")").removeClass('currentChapter');
		$("#plan a:eq(" + min + ")").addClass('currentChapter');
		$('#plan li:has(a.currentChapter):last').addClass('currentChapter');
		this.chapters.currentChapter = min;
		if (this.chapters[min].title.length > 40) {
		  $('#plan span#currentChapter span').text(this.chapters[min].title.substr(0, 40) + '...');
		} else {
		  $('#plan span#currentChapter span').text(this.chapters[min].title);
		}
	}
  },

  formatTime: function(time) { // format time to hh:mm:ss
    var t = new Array(time, 0, 0); // t[0] => seconds, t[1] => minutes, t[2] => hours

    if (t[0] > 60) {
      t[1] = parseInt(time / 60, 10);
      t[0] = parseInt(time % 60, 10);
    }
    if (t[1] > 60) {
      t[2] = parseInt(t[1] / 60, 10);
      t[1] = parseInt(t[1] % 60, 10);
    }

    for (i = 0; i < 3; i++)
      t[i] = t[i] < 10 ? '0' + t[i] : t[i];

    if (t[2] != '00') {
      return t[2] + ':' + t[1] + ':' + t[0];
    } else {
      return t[1] + ':' + t[0];
    }
  }
});


/**
 * Colibri Component : documents
 **/

documents = function(XMLPresentation, XMLDocuments) {
  this.init(XMLPresentation, XMLDocuments);
};

$.extend(documents.prototype, {
  documents:  {length: 0, currentDocument: null},
  isSync:  true,

  init: function(XMLPresentation, XMLDocuments) {
	this.getDocuments(this, XMLPresentation.speech.content.outline);
    if (XMLDocuments.documents.attributes.count > 0) {
		this.getDocumentsFilename(this, XMLDocuments.documents.document);
	}
    this.triInsertionR(this.documents.length); // Really need to rebuild parsing of XML without using JSON
	if (this.documents.length > 0) {
		$("#maxDocumentPosition").html(this.documents.length);
		$("#loadingLi").hide();
		$("#documentsUl").show();
	} else {
		$("#documentsCounter").text('Aucun document');
	}
  },

  insertionR: function(n, e) {
   if ((n == 0) || (parseInt(e.timecode) >= parseInt(this.documents[n - 1].timecode)))
      this.documents[n] = e;
   else {
      this.documents[n] = this.documents[n - 1];
      this.insertionR(n - 1, e);
   }
  },
  
  triInsertionR: function(n) {
   if (n > 1) {
      this.triInsertionR(n - 1);
      this.insertionR(n - 1, this.documents[n - 1]);
   }
  },

  getDocuments: function (obj, data) { // build the document array, containing slides and documents excluding annexes 
    $.each(data, function() {
		
    	if (this.outline) {
			obj.getDocuments(obj, this.outline);
    	}
    	if (this.document && this.document.attributes && this.document.attributes.zone == undefined) {
			obj.documents[obj.documents.length] = {
				num:		obj.documents.length,
				id:			this.document.attributes.id,
				timecode:	this.document.attributes.timecode,
				zone:		this.document.attributes.zone
			}
			obj.documents.length++;
    	} else if (this.document && this.document.length) {
    		for (i = 0; i < this.document.length; i++) {
    			if (this.document[i].attributes.zone == undefined) {
					obj.documents[obj.documents.length] = {
						num:		obj.documents.length,
						id:			this.document[i].attributes.id,
						timecode:	this.document[i].attributes.timecode,
						zone:		this.document[i].attributes.zone
					}
					obj.documents.length++;
    			}
    		}
    	}
    	if (this.slide && this.slide.attributes) {
			obj.documents[obj.documents.length] = {
				num:		obj.documents.length,
				id:			this.slide.attributes.id,
				timecode:	this.slide.attributes.timecode,
				type:		'slide'
			}
			obj.documents.length++;
    	} else if (this.slide && this.slide.length) {
    		for (i = 0; i < this.slide.length; i++) {
				if (this.slide[i].attributes && this.slide[i].attributes.id && this.slide[i].attributes.timecode) {
					obj.documents[obj.documents.length] = {
						num:		obj.documents.length,
						id:			this.slide[i].attributes.id,
						timecode:	this.slide[i].attributes.timecode,
						type:		'slide'
					}
					obj.documents.length++;
				}
    		}
    	} else if (this.length && this[0].attributes && this[0].attributes.id && this[0].attributes.timecode) {
			for (i = 0; i < this.length; i++) {
				if (this[i].attributes && this[i].attributes.id && this[i].attributes.timecode) {
					obj.documents[obj.documents.length] = {
						num:		obj.documents.length,
						id:			this[i].attributes.id,
						timecode:	this[i].attributes.timecode,
						type:		'slide'
					}
					obj.documents.length++;
				}
    		}
		}
    });
  },

  getDocumentsFilename: function (obj, data) { // set filenames and titles to documents array 
	$.each(data, function () {
		if (this.file) {
			for (i = 0; i < obj.documents.length ; i++) {
				if (this.attributes.id == obj.documents[i].id && obj.documents[i].type != "slide") {
					$.extend(obj.documents[i], {
						title: this.attributes.title,
						filename: this.file.filename,
						type: this.file.filename.slice(this.file.filename.lastIndexOf('.') + 1)
					});
				}
			}
		} else if (this.url) {
			for (i = 0; i < obj.documents.length ; i++) {
				if (this.attributes.id == obj.documents[i].id && obj.documents[i].type != "slide") {
					$.extend(obj.documents[i], {
						title: this.attributes.title,
						url: this.url,
						type: 'url'
					});
				}			
			}
		}
	});
  },

  sync: function(timecode) { // set the current document
	
    if (this.documents.length > 0 && this.isSync == true) {
			var min = 0;
			var max = this.documents.length;
			var mid = parseInt((min + max) / 2);

			while(mid != min) {
				if (this.documents[mid].timecode > timecode * 1000) {
					max = mid;
				}
				else {
					min = mid;
				}
				mid = parseInt((min + max) / 2); 
			}
			if (this.documents[min] != this.documents.currentDocument) {
				this.setDocument(this.documents[min]);
				$('#currentDocumentPosition').html(parseInt(this.documents.currentDocument.num, 10) + 1);
				return 0;
			} else {
				return 1;
			}
		}
	},

	setDocument: function(doc) {
		this.documents.currentDocument = doc;
		this.resetDocControls();
		$('#doc').empty();
		switch(doc.type) {
			case 'slide':
				if (colibriOptions.videoMax) {
				  $("#doc").html("<img id=\"slide\" src=\"" + theColibri.relativeURL + "documents/" + document.getElementById('presentationId').value + "/" + doc.id + "_medium.jpg\" width=\"236\" height=\"177\" border=\"0\" />");
				} else {
				  $("#doc").html("<img id=\"slide\" src=\"" + theColibri.relativeURL + "documents/" + document.getElementById('presentationId').value + "/" + doc.id + "_medium.jpg\" border=\"0\" />");
				}
				this.showZoom(doc);
				this.showSave(doc);
				break;
			case 'url':
				if (colibriOptions.videoMax) {
				  $('#doc').html('<iframe id="urlIframe" width="236" height="177" scrolling="auto" frameborder="0" src="' + doc.url + '" ></iframe>');
				} else {
				  $('#doc').html('<iframe id="urlIframe" width="504" height="378" scrolling="auto" frameborder="0" src="' + doc.url + '" ></iframe>');
				}
				this.showOpen(doc);
				break;
			case 'htm':
				$('#doc').html('<iframe id="ifr" scrolling="auto" frameborder="0" src="' + theColibri.relativeURL + 'documents/' + doc.url + '" ></iframe><br class"clear" />');
				this.showOpen(doc);
				break;
			case 'swf':
				if (colibriOptions.videoMax) {
				  $('#doc').append('<object width="236" height="177"><param name="movie" value="' + theColibri.relativeURL + 'documents/'+doc.filename+'"><embed src="' + theColibri.relativeURL + 'documents/'+doc.filename+'" width="235" height="264"></embed></object>');
				}
				else {
				  $('#doc').append('<object width="504" height="378"><param name="movie" value="' + theColibri.relativeURL + 'documents/'+doc.filename+'"><embed src="' + theColibri.relativeURL + 'documents/'+doc.filename+'" width="504" height="378"></embed></object>');
				}
				$("#swfObject").append("<a href=\"" + theColibri.relativeURL + "documents/" + doc.filename.slice(0, doc.filename.indexOf('.')) + ".html\">"+ doc.title + "</a>");
				break;
			case 'pdf':
				if (colibriOptions.videoMax) {
				  $("#doc").html('<embed id="pdf" type="application/pdf" width="236" height="177" src="' + theColibri.relativeURL + 'documents/' + doc.filename + '"></embed>');
				}
				else {
				  $("#doc").html('<embed id="pdf" type="application/pdf" width="504" height="378" src="' + theColibri.relativeURL + 'documents/' + doc.filename + '"></embed>');
				}
				this.showSave(doc);
				break;
			case 'png':
				if (colibriOptions.videoMax) {
				  $("#doc").html('<img id=\"png\" width=\"236\" height=\"177\" border=\"0\" src="' + theColibri.relativeURL + 'documents/' + doc.filename + '"></img>');
				}
				else {
				  $("#doc").html('<img id=\"png\" width="504" height="378" src="' + theColibri.relativeURL + 'documents/' + doc.filename + '"></img>');
				}
				this.showSave(doc);
				break;
		}
	},
	
	toggleSync: function() {
		if (this.isSync == true) {
			$(".syncON").attr({style: 'display:none;'});
			$(".syncOFF").attr({style: 'display:inline;'});
			this.isSync = false;
		} else {
			$(".syncON").attr({style: 'display:inline;'});
			$(".syncOFF").attr({style: 'display:none;'});
			this.isSync = true;
		}
	},
	
	firstDocument: function() {
		if (this.isSync == true) {
			theColibri.components.player.setTimecode(parseInt(this.documents[0].timecode, 10) * 1000);
		} else {
			this.setDocument(this.documents[0]);
			$('#currentDocumentPosition').text(parseInt(this.documents.currentDocument.num, 10) + 1);
		}
	},
	
	previousDocument: function() {
		if (this.documents.currentDocument.num - 1 >= 0) {
			if(this.isSync == true) {
				theColibri.components.player.setTimecode(parseInt(this.documents[this.documents.currentDocument.num - 1].timecode, 10));
			} else {
				this.setDocument(this.documents[this.documents.currentDocument.num - 1]);
				$('#currentDocumentPosition').text(parseInt(this.documents.currentDocument.num, 10) + 1);
			}
		}
	},
	
	nextDocument: function() {
		if (this.documents.currentDocument.num + 1 < this.documents.length) {
			if (this.isSync == true) {
				theColibri.components.player.setTimecode(parseInt(this.documents[this.documents.currentDocument.num + 1].timecode, 10));
			} else {
				this.setDocument(this.documents[this.documents.currentDocument.num + 1]);
				$('#currentDocumentPosition').text(parseInt(this.documents.currentDocument.num, 10) + 1);
			}
		}
	},
	
	lastDocument: function() {
		if (this.isSync == true) {
			theColibri.components.player.setTimecode(parseInt(this.documents[this.documents.length - 1].timecode, 10) * 1000);
		} else {
			this.setDocument(this.documents[this.documents.length - 1]);
			$('#currentDocumentPosition').text(parseInt(this.documents.currentDocument.num, 10) + 1);
		}
	},
	
	resetDocControls: function() {
		$(".documentsFunctions").each(function() {
			$(this).empty();
			$(this).remove();
		})
	},

	showZoom: function(doc) {
		$("#documentControls ul").append("<li><a id=\"zoom\" class=\"documentsFunctions\" href=\"#\"><img src=\"/images/watch/btnOpenWindow.png\" alt=\"" + zoomI18n + "\" border=\"0\" /></a></li>");
		$("#zoom.documentsFunctions").click(function() {
			window.open(theColibri.relativeURL + "/documents/" + document.getElementById('presentationId').value + "/" + doc.id + "_big.jpg", "viewDocument", "width=960, height=720");
		});
	},

	showSave: function(doc) {
		if (doc.type == "slide")
			$("#documentControls ul").append("<li><a id=\"save\" class=\"documentsFunctions\" href=\"" + theColibri.relativeURL + "documents/" + document.getElementById('presentationId').value + "/" + doc.id + "_medium.jpg\"><img src=\"/images/watch/btnSave.png\" alt=\"" + saveI18n + "\" border=\"0\" /></a></li>");
		else if (doc.type == "pdf")
			$("#documentControls ul").append("<li><a id=\"save\" class=\"documentsFunctions\" href=\"" + theColibri.relativeURL + "data/" + doc.filename + "\"><img src=\"/images/watch/btnSave.png\" alt=\"" + saveI18n + "\" border=\"0\" /></a></li>");
		$("#save.documentsFunctions").onclick = function() {
			window.open(this.href);
	    	return false;
		};
	},

	showOpen: function(doc) {
		$("#documentControls ul").append("<li><a id=\"open\" class=\"documentsFunctions\" href=\"" + doc.url + "\"><img src=\"/images/watch/btnOpenWindow.png\" alt=\"" + openI18n + "\" border=\"0\" /></a></li>");
		document.getElementById('open').onclick = function() {
			window.open(this.href); 
			return false;
		};
	}
});


/**
 * Colibri Component : annexes
 **/

annexes = function(XMLPresentation, XMLDocuments) {
  this.init(XMLPresentation, XMLDocuments);
};

$.extend(annexes.prototype, {
  annexes:  {length: 0},
  currentAnnexesNum: 0,

  init: function(XMLPresentation, XMLDocuments) {
    if (XMLDocuments && XMLDocuments.documents.attributes.count > 0) {
		this.getAnnexes(this, XMLPresentation.speech.content.outline);
		this.getAnnexesFilename(this, XMLDocuments.documents.document);
	}
  },

  getAnnexes: function (obj, data) { // build the annexes array, containing only annexes 
    $.each(data, function() {
    	if (this.document && this.document.attributes && this.document.attributes.zone == "annex") {
			obj.annexes[obj.annexes.length] = {
				num:		obj.annexes.length,
				id:			this.document.attributes.id,
				timecode:	this.document.attributes.timecode,
				zone:		this.document.attributes.zone,
				setted:		0
			}
			obj.annexes.length++;
    	} else if (this.document && this.document.length) {
    		for (i = 0; i < this.document.length; i++) {
    			if (this.document[i].attributes.zone == "annex") {
					obj.annexes[obj.annexes.length] = {
						num:		obj.annexes.length,
						id:			this.document[i].attributes.id,
						timecode:	this.document[i].attributes.timecode,
						zone:		this.document[i].attributes.zone,
						setted:		0
					}
					obj.annexes.length++;
    			}
    		}
    	}
    	if (this.outline) {
			obj.getAnnexes(obj, this.outline);
    	}
    });
  },

  getAnnexesFilename: function (obj, data) { // set filenames and titles to annexes array 
    //if there's just one document, make an array to be iterated
    if(data.constructor != Array)
      data = [ data ];
    
    $.each(data, function () {
		if (this.file) {
			for (i = 0; i < obj.annexes.length ; i++) {
				if (this.attributes.id == obj.annexes[i].id && obj.annexes[i].type != "slide") {
					$.extend(obj.annexes[i], {
						title: this.attributes.title,
						filename: this.file.filename,
						type: this.file.filename.substr(this.file.filename.lastIndexOf('.') + 1).toLowerCase()
					});
				}
			}
		} else if (this.url) {
			for (i = 0; i < obj.annexes.length ; i++) {
				if (this.attributes.id == obj.annexes[i].id && obj.annexes[i].type != "slide") {
					$.extend(obj.annexes[i], {
						title: this.attributes.title,
						url: this.url,
						type: 'url'
					});
				}			
			}
		}
	});
  },  
  
  sync: function(timecode) {
    if (this.annexes.length > 0) {
		var min = 0;
		var max = this.annexes.length;
		var mid = parseInt((min + max) / 2);

		while(mid != min) {
			if (this.annexes[mid].timecode > timecode * 1000) {
				max = mid;
			}
			else {
				min = mid;
			}
			mid = parseInt((min + max) / 2); 
		}
		if (this.annexes[min] != this.annexes.currentAnnexesNum) {
			this.addAnnex(this.annexes[min]);
			this.annexes.currentAnnexesNum = this.annexes[min];
		}
	}
  },

  addAnnex: function(doc) {
	if (this.currentAnnexesNum == 4) {
	  $('#annex ul').empty();
	  this.currentAnnexesNum = 0;
	}
	++this.currentAnnexesNum;
	if (doc.type == 'url')
		var href = doc.url;
	else 
		var href = theColibri.relativeURL + 'documents/' + doc.filename;
	$('#annex ul').prepend("<li><img src=\"" + theColibri.relativeURL + "images/watch/ico" + doc.type + ".png\" /><a id=\"annexN" + doc.num + "\" class=\"annexDoc\" href=\""+ href +"\" title=\"" + annexI18n + doc.title + ".\">  "+ doc.title +" (" + doc.type + ")</a></li>");
	document.getElementById('annexN' + doc.num).onclick = function() {
		window.open(this.href); 
		return false;
	};
  }
});


/**
 * Colibri Component : sidebar
 **/

sidebar = function(XMLPresentation, XMLDocuments) {
  this.init(XMLPresentation, XMLDocuments);
};

$.extend(sidebar.prototype, {
  shareInstantUrl: '',
  
  init: function(XMLPresentation, XMLDocuments) {
	$('.tagQuotes').hide();
	$('.documentQuotes').hide();
	$('.tag a').bind("click", function () {
		$('.tag div:eq(' + $(this).attr('id') + ')').toggle();
	});
	$('.document a').bind("click", function () {
		$('.document div:eq(' + $(this).attr('id') + ')').toggle(); 
	});
  },
  
  getNoteContent: function (id) {
	  editor = tinyMCE.activeEditor;
	  if(id == null)
	    editor = tinyMCE.getInstanceById(id);
	  if(editor != null)
	  	return editor.getContent({format : 'html'});
	  else
	    return "";
  },
  
  scrollToChapter: function (timecode) {
	  theColibri.components.player.setTimecode(timecode);
	  setTimeout("$('#chapterList').scrollTo($('#plan li.currentChapter'), 'y');", 2000);
  },

  sync: function(timecode) {
	  if (document.location.href.slice(document.location.href.lastIndexOf('/') + 1) == document.getElementById('timecodeAtStart').value)
		  this.shareInstantUrl = document.location.href.slice(0, document.location.href.lastIndexOf('/'));
	  else
		  this.shareInstantUrl = document.location.href;
	  $('#shareInstantField').text(this.shareInstantUrl + '/' + Math.round(timecode * 1000));
	  //$('#shareInstantField').select();
  }
});


/**
 * Colibri launcher
 */

$(document).ready(function () {
  theColibri = new Colibri(colibriOptions);
  if(typeof(theColibri) != 'undefined') {
    theColibri.sync();
  }
});
