var jta_projects = [
    {
        id: "001",
        title: "Agrarian Vernacular Estate with 8,000 sf. Greenhouse",
        location: "Park City, UT",
        description1: "Green construction using reclaimed structural and finish materials",
        description2: "Heated and cooled by ground-source heat pumps",
		images: "project-001-01.jpg,project-001-02.jpg,project-001-03.jpg,project-001-04.jpg,project-001-05.jpg,project-001-06.jpg,project-001-07.jpg,project-001-08.jpg,project-001-09.jpg,project-001-10.jpg,project-001-11.jpg,project-001-12.jpg,project-001-13.jpg"
    },
    {
        id: "002",
        title: "Red Cloud at Empire Pass Residence",
        location: "Deer Valley, UT",
        description1: "Ski-in, ski-out property at 9,000 ft. elevation",
        description2: "Delicately sited within mature evergreen forest",
		images: "project-002-01.jpg,project-002-02.jpg,project-002-03.jpg,project-002-04.jpg,project-002-05.jpg,project-002-06.jpg,project-002-07.jpg,project-002-08.jpg,project-002-09.jpg,project-002-10.jpg,project-002-11.jpg,project-002-12.jpg,project-002-13.jpg,project-002-14.jpg"
    },
    {
        id: "003",
        title: "White Pine Canyon Contemporary",
        location: "Park City, UT",
        description1: "Design roots in New England farmhouse architecture",
        description2: "Zero-maintenance exterior finishes",
		images: "project-003-01.jpg,project-003-02.jpg,project-003-03.jpg,project-003-04.jpg,project-003-05.jpg,project-003-06.jpg,project-003-07.jpg,project-003-08.jpg,project-003-09.jpg,project-003-10.jpg,project-003-11.jpg"
    },
    {
        id: "004",
        title: "Contemporary Colony House",
        location: "Park City, UT",
        description1: "Exposed curvilinear structure",
        description2: "",
		images: "project-004-01.jpg,project-004-02.jpg,project-004-03.jpg,project-004-04.jpg"
    },
    {
        id: "005",
        title: "Promontory Family Home",
        location: "Park City, UT",
        description1: "Stepped pavilion house, maximizing views",
        description2: "",
		images: "project-005-01.jpg,project-005-02.jpg,project-005-03.jpg"
    },
    {
        id: "006",
        title: "Arts and Crafts Colony Home",
        location: "Park City, UT",
        description1: "Ski-in/Ski-out",
        description2: "Contemporary Colony home",
		images: "project-006-01.jpg,project-006-02.jpg,project-006-03.jpg,project-006-04.jpg"
    },
    {
        id: "007",
        title: "Colony Family Ski Home",
        location: "Park City, UT",
        description1: "Contemporary transitional",
        description2: "Clean expression of structure",
		images: "project-007-01.jpg,project-007-02.jpg,project-007-03.jpg,project-007-04.jpg,project-007-05.jpg,project-007-06.jpg"
    },
    {
        id: "008",
        title: "Bald Eagle Timber Frame Home",
        location: "Deer Valley, UT",
        description1: "Post and beam structure",
        description2: "Clean expression of structure",
		images: "project-008-01.jpg,project-008-02.jpg,project-008-03.jpg"
    },
    {
        id: "009",
        title: "Bald Eagle Log Frame Home",
        location: "Deer Valley, UT",
        description1: "",
        description2: "",
		images: "project-009-01.jpg"
    },
    {
        id: "010",
        title: "Colony Mountain Home",
        location: "Park City, UT",
        description1: "Reclaimed timber trusses and siding",
        description2: "",
		images: "project-010-01.jpg,project-010-02.jpg,project-010-03.jpg,project-010-04.jpg"
    },
    {
        id: "011",
        title: "Colony Ridgeline Estate",
        location: "Park City, UT",
        description1: "Staggered pavilions responding to views and vegetation",
        description2: "Contemporary with its roots in mining vernacular",
		images: "project-011-01.jpg,project-011-02.jpg,project-011-03.jpg,project-011-04.jpg,project-011-05.jpg,project-011-06.jpg"
    },
    {
        id: "012",
        title: "Colony Tree House",
        location: "Park City, UT",
        description1: "Cruciform house plan in the evergreens",
        description2: "",
		images: "project-012-01.jpg,project-012-02.jpg,project-012-03.jpg,project-012-04.jpg"
    },
    {
        id: "013",
        title: "Bald Eagle Rustic Ski Home",
        location: "Deer Valley, UT",
        description1: "Adirondack vernacular and details",
        description2: "",
		images: "project-013-01.jpg,project-013-02.jpg,project-013-03.jpg"
    },
    {
        id: "014",
        title: "Glenwilde Golf Home",
        location: "Park City, UT",
        description1: "New England shingle-style vernacular",
        description2: "",
		images: "project-014-01.jpg,project-014-02.jpg,project-014-03.jpg,project-014-05.jpg"
    },
    {
        id: "015",
        title: "Colony Home at 9,000 ft. Elevation",
        location: "Park City, UT",
        description1: "Shaker/agrarian design roots",
        description2: "Indoor lap pool",
		images: "project-015-01.jpg,project-015-02.jpg,project-015-03.jpg,project-015-04.jpg,project-015-05.jpg,project-015-06.jpg,project-015-07.jpg,project-015-08.jpg"
    },
    {
        id: "016",
        title: "Deer Valley Mountain Contemporary",
        location: "Deer Valley, UT",
        description1: "Reflections of Le Corbusier and Hugh Newell Jacobsen",
        description2: "",
		images: "project-016-01.jpg,project-016-02.jpg,project-016-03.jpg"
    },
    {
        id: "017",
        title: "Colonu Rustic House",
        location: "Park City, UT",
        description1: "",
        description2: "",
		images: "project-017-01.jpg"
    },
    {
        id: "018",
        title: "Straw Bale House",
        location: "Park City, UT",
        description1: "Lime plaster straw bale construction",
        description2: "All structural and finish materials reclaimed",
		images: "project-018-01.jpg,project-018-02.jpg,project-018-03.jpg,project-018-04.jpg,project-018-05.jpg"
    },
    {
        id: "019",
        title: "Empire Pass Residential Development",
        location: "Deer Valley, UT",
        description1: "Site-specific design; ski-in, ski-out properties",
        description2: "Eighteen custom-designed units",
		images: "project-019-01.jpg,project-019-02.jpg,project-019-03.jpg,project-019-04.jpg"
    },
    {
        id: "021",
        title: "Colony Ski-in, Ski-out Estate with Ski Kiva",
        location: "Park City, UT",
        description1: "Unique star-shaped floor plan to capture adjacent peak views",
        description2: "Mountain contemporary vernacular",
		images: "project-021-01.jpg,project-021-10.jpg,project-021-11.jpg"
    },
    {
        id: "051",
        title: "Egyptian Theater",
        location: "Park City, UT",
        description1: "Award-winning restoration",
        description2: "Facade and marquis rebuild from historic photographs",
		images: "project-051-01.jpg,project-051-02.jpg,project-051-03.jpg,project-051-04.jpg,project-051-05.jpg,project-051-06.jpg"
    },
    {
        id: "052",
        title: "340 Main Street",
        location: "Park City, UT",
        description1: "",
        description2: "",
		images: "project-052-01.jpg,project-052-02.jpg"
    },
    {
        id: "053",
        title: "364 Main Street",
        location: "Park City, UT",
        description1: "",
        description2: "",
		images: "project-053-01.jpg"
    },
    {
        id: "054",
        title: "368 Main Street",
        location: "Park City, UT",
        description1: "",
        description2: "",
		images: "project-054-01.jpg"
    },
    {
        id: "055",
        title: "Sweede Alley Mixed Use Retail, Office and Residential",
        location: "Park City, UT",
        description1: "",
        description2: "",
		images: "project-055-01.jpg,project-055-02.jpg"
    },
    {
        id: "056",
        title: "352 Main Street",
        location: "Park City, UT",
        description1: "",
        description2: "",
		images: "project-056-01.jpg,project-056-02.jpg,project-056-03.jpg"
    },
    {
        id: "057",
        title: "St. Mary’s Church",
        location: "Park City, UT",
        description1: "",
        description2: "",
		images: "project-057-01.jpg,project-057-02.jpg,project-057-03.jpg"
    },
    {
        id: "058",
        title: "Post Office at The Colony",
        location: "Park City, UT",
        description1: "",
        description2: "",
		images: "project-058-01.jpg"
    }
];

