/**************************************************************************
função para fazer bind (manter o escopo de variaveis)
**************************************************************************/
Function.prototype.bind = function (obj) {
	var fn = this;
	return function () {
		var args = [this];
		for (var i = 0, ix = arguments.length; i < ix; i++) {
			args.push(arguments[i]);
		}
		return fn.apply(obj, args);
	};
};

function delegate( that, thatMethod ) {
	if(arguments.length > 2) {
		var _params = [];
		for(var n = 2; n < arguments.length; ++n) {
			_params.push(arguments[n]);
		}
		return function(e) {
			if(window.event)
			{
				e = window.event;
			}
			_params.push(e);
			return thatMethod.apply(that,_params);
		}
	} else {
		return function(e) {
			if(window.event)
			{
				e = window.event;
			}
			return thatMethod.apply(that,[e]);
		}
	}
}

/**************************************************************************/

/**
 * pega a posição do objeto
 */
var getPosition = function (o) {
	var x=0, y=0;
	while(o != null) {
		x += parseFloat(o.offsetLeft);
		y += parseFloat(o.offsetTop);
		o = o.offsetParent;
	}
	return {x:x, y:y};
}

/**
 * pega a posição do mouse
 */
var getMousePosition = function (e) {
	var ie = document.all ? true : false;
	var x=0; y=0;
	if(ie) {
		x = event.clientX;
		y = event.clientY;
	} else {
		x = e.clientX;
		y = e.clientY;
	}

	var iebody=(document.compatMode && document.compatMode != 'BackCompat') ? document.documentElement : document.body;

	var ie5 = (document.getElementById && document.all); 
	var ns6 = (document.getElementById && !document.all); 
	var ua = navigator.userAgent.toLowerCase();
	var isapple = (ua.indexOf('applewebkit') != -1 ? 1 : 0);

	pagex = (isapple == 1 ? 0:(ie5)?iebody.scrollLeft:window.pageXOffset);
	pagey = (isapple == 1 ? 0:(ie5)?iebody.scrollTop:window.pageYOffset);

	x += pagex;
	y += pagey;
	return {x:x, y:y};
}

/**
 * altera a posição do objeto
 */
var setPosition = function (o, x, y) {
	o.style.left = x +'px';
	o.style.top = y + 'px';
}

/**
 * pega o tamanho do objeto
 */
var getSize = function(o) {
	return {width:o.offsetWidth, height:o.offsetHeight};
}

/**
 * testa se um objeto colidiu com o outro
 */
var hitTest = function (o1, o2) {
	var d1 = getSize(o1);
	var d2 = getSize(o2);
	var p1 = getPosition(o1);
	var p2 = getPosition(o2);
	if(p1.x + d1.width >= p2.x && p1.x <= p2.x + d2.width) {
		if(p1.y + d1.height >= p2.y && p1.y <= p2.y + d2.height) {
			return true;
		}
	}
	return false;
}

var setSize = function(o, x, y) {
	o.style.width=x+'px';
	o.style.height=y+'px';
}

var getWindowSize = function()
{
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
	
	return {
		width: myWidth,
		height: myHeight
	};
}

/**
 * pega o valor de um atributo pelo nome
 */
function getAttributeValue(node, id) {
	for(var i=0; i<node.attributes.length; i++) {
		if(node.attributes.item(i).nodeName == id) {
			return node.attributes.item(i).nodeValue;
		}
	}
	return null;
}

function setVisible(o, v) {
	o.style.visibility = v ? 'visible':'hidden';
	o.style.display = v ? '' : 'none';
}

function $(id) {
	return document.getElementById(id);
}

function writeFlash(id,file,w,h, ret) {
	var str = '<object id="'+id+'-object" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="'+w+'" height="'+h+'">'+
		'<param name="movie" value="'+file+'" />'+
		'<param name="quality" value="high" />'+
		'<param name="wmode" value="opaque" />'+
		'<param name="menu" value="false" />'+
		'<embed wmode="opaque" id="'+id+'-embed" src="'+file+'" width="'+w+'" height="'+h+'" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" menu="false"></embed>'+
	'</object>';
	
	if(ret) {
		return str;
	}
	document.write( str );
}

