(function(){
	window.cache = [];
	var imgArr = [],
	displayStyle = "none",
	shown = true,
	src = "hide";
	$.fn.slideFn = $.fn.slideDown;
	$("#prev").css("visibility","hidden")
	$("#hide").click(function(){
		var html = $(this).html();
		if (shown) {
			displayStyle = "block";
			$.fn.slideFn = $.fn.slideUp;
			html = "- Show text";
			src = "show";
			shown = false;
		}
		else {
			displayStyle = "none";
			$.fn.slideFn = $.fn.slideDown;
			html = "- Hide text";
			src = "hide";
			shown = true;
		};
		$(this).html(html).css("backgroundImage","url(/images/"+src+".jpg)");
		$("#news,#welcome,h1").stop().slideFn(function(){
			document.getElementById("caption").style.display = displayStyle;
			if(displayStyle === "none") $("#news,#welcome,h1").removeAttr("style");
		});
	});	
	
	function Background(img) {
		this.elem = new Image();
		this.elem.src = "/images/backgrounds/" + img.url;
		this.caption = img.caption;
		this.cacher = (function(e){
			cache.push(e);
		})(this.elem);
	}
	
	var body2 = $("#body2"),
	body3 = $("#body3").css("opacity",0),
	count = 1,
	doInterval = true;
	$("#prev").click(function(){
		showBackground(count-1);
		doInterval = false;
	});
	$("#next").click(function(){
		showBackground(count+1);
		doInterval = false;
	});
	
	function showBackground(i) {
		if(i > (cache.length-2)) {
			i = 1;
		} else if(i < 1) {
			i = cache.length-2;
		};
		
		if(imgArr.length === 1) { setBackgrounds(true); }
		else {doBg(i)}
		
		count = i;
		
		if(doInterval) {
			setTimeout(function(){
				showBackground(count+1)
			},10e3);
		};
		
	};
	
	function doBg(bgCount) {
		body3.css({"background-image":"url(/images/backgrounds/bg"+bgCount+".jpg)"});
		body3.stop().animate({"opacity":1},function(){
			body2.css({"background-image":"url(/images/backgrounds/bg"+bgCount+".jpg)"});
			body3.css({"opacity":0});
		});
		document.getElementById("caption").innerHTML = imgArr[bgCount].caption;
		$("#prev").css("visibility",bgCount <= 1 ? "hidden" : "visible");
		$("#next").css("visibility",(bgCount >= (cache.length-2)) ? "hidden" : "visible");
	};
	
	function setBackgrounds() {
		$.ajax({
			type: "GET",
			url: "/backgrounds.asp",
			dataType: "json",
			cache: false,
			success: function(json) {
				for(var x in json) {
					var image = new Background(json[x]);
					imgArr.push(image);
				};
				showBackground(1);
			},
			error: function(e){window.ajaxErrorResponse = e}
		});
	};
	
	setBackgrounds();

})();

