// JavaScript Document
fwc = {
		_count:undefined,
		_root:undefined,
		_current:undefined,
		_itemContainer:undefined,
		_animating:false,
		_aniTime:500,
		_leftButton:undefined,
		_rightButton:undefined,
		_loops:undefined,
		_containerParent : undefined,
		_started : false,
		_loaded: false,
		_timer: undefined,
		delegate: undefined,
		_enabled:true,
		_pager:undefined
	};

fwc.getViewportSize = function()
{
	var viewportwidth;
	var viewportheight;
	
	 if (typeof window.innerWidth != 'undefined')
	 {
		  viewportwidth = window.innerWidth;
		  viewportheight = window.innerHeight;
	 } else if (typeof document.documentElement != 'undefined'
		 && typeof document.documentElement.clientWidth !=
		 'undefined' && document.documentElement.clientWidth != 0)
	 {
		 viewportwidth = document.documentElement.clientWidth;
		 viewportheight = document.documentElement.clientHeight;
	 } else {
		   viewportwidth = document.getElementsByTagName('body')[0].clientWidth;
		   viewportheight = document.getElementsByTagName('body')[0].clientHeight;
	 }
	 
	 return [viewportwidth, viewportheight-30];
}
	
fwc.init = function($, inSelector, inAniTime, inLoops)
{
	if ($(inSelector).length == 0) return;
	var self = this;
	
	if (this._started || this._loaded) return;
	this._started = true;
	
	this._$ = $;
	
	if (inLoops != undefined) {
		self._loops = inLoops;
	}
	
	this._root = $(inSelector);
	if (this._root.length == 0) return;

	if (self.delegate && typeof self.delegate.carouselDidStartLoading == 'function') {
		self.delegate.carouselDidStartLoading(self);
	}
	
	var _hasPages = this._root.hasClass('paged');
	
	if (inAniTime != undefined) {
		this._aniTime = inAniTime;
	}
	
    this._root.css('overflow', 'hidden');

	this._root.children('ul').addClass('fwc-items');
	this._itemContainer = this._root.find('.fwc-items');
	
	this._root.append('<ul id="fwc-controls"><li id="fwc-left"><a href="#" class="hidden" title="Previous">Previous</a></li><li id="fwc-right"><a href="#" class="hidden" title="Next">Next</a></li></ul>');
	
	this._leftButton = this._root.find('#fwc-left');
	this._rightButton = this._root.find('#fwc-right');
	this._leftButton.click(function(e) { e.preventDefault(); self.moveRight(); });
	this._rightButton.click(function(e) {e.preventDefault(); self.moveLeft(); });

	var items = this._itemContainer.children();
	this._count = items.length;
	
	items.find('img').css('display', 'block').removeAttr('width').removeAttr('height');
	
	self._itemContainer.wrap('<div></div>');
	self._itemContainer.css('overflow', 'hidden');
	self._containerParent = this._itemContainer.parent();
	self._containerParent.css('overflow', 'hidden');
		
	if (self._loops) {
		self._itemContainer.width(9000);
		var firstItem = $(self._itemContainer.children().get(0)).clone();
		var lastItem = $(self._itemContainer.children().get(this._count - 1)).clone();
		self._itemContainer.append(firstItem);
		this._count++;
		self._itemContainer.prepend(lastItem);
		this._count++;
		
		this._current = 1;
		this.refresh(false);
		
		$(self._itemContainer.children()[1]).css('position', 'absolute');
		self._enabled = false;
		
		if (_hasPages) {
			this._root.append('<ul id="fwc-pager"></ul>');
			this._pager = this._root.find('#fwc-pager');
			for (var c = 1; c < self._count - 1; c++) {
				self._pager.append('<li data-page="' + c + '" class="' + ((c == self._current) ? 'current' : '') + '"><a href="#" title="View image ' + c + '">' + c + '</a></li>');
			}
			
			self._pager.find('li').click(function(e) {
				e.preventDefault();
				self._current = $(this).attr('data-page');
				self.refresh();
			});
		}
		
	} else {
		this._current = 0;
		this._leftButton.addClass('disabled');
	} 
	
	self._containerParent.scrollTo(self._itemContainer.children()[self._current]);
	
	var items = this._itemContainer.children();
	items.css('float', 'left').css('overflow', 'hidden');
	
    this._root.addClass('fwc');
    
	$(window).resize(function() {
		self.doResize();
		clearTimeout(self._timer);
		self._timer = setTimeout(function() {
			var reWidth = new RegExp('\width\/[0-9]*');
			var reHeight = new RegExp('\height\/[0-9]*');
			for (var i = 0; i < self._count; i++) {
				var theImg = items.find('img')[i];
				var newWidth = self._containerParent.width();
				var newHeight = self._containerParent.height();
				var newUrl = theImg.src.replace(reWidth, 'width/' + newWidth);
				newUrl = newUrl.replace(reHeight, 'height/' + newHeight);
				
				theImg.src = newUrl;
				
				if (i == 1 && self._loops && self._current == 1) {
					$(theImg).load(function(e) {
						$(self._itemContainer.children()[1]).css('position', 'static');
						//self._containerParent.scrollTo(self._itemContainer.children()[1]);
						self._enabled = true;
						$(this).unbind(e);
						
						if (!self._loaded) {
							if (self.delegate && typeof self.delegate.carouselDidFinishLoading == 'function') {
								self.delegate.carouselDidFinishLoading(self);
							}
							self._loaded = true;
						}
						
					});
				}
				
			}
			
			//self._containerParent.scrollTo(self._itemContainer.children()[self._current]);
			
		}, 500);
	});
		
	$(window).trigger('resize');
	
	var img = new Image();
	$(img).load(function() { setTimeout(function() { 
		self.doResize();
	}), 600});
	img.src = self._$(items[self._current]).find('img').attr('src');
		
	items.find('.projects_overview').hide();
		
}

