/**
 * Objecto estatico Delegate
 */
Delegate = {
	version: "1.0"
}
Delegate.create = function(obj, func, args){
	var f = function(){
		var target = arguments.callee.target;
		var func = arguments.callee.func;
		var args = arguments.callee.args;
		return func.apply(target, (args.length <1 ? arguments : args));
	};
	
	f.args = (args != undefined && args.length> 0 ? args : new Array());
	f.target = obj;
	f.func = func;

	return f;
}

/**
 * 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;
	}
	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';
}

/**
 * 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(v) {
	if(isNaN(v)) {
		return v;
	}
	var inteiro=v.split('.').shift();
	var cents=v.split('.').pop();
	if(cents == inteiro) {
		cents = '0';
	}
	if(cents.length > 2) {
		cents.substr(0, 2);
	}
	if(cents.length < 2) {
		cents += '0';
	}
	var f='';
	for(var i=inteiro.length-1, c=0; i>=0; i--) {
		f = inteiro.substr(i, 1).toString() + f;
		if(++c == 3 && i > 0) {
			f = '.' + f;
			c=0;
		}
	}
	return (f +',' +cents);
}

function doAc(action, frm)
{
	frm = frm || 'form1';
	
	if( typeof frm == 'string' )
	{
		frm = $(frm);
		if( frm == null )
		{
			alert('Este formulário não existe: '+frm);
			return;
		}
	}
	var acao = $('acao');
	
	if( acao == null )
	{
		acao = document.createElement('INPUT');
		acao.type = 'hidden';
		acao.name = 'acao';
	}
	
	acao.value = action;
	frm.appendChild( acao );
	frm.submit();

}


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(__[_].type && /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);
}