// MicroAngelo.co.uk Javascript Document

// ================================================================================================================================
// ================================================================================================================================

// Suckerfish menu fix for IE's lack of Hover pseudo-selectors
function sfHover(Id) {
	// Make sure we have the tools for the job
	if (!document.getElementById)
		return;
	// Get all the list items inside the element passed in as Id and add two listeners
	var sfEls = document.getElementById(Id).getElementsByTagName("li");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
}

// ================================================================================================================================

// Create Pullquotes as extra content (e.g. automatically repeat the text)
function makePullQuotes() {
	// Make sure we have the tools for the job
	if (!document.getElementsByTagName)
		return;
	var spans = document.getElementsByTagName('span');
	for (i = 0;  i < spans.length;  i++) {	
		if(spans[i].className == "pullquote1" || spans[i].className == "pullquote2" || spans[i].className == "pullquote3") {
			var pullquote = document.createElement('blockquote');
			pullquote.innerHTML = spans[i].innerHTML;
			
			// Different versions (perhaps left and right floats?)
			if (spans[i].className == "pullquote3") {
				pullquote.className="v3";
			} else if (spans[i].className == "pullquote2") {
				pullquote.className="v2";
			} else {
				pullquote.className="v1";
			}
			spans[i].parentNode.parentNode.insertBefore(pullquote, spans[i].parentNode);
			i++; // as "inserting before" changes the ordering of the objects... tricky!
		}	
	}
}

// ================================================================================================================================

// Stylesheet switcher script by British coder Paul Sowden of http://www.idontsmoke.co.uk
function setActiveStyleSheet(title) {
	var i, a, main;
	for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
		if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
			a.disabled = true;
			if(a.getAttribute("title") == title) a.disabled = false;
		}
	}
}

function getActiveStyleSheet() {
	var i, a;
	for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
		if(a.getAttribute("rel").indexOf("style") != -1 
		&& a.getAttribute("title") 
		&& !a.disabled) return a.getAttribute("title");
	}
	return null;
}

function getPreferredStyleSheet() {
	var i, a;
	for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
		if(a.getAttribute("rel").indexOf("style") != -1 
		&& a.getAttribute("rel").indexOf("alt") == -1 
		&& a.getAttribute("title")
		) return a.getAttribute("title");
	}
	return null;
}

// ================================================================================================================================

