var default_keywords = 'Search Listings';
var refresh_rate = 180;
var stored_hash = '';

function init () {
	filter = location.hash.length > 1 ? '&filter=' + encodeURI(location.hash.replace('#', '')) : '';
	selling = $.ajax({
		url: '/search/?q=%23selling' + filter, 
		type: 'get',
		cache: false,
		success: function (response) {
    		$('#selling').html((response.length > 0 ? response : '<li class="last">No listings could be found.</li>'));
  		}
	});
	buying = $.ajax({
		url: '/search/?q=%23buying' + filter, 
		type: 'get',
		cache: false,
		success: function (response) {
    		$('#buying').html((response.length > 0 ? response : '<li class="last">No listings could be found.</li>'));
  		}
	});
	$.each($('li', document), function(listing){
		$(this).mouseenter(function(){
			$('a.user-image img', $(this)).fadeOut();
		}).mouseleave(function(){
			$('a.user-image img', $(this)).fadeIn();
		});
	});
}
function hash_check () {
	if (location.hash != stored_hash) {
		stored_hash = location.hash;
		$('#keywords').val(stored_hash.replace('#', ''));
		$('#keywords').css('color', '#000000');
		init();	
	}
}
function filter_submit () {
	location.hash = '#' + $('#keywords').val();
	return false;
}	
function toggle_options (tweet_id) {
	return false;
}
function remove (tweet_id, reference) {
	$.ajax({
		url: '/remove/?tweet_id=' + tweet_id, 
		type: 'get',
		cache: false,
		success: function (response) {
    		if (response == 'removed') {
				$(reference).fadeOut(500, function(){
					$(reference).remove();
				});
			}
  		}
	});
}
$(document).ready(function(){
	setInterval('init()', (refresh_rate * 1000));
	setInterval('hash_check()', 10);
	$('#filter').submit(function(){
		filter_submit();
		return false;
	});
	$('#keywords').val(default_keywords);
	$('#keywords').click(function(){
		if ($(this).val() == default_keywords) {
			$(this).val('');	
			$(this).css('color', '#000000');
		}
	});
	$('#keywords').blur(function(){
		if ($.trim($(this).val()) == '') {
			$(this).val(default_keywords);	
			$(this).css('color', '#AAAAAA');
		}
	});
	$.each($('li.column li'), function(listing){
		$(this).mouseenter(function(){
			$('a.user-image img', $(this)).fadeOut();
		}).mouseleave(function(){
			$('a.user-image img', $(this)).fadeIn();
		});
	});
	$('#post-classitweet').submit(function(){
		if ($.trim($('#classitweet-body').val()).length < 10) {
			$('#classitweet-body').animate('background-color', '#FFBFBF');
			$('#classitweet-body').keyup(function(){
				if ($.trim($(this).val()).length >= 10) {
					$(this).animate('background-color', '#FFFFFF');		
				}
			});
			return false;
		} else {
			return true;	
		}
	});
	// arrangable columns
	$('#toggle-post').click(function(){
		$('#post-classitweet').toggle();
		return false;
	});
});