/*
 * $Revision: 1.33 $
 * $Date: 2007/03/20 14:46:27 $
 */

var cumulativeOffset = function(element) {
	var valueT = 0, valueL = 0;
	do {
		valueT += element.offsetTop  || 0;
		valueL += element.offsetLeft || 0;
		element = element.offsetParent;
	} while (element);
	return [valueL, valueT];
};


function getViewportScrollY() {
  var scrollY = 0;
  if( document.documentElement && document.documentElement.scrollTop ) {
    scrollY = document.documentElement.scrollTop;
  }
  else if( document.body && document.body.scrollTop ) {
    scrollY = document.body.scrollTop;
  }
  else if( window.pageYOffset ) {
    scrollY = window.pageYOffset;
  }
  else if( window.scrollY ) {
    scrollY = window.scrollY;
  }
  return scrollY;
};

function Anotacao ( bean ) {
	
	var x1 = bean.topX;
	var y1 = bean.topY;
	var x2 = bean.bottomX;
	var y2 = bean.bottomY;
	var text = bean.text;
	if(bean.ownerName != undefined) {
		text = text + ' - ' + bean.ownerName;
	}
	
	this.id = (bean.idAnotacao || null); 
	this.isEditable = false; 
	
	if (Anotacao.flog.isEditorExcluirAnotacao || bean.owner || bean.isAdministradorFotolog || bean.isDonoFoto ) {
		this.isEditable = true;
	}

	// out
	this.out = document.createElement('div');
	this.out.style.zIndex = Anotacao.zIndex++;
	this.out.className = 'anotacao';
	this.out.style.left = x1 + 'px';
	this.out.style.top = y1 + 'px';
	
	this.out.onmousedown = this.onMouseDown.bindAsEventListener(this);
	this.out.onclick = this.onClick.bindAsEventListener(this); //function() {return false;}
	this.out.onmouseover = this.onMouseOver.bindAsEventListener(this);
	this.out.onmouseout = this.onMouseOut.bindAsEventListener(this);

	// inner
	this.inner = document.createElement('div');
	this.inner.className = 'interno';
	this.inner.style.width = ( x2 - x1 )+ 'px';
	this.inner.style.height = ( y2 - y1 ) + 'px';
	
	this.out.appendChild(this.inner);
	this.mensagemVazia = true;
	
	//Criando handlers
	this.addHandler( 'lt' );
	this.addHandler( 'lb' );
	this.addHandler( 'rt' );
	this.addHandler( 'rb' );
	
	if ( this.isEditable) {
		this.out.appendChild(this.addButton('x', this.onDelete));
	}
	
/* box of addition information */

	this.edit = document.createElement('div');
	this.edit.className = 'detalhes';
	this.edit.style.display = 'none';
	
	var em = document.createElement('em');
	em.innerHTML = 'Escreva sua mensagem';
	this.edit.appendChild(em);
	this.edit.appendChild( document.createElement('br') );	

	
	this.textarea = document.createElement('textarea');
	this.textarea.onkeypress = this.onKeyUp.bind(this);
	this.textarea.onfocus = this.onFocus.bind(this);	
	this.textarea.onkeydown = this.onKeyUp.bind(this);
	this.textarea.value = text;

	
	this.edit.appendChild( this.textarea );
	this.edit.appendChild( document.createElement('br') );
	
	this.saveBtn = this.addButton('SALVAR', this.onSave);
	this.edit.appendChild( this.saveBtn );
	this.edit.appendChild(this.addButton('CANCELAR', this.onCancel) );
	//this.edit.appendChild(this.addButton('Deletar', this.onDelete) );

	this.span = document.createElement('span');
	this.span.innerHTML = text;
	this.edit.appendChild(this.span);

	this.updateEdit();

	//Adiciona na area 
	Anotacao.add( this.out );
	Anotacao.add( this.edit );
};

Anotacao.prototype.onFocus = function() {
	if ( this.mensagemVazia ) {
		this.textarea.value = '';
		this.textarea.onfocus = null;
		this.mensagemVazia = false;
	}
}

