if(!ws) var ws = {};
if(!ws.community) ws.community = {};
if(!ws.community.blogs) ws.community.blogs = {};
if(BLOGS == null) var BLOGS = ws.community.blogs;

BLOGS.errorMessageHTML = "<div align='center' style='margin-top: 50px;'>" +
		"<div style='width: 400px; height: 30px; border: solid 1px grey; background-color: #E6E6E6;'>" +
		"<div style='padding: 5px;'><p>No blogs found for your criteria. Please refine your selection" +
		"</p></div></div></div>";

// store global meta information to be available across functions
if(!BLOGS.meta) {
	BLOGS.meta = {};
	BLOGS.meta.total = 0;
	BLOGS.meta.period = 0;
	BLOGS.meta.startIndex = 0;		
}



function ShowHide(id, anchor) {
	
	if(!StringUtils.isEmpty(id)) {
		jQuery("#" + id).animate({"height": "toggle"}, { duration: 300 });
		
		if(anchor || StringUtils.isEmpty(anchor.id)) {
			// parse id for state  
			var regex = /^([\w]*)_([\w]*)$/;
			var state = regex.exec(anchor.id)[2];
			if("hide" === state) {
				
				anchor.innerHTML = "<span class='portletState'>-</span>";
				anchor.id = regex.exec(anchor.id)[1] + "_show";
				BLOGS.showRSSLinks();
				BLOGS.showRSSLinks2();
			}
			else {
				anchor.innerHTML = "<span class='portletState'>+</span>";
				anchor.id = regex.exec(anchor.id)[1] + "_hide";
				
			}
		}
		else {
			return false;
		}
	}
	else {
		jQuery("#slidingDiv").animate({"height": "toggle"}, { duration: 300 });
	}	
}


