// JavaScript Document
window.onload = function (e){
	contextMenu(e);
	
	buildDl();//barra principal

	addTerm("Inventário Cultural","titulo","javascript:void(0)");
	
	addTerm("Home","menu0","main.php");

	addTerm("Grupo","menu1");
	addLink("form_grupo.php","Novo grupo","menu1");
	
	addTerm("Listagem","menu2");
	addLink("view_grupos.php","Listar grupos","menu2");
	
	/*addTerm("Mesorregiões","menu2");
	addLink("view_mesoregiao.php","Edição de mesoregiões","menu2");
	addLink("javascript:void(0)","--------------------------------","menu2");
	addLink("form_mesoregiao.php","Nova mesoregião","menu2");
	
	addTerm("Microregiões","menu3");
	addLink("view_tutorial.php","Edição de tutoriais","menu3");
	addLink("view_os.php","Tutoriais: Sistemas Operacionais","menu3");
	addLink("view_software.php","Tutoriais: Softwares","menu3");
	addLink("javascript:void(0)","--------------------------------","menu3");
	addLink("form_tutorial.php","Novo tutorial","menu3");
	addLink("form_software.php","Novo software","menu3");
	addLink("form_os.php","Novo sistema operacional","menu3");
	
	addTerm("Municípios","menu4");
	addLink("view_tutorial.php","Edição de tutoriais","menu4");
	addLink("view_os.php","Tutoriais: Sistemas Operacionais","menu4");
	addLink("view_software.php","Tutoriais: Softwares","menu4");
	addLink("javascript:void(0)","--------------------------------","menu4");
	addLink("form_tutorial.php","Novo tutorial","menu4");
	addLink("form_software.php","Novo software","menu4");
	addLink("form_os.php","Novo sistema operacional","menu4");*/
	
	//addTerm("Opções","menu5");
	//addLink("../","Ir para o site","menu5");
	selectTipoGrupo();
}
function addMenu(user){
	//contextMenu(e);
	
	criaDivMenu(user);//barra principal

	addTerm("Inventário Cultural","titulo","javascript:void(0)");
	
	addTerm("Home","menu0","main.php");

	addTerm("Grupo","menu1");
	addLink("form_grupo.php","Novo grupo","menu1");
	
	addTerm("Listagem","menu2");
	addLink("view_grupos.php","Listar grupos","menu2");
	
	selectTipoGrupo();
}


//contador de leftclicks (global)
var count = 0;


//Cria objeto XML
function criaObjetoXml(){
	var req;
	var browser = navigator.appName;
	if(browser == "Microsoft Internet Explorer"){
		req = new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		req = new XMLHttpRequest();
	}
	return req; 
}
var request_o = criaObjetoXml();


//INICIALIZAÇÃO DA PÁGINA
function delCadastro(cod){
	if(confirm('Deseja realmente excluir este grupo?')){
		window.location="del_cadastro.php?cod="+cod;
	}
}

