// JavaScript Document

/* ###########################################################################################
	Requer: CrossBrowse.js
########################################################################################### */

/** ============================================================================================
	Permite inserir um caracter em uma string em uma posio especifica 
*/
function InsChar( str, charr, pos ) {
	var aux = '';
	var tmp = new String( str );
	var auxstr = tmp.split('');
	for( i=0; i < auxstr.length; i++ ) {
		if( (pos == i) && ( auxstr[i] != charr ) ) {
			aux = aux + charr;
		}
		aux = aux + auxstr[i];
	}
	return aux;
}

/** ============================================================================================
	Retorna apenas os digitos numericos de uma string 
*/
function GetNum( str, sinal ) {
	if( typeof( sinal ) == "undefined" ) {
		sinal = false;
	}
	var aux = '';
	var firstNum = false;
	var tmp = new String( str );
	var arr = tmp.split('');
	for( i=0; i < arr.length; i++ ) {
		if( (!isNaN( arr[i] ) && (arr[i] != ' ')) || ((arr[i] != '-') && (sinal))) {
			aux = aux + arr[i];
		}
	}
	return aux;
}
// -----------------------------------------------------------------------------------------
function isNegativo( str ) {
    var valor_str = new String( str );
    var valor_array = valor_str.split("");
    if( valor_array.length > 1 ) {
        return ( valor_array[0] == '-' );
    } else {
        return false;
    }
}
// -----------------------------------------------------------------------------------------
function getEvent( args_array ) {
	if( args_array.length > 0 ) {
		return args_array[0];
	} else {
		return false;
	}
}
// -----------------------------------------------------------------------------------------
function getElement( args_array, obj ) {
	var element = null;
	if( args_array.length == 1 ) {
		e = args_array[0];
		if (typeof(e)=='undefined'){var e=window.event;}
		source=e.target?e.target:e.srcElement;
		if(source.nodeType == 3)source = source.parentNode;
		element = source;
		element.evento_obj = e;
	} else {
		element = obj;
		element.evento_obj = null;
	}
	return element;
}
// -----------------------------------------------------------------------------------------
function strData() {
	var dt_obj = new Date();
	var ano = dt_obj.getFullYear();
	var mes = dt_obj.getMonth() + 1;
	var dia = dt_obj.getDate();
	var dt_str = "";
	if( dia < 10 ) {
		dt_str = dt_str + "0" + dia;
	} else {
		dt_str = dt_str + "" + dia;
	}
	if( mes < 10 ) {
		dt_str = dt_str + "/0" + mes;
	} else {
		dt_str = dt_str + "/" + mes;
	}
	dt_str = dt_str + "/" + ano;
	return dt_str;
}

function addEventLis(obj, evType, fn){
    if (obj.addEventListener)
		obj.addEventListener(evType, fn, true);
	if (obj.attachEvent)
		obj.attachEvent("on"+evType, fn);
}

function $( id ){
	return document.getElementById( id );
}

function getDocCoords() {
	var L = document.documentElement.scrollLeft;
	var T = document.documentElement.scrollTop;
	var W = document.documentElement.clientWidth;
	var H = document.documentElement.clientHeight;
	return { L:L, T:T, W:W, H:H };
}

function centrar( obj ){
	var pos = getDocCoords();
	if( typeof( obj ) == "string" )
		obj = $(obj);
	var x = pos.L + parseInt((pos.W - obj.offsetWidth)/2);
	var y = pos.T + parseInt((pos.H - obj.offsetHeight)/2);
	obj.style.left = x + "px";
	obj.style.top = y + "px";
}

function getTargetCoords( obj ){
	var x = obj.offsetLeft;
	var y = obj.offsetTop;
	var xb = 0;
	var yb = 0;
	var t = 1; 
	if( obj.clientTop && (t>0) ){
		yb = yb + obj.clientTop;
		xb = xb + obj.clientLeft;
		t = 2;
	}
	var pai = obj.offsetParent;
	while( pai ){
		if( pai.clientTop && (t>0) ){
			yb = yb + pai.clientTop;
			xb = xb + pai.clientLeft;
		}
		x = x + pai.offsetLeft;
		y = y + pai.offsetTop;
		pai = pai.offsetParent;
	}
	if( t == 2 ){
		xb = xb - 2;
		yb = xb - 2;
	}
	return { left: x + xb, top: y + yb, height: obj.offsetHeight, width: obj.offsetWidth }
}

