	path = 'http://primatadesign.com/';

	function validaCPF(numcpf){
		cpf = numcpf.replace(/\D/g,"");
		len = cpf.length;
		while(cpf.length < 11){ cpf = "0"+cpf; }
		if (cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999") return false;
		add = 0;
		for (i=0; i < 9; i ++) add += parseInt(cpf.charAt(i)) * (10 - i);
		rev = 11 - (add % 11);
		if (rev == 10 || rev == 11)rev = 0;
		if (rev != parseInt(cpf.charAt(9)))return false;
		add = 0;
		for (i = 0; i < 10; i ++)add += parseInt(cpf.charAt(i)) * (11 - i);
		rev = 11 - (add % 11);
		if (rev == 10 || rev == 11)rev = 0;
		if (rev != parseInt(cpf.charAt(10)))return false;
		return true;
	}

	function ajaxInit(){
		var xmlhttp;
		try{ xmlhttp = new XMLHttpRequest(); }
		catch(ee) {
			try{ xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
			catch(e) {
				try{ xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
				catch(E){ xmlhttp = false ;	}
			}
		}
		return xmlhttp;
	}
	
	function carregar(formulario, local){
		if(local != ''){ $("#"+local).html('<img src="'+path+'/img/loading.gif" border="0" />'); }
		ajax = ajaxInit();
		if(ajax){
			ajax.open('POST', path+'ajax.php', true);
			ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			ajax.onreadystatechange = function(){
				if(ajax.readyState == 4){
					if(ajax.status == 200){
						var arrayCampos=ajax.responseText.split("|");
						switch(arrayCampos[0]){
							case 'Newsletter': alert(arrayCampos[1]); break;
							default: alert(arrayCampos[0]);
						}
					}
				}
			}
			var params = capturaDados(formulario);
			ajax.send(params);
		}
	}

	function capturaDados(formulario){
		var arrayFormulario = document.getElementsByTagName('form');
		var campos = '';
		var navegador = navigator.appName;
		var ua = window.navigator.userAgent;
		var msie = ua.indexOf("MSIE")
		if(msie>0) versao = parseInt(ua.substring(msie+5, ua.indexOf(".", msie)));
		else versao = 0;

		if(navegador == 'Netscape' || versao >= 9){
			inicioArray = arrayFormulario[formulario].length;
			i=1;
			for(chaves in arrayFormulario[formulario]){ 
				if(i <= inicioArray ){
					if(campos!=''){ campos = campos + '&' }
					c = arrayFormulario[formulario][chaves].id;
					campos = campos + c + '=' + arrayFormulario[formulario][chaves].value;
				}i++;
			}
		} else {
			nCampos = arrayFormulario[formulario].length;
			totalArray=1;
			for(chaves in arrayFormulario[formulario]){ totalArray++; }
			inicioArray = totalArray-nCampos;
			i=1;
			for(chaves in arrayFormulario[formulario]){ 
				if(i >= inicioArray ){
					if(campos!=''){ campos = campos + '&' }
					c = arrayFormulario[formulario][chaves].id;
					campos = campos + chaves + '=' + arrayFormulario[formulario][chaves].value;
				}i++;
			}
		}
		return campos;
	}

	String.prototype.empty = function(){
		if(this.value == '') return false;
		else return true;
	}
	String.prototype.trim = function(){ return this.replace(/(^\s*)|(\s*$)/g,''); }
	String.prototype.isMail = function(){
		var objExclude = /[^@\-\.\w]|^[_@\.\-]|[\._\-]{2}|[@\.]{2}|(@)[^@]*\1/;
		var objCheck = /@[\w\-]+\./;
		var objCheckEnd = /\.[a-zA-Z]{2,3}$/;
		var strEmail = this;
		if(((strEmail.search(objExclude) != -1) || (strEmail.search(objCheck)) == -1) || (strEmail.search(objCheckEnd) == -1))
			return false;
		else
			return true;
	}

	function openUrl(url, target, params){ window.open(url, target, params); }

	function MM_format(e,src,mask){
		if(window.event){ _TXT = e.keyCode; } else if(e.which){ _TXT = e.which; }
		if(_TXT > 47 && _TXT < 58){
			var j = $('#'+src).val();
			var i = j.length;
			var saida = mask.substring(0,1);
			var texto = mask.substring(i);
			if(texto.substring(0,1) != saida){ $('#'+src).val($('#'+src).val() + texto.substring(0,1)); } 
			return true;
		} else { if(_TXT != 8){ return false; } else { return true; } }
	}

	$(document).ready(function(){
		$('html body div#container div#barra-superior h1').click(function(e){ openUrl(path+'teoria-da-evolucao', '_self', ''); });
		$('html body div#rodape div.centro div.logo').click(function(e){ openUrl(path+'teoria-da-evolucao', '_self', ''); });
		$('#bt-enviar-news').click(function(e){ validacao('formNews'); });
		$('#bt-enviar-contato').click(function(e){ validacao('formContato'); });
		$('.telefone').keypress(function(e){ return MM_format(e,this.id,'## ####-####'); }); $('.telefone').attr('maxlength', 12);
		$(".box-branco-twitter").tweet({
			username: "primatadesign",
			join_text: "auto",
			avatar_size: 32,
			count: 3,
		    auto_join_text_default: "",
			auto_join_text_ed: "",
		    auto_join_text_ing: "",
	        auto_join_text_reply: "",
	        auto_join_text_url: "",
	        loading_text: "carregando..."
	    });
	});

	function get_date_twitter(data){
		var tTime=new Date(Date.parse(data));
		var cTime=new Date();
		var sinceMin=Math.round((cTime-tTime)/60000);
		if(sinceMin==0){
			var sinceSec=Math.round((cTime-tTime)/1000);
			if(sinceSec<10)
				return 'menos de 10 segundos atrás';
			else if(sinceSec<20)
				return 'menos de 20 segundos atrás';
			else
				return 'menos de 30 segundos atrás';
		}
		else if(sinceMin==1){
			var sinceSec=Math.round((cTime-tTime)/1000);
			if(sinceSec==30)
				return 'menos de 30 segundos atrás';
			else if(sinceSec<60)
				return 'menos de 1 minuto atrás';
			else
				return '1 minuto atrás';
		}
		else if(sinceMin<45)
			return sinceMin+' minuto atrás';
		else if(sinceMin>44&&sinceMin<60)
			return 'mais de 1 horá atrás';
		else if(sinceMin<1440){
			var sinceHr=Math.round(sinceMin/60);
			if(sinceHr==1)
				return 'mais de 1 horá atrás';
			else
				return 'mais de '+sinceHr+' horás atrás';
		}
		else if(sinceMin>1439&&sinceMin<2880)
			return '1 dia atrás';
		else{
			var sinceDay=Math.round(sinceMin/1440);
			return sinceDay+' dias atrás';
		}	
	}

	function ativarMenu(a){ $(a).addClass('active'); }

	function validacao(form){
		var str = $("#"+form).serialize();
		var arr = str.split("&");
		for(i=0;i<arr.length;i++){
			fields = arr[i].split("=");
			erro = false;
			if($('#'+fields[0]).hasClass("obrigatorio")){
				msg = 'O campo "'+$('#'+fields[0]).attr('title')+'" é obrigatório!';
				if($('#'+fields[0]).hasClass("email")){ if(!$('#'+fields[0]).val().trim().isMail()){ erro = true; } }
				if($('#'+fields[0]).hasClass("cpf")){ if(!$('#'+fields[0]).val().trim().isCpf()){ erro = true; } }
				if($('#'+fields[0]).hasClass("permalink")){ permalink(fields[0], oldField); }
				if(!$('#'+fields[0]).val().trim()){ erro = true; }
				if($('#'+fields[0]).hasClass("senha") && $('#id').val()){ erro = false; }
				if(erro){ alert(msg); $('#'+fields[0]).focus(); return false; }
				oldField = fields[0];
			}
		}
		$("#"+form).submit();
	}

	function showModal(id, produto){
		$('#promocao').val(produto);
		carregar('formPromocoes', 'conteudoPromocao');
		id = "#"+id;
		showOverlay();
		var winH = $(window).height()/2;
		var winW = $(window).width();
		var modW = $(id).width() + parseInt($(id).css("paddingLeft"))  + parseInt($(id).css("paddingRight"));
		var modH = $(id).height() + parseInt($(id).css("paddingTop"))  + parseInt($(id).css("paddingBottom"));
		//var topX = winH/2-modH/2;
		//if(topX < 20) topX = 10+"px";
		topX = "20px";
		$(id).css({top:topX, left:winW/2-modW/2, zIndex:"11"});
		$('html, body').animate({scrollTop: 0}, 300);
		$(id).fadeIn(1000);
	}

	function showOverlay(){
		if(!document.getElementById("overlay")){ $('<div id="overlay"></div>').insertBefore(document.body.firstChild); }
		$("#overlay").css({ backgroundColor:"#000000", zIndex:"10", width:"100%", height:"100%", display:"none", top:"0", left:"0" });
		if(navigator.userAgent.toLowerCase().indexOf("msie 6") != -1){ $("#overlay").css({position: "absolute", height: $(document).height()}); }
		else{ $("#overlay").css("position", "fixed"); }
		$("#overlay").fadeIn(600);
		$("#overlay").fadeTo("slow",0.6);
		$('.closeOverlay').click(function(e){ e.preventDefault(); $("#overlay").fadeOut(500); $('.modal').hide(); $('#conteudoPromocao').html(''); });
	}

	function hideModal(){ $("#overlay").fadeOut(500); $('.modal').hide(); $('#conteudoPromocao').html(''); }

	function fmtMoney(n, c, d, t){
	   var m = (c = Math.abs(c) + 1 ? c : 2, d = d || ",", t = t || ".", /(\d+)(?:(\.\d+)|)/.exec(n + "")), x = m[1].length > 3 ? m[1].length % 3 : 0;
	   return (x ? m[1].substr(0, x) + t : "") + m[1].substr(x).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + (+m[2] || 0).toFixed(c).substr(2) : "");
	}
