﻿
var currentFilter = new Array();
var page = 1;
var searchTerm = "";

$(parseHash);
function parseHash()
{
	var hash = window.location.hash;
    if(hash.indexOf('#') == 0)
    {
        hash = hash.length > 1 ? hash.substring(1) : null;
    }
	
	if(hash)
	{
		var params = hash.split("&");
		var len = params.length;
		for(var i = 0; i < len; i++)
		{
			var pos = params[i].indexOf('=');
			if (pos > 0) 
			{
				var key = params[i].substring(0,pos);
				var val = params[i].substring(pos+1);
				switch(key)
				{
					case "searchTerm":
						searchTerm = val;
						break;
				}
			}
		}
	}
	loadBlogs();
}

function loadBlogs()
{
	AtomicPlaypen.AjaxAPI.AtomicPlaypenAjax.GetBlogPosts(blogItemID, currentFilter, searchTerm, page, Callback_loadBlogs);
	AtomicPlaypen.AjaxAPI.AtomicPlaypenAjax.GetBlogTags(currentFilter, searchTerm, Callback_loadTags);	
	$("input[name='searchInput']").keypress(inputKeyPress);
}
function inputKeyPress(e)
{
	if(e.which == 13)
	{
		blogSearch();
	}
}
function blogSearch()
{
	searchTerm = $("input[name='searchInput']").val();
	loadBlogs();
}
function changeFilter(filter)
{
	//Add a filter
	currentPage = 1;
	
	var newFilter = true;
	if(filter != "" && filter != null)
	{
		for(key in currentFilter)
		{
			if(currentFilter[key] == filter)
			{
				newFilter = false;
			}
		}
		if(newFilter)
		{
			currentFilter.push(filter);
		}
	}
	loadBlogs();
}
function changeFilterTo(filter)
{
	currentFilter = new Array();
	currentPage = 1;
	changeFilter(filter);
}
function clearFilter(filter)
{
	currentPage = 1;
	var newAry = new Array();
	for(var i = 0; i < currentFilter.length; i++)
	{
		if(currentFilter[i] != filter)
		{
			newAry.push(currentFilter[i]);
		}
	}
	currentFilter = newAry;
	loadBlogs();
}
function clearFilters()
{
	currentFilter = new Array();
	currentPage = 1;
	loadBlogs();
}

function Callback_loadBlogs(res)
{
	if (res.error)
	{
		//alert("An error occurred.\nYour request could not be processed.  " + res.error.Message)
	}
	else
	{
		var results = res.value;
		$("#blogListDiv").html(results);
		blogPostSifr();
	}
}
function Callback_loadTags(res)
{
	if (res.error)
	{
		//alert("An error occurred.\nYour request could not be processed.  " + res.error.Message)
	}
	else
	{
		var results = res.value;
		$("#categoriesList").html(results);
	}
}
function olderPage()
{
	page++;
	loadBlogs();	
	sifrSwap(); 
}
function newerPage()
{
	page--;
	loadBlogs();	
}