/* Globals */
var $timeLineListBG  = false;
var sliderIncrement = 0;
var pageCount 		= 1;
var scaleNotchWidth = 20; 
var cursorPositionX = 0;
var cursorPositionY = 0;
var timelineImagesToPreload = [];	
var timelineLoaderTimeout = false;		
		
var currentEra	= 0;		
var $eraBGs 	= false;
var $eraFGs 	= false;
var $tooltip	= false;
var $loader		= false;
var $progressBar	= false;
var assetsLoaded = 0;


/**
 * DOM Load
 */
$(document).ready(function() {
	pageEnhance();

});

/**
 * General "init" function for progressively enhancing the page on DOM load
 */
function getImgSize(imgSrc){
    var newImg = new Image();
    newImg.src = imgSrc;
    var height = newImg.height;
    var width = newImg.width;
    p = $(newImg).ready(function(){
        return {width: newImg.width, height: newImg.height};
    });
}

function pageEnhance() {
	
	$(window).mousemove(function(e){
		cursorPositionX = e.pageX;
		cursorPositionY = e.pageY;
	})
	
		
	
	// timeline  Init
	if($("body").hasClass("home")) {
		timelineInit();
	}
	
	// Grid page
	$('#grid').masonry({
		gutterWidth: 45
	});	
	
	// Gallery	
	$("#full").append('<div class="loader" />')
	$('#galleryNav a').live("click",function(){
		var href = $(this).attr("href");
		var loader = $("#full .loader");
		$('#galleryNav a').removeClass("selected");
		$(this).addClass("selected");
		loader.stop().fadeTo(0,1);
		var to = setTimeout(function(){ loader.stop().fadeTo(300,.8); },500);
		$.imgpreload(href,{
			all: function() {
				clearTimeout(to);			
				var newImg = new Image();
			    	newImg.src = href;
			    	var height = newImg.height;
			    	$(newImg).ready(function(){						
						$("#full").animate({height:newImg.height+"px"},600,"easeOutCirc",function(){
							$("#full img").attr("src",href);				
							loader.stop().fadeTo(300,0);
						})
			    	});				
			}
		});
		return false
	})
	if($("#galleryNav").size()>0) {		
		$('#galleryNav img').imgpreload({
			each: function() {				
				$(this).css({visibility:"visible"})		
			}
		});	
	}
	if($("#full").size()>0) {
		var to = setTimeout(function(){ loader.stop().fadeTo(300,.8); },500);		
		$('#full img').imgpreload({
			each: function() {
				clearTimeout(to);	
				$(this).css({visibility:"visible"})		
				var loader = $("#full .loader");			
				loader.stop().fadeTo(1000,0);
			}
		});	
	}
	
	// Reinstate timeline
	$("#timelineBtn:not(.disabled)").click(function(){
		$(this).addClass("disabled")
		var targ = $("#timelineLoaderTarget");
		if($("#timelineLoaderTarget").size()==0) {
			
			var eID = parseFloat($(this).attr("class").split("era")[1]);
			targ = $('<div id="timelineLoaderTarget"></div>"')
			$("#header").after(targ);
				targ.animate({height:"535px"},1000,"easeOutCirc",function(){

				})
				$.ajax({
					type: "GET",
					url: "/timeline",
					success: function(msg){
					 	targ.html(msg);
						timelineInit(function(){
							val = eras[eID].threshold
							$("#timelineSlider").slider( "value", val );
						});			
						
					}
				});
		}
		return false;
	})
	
	/* email */
	$(".rplcml").each(function(){	
		var unpack = $(this).text().replace(/( \[ATSIGN\] )/,'@');
		$(this).html('<a href="mailto:'+unpack+'" class="btn">Email the trust</a>');
	})
	$(".rplcmllit").each(function(){	
		var unpack = $(this).text().replace(/( \[ATSIGN\] )/,'@');
		$(this).html('<a href="mailto:'+unpack+'">'+unpack.replace('@','<span class="arial">@</span>')+'</a>');
	})
	$(".rplcmlsub").each(function(){	
		var unpack = $(this).text().replace(/( \[ATSIGN\] )/,'@');
		$(this).html('<a href="mailto:'+unpack+'" class="btn">Submit content</a>');
	})
	
	
	// New windows
	newWindowLinks();
	
	// Default text
	defaultText();
	
	// Filter hide
	$('html').click(function() {
		$("#eraFilter.on").removeClass("on");
		$("#filters:visible").hide();
	});


	

}


