//Event.observe(window, 'load', initialize)
function initialize() {
	// Validacao do campo de busca principal
	var buscar = document.search.keywords;
	  if(buscar.value.blank()){
	  	alert(searchfield);
		
	  }
		else{$("search").submit()}
		
	maskInputs();
	validateForms();

}
function advanced(){
	
// Validacao do campo de busca avançada
	var busca = document.getElementById('pesq');
	  if(busca.value.blank()){
	  	alert(searchfield);
		
	  }
		else{$("createUser").submit()}
		
	maskInputs();
	validateForms();
}	
function validateForms(){
	$A(document.getElementsByTagName('form')).each(function(elem){
		Event.observe(elem, 'submit', function(e){
			var error = "";
			$A(e.element().getElements()).each(function(e){
				var title = (e.title)? e.title:e.name;
				if(e.tagName=="INPUT" || e.tagName=="SELECT" || e.tagName=="TEXTAREA"){
					e.removeClassName("error");
					// Preenchimento obrigatório
					if(e.hasClassName("required"))
						if(e.type=="checkbox"){ // Checkbox marcado
							if(!e.checked){
								error+="O item " + title + " é de marcação obrigatória.<br/>";
								e.addClassName("error");
							}
						}
						else if($F(e).blank() || $F(e)=="-1"){ // Input vazio ou select com valor "" ou "-1"
							error+="O campo " + title + " é de preenchimento obrigatório.<br/>";
							e.addClassName("error");
						}
					// Email
					if(e.hasClassName('email') && !$F(e).blank() && ($F(e).indexOf("@")==-1 || $F(e).lastIndexOf(".")==-1 || $F(e).indexOf("@")+1 > $F(e).lastIndexOf("."))){
						error+="O campo " + title + " tem formato inválido.<br/>";
						e.addClassName("error");
					}
				}
			})
			if(error.length>0){
				if($("error")) {
					$("error").setStyle({ display: "block" });
					$("error").update(error);
				} else
					alert(error);
				Event.stop(e);
			}
		})
	});
}


function maskInputs(){
	$A(document.getElementsByClassName('phone')).each(function(elem){
		if(elem.tagName=="INPUT")
		Event.observe(elem, 'keypress', function(e){
			if(!txtBoxFormat(e.element(), "(99) 9999-9999", e))
				Event.stop(e)
		})
	});
	$A(document.getElementsByClassName('zipCode')).each(function(elem){
		if(elem.tagName=="INPUT")
		Event.observe(elem, 'keypress', function(e){
			if(!txtBoxFormat(e.element(), "99999-999", e))
				Event.stop(e)
		})
	});
	$A(document.getElementsByClassName('rg')).each(function(elem){
		if(elem.tagName=="INPUT")
		Event.observe(elem, 'keypress', function(e){
			if(!txtBoxFormat(e.element(), "99.999.999-X", e))
				Event.stop(e)
		})
	});
	$A(document.getElementsByClassName('date')).each(function(elem){
		if(elem.tagName=="INPUT")
		Event.observe(elem, 'keypress', function(e){
			if(!txtBoxFormat(e.element(), "99/99/9999", e))
				Event.stop(e)
		})
	});	
}

function txtBoxFormat(objeto, sMask, evtKeyPress) {
    var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;

	if(document.all) { // Internet Explorer
		nTecla = evtKeyPress.keyCode;
	} else if(document.layers) { // Nestcape
		nTecla = evtKeyPress.which;
	} else {
		nTecla = evtKeyPress.which;
		if (nTecla == 8) {
			return true;
		}
	}

    sValue = objeto.value;

    // Limpa todos os caracteres de formatação que
    // já estiverem no campo.
    sValue = sValue.toString().replace( "-", "" );
    sValue = sValue.toString().replace( "-", "" );
    sValue = sValue.toString().replace( ".", "" );
    sValue = sValue.toString().replace( ".", "" );
    sValue = sValue.toString().replace( "/", "" );
    sValue = sValue.toString().replace( "/", "" );
    sValue = sValue.toString().replace( ":", "" );
    sValue = sValue.toString().replace( ":", "" );
    sValue = sValue.toString().replace( "(", "" );
    sValue = sValue.toString().replace( "(", "" );
    sValue = sValue.toString().replace( ")", "" );
    sValue = sValue.toString().replace( ")", "" );
    sValue = sValue.toString().replace( " ", "" );
    sValue = sValue.toString().replace( " ", "" );
    fldLen = sValue.length;
    mskLen = sMask.length;

    i = 0;
    nCount = 0;
    sCod = "";
    mskLen = fldLen;

    while (i <= mskLen) {
      bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/") || (sMask.charAt(i) == ":"))
      bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))

      if (bolMask) {
        sCod += sMask.charAt(i);
        mskLen++; }
      else {
        sCod += sValue.charAt(nCount);
        nCount++;
      }

      i++;
    }
	objeto.value = sCod;
    if (nTecla != 8) { // backspace
      if (sMask.charAt(i-1) == "9") { // apenas números...
        return ((nTecla > 47) && (nTecla < 58)); } 
      else { // qualquer caracter...
        return true;
      } 
    }
    else {
      return true;
    }
}
 
