var usedContent = new Array();
var currentFilter;
var contentArray = new Array();

var gridAnimating = false;

var numLayoutColumns = -1;

var cellWidth = 222;
var cellHeight = 330;

var cellBorderWidth = 12;
var cellBorderHeight = 12;

var cellCompleteWidth = cellWidth + (2*cellBorderWidth);
var cellCompleteHeight = cellHeight + (2*cellBorderHeight);

var lastGridCol = 0;
var lastGridRow = 0;

var specialContent = new Array();

var forcePostDiversityOnPage = false;
var enforcingPostDiversity = false;
var tooSamey = false;
var lastPostTypes = new Array();

var headerHeight = 400;

var bSquareOffEnd = true;

var holderLeftPadding = 0;

var maxRows = -1;

var hashAnchor;
var bodyClass;

function logIt(v)
{
	//if(console)
//		console.log(v);
}

function comparatorTitle(itemA, itemB)
{
	if (itemA.attr("title") <  itemB.attr("title"))
		return -1;
	else if(itemA.attr("title") > itemB.attr("title"))
		return 1;
	else
		return 0;
}

function comparatorTitleRev(itemA, itemB)
{
	if (itemA.attr("title") >  itemB.attr("title"))
		return -1;
	else if(itemA.attr("title") < itemB.attr("title"))
		return 1;
	else
		return 0;
}

function getItemMeta(item, metaTag, def)
{
	var tag = item.find("div.content-meta span.meta-info-" + metaTag);

	if(tag.length == 1)
	{
		return jQuery.trim(tag.text());
	}
	else
		return def;
}

function getURLMeta(item)
{
	var tag = item.find("div.content-meta span.meta-info-url a");

	if(tag.length == 1)
	{
		return tag.attr("href");
	}
	else
		return "";
}


function comparatorImportance(itemA, itemB)
{
	var importanceA = parseInt(getItemMeta(itemA, "importance", "0"));
	var importanceB = parseInt(getItemMeta(itemB, "importance", "0"));

	if (importanceA > importanceB)
		return -1;
	else if(importanceA < importanceB)
		return 1;
	else
		return 0;
}


function comparatorPageViews(itemA, itemB)
{
	var importanceA = parseInt(getItemMeta(itemA, "views", "0"));
	var importanceB = parseInt(getItemMeta(itemB, "views", "0"));

	if (importanceA > importanceB)
		return -1;
	else if(importanceA < importanceB)
		return 1;
	else
		return 0;
}

function AllFilter()
{
	this.filterName = "all";
	this.matches = function(jqObj) { return true; };
}

function doTagMatch(jqObj)
{
	// get all the tags as text..

	var tagItems = jqObj.find("div.content-meta ul.content-tags li");

	for(var i=0; i<this.tagList.length; i++)
	{

		for(var j=0; j<tagItems.size(); j++)
		{
			//if(tagItems.eq(j).text().indexOf(this.tagList[i]) != -1)

			if(jQuery.trim(tagItems.eq(j).text()) == jQuery.trim(this.tagList[i]))
			{
				return true;
			}
		}
	}

	return false;
}

function TagFilter(_tagList)
{
	this.tagList = _tagList;
	this.filterName = "tag";
	this.matches = doTagMatch;
}

function doFavMatch(jqObj)
{
	if(getItemMeta(jqObj, "fav", "") == "favorite")
		return true;
	else
		return false;

	return false;
}

function FavoriteFilter()
{
	this.filterName = "favorite";
	this.matches = doFavMatch;
}

function reorderItem(item, posStart, posEnd)
{
	var contents = $(".grid-content-item");
	var newIndex = posStart + Math.floor(Math.random() * (posEnd - posStart));

	$("#" + item).insertBefore(contents.eq(newIndex));

}

function initContent()
{
	for(var j=0; j<specialContent.length; j++)
	{
		reorderItem(specialContent[j].id, specialContent[j].after, specialContent[j].before);
	}

	contentArray = new Array();

	var contents = $(".grid-content-item");
	var numContents = contents.length;

	for(var i=0; i<numContents; i++)
	{
		contentArray.push(contents.eq(i));
	}

}

function sortContent( sortFunc )
{
	contentArray.sort( sortFunc );
}


