jQuery(document).ready(function()
{
	j = jQuery.noConflict();
	setStage();
});

function refilter(ref)
{
	thisOrder=jQuery(ref).val();
	jQuery("#filter").val(thisOrder);
	ajaxCenter();
}

function paginate(thisPage)
{
	jQuery("#page").val(thisPage);
	ajaxCenter();
}

function setStage()
{
// 	alert("setstage");
	jQuery("#hiddenFilters").empty();
	var thisKeyword=jQuery("#keywords").val(); 
	ajaxCenter();
}

function ajaxCenter()
{
// 	alert("ajaxCenter firing");
	if(jQuery(".blockMsg").css('display'))
	{
		return false;
	}
	var recordsPerPage = 15;
	var pagination = "";
	var inodes=buildInodesOnToURL();
	var keywords = jQuery("#keywords").val();
	var activeOrdering = jQuery("#filter").val();
	var thisPage = parseInt(jQuery("#page").val());
	var url ='ajax.dot?action=center&srch='+keywords+inodes+'&orderBy='+activeOrdering+'&page='+thisPage+'&recspage='+recordsPerPage;
	var lastStructureInode = "";
	orderingVals = new Array(["","Please select a sort order"],["az","A-Z"],["za","Z-A"]);	
	var urlLeft ='ajax.dot?action=left&srch='+keywords+inodes;
	jQuery.blockUI({message:'<h4>Loading Search Results...</h4><img src="/global/images/ajax-loader-loadingBar.gif" border="0">'});
	jQuery.get(url,function(data)
	{
		var totalRecs = jQuery(data).find('result').attr('totalRecs');
		var returnRecs = jQuery(data).find('result').attr('returnRecs');
		var recStart=(thisPage==1)?1:((thisPage-1)*recordsPerPage)+1;
		if(thisPage==1)
		{
			var recEnd = (totalRecs>recordsPerPage)?recordsPerPage:totalRecs;
		}else{
			var recEnd = parseInt((thisPage-1)*recordsPerPage)+parseInt(returnRecs);
		}
		pluraler = (totalRecs==1)?"":"s";
		var recordsetDescr = "Showing record"+pluraler+" "+recStart+"-"+recEnd+" of "+totalRecs;
		var totalPages = Math.ceil(totalRecs/recordsPerPage);
		for(i=1;i<=totalPages;i++)
		{
			cssPagination=(i==thisPage)?"class=\"selectedPage\"":"";
			pagination += "<a href=\"javascript: paginate('"+i+"')\" "+cssPagination+">"+i+"</a> ";
		}
		linkPrevious=(thisPage==1)?"":"<a href=\"javascript: paginate('"+(thisPage-1)+"')\">«Previous</a>";
		linkNext=(thisPage==totalPages)?"":"<a href=\"javascript: paginate('"+(thisPage+1)+"')\">Next »</a>";
		pagination=(totalPages==1)?"":linkPrevious+pagination+linkNext;
		
		var out="";
		orderingDropDown = "<select onChange=\"refilter(this);\">";
		jQuery(orderingVals).each(function(i)
		{
			isSelected=(activeOrdering==orderingVals[i][0])?"selected":"";
			orderingDropDown +="<option value=\""+orderingVals[i][0]+"\" "+isSelected+">"+orderingVals[i][1]+"</option>";
		});
		orderingDropDown +="</select>";
		jQuery(data).find('result').find('record').each(function()
		{
			thisInode = jQuery(this).attr('INODE');
			thisTitle = jQuery(this).find('title').text();
			thisOverview = jQuery(this).find('overview').text();
			thisStructureInode = jQuery(this).attr('STRUCTURE_INODE');
			switch(thisStructureInode)
			{
				case "153065": structureDescr = "Citation Guide"; break;
				case "153008": structureDescr = "FAQ"; break;
				case "153032": structureDescr = "Tutorial"; break;
			}
			structureHDR=(lastStructureInode!=thisStructureInode)?"<h2>"+structureDescr+"</h2>":"";
			out+="<div class=\"content\">"+structureHDR+"<h4><a href=\"javascript:visitPage('"+thisInode+"')\">"+thisTitle+"</a></h4><p>"+thisOverview+"</p></div>";
			lastStructureInode = thisStructureInode;
		});
		jQuery(".yui-b").eq(0).fadeOut('fast',function()
		{
			jQuery(".yui-b").eq(0).empty().html("<div id=\"returnDescr\"><div id=\"recCounts\">"+recordsetDescr+"</div><div id=\"orderer\">"+orderingDropDown+"</div></div>"+"<div id=\"paginationWrapper\"><div id=\"hdrPagination\">"+pagination+"</div></div>"+out+"<div id=\"recCounts\">"+recordsetDescr+"</div><div id=\"paginationWrapper\"><div id=\"hdrPagination\">"+pagination+"</div></div>").fadeIn('fast',function()
			{
				ajaxLeftSide(keywords,urlLeft);
			});
		});
	});
}

