

function setActiveStyleSheet(title) {
  var i, a, main;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
      a.disabled = true;
      if(a.getAttribute("title") == title) a.disabled = false;
    }
  }
}

function safeInnerHtml( node, isTextArea ) {
	try {
		var text = '';
		for ( var i = 0; i < node.childNodes.length;i++ ){
			var n = node.childNodes[i];
			switch ( n.nodeType ) {
				case 1:
					if ( n.nodeName == 'BR' && isTextArea ) {
						text += "\n";
					} 	
					break;
				case 3:
					text += n.nodeValue.replace("\n", ""); //evitar \n duplicados
					break;
			}
		}
		return text;
	} catch (e) {
		return node.innerHTML;
	}
}


f8p = {};


f8p.flog = {
	open:function ( picture, album ) {
		document.location = (document.location+"").split('#')[0] + '#'+picture+';'+album;
	}
};

String.prototype.wordWrap = function(m, b, c){
	var i, j, l, s, r = this.split("\n");
	if(m > 0) for(i = -1, l = r.length; ++i < l;){
		for(s = r[i], r[i] = ""; s.length > m;
			j = c ? m : (j = s.substr(0, m).match(/\S*$/)).input.length - j[0].length
			|| j.input.length + (j = s.substr(m).match(/^\S*/)).input.length + j[0].length,
			r[i] += s.substr(0, j) + ((s = s.substr(j)).length ? b : "")
		);
		r[i] += s;
	}
	return r.join("\n");
};

f8p.util = {
	/* 
	 * Registra o onkeydown de um input a um span - ele utiliza o maxLengh para autalizar 
	 * os caracteres restantes - Colocar no window.onload
     * @author: Falcão
     */
	updateRest:function( input, span , maxlength) {
		var input = document.getElementsByName(input)[0];
		var plength = input.maxLength;
		if (maxlength) plength = maxlength;
	    
		glb.dom.addEvent('keyup', input, function() {
			setTimeout( function() {
				document.getElementById(span).innerHTML = plength - this.value.length;	
			}.bind(this), 100);
		});
		document.getElementById(span).innerHTML = plength - input.value.length;	
	},
	restrict:function( inputName ) {
		var input = document.getElementsByName( inputName )[0];
		input.onkeypress = function( event ) {
			var e = event || window.event;
			var code = e.keyCode || e.charCode;
			switch ( code ) {
				case 8:		
				case 13:
				case 9:
				case 0:
				return true;
			}
			var reg = new RegExp("^[a-zA-Z0-9_]{1}$");
			return reg.test( String.fromCharCode( code ) );		
		}
	},
	/* converte login para url de acordo com regra */
	convert:function( palavra ) {
		//Declaração dos domínios de validação
		var invalidos = 'àá@äãâªß©ç¢êéèë&ìíîïñõòóôöø®$ùúûüýÿ'
		var validos   = 'aaaaaaabccceeeeeiiiinoooooorsuuuuyy'
		//var caracteresIniciais  = 'abcdefghijklmnopqrstuvwxyz'
 
		palavra = palavra.toLowerCase();
		var ret = '';
		var reg = new RegExp('[a-z0-9]{1}');
		for ( var i = 0; i < palavra.length; i++ ) {
			var ch = "" + palavra.charAt(i);
			if ( !ch.match( reg ) ) {
				var n = invalidos.indexOf( ch );
				if ( n == -1 ) {
					continue;
				}
				ch = validos.charAt(n);
			}
			ret += ch;
		}
	 	return ret;
	},
	/* <textarea onkeydown="return limitLength(this, 1000)"></textarea>*/
	
	limitLength:function( obj, maxLength ) {
		if ( obj.value.length > maxLength ) {
			obj.value = obj.value.substr(0, maxLength);
			return false;			
		}
		return true;
	}
	
}; //f8p.util



/*
 * Inline
 * textoVazio = Texto que aparece quando o campo é vazio - se textoVazio == null ou false não permite vazio
 * unico : apenas um poderá ser editado por vez
 **/
