window.onload = function() {
	if(document.getElementById("hasMMMark")) {
		if(document.getElementById("hasMMMark").value=="false")
			listMMMark(false);
		else
			listMMMark(true);
	} else
		listMMMark(false);
		
}
/* para montar a nuvem de tags */
function getTagCloud() {
	
	if(!document.getElementById("category"))
		return;
	tagService.findTagCloud({
		callback:function(dataFromServer) {			
			document.getElementById("category").innerHTML = "";
			for(var i=0; i<dataFromServer.length; i++) {
				var a = document.createElement("a");
				a.id = "tagId_" + dataFromServer[i].tag.id;
				a.className = "tagcloud_scale_" + dataFromServer[i].scale;
				a.href = "/noticias/list.publiblishingObjectByTag.action?tagId=" + dataFromServer[i].tag.id + "&tagName=" + dataFromServer[i].tag.name;
				a.innerHTML = dataFromServer[i].tag.name;
				a.title = "procurar por " + dataFromServer[i].tag.name;
				var li = document.createElement("li");
				li.appendChild(a);
				
				li.appendChild(document.createTextNode(" (" + dataFromServer[i].count + ")"));
				document.getElementById("category").appendChild(li);
			}
		}
	});
}

/* submete formulário de busca de campanhas */
function submitCampanhasSearchForm() {
	//verifica se escolheu um cliente
	var cliente = document.getElementById("cliente");
	if(cliente.options[cliente.selectedIndex].value==0) {
		alert("Selecione um cliente para efetuar a busca");
		return false;
	}
	var ano = document.getElementById("ano");
	var mes = document.getElementById("mes");
	
	/* se escolher ou mês ou ano, deve escolher os dois obrigatoriamente */
	if(mes.options[mes.selectedIndex].value!=0 && ano.options[ano.selectedIndex].value==0) {
		alert("Selecione um ano para efetuar a busca");
		return false;
	}
	
	if(mes.options[mes.selectedIndex].value==0 && ano.options[ano.selectedIndex].value!=0) {
		alert("Selecione um mês para efetuar a busca");
		return false;
	}
	
	//precisa selecionar pelo menos um tipo de mídia
	/*if(!document.getElementById("midia_filme").checked && 
	   !document.getElementById("midia_impressa").checked &&
	   !document.getElementById("midia_audio").checked &&
	   !document.getElementById("midia_web").checked &&
	   !document.getElementById("midia_exterior").checked &&
	   !document.getElementById("midia_promocional").checked) {
	   	alert("Selecione pelo menos um tipo de mídia para efetuar a busca");
		return false;
	  }
	*/
	//popula os campos hidden a partir dos checkboxes
	if(document.getElementById("midia_filme").checked)
		document.getElementById("midia_filme_submit").value = "true";
	if(document.getElementById("midia_impressa").checked)
		document.getElementById("midia_impressao_submit").value = "true";
	if(document.getElementById("midia_audio").checked)
		document.getElementById("midia_audio_submit").value = "true";
	if(document.getElementById("midia_promocional").checked)
		document.getElementById("midia_promocional_submit").value = "true";
	if(document.getElementById("midia_web").checked)
		document.getElementById("midia_web_submit").value = "true";
	if(document.getElementById("midia_exterior").checked)
		document.getElementById("midia_exterior_submit").value = "true";
	
	document.getElementById('form_campanhas').submit();
}

function getFolders(folderId) {
	var option = document.createElement("option");
	option.value = "-1";
	option.innerHTML = "Aguarde, carregando...";
	document.getElementById("produto").appendChild(option);
	coreService.getFolders(folderId, null, true, {
	callback:function(dataFromServer) {
		DWRUtil.removeAllOptions("produto");
		var option = document.createElement("option");
		option.value = "-1";
		option.innerHTML = "Produto";
		document.getElementById("produto").appendChild(option);
		for(i=0; i<dataFromServer.length; i++) {
			var option = document.createElement("option");
			option.value = dataFromServer[i].id;
			option.innerHTML = dataFromServer[i].name;
			document.getElementById("produto").appendChild(option);
		}
		}
	});
}

