/**
 * Suchvorschläge laden und anzeigen (benötigt ajaxsearch.php im Hauptverzeichnis!)
 * Autor: Marc Schieferdecker, Tel. 171
 * Braucht prototype.js und scriptaculous!
 */

/**
 * Ajax Request results
 */
var AS_s = '';
var AS_field = '';
var AS_layer = '';
var AS_form = '';
function ajaxsearch( str, fieldid, layerid, formid )
{
	AS_s = str;
	AS_field = fieldid;
	AS_layer = layerid;
	AS_form = formid;
	$(fieldid).setAttribute( 'autocomplete', 'off' );
	new Ajax.Request( '/ajaxsearch.php?s=' + AS_s + '&field=' + AS_field + '&layer=' + AS_layer + '&form=' + AS_form, {
		method: 'get',
		onSuccess: function( r ) {
			AS_displayDownTo( AS_layer, AS_field, 77, r.responseText );
		}
	});
}

/**
 * Display a layer next to an object
 */
effects = [];
function AS_displayDownTo( sourceid, targetid, effectid, chtml )
{
	$(sourceid).update( chtml );
	AS_optimalPosition( sourceid, targetid );
	if( effects[effectid] )
		effects[effectid].cancel();
	effects[effectid] = new Effect.Appear($(sourceid),{duration:0.4,to:0.9});
}

/**
 * Hide out a layer
 */
function AS_displayNone( sourceid, effectid )
{
	if( effects[effectid] )
		effects[effectid].cancel();
	effects[effectid] = new Effect.Fade($(sourceid),{duration:0.1});
}

/**
 * Calculates optimal position of helper layer to target id
 */
function AS_optimalPosition( sourceid, targetid )
{
	var targetHeight = $(targetid).getHeight();
	var targetX = $(targetid).viewportOffset()[0] + document.viewport.getScrollOffsets()[0];
	var targetY = $(targetid).viewportOffset()[1] + document.viewport.getScrollOffsets()[1] + targetHeight + 1;
	$(sourceid).style.left = targetX + 'px';
	$(sourceid).style.top = targetY + 'px';
}

/**
 * Create Result Layer in DOM
 */
document.observe('dom:loaded', function () {
	ajaxsearch_layer = new Element( 'div', {'class': 'ajaxsearch', id: 'ajaxsearch', style: 'text-align:left;position:absolute;background-color:#EEE;border:1px solid #333;padding:3px;width:200px;min-height:100px'});
	ajaxsearch_layer.observe('click', function() {
		AS_displayNone( 'ajaxsearch', 77 );
	} );
	ajaxsearch_layer.hide();
	document.body.appendChild( ajaxsearch_layer );
});