function mostraNews(uid){
	if(uid==1){
		$('newsnovas').setStyle({ display: "block", visibility: "visible" });
		$('newsvisualizadas').setStyle({ display: "none", visibility: "hidden" });
		$("viewMostAccessedNews").className = "an2off";
		$("viewRecentNews").className = "an1on";
		
		$("viewRecentNews").onmouseover = function(){};
		$("viewRecentNews").onmouseout = function(){};
		$("viewMostAccessedNews").onmouseover = function(){this.className = "an2on"};
		$("viewMostAccessedNews").onmouseout = function(){this.className = "an2off"};
	} else {
		$('newsnovas').setStyle({ display: "none", visibility: "hidden" });
		$('newsvisualizadas').setStyle({ display: "block", visibility: "visible" });
		$("viewMostAccessedNews").className = "an2on";
		$("viewRecentNews").className = "an1off";

		$("viewMostAccessedNews").onmouseover = function(){};
		$("viewMostAccessedNews").onmouseout = function(){};
		$("viewRecentNews").onmouseover = function(){this.className = "an1on"};
		$("viewRecentNews").onmouseout = function(){this.className = "an1off"};
	}
}
tam = 10;
var inicSize = 1;
function MudaFonte(tipo,elemento){
	if (tipo=="mais") {
		if(inicSize<1.6) inicSize+=0.1;
	} else {
		if(inicSize>1) inicSize-=0.1;
	}
	document.getElementById(elemento).style.fontSize = inicSize+'em';
}

Event.observe(window, 'load', initTree);
function initList(u){
	
	var lis=u.childElements();
	for(var ii=0;ii<lis.length;ii++)
		if(lis[ii].nodeType==1 && lis[ii].getElementsByTagName("ul").length>0){
				//lis[ii].className=($(lis[ii]).down('.active'))?"node_folder_opened":"node_folder_closed"; //deixa o menu lateral com link ativo aberto
			if($(lis[ii]).down('.active')) {
				lis[ii].className = "node_folder_opened"
			}
			//lis[ii].className=($(lis[ii]).down('.active'))?"node_folder_opened":"node_folder_closed"; //deixa o menu lateral com link ativo aberto
				$(lis[ii]).firstDescendant().observe('click', toggleSitemapNode);
				if($(lis[ii]).firstDescendant() && $(lis[ii]).firstDescendant().className=="root")
					lis[ii].className="node_folder_opened";
		}
	var us=u.getElementsByTagName("ul");
	for(var i=0;i<us.length;i++){
		initList($(us[i]))
	}
	
}
function initTree(){
	if($("sitemap")) 
		initList($("sitemap"))
	if($("innermenu")) 
		initList($("innermenu"))
}
function toggleSitemapNode(e){
	var node=e.element().parentNode;
	node.className=(node.className=="node_folder_closed")?"node_folder_opened":"node_folder_closed";
	return false
}
function goToPage(page) {
	$("startObject_header").disabled = "";
	//$("exibir_porpagina_header").disabled = "";
	$("page").value = page;
	$("search").submit();
}
function sortSearch(sort) {
	$("page").value = 0;
	$("startObject_header").disabled = "";
	//$("exibir_porpagina_header").disabled = "";
	$("sortSearch").value = sort;
	$("search").submit();
}

/*function viewLanguages(field) {
	if(field.className=="invisible_lang") {
		field.className = "visible_lang";
		$("lang_lists").style.display = "block";
	} else {
		field.className = "invisible_lang";
		$("lang_lists").style.display = "none";
	}
}*/

function hideLanguages() {
	$("lang_lists").style.display = "none";
}

function contactSubmit() {
	
	var allow = true;
	var inputs = $A($("contact").getElementsByTagName("input"));
	inputs.each(function(field) {
		if($F(field)=="") {
			allow = false;
		}
	});
	alert(allow);
	if($F("contact_country")==-1 || !allow) {
		alert(fillallfields);
		return false;
	}
	
	if($F("contact_country")=="talkto.brazil")
		$("mailTemplate").value = "talkto_pt";
	else
		$("mailTemplate").value = "talkto_es";
	
	var url = $("contact").action;
	var pars = $("contact").serialize() + "&rnd=" + Math.random()*4;
	var myAjax = new Ajax.Updater( 
		{}, 
		url, { 
			method: "post", 
			parameters: pars,
			onFailure: function(request) {
				$("textdiv").update(request.responseText);
			}, 
			onSuccess: function(request) {
				$("textdiv").update(request.responseText);
			}
	});
	return false;
}

function phoneAreaSelect(value) {
	//percorre lista e seta todos como invisíveis
	var array = $$('div.phone_area_detail');
	for(var i=0; i<array.length; i++) {
		array[i].style.display = "none";
	}

	if($("area_" + value))
		$("area_" + value).style.display="block";
}

