/**
 * @author Danilo Ribeiro da Silveira
 * @copyright VipMultimidia
 * @copyright Http://www.vipmultimidia.com.br
 * @copyright danilo@vipmultimidia.com.br
 */
function cadastrar_ajax(tipo) {
	var cadastrar = false;
	if (window.XMLHttpRequest) { //mozilla.
		cadastrar = new XMLHttpRequest();
	} else if (window.ActiveXObject) { //IE
		cadastrar = ObjMSXMLHttp();
	}
	switch (tipo) {
		case "cliente":
			var formulario = document.getElementById("form_cadastrar");
			var campo_nome = trim(formulario.campo_nome.value);
			if(campo_nome.length == 0) { alert("Campo Nome Em Branco."); loading("hide"); return false; }
			var dados = "acao=cadastrar";
			dados += "&tipo=cliente";
			dados += "&campo_nome="+campo_nome;
		break;

		case "usuario":
			var formulario = document.getElementById("form_cadastrar");
			var campo_nome = trim(formulario.campo_nome.value);
			var campo_login = trim(formulario.campo_login.value);
			var campo_senha = trim(formulario.campo_senha.value);
			if(campo_nome.length == 0) { alert("Campo Nome Em Branco."); loading("hide"); return false; }
			if(campo_login.length == 0) { alert("Campo Login Em Branco."); loading("hide"); return false; }
			if(campo_senha.length == 0) { alert("Campo Senha Em Branco."); loading("hide"); return false; }
			if(campo_login.length > 8) { alert("Máximo 8 caracteres para campo Login."); loading("hide"); return false; }
			if(campo_senha.length > 8) { alert("Máximo 8 caracteres para campo Senha."); loading("hide"); return false; }
			var dados = "acao=cadastrar";
			dados += "&tipo=usuario";
			dados += "&campo_nome="+campo_nome;
			dados += "&campo_login="+campo_login;
			dados += "&campo_senha="+campo_senha;
		break;
	}
	
	cadastrar.open("POST", "intranet.php", true);
	cadastrar.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	cadastrar.onreadystatechange = function() {
		if(cadastrar.readyState == 1) {
			loading("show");
		}
		if(cadastrar.readyState == 4) {
			if(cadastrar.status == 200) {
				var response = trim(cadastrar.responseText);
				if(response > 0) {
					var id = trim(response);
					return incluir_cadastrar(id, tipo, '0');
				} else {
					loading("hide");
					return alert(response);
				}
			} else {
				loading("hide");
				return alert("Erro ao carregar os dados");
			}
		}
	}
	cadastrar.send(dados);
}
function iframe($tipo) {
	var elemento = document.getElementById("form_cadastrar");
	if (elemento) {
		switch ($tipo) {
			case "projeto":
				var campo_titulo = trim(elemento.campo_titulo.value);
				var campo_descricao = trim(elemento.campo_descricao.value);
				var campo_file = trim(elemento.campo_file.value);
				if(campo_titulo.length == 0) { alert("Campo Titulo Em Branco."); return false; }
				if(campo_descricao.length == 0) { alert("Campo Descricao Em Branco."); return false; }
				if(campo_file.length == 0) { alert("Campo Imagem Em Branco."); return false; }
			break;
			case "equipamento":
				var campo_modelo = trim(elemento.campo_modelo.value);
				var campo_file = trim(elemento.campo_file.value);
				if(campo_modelo.length == 0) { alert("Campo Modelo Em Branco."); return false; }
				if(campo_file.length == 0) { alert("Campo PDF Em Branco."); return false; }
			break;
			case "semi_novo":
				var campo_descricao = trim(elemento.campo_descricao.value);
				var campo_file = trim(elemento.campo_file.value);
				if(campo_descricao.length == 0) { alert("Campo Descrição Em Branco."); return false; }
				if(campo_file.length == 0) { alert("Campo PDF Em Branco."); return false; }
			break;
		}
		loading("show");
		var iframe = document.createElement("iframe");
			iframe.setAttribute("id","post");
			iframe.setAttribute("name","post");
			iframe.setAttribute("width","0");
			iframe.setAttribute("height","0");
			iframe.setAttribute("border","0");
			iframe.setAttribute("style","width: 0; height: 0; border: none;");
		elemento.parentNode.appendChild(iframe);
		window.frames['post'].name="post"; //ie sucks
		elemento.setAttribute("target","post");
		elemento.setAttribute("action","intranet.php");
		elemento.setAttribute("method","post");
		elemento.setAttribute("enctype","multipart/form-data");
		elemento.setAttribute("encoding","multipart/form-data");		
	} else {
		return alert("Elemento nao encontrado");
	}
}
function incluir_cadastrar(id, tipo, erro) {
	if(erro != "0") {
		var elemento_post = document.getElementById("post");
		if(elemento_post) {
			elemento_post.parentNode.removeChild(elemento_post);
		}
		loading("hide");
		return alert(trim(erro));
	} else {
		var elemento_post = document.getElementById("post");
		if(elemento_post) {
			elemento_post.parentNode.removeChild(elemento_post);
		}
		var elemento = document.getElementById("lista");
		if(elemento) {
			if(document.getElementById("sem_registro")) {
				var sem_registro = document.getElementById("sem_registro");
				var remover = sem_registro.parentNode;
				remover.removeChild(sem_registro);
			}
			var formulario = document.getElementById("form_cadastrar");
			switch (tipo) { // ELEMENTO A SER INCLUIDO
				case "projeto": /*################################################ PROJETO*/
					var titulo = trim(formulario.campo_titulo.value);
					var descricao_original = trim(formulario.campo_descricao.value);
					var descricao = descricao_original.replace(/\n/gi, "<br>");
					var imagem = trim(formulario.campo_file.value);
					imagem=imagem.slice(imagem.lastIndexOf('\\')+1);
					var div = document.createElement("div");
						div.setAttribute("id", "projeto"+id);
						div.setAttribute("class", "lista");
						div.setAttribute("className", "lista");
					var ul = document.createElement("ul");
						var li = document.createElement("li");
							var img = document.createElement("img");
								img.setAttribute("src", "estrutura/erro.gif");
								img.setAttribute("style", "cursor: pointer;");
								img.onclick = function () { excluir(id, 'projeto'); };
						li.appendChild(img);
					ul.appendChild(li);
				div.appendChild(ul);
					var ul = document.createElement("ul");
						var li = document.createElement("li");
							var strong = document.createElement("strong");
								strong.appendChild(document.createTextNode("Titulo: "));
						li.appendChild(strong);
					ul.appendChild(li);
						var li2 = document.createElement("li");
							var span = document.createElement("span");
								span.setAttribute("id", "titulo"+id);
								span.appendChild(document.createTextNode(titulo));
								span.onclick = function () { editar(id, this, 'input', 'projeto', '1'); };
						li2.appendChild(span);
					ul.appendChild(li2);
				div.appendChild(ul);
					var ul = document.createElement("ul");
						var li = document.createElement("li");
							var strong = document.createElement("strong");
								strong.appendChild(document.createTextNode("Descrição: "));
						li.appendChild(strong);
					ul.appendChild(li);
						var li2 = document.createElement("li");
							var span = document.createElement("span");
								span.setAttribute("id", "descricao"+id);
								span.innerHTML = descricao;
								span.onclick = function () { editar(id, this, 'textarea', 'projeto', '2'); };
						li2.appendChild(span);
					ul.appendChild(li2);
				div.appendChild(ul);
					var ul = document.createElement("ul");
						var li = document.createElement("li");
							var strong = document.createElement("strong");
								strong.appendChild(document.createTextNode("Imagem: "));
						li.appendChild(strong);
					ul.appendChild(li);
						var li2 = document.createElement("li");
							var span = document.createElement("span");
								span.setAttribute("id", "imagem"+id);
								span.appendChild(document.createTextNode(imagem));
						li2.appendChild(span);
					ul.appendChild(li2);
				div.appendChild(ul);
				break;
				
				case "equipamento": /*################################################ EQUIPAMENTO*/
					var modelo = trim(formulario.campo_modelo.value);
					var pdf = trim(formulario.campo_file.value);
					pdf = pdf.slice(pdf.lastIndexOf('\\')+1);
					var div = document.createElement("div");
						div.setAttribute("id", "equipamento"+id);
						div.setAttribute("class", "lista");
						div.setAttribute("className", "lista");
					var ul = document.createElement("ul");
						var li = document.createElement("li")
							var img = document.createElement("img");
								img.setAttribute("src", "estrutura/erro.gif");
								img.setAttribute("style", "cursor: pointer;");
								img.onclick = function () { excluir(id, 'equipamento'); };
						li.appendChild(img);
					ul.appendChild(li);
				div.appendChild(ul);
					var ul = document.createElement("ul");
						var li = document.createElement("li");
							var strong = document.createElement("strong");
								strong.appendChild(document.createTextNode("Modelo: "));
						li.appendChild(strong);
					ul.appendChild(li);
						var li2 = document.createElement("li");
							var span = document.createElement("span");
								span.setAttribute("id", "modelo"+id);
								span.appendChild(document.createTextNode(modelo));
								span.onclick = function () { editar(id, this, 'input', 'equipamento', '1'); };
						li2.appendChild(span);
					ul.appendChild(li2);
				div.appendChild(ul);
					var ul = document.createElement("ul");
						var li = document.createElement("li");
							var strong = document.createElement("strong");
								strong.appendChild(document.createTextNode("PDF: "));
						li.appendChild(strong);
					ul.appendChild(li);
						var li2 = document.createElement("li");
							var span = document.createElement("span");
								span.setAttribute("id", "pdf"+id);
								span.appendChild(document.createTextNode(pdf));
						li2.appendChild(span);
					ul.appendChild(li2);
				div.appendChild(ul);
				break;

				case "semi_novo": /*################################################ SEMI_NOVOS*/
					var descricao = trim(formulario.campo_descricao.value);
					var pdf = trim(formulario.campo_file.value);
					pdf = pdf.slice(pdf.lastIndexOf('\\')+1);
					var div = document.createElement("div");
						div.setAttribute("id", "semi_novo"+id);
						div.setAttribute("class", "lista")
						div.setAttribute("className", "lista")
							var ul = document.createElement("ul");
								var li = document.createElement("li")
									var img = document.createElement("img");
										img.setAttribute("src", "estrutura/erro.gif");
										img.setAttribute("style", "cursor: pointer;");
										img.onclick = function () { excluir(id, 'semi_novo'); };
								li.appendChild(img);
							ul.appendChild(li);
						div.appendChild(ul);
							var ul = document.createElement("ul");
								var li = document.createElement("li");
									var strong = document.createElement("strong");
										strong.appendChild(document.createTextNode("Descrição: "));
								li.appendChild(strong);
							ul.appendChild(li);
								var li2 = document.createElement("li");
									var span = document.createElement("span");
										span.setAttribute("id", "descricao"+id);
										span.appendChild(document.createTextNode(descricao));
										span.onclick = function () { editar(id, this, 'input', 'semi_novo', '1'); };
								li2.appendChild(span);
							ul.appendChild(li2);
						div.appendChild(ul);
							var ul = document.createElement("ul");
								var li = document.createElement("li");
									var strong = document.createElement("strong");
										strong.appendChild(document.createTextNode("PDF: "));
								li.appendChild(strong);
							ul.appendChild(li);
								var li2 = document.createElement("li");
									var span = document.createElement("span");
										span.setAttribute("id", "pdf"+id);
										span.appendChild(document.createTextNode(pdf));
								li2.appendChild(span);
							ul.appendChild(li2);
						div.appendChild(ul);
				break;

				case "cliente": /*################################################ CLIENTE*/
					var nome = trim(formulario.campo_nome.value);
					var div = document.createElement("div");
						div.setAttribute("id", "cliente"+id);
						div.setAttribute("class", "lista")
						div.setAttribute("className", "lista")
							var ul = document.createElement("ul");
								var li = document.createElement("li")
									var img = document.createElement("img");
										img.setAttribute("src", "estrutura/erro.gif");
										img.setAttribute("style", "cursor: pointer;");
										img.onclick = function () { excluir(id, 'cliente'); };
								li.appendChild(img);
							ul.appendChild(li);
						div.appendChild(ul);
							var ul = document.createElement("ul");
								var li = document.createElement("li");
									var strong = document.createElement("strong");
										strong.appendChild(document.createTextNode("Nome: "));
								li.appendChild(strong);
							ul.appendChild(li);
								var li2 = document.createElement("li");
									var span = document.createElement("span");
										span.setAttribute("id", "nome"+id);
										span.appendChild(document.createTextNode(nome));
										span.onclick = function () { editar(id, this, 'input', 'cliente', '1'); };
								li2.appendChild(span);
							ul.appendChild(li2);
						div.appendChild(ul);
				break;

				case "usuario": /*################################################ USUARIO*/
					var nome = trim(formulario.campo_nome.value);
					var login = trim(formulario.campo_login.value);
					var senha = trim(formulario.campo_senha.value);
					var div = document.createElement("div");
						div.setAttribute("id", "usuario"+id);
						div.setAttribute("class", "lista")
						div.setAttribute("className", "lista")
							var ul = document.createElement("ul");
								var li = document.createElement("li")
									var img = document.createElement("img");
										img.setAttribute("src", "estrutura/erro.gif");
										img.setAttribute("style", "cursor: pointer;");
										img.onclick = function () { excluir(id, 'usuario'); };
								li.appendChild(img);
							ul.appendChild(li);
						div.appendChild(ul);
							var ul = document.createElement("ul");
								var li = document.createElement("li");
									var strong = document.createElement("strong");
										strong.appendChild(document.createTextNode("Nome: "));
								li.appendChild(strong);
							ul.appendChild(li);
								var li2 = document.createElement("li");
									var span = document.createElement("span");
										span.setAttribute("id", "nome"+id);
										span.appendChild(document.createTextNode(nome));
										span.onclick = function () { editar(id, this, 'input', 'usuario', '1'); };
								li2.appendChild(span);
							ul.appendChild(li2);
						div.appendChild(ul);
							var ul = document.createElement("ul");
								var li = document.createElement("li");
									var strong = document.createElement("strong");
										strong.appendChild(document.createTextNode("Login: "));
								li.appendChild(strong);
							ul.appendChild(li);
								var li2 = document.createElement("li");
									var span = document.createElement("span");
										span.setAttribute("id", "login"+id);
										span.appendChild(document.createTextNode(login));
										span.onclick = function () { editar(id, this, 'input', 'usuario', '2'); };
								li2.appendChild(span);
							ul.appendChild(li2);
						div.appendChild(ul);
							var ul = document.createElement("ul");
								var li = document.createElement("li");
									var strong = document.createElement("strong");
										strong.appendChild(document.createTextNode("Senha: "));
								li.appendChild(strong);
							ul.appendChild(li);
								var li2 = document.createElement("li");
									var span = document.createElement("span");
										span.setAttribute("id", "senha"+id);
										span.appendChild(document.createTextNode(senha));
										span.onclick = function () { editar(id, this, 'input', 'usuario', '3'); };
								li2.appendChild(span);
							ul.appendChild(li2);
						div.appendChild(ul);
				break;
			}
			formulario.reset();
			loading("hide");
			if(elemento.appendChild(div)) {
				loading("hide");
				return alert("Cadastro efetuado com sucesso!");			
			} else {
				loading("hide");
				return alert("Cadastro efetuado com sucesso, mas o registro não pode ser inserido na lista.");			
			}
		} else {
			return alert("Elemento não encontrado")
		}
	}
}

