/**
 * News functions
 */
targetCategory = null;

var total_images = 0; 

//	loadFirebugConsole(); 
 
/**
 * Init common my news page elements
 */
 function initMyNewsCommon() {
	var search_results = '#search_results_widget';
	var search_button = '#search_button';
	var search_text = '#search_text';
	var feed_results = '#news_feed_results_widget';
    
	$(feed_results).hide();
	
	$('#container_3').css('left', $('#ad_widget').css('left'));
	
	$('#add_feed_link').click(function(e) {
		$(this).css('opacity', .7);
		$('#feed_settings_link').css('opacity', 1);
		$('#feed_settings_buttons').hide();
		$('#add_feed_buttons').toggle();
		if ($.browser.msie) {
			if ($('#add_feed_buttons').css("display") == "none") {
				initWidgetResize("#news_options_widget", 150);		
			} else {
				initWidgetResize("#news_options_widget", 220);		
			}
		}		
	});
	$('#feed_settings_link').click(function(e) {
		$(this).css('opacity', .7);
		$('#add_feed_link').css('opacity', 1);
		$('#add_feed_buttons').hide();
		$('#feed_settings_buttons').toggle();
		if ($.browser.msie) {
			if ($('#feed_settings_buttons').css("display") == "none") {
				initWidgetResize("#news_options_widget", 150);		
			} else {
				initWidgetResize("#news_options_widget", 200);		
			}
		}		
	});
	
	$('#add_feed_buttons').hide();
	$('#feed_settings_buttons').hide();
	
	// Next three calls must be in this SPECIFC ORDER to work
	initSearchWidget();
	initWidgetResize(search_results);
	$(search_results).hide();
					 
	initMyClippings();
	initEmailPost();

	$("#news_move_clipping_widget .widget_collapse_up").click(function(e) {
		$("#news_move_clipping_widget .widget_collapse_down").trigger('click');
		e.preventDefault();
		$("#news_move_clipping_widget").hide();
		$("#email_message").val(' ');
	});	


	refreshMyFeedSideBar();
	initWidgetResize("#news_sidebar_feeds");
 }
 
/**
 * Initial Email post functionality
 */
 function initEmailPost()
 {
	$("#email_send").click(function() {
		emailPost();
	});
	
	$("#email_close").click(function() {
		$("#news_email_widget .widget_collapse_up").trigger('click');
	});	
	
	$("#news_email_widget .widget_collapse_up").click(function(e) {
		$("#news_email_widget .widget_collapse_down").trigger('click');
		e.preventDefault();
		$("#news_email_widget").hide();
		$("#email_message").val(' ');
	});	

 }

/**
 * Initialize my clippings
 */
function initMyClippings(showId)
{
	var clippingsUrl = "http://" + window.location.hostname + "/lookabooka_news/user/" + username + "/clippings/";
	var widget_content_id = "#clipping_content";
	
	folderHtml = "";
	clippingHtml = "";
	dropdownHtml = "";

	totalClippingCount = 0;
	totalClippingHtml = "";

	// Get Clippings
	$.getJSON(
		clippingsUrl,
		function(clippings)
		{
			// Build Folder/Clipping Hierarchy
			buildClippingTree(clippings, "");
			
			$("#move_clipping_dropdown").html(dropdownHtml);
			$("#my_clippings_tree").html(folderHtml);
			$(widget_content_id).html(clippingHtml);

//			console.log("move folder");

			safariHack();
//			console.log("end");

			$(".folderToggle").bind
			(
				"click",
				function()
				{
					$(this).siblings(".treeChild").toggle();

					if ($(this).children("img").attr("src") == "/images/folderExpand.gif")
					{
						$(this).children("img").attr("src", "/images/folderCollapse.gif")
					}
					else
					{
						$(this).children("img").attr("src", "/images/folderExpand.gif")
					}
					initWidgetResize('#news_sidebar_feeds');				
					return false;
				}
			);

			$(".treeFolder").bind
			(
				"click",
				function()
				{
					var feed_widget_id = "#news_feed_results_widget";
					
					$("#search_results_widget, .news_main_content, .folderClippings, #my_news_recommended, #feed_content").hide();
					$(feed_widget_id).show();
					
					$("#" + $(this).attr("target")).show();

					imagesCallBack(widget_content_id);

					return false;
				}
			);

			$(".clippingToggle").bind
			(
				"click",
				function()
				{
					
					$(this).parent().siblings(".clippingDisplay").toggle();

					if ($(this).children("img").attr("src") == "/images/clippingExpand.gif")
					{
						$(this).children("img").attr("src", "/images/clippingCollapse.gif")
					}
					else
					{
						$(this).children("img").attr("src", "/images/clippingExpand.gif")
					}
					
					imagesCallBack(widget_content_id);

					return false;
				}
			);

			$('.delete_clipping').click
			(
				function(e)
				{
					e.preventDefault();
					
					var url = 'http://' + window.location.hostname + '/lookabooka_news/user/' + username + '/clippings/';

					var showId = "#" + $(this).parents(".folderClippings").attr("id");
					$.post
					(
						url,
						{ "unclip":$(this).attr("target") },
						function(msg)
						{
							setTimeout("initMyClippings(\"" + showId + "\")", 2000);
						}
					);
				}
			);

			$('.email_post').click(function(e) {
				var subject = $(this).parent().parent().children("h3:first").text();
				$("#email_subject").val(subject);
				e.preventDefault();
				
				$("#news_email_widget").show().css({
					'top': '-100px',
					'left': '-400px',
					'z-index': 100
				});
				
				$("#post_id").val($(this).attr("target"));
			});

			$('.move_clipping').click
			(
				function(e)
				{
					e.preventDefault();

					$("#move_clip_id").val($(this).attr("target"));

					$("#news_move_clipping_widget").show().css({
						'top': '-100px',
						'left': '-400px',
						'z-index': 100
					});
				}
			);


			if (showId)
			{
				$(showId).show();
			}
		});
}

/**
 * Build one level of Clippings Tree
 */
function buildClippingTree(clippings, level)
{
	if (!clippings.id)
	{
		for (var i = 0; i < clippings.length; i++)
		{
			buildClippingNode(clippings[i], level)
		}
	}
	else
	{
		buildClippingNode(clippings, level)
	}

	return;

}

/**
 * Build one node of Clipping Tree
 */
function buildClippingNode(node, level)
{

	folderHtml += "<li>";

	if (node.children)
	{
		var clippingCount = buildClippingDisplay(node);

		folderHtml += "<a href=\"#\" class=\"folderToggle\"><img src=\"/images/folderExpand.gif\"></a><a href=\"#\" class=\"treeFolder\" target=\"folder" + node.id + "\">" + node.name + " (" + (node.id == "MYC" ? totalClippingCount : clippingCount) + ")</a>";
		dropdownHtml += "<option value=\"" + node.id + "\">" + level + node.name + "</option>";

		folderHtml += "<ul class=\"treeChild\">";
		buildClippingTree(node.children, level + "--");
		folderHtml += "</ul>";
	}
	else
	{
		var clippingCount = buildClippingDisplay(node);

		folderHtml += "<a href=\"#\" class=\"treeFolder noCollapse\" target=\"folder" + node.id + "\">" + node.name + " (" + (node.id == "MYC" ? totalClippingCount : clippingCount) + ")</a>";
		dropdownHtml += "<option value=\"" + node.id + "\">" + level + node.name + "</option>";
	}

	folderHtml += "</li>";

	return;
}