function ev(e) {
	
	var self = this;
	if( typeof(e) != 'undefined' ) {
		this.e = e;
	} else {
		this.e = window.event;
	}
	if( !this.e.target ) {
		this.e.target = e.srcElement;
	}
	// this.e.target = (e.target)?(e.target):(e.srcElement);
	if( this.e.target.nodeType == 3 ) {
		this.e.target.parentNode;
	}
	
	this.element = this.e.target;
	
	this.getDocumentMouseCoords = function(){
		if( self.e.pageX || self.e.pageY){
			return {x:self.e.pageX, y:self.e.pageY};
		}
		return {
			x:self.e.clientX + document.body.scrollLeft - document.body.clientLeft,
			y:self.e.clientY + document.body.scrollTop  - document.body.clientTop
		};
	}
	
	this.getTargetCoords = function(){
		var left = 0;
		var top  = 0;
		var e = self.e.target;
	
		while (e.offsetParent){
			left += e.offsetLeft;
			top  += e.offsetTop;
			e     = e.offsetParent;
		}
	
		left += e.offsetLeft;
		top  += e.offsetTop;
	
		return {x:left, y:top};
	}
	
	this.getTargetMouseCoords = function(){
		var docPos    = self.getTargetCoords();
		var mousePos  = self.getDocumentMouseCoords();
		return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
	}
	
	this.bloquear = function(){
		if( self.e.preventDefault ) {
			self.e.preventDefault();
		} else {
			self.e.returnValue = false;
		}	
	}
	
	this.keyCode = function() {
		return (self.e.keyCode)?(self.e.keyCode):(self.e.which);
	}
}
/** ============================================================================================
*/
function InverteString( str ) {
	var aux1 = new String( str );
	var aux = aux1.split("");
	var tmp = '';
	for( i=0; i < aux.length; i++ ) {
		tmp = aux[i] + tmp;
	}
	return tmp;
}

// ##### Setar propriedades do objetos do form #################################################
function formPropriedades( form_obj, converter_bool ) {
	form_obj.self = form_obj;
	if( typeof( converter_bool ) == "undefined" ) {
		converter_bool = false;
	}
	form_obj.converter_bool = converter_bool;
	
	for( var i=0; i < form_obj.elements.length; i++ ) {
		form_obj.elements[i].requerido_bool = false;
	}
	// -----------------------------------------------------------------------------------------
	form_obj.verificarRequeridos = function() {
		var ok_bool = true;
		for( var i=0; (i < this.elements.length) && (ok_bool); i++ ) {
			if( (this.elements[i].requerido_bool == true) && (this.elements[i].value == "") ) {
				ok_bool = false;
				alert( "Campo requerido no preenchido" );
				this.elements[i].focus();
			}
			if( typeof( this.elements[i].verificar ) == "function" ) {
				ok_bool = ok_bool && this.elements[i].verificar();
			}
			
		}
		return ok_bool;
	}
	// -----------------------------------------------------------------------------------------
	form_obj.converterTudo = function(e) {
		for( var i=0; i < this.elements.length; i++ ) {
			if( typeof( this.elements[i].converter ) == "function" ) {
				this.elements[i].setAttribute("readonly", "readonly");
				this.elements[i].value = this.elements[i].converter();
			}
		}
	}
	
	// CrossBrowse.addEventLis( form_obj, "submit", form_obj.coverterTudo );
}