function getPinnedContent(s, wpId)
{
	for(var k=0; k<contentArray.length; k++)
	{
		var new_content = contentArray[k];		//jQuery('div.grid-content-item:eq('+k+')');
		if(getItemMeta(new_content, "wp-id", "0") == wpId)
		{


			var new_content_sized = new_content.children(s).clone();

			if(new_content_sized.length >= 1)
			{
				var linkURL = getURLMeta(new_content);

				new_content_sized.find(".image-holder").each(function(index) {
					$(this).parent().wrapInner('<a class="tile-shell" href="' + linkURL + '"/>');
					$(this).replaceWith($('<img alt="' + $(this).parent().parent().attr('title') + '" src="' + $(this).attr('href') + '" />'));
				} );

				usedContent.push(k);
				new_content_sized.css('position', 'absolute');

				return new_content_sized;
			}

			return null;
		}
	}
}

function getNextContentWithSize(s, filterObj)
{
	if(tooSamey)
		return false;



	for(var k=0; k<contentArray.length; k++)
	{


		if(jQuery.inArray(k, usedContent) == -1)
		{
			var new_content = contentArray[k];		//jQuery('div.grid-content-item:eq('+k+')');
			if(filterObj.matches(new_content))
			{
				var new_content_sized = new_content.children(s).clone();

				if(new_content_sized.length >= 1)
				{
					var contentType = getItemMeta(new_content, "type", "");


					var sames = 0;
					for(var m=0; m<lastPostTypes.length; m++)
					{
						if(lastPostTypes[m] == contentType)
							sames ++;
					}

					var lastType = "";
					if(lastPostTypes.length > 0)
						lastType = lastPostTypes[lastPostTypes.length-1];


					if(!enforcingPostDiversity || (enforcingPostDiversity && lastType != contentType) || contentType == "" || lastPostTypes.length == 0 || sames == 0 || (contentType == "featured-work" && sames < 2) )		//
					{
						// add twice for doubles.
						if(s == ".grid-content-size-double")
						{
							lastPostTypes.push(contentType);
						}
						lastPostTypes.push(contentType);
						if(lastPostTypes.length > 4)
						{
							lastPostTypes.shift();
						}



						var linkURL = getURLMeta(new_content);
						var titleText = new_content.attr('title');
						new_content_sized.find(".image-holder").each(function(index) {
							$(this).parent().wrapInner('<a class="tile-shell" href="' + linkURL + '"/>');
							$(this).replaceWith($('<img alt="' + titleText + '" src="' + $(this).attr('href') + '" /></a>'));
						} );

						usedContent.push(k);
						new_content_sized.css('position', 'absolute');

						sames = 0;
						for(m in lastPostTypes)
						{
							if(lastPostTypes[m] == contentType)
								sames ++;
						}

						//console.log("" + sames);
						//console.log( "" + lastPostTypes);
						//console.log(contentType);

						if(forcePostDiversityOnPage && !enforcingPostDiversity && filterObj.filterName == "all" && contentType != "")
						{
							// if things have gotten too boring, bail.
							if(sames >= 4)
							{
								//console.log("Too samey!!! " + forcePostDiversityOnPage + " " + enforcingPostDiversity);
								tooSamey = true;


							}
						}


						return new_content_sized;
					}
				}
			} else {

			}
		}
	}


	if(enforcingPostDiversity)
	{
		enforcingPostDiversity = false;
		// try again?
		return getNextContentWithSize(s, filterObj)
	}


	return null;
}

function appearAnimCallback()
{
	var nextElem = $(this).next();

	if(nextElem.length == 1)
	{
		nextElem.show();

		// If this is a mobile device, we might want to skip the animation.

		var realLeft = nextElem.css("left");
		nextElem.css("left", parseInt(realLeft) - 100);
		nextElem.css("opacity", "0");
		nextElem.animate({
			left: "+=100",
			opacity: "1.0"
		}, 100, appearAnimCallback);
	} else {
		gridAnimating = false;
	}
}

function hideAnimCallback()
{
	var nextElem = $(this).next();

	if(nextElem.length == 1)
	{
		nextElem.clearQueue();

		nextElem.animate({
			left: "+=100",
			opacity: "0.0"
		}, 100, hideAnimCallback);

	} else {
		$(this).parent().remove();
	}
}

