var active = false;

switchStyle = function (elem) {
	if (active) {
		$$('link[rel*=alternate stylesheet][title=' + active.readAttribute('title') + ']').last().disabled = true;
		active.removeClassName('active');
	}
	elem.addClassName('active');
	$$('link[rel*=alternate stylesheet][title="' + elem.readAttribute('title') + '"]').last().disabled = false;
	active = elem;
}

document.observe ("dom:loaded", function() {

	/* stylesheet switcher (small vs large bodytext) */
	var activeDefaultName = GetCookie("style") ? GetCookie("style") : 'normal';
	$$('link[rel*=alternate stylesheet][title!=empty]').each(function(elem){elem.disabled = true;});
	$$('link[rel*=alternate stylesheet][title="' + activeDefaultName + '"]').last().disabled = false;
	if ($('header')) {
		$('header').insert(
			new Element('ul', { 'class' : 'css-switcher' })
				.insert(new Element('li', { 'class': 'switch m', title: 'normal'}).update('A').observe('click', function(event){switchStyle(event.element());}))
				.insert(new Element('li', { 'class': 'switch l', title: 'large'}).update('A').observe('click', function(event){switchStyle(event.element());}))
				.insert(new Element('li', { 'class': 'switch xl', title: 'extra-large'}).update('A').observe('click', function(event){switchStyle(event.element());}))
			);
	}
	active = $$('li[title=' + activeDefaultName + ']').last();
	active.addClassName('active');
	Event.observe(window, 'unload', function() {
		SetCookie("style", active.title, 365);
	})

	/* add-to-favorites button behavior */
	if ($('add-to-favorites')) {
		$('add-to-favorites').hide();
		if (window.sidebar || window.external || window.opera) {
			$('add-to-favorites').show();
		}
		if (!window.opera) {
			$('add-to-favorites').observe('click', function(e) {
				e.stop();
				if (window.sidebar) {
					window.sidebar.addPanel(document.title,self.location,'');
				} else if (window.external) {
					window.external.AddFavorite(self.location,document.title);
				}
			});
		}
	}

	// open links to external domains in a new window
	var d = window.location.href.match(/http:\/\/([^\/]*)/)[1].split('.');
	var r = new RegExp(d.splice(d.length - 2).join('.'));

	$(document.body).on('click', 'a[href]', function (event, element) {
		var onclickEvent = element.readAttribute('onclick');

		if (!element.href.match(r) && element.href.match(/^http:\/\//) && !onclickEvent) {

			window.open(element.href);
			event.stop();
			_gaq.push(["_trackEvent", "Outgoing links", element.href]);
		}
	});
});