// ##### Mascara para formatao de data #####################################################
function mskData( input_obj, preencher_bool ) {
	if( typeof( preencher_bool ) == "undefined" ) {
		preencher_bool = true;
	}
	input_obj.preencher_bool = preencher_bool;
	input_obj.style.textAlign = "right";
	input_obj.setAttribute( "maxlength", 10 );
	input_obj.setAttribute( "size", 10 );
	// ---------------------------------------------------------------------------------------
	input_obj.formatar = function() {
		var e = getEvent( arguments );
		if( e ) {
			var evt = new ev(e);
			Element = evt.e.target;
		} else {
			Element = this;
		}
		var valor_str = new String( Element.value );
		if( (valor_str.length == 0) || (valor_str == "0000-00-00") ) {

			if( Element.preencher_bool ) {
				Element.value = strData();
			} else {
				Element.value = "";
			}
		} else {
			if( valor_str.length == 10 ) {
				if( valor_str.indexOf( "-" ) > -1 ) {
					var data_array = valor_str.split("-");
					if( valor_str.indexOf("-") == 4 ) {
						var dia_str = data_array[2];
						var mes_str = data_array[1];
						var ano_str = data_array[0];
					} else {
						var dia_str = data_array[0];
						var mes_str = data_array[1];
						var ano_str = data_array[2];
					}
					Element.value = dia_str + "/" + mes_str + "/" + ano_str;
				}
			}
		}
	}
	// ---------------------------------------------------------------------------------------
	input_obj.formatar();
	// ---------------------------------------------------------------------------------------
	input_obj.verificar = function() {
		var e = getEvent( arguments );
		if( e ) {
			var evt = new ev(e);
			Element = evt.e.target;
		} else {
			Element = this;
		}
		var valor_str = new String( InsChar( GetNum( Element.value ), '/', 2 ) );
		var erro_int = 0;
		valor_str = valor_str.substring( 0, 10 );
		valor_str = InsChar( valor_str, '/', 5 );
		if( valor_str.length == 10 ) {
			var data_array = valor_str.split("/");
			var dia_str = parseFloat( data_array[0] );
			if( (dia_str > 31) || (dia_str < 1)) {
				erro_int = 1
			} else {
				var mes_str = parseFloat( data_array[1] );
				if( (mes_str>12) || (mes_str<1) ) {
					erro_int = 2;
				} else {
					var ano_str = parseFloat( data_array[2] );
					switch ( mes_str ) {
						case 4:
						case 6:
						case 9:
						case 11:
							if( dia_str > 30 ) {
								erro_int = 3;
							}
						break;
						case 2:
							if( (ano_str % 4) == 0 ) {
								if( dia_str > 29 ) {
									erro_int = 4;
								}
							} else {
								if( dia_str > 28 ) {
									erro_int = 5;
								}
							}
						break;
					} // end switch
				} // end else
			} // end else
		} // end else
		Element.value = valor_str.substring( 0, 10 );
		return erro_int;
	}
	// ---------------------------------------------------------------------------------------
	input_obj.corrigir = function() {
		var e = getEvent( arguments );
		if( e ) {
			var evt = new ev(e);
			Element = evt.e.target;
		} else {
			Element = this;
		}
		var err = Element.verificar();
		if( err > 0 ) {
			alert("Data invalida!");
		}
	}
	// ---------------------------------------------------------------------------------------
	input_obj.voltar = function() {
		var e = getEvent( arguments );
		if( e ) {
			var evt = new ev(e);
			Element = evt.e.target;
		} else {
			Element = this;
		}
		if( Element.verificar() > 0 ) {
			Element.focus();
			return false;
		} else {
			return true;
		}
	}
	// ---------------------------------------------------------------------------------------
	input_obj.converter = function() {
		var valor_str = new String( this.value );
		var dt = valor_str.split("/");
		return ( dt[2] + '-' + dt[1] + '-' + dt[0]);
	}
	// ---------------------------------------------------------------------------------------
	addEventLis( input_obj, "keyup", input_obj.corrigir );
	addEventLis( input_obj, "blur", input_obj.voltar );
}