Anotacao.prototype.rebuild = function (){
	this.out.appendChild(this.addButton('x', this.onDelete));
}

Anotacao.prototype.addButton = function(label, onclick) {
	var button = document.createElement('input');
	button.type = 'button';
	button.className = 'botao3';
	button.value = label;
	button.onclick = onclick.bind(this);
	return button;	
}

Anotacao.prototype.onClick = function( ev ) {
	this.out.style.zIndex = Anotacao.zIndex++;
	return false;
}

Anotacao.prototype.onKeyUp = function( event ) {
	setTimeout( this.onKeyUpTimeout.bind(this), 100);
}

Anotacao.prototype.onKeyUpTimeout = function() {
	if ( this.textarea.value.trim().length == 0 ) {
		Element.addClassName(this.saveBtn, 'off');
	} else {
		Element.removeClassName(this.saveBtn, 'off');
	}
	if ( this.textarea.value.length > 60 ) {
		this.textarea.value = this.textarea.value.substr(0,60);
	}
}


/* STATIC */
Anotacao.editando = null;
Anotacao.zIndex = 1000;

Anotacao.init = function( area, flog, hasAnotacao ) {
	this.flog = flog;
	this._area = document.getElementById(area);
	this._area.className = 'invisible';
	
	var over = document.getElementById('boxFoto');

	over.onmouseover = this.onMouseOver.bind(this);
	over.onmouseout = this.onMouseOut.bind(this);

	this._info = document.createElement('div');
	this._info.style.display = 'none';
	this._info.id = 'info';
	var img = document.createElement('img');
	img.src = '/estatico/imagens/carregando_gif.gif';
	this._info.appendChild(img);
	this._info_span = document.createElement('span');
	this._info_span.innerHTML = '';
	this._info.appendChild(this._info_span);

	this._dimensions = cumulativeOffset(this._area);
	this._area.appendChild(	this._info );
	if ( Anotacao.editando ) {
		Anotacao.editando.clear();
		delete Anotacao.editando;
		Anotacao.editando = null;
	}
	//Carrego as anotacoes
	if ( hasAnotacao ) {
		Fotolog.loadNotes(flog.albumId, flog.fotologId, flog.fotoId, this.onLoad.bind(this));
	}
}

Anotacao.onLoad = function( json ) {
	for ( var i = 0; i < json.length; i++ ) {
		new Anotacao( json[i] );	
	} 
}

Anotacao.getHeight = function() {
	return this._area.offsetHeight;
}

Anotacao.disable = function() {
	this._disabled = true;
	Element.addClassName(this._area, 'invisible');
}

Anotacao.enable = function () {
	this._disabled = false;
	
}

Anotacao.showInfo = function( text ) {
	document.getElementById('area').className = 'saving';
	this._info.style.display = 'block';
	this._info_span.innerHTML = text;
}

Anotacao.hideInfo = function() {
	this._info.style.display = 'none';
}

Anotacao.onMouseOver = function() {
	if ( this._disabled ) { 
		return;
	}
	
	if ( !this.editando ) {
		Element.removeClassName(this._area, 'invisible');
	}
}	
		


Anotacao.onMouseOut = function() {
	if ( !this.editando ) {
		Element.addClassName(this._area, 'invisible');
	}
}

Anotacao.getClientPosition = function( e ) {	
	//var area = cumulativeOffset(document.getElementById('area'));
	return [e.clientX - this._dimensions[0], (e.clientY+getViewportScrollY()) - this._dimensions[1]];
}

Anotacao.add = function( anotacao ) {
	this._area.appendChild( anotacao )
}


Anotacao.save = function( anotacao ) {
	anotacao.setEditMode(false);

	this.showInfo('Salvando');
	anotacao.setText( anotacao.getInputText() );
	if ( anotacao.id == null ) {
		this._saving = anotacao;
		var x = anotacao.getX();
		var y = anotacao.getY();
		var x2 = anotacao.getX2();
		var y2 = anotacao.getY2();
		Fotolog.addNote(this.flog.fotologId, this.flog.albumId, this.flog.fotoId, anotacao.getInputText(), x, y, x2, y2,this.onSave.bind(this)); 
	}
}

