var CS = {
	items : null,
	siteUrl : null,
	uploadsUrl : null,
	templateUrl : null,
	
	JQs : null,

	timer : null,
	startTimer : function () {
		CS.timer = setInterval(CS.updateTile, 7000);
	},

	init : function () {
		CS.JQs = jQuery('.replaceable');

		// populate all replaceable elements
		var tilesToPopulate = CS.JQs.length;
		if (CS.JQs.length > CS.items.length) {
			tilesToPopulate = CS.items.length;
		}
		
		for (var i = 0; i < tilesToPopulate; i += 1) {
			var $element = null;
			if (CS.JQs.length > CS.items.length) {
				var $elements = CS.JQs;
				var tileIndex = null;
				
				tileIndex = CS.getRandomInt(0, $elements.length - 1);
				$element = $elements[tileIndex];
				$elements.splice(tileIndex, 1);
			} else {
				$element = CS.JQs[i];
			}
			
			if (CS.items[0]) {
				CS.setValues($element, CS.items[0]);		
			}
		}
		
		CS.startTimer();
	},

	setValues : function (jq, item) {
		jq = jQuery(jq);

		if (item.type && item.type !== 'client') {
			jq.attr('href', CS.getUrl(item));
		}
		
		CS.items.splice(jQuery.inArray(item, CS.items), 1);
		if (jq.data('tile')) {
			CS.items.push(JSON.parse(jq.data('tile')));
		}
		jq.data('tile', JSON.stringify(item));
		
		var images = jq.find('img');
		jQuery(images[0]).fadeOut('slow');
		setTimeout(function () {
			jQuery(images[0]).attr('src', CS.getImageUrl(item, false));
			jQuery(images[1]).attr('src', CS.getImageUrl(item, true));

			setTimeout(function () {
				jQuery(images[0]).fadeIn('slow');
			}, 300);
		}, 600);
	},

	// replace a single tile
	updateTile : function () {
		var tileIndex = CS.getRandomInt(0, CS.JQs.length - 1);
		var newIndex = CS.getRandomInt(0, CS.items.length - 1);

		if (CS.items[newIndex]) {
			CS.setValues(CS.JQs[tileIndex], CS.items[newIndex]);		
		}
	},

	getRandomInt : function (min, max) {
		return Math.floor(Math.random() * (max - min + 1)) + min;
	},

	getImageUrl : function (item, hover) {
		var dir = (item.type && item.type == 'client') ? CS.templateUrl + '/clients' : CS.uploadsUrl;
		return  dir + '/' + item.img + (hover ? '_hover.jpg' : '.jpg');
	},

	getUrl : function (item) {
		return CS.siteUrl + (item.type == 'post' ? '/' : '/case-study/') + item.slug;
	}
};