// ##### Mascara para formatao de nmero ###################################################
function mskNumero( input_obj, cd_int ) {
	// ---------------------------------------------------------------------------------------
	input_obj.casasDecimais = cd_int;
	input_obj.converter_bool = true;
	// input_obj.style.textAlign = 'right';
	// ---------------------------------------------------------------------------------------
	input_obj.converter = function() {
		var convertido_str = "";
		var valor_str = new String( this.value );
		var valor_array = valor_str.split("");
		if( valor_array.length > 0 ) {
			for( i=0; i < valor_array.length; i++ ) {
				if( (!isNaN( valor_array[i] )) || (valor_array[i] == ",")) {
					if( valor_array[i] == "," ) {
						convertido_str = convertido_str + ".";
					} else {
						convertido_str = convertido_str + "" + valor_array[i];
					}
				}
			}
			if( isNegativo( valor_str ) ) {
				convertido_str = "-" + convertido_str;
			}
		} else {
			convertido_str = "0";
		}
		return parseFloat( convertido_str );
	}
	// ---------------------------------------------------------------------------------------
	input_obj.isNumber = function() {
		
	}
	// ---------------------------------------------------------------------------------------
	/**
	 * 
	 */
	input_obj.formatar = function() {
		var e = getEvent( arguments );
		if( e ) {
			var evt = new ev(e);
			Element = evt.e.target;
		} else {
			Element = this;
		}
		var aux_num = new Number();
		
		
		
		
		var valor_str = new String( Element.value );
		if( valor_str == "" ) { valor_str = "0"; } 
		var casas_array = valor_str.split(".");
		var NumeroNovo_str = 0;
		if( this.casasDecimais > 0 ) {
            NumeroNovo_str = NumeroNovo_str + ",";
            for(i=0; i < this.casasDecimais; i++ ) {
                NumeroNovo_str = NumeroNovo_str + "0";
            }
		}
		if( (casas_array.length > 0) && (valor_str != "") ) {
			var inteiro_str = new String( casas_array[0] );
			var inteiro_array = inteiro_str.split("");
			var inteiroNovo_str = "";
			var ponto_int = 0;
			var j = null;
			for( i=inteiro_array.length-1; i >= 0; i-- ) {
				if( (ponto_int == 3) && (inteiro_array[i] != "-") ) {
					inteiroNovo_str = inteiro_array[i] + "." + inteiroNovo_str;
					ponto_int = 0;
				} else {
				    inteiroNovo_str = inteiro_array[i] + inteiroNovo_str;
				}
			    ponto_int++;
			}
			NumeroNovo_str = inteiroNovo_str;
			if( Element.casasDecimais > 0 ) {
                if( casas_array.length > 1 ) {
                    var decimal_str = new String( casas_array[1] );
                } else {
                    var decimal_str = new String( "" );
                }
                for( i=decimal_str.length; i < Element.casasDecimais; i++ ) {
                    decimal_str = decimal_str + "0";
                }
                NumeroNovo_str = NumeroNovo_str + "," + decimal_str;
			}
		}
		Element.value = NumeroNovo_str;
	}
	// -----------------------------------------------------------------------------------------
	input_obj.formatar();
	// -----------------------------------------------------------------------------------------
    input_obj.corrigir = function() {
		var e = getEvent( arguments );
		if( e ) {
			var evt = new ev(e);
			Element = evt.e.target;
		} else {
			Element = this;
		}
		var sinal = "";
        if( isNegativo( Element.value ) ) {
			sinal = "-";
		}
		if( (CrossBrowse.ObjEvento.keyCode == 109) || (CrossBrowse.ObjEvento.keyCode == 189)) {
			sinal = '-';
		}
		if( (CrossBrowse.ObjEvento.keyCode == 107) || (CrossBrowse.ObjEvento.keyCode == 187)) {
			sinal = '';
		}
        var valor_str = new String( GetNum( Element.value ) );
		if( valor_str == "" ) { valor_str = "0"; } 
		var valor_array = valor_str.split("");
		var formatado_str = "";
		if( typeof( Element.casasDecimais ) == "undefined" ) {
			Element.casasDecimais = 0;
		}
		if( valor_array.length != 0 ) {
			var valor_int = parseFloat( valor_str );
			var divisor_int = Math.pow(10,Element.casasDecimais);
			var inteiro_str = new String( Math.floor( valor_int / divisor_int ) );
			var inteiro_array = inteiro_str.split("");
			var ponto_int = 0;
			for( var i=inteiro_array.length-1; i >= 0; i-- ) {
				if( ponto_int == 3 ) {
					formatado_str = inteiro_array[i] + "." + formatado_str;
					ponto_int = 0;
				} else {
				    formatado_str = inteiro_array[i] + formatado_str;
				}
			    ponto_int++;
			}
			if( Element.casasDecimais > 0 ) {
				var decimal_str = "";
				for( i=0; i < Element.casasDecimais; i++ ) {
					j = valor_array.length-i-1;
					var vlr = valor_array[j];
					if (typeof(vlr) == "undefined")
						decimal_str = "0" + decimal_str;
					else
						decimal_str = valor_array[j] + decimal_str;
				}
				formatado_str = formatado_str + "," + decimal_str;
			}
		} else {
			formatado_str = "0";
			if( Element.casasDecimais > 0 ) {
				formatado_str = formatado_str + ",";
				for( i=0; i < Element.casasDecimais; i++ ) {
					formatado_str = formatado_str + "0";
				}
			}
		}		
		Element.value = sinal + formatado_str;
	}
	// -----------------------------------------------------------------------------------------
	input_obj.voltar = function() {
		var e = getEvent( arguments );
		if( e ) {
			var evt = new ev(e);
			Element = evt.e.target;
		} else {
			Element = this;
		}
	   //alert("Voltar: "+Element.casasDecimais);
	}
	// -----------------------------------------------------------------------------------------
	addEventLis( input_obj, "keyup", input_obj.corrigir );
	addEventLis( input_obj, "blur", input_obj.voltar );
}