/**
 * Build one panel of Clipping Display
 */
function buildClippingDisplay(node)
{
	var clippingCount = 0;

	if (node.item)
	{
		clippingHtml += "<div id=\"folder" + node.id + "\" class=\"folderClippings\">";
		clippingHtml += "<a name=\"top\" style=\"cursor: pointer;\"/>";
		clippingHtml += "<h5>" + node.name + "</h5>";
		clippingHtml += "<ul>";

		for (var i = 0; i < node.item.length; i++)
		{
			totalClippingCount++;
			clippingCount++;

			var news_item = node.item[i];

			var title = 'No title';
			if (news_item.title._text) {
				 title = '<h3><a href=\"#\" class=\"clippingToggle\"><img src=\"/images/clippingExpand.gif\"></a>' + news_item.title._text + '</h3>';
			 }
				
			var description = new String();
			if (news_item.description._text) {
				description = '<div class=\"clippingDisplay\">' + news_item.description._text + '</div>';
				description = description.replace(/<script((\n|.)(?!(script>)))*\/script>/gi, '');
			} else {
				description = "<div class=\"clippingDisplay\">No description available.</div>";
			}
			
			
			var link = '<div><a target="_blank" href="' + news_item.link._text + '">Keep reading</a>  <img class="readmore_arrow" src="/images/readmore_arrows.gif" /></div>';
			if (news_item.ng_modifiedDate) {
				var date = '<div style="font-weight: bold">' + news_item.ng_modifiedDate._text + '</div>';
			} else if(news_item.pubDate) {
				var date = '<div style="font-weight: bold">' + news_item.pubDate._text + '</div>';	
			} 
			
			clippingHtml += '<li class="news_article">' + title + date + description + getUserActionsHtml(news_item.ng_postId._text, "clipping") + link + '</li>';
			
			// Keep track of all clippings for root directory
			if (node.id != "MYC")
			{
				totalClippingHtml += '<li class="news_article">' + title + date + description + getUserActionsHtml(news_item.ng_postId._text, "clipping") + link + '</li>';
			}
		}

		// All clippings show in root directory
		if (node.id == "MYC")
		{
			clippingHtml += totalClippingHtml;
		}
		
		clippingHtml += "</ul>";


		clippingHtml += "</div>";
	}
	else
	{
		clippingHtml += "<div id=\"folder" + node.id + "\" class=\"folderClippings\">";
		clippingHtml += "<a name=\"top\" style=\"cursor: auto;\"/>";
		clippingHtml += "<h5>" + node.name + "</h5>";
		clippingHtml += "There are no clippings in this folder.";
		clippingHtml += "</div>";
	}

	if (node.id == "MYC")
	{
		clippingHtml += totalClippingHtml;
		returnCount = totalClippingCount;
	}
	else
	{
		returnCount = clippingCount;
	}

	return returnCount;
}



/**
 * Initialize my news page
 */ 
 function initMyNews() {	
//	var domain = 'http://' + window.location.hostname + '/';		
//	var my_news_recommended_url = domain + 'lookabooka_news/recs?s=0&c=10';	
//	var total_feed_count = '';
//	var current_page = 0;
//	var feed_id = 'rec';
	var widget_content_id = '#my_news_recommended';
//	var feed_type = 'recommended feed';
	

	initMyNewsCommon();

	var category = 'Headline News';
	displayLatestNewsCategory(category, widget_content_id, 500);

	//getNewsFeed(my_news_recommended_url, widget_content_id, feed_id, current_page, total_feed_count, feed_type);
	
	
 }
 
/**
 * Displays the categories in Browse Categories section 
 * Utilizes taxonomy
 * GET /taxonomy
 */
 function displayTaxonomy() {
	var url = 'http://' + window.location.hostname + '/lookabooka_news/taxonomy';
		
	$.getJSON(url, function(result) {		
		var taxonomy = result.taxonomy;
		if(taxonomy && taxonomy.children.length > 0) {
			
			var categories = taxonomy.children[0].children;
			
			var content = "<ul>";
			for (var index = 0; index < categories.length; index++) {
				var category = categories[index];
				content = content + "<li><a href='#'><img src='" + category.faviconURL + "'/>" + category.text + "</a></li>";
			}
			content += "</ul>";
			$('#my_categories').append(content);
		} 
	}); 
	 	
 } 
  
 
/**
 * Initialize my feeds page
 * http://lookabooka.com/social/news_smart_feeds.php
 * Add Keyword Subscription (SmartFeed)
	Input x-www-form-urlencoded parameters
		POST /subs/<username>/ 
		 keyword - word to search for in subscription
		 folderId - id of the folder to put the subscription in
		 customTitle - custom title for the keyword feed
	Output
		{"ng_id": <NewsGator feed ID>}    
 */ 
 function initSmartFeeds() {
	 
	var url = 'http://' + window.location.hostname + "/lookabooka_news/subs/" + username + "/";	
	
	initMyNewsCommon();	
 } 
 
/**
 * Get source content of my folders
 */ 
 function getMyFoldersJSON() {
	 if (!username) {
		 var url = 'http://' + window.location.hostname + "/lookabooka_news/folders/" + username + "/MYF";
		 $.getJSON(url, function(myFolders) {		 
			return myFolders;	 
		 });
	 }
 }
     
/**
 * Initialize all news page
 */ 
 function initAllNews() {
	 
	var search_results = '#search_results_widget';
	var category = 'Headline News';
	var news_headlines_id = '#news_headlines';
	
	initSearchWidget();	
	initWidgetResize(search_results);
	
	$(search_results).hide();
	displayLatestNewsCategory(category, news_headlines_id, 500);
	getCategoryLinks();

	initEmailPost();
 } 

/**
 * Retrieves the Category news links from the passed in url parameter,
 * then formats the data and inserts it into the Categories(left) column widget.
 */
