var yearWidths = new Array();

function addYearWidth(t, w, i){
	if ( t!="" && w!="" && i!="" ){
		yearWidths.push({threshold:Number(t), width:Number(w), interval:Number(i)});
	}
}

$(document).ready(function(){

	if(eventsHeight==undefined){
		var eventsHeight=330;
	}


	$_(".third").css('margin','0px');
	$_(".thirdwrapper .vevent,.third").css('padding-right','40px');
	$_(".thirdwrapper .vevent,.third").css('width','210px');
	$_(".thirdwrapper .vevent:eq(2),.third:eq(2)").css('padding-right','0px');

	for ( var el = 0; el < epochs.length; el++ ){
		if ( epochs[el]['threshold']!="" && epochs[el]['width']!="" && epochs[el]['interval']!="" ){
			yearWidths.push({threshold:Number(epochs[el]['threshold']), width:Number(epochs[el]['width']), interval:Number(epochs[el]['interval'])});
		}
	}

	if( tl_config.gap==undefined || tl_config==undefined ){

		var gap=1;

	} else {

		var gap = tl_config.gap;
	}


	var yearWidth=50;
	var thresholdX=gap;
	yearWidths[0].thresholdX=gap;

	for(var i=1;i<yearWidths.length;i++){
		thresholdX+=gap+((yearWidths[i-1].width)*(yearWidths[i].threshold-yearWidths[i-1].threshold));
		yearWidths[i].thresholdX=thresholdX;
	}

	var lastTop=0;
	var thisTop=0;
	var eventTop = 0;
	var keywordTop=0;
	if ( styleRules['auto'].top == undefined ){
		var nextTop = 0;
	} else {
		var nextTop = styleRules['auto'].top;
	}

	if ( styleRules['auto'].bottom == undefined ){
		var myBottom = 400;
	} else {
		var myBottom = styleRules['auto'].bottom;
	}

	if ( styleRules['auto'].imageheight == undefined ){
		var imageHeight = 150;
	} else {
		var imageHeight = styleRules['auto'].imageheight;
	}

	var eventHeight = 0;


	for(var n in styleRules){
		styleRules[n].currentY=0;
	}

	//alert(styleRules['auto'].bottom);

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

		var eventDetail="";

		var myYear=$(this).attr("id");
		var title=$(this).attr("title");

		if (myYear.indexOf("-")!=-1) {
			myYear=myYear.split("-")[0];
		}
		else if (myYear.indexOf("'")!=-1) {
			myYear=myYear.split("'")[0];
		}
		else if (myYear.indexOf("Pre")!=-1){
			myYear=myYear.split("Pre")[1];
		}
		if (myYear.indexOf("Mid")!=-1){
			myYear=myYear.split("Mid")[1];
		}


		if ($(this).hasClass('intro')) {
			var introLeft=yearToPixel(myYear)-($(this).width()+15);
			$(this).css("left",introLeft+'px');
		}
		else {
			$(this).css("left",yearToPixel(myYear)+ 'px');
		}

		if ($(this).hasClass('background')){
			var oldImgSrc = $(this).find('img').attr('src');


			/*var startCha = oldImgSrc.indexOf('file=.') + 6;
			var endCha = oldImgSrc.indexOf('&');

			var newImgSrc = oldImgSrc.substring(startCha, endCha);*/

			var hregex = /height=\d*/;
			var wregex = /width=\d*/;
			var dregex = /fittodimensions=fit/;

			var newImgSrc = oldImgSrc;

			newImgSrc = newImgSrc.replace(hregex, 'height=' + myBottom);
			newImgSrc = newImgSrc.replace(wregex, 'width=0');
			newImgSrc = newImgSrc.replace(dregex, 'proportional=true');

			//alert ( oldImgSrc + '\n\n\n' + newImgSrc);


			$(this).find('img').attr('src', newImgSrc);

			$(this).css('cursor', 'normal');
		} else if ($(this).hasClass('intro')) {
			$(this).css("top",'0px');
		} else if ($(this).hasClass('keyword')){
			keywordTop+=40;
			if ((keywordTop<225) || (keywordTop>360)) {
				keywordTop=225;
			}

			$(this).css("top",keywordTop+ 'px');


		} else if ( $(this).css('visibility')!='hidden' && $(this).find("h2 strong").html()!='' )  {

			eventTop = nextTop;

			//alert( $(this).height() + '\n' + $(this).css('border-bottom-width').replace(/px/, '') );

			//eventHeight = parseInt($(this).height()) + parseInt($(this).css('border-top-width').replace(/px/, '')) + parseInt($(this).css('border-bottom-width').replace(/px/, ''));

			var myBTW = 0;
			if ( $(this).css('border-top-width') == 'thin' ){
				myBTW = '1';
			} else if ( $(this).css('border-top-width') == 'medium' ){
				myBTW = '2';
			} else if ( $(this).css('border-top-width') == 'thick' ){
				myBTW = '3';
			} else {
				myBTW = parseInt($(this).css('border-top-width').replace(/px/, ''));
			}

			var myBBW = 0;
			if ( $(this).css('border-bottom-width') == 'thin' ){
				myBBW = '1';
			} else if ( $(this).css('border-bottom-width') == 'medium' ){
				myBBW = '2';
			} else if ( $(this).css('border-bottom-width') == 'thick' ){
				myBBW = '3';
			} else {
				myBBW = parseInt($(this).css('border-bottom-width').replace(/px/, ''));
			}

			var myMT = 0;
			if ( $(this).css('margin-top').replace(/px/, '').match(/^\d*$/) ){
				myMT = parseInt($(this).css('margin-top').replace(/px/, ''));
			}

			var myMB = 0;
			if ( $(this).css('margin-bottom').replace(/px/, '').match(/^\d*$/) ){
				myMB = parseInt($(this).css('margin-bottom').replace(/px/, ''));
			}

			eventHeight = parseInt($(this).height()) + parseInt(myBTW) + parseInt(myBBW) + parseInt(myMT) + parseInt(myMB);

			if ( $(this).find('img').css('height')=='0px' ){
				eventHeight += parseInt(imageHeight);
			}

			if (eventTop + eventHeight > styleRules['auto'].bottom) {
				eventTop = styleRules['auto'].top;
			}

			nextTop = parseInt(eventTop) + parseInt(eventHeight);

			//alert( '$(this).height()\t' + $(this).height() + '\nmyBTW\t\t' + myBTW + '\nmyBBW\t\t' + myBBW + '\nmyMT\t\t' + myMT + '\nmyMB\t\t' + myMB + '\nimageHeight\t' + imageHeight + '\neventTop\t\t' + eventTop + '\nnextTop\t\t' + nextTop + '\neventHeight\t' + eventHeight );

			$(this).css("top", eventTop + 'px');
		}

		//tl_get_y($(this));

		//lastTop=thisTop;
		//alert( $(this).css('height') );

		eventDetail = '';

		//alert( $(this).find(".event_image").html() );

		if ( $(this).find(".caption").html() != null ){
			eventDetail += '<div class="timelineimagewrapper">';
		}

		if ( $(this).find(".event_image").html() != null ){
			eventDetail += $(this).find(".event_image").html();
		}

		if ( $(this).find(".caption").html() != null ){
			eventDetail += '<div class="caption">' + $(this).find(".caption").html() + '</div><div class="clearboth"></div></div>';
		}
		eventDetail += '<span class="eventdescription">'+$(this).find(".event_description").html()+'</span>';


		$(this).click(function(){
			var newClass="";

			if ($(this).hasClass("keyword")) {
				newClass="keyword_window";
			} else {
				newClass="event_window";
			}
			if( !$(this).hasClass("intro") && !$(this).hasClass("background") ){
				displayInfo(eventDetail,myYear,title,newClass);
			}
		});

	});

	$(".timeline ul").append("<li class='year_bar'></li>");

	$(".year_bar").css("width",yearToPixel(yearWidths[yearWidths.length-1].threshold - 1)+'px');

	for(var j=1;j<yearWidths.length;j++){
		tl_placeyearmarkers(yearWidths[j-1].interval, yearWidths[j-1].threshold, yearWidths[j].threshold);
	}

	function tl_placeyearmarkers(interval, startYear, endYear){

		if(interval==null || interval==undefined){
			interval=1;
		}

		for (var i=startYear;i<endYear;i++){
			if(i%interval==0){

				$(".year_bar").append("<div class='year_marker' id='yearmarker"+i+"'><span>"+(i)+"</span></div>");

				yearBarWidth=yearWidth+'px';
				$(".year_marker:last").css("width",yearBarWidth);

				yearBarLeft=yearToPixel(i)+'px';
				$(".year_marker:last").css("left",yearBarLeft);
			}
		}
	}

	function displayInfo(eventDetail,myYear,title,newClass) {
		if(eventDetail==""){
		  return;
		}
		var content='';
		//alert('eventDetail = ' + eventDetail + '\nmyYear = ' + myYear + '\ntitle = ' + title );

		$("#tl_window").remove(); //or remove()
		$(".timeline").parent().append("<div id='tl_window'></div>");

		$("#tl_window").addClass(newClass);
		left=yearToPixel(myYear)+50;

		//Try to center the pop up Window
		$("#tl_window").css('position', 'absolute');
		$("#tl_window").css("left",left);
		$("#tl_window").css("zIndex",5010);
		var popup_window=$("#tl_window:last");
		var offset=popup_window.offset();
		$("#tl_window").css("left",left-offset.left+460);
		$("#tl_window").css("top",'100px');
		content='<div class="timeline_event">' + '<h2>' + myYear + ' ' + title + '</h2><div class="eventdetail">' + eventDetail + '<div class="clearall"></div><div class="clearboth"></div></div></div>';
		$("#tl_window").append(content);

		$("#tl_window").click(function(){
			//$("#tl_window").css("display","none");
			$("#tl_window").remove();
		});

		//tb_init('#tl_window a.thickbox');
	}

	function yearToPixel(yearToCalculate) {
		var value;
		var myOffset=0;
		for(var i=0;i<yearWidths.length;i++){
			if( (typeof yearWidths[i+1])!='undefined' && yearToCalculate<yearWidths[i+1].threshold){
				var	myYearWidth=yearWidths[i].width;
				var myThreshold=yearWidths[i].threshold;
				var myOffset=yearWidths[i].thresholdX;
				break;
			}
		}
		value=((myOffset+((yearToCalculate-myThreshold)*myYearWidth)));
		return value
	}

	if ( yearWidths.length > 0){

		var tlButtonBar = '<div class="tl_toolbar">';

		tlButtonBar += '<a id="intro_0" class="event_intro" onclick="$(\'#tline\').scrollTo(\'-=800px\',1000,{axis:\'x\'});">&lt;</a> <span class="separator">|</span> ';

		for ( var yw = 1; yw < (yearWidths.length - 1); yw++ ){

			$(".year_bar").append("<div class='year_anchor' style='position:absolute;width:1px' id='yearanchor"+yearWidths[yw].threshold+"'></div>");

			yearBarLeft=(yearToPixel(yearWidths[yw].threshold)-gap)+'px';

			$(".year_anchor:last").css("left",yearBarLeft);

			var myScroll = Math.max(0, ( parseInt($_('#yearanchor'+yearWidths[yw].threshold).css('left')) - (parseInt($('#tline').width()) /2) ) );

			tlButtonBar += '<a id="intro_'+yw+'" class="event_intro" onclick="$(\'#tline\').scrollTo(\''+myScroll+'\',1000,{axis:\'x\'});">'+yearWidths[yw].threshold+'</a> <span class="separator">|</span> ';
		}

		tlButtonBar += '<a id="intro_max" class="event_intro" onclick="$(\'#tline\').scrollTo(\'+=800px\',1000,{axis:\'x\'});">&gt;</a>';

		tlButtonBar += '</div>';

		$('#tline').before(tlButtonBar);
		$('.event_intro').css('cursor', 'pointer');
	}
});

