/**
 * This js file contains almost all the site status methods. 
 * 
 * @author Basit (i@Basit.me || http://Basit.me)
 */
var feed = {
	
	set_media_id: 0,
	
	getID: function($this)
	{
		var feed_id = $j($this).parents('.status_update').attr('id');
		feed_id = feed_id.replace(/^s{1}/ig, '');
		return feed_id;
	},
	
	ui_row: function (feed_id)
	{
		return $j('#s'+feed_id);
	},
	
	add: null,
	
	reply_box: function($this)
	{	
		if ($this.parent('.status_update').hasClass('status_current'))
			var username = $this.parent('.status_update').find('h2').attr('title');
		else
			var username = $this.parent('.status_update').find('p > a').html();
		
		var reply_box = '<div class="status_comments">\
							<div class="new">\
								<a href="#" class="remove">remove</a>\
								<form method="post" action="#">\
									<textarea rows="2" cols="45" name="status_comment_new" id="status_comment_new">@'+username+' </textarea>\
									<p class="subtext">You have <span id="status_comment_new_charcount">140</span> characters left.</p>\
									<input type="submit" class="white_button_small" value="post" />\
								</form>\
							</div>\
						</div>';
			
		var feed_id = feed.getID($this);
		var row = feed.ui_row(feed_id);
		feed.reply_box_remove(row);
		
		row.append(reply_box);
		row.find('.status_comments').find('form').submit(function() {

			$j(this).find('.white_button_small').attr('disabled', true).val('loading...');
			var post = {
				username: 	login_username ? login_username : 'basit', 
				text: 		$j(this).find('[name="status_comment_new"]').val(),
				reply_to:	feed_id 
			}
			
			if (feed.set_media_id != 0)
				post.media_id = feed.set_media_id;
			
			api.feedCreate(post, function(response) {
				api.ajax_response(response, 'replied to @'+username);
				
				var row = feed.ui_row(feed_id);
				if (response.status_valid == 1) 
				{
					feed.reply_box_remove(row);
				}
				else
				{
					row.find('.status_comments').find('.white_button_small').attr('disabled', false).val('post');
					
					var chars = row.find('#status_comment_new').val().length;
					row.find('#status_comment_new').selectRange(chars, chars);
				}
			});
			
			return false;
		});
		
		feed.limitChars('status_comment_new', 140, 'status_comment_new_charcount');
		
		var chars = row.find('#status_comment_new').val().length;
		row.find('#status_comment_new').selectRange(chars, chars);
	},
	
	reply_box_remove: function (ui_row)
	{
		//ui_row.find('.status_comments').remove();
		$j('.status_comments').each(function() {
			$j(this).remove();
		})
	},
	
	remove: function (feed_id)
	{
		api.feedDelete(feed_id, function(response) {
			if (response.status_valid == 1) 
			{
				feed.ui_row(feed_id).slideUp("slow");
			}
		});
	},
	
	vote: function ($this)
	{
		var clicked_on  = $this.attr('class');
		var didnt_click = (clicked_on == 'like_it') ? 'dontlike_it' : 'like_it';	
		
		var feed_id = feed.getID($this);
		var vote    = (clicked_on == 'like_it') ? 'up' : 'down';			
		
		api.feedVote(feed_id, vote, function(response) {
			if (response.status_valid == 1)
			{
				if (response.vote_score > 0)
					var rating = 'liked_it';
				else
					var rating = 'dontliked_it'
				
				var row = feed.ui_row(feed_id);	
				row.find('.dontlike_it').after('<li class="'+rating+' feed_rating"><span>'+response.vote_score+'</span></li>');
				row.find('.'+clicked_on).removeClass(clicked_on).addClass(clicked_on + "_selected").fadeIn(200);
				row.find('.'+didnt_click).removeClass(didnt_click).addClass(didnt_click+'_static').fadeIn(200);					
			}
		});
	},
	
	report_spam: null,
	
	/**
	 * get the list of feeds of user or a search, depending if user is on search page or profile feed page
	 * 
	 * @param {Object} filter this can be filter for profile page (ifeed or thread) or it can be a search word for search feed page
	 * @param {Object} type_or_thread_id  type for search page or profile page or id of a thread, if filter is set to thread
	 */
	get_list: function (filter, type_or_thread_id, after)
	{
		if (!profile_username || profile_username == 'x')
		{
			if (!filter && !type_or_thread_id)
				api.feedEveryone(after, feed.built_list);
			else if (!filter)
				api.feedSearch(null, (type_or_thread_id == 'all') ? '' : type_or_thread_id, after, feed.built_list);
			else
				api.feedSearch(filter, type_or_thread_id, after, feed.built_list);
		}
		else
		{
			if (filter == 'thread')
				api.feedThread(type_or_thread_id, after, feed.built_list);
			if (filter == 'media')
				api.feedMedia(type_or_thread_id, after, feed.built_list);
			else
				api.feedUser((type_or_thread_id == 'all') ? '' : type_or_thread_id, (filter == 'ifeed'), after, feed.built_list);
		}
		
		return false;
	},
	
	built_list: function (response)
	{
		// change title 
		//$j('h2').html(profile_username+' '+$j('#filters > a[name='+$j("[name='selected']").val()+']').html());
		
		if (feed.callback_success_list)
			feed.callback_success_list(response);
		
		$list_container = $j('#results_panel, #rows');
		
		if (response.paging.total_rows)
		{
			$j.each(response.items, function(i, $status) {
				$list_container.append(feed.row($status));
			});
			
			$j('.status_update').trigger('status_icons_hide');
			$j(".feed_media").trigger('feed_media_extra_hide');
		}
		else
		{
			$list_container.append('<div class="status_update">none.</div>');
		}
		
		if ($j('#paginator').html())
			ui.paging(response.paging, $j('#paginator'));
		else if ($j('.status_getmore').html())
		{
			if (response.paging.next)
			{
				$j('#paging_next').val(response.paging.next);
				$j('.status_getmore').show();
					
			}
			else
			{
				$j('#paging_next').val(0);
				$j('.status_getmore').hide();
			}				
		}
	},
	
	callback_success_list: null,
	
	row: function ($status)
	{
		//console.log($status);
		var remove 		= (profile_username == login_username && $status.username == login_username) ? '<a href="#" class="remove">remove</a>' : '';
		var reply 		= ($status.reply_id > 0) ? '<li class="thread"><a href="http://'+$status.username+'.'+$domain_only+'/status/thread/'+$status.thread_id+'">Thread</a></li>' : '';
		var vote		= ($status.username != login_username) ? '<li class="like_it"><a href="#">I like it</a></li><li class="dontlike_it"><a href="#">I dont like it</a></li>' : '';
		var direct_link = ($status.thumbnails == 0 && $status.direct_links != 0 && $status.direct_links != '') ? '<a href="'+$status.direct_links+'">link</a>' : '';
		var thumbnail 	= '';
		
		if ($status.thumbnails && $status.thumbnails != 0)
		{
			var icon = ($status.type == 'video') ? "<span class='videothumb_play_medium'></span>" : '';
			thumbnail  = '<div class="feed_media">';
			$j.each($status.thumbnails, function(key, row) {		
				var image = "<img src='"+row['0']+"' alt='"+$status.type+"' />";
				var link  = (row['1'] != '' && row['1'] != 0) ? row['1'] : '';
				thumbnail +=  link ? "<div><a href='"+link+"'>"+image+"</a>"+icon+"</div>" : "<div>"+image+""+icon+"</div>";
			});			
			thumbnail += '</div>';
		}
	
		return '<div class="status_update" id="s'+$status.feed_id+'">\
					'+remove+'\
	                <a href="#" class="reply-to">reply</a>\
					<div class="user-img">\
						<a href="http://'+$status.username+'.'+$domain_only+'"><img src="http://'+$status.username+'.'+$domain_only+'/avatar/64.jpg" alt="'+$status.username+'" /></a>\
	                </div>\
					<p>\
					<a href="http://'+$status.username+'.'+$domain_only+'">'+$status.username+'</a>\
					'+feed.parse($status.text)+' '+direct_link+'</p>\
					'+thumbnail+'\
					\
					<ul class="options">\
						<li class="date_duration"><a href="http://'+$status.username+'.'+$domain_only+'/status/'+$status.feed_id+'">'+$status.created_date_duration+'</a></li>\
						'+reply+'\
						'+vote+'\
					</ul>\
	            </div>';
	},
	
	row_current_status: function ($status)
	{
		//console.log($status);
		var remove 		= (profile_username == login_username && $status.username == login_username) ? '<a href="#" class="remove">remove</a>' : '';
		var reply 		= ($status.reply_id > 0) ? '<li class="status_comment"><a href="http://'+$status.username+'.'+$domain_only+'/status/thread/'+$status.thread_id+'">Thread</a></li>' : '';
		var vote		= ($status.username != login_username) ? '<li class="like_it"><a href="#">I like it</a></li><li class="dontlike_it"><a href="#">I dont like it</a></li>' : '';
		var direct_link = ($status.thumbnails == 0 && $status.direct_links != 0 && $status.direct_links != '') ? '<a href="'+$status.direct_links+'">link</a>' : '';
		var thumbnail 	= '';
		
		if (login_first_name && login_last_name)
			var name = login_first_name+', '+login_last_name;
		else if (login_first_name)
			var name = login_first_name;
		else
			var name = $status.username;
	/*
		if ($status.thumbnails && $status.thumbnails != 0)
		{
			var icon = ($status.type == 'video') ? "<span class='videothumb_play_medium'></span>" : '';
			thumbnail  = '<div class="feed_media">';
			$j.each($status.thumbnails, function(key, row) {		
				var image = "<img src='"+row['0']+"' alt='"+$status.type+"' />";
				var link  = (row['1'] != '' && row['1'] != 0) ? row['1'] : '';
				thumbnail +=  link ? "<div><a href='"+link+"'>"+image+"</a>"+icon+"</div>" : "<div>"+image+""+icon+"</div>";
			});			
			thumbnail += '</div>';
		}
	*/
		return '<div class="status_update status_current" id="s'+$status.feed_id+'">\
					<h2 title="'+$status.username+'">'+name+'</h2>\
					'+remove+'\
	                <a href="#" class="reply-to">reply</a>\
					<p>\
					'+feed.parse($status.text)+' '+direct_link+'</p>\
					'+thumbnail+'\
					\
					<ul class="options">\
						<li class="date_duration"><a href="http://'+$status.username+'.'+$domain_only+'/status/'+$status.feed_id+'">'+$status.created_date_duration+'</a></li>\
						'+reply+'\
						'+vote+'\
					</ul>\
	            </div>';
	},
	
	parse: function (text)
	{
		var length = 30;
		var end    = '...';
		
		text = text.replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1' target='_blank'>$1</a>");
		text = text.replace(/@+((?:[A-Za-z0-9]+(?:\.?[-_A-Za-z0-9]+)*){2,255})/ig, "<a href='http://$1."+$domain_only+"'>@$1</a>");

		var div = $j('<div>' + text + '</div>');
		$j(div).find('a').each(function() {
			var link_value = $j(this).html();
			$j(this).html(link_value.substring(0, length)+(link_value.length > length ? end : ''));
		});
		
		var text = div.html();
		
		return text;
	},
	
	limitChars: function (textid, limit, infodiv)
	{
		var text = $j('#' + textid).val();
		var textlength = text.length;
		
		if (textlength > limit) 
		{
			$j('#' + infodiv).text(limit - textlength).css("color", "#f00");
			return false;
		}
		else 
		{
			$j('#' + infodiv).text(limit - textlength).css("color", "#333");
			return true;
		}
	}
}
	