fwc.doResize = function()
{
	var self = this;
	var viewportSize = self.getViewportSize();
	
	var containerwidth = self._containerParent.width();
	var viewportheight = viewportSize[1];
	var viewportwidth = viewportSize[0];
	
	self._itemContainer.children().width(containerwidth);
	self._itemContainer.width(containerwidth * self._count);
	self._itemContainer.height(viewportheight - $('.header').height());
	
	var containerheight = self._itemContainer.height();
	
	var oneImg = self._itemContainer.children().find('img:first');
	var imgAspect = oneImg.width() / oneImg.height();
	var containerAspect = viewportwidth / self._itemContainer.height();
	var allImgs = self._itemContainer.children().find('img');
	
	if (imgAspect >= containerAspect) {
		allImgs.height(containerheight);
		allImgs.width('');
		if (oneImg.width() <= containerwidth) {
			allImgs.height('');
			allImgs.width(containerwidth);
		}
	} else {
		allImgs.width(containerwidth);
		allImgs.height('');				
	}
		
	self._containerParent.scrollTo(self._itemContainer.children()[self._current], 0);
	
}

fwc.moveLeft = function ()
{
	if (!this._animating && this._enabled) {
		this._animating = this.incrementCurrent(1);
		this.refresh();
	}
}

fwc.moveRight = function ()
{
	if (!this._animating  && this._enabled) {
		this._animating = this.incrementCurrent(-1);
		this.refresh();
	}
}

fwc.incrementCurrent = function (inAmount)
{
	this._current = parseInt(this._current);
	var original = this._current;
	this._current = this._current + inAmount;
	this._current = Math.max(Math.min(this._count - 1, this._current), 0);
	
	if (!this._loops) {
		if (this._current == 0) {
			if (!this._leftButton.hasClass('disabled')) {
				this._leftButton.addClass('disabled');
			}
		} else {
			this._leftButton.removeClass('disabled');
		}

		if (this._current == this._count - 1) {
			if (!this._rightButton.hasClass('disabled')) {
				this._rightButton.addClass('disabled');
			}
		} else {
			this._rightButton.removeClass('disabled');
		}
	}

	return original != this._current;	

}

