$(window).load(function(){
	
	// add spinner ready
	addSpinner();

	// Assign body class
	if(isMobile()){
		$(document.body).addClass("mobile");
	} else {
		$(document.body).addClass("desktop");
	}
			
	// jQuery Address
	// ------------------------------------------------------------------------------------------------	
	$('nav ul li a').address();	
	$.address.change(function(event) {
		
		clearInterval(loadPageInterval);
		clearInterval(addItemInterval);		
		
		
		console.log(event.pathNames.length);
		
		if(event.pathNames.length == 4){
			removeByIndex(event.pathNames,0);
			removeByIndex(event.pathNames,1);
		}
		
		console.log(event.pathNames.length);
				
		
		// Show spinner
		$('#spinner').fadeIn(200);
		
		$('#thumbs_container').fadeOut(400);
			switch(event.pathNames.length){
			case 0:
			  document.title = 'Soutra Gilmour';  			
				$('#carousel').fadeOut(400,function(){
					$('#items > li').remove();
					if($('#carousel').elastislide()){
						$('#carousel').elastislide('destroy');	
					};
				});				
				loadPage("home", "sections", false);
				break;
			case 1:			
				$('#carousel').fadeOut(400,function(){
					$('#items > li').remove();
					if($('#carousel').elastislide()){
						$('#carousel').elastislide('destroy');	
					};
				});
				var target = event.pathNames[0];					
			  	document.title = unSEO(target) + ' | Soutra Gilmour';  				
				jQuery.data(document.body, 'current_page', target);	
				jQuery.data(document.body, 'sketchbook', false);					
				loadPage(target, "sections", false);	
				break;	
			case 2:
				var target = event.pathNames[1];	
			  	document.title = unSEO(target) + ' | Soutra Gilmour';  		
				jQuery.data(document.body, 'current_page', target);
				jQuery.data(document.body, 'sketchbook', false);
				loadPage(target, "projects", false);	
				break;
			case 3:
				$('#container').fadeOut(400);
				var target = event.pathNames[1];	
			  document.title = unSEO(target) + ' | Soutra Gilmour';  				
				jQuery.data(document.body, 'current_page', target);
				jQuery.data(document.body, 'sketchbook', true);
				loadPage(target, "projects", true);	
				break;				
			};
		}); 
	
	// Toggle content visibility
	$('#toggle').click(function(e){
		e.preventDefault();
		if($('#container').is(":visible")){
			$('#container').fadeOut(300);
			$(this).animate({backgroundPosition: '0 -26px'});
		} else {
			$('#container').fadeIn(300);
			$(this).animate({backgroundPosition: '0 0'});
		};
	});
		
	// Toggle bg image zoom
	$('#zoom').click(function(e){		
		e.preventDefault();
		$tf_bg_img = $('#bgs img');
		var $this	= $(this);
		if($this.hasClass('zoom')){
			resize($tf_bg_img);
			$this.addClass('tf_fullscreen').removeClass('zoom');
			$(this).animate({backgroundPosition: '0 0'});		 
		} else {
			var dim	= getImageDim($tf_bg_img);
			$tf_bg_img.animate({ width : dim.width, height	: dim.height, top		: dim.top, left : dim.left },350);
			$this.addClass('zoom').removeClass('tf_fullscreen');	
			$(this).animate({backgroundPosition: '0 -26px'});										 
		};
		}
	);		
			
});


// INtervals
var loadPageInterval, addItemInterval;

