/**
 * Arquivo das funções do Enturma
 *
 * Todas as funções que são genéricas ou utilizadas em todo o sistema devem
 * estar neste arquivo encapsuladas no namespace Enturma
 */
Enturma = {
	/**
	 * Realiza uma chamada AJAX
	 *
	 * Esta função abre automaticamente a caixa de carregamento e a fecha no
	 * final da conexao. Em caso de erros, eles são tratados da maneira padrão
	 * ou por callback.
	 *
	 * Cuidado: Sempre passe o ajaxOptions contendo:
	 *   [successCallback]     Callback para sucesso
	 *   [errorCallback]       Callback para erros
	 *   [parameters]          Parametros que serao repassados para as funcoes
	 *                         de callback
	 *
	 * A ordem dos parametros enviados para a funcao Callback sera sempre:
	 * ( request.responseText, parameters )
	 *
	 * A variável `request' será repassada com o nome _request nos parâmetros.
	 *
	 * @param id - ID do elemento a ser atualizado
	 * @param url - URL a ser chamada
	 * @param enturmaOptions - Array de opcoes para callback
	 * @param ajaxOptions - Opcoes para a chamada ajax
	 *
	 * TODO: Tratamento de erros
	 */
	callFunction: function (id, url, enturmaOptions, ajaxOptions) {
		var options = Object.extend( {
			onLoading: function(request) {
				Enturma.showLoadLayer();
			},
			onComplete: function(request) {
				Enturma.hideLoadLayer();
				parameters = Object.extend(enturmaOptions["parameters"], {_request: request});
				enturmaOptions["successCallback"](request.responseText, parameters);
			},
			encoding: 'ISO-8859-1'
		},
		ajaxOptions || {} ); // extend

		new Ajax.Updater($(id), url, options);
	},
	/**
	 * Retorna o tamanho (largura, altura) maior da janela
	 * @return [width, height]
	 */
	getWindowSize: function () {
		var width=0, height=0;
	    if (window.clientHeight) {
			width = window.clientWidth;
			height = window.clientHeight;
		}
		if (top) {
			var doc = top.document;
		} else {
			var doc = document;
		}
		if (doc && doc.body)	{
			var width2 = doc.body.clientWidth;
			var height2 = doc.body.clientHeight;
			if (width2 > width) width = width2;
			if (height2 > height) height = height2;
			if (doc.body.scrollHeight > height)
				height = doc.body.scrollHeight;
			if (doc.body.scrollWidth > width)
				width = doc.body.scrollWidth;
		}
		if (document.documentElement && document.documentElement.clientWidth) {
			var width3 = document.documentElement.clientWidth;
			var height3 = document.documentElement.clientHeight;
			if (width3 > width) width = width3;
			if (height3 > height) height = height3;
		}

		var obj = document.getElementsByTagName('html')[0];
		if (obj.offsetHeight && obj.offsetHeight > height) {
			height = obj.offsetHeight;
		}
		if (obj.offsetWidth && obj.offsetWidth > width) {
			width = obj.offsetWidth;
		}
		if (document.body) {
			if (document.body.offsetHeight && document.body.offsetHeight > height) {
				height = document.body.offsetHeight;
			}
			if (document.body.offsetWidth && document.body.offsetWidth > width) {
				width = document.body.offsetHeight;
			}
		}
		return [width, height];
	},
	/**
	 * Retorna o tamanho (largura, altura) apenas da area visivel
	 * @return [width, height]
	 */
	getWindowVisibleSize: function () {
		var width = 0;
		var height = 0;
		if( typeof( window.innerWidth ) == 'number' ) {
			//Firefox, Opera, Safari, etc...
			width = window.innerWidth;
			height = window.innerHeight;
		} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
			//IE 6+ em modo padrao
			width = document.documentElement.clientWidth;
			height = document.documentElement.clientHeight;
		} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
			//IE 4
			width = document.body.clientWidth;
			height = document.body.clientHeight;
		}
		return [width, height];
	},
	/**
	 * Modifica o cursor padrão
	 */
	setCursor: function(cursor) {
		document.body.style.cursor = cursor;
		parent.document.body.style.cursor = cursor;
	},
	/**
	 * Fecha uma janela
	 */
	closeWindow: function(id) {
		var obj = $(id);
		if (obj != 'undefined' && obj != undefined) {
			Enturma.hide(obj);
		}
	},
	/**
	 * Move elemento de acordo com clica do mouse.
	 */
	moveElement: function(id, e, x, y) {
		var obj = $(id);
		var xx;
		var xy;
		if (obj) {
			if (x && y) {
				xx = x;
				xy = y;
			}
			else {
				var srcElem = e.srcElement || e.target;
				var height = Element.getHeight(srcElem);
				var pos = (Element.positionedOffset(srcElem));
				
				xx = parseInt(pos[0]);
				xy = parseInt(pos[1]) + parseInt(height);
			}
			obj.style.left = xx +'px';
			obj.style.top = xy +'px';
		}
		return true;
	},
	/**
	 * Seta as propriedades da layer de bloqueio e apresenta na tela
	 * @param elementToShow: id elemento a ser mostrado por cima do block
	 * @param elementToFocs: id elemento a ser focado depois de mostrar elementToShow
	 */
	showBlockLayer: function(elementToShow, elementToFocus) {
		var size = Enturma.getWindowSize();
		var width = 0;
		var height = size[1];

		var blockLayer = $('blockLayer');
		blockLayer.style.opacity = '0';
		blockLayer.style.background = '#cecece repeat';
		blockLayer.style.zIndex = 59;
		var zIndexElement = parseInt(blockLayer.style.zIndex) + 2;

		// Se for IE6 Não bloqueia
		if (elementToShow && Enturma.isIEVersionLessThanOrEqual6()) {
			Enturma.showElementBlockLayer(zIndexElement, elementToShow, elementToFocus);
			return;
		}

		if (height) {
			blockLayer.style.height = height+'px';
		}
		else {
			blockLayer.style.height = '100%';
		}
		if (width) {
			blockLayer.style.width = width+'px';
		}
		else {
			blockLayer.style.width = '100%';
		}
		Effect.Appear(blockLayer, {duration: 0.1, from: 0, to: 0.4,
			afterFinish: function() {
				// Porque o Appear do prototype só testa o disabled
				blockLayer.setStyle({visibility: "visible"});
				if (elementToShow) {
					Enturma.showElementBlockLayer(zIndexElement, elementToShow, elementToFocus);
				}
			}
			});
	},
	showElementBlockLayer: function(zIndex, elementToShow, elementToFocus) {
		var elem = $(elementToShow);
		if (elem) {
			elem.style.zIndex = zIndex;
			elem.style.border = '1px solid #898989';
			Enturma.show(elementToShow);
			Enturma.stickElement(elementToShow, 10);
			if (elementToFocus) {
				var elemFocus = $(elementToFocus);
				if (elemFocus && Enturma.visible(elementToFocus))
					elemFocus.focus();
			}
		}
		else {
			Enturma.hideBlockLayer();
		}
	},

	/**
	 * Esconde a layer de bloqueio
	 */
	hideBlockLayer: function(elementToHide) {
		if (elementToHide) {
			Enturma.hide(elementToHide);
		}
		var blockLayer = $('blockLayer');
		Enturma.closeWindow(blockLayer);
		setTimeout( function() {
			var blockLayer = $('blockLayer');
			blockLayer.style.zIndex = -1;
			blockLayer.style.opacity = '';
			blockLayer.style.filter = '';
			blockLayer.style.zIndex = -1;
			blockLayer.style.backgroundColor = 'transparent';
			blockLayer.style.width = '0px';
			blockLayer.style.height = '0px';
		}, 1);
	},
	/**
	 * Apresenta a div de carregamento via AJAX
	 */
	showLoadLayer: function() {
		Enturma.setCursor('wait');
		Enturma.hideAllMessages();
		Enturma.show('loading');
		Enturma.stickElement($('loading'), 10, 'top', true);
	},
	/**
	 * Esconde a div de carregamento via AJAX
	 *
	 * TODO: Procurar função equivalente ao switchDocumentCursor
	 */
	hideLoadLayer: function() {
		Enturma.hide('loading');
		Enturma.setCursor('auto');
	},
	/**
	 * Esconde todas as mensagens (avisos ou erros) do sistema
	 */
	hideAllMessages: function() {
		Enturma.closeWindow('toolTip');
		Enturma.closeWindow('messageBox');
		Enturma.closeWindow('errorBox');
		Enturma.closeWindow('confirmBox');
	},
	/**
	 * Mantém a posição de um elemento fixa, mesmo que a página tenha barras
	 * de rolagem.
	 *
	 * [1] Caso a orientação seja omitida, o elemento apenas será marcado como
	 *     posicionamento fixo.
	 *
	 * @param id Elemento
	 * @param y Offset em Y
	 * @param orientation [top, bottom] Orientação do elemento [1]
	 */
	stickElement: function(id, y, orientation, floatIE6) {
		if (Enturma.isIEVersionLessThanOrEqual6()) {
			if (floatIE6) {
				floatDiv(id, 'fromtop', 1, y);
			}
		}
		else {
			var obj = $(id);
			if (obj) {
				var size = Enturma.getWindowVisibleSize();
				obj.setStyle({position: 'fixed'});
				if (orientation == 'bottom') {
					obj.setStyle({top: (size[1] - y)+"px"});
				}
				else {
					obj.setStyle({top: y+'px'});
				}
			}
		}
	},
	/**
	 * Abre a janela de bloqueio
	 *
	 * Esta funcao abre a layer de bloqueio e carrega a janela de bloqueio em
	 * cima da layer de bloqueio.
	 *
	 * Parametros do array content:
	 *    [url]                 Url a ser chamada por AJAX
	 *    [ajaxOptions]         Opções da chamada AJAX
	 * Parametros do array parameters:
	 *    [behaviours]          Array de comportamentos da janela
	 *    [dragzone]            Zona de arrasto da janela
	 */
	openBlockWindow: function(content, parameters) {
		if (typeof content != "string") {
			Enturma.callFunction($('blockWindow'), content["url"], {successCallback: Enturma.openBlockWindow, parameters: parameters}, content["ajaxOptions"]);
			return;
		}

		Enturma.showBlockLayer();
		var wnd = $('blockWindow');
		wnd.update(content);
		Enturma.center(wnd);
		Enturma.stickElement(wnd, 50, 'top', true);
		Enturma.show(wnd);
		new Draggable(wnd, {handle:$(parameters["dragzone"])});
		Behaviour.register(parameters["behaviours"]);
		Behaviour.apply();
	},
	/**
	 * Fecha a janela de bloqueio
	 */
	closeBlockWindow: function(event) {
		Enturma.hideBlockLayer();
		Enturma.closeWindow('blockWindow');
		Event.stop(event);
	},
	/**
	 * Abre a janela do mini meu espaço
	 */
	showMiniMySpace: function(event) {
		var content = {
			url: urlhome + 'account/MySpace.html?action=miniMySpace&resultLayout=3'
		}
		var parameters = {
			behaviours: {
				'#miniMySpaceClose': function(element) {
					Event.observe(element, 'click', Enturma.closeBlockWindow);
				},
				'#miniMySpaceGotoCommunity': function(element) {
					Event.observe(element, 'click', Enturma.redirectMiniMySpace);
				},
				'#autocomplete': function(element) {
					Event.observe(element, 'keyup', Enturma.renderAutoCompleteMiniMySpace );
				}
			},
			dragzone: "miniMySpaceHeader"
		};

		Enturma.openBlockWindow(content, parameters);
		Event.stop(event);
	},
	/**
	 * Comportamento de redirecionamento do mini meu espaço
	 */
	redirectMiniMySpace: function(event) {
		var tool = $('miniMySpaceComponent');
		var community = $('miniMySpaceCommunity');
		var selectedTool = tool.options[tool.selectedIndex].value;
		if (!selectedTool) selectedTool = 'Index';
		var selectedCommunity = community.value;
		if (selectedTool && selectedCommunity) {
			Enturma.redirect(urlhome + 'community/' + selectedCommunity + '/' + selectedTool + '.html');
		}
		Event.stop(event);
	},
	/**
	 * Redireciona o navegador para url
	 */
	redirect: function(url) {
		window.location.href = url;
	},
	/**
	 * Cria os divs de layer e mensagens necessários
	 * divs: blockLayer, blockWindow, errorDiv, sysErrorDiv,
	 * 		 messagesDiv, helpBox, toolTipLayer, sendScrapForm
	 */
	createLayers: function () {
		['toolTipLayer', 'sendScrapForm', 'blockLayer','blockWindow',
		'errorDiv', 'sysErrorDiv', 'messagesDiv', 'helpBox'].each(function(id) {
			if (!$(id)) {
				var element = Builder.node('div', {id: id});
				$('containerDefault').appendChild(element);
			}
		});
		$('toolTipLayer').setStyle({position:'absolute', visibility: 'hidden', zIndex: '19'});
		$('blockWindow').setStyle({position: 'absolute', display: 'none', zIndex:'60', top:'0', left:'0'});

		//TODO: Remover o frame - obsoletos
		if (!$('fAction')) {
			var iframe = Builder.node('iframe', {id:'fAction', name:'fAction', width:0, height:0, frameborder:0, src:'about:blank'});
			$('containerDefault').appendChild(iframe);
		}
		$('fAction').setStyle({display: 'none', border: '0'});
	},

	/**
	 * Esconde um elemento, caso exista.
	 */
	hide: function(element) {
		var obj = $(element);
		if (obj != undefined && obj != 'undefined') {
			obj.hide();
			// TODO: Verificar como fazer isso melhor
			/* O prototype não modifica o estilo visibility nos métodos show e
			 * hide do Element.
			 * Duas opções, a principio:
			 * a) tornar esta maneira aqui difinitiva e _SEMPRE_ utilizar os
			 *    método Enturma.show|hide para mostrar ou esconder elementos
			 * b) adaptar os estilos para utilizar _SEMPRE_ o display none
			 *    quando se deseja esconder elementos
			 */
			obj.setStyle({visibility: "hidden"});
		}
	},
	/**
	 * Mostra um elemento, caso exista.
	 */
	show: function(element) {
		var obj = $(element);
		if (obj != undefined && obj != 'undefined') {
			obj.show();
			obj.setStyle({visibility: "visible"});
		}
	},
	/**
	 * Alterna entre mostrar ou esconder um elemento, caso exista.
	 */
	toggle: function(element) {
		var obj = $(element);
		if (Enturma.visible(obj)) {
	    	Enturma.hide(obj);
	    }
	    else {
	    	Enturma.show(obj);
	    }
		/* Mesmo problema do show|hide
		if (obj != undefined && obj != 'undefined') {
			obj.toggle();
		}
		*/
	},

	/**
	* O visible do prototype não é usado
	* pois ele só testa se o atributo style existir
	* e não se o estilo for definido no arquivo css.
	*/
	visible: function(element) {
		var sdisplay = $(element).getStyle('display');
		var svisibility = $(element).getStyle('visibility');
		if (svisibility == 'inherit')
			svisibility = $(element).up().getStyle('visibility');

		var displayed = (!sdisplay || sdisplay != 'none');
		var visible = (!svisibility || svisibility != 'hidden');
		return (displayed && visible);
	},

	/**
	 * Marca o foco de um elemento selecionado no formulário
	 */
	focusInput: function(element, blur) {
		if (element.tagName == 'SELECT')
			return;
		if (element.tagName=="TEXTAREA" || (element.tagName=="INPUT" && (element.type =='text' || element.type=='password'))) {
			if (blur || element.disabled || element.getAttribute('readonly') || element.getAttribute('readonly') == "readonly") {
				element.removeClassName('focusInputSelected');
			}
			else {
				element.addClassName('focusInputSelected');
			}
		}
		else {
			return;
		}
	},

	/**
	 * Seleciona permissões de conteúdo mais comuns
	 */
	selectDefaultContentPermissions: function() {
		$('allMembersView').checked = true;
		$('allMembersView').onclick();
		$('onlyAuthorUpdate').checked = true;
		$('onlyAuthorUpdate').onclick();
		$('onlyAuthorPublish').checked = true;
		$('onlyAuthorPublish').onclick();
		$('onlyAuthorDelete').checked = true;
		$('onlyAuthorDelete').onclick();
	},

	/**
	 * Verificar se navegador é ie e <= ie6
	 */
	isIEVersionLessThanOrEqual6: function() {
	    if (Enturma.isIE()) {
	        var temp = navigator.appVersion.toLowerCase().split("msie");
    	    var version = parseFloat(temp[1]);
        	return (version <= 6);
	    } else {
    	    return false;
	    }
	},
	isIE: function() {
	  return (navigator.userAgent.toLowerCase().indexOf("msie") > -1);
	},

	/**
	 * Mostrar box para Enviar página de conteúdo por email
	*/
	showSendPageEmail: function(event, urlPage) {
		if ($('sendEmail').innerHTML) {
			Enturma.openSendPageEmail();
		}
		else {
			var content = {
				url: urlPage + '?action=sendPageToEmail&resultLayout=3'
			}
			var parameters = {
				behaviours: {}
			};

			Enturma.callFunction($('sendEmail'), content["url"], {successCallback: Enturma.openSendPageEmail, parameters: parameters});
		}

		Event.stop(event);
	},
	openSendPageEmail: function() {
		$('comments').value = '';
		$('to').value = '';
		$('subject').value = '';
		Enturma.hide('errorTto');
		Enturma.hide('errorTfrom');
		Enturma.center('sendEmail');
		Enturma.stickElement('sendEmail', 50, 'top', true);
		Enturma.show('sendEmail');
	},

	/**
	 * Função que usa Scriptaculous pra centralizar Elemento
	*/
	center: function(element){
	    try {
	        element = $(element);
	    }
	    catch(e) {
	        return;
	    }

	    var my_width  = 0;
	    var my_height = 0;

	    if ( typeof( window.innerWidth ) == 'number' )
	    {

	        my_width  = window.innerWidth;
	        my_height = window.innerHeight;
	    }
	    else if ( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) )
	    {

	        my_width  = document.documentElement.clientWidth;
	        my_height = document.documentElement.clientHeight;
	    }
	    else if ( document.body && ( document.body.clientWidth || document.body.clientHeight ) )
	    {

	        my_width  = document.body.clientWidth;
	        my_height = document.body.clientHeight;
	    }
	    element.style.position = 'absolute';
	    element.style.display  = 'block';
	    element.style.zIndex   = 99;

	    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;
	    }

	    var elementDimensions = Element.getDimensions(element);

	    var setX = ( my_width  - elementDimensions.width  ) / 2;
	    var setY = ( my_height - elementDimensions.height ) / 2 + scrollY;

	    setX = ( setX < 0 ) ? 0 : setX;
	    setY = ( setY < 0 ) ? 0 : setY;

	    element.style.left = setX + "px";
	    element.style.top  = setY + "px";
	},

	/**
	 * Ver detalhes de acesso e respostas ed um conteudo
	*/
	viewDetailedContentLog: function(urlPage) {
		var content = {
			url: urlPage + '&resultLayout=3'
		}
		var parameters = {
			behaviours: {},
			dragzone: "viewDetailedBoxfloatBoxTitle"
		};
		$('viewDetailedBoxfloatBoxContent').innerHTML = '';
		Enturma.callFunction($('viewDetailedBoxfloatBoxContent'), content["url"], {successCallback: Enturma.showDetailedBox, parameters: parameters});
	},
	/**
	 * Mostra detalhes de acesso e respostas ed um conteudo
	 *	chamado pelo viewDetailedContentLog()
	*/
	showDetailedBox: function() {
	    Enturma.show('viewDetailedBox');
	    Enturma.stickElement('viewDetailedBox', 40, 'top', true);
	},
	/**
	 * Mostra perfil de um usuário no sistema
	 * Usado na página de participantes e cronograma de aulas
	*/
	showMemberProfile: function(idBox, idContent, community, idUser, textLoading) {
	    callFunctionFrame('community/'+community+'/Members.html', 'memberProfile', idContent, 'idUser='+idUser);
	    $(idContent).innerHTML = textLoading;

	    Enturma.show(idBox);
	    Enturma.stickElement(idBox, 40, 'top', true);
		$(idBox).style.left= '20%';
	},
	/**
	 * Mostra estatísticas de acesso de um conteúdo em uma data específica
	*/
	goToLogDate: function(idContent, idUser) {
		if ($('viewDetailedBoxfloatBoxContent')) {
			month = $('selmonth').value;
			year = $('selyear').value;
			var urlPage = $('viewLog'+idContent+idUser).href + '&year='+year+'&month='+month;
			return Enturma.viewDetailedContentLog(urlPage);
		}
	},
	/** Cria novo item de texto no formulário (usado nas Enquetes)
	*/
	addNewItems: function(selName, selText) {
		var elems = document.getElementsByTagName("input");
		var count  = 0;
		for (i=0; i< elems.length; i++) {
			if (elems[i].type == "text" && elems[i].name == selName)  count++;
		}

		var nro = $('moreOptions').value;
		var elems = document.getElementsByTagName("span");
		for (i=0; i<elems.length; i++) {
			if (elems[i].id == selName + "Group")
				objParent = elems[i];
		}
		var opnro = parseInt(count) + 1;
		for (i=0; i<nro; i++) {
			var objElement = createInput('text', selName, selName, 35, 'inputField');
			if (objParent && objElement) {
				objParent.appendChild(document.createElement('br'));
				var spanElem = document.createElement('span');
				spanElem.innerHTML = selText+' '+opnro+' ';
				opnro += 1;
				objParent.appendChild(spanElem);
				objParent.appendChild(objElement);
			}
		}
	},
	joinSelectedCheckbox: function(chk){
		var list = '';
		if(chk[0] == undefined)
			return chk.value;
		var length = chk.length;
		for (i=0; i< length; i++)
			if (chk[i].checked==true){
				list+=chk[i].value;
				if(i<length-1)
					list+=',';
			}
		return list;
	},
	selectListFromSearch: function(separator){
		Enturma.selectFromSearch('', separator);
	},
	selectFromSearch: function(valor, separator) {
		// Valor: string '<id>@<name>@<uid>'
		var formSel = document.getElementById('selall');
		if (window.opener) winparent = window.opener;
		else winparent = parent;
		if (valor || formSel) {
			var formId = document.getElementById('search_id');
			var formUid = document.getElementById('search_uid');
			var formName = document.getElementById('search_name');
			var elemento = winparent.document.getElementById(formId.value);
			var elementoUid = null;
			if (formUid && formUid.value)
				elementoUid = winparent.document.getElementById(formUid.value);

			if (!elemento && !elementoUid)
				return;

			// Se puder selecionar mais de um elemento, elemento "id" deve ser um array "id[]"
			if (formSel && !valor) {
				var sel = getSelected();
				var size = sel.length;
				var retorno = Array();
				var retornoName = Array();
				var retornoUid = Array();
				i = 0;
		    	for (i = 0; i < size; i++) {
	    	    	valor = document.getElementById(sel[i]).value.split("@");
					retorno[i] = valor[0];
					// Pode se informar um id de um elemento para mostrar o nome do item pesquisado
					if (formName.value != '') {
						retornoName[i] = valor[1];
					}
					if (formUid && formUid.value != '') {
						retornoUid[i] = valor[2];
					}
				}
				if (separator) {
					 if (elemento.value)
						elemento.value += separator+replaceAll(retorno.toString(), ',', separator);
					else
						elemento.value = replaceAll(retorno.toString(), ',', separator);
				} else
					elemento.value = retorno;
				// Pode se informar um id de um elemento para mostrar o nome do item pesquisado
				if (formName.value != '') {
					elementoName = winparent.document.getElementById(formName.value);
					if (separator) {
						if (elementoName.value)
							elementoName.value += separator+replaceAll(retornoName.toString(), ',', separator);
						else
							elementoName.value = replaceAll(retornoName.toString(), ',', separator);
					} else
						elementoName.value = retornoName;
				}
				// Pode se informar um id de um elemento para mostrar o uid do item pesquisado
				if (formUid && formUid.value != '') {
					if (separator) {
						if (elementoUid.value)
							elementoUid.value += separator+replaceAll(retornoUid.toString(), ',', separator);
						else
							elementoUid.value = replaceAll(retornoUid.toString(), ',', separator);
					} else
						elementoUid.value = retornoUid;
				}
			}
			// Somente um elemento
			else {
			  	valor = valor.split("@"); // <id>@<name>@<uid>
				// Pode se informar um id de um elemento para mostrar o id do item pesquisado
				if (formId.value != '') {
					if (separator && elemento.value)
						elemento.value += separator+valor[0];
					else
						elemento.value = valor[0];
				}
				// Pode se informar um id de um elemento para mostrar o nome do item pesquisado
				if (formName.value != '') {
					elementoName = winparent.document.getElementById(formName.value);
					if (separator && elementoName.value)
						elementoName.value += separator+valor[1];
					else elementoName.value = valor[1];
				}
				// Pode se informar um id de um elemento para mostrar o uid do item pesquisado
				if (formUid && formUid.value != '') {
					if (separator && elementoUid.value)
						elementoUid.value += separator+valor[2];
					else elementoUid.value = valor[2];
				}
			}
			// Executa as funcoes, se existirem, incluir mais funcoes, se necessario
			if (elemento) {
				if (elemento.fireEvent) { // Soh para o IE
					elemento.fireEvent("onchange");
					elemento.fireEvent("onfocus");
				}
				else { // Mozilla e outros?
					if (elemento.onchange)  elemento.onchange();
					if (elemento.onfocus)   elemento.onfocus();
				}
			}
			// Executa as funcoes, se existirem, incluir mais funcoes, se necessario
			if (elementoUid) {
				if (elementoUid.fireEvent) { // Soh para o IE
					elementoUid.fireEvent("onchange");
					elementoUid.fireEvent("onfocus");
				}
				else { // Mozilla e outros?
					if (elementoUid.onchange)  elementoUid.onchange();
					if (elementoUid.onfocus)   elementoUid.onfocus();
				}
			}
			if (window.opener) window.close();
			else Enturma.hide('search');
		}
	},
	showMacroDetails: function(event, box, url) {
		Event.stop(event);
		if(!box.innerHTML){
			Enturma.callFunction(box, url);
	}
		if(box.visible())
			box.hide();
		else
			box.show();

	},
	showFaqAnswer: function(event, el, box, urlPage, edit){
		Event.stop(event);
		if(!box.innerHTML || edit){
			var url = urlPage + '&resultLayout=3';
			Enturma.callFunction(box, url);
			Enturma.show(el);
		} else {
			box.innerHTML = '';
			Enturma.toggle(el);
		}
	},
	showScormBlockFrame: function(event, urlPage){
		Event.stop(event);
	//	var content = {
	//		url: urlPage + '&popup=1'
	//	}
	//	var parameters = {
	//		behaviours: {
	//			'#scormBlockClose': function(element) {
	//					Event.observe(element, 'click', Enturma.closeBlockWindow);
	//			}
	//		}
	//	};
		popUp(url, 800, 600, 'scormViewExpand', true, true);
		//Enturma.openFullScormFrame(content, parameters);

	},
	openFullScormFrame: function(content, parameters) {
		if (typeof content != "string") {
			Enturma.callFunction($('blockWindow'), content["url"], {successCallback: Enturma.openFullScormFrame, parameters: parameters}, content["ajaxOptions"]);
			return;
		}

		Enturma.showBlockLayer();
		var wnd = $('blockWindow');
		wnd.update(content);
		wnd.style.left = "0px";
	    wnd.style.top  = "0px";
		Enturma.stickElement(wnd, 0, 'top', true);
		Enturma.show(wnd);
		new Draggable(wnd, {handle:$(parameters["dragzone"])});
		Behaviour.register(parameters["behaviours"]);
		Behaviour.apply();
	},
	openWizard: function(url){
		var content = {
			url: urlhome + url
		}
		var parameters = {
			behaviours: {
				/*'#miniMySpaceClose': function(element) {
					Event.observe(element, 'click', Enturma.closeBlockWindow);
				},
				'#miniMySpaceGotoCommunity': function(element) {
					Event.observe(element, 'click', Enturma.redirectMiniMySpace);
				}*/
			}
			//dragzone: "miniMySpaceHeader"
		};

		Enturma.openBlockWindow(content, parameters);

		Event.stop(event);
	},
	cookieToggle: function(element){
		var obj = $(element);
		var today = new Date();
		var zero_date = new Date(0, 0, 0);
		today.setTime(today.getTime() - zero_date.getTime());
		var cookie_expire_date = new Date(today.getTime() + (8 * 7 * 86400000));
		
		if (Enturma.visible(obj)) {
			Enturma.hide(obj);
			Set_Cookie('show' + obj.id, 'invisible', cookie_expire_date);
		}
		else {
			Enturma.show(obj);
			Set_Cookie('show' + obj.id, 'visible', cookie_expire_date);
		}
	},
	
	/**
	 * renderAutoCompleteMiniMySpace
	 * Realiza chamada Ajax para retornar uma lista de comunidades que serão sugeridas ao usuário
	 * @param {Object} event
	 */
	renderAutoCompleteMiniMySpace: function(event) {
		new Ajax.Autocompleter("autocomplete", "autocomplete_choices", "/account/MySpace.html?action=searchCommunities", {
			paramName: "value",
			minChars: 3,
			frequency: 0.5,
			indicator: 'indicator1',
			callback: setButtonDisabled,
			afterUpdateElement: getSelectionId
		});
		setTimeout(function() {Enturma.hideLoadLayer()}, 500);
		Event.stop(event);
	}
}

