function NoteObject(semilla, seed, cdataVersion, editable, left, top, content_media, content, highlight, floating, content_type, media_url, media_type){
	this._semilla = semilla;
	this._seed = seed;
	this._cdataVersion = cdataVersion;
	this._editable = editable;
	this._left = left;
	this._top = top;
	this._content_media = content_media;
	this._content = content;
	this._highlight = highlight;
	this._floating = floating;
	if(content_type)
		this._content_type = content_type;
	else
		this._content_type = 'html';
	this._media_url = media_url;
	this._media_type = media_type;	
}

NoteObject.prototype._semilla;
NoteObject.prototype._seed;
NoteObject.prototype._cdataVersion;
NoteObject.prototype._editable;
NoteObject.prototype._left;
NoteObject.prototype._top;
NoteObject.prototype._content_media;
NoteObject.prototype._content;
NoteObject.prototype._highlight;
NoteObject.prototype._floating;
NoteObject.prototype._content_type; // VERY IMPORTANT PROPERTY TO KEEP THE COMPATIBILITY WITH THE NOTES SAVED WITH THE HTML EDITOR
NoteObject.prototype._media_url;
NoteObject.prototype._media_type;


NoteObject.prototype.removeObject = function(){
	$('#' + this._seed).remove();
}

function Annotate(displayable, seed){
	 //Constructor
 	this._displayable = displayable;
	this._currentSeed = seed;	
	
	
	//Agroups the notes in one seed for this instance of application
	this.makeSeedGroup();			
}


Annotate.prototype._appName = 'Annotate';
Annotate.prototype._referal;
Annotate.prototype._displayable;
Annotate.prototype._server_path = "http://layers.com/";
Annotate.prototype._currentSeed;
Annotate.prototype._cdataVersion = '1.0';
Annotate.prototype._notes = new Array();
Annotate.prototype._object = new Object();



Annotate.prototype.drawNote = function(contents, media_url, media_type){
	var semilla = new Date().getTime();
	var left = parseInt(getWindowLeftScrollOffset()) + 'px';  
	var top = parseInt(getWindowTopScrollOffset()) + 'px';
	
	var media = "";
	//Make <img src......
	if (media_type=='photo') {
		media = '<img style="max-width:390px;" class="layersOS_annotate_photo" src="' + media_url + '">';
	}
	//Make embed video
	if (media_type == 'video') {
		media = embedVideo(media_url, 390, 324);
	}	
	
	var note = new NoteObject(
		semilla, 
		this._currentSeed, 
		this._cdataVersion, 
		true, 
		left, 
		top, 
		media, 
		contents, 
		'',
		true,
		'text',
		media_url,
		media_type
	);
	
	this.renderNote(note);

}

Annotate.prototype.renderNote = function(note){
	var me = this;
	var noteHtml = "";
	var ownerIcon = "/images/nouser.jpg";
	
	var idContainer='container_' + note._semilla;
	var noteHtml = this.drawNoteContainers(note);
	
	var noteHtmlContent = this.getNoteHtmlContent(note);
	
	$('#' + note._seed).append(noteHtml);
	$('#' + idContainer).append(noteHtmlContent);
	
	//Puts the Content in the Note
	this.putContent(note);
	
	//Add events in the Note
	this.addEventsToNote(note);	
	
	//Insert owner image		
	$('#' + note._semilla + ' .layersOS_annotate_menu_icon > img')[0].src = ownerIcon;
	
	//Resize Note
	this.resizeNote(note._semilla);		
}

Annotate.prototype.drawNoteContainers = function(note){
	var idAnclaje = 'anc_' + note._semilla;
	var idContainer='container_' + note._semilla;
	var noteHtml = "";
	var noteTop = note._top;
	var noteLeft = note._left;
	var zIndex = this.getMaxZIndex();
	noteHtml = noteHtml + "<div class=\"scrmlyrs " + note._semilla + " note_scroll_class\" style=\"top:50%;left:50%;z-index: " + zIndex + ";position: absolute;\" id=\""+ idAnclaje + "\">";
	noteHtml = noteHtml + "<div onclick=\"return false;\" class=\"scrmlyrs note note_container\" style=\"z-index: " + zIndex + ";left:" + noteLeft + "; top: " + noteTop + ";position:absolute; width:500px; height:117\" id=\"" + idContainer + "\">";	
	noteHtml = noteHtml + "</div>";
	noteHtml = noteHtml + "</div>";
	return noteHtml;	
}

