// Pós jQuery:
jQuery.cookie = function (key, value, options) {
    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }
        value = String(value);
		
		if(!options.raw){
			value = encodeURIComponent(value).replace(/(%7B|%7D|%3A|%22|%23|%5B|%5D)/g, function(charater){ return decodeURIComponent(charater); });
		}
		
        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw     ? value : value,
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path    ? '; path=' + options.path : '',
            options.domain  ? '; domain=' + options.domain : '',
            options.secure  ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

function trackNGo(categoria, acao, marcador, link){
	setTimeout(function(){
		_gaq.push(['_trackEvent', categoria, acao, marcador]);
	}, 500);
	if(link){
		setTimeout(function(){
			self.location.href = link;
		}, 1000);
		return false;
	}
}

// Decodificar base64 (útil para escrever e-mails na tela)
function prem(data) {
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, dec = "", tmp_arr = [];
    if (!data) {
        return data;
    }
    data += '';
    do {  // unpack four hexets into three octets using index points in b64
        h1 = b64.indexOf(data.charAt(i++));
        h2 = b64.indexOf(data.charAt(i++));
        h3 = b64.indexOf(data.charAt(i++));
        h4 = b64.indexOf(data.charAt(i++));

        bits = h1<<18 | h2<<12 | h3<<6 | h4;

        o1 = bits>>16 & 0xff;
        o2 = bits>>8 & 0xff;
        o3 = bits & 0xff;

        if (h3 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1);
        } else if (h4 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1, o2);
        } else {
            tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
        }
    } while (i < data.length);

    dec = tmp_arr.join('');
    //~ dec = this.utf8_decode(dec);

    return dec;
}


// Navegar:
$(function(){
	$(".in_list>li, .in_list>li>div>ul>li").each(function(){
		var nextEl    = $(this).children("div.subcats");
		var temSubCat = nextEl.length;
		if(!temSubCat){
			nextEl    = $(this).children("ul");
		}
		
		// Se  temSubCat, nextEl será o <DIV> que contém as subcategorias.
		// Se !temSubCat, nextEl será o <UL>  que deve ser carregado via AJAX.
		
		if(!temSubCat){
			$(this).find("a").first().click(function(){
				if($(this).attr('force_link')){
					return true;
				}
				
				if(nextEl.prop('loading') == 1)
					return false;
				
				if(nextEl.attr('loaded')){
					// Já estou carregado.
					// Vou apenas togglar a exibição.
					nextEl.slideToggle(function(){
						if($(this).is(":hidden")){
							$.cookie('_autoOpenCateg', '');
						}
						else{
							$.cookie('_autoOpenCateg', nextEl.attr('cid'));
						}
					});
					return false;
				}
				$.cookie('_autoOpenCateg', nextEl.attr('cid'));
				return showCateg(nextEl.attr('cid'));
			});
		}
		else{
			// Tem sub-categoria:
			$(this).find("a").first().click(function(){
				nextEl.slideToggle(function(){
					if($(this).is(":hidden")){
						$.cookie('_autoOpenCateg', '');
					}
				});
				return false;
			});
		}
	});
	if($.cookie('_autoOpenCateg'))
		showCateg($.cookie('_autoOpenCateg'));
});
function showCateg(cid){
	var el = $(".in_list").find("[cid='"+cid+"']");
	
	if(el.prop('loading') == 1)
		return false;
	
	if(el.attr('loaded')){
		el.closest("div:hidden").slideDown();
		return el.slideDown();
	}
	
	el.attr('loaded',  '1');
	el.prop('loading', '1');
	
	var lo = $("<div><table width='100%' height='25' style='background: #F6F1EC'><tr><td style='font: 11px Verdana; padding-left: 25px'><img src='images/ajax-loader.gif' width='15' height='15' style='margin-right: 6px'>Aguarde, carregando...</td></tr></table></div>").css('display', 'none');
	lo.insertBefore(el);
	lo.slideDown('fast');
	
	el.empty();
	el.closest("div:hidden").slideDown();
	
	el.load("ajax.navegar.php", {cid: cid }, function(){
		var oh = el.height();
		el
			.css('overflow', 'hidden')
			.css('height', '1')
			.css('visibility', 'visible')
			.prop('loading', '')
			.show()
			.animate({ height: oh }, 400, function(){
				el.css('overflow', '')
				.css('height', '')
				.css('visibility', '')
			});
		lo.slideUp(function(){ $(this).remove(); });
	});
	return false;
}