function getCategoryLinks() {	
	var url = 'http://' + window.location.hostname + '/lookabooka_news/syssubs';
	
	$.getJSON(url, function(news_data){
		// $.dump(news_data);
		var news_feed = news_data.subscriptions.children;
		var category_widget = $('#left_column');
		
		$(category_widget).html('');
		for(category=0; category < news_feed.length; category++) {
			var feedCategory = news_feed[category];
			if(feedCategory.children && feedCategory.children.length > 0) {
				var news_feed_category = "<li><h5><a href='#' class='category_title'>" 
										  + feedCategory.text + "</a></h5>";
				news_feed_category += "<ul>";
			
			
				var feedElements = feedCategory.children;					
				var feed_index;					
				for (feed_index=0; feed_index < feedElements.length; feed_index++) {					
					var feed = feedElements[feed_index];
					var feed_id = feed['ng:id'];
					var news_link = '<li><img class="favicon" src="' + feed.faviconUrl + '" /><a id="' + feed_id + '" feed_count="' + feed["ng:unreadCount"] + '" href="' + feed.htmlUrl  + '">' + feed.title + '</a> (' + 
								feed["ng:unreadCount"] + ')</li>\n';
					news_feed_category += news_link;
				}
			
				news_feed_category += "</ul></li>";
				$(category_widget).append(news_feed_category);	
			}
				
		}
		$('.favicon').error(function() {
			$(this).attr('src', '/images/feed-icon16x16.png');
		});
		$(category_widget).children("li:has(ul)").click(function(e) {
			var category = $(this);
			
			category.children('ul').slideToggle();
		});					
		//$("#left_column").accordion({autoHeight: false});
		
		$('#left_column li ul li a').click(function(e) {
			$('#left_column ul li a').removeClass('clicked');
			$(this).addClass('clicked');

			e.preventDefault();
			e.stopPropagation();			

			// Refresh Ad Widget
			refreshAdWidget();

			var current_page = 0;
			var feed_id = $(this).attr('id');			
			var feed_count = $(this).attr('feed_count');
			var domain = 'http://' + window.location.hostname + '/';
			var feed_url = domain + 'lookabooka_news/feed/' + feed_id + '?s=0&c=6';  //global var set at the top
							
			$('body').css('cursor', 'wait');
			if ($('.news_main_content').css('display') == 'none') {			
				$('#search_results_widget').fadeOut('fast');
				$('.news_main_content').show();			
			}				
			getNewsFeed(feed_url, '#main_content', feed_id, current_page, feed_count);
		});
		
		$('#left_column .category_title').click(function(e) {
			initWidgetResize('#news_sidebar_feeds');
		});
		
		
		
		
   		$(".accordion").accordion({ clearStyle: true, autoHeight: false, 'active':false, 'alwaysOpen':false});
		$(".accordion").accordion("activate", true);
	    
		$(".accordion li").click(function(e){			
			e.preventDefault();											
			targetCategory = $(this);				
		});				
	
		
		//initWidgetResize('#news_headline_categories');	
		
		accordion_resize("#news_headline_categories");
		$("a[href='#']").click(function(e) {
			e.preventDefault();
		});
		
		
		
   		$('#left_column .spinner').hide();
				
	
	});
} 
  
/**
 * Initialize latest news page specific functionality
 */
function initLatestNews() {
	// Initializations
	initLatestNewsMenu();

	var search_results = '#search_results_widget';
	var latest_news = '#latest_news';
	initSearchWidget();
	initWidgetResize(search_results);
	initWidgetResize(latest_news);	
	$(search_results).hide();

	initEmailPost();

}
 
 /**
  * Initialize the latest news category listing
  * URL - lookabooka_news/folder/lookabooka/MYF/
  */
function initLatestNewsMenu()
{
	var url = 'http://' + window.location.hostname + '/lookabooka_news/syssubs';

	$.getJSON
	(
		url,
		function(categories)
		{
			for (var i = 0; i < categories.subscriptions.children.length; i++)
			{
				if (typeof(categories.subscriptions.children[i].children) != "undefined")
				{
					if (categories.subscriptions.children[i].children.length > 0)
					{
						htmlId = categories.subscriptions.children[i].text.replace(/[^a-zA-Z0-9]+/g,'').toLowerCase();
						$("#menu").append("<li class=\"button_197\"><a id=\"" + htmlId + "\" href=\"#\">" + categories.subscriptions.children[i].text + "</a></li>");

						$('#' + htmlId).click(function() {
							$("#menu li a").removeClass("clicked");
							$(this).addClass("clicked");
							
							// Refresh Ad Widget
							refreshAdWidget();

							$('body').css('cursor', 'wait');

							if ($('.news_main_content').css('display') == 'none') {			
								$('#search_results_widget').fadeOut('fast');
								$('.news_main_content').show();			
							}				

							displayLatestNewsCategory($(this).text(), "#latest_news");
							return false;
						});
					}
				}
			}

			initWidgetResize("#latest_news_options");
			$("#menu li a:first").trigger("click");

		}
	);
}

 /**
  * Get the latest news from a category and display it in the passed in widget content area
  * URL - lookabooka_news/syssubs/Book%20News
  */
 function displayLatestNewsCategory(category, widget_id, category_widget_height, current_page, feed_count) {
	var itemsPerPage = 6;
	$(widget_id + " .spinner").show();

	if (!category_widget_height) {
		category_widget_height = 500;
	}

	if (!current_page) {
		current_page = 0;
	}	

	var pageUrl = "?s=" + current_page*itemsPerPage + "&c=" + itemsPerPage;;

	if (/\?/.test(category))
	{
		categoryUrl = category.split("?");
		category = categoryUrl[0];		
	}


	var host = window.location.hostname;	
	var domain = 'http://' + host + '/lookabooka_news/';
	var url = domain + 'syssubs/' + escape(category).replace(/amp\%3B+/g,'') + pageUrl;
	
	// For testing against Gordon's server since production server is faulty	
	//url = 'http://ec2-75-101-236-79.compute-1.amazonaws.com/syssubs/' + category;		
	
	$.getJSON(url, function(news) {
		var category_title = "<h5>" + category + "</h5>";						
		var news_content = category_title + "<ul>";
		var content = $(widget_id + ' .widget_inner_content');
		var count = 0;

		content.html("");

		for (var i = 0; i < 6; i++) {				
			var news_title = '<h3>' + news.items[i].title._text + '</h3>';
			var news_feed = (typeof(news.items[i].feedName) != "undefined" ? '<div style="font-style: italic">Feed Source: ' + news.items[i].feedName + '</div>' : "");
			var news_date = '<div style="font-weight: bold">' + news.items[i].pubDate._text + '</div>';
			var description = new String();
			description = "<div>" + news.items[i].description._text + "</div>";
			//console.log(description);
			description = description.replace(/<script((\n|.)(?!(script>)))*\/script>/gi, '');
			//console.log('==================Updated===================');
			//console.log(description);
			
			var user_actions = '';
			if (username) {
				user_actions = getUserActionsHtml(news.items[i].ng_postId._text);
			}

			
			var more_link = '<div><a href="' + news.items[i].link._text + '" style="font-variant: small-caps;" target="_blank">keep reading</a> <img class="readmore_arrow" src="/images/readmore_arrows.gif" /></div>';
			news_content = news_content + '<li class="news_article">' + news_title + news_feed + news_date + description + user_actions  +more_link + '</li>';
		}

		content.append(news_content + "</ul>");
		
		if (username) {
			addUserEventHandlers();
		}


		if (!feed_count) {
			feed_count = news.itemCount;
		}

		var page_count = Math.ceil(feed_count/6);

		if (page_count > 1) {
			
			/** 
			 * reference to call: getFeedPaginationLinks(feed_url, feed_id, current_page, feed_count)
			 * Without creating a new pagination function, we can modify the parameters for getFeedPaginationLinks
			 * to meet our needs.
			 */
			pagination = getFeedPaginationLinks('n/a', 'n/a', current_page, feed_count);
			content.append(pagination);

			$('#pagination_links a').click(function(e) {
				e.preventDefault();
				var current_page = $(this).text();				
				var feed_count = $(this).attr('feed_count');					
				$('body').css('cursor', 'wait');
				
				displayLatestNewsCategory(category, widget_id, category_widget_height, current_page-1, feed_count);
			});

		}
				
		var widget_content_id = '#' + $(content).attr('id');		
		$(widget_id + " .spinner").hide();

		total_images = 0;
		
		/** 
		 * Performs checks on the images that load and handles errors and oversize
		 */
		imagesCallBack(widget_content_id);
		
		widget_resize(widget_id);
	});	
		 
 }
 
