// JavaScript Document

var Reader = {

	_id: 1,

	init: function() {

		Reader.Popup.init();
		Reader.HelperBubble.init();
		Reader.Settings.check();

		jQuery('#content').selectable({ filter: 'var.word', delay: 50 });

		Reader.Events.on('startWord', function(data) {
			$(data.element).addClassName('progress');
		});

		Reader.Events.on('finishWord', function(data) {
			$(data.element).removeClassName('progress');
		});

	},

	current: function(element) {
		if(element) {
			if(this._current) this._current.removeClassName('highlight');
			this._current = $(element);
			this._current.addClassName('highlight');
		}
		return this._current;
	},

	url: function() {
		var current = document.location.href.toString();
		var parts = Reader.URL.parse(current);
		var url = parts.Protocol + '://' + parts.Host
		if(parts.Port) url += ':' + parts.Port;
		return url;
	},

	isDebugging: function() {
		if(document.location.href.toString().match(/debugger=true/))
			return true;
		else
			return false;
	},

	id: function(el) {
		var element = jQuery(el);
		var id = element.attr('id');
		if(!id) element.attr('id', (id = ('x-gen-' + this._id++)))
		return id;
	}

}

Reader.Cookies = {

	create: function(name, value, days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else 
			var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
		return value;
	},

	read: function(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i = 0, ii = ca.length; i < ii; 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;
	},

	remove: function(name) {
		this.create(name,"",-1);
	}

}

Reader.Settings = {

	DEFAULTS: {
		SYLLABLE_TIMING: 0,
		SNDS_IN_SYBLE_TIMING: 0,
		MA_TIMING: 0
	},

	check: function() {
		if(!this.loaded())
			return this.defaults();
	},

	loaded: function() {
		return Reader.Cookies.read('S_SET_BEFORE') ? true : false;
	},

	defaults: function() {
		return this.set(this.DEFAULTS);
	},

	get: function(key) {
		this.check();
		var value = Reader.Cookies.read('S_' + key);
		var num = parseInt(value);
		return (num == NaN) ? value : num;
	},

	_set: function(key, value) {
		Reader.Cookies.create('S_SET_BEFORE', true);
		return Reader.Cookies.create('S_' + key, value);
	},

	set: function(key, value) {
		if(typeof(key) == 'object') {
			for(var k in key)
				this._set(k, key[k]);
		} else {
			this._set(key, value);
		}
		if(Reader.Words.Player.isReady())
			Reader.Words.Player.loadSettings();
	}

}

