// JavaScript Document
// Felipe Gregorio - fgregorio@gmail.com

var is_ie = navigator.appName.toLowerCase().indexOf('explorer') > - 1;
		
var config = {
	menu_drop_down		: false
	//	popup( './indique-site.php', 400, 330 );
};

function g(obj_id){
	return document.getElementById(obj_id);
}

function indique(){
	frescura('indique',360,160);
}

function envie(){
	frescura('envie',460,160);
}

function duvida(){
	frescura('duvida',460,160);
}

function popup(p_url,p_largura,p_altura,extra){
	x = window.open(p_url,'p' + new Date().getSeconds(),'width='+p_largura+',height='+p_altura + ( extra ? ',' + extra : '' ) + ',resizable=no,scrollbars=1') ;
	try { x.focus() ; }
	catch(e) { 
		alert('por favor, desabilite o bloqueador de pop-ups para visualizar esta janela')  ;
	}
}

function ajax_send_form( obj_form, params ){
	document.getElementById('duvidas-loading').style.display = '' ;
	ajaxObject.open( 'GET', obj_form.action + '?' + get_form_elements_2_url(obj_form) ) ;
	ajaxObject.onreadystatechange = function(){
		if ( ajaxObject.readyState == 4 && ajaxObject.status == 200 ){
			//alert(params.f);
			params.f(ajaxObject.responseText) ;
		}
	}
	ajaxObject.send(null);
}

function ajax_send_url( url, params ){
	ajaxObject.open( 'GET', url ) ;
	ajaxObject.onreadystatechange = function(){
		if ( ajaxObject.readyState == 4 && ajaxObject.status == 200 ){
			//alert(params.f);
			params.f(ajaxObject.responseText) ;
		}
	}
	ajaxObject.send(null);
}

function ajax_get_string(url){
	ajaxObject.open( 'GET', url, false ) ;
	ajaxObject.onreadystatechange = function(){
		if ( ajaxObject.readyState == 4 && ajaxObject.status == 200 ){
			return ajaxObject.responseText ;
		}
	}
	ajaxObject.send(null);
}

function get_form_elements_2_url(obj_form){
	var retorno = [] ;	
	var p = ['input', 'select', 'textarea'] ;
	
	for ( var i = 0; i < p.length ; i ++ ){
		for ( var x = 0,	a = obj_form.getElementsByTagName(p[i]),m = obj_form.getElementsByTagName(p[i]).length ; x < m ; x ++ ){			
			condicao = false 	;
			element  = a[x] 	;
			switch( p[i] ){
				case 'input' :
					condicao = ( element.disabled == false && ! element.readOnly 
												&& ! ( element.getAttribute('type').toLowerCase() == 'button' || element.getAttribute('type').toLowerCase() == 'file' )
												|| ( element.getAttribute('type').toLowerCase() == 'radio' && element.checked )
												|| ( element.getAttribute('type').toLowerCase() == 'checkbox' && element.checked )) ;
				break ;
				case 'select' :
				case 'textarea' :
					condicao = ( element.disabled == false && ! element.readOnly ) ;				
				break ;
			}
			if ( condicao ){
				retorno[retorno.length] = element.getAttribute('name') + '=' + escape(element.value);		
			}
		}
	}
	return retorno.join('&');
}

function next_object(quantos_bytes,obj_atual,obj_next){
	if ( parseInt(obj_atual.value.length) == quantos_bytes ){
		obj_next.focus();		
	}
}

/*
**************************************
* String.isCPF Function v1.0         *
* Autor: Carlos R. L. Rodrigues      *
* BEGIN 							 *
**************************************
*/
String.prototype.isEmail = function(){
	return new RegExp(/[a-z0-9_\-.]{1,}@[a-z0-9_\-.]{1,}/ig).test(this) ;
};
String.prototype.isCPF = function(){
	var c = this;
	if((c = c.replace(/[^\d]/g,"").split("")).length != 11) return false;
	if(new RegExp("^" + c[0] + "{11}$").test(c.join(""))) return false;
	for(var s = 10, n = 0, i = 0; s >= 2; n += c[i++] * s--);
	if(c[9] != (((n %= 11) < 2) ? 0 : 11 - n)) return false;
	for(var s = 11, n = 0, i = 0; s >= 2; n += c[i++] * s--);
	if(c[10] != (((n %= 11) < 2) ? 0 : 11 - n)) return false;
	return true;
};