var jta_index, jta_entry;
for (jta_index = 0; jta_index < jta_projects.length; ++jta_index)
{
    jta_entry = jta_projects[jta_index];
    jta_projects[jta_entry.id] = jta_entry;
}

/**
------------------ [ CORE ] --------------------
**/

var CORE = (function () {
	var moduleData = {},
	to_s = function (anything) { return Object.prototype.toString.call(anything); },
 
	debug = true;
 
	return {
		debug : function (on) {
			debug  = on ? true : false;
		},
		create_module : function (moduleID, creator) {
			var temp;
			if (typeof moduleID === 'string' && typeof creator === 'function') {
				temp = creator(Sandbox.create(this, moduleID));
				if (temp.init && typeof temp.init === 'function' && temp.destroy && typeof temp.destroy === 'function') {
					temp = null;
					moduleData[moduleID] = {
						create : creator,
						instance : null
					};
				} else {
					this.log(1, "Module '" + moduleID + "' Registration : FAILED : instance has no init or destory functions");
				}
			} else {
				this.log(1, "Module '" + moduleID + "' Registration : FAILED : one or more arguments are of incorrect type");
			}
		},
		start : function (moduleID) {
			var mod = moduleData[moduleID];
			if (mod) {
				mod.instance = mod.create(Sandbox.create(this, moduleID));
				mod.instance.init();
			}
		},
		start_all : function () {
			var moduleID;
			for (moduleID in moduleData) {
				if (moduleData.hasOwnProperty(moduleID)) {
					this.start(moduleID);
				}
			}
		},
		stop : function (moduleID) {
			var data;
			if (moduleData[moduleID]) {
				data = moduleData[moduleID];
				if (data.instance) {
					data.instance.destroy();
					data.instance = null;
				}
/*
			// TODO: W=RND Why the original code did not work (error: data undefined)?
			if (data = moduleData[moduleID] && data.instance) {
				data.instance.destroy();
				data.instance = null;
*/
			} else {
				this.log(1, "Stop Module '" + moduleID + "': FAILED : module does not exist or has not been started");
			}
		},
		stop_all : function () {
			var moduleID;
			for (moduleID in moduleData) {
				if (moduleData.hasOwnProperty(moduleID)) {
					this.stop(moduleID);
				}
			}
		},
		registerEvents : function (evts, mod) {
			if (this.is_obj(evts) && mod) {
				if (moduleData[mod]) {
					moduleData[mod].events = evts;
				} else {
					this.log(1, "registerEvents ERROR 1");
				}
			} else {
				this.log(1, "registerEvents ERROR 2");
			}
		},
		triggerEvent : function (evt) {
			var mod;
			for (mod in moduleData) {
				if (moduleData.hasOwnProperty(mod)){
					mod = moduleData[mod];
					if (mod.events && mod.events[evt.type]) {
						mod.events[evt.type](evt.data);
					}
				}
			}
		},
		removeEvents : function (evts, mod) {
			if (this.is_obj(evts) && mod && (mod = moduleData[mod]) && mod.events) {
				delete mod.events;
			} 
		},
		log : function (severity, message) {
			if (debug) {
				console[ (severity === 1) ? 'log' : (severity === 2) ? 'warn' : 'error'](message);
			} else {
				// send to the server // TODO Create error logging on the server
			}	 
		},
		dom : {
			query : function (selector, context) {
				var ret = {}, that = this, jqEls, i = 0;
 
				if (context && context.find) {
					jqEls = context.find(selector);
				} else {
					jqEls = jQuery(selector);
				}

				ret = jqEls.get();
				ret.length = jqEls.length;
				ret.query = function (sel) {
					return that.query(sel, jqEls);
				}
				return ret;
			},
			bind : function (element, evt, fn) {
				if (element && evt) {
					if (typeof evt === 'function') {
						fn = evt;
						evt = 'click';
					}
					jQuery(element).bind(evt, fn);
				} else {
					// log wrong arguments
				}
			},
			unbind : function (element, evt, fn) {
				if (element && evt) {
					if (typeof evt === 'function') {
						fn = evt;
						evt = 'click';
					}
					jQuery(element).unbind(evt, fn);
				} else {
					// log wrong arguments // TODO Implement logging of wrong arguments
				}
			},
			create: function (el) {
				return document.createElement(el);
			},
			apply_attrs: function (el, attrs) {
				jQuery(el).attr(attrs);
			}
		},
		is_arr : function (arr) {
			return jQuery.isArray(arr);
		},
		is_obj : function (obj) {
			return jQuery.isPlainObject(obj);
		}
	};
 
}());