Anotacao.onSave = function( json ) {
	this.hideInfo();
	document.getElementById('area').className = '';		
	if ( json.STATUS == 'ERRO' ) {
		Anotacao.remove(this._saving)
		Erro(json.ERROR);	
	} else {
		try {
			this._saving.id = json.anotacaoID;
			this._saving.rebuild();
		} catch( e ) {};
	}
	this._saving = null; 
}

Anotacao.remove = function( anotacao ) {
	anotacao.setEditMode(false);
	
	if ( anotacao.id != null ) {
		this.showInfo('Removendo');
	}

	anotacao.clear();
	delete anotacao;
	
	if ( anotacao.id == null ) {
		this.onRemove.bind(this);
	} else {
		Fotolog.removeNote( this.flog.albumId, anotacao.id, this.flog.fotoId, this.onRemove.bind(this) ); 		
	}
}

Anotacao.onRemove = function() {
	this.hideInfo();
	document.getElementById('area').className = '';
}


/* PROTOTYPE */




/* cria uma nova anotação randomica */
Anotacao.addRandom = function () {
	if ( Anotacao.editando ) {
		return;
	}

	//Algumas vezes o album não é carregado
	if ( !this._area ) {
		try {
			Anotacao.init( document.getElementById('area'), MenuFoto.flog );
		} catch ( e ) {console.debug(e); }
	}

	var h = this._area.clientHeight;
	if ( this._area.offsetHeight > 0 ) {
		h = this._area.offsetHeight;
	}
	
	var w = this._area.clientWidth;
	if ( this._area.offsetWidth > 0 ) {
		w = this._area.offsetWidth;
	}

	var quarter = Math.ceil( Math.min(h, w)/4 );
	var d = Math.ceil(Math.random() * quarter) + quarter;
	var x = Math.ceil(Math.random() * w/2);
	var y = Math.ceil(Math.random() * h/2);

	var rand = {
		idAnotacao:null,
		topX:x,
		topY:y,
		bottomX:x+d,
		bottomY:y+d,
		text:"Seu texto aqui"
	};
	var n = new Anotacao( rand );
	n.setEditMode(true);
	n.updateEdit();
	try { MenuFoto.onClose(); } catch(e) {};
};


Anotacao.clear2 = function() {
	if ( Anotacao.editando ) {
		//Anotacao.editando.clear();
		//Anotacao.editando = null;
		Anotacao.remove(Anotacao.editando);
	}
}

Anotacao.addNew = Anotacao.addRandom;

Anotacao.prototype.onMouseOver = function() {
	Anotacao.onMouseOver();
	if ( !this.editMode && Anotacao.editando == null ) {
		this.out.className = 'anotacao_hover';
		this.edit.style.display = '';
		this.updateEdit();
	}
}

Anotacao.prototype.onMouseOut = function() {
	Anotacao.onMouseOver();
	if ( !this.editMode && Anotacao.editando == null  ) {
		this.out.className = 'anotacao';
		this.edit.style.display = 'none';
	}
}

Anotacao.prototype.updateEdit = function() {
	var h = Anotacao.getHeight();

	var h1 = parseInt(this.out.style.top) + parseInt(this.inner.style.height);
	
	this.edit.style.left = parseInt(this.out.style.left) + 'px';
	
	var margem = 5;
	
	var hw;
	if ( this.editMode ) {
		hw = this.edit.offsetHeight;
	} else {
		hw = this.span.clientHeight;
	}
	
	if ( ( h - h1 ) < ( margem + hw ) ) { // && Anotacao.editando != null ) {
		this.edit.style.top  = parseInt(this.out.style.top) - ( hw + margem ) + 'px';		
	} else {
		this.edit.style.top  = parseInt(this.out.style.top) + parseInt(this.inner.style.height) + margem + 'px';
	}

}

