var test_div = document.createElement('div');
test_div.setAttribute('className', 'ignore_test');
var classText = (test_div.className) ? 'className' : 'class';
test_div.style.cssText = 'display: none;';
var cssMethod = (test_div.style.cssText) ? "ie" : "non-ie";
var eventMethod = (test_div.attachEvent) ? "ie" : "non-ie";

function doNothing() {
	var totallyObscureName = "pointless";
}

function preloadImage() {
	var d = document;
	if(d.images) {
		if(!d.MM_p)
			d.MM_p = new Array();
		var i,j = d.MM_p.length, a = preloadImage.arguments;
		for(i=0; i<a.length; i++)
			if(a[i].indexOf("#") != 0) {
				d.MM_p[j] = new Image;
				d.MM_p[j++].src = a[i];
			}
	}
}

function GetXmlHttpObject() {
	var xmlHttp = null;
	try {
		xmlHttp=new XMLHttpRequest();
	}
	catch (e) {
		try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e) {
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	return xmlHttp;
}

document.getElementsByClassName = function(cl) {
	var retnode = [];
	var myclass = new RegExp('\\b'+cl+'\\b');
	var elem = this.getElementsByTagName('*');
	for (var i = 0; i < elem.length; i++) {
		var classes = elem[i].className;
		if (myclass.test(classes)) retnode.push(elem[i]);
	}
	return retnode;
};

function createAjax() {
	var ajax = false;
	if(window.XMLHttpRequest) {
		ajax = new XMLHttpRequest();
	} else if(window.ActiveXObject) {
		ajax = new ActiveXObject("Microsoft.XMLHTTP");
	}
	return ajax;
}

function isAjaxReady(ajax) {
	if (ajax.readyState == 4) {
		return true;
	} else {
		return false;
	}
}

function textBoxFocusEnd(textBox) {
	var charMove = 99999999999;
	if(textBox.setSelectionRange) {
		textBox.focus();
		textBox.setSelectionRange(charMove, charMove);
	} else if(textBox.createTextRange) {
		range = textBox.createTextRange();
		range.collapse(true);
		range.moveEnd('character', charMove);
		range.moveStart('character', charMove);
		range.select();
	}
}

function safariResizeFix(obj) {
	var test_div_resize = document.createElement('div');
	test_div_resize.style.resize = "none";
	if(test_div_resize.style.resize) {
		document.getElementById(obj).style.resize = "none";
	}
}

function currentYPosition() {
	if (self.pageYOffset)
		 return self.pageYOffset;
	if (document.documentElement && document.documentElement.scrollTop)
		return document.documentElement.scrollTop;
	if (document.body.scrollTop)
		 return document.body.scrollTop;
	return 0;
}

function elmYPosition(eID) {
	var elm  = document.getElementById(eID);
	var y    = elm.offsetTop;
	var node = elm;
	while (node.offsetParent && node.offsetParent != document.body) {
		node = node.offsetParent;
		y   += node.offsetTop;
	} return y;
}

function scrollToId(eID) {
	Effect.ScrollTo(eID, {duration: 0.5});
}

function URLEncode(textToEncode) {
	var SAFECHARS = "0123456789" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "-_.!~*'()";
	var HEX = "0123456789ABCDEF";

	var plaintext = textToEncode.replace(/\+/gi, "%2B");
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	}
	return encoded;
};

function URLDecode(textToDecode) {
	var HEXCHARS = "0123456789ABCDEFabcdef"; 
	var encoded = textToDecode;
	var plaintext = "";
	var i = 0;
	while (i < encoded.length) {
		var ch = encoded.charAt(i);
		if(ch == "+") {
			plaintext += " ";
			i++;
		} else if(ch == "%") {
			if (i < (encoded.length-2) 
			&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
			&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				i++;
			}
		} else {
			plaintext += ch;
			i++;
		}
	}
	return plaintext;
}

function disableEnterKey(e) {
	var key;
	key = (window.event) ? window.event.keyCode : e.which;
	if(key == 13) {
		return false;
	} else {
		return true;
	}
}