// Load page content
// ------------------------------------------------------------------------------------------------	
function loadPage(target, content_type, sketchbook){
	
	// Add content once loaded
	function contentLoaded(){
		if(target_copy && target_image){
			clearInterval(loadPageInterval);
			addContent(target_copy,target_image); 					
		}
	}
	loadPageInterval = setInterval(contentLoaded, 500);	

	// Create URLS
	var base_url = getBaseURL();	
	var inc = "_inc/" + content_type + "/";	
	var img = "img/" + content_type + "/";	
	var target_page = base_url + inc + target + ".php";

	switch(content_type){
		case "sections":
			var target_background = base_url + img + target + ".jpg";
			break;
		case "projects":
			if(!sketchbook){
				var target_background = base_url + img + target + "/1.jpg";
			} else {
				var target_background = base_url + img + target + "/sketchbook/1.jpg";				
			};
			break;				
	};
	// Load content	
	target_copy = loadContent(target_page,null);	
	target_image = loadContent(null,target_background);
};

	function loadContent(target_page, target_background){
		if(target_page){
			return $.ajax({
				url: target_page,
				context: document.body,
				success: function(data){
				return data;
				}
			});				
		}
		if(target_background){
			var img = new Image();		
			$(img).load(function () {
				var new_image = $(this);
				$(this).hide();
				$('#bgs').append(this);
				target_image = $(this);	
				return target_image;
			})
			.error(function () {
				console.log("image error");
			})
			.attr('src', target_background);				
		}		
	}
	
	function addContent(target_copy, target_image){
		
		if(target_copy){
			$('#copy').stop().fadeOut(400, function() {
				addImage();
			});
		} else {
			addImage();	
		};
		
		function addImage(){
			repositionImage();				
			$(target_image).stop().fadeIn(400, function(){
				$('#spinner').fadeOut(200);				
				if(target_copy){
					addCopy();
				};				
				$('#bgs img').each(function(index){
					if($(this)[0] !== target_image[0]){
						$(this).remove();
					};
				});		
			});			
		};
		
		function addCopy(){
				$('#copy').html(target_copy.responseText);
				$('#copy .show a').address();				
				$('#copy').delay(400).fadeIn(400,function(){
					if(isMobile()){
						if($('h3')[0]){
							$.scrollTo('h3', 1200);		
						} else {
							$.scrollTo('h2.show-title', 1200);	
						}
					};
				});
				$('#spinner').fadeOut(200);				
				
				if($('#copy > #thumbs')[0] && !isMobile() ){
					// Remove elistislide
					$('#items > li').remove();
					if($('#carousel').elastislide()){
						$('#carousel').elastislide('destroy');	
					};					
					// Move thumbs
					if(!jQuery.data(document.body, 'sketchbook')){
						var thumbs = $('#thumbs li').detach();
						thumbs.appendTo('#items');			
						$('#sketchbooks').hide();
					} else {
						var thumbs = $('#sketchbooks li').detach();
						thumbs.appendTo('#items');			
						$('#thumbs').hide();						
					};
					// Add elastislide
					$('#carousel').elastislide({
						imageW 		: 80,
						minItems	: 3,
						border		: 0,
						onClick     : function( $item ) { 
							var target_image = $($item).find('a').attr('href')				
							addItem(target_image); 
							// Show spinner
							$('#spinner').fadeIn(200);							
						}
					});										
					$('#carousel').fadeIn(400);
				};
				
				// Toggle sketchbook HTML
				if(jQuery.data(document.body, 'sketchbook')){
						$("a#sketchbook_toggle").html("view gallery &raquo;");	
					} else {
						$("a#sketchbook_toggle").html("view sketchbook &raquo;");							
					}													
				$(window).resize();
								
				// Toggle sketchbook
				$("a#sketchbook_toggle").click(function(e){
					e.preventDefault();
					if(jQuery.data(document.body, 'sketchbook')){
						var href = getBaseURL();
						var uris = document.location.href.split("/");
						href += uris[3] + "/" + uris[4] + "/" + uris[5];
						//console.log(href);
						window.location.href = href;	
					} else {
						window.location.href = document.location.href+"/sketchbook/";						
					}
				});					
				
		};
	}		

		function addItem(target_background){				
			function contentLoaded(){		
				if(target_image){
					clearInterval(addItemInterval);
					addContent(null,target_image);		  					
				}
			};
			addItemInterval = setInterval(contentLoaded, 500);	
			target_image = loadContent(null,target_background);
		}		

		function attachFancybox(){	
			$("a#sketchbook_trigger").click(function(e){
				e.preventDefault();
				$("a.fancybox-thumb").first().trigger('click');
			});
		};