function loader() {
	var percentageLoaded = (assetsLoaded/(timelineImagesToPreload.length))*100;	
	try	{
		
		if(percentageLoaded>=100) {			
			clearTimeout(timelineLoaderTimeout);
			if($.browser.msie && $.browser.version<=8) {
				$("#timeLineContent").fadeIn(1000);
				$("#timelineLoader").fadeOut(1000);
			} else {
				$progressBar.animate({"width":"100%","background-color":"#6f6f6f"},500,"linear",function(){		
					$("#timeLineContent").fadeIn(1000);
					$("#timelineLoader").fadeOut(1000);		
					timelineImagesToPreload = null;	
				})
			}
				
		} else {
			$progressBar.stop().animate({"width":percentageLoaded+"%"},300)
		}
			
	
		
	} catch(err) {}
}


function timelineInit(callback) {
	
	var callback = callback || false;
	
	// Set up loader
	$loader = $("#timelineLoader");
	$loader.html('<div id="progress"><div id="bar"></div></div>');
	$progressBar = $("#bar");
	
	// Define assets to load	
	for(i=0;i<eras.length;i++) {
		timelineImagesToPreload.push(eras[i].bg);
	}
	$("#timelineList li:lt(10) img").each(function(){
		timelineImagesToPreload.push($(this).attr("src"));
	})
	
	
	
	// Preloading
	timelineLoaderTimeout = setTimeout(function(){ 	 $loader.show() },1);
	$.imgpreload(timelineImagesToPreload,{
		each: function() {		
			assetsLoaded++;	
			loader();			
		}
	});
	
	$tooltip		 = $('<div id="tooltip"></div>');
	$("body").append($tooltip);
	setInterval(function() {		
	   	$tooltip.stop().css({top:(cursorPositionY-15)+"px",left:(cursorPositionX-15)+"px"});	    
	}, 15);

	$timeLineListBG  = $("#timelineList");
	$timeLineListFG  = $("#timelineList ol");
	
	// Arrange the boxes then...
	var nextX			= 0;
	var nextY			= 0;
	var trackEra		= -1;
	var prevItemWidth	= 0;
	var currPageCol		= 1;
	var claimedCols		= 0;
	
	$("#timelineList li").each(function(i){
		
		$this = $(this);
		var classes = $this.attr("class");
		
		// Get era
		var era = parseFloat(classes.split(" ")[0].split("era")[1]);		
		
		// New Era beginning!
		if(era!=trackEra) {		
					
		
			eras[era].threshold = era==0 ? 0 : pageCount;			
			jsdebug("Era "+ era + " threshold = " + eras[era].threshold);			
			claimedCols = pageCount;
			
					
			trackEra = era;
			
			// Add this to it's own column
			if(nextY>0) {
				nextY = 0;
				nextX += prevItemWidth+20;
				pageCount++;
				if(era==0) {
					$("#eraBar"+era).css({width:(((pageCount-claimedCols+1)*scaleNotchWidth)-2)+"px"})
				} else {
					$("#eraBar"+era).css({width:((pageCount-claimedCols)*scaleNotchWidth)+"px"})
				}
			}
				
			
		}
		
		// Get box
		var boxSize = parseFloat(classes.split("size")[1].split(" ")[0]);
			
		// Get dimensions of this box	
		var thisHeight 	=  parseInt(boxDimensions[boxSize].height);
		var thisWidth 	=  parseInt(boxDimensions[boxSize].width);
		
		// if we can't fit this box under previous then advance to next column
		if(nextY+thisHeight>380) {
			nextY = 0;
			nextX += prevItemWidth+20;
			pageCount++;
			if(era==0) {
				$("#eraBar"+era).css({width:((((pageCount-claimedCols+1)*scaleNotchWidth)+1)-2)+"px"})
			} else {
				$("#eraBar"+era).css({width:((pageCount-claimedCols)*scaleNotchWidth)+"px"})
			}			
		} 
		
		// Let's try and anchor some of them to the bottom as this looks nicer	
		if(i%2==0 && i>0 && thisHeight<380 && nextY==0) {					
			nextY = 380-thisHeight;
			//jsdebug('Trying to set this one to bottom anchor of Y pos ');		
		}
		
		// Position box and show
		$(this).css({position:"absolute",top:nextY+"px",left:nextX+"px"});
		$(this).show();
		
		
		
		// Set next coords
		nextY += thisHeight+20;
		prevItemWidth = thisWidth;
	
		
	
	}).hover(function(){	
		var era = parseFloat($(this).attr("class").split(" ")[0].split("era")[1]);
		var tt = $('<div id="viewTip" style="background-color:'+eras[era].color+';">View</div>');	
		$tooltip.html(tt);
		$tooltip.show();		
	
	},function(){
		$tooltip.hide();
	})
		
		
	
	// Calculate number of "pages" and how much the slider will move in px for each notch
	sliderIncrement 	= 899/pageCount;
	
	// Show eras
	$("#timelineSliderEras").delay(200).fadeIn(1500);
	
	// set top bar colour
	$("#header").css({"border-color":eras[currentEra].color},1000);
		
	
	// attach era bar tooltips
	$("#timelineSliderEras div").mouseenter(function(){
		var eraIndex = $(this).attr("id").split("eraBar")[1];	
		$tooltip.html('<div id="eraTip" style="background-color:'+eras[eraIndex].color+';width:800px"><span><i>'+eras[eraIndex].start+'-'+eras[eraIndex].end+'</i> - '+eras[eraIndex].title+'</span></div>');
		var span = $tooltip.find('span');
		$tooltip.show();	
		var w = span.width();
		$tooltip.find('div').css({width:(w+10)+"px",left:-(w+10)/2+"px"}).show();		
	}).mouseleave(function(){
		$tooltip.hide();
	}).click(function(){
		var eID = $(this).attr("id").split("eraBar")[1];	
	
		$("#timelineSlider").slider( "value", eras[eID].threshold );

	})
	
	
	
 	$eraBGs = $(".era");
	$eraFGs = $(".fg");
	
	$("#timelineSlider").slider({
		value: 0,
		min: 0,
		max: pageCount-3,	
		create: function(event,ui) {			
			if(callback) {
				callback()			
			}
		},
		slide: function(event,ui) {
			var ui = ui;
			setTimeout(function(){				
				sliderMoved(ui)
			},10);
		},
		change: function(event,ui) {
			var ui = ui;
			setTimeout(function(){
				sliderMoved(ui)
			},10);
			//var params = ui.value;			
		}
	});
	
	
	
	$("#eraFilter").click(function(){
		if($(this).hasClass("on")) {
			$(this).removeClass("on");
			$("#filters").hide();
		} else {
			$(this).addClass("on");
			$("#filters").show();
		}
		return false
	})
	
	$("#filters a").click(function(){
		var eID = parseInt($(this).attr("href").split("#era")[1]);				
		$("#timelineSlider").slider( "value", eras[eID].threshold );
		$("#eraFilter").click()
		return false;
	})
	
	
	
	
}


