
// nicorosberg.com - JS
// Requires: jquery


var streamFilters = []; // Fill this array with filters, see checkFilters()
var page = 1; // Show page 1 first, and manipulate this before loading nico_stream()

var showDebug = false;


// ÜBER COOL AJAX-FILTER. you need index.php, filter.php and sidebar.php for this
function nico_stream(filter, page, v2) {
		
	// Scroll top
	$(window).scrollTop(0);
		
	// Show loading
	$("#filtered_list_loading").fadeIn(100);
	$("#filtered_list_loading").height($('#filtered_list').height());
	
	// Hide contents
    //$('#filtered_list *').fideIn(300);
    //$('#filtered_list + p').fideIn(300);
    $('#filtered_list').slideUp(300);
	// Load contents
    $('#filtered_list').load("/stream/page/" + page + "/?embed=c" + cachebuster() + "&toparticle=" + frontpageTopArticleID() + "&filters=" + filter.join(","), function(){	
		// Hide loading
		$("#filtered_list_loading").fadeOut(1);
		// Show contents
    	$('#filtered_list').slideDown(300);
		
		
		// Rebuild share-button
		addthis.toolbox(".addthis_toolbox",{
							services_expanded:"favorites,email,delicious,digg,google,twitter,facebook",
							ui_508_compliant:"true",
							data_track_linkback: "true",
							username: "nicorosberg"
						//	,data_ga_tracker: pageTracker
						},{
							url: $(this).parent(".theBox").children(".postLink").attr("href")
						});
		
		$("#filtered_list .addthis_button_compact").each(function(){						   
			var linkTitle = $(this).parent(".theBox").children(".postLink").text();
			var linkHref = $(this).parent(".theBox").children(".postLink").attr("href");
			$(this).attr("onMouseOver", "return addthis_open(this, '', '"+linkHref+"', '"+linkTitle+"');");
		});
		
		
	});
}

// Load filter-settings from html, see filters.php
function checkFilters() {
	
	var filterArray = [];
	
	// Go trough all toplevel a-tags
	$(".filters a.toplevel").each(function() {
		// Add it as a filter if it's selected
		if($(this).children("span").attr("class") == "selected") {
			filterArray.push($(this).attr("id"));
		}
	});
	
	// Go trough all toplevel a-tags
	$(".filters a.sublevel").each(function() {
		// Add it as a filter if it's selected
		if($(this).children("span").attr("class") == "selected") {
			filterArray.push($(this).attr("id"));
		}
	});
	
	return filterArray;
}


// Remove filter from streamFilters-array
function removeFilter(id) {
	
	page = 1; // Reset pagination
	
	for ( var i in streamFilters ) {
		
		if(streamFilters[i] == id) { 
		
			streamFilters.splice(i, 1);
		}
		
	}
	
	updateFilterStatus();
	
	updateFilterCookie(streamFilters);
	
}

// Add filter to streamFilters-array
function addFilter(id) {
	
	page = 1; // Reset pagination
	
	streamFilters.push(id);
	
	updateFilterStatus();
	
	updateFilterCookie(streamFilters);
}

// Set filter-cookie
// Requires jquery.cookie.js
function updateFilterCookie(filters) {
	$.cookie("filters", filters.join(","), { path: '/', expires: 10 });	
}


// Return random int
function cachebuster() {
	return Math.floor(Math.random()*10001);
}

// Check what article (ID) is visible on the top of the page
function frontpageTopArticleID() {
	if ($("#frontpageTopArticle").length > 0){
		var post_id = $("#frontpageTopArticle .theBox").attr("id");
		return post_id.replace("post-", "");;
	} else {
		return "";	
	}
}

// Pagination
function older_posts() {
	page = page+1;
	
	$("#tickerBox").hide();
	$("#frontpageTopArticle").hide();
	init_floatingBox();
	
	//$(window).scrollTop(0);
	streamFilters = checkFilters();
	nico_stream(streamFilters, page);
	
	return false;
}
function newer_posts() {
	if(page > 1) {
		
		$("#tickerBox").hide();
		$("#frontpageTopArticle").hide();
		init_floatingBox();
		
		page = page-1;
		//$(window).scrollTop(0);
		streamFilters = checkFilters();
		nico_stream(streamFilters, page);
	}
	return false;
}


