//Globals
var menu_open = false;
var on_workpage = false;
var trianglePos = 0;
var bodyclicked = false;

// loadContent function
// This function is called:
// 1. after calling $.historyInit();
// 2. after calling $.historyLoad();
// 3. after clicking "Go Back" button of a browser

function loadContent(html_url) {

	if (html_url) {

		// restore ajax loaded state
		if ($.browser.msie) {
			html_url = encodeURIComponent(html_url);
		}

		$('#main-content .innertube .content').animate({
			opacity: 0
		}, 300);

		$.ajax({
			type: "GET",
			url: html_url + ".html",
			async: true,
			cache: true,
			success: function (msg) {
				setTimeout(function () {
					$('#main-content .innertube .content').html(msg);
					$('#main-content .innertube .content').animate({
						opacity: 1
					}, 300);
					$("html").scrollTop(0);
					$("body").scrollTop(0);
					// Move triangle
					var page = window.location.href.split("#")[1];
					
					switch(page){
						case "news" :
							// nothing
							moveTriangle('76');
							break;
						case "aboutme" :
							moveTriangle((getY($('#menu .innertube li a[href="#aboutme"]')[0]) - 27));
							break;
						case "contact" :
							moveTriangle((getY($('#menu .innertube li a[href="#contact"]')[0]) - 27));
							break;
						case "friends" :
							moveTriangle((getY($('#menu .innertube li a[href="#friends"]')[0]) - 27));
							break;		
						case "legal" :
							// nothing
							moveTriangle('76');
							break;
						case undefined : 
							//moveTriangle('76');
							break;
						default :
							//moveTriangle((getY($('#menu .innertube li a[href="#work_archive"]')[0]) - 27));
							var trianglePosTemp = $("#lefttriangle").css("margin-top").substring(0, $("#lefttriangle").css("margin-top").length - 2) * 1;
					
							if (menu_open) {

								if($('li.active').parent().hasClass('worknav')) {
									//console.log("here");

								} else if(page === "news") {
									// do nothing
								} else if(page === "work_archive"){
									var el = $('#menu .innertube li a[href="#'+window.location.href.split("#")[1]+'"]');
									moveTriangle((getY(el[0]) - 27));
									el.parent().addClass("active");									
									//console.log("there");
								} else if(page === "contact" || page === "aboutme" || page === "friends") {
									$("#lefttriangle").animate({
										marginTop: "" + (trianglePosTemp - ($('ul.worknav').height() * 1) - 4) + "px"
									}, 500);
								} else {
									//console.log("everywhere");
									
									// go to work
									
									var el = $('#menu .innertube li a[href="#'+window.location.href.split("#")[1]+'"]');
									
									if(el.length != 0 || window.location.href.split("#")[1] === "news"){
										el = el.parent();
										
										if(window.location.href.split("#")[1] === "news") {
											// do nothing
										} else {
											moveTriangle((getY(el[0]) - 27));
										}
									} else {									
										moveTriangle((getY($('#menu .innertube li a[href="#work_archive"]')[0]) - 27));
									}
											
									el.addClass("active");										
								}
													
							} else {

								$("li#work img.work-sign").click();	
								
/*
								menu_open = true;

								var el = $('#menu .innertube li a[href="#'+window.location.href.split("#")[1]+'"]');
								if(el.length != 0 || window.location.href.split("#")[1] === "news"){
									el = el.parent();
									
									if(window.location.href.split("#")[1] === "news") {
										// do nothing
									} else {
										$("#lefttriangle").animate({
												marginTop: getY(el[0])-25 + "px"
										}, 500);
									}
								} else {
									moveTriangle((getY($('#menu .innertube li a[href="#work_archive"]')[0]) - 27));
								}
*/					
							}							
							break;
					}					
				}, 400);
			}
		});

	} else {

		// start page
		$('#main-content .innertube .content').animate({
			opacity: 0
		}, 300);

		$.ajax({
			type: "GET",
			url: "news.html",
			async: true,
			cache: true,
			success: function (msg) {

				setTimeout(function () {
					$('#main-content .innertube .content').html(msg);
					$('#main-content .innertube .content').animate({
						opacity: 1
					}, 300);
					$("html").scrollTop(0);
					$("body").scrollTop(0);
				}, 400);

			}
		});
	}

	$('img.info_button').each(function () {
		$(this).click(function () {
			$('div.info').toggle(500);
		});
	});

	$('img.credits_button').each(function () {
		$(this).click(function () {
			$('div.credits').toggle(500);
		});
	});

	$("ul#menulist li").removeClass("active");
	on_workpage = false;

	return false;
}