Annotate.prototype.getNoteHtmlContent = function(note){
	var annotateIcon = "/os/img/apps_annotate.gif";
	var noteHtmlContent = "";
		noteHtmlContent += "<div class=\"layersOS_annotate\" id=\"" + note._semilla + "\">";
		noteHtmlContent += "  <input type=\"hidden\" name=\"layerOS_semilla\" class=\"layerOS_semilla\" value=\"" + note._semilla + "\">";
		noteHtmlContent += "  <input type=\"hidden\" name=\"layerOS_highlight\" class=\"layerOS_highlight\" value=\"" + note._highlight + "\">";
		noteHtmlContent += "  <input type=\"hidden\" name=\"layerOS_top\" class=\"layerOS_top\" value=\"" + note._top + "\">";
		noteHtmlContent += "  <input type=\"hidden\" name=\"layerOS_left\" class=\"layerOS_left\" value=\"" + note._left + "\">";
		noteHtmlContent += "  <div class=\"layersOS_annotate_menu layersOS_own layersOS_annotate_createover\">";
		noteHtmlContent += "      <div class=\"layersOS_annotate_menu_icon layersOS_object_type_video layersOS_own layersOS_annotate_createover\"><img style=\"\" width=\"24\" height=\"24\" src=\"" + annotateIcon + "\"/></div>";
		noteHtmlContent += "   	  <a style=\"display: none;\" class=\"layersOS_annotate_maximize_link\" href=\"#\" onclick=\"return false;\"><img src=\"/os/apps/Annotate/css/images/annotate_maximize.gif\"/></a>";
		noteHtmlContent += "   	  <a style=\"display: inline;\" class=\"layersOS_annotate_minimize_link\" href=\"#\" onclick=\"return false;\"><img src=\"/os/apps/Annotate/css/images/annotate_minimize.gif\"/></a>";
		noteHtmlContent += "   	  <a class=\"layersOS_annotate_close_link\" href=\"#\" onclick=\"return false;\"><img width=\"11\" height=\"16\" src=\"/os/apps/Annotate/css/images/annotate_close.gif\"/></a>";
		noteHtmlContent += "  </div>";
		noteHtmlContent += "   <div class=\"layersOS_annotate_content layersOS_own\">";		
		noteHtmlContent += "   		<div class=\"layersOS_annotate_content_media\" style=\"display: none;\"></div>";
		noteHtmlContent += "		<div class=\"layersOS_annotate_content_text\"></div>";
		noteHtmlContent += "  	</div>";					                
		noteHtmlContent += "</div>";		
	return noteHtmlContent; 
}

Annotate.prototype.getMaxZIndex = function(){
	var zmax = 0;
    $( '.note_scroll_class' ).each(function() { 
    	var cur =  $( this ).css( 'zIndex');
        zmax = cur > zmax ? $( this ).css( 'zIndex') : zmax;
		$( this )[0].style.zIndex = '8000';
	});
	if(zmax != 0) zmax = parseInt(zmax)+2;
	else zmax = 8002;
	return zmax;	
}

Annotate.prototype.makeSeedGroup = function(){
	this._currentSeed = 'seed_' + new Date().getTime();
	this._displayable.append('<div class="seed seed_annotate" id="' + this._currentSeed  + '"></div>');
}

Annotate.prototype.putContent = function(note){
	//Before put the content we resize the note until the max width
	$('#container_' + note._semilla).css({width: '390px'});
	
	//Note._content = createHyperlinks(Note._content);
	//Put the media content
	if (note._content.length > 0 && note._content != 'null') {
		$('#' + note._semilla + ' .layersOS_annotate_content_text').show();
		$('#' + note._semilla + ' .layersOS_annotate_content_text').empty();
		if(note._content_type=='text')
			$('#' + note._semilla + ' .layersOS_annotate_content_text').append(Utils.prototype.createHyperlinks(note._content.htmlEntities().replace(/\r\n|\n/g,"<br />")));
		else if(note._content_type=='html')
			$('#' + note._semilla + ' .layersOS_annotate_content_text').append(note._content);
	}
	else{
		$('#' + note._semilla + ' .layersOS_annotate_content_text').hide();
	}	
	
	//Put the media content
	if (note._content_media.length > 0 && note._content_media != 'null') {
		$('#' + note._semilla + ' .layersOS_annotate_content_media').show();
		$('#' + note._semilla + ' .layersOS_annotate_content_media').empty();
		$('#' + note._semilla + ' .layersOS_annotate_content_media').append(note._content_media);	
	}
	//Calculate the new size
	this.resizeNote(note._semilla);
}