/**
------------------ [ SANDBOX ] --------------------
**/


var Sandbox = {
	create : function (core, module_selector) {
		var CONTAINER = core.dom.query('#' + module_selector);
		return {
			find : function (selector) {
				return CONTAINER.query(selector);
			},
			addEvent : function (element, type, fn) {
				core.dom.bind(element, type, fn);
			},
			removeEvent : function (element, type, fn) {
				core.dom.unbind(element, type, fn);
			},
			notify : function (evt) {
				if (core.is_obj(evt) && evt.type) {
					core.triggerEvent(evt);
				}
			},
			listen : function (evts) {
				if (core.is_obj(evts)) {
					core.registerEvents(evts, module_selector);
				}
			},
			// TODO Likey an unnecessary method. Consider removing in favour of expanding core.stop method
			ignore : function (evts) {
				if (core.is_arr) {
					core.removeEvents(evts, module_selector);
				}
			},
			create_element : function (el, config) {
				var i, child;
				el = core.dom.create(el);

				if (config) {
					if (config.children && core.is_arr(config.children)) {
						i = 0;
						while(child = config.children[i]) {
							el.appendChild(child);
							i++;
						}
						delete config.children;
					}
					if (config.text) {
						el.appendChild(document.createTextNode(config.text));
						delete config.text;
					}
					core.dom.apply_attrs(el, config);
				}
				return el;
			}
		};
	}
};


/**
------------------ [ Module: Reasons ] --------------------
**/


