// Astrus p4pA Framework versão 4.0
// WFramework versão 2.1
// Última atualização: 26/09/2008
//
// ATENÇÃO
//
// Todos os códigos deste arquivo são de propriedade
// de Wilian Fiabani (wilian@astrusweb.com) - Programador/Gerente de produção Astru's Agência.
// Lembre-se: cópia não autorizada é crime!
// Se seu grau de conhecimento não ajuda muito, ou se você for daqueles que se auto declara
// expert em web mas só da boca pra fora, aqui vai uma dica:
// www.w3schools.com
// www.php.net
//
// Desejo à todos uma boa viagem!
// astrusweb.com


function w(div_name){
	try{
		return document.getElementById(div_name);
	}catch(e){
		alert('Seu browser não possui recursos para visualização desta aplicação!');
		parent.location = 'http://br.mozdev.org/firefox/download.html';
	}
}

function rand(min_number,max_number){
    return (parseInt(min_number) + Math.floor(Math.random() * (min_number-max_number)));
}



function Ajax(){
	this.assincr = false;
	this.method = "POST";
	this.val = "";
	this.xmlhttp = null;
	
	try{
		this.xmlhttp =  new ActiveXObject("Microsoft.XMLHTTP");
	}catch(e){
		try{
			this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		}catch(ex){
			try{
				this.xmlhttp = new XMLHttpRequest();
			}catch(exc){
				alert("Esse browser não tem recursos para uso do Ajax");
				this.xmlhttp = null;
			}
		}
	}
	
	this.urlRand = function(uri){
		var dt = new Date();
		if(uri.indexOf("?")>=0){
			return uri+"&"+encodeURI(Math.random()+"_"+dt.getTime());
		}else{
			return uri+"?"+encodeURI(Math.random()+"_"+dt.getTime());
		}
	}
	
	
	//executa os script que estiverem dentro do text
	this.loadScripts = function(content){
		var start, src_pos, end, source;  
		var objScript = null;  
		start = content.indexOf('<script', 0)  
		while (start!=-1){  
			var objScript = document.createElement("script");  
			src_pos = content.indexOf(' src', start)  
			start = content.indexOf('>', start) + 1;  
			if (src_pos < start && src_pos >=0){
				start = src_pos + 4;  
				end = content.indexOf('.', start)+4;  
				source = content.substring(start,end);  
				source = source.replace("=","").replace(" ","").replace("\"","").replace("\"","").replace("\'","").replace("\'","").replace(">","");  
				objScript.src = source;  
			}else{
				end = content.indexOf('</script>', start);  
				source = content.substring(start,end);  
				objScript.text = source;  
			}  
			document.body.appendChild(objScript);  
			start = content.indexOf('<script', end);  
			objScript = null;  
		}  
	}


	//retorna o conteudo de uma ajax
	this.loadResult = function(url){
		if(this.xmlhttp) {
			this.xmlhttp.open(this.method, this.urlRand(url) , this.assincr);
			//headers, vulnerável
			this.xmlhttp.setRequestHeader("Cache-Control", "no-cache");
        	this.xmlhttp.setRequestHeader("Pragma", "no-cache");
			//
			if(this.method == 'GET'){
				this.xmlhttp.send(null);
			}else if(this.method == 'POST'){
				this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
				try{
					this.xmlhttp.send(url.split("?")[1]);
				}catch(e){}
			}
			//
			if(this.assincr){
				this.xmlhttp.onreadystatechange = function(){
					if(ajax.xmlhttp.readyState == 4){
						if(ajax.xmlhttp.status == 200){
							//
							if(ajax.val == 'desconectado'){
								alert('Você foi desconectado e será redirecionado em instantes...!');
								parent.location = '';
							}
							//
							ajax.val = ajax.xmlhttp.responseText;
						}else{
							alert(ajax.xmlhttp.statusText);
						}
					}
				}
			}else{
				ajax.val = ajax.xmlhttp.responseText;
			}
			//
			ajax.loadScripts(ajax.val);
			//window.onload();
		}
		return this.val;
	}
	
	//carrega uma requisição dentro de um div
	this.loadContent = function(url , div_name){
		try{
			document.getElementById(div_name).innerHTML = ajax.loadResult(url);
		}catch(e){
			alert(e.Message);
		}
	}
	
	//carrega uma página sem ajax e sem reload
	this.simpleLoad = function(url){
		try{
			var js = document.createElement("script");
			js.setAttribute('type' , 'text/javascript');
			js.setAttribute('src' , url);
			document.body.appendChild(js);
		}catch(e){
			alert('Impossível carregar o script solicitado!')
		}
	}
	
}



/*/cria um componente de pesquiza
idd = id do componente
div_name = id do div que vai conter o component
pg = página p/ onde serão enviados os dados
/*/

//pegar o sa soccol e colar aqui q funciona melhor
this.wsearch = function(idd, div_name , pg){
	var field = document.createElement("input");
	field.setAttribute("type" , "text");
	field.className = "wsearch";
	field.setAttribute("id" , idd);
	field.setAttribute("name" , idd);
	field.onkeydown = function(){
		return false;
	}
	//
	var lupa = document.createElement("input");
	lupa.setAttribute("type" , "image");
	lupa.setAttribute("src" , "../intranet/app_view/imgs/lupa.gif");
	lupa.className = "wsearch_lupa";
	lupa.setAttribute("title" , "Pesquisar");
	lupa.setAttribute("label" , "Pesquisar");
	lupa.onclick = field.onfocus = function(){
		if(document.getElementById(idd+'_win').style.display=='block'){
			document.getElementById(idd+'_win').style.display = 'none';
			document.getElementById(div_name).style.zIndex = '0';
		}else{
			document.getElementById(idd+'_win').style.display = 'block';
			document.getElementById(div_name).style.zIndex = '80000';
			document.getElementById(idd+'_input').value = document.getElementById(idd).value;
			document.getElementById(idd+'_input').focus();
		}
		return false;
	}
	//
	var divp = document.createElement("div");
	divp.className = "wsearch_popup";
	divp.setAttribute("id" , idd+'_win');
	//
	var goo = document.createElement("input");
	goo.setAttribute("type" , "image");
	goo.setAttribute("src" , "../intranet/app_view/imgs/go.gif");
	goo.setAttribute("title" , "Iniciar pesquisa...");
	goo.setAttribute("label" , "Iniciar pesquisa...");
	goo.className = 'wsearch_goo';
	goo.onclick = function(){
		//limpa o div
		this.blur();
		try{
			document.getElementById(idd+'_win').removeChild(document.getElementById(idd+'_win').getElementsByTagName("div")[0]);
		}catch(e){}
		var loading = document.createElement("div");
		loading.appendChild(document.createTextNode('carregando, aguarde...'));
		loading.className = 'wsearch_loading';
		document.getElementById(idd+'_win').appendChild(loading);
		//
		setTimeout(
			function(){
				var dopt = document.createElement("div");
				dopt.className = 'wsearch_dopt';
				var str = ajax.loadResult(pg+document.getElementById(idd+'_input').value);
				var opts = str.split(";");
				if(opts.length>0 && str!=''){
					for(i=0 ; i<(opts.length-1) ; i++){
						var opt = opts[i].split(":");
						var o = document.createElement("div");
						o.className = "wsearch_opt";
						o.setAttribute("id" , idd+'_opt_'+opt[1]);
						o.appendChild(document.createTextNode(opt[0]));
						o.onclick = function(){
							document.getElementById(idd).value = this.id.split('_opt_')[1];
							document.getElementById(idd+'_win').style.display = 'none';
							document.getElementById(div_name).style.zIndex = '0';
						}
						o.onmouseover = function(){
							this.style.background = '#333333';
							this.style.color = '#efefef';
						}
						o.onmouseout = function(){
							this.style.background = '#efefef';
							this.style.color = '#333333';
						}
						dopt.appendChild(o);
					}
					//limpa o div
					try{
						document.getElementById(idd+'_win').removeChild(document.getElementById(idd+'_win').getElementsByTagName("div")[0]);
					}catch(e){}
					//
					document.getElementById(idd+'_win').appendChild(dopt);
				}else{
					//alert('nao teve resultados');
					var div_interno = document.getElementById(idd+'_win').getElementsByTagName('div')[0];
					div_interno.removeChild(div_interno.childNodes[0]);
					div_interno.appendChild(document.createTextNode("busca sem resultados!"));
				}
				
			},100);
		return false;
	}
	divp.appendChild(goo);
	//
	var div = document.createElement("div");
	div.className = "wsearch_main";
	//
	var input = document.createElement("input");
	input.setAttribute("type" , "text");
	input.setAttribute("maxlength", "30");
	input.className = "wsearch_input";
	input.setAttribute("id" , idd+'_input');
	divp.appendChild(input);
	//
	div.appendChild(field);
	div.appendChild(lupa);
	div.appendChild(divp);
	if(!document.getElementById(idd) && document.getElementById(div_name)){
		try{
			document.getElementById(div_name).appendChild(div);
			document.getElementById(div_name).style.position = 'relative';
			document.getElementById(div_name).style.zIndex = '0';
		}catch(e){
			alert('WSearch Mensagem: '+e.Message);
		}
	}
}


