// Preload Images for navigation
var images  = [];
var preload = [];
preload[0]  = '/images/nav_left_arrow.png';
preload[1]  = '/images/nav_right_arrow.png';
preload[2]  = '/images/nav_info.png';
for (i=0; i < preload.length; i++) {
	images[i] = new Image();
	images[i].src = preload[i];
}



// Public variables
var data           = null;
var timer          = null;
var nav_fading     = false;
var nav_clickable  = true;
var info_clickable = true;



// Easing Definition
$.easing.def = "easeOutQuad";


function nav_init() {
	$('#project_info').hide();
	$('#project_nav_links').hide();
	$('#project_info').css('left', '-500px');
	
	var justDragged = false;
	
	var x_cord = null;
	var y_cord = null;
	var nav_cords = getCookie('navPosition');
	if (nav_cords.length > 0) {
		var seperator = nav_cords.indexOf(',');
		y_cord = nav_cords.substring(0, seperator);
		x_cord = nav_cords.substring((seperator+1));
	}
	else {
		x_cord = ($('body').width() - 150) / 2;
		y_cord = -150;
		
		if ($.browser.mozilla) {
			y_cord = 450;
		}
		if (isiPhone()) {
			switch(window.orientation){
				case 0:
					x_cord = 42;
					break;
				case -90:
					x_cord = 121;
					break;
				case 90:
					x_cord = 121;
					break;
			}
			
			y_cord = -110;
		}
	}
	
//	alert(x_cord + ';' + y_cord);
	
	
	var nav = $('<div/>');
	nav.attr('id','nav');
	nav.css('left', x_cord + 'px');
	nav.css('top', y_cord + 'px');
	nav.draggable({
		delay: 0,
		distance: 10,
		containment: 'document',
		scroll: false,
		start:  function(event, ui) { justDragged = true; },
		drag:   function(event, ui) { },
		stop:   function(event, ui) { setCookie('navPosition',ui.position.top + ',' + ui.position.left, 30); }
	});
	
	var left_arrow = $('<div/>');
	left_arrow.attr('href','#prev');
	left_arrow.attr('id','nav_left_arrow');
	left_arrow.attr('title','See the previous project');
	left_arrow.bind('click', function() {
		if (justDragged) {
			justDragged = false;
			return false;
		}
		projectScroll('prev');
	});
	
	var right_arrow = $('<div/>');
	right_arrow.attr('href','#next');
	right_arrow.attr('id','nav_right_arrow');
	right_arrow.attr('title','See the next project');
	right_arrow.bind('click', function() {
		if (justDragged) {
			justDragged = false;
			return false;
		}
		projectScroll('next');
	});
	
	var info = $('<div/>');
	info.attr('href','#info');
	info.attr('id','nav_info');
	info.attr('title','View extra information');
	info.bind('click', function() {
		if (justDragged) {
			justDragged = false;
			return false;
		}
		projectInfo();
	});
	
	
	
	$(nav).append(left_arrow);
	$(nav).append(info);
	$(nav).append(right_arrow);
	$('body').append(nav);
	
	
	$(document).bind('mousemove', function MouseMovement(e) {
//		console.log('mouse moved');
		if (nav_fading) {
			return false;
		}
		
		
		if ($('#nav').css('display') != 'block') {
			showNav();
		}
		else {
			resetTimer();
		}
	});
}





function projectScroll(direction) {
//	console.log('arrow clicked: ' + direction);
	resetTimer();
	
	
	if (!nav_clickable) {
		return false;
	}
	nav_clickable = false;
	
	
	if (data == null) {
		var url = "/ajaxProjectsXML";
		$.get(url, function(xml) {
			data = xml;
			return handlePageFlip(direction);
		});
	}
	else {
		return handlePageFlip(direction);
	}	
}



