/**
 * Worker function used by setupColumnarLists().
 * Reformats the given ul list into numColumns columns.
 */
function formatInColumns(ul, numColumns) {
	var div = new Element('div', { 'class': 'columns-' + numColumns });
	div.wraps(ul);
	
	// surround the ul in a div
	var divs = [ new Element('div', { 'class': 'column-1' }) ];
	divs[0].wraps(ul);
	ul.removeClass('columns-' + numColumns);
	
	// create extra uls
	var uls = [ ul ];
	for (var i = 1; i < numColumns; ++i) {
		divs[i] = new Element('div', { 'class': 'column-' + (i + 1) });
		divs[i].inject(div, 'bottom');
		uls[i] = new Element('ul', { 'class': ul.get('class') });
		uls[i].inject(divs[i], 'bottom');
	}

	// distribute <li> elements from the first ul into the new uls.
	var lis = ul.getChildren('li');
	var numChildren = lis.length;
	if (numChildren > 1) {
		var itemsPerColumn = Math.floor(numChildren / numColumns);
		var leftOver = numChildren - (itemsPerColumn * numColumns);
		if (leftOver > 0) itemsPerColumn++;
		
		var col = 0;
		var colItems = 0;
		for (var i = 0; i < numChildren; ++i) {
			if (col > 0) {
				lis[i].inject(uls[col], 'bottom');
			}
			colItems++;
			if (colItems == itemsPerColumn) {
				col++; colItems = 0;
				if (leftOver > 0) {
					leftOver--;
					if (leftOver == 0) {
						itemsPerColumn--;
					}
				}
			}
		}
	}
}

/**
 * Reformats all ul elements with class=columns-2, columns-3 or columns-4
 * into two, three or four columns. This is done by dynamically replacing
 * the single list with up to four lists.
 */
function setupColumnarLists() {
	for (var i = 2; i <= 4; ++i) {
		$$('ul.columns-' + i).each(function(item) {
			formatInColumns(item, i);
		});
	}
}

/**
 * Shows (when showing == true) or hides (when showing == false)
 * the secondary nav associated with the li element bound to 'this'.
 */
function showHideSecondaryNav(event, showing) {
	this.addClass('fading');
	
	var secondary = this.getElement('ul');
	var widths = [0, secondary.offsetWidth], 
		heights = [0, secondary.offsetHeight], 
		opacities = [0, 1];
		
	if (!showing) {
		// reverse the direction of the transition
		[widths, heights, opacities].each(function(arr) { var temp = arr[0]; arr[0] = arr[1]; arr[1] = temp; });
	}
	var myFx = secondary.get('morph', {duration: 200, transition: Fx.Transitions.Sine.easeIn}).addEvent('complete', (function(event) {
		this.removeClass('fading');
		// reset the width and height
		secondary.setStyle('width', null); secondary.setStyle('height', null); 
	}).bindWithEvent(this));
	myFx.start({width: widths, height: heights, opacity: opacities});
}

/**
 * Initialises the popup menu animation and calls positionSecondaryNav().
 */
function setupSecondaryNav() {
	$$('#leftNav .hasSecondaryNav').each(function(item) {
		item.addEvent('mouseenter', showHideSecondaryNav.bindWithEvent(item, true));
		item.addEvent('mouseleave', showHideSecondaryNav.bindWithEvent(item, false));
		item.getElement('ul').setStyle('opacity', 0); // initially invisible
	});
}

/**
 * Sets up the a- and A+ buttons that resize the site's text and stores the user's
 * preference in a cookie.
 */
function setupTextResizing() {
	if ($('navFontLarger')) {
		$('navFontLarger').addEvent('click', function(event) {
			new Event(event).stop();
			switch(getActiveStyleSheet()) {
			case 'A+':
				setActiveStyleSheet('A++');
				break;
			case 'A++':
				break;
			default:
				setActiveStyleSheet('A+');
			}
		});
		$('navFontSmaller').addEvent('click', function(event) {
			new Event(event).stop();
			switch(getActiveStyleSheet()) {
			case 'A+':
				setActiveStyleSheet('normal');
				break;
			case 'A++':
				setActiveStyleSheet('A+');
				break;
			}
		});
	}
}

/**
 * Sets up showing and hiding the 'Search' label text for the search box.
 */
function setupSearchBox() {
	var searchBox = $$('.searchBox')[0];
		searchBox.addEvent('focus', (function(event) { if (this.get('value') == this.defaultValue) this.set('value', ''); }).bindWithEvent(searchBox));
		searchBox.addEvent('blur', (function(event) { if (this.get('value') == '') this.set('value', this.defaultValue); }).bindWithEvent(searchBox));
		$$('.searchButton').addEvent('click', (function(event) {
		    var q = searchBox.get('value');
		    if (q == '' || q == $$('.searchBox')[0].defaultValue) {
		        new Event(event).stop();
		        searchBox.focus();
		    }
		}));
}

function DefaultButtonKeyPress(evt, thisElementName)
{
    if(evt.which || evt.keyCode)
    {
        if ((evt.which == 13) || (evt.keyCode == 13))
        {
            // alert('post back href: ' + document.getElementById(thisElementName).href);
            location = document.getElementById(thisElementName).href;
            return false;
        }
    }
    else
    {
        return true;
    }
}

window.addEvent('domready', function() {
	setupTextResizing();
	setupColumnarLists();
	setupSecondaryNav();
	setupSearchBox();
});