String.prototype.isCNPJ = function(){
	var b = [6,5,4,3,2,9,8,7,6,5,4,3,2], c = this;
	if((c = c.replace(/[^\d]/g,"").split("")).length != 14) return false;
	for(var i = 0, n = 0; i < 12; n += c[i] * b[++i]);
	if(c[12] != (((n %= 11) < 2) ? 0 : 11 - n)) return false;
	for(var i = 0, n = 0; i <= 12; n += c[i] * b[i++]);
	if(c[13] != (((n %= 11) < 2) ? 0 : 11 - n)) return false;
	return true;
};

function swf(url, width, height, flashvars){
	var retorno = '' ;
	if( url.indexOf('.jpg') > -1 || url.indexOf('.gif') > -1 ){
		retorno = '<img src="'+url+'" width="'+width+'" height="'+height+'"/>' ;
	}
	else{
		retorno += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0" width="'+ width +'" height="'+ height +'">' ;
		retorno += '<param name="movie" value="'+ url +'?m='+ new Date().getTime() +'">' ;
		retorno += '<param name="quality" value="high">' ;
		retorno += '<param name="wmode" value="transparent">' ;
		retorno += '<param name="flashvars" value="'+ flashvars +'">' ;
		retorno += '<embed wmode="opaque" src="'+ url +'?m='+ new Date().getTime() +'" flashvars="'+ flashvars +'" quality="high" pluginspage="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" width="'+ width +'" height="'+ height +'"></embed>' ;
		retorno += '</object>' ;
	}
	//alert(retorno);
	document.write(retorno);
	//return retorno ;
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft ;
		curtop = obj.offsetTop ;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

function event_add(obj, evType, fn){
   if (obj.addEventListener){
       obj.addEventListener(evType, fn, true)
   }    
   if (obj.attachEvent){
       obj.attachEvent("on"+evType, fn)
   }
}

//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.org
//
function getPageScroll(){

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}

//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
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;
}

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/forms/masked-input [v1.0]

MaskInput = function(f, m){
    function mask(e){
        var patterns = {"1": /[A-Z]/i, "2": /[0-9]/, "4": /[\xC0-\xFF]/i, "8": /./ },
            rules = { "a": 3, "A": 7, "9": 2, "C":5, "c": 1, "*": 8};
        function accept(c, rule){
            for(var i = 1, r = rules[rule] || 0; i <= r; i<<=1)
                if(r & i && patterns[i].test(c))
                    break;
                return i <= r || c == rule;
        }
        var k, mC, r, c = String.fromCharCode(k = e.key), l = f.value.length;
        (!k || k == 8 ? 1 : (r = /^(.)\^(.*)$/.exec(m)) && (r[0] = r[2].indexOf(c) + 1) + 1 ?
            r[1] == "O" ? r[0] : r[1] == "E" ? !r[0] : accept(c, r[1]) || r[0]
            : (l = (f.value += m.substr(l, (r = /[A|9|C|\*]/i.exec(m.substr(l))) ?
            r.index : l)).length) < m.length && accept(c, m.charAt(l))) || e.preventDefault();
    }
    for(var i in !/^(.)\^(.*)$/.test(m) && (f.maxLength = m.length), {keypress: 0, keyup: 1}){
	    addEvent(f, i, mask);
	}
};

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;
};


// frescuras
function frescura(div_id,w,h) {	
	// display:none em tudo dentro de capa-img

	var dentro = frescura_dentro(div_id);

	for(var x = 0, o = dentro.childNodes, m = o.length ; x < m ; x ++ )
		if(o[x].tagName)
			o[x].style.display = 'none' ;

	pageSize	= getPageSize();
	pageScroll	= getPageScroll();  

	document.getElementById(div_id).style.height = new String(pageSize[1])+'px' ;
	dentro.style.top  = new String(y=(pageScroll[1]+(pageSize[3]-h-10)/2))+'px' ;
	dentro.style.left = new String(x=(document.body.clientWidth-w)/2)+'px' ;

	document.getElementById(div_id).style.display = '';
	dentro.style.display = '';
	frescura_abre1(div_id,w,h);
}

function frescura_dentro(div_id){
	return document.getElementById(div_id).getElementsByTagName('div')[0];
}