function signInSubmit() {
	var allow = true;
	var inputs = $A($("professionalAnduserfields").getElementsByTagName("input"));
	var cel = $("fullName");
	var phone = $("phone");
	var mail = $("mail");
	var birthDate = $("birthDate");
	
		if(cel.value == "") {
			allow = false;
			alert(fillallfields);
		    return false;
		}
		if(phone.value == "") {
			allow = false;
			alert(fillallfields);
		    return false;
		}
		if(mail.value == "") {
			allow = false;
			alert(fillallfields);
		    return false;
		}
		if(birthDate.value == "") {
			allow = false;
			alert(fillallfields);
		    return false;
		}
		inputs.each(function(field) {
		if($F(field)== "") {
			allow = false;
		}
	});

	if($("medias_list") && $F("medias_list")==-1 || !allow) {
		alert(fillallfields);
		return false;
	}
	
	
	$('createUser').submit();
	
}

function popup(url,w,h){
	window.open(url,'Term','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width='+w+',height='+h);
}

function ContactSubmit(){
	//Inclui o email no noReply 
	var email = $F('contact_email');
	$('replyTo').value = email;
	
	var countryName = $('contact_country').options[$('contact_country').selectedIndex].innerHTML;
	$("countryName").value = countryName;
	
	if($('list')!=null) {
		var depName = $('list').options[$('list').selectedIndex].innerHTML;
		$("depName").value = depName;
		
	}
	
	if(countryName!="Global")
		var sub = $("form-subject").value + " - " + countryName;
	else
		var sub = $("form-subject").value
	if(depName!=null && depName!="talkto.global")
		sub += " - " + depName;
	
	$("form-subject").value = sub;
	
	$('contact').submit();
	
	
}
	
function popvideo(video,title){
	window.open('/pop_video.html?video='+video+'&title='+title,'Video','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=320,height=240');
	return false;
}

function SelectArea(select,condition){
	var value = select.value;
	if(value.indexOf(condition) > -1){
		$(condition).style.display='block';
	}else{
		$(condition).style.display='none';
	}
}

function ShowContacts(id){
	if($(id).style.display=="block"){
		$(id).style.display="none";
	}else{
		$(id).style.display="block";
	}
}

function selectMonth(value){
	var path = $F("hpLangId") + "_" + value;
	coreService.getPropertiesByContent($F("idContent"), path,{
		callback:function(dataFromServer) {
			var listInner = $("list");
			var str = "";
			listInner.innerHTML = "";
			if(dataFromServer != ""){
				for(i=0; i<dataFromServer.length; i++) {
					var el = new Element("option", {'value':dataFromServer[i].split(":")[1]}).update(dataFromServer[i].split(":")[0]);
					listInner.insert(el);
					
				}
			}else{
				var el = new Element("option", {}).update("talkto.global");
				listInner.insert(el);
			}
			if(dataFromServer!=null && dataFromServer != "" && dataFromServer!=" "){
				$("deps_list").style.visibility="visible";
			}else{
				$("deps_list").style.visibility="hidden";
			}

			return false;
		}
	});
}

	
function ContactSubmitBR(){
	//Inclui o email no noReply 
	var email = $F('contact_email');
	$('replyTo').value = email;
	
	if($F("contact_area")=="view.message.talkto.area.press")
		$("frm_to").value = "imprensa@atento.com.br";
	else if($F("contact_area")=="view.message.form.contactbr.rh")
		$("frm_to").value = "atendimentopessoas@atento.com.br";
	else
		$("frm_to").value = "atento@atento.com.br";

	$("form-subject").value = "Atento.com - Brasil - " +  $('contact_area').options[$('contact_area').selectedIndex].innerHTML;
	$('contact').submit();
}

function onnload(){
	var value = ($('contact_country').value);
	var path = $F("hpLangId") + "_" + value;
	coreService.getPropertiesByContent($F("idContent"), path,{
		callback:function(dataFromServer) {
			var listInner = $("list");
			var str = "";
			listInner.innerHTML = "";
			if(dataFromServer != ""){
				for(i=0; i<dataFromServer.length; i++) {
					var el = new Element("option", {'value':dataFromServer[i].split(":")[1]}).update(dataFromServer[i].split(":")[0]);
					listInner.insert(el);
				}
				
			}else{
				var el = new Element("option", {}).update("talkto.global");
				listInner.insert(el);
			}
			if(dataFromServer!=null && dataFromServer != "" && dataFromServer!=" "){
				$("deps_list").style.visibility="visible";
			}else{
				$("deps_list").style.visibility="hidden";
			}
				
			return false;
		}
	});
}

Event.observe(window, 'load', function() {
	var spans = $("breadcrumbs").getElementsByTagName("span");
	var sp = spans[spans.length - 1];
	sp.setStyle({ fontWeight: "bold"});
});
