function ensurePackage(packageName) {
	var package_parts = packageName.split(".");
	var package_so_far = this;
	for (var i = 0; i < package_parts.length; i += 1) {
		var package_part = package_parts[i];
		if (!package_so_far[package_part]) {
			package_so_far[package_part] = {};
		}
		package_so_far = package_so_far[package_part];
	}
	return package_so_far;
}

ensurePackage('SuchMuch');

SuchMuch.dom = new (function dom() {
	
	this.getAncestorByAttribute = function (obj, attrName, attrValue) {
		return obj[attrName].toLowerCase() === attrValue.toLowerCase() ? obj : arguments.callee(obj.parentNode, attrName, attrValue); 
	};
	
	this.showHiddenBlock = function (obj, target, showText, hideText) {
		if (typeof obj === 'string') {
			obj = document.getElementById(obj);
		}
		if (typeof target === 'string') {
			target = document.getElementById(target);
		}
		obj.style.display = (obj.style.display === 'block') ? 'none' : 'block';
		target.innerHTML = target.innerHTML === showText ? hideText : showText;
		
	};
	
})();

SuchMuch.anim = new (function animation() {
	
	var that = this;
	
	this.setOpacity = function (element, amount) {
		if(element.filters) {
			element.style.filter="progid:DXImageTransform.Microsoft.Alpha(opacity=" + amount + ")";
		} else {
			element.style.opacity = amount/100;
		}
	};
	
	this.removeOpacity = function(element) {
		if(element.filters) {
			element.style.filter="";
		}
	};

	this.fadeIn = function (obj, duration) {
		var increment = 5;
		var totalOpacity = 100;
		var number_of_changes = totalOpacity / increment;
		var frequency = Math.ceil(duration / number_of_changes);

		var interval;
		var currentOpacity = 0;
		var callback = function() {
			currentOpacity = currentOpacity + increment;
			if (currentOpacity < 100) {
				that.setOpacity(obj, currentOpacity);
			} else {
				clearInterval(interval);
				that.removeOpacity(obj);
			}
		};
		interval = setInterval(callback, frequency);
	};
	
	this.fadeOut = function (obj, duration, finalCallback) {
		var increment = 5;
		var totalOpacity = 100;
		var number_of_changes = totalOpacity / increment;
		var frequency = Math.ceil(duration / number_of_changes);
		 
		var interval;
		var currentOpacity = 100;
		var callback = function() {
			currentOpacity = currentOpacity - increment;
			if (currentOpacity > 0) {
				that.setOpacity(obj, currentOpacity);
			} else {
				clearInterval(interval);
				that.setOpacity(obj, 0);
				setTimeout(finalCallback, 200);
			}
		};
		interval = setInterval(callback, frequency);
	};
	
})();

SuchMuch.events = new (function events() {

	var instance = this;
	var loadEventList = [];
	
	loadEventList.addLoadEvent = function(fn){
	    loadEventList[loadEventList.length] = fn;
	};
	
	this.loadEventListHasFired = false;

	loadEventList.fireLoadEvents = function(){
	    for (var i = 0; i < loadEventList.length; i++) {
	        loadEventList[i]();
	    }
	    instance.loadEventListHasFired = true;
	};
	
	this.addEvent = function (obj, type, fn) {
	    if (type === "load") {
	        loadEventList.addLoadEvent(fn);
    	    return true;
		}

		if (typeof obj === "string") {
			obj = document.getElementById(obj);
		}
		if (!obj) {
			return null;
		}
    
	    if (obj.addEventListener) {
	        obj.addEventListener(type, fn, false);
	        return true;
	    } else if (obj.attachEvent) {
            var r = obj.attachEvent("on" + type, fn);
            return r;
        } else {
            return false;
        }
	};

	if (/WebKit/i.test(navigator.userAgent)) { // Safari
	    var _timer = setInterval(function() {
	        if (/loaded|complete/.test(document.readyState)) {
	            clearInterval(_timer);
	            loadEventList.fireLoadEvents(); // call the onload handler
	        }
	    }, 100);
	} else if (document.addEventListener) {
		document.addEventListener("DOMContentLoaded", loadEventList.fireLoadEvents, false);
	} else {
	    // IE HACK
	    /*@cc_on @*/
	    /*@if (@_win32)
	     document.write("<script id='__ie_onload' defer='defer' src='//:'><\/script>");
	     var script = document.getElementById("__ie_onload");
	     script.onreadystatechange = function() {
		     if (this.readyState == "complete") {
			     loadEventList.fireLoadEvents(); // call the onload handler
		     }
	     };
	     @else @*/
	     window.onload = loadEventList.fireLoadEvents;
	     /*@end @*/
	}
	this.stop = function (event) {
		event = event || window.event; //IE.
		if (event.preventDefault) {
			event.preventDefault();
		} else { //IE
			event.returnValue = false;
		}
		if (event.stopPropagation) {
			event.stopPropagation();
		} else { //IE. Again.
			event.cancelBubble = true;
		}
	};
	
	this.getElement = function (event) {
		if ( !event.target ) {
			event.target = event.srcElement || document;
		}
		// check if target is a textnode (safari)
		if ( event.target.nodeType == 3 ) {
			event.target = event.target.parentNode;
		}
		return event.target;
	};
	
})();

