	/* -------------------------------------------------------------------------------------------------
				Função que retorna o elemento buscando-o pelo id.
------------------------------------------------------------------------------------------------- */
function $(name)
{
	//try {
		if ("undefined" == typeof(document.getElementById) || "unknown" == typeof(document.getElementById) || null == document.getElementById) {
			return document.getElementById(name);
		}
		if (document.all != null) {
			return document.all[name];
		}
//	} catch () {
		alert("Erro ao tentar encontrar o elemento!\n\n'" + name + "'");
		return null;
	//}
	
	alert("Erro ao tentar encontrar o elemento!\n\n'" + name + "'");
	return null;
}

/* -------------------------------------------------------------------------------------------------
				Função que retorna o valor de um elemento
------------------------------------------------------------------------------------------------- */
function $v(name)
{
	if (!isNull$(name) && !isNull($(name).value)) {
		return $(name).value;
	}

	return null;
}

/* -------------------------------------------------------------------------------------------------
				Função para exibir uma mensagem com as dimensões do elemento.
------------------------------------------------------------------------------------------------- */
function dimensionShow(id)
{
	if ($(id) != null) {
		alert('offsetWidth ' + $(id).offsetWidth + '\n\n' + 'offsetHeight ' + $(id).offsetHeight);
	}
}

/* -------------------------------------------------------------------------------------------------
				Função para verificar se o elemento é nulo.
------------------------------------------------------------------------------------------------- */
function isNull(o)
{
	return ("undefined" == typeof(o) || "unknown" == typeof(o) || null == o);
}

/* -------------------------------------------------------------------------------------------------
				Função para verificar se o elemento é nulo, pelo id.
------------------------------------------------------------------------------------------------- */
function isNull$(o)
{
	return isNull($(o));
}

/* -------------------------------------------------------------------------------------------------
				Função para remover os espaços em branco do início do texto.
------------------------------------------------------------------------------------------------- */
function lTrim( value )
{
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
}

/* -------------------------------------------------------------------------------------------------
				Função para remover os espaços em branco do fim do texto.
------------------------------------------------------------------------------------------------- */
function rTrim( value )
{
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
}

/* -------------------------------------------------------------------------------------------------
				Função para remover espaços em branco do fim e início do texto.
------------------------------------------------------------------------------------------------- */
function trim( value )
{
	return lTrim(rTrim(value));
}

/* -------------------------------------------------------------------------------------------------
				Propriedade no tipo String que executa o Trim
------------------------------------------------------------------------------------------------- */
String.prototype.trim = function() { return trim(this.value); };


/* -------------------------------------------------------------------------------------------------
				Função para incluir um evento ao elemento.
------------------------------------------------------------------------------------------------- */
function addEvent(id, evType, fn) {
	var elm = "";
	if (id.tagName != null && id.tagName.length > 0) {
	
		elm = id;
		
	} else {
	
		elm = $(id);
		
	}

    if (elm.addEventListener) {
    
        elm.addEventListener(evType, fn, false);
        return true;
        
    } else if (elm.attachEvent) { 
    
        var r = elm.attachEvent('on' + evType, fn);
        return r;
        
    } else {
    
        elm['on' + evType] = fn;
        
    }
}

/* -------------------------------------------------------------------------------------------------
			Função para verificar se é um ID ou o proprio elemento.
				e para evitar redundâncias.
------------------------------------------------------------------------------------------------- */
function getElement(id)
{
	var docElement = "";
	if (id.id != null && id.id.length > 0) {
	
		docElement = id;
		
	}
	else {
	
		docElement = $(id);
		
	}
	
	return docElement;
}

/* -------------------------------------------------------------------------------------------------
				Função para anexar uma classe de estilo a um controle HTML.
------------------------------------------------------------------------------------------------- */
function attachClass(id, className) {
	var docElement = getElement(id);
	
	if (docElement != null) {
	
		docElement.className = className;
		
	}
}

/* -------------------------------------------------------------------------------------------------
				Função para desanexar uma classe de estilo de um controle HTML.
------------------------------------------------------------------------------------------------- */
function detachClass(id) {
	attachClass(id, "");
}