function eliminateCellsAfter(holder, ypos)
{
	holder.children().each( function(index, Element) {
		if($(this).offset().top >= ypos)
		{
			$(this).remove();
		}

	} );
}

function PerformGridLayout(numCols, numRows, filterObj, addMore)
{
	var i, j, k;
	lastPostTypes = new Array();

	if(filterObj.filterName == "all")
	{
		enforcingPostDiversity = forcePostDiversityOnPage;
	} else {
		enforcingPostDiversity = false;
	}

	if(!addMore)
	{
		//$(".load-more-tiles").removeClass("no-more-content");
		$(".load-more-tiles").css("display", '');

		tooSamey = false;
		lastGridRow = 0;
		lastGridCol = 0;
		if(gridAnimating == true)
		{
			$('#grid-area').empty();
		}
		usedContent = new Array();

	} else {
		//usedContent = new Array();
	}

	if(maxRows != -1 && lastGridRow + numRows > maxRows)
		numRows = maxRows - lastGridRow;

	if(numRows == 0)
		return;


	var layoutGrid = new Array(numRows);

	for(i=0; i<numRows; i++)
		layoutGrid[i] = new Array(numCols);

	for(j=0; j<numRows; j++)
	{
		for(i=0; i<numCols; i++)
		{
			layoutGrid[j][i] = -1;		// set all the cells to 'undefined'.
		}
	}


	gridAnimating = true;

	// do any pinned sizes here
	if(filterObj.filterName == "all")
	{
		for(i=0; i<aPinnedContent.length; i++)
		{
			var _gridX = aPinnedContent[i].index % numCols;
			var _gridY = Math.floor(aPinnedContent[i].index / numCols) - lastGridRow;


			if(_gridY >= 0 && _gridY < numRows)
			{

				if(aPinnedContent[i].size == 3)
				{
					if(Math.random() < 0.5)
					{
						aPinnedContent[i].size = 0;
					} else {
						aPinnedContent[i].size = 2;
					}
				}

				layoutGrid[_gridY][_gridX] = aPinnedContent[i].size;

				if(aPinnedContent[i].size == 2)
				{

					if(_gridX == numCols - 1)	// this won't fit
					{
						layoutGrid[_gridY][_gridX] = 0;
						aPinnedContent[i].size = 0;
					} else {
						layoutGrid[_gridY][_gridX + 1] = 2;
					}
				}

				// Mark this as used so it doesn't get picked before we get to it.
				for(var k=0; k<contentArray.length; k++)
				{
					var new_content = contentArray[k];		//jQuery('div.grid-content-item:eq('+k+')');
					if(getItemMeta(new_content, "wp-id", "0") == aPinnedContent[i].id)
					{
						usedContent.push(k);
						break;
					}
				}
			}
		}
	}

	// Loop through the 'grid' and randomly assign numbers corresponding to the different cell sizes
	// 0 = single, 1 = quarter / three quarter block, etc..
	var szDebug = "";
	var lastChoice = -1;
	for(j=0; j<numRows; j++)
	{
		for(i=0; i<numCols; i++)
		{
			if(layoutGrid[j][i] == -1)
			{
				var choice = -1;

				// pick a random cell type.
				// don't pick the same one twice.
				while(choice == -1 || (choice == lastChoice && lastChoice != 0))
				{
					// If we've reached the rightmost column, we can't fit a double column here, so only pick single or 3/4 blocks.
					if(i<numCols-1)
						choice = Math.floor(Math.random()*2.999);	// random number 0..3
					else
						choice = Math.floor(Math.random()*1.999); 	// random number 0..2
				}

				lastChoice = choice;

				switch(choice)
				{
					case 0:		// single
						layoutGrid[j][i] = 0;
						szDebug += layoutGrid[j][i];
						break;
					case 1:		// quarter / three quarter block
						layoutGrid[j][i] = 1;
						szDebug += layoutGrid[j][i];
						break;
					case 2:		// double
						if(layoutGrid[j][i+1] != -1)			// if Pinned, don't overwrite it.
						{
							layoutGrid[j][i] = 0;
							szDebug += layoutGrid[j][i];
						} else {
							layoutGrid[j][i] = 2;
							layoutGrid[j][i+1] = 2;

							szDebug += layoutGrid[j][i];
							szDebug += layoutGrid[j][i+1];

							i++;
						}
						break;

				}
			} else {
				lastChoice = layoutGrid[j][i];

				if(layoutGrid[j][i] == 2)
				{
					i++;
				}

			}

		}

		lastChoice = -1;

		szDebug += "\n";
	}

	// print out the grid.
	//alert(szDebug);

	var gridArea = $('#grid-area');
	var firstElement;

	if(!addMore)
	{
		gridArea.children().each( function() {
			firstElement = $(this).children().eq(0);
			firstElement.fadeOut(100, hideAnimCallback);
		} );
	}

	//gridArea.empty();
	var holder = $('<div style="position: absolute;"/>');
	holder.offset( {left: holderLeftPadding, top: ((lastGridRow) * cellCompleteHeight) } );
	gridArea.append(holder);

	var noMoreContent = false;

	// now populate the grid with content.

	var linearIndex = (lastGridRow * numCols);

	if(addMore)
		linearIndex += lastGridCol;

	var countCellsAdded = 0;
	i = 0;
	j = 0;
	for(j=0; j<numRows; j++)
	{
		if(addMore && j == 0)
			i = lastGridCol;
		else
			i = 0;
		for(; i<numCols; i++)
		{

			// get the appropriately sized content for each grid cell, and position the blocks.
			var new_content_sized;
			var isPinned = false;
			var pinnedId = -1;

			// pinned stuff only shows when showing all

			if(filterObj.filterName == "all")
			{
				for(k=0; k<aPinnedContent.length; k++)
				{
					if(linearIndex == aPinnedContent[k].index)
					{
						isPinned = true;
						pinnedId = aPinnedContent[k].id;
						break;
					}
				}
			}

			function fillCell(cellType, i, j)
			{
				if(filterObj.filterName == "all")
				{
					enforcingPostDiversity = forcePostDiversityOnPage;
				}

				switch(cellType)
				{
					case 0:
						if(isPinned)
						{
							new_content_sized = getPinnedContent(".grid-content-size-single", pinnedId);

							if(!new_content_sized)
								new_content_sized = getNextContentWithSize(".grid-content-size-single", filterObj);
						} else
							new_content_sized = getNextContentWithSize(".grid-content-size-single", filterObj);

						if(new_content_sized)
						{
							new_content_sized.offset( {left: (i * cellCompleteWidth), top: ((j) * cellCompleteHeight) } );
							holder.append(new_content_sized);
						} else {

							return false;
						}
						break;
					case 1:
						if(isPinned) {
							new_content_sized1 = getPinnedContent(".grid-content-size-quarter", pinnedId);

							if(!new_content_sized1)
								new_content_sized1 = getNextContentWithSize(".grid-content-size-quarter", filterObj);
						} else
							new_content_sized1 = getNextContentWithSize(".grid-content-size-quarter", filterObj);

						if(new_content_sized1)
						{
							new_content_sized1.offset( {left: (i * cellCompleteWidth), top: ((j) * cellCompleteHeight) } );

						} else {

							return false;
						}

						// NOTE: we can't pin a three quarter and a quarter, since we can't uniquely address them under this system.. hopefully we never do that.
						new_content_sized = getNextContentWithSize(".grid-content-size-threequarter", filterObj);
						if(new_content_sized)
						{
							holder.append(new_content_sized1);
							new_content_sized.offset( {left: (i * cellCompleteWidth), top: ((j) * cellCompleteHeight) + 92} );
							holder.append(new_content_sized);
						} else {
							if(new_content_sized1)
								new_content_sized1.remove();

							usedContent.pop();

							return false;
						}

						break;
					case 2:
						if(isPinned) {
							new_content_sized = getPinnedContent(".grid-content-size-double", pinnedId);

							if(!new_content_sized)
								new_content_sized = getNextContentWithSize(".grid-content-size-double", filterObj);
						} else
							new_content_sized = getNextContentWithSize(".grid-content-size-double", filterObj);

						if(new_content_sized)
						{
							new_content_sized.offset( {left: (i * cellCompleteWidth), top: ((j) * cellCompleteHeight) } );
							holder.append(new_content_sized);
						} else {

							return false;
						}
						break;
				}
				countCellsAdded ++;
				return true;
			}



			switch(layoutGrid[j][i])
			{
				case 2:
					if(fillCell(2, i, j))
					{
						layoutGrid[j][i] = 2;
						i++;		// skip over next cell.
						linearIndex++;
						break;
					}
				case 1:
					if(fillCell(1, i, j))
					{
						layoutGrid[j][i] = 1;
						break;
					} else {

					}
				case 0:
					if(fillCell(0, i, j))
					{
						layoutGrid[j][i] = 0;
						break;
					}
				default:

					noMoreContent = true;
					break;
			}



			linearIndex++;

			if(noMoreContent)
				break;
		}

		if(countCellsAdded == 0)
		{
			//alert("No cells added.");
			//holder.remove();
			//return;
		}

		if(holder.children().length == 0)
		{
			$(".load-more-tiles").css("display", 'none');

			holder.remove();
			return;
		}


		lastGridCol = i;

		if(lastGridCol >= numCols)
			lastGridCol = 0;

		var endX = 0;
		var endTop = 0;
		var endItem = holder.children().eq(holder.children().length - 1);

		var finishedRow = false;

		if( i >= numCols )
			finishedRow = true;

		if(endItem.length > 0)
		{

			endTop = endItem.offset().top - gridArea.offset().top;
			endX = endItem.position().left + endItem.width();
		}


		if(noMoreContent)
		{

			// if we have more than one row, and we're in the 'all' mode
			if(j >= 1 && filterObj.filterName == "all" && bSquareOffEnd)
			{

				var ht = ((j - 1 + lastGridRow) * cellCompleteHeight);


				if(ht < cellCompleteHeight)
					ht = cellCompleteHeight;

					/*
					var sames = 0;
					for(var m=0; m<lastPostTypes.length; m++)
					{
						if(lastPostTypes[m] == contentType)
							sames ++;
					}
					*/

				if(endItem.length > 0 && (endX+(cellBorderWidth*2) < cellCompleteWidth * numCols))
				{
					if(endTop != 0)
						ht = endTop;

					if(tooSamey)
					{
						//console.log("Too samey 1");
						//console.log(lastPostTypes);
					}
				} else {
					if(tooSamey)
					{
						//console.log("Too samey 2");
						//console.log(lastPostTypes);
					}
				}



				eliminateCellsAfter(holder, ht + gridArea.offset().top );

				lastGridCol = 0;

				// resize content area..
				gridArea.clearQueue();

				gridArea.animate({height: ht + 'px' }, 500);

				lastGridRow = j - 1 + lastGridRow;
			} else {
				// resize content area..
				gridArea.clearQueue();

				var ht = ((j + lastGridRow) * cellCompleteHeight);

				if(ht < cellCompleteHeight)
					ht = cellCompleteHeight;



					//j -= 1;

				if(endItem.length > 0)
				{
					if(endTop != 0)
						ht = endTop + endItem.height();
				}

				if(tooSamey)
				{
					//console.log("Too Samey!! 3");
					//console.log(lastPostTypes);

				}

				eliminateCellsAfter(holder, ht + gridArea.offset().top );


				gridArea.animate({height: ht + 'px' }, 500);

				lastGridRow = j + lastGridRow;
			}


		} else {
			var ht = ((j +lastGridRow) * cellCompleteHeight);



			if(tooSamey)
			{
				//console.log("Too Samey!! 4");
				//console.log(lastPostTypes);

				if(finishedRow)
					ht -= cellCompleteHeight +  41;

				if(ht < cellCompleteHeight)
					ht = cellCompleteHeight;



				eliminateCellsAfter(holder, ht + gridArea.offset().top );

			} else {
				if(ht < cellCompleteHeight)
					ht = cellCompleteHeight;
			}

			gridArea.clearQueue();
			gridArea.animate({height: ht + 'px' }, 500);

			lastGridRow = j + lastGridRow;
		}


		if(noMoreContent)
		{
			$(".load-more-tiles").css("display", 'none');
			break;
		}
	}
	holder.children().hide();
	firstElement = holder.children().eq(0);

	// begin animation.
	firstElement.delay(500).fadeIn(100, appearAnimCallback);
	


	if ($(window).width() >= 1025) {
			addHoverPanelsOn();
		} else {
			addHoverPanelsOff();
		}

	

}