//v1.0
//falta funcionar
/*
.backgroundalpha{
	width: 100%;
	height: 100%;
	background-color:#000000;
	position: absolute;
	top: 0px;
	left: 0px;
	display: none;
	-moz-opacity:0.6;
	filter:progid:DXImageTransform.Microsoft.Alpha(opacity=60);
	filter: Alpha(opacity=60);
	opacity: 0.6;
}*/
this.AlphaBox = function(){
	var alpha = document.createElement("div");
	alpha.className = 'backgroundalpha';
	alpha.style.top = (document.body.scrollTop)+'px';
	alpha.style.left = (document.body.scrollLeft)+'px';
	alpha.style.display = 'block';
	
	this.show = function(){
		document.body.appendChild(alpha);
	}
	
	this.hidden = function(){
		document.body.removeChild(alpha);
	}
}



function fadeOut(target, flag) {
	time = 0.5;
	alpha = 100;
	timer = (time*1000)/50;
	var i = setInterval(
			function() {
				if (alpha <= 0){
					clearInterval(i);
					if(flag){
						target.style.display = 'none';
					}
				}
				setAlpha(target, alpha);
				alpha -= 2;
			}, timer);
}

function fadeIn(target, flag) {
	time = 0.5;
	alpha = 0;
	timer = (time*1000)/50;
	setAlpha(target, alpha);
	if(flag){
		target.style.display = 'block';
	}
	var i = setInterval(
			function() {
				if (alpha >= 100){
					clearInterval(i);
				}
				setAlpha(target, alpha);
				alpha += 2;
			}, timer);
}

function setAlpha(obj, alpha) {
	obj.style.filter = "alpha(opacity="+alpha+")";
	obj.style.opacity = alpha/100;
}



function hideSelect(){
	if(isIE()){
		for(i=0 ; i<document.forms.length ; i++){
			for(j=0 ; j<document.forms[i].elements.length ; j++){
				try{
					if(document.forms[i].elements[j].type.indexOf('select')>=0){
						document.forms[i].elements[j].style.display='none';
					}
				}catch(e){}
			}
		}
	}
}

function showSelect(){
	if(isIE()){
		for(i=0 ; i<document.forms.length ; i++){
			for(j=0 ; j<document.forms[i].elements.length ; j++){
				try{
					if(document.forms[i].elements[j].type.indexOf('select')>=0){
						document.forms[i].elements[j].style.display='block';
					}
				}catch(e){}
			}
		}
	}
}



//alimenta um select
function select_add(obj, str_opt){
	for(i=0 ; i<w(obj).options.length ; i++){
		w(obj).remove(i);
	}
	var opts = str_opt.split(";");
	if(opts.length > 1){
		for(i=0 ; i<(opts.length-1) ; i++){
			str = opts[i].split(":");
			w(obj).options[i] = new Option(str[1], true);
			w(obj).options[i].text = str[0];
			w(obj).options[i].value = str[1];
		}
	}else{
		w(obj).options[0] = new Option('-1' , true);
		w(obj).options[0].text = 'busca sem resultados!';
		w(obj).options[0].value = '-1'
	}
}


//valida os campos em branco de um formulario
function valida(f, l){
	for(i=0 ; i<f.length ; i++){
		alert(w(f[i]).id);
		switch(w(f[i]).type){
			case 'select-one':
				if(w(f[i]).options[w(f[i]).selectedIndex].value == "nulo"){
					alert('Selecione uma opção em '+l[i]+'!');
					return false;
				}
			break;
			
			case 'textarea':
			case 'password':
			case 'hidden':
			case 'text':
			if(w(f[i]).value == ''){
				alert('Preencha o campo '+l[i]+'!');
				//w(f[i]).focus();
				return false;
			}
			break;
		}
	}
	return true;
}

//pega os dados de um form em forma de url
function get(f){
	if(w(f)){
		var url = new Array();
		for(i=0 ; i<w(f).elements.length ; i++){
			switch(w(f).elements[i].type){
				case 'submit':
				case 'button':
				case 'textarea':
				case 'password':
				case 'hidden':
				case 'text':
					url[i] = w(f).elements[i].name+'='+filter(w(f).elements[i].value);
				break;
				
				case 'select-one':
					url[i] = w(f).elements[i].name+'='+filter(w(f).elements[i].options[w(f).elements[i].selectedIndex].value);
				break;
				
				case 'radio':
				case 'checkbox':
					if(w(f).elements[i].checked == true){
						url[i] = w(f).elements[i].name+'='+filter(w(f).elements[i].value);
					}
				break;
			}
		}
		
		return(url.join("&"));
	}
}



//tenta limpar todos os campos de um formulario
function clear(f){
	if(w(f)){
		for(i=0 ; i<w(f).elements.length ; i++){
			switch(w(f).elements[i].type){
				case 'textarea':
				case 'password':
				//case 'hidden':
				case 'text':
					w(f).elements[i].value = '';
				break;
				
				case 'select-one':
					w(f).elements[i].selectedIndex=0;
				break;
				
				case 'radio':
				case 'checkbox':
					//
				break;
			}
		}
	}
}



/* adiciona uma funcao dentro de outra, por exemplo, adicionar
uma função ao window.onload sem sorbescrever o que já existe */
function addFunction(){
}


//aplica um filtro sobre uma string
function filter(str){
	return escape(str);
}

//pega o actio de um formulario e envia por ajax, retorna o resultado (boolean) do ajax
function send(form_name){
	ajax.assincr = false;
	ajax.method = "POST";
	var res = ajax.loadResult(w(form_name).action+'?'+get(form_name));
	if(res == "true"){
		return true;
	}else{
		return false;
	}
}

//mesma coisa que o send, só que retorna de tudo cara...
function sendAndGet(form_name){
	ajax.assincr = false;
	ajax.method = "POST";
	return( ajax.loadResult(w(form_name).action+'?'+get(form_name)) );
}