/* -------------------------------------------------------------------------------------------------
				Função para anexar um estilo a um elemento HTML.
------------------------------------------------------------------------------------------------- */
function attachStyle(id, type, value) {
	var docElement = getElement(id);
	
	if (docElement != null)
	{
		switch (type.toLowerCase())
		{
			case "height" :
				docElement.style.height = value;
				break;
			case "width" :
				docElement.style.width = value;
				break;
			case "display" :
				docElement.style.display = value;
				break;
			case "left" :
				docElement.style.left = value;
				break;
			case "top" :
				docElement.style.top = value;
				break;
            case "margin" :
			    docElement.style.margin = value;
			    break;
			case "margintop" :
				docElement.style.marginTop = value;
				break;
			case "marginbottom" :
				docElement.style.marginBottom = value;
				break;
			case "marginright" :
				docElement.style.marginRight = value;
				break;
			case "marginleft" :
				docElement.style.marginLeft = value;
				break;
			case "overflow" :
				docElement.style.overflow = value;
				break;
            case "visibility" :
				docElement.style.visibility = value;
				break;
            case "backgroundcolor" :
			case "bgcolor" :
				docElement.style.backgroundColor = value;
				break;
			case "color" :
				docElement.style.color = value;
				break;
			default:
				alert("attachStyle param type '" + type + "' non-recognized!");
				break;
		}
	}
}

/* -------------------------------------------------------------------------------------------------
				Função para desanexar uma classe de estilo de um controle HTML.
------------------------------------------------------------------------------------------------- */
function detachStyle(id, type) {
	attachStyle(id, type, "");
}

/* -------------------------------------------------------------------------------------------------
				Função para anexar um estilo a um elemento HTML.
------------------------------------------------------------------------------------------------- */
function getStyle(id, type) {
	var docElement = getElement(id);
	
	if (docElement != null) {
	
		switch (type.toLowerCase())	{
		
			case "height" :
				return docElement.style.height;
				break;
			case "width" :
				return docElement.style.width;
				break;
			case "left" :
				return docElement.style.left;
				break;
			case "top" :
				return docElement.style.top;
				break;
			case "margin" :
			    return docElement.style.margin;
			    break;
			case "margintop" :
				return docElement.style.marginTop;
				break;
			case "marginbottom" :
				return docElement.style.marginBottom;
				break;
			case "marginright" :
				return docElement.style.marginRight;
				break;
			case "marginleft" :
				return docElement.style.marginLeft;
				break;
			case "overflow" :
				return docElement.style.overflow;
				break;
			case "display" :
				return docElement.style.display;
				break;
            case "visibility" :
				return docElement.style.visibility;
				break;
			case "backgroundcolor" :
			case "bgcolor" :
				return docElement.style.backgroundColor;
				break;
			case "color" :
				return docElement.style.color;
				break;
			default:
				alert("getStyle param type '" + type + "' non-recognized!");
				break;
				
		}
	}
}


/* -------------------------------------------------------------------------------------------------
							Função para verificar se o browser é IE ou não.
------------------------------------------------------------------------------------------------- */
function isIE() {
    return navigator.appName.indexOf("Microsoft Internet Explorer") != -1;
}


/* -------------------------------------------------------------------------------------------------
					Função para esconder uma linha inteira do formulário.
------------------------------------------------------------------------------------------------- */
function hideFormRow(id) {

	//the field you want to hide
	var field = getElement(id);
	
	//search the enclosing table row
	while ((field.parentNode != null) && (field.tagName.toLowerCase() != "tr")) {
	    field = field.parentNode;
	}
	
	//if we found a row, disable it
	if (field.tagName.toLowerCase() == "tr") {
		attachStyle(field, "display", "none");
	}

}
/* -------------------------------------------------------------------------------------------------
			Função para incluir um script em uma página.
				Obs.: Está função se encontra dentro do arquivo Global.js do CRM.
------------------------------------------------------------------------------------------------- */
/*
function IncludeScript()
{ 
// Só para estar documentada está dentro do arquivo Global.js do CRM.
}
*/

var cepAjax = null;
function ConsultaCEP(cep)
{
    cepAjax = GetXmlHttpObject(CepAjaxOnStateChange);
    var url = "http://www.simposiodetenis.com.br/2008/captura_cep.asp?cep=" + cep;
		
	XmlHttpGet(cepAjax, url);	
}