function useFilters(filters) {
	
	// Empty filter-array
	streamFilters = [];

	$("a.sublevel").children("span").attr("class", "unselected");
	$("a.toplevel").children("span").attr("class", "unselected");
	
	// Loop and set new filters
	for ( var i in filters ) {
		$("#"+filters[i]).children("span").attr("class", "selected");
	}
}


function updateFilterStatus() {
	
	if(showDebug==true) { $("#sideStatus").text("Active: "+streamFilters.join(", ")); }	
	
	//linkObject.attr("href","#"+streamFilters.join(","));
}

/* FLOATING BOX
 * http://nettuts.com/html-css-techniques/creating-a-floating-html-menu-using-jquery-and-css/
 * Demo: http://nettuts.s3.cdn.plus.org/018_Floating_Menu/demo/dhtml_float_menu_final_nettut.html
 */
function init_floatingBox() {
	if($(window).height() > $(floatingBox).height()) {
		
		var floatingBox = "#floatingbox";
		var menuYloc = null;
		var topBuffer = $("#middlePage").offset()["top"];//+5
	
		$(floatingBox).css("position","absolute");
		$(floatingBox).css("top",topBuffer+"px");
		
		menuYloc = parseInt($(floatingBox).css("top").substring(0,$(floatingBox).css("top").indexOf("px")));
				
			
		// When refreshing at middle of the page
		if( $(document).scrollTop() < topBuffer) {
			offset = topBuffer+"px";
		}
		else if( $(document).scrollTop() >= topBuffer ) {
			offset = 13+$(document).scrollTop()+"px";
		}
		else {
			offset = menuYloc+$(document).scrollTop()+"px";
		}
		
		$(floatingBox).animate({top:offset},{duration:1,queue:false});
		
		// When scrolling
		$(window).scroll(function () { 
			
			if( $(document).scrollTop() < topBuffer) {
				offset = topBuffer+"px";
			}
			else if( $(document).scrollTop() >= topBuffer ) {
				offset = 20+$(document).scrollTop()+"px";
			}
			else {
				offset = menuYloc+$(document).scrollTop()+"px";
			}
			
			$(floatingBox).animate({top:offset},{duration:300,queue:false});
		});
			
	}	
}

function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