function checkContato() {
	var msg = "";
	if(document.getElementById("nome") && document.getElementById("nome").value.replace(/^\s+|\s+$/, "")=="")
		msg+="Campo nome obrigatório.\n"
	//if(document.getElementById("telefone") && (document.getElementById("telefone").value.replace(/^\s+|\s+$/, "")=="" || document.getElementById("telefone").value.replace(/^\s+|\s+$/, "").length<8))
	//	msg+="Campo telefone obrigatório.\n"
	if(document.getElementById("email")){
		if(document.getElementById("email").value.replace(/^\s+|\s+$/, "")=="")
			msg+="Campo e-mail obrigatório.\n"
		else if(document.getElementById("email").value.indexOf("@")==-1 || document.getElementById("email").value.lastIndexOf(".")==-1 || document.getElementById("email").value.indexOf("@")+1 > document.getElementById("email").value.lastIndexOf("."))
			msg+="Campo e-mail inválido.\n"
	}
	if(document.getElementById("mensagem") && document.getElementById("mensagem").value.replace(/^\s+|\s+$/, "")=="")
		msg+="Campo mensagem obrigatório.\n"
		
	//verifica área/assunto selecionado
	//if(document.getElementById("assunto") && document.getElementById("area")){
	  if(document.getElementById("assunto")){
		var assunto = document.getElementById("assunto").options[document.getElementById("assunto").selectedIndex].value;
		//var area = document.getElementById("area").options[document.getElementById("area").selectedIndex].value;
	
		/*if(area!=-1)
			document.getElementById("to").value = area;
		else*/ if (assunto!=-1)
			document.getElementById("to").value = assunto;
		else
			msg+="Campo assunto necessário.\n"
	}



	if(msg.length>0){
		alert(msg);
		return false;
	}
	return true;
}

function checkNews() {
	var msg = "";
	if(document.getElementById("nome") && document.getElementById("nome").value.replace(/^\s+|\s+$/, "")=="")
		msg+="Campo nome obrigatório.\n"
	if(document.getElementById("email")){
		if(document.getElementById("email").value.replace(/^\s+|\s+$/, "")=="")
			msg+="Campo e-mail obrigatório.\n"
		else if(document.getElementById("email").value.indexOf("@")==-1 || document.getElementById("email").value.lastIndexOf(".")==-1 || document.getElementById("email").value.indexOf("@")+1 > document.getElementById("email").value.lastIndexOf("."))
			msg+="Campo e-mail inválido.\n"
	}
		
	
	if(msg.length>0){
		alert(msg);
		return false;
	}
	return true;
	
}

function checkTrabalhe() {
	var msg = "";
	
	var areaStats = true;
	var to = document.getElementsByName("to");
	for(i=0; i<to.length; i++) 
		if(to[i].checked)
			areaStats = false;
	if(areaStats)
		msg+="Selecione uma área.\n"
	
	if(document.getElementById("nome") && document.getElementById("nome").value.replace(/^\s+|\s+$/, "")=="")
		msg+="Campo nome obrigatório.\n"
	if(document.getElementById("telefone") && (document.getElementById("telefone").value.replace(/^\s+|\s+$/, "")=="" || document.getElementById("telefone").value.replace(/^\s+|\s+$/, "").length<8))
		msg+="Campo telefone obrigatório.\n"
	if(document.getElementById("email")){
		if(document.getElementById("email").value.replace(/^\s+|\s+$/, "")=="")
			msg+="Campo e-mail obrigatório.\n"
		else if(document.getElementById("email").value.indexOf("@")==-1 || document.getElementById("email").value.lastIndexOf(".")==-1 || document.getElementById("email").value.indexOf("@")+1 > document.getElementById("email").value.lastIndexOf("."))
			msg+="Campo e-mail inválido.\n"
	}
	if(document.getElementById("mensagem") && document.getElementById("mensagem").value.replace(/^\s+|\s+$/, "")=="")
		msg+="Campo mensagem obrigatório.\n"
		
	if(document.getElementById("anexo")){
		if(document.getElementById("anexo").value.replace(/^\s+|\s+$/, "")=="")
			msg+="Anexe seu currículo.\n"
		else{ 
			if(document.getElementById("anexo").value.lastIndexOf(".")>0){
				var fileType = document.getElementById("anexo").value.substring(document.getElementById("anexo").value.lastIndexOf(".")+1)
				if(!(fileType=="doc"||fileType=="pdf"||fileType=="rtf"||fileType=="odt"))
					msg+="Seu currículo deve estar no formato word, pdf ou rtf.\n"
			}
		}
	}
	if(document.getElementById("assunto") && document.getElementById("area")){
		var assunto = document.getElementById("assunto").options[document.getElementById("assunto").selectedIndex].value;
		var area = document.getElementById("area").options[document.getElementById("area").selectedIndex].value;
	
		if(area!=-1)
			document.getElementById("to").value = area;
		else if (assunto!=-1)
			document.getElementById("to").value = assunto;
		else
			msg+="Campo assunto ou área necessário.\n"
	}
	if(msg.length>0){
		alert(msg);
		return false;
	}
	return true;
}
/*function selecionaAssunto(field) {
	if(field=="perguntas" || field=="outros") {
		document.getElementById("area").disabled = "";
	} else {
		document.getElementById("area").disabled = "disabled";
		document.getElementById("area").options[0].selected = "selected";
	}
}*/