fwc.refresh = function(animate, inAniTime)
{
	if (animate == undefined) animate = true;
	var self = this;
		
	var aniTime = self._aniTime;
	
	if (inAniTime !== undefined) aniTime = inAniTime;
	
	if (!animate) aniTime = 0;
	
	self._containerParent.scrollTo(self._itemContainer.children()[self._current], aniTime, {
		easing: 'swing',
		offset: 0,
		axis: 'x',
		onAfter: function() {
			self._animating  = false;
			if (self._loops) {
				
				if (self._current == 0) {
					self._current = self._count - 2;
					self._itemContainer.parent().scrollLeft(self._current * self._itemContainer.parent().width());
					self.doResize();
				}
				
				if (self._current == self._count - 1) {
					self._current = 1;
					self._itemContainer.parent().scrollLeft(self._current * self._itemContainer.parent().width());
					self.doResize();
				}
												
			}
		}
	});
	
	if (self._pager) {
		self._pager.find('li').removeClass('current');
		var pageToSet = self._current % (self._count - 2);
		if (pageToSet == 0) pageToSet = self._count - 2;
		self._pager.find('li:nth-child(' + pageToSet + ')').addClass('current');
	}
	
	if (this.delegate && typeof this.delegate.carouselDidShowItemFromItems == 'function') {
		this.delegate.carouselDidShowItemFromItems($(this._itemContainer.children()[this._current]), this._itemContainer.children());
	}
	
}

showHideDetails = {
		delegate : undefined
};

showHideDetails.init = function() {
	var self = this;
	
	if (!$('.project_details_container .project_details').length) return;
	
	$('.wrapper').append('<p id="details-show"><a href="#" title="Show project details">show info</a></p>');
	$('.project_details').append('<p id="details-hide"><a href="#" title="Hide project details">&#8212;</a></p>');
	
	var target;
	
	$('#details-show a').click(function(e){
		target = $(this);
		if (self.delegate && typeof self.delegate.showWasClickedWithEvent == 'function') {
			self.delegate.showWasClickedWithEvent(target, e);
		}
	});
	
	$('#details-hide a').click(function(e){
		target = $(this);
		if (self.delegate && typeof self.delegate.hideWasClickedWithEvent == 'function') {
			self.delegate.hideWasClickedWithEvent(target, e);
		}
	});
	
}

controller = { userWantsDetails : false };

controller.init = function($) {
	fwc.delegate = this;
	fwc.init($, '#top-carousel', 500, true);
	
	showHideDetails.delegate = this;
	showHideDetails.init();
	$("#accordion").accordion();
}

controller.showWasClickedWithEvent = function(target, event)
{
	event.preventDefault();
	this.showDetailsPanel();
	this.userWantsDetails = true;
}

controller.hideWasClickedWithEvent = function(target, event)
{
	event.preventDefault();
	this.hideDetailsPanel();
	this.userWantsDetails = false;
}

controller.hideDetailsPanel = function()
{	
	$('.project_details').slideUp();
	$('#details-show').fadeIn();
}

controller.showDetailsPanel = function()
{
	$('.project_details').slideDown();
	$('#details-show').fadeOut('fast');
	
}

controller.carouselDidShowItemFromItems = function(inItem, inAllItems)
{
	inAllItems.find('.projects_overview').fadeOut();
	inItem.find('.projects_overview').fadeIn();
	
	inAllItems.find('.view-projects-label, .back-to-thumbs').hide();
	inItem.find('.view-projects-label, .back-to-thumbs').show();
	
	if (!this.userWantsDetails) {
		this.hideDetailsPanel();
	}
	
}

controller.carouselDidStartLoading = function(carousel)
{

	if ($('.project_details').length) {
		$('.project_details').append($('.footer').addClass('clear_both'));
	}
	
	$('body').append('<div id="spinner"></div>');
	
	$('.project_details').hide();
	
	var viewportSize = fwc.getViewportSize();
	
	$('#spinner').width('100%').height(viewportSize[1] - $('.header').height()).css({'position':'absolute', 'top': $('.header').height(), 'left' : '0'} );
	
	$(window).bind('resize', function() {
		$('#spinner').height(fwc.getViewportSize()[1] - $('.header').height());
	});
	
	carousel._root.css('opacity', '0.01');
}

controller.carouselDidFinishLoading = function(carousel)
{
	$('#spinner').fadeOut('fast', function() {
		$('#spinner').remove();
	});
	carousel.refresh(false);
	carousel._root.animate({'opacity':'1'}, 1000, 'swing');
	
	this.showDetailsPanel();
}


$(document).ready(function() {
	controller.init($);
 });


				