SuchMuch.CaseStudySwitcherController = function(view, service) {
	// Settings
	var delay = 5; // seconds
	var number_of_case_studies = service.getNumberOfCaseStudies();
	
	var delay_ms = delay * 1000;
	var that = this;
	
	this.switchCaseStudy = function() {
		var currentCaseStudyId = view.getCurrentCaseStudy().id;
		var newCaseStudyId;
		if (currentCaseStudyId < number_of_case_studies) {
			newCaseStudyId = currentCaseStudyId + 1;
		} else {
			newCaseStudyId = 1;
		}
		var newCaseStudy = service.getCaseStudy(newCaseStudyId);
		
		view.setNewCaseStudy(newCaseStudy, that.switchCaseStudy, delay_ms);
	};
	
	this.onLoad = function() {
		view.setCaseStudyTimeout(that.switchCaseStudy, delay_ms)
	};
	
	view.addLoadEvent(this.onLoad);
};

SuchMuch.CaseStudySwitcherView = function(caseStudyDiv) {
	var currentCaseStudy;
	var that = this;
	this.getCurrentCaseStudy = function() {
		if (currentCaseStudy) {
			return currentCaseStudy;
		}
		return { 'id' : 1 }
	};
	
	this.addLoadEvent = function(callback) {
		SuchMuch.events.addEvent(null, 'load', callback);
	};	
	
	this.setCaseStudyTimeout = function(callback, delay) {
		setTimeout(callback, delay)
	}; 
	
	this.setNewCaseStudy = function(caseStudy, callback, delay) {
		var updateInfoCallback = function() {
			document.getElementById('case-study-title').innerHTML = caseStudy.title;
			document.getElementById('case-study-number').innerHTML = caseStudy.id;
			document.getElementById('case-study-image').src = caseStudy.image;
			document.getElementById('case-study-venue').innerHTML = caseStudy.venue;
			document.getElementById('full-story-link').href = caseStudy.url;
			SuchMuch.anim.fadeIn(caseStudyDiv, 500);
			currentCaseStudy = caseStudy;
			that.setCaseStudyTimeout(callback, delay)
		}
		SuchMuch.anim.fadeOut(caseStudyDiv, 500, updateInfoCallback);
	};
};

SuchMuch.CaseStudySwitcherService = function() {
	var caseStudies = [
		{
			'id' : 1,
			'title' : 'Butlins Butterflies ',
			'url' : '/case-studies/index.html',
			'image' : '/images/case-studies/front/case1.jpg',
			'venue' : 'Butlins'
		},	
		{
			'id' : 2,
			'title' : 'The Big Chill',
			'url' : '/case-studies/case2.html',
			'image' : '/images/case-studies/front/case2.jpg',
			'venue' : 'The Big Chill'
		},	
		{
			'id' : 3,
			'title' : 'Bath Fashion',
			'url' : '/case-studies/case3.html',
			'image' : '/images/case-studies/front/case3.jpg',
			'venue' : 'Assembly Rooms'
		}
	];
	
	this.getNumberOfCaseStudies = function() {
		return caseStudies.length;
	};
	
	this.getCaseStudy = function(studyId) {
		//overkill.
		for (var i = 0; i < caseStudies.length; i++) {
			if (caseStudies[i].id === studyId) {
				return caseStudies[i];
			}
		}
	};
};