/**
 * Get the search result data and display it the passed in widget content area
 * URL - GET /search?q=<search terms>&s=<startindex>&c=<number of items>
 */
 function displaySearchResults(url, widget_content_id) {
	 
 }
  
/**
 * Init search widget hover/hide states;
 */
function initSearchWidget() {
	var host = 	window.location.hostname;	
	var domain = 'http://' + host + '/lookabooka_news/';
	 
	var search_button = '#search_button';
	var search_text = '#search_text';
	var search_results_id = 'search_results';
	var search_results_content = '#search_results';
	var search_results_widget = '#search_results_widget';
	
	$('.search_header_text').click(function() {		
		$('.search_header_text').removeClass('text_clicked');
		$(this).addClass('text_clicked');	
	});
		
	$('#news_options_widget form').submit(function(e) {
		return false;
	});
	
	$(search_button).click(function(e) {
		
		fadeInSearchResults();				
				
		if($('.text_clicked').html() == 'News') {			
			var search_value = $(search_text).val();		
			
			var search_string = domain + 'search?q=' + $('<div/>').text(search_value).html() + '&s=0&c=6';
			
			$('body').css('cursor', 'wait');
			$(search_text).css('cursor', 'wait');
			getNewsSearch(search_string, search_results_content, search_value);
				
		} else {			
			var search_value = $(search_text).val();			
			
			// searchControl is a global var
			searchControl.draw(document.getElementById(search_results_id), options);			
			searchControl.execute(search_value);
			$(search_results_widget + ' .spinner').remove();

			initWidgetResize(search_results_widget);			
			$('.gsc-tabHeader').click(function() {			
				initWidgetResize(search_results_widget);
			});
		}		
		$(search_text).val('');
		return false;
	});
	
	$(search_text).one('click', function(){		
			$(this).val('');
	}).keypress(function(e) {
			if(window.event && e.keyCode == 13) { // IE
				// No need to trigger any events since by default the submit/button will be hit;
				fadeInSearchResults();		
			} else if(e.which == 13) { // Netscape/Firefox/Opera				
				fadeInSearchResults();
			}
	});					
}


/**
 * Fade out other widgets and fade in search results widget
 */
 function fadeInSearchResults() {			
	$('.news_main_content').hide();					 
	$('#search_results_widget').fadeIn('slow');
 }

/**
 * Init google search
 */
 
// Search key for localhost (lookabooka)

function initGoogleSearch(search_box_id, content_id) {
//<![CDATA[	
	google.load('search', '1.0');
	
	function OnLoad() {
		
		// create a search control
		searchControl = new google.search.SearchControl();
		searchControl.setSearchCompleteCallback(this, lookabookaGoogleCallback);		
		// create a draw options object so that we can position the search form root
		options = new google.search.DrawOptions();
		options.setSearchFormRoot(document.getElementById(search_box_id));
		options.setDrawMode(google.search.SearchControl.DRAW_MODE_TABBED);
		
		// populate with searchers
		searchControl.addSearcher(new google.search.WebSearch());
		searchControl.addSearcher(new google.search.VideoSearch());
		//searchControl.addSearcher(new google.search.BlogSearch());
		
		searchControl.draw(document.getElementById(content_id), options);
	
	}
	
	google.setOnLoadCallback(OnLoad, true);	
//]]>	
}

/**
 * Callback function for search results
 */
 function lookabookaGoogleCallback() {	 
	$('.gsc-trailing-more-results').remove();
 }
 


/**
 * Retrieves the JSON data from the url parameter and formats the content.
 * This content is placed in the "News Headlines" widget.
 */
function getNewsSearch(url, widget_content_id, search_term, current_page, search_count) {
		
	var widget_content = $(widget_content_id);
	
	if (!current_page) {
		current_page = 0;	
	}
	
	$.getJSON(url, function(news) {
		// First time search we want to get search count so recursive calls can reference
		//console.log(news);
		search_count = news.rss.channel.itemCount;		
		
		if (search_count != 0) {
			
			var news_feed = news.rss.channel.item;
			var category_title = "<h5>" + news.rss.channel.title._text + "</h5>";				
			var news_links = category_title + "<ul>";
			
			var num_pages = Math.ceil(search_count/6);								
			var pagination;
			var domain = 'http://' + window.location.hostname + '/lookabooka_news/';
			
			if(num_pages > 1) {				
				pagination = getSearchPaginationLinks(search_term, current_page, search_count);								
			} 
			//	$.dump(news_feed);			
		
			for(item_index=0; item_index < news_feed.length; item_index++) {
				var news_item = news_feed[item_index];
				var title = 'No title';
				if (news_item.title._text) {
					 title = '<h3>' +  widget_content.text(news_item.title._text).html() + '</h3>';
				 }
					
				var description = new String();
				if (news_item.description._text) {
					description = '<div>' + news_item.description._text + '</div>';
					description = description.replace(/<script((\n|.)(?!(script>)))*\/script>/gi, '');
				} else {
					description = "No description available.";
				}
				
				
				var link = '<div><a target="_blank" href="' + widget_content.text(news_item.link._text).html() + '">Keep reading</a>  <img class="readmore_arrow" src="/images/readmore_arrows.gif" /></div>';
				if (news_item.ng_modifiedDate) {
					var date = '<div style="font-weight: bold">' + news_item.ng_modifiedDate._text + '</div>';
				} else if(news_item.pubDate) {
					var date = '<div style="font-weight: bold">' + news_item.pubDate._text + '</div>';	
				} 
				var user_actions = '';
				if (username) {
					user_actions = getUserActionsHtml(news_item.ng_postId._text);	
				}
				news_links = news_links + 
							'<li class="news_article">' + title + date + description + user_actions + link + '</li>';
							
			}

			news_links += "</ul>";
			if (pagination) {
				news_links += pagination;
			}
			widget_content.html(news_links);
						
			if (username) {
				addUserEventHandlers();	
			}
						
			total_images = 0;
			
			var widget_container_id = '#search_results_widget';
			
			/** 
			 * Performs checks on the images that load and handles errors and oversize
			 */
			imagesCallBack(widget_content_id);
			
			$(widget_content_id).hide();
			

								
			$(widget_content_id + " [align]").removeAttr('align');
			if(pagination) {
				$('#search_pagination_links a').click(function(e) {						
					e.preventDefault();
					var current_page = $(this).text();
					current_page -= 1;
					
					var search_term = $(this).attr('id');
					var search_count = $(this).attr('search_count');						
					var search_url = $(this).attr('url');					
					$('body').css('cursor', 'wait');
					
					getNewsSearch(search_url, widget_content_id, search_term, current_page, search_count);	
					initWidgetResize(widget_container_id);
				});
			}
			
			
			
		} else {
			widget_content.append("<h5>No results found. Please enter a new search.</h5>");	
		}
				
		
		$('body').css('cursor','auto');
		$('#search_text').css('cursor', 'auto');
	});
}

