$(document).ready(function(){
	var section = $('body div#wrap').attr('class');
	
	
	//remove attribute style to revert back to original colour
	
	$('.hoverBox').hover(
			  function () {
			    
			  },
			  function () {
			    $(this).find('a').removeAttr("style");
			  }
			);
	
	
	$(window).scroll(function(){
		// infinte scroll trigger
		if  ($(window).scrollTop() == $(document).height() - $(window).height()){
			
			loadCovers();
			updateStatTrackers ();
			
        }
	});
	
	

	function loadCovers() {
		// ajax function to load further custom covers
		var count = $('#archives > div.hoverBox').size();
		
		$.getJSON('/ajaxload/' + section + '/'+count, function (data) {
			var thumbDiv = $('#archives > div.hoverBox:first');
			jQuery.each(data, function(i, val) {
				var newDiv = thumbDiv.clone(false);
				
				// Depending on the response, we may be using either the old CMA or new CMS. Check now:
				if(val.name !== undefined)
				{
					// CMA
					newDiv.find('a:eq(1)').text('loading...');
					newDiv.find('img:first').removeAttr('src');
					newDiv.find('img:first').attr( { 'src' : val.image} );
					newDiv.find('a').removeAttr('href');
					newDiv.find('a').attr( { 'href' : val.url} );
					newDiv.find('a:eq(1)').html(val.name);
				}
				else
				{
					// CMS
					$('a:eq(1)', newDiv).text('loading...');
					$('img:first', newDiv).attr('src', val.image);
					$('a', newDiv).attr('href', val.link);
					$('a:eq(1)', newDiv).html(val.headline);
				}
				
				newDiv.appendTo($('#archives'));
			});
		});
		
		
	}
	
	function updateStatTrackers () {
		
		// update omniture + google analytics on image swap
		if (typeof s != "undefined") 
		{
			void(s.t());
		}
		if (typeof localPageTracker0 != "undefined") 
		{
			var gaStr	=	getGAURL();
			localPageTracker0._trackPageview(gaStr)
		}

	}

	function getGAURL() {
		// get the page name for Google Analytics tracking
		// for a href of http://www.wallpaper.com//custom-covers/design-museum/gallery/2529 the pagename is /custom-covers/design-museum/gallery/2529
		var tmpStr	=	window.location.href.split('#')[0]; // remove any hash
		var tmpArray	=	tmpStr.split('/');
		var str	=	"/";
		var max	=	tmpArray.length;
		for (var i=3;i<max;i++)
		{
			str	+= tmpArray[i]+"/";
		}
		return str.substring(0,str.length-1);
	}
	
});