Reader.URL = {

	REGEX: /^((\w+):\/\/)?((\w+):?(\w+)?@)?([^\/\?:]+):?(\d+)?(\/?[^\?#]+)?\??([^#]+)?#?(\w*)/,

	FIELDS: { 'Username' : 4, 'Password' : 5, 'Port' : 7, 'Protocol' : 2, 
			   'Host' : 6, 'Pathname' : 8, 'URL' : 0, 'Querystring' : 9, 
			   'Fragment' : 10 },

	parse: function(url) {
		var parts = {}
		var r = this.REGEX.exec(url);
		for(var k in this.FIELDS)
			parts[k] = r[this.FIELDS[k]] || '';
		return parts;
	}

}

Reader.Debugger = {

	debug: function(message, type) {
		if(type == 'ERROR')
			alert(message)
		if(Reader.isDebugging())
			console.log(message);
	}

}

Reader.Video = {

	play: function(url) {
		Reader.Flash.get('video_player').playVideo(url);
	}

}

Reader.Flash = {

	get: function(movieName) {
		if (window.document[movieName])
			return window.document[movieName];
		if (navigator.appName.indexOf("Microsoft Internet")==-1)
			if (document.embeds && document.embeds[movieName])
				return document.embeds[movieName]; 
		else
			return document.getElementById(movieName);
	}

}

Reader.Events = {

	_events: {},
	_ids: 0,

	run: function() {
		var args = $A(arguments);
		var event = args.shift();
		if(this._events[event]) {
			var events = this._events[event];
			for(var i = 0, ii = events.length; i < ii; i++)
				events[i].func.apply(events[i].scope, args); 
		}
	},

	on: function(event, func, scope) {
		if(!this._events[event])
			this._events[event] = [];
		func._eventID = this._ids++;
		func._eventName = event;
		this._events[event].push({ func: func, scope: scope || func, id: func._eventID });
	},

	unregister: function(func) {
		var events = this._events[func._eventName];
		var idx = null;
		for(var i = 0, ii = events.length; i < ii; i++)
			if(events[i].id == func._eventID)
				idx = i;
		if(idx != null)
			this._events[func._eventName].remove(idx);
	}

}

Reader.Words = {

	CYCLE_COLORS: [ 'black', 'blue', 'all' ],
	CYCLE_COLORS_LETTERS: [ 'black', 'all' ],

	Player: {

		_accentPlayer: function() {
			return Reader.Flash.get('accent_player');
		},

		isReady: function() {
			return (this._accentPlayer() && this._accentPlayer().loadSettings) ? true : false;
		},

		loadSettings: function() {
			this._accentPlayer().loadSettings();
		},

		setAccent: function(accent) {
			this._accentPlayer().setAccent(accent);
		},

		playText: function(text) {
			this._accentPlayer().queue({
				style: 'text',
				sounds: text,
				finish: 'external:finishPlayText'
			});
		},

		playMemoryAid: function(mAid) {
			this._accentPlayer().queue({
				style: 'mAid',
				sounds: mAid,
				start: 'external:startPlayMemoryAid',
				finish: 'external:finishPlayMemoryAid'
			});
		},

		playWord: function(sounds, data) {
			this._accentPlayer().queue({
				style: 'word', 
				sounds: sounds, 
				start: 'external:startWord', 
				finish: 'external:finishWord',
				data: data
			});
		},

		playSound: function(sound) {
			this._accentPlayer().queue({ 
				style: 'sound', 
				sounds: sound, 
				start: 'external:startSound', 
				finish: 'external:endSound' 
			});
		},

		playSyllable: function(syllable) {
			this._accentPlayer().queue({ 
				style: 'syllable', 
				sounds: syllable, 
				start: 'external:startSyllable',
				finish: 'external:finishedSyllable' 
			});
		},

		playSyllables: function(sounds) {
			this._accentPlayer().queue({ 
				style: 'syllable', 
				sounds: sounds, 
				start: 'external:startSyllable',
				finish: 'external:finishedSyllable' 
			});
		},

		playSay: function(letters) {
			this._accentPlayer().queue({ style: 'sound', sounds: letters, start: 'external:startSound', finish: 'external:endSound' });
		}

	},

	parse: function(word) {
		word = $(word);
		var attributes = word.getAttribute('word').split(',');
		return {
			id: Reader.id(word),
			element: word,
			text: attributes.shift(),
			sounds: attributes
		}
	},

	run: function() {
		var args = $A(arguments);
// console.log('First argument is '+args[0]);
		var method = args.shift();
// console.log('The method is '+method);
		var word = this[method].apply(this, args);
// console.log('The word is '+word);
// console.log(word);
		return Reader.current(word);
	},

	playLetter: function(letter) {
		var word = letter.up('var.word');
		var sound = letter.getAttribute('params');
//			console.log('sound = '+sound);		
		Reader.Words.Player.playSound(sound);
		letter.addClassName('progress');
		setTimeout(function() {
			letter.removeClassName('progress');
		}, 1000);
		return word;
	},

	_getTriple: function(element) {
		var word = element.up('var.word');
		var sound = element.getAttribute('params');
		var letter = element.firstChild.nodeValue;
		var className = element.getAttribute('class').split(' ');
		var colour = className[1].split('l');
		var colourNo = colour[1];
		var triple = {letter: letter, sound: sound, colour: colourNo};
//		    console.log('triple = '+triple.letter+'  '+triple.sound+'  '+triple.colour);
		    
		return triple;
	},
	
	playMemoryAid: function(element) {
		var word = element.up('var.word');
		var triple = this._getTriple(element);
		
		//	Set memory aid files to be played
		var mAid = [];
		mAid[0] = triple.sound + '_' + triple.letter  + '_' + triple.colour + '-1';
		mAid[1] = triple.sound + '_' + triple.letter  + '_' + triple.colour + '-2';
		mAid[2] = triple.sound + '_' + triple.letter  + '_' + triple.colour + '-3';
/*		for (var i = 0, ii = mAid.length; i < ii; i++) {
			console.log('mAid '+i+' = '+mAid[i]);
		}
*/
		// play memory aid for the highlighted letter group
/*		
		if (mAid) {
			element.addClassName('progress');
			if (mAid[2]) {
				//console.log('mAid[2]'+mAid[2]);
				Reader.Events.on('finishPlayMemoryAid', function() {
					element.removeClassName('progress');
					Reader.Events.unregister(this);	
				});		
			} 
			Reader.Words.Player.playMemoryAid(mAid);
		} 
*/		
	},
	
	seeMemoryAid: function(element) {
		var word = element.up('var.word'); 
		var triple = this._getTriple(element);
		mAid = triple.sound + '_' + triple.letter  + '_' + triple.colour;
		//	console.log('The name of the picture file to get = '+mAid);	
		// see the memory aid for the highlighted letter group
	},
	
	toggleSyllables: function(word) {
		var className = 'syllables_on';
		if(word.hasClassName(className)) {
			word.removeClassName(className);
		} else {
			word.addClassName(className);
		}
		return word;
	},
	
	syllablesOnHidden: function(letter, word, action) {		
		var letters = word.childNodes;
		var className = 'syllables_on_hid';
		if(!word.hasClassName(className)) {
			word.addClassName(className);
		}
		for (var i = 0, ii = letters.length; i<ii; i++) {
			//console.log('word element is ', letters[i]);
			if (letters[i] == letter) {
				for (var j=i+1; j < ii; j++) {
					if (letters[j].hasClassName('syllable')) {
						// console.log('element is ', $(letters[j]));
						Reader.Words.run(action, $(letters[j]));
						break;
					}
				}
			}
		}

		word.removeClassName(className);
		return word;
	},
	
	sayWords: function(words) {
		words = words.push ? words : [ words ];
		for(var i = 0, ii = words.length; i < ii; i++) {
			var word = this.parse(words[i]);
			Reader.Words.Player.playWord(word.sounds.join('-'), {
				element: word.id
			});
		}
	},

	saySoundsOfWord: function(_word) {
		var word = this.parse(_word);
		var letters = word.element.childElements();
		var _sounds = [], _soundsAll = [],params = [], _letters = [], collectSounds = new String();
		for(var i = 0, ii = letters.length; i < ii; i++) {
			var letter = letters[i];
			if(letter.hasClassName('letter')) {
				var attributes = letter.getAttribute('params');	
				if(attributes != 'no_sound') {
					if (collectSounds !="") {
						collectSounds += ',' + attributes;
					} else {
						collectSounds = attributes; 
					}
				}
			} 		
		}
		
		_sounds.push(collectSounds);
		var soundsAll =_sounds[0].split(',');

		for(var i = 0, ii = letters.length; i < ii; i++) {
			if(letters[i].hasClassName('syllable'))  {	
				letters.splice(i,1);
				ii--; i--;
			}else {
				params[i] = letters[i].getAttribute('params');
				if(params[i] == 'no_sound') {
					letters.splice(i,1);
					ii--; i--;
				}
				_letters[i] = letters[i];
			}

			_soundsAll[i] = [ _letters[i] ];	
		}
		
		this._highlightLetters(word, _soundsAll, 'startSound', 'endSound');	
		Reader.Words.Player.playSay(soundsAll);

		return _word;
	},
	
	saySyllables: function(_word) {
		var word = this.parse(_word);
		var letters = word.element.childElements();
		var blocks = [], current = [];
		for(var i = 0, ii = letters.length; i < ii; i++) {
			var letter = letters[i];
			if(letter.hasClassName('syllable')) {
				blocks.push(current);
				current = [];
			} else
				current.push(letter);
		}

		this._highlightLetters(word.element, blocks, 'startSyllable', 'finishedSyllable');
		Reader.Words.Player.playSyllables(word.sounds);

		return _word;
	},

	playSyllableSounds: function(_syllable) {
		var word = _syllable.up('var.word');
		this._highlightLetters(word, this._findSyllableSounds(word, _syllable), 'startSound', 'endSound');
		Reader.Words.Player.playSay(_syllable.getAttribute('params').split(','));
		return word;
	},
	
	playSyllable: function(_syllable) {
		var word = _syllable.up('var.word');
		var sounds = this._findSyllableSounds(word, _syllable)

		sounds = [ sounds.flatten() ];
		this._highlightLetters(word, sounds, 'startSyllable', 'finishedSyllable');

		var letters = _syllable.getAttribute('params').replace(/,/g, '-');
		Reader.Words.Player.playSyllable(letters);

		return word;
	},

	cycleColors: function(_word) {
		var colors = Reader.Words.CYCLE_COLORS;
		var currentCycle = null;
		for(var i = 0, ii = colors.length; i < ii; i++) {
			if(_word.hasClassName(colors[i])) {
				currentCycle = colors[i];
				_word.removeClassName(colors[i]);
			}
		}

		var index = -1;
		if(currentCycle) {
			index = colors.indexOf(currentCycle);
		} else {
			var parentClass = $('content').className || 'full';
			index = colors.indexOf(parentClass)
		}

		var nextColor = Reader.Words.CYCLE_COLORS[index + 1] || Reader.Words.CYCLE_COLORS.first();
		_word.addClassName(nextColor);

		return _word;
	},

	cycleColorsLetter: function(_letter, _word) {
		var _content = $('content');
		var colors = Reader.Words.CYCLE_COLORS;
		var colorsLetters = Reader.Words.CYCLE_COLORS_LETTERS;
		var currentCycleLetter = null;
		for(var i = 0, ii = colors.length; i < ii; i++) {
			if(_word.hasClassName(colors[i])) {
				_word.removeClassName(colors[i]);
			}
		}
		for(var i = 0, ii = colorsLetters.length; i < ii; i++) {
			if(_letter.hasClassName(colorsLetters[i])) {
				currentCycleLetter = colorsLetters[i];
				_letter.removeClassName(colorsLetters[i]);
			}
		}
		
		var index = -1;	
		if(currentCycleLetter) {
			index = colorsLetters.indexOf(currentCycleLetter);
		}
				
		if(_content.hasClassName('black')) {
			index = 0;
			if(currentCycleLetter) {
				index = colorsLetters.indexOf(currentCycleLetter);
			}
			
			var nextColor = Reader.Words.CYCLE_COLORS_LETTERS[index + 1] || Reader.Words.CYCLE_COLORS_LETTERS.first();
			_letter.addClassName(nextColor);
			
		} else {
			var nextColor = Reader.Words.CYCLE_COLORS_LETTERS[index + 1] || Reader.Words.CYCLE_COLORS_LETTERS.first();
			_letter.addClassName(nextColor);	
		}
		
		return _letter;
	},
	
	_findSyllableSounds: function(_word, _syllable) {
		var letters = _word.childElements();
		var sounds = [], current = _syllable.previous();
		while(true) {
			if(!current || (current && current.hasClassName('syllable'))) {
				break;
			} else {
				var params = current.getAttribute('params');
				if(params != 'no_sound') {
					sounds.unshift([ current ]);
				} 
				current = current.previous();
			}
		}
		return sounds;
	 },

	 
	_removeHighlight: function(word) {
		$$('.progress', word).each(function(el) {
			el.removeClassName('progress');
		});
	},

 	_highlightLetters: function(word, blocks, startEventName, endEventName) {
		var moveOn = function(syllable) {
			Reader.Words._removeHighlight(word);

			// Highlight the new letters.
			var parts = blocks.shift();
			for(var i = 0, ii = parts.length; i < ii; i++) {
				$(parts[i]).addClassName('progress');
			}

			if(!blocks.length) {
				var self = this;
				Reader.Events.on(endEventName, function() {
					Reader.Words._removeHighlight(word);
					Reader.Events.unregister(this);
					Reader.Events.unregister(self);
				});
			}

		}
		Reader.Events.on(startEventName, moveOn);
	}

}

Reader.Popup = {

	_hidden: true,

	init: function() {
		this._popup = $('popup');
		this._proxy = this._popup.down('var');
	},

	open: function(word) {
		this._word = $(word);

		this._proxy.setAttribute('word', word.getAttribute('word'));
		if ($(word).hasAttribute('abbrev')) {this._proxy.setAttribute('abbrev', word.getAttribute('abbrev'));}
		this._proxy.update(word.innerHTML);
		this._proxy.className = 'word';

		// Clean slate.
		this._popup.removeClassName('respell');
		$("respell_container").hide();
		$('abbrev_container').hide();


		// Do we need to show the respell text?
		var respell = word.getAttribute('respell');
		var abbrev = word.getAttribute('abbrev');
		if(respell) {
			if(abbrev) {
				$('abbrev_container').show();
			} else {
				$('respell_container').show();
			}
			this._popup.addClassName('respell');
			$($$("#respell_container .respell").first()).update(respell);
			$($$("#abbrev_container .respell").first()).update(respell);
			$($$("#abbrev_container .word").first()).update(word.innerHTML);
		}

		this._popup.show();
		Position.Center(this._popup);

		setTimeout(function() {
			Reader.Popup._hidden = false;
		}, 500);
	},

	close: function() {
		this._popup.hide();
		this._hidden = true;
	},

	active: function() {
		return !this._hidden;
	},

	proxy: function() {
		return this._proxy;
	},

	word: function() {
		return this._word;
	},

	reposition: function() {
		if(!this._hidden) {
			Position.Center(this._popup);
		}
	},

	click: function(element) {
		if(this.active()) {
			if (element == Reader.HelperBubble.bubble()) {
				// Do nothing as the popup is switching.
			} else if(!element.descendantOf('popup')) {
				Reader.Popup.close();
				return true;
			} else {
				if(element.hasClassName('action')) {
					// Call the tooltip action that has the same class name as the link.
					var func = element.getAttribute('params');
					if(Reader.Words[func]) {
						Reader.Words.run(func, this._proxy);
						return true;
					}
				}
			}
		}
	}

}

Reader.HelperBubble = {

	init: function() {
		this._helper = $('helper');
		this._helper.observe('click', function() {
			Reader.Popup.open(Reader.HelperBubble.word());
		});
		this._hidden = true;
	},

	bubble: function() {
		return this._helper;
	},

	startTimeout: function(element) {
		if(this._timeout) {
			clearTimeout(this._timeout);	
		}
		this._timeout = setTimeout(function() {
			Reader.HelperBubble.show(element);
		}, 250);
	},

	clearTimeout: function() {
		this.hide();
		clearTimeout(this._timeout);
	},

	show: function(element) {
		if(this._hidden) {	
			this._hidden = false;
			this._word = $(element.up('var.word'));
			this.reposition();
			this._helper.show();	
		}
	},

	hide: function() {
		if(!this._hidden) {	
			this._hidden = true;
			this._word = null;
			this._helper.hide();
		}
	},

	cycle: function(element) {

		if (this.active()) {
			// See if are still hovering over the word or the tooltip,
			// if not, close the tooltip.
			if(element.id == 'helper') {
				clearTimeout(this._hideTimeout);
				this._hideTimeout = null;
				return true;
			} else if (element.descendantOf('helper')) {
				clearTimeout(this._hideTimeout);
				this._hideTimeout = null;
				return true;
			} else if (element.parentNode == this._word) {
				clearTimeout(this._hideTimeout);
				this._hideTimeout = null;
				return true;
			} else {
				this._hideTimeout = setTimeout(function() {
					Reader.HelperBubble.hide();
				}, 200);
			}
		}

		if (element.parentNode && element.parentNode.className && element.parentNode.className.match(/word/)) {
			this.startTimeout(element);
		} else {
			this.clearTimeout();
		}

	},

	active: function() {
		return !this._hidden;
	},

	word: function() {
		return this._word;
	},

	reposition: function() {
		if(!this._word) return null;
		this._helper.clonePosition(this._word, { setWidth: false, setHeight: false, offsetLeft: this._word.getWidth() });
	}

}

Reader.Help = {

	play: function(element) {

		if(this._playing) return;

		var attribute = element.getAttribute('params');
		var params = attribute.split(';');
//console.log('atribute = '+attribute);
//console.log('params = '+params);
		var options = {}
		for(var i = 0, ii = params.length; i < ii; i++) {
			var p = params[i];
//console.log('params '+[i]+' = '+params[i]);
//console.log('p '+' = '+p);
			var split = p.split(':');
//console.log('split = '+split);
			options[split[0]] = split[1];
//console.log('options ='+options[split[0]]);
		}

//console.log('options.text ='+options.text);

		if(options.text) {
			element.addClassName('playing');
			this._playing = true;
			Reader.Events.on('finishPlayText', function() {
				element.removeClassName('playing');
				Reader.Events.unregister(this);	
				Reader.Help._playing = false;
			});
			Reader.Words.Player.playText(options.text);
		}

	}

}

var Page = {
//	_id: 2,
	init: function() {
	},
}

Page.Appearance = {
	CYCLE_FONT_FAMILY: ['times','arial'],
	
	run: function() {
		var args = $A(arguments);
		var method = args.shift();
		var element = this[method].apply(this, args);
	},

	cycleFontFamily: function() {
		var fontFamily = Page.Appearance.CYCLE_FONT_FAMILY;
		var currentCycle = null;
		var _content = $('content');
		for(var i = 0, ii = fontFamily.length; i < ii; i++) {
			if(_content.hasClassName(fontFamily[i])) {
				currentCycle = fontFamily[i];
				_content.removeClassName(fontFamily[i]);
			}
		}

		var index = -1;
		if(currentCycle) {
			index = fontFamily.indexOf(currentCycle);
		} 
		var nextFontFamily = Page.Appearance.CYCLE_FONT_FAMILY[index + 1] || Page.Appearance.CYCLE_FONT_FAMILY.first();
		_content.addClassName(nextFontFamily);
	},
	
	changeFontSize: function(element,fSize,step) {
		var defaultFontSize =16; var min=5; var max=246;
		var step = parseInt(step,10);
		var el = document.getElementById(element);
		// Change font size by step size (e.g.10px or -10px)
		if(fSize==0 && step!=0) {
			if(el.style.fontSize) {
				var curFont = parseInt(el.style.fontSize,10);
			} else {
				var curFont = defaultFontSize;
			}
			if(curFont>min && curFont<max) {
				el.style.fontSize = (curFont+step) + 'px';
			} else {
				el.style.fontSize = (curFont-10) + 'px';
			}
		} else {
		var el = document.getElementById(element);
			el.style.fontSize = defaultFontSize +'px';			
		}	
	},

	changeFontFamily: function(family) {
		var content = $('content');
		var _family = ['times','arial'];
		for(var i = 0, ii = _family.length; i < ii; i++) {
			content.removeClassName(_family[i]);}
		content.addClassName(family);
	},

	setVoice: function(voice) {
		//$('loader').show();
		Reader.Words.Player.setAccent(voice);
	},

	loadAccentComplete: function() {
	  //$('loader').hide();	
	},	
	
	setColour: function(colour) {
		var content = $('content');
		var colors = ['black', 'blue', 'all'];
		for (var i = 0, ii = colors.length; i < ii; i++) {
			content.removeClassName(colors[i]);}
		content.addClassName(colour);

		$$('var.word.black, var.word.blue, var.word.all').each(function(element) {
			element.className = 'word';
		});

		$$('a.letter.black, a.letter.all').each(function(element) {
			var className = element.getAttribute('class').split(' ');
			var colour = className[1];
			element.className = 'letter '+ colour;
		});
	},

	setSyllable: function(syllable) {
	  var content = $('content');
	  // toggle the show_syllables class name on the content element.
	  if (syllable == 'syllables_on') {
		  content.addClassName('show_syllables');
	  } else if (syllable == 'syllables_off') { 
		  content.removeClassName('show_syllables');
	  }
 
	  // Reset any manually toggeld words.
	  $$('#content var.word.syllables_on').each(function(element) {
		element.removeClassName('syllables_on');
	  });
	  
	  $$('#content var.word.syllables_on_hid').each(function(element) {
		element.removeClassName('syllables_on_hid');
	  });
	}
	
}		

Event.observe(window, 'resize', function() {
	Reader.Popup.reposition();
});

Event.observe(window, 'scroll', function() {
	Reader.Popup.reposition();
});

Event.observe(window, 'load', function() {

	Reader.init();

	Event.KEY_RETURN = 13;  // User pressess 'Enter' key to hear a cgroup of words
	Event.KEY_ESC = 27;     // User pressess 'Esc' key to close the popup
	Event.KEY_PLUS = 107;   // User pressess '+' key to increase font size
	Event.KEY_MINUS = 109;  // User pressess '-' key to decrease font size
	
	Event.KEY_A = 65;  // User pressess 'a' key + clicks anywhere in the word and hears all the individual sounds in the word
	Event.KEY_C = 67;  // User pressess 'c' key + clicks the letter to cycle through the colours (black, blue, all)
	Event.KEY_D = 68;  // User pressess 'd' key to return to default appearance
	Event.KEY_F = 70;  // User pressess 'f' key to cycle through the four fonts (times, timesB, arial, arialB)
	Event.KEY_I = 73;  // User pressess 'i' key + clicks the word to bring up the info popup
	Event.KEY_K = 75;  // User pressess 'k' key + clicks the word to cycle through the colours (black, blue, all)
	Event.KEY_M = 77;  // User pressess 'm' key + clicks the letter to to hear the audio for the memory aid of that letter
	Event.KEY_P = 80;  // User pressess 'p' key + clicks the letter to hear and see the picture for the memory aid of that letter
	Event.KEY_R = 82;  // User pressess 'r' key to read a group of words
	Event.KEY_S = 83;  // User pressess 's' key + clicks on a letter in a syllable to hear the individual sounds in a syllable
	Event.KEY_W = 87;  // User pressess 'w' key to hear a word spoken
	Event.KEY_CO = 188; // User presses Comma to hear the whole word in syllables
	Event.KEY_SC = 59; // User presses Semi-colon to show syllables (NB FS + letter to hear a single syllable said)
	Event.KEY_FS = 190; // User presses Full stop and clicks on any letter within a syllable to hear that syllable
// 	Event.KEY_Q = 191;  // User pressess Forward slash key or shift question mark to bring up popup
//  NB Event.KEY_RETURN and Event.KEY_ESC are pre-defined Key Codes

	var GlobalEventTarget = Prototype.Browser.IE ? document.body : document;

	Event.observe(GlobalEventTarget, 'keydown', function(e) {
		window._currentKeyDown = e.keyCode;
		if(e.keyCode == Event.KEY_ESC) {
			Reader.Popup.close();
		}
		if((e.keyCode == Event.KEY_R) || (e.keyCode == Event.KEY_RETURN)) {
			Reader.Words.sayWords(jQuery("#content var.word.ui-selected"));
			e.stop();
		}
		if(e.keyCode == Event.KEY_PLUS) {
			Page.Appearance.changeFontSize("rs",0,10);
		}
		if(e.keyCode == Event.KEY_MINUS) {
			Page.Appearance.changeFontSize("rs",0,-10);
		}
		if(e.keyCode == Event.KEY_D) {
			Page.Appearance.changeFontSize("rs",16,0);
		}
		if(e.keyCode == Event.KEY_F) {
			Page.Appearance.run('cycleFontFamily');
		}
	});

	Event.observe(GlobalEventTarget, 'keyup', function(e) {
		window._currentKeyDown = null;
	});


	Event.observe(GlobalEventTarget, 'mouseover', function(e) {
		var element = $(e.target);
		Reader.HelperBubble.cycle(element);
	});

	Event.observe($('content'), 'click', function(e) {

		var element = $(e.target);
		var metaKey = e.shiftKey;
		// If the tooltip wanted something to do with the click,
		// halt the event and stop execution of the function.
		if(Reader.Popup.click(element)) {
			return Event.stop(e);
		}

		// If the user is holding the 'I' key and at the same time
		// they click a letter in a word, display the popup for that word. 
		if ((window._currentKeyDown == Event.KEY_I) && element.hasClassName('letter')) {
			Reader.Popup.open($(element).up('var.word'));
			return Event.stop(e);
		}

		// If the user is holding the ';' key (semi-colon key) and at the same time
		// they click a letter in a word, display the syllables for that word.
		if (window._currentKeyDown == Event.KEY_SC && element.hasClassName('letter')) {
			var word = element.up('var.word');
			Reader.Words.run('toggleSyllables', word);
			Reader.HelperBubble.reposition();
			return Event.stop(e);
		}

		// If the user is holding the 'Full Stop' key  and at the same time
		// they click a letter in a syllable say the syllable.

		if (window._currentKeyDown == Event.KEY_FS && element.hasClassName('letter')) {
			var letter = element;
			var word = element.up('var.word');
			var action = 'playSyllable';
			Reader.Words.run('syllablesOnHidden', letter, word, action);
			return Event.stop(e);
		} 
		
		// If the user is holding the 'S' key and at the same time
		// they click a letter in a syllable  say the individual sounds in the syllable.
		if (window._currentKeyDown == Event.KEY_S && element.hasClassName('letter')) {
			var letter = element;
			var word = element.up('var.word');
			var action = 'playSyllableSounds';
			Reader.Words.run('syllablesOnHidden', letter, word, action);
			return Event.stop(e);
		} 
		
		// If the user is holding the 'A' key and at the same time
		// they click a letter in a word  say the individual sounds in the whole word.
		if (window._currentKeyDown == Event.KEY_A && element.hasClassName('letter')) {
			var letter = element;
			var word = element.up('var.word');
			Reader.Words.run('saySoundsOfWord', word);
			return Event.stop(e);
		} 
		
		// If the user has syllable dots on and they click the syllable dot and are holding the 'Full Stop' key at the same time,
		// say the syllable otherwise say the individual sounds in the syllable.
		if (element.hasClassName('syllable')) {
			//letters = element.getAttribute('params').split(',');
			if (window._currentKeyDown == Event.KEY_FS) {
				Reader.Words.run('playSyllable', element);
			} else {
				Reader.Words.run('playSyllableSounds', element);
			}
			return Event.stop(e);
		}

		// If the user is holding the 'comma' key and at the same time
		// they click a letter in a word, say the whole word in syllables.
		if (window._currentKeyDown == Event.KEY_CO && element.hasClassName('letter')) {
			var word = element.up('var.word');
			Reader.Words.run('saySyllables', word);
			return Event.stop(e);
		}
		
		// If they have clicked on a letter, and they are holding
		// the 'W' key at the same time, say the whole word.
		if (window._currentKeyDown == Event.KEY_W && element.hasClassName('letter')) {
			var word = element.up('var.word');
			Reader.Words.run('sayWords', word);
			return Event.stop(e);
		}

		// If they have clicked on a letter, and they are holding
		// the 'K' key at the same time, cycle through colors for word.
		if (window._currentKeyDown == Event.KEY_K && element.hasClassName('letter')) {
			var word = element.up('var.word');
			Reader.Words.run('cycleColors', word);
			return Event.stop(e);
		}
		// If they have clicked on a letter, and they are holding
		// the 'C' key at the same time, cycle through colors for letter.
		if (window._currentKeyDown == Event.KEY_C && element.hasClassName('letter')) {
			var word = element.up('var.word');
			var letter = element;
			Reader.Words.run('cycleColorsLetter', letter, word);
			return Event.stop(e);
		}

		// If they have clicked on a letter, and they are holding
		// the 'M' key at the same time, say the memory aid for letter.
		if ((window._currentKeyDown == Event.KEY_M) && element.hasClassName('letter')) {
			//console.log($(element));
			Reader.Words.playMemoryAid($(element));
		    return Event.stop(e);		
		}
		
		// If they have clicked on a letter, and they are holding
		// the 'P' key at the same time, see the memory aid for letter.
		if ((window._currentKeyDown == Event.KEY_P) && element.hasClassName('letter')) {
			//console.log($(element));
			Reader.Words.seeMemoryAid($(element));
		    return Event.stop(e);
		}

		// If the user is clicking on a help node.
		if (element.hasClassName('play')) {
			Reader.Help.play(element);
			return Event.stop(e);
		}

		if (element.hasClassName('abbrev')) {
			Reader.Popup.open($(element).up('var.word'));
			return Event.stop(e);
		}

		// If the user is clicking on a letter play the sound of the letter.
		// If the letter is an abbreviation play the word.
		if (element.hasClassName('letter')) {
			if ($(element).up('var.word').hasAttribute('abbrev')) {
				var word = element.up('var.word');
				Reader.Words.run('sayWords', word);
//					console.log('test for abbreviation '); // Need comment on separate line for below to work correctly.
//					console.log($(element).up('var.word').hasAttribute('abbrev'));
				return Event.stop(e);
			} else {
				Reader.Words.run('playLetter', element);
				return Event.stop(e);
			}
		}
				
	});

});

 //
function readFileViaApplet() {
	//document.form1.textarea1.value='Reading in progress...';
	window.status=document.HbcToHtml_applet.loadStatus;
	document.HbcToHtml_applet.hbcToHtml(theLocation);
	setTimeout("showFileContent()",100);
}
function showFileContent() {
	if (document.HbcToHtml_applet.finished==0) {
		setTimeout("showFileContent()",100);
		return;
	}
	//document.form1.textarea1.value=document.hbc_applet.fileContent;
	//document.write("fileContent3 = ", document.hbc_applet.fileContent);
	//window.status=document.HbcToHtml_applet.loadStatus;
}

Position.GetWindowSize = function(w) {
	w = w ? w : window;
	var width = w.innerWidth || (w.document.documentElement.clientWidth || w.document.body.clientWidth);
	var height = w.innerHeight || (w.document.documentElement.clientHeight || w.document.body.clientHeight);
	return [width, height]
}

Position.Center = function(element, parent) {
	var w, h, pw, ph;
	var d = Element.getDimensions(element);
	w = d.width;
	h = d.height;

	Position.prepare();

	if (!parent) {
	var ws = Position.GetWindowSize();
		pw = ws[0];
		ph = ws[1];
	} else {
		pw = parent.offsetWidth;
		ph = parent.offsetHeight;
	}

	element.style.top = (ph/2) - (h/2) + "px";
	element.style.left = (pw/2) - (w/2) + "px";
}

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
   var rest = this.slice((to || from) + 1 || this.length);
   this.length = from < 0 ? this.length + from : from;
   return this.push.apply(this, rest);
};