function handlePageFlip(direction) {
	var id = $('#project_id').val();
	var og_width = 956//$('#body img.project_preview').width();
	
	
	// determine wether to go to next or previous project
	switch (direction) {
		case 'next':
			var new_project = $('project[id='+id+']', data).next();
			var left_cord   = -1000;
			var right_cord  = 1000;
			break;
		case 'prev':
			var new_project = $('project[id='+id+']', data).prev();
			var left_cord   = 1000;
			var right_cord  = -1000;
			break;
		default:
			alert('error');
	}
	
	if (new_project.size() < 1) {
//		console.log('no more that direction');
		nav_clickable = true;
		return false;
	}
	
//	alert(new_project.children('description').val());
	
	//new project values
	var new_id      = new_project.attr('id');
	var new_slug    = new_project.children('slug').text();
	var new_title   = new_project.children('title').text();
	var new_desc    = new_project.children('description').text();
	var new_url     = new_project.children('url').text();
	
	
	
	// show new project preview
	$('#project_preview_container img.project_preview').animate({left:left_cord}, 400, function() {
		// update url hash
		lastHash = "#project/" + new_slug;
		window.location.hash = "project/" + new_slug;
		
		// update page title
		updateTitle(new_title);
		
		// track page change with google analytics
		pageTracker._trackPageview(window.location);
		
		// reset timer
		var t = null;
		
		var newPreview = new Image();
		newPreview.onload = function() {
			clearTimeout(t);
			$('#project_preview_container').css('background-image', 'none');
			
			var p = $('#project_preview_container img.project_preview');
			p.css('left', right_cord);
			p.attr('src', this.src);
			p.animate({left:0}, 1300, 'easeOutCirc', function() {
				nav_clickable = true;
			});
		};
		
		t = setTimeout(function() {
			$('#project_preview_container').css('background-image', 'url(/images/ajax-loader.gif)');
		}, 100);
		
		var iphone_path = ""
		if (isiPhone()) { iphone_path = "_iphone"; } 
		newPreview.src = '/project_images/'+new_slug+iphone_path+'.jpg'
	});
	
	// show new project info
	$('#project_info_fader').hide();
	
//	alert(new_desc);
	
	$('#project_id').val(new_id);
	$('#project_title').html(new_title);
	$('#project_description').html(new_desc);
	$('#project_url').attr('href', new_url);
	$('#project_url').html(new_url);
	
	$('#project_info_fader').fadeIn(1700, 'easeInCirc');
}




function projectInfo() {
	resetTimer();
	
	if (!info_clickable) {
		return false;
	}
	info_clickable = false;
	
	
	
	
	
	var info_panel    = $('#project_info');
	var panel_width   = info_panel.outerWidth();
	var rest_position = null;
	var direction     = '';
	
	
	if (info_panel.css('left') == '-200px') {
		rest_position = panel_width * -1;
	}
	else {
		rest_position = -200;
	}
	
	info_panel.show();
	info_panel.animate({left:rest_position}, 1200, 'easeInOutBack',  function() {
		if (rest_position < -200) {
			$(this).hide();
		}
		info_clickable = true;
	});
	
	
	return false;
}




function resetTimer() {
//	console.log('timer reset');
	clearTimeout(timer);
	timer = setTimeout(function timerSet() {
		hideNav();
	}, 3000);
}


function showNav() {
//	console.log('show');
	nav_fading = true;
	$('#nav').fadeIn(400, function fadedIn() {
		nav_fading = false;
	});
}

function hideNav() {
//	console.log('hide');
	nav_fading = true;
	$('#nav').fadeOut(400, function fadedOut() {
		nav_fading = false;
	});

	
}



function getCookie(name) {
	if (document.cookie.length > 0) {
	  c_start = document.cookie.indexOf(name + "=");
	  if (c_start != -1) {
	    c_start = c_start + name.length+1;
	    c_end   = document.cookie.indexOf(";", c_start);
	    
	    if (c_end == -1) { c_end = document.cookie.length; }
	    return unescape(document.cookie.substring(c_start,c_end));
	  }
	}
	
	return "";
}

function setCookie(name, value, expireDays) {
	var expire_date = new Date();
	expire_date.setDate(expire_date.getDate() + expireDays);
	
	document.cookie = name + "=" + escape(value) + 
					  ((expireDays==null)? "" : ";expires=" + expire_date.toGMTString());
}




function nav_remove() {
	timer          = null;
	nav_fading     = false;
	nav_clickable  = true;
	info_clickable = true;
	
	$('#nav').draggable('destroy');
	$('#nav').remove();
	$(document).unbind('mousemove');
}


function isiPhone() {
    var agent = navigator.userAgent.toLowerCase();
    
    if (agent.match(/iPhone/i)) {
    	return true;
    }
    else if (agent.match(/iPod/i)) {
    	return true;
    }
    else {
    	return false;
    }
} 