BLOGS.initializeBlogsHomepage = function (staticOptions) {	
	
	jQuery("#createNewPostTableCell").show();	
		
	// precondition check
	if(StringUtils.isEmpty(staticOptions.spaceKey)) {
		throw {
			name:    "IllegalArgumentException",
			message: "Expected space key!"			
		}
	}
	
	BLOGS.meta.spaceKey = staticOptions.spaceKey;
	BLOGS.meta.period = staticOptions.period;
	BLOGS.meta.month = staticOptions.month;
	BLOGS.meta.year  = staticOptions.year;
	BLOGS.meta.pageSize = staticOptions.pageSize;
	BLOGS.meta.startIndex = staticOptions.startIndex;
	BLOGS.meta.total = staticOptions.total;
	BLOGS.meta.user = staticOptions.selectedUser;
	BLOGS.meta.selectedGroup = staticOptions.selectedGroup;
	BLOGS.meta.selectedGroupType = staticOptions.selectedGroupType;		
	BLOGS.meta.labelString = staticOptions.labelString;
		    
	
	// initialize current page	
	BLOGS.meta.currentPage = parseInt(staticOptions.startIndex / staticOptions.pageSize) + 1;
		
	// replace static pagination with dynamic pagination
	if(staticOptions.total > 0) {
		
		WSUtils.generatePagination("paginationTop", staticOptions.total, staticOptions.pageSize, 
			"#switchpage", BLOGS.meta.currentPage, BLOGS.pageSwitchHandler);	
		
		WSUtils.generatePagination("paginationBottom", staticOptions.total, staticOptions.pageSize, 
			"#switchpage", BLOGS.meta.currentPage, BLOGS.pageSwitchHandler);		
	}
			
	
	
	//  "select all" button functionality
	if(StringUtils.isEmpty(staticOptions.selectedGroup)) {
				
		var prepareSelectAllSelectNone = function (selectAllLink, selectNoneLink, cssStyleName) {
			
			jQuery("#" + selectAllLink).show().click(function () {
		
				jQuery(".selectionFilterCheckbox." + cssStyleName).each(function() {			
					jQuery(this).attr("checked", "checked");
				});			
				BLOGS.toggleCheckboxes(false);	
				BLOGS.toggleContainer(true);		  	  	
				BLOGS.meta.currentPage = 0;			  			
				BLOGS.updateBlogs(0);				
				return false;	
			});
				
			//  "select none" button functionality
			jQuery("#" + selectNoneLink).show().click(function () {
				
				jQuery(".selectionFilterCheckbox." + cssStyleName).each(function () {			
					if(jQuery(this).attr("class").indexOf("nonspecific") < 0) {
						jQuery(this).removeAttr("checked");	
					}			
				});
				
				BLOGS.toggleContainer(true);
				BLOGS.toggleCheckboxes(false);	  	  	
				BLOGS.meta.currentPage = 0;			
				BLOGS.updateBlogs(0);		
				return false;	
			});			
		};				
		
		prepareSelectAllSelectNone("selectAllProductLink", "deSelectAllProductLink", "product");
		prepareSelectAllSelectNone("selectAllTeamsLink", "deSelectAllTeamsLink", "team");
		prepareSelectAllSelectNone("selectAllLangsLink", "deSelectAllLangsLink", "lang");	
	}
	
	
	
	var eventStack = new Array();
	
	
	if(jQuery.browser.msie) {
		// Note: IE event is firing very slowly, use the click event 
		// instead of the change event for checkboxes		
		jQuery(".selectionFilterCheckbox").click(function () {
			for(var i = 0; i < eventStack.length; i++) {
		  		clearTimeout(eventStack[i]);
		  	}
		  		  				  	
	  		var timeout = setTimeout(function () {
		  		BLOGS.toggleContainer(true);	  		
			  	BLOGS.toggleCheckboxes(false);			  		  	
				BLOGS.meta.currentPage = 0;			
				BLOGS.updateBlogs(0);	
				eventStack = new Array();											  	
		  	}, 1000);		
		  	eventStack.push(timeout);		  	
		});
	}
	else {
		// traverse all check boxes and add the change event listener	
		jQuery(".selectionFilterCheckbox").change(function () {
				  		  	  
		  	for(var i = 0; i < eventStack.length; i++) {
		  		clearTimeout(eventStack[i]);
		  	}
		  		  				  	
	  		var timeout = setTimeout(function () {
		  		BLOGS.toggleContainer(true);	  		
			  	BLOGS.toggleCheckboxes(false);			  		  	
				BLOGS.meta.currentPage = 0;			
				BLOGS.updateBlogs(0);	
				eventStack = new Array();											  	
		  	}, 1000);		
		  	eventStack.push(timeout);		  									
	  });
	}

   BLOGS.fetchTopBloggers("", BLOGS.meta.spaceKey, 10,
		
		function (data) {
			if(StringUtils.isEmpty(data)) {
				data = "Could not find top blogger data";							
			}			
			jQuery("#topBloggersContainer").empty().append(data);			
		}, 
		
		function (req, textStatus, error) {
			// ignore			
	});	
	
	
	// fetch popular tags for this space
	BLOGS.fetchPopularTags(BLOGS.meta.spaceKey, 10,		
		function (data) {
			if(StringUtils.isEmpty(data)) {
				data = "Could not find popular tags data";							
			}			
			jQuery("#popularTagsContainer").empty().append(data);			
		}, 
		
		function (req, textStatus, error) {		
			// ignore	
	});	
	
	// fetch archives for this space 
	BLOGS.fetchBlogArchives(BLOGS.meta.spaceKey, 10,		
		function (data) {
			if(StringUtils.isEmpty(data)) {
				data = "Could not find archive data";							
			}			
			jQuery("#blogArchivesContainer").empty().append(data);			
		}, 
		
		function (req, textStatus, error) {		
			// ignore	
	});	
	
	// fetch most viewed content 
	BLOGS.fetchMostViewed(BLOGS.meta.spaceKey, 10,		
		function (data) {
			if(StringUtils.isEmpty(data)) {
				data = "Could not find archive data";							
			}			
			jQuery("#mostViewedPostsContainer").empty().append(data);			
		}, 		
		function (req, textStatus, error) {		
			// ignore	
	});	
	
	// initialize session for preferences
	var labelString = BLOGS.parseLabelString();
	var labelStringFromCookie = BLOGS.getUserPrefsCookie();
	
	if(StringUtils.isEmpty(BLOGS.meta.labelString) &&
	    StringUtils.isEmpty(BLOGS.meta.selectedGroup) && 
		!StringUtils.isEmpty(labelStringFromCookie)  && 
		labelString != labelStringFromCookie  && 
		BLOGS.meta.period === 0 &&
		StringUtils.isEmpty(BLOGS.meta.user)) {		
		
		// client side check to make sure preferences are in sync with cookie		
		BLOGS.toggleContainer(true);	  		
	  	BLOGS.toggleCheckboxes(false);	
		
		var preferences = new Array();
		if(labelStringFromCookie.indexOf("+") > 0) {
			preferences = labelStringFromCookie.split("+");
		}
		else {
			preferences.push(labelStringFromCookie);
		}
		// check all appropiate filters
		jQuery(".selectionFilterCheckbox").each(function() {			
			var labelStr = jQuery(this).attr("id");
			if(ArrayUtils.find(preferences, labelStr) >= 0) { 
				jQuery(this).attr("checked", "checked");
			}
			else {
				
				//BLOGS.meta.selectedGroupType = staticOptions.selectedGroupType;
				if(BLOGS.meta.selectedGroup != labelStr) {
					jQuery(this).removeAttr("checked");
				}				
			}			
		});
		BLOGS.updateBlogs(0, labelStringFromCookie);		
	}
	else { 	
		if(StringUtils.isEmpty(BLOGS.meta.selectedGroup)) {
			BLOGS.setUserPrefsCookie(labelString);
		}
					
		
//		if(!StringUtils.isEmpty(labelStringFromCookie)) {		
//			jQuery("#savePrefsMsg").empty().append("<strong>Preferences Loaded...</strong>").show();
//				setTimeout(function() {
//					jQuery("#savePrefsMsg").slideUp("slow");
//				}, "1000");
//		}
	}					
};