function ajaxLeftSide(thisKeyword,url)
{
	
	var availFilters=activeFilters="";
	if(url=="")
	{
		leftSideURL = "ajax.dot?action=left&srch="+thisKeyword;
		
	} else {
		leftSideURL = url;
	}
	jQuery.blockUI({message:'<h4>Loading Search Filters...</h4><img src="/global/images/ajax-loader-loadingBar.gif" border="0">' });
	jQuery.get(leftSideURL,function(data)
	{
		activeFilterCount = jQuery(".addToFilters").length;
		preLoadedFilters = jQuery("#cat").val().split(",");
		activeVisible = 0;
		jQuery(data).find('result').find('record').each(function(i)
		{
			thisCategoryName = jQuery(this).attr('CATEGORY_NAME');
			thisParent = jQuery(this).attr('PARENT');
			thisParent2 = jQuery(this).attr('PARENT_2');
			thisParent3 = jQuery(this).attr('PARENT_3');
			if(activeFilterCount>0)		// we have active filters
			{
				// before we add this one to the string to populate the HTML of available filters, we gotta make sure that it isn't an active filter
				if(!isFilterActive(thisParent))
				{
					availFilters+="<li id=\""+thisParent+"\"><a href=\"javascript: addFilter("+thisParent+", "+i+")\">"+thisCategoryName+"</a></li>";			
					activeVisible++;
				} else {
					availFilters+="<li id=\""+thisParent+"\" style=\"display: none;\"><a href=\"javascript: addFilter("+thisParent+", "+i+")\">"+thisCategoryName+"</a></li>";
				}
			} else {
				activeFilters+="<li id=\""+thisParent+"\">"+thisCategoryName+" <a href=\"javascript: removeFilter("+thisParent+", "+i+")\">remove</a></li>";
				availFilters+="<li id=\""+thisParent+"\"><a href=\"javascript: addFilter("+thisParent+", "+i+")\">"+thisCategoryName+"</a></li>";			
			}
		});
// 		alert("count preloaded filters "+preLoadedFilters.length);
		
		jQuery(preLoadedFilters).each(function(i)
		{
			if(preLoadedFilters[i].length>0)
			{
// 				alert(preLoadedFilters[i]);
				activeFilters+="<li id=\""+thisParent+"\"><a href=\"javascript: addFilter("+thisParent+", "+preLoadedFilters[i]+")\">test</a></li>";
				activeVisible++;
				activeFilterCount++;
			}
		});
		
		if(activeFilterCount>0)
		{
			if(activeVisible>0)
			{
				jQuery("#helpFiltersAvailable ul").empty().hide().html(availFilters).slideDown();
			}
		} else {
			jQuery("#helpFiltersAvailable ul").empty().hide().html(availFilters).slideDown();
			jQuery("#helpFiltersApplied ul").empty().hide().html(activeFilters).slideDown();
		}
		jQuery.unblockUI();
	});
}

function isFilterActive(inode)
{
	var isFiltered = false;
	jQuery(".addToFilters").each(function()
	{
		thisInode=jQuery(this).val();
		if(thisInode==inode)
		{
			isFiltered=true;
		}
	});
	return isFiltered;
}


function addFilter(thisInode, indx)
{
	addToFilters(thisInode);
	jQuery("#helpFiltersAvailable ul li").slideUp('fast',function()
	{
		jQuery("#helpFiltersApplied #"+thisInode).slideDown('fast',function()
		{
			jQuery("#page").val(1);
			ajaxCenter();
		});
	});
}

function removeFilter(thisInode, indx)
{
	removeFromFilters(thisInode);
	jQuery("#helpFiltersApplied ul li").eq(indx).slideUp('fast',function()
	{
		if(jQuery("#helpFiltersAvailable ul li").length==0)
		{
			ajaxCenter();
		} else {
			jQuery("#page").val(1);
			ajaxCenter();
		}
	});
}

function buildInodesOnToURL()
{
	var out="";
	jQuery("#helpFiltersApplied ul li").each(function()
	{
		thisCSS = jQuery(this).css('display');
		if(thisCSS=="block")
		{
			out+="&inodes="+jQuery(this).attr('id');
		}
	});
	return out;
}

// These hidden values track the existence of the active filters on the page.
function addToFilters(inode)
{
	jQuery("<input type=\"hidden\" class=\"addToFilters\" value=\""+inode+"\">").appendTo("#helpFiltersApplied");
}

// this is the one that handles the removal of the hidden value from the DOM.
function removeFromFilters(inode)
{
	jQuery(".addToFilters").each(function()
	{
		if(jQuery(this).val()==inode)
		{
// 			alert("removing "+inode);
			jQuery(this).remove();
		}
	});
}