function initCentreLine(){

	$('#tline').parent().append('<div id="tlineCentreline"><div id="tlineCentrelineLabel"></div></div>');
	$('#tlineCentreline').css('width', '1px');
	$('#tlineCentreline').css('height', parseInt($('#tline').height())-20 + 'px' );
	$('#tlineCentreline').css('z-index', '5000');
	$('#tlineCentreline').css('position', 'absolute');

	$('#tlineCentreline').css('top', '173px');
	$('#tlineCentreline').css('left', (parseInt($('#tline').width())/2) + 4 +'px');

	updateCentrelineLabel();

	$('#tline').scroll(function(){
		updateCentrelineLabel();
	});
}

function updateCentrelineLabel(){

	var sPos = parseInt($('#tlineCentreline').css('left'));

	var thisYear = 0;
	var thisPos = -0 - parseInt(document.getElementById('tline').scrollLeft);

	for( var i = 0; i < epochs.length-1 && thisPos < sPos ; i++ ){

		for ( var y = epochs[i].threshold; y<epochs[i+1].threshold; y++ ){
			thisPos += parseInt(epochs[i].width);

			if ( thisPos <= sPos ){
				thisYear = parseInt(y) + 1;
			}
		}

	}

	$('#tlineCentrelineLabel').html(thisYear);
}