// abre width
function frescura_abre1(div_id,w,h) {
	var dentro = frescura_dentro(div_id);
	_w = int_val(dentro.style.width); 
	//alert(_w);
	if(_w<w) {
		dentro.style.width = new String(_w + 25)+'px' ;
		setTimeout('frescura_abre1(\''+div_id+'\','+w+','+h+');',15);
	}
	else{
		frescura_abre2(div_id,w,h);
	}
}

// abre height
function frescura_abre2(div_id,w,h) {
	var dentro = frescura_dentro(div_id);
	_h = int_val(dentro.style.height); 
	if(_h<h) {
		dentro.style.height = new String(_h + 25)+'px' ;
		setTimeout('frescura_abre2(\''+div_id+'\','+w+','+h+');',15);
	}
	else{
		frescura_abre3(dentro);
	}
}

// acende imagem, legenda e botao de fechar
function frescura_abre3(dentro) {
	for(var x = 0, o = dentro.childNodes, m = o.length ; x < m ; x ++ ){
		if(o[x].tagName)
			o[x].style.display = '' ;
	}
}

function frescura_fim(div_id) {
	document.getElementById(div_id).style.display='none' ;
	var dentro = frescura_dentro(div_id);
	dentro.style.width='20px';
	dentro.style.height='0px';
}

function int_val(x) {
	//alert('de'+x);
	x = new String(x);
	x = x.replace(/[a-z]/ig, '') ;
	x = new Number(x);
	//alert('para'+x);
	return x ;
}

function getParentByTagName(obj, tagName){
	
	var objReturn = obj.parentNode;
	
	while(objReturn.tagName != tagName){
		objReturn = objReturn.parentNode;
	}
	return objReturn;
}

function tab(objLI, tabn){
	var t = [];
	for ( var i = 0, m = document.getElementsByTagName('div'); i < m.length ; i ++ ){
		if(m[i].getAttribute("tab")=="1"){
			t[t.length] = m[i];
		}
	}
	//var objUL = (objLI.parentNode);
//	var objUL = getParentByTagName(objLI, 'UL');

	// tira estilo de selecionado de todos LI's dentro do UL pai
	for( var i=0,  maximo = objLI.parentNode.getElementsByTagName('LI').length; i < maximo ; i ++ ){
		objLI.parentNode.getElementsByTagName('LI')[i].className = 'normal';
	}

	// poe estilo no clicado
	objLI.className = 'selecionado';

	// apaga todos os divs de tab
	for ( var i = 0, m = t.length; i < t.length ; i ++ ){
		t[i].style.display = 'none';
	}

	// acende div do selecionado
	for ( var i = 0, m = t.length; i < t.length ; i ++ ){
		if(i == tabn)
			t[i].style.display = '';
	}
}

function formata(v) {
	var s = new String(v);
	if(s.indexOf('.')==-1) {
		return s+',00';
	}
	else {
		var x = s.split('.');
		if(x[1].length>=2){
			return x[0]+','+x[1].substr(0,2);
		}
		else{
			return x[0]+','+x[1]+'0';
		}
	}
}

function formataMoeda(objTextBox, e){

	var SeparadorMilesimo = '' ;
	var SeparadorDecimal = ',' ;
	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;

	var whichCode = (document.all) ? e.keyCode : e.which ;

	//alert(whichCode);

	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 = objTextBox.value.length;
    for(i = 0; i < len; i++)
        if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;
    aux = '';
    for(; i < len; i++)
        if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) aux += objTextBox.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) objTextBox.value = '';
    if (len == 1) objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;
    if (len == 2) objTextBox.value = '0'+ SeparadorDecimal + aux;
    if (len > 2) {
        aux2 = '';
        for (j = 0, i = len - 3; i >= 0; i--) {
            if (j == 3) {
                aux2 += SeparadorMilesimo;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        objTextBox.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
        objTextBox.value += aux2.charAt(i);
        objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
    }
    return false;
}

/**
essa funcao eh apenas um alias para a maneira de atribuir:
object.onkeypress = formataMoedaEvent
**/

function formataMoedaEvent(e){
	if(document.all){
		e = event;
		objTextBox = event.srcElement;
	}
	else {
		objTextBox = e.target;
	}
	return formataMoeda(objTextBox, e);
}

/**
supondo que esta vindo algo como 10000,67
*/
function toFloat(str){
	str = new String(str);
	str = new Number(str.replace(',','.'));
	return str;
}