/* TODO Rename to avoid JS errors on reasons page */
CORE.create_module("reasons", function(sb){
	var
		slides,
		slidesAmount = 0,
		currentSlide = 1,
		slidesCont,

		nextBtn,
		nextActionBtns,
		navBtns,
		footerBtns;

	function isLastSlide(slideIndex) {
		if (slideIndex < slidesAmount-1) {
			return false;
		} else {
			return true;
		}
	}

	function showSlide (slide) {
		var position = slide * -990;

		if (isLastSlide(slide)) {
			$(nextBtn).fadeOut('fast');
			$(nextActionBtns).fadeIn('fast');
		} else {
			$(nextActionBtns).fadeOut('fast');
			$(nextBtn).fadeIn('fast');
		}

		$(slidesCont).animate({
			left: position
		});

		$(navBtns).parent().removeClass("current");
		$(footerBtns).parent().removeClass("current");
		$(navBtns[slide]).parent().addClass("current");
		$(footerBtns[slide]).parent().addClass("current");
	/*
				if (isCurrent) {
					jQuery(parentElm).siblings().removeClass("current"); // TODO Remove jQuery mothod from model
					parentElm.className = "current";
				}
	*/
	}

	return {
		init : function() {
			slidesCont = sb.find('.wrapper');
			slides = sb.find('.content');
			nextBtn = sb.find('.next');
			nextActionBtns = sb.find('.next-action');
			navBtns = sb.find('#reasons-nav a');
			footerBtns = sb.find('.footer a');
			slidesAmount = slides.length;

			sb.addEvent(nextBtn, 'click', this.showNextSlide);
			sb.addEvent(navBtns, 'click', this.showSpecificSlide);
			sb.addEvent(footerBtns, 'click', this.showSpecificSlide);
		},
		destroy : function() {
			sb.removeEvent(nextBtn, 'click', this.showNextSlide);
			sb.removeEvent(navBtns, 'click', this.showSpecificSlide);
			sb.removeEvent(footerBtns, 'click', this.showSpecificSlide);
			slides = slidesAmount = currentSlide = slidesCont = nextBtn = nextActionBtns = footerBtns = navBtns = null;
		},
		showNextSlide : function () {
			showSlide(currentSlide++);
			return false;
		},
		showSpecificSlide : function (e) {
			var parentOfSelected = e.currentTarget.parentNode;
			currentSlide = $(parentOfSelected).index();

			showSlide(currentSlide);

			if (! slides.length === navBtns.length === footerBtns.length) {
				this.log(2, "Module '" + moduleID + "' :  : number of slides does not match number of corresponding elements in navigation and / or footer");
			}
			return false;
		}
	};
});


/**
------------------ [ Module: Portfolio Filter ] --------------------
**/


CORE.create_module("portfolio-filters", function(sb){
	var filters;

	return {
		init : function() {
			filters = sb.find('a');
			sb.addEvent(filters, "click", this.filterPortfolio);
		},
		destroy : function() {
			sb.removeEvent(filters, "click", this.filterPortfolio);
			filters = null;
		},
		filterPortfolio : function (e) {
			var parentElm = e.currentTarget.parentNode;
			var isCurrent = (parentElm.getAttribute("class") === "current" ? false : true);

			if (isCurrent) {
				jQuery(parentElm).siblings().removeClass("current"); // TODO Remove jQuery mothod from model
				parentElm.className = "current";

				sb.notify({
					type : 'filter-selected',
					data : e.currentTarget.getAttribute("class")
				});
			}
		}
	};
});


/**
------------------ [ Module: Portfolio Items ] --------------------
**/