f8p.Inline = function( target, targetId, f, textoVazio, textarea, maxLength, unico ) {
	
	this._id = targetId
	this._function = f;
	this._name = target;
	var div = glb.dom.$(target);
	
	this.maxLength = maxLength || 30;
	this.unico = unico || false;


	if ( textoVazio ) {
		this._textoVazio = textoVazio;
	} else {
		this._textoVazio = false;
	}

	this._textarea = textarea || false;
	
	var text = safeInnerHtml(div, this._textarea);
	div.innerHTML = '';

	if ( this._textarea ) {
		this._h1 = document.createElement('p');
	} else {
		this._h1 = document.createElement('h1');
	}

	this._h1.onmouseover = this.onMouseOver.bind(this);
	this._h1.onmouseout = this.onMouseOut.bind(this);
	this._h1.onclick = this.onEditar.bind(this);			
	this.setText( text );
	div.appendChild(this._h1);


	this._span = document.createElement('span');
	this._span.style.display = 'none';
	this._span.innerHTML = 'Clique para editar';
	div.appendChild(this._span);
		
	this._editar = document.createElement('div');
	this._editar.style.display = 'none';
	
	if ( this._textarea ) {
		this._input = document.createElement('textarea');
		this._input.onkeydown = this.onKeyDown.bind(this);
		this._input.onkeyup = this.onKeyUp.bind(this);
		//TODO: MaxLength
		this._editar.appendChild(this._input);
	} else {
		this._input = document.createElement('input');
		this._input.maxLength = this.maxLength;
		this._input.type = 'text';
		this._input.onkeydown = this.onKeyDown.bind(this);
		this._editar.appendChild(this._input);
	}
	

	
	var cancel = document.createElement('a');
	cancel.className = 'gBotao';	
	cancel.innerHTML = 'CANCELAR';
	cancel.onclick = this.onCancel.bind(this);
	this._editar.appendChild(cancel);

	var save = document.createElement('a');
	save.className = 'gBotao';
	save.innerHTML = 'SALVAR';
	save.onclick = this.onSave.bind(this);
	this._editar.appendChild(save);
	div.appendChild(this._editar);
};



//f8p.Inline.edit = false;