function getElementsByClassName(oElm, strTagName, oClassNames){
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	var arrRegExpClassNames = new Array();
	if(typeof oClassNames == "object"){
		for(var i=0; i<oClassNames.length; i++){
			arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames[i].replace(/\-/g, "\\-") + "(\\s|$)"));
		}
	}
	else{
		arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames.replace(/\-/g, "\\-") + "(\\s|$)"));
	}
	var oElement;
	var bMatchesAll;
	for(var j=0; j<arrElements.length; j++){
		oElement = arrElements[j];
		bMatchesAll = true;
		for(var k=0; k<arrRegExpClassNames.length; k++){
			if(!arrRegExpClassNames[k].test(oElement.className)){
				bMatchesAll = false;
				break;                      
			}
		}
		if(bMatchesAll){
			arrReturnElements.push(oElement);
		}
	}
	return (arrReturnElements)
}

function toMoney(num) {
	num = num.toString().replace(/(\$|\,)/g,'');
	if(isNaN(num))
	{
		num = "0";
	}
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	{
		cents = "0" + cents;
	}
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	{
		num = num.substring(0,num.length-(4*i+3))+'.'+
		num.substring(num.length-(4*i+3));
	}
	return (((sign)?'':'-') + num + ',' + cents);
}

function number_format(a, b, c, d) {
 a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
 e = a + '';
 f = e.split('.');
 if (!f[0]) {
  f[0] = '0';
 }
 if (!f[1]) {
  f[1] = '';
 }
 if (f[1].length < b) {
  g = f[1];
  for (i=f[1].length + 1; i <= b; i++) {
   g += '0';
  }
  f[1] = g;
 }
 if(d != '' && f[0].length > 3) {
  h = f[0];
  f[0] = '';
  for(j = 3; j < h.length; j+=3) {
   i = h.slice(h.length - j, h.length - j + 3);
   f[0] = d + i +  f[0] + '';
  }
  j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
  f[0] = j + f[0];
 }
 c = (b <= 0) ? '' : c;
 return f[0] + c + f[1];
}

function toFloat( v )
{
	var f = parseFloat( v.replace('.', '').replace(',','.') );
	return isNaN(f) ? 0 : f;
}

function doAc(ac, f) {
	if(f == undefined) {
		f=document.form1;
	}
	if(typeof(f) == 'string') {
		var s=f;
		f=$(f);
		if(f==null) {
			alert('Nenhum formulário encontrado com o nome "'+s+'"');
			return;
		}
	}
	var a=f.acao;
	if(a==null || a==undefined) {
		a = document.createElement('INPUT');
		a.type='hidden';
		a.name='acao';
		a.id = 'acao';
		f.appendChild(a);
	}
	a.value=ac;
	f.submit();
}

function acaoCritica( ac, f ) {
	if(confirm('Atenção:\n\nEsta ação não poderá ser desfeita.\n\nDeseja continuar?')) {
		doAc(ac, f);
	}
}

/**
 * Altera o formatdo de uma string para servir de permalink (URL amigável)
 * @param string $str Texto a ser alterado
 * @param boolean $lower Converter tudo para lower-case
 * @return string Texto corrigido
 * @author Hugo Ferreira da Silva
 */
function doPermalink(str, lower) {
	if(lower == undefined) {
		lower = true;
	}
	var chars = 'áàãâäÁÀÂÃÄéèêëÉÈÊËíìîïÍÌÎÏóòõöôÓÒÕÔÖúùûüÚÙÜÛñÑçÇ |-/\\][{}+=)(*%$#@!&"\'ºª.;<>,?^~´`:“”';
	var reps =  'aaaaaAAAAAeeeeEEEEiiiiIIIIoooooOOOOOuuuuUUUUnNcc______________________________________';
	var nova = '';
	
	for(var i=0; i<str.length; i++) {
		var c = str.substr(i, 1);
		var idx = chars.indexOf(c);
		if(idx > -1) {
			var rep = reps.substr(idx, 1);
			c = rep;
		}
		
		nova += c;
	}
	
	if(lower == true) {
		nova = nova.toLowerCase();
	}
	
	return nova;
}