CORE.create_module("portfolio-items", function(sb){
	var items; //, currentItem;

	function eachItem(fn) {
		var i = 0, item;
		for ( ; item = items[i++]; ) {
			fn(item);
		}
	}
	function reset () {
		jQuery("#portfolio-items").removeClass("active"); // TODO Remove dependency on jQuery
		jQuery(".thumbs > li").show("slow");
	}

	return {
		init : function () {
			var that = this;

			items = sb.find(".thumbs a");
			sb.listen({
				'filter-selected' : this.apply_filter,
				'project-details-closed' : this.set_inactive
			});
			eachItem(function (item) {
				sb.addEvent(item, 'click', that.selectProject);
			});
		},
		destroy : function () {
			var that = this;

			eachItem(function (item) {
				sb.removeEvent(item, 'click', that.selectProject);
			});
			sb.ignore(['filter-selected, project-details-closed']); // , 'reset-filter'
		},
		reset : reset,
		set_inactive : function () {
			jQuery("#portfolio-items").removeClass("active"); // TODO Remove jQuery dependency
		},
		apply_filter : function (filter) {
			// test for null
			if (filter) {
				reset();

				if (filter !== "all") { // TODO RND JavaScript Testing for null
					jQuery("#portfolio-items .thumbs:not(." + filter + ") > li").hide("slow");//var typeOfProjects = ;
					//alert(typeOfProjects);
					/*
					eachItem(function (item) {
						var projectType = item.getAttribute("data-9696-projecttype");

						if (projectType.indexOf(filter) === -1) {
							jQuery(item).parent().hide("slow"); // TODO Remove jQuery dependency
						}
					});
					*/
				}
			}
		},
		selectProject : function (e) {
			var projectID, selectLocation = 0;

			if ($("#project-details").length) {
				$("#project-details").remove();
				CORE.stop("project-details");
			}

			projectID = e.currentTarget.getAttribute("id");
			projectID = projectID.replace('project-','');
			
			var elm = $(e.currentTarget.parentNode.parentNode);
			selectLocation = $("#portfolio-items ul").index(elm);

			var jta_project = jta_projects[projectID];    // <= Country code lookup
			var jta_images = jta_project.images; // <= Alerts "Country name: Andorra"
			jta_images = jta_images.split(",");

			var imagesHTML = '';
			var thumbsHTML = '';
			var image = 0;
			for (image in jta_images) {
				var temp = jta_images[image];
				imagesHTML = imagesHTML + '<div class="image clearfix"><img src="img/portfolio/'+temp+'" /></div>';
				temp = temp.replace('.jpg','-t02.jpg');
				thumbsHTML = thumbsHTML + '<a href="#" class="clearfix"><img src="img/portfolio/'+temp+'" /></a>';
			}


			var myDiv = '<div id="project-details" class="clearfix"></div>';

			var myHTML =
'<div class="images" style="width: '+ 990*jta_images.length +'px">'
+ imagesHTML
//+ '<div class="prev-image clearfix"><img src="img/portfolio/'+jta_images[0]+'" /></div>'
//+ '<div class="main-image clearfix"><img src="img/portfolio/'+jta_images[0]+'" /></div>'
//+ '<div class="next-image clearfix"><img src="img/portfolio/'+jta_images[1]+'" /></div>'
+ '</div>'
//+ '<div class="temp-image clearfix"><img src="img/portfolio/'+jta_images[1]+'.jpg" /></div>'
+ '<div class="temp-image clearfix">'
+ '<img src="img/portfolio/'+jta_images[0]+'" />'
+ '</div>'
+ '<div class="project-info clearfix">'
+ '	<div class="project-title">'
+ '		<strong>'+jta_project.title+'</strong><br />'
+ '		<span class="project-location">'+jta_project.location+'</span>'
+ '	</div>'
+ '	<div class="project-description">'+jta_project.description1+'<br />'+jta_project.description2+'</div>'
+ '</div>'

+ '<div class="project-thumbs nav clearfix">'
+ thumbsHTML
+ '</div>'

+ '<a class="controls show-info" href="#"><span></span></a>'
+ '<a class="controls show-thumbs" href="#"><span></span></a>'
+ '<a class="controls inactive prev" href="#"><span></span></a>'
+ '<a class="controls next" href="#"><span></span></a>'
+ '<a class="close" href="#"><span></span></a>';


			$(elm).after(myDiv);
			$("#project-details").html(myHTML);

			jQuery("#portfolio-items").addClass("active"); // TODO Remove dependency on jQuery
			jQuery(".thumbs .current").removeClass("current");
			jQuery(e.currentTarget).addClass("current"); // TODO Remove dependency on jQuery

			CORE.start('project-details');

			sb.notify({
				type : 'project-selected',
				data : { projectID : projectID, selectLocation : selectLocation }
			});

			return false; // TODO to prevent click event
		}
	};
});


/**
------------------ [ Module: Project Details ] --------------------
**/