Annotate.prototype.addEventsToNote = function(note){
	var me = this;
	//Minimize
	$('#' + note._semilla + ' .layersOS_annotate_minimize_link').click(function(){
		var idDiv='div_canvas_' + note._semilla;
		if ($('#' + idDiv).length > 0) {
			$('#' + idDiv).remove();
		}
		$('#' + note._semilla + ' .layersOS_annotate_menu_icon > img')[0].src = "/os/img/apps_annotate.gif";			
		$('#' + note._semilla + ' .layersOS_annotate_maximize_link').css({display:'inline'});
		$('#' + note._semilla + ' .layersOS_annotate_minimize_link').css({display:'none'});
		$('#' + note._semilla + ' .layersOS_annotate_content').fadeOut('slow');
		$('#container_' + note._semilla).css({height:'0px'});
	});				
	
	//Maximize
	$('#' + note._semilla + ' .layersOS_annotate_maximize_link').click(function(){
		$('#' + note._semilla + ' .layersOS_annotate_menu_icon > img')[0].src = "/images/nouser.jpg";;
		$('#' + note._semilla + ' .layersOS_annotate_minimize_link').css({display:'inline'});
		$('#' + note._semilla + ' .layersOS_annotate_maximize_link').css({display:'none'});
		$('#' + note._semilla + ' .layersOS_annotate_content').fadeIn('slow');
		//Resize
		me.resizeNote(note._semilla);
	});		
	
	if (note._editable) {
		//Close and delete
		$('#' + note._semilla + ' .layersOS_annotate_close_link').click(function(){
			note.removeObject();
		});
	}
	me.putContent(note);

	//Click zIndex
	$('#' + note._semilla).click(function(){
		zmax = me.getMaxZIndex();
		$('#' + note._seed + ' .note_scroll_class').each(function(){
			this.style.zIndex = zmax-1;
		});
		$(this).parent().parent()[0].style.zIndex = zmax;
	});		
	//Draggable		
	me.convertDraggable(note);	
}

Annotate.prototype.convertDraggable = function(note){
		var idContainer='container_' + note._semilla;
		var idDiv='div_canvas_' + note._semilla;
		var idAnclaje = 'anc_' + note._semilla;
		if($('#' + note._semilla + ' .layerOS_highlight')[0].value.length > 0) note._floating = false;
		var me = this;
		
		var noteWidth = $('#' + idContainer).width();
		
		var x = $('#' + idContainer).draggable({
		containment: [0, 25, $('body').width() - noteWidth, $('body').height()],
		handle: '.layersOS_annotate_menu_icon',
		scroll: true,
		stack: { group: '.note_container', min: 1 },		
		start: function() {
			//Put a transparent div over the whole page to avoid Iframe event robbery
			$('#layersOS_transparentHelper').css({display: 'block'});		
			if ($('#' + idDiv).length > 0) {
				$('#' + idDiv).remove();
			}
		},
		stop: function(event, ui) {
			if($('#' + note._semilla + ' .layerOS_highlight')[0].value.length > 0) note._floating = false;			
			//Hide the transparent div
			$('#layersOS_transparentHelper').css({display: 'none'});
			
			pos = findPos($('#' + idAnclaje)[0]);
			topMoved = ui.position.top;
			leftMoved = ui.position.left;							
		}
	});
}

Annotate.prototype.resizeNote = function(semilla){
	//var newHeight = $('#' + semilla + ' .layersOS_annotate_content').css('height');
	//newHeight = parseInt(newHeight.replace('px',''));// + 48;
	var newHeight = $('#' + semilla)[0].clientHeight;
	var newWidth = $('#' + semilla)[0].clientWidth + 24;

	$('#container_' + semilla).css({width: newWidth+'px', height: newHeight +'px'});
}

Annotate.prototype.clear = function(){
	for (var i=0; i < this._notes.length ; i++){
		this._notes[i].removeObject();
	}	
}

function getWindowTopScrollOffset()
{
	 if(window.pageYOffset){
		return window.pageYOffset;
	 }
	 else {
		return  Math.max(document.body.scrollTop, document.documentElement.scrollTop);
	 }
}

function getWindowLeftScrollOffset()
{
	 if(window.pageXOffset){
		return window.pageXOffset;
	 }
	 else {
		return  Math.max(document.body.scrollLeft, document.documentElement.scrollLeft);
	 }
}