function scrollRight(sright) {
	while (sright) {
		$('#tline').scrollTo('+=100px',1000,{axis:'x'});
	}
}


function swapTitle(){
	var h2height = 87;

	var pageTitle=escape($_(".pagetitle span").text());
	var titleColour = rgbtohex($_("h2.pagetitle").css("color"));

	var titleBgColour = rgbtohex($_("h2.pagetitle").css("background-color"));
	var imageURL="url(/public_scripts/text_image_writer.php?string="+pageTitle.toUpperCase()+"&font=Tondo_Std_Bold.ttf&size=40&x=0&width=350&height="+h2height+"&trans=1&colour="+titleColour+"&bgcolour="+titleBgColour+"&leading=44)";

	$_("h2.pagetitle").css("background-image",imageURL);
	$_("h2.pagetitle").css("background-position", 'left center');
	$_("h2.pagetitle").css("height", h2height+'px');
	$_("h2.pagetitle span").css("text-indent","-3000px");
}

var hexArray = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F");

function rgbtohex( rgb ){

	if ( rgb.indexOf('#')==0 ){
		return rgb.substring(1, 7);
	}

	var ret = "";
	var str = "";

	if ( rgb.substring(0,5) == 'rgba('){
		str = rgb.substring(5, rgb.length-1);
	} else {
		str = rgb.substring(4, rgb.length-1);
	}

	var arr = str.split(', ');

	for ( var a = 0; a < 3; a++ ){
		arr[a] =  hexArray[Math.floor(arr[a]/16)] + hexArray[(arr[a]%16)];
	}

	ret = arr[0] + arr[1] + arr[2];

	return ret;
}
