var lang;
var thisSiteXML=undefined;

var siteState="initialState";

var regexon=/^on/;

var regexstyle=/^style/;
var regexJson=/^(\s)*\{(\"|')?[\w\d\s]+(\"|')?\:(.|\n)*\}(\s)*$/;
var mousePos;
var errorAlerts = {"dates":{"outPattern":"Por favor insira uma data no padrão dd/mm/aaaa por exemplo: 23/11/2009","invalidMonth":"Numêro do mês inválido, insira um value entre 01 e 12","invalidDay":"Dia inválido para o mês por favor colocar algo entre 01 e "},"patterns":{"numbers":"Por favor insira apenas numeros","dates":"Por favor insira uma data no padrão dd/mm/aaaa","letters":"por favor insira apenas letras","email":"Por favor insira um endereço de e-mail válido","decimal":"Por favor insira um value válido para este campo \n (número podendo ser precedido de ponto ou virgula e 2 numeros após o ponto ou virgula) \n exemplo 10 OU 120,00 OU 1.99 ","weight":"Por favor insira um value válido para peso(número podendo ser precedido ponto e 2 números após o ponto) \n ex:10.00 ,145"}};
function playFlashMovie(containerId,movie,width,height,flashVars,wmode){
	var movieData='<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0"  height="'+height+'" width="'+width+'"align="middle">';
	movieData+='<param name="quality" value="high"/>';
	movieData+='<param name="movie" value="'+movie+'" />';
	movieData+='<param name="wmode" value="'+wmode+'"/>';
	movieData+='<param name="FlashVars" value="'+flashVars+'"/>';
	movieData+='<embed height="'+height+'" flashvars="'+flashVars+'" width="'+width+'"  wmode="'+wmode+'" src="'+movie+'" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"  wmode="window" scale="showall" />';
	movieData+='</object>';
	getById(containerId).innerHTML=movieData;
}

function cleanChilds(id){
	var el=getById(id);
	if(isNothingNess(el)){
		return;
	}
	while(el.hasChildNodes()){
		el.removeChild(el.firstChild);
	}
	
	
}
function findPos(obj){
	var posX = obj.offsetLeft;
	var posY = obj.offsetTop;
	var firstEl = document.getElementsByTagName('body')[0];
	while (obj.offsetParent) {
		if (obj == firstEl) {
			break;
		}
		else {
			posX = posX + obj.offsetParent.offsetLeft;
			posY = posY + obj.offsetParent.offsetTop;
			obj = obj.offsetParent;
		}
		
	}
	return {
		'x': posX,
		'y': posY
	};
}
function maskBrazilianDate(value){
	var justNums=value.replace(/\D/g,'');
	var ret;
	if (justNums.length >= 2) {
		var day = justNums.substring(0, 2);
		ret=day+'/';
		if (justNums.length >= 4){
			var month=justNums.substring(2,4);
			ret+=month;
			var year= justNums.substring(4);
			if (year.length > 4) {
				year=year.substring(0,4);
			}
			ret+='/'+year
			return ret;
		}
	}
	return justNums;
	
}

/**
 * Function to see if some data is in the json syntax
 * @param {Object} dado
 */
function isJson(dado){
	
	return dado.match(regexJson)!=null;
}

/**

*

* UTF-8 data encode / decode

* http://www.webtoolkit.info/

*

**/
var utf8 = {
	// public method for url encoding
	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;
	},
// public method for url decoding
	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;
	}
}


//funcao para dar um replace no conteudo segundo as regras usadas no handleAjax