var WindowManager = function() {
	this.vars=[];
	this.width = 100;
	this.height = 100;
	this.left = 0;
	this.top = 0;
	this.options = '';
	this.name = '_janela';
	this.auto_focus = true;
	this.auto_center = true;
}
WindowManager.prototype = {
	open:function( url ) {
		if(this.auto_center == true) {
			this.left = screen.availWidth/2 - this.width/2;
			this.top = screen.availHeight/2 - this.height/2;
		}
		
		var vars = this._buildQueryString();
		if(url.indexOf('?') == -1) {
			url += '?';
		}
		url += '&' + vars;
		
		var opts = 'width='+this.width+', height='+this.height+',left='+this.left+',top='+this.top;
		if(this.options != '') {
			opts += ','+this.options;
		}
		
		var w = window.open(url, this.name, opts);
		if(this.auto_focus == true) {
			w.focus();
		}
	},
	
	_buildQueryString:function() {
		var str = '';
		for(var i=0; i<this.vars.length; i++) {
			str += this.vars[i].key +'=' +this.vars[i].value + '&';
		}
		
		return str;
	},
	
	addVar:function(k, v) {
		this.vars.push({key:k, value:v});
	}
}

function ShowAccessKeys() {
	var list = document.getElementsByTagName('label');
	
	if(list.length > 0) {
		for(var i=0; i<list.length; i++) {
			var el=list[i];
			if(el.accessKey != '') {
				var t = el.innerHTML.toLowerCase();
				var n = '';
				
				var p =t.indexOf(el.accessKey);
				if(p > -1) {
					var l = el.innerHTML.substr(p, 1);
					n = el.innerHTML.substr(0, p) + '<u>' + l + '</' + 'u>' + el.innerHTML.substr(p + 1);
					el.innerHTML = n;
				}
			}
		}
	}
}

String.prototype.trim = function() {
	var n=this;
	
	do {
		var c=n.substr(0,1);
		if(c==' ' || c=='\n' || c=='\r') {
			n=n.substr(1);
		} else {
			break;
		}
	} while(true);
	
	do {
		var c=n.substr(-1);
		if(c==' ' || c=='\n' || c=='\r') {
			n=n.substr(0, n.length-1);
		} else {
			break;
		}
	} while(true);
	
	return n;
}

String.prototype.check_email = function() {
	return this.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1;
}

String.prototype.isCPF = function()
{
	var numcpf = this;
	var x = 0;
	var soma = 0;
	var dig1 = 0;
	var dig2 = 0;
	var texto = "";
	var numcpf1="";
	var 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;
	}
	return false;
}

String.prototype.isHora = function() 
{
	var m = this.match(/^(\d{2}):(\d{2})$/);
	if( m == null )
	{
		return false;
	}
	
	if( m[1] > 24 || m[1] < 0 )
	{
		return false;
	}
	
	if( m[2] > 59 || m[2] < 0 )
	{
		return false;
	}
	return true;
}

String.prototype.isDate = function()
{
	var m = this.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
	if( m == null )
	{
		return false;
	}
	
	var dias = [31,28,31,30,31,30,31,31,30,31,30,31];
	
	var dia  = parseFloat( m[1] );
	var mes  = parseFloat( m[2] ) - 1;
	var ano  = parseFloat( m[3] );

	if( mes < 0 || mes > 11 ) return false;
	if( dias < 1 || dias > 31) return false;
	if( ano < 1900) return false;
	if( ano % 4 == 0 ) dias[1] = 29;
	
	if( dia > dias[mes] ) return false;
	
	return true;
}



/*********************************************************
Função para montar uma máscara em um input
@author Banco do Brasil :-)
*********************************************************/
enterAsTab = function(f, a){
    addEvent(f, "keypress", function(e){
        var l, i, f, j, o = e.target;
        if(e.key == 13 && (a || !/textarea|select/i.test(o.type))){
            for(i = l = (f = o.form.elements).length; f[--i] != o;);
            for(j = i; (j = (j + 1) % l) != i && (!f[j].type || f[j].disabled || f[j].readOnly || f[j].type.toLowerCase() == "hidden"););
            e.preventDefault(), j != i && f[j].focus();
        }
    });
};