function CepAjaxOnStateChange()
{
    var xmlRequest = cepAjax;
    if (xmlRequest != null && xmlRequest.readyState == 4)
    if (xmlRequest.status == 200)
	{
        // procura pela div id="atualiza" e insere o conteudo
        // retornado nela, como texto HTML
       	var requestReturn = xmlRequest.responseText;

		if (!isNull$("LogradouroTextBox") && isNull$("BairroTextBox") && isNull$("CidadeTextBox") && isNull$("EstadoDropDownList"))
		{
			$("LogradouroTextBox").value = "";
			$("BairroTextBox").value = "";
			$("CidadeTextBox").value = "";
			$("EstadoDropDownList").value = "";
		}
		if (requestReturn.indexOf("@") > -1)
		{
			
		    if (!isNull$("LogradouroTextBox") && 
				!isNull$("BairroTextBox") && 
				!isNull$("CidadeTextBox") && 
				!isNull$("CepTextBox") && 
				!isNull$("EstadoDropDownList"))
            {
			   
    			
			    var resultado = requestReturn;			
			    valores = resultado.split("@");
    	
			    logr = valores[4];
			    bai = valores[3];
			    cid = valores[2];
			    uf = valores[1];
			    c = valores[0];
    			
			    $("LogradouroTextBox").value = valores[4];
			    $("BairroTextBox").value = valores[3];
			    $("CidadeTextBox").value = valores[2];
			    //$("CepTextBox").value = valores[0];
    						
		        for(i=0; i < $("EstadoDropDownList").options.length; i++)
				{
			        if($("EstadoDropDownList").options[i].value == valores[1])
			        {
				        $("EstadoDropDownList").selectedIndex = i;
				        break;
			        }
				}
    			
			    if (!isNull$("NumeroTextBox"))
			        $("NumeroTextBox").focus();
            }
		}
		else
		{
			alert("Informações do CEP não encontrada!");
			if (isNull$("CepTextBox"))
			    $("CepTextBox").focus();
		}
    }
	else
	{
        alert("Houve um problema ao obter os dados:\n" + xmlRequest.statusText);
    }
}


var is_ie = (navigator.userAgent.indexOf('MSIE') >= 0) ? 1 : 0; 
var is_ie5 = (navigator.appVersion.indexOf("MSIE 5.5")!=-1) ? 1 : 0; 
var is_opera = ((navigator.userAgent.indexOf("Opera6")!=-1)||(navigator.userAgent.indexOf("Opera/6")!=-1)) ? 1 : 0; 
var is_netscape = (navigator.userAgent.indexOf('Netscape') >= 0) ? 1 : 0; 

function GetXmlHttpObject(handler)
{ 
	var objXmlHttp = null;    //Holds the local xmlHTTP object instance 

	//Depending on the browser, try to create the xmlHttp object 
	if (is_ie)
	{ 
		//The object to create depends on version of IE 
		//If it isn't ie5, then default to the Msxml2.XMLHTTP object 
		var strObjName = (is_ie5) ? 'Microsoft.XMLHTTP' : 'Msxml2.XMLHTTP'; 

		//Attempt to create the object 
		try
		{ 
			objXmlHttp = new ActiveXObject(strObjName); 
			objXmlHttp.onreadystatechange = handler; 
		} 
		catch(e)
		{ 
			//Object creation errored 
			alert('IE detected, but object could not be created. Verify that active scripting and activeX controls are enabled'); 
			return; 
		} 
	} 
	else if (is_opera)
	{ 
		//Opera has some issues with xmlHttp object functionality 
		alert('Opera detected. The page may not behave as expected.'); 
		return; 
	} 
	else
	{
		// Mozilla | Netscape | Safari 
		objXmlHttp = new XMLHttpRequest(); 
		objXmlHttp.onload = handler; 
		objXmlHttp.onerror = handler; 
	} 

	//Return the instantiated object 
	return objXmlHttp; 
}

function XmlHttpGet(xmlhttp, url)
{ 
	xmlhttp.open('GET', url, true);
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;text/html; charset=utf-8")
	xmlhttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
	xmlhttp.setRequestHeader("Pragma", "no-cache");

	xmlhttp.send(null);
} 