// Retorno do flash de Widget Wallpaper
function downloadWallpaper(ID, URI800, URI1024){
	var wp800 = document.getElementById("wp800");
	var wp1024 = document.getElementById("wp1024");
	var fotoWallpaper = document.getElementById("fotoWallpaper");
	fotoWallpaper.src = ID;
	wp800.href = URI800;
	wp1024.href = URI1024;
}
// Retorno do flash de Widget Livros
function downloadLivros(DISPLAY,URI,TITLE,DESCRIPTION){
    var linkLivro = document.getElementById("linkLivro");
    var imgLivro = document.getElementById("imgLivro");
    var fotoLivro = document.getElementById("fotoLivro");
	var titleLivro = document.getElementById("titleLivro");
    var descriptionLivro = document.getElementById("descriptionLivro");
    linkLivro.href = URI;
    imgLivro.href = URI;
    fotoLivro.src = DISPLAY;
	titleLivro.innerHTML = TITLE;
	descriptionLivro.innerHTML = DESCRIPTION; 
}


function loadBranches() {
	var option = document.createElement("option");
	option.value = "-1";
	option.innerHTML = "Aguarde, carregando...";
	document.getElementById("estados").appendChild(option);
	companyService.getBranches(null, "402880e4179776fa011798aaf3730007", {
	callback:function(dataFromServer) {
		$("#estados option").remove();
		var option = document.createElement("option");
		option.value = "";
		option.innerHTML = "Selecione um estado";
		document.getElementById("estados").appendChild(option);
		for(i=0; i<dataFromServer.length; i++) {
			var option = document.createElement("option");
			option.value = dataFromServer[i].id;
			option.innerHTML = dataFromServer[i].name;
			$("#estados").append(option);
		}
		}
	});
}

function loadDepartments(branchId) {
	var option = document.createElement("option");
	option.value = "-1";
	option.innerHTML = "Aguarde, carregando...";
	document.getElementById("area").appendChild(option);
	companyService.getDepartments(null, branchId, {
	callback:function(dataFromServer) {
		$("#area option").remove();
		var option = document.createElement("option");
		option.value = "";
		option.innerHTML = "Selecione uma área";
		document.getElementById("area").appendChild(option);
		for(i=0; i<dataFromServer.length; i++) {
			var option = document.createElement("option");
			option.value = dataFromServer[i].id;
			option.innerHTML = dataFromServer[i].name;
			$("#area").append(option);
		}
		}
	});
}

function submitUserForm() {
	/*
	if($("#estados option:selected").val()=="" || $("#area option:selected").val()=="") {
		alert("Selecione o estado e a área");
		return false;
	}
	$("#user_search_form").submit();
	* */
	if($("#estados option:selected").val()=="-1") {
		alert("Selecione a área");
		return false;
	}
	var vals = $("#estados option:selected").val().split("_");
	document.getElementById("user_branch").value = vals[0];
	document.getElementById("user_department").value = vals[1];
	document.getElementById("departmentName").value = document.getElementById("estados").options[document.getElementById("estados").selectedIndex].innerHTML;
	document.getElementById("branchName").value = vals[2];
	$("#user_search_form").submit();
	
}

