/*global $ */

var undefined;

var setup = false;

var single_column = false;
var scale_pages = true;
var max_paper_height = 1020;

var paper_ratio = null;
var fontsize_ratio = null;

var auto_scrolling = false;
var scrolling_timer = null;


$(document).ready(function (e){
	var paper_height = $(".paper:eq(0)").height();
	paper_ratio = $(".paper:eq(0)").width() / paper_height;
	fontsize_ratio = parseFloat($(".page").css("font-size")) / paper_height;
	
	// Browser-specific overrides
	if ($.browser.mozilla){
		if (parseFloat($.browser.version.substr(0,3)) < 1.9){
			scale_pages = false;
		}
	}
	
	if (!single_column){
		$(".spread").css("clear", "none");
	}
	
	layout(scale_pages);
	if (scale_pages){
	 	if(document.elementFromPoint){
			$(window).resize(function (e){
				layout(true, e);
				show_bookmarks();
			});
		} else {
			$(window).resize(function (e){ layout(true, e); });
		}
	}
	
	animate_links();
	show();
	
	if (document.elementFromPoint){
		show_bookmarks(!$.browser.msie);
		$(window).scroll(function (e){ clearTimeout(scrolling_timer); scrolling_timer = setTimeout(function (e){ show_bookmarks(); }, 500); });
	}
	
	// var form_id = "#contact";
	// $(form_id).ajaxForm({
	// 	beforeSubmit: function (data, form, options){
	// 		$(form_id).find(":submit").each(function (i){
	// 			this.value = "Sending...";
	// 		});
	// 		$(form_id).find(":input").enable(false);
	// 		$(form_id).fadeTo("slow", 0.3);
	// 	},
	// 	success: function (response){
	// 		var contents = $(response).find(form_id).parents(".page").contents();
	// 		$(form_id).parents(".page").empty().append(contents);
	// 	},
	// 	resetForm: true
	// });
	
	setTimeout(function (){
		if (document.location.hash !== ""){
			reveal(document.location.hash);
		} else {
			if ($(window).scrollLeft() == 0 && $(window).scrollTop() == 0){
				reveal($(".bookmark a").attr("href"));
			}
		}
	}, 5 * 1000);
	
	setup = true;
});

function show(name){
	var switched = $("#switched");
	var buttons = switched.parent().find(".buttons a");
	if (name === undefined){
		switched.find("div:eq(0)").css("left", -1 * $(".page").width());
		$("a[rel=popup]").click(function (e){ show($(this).attr('id')); return false; });
		buttons.show();
	} else if (name === false){
		switched.find("div:eq(0)").animate({left: -1 * $(".page").width()}, "slow", function (e){
			switched.find("img:eq(0)").attr("src", "media/img/blank.gif");
			buttons.show();
		});
	} else {
		buttons.hide();
		var dogging_timer = setInterval(function (e){ dogear(); }, 1500);
		switched.find("img:eq(0)").one("load", function (e){
			clearInterval(dogging_timer);
			dogear(false);
			switched.find("div:eq(0)").animate({left: 0}, "slow");
			buttons.parent().one("click", function (e){ show(false); $(this).removeClass("clickable") }).addClass("clickable");
		});
		switched.find("img:eq(0)").attr("src", "media/img/pages/" + name + ".jpg");
	}
}


function dogear(state){
	state = (state === undefined) ? true : state;
	var ears = $("#switched").find(".ears")
	var ear_static = ears.find(".static");
	var ear_animated = ears.find(".animated");
	var width = ear_static.width();
	if (state){
		ear_static.width(width).height(width);
		ear_animated.width(0).height(0).show();
		ear_animated.animate({
			width: width,
			height: width
		}, "normal", function (){
			ear_static.show();
			$(this).width(0).height(0).hide();
		});
	} else {
		ear_animated.width(0).height(0).hide();
		// ear_static.animate({
		// 	width: 0,
		// 	height: 0
		// }, "fast", function (){
		// 	$(this).hide();
		// });
		ear_static.width(0).height(0).hide();
	}
}

function bookmark_css(state){
	state = state + 0;
	return {
		top: [-0.7, -0.4][state] * $(".bookmark:eq(0)").outerHeight(),
		opacity: state
	};
}
function show_bookmarks(state){
	if(state === false){
		$(".bookmark").hide();
	}
	
	var x = $(window).width() / 2;
	if (scale_pages){
		var y = 4/5 * $(window).height();
	} else {
		var y = 1/2 * $(window).height();
	}
	if ($.browser.safari || $.browser.opera){
		x += $(window).scrollLeft();
		y += $(window).scrollTop();
	}
	var menu = $(document.elementFromPoint(x, y)).parents(".spread").find(".bookmark");
	$(".bookmark").each(function (i){
		if ($(this)[0] === menu[0]){
			if ($(this).css("display") === "none"){
				$(this).show();
				$(this).animate(bookmark_css(true));
			}
		} else {
			if ($(this).css("display") !== "none"){
				$(this).animate(bookmark_css(false), function (){ $(this).hide(); });
			}
		}
	});
}