addEvent = function(o, e, f, s){
    var r = o[r = "_" + (e = "on" + e)] = o[r] || (o[e] ? [[o[e], o]] : []), a, c, d;
    r[r.length] = [f, s || o], o[e] = function(e){
        try{
            (e = e || event).preventDefault || (e.preventDefault = function(){e.returnValue = false;});
            e.stopPropagation || (e.stopPropagation = function(){e.cancelBubble = true;});
            e.target || (e.target = e.srcElement || null);
            e.key = (e.which + 1 || e.keyCode + 1) - 1 || 0;
        }catch(f){}
        for(d = 1, f = r.length; f; r[--f] && (a = r[f][0], o = r[f][1], a.call ? c = a.call(o, e) : (o._ = a, c = o._(e), o._ = null), d &= c !== false));
        return e = null, !!d;
    }
};

removeEvent = function(o, e, f, s){
    for(var i = (e = o["_on" + e] || []).length; i;)
        if(e[--i] && e[i][0] == f && (s || o) == e[i][1])
            return delete e[i];
    return false;
};

Restrict = function(form){
    this.form = form, this.field = {}, this.mask = {};
}
Restrict.field = Restrict.inst = Restrict.c = null;
Restrict.prototype.start = function(){
    var $, __ = document.forms[this.form], s, x, j, c, sp, o = this, l;
    var p = {".":/./, w:/\w/, W:/\W/, d:/\d/, D:/\D/, s:/\s/, a:/[\xc0-\xff]/, A:/[^\xc0-\xff]/};
    for(var _ in $ = this.field)
		if(_ == 'toJSONString') 
		{
		} else 
		
        if(/text|textarea|password/i.test(__[_].type)){
            x = $[_].split(""), c = j = 0, sp, s = [[],[]];
            for(var i = 0, l = x.length; i < l; i++)
                if(x[i] == "\\" || sp){
                    if(sp = !sp) continue;
                    s[j][c++] = p[x[i]] || x[i];
                }
                else if(x[i] == "^") c = (j = 1) - 1;
                else s[j][c++] = x[i];
            o.mask[__[_].name] && (__[_].maxLength = o.mask[__[_].name].length);
            __[_].pt = s, addEvent(__[_], "keydown", function(e){
                var r = Restrict.field = e.target;
                if(!o.mask[r.name]) return;
                r.l = r.value.length, Restrict.inst = o; Restrict.c = e.key;
                setTimeout(o.onchanged, r.e = 1);
            });
            addEvent(__[_], "keyup", function(e){
                (Restrict.field = e.target).e = 0;
            });
            addEvent(__[_], "keypress", function(e){
                o.restrict(e) || e.preventDefault();
                var r = Restrict.field = e.target;
                if(!o.mask[r.name]) return;
                if(!r.e){
                    r.l = r.value.length, Restrict.inst = o, Restrict.c = e.key || 0;
                    setTimeout(o.onchanged, 1);
                }
            });
        }
}
Restrict.prototype.restrict = function(e){
    var o, c = e.key, n = (o = e.target).name, r;
    var has = function(c, r){
        for(var i = r.length; i--;)
            if((r[i] instanceof RegExp && r[i].test(c)) || r[i] == c) return true;
        return false;
    }
    var inRange = function(c){
        return has(c, o.pt[0]) && !has(c, o.pt[1]);
    }
    return (c < 30 || inRange(String.fromCharCode(c))) ?
        (this.onKeyAccept && this.onKeyAccept(o, c), !0) :
        (this.onKeyRefuse && this.onKeyRefuse(o, c),  !1);
}
Restrict.prototype.onchanged = function(){
    var ob = Restrict, si, moz = false, o = ob.field, t, lt = (t = o.value).length, m = ob.inst.mask[o.name];
    if(o.l == o.value.length) return;
    if(si = o.selectionStart) moz = true;
    else if(o.createTextRange){
        var obj = document.selection.createRange(), r = o.createTextRange();
        if(!r.setEndPoint) return false;
        r.setEndPoint("EndToStart", obj); si = r.text.length;
    }
    else return false;
    for(var i in m = m.split(""))
        if(m[i] != "#")
            t = t.replace(m[i] == "\\" ? m[++i] : m[i], "");
    var j = 0, h = "", l = m.length, ini = si == 1, t = t.split("");
    for(i = 0; i < l; i++)
        if(m[i] != "#"){
            if(m[i] == "\\" && (h += m[++i])) continue;
            h += m[i], i + 1 == l && (t[j - 1] += h, h = "");
        }
        else{
            if(!t[j] && !(h = "")) break;
            (t[j] = h + t[j++]) && (h = "");
        }
    o.value = o.maxLength > -1 && o.maxLength < (t = t.join("")).length ? t.slice(0, o.maxLength) : t;
    if(ob.c && ob.c != 46 && ob.c != 8){
        if(si != lt){
            while(m[si] != "#" && m[si]) si++;
            ini && m[0] != "#" && si++;
        }
        else si = o.value.length;
    }
    !moz ? (obj.move("character", si), obj.select()) : o.setSelectionRange(si, si);
}
/*********************************************************/

