var Util = new Class({

    Implements: [Events, Options],
    
	vazio: function() {},

	options: {
		base_url:'',
		site_url:'',
		suffix_url:'',
		controller:'',
		method:'get'
	},
	
	formatMoeda: function (valor, temDecimal) {
	      var centavos = "00";
	      if(valor.indexOf(".") >= 0) {
	            centavos = valor.split(".")[1];
	            valor = Math.floor(valor.split(".")[0]);
	      }
	      if(valor.indexOf(",") >= 0) {
	            centavos = valor.split(",")[1];
	            valor = Math.floor(valor.split(",")[0]);
	      }
	      
	      var result = "";
	      var tamanho = valor.length;
	      var pontos = Math.floor(tamanho / 3);
	      for(var i = 0; i <= pontos; i++) {
	            if(tamanho - (i * 3) > 3)
	                  result = "." + valor.substr(tamanho - ((i + 1) * 3), 3) + "" + result;
	            else
	                  result = valor.substr(0, tamanho - (i * 3)) + "" + result;
	      }
	      if(temDecimal)
	            return result + "," + centavos;
	      else
	            return result;
	},
	
	
	MascaraMoeda: function(objTextBox, SeparadorMilesimo, SeparadorDecimal, 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) return true;
	   if ((objTextBox.value.length >= objTextBox.maxLength) && (whichCode != 13) && (whichCode != 8)) whichCode = 1;
	   
	   
	   if(whichCode==8)
	   {
	   		
	   		var tamanho = objTextBox.value.length;
	   		
	   		if(tamanho>0)
	   		{
	   			var valor = objTextBox.value;
	   			var size = (valor.length-1);
	   			objTextBox.value = valor.substring(0,size)
	   		}
	   		
	   		objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
	   		
	   		return;
	   }
	   
	    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;
	},
	

	call: function(uri, data, response, method)
	{
		
		var site_url = this.options.site_url;
        data = data!=null ?data :null;
        response = response!=null ?response :new Util().vazio;

        if (site_url.substr(site_url.length-1, 1) != '/' )
            site_url+= '/';
			
        var url = site_url + 'json/' + uri + this.options.suffix_url;
        response = (response!=null) ?response :this.vazio;
        method = (method!=null) ?method :this.options.method;
        
        //alert(data['nome']);
        
        new Request.JSON({
            url: url,
            method: method,
            onComplete: response,
            data: data
        }).send();
    },
    
	callPHP: function(uri, data, response, method)
	{
		
		var site_url = this.options.site_url;
        data = data!=null ?data :null;
        response = response!=null ?response :new Util().vazio;

        if (site_url.substr(site_url.length-1, 1) != '/' )
            site_url+= '/';
			
        var url = site_url +  uri + this.options.suffix_url;
        response = (response!=null) ?response :this.vazio;
        method = (method!=null) ?method :this.options.method;
        
        //alert(data['nome']);
        
        new Request.JSON({
            url: url,
            method: method,
            onComplete: response,
            data: data
        }).send();
    },
    
    callHTML: function(uri, response, method)
	{
		method = method!=null ?method :'get';
		response = response!=null ?response :function(content){return;};
		var url = uri;

        new Request({
			url: url,
			method: method,
			onComplete: response
		}).send();

        
	},
	
	jumpField: function (fields) {
		 if (fields.value.length == fields.maxLength) {
		  for (var i = 0; i < fields.form.length; i++) {
		   if (fields.form[i] == fields && fields.form[(i + 1)] && fields.form[(i + 1)].type != "hidden") {
		    fields.form[(i + 1)].focus();
		    break;
		   }
		  }
		 }
	},
	
	addContent: function(controller,elemento,indice)
	{
		var count = parseInt($('counter').innerHTML)+1;
		util.callPHP(controller,{'elemento':elemento,'indice':indice,'total':count},util.mountContent);
	},
	
    mountContent: function(response)
    {
    	new Element('div',{'html':response.html}).inject($(response.elemento));
    	
    	new RecalcHeight ($(response.elemento).getParent('div.conteudo'));
    	
    	var total = parseInt($('counter').innerHTML);
    	$('counter').innerHTML = total+1; 
    	  
    	
    },
    /**
     * Funcao criada para a funcionalidade adicionar pecas dentro de subareas
     * O cliente pediu para nao deixar apagar caso exista precos para esta peca
     */
    elimineLineWithCheck: function(id,identifier)
    {
    	if(identifier!=0)
    	{
            new Request({
    			url: site_url + "/formato/verificaExclusao/"+identifier,
    			method: 'get',
    			onComplete: 
    				function(resText)
	        		{	    			
		    			var result = JSON.decode( resText.replace( /\[\&([^\&]+[^\]]*)\&\]/gi, '<$1>' ) );
		    			
		    			/**
		    			 * Tem precos???
		    			 * alert(result.status);
		    			 */
		    			if(result.status==true)
		    			{
		    				alert("Esta peça já foi precificada. Remova os preços antes de exclui-lá.");
		    			}else{
		    				/**
		    				 * Pode eliminar a linha
		    				 */
		    				util.elimineLine(id);
		    				
		    			}	
		    		} 
    		}).send();
    		
    	}else{
    		/**
    		 * Removendo a linha
    		 */
    		util.elimineLine(id);
    	}	
    },	
    
    elimineLine: function(id)
    {
    	var total = parseInt($('counter').innerHTML);
    	
    	if(total>0)
    	{
    		$('counter').innerHTML = total-1;	
    	}    	 

    	var elementoConteudo = $(id).getParent('div.conteudo'); 
    	
    	$(id).destroy();
    	new RecalcHeight (elementoConteudo);
    },

	addContentperfil: function(controller,elemento,indice)
	{
		var count = parseInt($('counter_perfil').innerHTML)+1;
		
		util.callPHP(controller,{'elemento':elemento,'indice':indice,'total':count},util.mountContentPerfil);
	},
	
    mountContentPerfil: function(response)
    {
    	new Element('div',{'html':response.html}).inject($(response.elemento));
    	
    	new RecalcHeight ($(response.elemento).getParent('div.conteudo'));
    	
    	var total = parseInt($('counter_perfil').innerHTML);
    	$('counter_perfil').innerHTML = total+1; 
    		
    },
    
    elimineLinePerfil: function(id)
    {
    	var total = parseInt($('counter_perfil').innerHTML);
    	
    	if(total>0)
    	{
    		$('counter_perfil').innerHTML = total-1;	
    	}    	 

    	var elementoConteudo = $(id).getParent('div.conteudo'); 
    	
    	$(id).destroy();
    	
    	
    	new RecalcHeight (elementoConteudo);
    },
     
    verificaCampo: function(event,campo,npage,destino)
    {
    	if ((window.event ? event.keyCode : event.which) == 13) 
    	{
    		if(campo.value>=1&&campo.value<=npage)
    		{
				window.location=destino;    			
    		}
    	}else{
    		return util.soNums(event);
    	}
    },
    
	pegaTexto: function(e)
	{
		var inputFile;
		text = $("uploadSwf").get('value');
		var inputText;
		inputText = $('inputSwf').set('value', text);
			
		if(text.indexOf(".swf")==-1) {
			alert("Por favor, insira um arquivo com formato swf");
			inputText = $('inputSwf').set('value', '');	
		}
	},
	 
    formatCurrency: function(o, n, dig, dec)
    {

		o.c = !isNaN(n) ? Math.abs(n) : 2;
		o.dec = typeof dec != "string" ? "," : dec, o.dig = typeof dig != "string" ? "." : dig;
		new Util().addEvent(o, "keypress", function(e){
			if(e.key > 47 && e.key < 58){
				var o, s, l = (s = ((o = this).value.replace(/^0+/g, "") + String.fromCharCode(e.key)).replace(/\D/g, "")).length, n;
				if(o.maxLength + 1 && l >= o.maxLength) return false;
				l <= (n = o.c) && (s = new Array(n - l + 2).join("0") + s);
				for(var i = (l = (s = s.split("")).length) - n; (i -= 3) > 0; s[i - 1] += o.dig);
				n && n < l && (s[l - ++n] += o.dec);
				o.value = s.join("");
			}
			e.key > 30 && e.preventDefault();
		});
    },

     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;
	        }
    },
    
	formatarmoeda: function(num){

		var erro = 0;
		valor = !isNaN(num) ? Math.abs(num) : erro++;

		if(num<=0)
		{
			erro++;
		}

		stringnum = num.toString();

		size = stringnum.length;
		if(size<=2)
		{
			return stringnum;
		}else{
			digito = stringnum.substr(size-2,size);
			resto = stringnum.substr(0,size-2);

			for (var i = 0; i < Math.floor((resto.length-(1+i))/3); i++)
			{
				resto = resto.substring(0,resto.length-(4*i+3))+"."+resto.substring(resto.length-(4*i+3));
			}
			total = resto+","+digito;

		}

		if(erro>0)
		{
			return "falso";
		}else{
			return total;
		}
    },
    
    soLetras: function(e)
    {
        if (document.all){var evt=event.keyCode;} // caso seja IE
        else{var evt = e.charCode;}    // do contrrio deve ser Mozilla
        var valid_chars = 'qwertyuiopasdfghjklçzxcvbnmQWERTYUIOPASDFGHJKLÇZXCVBNMáéíóúÁÉÍÓÚãõÃÕâêÂÊÜü ';    // criando a lista de teclas permitidas
        var chr= String.fromCharCode(evt);    // pegando a tecla digitada
        if (valid_chars.indexOf(chr)>-1 ){return true;}    // se a tecla estiver na lista de permisso permite-a
        // para permitir teclas como <BACKSPACE> adicionamos uma permisso para
        // cdigos de tecla menores que 09 por exemplo (geralmente uso menores que 20)
        if (valid_chars.indexOf(chr)>-1 || evt < 9){return true;}    // se a tecla estiver na lista de permisso permite-a
        return false;    // do contrario nega
    },
    
	soNums: function(e)
    {
        if (document.all){var evt=event.keyCode;} // caso seja IE
        else{var evt = e.charCode;}    // do contrrio deve ser Mozilla
        var valid_chars = '0123456789,';    // criando a lista de teclas permitidas
        var chr= String.fromCharCode(evt);    // pegando a tecla digitada
        if (valid_chars.indexOf(chr)>-1 ){return true;}    // se a tecla estiver na lista de permisso permite-a
        // para permitir teclas como <BACKSPACE> adicionamos uma permisso para
        // cdigos de tecla menores que 09 por exemplo (geralmente uso menores que 20)
        if (valid_chars.indexOf(chr)>-1 || evt < 9){return true;}    // se a tecla estiver na lista de permisso permite-a
        return false;    // do contrario nega
    },
    
    confirmRedirect: function(msg,destino)
    {
		if(confirm(msg))
		{
			var url = util.options.site_url+"/"+destino;			
			window.location=url;
		}    	
    },
    
    validaFormm: function(e)
    {
    	if($("uploadGif").get('value')== "" && $("uploadSwf").get('value') == "")
    	{
    		alert("Preencha pelo menos um campo");
    		return false;
    	}
    	else
    	{
    		//document.forms[0].submit();
    		$(e).submit();
    	}
    	
    	return true;
    },
    
    pegaTexto2: function(e)
	{
		var inputFile;
		var extensao = new Array();
		text = $("uploadGif").get('value');
		var inputText;
		inputText = $('inputGif').set('value', text);	
		if(text.indexOf(".gif")==-1 && text.indexOf(".jpg") ==-1) {
			alert("Por favor, insira um arquivo com formato gif/jpg");
			inputText = $('inputGif').set('value', '');	
		}
	},
    
    criaLinha: function(dados,entidade)
    {    	
    	eval('new '+entidade+'().criaLinha(dados);');    	
    },

	limitChars: function( textobj, limit, infoobj )
    {		
		if( !textobj || !infoobj)
            return;

        function checkIt( textobj, limit, infoobj)
        {
            var text = textobj.value;

            if( text.length > limit )
            {
                infoobj.set( 'html', '0' );
                textobj.value = text.substr( 0, limit );
                return false;
            }
            else
            {
                infoobj.set( 'html', (limit - text.length) );
                return true;
            }
        }

       	checkIt( textobj, limit, infoobj);

		textobj.onkeyup = function( )
        {
            checkIt( textobj, limit, infoobj);
        }

    },
    
    addAtributosGrafico: function( limite, id )
    {
		if (!limite)
			limite = 15;
			
        var quantidade = $$('#divAudiencias_' + id + ' div.audiencias').length;
        
        if ( limite == quantidade )
			return;
        else{
            var textAudiencia = '<div>' +
                '<div class="linhaDivisoriaFullMargens"></div>' +
                '<table summary="">' +
                    '<tr>' +
                        '<td>Valor:</td>' +
                        '<td>Descrição:</td>' +
                    '</tr>' +
                    '<tr>' +
                        '<td valign="top"><input value="" type="text" style="width: 240px;" class="txt_input" id="GraficoAtributos.' + quantidade + '.valor' + id + '"  onkeypress="return util.soNums(event);" name="GraficoAtributos['+quantidade+'][valor]"/></td>'+
                        '<td><textarea name="GraficoAtributos['+quantidade+'][titulo]" id="GraficoAtributos.' + quantidade + '.titulo' + id + '" class="textAreaMenor" style="width:330px;"></textarea></td>'+
                        '<td valign="top">' +
                            '<input type="button" class="bts" value="Deletar" onclick="util.deleteAudienciaValor( $(this), \'' + id + '\')" />' +
                        '</td>' +
                    '</tr>' +
                '</table>' +
            '</div>' +
            '<div class="audienciaLinha"></div>';

            var Audiencia = new Element( 'div', {'class': 'audiencias', 'html': textAudiencia } );
            Audiencia.inject( $('divAudiencias_' + id ) );
            new RecalcHeight().init( $('divAudiencias_' + id) );
			
        }
    },
    
    addDados: function( tipo, limite, id )
    {       
		if (!limite)
			limite = 4;
			
        var quantidade = $$('#divAudiencias_' + id + ' div.audiencias').length;
        
        if ( limite == quantidade )
			return;
        else{
            new Util().callHTML(
                site_url + '/admin/' + controller + '/addDados/' + tipo + '/' + id + '/' + quantidade + '/', function( response ){
                var newAudiencia = new Element('div', { 'class': 'audiencias', 'html': response });
                newAudiencia.inject( $('divAudiencias_' + id ) );
                new RecalcHeight( $('elementoConteudo_' + id) );
                new Util().LimitChars();
            });
        }
    },

    deleteDados: function ( tipo, elemento, id )
    {
        var quantidade = $$('#divAudiencias_' + id + ' div.audiencias').length;
        if ( quantidade > 1 )
        {
            elemento.getParent('div.audiencias').destroy();
            new RecalcHeight( $('elementoConteudo_' + id) );
        }
    },

    applyToolTip: function (  ){
        $$('a.previews').each(function(el){
            util.previewToolTip(el);
        });
    },

    previewToolTip: function ( elemento )
    {
        var src = elemento.href;
        
        elemento.addEvent( "mouseover", function(event)
        {
            elemento.href = '#';
            
            var pos = elemento.getPosition();
            var preview = new Element('div', {
                                                'id': 'preview',
                                                'class': 'myClass',
                                                'html': '<img src=\'' + src + '\' height="250"/>',
                                                'styles': {
                                                    'position': 'absolute',
                                                    'visibility': 'visible',
                                                    'left': (pos.x + 10) + 'px',
                                                    'top': (pos.y - 255 ) + 'px'
                                                }
                                            });
            preview.inject(document.body);
        });

        elemento.addEvent( 'mouseleave', function(event)
        {
            elemento.href = src;
            if ($('preview'))
                $('preview').destroy();
        });
    },
    
	formatar: function(src, mask) 
	{ 
	  var tipoCampo = ''; 
	  var i = src.value.length; 
	  var saida = mask.substring(0,1); 
	  var texto = mask.substring(i); 
	  if(i-1 < 0) 
	      i = 0; 
	  var cAtual = mask.substring(i, i+1); 
	  var cNext = mask.substring(i+1, i+2); 
	
	  if(i==1 && saida != "#") 
	      src.value = saida+src.value; 
	  else if(cAtual != "#") { 
	       src.value+= cAtual; 
	  } 
	  if(cNext == " ") { 
	      src.value += " "; 
	  } 
	}, 

    applyMouseDataGrid: function (){
        if ( $('conteudoLista') )
            $('conteudoLista').getElements("*[class*=listaElemento]").each(function(div){
                util.mouseDataGrid( $(div).getChildren('div.resumoElemento') );
            });
    },
    
    mouseDataGrid: function (el)
    {
    	el.addEvent( "mouseover", function(event)
        { el.setStyle('background-color','#FFFFFF'); });
        
    	el.addEvent( 'mouseleave', function(event)
        { el.setStyle('background-color','#F7F6F1'); });
    },
    
    filterPrecoBySubArea: function(oportunidade, subarea){
        var f = new Fx.Slide($$('.slide-'+oportunidade)[0]);
        if(subarea == ''){
            f.slideOut();
        }else{
            if(subarea == 0){
                $$(".oportunidade-"+oportunidade).setStyle('display', 'table-row');
            }else{
                $$(".oportunidade-"+oportunidade).setStyle('display', 'none');
                $$(".linha-"+oportunidade+'-'+subarea).setStyle('display', '');                
            }
            f.slideIn();
        }
    },
    
    filterBySubArea: function(oportunidade, subarea){
        // Esconde a tabela antes de filtrar
        var slide = new Fx.Slide($$('.slide-'+oportunidade)[0]);
        // slide.hide();
        if(subarea == '') {
        	slide.slideOut();
        }

        if(subarea == 0){
            $$(".oportunidade_"+oportunidade).setStyle('display', 'table-row');
        }else{
            $$(".oportunidade_"+oportunidade).setStyle('display', 'none');
            $$(".linha_"+oportunidade+'_'+subarea).setStyle('display', '');
        }
        // slide.show();
        slide.slideIn();
    },
    
    
    hiddenPecas: function(opcao,id)
    {
    	if(opcao==0||opcao=="")
    	{
    		$("hiddenElement"+id).setStyle('display','block');
    	}else{
    		if(opcao==1)
    		{
    			$("hiddenElement"+id).setStyle('display','none');
    		}	
    	}
    	new RecalcHeight( $("hiddenElement"+id) );
    },	
    
    getContentByOportunity: function(oportunidade, subarea)
    {
        // Esconde a tabela antes de filtrar
        var slide = new Fx.Slide($$('.slide-'+oportunidade)[0]);
        
        var imagem = "<img src='http://localhost/DM9_Terra_Media-kit/img/loading.gif' />";
        
        // slide.hide();
        if(subarea == '') {
        	
        	slide.slideOut();
        	$('tabela_'+oportunidade).set('html','');
        }else{
        	
            new Request({
    			url: site_url + "/formato/getItemOportunidade/"+oportunidade+"/"+subarea,
    			method: 'get',
    			onRequest: function()
    			{
	            	$('tabela_'+oportunidade).set('html',imagem);
	            	
	    	        if(subarea == 0){
	    	            $$(".oportunidade_"+oportunidade).setStyle('display', 'table-row');
	    	        }else{
	    	            $$(".oportunidade_"+oportunidade).setStyle('display', 'none');
	    	            $$(".linha_"+oportunidade+'_'+subarea).setStyle('display', 'table-row');
	    	        }
	    	        
            	
    			},
    			onComplete: 
    				function(resText)
	        		{	    			
		    			var result = JSON.decode( resText.replace( /\[\&([^\&]+[^\]]*)\&\]/gi, '<$1>' ) );
		    			$('tabela_'+oportunidade).set('html',result.html);
		    			
		    			slide.slideIn();
		    		} 
    		}).send();
        	
        	
        }	
    	
        
    },
    
    loadFormatos: function(subarea)
    {
        new Request({
			url: site_url + "/oportunidades/getFormatosBySubArea/"+subarea,
			method: 'get',
			onRequest: function()
			{
        		$("loadingimage").setStyle("visibility","visible");
        		$("filter_formato").empty();
			},
			onComplete: 
				function(resText)
        		{	    			
	    			/*var result = JSON.decode( resText.replace( /\[\&([^\&]+[^\]]*)\&\]/gi, '<$1>' ) );
	    			$('tabela_'+oportunidade).set('html',result.html);
	    			
	    			slide.slideIn();*/
					var result = JSON.decode( resText.replace( /\[\&([^\&]+[^\]]*)\&\]/gi, '<$1>' ) );
					
					$("filtro_formato").set('html',result);
					$("loadingimage").setStyle("visibility","hidden");
	    		} 
		}).send();

    },	
    
    mountTeste: function(response)
    {
    	alert(response['html']);
    	/*new Element('div',{'html':response.html}).inject($(response.elemento));
    	
    	new RecalcHeight ($(response.elemento).getParent('div.conteudo'));
    	
    	var total = parseInt($('counter').innerHTML);
    	$('counter').innerHTML = total+1; */
    },
    LimitChars: function(){
        
        $$('FORM').each(function(form){
           var elementos = form.getElements("*[class*=LimitChars]").each( function(el) {
                el.getProperty("class").split(' ').each( function(classe){
                    if(classe.match(/^LimitChars(\[.+\])$/)) {
                        var argumentos = eval(classe.match(/^LimitChars(\[.+\])$/)[1]);
                        util.limitChars( $( argumentos[1] ), argumentos[0], el );
                    }
                });
           });
        });
    }
    
});
 

