function $(id) {
	return document.getElementById(id)
}
function redir(url) {
	document.location.href = url;
}
function d(a,b) {
	return interface.display(a,b);
}

function myobject(x){
	this.value = x;
}

String.prototype.trim = function() {
	return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

var interface = {

	pegarObj: function(obj) {
	  if(typeof obj=="undefined")obj=document
	  if(typeof obj=="string")obj=$(obj)
	  return obj
	},
	
	tags: function(tagName, classe) {
		e = document.getElementsByTagName(tagName)
		filtro = [];
		if (classe) {
			n = 0
			for (i=0; i < e.length; i++)
				if (e[i].className.indexOf(classe) > -1) {
					filtro[n] = e[i]
					n =+ 1
				}
		} else 
			filtro = e
		return filtro
	},
	
	byName: function(tag, name) {
        var elem = this.tags(tag);
        var arr = new Array();
        for(i = 0,iarr = 0; i < elem.length; i++) {
	    	att = elem[i].getAttribute("name");
            if(att == name) {
              arr[iarr] = elem[i];
              iarr++;
            }
        }
        return arr;
    }, 
	
	novo: function(tagName,innerHTML) {
		var newTag=document.createElement(tagName)
		if(typeof innerHTML=="string")
		  newTag.innerHTML=innerHTML
		return newTag
	},

	inserirAntes: function(n,o){
	  o=this.pegarObj(o)
	  o.parentNode.insertBefore(n,o)
	},

	substituir: function(n,o){
	  o=this.pegarObj(o)
	  o.parentNode.replaceChild(n,o)
	},

	remover: function(o){
	  o=this.pegarObj(o)
	  o.parentNode.removeChild(o)
	},
	
	removerClasse: function(o,className) {
	  o=this.pegarObj(o)
	  var r=eval("/\\b"+className+"\\b/g")
	  o.className=o.className.replace(r,"")
	},

	mudarClasse: function(id, classA, classB) {
		if (id instanceof Array) 
			for (i=0; i<id.length; i++)	{
				if (typeof classB == 'undefined') classB = ''
				mudar(id[i], classA[i], classB[i])
			} 
		else 
			mudar(id, classA, classB)
		function mudar(id, classA, classB) {
			if (!classB) 
				$(id).className = classA 
			else 
				($(id).className == classA) ? $(id).className = classB : $(id).className = classA 
		}
	},

	tabs: function(id, prefixo, cssAtivo, cssDesativo) {
		for (i=1; i < 100; i++) {
			if ($(prefixo+i)) $(prefixo+i).className = cssDesativo
			if ($(prefixo+'-contexto'+i)) this.display(prefixo+'-contexto'+i, 'none')
		}
		$(prefixo+id).className = cssAtivo
		this.display(prefixo+'-contexto'+id, 'block')
	},
	
	display: function(id, d, overlay) {
		muda = function (id, d) {	
			ob = $(id).style, e = ob.display
			if (d) ob.display = d
			else 
				e!='none' ? ob.display = 'none' : ob.display = ''
		}
		if (id instanceof Array && d instanceof Array) 
			for (i=0; i<id.length; i++)	muda(id[i], d[i])
		else if (id instanceof Array) 
			for (i=0; i<id.length; i++)	muda(id[i], d)
		else muda(id, d)
		if (overlay && overlay == 'overlay') this.overlay()
	},
	
	col_vars: {
		colapse_slideSpeed: 			10,	
		colapse_timer: 					10,	
		objectIdToSlideDown: 			false,
		colapse_activeId: 				false,
		colapse_slideInProgress: 		false
	},
	
	showHideContent: function(e,inputId) { // Apenas esconde o conteudo
		if(this.col_vars.colapse_slideInProgress) return;
		this.col_vars.colapse_slideInProgress = true;
		if(!inputId) inputId = this.id;
		inputId = inputId + '';
		var numericId = inputId.replace(/[^0-9]/g,'');
		var answerDiv = $('colapse_a' + numericId);
	
		this.col_vars.objectIdToSlideDown = false;
		
		if (!answerDiv.style.display || answerDiv.style.display == 'none') {		
			if (this.col_vars.colapse_activeId &&  this.col_vars.colapse_activeId!=numericId) {			
				this.col_vars.objectIdToSlideDown = numericId;
				this.slideContent(this.col_vars.colapse_activeId,(this.col_vars.colapse_slideSpeed*-1));
				this.mudarClasse('colapse-icone-'+this.col_vars.colapse_activeId, 'expandido', 'contraido')
				this.mudarClasse('colapse-icone-'+numericId, 'expandido', 'contraido')
			} else {
				answerDiv.style.display = 'block';
				answerDiv.style.visibility = 'visible';
				this.slideContent(numericId,this.col_vars.colapse_slideSpeed);
				this.mudarClasse('colapse-icone-'+numericId, 'expandido', 'contraido')
			}
		} else {
			this.slideContent(numericId,(this.col_vars.colapse_slideSpeed*-1));
			this.col_vars.colapse_activeId = false;
			this.mudarClasse('colapse-icone-'+numericId, 'expandido', 'contraido')
		}	
	},
	
	slideContent: function(inputId,direction) {
		var obj =$('colapse_a' + inputId);
		var contentObj = $('colapse_ac' + inputId);
		height = obj.clientHeight;
		if (height==0) height = obj.offsetHeight;
		height = height + direction;
		rerunFunction = true;
		if (height>contentObj.offsetHeight) {
			height = contentObj.offsetHeight;
			rerunFunction = false;
		}
		if (height<=1) {
			height = 1;
			rerunFunction = false;
		}
		obj.style.height = height + 'px';
		var topPos = height - contentObj.offsetHeight;
		if (topPos>0) topPos=0;
		contentObj.style.top = topPos + 'px';
		if (rerunFunction) 
			setTimeout('this.slideContent(' + inputId + ',' + direction + ')',this.col_vars.colapse_timer);
		else {
			if(height<=1){
				obj.style.display='none'; 
				if(this.col_vars.objectIdToSlideDown && this.col_vars.objectIdToSlideDown!=inputId){
					this.display('colapse_a' + this.col_vars.objectIdToSlideDown,'block');
					$('colapse_a' + this.col_vars.objectIdToSlideDown).style.visibility='visible';
					this.slideContent(this.col_vars.objectIdToSlideDown,this.col_vars.colapse_slideSpeed);				
				}else{
					this.col_vars.colapse_slideInProgress = false;
				}
			}else{
				this.col_vars.colapse_activeId = inputId;
				this.col_vars.colapse_slideInProgress = false;
			}
		}
	},

	obtemFilho: function(objPai, display) {
		idFilho = objPai.id.split("-")
		idFilho = idFilho[2].split(" ",1)
		/* d(idFilho, display); */
		interface.display(idFilho, display);
	},

	menuDinamico: function() {
		var e = this.tags('LI');
		for(i=0; i<e.length; i++)
			if (e[i].id.indexOf("pai-de-") > -1) {
				e[i].onmouseover = function(){interface.obtemFilho(this,'block')}
				e[i].onmouseout = function(){interface.obtemFilho(this,'')}
			}
	},
	
	confirmaEmail: function(a, b) {
		if ($(a).value!=$(b).value) {
			alert('O e-mail digitado não confirma!')
			$(a).focus()
			return false
		} 
	},
	
	validaCPF: function(cpf) {
	  var nonNumbers = /\D/;
	  if (cpf=="" || cpf.length < 11 || nonNumbers.test(cpf) || cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999") return false
	  var a = [];
	  var b = new Number;
	  var c = 11;
	  for (i=0; i<11; i++) {
			  a[i] = cpf.charAt(i);
			  if (i < 9) b += (a[i] * --c);
	  }
	  if ((x = b % 11) < 2) a[9] = 0 
	  else a[9] = 11-x
	  b = 0;
	  c = 11;
	  for (y=0; y<10; y++) b += (a[y] * c--)
	  	if ((x = b % 11) < 2) a[10] = 0
	  	else a[10] = 11-x
	  if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])) return false
	  return true;
	},

	validaEmail: function(t) {
		return t.replace(/\w[\w\+-\.]*@([\w\+-]+\.)+\w\w+/,"")==""
	},
	validaRequerido: function(t){
		return t!=""
	},
	validaNumerico: function(t){
		return t.replace(/\d/g,"")==""
	},
	validaDDD: function(t){
		return t.replace(/\({0,1}\d\){0,1}/g,"")==""
	},
	validaTelefone: function(t){
		return t.replace(/[\d\-\ ]/g,"")==""
	},
	validaCEP: function(t){
		return t.replace(/\d{5}-?\d{3}/g,"")==""
	},
	validaMoeda: function(t){
		return t.replace(/\d+(\.\d{3})*(,\d\d?)?/,"")==""
	},

	validaForm: function(f) {
		for(var i=0; i < f.length; i++) {
			obj = f.elements[i]
			v = obj.value
			if (!v || v.trim()=="" || obj.type == "radio" && !obj.checked || obj.className.indexOf("validar_") > -1)
				if (obj.className.indexOf("opcional") == -1 && obj.nodeName != 'FIELDSET') {
					if (obj.type == "radio") {
						radios = this.byName('INPUT', obj.name)
						estado = '';
						for (var radio in radios)
							if (radios[radio].checked) estado = 'checado'
						if (estado == '') {
							(!obj.title) ? alert("Por favor, escolha uma opção do campo " + obj.name) : alert(obj.title)
							obj.focus()
							return false
						}
					} else {
							if (v && v.trim() != "") {
								if (obj.className.indexOf("validar_email") > -1 && this.validaEmail(v) == false) {
									alert('E-mail incorreto. Por favor, digite um e-mail v\u00e1lido!')
									obj.focus()
									return false
								} 
								if (obj.className.indexOf("validar_DDD") > -1 && this.validaDDD(v) == false) {
									alert('Por favor, digite apenas n\u00FAmeros para o campo DDD!')
									obj.focus()
									return false
								} 
								if (obj.className.indexOf("validar_Telefone") > -1 && this.validaTelefone(v) == false) {
									alert('Por favor, digite apenas n\u00FAmeros para Telefone!')
									obj.focus()
									return false
								} 
								if (obj.className.indexOf("validar_Confirmacao") > -1) {
									if ($('email').value != $('confirme').value) {
										alert("E-mail n\u00E3o confirma! Por favor, digite novamente!")
										obj.focus()
										return false
									}
								} 
							} else {
								(!obj.title) ? alert("Por favor, preencha o campo " + obj.name) : alert(obj.title)
								obj.focus()
								return false
							}
					}
				} 
		}
	},

	initShowHideDivs: function() {
		var divs = this.tags('DIV');
		var divCounter = 1;
		for(var no=0;no<divs.length;no++){
			if(divs[no].className=='colapse-titulo'){
				divs[no].onclick = this.showHideContent;
				divs[no].title = 'Clique aqui para expandir ou contrair esse item';
				divs[no].id = 'colapse_q'+divCounter;
				var answer = divs[no].nextSibling;
				while(answer && answer.tagName!='DIV'){
					answer = answer.nextSibling;
				}
				answer.id = 'colapse_a'+divCounter;	
				contentDiv = answer.getElementsByTagName('DIV')[0];
				contentDiv.style.top = 0 - contentDiv.offsetHeight + 'px'; 	
				contentDiv.className='colapse-conteudo_content';
				contentDiv.id = 'colapse_ac' + divCounter;
				answer.style.display='none';
				answer.style.height='1px';
				divCounter++;
			}		
		}	
	},
	
	proAjax: function(
						url, 
						parametros, 
						div_retorno, 
						display_retorno, 
						innerHTML_retorno, 
						loading, 
						opcao_alert, 
						msg_alert
					  ) {

		try { 
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); 
		} catch (e) { 
			try { 
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
			} catch (E) { 
				xmlhttp = false; 
			} 
		} 
		if  (!xmlhttp && typeof  XMLHttpRequest != 'undefined' ) { 
			try  { 
				xmlhttp = new  XMLHttpRequest(); 
			} catch  (e) { 
				xmlhttp = false ; 
			} 
		} 
		
		this.display(loading, 'block');
		$(loading).innerHTML = '<img src="imagens/ajax.gif" /><span style="font: 12px Verdana">Processando...</span>';
		xmlhttp.open("POST", url, "TRUE");
		xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=iso-8859-1");
		xmlhttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		xmlhttp.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
		xmlhttp.setRequestHeader("Pragma", "no-cache");
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4) {
				if (xmlhttp.status == 200) {
					retorno=xmlhttp.responseText
					this.display(loading, 'none');
					$(loading).innerHTML = '';	
					this.display(div_retorno, display_retorno);
					if (innerHTML_retorno == "sim") $(div_retorno).innerHTML=retorno;
					if (opcao_alert == "sim") alert(msg_alert);
				} 
				else //a mensagem abaixo pode aparecer tbm se o site nÃƒÂ£o estiver dentro de um servidor
					alert("Ocorreu um erro na sua solicitaÃƒÂ§ÃƒÂ£o(Erro:"+ xmlhttp.status +").\nPor favor, tente novamente dentro de alguns instantes!");
			}
		}
		xmlhttp.send(parametros);
	},

	exemploAjax: function(id) {
		this.proAjax(
							"ajax.html",				 				// url
							"n=n", 										// parametros (completos)
							"ajax-exemplo",								// id da div de retorno
							"block", 									// parametro css display da div de retorno (block/none/inline, etc)
							"sim",										// permitir retorno innerHTML (sim/nao)
							"ajax-exemplo",								// id do elemento loading
							"nao",										// utilizar alert ao finalizar procedimento (sim/nao)
							"n"											// mensagem para o alert (se sim)
						);
		
	},
	
	overlay: function() {
		if (!$('modal-overlay')) {		
			var novaTag = this.novo('div','<div id="modal-overlay" style="background: black; position: absolute; top:0; left:0; filter: alpha(opacity=20); opacity: .2;"></div>')
			var t = this.tags('BODY')
			for(i=0; i < t.length; i++) 
				if (!t[i].id) {
					var id = t[i].id = 'id-momentaneo-overlay'
				} else if (t[i].id) {
					var id = t[i].id
				}
			$(id).appendChild(novaTag)
			w =	document.body.clientWidth
			h =	document.body.clientHeight
			o = $('modal-overlay').style
			o.zIndex = '1'
			o.height = h+'px'
			o.width = w+'px'
		} else if ($('modal-overlay') && $('modal-overlay').style.display == '') {
			this.remover('modal-overlay')
			var t = this.tags('BODY')
			for(i=0; i < t.length; i++) 
				if (t[i].id && t[i].id == 'id-momentaneo-overlay') t[i].id = ''
		}
		var s = this.tags('SELECT')
		for(i=0; i < s.length; i++) this.display(s[i].id)
	},

	modal: function(id_pai, tag, id, classe, pagina, overlay) {
		var n = document.createElement(tag)
		n.setAttribute('id', id)
		$(id_pai).appendChild(n)
		$(id).className = classe
		$(id).style.zIndex = '100'
		this.proAjax(pagina, "", id, "", "sim", id, "", "")
		if (overlay && overlay == 'overlay') this.overlay()
	},
	
	tipoBrowser: function() {
		return navigator.userAgent
	}

} // Fim interface

function setCookie(c_name,value,expiredays) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}
function getCookie(c_name) {
	if (document.cookie.length>0) {
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1) {
			c_start=c_start + c_name.length+1;
			c_end=document.cookie.indexOf(";",c_start);
		if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		}
	}
	return "";
}
setCookie("tentativaAfiliado","");
function init() {
	interface.initShowHideDivs();
	interface.menuDinamico();
}

window.onload = init;
 
