//ROTATE IMAGES FROM HOMEPAGE_FLASH FOLDER
//Written By Joel Grannas - Creative Director @ Schoolwires

(function($){
    $.fn.rotateJSON = function(settings){
        //SETTINGS
	var config = {
		'siteID'	: '0',
		'baseFolder'	: 'homepage_flash',
		'folderName'	: 'set1',
		'random'	: 'yes',
		'delay'		: 10,
		'fadeSpeed'	: 1,
		'width'		: '300px',
		'height'	: '300px',
		'static'	: 'none'
	};
	if (settings){$.extend(config, settings);}
	  	
        return this.each(function(settings){
        	var element = this;
        	//SET CSS FOR CONTAINER
        	$(element).css({
        		"overflow"	: "hidden",
        		"width"		: config.width,
        		"height"	: config.height
        	});
        	var url = "/site/handlers/getimagesxml.ashx?SiteID=" + config.siteID + "&base_folder=" + config.baseFolder + "&foldername=" + config.folderName + "&output=1";
        	//*****************************
        	//BUILD ARRAY OF IMAGES
        	$.getJSON(url, function(data) {
        		var imagesArray = new Array();
			$.each(data.images, function(i){
				imagesArray.push(data.images[i]);
			});
			buildRotate(imagesArray);
		});
		function buildRotate(imagesArray){
			//SORT IMAGES RANDOMLY (IF CALLED)
			if(config.random !== "no"){
				imagesArray = imagesArray.sort(function(){return 0.5 - Math.random()});
			}
			//PLACE THE IMAGES
			$.each(imagesArray, function(i){
				$("<img/>").attr("src",imagesArray[i]).css("position","absolute").appendTo(element).hide();
			});
			$("img:last",element).fadeIn("fast");
			//ROTATE THE IMAGES
			if(imagesArray.length > 1){
				rotateTimer = setInterval(function(){
					var nextToLast = "img:eq(" + (imagesArray.length-2) + ")";
					$(nextToLast,element).show();
					$("img:last",element).fadeOut(config.fadeSpeed*1000, function(){
						$(this).parent().prepend(this);
						$(this).hide();
					});
				}, config.delay*1000);
			}
			if(!imagesArray.length){
				$("<img/>").attr("src",config.static).css("position","absolute").appendTo(element);	
			}
		}
        	//*****************************
        });
    };
})(jQuery);