jQuery(function($) {
	feed.parse('newstatus', 140, 'charcount');
	$("#status_new").find('form').submit(function() {
		$(this).find('.white_button_small').attr('disabled', true).val('loading...');
		var post = {
			username: 	login_username ? login_username : 'basit', 
			text: 		$('#newstatus').val() 
		}
		
		if (feed.set_media_id != 0)
			post.media_id = feed.set_media_id;
				
		api.ajax_options.complete = function ()
		{
			$('#status_new').find('.white_button_small').attr('disabled', false).val('save');
			$('#newstatus').focus();
			api.ajax_options.complete = null;
		}
		
		var success_msg = post.media_id ? post.username+' your comment has been added successfully!' : 'iFeed Updated!';
		
		api.feedCreate(post, function(response) {
			api.ajax_response(response, success_msg);
			
			if (response.status_valid == 1) 
			{
				$('#newstatus').val('');
				feed.limitChars('newstatus', 140, 'charcount');
				
				if ($('.status_current').html())
				{
					$('.status_current').remove();
				}
				
				if (!post.media_id)
					$('#status_new').before(feed.row_current_status(response));
			}
			
			$('#status_new').find('.white_button_small').attr('disabled', false).val('save');
			$('#newstatus').focus();
		});
		
		return false;
	});
	
	$('#newstatus').keyup(function() {
		feed.limitChars('newstatus', 140, 'charcount');
	});
	
	$('.status_getmore a').click(function() {
		var more = $(this).html();
		$(this).html('loading...');
		feed.callback_success_list = function(response) {
			$('.status_getmore a').html(more);
		}
		
		feed.get_list($('#action_1').val(), $('#action_2').val(), $('#paging_next').val());
		return false;
	});
	
	$('.new > a.remove').live('click', function() {
		$(this).parents('.status_comments').remove();
		return false;
	});
	
	$('.reply-to').live('click', function(event) {
		feed.reply_box($(this));
		return false;
	});
	
	$(".like_it, .dontlike_it").live("click",  function() {
		feed.vote($(this));
		return false;
	});
	
	$(".favorites").live('click', function(event) {
		event.preventDefault();
		var className = $(this).attr('class');
		$(this).removeClass(className).addClass(className + "_selected");
		return false;
	});
	
	$(".status_update  a.remove").live('click', function(event) {
		feed.remove(feed.getID($(this)));
		return false;
	});
	
	$('#status_comment_new').live('keyup', function() {
		feed.limitChars('status_comment_new', 140, 'status_comment_new_charcount');
	});
	
	$("#status_filter").find('a').click(function() {
		
		$("#status_filter").find('.selected').removeClass('selected');
		
		$(this).addClass('selected');
		
		var selected_value = $(this).attr('rel');
		$('#results_panel, #rows').html('');
		
		if (selected_value == 'ifeed')
		{
			$('#action_1').val('ifeed');
			$('#action_2').val('');
			$('#paging_next').val('20');
			feed.get_list('ifeed', '', 0);
		}
		else if (selected_value == '@')
		{		
			$('#action_1').val('');
			$('#action_2').val('mentions');
			$('#paging_next').val('20');
			feed.get_list('', 'mentions', 0);
		}
		else
		{
			$('#action_1').val('');
			$('#action_2').val(selected_value);
			$('#paging_next').val('20');
			feed.get_list('', selected_value, 0);
		}
		
		
		return false;
	});
	
	$(".status_update").live('status_icons_hide', function() {
			
		$(".like_it").hide();
		$(".dontlike_it").hide();
		$(".favorites").hide();
		$(".reply-to").hide();
		
		$(this).mouseover(function() {
			$(this).find(".reply-to").fadeIn(400);
			$(this).find(".like_it").fadeIn(400);
			$(this).find(".dontlike_it").fadeIn(400);
			$(this).find(".favorites").fadeIn(400);
		//	$(this).css("background-color","#eee");	
		}).mouseleave(function() {
			$(this).find(".reply-to").fadeOut(400);
			$(this).find(".like_it").fadeOut(400);
			$(this).find(".dontlike_it").fadeOut(400);
			$(this).find(".favorites").fadeOut(400);
		//	$(this).css("background-color","#fff");	
		});											 
	}).trigger('status_icons_hide');
	
	$(".feed_media").live('feed_media_extra_hide', function() {
		
		// show more media links
		$(".feed_media").each(function() {
			var i = 0;
			var showLink = false;
			
			$(this).find("div[class!='content_option']").each(function() {
				if (i > 2) 
				{
					$(this).hide();
					showLink = true;
				}
				i++;
			});
			
			if (showLink == true) 
			{
				if (!$(this).find('.content_option').html())
				{
					$(this).append("<div class='content_option'><a href='#'>show all</a></div>");
					// toggle more media links
					$(this).find(".content_option a").toggle(function() {
						
						$(this).parent().parent().find("div[class!='content_option']").each(function() {
							$(this).show();
						});
						
						$(this).text("hide");
						
					}, function() {
						var i = 0;
						
						$(this).parent().parent().find("div[class!='content_option']").each(function() {
							if (i > 2) 
							{
								$(this).hide();
							}
							i++;
						});
						
						$(this).parent().show();
						$(this).text("show all");
					});
				}
			}
		});
	}).
	trigger('feed_media_extra_hide');
});