// ##### Mascara para formatao de E-mail ###################################################
function mskEmail( input_obj ) {
	// -----------------------------------------------------------------------------------------
    input_obj.verificar = function() {
		var e = getEvent( arguments );
		if( e ) {
			var evt = new ev(e);
			Element = evt.e.target;
		} else {
			Element = this;
		}
        var valor_str = new String( Element.value );
        if( valor_str.indexOf("@") > 0 ) {
            var valor_array = valor_str.split("@");
            var user_str = new String( valor_array[0] );
            if( (user_str.length > 0) && (valor_array.length == 2) ) {
                var domain_str = new String( valor_array[1] );
                if( domain_str.length > 2 ) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
	// -----------------------------------------------------------------------------------------
    input_obj.voltar = function() {
		var e = getEvent( arguments );
		if( e ) {
			var evt = new ev(e);
			Element = evt.e.target;
		} else {
			Element = this;
		}
        if( !Element.verificar() ) {
            alert("Email incorreto, favor corrigir");
        }
        return Element.verificar();
    }
	// -----------------------------------------------------------------------------------------
	addEventLis( input_obj, "blur", input_obj.voltar );
}


// ##### Mascara para formatao de telefone ##################################################
function mskTelefone( input_obj ) {
	// -----------------------------------------------------------------------------------------
	
	input_obj.setAttribute( "maxlength", 14 );
	input_obj.setAttribute( "size", 14 );
	input_obj.corrigir = function() {
		var e = getEvent( arguments );
		if( e ) {
			var evt = new ev(e);
			Element = evt.e.target;
		} else {
			Element = this;
		}
		var valor_str = new String( GetNum( Element.value ) );
		var valor_array = valor_str.split("");
		var telefone_str = "";
		for( i=0; i < valor_array.length; i++ ) {
			if( i==0 ) { telefone_str = telefone_str + "(";	}
			if( i==2 ) { telefone_str = telefone_str + ") ";	}
			if( i==6 ) { telefone_str = telefone_str + ".";	}
			telefone_str = telefone_str + valor_array[i];
		}
		Element.value = telefone_str;
	}
	// -----------------------------------------------------------------------------------------
	addEventLis( input_obj, "keyup", input_obj.corrigir );
}

// ##### Mascara para formatao de texto simples ############################################
function mskTexto( input_obj ) {
	// -----------------------------------------------------------------------------------------
	input_obj.maxlength = 255;
	input_obj.verificar = function() {
		var e = getEvent( arguments );
		if( e ) {
			var evt = new ev(e);
			Element = evt.e.target;
		} else {
			Element = this;
		}
		var valor_str = new String( Element.value );
		var valor_array = valor_str.slice("");
		if( valor_array.length > 0 ) {
			var repeticoes_int = 0;
			var ultimoChar_str = null;
			for(i=0; (i < valor_array.length) && (repeticoes_int < 2); i++ ) {
				if( ultimoChar_str != valor_array[i] ) {
					repeticoes_int = 0;
				} else {
					repeticoes_int++;
				}
				ultimoChar_str = valor_array[i];
			}
			return (repeticoes_int < 2);
		} else {
			return !Element.requerido_bool;
		}
	}
	// -----------------------------------------------------------------------------------------
	input_obj.corrigir = function() {		
		var e = getEvent( arguments );
		if( e ) {
			var evt = new ev(e);
			Element = evt.e.target;
		} else {
			Element = this;
		}		
		if (Element.value.length >= Element.maxlength) {
			Element.value = Element.value.substring(0, Element.maxlength);
		}
//		if( (Element.value != "") && ( Element.verificar() )) {
//			alert("Este texto possui mais de 2 caracteres repetidos em sequencia");
//		}
	}
	// -----------------------------------------------------------------------------------------
	input_obj.voltar = function() {
		var e = getEvent( arguments );
		if( e ) {
			var evt = new ev(e);
			Element = evt.e.target;
		} else {
			Element = this;
		}
		if( (Element.value == "") && ( Element.requerido_bool ) && ( Element.verificar() )) {
			alert("Este texto possui mais de 2 caracteres repetidos em sequencia");
		}		
	}
	// -----------------------------------------------------------------------------------------
	addEventLis( input_obj, "keyup", input_obj.corrigir );
	addEventLis( input_obj, "blur", input_obj.voltar );
}
