(function($) {
	shuffle = function( list ) {
	    var result = [];
	    while( list.length > 0 ) {
	        var i = Math.floor( list.length * Math.random() );
	        result.push( list.splice( i, 1 )[0] );
	    };
	    return result;
	}
	
	timeAgo = function( dateString ) {
		var diff = new Date().getTime() - new Date( dateString ).getTime();
		var minutes = Math.floor(diff/60000);
		var hours = Math.floor(minutes/60);
		var days = Math.floor(hours /24);
		var weeks = Math.floor(days /7);
		var months = Math.floor(days /30);
		var years = Math.floor(days/365);
		if( years > 1 ) { 
			return years + " years ago"; 
		} else if ( years == 1 ) {
			return years + " year ago";
		} else if ( months > 1 ) {
			return months + " months ago";
		} else if ( months == 1 ) {
			return months + " month ago";
		} else if ( weeks > 1 ) {
			return weeks + " weeks ago";
		} else if ( weeks == 1 ) {
			return weeks + " week ago";
		} else if ( days > 1 ) {
			return days + " days ago";
		} else if ( days == 1 ) {
			return days + " day ago";
		} else if ( hours > 1 ) {
			return hours + " hours ago";
		} else if ( hours == 1 ) {
			return hours + " hour ago";
		} else if ( minutes > 1 ) {
			return minutes + " minutes ago";
		} else if ( minutes == 1 ) {
			return minutes + " minute ago";
		} else {
			return "moments ago";
		}
	}

	stripTags = function( string ) {
    	return string.replace(/<\w+(\s+("[^"]*"|'[^']*'|[^>])+)?>|<\/\w+>/gi, '');
  	} 

	cleanURL = function ( string ) {
		return $.trim(string).replace(/[^A-Z0-9]/g,"-");
	}
	
	elipsify = function( string, length ) {
		var result = stripTags( string );
		var lastPos = 0;
		var nextPos = 0;
		if( result.length <= length ) return result;
		while( ( nextPos = result.indexOf(" ", lastPos+1) ) <= length && nextPos != -1 ) {
			lastPos = nextPos;
		}
		return result.substr(0,lastPos) + "...";
	}
	
	buildCell = function() {
		return $("<div class='block'><a class='articleLink' "+
			"href='javascript:void(0);'><img class='sizer' />"+
			"<img class='cell' src='images/square.png' /><div "+
			"class='hoverer'><div class='background'>&nbsp;</div>"+
	        "<div class='post'><div class='time'>&nbsp;</div>"+
	        "<p class='title'>&nbsp;</p><p class='blurb'>&nbsp;</p>"+
			"<div class='viewPost'>View Post</div></div></div></a></div>");	
	}
	
	buildGrid = function( gridNumber ) {
		var grid = $("<div class='grid'/>");
		var block;
		grid.addClass("grid"+gridNumber);
		for( var i =0; i<9; i++ ) {
			block = buildCell();
			block.addClass("c"+(i+1));
			grid.append( block );
		}
		return grid;
	}
	var gridTypes = [
		[ 'wide','small','small','tall','small','small','big','wide','small'],
		[ 'huge','wide','small','small','tall','small','small','big','wide'],
		[ 'tall','huge','tall','wide','small','wide','tall','big','big'],
	];
	var sizers = {
		small:'square.png',
		tall: 'tall.png',
		wide: 'wide.png',
		big: 'square.png',
		huge: 'huge.png'
	};

    $.fn.pictureGrid = function( items ) {
		var gridNumber = this.children().length % 3 + 1
		var $grid = buildGrid( gridNumber ); 
        items = shuffle(items);
        $.each(items,function(index,item) {
			var $block = $grid.find(".block:eq("+index+")");
			var gridType = gridTypes[gridNumber-1][index];
			var href = item.TYPE == "B" 
				? "article.cfm?aid="+item.ASSETID+"&"+cleanURL(item.TITLE) 
				: "view-video.cfm?id="+item.ASSETID+"&full=1"
			$block.addClass( gridType );
			$block.find("img.sizer")
				.attr("src",'../../usopenwall/images/'+sizers[gridType]);
			$block.find("div.time")
				.text( timeAgo(item.DATEENTERED) )
			$block.find("a.articleLink")
				.attr("href",href)
				.mouseenter(function(){
					$(this).find(".hoverer").fadeIn('fast');
				}).mouseleave(function(){
					$(this).find(".hoverer").fadeOut('fast');
				});
			$block.find("img.cell")
				.attr("src","http://www.hurley.com/img/"+item.IMAGEMEDIUM);
			$block.find("p.title")
				.text(item.TITLE);
			$block.find("p.blurb")
				.html(elipsify(item.SUMMARY,140));
        });
		this.append( $grid ).find("img.cell").center();
		
    }

    $.fn.center = function() {
		this.each(function(elem){
			$this = $(this);
			$parent = $this.parent();
			var top = 0;
			var left = 0;
			if( $this.height() > $parent.height() ) {
				top = 0-($this.height() - $parent.height()) / 2;
			}
			if( $this.width() > $parent.width() ) {
		        left = 0-($this.width() - $parent.width()) / 2;
			}
			$this.css({
				left: left,
				top: top
			});
		});
		return this;
    }
})(jQuery);

$(function(){
	// Handle re-centering everything on resizes, and occasionally, just in case things go weird
	refreshGrids();
	$(window).resize(centerAll);
	window.setInterval( centerAll, 5000 );
	$("#moreLink").click(function() {
		var offset = $("#moreLink").data("offset") || 0;
		offset += 27;
		refreshGrids(offset);
		$("#moreLink").data("offset",offset);
	})
});
$(document).load(function(){
	centerAll();
})

centerAll = function() {
	$(".block img.sizer").each(function(elem) {
		$(this).parent().parent().css('height',$(this).height());
	});
	$(".grid").each(function() {
		var $this = $(this);
		var square = $($this.find(".small")[0]);
		var height = 0;
		if( $this.is(".grid1") ) { height = square.height() * 3; }
		else if ( $this.is(".grid2") ) { height = square.height() * 4; }
		else if ( $this.is(".grid3") ) { height = square.height() * 5; }
		$this.css('height',height);
	});
	$("img.cell").center();
}

refreshGrids = function( offset ) {
	offset = offset || 0;
	$.ajax({
		dataType:"json",
		url:"pictureService.cfc?method=recentPosts",
		data:"offset="+offset,
		success: function(data){
			$("#gridContainer").pictureGrid(data.slice(0, 9));
			$("#gridContainer").pictureGrid(data.slice(9, 18));
			$("#gridContainer").pictureGrid(data.slice(18, 27));
		}
	});
}

