/* Hide elements that are only used in non-javascript situations */
window.onload = function(){
	if(window.hideAll){
		hideAll();
	}
}

/* Show and hide the 'loading' indicator */
function hideLoading(){
	Ext.get('ajaxicon').hide();
}

function showLoading(){
	Ext.get('ajaxicon').show();
}

/* 
 * Load a new page into the pane.
 * 
 * Both parameters are passed through to buildUrl.
 */
function go(usePages,showId){
	var url = buildUrl(usePages, showId);
	var ajaxifiedUrl = url + '&' + AJAX_FIELD + '=true';
	showLoading();
	Ext.Ajax.request({
		url : ajaxifiedUrl,
		method: 'GET',
		success: function ( result, request ) { 
			//Replace the tabpane with the contents of the response
			hideLoading();
			Ext.get(paneid).dom.innerHTML = result.responseText;
			hideAll();
		},
		failure: function ( result, request) {
			//If the request fails, just redirect the page 
			hideLoading();
			window.location = url;
		} 
	});
}

/*
 * Construct a URL containing the relevant state information. Calls 
 * 'buildOptions' which can be implemented by a template to add extra.
 * 
 * boolean usePages If true, uses pages to define which items to show rather
 *  	than a start value.
 * int showId If present, the detail of article 'showId' should be shown
 *  	instead of a list.
 */
function buildUrl(usePages,showId){
	var options = [];
	var url = articleUrl;
	if(window.buildOptions){
		options = buildOptions();	
	}
	var first = true;
	if(showId){
		options.push({field : SHOW_FIELD, value : showId});
	}
	if(usePages){
		options.push({field : PAGE_FIELD, value : page});
	} else {
		options.push({field : START_FIELD, value : start});
	}
	options.push({field : STEP_FIELD, value : step});
	for (var i in options){
		if(!first){
			url = url + '&' + options[i].field + '=' + options[i].value;
		}else{
			var sep = articleUrl.indexOf("?") < 0 ? '?' : '&';
			url = url + sep + options[i].field + '=' + options[i].value;
			first = false;
		}
	}
	return url;
}

/* Navigation functions */
function next(){
	goPage(page + 1);
}

function previous(){
	goPage(page - 1);
}

function goPage(newPage){
	page = newPage;
	start = (page-1) * step;
	go(true);
}

function first(){
	goPage(1);
}

function last(){
	goPage(pages);
}