jQuery(document).ready(function() {
	/*
	var defaults = {
		containerID: 'moccaUItoTop', // fading element id
		containerHoverClass: 'moccaUIhover', // fading element hover class
		scrollSpeed: 1200,
		easingType: 'linear' 
	};
	*/
	
	jQuery().UItoTop({ easingType: 'easeOutQuart', scrollSpeed: 400 });
	
	setTimeout('Util.hideLoading()',15000);
	
});


jQuery(document).ready(function(){
   Accordion.init();
});

jQuery(document).keydown(function (e) {
	if(e.which == 27){
		jQuery('#shShutter').fadeOut('fast', function() {
			// Animation complete.
		});
		
		jQuery('.BlocoCarregando').fadeOut('fast', function() {
			// Animation complete.
		});
		
		return false;
	}
});

var Accordion = {
    init : function () {
      jQuery('.AbaBotao').each(function () {
        if (!jQuery(this).hasClass('static'))
            jQuery(this).click(function () {
               var parent = jQuery(this).parent('.AbaItem');
                Accordion.toggle(parent);
            });
      });
      //$('.AbaItem:first').addClass('aberto');
    },
    toggle : function (object) {
        if (object.hasClass('aberto'))
            Accordion.close(object);
        else Accordion.open(object);
    },
    open : function (object) {
        Accordion.closeAll();
        object.addClass('aberto');
    },
    close : function (object) {
        object.removeClass('aberto');
    },
    closeAll : function () {
        jQuery('.AbaItem').each(function () {
           if (jQuery(this).hasClass('aberto'))
               jQuery(this).removeClass('aberto');
        });
    }
}

function move(id,spd){
	
	var obj=document.getElementById(id),max=-obj.offsetHeight+obj.parentNode.offsetHeight,top=parseInt(obj.style.top);
	
	if ((spd>0&&top<=0)||(spd<0&&top>=max)){
		obj.style.top=top+spd+"px";
		move.to=setTimeout(function(){ move(id,spd); },20);
	}else
		obj.style.top=(spd>0?0:max)+"px";
	
}

function retiraUltimoCaractere(str)
{
	
	if(str.indexOf('.php') != -1){
		// Aqui...
		str += '&load=click';
	}
	
	if(str.indexOf('.html') != -1){
		// Aqui...
		str = str.replace('?go=/', '');
	}
	
	if((str.indexOf('.php') == -1) && (str.indexOf('.html') == -1)){
		// Aqui...
		if((str.substring(-1,1)) == '/'){
			// Aqui...
			str += '&load=click';
		}else
			str += '/&load=click';
	}
	
	str = str.replace('//', '/');
	
	//alert(str);
	
	return str;
}

Util = {

	carregaHtml:
		function(Url, div) {
			
				jQuery.ajax({
					url: Url,
					type: "GET",
					data: {"div":div},
					cache: false,
					async: true,
					beforeSend: function(xmlhttprequest){
						Util.showLoading();
						jQuery('#div').html('');
					},
					error: function (XMLHttpRequest, textStatus, errorThrown) {Util.hideLoading();},
					complete: function(xmlhttprequest){Util.hideLoading();},
					success: function(html){
	
						var jq = jQuery(div);
						jq.html(html);
						Util.hideLoading();
					}
				});
			
		},
		
		
		
	enviaForm:
		function(form, div) {
			
			//if(text != null)
			var txt = "Enviando...";
			jQuery(div).html(txt);
			
			var frm = jQuery(form).get(0);
			var data = jQuery(form).serialize();
			// + "&div=" + div;
			
			data = data.replace(/%E2%80%93/gi, "-");
			data = data.replace(/%E2%80%9D/gi, "%22");
			data = data.replace(/%E2%80%9C/gi, "%22");
			jQuery.ajax( {
				url: jQuery(form).attr("action"),
				type: jQuery(form).attr("method"),
				data: data,
				cache: true,
				async: true,
				beforeSend: function(xmlhttprequest){
					Util.showLoading();
				},
				complete: function(xmlhttprequest) {
					Util.hideLoading();
				},
				error: function(XMLHttpRequest, textStatus, errorThrown){
					Util.hideLoading();
				},
				success: function(html){
					Util.hideLoading();

					var jq = jQuery(div);
					jq.show();
					jq.html(html);

				}
			});
		},
		
	showLoading:
		function() {
			if (typeof loadingQt == "undefined")
				loadingQt=0;
			
			loadingQt++;
			jQuery('#shShutter').fadeIn('fast', function() {});
			jQuery('.BlocoCarregando').fadeIn('fast', function() {});
			
		},
		
		
	hideLoading:
		function() {
			
			if (typeof loadingQt == "undefined")
				loadingQt=0;

			loadingQt--;
			if (loadingQt<0)
				loadingQt=0;
			if (loadingQt == 0){
				jQuery('#shShutter').fadeOut('fast', function() {});
				jQuery('.BlocoCarregando').fadeOut('fast', function() {});
			}
				
				
		},		
		
	textCounter:
		function(field, countfield, maxlimit) {
			if (field.value.length > maxlimit)
				field.value = field.value.substring(0, maxlimit);
			else 
				countfield.value = maxlimit - field.value.length;
		}
		
}