// coloca a primeira letra das palavras em maiusculo
// @author Hugo Ferreira da Silva
function capitalize(obj, tudo)
{
	if(tudo == undefined)
	{
		tudo = false;
	}
	
	var lista         = ['do','da','dos','das','de','e','y','del','I','II','III','IV','V','VI','VII','VIII','IX','X','XI','XII','XIII','XIV','XV','XVI','XVII','XVIII','XIX','XX','XXI','XXII','XXIII','XXIV','XXV','XXVI','XXVII','XXVIII','XXIX','XXX','XXXI','XXXII','XXXIII','XXXIV','XXXV','XXXVI','XXXVII','XXXVIII','XXXIX','XXXX','XXXXI','XXXXII','XXXXIII','XXXXIV','XXXXV','XXXXVI','XXXXVII','XXXXVIII','XXXXIX','L'];
	var tokens        = obj.value.split(' ');
	var novo_valor    = [];
	var passou        = true;
	
	for(var i=0; i<tokens.length; i++){
		if(tudo == true) {
			novo_valor.push( tokens[i].toUpperCase() );
		} else {
			passou = true;
			
			for(var j=0; j<lista.length; j++) {
				if(lista[j].toLowerCase() == tokens[i].trim().toLowerCase()) {
					passou = false;
					break;
				}
			}
			
			if(passou == true && tokens[i].length > 1) {
				var primeira = tokens[i].substr(0, 1).toUpperCase();
				var restante = tokens[i].substr(1).toLowerCase();
			
				novo_valor.push( primeira + restante );
			} else {
				novo_valor.push( tokens[i] );
			}
		}
	}
	
	obj.value = novo_valor.join(' ');
}

/*************************************************************
Temporizador
*************************************************************/

Timer = function(escope, fnc)
{
	this._id     = '__timer' + Math.round(Math.random() * (new Date().getTime()));
	this.escope  = escope;
	this.fnc     = fnc;
	this.args    = [];
	this.timeout = null;
	this.type    = '';
	
	if(arguments.length > 2)
	{
		for(var i=2; i<arguments.length; i++)
		{
			this.args.push( arguments[i] );
		}
	}
	
	window[ this.id ] = this;
}


Timer.prototype = {
	start : function( tempo )
	{
		if(this.type == '')
		{
			this.timeout = setTimeout(this.id + '._executeTimeout()', tempo);
			this.type    = 'timeout';
		}
	},
	
	interval : function( tempo )
	{
		if(this.type == '')
		{
			this.timeout = setInterval(this.id + '._executeInterval()', tempo);
			this.type    = 'interval';
		}
	},
	
	clear : function()
	{
		if(this.type == 'timeout')
		{
			clearTimeout( this.timeout );
		} else {
			clearInterval( this.timeout );
		}
		this.type = '';
	},

	_executeTimeout : function()
	{
		this.fnc.apply(this.escope, this.args);
		this.clear();
	},
	
	_executeInterval : function()
	{
		this.fnc.apply(this.escope, this.args);
	}
}

function intToData(v)
{
	return v.replace(/^(\d{4})(\d{2})(\d{2})$/, '$3/$2/$1');
}