// JavaScript Random Images originally developed by Matt Ditter (April 2009)
// jQueryized/Updated to support unique random numbers by Derrick Gall (May 22, 2009)

$.fn.randomize = function(options) {
	if (!options) options = {};
	if (!options.numberOf) options.numberOf = 1;
	if (!options.altTags) options.altTags = [];
	
	// Used to generate a random number that was not used last time
	function uniqueRandom(cookie) {
		// Generate random number not equal to cookie
		do var num = Math.ceil(Math.random() * options.numberOf);
		while (num == cookie)
		return num;
	}
	
	// Used to store cookies
	function createCookie(name, value, days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime() + (days * 24 * 60 * 60 *1000));
			var expires = '; expires=' + date.toGMTString();
		} else expires = '';
		document.cookie = name + '=' + value + expires + '; path=/';
	};
	
	// Used to read cookies
	function readCookie(name) {
		var nameEQ = name + '=',
		ca = document.cookie.split(';');
		for(var i=0; i < ca.length; i++) {
			var c = ca[i];
			while (c.charAt(0) == ' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	}
	
	// For randomizing images
	if ($(this).is('img')) {
		// randomCooke = randomizeImage and whatever the images name is with out the last numbers and extension
		var randomCookie = 'randomizeImage' + $(this).attr('src').replace(/.*\/([^\d]+)\d+(\.\w+)$/g, '$1'),
		// Get random image number that was not the last image loaded
		num = uniqueRandom(readCookie(randomCookie));
		// Set image src
		$(this).attr('src', $(this).attr('src').replace(/\d+(\.\w+)$/g, num + '$1'));
		// Set image alt if it exists
		if (options.altTags[num]) $(this).attr('alt', options.altTags[num]);
	}
	
	// For randomizing divs
	if ($(this).children()[0]) {
		// randomCooke = randomizeParent and ID if it has one
		var randomCookie = 'randomizeParent';
		if ($(this).attr('id')) randomCookie += $(this).attr('id');
		// Set numberOf = to the number of children
		options.numberOf = $(this).children().length;
		// Get random child number that was not the last image loaded
		num = uniqueRandom(readCookie(randomCookie));
		// Hide every child that is not at the index of num
		$(this).children(':eq(' + (num - 1) + ')').siblings().hide();
	}
	
	// Save random number
	if (randomCookie) createCookie(randomCookie, num, 365);
}

