(function(jQuery){
    jQuery('#articlelist').empty();

    var base_url = 'http://nicknotned.tumblr.com';
    var rss_url = base_url +'/rss';
    var search_url = base_url +'/api/read/json';
    var max_items = 10;

	var nicknotned = {
		init: function() {
			// drop search on main page
			path_parts = document.location.toString().split('/')
			if (path_parts.length <= 4)
			{
				nicknotned.clearSearch();
			}

			// reload search on other pages
			var search_phrase = jQuery.cookie('__search_phrase');
			if (search_phrase) {
				jQuery('#search-form .query').val(search_phrase);
				jQuery('#clearsearch').show();
				nicknotned.loadArticles('search');
				nicknotned.highlightCurrentPost();
			} else {
				// load rss anyway
				nicknotned.loadRss();
			}

			jQuery('#search-form').bind('submit', function() {
				nicknotned.doSearch(0);
				return false;
			});

			jQuery('#clearsearch').bind('click', function() {
				nicknotned.clearSearch();
				nicknotned.loadRss();
				return false;
			});

			jQuery('#results_pager .next').bind('click', function() {
				var page = jQuery.cookie('__search_page');
				if (!page) {
					page = 0;
				}
				nicknotned.doSearch(page + 1);
				return false;
			});

			jQuery('#results_pager .prev').bind('click', function() {
				var page = jQuery.cookie('__search_page');
				if (!page) {
					page = 0;
				}
				nicknotned.doSearch(page - 1);
				return false;
			});
		},

		cleanPosts: function() {
			return jQuery('#articlelist').empty();
		},

		addPost: function(url, title) {
            jQuery('#articlelist').append('<li><a href="'+ url +'">'+ title +'</a></li>');
		},

		searchProgress: function(in_progress) {
			if (in_progress) {
				jQuery('#search-form .query').css('background-image', 'url("")');
				jQuery('#search-form .indicator').show();
			} else {
				jQuery('#search-form .query').css('background-image', 'url("http://transparentbutcher.com/gawker/images/search_glass.png")');
				jQuery('#search-form .indicator').hide();
			}
		},

		loadRss: function() {
		    jQuery.get(rss_url, function(data, status_text, req) {
		        // adding LI+A elements
				nicknotned.cleanPosts();
		        jQuery('item', jQuery(data)).each(function(i, item) {
		            if (i < max_items) {
		                var post_title = jQuery('title', jQuery(item)).text();
		                var post_url = jQuery('link', jQuery(item)).text();
						nicknotned.addPost(post_url, post_title);
		            }
		        });
				nicknotned.saveArticles('rss');
				nicknotned.highlightCurrentPost();
		    });
		},

		doSearch: function(page) {
			var search_phrase = jQuery('#search-form .query').val();

			params = 'start='+ (page * max_items) +'&search='+ search_phrase +'&num='+ max_items +'&callback=?';
			nicknotned.searchProgress(true);
			jQuery.getJSON(search_url +'?'+ params, function(data) {
				nicknotned.searchProgress(false);
				if (search_phrase != '') {
					jQuery('#clearsearch').show();
				}
				if (data.posts.length > 0)
				{
					nicknotned.cleanPosts();
					jQuery.cookie('__search_phrase', search_phrase, {path: '/', expires: 0});
					jQuery.cookie('__search_page', page, {path: '/', expires: 0});
					for (i in data.posts) {
						post = data.posts[i];
						switch (post.type) {
							case 'link':
								nicknotned.addPost(post.url, post['link-text']);
								break;
							case 'regular':
								nicknotned.addPost(post.url, post['regular-title']);
								break;
						}
					}
					jQuery('#noresults').hide();
					if (data.posts.length == max_items) {
						jQuery('#results_pager .next').show();
					} else {
						jQuery('#results_pager .next').hide();
					}
					if (page > 0) {
						jQuery('#results_pager .prev').show();
					} else {
						jQuery('#results_pager .prev').hide();
					}
				} else {
					if (page == 0) {
						nicknotned.cleanPosts();
						jQuery('#noresults').show();
						jQuery('#results_pager .prev').hide();
					}
					jQuery('#results_pager .next').hide();
				}

				nicknotned.saveArticles('search');
				nicknotned.highlightCurrentPost();
			});
		},

		saveArticles: function(key) {
			var options = {
				key: 'nicknotned._articles.'+ key,
				def: '',
				errorfunc: function() {
					jQuery.cookie('__no_storage', 1, {path: '/', expires: 365});
				}
			}

			jQuery('#list_container').saveit(options);
		},

		loadArticles: function(key) {
			var options = {
				key: 'nicknotned._articles.'+ key
			}
			switch (key) {
				case 'search':
					options.errorfunc = function() {
						jQuery.cookie('__no_storage', 1, {path: '/', expires: 365});
						nicknotned.doSearch(0);
					};
					break;
				case 'rss':
					options.errorfunc = function() {
						jQuery.cookie('__no_storage', 1, {path: '/', expires: 365});
						nicknotned.loadRss();
					};
					break;
			}

			jQuery('#list_container').loadit(options);
		},

		highlightCurrentPost: function() {
	        // if any one of the list is displayed in the main content area, highlight it
	        current_post_id = nicknotned.getCurrentPostId();
	        jQuery('#articlelist a').each(function(i, link) {
	            if (current_post_id == nicknotned.getPostId(link.href)) {
	                jQuery(link).addClass('current');
	            }
	        });
		},

		getCurrentPostId: function() {
			var class_names = jQuery('#article').attr('class');
			if (class_names != undefined) {
				class_names = class_names.split(' ');
				for (var i = 0, l = class_names.length; i < l; i++) {
					if (class_names[i].indexOf('post_') == 0) {
						return class_names[i].substr(5);
					}
				}
			}

			return 0;
		},

		getPostId: function(post_url) {
            var url_parts = post_url.split('/');
            if (url_parts[3] == 'post') {
                return url_parts[4];
            }

            return undefined;
		},

		clearSearch: function() {
			jQuery('#results_pager .next').hide();
			jQuery('#results_pager .prev').hide();
			jQuery('#noresults').hide();
			jQuery('#clearsearch').hide();
			jQuery('#search-form .query').val('');
			jQuery.cookie('__search_phrase', null, {path: '/', expires: 0});
			jQuery.cookie('__search_page', null, {path: '/', expires: 0});
		}
	}

	nicknotned.init();
})(jQuery);