/**
 * Image callback function
 */
function imagesCallBack(widget_content_id) {
	var widget_width = 460;
	var embed_width = 450;
	
	$(widget_content_id + ' img').error(function() {			
		initWidgeResizePreload(widget_content_id);
	});		

	$(widget_content_id + ' img').load(function() {
		if ($(this).css('width') > widget_width || $(this).attr('width') > widget_width) {
			$(this).wrap("<div class='overflow_container' style='clear:both;' ></div>");
		}
		$('body').css('cursor', 'wait');
		initWidgeResizePreload(widget_content_id, true);
	});			
			
	$(widget_content_id + ' embed').load(function() {
		if ($(this).css('width') > embed_width || $(this).attr('width') > embed_width) {
			$(this).wrap("<div class='overflow_container'  style='clear:both;' ></div>");
		}
		$('body').css('cursor', 'wait');
		initWidgeResizePreload(widget_content_id, true);
	});			
	
	if ($(widget_content_id + ' img').length == 0 || $(widget_content_id + ' embed').length == 0) {			
		
		$('body').css('cursor', 'wait');
		initWidgeResizePreload(widget_content_id, true);
	}
	//converting flash and videos to correct size
	if ($('embed').attr('width') > 450){
		$('embed').attr('width', 450);	
	}	
	if($('object').attr('width') > 450){
		$('object').attr('width', 450);	
	}	
	
	safariHack();	
	
}

/**
 * Community Version of image callback function
 */
function imagesCallBackCommunity(widget_content_id)
{
	var widget_width = 460;
	var embed_width = 450;
	
	$(widget_content_id + ' img').error(function() {			
		initWidgeResizePreload(widget_content_id);
	});		

	$(widget_content_id + ' img').each(function() {
		if ($(this).css('width') > widget_width || $(this).attr('width') > widget_width) {
			$(this).wrap("<div class='overflow_container' style='clear:both;' ></div>");
		}
		$('body').css('cursor', 'wait');
		initWidgeResizePreload(widget_content_id, true);
	});			
			
	$(widget_content_id + ' embed').each(function() {
		if ($(this).css('width') > embed_width || $(this).attr('width') > embed_width) {
			$(this).wrap("<div class='overflow_container'  style='clear:both;' ></div>");
		}
		$('body').css('cursor', 'wait');
		initWidgeResizePreload(widget_content_id, true);
	});			
	
	if ($(widget_content_id + ' img').length == 0 || $(widget_content_id + ' embed').length == 0) {			
		
		$('body').css('cursor', 'wait');
		initWidgeResizePreload(widget_content_id, true);
	}
	//converting flash and videos to correct size
	if ($('embed').attr('width') > 450){
		$('embed').attr('width', 450);	
	}	
	if($('object').attr('width') > 450){
		$('object').attr('width', 450);	
	}	
	
	safariHack();	
}

/**
 * Returns html that allows users to perform actions on feeds, such as email or clip them.
 */
function getUserActionsHtml(feed_id, mode, read) {
	if (!mode)
	{
		mode = "default";
	}
	
	if (!read)
	{
		read = "False";
	}

	var mark_read_unread = "";
	var add_to_clipping = ""

	if (mode != "clipping")
	{
		mark_read_unread = "<a  target='" + feed_id + "' href='#' class='" + (read == "False" ? "mark_read" : "mark_unread") + "'>" + (read == "False" ? "Mark as Read" : "Mark as Unread") + "</a>";
		add_to_clipping = "<a  target='" + feed_id + "' href='#' class='add_clipping'>Add to clippings</a>";	
	}

	var email_post = "<a  target='" + feed_id + "' href='#' class='email_post'>Email post</a>";

	var delete_clipping = "";
	var move_clipping = "";

	if (mode == "clipping")
	{
		delete_clipping = "<a  target='" + feed_id + "' href='#' class='delete_clipping'>Remove clipping</a>";
		move_clipping = "<a  target='" + feed_id + "' href='#' class='move_clipping'>Move clipping</a>";
	}

	var user_actions = "<div style='float: left; overflow: hidden; width: 500px;'>" + mark_read_unread + add_to_clipping + email_post + delete_clipping + move_clipping + "</div>";
	return user_actions;
}

/**
 * Create the page links for the search results
 * URL - GET /search?q=<search terms>&s=<startindex>&c=<number of items>
 */
 function getSearchPaginationLinks(search_term, current_page, results_count) {	
	var num_pages = Math.ceil(results_count/6);
	var search_url = 'http://' + window.location.hostname + '/lookabooka_news/search?q=' + search_term;
	var first_page = (current_page - 3) < 0 ? 0 : current_page - 3;
	var last_page = (current_page + 3) > num_pages ? num_pages : current_page + 3;
	var pagination = "<div id='search_pagination_links'>";
	var index_page;
	
	// If we no longer can see the first page, indicate more pages if you go back
	if (first_page != 0) {
		pagination += "... ";	
	}
				
	for (index_page = first_page; index_page < last_page; index_page++) {
		var page = index_page + 1;
		if(index_page != current_page) {
			var page_name = window.location.pathname;
			var page_name = page_name.substring(page_name.lastIndexOf('/')+1);
			var search_link = "<a id='" + search_term + "' search_count='" + results_count + "' href='" + page_name + "#top' url='" + search_url + "&s=" + (index_page*6) + "&c=6'>" + page + "</a>";
			pagination += search_link;
		} else {
			pagination += page;
		}
		
		// Create page delimiter
		if((index_page + 1) != last_page) {
			pagination += ' | ';
		}
	}
	
	// If we haven't reached the last page, then indicate there's more
	if (last_page != num_pages) {
		pagination += " ...";
	}
	
	pagination += "</div>";
	return pagination;			 
 }