var aPinnedContent = new Array();

function setPinnedContent(pc)
{
	aPinnedContent = pc;
}

function resizePage()
{


	var newLayoutColumns = 0;


	var w = $('#grid-area').width();
	var availableWidth = w;


	if(availableWidth < 232)
	{
		cellBorderWidth = 0;
		cellBorderHeight = 12;
	} else {
		cellBorderWidth = 12;
		cellBorderHeight = 12;
	}

	cellCompleteWidth = cellWidth + (2*cellBorderWidth);
	cellCompleteHeight = cellHeight + (2*cellBorderHeight);

	holderLeftPadding = 0;

	newLayoutColumns = Math.floor(availableWidth / cellCompleteWidth );

	availableWidth -= newLayoutColumns * cellCompleteWidth;
	if(availableWidth > cellWidth)
		newLayoutColumns += 1;

	if(newLayoutColumns <= 0)
		newLayoutColumns = 1;

	// hackish: make columns match media queries
	if(w == 707)
	{
		newLayoutColumns = 3;
	} else if(w == 468)
	{
		newLayoutColumns = 2;
	} else if(w == 222)
	{
		newLayoutColumns = 1;
	}



	if(newLayoutColumns != numLayoutColumns)
	{
		// TODO: any resizing of the page elements could also be done here.
		numLayoutColumns = newLayoutColumns;

		PerformGridLayout(numLayoutColumns, 3, currentFilter);
	}
	

	
}




