/**
 *    AJAX functions for the SILVA/search page
 */

document.observe("dom:loaded", function() {
	var search = new SilvaSearch();
});


var SilvaSearch = Class.create( {
    initialize: function() {
	var root = $('tx_pmtree_pi1_search');
	this.root = root;
	this.from = 0;

	root.observe('click',this.clickHandler.bind(this));
	root.observe('change',this.changeHandler.bind(this));
        $('tx_pmtree_pi1_search_form').onsubmit = function() { return false; }
	this.installAutocompleters(root);
	this.instrumentResult(root);
	this.updateSelectedDb();
	document.observe('slv:reloadCart', this.updateResult.bind(this, null));

    },

    instrumentResult: function(root) {
	// fixme: this takes AGES!
	registerToolTips();
	this.installDetailPopups(root);
	root.select("#tx_pmtree_pi1_submit_go").each(Element.hide);
    },

    installAutocompleters: function(root) {
	root.select(".tx_pmtree_pi1_search_optionstable tr")
	    .each(function(x,i) {
	    var sel = x.select("select")[0];
	    var inp = x.select("input")[0];
	    if (!inp) return;
	    var d = new Element('div', {'class':'autocomplete'});
	    inp.up().insert(d);
	    var url = '?id=3&type=1&tx_pmtree_pi1[type]=search'
		    +'&tx_pmtree_pi1[action]=autocomplete';
	    new Ajax.Autocompleter(inp, d, url, { callback: function(elem, entry) {
		return entry + "&tx_pmtree_pi1[field_id]="+sel.value+
			"&tx_pmtree_pi1[db]="+getDB();
	    }});
	});
    },

    installDetailPopups: function(root) {
	root.select('.fullDetailBtn').each((function(e) {
	    createDetailPopup(e, e.readAttribute('oname'),
			      e.up().up().readAttribute('sid'));
	    e.observe('click',function(f){f.stop()});
	}).bind(this));
    },

    updateSelectedDb: function() {
	this.db = $F($('tx_pmtree_pi1_search_form')['tx_pmtree_pi1[db]']);
    },

    showSpinner: function(elem) {
	var d = new Element('div');
	d.update('<div style="text-align:center; width:100%; '
		 + 'height:100%;background: transparent '
		 + 'url(typo3conf/ext/pm_tree/pi1/include/gfx/loading.gif)'
		 + ' no-repeat center center; " alt="loading">&nbsp;</div>');
	d.setStyle('filter:alpha(opacity=50);'
		   + '-moz-opacity:0.5;'
		   + '-khtml-opacity: 0.5;'
		   + 'opacity: 0.5;'
		   + 'background: grey;');
	d.style.position='absolute';
	d.hide();
	elem.insert(d);
	d.clonePosition(elem);
	d.show();
    },

    clickHandler: function(event) {
	var stop = true;
	var element;
	if (element = event.findElement('.addSequence')) {
	    this.toggleCart(element.down());
	} else if (element = event.findElement('.submitFocus')) {
	    this.from = 0;
	    this.updateResult(element);
	} else if (element = event.findElement('.searchLink a')) {
	    this.updateResult(element);
	} else {
	    stop = false;
	}
	if (stop) event.stop();
    },

    changeHandler: function(event) {
	var elem = event.findElement('select');
	if (elem == null) return;

	switch(elem.getAttribute('name')) {
	    case 'tx_pmtree_pi1[taxname]':
              this.updateResult(elem);
              event.stop();
              break;
	    default:
	}
    },

    cartOp: function(elem) {
	elem.setStyle('cursor:wait');
	this.showSpinner($('tx_pmtree_pi1_search_result'));

	var params = unwrapParams($('tx_pmtree_pi1_search_form').serialize(true));
	params.action = 'cartOp';

	callServer('search', params, this.ajaxCallback.bind(this,elem));
    },

    toggleCart: function(elem) {
	var act = elem.hasClassName('cartRemove')?'del':'add';
	var sid = elem.up().up().getAttribute('sid');
	callServer('cart', { id:sid, obj: 'leaf', action:act },
		   this.ajaxCallback.bind(this, elem));
    },

    updateResult: function(elem, event) {
	if (event) elem = event.element();

	this.updateSelectedDb();
	elem.setStyle('cursor:wait');

	var params = unwrapParams($('tx_pmtree_pi1_search_form').serialize(true));
	if (elem.getAttribute('href')) {
	    var query = unwrapParams(elem.getAttribute('href').parseQuery());
	    var h = $H(params).update(query);
	    params = h.toObject();
	}

	params.action = 'result';
	if (elem.getAttribute('value')=='Reset') {
	    params.submit=elem.getAttribute('value');
	} else {
	    params.submit="";
	}
	if (this.from != 0) params.from = this.from;

	this.showSpinner($('tx_pmtree_pi1_search_result'));
	callServer('search', params, this.ajaxCallback.bind(this,elem));

	params.action = 'stats';
	$$('.tx_pmtree_pi1_search_result_navi, '
	   + '#tx_pmtree_pi1_search_stats')
	   .each(this.showSpinner.bind(this));

	if (elem.getAttribute('value')!="Reset") {
	    callServer('search', params, this.ajaxCallback.bind(this,null));
	}
    },

    ajaxCallback: function(elem, json) {
	if (json.selected != null) {
	    if (json.selected > 0) {
		elem.removeClassName('cartAdd').addClassName('cartRemove');
	    } else {
		elem.removeClassName('cartRemove').addClassName('cartAdd');
	    }
	}
	if (json.cartSize != null) {
	    updateCartSize(json.cartSize);
	}
	if (json.searchResult != null) {
	    $('tx_pmtree_pi1_search_result').update(json.searchResult);
	    this.instrumentResult(this.root);
	    elem.setStyle('cursor:pointer');
	}
	if (json.searchStats != null) {
	    $('tx_pmtree_pi1_search_stats').update(json.searchStats);
	}

	if (json.searchForm != null) {
	    $('tx_pmtree_pi1_search_form_div').update(json.searchForm);
	}

	if (json.searchPageBrowser != null) {
	    $$('.tx_pmtree_pi1_search_result_navi').invoke('update',json.searchPageBrowser);
	}
    }
});