function ge(id) {
	if(typeof(id) == 'undefined') {
		Util.error('Tried to get an undefined element!');
		return null;
	}
	var obj;
	if(typeof(id) == 'string') {
		obj = document.getElementById(id);
		if(!obj) {
			return null;
		} else if(typeof(obj.id) == 'string' && obj.id == id) {
			return obj;
		} else {
			var candidates = document.getElementsByName(id);
			if(!candidates || !candidates.length) {
				return null;
			}
			var maybe = [];
			for(var ii = 0; ii < candidates.length; ii++) {
				var c = candidates[ii];
				if(!c.id&&id) {
					continue;
				}
				if(typeof(c.id) == 'string' && c.id != id) {
					continue;
				}
				maybe.push(candidates[ii]);
			}
			if(maybe.length != 1) {
				Util.error('ge() failed in a bizarre complicated edge case. Check comments.');
				return null;
			}
			return maybe[0];
		}
	} else {
		return id;
	}
	return null;
}

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 actionBox(id, action, text, style) {
	var aBox = document.getElementById(id);
	var aBoxLabel = document.getElementById(id + '_label');
	var def_txt = text + "      ";
	var curTxt = aBox.value;
	switch(action) {
		case "setup":
			aBoxLabel.style.display = "none";
			aBox.setAttribute(classText, style + '_u');
			aBox.value = def_txt;
		break
		case "focus":
			if(aBox.value == def_txt) {
				aBox.setAttribute(classText, style + '_f');
				aBox.value = "";
			}
		break
		case "blur":
			if(aBox.value == "") {
				aBox.setAttribute(classText, style + '_u');
				aBox.value = def_txt;
			}
		break
	}
}

// Library
TQG = function(){};

(function() {
	
    this.ns = function(fn){
        var ns = {};
        fn.apply(ns);
        return ns;
    };
}).apply(TQG);

TQG.ns(function() {with(TQG) {
	Carousel = Class.create({
		initialize: function(containerId, options) {
			this.setOptions(options);
			
			this.currentIndex = 0;
			this.liSize = 0;
			this.animDone = true;
			
			this.containerId = containerId;
	
			this.updateCount();
			
			//this.buttonLeft = $(this.options.leftId);
			//this.buttonRight = $(this.options.rightId);
		
			//this.buttonLeft.observe('click', this.moveLeft.bindAsEventListener(this));
			//this.buttonRight.observe('click', this.moveRight.bindAsEventListener(this));

			if(this.options.show_selected)
				this._show_selected();
			else			
				this.moveLeft(); // force the left button to start disabled

            this.automove(8500);
		},

        automove: function(timeout){
            var obj = this;

            clearTimeout(obj.current_timer);

            if(!timeout)
                var timeout = 6000;

            if(obj.currentIndex + 1 == obj.listCount){
                obj.current_timer = setTimeout(function() {obj.allLeft();}, timeout);
            }
            else {
                obj.current_timer = setTimeout(function() {obj.moveRight();}, timeout);
            }
        },
		
		updateCount: function() {
			this.ul = $$('#' + this.containerId + ' ul')[0];
			this.listCount = this.ul.getElementsByTagName("li").length;
			
			if(this.listCount < this.options.numVisible) {
				this.options.numVisible = this.listCount;
			}
		},
		
		moveRight: function() {
	
			if (this.animDone != true) 
				return false;
			
			if (this.currentIndex + this.options.numVisible + this.options.increment <= this.listCount)
				this._scroll(-this.options.increment);
			else 
				this._scroll(-(this.listCount - (this.currentIndex + this.options.numVisible)));
			
			if(this.listCount == this.currentIndex + this.options.numVisible)
				Element.addClassName(this.buttonRight, this.options.disabledClass);
			
			Element.removeClassName(this.buttonLeft, this.options.disabledClass);

            this.automove();

		},
		
		moveLeft: function() {
			if (this.animDone != true)
				return false;
			
			var inc = this.options.increment;
	
			if (this.currentIndex - inc < 0)
				inc = this.currentIndex;
			
			this._scroll(inc);
			
			if (this.currentIndex == 0)
				Element.addClassName(this.buttonLeft, this.options.disabledClass);
			
			Element.removeClassName(this.buttonRight, this.options.disabledClass);

            this.automove();
			
		},
		
		allRight: function() {
			if (this.animDone != true)
				return false;
		
			var inc = this.listCount - this.currentIndex - this.options.numVisible;
			this._scroll(-inc);
			
			Element.addClassName(this.buttonRight, this.options.disabledClass);
			Element.removeClassName(this.buttonLeft, this.options.disabledClass);

            this.automove();
		},
		
		allLeft: function() {
			if (this.animDone != true)
				return false;
		
			this._scroll(this.currentIndex, true);

            this.automove(200);
		},
		
		_show_selected: function() {

			var selected = this.ul.select('.' + this.options.selected_class)[0];
			
			var index = this.ul.childElements().indexOf(selected);
			
			var offset = this.options.show_offset;
			
			if(index > offset){

				if((this.listCount - index) < offset)
					offset = this.options.numVisible - (this.listCount - index);

				if(offset > 0)
					index = -index + offset;

				if (index + this.options.numVisible > this.listCount)
					index = this.listCount - this.options.numVisible;
				
				if (index < 0)
					index = 0;
				
				this._scroll(-1 * index);

			}
		},
		
		_scroll: function(delta, effect_duration) { 
			this.animDone = false;

            if(!effect_duration)
                var effect_duration = 0.5;
            else
                var effect_duration = 0.0
			
			if(this.liSize <= 0) 
				this.liSize = this._getLiElementSize();

            new Effect.MoveBy(this.ul, 0, delta * this.liSize, {duration: effect_duration, afterFinish: function() {this.animDone = true}.bind(this)});
    
            this.currentIndex -= delta;

            this._select_current_nav_item(this.currentIndex);
	
		},
		
		_getLiElementSize: function() {
			var li = $(this.ul.getElementsByTagName("li")[0]);
			return li.getDimensions().width + parseFloat(li.getStyle("margin-left")) + parseFloat(li.getStyle("margin-right"));
		},

        moveTo: function(list_position){
			if (this.animDone != true)
				return false;

            var delta = this.currentIndex - list_position;

            //this will happen if we're at the last element (which is fake)
            if(delta == this.listCount){
                list_position = 0;
                delta = this.currentIndex - this.listCount;
            }

            this._scroll(delta);

            this.automove();

        },

        _select_current_nav_item: function(current_list_position) {

            if(current_list_position + 1 == this.listCount)
                current_list_position = "0";

            $$('.carousel_nav li').each(function(nav_item) {
                nav_item.removeClassName('carousel_nav_s');
                nav_item.addClassName('carousel_nav_ns');
            });

            $('carousel_nav_pos_' + current_list_position).removeClassName('carousel_nav_ns');
            $('carousel_nav_pos_' + current_list_position).addClassName('carousel_nav_s');
        },
	
		setOptions: function (options) {
			this.options = {
				numVisible: 1,
				slider_element: 'ul',
				increment: 1,
				leftId: 'slide_left',
				rightId: 'slide_right',
				disabledClass: 'slide_disabled',
				show_selected: false,
				selected_class: 'selected',
				show_offset: 0,
                instanceName: 'slideGallery' 
			};
			Object.extend(this.options, options || {});
		}
	});
}});

