/**
 * @author pedromoraes@gmail.com
 */
var initialized = false;
var loaded = false;
var loadedData = false;
var openedData;
var posts = [];
var postData;

var postsNav = {
	pageSize: 4, page: 0,
	commentData : null, firstRender : true,
	loadOlder : function() {
		if ( this.page < this.getLastPage() ) {
			this.page ++;
			this.showLoadFeedback();
			this.load();
		}
	},
	loadNewer : function() {
		if (this.page > 0) {
			this.page--;
			this.showLoadFeedback();
			this.load();
		}
	},
	render : function() {
		this.clear();
		posts = [];
		$.each(postData, function(i,item){
			var f = "<div class=\"footer\">" +
			"<span class=\"comments\" id=\"" + i + "comments\"><a href=\"#\">{comments}</a></span>" +
			"<span class=\"sm\"><a href=\"{share_url_fb}\" target=\"_blank\"><img src=\"img/postbt_fb_off.gif\" width=\"14\" height=\"16\" /></a>" +
			"<a href=\"{share_url_tw}\" target=\"_blank\"><img src=\"img/postbt_twitter_off.gif\" width=\"14\" height=\"16\" /></a></span>" +
			"<span class=\"date\">{date}</span>" +
			"</div>";
			var hoverImg = '<img src="img/small_edge.png" width="22" height="20" class="hover" />';
			item['date'] = formatPostDate(item['unix-timestamp']);
			item['share_url_tw'] = getShareURL( item['regular-title'] || "", item.url, "tw" );
			item['share_url_fb'] = getShareURL( item['regular-title'] || "", item.url, "fb" );
			for (var s in item) f = f.split("{" + s + "}").join(item[s]);
			var m ="";
			//for ( var s in item ) m+=s+","; alert(m);
	
			if (item.type == "video") {
	
				var node = $("<span />").attr("id", i + "post").html(
					f + hoverImg +
					"<div class=\"content\" id=\"" + i + "content\">" +
						'<div class="over"><img src="img/pixel.gif" class="overimg" /></div>' +
						'<div id="player'+i+'"></div>' +
					"</div>"
				).appendTo("#posts");
				item.title = null;
				item.caption = item['video-caption'];
				var playerSrc = item['video-player'];
				$("#player" + i).flash(
					{
						swf: playerSrc.match(/src=\"(.*?)\"/)[1],
						width: 236, height: 200,
						wmode : "transparent",
						flashvars : {
							autoplay : "false"
						}
					}
				);
				$( "#" + i + "post .over" ).click(function(){openNode(i);});

	
			} else if (item.type == "audio") {
	
				var node = $("<span />").attr("id", i + "post").html(
					f + hoverImg +
					"<div class=\"content\" id=\"" + i + "content\">" +
						item['audio-player'] +
						"<div class=\"body audiocaption\">" + item["audio-caption"] + "</div>" + 
					"</div>"
				).appendTo("#posts");
				item.title = null;
				item.caption = item['audio-caption'];
	
			} else if (item.type == "photo") {
	
				var node = $("<span />").attr("id", i + "post").html(
					f + hoverImg +
					"<div class=\"content\" id=\"" + i + "content\">" +
						"<img src=\"" + item["photo-url-250"] + "\" width=250 />" +
					"</div>"
				).appendTo("#posts");
				item.title = null;
				item.caption = item['photo-caption'];
				$( "#" + i + "post" ).css("cursor","pointer").click(function(){openNode(i);});
	
			} else if (item.type == "quote") {
	
				var text = item["quote-text"] || "";
				var node = $("<span />").attr("id", i + "post").html(
					f + hoverImg +
					"<div class=\"content\" id=\"" + i + "content\">" + 
						"<p class=\"title quote\">" + item["quote-text"] + "</p>" +
						"<div class=\"body quotesrc\">" + item["quote-source"] +	"</div>" +
					"</div>"
				).appendTo("#posts");
				item.title = item['quote-text'];
	
			} else if (item.type == "link") {
	
				var text = item["link-description"] || "";
				var node = $("<span />").attr("id", i + "post").html(
					f + hoverImg +
					"<div class=\"content\" id=\"" + i + "content\">" + 
						"<a class=\"title link\" href=\"" + item["link-url"] + "\" target=\"_blank\">" + item["link-text"] + "</a>" +
						"<div class=\"body linkdesc\">" + item["link-description"] +	"</div>" +
					"</div>"
				).appendTo("#posts");
				item.title = item['link-text'];
	
			} else {
	
				var text = item["regular-body"] || "";
				var node = $("<span />").attr("id", i + "post").html(
					f + hoverImg +
					"<div class=\"content\" id=\"" + i + "content\">" + 
						"<p class=\"title\">" + item["regular-title"] + "</p>" +
						"<div class=\"body\">" + text +	"</div>" +
					"</div>"
				).appendTo("#posts");
				$("#" + i + "post .body img").attr({width:236,height:null});
				item.title = item['regular-title'];
				$( "#" + i + "post" ).css("cursor","pointer").click(function(){openNode(i);});
	
			}
			$( "#" + i + "comments").click(function(){openComments(i);return false;});
			$(node).css("opacity", 0);
			posts.push(node);
			
			if ( posts.length == 2 ) {
				$("#blogroll").remove().show().css("opacity", 0).appendTo("#posts");
				posts.push( $("#blogroll") );
			}
		}); 
		
		while ( posts.length < 5 ) {
			posts.push( $("<span />").addClass("blank").css("opacity", 0).html('<div class="content"><div class="body">&nbsp;</div></div>').appendTo("#posts") );
			if ( posts.length == 2 ) {
				$("#blogroll").remove().show().css("opacity", 0).appendTo("#posts");
				posts.push( $("#blogroll") );
			}
		}
		
		posts.push($("#agenda"));
		
		$("#posts .loading").animate({opacity:0}, 200,null,function(){$(this).hide();})
		$("#agenda").remove().show().css("opacity", 0).appendTo("#posts");
		
		$.each( posts, function (i) {
			if ((i + 1) % 3 == 0) {
				$(this).addClass("last_of_row");
			}
			$(this).wait( ( 100*i ) || 1 ).animate({ opacity: 1 }, 300);
		} );
		
		postsNav.updateNavButtons();
		postsNav.fillCommentCounts();
		
		
		if ( !this.firstRender ) $('html,body').animate({scrollTop: 300}, 600 );
		this.firstRender = false;
	},
	showLoadFeedback : function() {
		$("#posts_nav .older").hide();
		$("#posts_nav .newer").hide();
		$("#posts .loading").show().css('opacity',0).animate({opacity:1}, 200,null);
	},
	updateNavButtons : function() {
		if ( this.page < this.getLastPage() ) $("#posts_nav .older").show();
		else $("#posts_nav .older").hide();
		
		if ( this.page > 0 ) $("#posts_nav .newer").show();
		else $("#posts_nav .newer").hide();
	},
	load : function( cb ) {
		$.getJSON("http://cartaz.tumblr.com/api/read/json/?start="+(this.page*this.pageSize)+"&num="+this.pageSize+"&"+ Math.random() +"&callback=?",
		//$.getJSON("data/proxy.php?proxy_url=http://cartaz.tumblr.com/api/read/json/$start="+(this.page*this.pageSize)+"*num="+this.pageSize,
			function( data ) {
				postData = data.posts;
				postsNav.recordCount = parseInt( data['posts-total'] );
				postsNav.pageCount = postsNav.recordCount / postsNav.pageSize;
				
				postsNav.render();
				if ( cb != undefined ) cb.apply( this, [] );
		});
	},
	getLastPage : function() {
		return Math.ceil( this.recordCount / this.pageSize ) - 1;
	},
	clear : function() {
		$("#posts span").each(function(i){
			if ( $(this).attr("id") != "blogroll" && $(this).attr("id") != "agenda" ) $(this).remove();
		});
	},
	loadCommentCount : function () {
		var ids = "";
		$.each(postData, function(i){
			if ( ids != "" ) ids += ",";
			ids += postData[i].id;
		});
		$.get("data/gateway.php?action=getCommentCount&post_ids=" + ids, {}, function(xml) {
			var cnts = {};
			$("row", xml).each(function(i){
				var id = $(this).find("post_id").text();
				var cnt = $(this).find("cnt").text();
				cnts['_'+id] = cnt;
			});
			postsNav.commentData = cnts;
			postsNav.fillCommentCounts();
		});
	},
	fillCommentCounts : function() {
		if ( postsNav.commentData == null ) return;
		var cnts = postsNav.commentData;
		$.each(postData,function(i){
			var id = postData[i].id;
			var node = $("#" + i + "comments a");
			if ( cnts['_'+id] ) {
				node.show().html(cnts['_'+id] + " " + LOCALE['comments'] + (parseInt(cnts['_'+id])>1?"s":""));
			} else {
				node.show().html( LOCALE['no_comments'] );
			}
		})
	}
};
var init = function(){
	$("img").each(function(i){
		if ( this.src.indexOf("_off") > -1 ) {
			$("<img />").attr("src",this.src.replace("_off","_on")).css("display","none").appendTo("body")
			$(this).hover(
				function() {
					this.src = this.src.replace("_off","_on");
				},
				function() {
					this.src = this.src.replace("_on","_off");
				}
			);
		}
	});
	$(".internal_content .comment a").click(function(){
		$('html,body').animate({scrollTop: 200}, 300 );
		openComments( openedData.i );
		return false;
	});
	$("#posts_nav .older").click(function(){
		postsNav.loadOlder();
		return false;
	});
	$("#posts_nav .newer").click(function(){
		postsNav.loadNewer();
		return false;
	});
	initialized = true;
	postsNav.loadCommentCount();
};
$(document).ready(function() {
	loaded = true;
	if ( loadedData ) init();
});


postsNav.load(function(){
	loadedData = true;
	if ( loaded ) init();
}); 

function getPhotoSetHtml( post ) {
	var p = post.photos[0];
	var url = p['photo-url-500'];
	var start = '/tumblr_';
	var pscode = url.substring(url.indexOf(start)+start.length,url.indexOf(p.offset+"_"));
	return '<embed type="application/x-shockwave-flash" src="http://cartaz.tumblr.com/swf/photoset.swf" bgcolor="#000000" quality="high" class="photoset" flashvars="showLogo=false&amp;showVersionInfo=false&amp;dataFile=http://cartaz.tumblr.com/post/' + post.id + '/photoset_xml/tumblr_' + pscode + '/500" height="400" width="640"></embed>';
}

function formatPostDate( ustamp ) {
	date = new Date();
	date.setTime( ustamp * 1000 );
	return date.getDate() + "/" + ( date.getMonth() + 1 ) + "/" + date.getFullYear().toString().substr( 2 );
}
function openNode(i) {
	var title;
	var text;
	openedData = postData[i];
	openedData.i = i;
	switch ( openedData.type ) {
		case "photo":
			if ( openedData.photos )
			{
				text = openedData.caption + getPhotoSetHtml( openedData );
			}
			else
			{
				text = openedData.caption + "<img src='" + openedData['photo-url-500'] + "' />";
			}
			title = "";
			//title = openedData["photo-caption"];
			break;
		case "video":
			text = openedData.caption + openedData["video-player"];
			title = "";
			break;
		default:
			title = openedData["regular-title"];
			text = openedData["regular-body"];
	}
	$("#full_title").html(title);
	$("#full_content").html(text);
	$("#full").show().css("opacity", 0).animate({opacity:1}, 600 );
	$('html,body').animate({scrollTop: 800}, 600 );
}
function openComments(i) {
	$("#" + i + "content").hide();
	$("#" + i + "post .footer").hide();
	$('<div>').attr("class", "closeComments").html('<a href="#">X</a>').appendTo("#" + i + "post").click(function(){closeComments(i);return false;});
	var node = $('<iframe/>').attr({ scrolling : "auto" }).addClass("comments_box").attr({ id: i+"commentsFrame", width: "100%", height: "100%", frameborder : "no" }).appendTo("#" + i + "post");
    node.attr('src', "comentarios.php?POST_ID=" + postData[i]['id'] + "&POST_TITLE=" + postData[i]['title']);
  	node.load(function()
    {
    });
}
function closeComments(i) {
	$('#' + i + 'post .closeComments').remove();
	$('#' + i + 'commentsFrame').remove();
	$("#" + i + "content").show();
	$("#" + i + "post .footer").show();
}
