Util = {
	somenteNumero: function(e)
	{
	    //var tecla=(window.event)?event.keyCode:e.which;
		this.e = e;
	    var tecla = e.code;
	    
	    if((tecla > 47 && tecla < 58) || (tecla >=96 && tecla <= 105) || tecla == 9) return true;
	    else{
	    	if (tecla != 8) return false;
	    	else return true;
	    }
	},
	
	limitadorTexto: function(element, limit, elementText)
	{
		$(elementText).set('html', element.value.length);
		
		element.addEvents({
			keydown: function(e)
			{
				var e = new Event(e);
			
				if ( e.code != 8 && this.value.length >= limit )
					e.stop();
			},
			
			keyup: function()
			{
				if ( this.value.length >= limit )
					this.value = this.value.substring(0, limit);

				$(elementText).set('html', this.value.length);
			}
		});
	},
	
	addCalendar: function(input){
		/*if ( $$('.btCalendar') && $$('INPUT.txtCalendar') )
		{
			var campos = $$('INPUT.txtCalendar');

			$$('.btCalendar').each(function(bt, i)
			{
				bt.addEvent('click', function(e){
					new Event(e).stop();
					
					var strDate = 'dd/mm/yyyy';
					var hasTime = false;
					
					if ( campos[i].hasClass('calendarWithTime') )
					{
						strDate+= ' hh:ii';
						hasTime = true;
					}
						
					displayCalendar(campos[i], strDate, this, hasTime);
				});
				
				campos[i].addEvent('focus', function(e){
					new Event(e).stop();
					
					this.value = '';
				});
			});
		}*/
	},
	
	init: function()
	{

		Util.addCalendar();
		Util.corBotaoFiltro();
		Util.LimitChars();
		setInterval(Util.removeAnexo, 1000);
		//Util.validaImagem();
	},
	
	removeAnexo: function(){

		
		if($$('.remove-attachment')){
			$$('.remove-attachment').each(function(a){
				var confirma = function(e){
					new Event(e).stop();
					if(window.confirm('Deseja realmente apagar ')){
						new Request({
							url: a.href,
							method: 'get',
							onComplete: function(raw_json){
			    				var response = JSON.decode(raw_json);
					    			if(response.ok){
					    				//alert("Arquivo removido com sucesso");
					    				$('textoNotificacao').set('html', 'Arquivo removido com sucesso!');
				                		$('blocoNotificacao').removeClass('blocoNotificacaoErro');
					                    $('blocoNotificacao').addClass('blocoNotificacaoSucesso');
					                    $('blocoNotificacao').setStyle('display', 'block');
					                    $('imgNotificacaoSucesso').setStyle('display', 'block');
					                    setTimeout("$('blocoNotificacao').setStyle('display', 'none'); $('imgNotificacaoSucesso').setStyle('display', 'none');", 3000);
					                    new Fx.Scroll(document).toTop();
					    				//a.getPrevious().set('html', '<img border="0" src="'+base_url+'img/admin/file_type/img.gif">(3KB - image/jpeg)');
					                    a.getParent().getParent().getElement('input[type=hidden]').set('value', '');
					                    a.getParent().set('html', '');
					    				//window.location.reload();
					    			}else{
					    				//alert("Não foi possivel remover o arquivo")
					    				$('textoNotificacao').set('html', 'Erro ao remover arquivo!');
				                		$('blocoNotificacao').removeClass('blocoNotificacaoSucesso');
					                    $('blocoNotificacao').addClass('blocoNotificacaoErro');
					                    $('blocoNotificacao').setStyle('display', 'block');
					                    $('imgNotificacaoErro').setStyle('display', 'block');
					                    setTimeout("$('blocoNotificacao').setStyle('display', 'none'); $('imgNotificacaoErro').setStyle('display', 'none');", 3000);
					                    new Fx.Scroll(document).toTop();
					    			}
		                	}
						}).send();
					}
				}
				a.removeEvents('click');
				a.addEvent('click', confirma);
			});
		}
	},
	
	limparFiltro: function()
	{
		$$('.iptSearch').each(function (ipt, i)
		{
			ipt.set('value', '');
		});
		
	},
	
	validaImagem: function()
	{
		$('formMarketing').addEvent('submit', function(e){
			var i = 0;
			var extensoes = new Array('jpg', 'jpeg', 'gif', 'png');
			var valor = $('imagem').value;
			var separador = valor.split('.');
			var extensao = separador.pop();
			
			extensoes.each(function(ext)
			{
				if(extensao == ext)
				{
					i++;
				}
			});
			if(i>0)
			{
				$('formMarketing').submit();
			}else{
				alert('As extensï¿½es permitidas sÃ£o: jpg, png e gif.');
				new Event(e).stop();
			}
		});
	},	
	
	
	corBotaoFiltro: function()
	{
		if ( $$('.iptSearch') )
		{
			$$('.iptSearch').each(function(item)
			{
				if ( item.value.length > 0 )
					$('btFiltro').style.background = '#BB0000';
				else if ( item.selectedIndex > 0 )
					$('btFiltro').style.background = '#BB0000';
			});
		}
	},
	
	base_url: function()
	{
		return base_url;
	},
	
	isIframe: function()
	{	
		return isIframe;
	},
	site_url: function(uri)
	{
		if ( uri == null )
			return base_url + index_page;
			
		return base_url + (index_page!='' ?index_page + '/' :'') + uri;
	},
	
	call: function(uri, response, method, data)
	{
		method = method!=null ?method :'get';
		response = response!=null ?response :function(content){return;};
		data = data!=null ?data :'';
		
		var url = Util.site_url(uri);
		
		new Request({
			url: url,
			method: method,
			onComplete: response,
			data: data
		}).send();
	},
	
	save_position: function( produtoId, pagina, xProduto, yProduto, xCaption, yCaption )
	{
        Util.call('home/save_position/' + produtoId +"/"+pagina+"/"+xProduto+"/"+yProduto+"/"+xCaption+"/"+yCaption);
	},
	
	save_position_produto_media:function(produto,media,xProduto, yProduto, xCaption, yCaption, check )
	{
		Util.call('home/save_position_produto_media/' + produto +"/"+media+"/"+xProduto+"/"+yProduto+"/"+xCaption+"/"+yCaption+"/"+check);
	},
	
	mostraImagem: function(id,total,idproduto, str_quatidade, proId,selo,imgSRC)
	{
		
		
		Produto.montaComboTamanho(str_quatidade, $('tamanho' + proId), $('quantidade' + proId));
		
			
		
		$$('.'+id).each(function(item,index){
			item.getParent().getElements('.imgProdutolimit').each(function(item2,index2){
				item2.setStyle('display','none')
			});
			
			
		})
		
		$$('.'+id).setStyle('display','inline');
		
		if(selo== ''){
			
			$('selo'+proId).setStyle('display','none');
			
		}
		else{
			$('selo'+proId).setStyle('display','inline');
			$('seloimg'+proId).src = imgSRC;
		}
	},

    trocaLookProduto: function(host, id, cor)
        {
            new Request({
                url: ''+host+'produtos/getLookProduto/'+id+'/'+cor,
                onComplete: function(product){
                    var res = JSON.decode(product);
                    $('imagemLook'+id).set('src',res.imagem);
                    if(res.total == 0)
                    	msg = 'Não existe um look criado com este item.';
                    else if(res.total == 1)
                        msg = 'Existe '+res.total+' look criado com este item.';
                    else
                        msg = 'Existem '+res.total+' looks criados com este item.';
                    $('count'+id).innerHTML = msg;
                    $('linkLook'+id).set('href', res.link);
                    $('linkImagemLook'+id).set('href', res.link);
                }
            }).get();
        },
	
	navegacaoCatalogo:function(total,indice,sentido)
	{
		var indice = 1;
		var sentido = "right";
		var total = 10;
		var anterior = indice-1;
		var proxima = indice+1;
		
		/**
		 * Desabilitando todos os paineis
		 */
		for(i=1;i<=total;i++)
		{
			$("vitrinePainel"+i).style.display = "none";
		}	
		
		if(sentido=="left"&&anterior>=1)
		{
			$("vitrinePainel"+anterior).style.display = "block";
			$("paginaAtual").value = $("paginaAtual").value-1; 
		}	
		
		if(sentido=="right"&&proxima<=total)
		{
			$("vitrinePainel"+proxima).style.display = "block"
			$("paginaAtual").value = $("paginaAtual").value+1;
		}	
		
		 
		
	},	
	
	ativaStage: function(id,total)
	{
		for(i=1;i<=total;i++)
		{
			$("vitrine"+i).style.display = "none";
		}	
		
		$("vitrine"+id).style.display  = "block";
	},	

    getVideoPage: function ( videoId )
    {
        Util.call(
            'home/getVideoPage/' + videoId,

            function(content){
				/* resultado do util */
                //console.log( content );
				$('containerVideo').empty();
				$('containerVideo').innerHTML = content;
            }
        );
    },
	
	permissionMessage: function()
	{
        alert('VocÃª nÃ£o tem permissÃ£o para continuar essa aÃ§Ã£o.'+"\n"+'Para maiores informaÃ§Ãµes, contate o Administrador do sistema.');
	},
	
	menuProgramas: function ( )
	{
        if ( $('menuEsq') )
            $('menuEsq').getElements('div.menu').each(function( div, i )
            {
                div.addEvent('click', function( e )
                {
                    Util.menuCorDefault( );
                    div.removeClass('imgMenus');
                    div.addClass('imgMenusActive');

                    div.getChildren('div.txtMenu').each(function( divTxt ){
                        divTxt.addClass('txtMenuActive');
                        divTxt.removeClass('txtMenu');
                    });
                });
            });
		
		
	},
	
	menuCorDefault: function ( )
	{
		$('menuEsq').getElements('div.menu').each(function( div2, i )
		{
			div2.removeClass('imgMenusActive');
			div2.addClass('imgMenus');
			
			div2.getChildren('div.txtMenuActive').each(function( divTxt ){
				divTxt.addClass('txtMenu');
				divTxt.removeClass('txtMenuActive');
			});
		});
		
		
	},

    montaDropdown: function(data, dropdown, first)
    {
        $(dropdown).empty();

        var option = null;

        if ( first != null )
        {
            option = document.createElement('OPTION');
            option.value = '';
            option.innerHTML = first;

            dropdown.appendChild(option);
        }

        if ( data != null )
        {
            for ( var chv in data )
            {
                option = document.createElement('OPTION');
                option.value = chv;
                option.innerHTML = data[chv];

                dropdown.appendChild(option);
            }
        }
    },

    // Classe para recalcular o tamanho do slider
    recalcSlideHeight: function( idiv )
    {
        // Procura o wrapper de fora do slide
        while( idiv )
        {
            if( idiv.className && (idiv.hasClass('formDiv') || idiv.hasClass('recalDiv')) )
                break;
            idiv = idiv.parentNode;
        }

        if( !idiv )
            return;

		var height = idiv.offsetHeight;

        // Atualiza a altura da div
        idiv = idiv.parentNode;

        // Atualiza a altura da div
        if( idiv )
			idiv.setStyle( 'height', height );

    },
    
    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 
    },
    
    number_format: function(value, numberDecimal, separatorDecimal, separatorMilhar)
	{
		if ( !isNaN(value) )
		{
			value = Math.round(value * Math.pow(10, numberDecimal)) / Math.pow(10, numberDecimal);

			var str_value = "" + value;
			var v_value = str_value.split(".");

			var new_value = '';
			var v_new_value = new Array();
			var j = 0;

			for(var i = v_value[0].length-1; i >= 0; i-=3)
				v_new_value[j++] = v_value[0].substring((i-2), i+1);

			for ( var i = v_new_value.length-1; i >= 0; i-- )
				new_value+= (new_value!='' ?separatorMilhar :'') + v_new_value[i];

			if ( v_value[1]==null )
				v_value[1] = '';

			for ( var i = v_value[1].length; i < numberDecimal; i++ )
				v_value[1]+=0;

			return new_value + separatorDecimal + v_value[1];
		}

		return "";
	},
	
	keypress_formatCurrency: function(e)
	{
		var e = new Event(e);

		if(e.code > 47 && e.code < 58){
			var o, s, l = (s = ((o = this).value.replace(/^0+/g, "") + String.fromCharCode(e.code)).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.code > 30 && e.preventDefault();
	},

    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;
		
		
		$(o).removeEvent('keypress', Util.keypress_formatCurrency);
		
		$(o).addEvent('keypress', Util.keypress_formatCurrency);
    },
    
    parse_number: function(valor)
    {
    	return parseFloat(valor.replace(/\./g, '').replace(/,/g, '.'));
    },
    
    number_format: function (number, decimals, dec_point, thousands_sep) {
	    // Formats a number with grouped thousands
	    //
	    // version: 906.1806
	    // discuss at: http://phpjs.org/functions/number_format
	    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
	    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	    // +     bugfix by: Michael White (http://getsprink.com)
	    // +     bugfix by: Benjamin Lupton
	    // +     bugfix by: Allan Jensen (http://www.winternet.no)
	    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
	    // +     bugfix by: Howard Yeend
	    // +    revised by: Luke Smith (http://lucassmith.name)
	    // +     bugfix by: Diogo Resende
	    // +     bugfix by: Rival
	    // +     input by: Kheang Hok Chin (http://www.distantia.ca/)
	    // +     improved by: davook
	    // +     improved by: Brett Zamir (http://brett-zamir.me)
	    // +     input by: Jay Klehr
	    // +     improved by: Brett Zamir (http://brett-zamir.me)
	    // +     input by: Amir Habibi (http://www.residence-mixte.com/)
	    // +     bugfix by: Brett Zamir (http://brett-zamir.me)
	    // *     example 1: number_format(1234.56);
	    // *     returns 1: '1,235'
	    // *     example 2: number_format(1234.56, 2, ',', ' ');
	    // *     returns 2: '1 234,56'
	    // *     example 3: number_format(1234.5678, 2, '.', '');
	    // *     returns 3: '1234.57'
	    // *     example 4: number_format(67, 2, ',', '.');
	    // *     returns 4: '67,00'
	    // *     example 5: number_format(1000);
	    // *     returns 5: '1,000'
	    // *     example 6: number_format(67.311, 2);
	    // *     returns 6: '67.31'
	    // *     example 7: number_format(1000.55, 1);
	    // *     returns 7: '1,000.6'
	    // *     example 8: number_format(67000, 5, ',', '.');
	    // *     returns 8: '67.000,00000'
	    // *     example 9: number_format(0.9, 0);
	    // *     returns 9: '1'
	    // *     example 10: number_format('1.20', 2);
	    // *     returns 10: '1.20'
	    // *     example 11: number_format('1.20', 4);
	    // *     returns 11: '1.2000'
	    // *     example 12: number_format('1.2000', 3);
	    // *     returns 12: '1.200'
	    var n = number, prec = decimals;
	 
	    var toFixedFix = function (n,prec) {
	        var k = Math.pow(10,prec);
	        return (Math.round(n*k)/k).toString();
	    };
	 
	    n = !isFinite(+n) ? 0 : +n;
	    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
	    var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
	    var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;
	 
	    var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;
	 
	    var abs = toFixedFix(Math.abs(n), prec);
	    var _, i;
	 
	    if (abs >= 1000) {
	        _ = abs.split(/\D/);
	        i = _[0].length % 3 || 3;
	 
	        _[0] = s.slice(0,i + (n < 0)) +
	              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
	        s = _.join(dec);
	    } else {
	        s = s.replace('.', dec);
	    }
	 
	    var decPos = s.indexOf(dec);
	    if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) {
	        s += new Array(prec-(s.length-decPos-1)).join(0)+'0';
	    }
	    else if (prec >= 1 && decPos === -1) {
	        s += dec+new Array(prec).join(0)+'0';
	    }
	    return s;
	},
	
	LimitChars: function(){
        
		//alert('aqui em baixo');
        $$('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 );
                    }
                });
           });
        });
    },
    
    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);
        }

    }
    
    
};
