/**
_______________________________
DOCUMENTS COMPONENT */

Colibri.documents = function(XMLPresentation, XMLDocuments) {
	this.init(XMLPresentation, XMLDocuments);
};

$.extend(Colibri.documents.prototype, {
	documents:  {length: 0, currentDocument: 0},
	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;
		   	  //@quickfix #159
		      this.documents[n].num = n;
		   } else {
		      this.documents[n] = this.documents[n - 1];
		      //@quickfix #159
		      this.documents[n].num = n;
		      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) {
	      //console.info("sync dans les docs : ", timecode);
				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); 
				}
				//console.info(this.documents[min], "!=", this.documents.currentDocument);
				if (this.documents[min] != this.documents.currentDocument) {
				  //console.info("changement de doc ", min);
					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 (theColibriOptions.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 (theColibriOptions.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 (theColibriOptions.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 (theColibriOptions.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 'jpg':
					if (theColibriOptions.videoMax) {
						$('#doc').html('<object tabindex="0" width="233" height="177" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"><param value="' + theColibri.relativeURL + 'assets/images.swf" name="movie"/><param value="high" name="quality"/><param value="#FFFFFF" name="bgcolor"/><param value="window" name="wmode"/><param value="initUrl=' + theColibri.relativeURL + "documents/" + doc.filename + '" name="FlashVars"/><embed src="' + theColibri.relativeURL + 'assets/images.swf" FlashVars="initUrl='+ theColibri.relativeURL + '/documents/' + doc.filename + '" width="236" height="177"></embed></object>');
					} else {
						$('#doc').html('<object tabindex="0" width="504" height="378" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"><param value="' + theColibri.relativeURL + 'assets/images.swf" name="movie"/><param value="high" name="quality"/><param value="#FFFFFF" name="bgcolor"/><param value="window" name="wmode"/><param value="initUrl=' + theColibri.relativeURL + "documents/" + doc.filename + '" name="FlashVars"/><embed src="' + theColibri.relativeURL + 'assets/images.swf" FlashVars="initUrl='+ theColibri.relativeURL + '/documents/'+ doc.filename + '" width="504" height="378"></embed></object>');
					}
				case 'gif':
					if (theColibriOptions.videoMax) {
						$('#doc').html('<object tabindex="0" width="233" height="177" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"><param value="' + theColibri.relativeURL + 'assets/images.swf" name="movie"/><param value="high" name="quality"/><param value="#FFFFFF" name="bgcolor"/><param value="window" name="wmode"/><param value="initUrl=' + theColibri.relativeURL + "documents/" + doc.filename + '" name="FlashVars"/><embed src="' + theColibri.relativeURL + 'assets/images.swf" FlashVars="initUrl='+ theColibri.relativeURL + '/documents/' + doc.filename + '" width="236" height="177"></embed></object>');
					} else {
						$('#doc').html('<object tabindex="0" width="504" height="378" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"><param value="' + theColibri.relativeURL + 'assets/images.swf" name="movie"/><param value="high" name="quality"/><param value="#FFFFFF" name="bgcolor"/><param value="window" name="wmode"/><param value="initUrl=' + theColibri.relativeURL + "documents/" + doc.filename + '" name="FlashVars"/><embed src="' + theColibri.relativeURL + 'assets/images.swf" FlashVars="initUrl='+ theColibri.relativeURL + '/documents/'+ doc.filename + '" width="504" height="378"></embed></object>');
					}
				case 'png':
					if (theColibriOptions.videoMax) {
						$('#doc').html('<object tabindex="0" width="233" height="177" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"><param value="' + theColibri.relativeURL + 'assets/images.swf" name="movie"/><param value="high" name="quality"/><param value="#FFFFFF" name="bgcolor"/><param value="window" name="wmode"/><param value="initUrl=' + theColibri.relativeURL + "documents/" + doc.filename + '" name="FlashVars"/><embed src="' + theColibri.relativeURL + 'assets/images.swf" FlashVars="initUrl='+ theColibri.relativeURL + '/documents/' + doc.filename + '" width="236" height="177"></embed></object>');
					} else {
						$('#doc').html('<object tabindex="0" width="504" height="378" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"><param value="' + theColibri.relativeURL + 'assets/images.swf" name="movie"/><param value="high" name="quality"/><param value="#FFFFFF" name="bgcolor"/><param value="window" name="wmode"/><param value="initUrl=' + theColibri.relativeURL + "documents/" + doc.filename + '" name="FlashVars"/><embed src="' + theColibri.relativeURL + 'assets/images.swf" FlashVars="initUrl='+ theColibri.relativeURL + '/documents/'+ doc.filename + '" width="504" height="378"></embed></object>');
					}
			}
		},
		
		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;
			};
		}
	});