/* lt, lb, rt, rb */
Anotacao.prototype.addHandler = function( name ) {
	var hn = document.createElement('div');
	hn.className = name;	
	hn.onmousedown = this.onHandlerClick.bindAsEventListener(this);
	var span = document.createElement('span');
	hn.appendChild(span);
	this.inner.appendChild( hn );
}


/* quando o box é clicado */
Anotacao.prototype.onMouseDown = function(event) {

	if ( Anotacao.editando && Anotacao.editando != this && this.isEditable ) {
		return;
	}
	if ( Anotacao.editando != this ) return;
	Anotacao.editando = this;

	this.setEditMode( true );
	
	this._offset = {x:(event.clientX - this.out.offsetLeft), y:(event.clientY - this.out.offsetTop)};
	document.onmousemove = this.onDrag.bindAsEventListener(this);
	document.onmouseup = this.onDragStop.bindAsEventListener(this);
}

Anotacao.prototype.onDrag = function(event) {

	var max_w = this.out.parentNode.offsetWidth - parseInt(this.inner.style.width);
	var max_h = this.out.parentNode.offsetHeight - parseInt(this.inner.style.height);

	this.out.style.left = Math.min(Math.max((event.clientX - this._offset.x), 0), max_w - 6) + 'px';
	this.out.style.top =  Math.min(Math.max((event.clientY - this._offset.y), 0), max_h - 6) + 'px';
	this.updateEdit();

	return false;
}

Anotacao.prototype.onDragStop = function(event) {
	document.onmousemove = null;
}


Anotacao.prototype.setEditMode = function( bool ) {
	this.editMode = bool;
	this.updateEdit();
	if ( bool ) {
		Element.addClassName(Anotacao._area, 'invisible');
		this.out.className = 'anotacao_edit';
		this.edit.className = 'detalhes_edit';
		this.edit.style.display = 'block';
		Anotacao.editando = this;
	} else {
		Element.removeClassName(Anotacao._area, 'invisible');
		this.out.className = 'anotacao';
		this.edit.className = 'detalhes';
		this.edit.style.display = 'none';
		Anotacao.editando = null;
	}
}

Anotacao.prototype.setText = function( text ) {
	this.span.innerHTML = text;
}

Anotacao.prototype.getInputText = function() {
	return this.textarea.value;
}

Anotacao.prototype.getX = function() {
	return Math.max(1 ,parseInt(this.out.style.left||1));
}

Anotacao.prototype.getY = function() {
	return Math.max(1 ,parseInt(this.out.style.top||1));
}

Anotacao.prototype.getX2 = function() {
	return this.getX() + this.getWidth();	
}

Anotacao.prototype.getY2 = function() {
	return this.getY() + this.getHeight();	
}


Anotacao.prototype.getWidth = function() {
	return parseInt(this.inner.style.width);
}

Anotacao.prototype.getHeight = function() {
	return parseInt(this.inner.style.height);
}


Anotacao.prototype.onSave = function() {
	if ( this.textarea.value.trim().length > 0 ) {
		Anotacao.save( this );
	}
}

Anotacao.prototype.onCancel = function() {
	this.setEditMode(false);
	Anotacao.remove(this);
}

Anotacao.prototype.onDelete = function() {
	Anotacao.remove( this );
}

Anotacao.prototype.clear = function() {

	this.textarea.parentNode.removeChild( this.textarea );
	this.textarea = null;
	
	this.span.parentNode.removeChild( this.span );
	this.span = null;

	this.edit.parentNode.removeChild( this.edit );
	this.edit = null;

	this.out.parentNode.removeChild( this.out );
	this.out = null;
	
	this.inner.parentNode.removeChild( this.inner );
	this.inner = null;
}