function replaceForAjax(value){
	value=value.replace(/\+/g,"#@PLUS@#");
	//value=value.replace(/<span class="underline">(.*?)<\/span>/g, '<u>$1</u>');
	value=value.replace(/\&/g,"#@Ecom@#");
	value=value.replace(/\=/g,"#@equal#");
	value=value.replace(/\</g,"#@lt#");
	value=value.replace(/\>/g,"#@gt#");
	value=value.replace(/\"/g,"#@dQuote#");
	value=value.replace(/\'/g,"#@sQuote#");
	return value;
}
function replaceFromAjax(value){
	value=value.replace(/#@PLUS@#/g,"+");
	//value=value.replace(/<span class="underline">(.*?)<\/span>/g, '<u>$1</u>');
	value=value.replace(/#@Ecom@#/g,"&");
	value=value.replace(/#@equal#/g,"=");
	value=value.replace(/#@lt#/g,"<");
	value=value.replace(/#@gt#/g,">");
	value=value.replace(/#@dQuote#/g,"\"");
	value=value.replace(/#@sQuote#/g,"'");
	return value;
}
function showToolTip(tooltip,interval){
	var toolTipElement=getById("tooltip");
	if (isNothingNess(interval)) {
		getById('toolTipContent').innerHTML = "";
		setTimeout('showToolTip("'+tooltip+'",'+true+')',1000);
		toolTipElement.style.display="none";//dessa forma colocmaos ela la se o tempo se passar eo mouse nao sair ela estara no meio se nao podemos se tar pra block q tbm ficara invisivel
		putInto("tooltip","wrapper");
	}
	else{
		toolTipElement.style.top = mousePos.y+"px";
		toolTipElement.style.left = mousePos.x+"px";
		getById('toolTipContent').innerHTML = tooltip;
		toolTipElement.style.display="block";
	}
	}
String.prototype.trim = function(){
	return this.replace(/^\s*/, "").replace(/\s*$/, "");
}
function selecionaItemSelect(selectId, value, innerHTML){
	var select = getById(selectId);
	if (isNothingNess(select)) {
		return false;
	}
	
	var tamSelect = select.length;
	
	if (isNothingNess(value) == false && isNothingNess(innerHTML) == false) {
	
		for (var i = 0; i < tamSelect; i++) {
		
			if (select.options[i].value == value && select.options[i].innerHTML == innerHTML) {
			
			
			
				selectedIndex = select.options[i].index;
				
				select.selectedIndex = selectedIndex;
				
				return new Array(select.options[i].value, select.options[i].innerHTML);
				
			}
			
		}
		
	}
	
	else 
	
		if (!isNothingNess(value)) {
		
			for (var i = 0; i < tamSelect; i++) {
			
				if (select.options[i].value == value) {
				
				
					selectedIndex = select.options[i].index;
					
					select.selectedIndex = selectedIndex;
					
					return new Array(select.options[i].value, select.options[i].innerHTML);
					
				}
				
			}
			
		}
		
		else 
			if (!isNothingNess(innerHTML)) {
			
				for (var i = 0; i < tamSelect; i++) {
				
					if (select.options[i].innerHTML == innerHTML) {
					
					
						selectedIndex = select.options[i].index;
						
						select.selectedIndex = selectedIndex;
						
						return new Array(select.options[i].value, select.options[i].innerHTML);
						
					}
					
				}
				
			}
	
	return null;
	
}

function changeSelectContent(selectId,value,oldInnerHTML,newInnerHTML){

var select=getById(selectId);

if (isNothingNess(select)) {

	return false;
	
}

var tamSelect=select.length;

if (isNothingNess(value) == false && isNothingNess(oldInnerHTML) == false) {

	for (var i = 0; i < tamSelect; i++) {
	
		if (select.options[i].value == value && select.options[i].innerHTML == oldInnerHTML) {
		
			select.options[i].innerHTML = newInnerHTML;
			
			return;
			
		}
		
	}
	
}

else 
	if (!isNothingNess(value)) {
	
		for (var i = 0; i < tamSelect; i++) {
		
			if (select.options[i].value == value) {
			
				select.options[i].innerHTML = newInnerHTML;
				
				return;
				
			}
			
		}
		
	}
	
	else 
		if (!isNothingNess(oldInnerHTML)) {
		
			for (var i = 0; i < tamSelect; i++) {
			
				if (select.options[i].innerHTML == oldInnerHTML) {
				
					select.options[i].innerHTML = newInnerHTML;
					
					return;
					
				}
				
			}
			
		}

}


function pegarConteudoSelect(selectId,value){

var select=getById(selectId);

if(isNothingNess(select)){

return false;

}

var tamSelect=select.length;

for (var i = 0; i < tamSelect; i++) {

if(select.options[i].value==value){

return select.options[i].innerHTML;

}

}

}

function changeValueSelect(selectId, oldValue, newValue, innerHTML){

	var select = getById(selectId);
	
	if (isNothingNess(select)) {
	
		return false;
		
	}
	
	var tamSelect = select.length;
	
	if (isNothingNess(oldValue) == false && isNothingNess(innerHTML) == false) {
	
		for (var i = 0; i < tamSelect; i++) {
		
			if (select.options[i].value == oldValue && select.options[i].innerHTML == innerHTML) {
			
				select.options[i].value = newValue;
				
				return;
				
			}
			
		}
		
	}
	
	else 
		if (!isNothingNess(oldValue)) {
		
			for (var i = 0; i < tamSelect; i++) {
			
				if (select.options[i].value == oldValue) {
				
					select.options[i].value = newValue;
					
					return;
					
				}
				
			}
			
		}
		
		else 
			if (!isNothingNess(innerHTML)) {
			
				for (var i = 0; i < tamSelect; i++) {
				
					if (select.options[i].innerHTML == innerHTML) {
					
						select.options[i].value = newValue
						
						return;
						
					}
					
				}
				
			}
	
}

function removeFromSelect(selectId, value, innerHTML){

	var select = getById(selectId);
	
	if (isNothingNess(select)) {
	
		return false;
		
	}
	
	var tamSelect = select.options.length;
	
	if (isNothingNess(value) == false && isNothingNess(innerHTML) == false) {
	
		for (var i = 0; i < tamSelect; i++) {
		
			if (select.options[i].value == value && select.options[i].innerHTML == innerHTML) {
			
				select.removeChild(select.options[i]);
				
				return;
				
			}
			
		}
		
	}
	
	else 
		if (!isNothingNess(value)) {
		
			for (var i = 0; i < tamSelect; i++) {
			
				if (select.options[i].value == value) {
				
					select.removeChild(select.options[i]);
					
					return;
					
				}
				
			}
			
		}
		
		else 
			if (!isNothingNess(innerHTML)) {
			
				for (var i = 0; i < tamSelect; i++) {
				
					if (select.options[i].innerHTML == innerHTML) {
					
						select.removeChild(select.options[i]);
						
						return;
						
					}
					
				}
				
			}
	
}
function formatToMoney(value){
	var value=value+"";
	posSep=-1;
	posSep=value.indexOf(",");
	if (posSep == -1) {
		posSep=value.indexOf(".");
	}
	//Sen ao acho nem ponto ou virgula adcionamos
	if (posSep == -1) {
		return value+",00";
	}
	//achou ou ponto ou virgula
	var inteiro=value.substring(0,posSep);
	var decimal=value.substring(posSep+1);
	if (decimal.length == 1) {
		decimal+="0";
	}
	if (decimal.length >2) {
		decimal=decimal.substring(0,2);
	}
	return inteiro+","+decimal;
}
/**
 *Function to add Options into a select 
 * @param String selectId the id of the select
 * @param String inner the inerHTML of the select
 * @param {Object} value the value of the select
 */
function addOptionIntoTheSelect(selectId,inner,value){
	var option=makeHTML("option",new Array("innerHTML",inner,"value",value));
	var sel=getById(selectId);
	if(isNothingNess(sel)){
		return false;
	}
	sel.appendChild(option);
	return true;
}
/**
 * 
 * Function to turn special chars into normal chars
 * @param {Object}  str
 */
 function removeSpecialChars(str){
	var reps=[/ñ/gi,'n',/ç/gi,'c',/(á|ã|â|à)/gi,'a',/(é|ê|è)/gi,'e',/(õ|ò|ó|ô)/gi,'o',/(í|ì|î)/gi,'i',/(ú|û)/gi,'u'];
	var num=reps.length;
	var regex;
	for(var i=0;i<num;i+=2){
		str=str.replace(reps[i],reps[i+1]);
	}
	return str;
 }

/**
 * Function to create a tinyMCE image
 */
function createTinyMceImg(src,id){
	var img="<img mce_src=\""+src+"\" src=\""+src+"\" />";
	addTinyMceHTMLContent(img,id);
}
function getInnerDoc(frameId){
var frame = document.getElementById(frameId);
		return (frame.contentDocument) ? frame.contentDocument : frame.contentWindow.document;

}
/**
 * Function to autoResize an iframe
 * @param {Object} frameId
 */
function autoIframe(frameId){
	try {
		
var frame = document.getElementById(frameId);
	var innerDoc=(frame.contentDocument) ? frame.contentDocument : frame.contentWindow.document;

//		alert("SCROOL HEIGHT1 E "+ frame.contentDocument.body.scrollHeight);
		objToResize = (frame.style) ? frame.style : frame;
		objToResize.height=10;
		objToResize.height = innerDoc.body.scrollHeight+10;
	} 
	catch (err) {
		window.status = err.message;
	}
}
function validateCNPJ(cnpj){
	//First temove non numerical characters
	cnpj=cnpj.replace(/\D/g,'');
	if (cnpj.length != 14) {
		return false;
	}
	if (parseInt(cnpj) == 0) {
		return false;
	}
	var nums1=[5,4,3,2,9,8,7,6,5,4,3,2];
	var firstDigit=0;
	for (var i = 0; i < 12; i++) {
		firstDigit+=parseInt(cnpj.charAt(i))*nums1[i];
	}
	var resto=firstDigit-Math.floor(firstDigit/11)*11;
	firstDigit=(resto<2)?0:(11-resto);

	if (firstDigit != cnpj.charAt(12)) {
		return false;
	}
	var secondDigit=0;
	var nums2=[6,5,4,3,2,9,8,7,6,5,4,3,2];
	for (var i = 0; i < 13; i++) {
			secondDigit+=parseInt(cnpj.charAt(i))*nums2[i];
	}
	resto=secondDigit-Math.floor(secondDigit/11)*11;
	secondDigit=(resto<2)?0:(11-resto);
	
	if (secondDigit != cnpj.charAt(13)) {
		return false;
	}
	return true;
}
/**
 * Function to get a element by Id,Set some atribute or get some atribute
 * @param {Object} id
 * @param {Object} what what to get
 * @param {Object} value
 */
function getById(id, what, value){

	if (isNothingNess(what)) {
		if (!isNothingNess(document)) {
			return document.getElementById(id);
		}
	}
	
	if (!isNothingNess(value)) {
	
		eval('getById("' + id + '").' + what + '=' + value);
		
	}
	
	return eval('getById("' + id + '").' + what);
	
}



/**
 * Closes a window
 */
function close(){

window.close();

}
/**
 * Function to get some html element value
 * @param String id
 */
function getValue(id){
	var el=getById(id);
	if (isNothingNess(el)) {
		return null;
	}
	return el.value

}

function validateCPF(cpf) {
	cpf = cpf.replace(/\D/g,'');
	if (cpf.length != 11) return false; 
	if (cpf == "00000000000" || cpf == "11111111111" )	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;
}
function validateCNPJ(cnpj){

	cnpj=cnpj.replace(/\D/g,'');

	if (cnpj.length != 14) {
		return false;
	}
	if (parseInt(cnpj) == 0) {
		return false;
	}
	var nums1=[5,4,3,2,9,8,7,6,5,4,3,2];
	var firstDigit=0;
	for (var i = 0; i < 12; i++) {
		firstDigit+=parseInt(cnpj.charAt(i))*nums1[i];
	}
	var resto=firstDigit-Math.floor(firstDigit/11)*11;
	firstDigit=(resto<2)?0:(11-resto);

	if (firstDigit != cnpj.charAt(12)) {
		return false;
	}
	var secondDigit=0;
	var nums2=[6,5,4,3,2,9,8,7,6,5,4,3,2];
	for (var i = 0; i < 13; i++) {
			secondDigit+=parseInt(cnpj.charAt(i))*nums2[i];
	}
	resto=secondDigit-Math.floor(secondDigit/11)*11;
	if(resto<2){
		secondDigit=0;
		}else{
		secondDigit=(11-resto);
	}
	if (secondDigit != cnpj.charAt(13)) {
		return false;
	}
	return true;
}
/**
 * Function to make some html element a tinyMCE instance
 * @param String id id of the element
 */
function makeTinyMce(id){
	return tinyMCE.execCommand('mceAddControl', false, id);
}
/**
 * Function to get the content of an active tinyMCE instance
 */
function getTinyMceContent(id){
	return tinyMCE.get(id).getContent();
}
/**
 * Function to set a tiny MCe content
 * @param {Object} content the content to set
 * @param {Object} id Id of the textArea instance that originated the tinyMCe
 */
function setTinyMceContent(content,id){
	tinyMCE.get(id).setContent(content);
}
/**
 * Function to add tinyMCE content
 */ 
 function addTinyMceHTMLContent(content, id){
	tinyMCE.execInstanceCommand(id,'mceInsertRawHTML',false,content)
 }
 /**
 * @param {Object} id
 */
/**
 * Function to remove an active tinyMCe control
 * @param {Object} id
 */
function removeTinyMce(id){
	tinyMCE.execCommand('mceRemoveControl', false, id);

}
/**
 * Function to get mouse coordinates
 * @param {Object} ev
 */
function mouseCoords(ev){//Pegamos aqui a coordenada do Mouse

if(ev.pageX || ev.pageY){

return {x:ev.pageX, y:ev.pageY};

}

else return {

x:ev.clientX + document.body.scrollLeft-document.body.clientLeft,

y:ev.clientY + document.body.scrollTop-document.body.clientTop

};

}

/**
 * Listener to mouseMove function
 * @param {Object} ev
 */
function mouseMove(ev){

ev = ev || window.event;

mousePos = mouseCoords(ev);

}

 /**
  * Function to change a date format from  dd/mm/YYY to YYY/mm/dd
  * @param {Object} date
  */
function changeDateFormat(date){

	var barraPos = date.indexOf("/");
	
	var dia = parseInt(date.substr(0, barraPos));
	
	var mes = parseInt(date.substring(barraPos + 1, (barraPos = date.indexOf("/", barraPos + 1))));
	
	var ano = parseInt(date.substr(barraPos + 1));
	
	return ano + "/" + mes + "/" + dia;
	
}
/**
 * Function to check if date1 is bigger than two
 * @param {Object} date1
 * @param {Object} date2
 * @param Boolean englishFormat if true it is in the english format if not it is in dd/mm/yyyy format
 * @return true if date1 is bigger false if date2 is bigger and null if they are equal
 */
function dateIsBigger(date1, date2, englishFormat){

	var ano1;
	
	var dia1;
	
	var mes1;
	
	var ano2;
	
	var dia2;
	
	var mes2;
	
	var value;
	
	var barraPos;
	
	if (isNothingNess(englishFormat)) {
	
		value = date1;
		
		barraPos = value.indexOf("/");
		
		dia1 = parseInt(value.substr(0, barraPos));
		
		mes1 = parseInt(value.substring(barraPos + 1, (barraPos = value.indexOf("/", barraPos + 1))));
		
		ano1 = parseInt(value.substr(barraPos + 1));
		
		value = date2;
		
		barraPos = value.indexOf("/");
		
		dia2 = parseInt(value.substr(0, barraPos));
		
		mes2 = parseInt(value.substring(barraPos + 1, (barraPos = value.indexOf("/", barraPos + 1))));
		
		ano2 = parseInt(value.substr(barraPos + 1));
		
	}
	else 
		if (englishFormat === true) {
		
			value = date1;
			
			barraPos = value.indexOf("/");
			
			ano1 = parseInt(value.substr(0, barraPos));
			
			mes1 = parseInt(value.substring(barraPos + 1, (barraPos = value.indexOf("/", barraPos + 1))));
			
			dia1 = parseInt(value.substr(barraPos + 1));
			
			value = date2;
			
			barraPos = value.indexOf("/");
			
			ano2 = parseInt(value.substr(0, barraPos));
			
			mes2 = parseInt(value.substring(barraPos + 1, (barraPos = value.indexOf("/", barraPos + 1))));
			
			dia2 = parseInt(value.substr(barraPos + 1));
			
		}
	
	if (ano1 > ano2) {
	
		return true;
		
	}
	
	else 
		if (ano1 < ano2) {
		
			return false;
			
		}
	
	//Aqui o ano deve ser igual
	
	if (mes1 > mes2) {
	
		return true;
		
	}
	
	else 
		if (mes1 < mes2) {
		
			return false;
			
		}
	
	//Aqui o mes seria igual
	
	if (dia1 > dia2) {
	
		return true;
		
	}
	
	else 
		if (dia1 < dia2) {
		
			return false;
			
		}
		
		else 
			if (dia1 == dia2) {
			
				return null;
				
			}
	
}
function removeLeadingZero(str){
var start = str.substr(0, 1);
	
	if (start == "0") {
	
		return str.substr(1);
		
	}
	
	return str;
	
}
/**
 * Function to see if there is a leading zero or
 * @param {Object} theDate
 */ 
function dateWithZero(theDate){

	var start = theDate.substr(0, 1);
	
	if (start == "0") {
	
		return theDate;
		
	}
	
	return "0"+theDate;
	
}
function setUrlFocus(anchorName){
	var location=window.location.toString();
	var pos=location.indexOf("#");
	if (pos >=0) {
		location=location.substr(0,pos+1);
	}
	location+=anchorName;
	window.location=location;
}
/**
 * Funtion to make a date object into a dd/mm/YYYY formar
 */
function dateObjectToDateStr(theDate){
return dateWithZero(theDate.getDate().toString())+"/"+dateWithZero((theDate.getMonth()+1).toString())+"/"+theDate.getFullYear()
}
/**
 * Check if a date is in the date pattern 
 * @param {Object} id
 * @return boolean if the value is  invalid returns null, if doesn't match return false if it's ok retturns true
 */
function checkDate(id){

	var value = getById(id).value;
	
	var padraoData = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
	if (isNothingNess(value) || value.match("dd/mm/aaaa")) {
		return null;
	}
	if (!value.match(padraoData)) {
	
		alert(errorAlerts['dates']['outPattern']);
		getById(id).value = "dd/mm/aaaa";
		
		return false;
		
	}
	
	var erro;
	
	var numDia;
	
	var numMes;
	
	var barraPos = value.indexOf("/");
	
	var odia = value.substr(0, barraPos);
	
	odia = dateWithZero(odia);
	
	var dia = parseInt(value.substr(0, barraPos));
	
	var omes = value.substring(barraPos + 1, (barraPos = value.indexOf("/", barraPos + 1)));
	
	omes = dateWithZero(omes);
	
	var mes = parseInt(omes);
	
	
	var ano = parseInt(value.substr(barraPos + 1));
	
	if (mes > 12 || mes <= 0) {
	
	
		alert(errorAlerts['dates']['outPattern']);
		
		numMes = (mes <= 0) ? "01" : "12";
		
		erro = true;
		
	}
	else {
	
		numMes = mes;
		
	}
	
	//JS considera o mes de janeiro como 0 logo substraimos 1
	
	var maxDia = getNumberOfDays(numMes - 1, ano);
	
	if (dia > maxDia) {
	
		alert(errorAlerts["dates"]["invalidDay"] + maxDia);
		
		numDia = maxDia;
		
		erro = true;
		
	}
	else {
	
		numDia = dia;
		
	}
	
	if (numMes.toString().length == 1) {
	
		numMes = "0" + numMes;
		
	}
	
	if (numDia.toString().length == 1) {
	
		numDia = "0" + numDia;
		
	}
	
	if (erro) {
	
		getById(id).value = numDia + "/" + numMes + "/" + ano;
		
		return false;
		
	}
	
	return true;
	
}
/**
 * Function to check if something is in the right parrern or not
 * @param {Object} id
 * @param {Object} padrao
 * @return boolean true if it's all ok,false if it doesn't match a pattern and null if it is nothingness
 */
function checkInPattern(id, thePattern){
	
	var pattern;
	
	var value = getById(id).value;
	if (isNothingNess(value)) {
		return null;
	}
	var theAlert = errorAlerts["patterns"][thePattern];
	if (thePattern == "numbers") {
	
		pattern = /^\d+$/;
		
		theAlert = errorAlerts["patterns"][thePattern];
		
	}
	else 
		if (thePattern == "dates") {
			pattern = /^$\d{2}\/\d{2}\/\d{4}/;
		}
		else 
			if (thePattern == "letters") {
			
				pattern = /^([a-zA-z])+$/;
				
			}
			
			else 
				if (thePattern == "email") {
				
					pattern = /^[a-z0-9][^\(\)\<\>\@\,\.\:\\\"\[\]]*\@[a-z0-9][a-z0-9\-\.]*\.[a-z]{2-4}$/i;
					
				}
				
				else 
					if (thePattern == "money" || thePattern == "decimal") {
					
						pattern = /^\d+(\.|\,)?[0-9]{0,2}$/;
						
						theAlert = errorAlerts["patterns"]["decimal"];
					}
					
					
					else 
						if (thePattern == "weight") {
						
							pattern = /^\d+\.?[0-9]{0,2}$/;
							
						}
	
	
	if (value.length != 0) {
	
		if (!value.match(pattern)) {
		
			if (thePattern == "datas" || thePattern == "numeros" || thePattern == "letras" || thePattern == "priotidade" || thePattern == "dinheiro" || thePattern == "peso") {
			
				getById(id).value = "";
				
			}
			
			alert(theAlert);
			return false;
		}
		
	}
	
	return true;	
}
/**
 * Fucntion do set a display of an element to none
 * @param {Object} id
 */
function hide(id){

getById(id).style.display="none";

}
/**
 * Function to set a display of an element to block
 * @param {Object} id
 */
function show(id){

getById(id).style.display="block";

}


function handleDefValue(el,focus,value){
	if(focus){
		if(el.value==value){
			el.value="";
		}
	}
	else if(isNothingNess(el.value)){
		el.value=value;
	}
}
function putMask(el,type,ev){
	var value=el.value;

	if (window.event) {
		key = window.event.keyCode;
	} else if (ev) {
		key = ev.which;
	} else {
		return true;
	}
	// teclas de controle
	if ((key==null) || (key==0) || (key==8) ||
		(key==9) || (key==13) || (key==16)  || (key==17)  || (key==27)  || (key==46) ) {
		return;
	} 
	switch(type){
		case 'fone':
			value=value.replace(/[^\d]*/g,'');
			var strValue=value.split("");
			var num=strValue.length;
			
			if(num>10){
				num=10;
			}
			var str='(';
			for(var i=0;(i<num);i++){
				
				str+=strValue[i];
				if(i==1){
					str+=') ';
				}
				if(i==5){
					str+='-';
				}
			}
			el.value=str;
		break;
		case 'date':
			value=value.replace(/[^\d]*/g,'');
			var str='';
			var strValue=value.split("");
			var num=strValue.length;
			if(num>7){
				num=7;
			}
			for(var i=0;(i<num);i++){
				
				str+=strValue[i];
				if(i==1){
					str+='/';
				}
				if(i==3){
					str+='/';
				}
			}
			el.value=str;
		break;
		case 'dateHM':
			value=value.replace(/[^\d]*/g,'');
			var str='';
			var strValue=value.split("");
			var num=strValue.length;
			if(num>13){
				num=13;
			}
			for(var i=0;(i<num);i++){
				
				str+=strValue[i];
				if(i==1){
					str+='/';
				}
				if(i==3){
					str+='/';
				}
				if(i==7){
					str+=' ';
				}
				if(i==9){
					str+=':';
				}
			}
			el.value=str;
		break;
			
		case 'zipcode':
			value=value.replace(/[^\d]*/g,'');
			var str='';
			var strValue=value.split("");
			var num=strValue.length;
			if(num>7){
				num=7;
			}
			for(var i=0;(i<num);i++){
				
				str+=strValue[i];
				if(i==4){
					str+='-';
				}
			}
			el.value=str;
		break;
	}

}
/**
 * Function used to get  XMLHTTP request according to the browser
 */
function getXmlhttp(){

try

{

// Firefox, Opera 8.0+, Safari

xmlHttp=new XMLHttpRequest();


}

catch (e)

{

// Internet Explorer

try

{

xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");

}

catch (e)

{

try

{

xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");

}

catch (e)

{

alert("Seu browser n�o suporta AJAX!");

return false;

}

}

}


return xmlHttp;

}


/**
 * Function to set an XMLHTTPrequest
 * @param {Object} varpost 
 * @param {Object} site
 * @param {Object} assinc
 * @param {Object} PostOuGet
 */
function sendAjax(varpost,site,assinc,PostOuGet){

var enviarAjax=getXmlhttp();

if(PostOuGet=="GET"){

site+="?"+varpost;

}

enviarAjax.open(PostOuGet,site,assinc);


if(PostOuGet=="POST"){

enviarAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

enviarAjax.setRequestHeader("Content-length", varpost.length);

}

enviarAjax.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");

enviarAjax.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");

enviarAjax.setRequestHeader("Pragma", "no-cache");

enviarAjax.setRequestHeader("Connection", "close");

return enviarAjax;

}
/**
 * Function to remove all the child nodes from an html element
 * @param {Object} id the id of the element
 * @param {Object} htmlEl or the html element
 */
function cleanHTML(id, htmlEl){
	var oque;
	if (htmlEl != "undefined" && htmlEl != "null" && htmlEl != null) {
		oque = htmlEl;
	}
	else {
		var oque = getById(id);
	}
	while (oque.hasChildNodes()) {
		oque.removeChild(oque.firstChild);
		
	}
}
/**
 * Function to check if something is null or not
 * @param {Object} _1
 */
function isNothingNess(_1){

if(typeof(_1)=="undefined" || _1==null || _1==""  || _1==="null" ){

return true;

}

return false;

}


Array.prototype.in_array=isInArray;

String.prototype.startsWith=regexStart;

Date.prototype.numberOfDays=getNumberOfDays;

Date.prototype.weekDay_monthStarted=getWeekDayMonth;

/**
 * Function to get the weekDay of a month
 */
function getWeekDayMonth(){

var realDay=this.getDate();

this.setDate(1);

var startDay=this.getDay();

this.setDate(realDay);

return startDay;

}
function setValue(id, value){
	getById(id).value=value;
}
/**
 * Function to remove a tr element
 * @param {Object} tableId
 * @param {Object} trId
 * @return Integer the number of rows in the table
 */
function removeTr(tableId,trId){
	var tr=getById(trId);
	var table=getById(tableId);
	table.deleteRow(tr.rowIndex);
	return table.rows.length;
}
 /**
  * Function to get the number of days of a month
  * @param {Object} m the month 
  * @param {Object} y the year
  */
function getNumberOfDays(m, y){
	if (isNothingNess(m)) {
		m = this.getMonth();
	}
	if (isNothingNess(y)) {
		var y = this.getFullYear();
	}
	var thirt = new Array(3, 5, 8, 10);//months with 30 days
	if (m == 1) {//if it is feb
		if (y % 4 == 0 && y % 100 != 0 || y % 400 == 0) {//bissext math
			return 29;
		}
		else {
			return 28;
		}
	}
	else 
		if (thirt.in_array(m)) {
			return 30;
		}
		else {
			return 31;
		}
}
/**
 * Function to see if something starts with the string
 * @param {Object} string
 */
function regexStart(string){

	var regex = new RegExp('^' + string);
	
	return regex.test(this);
	
}

/**
 * Function to see if some objet is an array
 * @param {Object} obj
 */
function isArray(obj){

	if (obj.constructor == Array) {
	
		return true;
		
	}
	
	else {
	
		return false;
		
	}
	
}
/**
 * Function to put an element in a container
 * @param String id the id of the element we want to put 
 * @param String container the id of the container
 */
function putInto(id, container){
var el=	getById(container);
	var el2=getById(id);
	
el.appendChild(el2);
	
}

/**
 * Makes a table line 
 * @param HTMLElement Tabela the HTMLElement table
 * @param Number rowNumber the number of row we want to insert
 * @param Array arrayTdAttributes an array in the syntax (atribute,value)
 * @param String TrClass a calass to the tr
 * @param String TrId
 */
function makeTableLine(Tabela, rowNumber, arrayTdAttributes, TrClass, TrId){

var tr = Tabela.insertRow(rowNumber);

if (!isNothingNess(TrClass)) {

tr.className = TrClass;

}

if(!isNothingNess(TrId)){

tr.setAttribute("id",TrId);

}

var numTd=arrayTdAttributes.length;

var td;

var tdContent;

for(var i=0;i<numTd;i++){

tdContent=arrayTdAttributes[i];

if (isArray(tdContent)) {

td = makeHTML('td', tdContent);

tr.appendChild(td);

}

else if(tdContent.nodeType==1){//Se nao for array e for um elemento html adciona-o

tr.appendChild(tdContent);

}

}

return tr;

}

function putInside(elementID,TheValue,apend){

var el=getById(elementID);

if(el.tagName=="INPUT" || el.tagName=="input"){

if (apend) {

el.value += TheValue;

}

else {

el.value = TheValue;

}

}

else{

if (apend) {

el.innerHTML+=TheValue;

}

else {

el.innerHTML = TheValue;

}

}

}
/**
 * Function to put all childs od one element into another
 * @param {Object} containerFrom
 * @param {Object} containerTo
 */
function putAllchildsInto(containerFrom, containerTo){

	var from = getById(containerFrom);
	
	var to = getById(containerTo);
	
	while (from.hasChildNodes()) {
	
		to.appendChild(from.firstChild);
		
	}
	
}
/**
 * Function to make an htmlElement
 * @param String element the element Name
 * @param Array atributos an array in the syntax (key,value)
 */
function makeHTML(el, atributos){
	
	var element = document.createElement(el);
	
	
	if (atributos != undefined && atributos != null) {
	
		var numatributos = atributos.length;
		
		for (var i = 0; i < numatributos; i += 2) {
		
			var atr = atributos[i];
			var value = atributos[i + 1];
			
			if (regexon.test(atr) == false && atr != "class" && atr != "innerHTML" && regexstyle.test(atr) == false && atr != "appendChild") {
			
				element.setAttribute(atr, value);
				
			}
			
			else 
				if (regexon.test(atr)) {
				
					if (atr == "onclick") {
					
						element.onclick = new Function(value);
						
					}
					
					else 
						if (atr == "onchange") {
						
							element.onchange = new Function(value);
							
						}
						
						else 
							if (atr == "onmouseover") {
							
								element.onmouseover = new Function(value);
								
							}
							
							else 
								if (atr == "onmouseleave") {
								
									element.onmouseleave = new Function(value);
									
								}
								
								else 
									if (atr == "onmouseout") {
									
										element.onmouseout = new Function(value);
										
									}
									else 
										if (atr == "onfocus") {
											element.onfocus = new Function(value);
										}
										else 
										if (atr == "onblur") {
											element.onblur = new Function(value);
										}
					
				}
				
				else 
					if (atr == "class") {
					
						element.className = value;
						
					}
					
					else 
						if (atr == "innerHTML") {
						
							element.innerHTML = value;
							
						}
						
						else 
							if (atr == "appendChild") {
								if (isArray(value)) {
									var tam=value.length;
									
									for (var toolM = 0; toolM< tam; toolM++) {
										
										element.appendChild(value[toolM]);
									
									}
								}
								else {
									element.appendChild(value);
								}
							}
			
		}
		
	}
	
	return element;
	
}
/**
 * Function to check if an element is in a array
 * @param {Object} element
 */
function isInArray(element){

for(x in this){
	if(this[x]==element)	return true;

}
return false;
}

/*
JSONstring v 1.01
copyright 2006 Thomas Frank
(small sanitizer added to the toObject-method, May 2008)

This EULA grants you the following rights:

Installation and Use. You may install and use an unlimited number of copies of the SOFTWARE PRODUCT.

Reproduction and Distribution. You may reproduce and distribute an unlimited number of copies of the SOFTWARE PRODUCT either in whole or in part; each copy should include all copyright and trademark notices, and shall be accompanied by a copy of this EULA. Copies of the SOFTWARE PRODUCT may be distributed as a standalone product or included with your own product.

Commercial Use. You may sell for profit and freely distribute scripts and/or compiled scripts that were created with the SOFTWARE PRODUCT.

Based on Steve Yen's implementation:
http://trimpath.com/project/wiki/JsonLibrary

Sanitizer regExp:
Andrea Giammarchi 2007

*/
Object.prototype.clone = function() {
  var newObj = (this instanceof Array) ? [] : {};
  for (i in this) {
    if (i == 'clone') continue;
    if (this[i] && typeof this[i] == "object") {
      newObj[i] = this[i].clone();
    } else newObj[i] = this[i]
  } return newObj;
};
JSONstring={
	compactOutput:false, 		
	includeProtos:false, 	
	includeFunctions: false,
	detectCirculars:true,
	restoreCirculars:true,
	make:function(arg,restore) {
		this.restore=restore;
		this.mem=[];this.pathMem=[];
		return this.toJsonStringArray(arg).join('');
	},
	toObject:function(x){
		if(!this.cleaner){
			try{this.cleaner=new RegExp('^("(\\\\.|[^"\\\\\\n\\r])*?"|[,:{}\\[\\]0-9.\\-+Eaeflnr-u \\n\\r\\t])+?$')}
			catch(a){this.cleaner=/^(true|false|null|\[.*\]|\{.*\}|".*"|\d+|\d+\.\d+)$/}
		};
		if(!this.cleaner.test(x)){return {}};
		eval("this.myObj="+x);
		if(!this.restoreCirculars || !alert){return this.myObj};
		if(this.includeFunctions){
			var x=this.myObj;
			for(var i in x){if(typeof x[i]=="string" && !x[i].indexOf("JSONincludedFunc:")){
				x[i]=x[i].substring(17);
				eval("x[i]="+x[i])
			}}
		};
		this.restoreCode=[];
		this.make(this.myObj,true);
		var r=this.restoreCode.join(";")+";";
		eval('r=r.replace(/\\W([0-9]{1,})(\\W)/g,"[$1]$2").replace(/\\.\\;/g,";")');
		eval(r);
		return this.myObj
	},
	toJsonStringArray:function(arg, out) {
		if(!out){this.path=[]};
		out = out || [];
		var u; // undefined
		switch (typeof arg) {
		case 'object':
			this.lastObj=arg;
			if(this.detectCirculars){
				var m=this.mem; var n=this.pathMem;
				for(var i=0;i<m.length;i++){
					if(arg===m[i]){
						out.push('"JSONcircRef:'+n[i]+'"');return out
					}
				};
				m.push(arg); n.push(this.path.join("."));
			};
			if (arg) {
				if (arg.constructor == Array) {
					out.push('[');
					for (var i = 0; i < arg.length; ++i) {
						this.path.push(i);
						if (i > 0)
							out.push(',\n');
						this.toJsonStringArray(arg[i], out);
						this.path.pop();
					}
					out.push(']');
					return out;
				} else if (typeof arg.toString != 'undefined') {
					out.push('{');
					var first = true;
					for (var i in arg) {
						if(!this.includeProtos && arg[i]===arg.constructor.prototype[i]){continue};
						this.path.push(i);
						var curr = out.length; 
						if (!first)
							out.push(this.compactOutput?',':',\n');
						this.toJsonStringArray(i, out);
						out.push(':');                    
						this.toJsonStringArray(arg[i], out);
						if (out[out.length - 1] == u)
							out.splice(curr, out.length - curr);
						else
							first = false;
						this.path.pop();
					}
					out.push('}');
					return out;
				}
				return out;
			}
			out.push('null');
			return out;
		case 'unknown':
		case 'undefined':
		case 'function':
			if(!this.includeFunctions){out.push(u);return out};
			arg="JSONincludedFunc:"+arg;
			out.push('"');
			var a=['\n','\\n','\r','\\r','"','\\"'];
			arg+=""; for(var i=0;i<6;i+=2){arg=arg.split(a[i]).join(a[i+1])};
			out.push(arg);
			out.push('"');
			return out;
		case 'string':
			if(this.restore && arg.indexOf("JSONcircRef:")==0){
				this.restoreCode.push('this.myObj.'+this.path.join(".")+"="+arg.split("JSONcircRef:").join("this.myObj."));
			};
			out.push('"');
			var a=['\n','\\n','\r','\\r','"','\\"'];
			arg+=""; for(var i=0;i<6;i+=2){arg=arg.split(a[i]).join(a[i+1])};
			out.push(arg);
			out.push('"');
			return out;
		default:
			out.push(String(arg));
			return out;
		}
	}
};
