/* MAKE WALL - 10150146692405447 by andrei.ross@gmail.com */

function showWall(filter,dateRange,species){

	var source_id = "120452987982740"; //10150146692405447
	var access_token = '206158599425293|1df31a8727c3377cea29f485.1-100000221135225|YRxEUQA5gDlA4yFvGCBI3IMYO8U';
	
	/* clear wall */
	$("ul#ideas").empty();

	/* The Basic FQL Query */
	var api = "https://api.facebook.com/method/fql.query?format=json&access_token=" + access_token + "&query=";
	var fql = "SELECT+actor_id%2Ccreated_time%2C+post_id%2C+message%2C+comments%2C+likes%2C+action_links+FROM+stream+WHERE+source_id+%3D%27"+source_id+"%27+LIMIT+5&callback=?";
		
	/* Sort by Species >filter< */
	if(species!=0){
		spec = escape(species).toLowerCase();
		var fql = "SELECT+actor_id%2Ccreated_time%2C+post_id%2C+message%2C+comments%2C+likes%2C+action_links+FROM+stream+WHERE+source_id+%3D%27"+source_id+"%27+AND+%28strpos%28message%2C+%27"+spec+"%27%29+%3E%3D+0+OR+strpos%28message%2C+%27"+species+"%27%29+%3E%3D+0%29&callback=?";
		// no limit
	}

	/* Show older posts for dateRange */
	if(dateRange!=0){
		befo = $("div#olderPosts").attr("date");
		var fql = "SELECT+actor_id%2Ccreated_time%2C+post_id%2C+message%2C+comments%2C+likes%2C+action_links+FROM+stream+WHERE+source_id+%3D%27"+source_id+"%27+AND+created_time+%3C+%27"+befo+"%27+LIMIT+5&callback=?";
	}

	/* Most Liked */
	if(filter=='most_liked'){
		var fql = "SELECT+actor_id%2Ccreated_time%2C+post_id%2C+message%2C+comments%2C+likes%2C+action_links+FROM+stream+WHERE+source_id+%3D%27"+source_id+"%27&callback=?";
	}		

	// alert("query:"+api+fql);	
				
	$.getJSON(api+fql,function(wallData){
			var userId = $('div.userID').attr('id');
			var offset = 0;
			var limit = wallData.length;
			for(var i=offset;i<limit;i++){
				// Comment List w/ Count
				var commentCount=0;
				var commentListDivs='';
				var viewComments='';
				if(wallData[i].comments['count']>0){
					var commentList = wallData[i].comments['comment_list']; 
					var commentCount =  wallData[i].comments['count'];
					if(wallData[i].comments['count']>2){
						viewComments = "<div class='fbComments pc_"+wallData[i].post_id+"' id='postComments_"+wallData[i].post_id+"'><img src='media/fbComments.gif' alt='comments for this post icon' /> "+
							"<a class='fbLink viewAllComments' href='javascript:getMoreComments(\""+wallData[i].post_id+"\")'>View all "+commentCount+" comments.</a>"+
						"</div>";
					}
					$.each(commentList, function(index, comm){
						commentListDivs = createComment(comm,commentListDivs);
					});
				}
				// Create Likes
				var viewLikes='';
				var ppl = "people</a> like";
				if(wallData[i].likes['count']>0){
					if(wallData[i].likes['count']==1){ ppl = "person</a> likes"; }
					viewLikes="<div class='fbLikes'><img src='media/fbLikes.gif' alt='like this post icon' border='0' /> "+ 
						"<a class='fbLink' href='http://www.facebook.com/pages/Tatzoo/120452987982740'>"+wallData[i].likes['count']+" "+ppl+" this."+
						"</a></div>";
				}

				// Set Actor and Message
				var actor = "<span class='bb username user_"+wallData[i].actor_id+"' title='"+wallData[i].actor_id+"'></span>";
				var message = actor+" "+wallData[i].message;

				// See More of this Post
				if(wallData[i].message.length>320){
					cMess = "<span style='display:none' id='more_"+wallData[i].post_id+"'>"+message+"</span><span id='less_"+wallData[i].post_id+"'>"+message.substring(0,320)+"...</span>";
					message = cMess+"<br /><div class='seeMorePosts' id='seeMore_"+wallData[i].post_id+"'><a class='fbLink seeMore' title='"+wallData[i].post_id+"' href='SeeMore'>See more</a></div>";
				}
				
				// Figure Time
				var date = new Date(wallData[i].created_time*1000);
				var year = date.getFullYear();
				var month = date.getMonth()+1;
				var day = date.getDate();
				var hours = date.getHours();
				var minutes = date.getMinutes();
				var seconds = date.getSeconds();
				var formattedTime = year +"-"+ month +"-"+ day +" "+ hours + ':' + minutes + ':' + seconds;
				var createdTime = jQuery.timeago(formattedTime);

				// Append Posts
				$("ul#ideas").append( 
					"<li class='idea' id='pid_"+wallData[i].post_id+"' created='"+wallData[i].created_time+"' likes='"+wallData[i].likes['count']+"'>"+
						"<div class='fbProfileImg'><a href='http://facebook.com/profile.php?id="+wallData[i].actor_id+"'><img src='https://graph.facebook.com/"+wallData[i].actor_id+"/picture' alt='face book profile picture' /></a></div>"+
						"<div class='fbPost fp_"+wallData[i].post_id+"'>"+message+"<div class='commentLike'><span class='timeago'>"+createdTime+"</span>"+
							"</div>"+viewLikes+viewComments+commentListDivs+
							"<div class='fbComments enterComment' id='co_"+wallData[i].post_id+"'>"+
							"<img class='fbCommentThumb' src='https://graph.facebook.com/"+userId+"/picture' />"+
							"<div class='fbCommentsText'><textarea class='newCommentBox expand' maxlength='420' id='nc_"+wallData[i].post_id+"'></textarea> "+
								"<div class='submitComment' onclick='submitNewWallComment(\"nc_"+wallData[i].post_id+"\")'>Comment</div>"+
							"</div></div></div>"+
					"</li>"
				);

			// &bull; 
			// "<a class='fbLink' href='javascript:dspCommentBox(\"co_"+wallData[i].post_id+"\");'>Comment</a> &bull; "+
			// "<a class='fbLink' href='javascript:likeThisPost(\"li_"+wallData[i].post_id+"\");'>Like</a>"+


			// Older Date State
			$("div#olderPosts").attr("date",wallData[i].created_time);

			} // end foreach post
			writeUserNames();
			handleSeeMore();
			initTextExpander();
			/* Re-Sort By Likes */
			if(filter=='most_liked'){
				// sort by likes
				sortWallByLikes();
			}
		}
	);
}