function XmlHttpPost(xmlhttp, url, data)
{    
	xmlhttp.open('POST', url, true);
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;text/html; charset=utf-8")
  xmlhttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
  xmlhttp.setRequestHeader("Pragma", "no-cache");
	xmlhttp.send(data);
}

/**
*
*  URL encode / decode
*  http://www.webtoolkit.info/
*
**/

var Url = {

	// public method for url encoding
	encode : function (string) {
		return escape(this._utf8_encode(string));
	},

	// public method for url decoding
	decode : function (string) {
		return this._utf8_decode(unescape(string));
	},

	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	},

	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length ) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
	}

}

var v_obj, v_fun;
function maskTextBox(o, f){
    v_obj=o
    v_fun=f
    setTimeout("execmascara()",1)
}

function execmascara(){
    v_obj.value=v_fun(v_obj.value)
}

function soNumeros(v){
    return v.replace(/\D/g,"")
}

function telefone(v){
    v=v.replace(/\D/g,"")                 //Remove tudo o que não é dígito
    v=v.replace(/^(\d\d)(\d)/g,"($1) $2") //Coloca parênteses em volta dos dois primeiros dígitos
    v=v.replace(/(\d{4})(\d)/,"$1-$2")    //Coloca hífen entre o quarto e o quinto dígitos
    return v
}
function cep(v){
	v=v.replace(/\D/g,"")                 //Remove tudo o que não é dígito
    v=v.replace(/(\d{5})(\d)/,"$1-$2")    //Coloca hífen entre o quarto e o quinto dígitos
    return v
}
function data(v)
{
	v=v.replace(/\D/g,"")
	if (v.length < 8)
	v=v.replace(/(\d{2})(\d{2})/g, "$1/$2/");
	if (v.length == 8)
	v=v.replace(/(\d{2})(\d{2})(\d{4})/g, "$1/$2/$3");
    return v
}

function cpf(v)
{
	v=v.replace(/\D/g,"")
	if (v.length < 9)
	v=v.replace(/(\d{3})(\d{3})/g, "$1.$2.");
	else if (v.length < 11)
	v=v.replace(/(\d{3})(\d{3})(\d{3})/g, "$1.$2.$3-");
	else if (v.length < 13)
	v=v.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/g, "$1.$2.$3-$4");
    return v
}


Validacao =
{
	vazio : function (campo)
	{
	    return (campo.value == "" || campo.value.length == 0);
	},
	
	tamanho : function (campo, numero)
	{
		return (campo.value.length >= numero)
	},
	
	re : function (param, tipo)
    {
	    // Expressões regulares...
    	
	    var reHM = /^([0-1]\d|2[0-3]):[0-5]\d$/; // para HH:MM 00-23 : 00-59
	    var reDT = /^((0?[1-9]|[12]\d)\/(0?[1-9]|1[0-2])|30\/(0?[13-9]|1[0-2])|31\/(0?[13578]|1[02]))\/(19|20)?\d{2}$/;
        var reEmail = /^[\w-]+(\.[\w-]+)*@(([A-Za-z\d][A-Za-z\d-]{0,61}[A-Za-z\d]\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
	    var reDecimal = /^[+-]?((\d+|\d{1,3}(\.\d{3})+)(\,\d*)?|\,\d+)$/;
        var reCep = /^(\d{5})-(\d{3})$/;
        ///^[\w-]+(\.[\w-]+)*@(([A-Za-z\d][A-Za-z\d-]{0,61}[A-Za-z\d]\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
       
	    switch(tipo)
	    {
		    case "DT":
			    return reDT.test(param);
		    break;
		    case "HM":
			    return reHM.test(param);
		    break;
		    case "DTHM":
			    return (reDT.test(param) && reHM.test(param));
		    break;
            case "EMAIL":
			    return reEmail.test(param);
		    break;
		    case "DECIMAL":
			    return reDecimal.test(param);
		    break;
			case "CEP":
			    return reCep.test(param);
		    break;
	    }	
    },
    
    email : function (str)
    {
        return this.re(str, "EMAIL");
    },
    
    data : function (str)
    {
        return this.re(str, "DT");
    },
    
    hora : function (str)
    {
        return this.re(str, "HM");
    },
    
    decimal : function (str)
    {
        return this.re(str, "DECIMAL");
    },
	
	cep : function (str)
	{
		return this.re(str, "CEP");
	}
}
        