// Background management
// ------------------------------------------------------------------------------------------------	
function repositionImage(){
	// Reposition the image				
	$tf_bg_img = $('#bgs img');
	var dim	= getImageDim($tf_bg_img );
	$tf_bg_img.css({
		width	: dim.width,
		height	: dim.height,
		left	: dim.left,
		top		: dim.top
	});	
};

//get dimentions of the image, 
//in order to make it full size and centered
function getImageDim($img){
	var w_w	= $(window).width(),
		w_h	= $(window).height(),
		r_w	= w_h / w_w,
		i_w	= $img.width(),
		i_h	= $img.height(),
		r_i	= i_h / i_w,
		new_w,new_h,
		new_left,new_top;
	
	if(r_w > r_i){
		new_h	= w_h;
		new_w	= w_h / r_i;
	}
	else{
		new_h	= w_w * r_i;
		new_w	= w_w;
	}
	
	return {
		width	: new_w + 'px',
		height	: new_h + 'px',
		left	: (w_w - new_w) / 2 + 'px',
		top		: (w_h - new_h) / 2 + 'px'
	};
}

//resizing the window resizes the $tf_bg_img
$(window).bind('resize',function(){
	resizeRighthand();
	repositionImage();
});

//expand and fit the image to the screen

	//animate the image to fit in the viewport
	function resize($img){
		var w_w	= $(window).width(),
			w_h	= $(window).height(),
			i_w	= $img.width(),
			i_h	= $img.height(),
			r_i	= i_h / i_w,
			new_w,new_h;
		
		if(i_w > i_h){
			new_w	= w_w;
			new_h	= w_w * r_i;
			
			if(new_h > w_h){
				new_h	= w_h;
				new_w	= w_h / r_i;
			}
		}	
		else{
			new_h	= w_w * r_i;
			new_w	= w_w;
		}
		
		$img.animate({
			width	: new_w + 'px',
			height	: new_h + 'px',
			top		: '0px',
			left	: '0px'
		},350);
	}
	
// Utilities
// ------------------------------------------------------------------------------------------------	
$.fn.image = function(src, f){ 
   return this.each(function(){ 
     var i = new Image(); 
     i.src = src; 
     i.onload = f; 
     this.appendChild(i);
   }); 
}

function isMobile(){
	if($(window).width() < 490 ){
		return true;
	} else {
		return false;
	};
};

function getBaseURL(){
	// Work out base url
	var href = document.location.href;
	var location = href.split('/');	
	var domain = location[2].toString();
	var foundDev = domain.search(/dev./);
	var foundLocalHost = domain.search(/localhost/);

	// return on dev or localhost
	if(foundDev != -1 || foundLocalHost != -1){
		return location[0] + "//" + location[2] + "/" + location[3] + "/";
	// else live
	} else {
		return location[0] + "//" + location[2] + "/";	
	};	
}

	function resizeRighthand(){
		// Resize	the carosel container
		width = ($(window).width() - $('#container').width()) - 170;
		if($('#righthand').width() !== width){
			$('#righthand').width(width);
		};
	};
	
function unSEO(target){
	title = target.replace(/-/gi," ");
	title = title.toCapitalize();
	return title;
}

function addSpinner(){
	var spinner = new Spinner({
		lines: 12, // The number of lines to draw
		length: 4, // The length of each line
		width: 3, // The line thickness
		radius: 10, // The radius of the inner circle
		color: '#fff', // #rbg or #rrggbb
		speed: 1, // Rounds per second
		trail: 100, // Afterglow percentage
		shadow: true // Whether to render a shadow
	}).spin(document.getElementById("spinner"));	
};

String.prototype.toCapitalize = function()
{ 
   return this.toLowerCase().replace(/^.|\s\S/g, function(a) { return a.toUpperCase(); });
}		


function removeByIndex(arr, index) {
    arr.splice(index, 1);
}