function layout(fit, e){
	fit = (fit === undefined) ? true : fit;
	
	if (auto_scrolling){
		return null;
	}
	
	var target_width;
	if (fit){
		var target_height = Math.min($(window).height() * 0.80, max_paper_height);
		var target_fontsize = target_height * fontsize_ratio;
		
		if ($.browser.msie){
			target_fontsize = parseInt(target_fontsize);
			target_height = target_fontsize / fontsize_ratio;
		}
		
		target_width = target_height * paper_ratio;
		
		// var h_position_ratio = $(window).scrollLeft() / $(document).width();
		var h_position_ratio = ($(window).scrollLeft() + $(window).width()/2) / $(document).width();
		var v_position_ratio = $(window).scrollTop() / $(document).height();
		
		$(".page").each(function (i){
			$(this).width(target_width);
			$(this).height(target_height);
			$("body").css("font-size", target_fontsize);
		});
	} else {
		target_width = $(".page:eq(0)").width();
	}
	
	if ($.browser.msie){
		$(".spread").width((target_width * 2) + 5);
	}
	
	var spread_width = $(".spread:eq(1)").outerWidth({margin: true});
	var spreads_across = single_column + 0 || Math.floor(Math.sqrt($(".spread").length));
	$("#artboard").width(spreads_across * (spread_width * 1.02));
	
	if (setup) {
		// var h_position = $(document).width() * h_position_ratio;
		var h_position = $(document).width() * h_position_ratio - $(window).width()/2;
		var v_position = $(document).height() * v_position_ratio;
		$(window).scrollLeft(h_position);
		$(window).scrollTop(v_position);
		
		show();
	}
}

function animate_links(){
	$("a[href^=#]").bind("click", function(e){
		if (this.hash.length){
			reveal(this.hash);
		}
		return false;
	});
}

function reveal(target){
	auto_scrolling = true;
	
	var scroll_settings = {
		axis: (single_column) ? "y" : "xy",
		queue: false,
		easing: "easeOutQuad",  // easeOutBounce
		onAfter: function (){
			auto_scrolling = false;
		}
	};
	
	var page = $(target);
	if (!page.length){
		return false;
	}
	var spread = $(target).parents(".spread");
	
	var v_offset = ($(window).height() - spread.height()) / -2;
	var h_offset;
	if ($(window).width() > spread.width()){
		h_offset = ($(window).width() - spread.width()) / -2;
		target = spread;
	} else {
		h_offset = ($(window).width() - page.width()) / -2;
		target = page;
	}
	scroll_settings.offset = {left: h_offset, top: v_offset};
	
	var h_distance = (target.offset().left + h_offset) - $(window).scrollLeft();
	var v_distance = (target.offset().top + v_offset) - $(window).scrollTop();
	var distance = Math.sqrt(Math.pow(h_distance, 2) + Math.pow(v_distance, 2));
	var duration = ((single_column)?1:1.7) * distance;
	
	$.scrollTo(target, duration, scroll_settings);
}

function popup (href, width, height){
	width = (width === undefined) ? 995 : width;
	//height = (height === undefined) ? 675 : height;
	height = (height === undefined) ? 690 : height;
	
	
	var top = (screen.height - (height + 110)) / 2;
	var left = (screen.width - width) / 2;
	
	var parameters = "";
	parameters += "left=" + left + "," + "screenX=" + left + ",";
	parameters += "top=" + top + "," + "screenY=" + top + ",";
	parameters += "width=" + width + ",";
	parameters += "height=" + height + ",";
	parameters += "menubar=" + "no" + ",";
	parameters += "toolbar=" + "no" + ",";
	parameters += "location=" + "no" + ",";
	parameters += "personalbar=" + "no" + ",";
	parameters += "scrollbars=" + "yes" + ",";
	parameters += "status=" + "no" + ",";
	parameters += "resizable=" + "yes" + ",";
	parameters += "copyhistory=" + "no" + ",";
	parameters += "channelmode=" + "no" + ",";
	parameters += "dependent=" + "no" + ",";
	parameters += "dialog=" + "no" + ",";
	parameters += "minimizable=" + "no" + ",";
	window.open(href, "neyn_popup", parameters).focus();
}

function debug(msg, clear){
	$("#debug").show();
	if(clear){
		$("#debug").text(msg + "\n");
	} else {
		$("#debug").text($("#debug").text() + msg + "\n");
	}
}