// init page switch handler function
// this function gets invoked on a page switch	
BLOGS.pageSwitchHandler = function () {
	
	var id = this.getAttribute("class");
	var regex = /^page_(.*)$/;
	var pageNumber = regex.exec(id)[1];
	
	BLOGS.meta.currentPage = pageNumber;
	
	// compute start index from page number
	var startIndex = BLOGS.meta.pageSize * (pageNumber - 1);
	BLOGS.toggleCheckboxes(false);
	BLOGS.toggleContainer(true);	
	BLOGS.updateBlogs(startIndex);						
	return false;
};


BLOGS.updateBlogs = function(startIndex, labelString) {
		
	if(StringUtils.isEmpty(labelString)) {
		labelString = BLOGS.parseLabelString();
	}
				
	BLOGS.fetchBlogs(BLOGS.meta.user, labelString, BLOGS.meta.spaceKey, startIndex, BLOGS.meta.period, BLOGS.meta.month, BLOGS.meta.year,
		function (data) {
							
			if(!StringUtils.isEmpty(data)) {		  							  		
												  							
				jQuery("#blogsContainer").empty().append(data);
				BLOGS.toggleContainer(false);
				
				var total = BLOGS.meta.total;				
				if(total > 0) {
					// replace static pagination with dynamic pagination
					WSUtils.generatePagination("paginationTop", total, BLOGS.meta.pageSize, 
						"#switchpage", BLOGS.meta.currentPage, BLOGS.pageSwitchHandler);
						
					WSUtils.generatePagination("paginationBottom", total, BLOGS.meta.pageSize, 
						"#switchpage", BLOGS.meta.currentPage, BLOGS.pageSwitchHandler);					
				}
				else {
					jQuery("#paginationTop").empty();
					jQuery("#paginationBottom").empty();
					jQuery("#blogsContainer").empty().append(BLOGS.errorMessageHTML);
				}									
			}
			else {
				jQuery("#paginationTop").empty();
				jQuery("#paginationBottom").empty();					
				jQuery("#blogsContainer").empty().append(BLOGS.errorMessageHTML);
			}	
			
			// if a group is not selected, enable all checkboxes		
			if(StringUtils.isEmpty(BLOGS.meta.selectedGroup)) {
				BLOGS.toggleCheckboxes(true);
			}
			else {
				// otherwise, active teams and langs
				jQuery(".selectionFilterCheckbox.team, .selectionFilterCheckbox.lang").each(function() {								
					jQuery(this).removeAttr("disabled");								
				});
					
				// active products only if selected group label is a team
				if(!StringUtils.isEmpty(BLOGS.meta.selectedGroupType) && BLOGS.meta.selectedGroupType === "team") { 					
					jQuery(".selectionFilterCheckbox.product").each(function() {								
						jQuery(this).removeAttr("disabled");								
					});
				}				
			}			
			BLOGS.initCollapseButton();				
			BLOGS.setUserPrefsCookie(labelString);					
		},
		function (req, textStatus, error) {
			// ignore				
		}			
	);	
};


BLOGS.toggleCheckboxes = function (on) {	
	if(on) {
		jQuery(".selectionFilterCheckbox").each(function() {			
			jQuery(this).removeAttr("disabled");							
		});
	}
	else {
		jQuery(".selectionFilterCheckbox").each(function() {
			jQuery(this).attr("disabled", "disabled");			
		});
	}	
};


BLOGS.parseLabelString = function () {
	
	var join = "";	
	// is there are any tags in the URL, read those 
	// as well, and add them to the labelString
	if(location.href) {
		var urlRegex = /http:\/\/.*\/blogs\/tag\/([^\/]+)\/?$/;
		var result = urlRegex.exec(location.href);
		if(result && !StringUtils.isEmpty(result[1])) {
			var labels = result[1];
			if(labels.indexOf("+") > 0) {
				var labelArray = labels.split("+");
				labelArray.forEach(function(elem, pos, arr) {
					join = join.concat(elem + "+");
				});
			}
			else {
				join = labels + "+";	
			}					
		}
	}
	
	jQuery(".selectionFilterCheckbox").each(function () {	  										 				
		if(jQuery(this).attr("checked")) {	 					
			join = join.concat(jQuery(this).val() + "+");		
		}				 							 			 			 
	});
	
	if(!StringUtils.isEmpty(join)) {
		join = join.slice(0, join.length - 1);		
	}	
	
	return join;
};


BLOGS.toggleContainer = function (isOn) {
				
	if(isOn) {	
		// show opacity div		
		jQuery("#blogsContainer").css("opacity", "0.2");
		jQuery("#blogsContainer").css("filter", "alpha(opacity=50)");
		jQuery("#blogsContainer").css("zoom", "1");
		jQuery("#loadingAnimation").show();
	}
	else {
		// hide opacity div
		jQuery("#blogsContainer").removeAttr("style");		
		jQuery("#loadingAnimation").hide();
	}
};