var m = m || {};

m.gl = {}; m.ev = {}; m.fn = {};

// -------------------------------------------------------------
// 1. Globals
// -------------------------------------------------------------

m.gl.state = {}, m.gl.state.hash = '', m.gl.state.depth = 0, m.gl.state.menus = {},
m.gl.data = {}, m.gl.data.projects = {}, m.gl.data.pages = {},
m.gl.image = {}, m.gl.image.width = 1440, m.gl.image.height = 900, m.gl.image.proportion = 1.6,
m.gl.view = {}, m.gl.view.width = 0, m.gl.view.height = 0, m.gl.view.proportion = 0,
m.gl.tooltip = {}, m.gl.tooltip.active = false, m.gl.tooltip.content = '', m.gl.tooltip.direction = '',
m.gl.dataSource = 'm.json',
m.gl.fileSource = 'files/',
m.gl.loadedImages = 0,
m.gl.activeData = {},
m.gl.activeImage = 0,
m.gl.entryHash = '',
m.gl.isReady = false,
m.gl.isLoading = true;

if(typeof console != 'undefined') { m.gl.debug = true; }

(function($) {
	
	// -------------------------------------------------------------	
	// 2. Events
	// -------------------------------------------------------------
	
	m.ev.ready = function(event) {
		
		m.gl.isReady = true;
		
		if(m.gl.debug) { console.log('Ready'); }
		
		m.ev.resize();
		
		m.fn.loadState();
		
		m.fn.loadData();
		
		m.fn.menuBoxes();
		
		m.fn.navigation();
		
	}
	
	m.ev.loadingStart = function(event) {
		
		if(!m.gl.isLoading) {
			m.gl.isLoading = true;
			if(m.gl.debug) { console.log('Loading Started'); console.time('Load'); }
			$('#spinner').stop(true, true).fadeIn('fast');
		}
		
	}
	
	m.ev.loadingFinish = function(event) {
		
		if(m.gl.isLoading) {
			m.gl.isLoading = false;
			if(m.gl.debug) { console.log('Loading Finished'); console.timeEnd('Load'); }
			$('#spinner').stop(true, true).fadeOut('slow');
		}
		
	}
	
	m.ev.imagesLoadedCallback = function() {
		
		return false;
		
	}
	
	m.ev.resize = function(event) {
		
		m.fn.layout();
		
	}
	
	m.ev.history = function() {
		
		$.history.init(function(hash) {
			
			if(!hash || hash.length < 3) {
				
				window.location.hash = '!/page/home';
				
			} else {
				m.gl.state = m.gl.state || {};

				m.gl.state.hash = hash.replace('#', '').replace('!/', '');
				m.gl.state.depth = m.gl.state.hash.split('/');

				m.fn.history();
			}

		});
		
	}
	
	m.ev.mouseMove = function(event) {
	
	}
	
	$(document)
		.ready(function(event) { m.ev.ready(event); } )
		.ajaxStart(function(event) { m.ev.loadingStart(event); } )
		.ajaxStop(function(event) { m.ev.loadingFinish(event); } );
	
	$(window)
		.bind('resize', function(event) { m.ev.resize(event); } )
		.bind('mousemove', function(event) { m.ev.mouseMove(event); });
	
	// -------------------------------------------------------------
	// 3. Functions
	// -------------------------------------------------------------
	
	m.fn.layout = function() {
		
		m.gl.view.width = $(window).width();
		m.gl.view.height = $(window).height();
		m.gl.view.proportion = m.gl.view.width / m.gl.view.height;
		
		$('#m, #images, #images li').css({
			width: m.gl.view.width,
			height: m.gl.view.height
		});
		
		if(m.gl.image.proportion < m.gl.view.proportion) {
			imageWidth = m.gl.view.width;
		 	imageHeight = Math.ceil(m.gl.view.width / m.gl.image.proportion);
		} else {
			imageHeight = m.gl.view.height;
			imageWidth = Math.ceil(m.gl.view.height * m.gl.image.proportion);
		}
		
		$('#images img').attr('width', imageWidth).attr('height', imageHeight);
		$('#images img').css({
			top: (m.gl.view.height - imageHeight) / 2,
			left: (m.gl.view.width - imageWidth) / 2
		});
		
		if($('#images li').eq(m.gl.state.depth[2]-1).length > 0) {
			$('#images').scrollTo($('#images li').eq(m.gl.state.depth[2]-1), 0);
		}
		
		$('#spinner').css({
			left: m.gl.view.width / 2 - (parseInt($('#spinner').outerWidth()) / 2),
			top: m.gl.view.height / 2 - (parseInt($('#spinner').outerHeight()) / 2)
		});
		
		$('.content p:last').css('margin-bottom', 0);
		
	}
	
	m.fn.tooltip = function(event) {
		if(m.gl.tooltip.active) {
			$('#tooltip').css({
				top: event.pageY,
				left: event.pageX
			});
		}
	}
	
	m.fn.history = function() {
		
		m.fn.loadContent();
		
	}
	
	m.fn.loadData = function() {
		
		$.getJSON(m.gl.dataSource, function(response) {
		
			m.gl.data = response.m;
			
			m.fn.appendNavigation();
			
			m.ev.history();
			
		});
		
	}
	
	m.fn.navigation = function() {
		
		$('#images').click(function(event) {
			event.preventDefault();
			m.fn.nextImage();
		});
		
	}
	
	m.fn.nextImage = function() {
		
		if(parseInt(m.gl.state.depth[2]) + 1 <= m.gl.activeData.images.length) {
			window.location.hash = '!/' + m.gl.state.depth[0] + '/' + m.gl.state.depth[1] + '/' + (parseInt(m.gl.state.depth[2]) + 1);
		} else {
			window.location.hash = '!/' + m.gl.state.depth[0] + '/' + m.gl.state.depth[1] + '/1';
		}
		
	}
	
	m.fn.appendNavigation = function() {
		
		$.each(m.gl.data.projects, function(i, project) {
			
			$('ul#projects_list').append(
				$('<li />').append(
					$('<a />').attr('href', '#!/project/' + project.slug)
					.attr('id', 'project_' + project.slug)
					.data(project)
					.html(project.title)
				)
			);
			
		});
		
		$.each(m.gl.data.pages, function(i, page) {
			
			$('ul#pages_list').append(
				$('<li />').append(
					$('<a />').attr('href', '#!/page/' + page.slug)
					.attr('id', 'page_' + page.slug)
					.data(page)
					.html(page.title)
				)
			);
			
		});
		
	}
	
	m.fn.menuBoxes = function() {
		
		$('.menu').data('active', false);
		
		$('*').disableSelection();
		
		$('.menu h2').click(function(event) {
			
			event.preventDefault();
			
			$menu = $(this).parents().closest('.menu');
			
			if(!$menu.data('active')) {
				
				$menu.addClass('active');
				$menu.find('.content').show();
				$menu.find('.toggle').text('-');
				$menu.find('.toggle').addClass('active');
				$menu.data('active', true);
				
			} else {
				
				$menu.removeClass('active');
				$menu.find('.content').hide();
				$menu.find('.toggle').text('+');
				$menu.find('.toggle').removeClass('active');
				$menu.data('active', false);
				
			}
			
		});
		
	}
	
	m.fn.saveState = function() {
		
		$.cookie('ml_state', $.toJSON(m.gl.state));
		
	}
	
	m.fn.loadState = function() {
		
		m.gl.state = $.parseJSON($.cookie('ml_state'));
		
	}

	m.fn.loadContent = function() {
		
		if(m.gl.activeData != $('#' + m.gl.state.depth[0] + '_' + m.gl.state.depth[1]).data()) {
			
			$('#images').scrollTo(0, 0);
			
			$('.replace_content').empty();
			
			
			m.gl.activeData = $('#' + m.gl.state.depth[0] + '_' + m.gl.state.depth[1]).data();
			
			$('#menu_projects li').removeClass('active');
			$('#' + m.gl.state.depth[0] + '_' + m.gl.state.depth[1]).parents('li').addClass('active');

			$('#menu_description .content').append(m.gl.activeData.description);
			
			$('#menu_description .content').children().last().append(' &para;')

			m.gl.loadedImages = {};
			
		}
		
		m.ev.imagesLoadedCallback = function() {
			m.fn.scrollImages();
		}
		
		m.fn.loadImages();
		

	}
	
	m.fn.scrollImages = function() {
		if(m.gl.state.depth[2] <= 1 || !m.gl.state.depth[2]) {
			m.gl.state.depth[2] = 1;
		}
		
		$('#menu_controls li').removeClass('active');
		
		$('#images').scrollTo($('#images li').eq(m.gl.state.depth[2]-1), 500, {easing: 'easeOutExpo'});
		
		$('#menu_controls li').eq(m.gl.state.depth[2]-1).addClass('active');
	}
	
	m.fn.loadImages = function() {
		
		m.gl.loadedImages = parseInt(m.gl.loadedImages) || 0;
		
		if(m.gl.loadedImages != m.gl.activeData.images.length) {
			$('#load_bar').show().stop(true, true).animate({
				height: (100 - ((m.gl.loadedImages) / m.gl.activeData.images.length) * 100) + '%'
			}, { duration: 500, easing: 'easeOutExpo' });
		}
		
		if(m.gl.loadedImages < m.gl.activeData.images.length) {
			
			m.ev.loadingStart();
			
			imageSrc = m.gl.fileSource + m.gl.activeData.images[m.gl.loadedImages];
			
			$('#images').append(
				$('<li />').css({
					width: m.gl.view.width,
					height: m.gl.view.height
				})
				.append(
					$('<img />').attr('src', imageSrc)
					.attr('width', m.gl.image.width).attr('height', m.gl.image.height)
					.hide().load(function() {
						
						m.fn.layout();
					
						$(this).show();
					
						m.gl.loadedImages++;
						
						$('#menu_controls .content ul').append(
							$('<li />').append(
								$('<a />').text(m.gl.loadedImages).attr('href', '#!/' + m.gl.state.depth[0] + '/' + m.gl.state.depth[1] + '/' + m.gl.loadedImages)
							)
						);

						m.fn.loadImages();
					
					})
				)
			);
			
		} else {
			m.ev.loadingFinish();
			$('#load_bar').stop(true, true).animate({
				height: '0%'
			}, { duration: 500, easing: 'easeOutExpo'}).fadeOut('slow', function() {
				$('#load_bar').hide();
			});
			
			m.ev.imagesLoadedCallback();
		}
		
	}
	
})(jQuery);