function sortByValueDesc(ka,vm) {
	return ka.sort(function(a,b){return vm[b]-vm[a];});
}

function sortWallByLikes(){
	var arr = [], keys = [], vals = [];
	$('li.idea').each(function(index) {
		arr[$(this).attr("id")] = $(this).attr("likes");
		keys.push($(this).attr("id"));
	});
	vals = sortByValueDesc(keys, arr);
	lim = 0;
	for(var i in vals){
		lim++;
		if(lim<6){ // Limit the Number of Posts, Compensate for F'QL
			$old = $('li#'+vals[i]);
			$('li#'+vals[i]).clone().appendTo('ul#ideas');
			$old.remove();
		} else{ 
			$old = $('li#'+vals[i]);
			$old.remove();
		}
	}
}

function getMoreComments(id){
	// Handle View All Comments
	var api = "https://api.facebook.com/method/fql.query?format=json&query=";
	var fql = "SELECT+fromid%2C+text+FROM+comment+WHERE+post_id%3D%27"+id+"%27&callback=?";
	$.getJSON(api+fql,function(commData){
		var limit = commData.length;
		var commentListDivs='';
		for(var i=0;i<limit;i++){
			// Create Comments
			var comm = commData[i];
			commentListDivs = createComment(comm,commentListDivs);
		}
		// Append all comments
		$('div.pc_'+id).remove();
		$('div.fp_'+id).append(commentListDivs);
		writeUserNames();
		handleSeeMore();
	});
}


function createComment(comm,commentListDivs){
	var commentor = "<span class='bb username user_"+comm['fromid']+"' title='"+comm['fromid']+"'></span>";
	var comment = commentor+" "+comm['text'];
	// See More of this Comment
	if(comm['text'].length>342){
		cCom = "<span style='display:none' id='more_"+comm['id']+"'>"+comment+"</span><span id='less_"+comm['id']+"'>"+comment.substring(0,342)+"...</span>";
		comment = cCom+"<br /><div class='seeMoreComments' id='seeMore_"+comm['id']+"'><a class='fbLink seeMore' title='"+comm['id']+"' href='SeeMore'>See more</a></div>";
	}
	commentListDivs += "<div class='fbComments'>"+
		"<a href='http://facebook.com/profile.php?id="+comm['fromid']+"'><img class='fbCommentThumb' src='https://graph.facebook.com/"+comm['fromid']+"/picture' /></a>"+
		"<div class='fbCommentsText'>"+comment+"</div></div>";
	return commentListDivs;
}


function writeUserNames(){
	// Write UserName for Posts and Comments
	$('span.username').each(function(index) {
		uid = $(this).attr("title");
		$.getJSON("https://graph.facebook.com/"+uid+"&callback=?",function(u){ 
			$("span.user_"+u.id).html(u.name);
		});
	});	
}



function handleSeeMore(){
	// Handle See Mores
	$("a.seeMore").click(function(event) {
		event.preventDefault();
		sid = "more_"+$(this).attr("title");
		hid = "less_"+$(this).attr("title");
		smo = "seeMore_"+$(this).attr("title");
		$("span#"+sid).show();
		$("span#"+hid).hide();
		$("div#"+smo).hide();
	});	
}


function initTextExpander(){
	$("textarea.newCommentBox").TextAreaExpander(36, 311);
}


function dspCommentBox(id){
	// hide all other comment boxes and show this comment box
	$("div.enterComment").hide();
	$("div#"+id).show();
}

function submitNewWallComment(id){
	var uid = $("div.userID").attr("id");
	var pid = id.substring(3,id.length);
	var fbc = $("textarea#"+id).val();
	var dat = 'user_id='+ uid + '&post_id='+ pid + '&post_message=' + fbc; 
	$.ajax({ type: "POST", url: "/fb/", data: dat, success: function(foo){ 
		//alert(foo);die;
		showWall(0,0,0);
	 } });  
	return false;
}

function likeThisPost(id){
	var pid = id.substring(3,id.length);
	var dat = 'add_like='+ pid; 
	$.ajax({ type: "POST", url: "/fb/", data: dat, success: function(){ 
		showWall(0,0,0);
	 } });  
	return false;
}