f8p.Inline.prototype = {
	setText:function( text ) {
		if ( text.trim().length == 0 ) {
			if ( this._textoVazio ) {
				this._h1.style.fontStyle = 'italic';
				this._setText( this._textoVazio );
				this._restore = '';
			} else {
				//Restore
				this._h1.style.fontStyle = '';
				this._setText( this._restore );
			}
		} else {
			this._h1.style.fontStyle = '';
			this._setText( text );
			this._restore = text;
		}
	},
	isEmpty:function() {
		return ( this._h1.style.fontStyle == 'italic' );
	},
	onSave:function() {
		var txt = this._input.value;
		
		this._txt = txt;
 
		if ( !this._textoVazio && txt.trim().length == 0 ) {
			glb.dom.show( this._h1 );
			glb.dom.hide( this._editar );
			return;
		}
		
		var objeto = this;
		
		this._function( this._id, this._txt, this.update.bind(this));
		
		this._h1.className = 'saving';
		this._setText("salvando...");
		
		glb.dom.show( this._h1 );
		glb.dom.hide( this._editar );
	},
	_setText:function ( text ) {
		
		this._h1.innerHTML = '';

		var lines = (""+text).split("\n");
		for ( var i = 0; i < lines.length;i++ ) {
			this._h1.appendChild( document.createTextNode(lines[i]) );
			this._h1.appendChild( document.createElement('br'));
		}
	},
	onError:function(string) {
		//this.
	},
	onCancel:function() {
		this._h1.className = '';	
		glb.dom.show( this._h1 );
		glb.dom.hide( this._editar );
		//f8p.Inline.edit = false;
		f8p.Inline._editando = null;
	},
	update:function( json ) {
		if ( json.STATUS == 'OK' ) {
			this.setText( json.TEXTO );
		} else {
			if ( json.STATUS == 'ERRO' ) {
				Erro(json.ERROR);
			}
			this.setText( this._restore );
		}
		this._h1.className = '';
		f8p.Inline._editando = null;
		//f8p.Inline.edit = false;
	},
	onMouseOut:function() {
		if ( this._ti ) {
			clearTimeout( this._ti );
		}

		if ( this._h1.className == 'saving' ) {
			return;
		}
		this._h1.className = '';
		glb.dom.hide( this._span );
		//document.getElementById('content2').style.height = '';
	},

	onMouseOver:function() {
		this._ti = setTimeout( this.onMouseOverTimeout.bind(this), 300);
		return;
		//var h = document.getElementById('content2').clientHeight;
		if ( this._h1.className == 'saving' ) {
			return;
		}
		this._h1.className = 'hover';
		if ( this._h1.style.display != 'none' ) {
			glb.dom.show( this._span );
		}
		//document.getElementById('content2').style.height = h + 'px';
	},


	onMouseOverTimeout:function() {
		//var h = document.getElementById('content2').clientHeight;
		if ( this._h1.className == 'saving' ) {
			return;
		}
		this._h1.className = 'hover';
		if ( this._h1.style.display != 'none' ) {
			glb.dom.show( this._span );
		}
		//document.getElementById('content2').style.height = h + 'px';
	},
	onEditar:function() {
		if ( this._h1.className == 'saving' ) {
			return;
		}
		if ( this.isEmpty() ) {
			this._input.value = '';
		} else {
			var text = safeInnerHtml(this._h1, this._textarea);
			this._input.value = text;
		}

		if ( f8p.Inline._editando != null ) {
			f8p.Inline._editando.onCancel();
		}
		f8p.Inline._editando = this;
		f8p.Inline.edit = true;
		glb.dom.hide( this._span );
		glb.dom.hide( this._h1 );
		glb.dom.show( this._editar );
		this._input.focus();
	},
	onKeyUp:function( event ) {
		if ( this._input.value.length > this.maxLength ) {
			this._input.value = this._input.value.substr(0, this.maxLength);
		}
	},
	onKeyDown:function( event ) {
		var event = event || window.event;
		if ( event.keyCode == '27' ) { //ESC
			this.onCancel();
		} else if ( event.keyCode == 13 && !this._textarea ) { //enter
			this.onSave();
		}
	}
};




/*
 * f8p.service
 */
 
/* 
	f8p.service.flog.excluirFoto( 23 );
*/


/* 
		var aviso = new f8p.UI.ExcluirFoto();
		aviso.addListener({
			onConfirm:function() {
				var queryString = {fotoId:23};
				var ajx = new glb.Ajax('/service/excluirFoto', queryString );
				ajx.addListener( this );
				ajx.send();	
			}	
		});
	
		aviso.show();*/



var LiveForm = {
	clear:function( inputName ) {
		try {
			if ( typeof inputName == 'string' ) {
				var input = document.getElementsByName( inputName )[0];
			} else {
				var input = inputName;	
			}
			if ( input.nextSibling.nodeName == 'SPAN' ) {
				input.parentNode.removeChild( input.nextSibling );
			}
		} catch( e ) {}
	},
	erro:function( input, text ) {
		var span = this._span( text, 'erro');
		this._append(input, span);
	},		
	ok:function( input, text ) {
		var span = this._span( text, 'ok');
		this._append(input, span);
	},
	wait:function( input, text ) {
		var span = this._span( text, 'wait');
		this._append(input, span);
	},		
	_append:function( input, span ) {
		if ( input.nextSibling != null ) {
			if ( input.nextSibling.nodeName == 'SPAN' && glb.dom.hasClassName(input.nextSibling, 'msg') ) {
				if ( input.nextSibling.className != span.className ) {
					input.nextSibling.className = span.className;
				}
				input.nextSibling.innerHTML = span.innerHTML;
			} else {
				input.parentNode.insertBefore( span, input.nextSibling );
			}
		} else {
			input.parentNode.appendChild( span );
		}		
	},
	_span:function( text, className ) {
		var span = document.createElement('span');
		span.innerHTML = text || '&nbsp;';	
		span.className = 'msg ' + className;
		return span;
	}
}