// Perform these when page has finished loading:
$(document).ready(function(){
	
	// startStream from header.php
	if(startStream == true) {

	// Hide JS-alert (not in use)
	//$("#noJavascriptAlert").hide();

	// Let's roll stream
    $('#filtered_list').hide();
	
	// Load filters
	streamFilters = checkFilters();
	
	// Load stream
	//var v2 = gup('v2');
	nico_stream(streamFilters, page, 1);

	updateFilterStatus();
	


/*
	// Default string after # in URL
	var pageURLExtension = "";

	// Grap URL
	var pageURL = document.location.toString();
	
	// IF an anchor (#) exists in URL, change pages depending rules
	if (pageURL.match('#')) {
			  
		  var selectedFiltersArr = pageURL.split('#')[1]+",";
		  var selectedFilters = selectedFiltersArr.split(',');

		  $("#sideStatus").text("selectedFilters: "+selectedFilters.join(", "));
		  
		  $.cookie("filters", selectedFilters.join(","), { path: '/', expires: 10 });	
		  
		  useFilters(selectedFilters);
  
	}
	
*/
	
	
	// Stream controls
	$(".filters a.sublevel, .filters a.toplevel").click(function(ev){
		
		ev.preventDefault();
		
		// Filter was selected, so let's make it UNselected
		if($(this).children("span").attr("class") == "selected") {
			
			// Hold it untill we check if it's safe to remove (not last one of the group or anything...)
			var holdSelection = true;
			
			var thisClickID = $(this).attr("id");
			
			// Filter was sublevel filter
			if($(this).parent("li").attr("class") == "sublevel") {
				
				// If it's last sublevel filter, make toplevel selected, 
				// as a default yes (but let's check it more deeply below)
				var makeTopSelected = true;
				
				// Yeah you can remove it
				holdSelection = false;
				
				// Pick toplevel of this sublevel
				var tree = $(this).parents("li.toplevel").attr("id");
				
				// Go trough all fellow sublevels
				$("#"+tree+" a.sublevel").each(function() {
					//alert($(this).attr("id"));
					
					// Yay, we found a selected sublevel fellow
					if($(this).children("span").attr("class") == "selected" && $(this).attr("id") != thisClickID) {
						makeTopSelected = false;
						//alert("break: "+$(this).attr("id"));
						return false;
					}
					
				});
				
				if(makeTopSelected == true) {
					var topLevel = $("#"+tree+" a.toplevel");
					addFilter(topLevel.attr("id"));
					$(topLevel).children("span").attr("class","selected");
				}
				
			} 
			// Filter was toplevel filter
			else if($(this).parent("li").attr("class") == "toplevel") {
				
				var tree = $(this).parent("li").attr("id");
				
				$("#"+tree+" a.sublevel").each(function() {
					//alert($(this).attr("id"));
					if($(this).children("span").attr("class") == "selected") {
						holdSelection = false;
						//alert("break: "+$(this).attr("id"));
						return false;
					}
					
				});
			} 
			else { holdSelection = false; }
			
			
			// We can remove filter... got permission. :-)
			if(holdSelection == false) {
				removeFilter(thisClickID);
				$(this).children("span").attr("class","unselected");	
			}
			
		
		// Filter was UNselected so lets make it selected
		} else {
			
			var thisClickID = $(this).attr("id");
			
			// Make clicked sublevel selected and add filter
			addFilter(thisClickID);
			$(this).children("span").attr("class","selected");
			
			// Filter was sublevel filter
			// Find and remove top-category-filter of this sub-category filter
			if($(this).parent("li").attr("class") == "sublevel") {
				
				// Pick toplevel of this sublevel
				var tree = $(this).parents("li.toplevel").attr("id");
				
				// Go trough all fellow sublevels
				$("#"+tree+" a.sublevel").each(function() {
					
					// Yay, we found a selected sublevel fellow - make it unselected! (and remove filter)
					if($(this).children("span").attr("class") == "selected" && $(this).attr("id") != thisClickID) {
						
						removeFilter($(this).attr("id"))
						$(this).children("span").attr("class","unselected");
					}
					
				});
				
				topFilter = $(this).parents("li.toplevel").children("a.toplevel");
				removeFilter(topFilter.attr("id"))
				topFilter.children("span").attr("class","unselected");
				
			
			// Filter was toplevel filter
			// Find and remove sub-category filters of this top-category filter
			} else if($(this).parent("li").attr("class") == "toplevel") {
				
				var tree = $(this).parent("li").attr("id");
				
				$("#"+tree+" a.sublevel").each(function() {
					if($(this).children("span").attr("class") == "selected") {
						
						removeFilter($(this).attr("id"));
						$(this).children("span").attr("class","unselected");
					}
					
				});
			}
			
		}
	
		updateFilterStatus();
		
		// Update stream:
		nico_stream(streamFilters, page);
		
		
		return false;
	});
	
	
		

	// News ticker
	// Requires:
	// - jquery.newsticker.css
	$('#tickerBox').show();
	$.get("/headlines/?query", {}, function(data){					 
		$("#ticker").html(data).find("ul").newsTicker();
	})
	
	
	 init_floatingBox();

	
	/*
			menuYloc = parseInt($(floatingBox).css("top").substring(0,$(floatingBox).css("top").indexOf("px")))
			$(window).scroll(function () { 
				offset = menuYloc+$(document).scrollTop()+"px";
				$(floatingBox).animate({top:offset},{duration:500,queue:false});
			});
			*/


	} //startStream * end
	
	

});

	