function findPos(obj){	
	if(!$.browser.safari)return [parseInt(obj.getBoundingClientRect().left), parseInt(obj.getBoundingClientRect().top)];
	var curleft = curtop = 0;
	//var el = obj;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
		while (obj = obj.offsetParent);
	}
	return [curleft, curtop];
}


String.prototype.htmlEntities = function () {
   return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}

function Utils(){
	
}

Utils.prototype.createHyperlinks = function(text)
{
    var txt = text.replace(/(http|ftp|https):\/\/([\w\-_]+(\.[\w\-_]+)+)([\w\-\.,@?^=%&amp;:\/~\+#]*[\w\-\@?^=%&amp;\/~\+#])/gim,'<a href="$&" title="$&" target="_blank">$2</a>');
	return txt;
}

function embedVideo(url,width,height)
{	
	if(url.length<=0) return '';
	//For internal use of media content
	var semilla = new Date().getTime();
	//Parse url
	var strEmbed = '<b id="video_embed_' + semilla +'">Video site not suported</b>';
	if (!url) return strEmbed;

	var res = (new RegExp( ":\/\/(.[^/]+)", "i" )).exec(url);
	var domain = res[1].split(".");
	domain = domain[domain.length-2] + "." + domain[domain.length-1] ;
	
	switch (domain){
		case 'google.com':
			var docid = (new RegExp( "\\?docid=([0-9]+)", "i")).exec(url);
			if(width==null || width=='') width = '390';
			if(height==null || height=='') height = '324';
			if (docid) strEmbed = '<embed id="video_embed_' + semilla + '" src="http://video.google.com/googleplayer.swf?docid=' + docid[1] + '&hl=es&fs=true" style="width:' + width + 'px;height:' + height + 'px" allowFullScreen="true" allowScriptAccess="always" wmode="transparent" type="application/x-shockwave-flash"> </embed>';
			break;
			
		case 'veoh.com':
			var videos = (new RegExp( "videos\/([a-z0-9]+)", "i" )).exec(url);
			if(width==null || width=='') width = '390';
			if(height==null || height=='') height = '324';			
			if (videos) strEmbed = '<embed id="video_embed_' + semilla + '" src="http://www.veoh.com/veohplayer.swf?permalinkId=' + videos[1] + '&id=12231543&player=videodetailsembedded&videoAutoPlay=0" allowFullScreen="true" width="' + width + '" height="' + height + '" bgcolor="#FFFFFF" type="application/x-shockwave-flash" wmode="transparent" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>';
			break;
			
		case 'metacafe.com':			
			var params = (new RegExp( "/watch/([a-z0-9\-]+)/([^/]+)", "i")).exec(url);
			if(width==null || width=='') width = '390';
			if(height==null || height=='') height = '324';
			if (params) strEmbed = '<embed id="video_embed_' + semilla + '" src="http://www.metacafe.com/fplayer/' + params[1] + '/' + params[2] + '.swf" width="' + width + '" height="' + height + '" wmode="transparent" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"> </embed>';
			break;
			
		case 'vimeo.com':
			var id = (new RegExp( "/([0-9]+)" )).exec(url);
			if(width==null || width=='') width = '390';
			if(height==null || height=='') height = '324';						
			strEmbed = '<embed id="video_embed_' + semilla + '" src="http://vimeo.com/moogaloop.swf?clip_id=' + id[1] + '&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1" type="application/x-shockwave-flash" allowfullscreen="true" wmode="transparent" allowscriptaccess="always" width="' + width + '" height="' + height + '"></embed>';
			break;
			
		case 'youtube.com':
			var id = (new RegExp( "[\\?&]v=([^/&]+)" , "i" )).exec(url);
			if(width==null || width=='') width = '390';
			if(height==null || height=='') height = '324';									
			strEmbed = '<embed id="video_embed_' + semilla + '" src="http://www.youtube.com/v/' + id[1] + '" type="application/x-shockwave-flash" allowscriptaccess="always" wmode="transparent" allowfullscreen="true" width="' + width + '" height="' + height + '"></embed>';					
			break;	
			
		case 'dailymotion.com':
			//var params = (new RegExp( "/video/([a-z0-9\-]+)", "i")).exec(url);
			if(width==null || width=='') width = '390';
			if (params) strEmbed = '<embed src="'+url+'" type="application/x-shockwave-flash" width="' + width + '" allowFullScreen="true" allowScriptAccess="always"></embed>';
			break;
	}
	
	return(strEmbed);
	
}