CORE.create_module("project-details", function(sb){
	var
		projectID = '001',
		position = 0, isDisplayed = false, isFirst = true, mainImgIndex = 0,
		thumbs, controls,
		mainImg, prevImg, nextImg, tempImg,
		imgsCont, mainImgCont, prevImgCont, nextImgCont, tempImgCont, thumbsCont, infoCont, // TODO rename Cont to Box?;
		closeBtn, infoBtn, thumbsBtn, prevBtn, nextBtn;

	function addProjectDetails (projectID) {
		alert("project-details-changed");
		sb.notify({
			type : 'project-details-changed',
			data : null
		});
	}

	function updateImgs () {
		// currentImgIndex

		// temp solution
	}

	function isFirst() { alert("Testing: is 1st?"); }

	function isLast(index) {
		index++;
		if (index === $("#project-details .images > .image").length) {
			return true;
		} else {
			return false;
		}
	}

	function moveToSpecificImg(index) {
		position = -990 * index;//: position+990;
		var temp = $(imgsCont).find("img").get(index);
		mainImgSrc = $(temp).attr("src");

		$(tempImgCont)
			.find("img")
			.attr("src",mainImgSrc)
			.end()
			.css("z-index","5")
			.fadeIn("normal",function(){
				$(imgsCont).animate({
					left: position
				}, 400, 'linear', function() {
						$(tempImgCont)
							.css("z-index","0")
							.hide();
				});
			});
		
		$(nextBtn).fadeIn();
		$(prevBtn).fadeIn();
		$(infoBtn).fadeIn();
		$(thumbsBtn).fadeIn();

	}

	function moveImgs(direction) {
		position = (direction === 'l') ? position-990 : position+990;

		$(imgsCont).animate({
			left: position
		}, 400, 'linear', function() { resetImgsCont(direction); });
	}

	function resetImgsCont (direction) {
/*
		var mainImgSrc, prevImgSrc, nextImgSrc, tempImgSrc;

//		imgSrc = (direction === "l") ? $(nextImg).attr("src") : $(prevImg).attr("src");

		if (direction === "l") {
			tempImgSrc = nextImg.attr("src");
			prevImgSrc = mainImg.attr("src");
			mainImgSrc = nextImg.attr("src");
			nextImgSrc = "/img/portfolio/project-001-05.jpg";
		} else {
			tempImgSrc = prevImg.attr("src");
			nextImgSrc = mainImg.attr("src");
			prevImgSrc = "/img/portfolio/project-001-05.jpg";
			mainImgSrc = prevImg.attr("src");
		}

		$(tempImg)
			.attr("src",tempImgSrc)
			.one("load", function() { //fires (only once) when loaded
				$(tempImgCont).css("z-index","2");
				$(prevImg).attr("src",prevImgSrc);
				$(mainImg).attr("src",mainImgSrc);
				$(nextImg).attr("src",nextImgSrc);
				$(imgsCont).css("left",position);
				$(tempImgCont).css("z-index","0");
			}).each(function(){
				// TODO RND Jerky rendering on Safari; potentially the same bug as in https://github.com/balupton/History.js/issues/6
				//if(this.complete) //trigger load if cached in certain browsers
				//$(this).trigger("load");
			});
*/
	}

	function updateControlsState(index) {
		if (index === 0) {
			$(prevBtn).addClass("inactive");
			$(infoCont).fadeIn();
		} else {
			$(prevBtn).removeClass("inactive");
			$(infoCont).fadeOut();
		}
		if (isLast(index)) {
			$(nextBtn).addClass("inactive");
		} else {
			$(nextBtn).removeClass("inactive");
		}
	}

	function eachThumb(fn) {
		var i = 0, thumb;
		for ( ; thumb = thumbs[i++]; ) {
			fn(thumb);
		}
	}

//	function changeProjectDetails() {}

/*
	function resetImgPosition() {
		(tempImgCont).css("z-index","2");
	}

	function changeImgs (index) {
		//moveImgs(position);
	}
*/

	return {
		init : function() {
			var that = this;

			controls = sb.find('.controls');
			thumbs = $('.project-thumbs > a');
			imgsCont = sb.find('.images');
			mainImgCont = sb.find('.main-image');
			nextImgCont = sb.find('.next-image');
			prevImgCont = sb.find('.prev-image');
			tempImgCont = sb.find('.temp-image');
			thumbsCont = sb.find('.project-thumbs');
			infoCont = sb.find('.project-info');
			infoBtn = sb.find('a.show-info');
			thumbsBtn = sb.find('.show-thumbs');
			prevBtn = sb.find('.prev');
			nextBtn = sb.find('.next');
			closeBtn = sb.find('.close');

			mainImg = $(mainImgCont).children("img"); // TODO Change to pick up only the first img child
			nextImg = $(nextImgCont).children("img");
			prevImg = $(prevImgCont).children("img");
			tempImg = $(tempImgCont).children("img");

			sb.listen({
				'filter-selected' : this.hide,
				'project-selected' : this.show
			});

			sb.addEvent(infoBtn, "click", this.toggleInfo);
			sb.addEvent(thumbsBtn, "click", this.showThumbs);
			sb.addEvent(nextBtn, "click", this.showNextImg);
			sb.addEvent(prevBtn, "click", this.showPrevImg);
			sb.addEvent(closeBtn, "click", this.hide);

			eachThumb(function (thumb) {
				sb.addEvent(thumb, "click", that.showSpecificImg);
			});
		},
		destroy : function() {
			// TODO Reset variables, removeEvents, ignoreListens

			var that = this;

			jQuery("#project-details").slideUp("normal"); // TODO Remove jQuery dependency
			/*
			sb.notify({
				type : 'project-details-closed',
				data : null
			});
			*/

			sb.ignore(['filter-selected, project-selected']);

			// sb.removeEvent(filters, "click", this.filterPortfolio);
			// filters = null;
			sb.removeEvent(infoBtn, "click", this.toggleInfo);
			sb.removeEvent(thumbsBtn, "click", this.showThumbs);
			sb.removeEvent(nextBtn, "click", this.showNextImg);
			sb.removeEvent(prevBtn, "click", this.showPrevImg);
			sb.removeEvent(closeBtn, "click", this.hide);

			eachThumb(function (thumb) {
				sb.removeEvent(thumb, "click", that.showSpecificImg);
			});

			projectID = position = isDisplayed = isFirst = mainImgIndex = thumbs = controls = mainImg = prevImg = nextImg = tempImg = imgsCont = mainImgCont = prevImgCont = nextImgCont = tempImgCont = thumbsCont = infoCont = closeBtn = infoBtn = thumbsBtn = prevBtn = nextBtn = null;
		},
		show : function () {

/*
			test : function (selectData) {
				alert(selectData.projectID + selectData.selectLocation);
			},
*/

			$("#project-details").slideDown("normal",function(){
				$(window)._scrollable();
				$.scrollTo( "#project-details", 800, {offset: {top:-25}});
			});
			sb.notify({
				type : 'project-details-displayed',
				data : null
			});
			if (isLast(mainImgIndex)) {
				$(nextBtn).addClass("inactive");
			};
			$(infoCont).fadeIn();
			return false; // TODO to prevent click event
		},
		hide : function () {
			// TODO Hide vs Destroy?
			$("#project-details").slideUp("normal");
			sb.notify({
				type : 'project-details-closed',
				data : null
			});
			return false;
		},
		showSpecificImg : function (event) {
			$(thumbsCont).fadeOut();
			mainImgIndex = $(event.target).parent().index();
			moveToSpecificImg(mainImgIndex);
			updateControlsState(mainImgIndex);
			return false;
		},
		showNextImg : function () {
			if (!isLast(mainImgIndex)) {
				moveImgs("l");
				mainImgIndex++;
				updateControlsState(mainImgIndex);
			}
			return false; // TODO to prevent click event
		},
		showPrevImg : function () {
			if (mainImgIndex !== 0) {
				moveImgs("r");
				mainImgIndex--;
				updateControlsState(mainImgIndex);
			}
			return false; // TODO to prevent click event
		},
		showThumbs : function () {
			$(controls).fadeOut();
			$(infoCont).fadeOut();
			$(thumbsCont).fadeIn();
			return false;
		},
		hideThumbs : function () {
			alert("thumbs hidden");
			return false; // TODO to prevent click event
		},
		toggleInfo : function () {
			$(infoCont).fadeToggle();
			return false; // TODO to prevent click event
		},
		hideControls : function () {
			$(controls).fadeOut("fast");
			return false;
		},
		showControls : function () {
			$(controls).fadeIn("fast");
			return false;
		},
		showInfo : function () {
		},
		hideInfo : function () {
		}
		// disablePrevBtn ?
		// enablePrevBtn ?
		// disableNextBtn ?
		// enableNextBtn ?
	};
});