/**
 * Retrieves the JSON data from the url parameter and formats the content.
 * This content is placed in the "News Headlines" widget.
 */
function getNewsFeed(url, widget_content_id, feed_id, current_page, feed_count, feed_type) {
	document.body.style.cursor = "wait";
	$('.widget_content').css('cursor', 'wait');
	$('a').css('cursor', 'wait');
	$('.buttons_list li').css('cursor', 'wait');
	$('.buttons_list li a').css('cursor', 'wait');
	
	var feed_url = 'http://' + window.location.hostname + '/lookabooka_news/';
	var widget_content = $(widget_content_id);
	
	if (!feed_count) {
		feed_count = 1;	
	}
	
	if (!current_page) {
		current_page = 0;
	}
	
	if (feed_type == 'user feed') {
		url = url + "&u=" + username;
		feed_url = feed_url + 'feed/' + feed_id;
	} else if(feed_type == 'recommended feed') {
		feed_url = feed_url + 'recs';
	} else {
		feed_url = feed_url + 'feed/' + feed_id;
	}
	
	widget_content.ajaxError
	(
		function(event, request, settings)
		{			
			widget_content.html("<h5>Could not retreive feed data. Please click the refresh button in your browser to try again.</h5>If errors persist, please contact the site administrator.");
			initWidgeResizePreload(widget_content_id, true);
		}
	);

	$.getJSON(url, function(news) {
		
		var news_feed = news.rss.channel.item;
		var category_title = "<h5>" + news.rss.channel.title._text + "</h5>";
		var news_links = '<a name="top"></a>' + category_title + "<ul>";

		var widget_container_id = $(widget_content_id).parents('.news_main_content').attr('id');
		
		 // This check is needed in the next var assignment
        
		if (news.rss.channel.itemCount) {
            feed_count = news.rss.channel.itemCount;    
        }
		var num_pages = Math.ceil(feed_count/6);								

		
		

		var pagination = '';
		// Get count
		if (news.rss.channel.itemCount) {
			feed_count = news.rss.channel.itemCount;	
		}		
		var num_pages = Math.ceil(feed_count/6);								
				
			
		
		if (num_pages > 1) {
			 pagination = getFeedPaginationLinks(feed_url, feed_id, current_page, feed_count);
		} 
		//	$.dump(news_feed);
		widget_content.html('');

		if (feed_count < 1)
		{
			widget_content.html("<h5>Could not retreive feed data. Please click the refresh button in your browser to try again.</h5>If errors persist, please contact the site administrator.");
			initWidgeResizePreload(widget_content_id, true);
		}
		else
		{
			for(item_index=0; item_index < news_feed.length; item_index++) {
				var news_item = news_feed[item_index];
				
				var news_read = news_item.ng_read ? news_item.ng_read._text : "False";

				var title = '<h3' + (news_read == "False" ? "" : " class=\"read\"") + '>' +  widget_content.text(news_item.title._text).html() + '</h3>';
				var description = new String();
				description = news_item.description._text;
				if (description) {							
					description = description.replace(/<script((\n|.)(?!(script>)))*\/script>/gi, '');
				} else {
					description = '';
				}				
							
				description = '<div>' + description + '</div>';
				var link = '<div><a target="_blank" href="' + widget_content.text(news_item.link._text).html() + '">Keep reading</a> >></div>';
				if (news_item.ng_modifiedDate) {
					var date = '<div style="font-weight: bold">' + news_item.ng_modifiedDate._text + '</div>';
				} else if(news_item.pubDate) {
					var date = '<div style="font-weight: bold">' + news_item.pubDate._text + '</div>';	
				}
				
				var user_actions = '';
							
				if (username) {
					user_actions = getUserActionsHtml(news_item.ng_postId._text, "default", news_read);
				}
				news_links = news_links + 
							'<li class="news_article">' + title + date + description + user_actions + link + '</li>';
			}
							
			news_links += "</ul>";
			if (pagination) {
				news_links += pagination;
			}
			
			var finished_writing = widget_content.html(news_links);
			
			/** 
			 * Performs checks on the images that load and handles errors and oversize
			 */
			 
			
			imagesCallBack(widget_content_id);		
			
					
			$(widget_content_id + ' ul li div').css('float', 'none');
			$(widget_content_id + ' [align]').removeAttr('align');
			$(widget_content_id + ' a:has(img)').css('float', 'none');		
			
			if (finished_writing) {
				if (username) {
					addUserEventHandlers();	
				}
				
				if (pagination) {
					$('#pagination_links a').click(function(e) {
						e.preventDefault();					
						var current_page = $(this).text();										
						var feed_id = $(this).attr('id');
						var feed_count = $(this).attr('feed_count');						
						var feed_url = $(this).attr('url');				
							
						$('body').css('cursor', 'wait');
						
						getNewsFeed(feed_url, widget_content_id, feed_id, current_page-1, feed_count, feed_type);					
					});
				}					
			}
			
		}

		$('body').css('cursor','auto');
		$('#search_text').css('cursor', 'auto');
				
		
		document.body.style.cursor = "auto";
	$('.widget_content').css('cursor', 'auto');
	$('a').css('cursor', 'pointer');
	$('.buttons_list li').css('cursor', 'auto');
	$('.buttons_list li a').css('cursor', 'pointer');
		
	});
}

/**
 * Adds the event handlers for user's actions such as emailing, adding to clips etc
 */
function addUserEventHandlers() {
	$('.add_clipping').click(function(e) {
		e.preventDefault();
		addClip($(this).attr('target'));	
	});
	
	$('.email_post').click(function(e) {
		var subject = $(this).parent().parent().children("h3:first").text();
		$("#email_subject").val(subject);
		e.preventDefault();
		
		$("#news_email_widget").show().css({
			'top': '-100px',
			'left': '-400px',
			'z-index': 100
		});
		
		$("#post_id").val($(this).attr("target"));
	});

	$('.mark_read').click
	(
		function(e)
		{
			e.preventDefault();
			togglePostRead($(this), false);
		}
	);

	$('.mark_unread').click
	(
		function(e)
		{
			e.preventDefault();
			togglePostRead($(this), true);
		}
	);
}
 
/**
 * Mark Post as Read/Unread
 */
function togglePostRead(post, read)
{
	var url = 'http://' + window.location.hostname + '/lookabooka_news/user/' + username + '/posts/';
	
	var params = (read ? {"unread":post.attr("target")} : {"read":post.attr("target")});
	
	var news_article_header = post.parents(".news_article").children("h3").filter(":first");

	$.post
	(
		url,
		params,
		function(msg)
		{
			news_article_header.toggleClass("read");
			post.html((read ? "Mark as Read" : "Mark as Unread"));
			post.toggleClass("mark_read");
			post.toggleClass("mark_unread");
			post.unbind("click");
			post.bind
			(
				"click",
				function(e)
				{
					e.preventDefault();
					togglePostRead($(this), !read);
				}
			);
		}
	);

}