function sliderMoved(ui) {
	
	var crossFadeSpeed = 500;
	var handleOffset = $("#timelineSlider .ui-slider-handle").position();
	$("#debugger").html(handleOffset.left)
	
	var value 			= ui.value;
	
	var startThreshold 	= eras[currentEra].threshold;
	var endThreshold 	= currentEra+1 > eras.length ? eras.length-1 : eras[currentEra+1].threshold;
	
	if(value>=endThreshold) { // move to next era		

		$("#eraBG"+currentEra).fadeOut(crossFadeSpeed)
		currentEra++;
		$("#header").css({"border-color":eras[currentEra].color});
		$("#eraTitle").html($("#eraBar"+currentEra).html())
	}
	if(value<startThreshold) { // move to previous era
		currentEra--;
		$("#eraBG"+currentEra).fadeIn(crossFadeSpeed);
		$("#header").css({"border-color":eras[currentEra].color})
		$("#eraTitle").html($("#eraBar"+currentEra).html())
	}
	
	
	
	theshold = 300;
	fbScalar = 2;	 	
	fgTravel =  ((value)/1000)*100;

	
	$("#timelineList ol").stop().animate({"left":"-" + ((value*307)) + "px"},1000,"easeOutExpo")

	if(sliderIncrement>scaleNotchWidth) {
		
	} else {
		
		$("#timelineSliderMask").css({backgroundPosition:  -((scaleNotchWidth-sliderIncrement)*value) + "px 0"});
		$("#timelineSliderEras").css({left:  -((scaleNotchWidth-sliderIncrement)*value) + "px"});
	}


}


function defaultText() {
	$(".defaultText").unbind("focus,blur").focus(function () {		
		if ($(this).val() == $(this)[0].defaultValue) {
        	$(this).val("");
        }
	 }).blur(function() {
        if ($(this).val() == "") {
        	$(this).val($(this)[0].defaultValue);
     	}
	 });
}



/**	
 * Target new windows
 */
function newWindowLinks(){
	$('a[rel=external],area[rel=external]').live("click",function(){
		window.open($(this).attr('href'));
		return false;
	});
}



function jsdebug(message) {
	try {
		if(window.console) {
			console.log(message);			
		}
	} catch(e) {}	
}