// Cookie script by Dutch coder Peter-Paul Koch of http://www.quirksmode.org
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	} else expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for (var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

// ================================================================================================================================

// Font size changer script by British coder Chris Eaton of www.MicroAngelo.co.uk
function getFontSize() {
	var body = document.getElementsByTagName('body')[0];
	if (body.style.fontSize) {
		return body.style.fontSize;
	} else {
		return '100%';
	}
}

function setFontSize(value) {
	var body = document.getElementsByTagName('body')[0];
	// Define scale
	var currentScale;
	var $scale = Array(
		'80%',
		'90%',
		'100%',
		'120%',
		'140%'
	)
	min = 0; //remember array starts from zero
	mid = 2;
	max = 4; //remember = size -1 as array starts at zero
	// Check for current scale:
	if (body.style.fontSize) {
		for (var i=min;i < (max+1);i++) {
			if (body.style.fontSize == $scale[i]) currentScale = i;
		}
	} else {
		currentScale = mid;	
	}
	// Define current size on 0-4 scale, normal = 2;
	if (value=='smaller') {
		if (currentScale>min) {
			body.style.fontSize = $scale[--currentScale];		
		}
	} else if (value=='larger') {
		if (currentScale<max) {
			body.style.fontSize = $scale[++currentScale];
		}		
	} else {
		if ('%' == value.substr(value.length-1, 1)) {
			body.style.fontSize = value;
		} else {
			// default to "normal"
			body.style.fontSize = $scale[mid]; 
		}
	}
}

// ================================================================================================================================

// Font alignment script by British coder Chris Eaton of www.MicroAngelo.co.uk
function getTextAlign() {
	var body = document.getElementsByTagName('body')[0];
	if (body.style.textAlign) {
		return body.style.textAlign;
	} else {
		return 'justify';
	}
}

function setTextAlign(value) {
	var body = document.getElementsByTagName('body')[0];
	body.style.textAlign = value;
}

// ================================================================================================================================

// Cross-Browser Event Handler registration and removal by US coder Scott Andrew LePera of http://www.scottandrew.com
function addEvent(obj, evType, fn, useCapture){
  if (obj.addEventListener){
    obj.addEventListener(evType, fn, useCapture);
    return true;
  } else if (obj.attachEvent){
    var r = obj.attachEvent("on"+evType, fn);
    return r;
  } else {
    alert("Handler could not be attached");
  }
}

function removeEvent(obj, evType, fn, useCapture){
  if (obj.removeEventListener){
    obj.removeEventListener(evType, fn, useCapture);
    return true;
  } else if (obj.detachEvent){
    var r = obj.detachEvent("on"+evType, fn);
    return r;
  } else {
    alert("Handler could not be removed");
  }
}

// ================================================================================================================================

// Only show "Customise this page" tools to JavaScript enabled users

function customiseInit() {
	// Define elements
	var customise = document.getElementById('customise');
	var customiselist = customise.getElementsByTagName('UL')[0];
	var customiselanguage = document.getElementById('customiselanguage');
	
	// create new list items
	
	// customisetext
	var customisetext = document.createElement('LI');
	customisetext.setAttribute('id','customisetext');
		var span = document.createElement('SPAN');
		
		//leftjustify
			var button = document.createElement('A');
			button.setAttribute('href', "#");
			button.onclick = function () {setTextAlign('left'); return false;};
			button.setAttribute('accesskey',"l");
			button.setAttribute('title', "Left align text. Accesskey: l");
			
				var image = document.createElement('IMG');
				image.setAttribute('src',"/commonimages/leftjustify");
				image.setAttribute('alt',"Left align text. Access key: l");
				image.setAttribute('height',"31");
				image.setAttribute('width',"33");
		
			button.appendChild(image);

		span.appendChild(button);

		//justify
			var button = document.createElement('A');
			button.setAttribute('href', "#");			
			button.onclick = function () {setTextAlign('justify'); return false;};
			button.setAttribute('accesskey',"j");
			button.setAttribute('title', "Justify align text. Accesskey: j");
			
				var image = document.createElement('IMG');
				image.setAttribute('src',"/commonimages/justify");
				image.setAttribute('alt',"Justify align text. Access key: j");
				image.setAttribute('height',"31");
				image.setAttribute('width',"35");
		
			button.appendChild(image);

		span.appendChild(button);

		//centre
			var button = document.createElement('A');
			button.setAttribute('href', "#");			
			button.onclick = function () {setTextAlign('center'); return false;};
			button.setAttribute('accesskey',"c");
			button.setAttribute('title', "Centre align text. Accesskey: c");
			
				var image = document.createElement('IMG');
				image.setAttribute('src',"/commonimages/centrejustify");
				image.setAttribute('alt',"Centre align text. Accesskey: c");
				image.setAttribute('height',"31");
				image.setAttribute('width',"33");
		
			button.appendChild(image);

		span.appendChild(button);

		//Smaller text
			var button = document.createElement('A');
			button.setAttribute('href', "#");			
			button.onclick = function () {setFontSize('smaller'); return false;};
			button.setAttribute('accesskey',"v");
			button.setAttribute('title', "Reduce the text size. Accesskey: v");
			
				var image = document.createElement('IMG');
				image.setAttribute('src',"/commonimages/smalltext");
				image.setAttribute('alt',"Reduce the text size. Accesskey: s");
				image.setAttribute('height',"31");
				image.setAttribute('width',"34");
		
			button.appendChild(image);

		span.appendChild(button);

		//Normal text
			var button = document.createElement('A');
			button.setAttribute('href', "#");			
			button.onclick = function () {setFontSize('100%'); return false;};
			button.setAttribute('accesskey',"n");
			button.setAttribute('title', "Normal text size. Accesskey: n");
			
				var image = document.createElement('IMG');
				image.setAttribute('src',"/commonimages/normaltext");
				image.setAttribute('alt',"Normal text size. Accesskey: n");
				image.setAttribute('height',"31");
				image.setAttribute('width',"34");
		
			button.appendChild(image);

		span.appendChild(button);

		//Larger text
			var button = document.createElement('A');
			button.setAttribute('href', "#");			
			button.onclick = function () {setFontSize('larger'); return false;};
			button.setAttribute('accesskey',"b");
			button.setAttribute('title', "Enlarge the text size. Accesskey: b");
			
				var image = document.createElement('IMG');
				image.setAttribute('src',"/commonimages/largetext");
				image.setAttribute('alt',"Enlarge the text size. Accesskey: b");
				image.setAttribute('height',"31");
				image.setAttribute('width',"34");
		
			button.appendChild(image);

		span.appendChild(button);


	customisetext.appendChild(span);
	
	// customisedesign
	var customisedesign = document.createElement('LI');
	customisedesign.setAttribute('id','customisedesign');

		// Heading button
		var button = document.createElement('A');
		button.setAttribute('title', "Choose from a selecting of Design Styles");
		button.setAttribute('href', "#");
			// <A> span
			var span = document.createElement('SPAN');
				// firstword span
				var firstword = document.createElement('SPAN');
				firstword.className = "firstword";
					var firstword_tn = document.createTextNode('Choose');
					firstword.appendChild(firstword_tn);
				var span_tn = document.createTextNode(' Design Style');
				span.appendChild(firstword);
				span.appendChild(span_tn);
		button.appendChild(span);

	customisedesign.appendChild(button);

		// List + items
		var list = document.createElement('UL');
			
			// Primary Choice
			var listitem = document.createElement('LI');
				var button = document.createElement('A');
				button.setAttribute('href', "#");
				button.onclick = function () {setActiveStyleSheet('Primary Choice'); return false;};
					// <A> span
					var span = document.createElement('SPAN');
						// firstword span
						var firstword = document.createElement('SPAN');
						firstword.className = "firstword";
							var firstword_tn = document.createTextNode('Primary');
							firstword.appendChild(firstword_tn);
						var span_tn = document.createTextNode(' Choice');
						span.appendChild(firstword);
						span.appendChild(span_tn);
				button.appendChild(span);
			listitem.appendChild(button);
		list.appendChild(listitem);
		
	/*
			// Corporate Blues
			var listitem = document.createElement('LI');
				var button = document.createElement('A');
				button.setAttribute('href', "#");
				button.onclick = function () {setActiveStyleSheet('Corporate Blues'); return false;};
					// <A> span
					var span = document.createElement('SPAN');
						// firstword span
						var firstword = document.createElement('SPAN');
						firstword.className = "firstword";
						var firstword_tn = document.createTextNode('Corporate');
							firstword.appendChild(firstword_tn);
						var span_tn = document.createTextNode(' Blues');
						span.appendChild(firstword);
						span.appendChild(span_tn);
				button.appendChild(span);
			listitem.appendChild(button);
		list.appendChild(listitem);
	*/
		
		
			// High Contrast
			var listitem = document.createElement('LI');
				var button = document.createElement('A');
				button.setAttribute('href', "#");
				button.onclick = function () {setActiveStyleSheet('High Contrast'); return false;};
					// <A> span
					var span = document.createElement('SPAN');
						// firstword span
						var firstword = document.createElement('SPAN');
						firstword.className = "firstword";
							var firstword_tn = document.createTextNode('High');
							firstword.appendChild(firstword_tn);
						var span_tn = document.createTextNode(' Contrast');
						span.appendChild(firstword);
						span.appendChild(span_tn);
				button.appendChild(span);
			listitem.appendChild(button);
		list.appendChild(listitem);
		
	customisedesign.appendChild(list);

	// Finally, add the new nodes to the Customise List
	customiselist.insertBefore(customisetext, customiselanguage);	
	customiselist.insertBefore(customisedesign, customiselanguage);
	// and change the class of the original item off of "nojs"
	customiselanguage.className = "";
	
	// and the same for the header
	document.getElementById('header').className = "";
	
}

// ================================================================================================================================

// DOM-Based Accessible scroller script by British coder Chris Eaton of www.MicroAngelo.co.uk
function startAnimation(elm) {
	// Set the speed of the animation: it moves 1px every "delay" ms (41ms ~ 24fps)
	var delay = 41;
	INTERVAL = setInterval(function() { tickerUpdate(elm); }, delay);
}

function restore() {
	// Define the height of the list when "shrunk":
	document.getElementById('newsarea').getElementsByTagName('UL')[0].style.height = '9em';
}

function stopButton() {
	var button = document.getElementById('startstopbutton');
	// Remove this event listener
	removeEvent(button, 'click', stopButton, false);
	// Stop the animation (check both methods in case it is already "stopped")
	clearInterval(INTERVAL);
	clearTimeout(TIMEOUT);
	// Stop the mouseover events
	removeTickerListeners();
	// Change the Stop Button into the Start Button
	button.setAttribute('value','Scroll');
	addEvent(button, 'click', startButton, false);
}

function startButton() {
	var button = document.getElementById('startstopbutton');
	// Remove this event listener
	removeEvent(button, 'click', startButton, false);
	// Change the Start Button into the Stop Button
	button.setAttribute('value','Stop');
	addEvent(button, 'click', stopButton, false);
	// Restart the mouseover events
	addTickerListeners();
	// Restart the animation
	startAnimation(document.getElementById('newsarea'));
}

function showButton() {
	var units = 'px';
	var button = document.getElementById('showhidebutton');
	// Remove this event listener
	removeEvent(button, 'click', showButton, false);
	// Stop Mouseover effects (doesn't effect CSS effects from :Hover)
	removeTickerListeners();
	// Hide the Stop/Start button, but fire it as a Stop
	stopButton();	
	document.getElementById('startstopbutton').style.display = "none";
	// Reset the top and bottom
	var list = document.getElementById('newsarea').getElementsByTagName('UL')[0];
	list.style.marginTop = '-2'+units;
	list.style.paddingBottom = '2'+units;	
	// Make the UL as big as it needs to be
	document.getElementById('newsarea').getElementsByTagName('UL')[0].style.height = 'auto';
	// Reset button to perform Hide
	button.setAttribute('value','Restore');
	addEvent(button, 'click', hideButton, false);
}

function hideButton() {
	var button = document.getElementById('showhidebutton');
	// Remove this event listener
	removeEvent(button, 'click', hideButton, false);
	// Reset the height of the UL
	restore();
	// Reset button to perform Show
	button.setAttribute('value','Show All');
	addEvent(button, 'click', showButton, false);	
	// Restart Mouseover effects
	addTickerListeners();
	// Show the stop/start button again, and fire the start button to get the animation going and to set the button to correct state
	document.getElementById('startstopbutton').style.display = "block";
	startButton();
}

function addTickerListeners() {
	var stories = document.getElementById('newsarea').getElementsByTagName("li");
	for (var i=0; i < stories.length; i++) {
		stories[i].getElementsByTagName("a")[0].onmouseover=function() {
			// Stop the animation (check both methods in case it is already "stopped")
			clearInterval(INTERVAL);
			clearTimeout(TIMEOUT);
		}
		stories[i].getElementsByTagName("a")[0].onmouseout=function() {
			// Restart the animation
			startAnimation(document.getElementById('newsarea'));
		}	
	}
}

function removeTickerListeners() {
	var stories = document.getElementById('newsarea').getElementsByTagName("li");
	for (var i=0; i < stories.length; i++) {
		stories[i].getElementsByTagName("a")[0].onmouseover=function() {
		}
		stories[i].getElementsByTagName("a")[0].onmouseout=function() {
		}	
	}
}

function tickerUpdate(elm) {
	// Don't do any animation if the style sheet is off,
	//  as it will just cause the list to jump around
	//if (getActiveStyleSheet()==null) return;

	var dy = -1;
	var units = 'px';
	var list = elm.getElementsByTagName('UL')[0];
	
	// Update whole list with the dy and/or dx
	
	// Make sure the attribute's set
	if (!list.style.marginTop) {
		var top = '0'+units;
	} else {
		var top = list.style.marginTop;
	}

	// remove units
	top = top.substr(0, top.length - units.length);
	// add delta value
	top = (top * 1) + dy; // times by one to ensure it's treated as a number
	// Do the update
	bottom = (top * -1);
	list.style.marginTop = top + units;
	list.style.paddingBottom = bottom + units;
	
	// check to see if the first element is off the edge:
	var stories = list.getElementsByTagName('LI');
	if ((stories[0].offsetHeight+7) < (top * -1)) {
		// stop animation
		clearInterval(INTERVAL);

		// Make DOM equivelant of an "off-screen buffer":
		var newlist = list.cloneNode(true);
		
		// Using the buffer:

			// Reset the top and bottom
			newlist.style.marginTop = '-2'+units;
			newlist.style.paddingBottom = '2'+units;		

			// move top news item to bottom
			var newstories = newlist.getElementsByTagName('LI');
			newlist.appendChild(newstories[0]);

		// Swap buffers:
		var parent = list.parentNode;
		parent.removeChild(list);
		var controls = document.getElementById('controls');
		parent.insertBefore(newlist, controls);
		addTickerListeners();
		
		//restart animation, after a wee pause
		TIMEOUT = setTimeout(function() { startAnimation(elm); }, 2500);
	}
}

function newsTickerInit() {
	// Don't do any anything if the style sheet is off
	//if (getActiveStyleSheet()==null) return;
	
	// Define elements
	var newsarea = document.getElementById('newsarea');
	var list = newsarea.getElementsByTagName('UL')[0];
	var listitems = list.firstChild;
	
	restore(); // Sets the height of the UL
	list.style.marginTop = '-2px';
	list.style.paddingBottom = '2px';		
	
	// Insert the controls
	var newpara = document.createElement('p');
	newpara.style.padding = '0';
	newpara.style.margin = '0';
	newpara.style.marginTop = '3px';	
	newpara.style.border = 'none';	
	newpara.style.borderBottom = '#FFF 1px solid'; // otherwise IE adds Random Padding (TM) to the bottom of the para	
	newpara.id = "controls";
		//show/hide button
		showhidebutton = document.createElement('input');
		showhidebutton.setAttribute('id','showhidebutton');
		showhidebutton.setAttribute('type','button');
		showhidebutton.setAttribute('value','Show All');
		addEvent(showhidebutton, 'click', showButton, false);
	newpara.appendChild(showhidebutton);	
		// start/stop buttom
		startstopbutton = document.createElement('input');
		startstopbutton.setAttribute('id','startstopbutton');
		startstopbutton.setAttribute('type','button');
		startstopbutton.setAttribute('value','Stop');	
		addEvent(startstopbutton, 'click', stopButton, false);
	newpara.appendChild(startstopbutton);
	newsarea.appendChild(newpara);
	
	// Assign Event Listeners to pause the scrolling
	addTickerListeners();
	
	// Set it rolling, after a wee pause
	TIMEOUT = setTimeout(function() { startAnimation(document.getElementById('newsarea')); }, 3500);
}

function newsTickerUnInit() {
	// Remove event listeners to save IE memory
	var button = document.getElementById('startstopbutton');
	removeEvent(button, 'click', stopButton, false);
	removeEvent(button, 'click', startButton, false);
	var button = document.getElementById('showhidebutton');
	removeEvent(button, 'click', showButton, false);
	removeEvent(button, 'click', hideButton, false);
}

// ================================================================================================================================

// Initialisation
function init() {
	// If we get here then JavaScript works, so we can inject the script buttons
	customiseInit();
	
	// Cookie stored preferences
	var cookie;
	
	//Body Font Size
	cookie = readCookie("fontSize");
	var fontSize = cookie ? cookie : '100%';
	setFontSize(fontSize);	

	//Body Text Align
	cookie = readCookie("textAlign");
	var textAlign = cookie ? cookie : 'justify';
	setTextAlign(textAlign);

	//Stylesheet switcher
	cookie = readCookie("style");
	var title = cookie ? cookie : getPreferredStyleSheet();
	setActiveStyleSheet(title);

	//Pullquotes
	makePullQuotes();	
	//Suckerfish menus
	if (window.attachEvent) {
		sfHover("customise");
		sfHover("nav");
	}
	
	// News Scroller for Index Page
	if (document.getElementById('newsarea')) {
		newsTickerInit();
	}
}

// Un-initialise (e.g. on unload)
function uninit() {
	// Save vars to cookie
	var title = getActiveStyleSheet();
	createCookie("style", title, 365);
	var fontSize = 	getFontSize();
	createCookie("fontSize", fontSize, 365);
	var textAlign = getTextAlign();
	createCookie("textAlign", textAlign, 365);
	// Unload newsTicker button hooks
	newsTickerUnInit()
}

// Kick it all off:

// Global variables for the ticker... will be encapsulated in the next version
var INTERVAL, TIMEOUT;

// Functions
window.onload = init;
//window.onunload = uninit;

// Try to read the style cookie and set the style (if no cookie then set default):
var cookie = readCookie("style");
var title = cookie ? cookie : getPreferredStyleSheet();
if (typeof(ce_overlay_loaded)=="undefined") {setActiveStyleSheet(title)};