/**
 * Emails the user's post to email addresses
 *	POST /user/<username>/posts/fwd
 *	     Inputs x-www-form-urlencoded parameters
 *		    postId - id of the post to forward
 *		    email - destination email address
 *		    subject - subject line for the email
 *		    comment - freeform text for the user to write a custom message 
 */
function emailPost() {
	var url = 'http://' + window.location.hostname + '/lookabooka_news/user/' + username + '/posts/fwd/';
	var email_address = $("#email_address").val();	
	var subject = $("#email_subject").val();
	var email_message = $("#email_message").val();
	var post_id = $("#post_id").val();
	
	var post_vars = {
		'postId': post_id, 
		'email': email_address, 
		'subject': subject,
		'comment': email_message};
	
	if (!email_address) {
		$("#email_address").val("Enter an email address!");		
	}
	
	$.post(url, post_vars, function (result, textStatus) {
		if (textStatus == 'success') {
			$("#email_status").html("EMAIL SENT!");
			$("#email_message").val(' ');
			$("#email_subject").val(' ');

			$("#news_email_widget .widget_collapse_up").trigger('click');
		} else {
			$("#email_status").html("Sorry, there was an issue sending your email. Please try again.");
		}			
	});
} 

/**
 * Adds a clip to user's account - default folder is root
 * POST /user/<username>/clippings
 	 clip = id of post to clip
	 fid = id of a folder in the MYC hierarchy where post will be stored, 0 means root.
 */
function addClip(feed_id) {
	var url = 'http://' + window.location.hostname + '/lookabooka_news/user/' + username + '/clippings/';
	var folder = 0;
	var post_vars = {'clip':feed_id, 'fid': folder}; 
	$.post(url, post_vars, function(result, textStatus) {
		if (textStatus == 'success') {
			$('.add_clipping[target="' + feed_id + '"]').remove();
			setTimeout("initMyClippings()", 2000);
		} else {
			alert("There was an issue adding your clip");
		}			
	});
}

/**
 * Refreshes the clipping tree to the left side widget
 */
function refreshClippingTree(defaultDisplay) {

	var clippingsUrl = "http://" + window.location.hostname + "/lookabooka_news/user/" + username + "/clippings/";
	// Get Clippings
	$.getJSON(
		clippingsUrl,
		function(clippings)
		{
			// Build Folder/Clipping Hierarchy
			buildClippingTree(clippings);
		}
	);	
}


 /**
  * Create the page links for the system feed source results
  * URL - GET /feeds?s=<startindex>&c=<number of items>
  */
function getFeedPaginationLinks(feed_url, feed_id, current_page, feed_count) {
	var num_pages = Math.ceil(feed_count/6);
	
	var first_page = (current_page - 3) < 0 ? 0 : current_page - 3;
	var last_page = (current_page + 3) > num_pages ? num_pages : current_page + 3;
	var pagination = "<div id='pagination_links'>";
	var index_page;
	
	// If we no longer can see the first page, indicate more pages if you go back
	if (first_page != 0) {
		pagination += "... ";	
	}
				
	for (index_page = first_page; index_page < last_page; index_page++) {
		var page = index_page + 1;
		if(index_page != current_page) {					
			var page_name = window.location.pathname;
			page_name = page_name.substring(page_name.lastIndexOf('/')+1);

			var feed_link = "<a id='" + feed_id + "' feed_count='" + feed_count + "' href='" + page_name + "#top' url='" + feed_url + "?s=" + (index_page*6) + "&c=6'>" + page + "</a>";
			pagination += feed_link;
		} else {
			pagination += page;
		}
		
		// Create page delimiter
		if((index_page + 1) != last_page) {
			pagination += ' | ';
		}
	}
	
	// If we haven't reached the last page, then indicate there's more
	if (last_page != num_pages) {
		pagination += " ...";
	}
	
	pagination += "</div>";
	return pagination;		
}

function initWidgeResizePreload(widget_content_id, force) {
	total_images++;

	var images_total_count = $(widget_content_id + ' img').length;
	
//	console.log(total_images + " : " + images_total_count);
		
	if (total_images > (images_total_count - 5) || force) {
		var widget_id = $(widget_content_id).parents('.news_main_content').attr('id')
		if(!widget_id) {			
			widget_id = 'search_results_widget';				
		}
		
		$(widget_content_id).show();
		
		widget_id = '#' + widget_id;
		
		$(widget_id + ' .spinner').remove();
		
	//	console.log(widget_id);
		
		initWidgetResize(widget_id);
		$('body').css('cursor', 'auto');
	}	
}

/**
 * Creates the folder tree in the left feed widget
 */
 function createFolderTree(results, treeWrapper) {
 	
	results = results.subscriptions;
	var content = "";
	if (results && results.children) {
	
	
		if (results.children.length && results.children.length  > 0) {
		
			var folders = results.children;
			
			for (var index = 0; index < folders.length; index++) {
				var folder = folders[index];
				var id = folder["ng:id"];
				var title = folder.title;
				
				// If there are children subfolders
				var subfolders = folder.children;
				if (subfolders) {
					var items_count = subfolders.length;
					content = content + "<li><a href='#'><div class='folder_plus'></div>" + title + " (" + items_count + ")</a>";
					var subfolder_content = createSubFolderTree(subfolders);
					content += subfolder_content;
				}
				else {
					if (folder.isSearchFeed == 'True') {
						title = 'Keyword: ' +  title;
					}
					content = content + "<li><img class='favicon' src='" + folder.faviconUrl + "' style='float: left' /><a href='#feed' feed_id='" + id + "'>" + title + "</a></li>";
				}
				
				
				content = content + "</li>";
			}
		}
	}
 	
 	$(treeWrapper).append(content);
	$('.favicon').error(function() {
		$(this).attr('src', '/images/feed-icon16x16.png');
	}); 	
 	$(treeWrapper + " a").click(function(e) {
	 	var widget_id = $(treeWrapper).parents(".widget_container").parent().attr("id");
	 	
 		e.preventDefault();
 		e.stopPropagation();
 		$(this).siblings('ul').toggle();
 		$(this).children('div').toggleClass('folder_minus');
 		$(this).siblings('a').children('div').toggleClass('folder_minus');
 		
	 	
	 	 //displays the feed from left feed widget
		 if ($(this).attr('feed_id')) {
			 
			$("#my_feed_tree li a").removeClass('clicked');
			$(this).addClass('clicked');

			// Refresh Ad Widget
			refreshAdWidget();

             var feed_id = $(this).attr('feed_id');
         
            $('.news_main_content, #search_results_widget, #clipping_content').hide();        
             $('#news_feed_results_widget').show();
             displayFeedResult(feed_id);
         }
	 	initWidgetResize('#' + widget_id);
	 	
 		return false;
 	});
 	 	
 	$(".subfolder").hide();

 	var widget_id =$(treeWrapper).parents(".widget_container").parent().attr("id"); 	
 	initWidgetResize('#' + widget_id);
 }
 