// retorna os tamanhos da pagina
function getPageSize(){
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

function centralize(obj){
	var size = getPageSize();
	var left = ((size[0]/2)-parseInt(w(obj).style.width));
	w(obj).style.left = left+'px';
}

//retorna um arquivo xml
function xmlLoader(url){
    //by Micox: micoxjcg@yahoo.com.br.
    if(window.XMLHttpRequest){
        var Loader = new XMLHttpRequest();
        Loader.open("GET", url ,false);
        Loader.send(null);
        return Loader.responseXML;
    }else if(window.ActiveXObject){
        var Loader = new ActiveXObject("Msxml2.DOMDocument.3.0");
        Loader.async = false;
        Loader.load(url);
        return Loader;
    }
}


//se tá no IE, retorna true
function isIE(){
	if(navigator.userAgent.toString().indexOf("IE") >= 0){
		return true;
	}else{
		return false;
	}
	/*
	Mozilla/5.0 (Windows; U; Windows NT 5.1; pt-BR; rv:1.9.0.4) Gecko/2008102920 Firefox/3.0.4
	*/
}







////////////////////////////////////////////////////////////////////////////
Function.prototype.bind = function(context){
	var closure = this;
	var tmp_fnc = function(){
		return closure.apply(context, arguments);
	}
	return tmp_fnc;
}
 
Object.prototype.merge = function(object){
	for(attr in object){
		this[attr] = object[attr];
	}
}
 
document.navigators = {
	settings: {
		interval: 100, //The interval which the verification for new data will be done (in miliseconds)
		helper: true, //Specify if the onnavigate function will return the helper, do not change!
		iframe_src: "control.html" //The location of the file control.htm, absolute path please
	},
	initialize: function(){
		this.is_ie = (navigator.userAgent.toLowerCase().indexOf("msie") > -1) ? true : false;
		if(this.is_ie){
			this.settings.iframe_src = this.settings.iframe_src.replace(/(\?|#).*$/, "");
			window.attachEvent("onload", (function(){
				//this.running = true; The iFrame that needs to make it running
				this.iframe = document.createElement("iframe");
				this.iframe.setAttribute("src", this.settings.iframe_src);
				this.iframe.style.display = "none";
				document.getElementsByTagName("body")[0].appendChild(this.iframe);
			}).bind(this));
		} else {this.running = true;}
	},
	//The function that is called by the user and puts new data in the hash to be called
	helper: function(data, force){
		var navs = document.navigators; var data = "[" + this.id + "]" + data;
		if(force){navs.data_buffer = "";} //If force is true then calling sequentially the same helper works
		if(navs.is_ie){navs.iframe.src = navs.settings.iframe_src + "?id=" + data;}
		else{window.location.hash = "#" + data;}
	},
	called: false,
	history: [],
	data_buffer: ""
};
 
function onnavigate(id, callback){
	var navs = document.navigators; navs[id] = {};
	if(!navs.running){navs.initialize();}
	setInterval(function(){if(navs.running){
		var url = window.location.href;
		var hash = window.location.hash.replace(/#/, "");
		var theid = "#[" + id + "]";
		if(url.indexOf(theid) > -1){ //If the call is with us!
			var data = url.split(theid)[1] || "";
			var new_data = theid + data;
			if(navs.data_buffer != new_data){ //If the old content is diferent
				callback(data); //Calling the callback function!
				navs.called = true; //To make sure was already called to fix the index state
				navs.history.push(new_data);
				navs.data_buffer = new_data;
			}
		} else if (!hash && navs.called){ //If the navigators was called and the page is in index state (no hashes), it means reload!
			navs.running = false; //To stop the others Intervals to dont make it the same way and broke something
			window.location = ((url.indexOf("#") > -1) ? url.split("#")[0] : url) + "#";
			window.location.reload();
		}
	}}, navs.settings.interval);
	navs[id].merge({callback: callback});
	if(navs.settings.helper){
		navs[id].helper = navs.helper.bind({id: id}); return navs[id].helper;
	}
}






//////////////////////////////////////////////////////////////////////////////
//gbr
function mask(v_obj, v_fun){
	w(v_obj).onkeypress = function(){
		setTimeout(
			function(){
				w(v_obj).value=v_fun(w(v_obj).value)
			}
		,1);
	}
}

function numbers(v){
	return v.replace(/\D/g,"");
}

function chars(v){
	return v.replace(/\d/g,"");
}

function charsUp(v){
	v=v.toUpperCase();
	return v.replace(/\d/g,"");
}

function charsDown(v){
	v=v.toLowerCase();
	return v.replace(/\d/g,"");
}


function phone(v){
	v=v.replace(/\D/g,"");
	v=v.replace(/^(\d\d)(\d)/g,"($1) $2");
	v=v.replace(/(\d{4})(\d)/,"$1-$2");
	return v;
}

function cpf(v){
	v=v.replace(/\D/g,"");
	v=v.replace(/(\d{3})(\d)/,"$1.$2");
	v=v.replace(/(\d{3})(\d)/,"$1.$2");
	v=v.replace(/(\d{3})(\d{1,2})$/,"$1-$2");
	return v;
}

function cep(v){
	v=v.replace(/\D/g,"");
	v=v.replace(/^(\d{5})(\d)/,"$1-$2");
	return v;
}

function cnpj(v){
	v=v.replace(/\D/g,"");
	v=v.replace(/^(\d{2})(\d)/,"$1.$2");
	v=v.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3");
	v=v.replace(/\.(\d{3})(\d)/,".$1/$2");
	v=v.replace(/(\d{4})(\d)/,"$1-$2");
	return v;
}


function date(v){
	v=v.replace(/\D/g,"");
	v=v.replace(/(\d{2})(\d)/,"$1/$2");
	v=v.replace(/(\d{2})(\d)/,"$1/$2");
	v=v.replace(/^((0[1-9]|[12]\d)\-(0[1-9]|1[0-2])|30\-(0[13-9]|1[0-2])|31\-(0[13578]|1[02]))\-\d{4}$/);
	return v;
}


function time(v){
	v=v.replace(/(\d{2})(\d)/,"$1:$2");
	v=v.replace( (/[012][0-9]:[0-5][0-9]/), "");
	return v;
}


function money (e,ob)  {
	if(window.event){
		keynum = e.keyCode
	}else if(e.which){
		keynum = e.which
	}/*
	if(keynum == 44){ //se for virgula
		keynum = 46; //passa a ser ponto
	}*/
	if(keynum == 46){
		if(ob.value.indexOf(String.fromCharCode(keynum)) == -1 ){
			return true;
		}else{
			return false;
		}
	}
	/*
	var cent=ob.value.split(String.fromCharCode(keynum));
	if(cent.length > 1){
		alert("ok");
		if(cent[1].length >= 2){
			return false;
		}
	}
	*/
	
    if(keynum !=8) {
		keychar = String.fromCharCode(keynum);
		numcheck = /\d/;		
		return numcheck.test(keychar);
	}
}


function validaCNPJ(obj) {
	CNPJ = w(obj).value;
	erro = new String;
	if (CNPJ.length < 18) erro += "É necessario preencher corretamente o número do CNPJ! \n\n";
	if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
	if (erro.length == 0) erro += "É necessário preencher corretamente o número do CNPJ! \n\n";
	}
	//substituir os caracteres que não são números
	CNPJ = CNPJ.replace (".","");
	CNPJ = CNPJ.replace (".","");
	CNPJ = CNPJ.replace ("-","");
	CNPJ = CNPJ.replace ("/","");
	var nonNumbers = /\D/;
	if (nonNumbers.test(CNPJ)) erro += "A verificação de CNPJ suporta apenas números! \n\n";
	var a = [];
	var b = new Number;
	var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
	for (i=0; i<12; i++){
	   a[i] = CNPJ.charAt(i);
	   b += a[i] * c[i+1];
	}
	if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
	b = 0;
	for (y=0; y<13; y++){
	   b += (a[y] * c[y]);
	}
	if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
	if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
	   erro += "Dígito verificador do CNPJ com problema!";
	}
	if (erro.length > 0){
	   alert(erro);
	   return false;
	}
	return true;
}


function validaCPF(obj) {
	var CPF = w(obj).value; // Recebe o valor digitado no campo
	CPF = CPF.replace("," , "");
	CPF = CPF.replace("." , "");
	CPF = CPF.replace("-" , "");
	// Aqui começa a checagem do CPF
	var POSICAO, I, SOMA, DV, DV_INFORMADO;
	var DIGITO = new Array(10);
	DV_INFORMADO = CPF.substr(9, 2); // Retira os dois últimos dígitos do número informado

	// Desemembra o número do CPF na array DIGITO
	for (I=0; I<=8; I++) {
		DIGITO[I] = CPF.substr( I, 1);
	}

	// Calcula o valor do 10º dígito da verificação
	POSICAO = 10;
	SOMA = 0;
	for (I=0; I<=8; I++) {
		SOMA = SOMA + DIGITO[I] * POSICAO;
		POSICAO = POSICAO - 1;
	}
	DIGITO[9] = SOMA % 11;
    if (DIGITO[9] < 2) {
		DIGITO[9] = 0;
	}else{
       DIGITO[9] = 11 - DIGITO[9];
	}

	// Calcula o valor do 11º dígito da verificação
	POSICAO = 11;
	SOMA = 0;
	for (I=0; I<=9; I++) {
		SOMA = SOMA + DIGITO[I] * POSICAO;
		POSICAO = POSICAO - 1;
	}
	DIGITO[10] = SOMA % 11;
	if (DIGITO[10] < 2) {
		DIGITO[10] = 0;
	}else {
        DIGITO[10] = 11 - DIGITO[10];
	}

	// Verifica se os valores dos dígitos verificadores conferem
	DV = DIGITO[9] * 10 + DIGITO[10];
	   if (DV != DV_INFORMADO) {
		  alert('CPF inválido');
		  return false;
	   }
	}


function validacpf(obj){
	var i;
	s = w(obj).value;
	s = s.replace("." , "");
	s = s.replace("-" , "");
	var c = s.substr(0,9);
	var dv = s.substr(9,2);
	var d1 = 0;
	for (i = 0; i < 9; i++){
		d1 += c.charAt(i)*(10-i);
	}
	if (d1 == 0){
		alert("CPF Invalido")
		return false;
	}
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
 
	if (dv.charAt(0) != d1){
		alert("CPF Invalido")
		return false; 
	}
	d1 *= 2;
	for (i = 0; i < 9; i++){
		d1 += c.charAt(i)*(11-i);
	}
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(1) != d1){
		alert("CPF Invalido")
		return false;
	}
	return true;
} 


function validaCPF(obj){
	numcpf = w(obj).value;
	numcpf = numcpf.replace("." , "");
	numcpf = numcpf.replace("." , "");
	numcpf = numcpf.replace("-" , "");
	x = 0;
	soma = 0;
	dig1 = 0;
	dig2 = 0;
	texto = "";
	numcpf1="";
	len = numcpf.length; x = len -1;
	// var numcpf = "12345678909";
	for (var i=0; i <= len - 3; i++) {
		y = numcpf.substring(i,i+1);
		soma = soma + ( y * x);
		x = x - 1;
		texto = texto + y;
	}
	dig1 = 11 - (soma % 11);
	if (dig1 == 10) dig1=0 ;
	if (dig1 == 11) dig1=0 ;
	numcpf1 = numcpf.substring(0,len - 2) + dig1 ;
	x = 11; soma=0;
	for (var i=0; i <= len - 2; i++) {
		soma = soma + (numcpf1.substring(i,i+1) * x);
		x = x - 1;
	}
	dig2= 11 - (soma % 11);
	if (dig2 == 10) dig2=0;
	if (dig2 == 11) dig2=0;
	//alert ("Digito Verificador : " + dig1 + "" + dig2);
	if ((dig1 + "" + dig2) == numcpf.substring(len,len-2)) {
		return true;
	}
	alert ("Numero do CPF invalido !!!");
	return false;
}


function validaData(obj){
	var data = w(obj).value;
	/*
	var str_data = data.split("/");
	if(str_data.length != 3){
		alert('Data Inválida!');
		return false;
	}
	var date = new Date();
	alert(date.setFullYear(str_data[2] , (str_data[1]-1) , str_data[0]));
	*/
	if(data.length != 10){
		alert('Data incompleta!');
		return false;
	}
	var arr_data = data.split("/");
	var dia = arr_data[0];
	var mes = arr_data[1];
	if(dia<=0 || dia > 31){
		alert('Dia do mês inválido: '+dia);
		return false;
	}
	if(mes<=0 || mes>12){
		alert('Mês inválido: '+mes+'!');
		return false;
	}
	return true;
}


function wValidaData(obj){
	var data = w(obj).value;
	/*
	var str_data = data.split("/");
	if(str_data.length != 3){
		alert('Data Inválida!');
		return false;
	}
	var date = new Date();
	alert(date.setFullYear(str_data[2] , (str_data[1]-1) , str_data[0]));
	*/
	if(data.length != 10){
		alert('Data incompleta!');
		setTimeout(
				   function(){
					   w(obj).focus();
				   }, 100);
		return false;
	}
	var arr_data = data.split("/");
	var dia = arr_data[0];
	var mes = arr_data[1];
	if(dia<=0 || dia > 31){
		alert('Dia do mês inválido: '+dia);
		setTimeout(
				   function(){
					   w(obj).focus();
				   }, 100);
		return false;
	}
	if(mes<=0 || mes>12){
		alert('Mês inválido: '+mes+'!');
		setTimeout(
				   function(){
					   w(obj).focus();
				   }, 100);
		return false;
	}
	return true;
}



/* executa uma função através da tecla enter do teclado */
function execute(e , func){
	if(window.event){
		keynum = e.keyCode
	}else if(e.which){
		keynum = e.which
	}
	if(keynum==13){
		func();
		return false;
	}
	return true;
}

function popup(url, width, height){
	var size = getPageSize();
	var left = Math.ceil((size[2]/2)-(width/2));
	var top = Math.ceil((size[3]/2)-(height/2));
	window.open(url , 'WFramework' , 'width='+width+' , height='+height+' , left='+left+' , top='+top+' , scrollbars=yes');
}



/*********************/
documentall = document.all;
/*
* função para formatação de valores monetários retirada de
* http://jonasgalvez.com/br/blog/2003-08/egocentrismo
*/

function formatamoney(c) {
    var t = this; if(c == undefined) c = 2;		
    var p, d = (t=t.split("."))[1].substr(0, c);
    for(p = (t=t[0]).length; (p-=3) >= 1;) {
	        t = t.substr(0,p) + "." + t.substr(p);
    }
    return t+","+d+Array(c+1-d.length).join(0);
}

String.prototype.formatCurrency=formatamoney

function demaskvalue(valor, currency){
/*
* Se currency é false, retorna o valor sem apenas com os números. Se é true, os dois últimos caracteres são considerados as 
* casas decimais
*/
var val2 = '';
var strCheck = '0123456789';
var len = valor.length;
	if (len== 0){
		return 0.00;
	}

	if (currency ==true){	
		/* Elimina os zeros à esquerda 
		* a variável  <i> passa a ser a localização do primeiro caractere após os zeros e 
		* val2 contém os caracteres (descontando os zeros à esquerda)
		*/
		
		for(var i = 0; i < len; i++)
			if ((valor.charAt(i) != '0') && (valor.charAt(i) != ',')) break;
		
		for(; i < len; i++){
			if (strCheck.indexOf(valor.charAt(i))!=-1) val2+= valor.charAt(i);
		}

		if(val2.length==0) return "0.00";
		if (val2.length==1)return "0.0" + val2;
		if (val2.length==2)return "0." + val2;
		
		var parte1 = val2.substring(0,val2.length-2);
		var parte2 = val2.substring(val2.length-2);
		var returnvalue = parte1 + "." + parte2;
		return returnvalue;
		
	}
	else{
			/* currency é false: retornamos os valores COM os zeros à esquerda, 
			* sem considerar os últimos 2 algarismos como casas decimais 
			*/
			val3 ="";
			for(var k=0; k < len; k++){
				if (strCheck.indexOf(valor.charAt(k))!=-1) val3+= valor.charAt(k);
			}			
	return val3;
	}
}

function reais(obj,event){

var whichCode = (window.Event) ? event.which : event.keyCode;
/*
Executa a formatação após o backspace nos navegadores !document.all
*/
if (whichCode == 8 && !documentall) {	
/*
Previne a ação padrão nos navegadores
*/
	if (event.preventDefault){ //standart browsers
			event.preventDefault();
		}else{ // internet explorer
			event.returnValue = false;
	}
	var valor = obj.value;
	var x = valor.substring(0,valor.length-1);
	obj.value= demaskvalue(x,true).formatCurrency();
	return false;
}
/*
Executa o Formata Reais e faz o format currency novamente após o backspace
*/
FormataReais(obj,'.',',',event);
} // end reais


function backspace(obj,event){
/*
Essa função basicamente altera o  backspace nos input com máscara reais para os navegadores IE e opera.
O IE não detecta o keycode 8 no evento keypress, por isso, tratamos no keydown.
Como o opera suporta o infame document.all, tratamos dele na mesma parte do código.
*/

var whichCode = (window.Event) ? event.which : event.keyCode;
if (whichCode == 8 && documentall) {	
	var valor = obj.value;
	var x = valor.substring(0,valor.length-1);
	var y = demaskvalue(x,true).formatCurrency();

	obj.value =""; //necessário para o opera
	obj.value += y;
	
	if (event.preventDefault){ //standart browsers
			event.preventDefault();
		}else{ // internet explorer
			event.returnValue = false;
	}
	return false;

	}// end if		
}// end backspace

function FormataReais(fld, milSep, decSep, e) {
var sep = 0;
var key = '';
var i = j = 0;
var len = len2 = 0;
var strCheck = '0123456789';
var aux = aux2 = '';
var whichCode = (window.Event) ? e.which : e.keyCode;

//if (whichCode == 8 ) return true; //backspace - estamos tratando disso em outra função no keydown
if (whichCode == 0 ) return true;
if (whichCode == 9 ) return true; //tecla tab
if (whichCode == 13) return true; //tecla enter
if (whichCode == 16) return true; //shift internet explorer
if (whichCode == 17) return true; //control no internet explorer
if (whichCode == 27 ) return true; //tecla esc
if (whichCode == 34 ) return true; //tecla end
if (whichCode == 35 ) return true;//tecla end
if (whichCode == 36 ) return true; //tecla home

/*
O trecho abaixo previne a ação padrão nos navegadores. Não estamos inserindo o caractere normalmente, mas via script
*/

if (e.preventDefault){ //standart browsers
		e.preventDefault()
	}else{ // internet explorer
		e.returnValue = false
}

var key = String.fromCharCode(whichCode);  // Valor para o código da Chave
if (strCheck.indexOf(key) == -1) return false;  // Chave inválida

/*
Concatenamos ao value o keycode de key, se esse for um número
*/
fld.value += key;

var len = fld.value.length;
var bodeaux = demaskvalue(fld.value,true).formatCurrency();
fld.value=bodeaux;

/*
Essa parte da função tão somente move o cursor para o final no opera. Atualmente não existe como movê-lo no konqueror.
*/
  if (fld.createTextRange) {
    var range = fld.createTextRange();
    range.collapse(false);
    range.select();
  }
  else if (fld.setSelectionRange) {
    fld.focus();
    var length = fld.value.length;
    fld.setSelectionRange(length, length);
  }
  return false;

}




function FormataReais(fld, milSep, decSep, e) {
	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	var whichCode = (window.Event) ? e.which : e.keyCode;
	 if ((whichCode == 13) || (whichCode == 0) || (whichCode == 8))
	return true;
	key = String.fromCharCode(whichCode);  // Valor para o código da Chave
	if (strCheck.indexOf(key) == -1) return false;  // Chave inválida
	len = fld.value.length;
	for(i = 0; i < len; i++)
	if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
	aux = '';
	for(; i < len; i++)
	if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
	aux += key;
	len = aux.length;
	if (len == 0) fld.value = '';
	if (len == 1) fld.value = '0'+ decSep + '0' + aux;
	if (len == 2) fld.value = '0'+ decSep + aux;
	if (len > 2) {
	aux2 = '';
	for (j = 0, i = len - 3; i >= 0; i--) {
	if (j == 3) {
	aux2 += milSep;
	j = 0;
	}
	aux2 += aux.charAt(i);
	j++;
	}
	fld.value = '';
	len2 = aux2.length;
	for (i = len2 - 1; i >= 0; i--)
	fld.value += aux2.charAt(i);
	fld.value += decSep + aux.substr(len - 2, len);
	}
	return false;

}
























// ===================================================================
// Author: Matt Kruse <matt@mattkruse.com>
// WWW: http://www.mattkruse.com/
//
// NOTICE: You may use this code for any purpose, commercial or
// private, without any further permission from the author. You may
// remove this notice from your final code if you wish, however it is
// appreciated by the author if at least my web site address is kept.
//
// You may *NOT* re-distribute this code in any way except through its
// use. That means, you can include it in your product, or your web
// site, or any other form where the code is actually being used. You
// may not put the plain javascript up on your site for download or
// include it in your javascript libraries for download. 
// If you wish to share this code with others, please just point them
// to the URL instead.
// Please DO NOT link directly to my .js files from your site. Copy
// the files to your server and use them there. Thank you.
// ===================================================================

// HISTORY
// ------------------------------------------------------------------
// Feb 7, 2005: Fixed a CSS styles to use px unit
// March 29, 2004: Added check in select() method for the form field
//      being disabled. If it is, just return and don't do anything.
// March 24, 2004: Fixed bug - when month name and abbreviations were
//      changed, date format still used original values.
// January 26, 2004: Added support for drop-down month and year
//      navigation (Thanks to Chris Reid for the idea)
// September 22, 2003: Fixed a minor problem in YEAR calendar with
//      CSS prefix.
// August 19, 2003: Renamed the function to get styles, and made it
//      work correctly without an object reference
// August 18, 2003: Changed showYearNavigation and 
//      showYearNavigationInput to optionally take an argument of
//      true or false
// July 31, 2003: Added text input option for year navigation.
//      Added a per-calendar CSS prefix option to optionally use 
//      different styles for different calendars.
// July 29, 2003: Fixed bug causing the Today link to be clickable 
//      even though today falls in a disabled date range.
//      Changed formatting to use pure CSS, allowing greater control
//      over look-and-feel options.
// June 11, 2003: Fixed bug causing the Today link to be unselectable
//      under certain cases when some days of week are disabled
// March 14, 2003: Added ability to disable individual dates or date
//      ranges, display as light gray and strike-through
// March 14, 2003: Removed dependency on graypixel.gif and instead 
///     use table border coloring
// March 12, 2003: Modified showCalendar() function to allow optional
//      start-date parameter
// March 11, 2003: Modified select() function to allow optional
//      start-date parameter
/* 
DESCRIPTION: This object implements a popup calendar to allow the user to
select a date, month, quarter, or year.

COMPATABILITY: Works with Netscape 4.x, 6.x, IE 5.x on Windows. Some small
positioning errors - usually with Window positioning - occur on the 
Macintosh platform.
The calendar can be modified to work for any location in the world by 
changing which weekday is displayed as the first column, changing the month
names, and changing the column headers for each day.

USAGE:
// Create a new CalendarPopup object of type WINDOW
var cal = new CalendarPopup(); 

// Create a new CalendarPopup object of type DIV using the DIV named 'mydiv'
var cal = new CalendarPopup('mydiv'); 

// Easy method to link the popup calendar with an input box. 
cal.select(inputObject, anchorname, dateFormat);
// Same method, but passing a default date other than the field's current value
cal.select(inputObject, anchorname, dateFormat, '01/02/2000');
// This is an example call to the popup calendar from a link to populate an 
// input box. Note that to use this, date.js must also be included!!
<A HREF="#" onClick="cal.select(document.forms[0].date,'anchorname','MM/dd/yyyy'); return false;">Select</A>

// Set the type of date select to be used. By default it is 'date'.
cal.setDisplayType(type);

// When a date, month, quarter, or year is clicked, a function is called and
// passed the details. You must write this function, and tell the calendar
// popup what the function name is.
// Function to be called for 'date' select receives y, m, d
cal.setReturnFunction(functionname);
// Function to be called for 'month' select receives y, m
cal.setReturnMonthFunction(functionname);
// Function to be called for 'quarter' select receives y, q
cal.setReturnQuarterFunction(functionname);
// Function to be called for 'year' select receives y
cal.setReturnYearFunction(functionname);

// Show the calendar relative to a given anchor
cal.showCalendar(anchorname);

// Hide the calendar. The calendar is set to autoHide automatically
cal.hideCalendar();

// Set the month names to be used. Default are English month names
cal.setMonthNames("January","February","March",...);

// Set the month abbreviations to be used. Default are English month abbreviations
cal.setMonthAbbreviations("Jan","Feb","Mar",...);

// Show navigation for changing by the year, not just one month at a time
cal.showYearNavigation();

// Show month and year dropdowns, for quicker selection of month of dates
cal.showNavigationDropdowns();

// Set the text to be used above each day column. The days start with 
// sunday regardless of the value of WeekStartDay
cal.setDayHeaders("S","M","T",...);

// Set the day for the first column in the calendar grid. By default this
// is Sunday (0) but it may be changed to fit the conventions of other
// countries.
cal.setWeekStartDay(1); // week is Monday - Sunday

// Set the weekdays which should be disabled in the 'date' select popup. You can
// then allow someone to only select week end dates, or Tuedays, for example
cal.setDisabledWeekDays(0,1); // To disable selecting the 1st or 2nd days of the week

// Selectively disable individual days or date ranges. Disabled days will not
// be clickable, and show as strike-through text on current browsers.
// Date format is any format recognized by parseDate() in date.js
// Pass a single date to disable:
cal.addDisabledDates("2003-01-01");
// Pass null as the first parameter to mean "anything up to and including" the
// passed date:
cal.addDisabledDates(null, "01/02/03");
// Pass null as the second parameter to mean "including the passed date and
// anything after it:
cal.addDisabledDates("Jan 01, 2003", null);
// Pass two dates to disable all dates inbetween and including the two
cal.addDisabledDates("January 01, 2003", "Dec 31, 2003");

// When the 'year' select is displayed, set the number of years back from the 
// current year to start listing years. Default is 2.
// This is also used for year drop-down, to decide how many years +/- to display
cal.setYearSelectStartOffset(2);

// Text for the word "Today" appearing on the calendar
cal.setTodayText("Today");

// The calendar uses CSS classes for formatting. If you want your calendar to
// have unique styles, you can set the prefix that will be added to all the
// classes in the output.
// For example, normal output may have this:
//     <SPAN CLASS="cpTodayTextDisabled">Today<SPAN>
// But if you set the prefix like this:
cal.setCssPrefix("Test");
// The output will then look like:
//     <SPAN CLASS="TestcpTodayTextDisabled">Today<SPAN>
// And you can define that style somewhere in your page.

// When using Year navigation, you can make the year be an input box, so
// the user can manually change it and jump to any year
cal.showYearNavigationInput();

// Set the calendar offset to be different than the default. By default it
// will appear just below and to the right of the anchorname. So if you have
// a text box where the date will go and and anchor immediately after the
// text box, the calendar will display immediately under the text box.
cal.offsetX = 20;
cal.offsetY = 20;

NOTES:

1) Requires the functions in AnchorPosition.js and PopupWindow.js

2) Your anchor tag MUST contain both NAME and ID attributes which are the 
   same. For example:
   <A NAME="test" ID="test"> </A>

3) There must be at least a space between <A> </A> for IE5.5 to see the 
   anchor tag correctly. Do not do <A></A> with no space.

4) When a CalendarPopup object is created, a handler for 'onmouseup' is
   attached to any event handler you may have already defined. Do NOT define
   an event handler for 'onmouseup' after you define a CalendarPopup object 
   or the autoHide() will not work correctly.
   
5) The calendar popup display uses style sheets to make it look nice.

*/ 

// CONSTRUCTOR for the CalendarPopup Object
function CalendarPopup() {
	var c;
	if (arguments.length>0) {
		c = new PopupWindow(arguments[0]);
		}
	else {
		c = new PopupWindow();
		c.setSize(150,175);
		}
	c.offsetX = -152;
	c.offsetY = 25;
	c.autoHide();
	// Calendar-specific properties
	c.monthNames = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
	c.monthAbbreviations = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
	c.dayHeaders = new Array("S","M","T","W","T","F","S");
	c.returnFunction = "CP_tmpReturnFunction";
	c.returnMonthFunction = "CP_tmpReturnMonthFunction";
	c.returnQuarterFunction = "CP_tmpReturnQuarterFunction";
	c.returnYearFunction = "CP_tmpReturnYearFunction";
	c.weekStartDay = 0;
	c.isShowYearNavigation = false;
	c.displayType = "date";
	c.disabledWeekDays = new Object();
	c.disabledDatesExpression = "";
	c.yearSelectStartOffset = 2;
	c.currentDate = null;
	c.todayText="Today";
	c.cssPrefix="";
	c.isShowNavigationDropdowns=false;
	c.isShowYearNavigationInput=false;
	window.CP_calendarObject = null;
	window.CP_targetInput = null;
	window.CP_dateFormat = "MM/dd/yyyy";
	// Method mappings
	c.copyMonthNamesToWindow = CP_copyMonthNamesToWindow;
	c.setReturnFunction = CP_setReturnFunction;
	c.setReturnMonthFunction = CP_setReturnMonthFunction;
	c.setReturnQuarterFunction = CP_setReturnQuarterFunction;
	c.setReturnYearFunction = CP_setReturnYearFunction;
	c.setMonthNames = CP_setMonthNames;
	c.setMonthAbbreviations = CP_setMonthAbbreviations;
	c.setDayHeaders = CP_setDayHeaders;
	c.setWeekStartDay = CP_setWeekStartDay;
	c.setDisplayType = CP_setDisplayType;
	c.setDisabledWeekDays = CP_setDisabledWeekDays;
	c.addDisabledDates = CP_addDisabledDates;
	c.setYearSelectStartOffset = CP_setYearSelectStartOffset;
	c.setTodayText = CP_setTodayText;
	c.showYearNavigation = CP_showYearNavigation;
	c.showCalendar = CP_showCalendar;
	c.hideCalendar = CP_hideCalendar;
	c.getStyles = getCalendarStyles;
	c.refreshCalendar = CP_refreshCalendar;
	c.getCalendar = CP_getCalendar;
	c.select = CP_select;
	c.setCssPrefix = CP_setCssPrefix;
	c.showNavigationDropdowns = CP_showNavigationDropdowns;
	c.showYearNavigationInput = CP_showYearNavigationInput;
	c.copyMonthNamesToWindow();
	// Return the object
	return c;
	}
function CP_copyMonthNamesToWindow() {
	// Copy these values over to the date.js 
	if (typeof(window.MONTH_NAMES)!="undefined" && window.MONTH_NAMES!=null) {
		window.MONTH_NAMES = new Array();
		for (var i=0; i<this.monthNames.length; i++) {
			window.MONTH_NAMES[window.MONTH_NAMES.length] = this.monthNames[i];
		}
		for (var i=0; i<this.monthAbbreviations.length; i++) {
			window.MONTH_NAMES[window.MONTH_NAMES.length] = this.monthAbbreviations[i];
		}
	}
}
// Temporary default functions to be called when items clicked, so no error is thrown
function CP_tmpReturnFunction(y,m,d) { 
	if (window.CP_targetInput!=null) {
		var dt = new Date(y,m-1,d,0,0,0);
		if (window.CP_calendarObject!=null) { window.CP_calendarObject.copyMonthNamesToWindow(); }
		window.CP_targetInput.value = formatDate(dt,window.CP_dateFormat);
		}
	else {
		alert('Use setReturnFunction() to define which function will get the clicked results!'); 
		}
	}
function CP_tmpReturnMonthFunction(y,m) { 
	alert('Use setReturnMonthFunction() to define which function will get the clicked results!\nYou clicked: year='+y+' , month='+m); 
	}
function CP_tmpReturnQuarterFunction(y,q) { 
	alert('Use setReturnQuarterFunction() to define which function will get the clicked results!\nYou clicked: year='+y+' , quarter='+q); 
	}
function CP_tmpReturnYearFunction(y) { 
	alert('Use setReturnYearFunction() to define which function will get the clicked results!\nYou clicked: year='+y); 
	}

// Set the name of the functions to call to get the clicked item
function CP_setReturnFunction(name) { this.returnFunction = name; }
function CP_setReturnMonthFunction(name) { this.returnMonthFunction = name; }
function CP_setReturnQuarterFunction(name) { this.returnQuarterFunction = name; }
function CP_setReturnYearFunction(name) { this.returnYearFunction = name; }

// Over-ride the built-in month names
function CP_setMonthNames() {
	for (var i=0; i<arguments.length; i++) { this.monthNames[i] = arguments[i]; }
	this.copyMonthNamesToWindow();
	}

// Over-ride the built-in month abbreviations
function CP_setMonthAbbreviations() {
	for (var i=0; i<arguments.length; i++) { this.monthAbbreviations[i] = arguments[i]; }
	this.copyMonthNamesToWindow();
	}

// Over-ride the built-in column headers for each day
function CP_setDayHeaders() {
	for (var i=0; i<arguments.length; i++) { this.dayHeaders[i] = arguments[i]; }
	}

// Set the day of the week (0-7) that the calendar display starts on
// This is for countries other than the US whose calendar displays start on Monday(1), for example
function CP_setWeekStartDay(day) { this.weekStartDay = day; }

// Show next/last year navigation links
function CP_showYearNavigation() { this.isShowYearNavigation = (arguments.length>0)?arguments[0]:true; }

// Which type of calendar to display
function CP_setDisplayType(type) {
	if (type!="date"&&type!="week-end"&&type!="month"&&type!="quarter"&&type!="year") { alert("Invalid display type! Must be one of: date,week-end,month,quarter,year"); return false; }
	this.displayType=type;
	}

// How many years back to start by default for year display
function CP_setYearSelectStartOffset(num) { this.yearSelectStartOffset=num; }

// Set which weekdays should not be clickable
function CP_setDisabledWeekDays() {
	this.disabledWeekDays = new Object();
	for (var i=0; i<arguments.length; i++) { this.disabledWeekDays[arguments[i]] = true; }
	}
	
// Disable individual dates or ranges
// Builds an internal logical test which is run via eval() for efficiency
function CP_addDisabledDates(start, end) {
	if (arguments.length==1) { end=start; }
	if (start==null && end==null) { return; }
	if (this.disabledDatesExpression!="") { this.disabledDatesExpression+= "||"; }
	if (start!=null) { start = parseDate(start); start=""+start.getFullYear()+LZ(start.getMonth()+1)+LZ(start.getDate());}
	if (end!=null) { end=parseDate(end); end=""+end.getFullYear()+LZ(end.getMonth()+1)+LZ(end.getDate());}
	if (start==null) { this.disabledDatesExpression+="(ds<="+end+")"; }
	else if (end  ==null) { this.disabledDatesExpression+="(ds>="+start+")"; }
	else { this.disabledDatesExpression+="(ds>="+start+"&&ds<="+end+")"; }
	}
	
// Set the text to use for the "Today" link
function CP_setTodayText(text) {
	this.todayText = text;
	}

// Set the prefix to be added to all CSS classes when writing output
function CP_setCssPrefix(val) { 
	this.cssPrefix = val; 
	}

// Show the navigation as an dropdowns that can be manually changed
function CP_showNavigationDropdowns() { this.isShowNavigationDropdowns = (arguments.length>0)?arguments[0]:true; }

// Show the year navigation as an input box that can be manually changed
function CP_showYearNavigationInput() { this.isShowYearNavigationInput = (arguments.length>0)?arguments[0]:true; }

// Hide a calendar object
function CP_hideCalendar() {
	if (arguments.length > 0) { window.popupWindowObjects[arguments[0]].hidePopup(); }
	else { this.hidePopup(); }
	}

// Refresh the contents of the calendar display
function CP_refreshCalendar(index) {
	var calObject = window.popupWindowObjects[index];
	if (arguments.length>1) { 
		calObject.populate(calObject.getCalendar(arguments[1],arguments[2],arguments[3],arguments[4],arguments[5]));
		}
	else {
		calObject.populate(calObject.getCalendar());
		}
	calObject.refresh();
	}

// Populate the calendar and display it
function CP_showCalendar(anchorname) {
	if (arguments.length>1) {
		if (arguments[1]==null||arguments[1]=="") {
			this.currentDate=new Date();
			}
		else {
			this.currentDate=new Date(parseDate(arguments[1]));
			}
		}
	this.populate(this.getCalendar());
	this.showPopup(anchorname);
	}

// Simple method to interface popup calendar with a text-entry box
function CP_select(inputobj, linkname, format) {
	var selectedDate=(arguments.length>3)?arguments[3]:null;
	if (!window.getDateFromFormat) {
		alert("calendar.select: To use this method you must also include 'date.js' for date formatting");
		return;
		}
	if (this.displayType!="date"&&this.displayType!="week-end") {
		alert("calendar.select: This function can only be used with displayType 'date' or 'week-end'");
		return;
		}
	if (inputobj.type!="text" && inputobj.type!="hidden" && inputobj.type!="textarea") { 
		alert("calendar.select: Input object passed is not a valid form input object"); 
		window.CP_targetInput=null;
		return;
		}
	if (inputobj.disabled) { return; } // Can't use calendar input on disabled form input!
	window.CP_targetInput = inputobj;
	window.CP_calendarObject = this;
	this.currentDate=null;
	var time=0;
	if (selectedDate!=null) {
		time = getDateFromFormat(selectedDate,format)
		}
	else if (inputobj.value!="") {
		time = getDateFromFormat(inputobj.value,format);
		}
	if (selectedDate!=null || inputobj.value!="") {
		if (time==0) { this.currentDate=null; }
		else { this.currentDate=new Date(time); }
		}
	window.CP_dateFormat = format;
	this.showCalendar(linkname);
	}
	
// Get style block needed to display the calendar correctly
function getCalendarStyles() {
	var result = "";
	var p = "";
	if (this!=null && typeof(this.cssPrefix)!="undefined" && this.cssPrefix!=null && this.cssPrefix!="") { p=this.cssPrefix; }
	result += "<STYLE>\n";
	result += "."+p+"cpYearNavigation,."+p+"cpMonthNavigation { background-color:#C0C0C0; text-align:center; vertical-align:center; text-decoration:none; color:#000000; font-weight:bold; }\n";
	result += "."+p+"cpDayColumnHeader, ."+p+"cpYearNavigation,."+p+"cpMonthNavigation,."+p+"cpCurrentMonthDate,."+p+"cpCurrentMonthDateDisabled,."+p+"cpOtherMonthDate,."+p+"cpOtherMonthDateDisabled,."+p+"cpCurrentDate,."+p+"cpCurrentDateDisabled,."+p+"cpTodayText,."+p+"cpTodayTextDisabled,."+p+"cpText { font-family:arial; font-size:8pt; }\n";
	result += "TD."+p+"cpDayColumnHeader { text-align:right; border:solid thin #C0C0C0;border-width:0px 0px 1px 0px; }\n";
	result += "."+p+"cpCurrentMonthDate, ."+p+"cpOtherMonthDate, ."+p+"cpCurrentDate  { text-align:right; text-decoration:none; }\n";
	result += "."+p+"cpCurrentMonthDateDisabled, ."+p+"cpOtherMonthDateDisabled, ."+p+"cpCurrentDateDisabled { color:#D0D0D0; text-align:right; text-decoration:line-through; }\n";
	result += "."+p+"cpCurrentMonthDate, .cpCurrentDate { color:#000000; }\n";
	result += "."+p+"cpOtherMonthDate { color:#808080; }\n";
	result += "TD."+p+"cpCurrentDate { color:white; background-color: #C0C0C0; border-width:1px; border:solid thin #800000; }\n";
	result += "TD."+p+"cpCurrentDateDisabled { border-width:1px; border:solid thin #FFAAAA; }\n";
	result += "TD."+p+"cpTodayText, TD."+p+"cpTodayTextDisabled { border:solid thin #C0C0C0; border-width:1px 0px 0px 0px;}\n";
	result += "A."+p+"cpTodayText, SPAN."+p+"cpTodayTextDisabled { height:20px; }\n";
	result += "A."+p+"cpTodayText { color:black; }\n";
	result += "."+p+"cpTodayTextDisabled { color:#D0D0D0; }\n";
	result += "."+p+"cpBorder { border:solid thin #808080; }\n";
	result += "</STYLE>\n";
	return result;
	}

// Return a string containing all the calendar code to be displayed
function CP_getCalendar() {
	var now = new Date();
	// Reference to window
	if (this.type == "WINDOW") { var windowref = "window.opener."; }
	else { var windowref = ""; }
	var result = "";
	// If POPUP, write entire HTML document
	if (this.type == "WINDOW") {
		result += "<HTML><HEAD><TITLE>Calendar</TITLE>"+this.getStyles()+"</HEAD><BODY MARGINWIDTH=0 MARGINHEIGHT=0 TOPMARGIN=0 RIGHTMARGIN=0 LEFTMARGIN=0>\n";
		result += '<CENTER><TABLE WIDTH=100% BORDER=0 BORDERWIDTH=0 CELLSPACING=0 CELLPADDING=0>\n';
		}
	else {
		result += '<TABLE CLASS="'+this.cssPrefix+'cpBorder" WIDTH=144 BORDER=1 BORDERWIDTH=1 CELLSPACING=0 CELLPADDING=1>\n';
		result += '<TR><TD ALIGN=CENTER>\n';
		result += '<CENTER>\n';
		}
	// Code for DATE display (default)
	// -------------------------------
	if (this.displayType=="date" || this.displayType=="week-end") {
		if (this.currentDate==null) { this.currentDate = now; }
		if (arguments.length > 0) { var month = arguments[0]; }
			else { var month = this.currentDate.getMonth()+1; }
		if (arguments.length > 1 && arguments[1]>0 && arguments[1]-0==arguments[1]) { var year = arguments[1]; }
			else { var year = this.currentDate.getFullYear(); }
		var daysinmonth= new Array(0,31,28,31,30,31,30,31,31,30,31,30,31);
		if ( ( (year%4 == 0)&&(year%100 != 0) ) || (year%400 == 0) ) {
			daysinmonth[2] = 29;
			}
		var current_month = new Date(year,month-1,1);
		var display_year = year;
		var display_month = month;
		var display_date = 1;
		var weekday= current_month.getDay();
		var offset = 0;
		
		offset = (weekday >= this.weekStartDay) ? weekday-this.weekStartDay : 7-this.weekStartDay+weekday ;
		if (offset > 0) {
			display_month--;
			if (display_month < 1) { display_month = 12; display_year--; }
			display_date = daysinmonth[display_month]-offset+1;
			}
		var next_month = month+1;
		var next_month_year = year;
		if (next_month > 12) { next_month=1; next_month_year++; }
		var last_month = month-1;
		var last_month_year = year;
		if (last_month < 1) { last_month=12; last_month_year--; }
		var date_class;
		if (this.type!="WINDOW") {
			result += "<TABLE WIDTH=144 BORDER=0 BORDERWIDTH=0 CELLSPACING=0 CELLPADDING=0>";
			}
		result += '<TR>\n';
		var refresh = windowref+'CP_refreshCalendar';
		var refreshLink = 'javascript:' + refresh;
		if (this.isShowNavigationDropdowns) {
			result += '<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" WIDTH="78" COLSPAN="3"><select CLASS="'+this.cssPrefix+'cpMonthNavigation" name="cpMonth" onChange="'+refresh+'('+this.index+',this.options[this.selectedIndex].value-0,'+(year-0)+');">';
			for( var monthCounter=1; monthCounter<=12; monthCounter++ ) {
				var selected = (monthCounter==month) ? 'SELECTED' : '';
				result += '<option value="'+monthCounter+'" '+selected+'>'+this.monthNames[monthCounter-1]+'</option>';
				}
			result += '</select></TD>';
			result += '<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" WIDTH="10">&nbsp;</TD>';

			result += '<TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="56" COLSPAN="3"><select CLASS="'+this.cssPrefix+'cpYearNavigation" name="cpYear" onChange="'+refresh+'('+this.index+','+month+',this.options[this.selectedIndex].value-0);">';
			for( var yearCounter=year-this.yearSelectStartOffset; yearCounter<=year+this.yearSelectStartOffset; yearCounter++ ) {
				var selected = (yearCounter==year) ? 'SELECTED' : '';
				result += '<option value="'+yearCounter+'" '+selected+'>'+yearCounter+'</option>';
				}
			result += '</select></TD>';
			}
		else {
			if (this.isShowYearNavigation) {
				result += '<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" WIDTH="10"><A CLASS="'+this.cssPrefix+'cpMonthNavigation" HREF="'+refreshLink+'('+this.index+','+last_month+','+last_month_year+');">&lt;</A></TD>';
				result += '<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" WIDTH="58"><SPAN CLASS="'+this.cssPrefix+'cpMonthNavigation">'+this.monthNames[month-1]+'</SPAN></TD>';
				result += '<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" WIDTH="10"><A CLASS="'+this.cssPrefix+'cpMonthNavigation" HREF="'+refreshLink+'('+this.index+','+next_month+','+next_month_year+');">&gt;</A></TD>';
				result += '<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" WIDTH="10">&nbsp;</TD>';

				result += '<TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="10"><A CLASS="'+this.cssPrefix+'cpYearNavigation" HREF="'+refreshLink+'('+this.index+','+month+','+(year-1)+');">&lt;</A></TD>';
				if (this.isShowYearNavigationInput) {
					result += '<TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="36"><INPUT NAME="cpYear" CLASS="'+this.cssPrefix+'cpYearNavigation" SIZE="4" MAXLENGTH="4" VALUE="'+year+'" onBlur="'+refresh+'('+this.index+','+month+',this.value-0);"></TD>';
					}
				else {
					result += '<TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="36"><SPAN CLASS="'+this.cssPrefix+'cpYearNavigation">'+year+'</SPAN></TD>';
					}
				result += '<TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="10"><A CLASS="'+this.cssPrefix+'cpYearNavigation" HREF="'+refreshLink+'('+this.index+','+month+','+(year+1)+');">&gt;</A></TD>';
				}
			else {
				result += '<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" WIDTH="22"><A CLASS="'+this.cssPrefix+'cpMonthNavigation" HREF="'+refreshLink+'('+this.index+','+last_month+','+last_month_year+');">&lt;&lt;</A></TD>\n';
				result += '<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" WIDTH="100"><SPAN CLASS="'+this.cssPrefix+'cpMonthNavigation">'+this.monthNames[month-1]+' '+year+'</SPAN></TD>\n';
				result += '<TD CLASS="'+this.cssPrefix+'cpMonthNavigation" WIDTH="22"><A CLASS="'+this.cssPrefix+'cpMonthNavigation" HREF="'+refreshLink+'('+this.index+','+next_month+','+next_month_year+');">&gt;&gt;</A></TD>\n';
				}
			}
		result += '</TR></TABLE>\n';
		result += '<TABLE WIDTH=120 BORDER=0 CELLSPACING=0 CELLPADDING=1 ALIGN=CENTER>\n';
		result += '<TR>\n';
		for (var j=0; j<7; j++) {

			result += '<TD CLASS="'+this.cssPrefix+'cpDayColumnHeader" WIDTH="14%"><SPAN CLASS="'+this.cssPrefix+'cpDayColumnHeader">'+this.dayHeaders[(this.weekStartDay+j)%7]+'</TD>\n';
			}
		result += '</TR>\n';
		for (var row=1; row<=6; row++) {
			result += '<TR>\n';
			for (var col=1; col<=7; col++) {
				var disabled=false;
				if (this.disabledDatesExpression!="") {
					var ds=""+display_year+LZ(display_month)+LZ(display_date);
					eval("disabled=("+this.disabledDatesExpression+")");
					}
				var dateClass = "";
				if ((display_month == this.currentDate.getMonth()+1) && (display_date==this.currentDate.getDate()) && (display_year==this.currentDate.getFullYear())) {
					dateClass = "cpCurrentDate";
					}
				else if (display_month == month) {
					dateClass = "cpCurrentMonthDate";
					}
				else {
					dateClass = "cpOtherMonthDate";
					}
				if (disabled || this.disabledWeekDays[col-1]) {
					result += '	<TD CLASS="'+this.cssPrefix+dateClass+'"><SPAN CLASS="'+this.cssPrefix+dateClass+'Disabled">'+display_date+'</SPAN></TD>\n';
					}
				else {
					var selected_date = display_date;
					var selected_month = display_month;
					var selected_year = display_year;
					if (this.displayType=="week-end") {
						var d = new Date(selected_year,selected_month-1,selected_date,0,0,0,0);
						d.setDate(d.getDate() + (7-col));
						selected_year = d.getYear();
						if (selected_year < 1000) { selected_year += 1900; }
						selected_month = d.getMonth()+1;
						selected_date = d.getDate();
						}
					result += '	<TD CLASS="'+this.cssPrefix+dateClass+'"><A HREF="javascript:'+windowref+this.returnFunction+'('+selected_year+','+selected_month+','+selected_date+');'+windowref+'CP_hideCalendar(\''+this.index+'\');" CLASS="'+this.cssPrefix+dateClass+'">'+display_date+'</A></TD>\n';
					}
				display_date++;
				if (display_date > daysinmonth[display_month]) {
					display_date=1;
					display_month++;
					}
				if (display_month > 12) {
					display_month=1;
					display_year++;
					}
				}
			result += '</TR>';
			}
		var current_weekday = now.getDay() - this.weekStartDay;
		if (current_weekday < 0) {
			current_weekday += 7;
			}
		result += '<TR>\n';
		result += '	<TD COLSPAN=7 ALIGN=CENTER CLASS="'+this.cssPrefix+'cpTodayText">\n';
		if (this.disabledDatesExpression!="") {
			var ds=""+now.getFullYear()+LZ(now.getMonth()+1)+LZ(now.getDate());
			eval("disabled=("+this.disabledDatesExpression+")");
			}
		if (disabled || this.disabledWeekDays[current_weekday+1]) {
			result += '		<SPAN CLASS="'+this.cssPrefix+'cpTodayTextDisabled">'+this.todayText+'</SPAN>\n';
			}
		else {
			result += '		<A CLASS="'+this.cssPrefix+'cpTodayText" HREF="javascript:'+windowref+this.returnFunction+'(\''+now.getFullYear()+'\',\''+(now.getMonth()+1)+'\',\''+now.getDate()+'\');'+windowref+'CP_hideCalendar(\''+this.index+'\');">'+this.todayText+'</A>\n';
			}
		result += '		<BR>\n';
		result += '	</TD></TR></TABLE></CENTER></TD></TR></TABLE>\n';
	}

	// Code common for MONTH, QUARTER, YEAR
	// ------------------------------------
	if (this.displayType=="month" || this.displayType=="quarter" || this.displayType=="year") {
		if (arguments.length > 0) { var year = arguments[0]; }
		else { 
			if (this.displayType=="year") {	var year = now.getFullYear()-this.yearSelectStartOffset; }
			else { var year = now.getFullYear(); }
			}
		if (this.displayType!="year" && this.isShowYearNavigation) {
			result += "<TABLE WIDTH=144 BORDER=0 BORDERWIDTH=0 CELLSPACING=0 CELLPADDING=0>";
			result += '<TR>\n';
			result += '	<TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="22"><A CLASS="'+this.cssPrefix+'cpYearNavigation" HREF="javascript:'+windowref+'CP_refreshCalendar('+this.index+','+(year-1)+');">&lt;&lt;</A></TD>\n';
			result += '	<TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="100">'+year+'</TD>\n';
			result += '	<TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="22"><A CLASS="'+this.cssPrefix+'cpYearNavigation" HREF="javascript:'+windowref+'CP_refreshCalendar('+this.index+','+(year+1)+');">&gt;&gt;</A></TD>\n';
			result += '</TR></TABLE>\n';
			}
		}
		
	// Code for MONTH display 
	// ----------------------
	if (this.displayType=="month") {
		// If POPUP, write entire HTML document
		result += '<TABLE WIDTH=120 BORDER=0 CELLSPACING=1 CELLPADDING=0 ALIGN=CENTER>\n';
		for (var i=0; i<4; i++) {
			result += '<TR>';
			for (var j=0; j<3; j++) {
				var monthindex = ((i*3)+j);
				result += '<TD WIDTH=33% ALIGN=CENTER><A CLASS="'+this.cssPrefix+'cpText" HREF="javascript:'+windowref+this.returnMonthFunction+'('+year+','+(monthindex+1)+');'+windowref+'CP_hideCalendar(\''+this.index+'\');" CLASS="'+date_class+'">'+this.monthAbbreviations[monthindex]+'</A></TD>';
				}
			result += '</TR>';
			}
		result += '</TABLE></CENTER></TD></TR></TABLE>\n';
		}
	
	// Code for QUARTER display
	// ------------------------
	if (this.displayType=="quarter") {
		result += '<BR><TABLE WIDTH=120 BORDER=1 CELLSPACING=0 CELLPADDING=0 ALIGN=CENTER>\n';
		for (var i=0; i<2; i++) {
			result += '<TR>';
			for (var j=0; j<2; j++) {
				var quarter = ((i*2)+j+1);
				result += '<TD WIDTH=50% ALIGN=CENTER><BR><A CLASS="'+this.cssPrefix+'cpText" HREF="javascript:'+windowref+this.returnQuarterFunction+'('+year+','+quarter+');'+windowref+'CP_hideCalendar(\''+this.index+'\');" CLASS="'+date_class+'">Q'+quarter+'</A><BR><BR></TD>';
				}
			result += '</TR>';
			}
		result += '</TABLE></CENTER></TD></TR></TABLE>\n';
		}

	// Code for YEAR display
	// ---------------------
	if (this.displayType=="year") {
		var yearColumnSize = 4;
		result += "<TABLE WIDTH=144 BORDER=0 BORDERWIDTH=0 CELLSPACING=0 CELLPADDING=0>";
		result += '<TR>\n';
		result += '	<TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="50%"><A CLASS="'+this.cssPrefix+'cpYearNavigation" HREF="javascript:'+windowref+'CP_refreshCalendar('+this.index+','+(year-(yearColumnSize*2))+');">&lt;&lt;</A></TD>\n';
		result += '	<TD CLASS="'+this.cssPrefix+'cpYearNavigation" WIDTH="50%"><A CLASS="'+this.cssPrefix+'cpYearNavigation" HREF="javascript:'+windowref+'CP_refreshCalendar('+this.index+','+(year+(yearColumnSize*2))+');">&gt;&gt;</A></TD>\n';
		result += '</TR></TABLE>\n';
		result += '<TABLE WIDTH=120 BORDER=0 CELLSPACING=1 CELLPADDING=0 ALIGN=CENTER>\n';
		for (var i=0; i<yearColumnSize; i++) {
			for (var j=0; j<2; j++) {
				var currentyear = year+(j*yearColumnSize)+i;
				result += '<TD WIDTH=50% ALIGN=CENTER><A CLASS="'+this.cssPrefix+'cpText" HREF="javascript:'+windowref+this.returnYearFunction+'('+currentyear+');'+windowref+'CP_hideCalendar(\''+this.index+'\');" CLASS="'+date_class+'">'+currentyear+'</A></TD>';
				}
			result += '</TR>';
			}
		result += '</TABLE></CENTER></TD></TR></TABLE>\n';
		}
	// Common
	if (this.type == "WINDOW") {
		result += "</BODY></HTML>\n";
		}
	return result;
	}