function moveTriangle(pixels) {
	$("#lefttriangle").animate({
		marginTop: pixels + "px"
	}, 500);

	return false;
}



function getX(oElement) {
	var iReturnValue = 0;
	while (oElement != null) {
		iReturnValue += oElement.offsetLeft;
		oElement = oElement.offsetParent;
	}
	return iReturnValue;
}

function getY(oElement) {
	var iReturnValue = 0;
	while (oElement != null) {
		iReturnValue += oElement.offsetTop;
		oElement = oElement.offsetParent;
	}
	return iReturnValue;
}


// TOOLTIP
$(function () {

	$("li.thumb").each(function () {

		$(this).hover(function () {
			$('div.tooltip').hide();
			//console.log($(this)[0]);
			$(this).next('div.tooltip').css('top', $(this)[0].offsetTop - 48 + 'px').show();
		});

	});

});

function resize() {
	return false;
}

/*
function resize() {
	
	setTimeout(function() {
	
				if(($('div.content').height()+86) < $(window).height()) {
					
					$("div#menu").css("margin-left",""+((($(window).width()-1009)/2)-5.5)+"px");
					$("div#outer").css("background-position",""+((($(window).width()-1009)/2)-5.5)+"px 50%");
					$("div#rightbar").width((($(window).width()-1139)/2)+78.5);	
					
					setTimeout(function() {
						if(($('div.content').height()+86+40+0) > $(window).height()) {
						   $("div#rightbar").height($('div.content').height()+119);
						} else {
						   $("div#rightbar").height($(window).height());
						}
					},100);
				}
				else {
			
					$("div#menu").css("margin-left",""+((($(window).width()-1009)/2)-5.5)+"px");
					$("div#outer").css("background-position",""+((($(window).width()-1009)/2)-5.5)+"px 50%");
					$("div#rightbar").width((($(window).width()-1139)/2)+63.5);	
					
					setTimeout(function() {
						$("div#rightbar").height($('div.content').height()+107);
						//$("div#rightbar").height($(window).height());						
					},100);
				}
	
				var vHeight = 0;
				
	},200);

	$(".content-tube").css("min-height",$(window).height()-20+"px");
 
    
	return false;
	
}
*/

function setFriendsLinks() {

	$("ul.friends-list li").mouseover(function () {
		$(this).css("background-image", "url('../images/selection_arrow.png') transparent scroll");
	});

	return false;
}

function setToggles() {

	$("ul.info-credits-toggle li.info").click(function () {
		var $this = $(this);
		if ($this.is('.active')) {
			$(this).removeClass("active");
		} else {
			$(this).addClass("active");
		}

		$('div.info').fadeSliderToggle();

	});

	$("ul.info-credits-toggle li.credits").click(function () {
		var $this = $(this);
		if ($this.is('.active')) {
			$(this).removeClass("active");
		} else {
			$(this).addClass("active");
		}

		$('div.credits').fadeSliderToggle();

	});

	$("ul.info-credits-toggle li.info").click();

	return false;

}


