var TxReferences = new Class({
	highlightsDisabled: false,
	
	initialize: function() {
		this.accordion = new ToggleAccordion($('searchReferences'), 'h3.toggler', 'div.togglerElement', {
			opacity: false,
			alwaysHide: true,
			display: -1,
			onActive: function(toggler, element){
				toggler.setStyles({
					'color': '#2f2f31',
					'cursor': 'pointer',
					'text-decoration': 'underline'
				});
			},
			onBackground: function(toggler, element){
				toggler.setStyles({
					'color': '#2f2f31',
					'cursor': 'pointer',
					'text-decoration': 'underline'
				});
			}
		});

		$$('#searchReferences input[type="checkbox"]').each(function(element){
			element.addEvent('click', this.doSearch.bind(this));
		}.bind(this));

		$('tx-references-pi1-submit').setStyle('display', 'none');

		this.initBrowseBoxLinks();
	},

	doSearch: function() {
		if(this.highlightsDisabled == false) {
			this.highlightsDisabled = true;
			if($('teaser').checked == true) {
				$('teaser').checked = false;
				$('jsCheckbox_teaser').setStyle('background-position', '0pt -18px');
			}
		}
		
		this.initUpdateList();

		var action = $('searchReferences').action;
		var params = 'type=2&ext=tx_references_pi1';
		
		if(action.indexOf('?') != -1) {
			var url = action+'&'+params
		} else {
			var url = action+'?'+params;
		}
		
		this.request = new Request.JSON({
			'url' : url,
			onComplete: function(jsonObj) {
				this.finishUpdateList(jsonObj.listHtml)
			}.bind(this)
		}).post($('searchReferences'));
	},

	updateList: function(href) {
		this.initUpdateList();

		this.request = new Request.JSON({
			'url' : href,
			onComplete: function(jsonObj) {
				this.finishUpdateList(jsonObj.listHtml)
			}.bind(this)
		}).send();

		return false;
	},

	initUpdateList: function() {
		//if an active request is running cancel this first.
		if(this.request) {
			this.request.cancel();
		}
		
		
		var newHeight = ($('references-list').getSize().y)+'px';
		$('spinner').setStyle('height', newHeight);
		$('references-list').setStyle('display', 'none');
		$('spinner').setStyle('display', 'block');
		$('references-list').innerHTML = '';
	},

	finishUpdateList: function(htmlContent) {
		$('references-list').innerHTML = htmlContent;
		
		$('references-list').setStyle('display', 'block');
		$('spinner').setStyle('display', 'none');
				
		this.initBrowseBoxLinks();
		MOOdalBox.init();
	},

	initBrowseBoxLinks: function() {
		$$('#browseBox a').each(function(element){
			var startString = element.href.indexOf('?') == -1 ? '?' : '&';
			var href = element.href+startString+'type=2&ext=tx_references_pi1';
			element.onclick = function() {
				return this.updateList(href);
			}.bind(this, href);

		}.bind(this));
	}
});

window.addEvent("domready", function() {
	var txReferences = new TxReferences();
});