var boxOffline = {
	divId:'box-nao-logado-erro',
	hideErro:function() {
		var tmp = document.getElementById(this.divId);
		if ( tmp != null ) {
			tmp.parentNode.removeChild( tmp );
		}
	},
	showErro:function( input, line1, line2 ) {
		this.hideErro();
		
		var t = input.offsetTop;
		var l = input.offsetLeft;
	
		var element = input;
	
    	var valueT = 0, valueL = 0;
    	do {
      		valueT += element.offsetTop  || 0;
      		valueL += element.offsetLeft || 0;
      		element = element.offsetParent;
    	} while (element);
	
		var a = document.createElement('a');
		a.id = this.divId;
		a.appendChild( document.createTextNode(line1) );
		if ( line2 ) {
			a.appendChild( document.createElement('br') );
			a.appendChild( document.createTextNode(line2) );
		}
		a.style.top = valueT + 22 + 'px';
		a.style.left = valueL + 'px';
		a.onclick = function() {
			this.parentNode.removeChild( this );
		};
		document.body.appendChild(a);
	},
	onSearch:function( form ) {
		var s = form.palavrasChave;
		if ( s.value.trim().length < 2) {
			this.showErro(s, 'O texto da busca deve conter', 'no mínimo duas letras.');
			s.focus();
			return false;
		} else if (checkCaracteresEspeciais(s.value.trim())) {
			this.showErro(s, 'O texto da busca possui caracter(es) inv\u00e1lido(s)', 'Por favor remova-os e tente novamente.');
			s.focus();
			return false;
		} else {
			this.hideErro();
			return true;
		}
	},
	onLogin:function( form ) {
		var l = form.login.value;
		var s = form.pass.value;
		if ( s.length == 0 || l.length == 0 ) {
			this.showErro(form.login, 'Login e Senha são', 'campos obrigatórios.');
			form.login.focus();
			return false;
		} else {
			this.hideErro();
			return true;
		}
	},
	onBusca:function( form, isOpcaoCampos ) 
	{
		var s = form.palavrasChave;
		if (!isOpcaoCampos) 
		{
			return this.onSearch(form);
		}	
		else if ( s.value.trim().length != 0 && checkCaracteresEspeciais(s.value.trim()))
		{
			this.showErro(s, 'O texto da busca possui caracter(es) inv\u00e1lido(s)', 'Por favor remova-os e tente novamente.');
			s.focus();
			return false;
		}
		return true;		
	}	
};


function checkCaracteresEspeciais(str){
/*
		var especialChars = "!@#$%^&*()+=-[]\\\';,./{}|:<>?_";
	
		for (var i = 0; i < str.length; i++) 
		{
			if (especialChars.indexOf(str.charAt(i)) != -1) 
			{
				return true;
			}
		}
*/		
		return false;
}
					


function open_busca() {
	alert(" open busca" );
}

function validarCampos() 
{
	var login = document.loginForm.login.value;
	var senha = document.loginForm.pass.value;
	if(login.trim() == "" || senha.trim() == "") 
	{
		showAlert("Login e Senha são campos obrigatórios.");
	}
	else
	{
		document.loginForm.submit();
	}
}
function validaDadosBusca(field, form) {

	var q = document[form][field].value.trim();
	//validar palavra digitada
	if (q.length < 2 ) 
	{
		showAlert("O texto da busca deve conter no mínimo duas letras.");
	}
	else
	{
		document[form].submit();
	}
}

function removeComboOptions(combo)
{
	var size = combo.options.length;
	for (var i = 0; i < size; i++)
	{
		combo.options[0] = null;
	}
}