/**
 * Recursive function that creates the subfolder branches in news_organize_folders widget
 */
 function createSubFolderTree(folders) {
	 
	var content = " ";
	
 	if (folders && folders.length != 0) {
 		content = "<ul class='subfolder'>";
 		for (var index = 0; index < folders.length; index++) {
 			var folder = folders[index];
 			
			var id = folder["ng:id"];
			var title = folder.title; 			
 			var folder_style = '';
 			
 			if (index == 0) {
	 			if($.browser.msie) { 
	 				folder_style = "position: relative; left: -14px;";
 				} else {
	 				folder_style = "margin-left: -14px;";	 				
	 			}
 			}
			
			var subfolders = folder.children;
			if (subfolders) {
				var items_count = subfolders.length;
				content = content + "<li style='" + folder_style + "'><a href='#'><div class='folder_plus'></div>" + title + " (" + items_count + ")</a>";
				subfolders = createSubFolderTree(subfolders);
				content += subfolders;
			}
			else {
				if (folder.isSearchFeed == 'True') {
					title = 'Keyword: ' +  title;
				}
				content = content + "<li style='" + folder_style + "'><img class='favicon' src='" + folder.faviconUrl + "' style='float: left' /><a href='#feed' feed_id='" + id + "'>" + title + "</a>";
			}
 			content += "</li>";
 		}
 		content += "</ul>"; 		
 		
 	}

 	return content;
 } 

/**
 * Creates the drop down box containing user's folders
 */
 function createFolderDropdown(results, folder_wrapper, folder_type) {
 	
 	if (results.children && results.children.length && results.children.length > 0) {
 		var folders = results.children;
 		var content = "";

 		for (var index = 0; index < folders.length; index++) {
 			var folder = folders[index];
 			
 			if (folder_type == 'MYC') {
	 			content = content + "<option value='MYC|" + folder.id + "'>--" + folder.name + "</option>";
 			} else {
 				content = content + "<option value='" + folder.id + "'>--" + folder.name + "</option>";
			}
 			
 			// If there are children subfolders
 			var subfolders = folder.children;
 			if (subfolders) {
 				subfolders = createSubFoldersDropdown(subfolders, '----', folder_type);
 				//console.log(subfolders);
 				content += subfolders; 				
 			}
 		}
 	}
 	
 	$(folder_wrapper).append(content);

 }
 
/**
 * Recursively creates the user's sub-level folders
 */  
 function createSubFoldersDropdown(folders, level, folder_type) {
 	if (folders) {
 		var content = "";
 		for (var index = 0; index < folders.length; index++) {
 			var folder = folders[index];
 			
 			if (folder_type == 'MYC') {
	 			content = content + "<option value='MYC|" + folder.id + "'>" + level + folder.name + "</option>";
 			} else {
 				content = content + "<option value='" + folder.id + "'>" + level + folder.name + "</option>";
			}
			
 			if (folder.children) {
	 			var next_level = level + '----';
 				var subfolders = createSubFoldersDropdown(folder.children, next_level, folder_type);
 				content += subfolders;
 			}
 		}
 		return content;
 	}
 } 


/**
 * Create folder drop down
 * folder_wrapper_element is the <select> drop-down down id
 */
 function initMyFoldersDropDown(folder_wrapper_element) {
	 
 	var url = "http://" + window.location.hostname + "/lookabooka_news/folder/" + username;

 	$(folder_wrapper_element).html(' '); 	
 	
 	$.getJSON(url + "/MYC", function(results) {
	 	
		if(results.id == "MYC") {
			$(folder_wrapper_element).append("<option value='MYC|0'>My Clippings</option>");
		
			createFolderDropdown(results, folder_wrapper_element, 'MYC');
		}
 	});  	
	
	 	
 	$.getJSON(url + "/MYF", function(results) {
		if(results.id == "MYF") {
			$(folder_wrapper_element).append("<option value='0'>My Folders</option>");			
			createFolderDropdown(results, folder_wrapper_element, 'MYF');
		}
 	}); 
 	
 } 

/**
 * Display only my feeds folders
 */ 
 function MyFeedsDropDown(folder_wrapper_element) {
 	var url = "http://" + window.location.hostname + "/lookabooka_news/folder/" + username + "/MYF";

 	$(folder_wrapper_element).html(''); 	
 	
 	$.getJSON(url, function(results) {
	 	
		if(results.id == "MYF") {
			$(folder_wrapper_element).append("<option value='0'>My Feeds</option>");		
			createFolderDropdown(results, folder_wrapper_element);
		}
 	});  	
 
 }  

/**
 * Refreshes the content of the sidebar widget containing my feeds
 */
function refreshMyFeedSideBar() {
	var url = "http://" + window.location.hostname + "/lookabooka_news/subs/" + username + "/";	
	var my_feed_tree = "#my_feed_tree";
	$(my_feed_tree).html('');
 	$.getJSON(url, function(results) {
 		createFolderTree(results, my_feed_tree);	 		
 	});
}  
   
/**
 * Fades out the status message
 */
 function fadeStatusMessage() { 	
 	$("#status_message").fadeOut("slow");
 }
 
/**
 * Removes subscription
 *  POST /subs/<username>/<feedid>
 *	delete = true 
 */ 
 function deleteSubscription(feed_id) {
	var url = "http://" + window.location.hostname + "/lookabooka_news/subs/" + username + "/" + feed_id + '/';
		
	var post_vars = {'delete' : 'True'}; 
		
	$.post(url, post_vars, function(results, textStatus) {
		if (textStatus == 'success') {			
			return true;				
		} else {
			return false;
		}
	});
 }

/**
 * Retrieves and displays the selected feed using the feed id
 * INPUT
 *   GET /feed/<feedid>/?s=<start>&c=<count>&u=<username>
 *		s = optional, start index (0 based) for pagination
 *		c = optional, number of news items to return (page size)
 *		u = optional, username of user subscribed to this feed.
 *   Output
 *		JSON Structure containing feed data
 */
function displayFeedResult(feed_id) {

	var widget_content_id = "#feed_content";	
	var feed_start_index = 0;
	var feed_per_page = 6;
	var current_page = 0;	
	var feed_count = '';
	var user_feed = 'user feed';
 	var url = "http://" + window.location.hostname + "/lookabooka_news/feed/" + feed_id + "/?s=" + feed_start_index + "&c=" + feed_per_page + "&u=" + username;
 	
	getNewsFeed(url, widget_content_id, feed_id, current_page, feed_count, user_feed);	
	

}


/**
 * Refresh Ad Widget
*/
function refreshAdWidget()
{
//	console.log("Refresh Ad Widget");
	$("#ad_widget iframe").attr("src", $("#ad_widget iframe").attr("src"));
}