// Codigo utilizado na paginacao estilo facebook e twitter
jQuery(function() {//When the Dom is ready

	jQuery('.load_more').live("click",function() {//If user clicks on hyperlink with class name = load_more
										  
		var last_msg_id = jQuery(this).attr("id");
		//Get the id of this hyperlink 
		//this id indicate the row id in the database 
		if(last_msg_id!='end'){
		//if  the hyperlink id is not equal to "end"
			jQuery.ajax({//Make the Ajax Request
				type: "POST",
				url: jQuery(this).attr("rel"),
				
				// lastmsg: Data de publicacao
				// l: quantidade de registros
				// cod: código do conteudo
				
				data: "categoria="+ last_msg_id + "&l="+jQuery(this).attr("title")+"&cod="+jQuery(this).attr("name")+"&load=click"+"&tag="+jQuery(this).attr("rev"),  
				beforeSend:  function() {
								jQuery('a.load_more').html('<img width="20" src="imagens/loading.gif" /> carregando...');//Loading image during the Ajax Request
	  
							},
				success: function(html){//html = the server response html code
							jQuery("#more").remove();//Remove the div with id=more 
							jQuery("#updates").append(html);//Append the html returned by the server .
	
							}
			});
	
		}
	
	return false;
	
	});
	
});




// Carregar oagina em ajax

var default_content = ""; // conteúdo padrão (é melhor não mexer)
var pageContent = "#conteudo"; // elemento onde o conteúdo será carregado
var loading = "#loading"; // elemento que contém a mensagem de carregamento



var lasturl = "";

function checkURL(hash) {
    
	if (!hash) {
        hash = window.location.hash;
    }

    if (hash != lasturl) {
        lasturl = hash;
		
		//alert(hash);
		
        if (hash == "") {
            loadPage('?go=/capa/');
			//jQuery(pageContent).html(default_content);
        } else { // se houver hash, a outra função é chamada para tratá-lo e executar o Ajax
            aux = hash.replace('#', '?go=');
			//alert(hash);
			//alert(aux);
			loadPage(aux);
        }
    }
}


function loadPage(url) { // o parâmetro é o HREF do link HTML, exemplo: href="#pagina1"

    // Simulando o click para subir o scroll animado quando mudar de página
	jQuery('#toTop').click();
	
	var url = retiraUltimoCaractere(url);
	
	//alert(url);
	
	url = url.replace('#', ''); // remove a cerquilha

    //$(loading).css('visibility', 'visible');
	Util.showLoading();

	//alert(url);

    jQuery.ajax({ // configurações Ajax
        type: "GET",
        //url: url + ".php", // extensão PHP, se quiser definir a extensão da página via atributo HREF, é só deixar somente a variável "url" aqui <<< e colocar href="#pagina.(extensao)"
		url: url, //+'&load=click',
        timeout: 15000,
        dataType: "html",
        success: function (msg) {
            if (parseInt(msg) != 0) {
                jQuery(pageContent).html(msg);
                Util.hideLoading();
            }
        },
        error: function () { // manipula a mensagem de erro
            jQuery(pageContent).html("Erro interno do servidor. Por favor, atualize a página");
            Util.hideLoading();
        }
    });

}