// CORE.start_all();
CORE.start('reasons');
CORE.start('portfolio-filters');
CORE.start('portfolio-items');


/* TODO: Is this a good placement for the function? */
function animateIntro() {
	$("#intro h1").fadeOut(function(){
		$("#intro .content").fadeIn();
	});
};

function switchHomepageHeader() {
	$("#page-header h1").fadeOut(function(){
		$("#teaser").fadeIn();
	});
};

$(document).ready(function()
{

	if ($('#homepage').length && $('#reasons').length) {
		window.setTimeout(animateIntro, 3000);
		window.setTimeout(switchHomepageHeader, 3000);

/*
		$(window).mousemove(function () {
			window.setTimeout(animateIntro, 8000);
		});

		$(window).scroll(function () {
			window.setTimeout(animateIntro, 8000);
		});
*/
	};


	var bodyClass = $("body").attr("class");
	switch(bodyClass){
	case "class-home":
		$("#global-nav li:nth-child(1)").addClass("current");
		break;
	case "class-portfolio":
		$("#global-nav li:nth-child(2)").addClass("current");
		break;
	case "class-services":
		$("#global-nav li:nth-child(3)").addClass("current");
		break;
	case "class-process":
		$("#global-nav li:nth-child(4)").addClass("current");
		break;
	case "class-about":
		$("#global-nav li:nth-child(5)").addClass("current");
		break;
	case "class-contactus":
		$("#global-nav li:nth-child(6)").addClass("current");
		break;
	default:
		break;
	}

	$('#intro .project-thumbs a').click(function(event){
		var box = $('#intro');
		var infoBtn = box.find(".show-info");
		var prevBtn = box.find(".prev");
		var nextBtn = box.find(".next");
		var mainImg = box.find("#image-00");
		var images = box.find(".images");
		var thumbs = box.find(".project-thumbs");
		var callsToAction = box.find(".calls-to-action");
		var selectedThumb = $(this);
		var parent = $(this).parent();
		var imgIndex = $(this).parent().index();
		var projectID;
		var prevImgIndex;

		function updateProjectInfo (id) {
			id = id.replace("project-",'');
			var jta_project = jta_projects[id];    // <= Country code lookup
			var description = jta_project.description1+'<br />'+jta_project.description2;
			box.find(".project-title > strong").text(jta_project.title);
			box.find(".project-title > span").text(jta_project.location);
			box.find(".project-description").html(description);
		}

		var showImg = function(index, prevIndex) {
			if (index === 0) {
				prevBtn.addClass("inactive");
			} else if (index === 1) {
				prevBtn.removeClass("inactive");
			} else if (index === 3) {
				nextBtn.removeClass("inactive");
				callsToAction.fadeOut();
			} else if (index === 4) {
				/* TODO: Move CSS to external CSS file */
				callsToAction.css({"position": "absolute", "top": "70%", "left": "130px", "margin": "0 auto", "z-index": "20", "display": "block"}).fadeIn();
				nextBtn.addClass("inactive");
			}

			if (typeof(prevIndex) === "number") {
				prevIndex++;
//				$('.images img[id="image-0'+prevIndex+'"]').css("z-index","1").css("display","inline");
			}

			index++;
			var currentImg = $('img[id="image-0'+index+'"]');

			projectID = currentImg.attr("rel");
			updateProjectInfo(projectID);

//			var test = '#image-0'+index+',#image-0'+prevIndex+'';
//			alert(test);

			currentImg
				.css("z-index","8")
				.fadeIn();
			currentImg
				.siblings()
//				.not('#image-0'+prevIndex+'')
				.css({"z-index": "0", "display": "none"});

		};

		box.addClass("loader");

		showImg(imgIndex);

		box.find(".content").fadeOut(function(){
			mainImg.fadeOut();
			box.find(".controls").fadeIn();
		});

		nextBtn.click(function(event){
			if (imgIndex <= 3) {
				prevImgIndex = imgIndex;
				imgIndex++;
				showImg(imgIndex, prevImgIndex);
			}
			event.preventDefault;
		});
		prevBtn.click(function(event){
			if (imgIndex >= 1) {
				prevImgIndex = imgIndex;
				imgIndex--;
				showImg(imgIndex, prevImgIndex);
			}
			event.preventDefault;
		});
		infoBtn.click(function(event){
			box.find(".project-info").fadeToggle();
			event.preventDefault;
		});
		event.preventDefault;
	});



	$('a[rel*=lightbox]').lightBox();

	$('#process .figure .next').click(function(event){
		var bullets = $(this).siblings(".figure-bullets").children("a");
		var index = bullets.filter(".active").index();

		if (index++ < bullets.length-- && index !== -1) {
			bullets.filter(".active")
				.removeClass("active")
				.next()
					.trigger("mouseover")
					.addClass("active");
			// $('#foo').trigger('click');
		};
		event.preventDefault();
	});

	$('#process .figure .prev').click(function(event){
		var bullets = $(this).siblings(".figure-bullets").children("a");
		var index = bullets.filter(".active").index();
		if (index < bullets.length && index > 0) {
			bullets.filter(".active")
				.removeClass("active")
				.prev()
					.trigger("mouseover")
					.addClass("active");
			// $('#foo').trigger('click');
		};
		event.preventDefault();
	});

	$('#process .figure-bullets > a').bind({
		mouseover: function(event){
			var index = $(this).index();
			var figure = $(this).parent().parent();

			var toShow = $(figure).children().get(index);
			$(toShow).siblings("a")
				.not(".controls")
				.css("display","none");
			$(toShow)
				.fadeIn();

			$(this).siblings().removeClass("active");
			$(this).addClass("active");

			event.preventDefault();
		},
		click: function(event){
			return false;
			event.preventDefault;
		}
	});

	$('#process .figure .image:visible').live({
		mouseover: function(event) {
			$(this).siblings(".zoom-in").css("display","none");
			
			$(this).siblings(".zoom-in-message").fadeIn("fast");
			//return false;
			event.preventDefault;
		},
		mouseout: function(event) {
			$(this).siblings(".zoom-in-message").css("display","none");
			$(this).siblings(".zoom-in").fadeIn("fast");
			//return false;
			event.preventDefault;
	  }
	});

/* TODO: Add click event on a zoom-in icon for Touch based devices
	$('#process .figure .zoom-in').click(function(event) {
		alert($(this).siblings(".image").filter(":hidden").html());//.trigger("click");
		event.preventDefault;
	});
*/

	$('#process .figure .zoom-in-message').mouseover(function(event) {
		$(this).css("visibility","hidden");
		event.preventDefault;
		return false;
	});


/*
	$('#global-nav a').bind({
		mouseover: function() {
			$(this).animate({
				top: -2,
				border: 2
			}, 150);
			//return false;
		},
		mouseout: function() {
			$(this).animate({
				top: 0,
				border: 0
			}, 150);
			//return false;
	  }
	});
*/

$(function() { $(".lavaLampNoImage").lavaLamp({ fx: "backout", speed: 700 })});

});