//busca produtos
function getFolders() {
	var folderId = $("#cliente option:selected").val()
	if(folderId=="0"){
		alert("Selecione um cliente válido.")
		return }
	var option = document.createElement("option");
	option.value = "-1";
	option.innerHTML = "Aguarde, carregando...";
	$("#produto").append(option);
	coreService.getFolders(folderId, null, true, {
	callback:function(dataFromServer) {
		$("#produto option").remove();
		var option = document.createElement("option");
		option.value = "-1";
		option.innerHTML = "Produto";
		$("#produto").append(option);
		for(i=0; i<dataFromServer.length; i++) {
			var option = document.createElement("option");
			option.value = dataFromServer[i].id;
			option.innerHTML = dataFromServer[i].name;
			$("#produto").append(option);
		}
		}
	});
}

//retorna as tags cadastradas no delicious
function getTagsFromDelicious() {
    var url = document.location.href;
	if(url.indexOf('?')>0)
		url = url.slice(0, url.indexOf('?'))
		
	var ct = $("#category");
	ct.empty();
	
	for (var k in Delicious.tags) {
    	var count = Delicious.tags[k];
    	var li = document.createElement('li');
		var a = document.createElement('a');
		a.appendChild(document.createTextNode(k +' '));
		a.setAttribute('href', url+'?tag='+k);
		li.appendChild(a);
		li.appendChild(document.createTextNode("(" + count + ")"));
        ct.append(li);        
	}
}

function sendFormFaleConosco(topic, area, msg, email) {
	var error = ""
	if(msg)
		if(msg.replace(/^\s+|\s+$/, "")=="" || msg=="Seu texto vai aqui.")
			error+="Campo de mensagem é de preenchimento obrigatório.\n"
	if(email){
		if(email.replace(/^\s+|\s+$/, "")=="" || email=="Seu e-mail vai aqui.")
			error+="Campo e-mail é de preenchimento obrigatório.\n"
		else if(email.indexOf("@")==-1 || email.lastIndexOf(".")==-1 || email.indexOf("@")+1 > email.lastIndexOf("."))
			error+="Campo e-mail inválido.\n"
	}
	if(!topic || !area)
		error+="Selecione um assunto."
	if(error.length>1){
		alert(error);
		return false;
	}
	var url = "/home/admin.mail.send.action";
	//var pars = "?to=" + area + "&from=from&subject=Contato W/Brasil&topic=" + topic + "&msg=" + msg + "&email=" + email + "&mailTemplate=home&keepThis=true&TB_iframe=false&width=430&height=114&modal=true";
	var pars = "?to=" + area + "&from=from&subject=Contato W/Brasil&topic=" + topic + "&msg=" + msg + "&email=" + email + "&mailTemplate=home&keepThis=true&TB_iframe=false&width=430&height=114&modal=true";
	tb_show("", url + pars, false);
	
}

function setMMMark() {
	if($("#hasMMMark").val()=="false"){
		$("#hasMMMark").val("true")
		$('#mmMarks').attr("src","/img/icon.gif");
	} else{
		$("#hasMMMark").val("false")
		$('#mmMarks').attr("src","/img/icon_off.gif");
	}
	var iframe = document.createElement("iframe");
	iframe.setAttribute("id", "tempFrame")
	iframe.setAttribute("src", "/mmMark/homepage.wbr?mmmark=" + $("#hasMMMark").val());
	document.body.appendChild(iframe);
	iframe.style.display = "none";
}

function listMMMark(isToShow) {
	//percorre lista de links e verifica se é mmMark
	var links = $("a");
	if(isToShow){
		$("#hasMMMark").val("true")
		$('#mmMarks').attr("src","/img/icon.gif");
	} else{
		$("#hasMMMark").val("false")
		$('#mmMarks').attr("src","/img/icon_off.gif");
	}
	
	for(i=0; i<links.length; i++) {
		if(links[i].className=="mmmark") {			
			links[i].style.visibility = (isToShow)?"visible":"hidden";
		}
	}
	
}