function addHoverPanelsOn()
{

		$(".tile-featured-work a, .tile-news a, .tile-article a, .tile-culture-post a, .tile-event-post a").hover(
		function () {
			$(this).children('.content-type1-title').clearQueue();
			$(this).children('.content-type1-title').css("right", -260);
			$(this).children('.content-type1-title').animate({
				right: ['+=260', 'swing']
			}, 300, function() {
				// Animation complete.
			});
		},
		function () {
			$(this).children('.content-type1-title').animate({
				right: ['-=260', 'swing']
			}, 300, function() {
				// Animation complete.
			});
		}
	);

}


function addHoverPanelsOff()
{
	
	$(".tile-featured-work a .content-type1-title, .tile-news a .content-type1-title, .tile-article a .content-type1-title, .tile-culture-post a .content-type1-title, .tile-event-post a .content-type1-title").css("right", 0);
	$(".grid-content-size-quarter .content-type1-title").css("right", -260);
}





function setFilter(sz, szPage, sortFunc)
{
	// revert to standard sorting?

	if(sortFunc != undefined)
		sortContent(sortFunc);
	else
		initContent();

	var pageURL = "" + document.location;
	var pageLink = (pageURL.split('#')[0]);
	if(sz === "all")
	{
		currentFilter = new AllFilter();

		document.location = pageLink + '#all';
	} else if (sz === "contact-us") {
		currentFilter = new AllFilter();
	} else if(sz === "favorite")
	{
		currentFilter = new FavoriteFilter( );
		pageLink = pageLink + "#" + sz;
		document.location = pageLink;
	} else {

		if(sz instanceof Array)
		{
			currentFilter = new TagFilter( sz );

			if (sz.length > 3) {
				pageLink = pageLink + "#" + "popularity";
			} else {
				pageLink = pageLink + "#" + sz[0];
			}
		} else {
			currentFilter = new TagFilter( new Array( sz ) );
			pageLink = pageLink + "#" + sz;
		}

		document.location = pageLink;
	}

	_gaq.push(["_trackPageview", szPage + "/filter-by/" + sz + "/vp"]);

	PerformGridLayout(numLayoutColumns, 3, currentFilter);


}