function setLinks() {
	$('div.project a.menu-load').each(function () {
		$(this).click(function () {
			var hash = this.href;
			hash = hash.replace(/^.*#/, '');
			// moves to a new page. 
			// pageload is called at once. 
			// hash don't contain "#", "?"
			$.history.load(hash);
			//return true;
		});
	});

	return false;
}

function fixTextHover() {

	$("img.centered").mouseover(function () {
		$(this).prev().css("border-color", "#FFFFFF");
	});

	$("a img.background").mouseover(function () {
		$(this).parent().css("border-color", "#FFFFFF");
	});

	$("a img.background").mouseout(function () {
		$(this).parent().css("border-color", "#333333");
	});

	$("img.centered").click(function () {
		$(this).prev().click();
		$(this).prev().css("border-color", "#333333");
	});

	return false;
}


// Handles triangle for back & forward button clickage
$(document).ajaxComplete(function () {

	//if (!bodyclicked) {
	//	$("#lefttriangle").animate({
	//		marginTop: "76px"
	//	}, 500);
	//}

	//console.log("ajaxcomplete - call hide thumbs");

	setTimeout(function () {
		
		Cufon.replace('h1', {
			color: '#FFFFFF',
			fontSize: '69px',
			letterSpacing: '-2px'
		});
		
		Cufon.replace('h2', {
			color: '#FFFFFF',
			fontSize: '43px',
			letterSpacing: '-1.1px'
		});

		Cufon.replace('h3', {
			color: '#FFFFFF',
			fontSize: '41px',
			letterSpacing: '-1.1px'
		});
				
		Cufon.replace('h4', {
			color: '#FFFFFF',
			fontSize: '34pt',
			letterSpacing: '-0.015em'
		});
				
		//console.log("called Cufon");
		$("h1,h2,h3").show();
		
	}, 500);
	
});

(function ($) {
	var cache = [];
	// Arguments are image paths relative to the current page.
	$.preLoadImages = function () {
		var args_len = arguments.length;
		for (var i = args_len; i--;) {
			var cacheImage = document.createElement('img');
			cacheImage.src = arguments[i];
			cache.push(cacheImage);
		}
	}
})(jQuery)

$(document).ready(function () {
	
	// Set triangle up
	var page = window.location.href.split("#")[1];
	
	switch(page){
		case "news" :
			// nothing
			break;
		case "aboutme" :
			moveTriangle((getY($('#menu .innertube li a[href="#aboutme"]')[0]) - 27));
			break;
		case "contact" :
			moveTriangle((getY($('#menu .innertube li a[href="#contact"]')[0]) - 27));
			break;
		case "friends" :
			moveTriangle((getY($('#menu .innertube li a[href="#friends"]')[0]) - 27));
			break;		
		case "legal" :
			// nothing
			break;
		case undefined : 
			moveTriangle('76');
			break;
		default :
			//console.log("here");
			moveTriangle((getY($('#menu .innertube li a[href="#work_archive"]')[0]) - 27));
			break;
	}
					
	// Initialize history plugin.
	// The callback is called at once by present location.hash. 
	$.history.init(loadContent, "news");

	if (window.location == "http://mrharrison.co.uk/" || window.location == "http://www.mrharrison.co.uk/") {
		$.history.load("news");
	}

	setTimeout(function () {
		$('body').animate({
			opacity: 1
		}, 500);
	}, 400);

	// set onclick event for buttons
	$("a[rel='history']").click(function () {

		var hash = this.href;
		hash = hash.replace(/^.*#/, '');
		// moves to a new page. 
		// pageload is called at once. 
		// hash don't contain "#", "?"
		$.history.load(hash);
		//return true;
	});

	// Initialise image & video gallery					   
	$("a[rel^='prettyPhoto']").prettyPhoto();

	// Set the resize function
	//window.onresize = resize;
	// Sets grey bar on active link
	$('#menu .innertube li a').each(function () {
		$(this).click(function () {

			$('#menu .innertube li').each(function () {
				$(this).removeClass("active");
			});

			$(this).parent().addClass("active");

		});
	});

	// Animates triangle
	$('ul#menulist a').each(function () {
		$(this).click(function () {

			$("#lefttriangle").animate({
				marginTop: (getY(this) - 27) + "px"
			}, 500);

		});
	});

	// Sets a timed boolean when page is clicked
	// (for back/forward triangle handler)
	$("body").click(function () {
		bodyclicked = true;
		setTimeout(function () {
			bodyclicked = false;
		}, 2000);
	});

	$("li.thumb").mouseleave(function () {
		$("div.tooltip").hide();
	});
	//======== END MENU LINKS
	//======== WORK LINK
	$("li#work").mouseover(function () {
		if (!menu_open) {
			$("li#work img.work-sign").attr("src", "images/plus_sign.png");
			$("li#work img.work-sign").css("opacity", "1");
		}
	});

	$("li#work").mouseout(function () {
		if (!menu_open) {
			$("li#work img.work-sign").css("opacity", "0");
			$("li#work img.work-sign").attr("src", "images/minus_sign.png");
		}
	});

	$("li#work a.work-list").click(function () {
		if (!on_workpage) {
			//$.historyLoad("work");
			on_workpage = true;
		} else {}

		if (!menu_open) {
			$("li#work img.work-sign").attr("src", "images/minus_sign.png");
			$('ul.worknav').slideDown(500);
			$("li#work img.work-sign").animate({
				opacity: 1
			});
			menu_open = true;
		} else {}
	});

	$("li#work img.work-sign").click(function () {

		var trianglePosTemp = $("#lefttriangle").css("margin-top").substring(0, $("#lefttriangle").css("margin-top").length - 2) * 1;

		if (menu_open) {

			//if (trianglePosTemp > 360) {
			//	$("#lefttriangle").animate({
			//		marginTop: "" + (trianglePosTemp - ($('ul.worknav').height() * 1) - 4) + "px"
			//	}, 500);
			//} else {
			var page = window.location.href.split("#")[1];
			if($('li.active').parent().hasClass('worknav')) {
				//console.log("here");
				$("#lefttriangle").animate({
					marginTop: (getY(document.getElementById("work")) - 27) + "px"
				}, 500);
			} else if(page === "news" || page === "work_archive") {
				// do nothing
				//console.log("there");
			} else if(page === "contact" || page === "aboutme" || page === "friends") {
				$("#lefttriangle").animate({
					marginTop: "" + (trianglePosTemp - ($('ul.worknav').height() * 1) - 4) + "px"
				}, 500);
			} else {
				//console.log("everywhere");
				// go to work
				$("#lefttriangle").animate({
					marginTop: (getY(document.getElementById("work")) - 27) + "px"
				}, 500);				
			}
			
			$('ul.worknav').slideUp(500);
			$("li#work img.work-sign").attr("src", "images/plus_sign.png");
			menu_open = false;

		} else {

			if (!on_workpage && trianglePosTemp > 122) {


/*				$("#lefttriangle").animate({
					marginTop: "" + (trianglePosTemp + ($('ul.worknav').height() * 1)) + "px"
				}, 500);
*/
				//$.historyLoad("work");
				$('#menu .innertube li').each(function () {
					$(this).removeClass("active");
				});
				$("li#work").addClass("active");
				on_workpage = true;

			} else {
				//$("#lefttriangle").animate({ 
				//	marginTop: (getY(document.getElementById("work"))-27)+"px"
				//}, 500 );
			}

			$("li#work img.work-sign").attr("src", "images/minus_sign.png");

			$('ul.worknav').slideDown(500, function(){
				var el = $('#menu .innertube li a[href="#'+window.location.href.split("#")[1]+'"]');
				$('#menu .innertube li').removeClass("active");
				if(el.length != 0 || window.location.href.split("#")[1] === "news"){
					el = el.parent();
					el.addClass("active");

					var page = window.location.href.split("#")[1];

					switch(page){
						case "news" :
							// nothing
							break;
						case "aboutme" :
							moveTriangle((getY($('#menu .innertube li a[href="#aboutme"]')[0]) - 27));
							break;
						case "contact" :
							moveTriangle((getY($('#menu .innertube li a[href="#contact"]')[0]) - 27));
							break;
						case "friends" :
							moveTriangle((getY($('#menu .innertube li a[href="#friends"]')[0]) - 27));
							break;		
						case "legal" :
							moveTriangle('76');
							break;
						case undefined : 
							moveTriangle('76');
							break;
						default :
							moveTriangle((getY(el[0]) - 27));
							break;
					}
				} else {
					$('#menu .innertube li a[href="#work_archive"]').addClass('active');
				}
			});

			
			$(this).animate({
				opacity: 1
			});

			menu_open = true;
		}
	});
	//======== END WORK LINK	
	$("img.thumb").click(function () {
		$(this).parent().parent().children().filter(".menu-load").click();
	});

/*$('ul#menulist li#work ul.worknav li.thumb a.menu-load img').each(function(){
  		var imgName = $(this).attr('src');
  		imgName = imgName.split('/');
  		imgName = imgName[1];
  		$.preLoadImages(imgName, $(this).attr('src'));
  	});*/

}); // end docready
