if(typeof console == undefined) {
	window.console = {
		log: function() {
			var message = arguments.join(', ');
		}
	}
}

var Samuji = {
	
	logoMargin: 20,
	logoPosition: null,
	
	initialize: function ()
	{
		$(window).bind('resize', Samuji.windowResizeHandler);
		this.animateLogoTo('centermiddle', 0);
		
		// Hide logo before we preposition it
		$('#logo').hide();
		$('#content').hide();
		
		this.PageController.initialize();
		this.PageController.pageChangeHandler();
		
		// Show logo after a slight delay
		$('#logo').delay(200).fadeIn();
	},
	
	animateLogoTo: function (to, duration)
	{
		this.logoPosition = to;
		
		var x, y;
		
		switch(to) {
			case 'centermiddle':
				x = ($(window).width() / 2) - ($('#logo').width() / 2);
				y = ($(window).height() / 2) - ($('#logo').height() / 2);
			break;
			case 'topleft':
				x = y = 0 + this.logoMargin;
			break;
			case 'topright':
				x = $(window).width() - ($('#logo').width() + this.logoMargin);
				y = 0 + this.logoMargin;
			break;
			case 'bottomleft':
				x = 0 + this.logoMargin;
				y = $(window).height() - ($('#logo').height() + this.logoMargin);
			break;
			case 'bottomright':
				x = $(window).width() - ($('#logo').width() + this.logoMargin);
				y = $(window).height() - ($('#logo').height() + this.logoMargin);
			break;
		}
		
		//// console.log(x, y);
		
		/*$('#logo').stop().animate({
			left: x,
			top: y
		}, (duration ? duration : 1000))*/
		$('#logo').stop().fadeTo((duration ? duration/2 : 500), 0, function(){
			$(this).css({
				left: x,
				top: y
			}).fadeTo((duration ? duration/2 : 500), 1);
		})
		$('#logo')
	},
	
	initializePage: function ()
	{
		// console.log('Samuji::initializePage');
		
		var duration = 400;
		$('body').removeClass();
		
		if(Samuji.PageController.current_page[0] != Samuji.PageController.last_page[0] || Samuji.PageController.current_page.length == 1)
		{
			// console.log('\tFirst page has changed, initializing ´' + Samuji.PageController.current_page[0] + '´...');
			switch (Samuji.PageController.current_page[0])
			{
				case 'home':
					Samuji.PageController.loadPage('home', function(){
						Samuji.FrontPage.initialize();
					});
				break;
				case 'story':
					Samuji.PageController.loadPage('story');
				break;
				case 'contact':
					Samuji.PageController.loadPage('contact');
				break;
				case 'inspirations':
					Samuji.PageController.loadPage('inspirations', function(){
						Samuji.Inspirations.initialize();
					});
				break;
				case 'collections':
					if(Samuji.PageController.current_page.length == 1) Samuji.PageController.loadPage('collections');
				break;
			}
		}
		
		if(Samuji.PageController.current_page[1] && Samuji.PageController.current_page[1] != Samuji.PageController.last_page[1])
		{
			if(Samuji.PageController.pages.inArray('collections-' + Samuji.PageController.current_page[1])) {
				Samuji.PageController.loadPage('collections-' + Samuji.PageController.current_page[1], function(){
					Samuji.Collections.initialize(Samuji.PageController.current_page[1]);
				});
			}
		}
		
		if(
			(Samuji.PageController.current_page[2] && Samuji.PageController.current_page[2] != Samuji.PageController.last_page[2]) ||
			(Samuji.PageController.current_page[3] && Samuji.PageController.current_page[3] != Samuji.PageController.last_page[3])
		)
		{
			switch (Samuji.PageController.current_page[0])
			{
				case 'home': break;
				case 'story': break;
				case 'contact': break;
				case 'inspirations': break;
				case 'collections':
					Samuji.Collections.pageChangedHandler();
				break;
			}
		}
	},
	
	showFullscreenWindow: function ()
	{
		$('#fullscreen').fadeIn();
	},
	
	hideFullscreenWindow: function ()
	{
		$('#fullscreen').fadeOut();
	},
	
	/**
	 * Event handlers
	 */
	
	windowResizeHandler: function ()
	{
		Samuji.animateLogoTo(Samuji.logoPosition, 50);
	},
	
	PageController: {
		
		current_page: ['home'],
		website_url: 'samuji.com/',
		pages: [
			'home',
			'story',
			'contact',
			'inspirations',
			'collections',
			'collections-classics-ss-2011',
			'collections-classics-fw-2011',
			'collections-seasonals-ss-2011',
			'collections-seasonals-fw-2011',
		],
		
		initialize: function ()
		{
			$.pathchange.init({
				useHistory: false
			});
			
			$(window).bind('pathchange', this.pageChangeHandler);
		},
		
		changePageTo: function (to)
		{
			if(to.charAt(0) !== '#') to = '#' + to;
			
			$.pathchange.changeTo('/' + to);
			
			return false;
		},
		
		parseHash: function (hash)
		{
			// Check that hash isn't empty
			if(!hash || hash == '' || hash == '#') return null;
			
			// Remove #
			if(hash.charAt(0) == '#') hash = hash.substr(1);
			
			// Remove first /
			if(hash.charAt(0) == '/') hash = hash.substr(1);
			
			// Remove last /
			if(hash.charAt(hash.length - 1) == '/') hash = hash.substr(0, hash.length - 1);
			
			// Split hash
			return hash.split('/');
		},
		
		/**
		 * Event handlers
		 */
		
		pageChangeHandler: function (e)
		{
			// console.log('PageController::pageChangeHandler', e, window.location.hash, window.location);
			
			var url = Samuji.PageController.parseHash(window.location.hash || window.location.href.split(Samuji.PageController.website_url)[1]);
			if(!url || !url[0] || url[0] == '') url = ['home'];
			
			Samuji.PageController.last_page = Samuji.PageController.current_page;
			Samuji.PageController.current_page = url;
			
			Samuji.initializePage();
		},
		
		loadPage: function (page, callback)
		{
			// console.log('PageController::loadPage', page);
			
			// Logo animation
			switch (page) {
				case Samuji.PageController.pages[0]:
					Samuji.animateLogoTo('centermiddle');
				break;
				case Samuji.PageController.pages[1]:
					Samuji.animateLogoTo('bottomright');
				break;
				case Samuji.PageController.pages[2]:
					Samuji.animateLogoTo('bottomleft');
				break;
				case Samuji.PageController.pages[3]:
					Samuji.animateLogoTo('topright');
				break;
				default:
					Samuji.animateLogoTo('topleft');
				break;
			}
			
			// Load the parent page
			$('body').addClass('loading');
			$('#content').fadeOut(function() {
				$('body').attr('id', '' + page);
				$(this).load('/_content/cnt-' + page + '', function() {
					$(this).fadeIn();
					$('body').removeClass('loading');
					if(typeof callback == 'function') callback();
				});
			});
		}
		
	},
	
	FrontPage: {
		
		initialize: function ()
		{
			// console.log('FrontPage::initialize');
			$('#content a').each(function(){
				$(this).hover(function(){
					// console.log('hover');
					$('img', this).stop().fadeTo(400, 100);
					//.stop().effect("scale", { percent: 90 }, 0).effect("scale", { percent: 111.11 }, 600);
				}, function() {
					// console.log('hover out');
					$('img', this).stop().fadeTo(400, 0);
				});
			});
		}
		
	},
		
	// 	Story: {
	// 		
	// 	},
	// 	
	// 	Contact: {
	// 		
	// 	},
	
	Inspirations: {
		
		initialize: function ()
		{
			$('#inspirations-canvas').draggable();
		}
		
	},
	
	Collections: {
		
		looksData: [],
		currentCategory: null,
		currentIndex: 0,
		currentModel: 0,
		currentView: 1,
		imagesPreloaded: false,
		useSpecialImages: false,
		
		COLUMNVIEW: 1,
		GRIDVIEW: 2,
		SPECIALVIEW: 3,
		
		initialize: function (category)
		{
			log('Collections::initialize', category);
			if(!category) category = 'classics';
			this.currentCategory = null;
			this.currentView = 1;
			this.imagesPreloaded = false;
			
			if($('body').hasClass('view-1')) $('body').removeClass('view-1');
			if($('body').hasClass('view-2')) $('body').removeClass('view-2');
			if($('body').hasClass('view-3')) $('body').removeClass('view-3');
			if($('body').hasClass('special-view')) $('body').removeClass('special-view');
			
			$('body').addClass('view-' + this.currentView);
			
			Samuji.Collections.changeCategory(category);
		},
		
		pageChangedHandler: function ()
		{
			// console.log('Page has changed?', Samuji.PageController.current_page);
		},
		
		loadLooksData: function (callback)
		{
			log('Collections::loadLooksData', '/_json/' + this.currentCategory + '/');
			$.ajax(
				'/_json/' + this.currentCategory + '/',
				{
					dataType: 'json',
					error: function(xhr, textStatus, errorThrown) {
						alert('Error loading models!\n\n' + errorThrown);
						log('Collections::loadLooksData', 'Error loading JSON looks data.', textStatus, errorThrown);
					},
					success: function(data, textStatus, xhr) {
						log('Collections::loadLooksData', 'Looks data JSON successfully fetched.', data);
						Samuji.Collections.looksData = data['data'];
						callback();
					}
				}
			);
		},
		
		changeCategory: function (category)
		{
			log('Collections::changeCategory', category, this.currentCategory)
			if(category == this.currentCategory) return false;
			this.currentCategory = category;
			
			// Load new category data
			Samuji.Collections.loadLooksData(function(){
				//Samuji.Collections.preloadImages();
				Samuji.Collections.loadModels();
			});
			
			return true;
		},
		
		changeView: function (view)
		{
			log('Collections::changeView', view);
			if(view == this.currentView) return false;
			
			$('body').removeClass('view-' + Samuji.Collections.currentView);
			if($('body').hasClass('special-view')) $('body').removeClass('special-view');
			
			// Change the view and loaded image to match the view
			switch (view)
			{
				case Samuji.Collections.SPECIALVIEW:
					$('body').addClass('view-' + Samuji.Collections.currentView).addClass('special-view');
					Samuji.Collections.loadView(Samuji.Collections.currentView, function(){
						Samuji.Collections.useSpecialImages = true;
						Samuji.Collections.loadModels(Samuji.Collections.currentIndex);
					});
				break;
				case Samuji.Collections.COLUMNVIEW:
				case Samuji.Collections.GRIDVIEW:
					$('body').addClass('view-' + view);
					Samuji.Collections.loadView(view, function(){
						Samuji.Collections.currentView = view;
						Samuji.Collections.loadModels(Samuji.Collections.currentIndex);
					});
				break;
			}
			
			return false;
		},
		
		loadView: function (view, callback)
		{
			view = (view == Samuji.Collections.GRIDVIEW ? 'thumbs' : 'coverflow');
			
			$('body').addClass('loading');
			$('#content').fadeOut(function() {
				$(this).load('_views/' + view, function() {
					$(this).fadeIn();
					$('body').removeClass('loading');
					if(typeof callback == 'function') callback();
				});
			});
		},
		
		loadSpecials: false,
		
		loadModels: function (index)
		{
			
			// Load set of new models and place them accordingly
			index = index || 0;
			index = parseInt(index);
			
			log('Collections::loadModels', index);
			Samuji.Collections.currentIndex = index;
			
			if(
				Samuji.Collections.currentView == Samuji.Collections.COLUMNVIEW ||
				Samuji.Collections.currentView == Samuji.Collections.SPECIALVIEW
			) {
				var looks = [index - 2, index - 1, index, index + 1, index + 2];
				var lookElements = $('.look');
				
				if(Samuji.Collections.useSpecialImages) {
					Samuji.Collections.loadSpecials = true;
					Samuji.Collections.currentView = Samuji.Collections.COLUMNVIEW;
				}
				
				$.each(looks, function(i, value)
				{
					if(value < 0) value = Samuji.Collections.looksData.length + value;
					if(value >= Samuji.Collections.looksData.length) value = value - Samuji.Collections.looksData.length;
					
					var source;
					if(Samuji.Collections.loadSpecials == true) {
						source = Samuji.Collections.looksData[value].images.special;
					}
					else {
						source = Samuji.Collections.looksData[value].images.front;
					}
					/*
					else if(i == 0) source = Samuji.Collections.looksData[value].images.left;
					else if(i == 1) source = Samuji.Collections.looksData[value].images['front-left'];
					else if(i == 2) source = Samuji.Collections.looksData[value].images.front;
					else if(i == 3) source = Samuji.Collections.looksData[value].images['front-right'];
					else if(i == 4) source = Samuji.Collections.looksData[value].images.right;*/
					
					
					var img = $('<img>').attr('src', source).attr('id', 'look-image-' + value).attr('rel', value);
					if(i == 2) img.addClass('front');
					$('article', lookElements[i]).html(img);
				});
				
				Samuji.Collections.loadSpecials = false;
				
				$('#content ul li:not(.main)').unbind('click');
				$('#content ul li:not(.main)').click(function(){
					Samuji.Collections.browseToIndex($('img', this).attr('rel'));
				});
				
				/*if(Samuji.Collections.imagesPreloaded == false) {
					//setTimeout("Samuji.Collections.preloadImages();", 1000);
				}*/
			}
			else if(Samuji.Collections.currentView == Samuji.Collections.GRIDVIEW) {
				
				var looks = $('li.look article');
				// console.log(looks);
				var i = 0, li = 0;
				$.each(Samuji.Collections.looksData, function(value, obj)
				{
					if(value < 0) value = Samuji.Collections.looksData.length + value;
					if(value >= Samuji.Collections.looksData.length) value = value - Samuji.Collections.looksData.length;
					
					if(Samuji.Collections.useSpecialImages) {
						var source = Samuji.Collections.looksData[value].images.special;
					}
					else {
						var source = Samuji.Collections.looksData[value].images.front;
					}
					
					var img = $('<img>').attr('src', source).attr('id', 'look-image-' + value).attr('rel', value);
					
					if(i == index) {
						// Place this image in the main window
						$('#main-thumb article').html(img).click(function(){
							
						});
					}
					else {
						// Start placing the images
						$(looks[li]).html(img).click(function(){
							// Swap main image to this one and vice versa
							var v = $('#main-thumb img').attr('rel');
							$('#main-thumb article').html($(this).html());
							
							var s = Samuji.Collections.looksData[v].images.front;
							var img = $('<img>').attr('src', s).attr('id', 'look-image-' + v).attr('rel', v);
							$(this).html(img);
						});
						li++;
					}
					i++;
				});
				
			}
			
			if(Samuji.Collections.useSpecialImages) Samuji.Collections.useSpecialImages = false;
			
		},
		
		preloadImages: function ()
		{
			var preloadedImages = [];
			$.each(Samuji.Collections.looksData, function(i, look) {
				$.each(look.images, function(i, v) {
					var preloader = new Image();
					preloader.src = v;
					preloadedImages.push(preloader);
				});
			});
			
			Samuji.Collections.imagesPreloaded = true;
		},
		
		rotateImage: function ()
		{
			if(Samuji.Collections.currentView == Samuji.Collections.GRIDVIEW) {
				var el = $('#main-thumb img'),
					id = el.attr('rel');
			}
			else {
				var el = $('.look.main img'),
					id = el.attr('rel');
			}
			
			var orientation = el.attr('class'),
				next;
			
			switch (orientation) {
				default:
				case 'front'		: next = 'front-left'; break;
				case 'front-left'	: next = 'left'; break;
				case 'left'			: next = 'back-left'; break;
				case 'back-left'	: next = 'back'; break;
				case 'back'			: next = 'back-right'; break;
				case 'back-right'	: next = 'right'; break;
				case 'right'		: next = 'front-right'; break;
				case 'front-right'	: next = 'front'; break;
			}
			
			var nextImage = Samuji.Collections.looksData[id].images[next]
			el.attr('src', nextImage).removeClass(orientation).addClass(next);
			
			return false;
		},
		
		browseToLeft: function ()
		{
			this.currentIndex = (this.currentIndex - 1 < 0 ? Samuji.Collections.looksData.length - 1 : this.currentIndex - 1);
			Samuji.Collections.loadModels(this.currentIndex);
		},
		
		browseToRight: function ()
		{
			this.currentIndex = (this.currentIndex + 1 >= Samuji.Collections.looksData.length ? 0 : this.currentIndex + 1);
			Samuji.Collections.loadModels(this.currentIndex);
		},
		
		browseToIndex: function (index)
		{
			if(index < 0) index = Samuji.Collections.looksData.length - (index % Samuji.Collections.looksData.length);
			if(index >= Samuji.Collections.looksData.length) index = index % Samuji.Collections.looksData.length;
			
			this.currentIndex = index;
			Samuji.Collections.loadModels(this.currentIndex);
		},
		
		zoomImage: function ()
		{
			Samuji.showFullscreenWindow();
			$('#fullscreen #close').click(Samuji.Collections.closeZoomedImage);
			
			if(Samuji.Collections.currentView == Samuji.Collections.GRIDVIEW) {
				var el = $('#main-thumb img'),
					id = el.attr('rel');
			}
			else {
				var el = $('.look.main img'),
					id = el.attr('rel');
			}
			
			var source = Samuji.Collections.looksData[id].images.fullscreen;
			var content = $('<img>').addClass('zoomed-image');
			$('#fullscreen #fs-content').html(content);
			
			var image = new Image();
			image.onload = function(){
				//// console.log('IMAGE LOADED');
				// preposition image
				$('#fs-content img').css({
					top: 0 - Math.round(image.height * 0.155),
					left: ($(window).width() / 2) - (image.width / 2)
				});
			}
			image.src = source;
			content.attr('src', source)
			
			content.draggable();
			
			return false;
		},
		
		closeZoomedImage: function ()
		{
			Samuji.hideFullscreenWindow();
			$(this).unbind();
		},
		
		showImageInfo: function ()
		{
			$('#fullscreen #fs-content').html('');
			Samuji.showFullscreenWindow();
			$('#fullscreen #close').click(Samuji.Collections.closeImageInfo);
			
			if(Samuji.Collections.currentView == Samuji.Collections.GRIDVIEW) {
				var el = $('#main-thumb img'),
					id = el.attr('rel');
			}
			else {
				var el = $('.look.main img'),
					id = el.attr('rel');
			}
			
			var image_id = Samuji.Collections.looksData[id].id,
				url = '/_views/info/' + image_id;
			
			$.get(url, function(data) {
				$('#fs-content').html(data);
			})
			
			return false;
		},
		
		closeImageInfo: function ()
		{
			Samuji.hideFullscreenWindow();
			$(this).unbind();
		}
		
		
	}
	
};

Samuji.initialize();