Anotacao.prototype.onHandlerClick = function( e ) {
	this._offset = {x:(e.clientX - this.out.offsetLeft), y:(e.clientY - this.out.offsetTop)};
	var target = (e.target)?e.target:e.srcElement;
	this.handler = target.className;
	//document.onmousemove = this['onDrag' + name.toUpperCase()].bindAsEventListener(this);
	document.onmousemove = this.onDragHandler.bindAsEventListener(this);
	document.onmouseup = function() {document.onmousemove = null};
}

Anotacao.prototype.onDragHandler = function(e) {

	var client = Anotacao.getClientPosition(e);

	/* horizontal */
	/* left */
	if ( this.handler.charAt(0) == 'l' ) {
		
		var left = parseInt(this.out.style.left||0);
		var w = parseInt(this.inner.style.width);		

		var deltaX = left - client[0];
		
		//Aumentando
		if ( deltaX > 0 && left > 0 ) {
			var novo_left = Math.max(left-deltaX, 0);
			var novo_width = w + deltaX;
			if ( left-deltaX < 0) { 
				novo_width += (left-deltaX);
			}
			this.out.style.left = novo_left + 'px';
			this.inner.style.width =  novo_width + 'px';

		//Diminuindo
		} else if ( deltaX < 0 && w > 25 ) {
			var novo_width = Math.max(w + deltaX, 25);
			var novo_left = Math.max(left-deltaX , 0);
			if ( ( w + deltaX ) < 25 ) {
				novo_left -= 25 - (w + deltaX)
			}
			this.out.style.left = novo_left + 'px';
			this.inner.style.width =  novo_width + 'px';			
		}

	/* right */
	} else {
		
		
		var left = parseInt(this.out.style.left||0);
		var w = parseInt(this.inner.style.width);		
		var right = (left + w);
		var deltaX = client[0] - right;
		
		//Aumentando
		if ( deltaX > 0  ) {
			var ow = this.out.parentNode.offsetWidth;
			
			var max = ow - parseInt(this.out.style.left||0) - 6;
			var novo_width = Math.min(w + deltaX, max);
			this.inner.style.width =  novo_width + 'px';
			
		//Diminuindo
		} else if ( deltaX < 0 && w > 25 ) {
			var novo_width = Math.max(w + deltaX, 25);
			this.inner.style.width =  novo_width + 'px';
		}
	
	}

	/* vertical */
	/* top */
	if ( this.handler.charAt(1) == 't' ) {
	

		var top = parseInt(this.out.style.top||0);
		var h = parseInt(this.inner.style.height);

		var deltaY = top - client[1];
		
		//Aumentando
		if ( deltaY > 0 && top > 0 ) {
			var novo_top = Math.max(top-deltaY, 0);
			var novo_height = h + deltaY;
			if ( top-deltaY < 0) { 
				novo_height += (top-deltaY);
			}
			this.out.style.top = novo_top + 'px';
			this.inner.style.height =  novo_height + 'px';

		//Diminuindo
		} else if ( deltaY < 0 && h > 25 ) {
			var novo_height = Math.max(h + deltaY, 25);
			var novo_top = Math.max(top-deltaY , 0);
			if ( ( h + deltaY ) < 25 ) {
				novo_top -= 25 - (h + deltaY)
			}
			this.out.style.top = novo_top + 'px';
			this.inner.style.height =  novo_height + 'px';
		}
		
	/* bottom */
	} else {
	
		var top = parseInt(this.out.style.top||0);
		var h = parseInt(this.inner.style.height||0);		
		var bottom = (top + h);
		var deltaY = client[1] - bottom;
		
		//Aumentando
		if ( deltaY > 0  ) {
			var max = this.out.parentNode.offsetHeight - parseInt(this.out.style.top) - 6;
			var novo_height = Math.min(h + deltaY, max);
			this.inner.style.height =  novo_height + 'px';
		//Diminuindo
		} else if ( deltaY < 0 && h > 25 ) {
			var novo_height = Math.max(h + deltaY, 25);
			this.inner.style.height =  novo_height + 'px';
		}	
		
	}
	this.updateEdit();
} 