//menu de contexto para o textearea
function contextMenu(e){
	
	if (document.getElementsByTagName("iframe").length!=0){
	
		var campo = document.getElementsByTagName('textarea')[0];
		//var campo = document.body;
		
		campo.parentNode.oncontextmenu=function(){
			return false;
		}
		
		campo.onmouseup = function (e){
			
			//botões do mouse
			var rightclick;
			var leftclick;
			if (!e){
				var e = window.event;
			}
			
			if (e.which){
				rightclick = (e.which == 3);
				leftclick = (e.which == 1);
			} else if (e.button){
				rightclick = (e.button == 2);
				leftclick = (e.button == 1);
			}
			
			
			if ((rightclick)&&(count!=0)){
				
				//remove quaisquer divs existentes
				if (document.getElementById("seleciona_imagem")){
					var div = document.getElementById("seleciona_imagem");
					div.parentNode.removeChild(div);
				}
				
				//criação da div
				var iframe = document.getElementsByTagName('iframe')[0];
				var div = document.createElement('div');
				div.id = "seleciona_imagem";
				
				var page = iframe.name;
				var imgs = frames[page].document.getElementsByTagName('img');
				
				var p = document.createElement('p');
				p.appendChild(document.createTextNode('adicionar imagem'));
				div.appendChild(p);
				
				if (imgs.length!=0){
					for (i=0; i<imgs.length; i++){
						
						var imagem = imgs[i];
						var a = document.createElement('a');
						a.href = 'javascript:void(0)';
						
						//posiciona a div
						div.style.top=findMouseCoords(e)[1];
						div.style.left=findMouseCoords(e)[0];
						
						var img = document.createElement('img');
						var source = imagem.src.replace("x=9000&y=9000","x=5000&y=5000"); 
						img.src = source;
						a.appendChild(img);
						div.appendChild(a);
						
						//insere a tag personalisada
						a.onclick = function(){
							var url = this.getElementsByTagName('img')[0].src;
							var ini = url.indexOf('cod=')+4;
							var fim = url.indexOf('&x=');
							imgcod = url.substring(ini, fim);
							
							if (campo.value.indexOf("<foto>"+imgcod+"</foto>")==-1){
								insertAtCursor(campo, " <foto>"+imgcod+"</foto> ");
								div.parentNode.removeChild(div);
							}else{
								alert('Foto já inserida no texto!')
								return false;
							}
							
						}
					}
					campo.parentNode.appendChild(div);
				}
				
			} else if (leftclick){
				count++;
				
				if (document.getElementById("seleciona_imagem")){
					var div = document.getElementById("seleciona_imagem");
					div.parentNode.removeChild(div);
				}
			}
		}
	}
}

/*INSERE TEXTO NA ÁREA ONDE O CURSOR APONTA*/
/*Cortesia de http://alexking.org/blog/2003/06/02/inserting-at-the-cursor-using-javascript*/
// calling the function: insertAtCursor(campo, "ABC");
function insertAtCursor(myField, myValue){
	
	//IE support
	if (document.selection){
		myField.focus();
		sel = document.selection.createRange();
		sel.text = myValue;
	}
	
	//MOZILLA/NETSCAPE support
	else if (myField.selectionStart || myField.selectionStart == '0'){
		var startPos = myField.selectionStart;
		var endPos = myField.selectionEnd;
		myField.value = myField.value.substring(0, startPos)
		+ myValue+ myField.value.substring(endPos, myField.value.length);
		
	} else {
		myField.value += myValue;
	}
}

/*QUIRKSMODE.ORG*/
//This is the correct script for detecting the mouse coordinates:
function findMouseCoords(e) {
	var posx = 0;
	var posy = 0;
	var pos = new Array();
	if (!e) var e = window.event;
	if (e.pageX || e.pageY) 	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		posx = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}
	
	// posx and posy contain the mouse position relative to the document
	// Do something with this information
	pos[0]=posx;
	pos[1]=posy;
	return pos;
}

function selectTipoGrupo(){
	var url = document.location.toString();
	var td = document.getElementById('td_grupo');
	if(url.indexOf("form_produto")!=-1){
		var tp = document.forms[0].tipoprod;
		
		//já no carregamento da pagina
		request_o.open('get','sel_grupo_tipo.php?tipo='+tp.value, false);
		request_o.send(null);
		td.innerHTML = request_o.responseText;
		
		//no onchange da select
		tp.onchange = function(){
			request_o.open('get','sel_grupo_tipo.php?tipo='+tp.value, false);
			request_o.send(null);
			td.innerHTML = request_o.responseText;
		}
	}
}