function xbarLangChoice(type) {
	var langHolder = document.getElementById('xbar_lang_holder');
	var langBox = document.getElementById('xbar_lang_pop');
	var langStatus = document.getElementById('xbar_lang_status');
	var popSpeed = 0.2;
	switch(type) {
		case 'setup':
			langHolder.setAttribute(classText, 'xbar_lang_current_j');
			langBox.style.display = 'none';
		break
		case 'switch':
			if(langBox.style.display == 'none') {
				var stlogBox = document.getElementById('xbar_stlog_pop');
				if(stlogBox != null && stlogBox.style.display == '') {
					new Effect.BlindUp(stlogBox, {duration: popSpeed});
				}
				new Effect.BlindDown(langBox, {queue: {position: 'end', scope: 'lang_switch', limit: 1}, duration: popSpeed});
			} else {
				new Effect.BlindUp(langBox, {queue: {position: 'end', scope: 'lang_switch', limit: 1}, duration: popSpeed});
			}
		break
		case 'go_en':
			langStatus.innerHTML = '<span class="xbar_lang_loading">Loading...</span>';
			new Effect.BlindUp(langBox, {duration: popSpeed});
		break
		case 'go_cy':
			langStatus.innerHTML = '<span class="xbar_lang_loading">Yn llwytho...</span>';
			new Effect.BlindUp(langBox, {duration: popSpeed});
		break
	}
}

function xbarLang(type, key) {
	if(key == "key") {
		if(event.keyCode == 13) {
			xbarLangChoice(type);
		}
	} else {
		xbarLangChoice(type);
	}
}