function update_filter() {
	var selectedfilter = $('#filter_options li.selected').text();
	$('#selected_filter').children().text(selectedfilter);
}

function lazyLoad()
{
	$(".lazy-image-holder").each(function(index) {
		$(this).removeClass("lazy-image-holder");
		var alt = $(this).attr("alt");
		var classStr = $(this).attr("class");
		var idStr = $(this).attr("id");

		$(this).replaceWith($('<img src="' + $(this).attr('href') + '" id="' + idStr + '" alt="' + alt + '" class="' + classStr + '"/>'));
	});
}

$(document).ready(function() {

	// fix for IE specific bug where hash tag replaces title
	if ($.browser.msie) {
		var originalTitle = document.title.split("#")[0];
		document.attachEvent('onpropertychange', function (evt) {
			if(evt.propertyName === 'title' && document.title !== originalTitle) {
				setTimeout(function () {
				   document.title = originalTitle;
				}, 1);
			}
		});
	}

	initContent();
	prettyPrint();
	numLayoutColumns = 0;

	var pageURL = "" + document.location;
	if (pageURL.indexOf('#') != -1) { // the URL contains an anchor

		var myAnchor = (pageURL.split('#')[1]);

		if (myAnchor && myAnchor.length > 0 && myAnchor != "contact-us") {
			if (myAnchor === "news" || myAnchor === "all" || myAnchor === "article" || myAnchor === "featured-work" || myAnchor === "popularity" || myAnchor === "favorite" || myAnchor === "post" || myAnchor === "job-opening" || myAnchor === "culture-post" || myAnchor === "event-post" || myAnchor === "mobile" || myAnchor === "websites" || myAnchor === "social-media" || myAnchor === "campaign" || myAnchor === "application") {
				if (myAnchor == "all") {
					currentFilter = new AllFilter();
				} else if (myAnchor == "favorite") {
					currentFilter = new FavoriteFilter();
				} else if (myAnchor == "popularity") {
					maxRows = 3;
					setFilter(["featured-work", "article", "news", "post", "blog" ], "home", comparatorPageViews);
				} else if (myAnchor == "article") {
					if ($("body").hasClass("home")) {
						setFilter( ["article", "culture-post"], "home");
					} else {
						currentFilter = new TagFilter( new Array(myAnchor) );
					}
				} else if (myAnchor == "news") {
					if ($("body").hasClass("home")) {
						setFilter( ["news", "event-post"], "home");
					} else {
						currentFilter = new TagFilter( new Array(myAnchor) );
					}
				} else {
					currentFilter = new TagFilter( new Array(myAnchor) );
				}
				$("#filter_options li").removeClass("selected");
				$("." + myAnchor).parent().addClass("selected");
				update_filter();
			} else {
				currentFilter = new AllFilter();
				myAnchor = "all";
			}
		} else if (myAnchor == "contact-us") {
			//set default filter to all filter
			currentFilter = new AllFilter();
		} else if (myAnchor == "") {
			//set default filter to all filter
			currentFilter = new AllFilter();
		}

	} else {
		currentFilter = new AllFilter();
	}

	$(window).bind('hashchange', function () {
		var hashURL = "" + document.location;
		var hashAnchor = (hashURL.split('#')[1]);
		var bodyClass = $("body").attr("class");

		if (hashAnchor == "news" || hashAnchor == "all" || hashAnchor == "article" || hashAnchor == "featured-work" || hashAnchor == "popularity" || hashAnchor == "favorite" || hashAnchor == "post" || hashAnchor == "job-opening" || hashAnchor == "culture-post" || hashAnchor == "event-post" || hashAnchor == "mobile" || hashAnchor == "websites" || hashAnchor == "social-media" || hashAnchor == "campaign" || hashAnchor == "application") {
			if (hashAnchor == "news" && bodyClass == "home") {
				maxRows = -1;
				setFilter( ["news", "event-post"], "home");
			} else if (hashAnchor == "popularity" && bodyClass == "home") {
				maxRows = 3;
				setFilter(["featured-work", "article", "news", "post", "blog" ], "home", comparatorPageViews);
			} else if (hashAnchor == "article" && bodyClass == "home") {
				maxRows = -1;
				setFilter( ["article", "culture-post"], "home");
			} else if (hashAnchor == "favorite" && bodyClass == "home") {
				maxRows = -1;
				setFilter("favorite", "home");
			} else if (hashAnchor != null) {
				setFilter(hashAnchor, bodyClass);
			}
			if ($("div.contact-us-modal-positioning").hasClass("contact-us-open")) {
				$('div.contact-us-modal-positioning').removeClass('contact-us-open');
				$('div.contact-us-modal-positioning').addClass('contact-us-closed');
				$('div.contact-us-modal-positioning').animate({bottom:300}, 500, 'swing',function() {
					$(this).css('z-index', '1000');
					$('div.contact-us-modal-positioning').animate({bottom:-585}, 500, 'swing', function() {
						$(this).css('display', 'none');
					});
				});
			} else {
				//do nothing
			}
			$("#filter_options li").removeClass("selected");
			$("." + hashAnchor).parent().addClass("selected");
			update_filter();
		} else if (hashAnchor == "contact-us") {
			if ($("div.contact-us-modal-positioning").hasClass("contact-us-open")) {
				//do nothing
			} else {
				$('div.contact-us-modal-positioning').css('display', 'block');
				$('div.contact-us-modal-positioning').animate({bottom:300}, 500, 'swing',function() {
					$(this).removeClass('contact-us-closed');
					$(this).addClass('contact-us-open');
					$(this).css('z-index', '3000');
					$(this).animate({bottom:155}, 500, 'swing');
				});
			}
		} else if (hashAnchor == "") {
			//do nothing
			if ($("div.contact-us-modal-positioning").hasClass("contact-us-open")) {
				$('div.contact-us-modal-positioning').removeClass('contact-us-open');
				$('div.contact-us-modal-positioning').addClass('contact-us-closed');
				$('div.contact-us-modal-positioning').animate({bottom:300}, 500, 'swing',function() {
					$(this).css('z-index', '1000');
					$('div.contact-us-modal-positioning').animate({bottom:-585}, 500, 'swing', function() {
						$(this).css('display', 'none');
					});
				});
			} else {
				//do nothing
			}
		} else {
			if ($("div.contact-us-modal-positioning").hasClass("contact-us-open")) {
				$('div.contact-us-modal-positioning').removeClass('contact-us-open');
				$('div.contact-us-modal-positioning').addClass('contact-us-closed');
				$('div.contact-us-modal-positioning').animate({bottom:300}, 500, 'swing',function() {
					$(this).css('z-index', '1000');
					$('div.contact-us-modal-positioning').animate({bottom:-585}, 500, 'swing', function() {
						$(this).css('display', 'none');
					});
				});
			} else {
				//do nothing
			}
			currentFilter = new AllFilter();
			PerformGridLayout(numLayoutColumns, 3, currentFilter);
			hashAnchor = "all";
			$("#filter_options li").removeClass("selected");
			$("." + hashAnchor).parent().addClass("selected");
			update_filter();
		}
	});

	resizePage();
	//setTimeout("resizePage()", 500);
	lazyLoad();

	$(window).resize(function() {
		resizePage();
	});

	$(window).scroll(function(){
		var scrollAmt = window.pageYOffset;
		var windowHt = window.innerHeight;
		var docHt = $(document).height();

		if(scrollAmt === undefined)
		{

			//var myregex = /MSIE 7\.0/i;
			//var myArray = navigator.appVersion.match(myregex);

			scrollAmt = $(window).scrollTop();
			windowHt = $(window).height();
		}

		if(scrollAmt + 200 >= docHt - windowHt && numLayoutColumns > 2)
		{
			PerformGridLayout(numLayoutColumns, 3, currentFilter, true)	;
		}

	} );

	
});


$(window).resize(function() {
		if ($(window).width() >= 1025) {
			$(".tile-featured-work a .content-type1-title, .tile-news a .content-type1-title, .tile-article a .content-type1-title, .tile-culture-post a .content-type1-title, .tile-event-post a .content-type1-title").removeAttr("style");
			addHoverPanelsOn();
		} else {
			$(".tile-featured-work a .content-type1-title, .tile-news a .content-type1-title, .tile-article a .content-type1-title, .tile-culture-post a .content-type1-title, .tile-event-post a .content-type1-title").removeAttr("style");
			addHoverPanelsOff();
		}
	});