function editar(id, local, campo, tipo, titulo) {
	/*
	 * id = id do elemento
	 * local = local aonde esta o elemento
	 * campo = tipo de campo (input, textarea)
	 * tipo = tipo de edicao (projeto, etc)
	 * titulo = titulo do campo a ser editado (titulo, descricao, pdf);
	 */
	var elemento = document.getElementById(local.getAttribute("id"));
	if (elemento) {
		var valor_original = elemento.innerHTML;
		switch (campo) {
		case "input":
			var incluir = document.createElement("input");
				incluir.setAttribute("name","editor");
				incluir.setAttribute("type","text");
				incluir.setAttribute("class","editar_input");
				incluir.setAttribute("className","editar_input");
				incluir.setAttribute("id","editor");
				incluir.setAttribute("value",valor_original);
				incluir.setAttribute("size","70");
		break;
		case "textarea":
			var valor_br = valor_original.replace(/<br>|<\/br>|<br\/>/gi, "\r");
			var incluir = document.createElement("textarea");
				incluir.setAttribute("name","editor");
				incluir.setAttribute("class","editar_textarea");
				incluir.setAttribute("className","editar_textarea");
				incluir.setAttribute("id","editor");
				incluir.appendChild(document.createTextNode(valor_br));
		break;
		}
		elemento.parentNode.replaceChild(incluir, elemento);
		incluir.focus();
		incluir.onblur = function () {
			var editor = document.getElementById("editor");
			if (editor) {
				if(campo == "textarea") {
					var valor_novo = editor.value;
					valor_novo = valor_novo.replace(/\n/gi, "<br>");
				} else {
					var valor_novo = editor.value;
				}
				if(valor_original != valor_novo && valor_novo.length > 0) {
					var dados = "acao=editar"; //acao
					dados += "&tipo="+tipo; //tipo (projeto, etc)
					dados += "&campo="+titulo; //campo a ser editado
					dados += "&id="+id;
					dados += "&valor="+valor_novo.replace(/<br>|<\/br>|<br\/>/gi, "\n");
					var enviar = false;
					if (window.XMLHttpRequest) { //mozilla.
						enviar = new XMLHttpRequest();
					} else if (window.ActiveXObject) { //IE
						enviar = ObjMSXMLHttp();
					}
					enviar.open("POST", "intranet.php", true);
					enviar.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
					enviar.onreadystatechange = function() {
						if(enviar.readyState == 1) {
							loading("show");
						}
						if(enviar.readyState == 4) {
							if(enviar.status == 200) {
								loading("hide");
								var response = enviar.responseText;
								if(trim(response) == "ok") {
									var span = document.createElement("span");
										span.setAttribute("id",local.getAttribute("id"));
										span.onclick = function () {editar(id, local, campo, tipo, titulo); };
									editor.parentNode.replaceChild(span, editor);
									span.innerHTML = valor_novo;
									return alert("Alteração efetuada com sucesso.");
								} else {
									var span = document.createElement("span");
										span.setAttribute("id",local.getAttribute("id"));
										span.onclick = function () {editar(id, local, campo, tipo, titulo); };
									editor.parentNode.replaceChild(span, editor);
									span.innerHTML = valor_original;
									return alert(trim(response));
								}				
							} else {
								return alert("Erro ao carregar os dados");
							}
						}
					}
					enviar.send(dados);	
				} else {
					var span = document.createElement("span");
						span.setAttribute("id",local.getAttribute("id"));
						span.onclick = function () {editar(id, local, campo, tipo, titulo); };
					editor.parentNode.replaceChild(span, editor);
					span.innerHTML = valor_original;
				}
			} else {
				return alert("Elemento nao encontrado.");
			}
		}
	} else {
		return alert("Elemento nao encontrado.");
	}
	
	
}
function excluir(id, tipo) {
	var i = "Atenção!\n";
	i += "Deseja realmente excluir este registro?\n";
	var pergunta = window.confirm(i);
	if (pergunta) {
		loading("show");
		var elemento = document.getElementById(tipo+id);
		if(elemento) {
			var enviar = false;
			if (window.XMLHttpRequest) { //mozilla.
				enviar = new XMLHttpRequest();
			} else if (window.ActiveXObject) { //IE
				enviar = ObjMSXMLHttp();
			}
			var dados = "acao=excluir";
			dados += "&tipo="+tipo;
			dados += "&id="+id;
			enviar.open("POST", "intranet.php", true);
			enviar.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			enviar.onreadystatechange = function() {
				if(enviar.readyState == 1) {
					loading("show");
				}
				if(enviar.readyState == 4) {
					if(enviar.status == 200) {
						loading("hide");
						var response = enviar.responseText;
						if(trim(response) == "ok") {
							var pai = elemento.parentNode;
							pai.removeChild(elemento);
							var j = document.getElementById("lista");
							if (j) {
								var divs = j.getElementsByTagName("div");
								if(divs.length < 1) {
									var div = document.createElement("div");
									div.setAttribute("id","sem_registro");
									div.appendChild(document.createTextNode("Nenhum registro encontrado no banco de dados."));
									j.appendChild(div);
								}								
							} else {
								alert("Removido com sucesso. Elemento nao encontrado.");
							}
							return alert("Removido com sucesso.");
						} else {
							return alert(trim(response));
						}				
					} else {
						return alert("Erro ao carregar os dados");
					}
				}
			}
			enviar.send(dados);		
		} else {
			loading("hide")
			return alert("Elemento nao encontrado");
		}
	} else {
		return false;
	}
}