function validaFormGrupo(){
	var status = true;
	if($("#idMunicipio").val() == ""){  
		/*$('#idUuee').css('border', '1px solid #F60');*/
		$('#idMunicipio').focus();
		$('#alerta').html('Escolha o Município.');
		status = false;
	}else if($("#idOpcao").val() == ""){
		$('#idOpcao').focus();
		$('#alerta').html('Escolha uma Opção.');
		status = false;
	}else if($("#idModalidade").val() == ""){  
		$('#idModalidade').focus();
		$('#alerta').html('Escolha a Modalidade.');
		status = false;
	}else if($("#idNome").val() == ""){  
		$('#idNome').focus();
		$('#alerta').html('Digite o nome da atividade.');
		status = false;
	}else if($("#idEndereco").val() == ""){  
		$('#idEndereco').focus();
		$('#alerta').html('Digite o endereço da grupo.');
		status = false;
	}else if($("#idBairro").val() == ""){  
		$('#idBairro').focus();
		$('#alerta').html('Digite o bairro da grupo.');
		status = false;
	}else if($("#idCep").val() == ""){  
		$('#idCep').focus();
		$('#alerta').html('Digite o CEP.');
		status = false;
	}else if($("#idTelefone").val() == ""){  
		$('#idTelefone').focus();
		$('#alerta').html('Digite o telefone para contato.');
		status = false;
	}else if($("#idNIntegrantes").val() == ""){  
		$('#idNIntegrantes').focus();
		$('#alerta').html('Digite o número de integrantes.');
		status = false;
	}

	if(status == false){
		$('#divAlerta').fadeOut();
		$('#divAlerta').fadeIn(300);
	}else{
		$("form#formGrupo").submit();	
	}
	
}

function msgSenha(){
	if ($('#msgErro').val() == "1"){
		$('#alertaSenha').html("<label style='color:#FF0000'>As duas senha devem ser iguais.</label>");
	} else if($('#msgErro').val() == "2"){
		$('#alertaSenha').html("<label style='color:#FF0000'>Tamanho da senha inferior a 4 caracteres.</label>");
	} else if ($('#msgErro').val() == "3"){
		$('#alertaSenha').html("<label style='color:#009900'>Senha atualizada com sucesso.</label>");
	}

	if ($('#msgErro').val() != ""){
		$('#divAlerta').fadeOut();
		$('#divAlerta').fadeIn(300);
	}
}

function validaFormSenhaGrupo(){
	var status = true;
	if($("#idSenha").val() == ""){  
		$('#idSenha').focus();
		$('#alerta').html('Preencha o campo de senha.');
		status = false;
	}
	if(status == false){
		$('#divAlerta').fadeOut();
		$('#divAlerta').fadeIn(300);
	} else {
		$("form#formSenha").submit();
	}
}

function validaFormUpdateSenha(){
	var status = true;
	if($("#senha1").val() == ""){  
		$('#senha1').focus();
		$('#alerta').html('Preencha o campo de senha.');
		status = false;
	} else {
		if($("#senha2").val() == ""){  
			$('#senha2').focus();
			$('#alerta').html('Preencha o campo de confirme senha.');
			status = false;
		}
	}
	if(status == false){
		$('#divAlerta').fadeOut();
		$('#divAlerta').fadeIn(300);
	} else {
		$("form#formSenha").submit();
	}
}

/*function validaEmail($email){
	var form = document.forms[0];
	if ($email == ""){
		//alert('O e-mail deve ser preenchido.');
		$('#idEmail').focus();
		$('#alerta').html('O e-mail deve ser preenchido.');

		return false;
	} else {
		var regmail = /^[\w!#$%&amp;'*+\/=?^`{|}~-]+(\.[\w!#$%&amp;'*+\/=?^`{|}~-]+)*@(([\w-]+\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
		if (regmail.test(form.email.value)) {
			return true;
		} else {
			//alert('O e-mail deve ser preenchido corretamente.');
			$('#idEmail').focus();
			$('#alerta').html('O e-mail deve ser preenchido corretamente.');

			return false;
		}
	}
}*/

function devolverGrupo(){
	if (confirm("Deseja devolver este grupo?")){
		document.formGrupo.action = "autoriza_grupo.php?dev";
		document.formGrupo.submit();
	}
}
function autorizarGrupo(){
	if (confirm("Deseja autorizar este grupo?")){
		document.formGrupo.action = "autoriza_grupo.php";
		document.formGrupo.submit();
	}
}

function escolheOpcao()
{
	var valor = document.getElementById('opcao').options[document.getElementById('opcao').selectedIndex].value;
	makeRequest('adm/opcao.php?opcao=' + valor);
}

function escolheModalidade()
{
	var valor = document.getElementById('modalidade').options[document.getElementById('modalidade').selectedIndex].value;
	makeRequest2('adm/retorna_modalidade.php?opcao=' + valor);
}

function num(dom){
        dom.value=dom.value.replace(/\D/g,'');
}

