function addLoadEvent(func)
{
	var oldonload = window.onload;
	if (typeof window.onload != 'function')
	{
		window.onload = func;
	}
	else
	{
		window.onload = function()
		{
			oldonload();
			func();
		}
	}
}
    
var mc = new Array();
var mc_result = new Array();
var mc_status = new Array();
var tout = new Array();
var closetout = new Array();

var debug = false;


function search(expression, url, idx)
{
	var httpRequest;

	if (window.XMLHttpRequest)
	{ // Mozilla, Safari, ...
		httpRequest = new XMLHttpRequest();
		if (httpRequest.overrideMimeType)
		{
			httpRequest.overrideMimeType('text/json');
			// See note below about this line
		}
	} 
	else if (window.ActiveXObject)
	{ // IE
		try
		{
			httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e)
		{
			try
			{
				httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} 
			catch (e) {}
		}
	}

	if (!httpRequest)
	{
		var outmsg = "";
		if(debug == 1)
		    outmsg = "<img src=\"images/loading_stop.gif\" style=\"padding-right: 5px;\"/>  Giving up :( Cannot create an XMLHTTP instance";
		else
		    outmsg = "<img src=\"images/loading_stop.gif\" style=\"padding-right: 5px;\"/>";

		mc_status[idx].update(outmsg);
		return false;
	}


	var outmsg = "";
	if(debug == 1)
	    outmsg = "<img src=\"images/loading.gif\" style=\"padding-right: 5px;\"/>Anfrage gesendet! \""+ expression +"\", bitte warten!";
	else
	    outmsg = "<img src=\"images/loading.gif\" style=\"padding-right: 5px;\"/>";

	mc_status[idx].update(outmsg);
	httpRequest.onreadystatechange = function() { insertContents(httpRequest, idx); };
	httpRequest.open('GET', url+'&expression='+expression, true);
	httpRequest.send('');
}

function insertContents(httpRequest, idx)
{
	if (httpRequest.readyState == 4)
	{
		if (httpRequest.status == 200)
		{
			mc_status[idx].update("<img src=\"images/loading_ok.gif\" style=\"padding-right: 5px;\"/> Antwort bekommen: ");
			
			if(httpRequest.responseText.length < 1)
			{
				var outmsg = "";
				if(debug == 1)
			    	    outmsg = "<img src=\"images/loading_stop.gif\" style=\"padding-right: 5px;\"/> Keine Daten empfangen!";
				else
				    outmsg = "<img src=\"images/loading_stop.gif\" style=\"padding-right: 5px;\"/>";

				mc_status[idx].update("outmsg");
				return;
			}
			
			try
			{
			    var obj = eval('(' + httpRequest.responseText + ')');
			}
			catch(e)
			{
			    var outmsg = "";
			    if(debug == 1)
				outmsg = "<img src=\"images/loading_stop.gif\" style=\"padding-right: 5px;\"/> "+e;
			    else 
				outmsg = "<img src=\"images/loading_stop.gif\" style=\"padding-right: 5px;\"/>";

			    mc_status[idx].update(outmsg);
			    removeResultBox(idx);
			    return;
			}

			var outmsg = "";
			if(debug == 1)
			    outmsg = mc_status[idx].innerHTML += obj.length + " Objekte";
			else
			    outmsg = "";

			mc_status[idx].update( outmsg );
			
			//delete old results
			/*
			for ( var i = mc_result[idx].options.length-1; i >= 0; i-- )
			    mc_result[idx].options[i] = null;
			
			
			if( obj.length > 0)
			    for ( var i = 0; i < obj.length; i++ )
			    {
				mc_result[idx].options.add( new Option(obj[i].id+" "+obj[i].model+" "+obj[i].name, obj[i].id) );
			    }
			else
			    mc_result[idx].options.add( new Option("keine Objekte gefunden!", 0) );
			*/

			if( obj.length > 0)
    			    showSuggestBox(obj, idx);
			else
			    removeResultBox(idx);

		}
		else
		{
		    var outmsg = "";
		    if(debug == 1)
		    	outmsg = "<img src=\"images/loading_stop.gif\" style=\"padding-right: 5px;\"/> There was a problem with the request.";
		    else
			outmsg = "<img src=\"images/loading_stop.gif\" style=\"padding-right: 5px;\"/>";

		    mc_status[idx].update(outmsg);
		}
	}
}

function click_closeButton(event)
{
    var element = event.element();
    var idx = element.readAttribute('mc_idx');


    realCloseResultBox(idx);
}

function realCloseResultBox(idx)
{
    clearTimeout(closetout[idx]);

    if( mc_result[idx] != null)
    {
	//alert("remove " + mc_result[idx]);
	mc_result[idx].remove();
	delete mc_result[idx];
	mc_result[idx] = null;
    }
}

function removeResultBox(idx)
{
    clearTimeout(closetout[idx]);
    closetout[idx] = setTimeout("realCloseResultBox("+idx+")", 800);
}


// inherit from Person class:
var McRow = Class.create({
 initialize: function(values)
 {
    this.row = new Element('tr', { 'class': 'suggest_row' });
    this.values = values;

    Event.observe(this.row, 'click', this.click.bindAsEventListener(this) );
    Event.observe(this.row, 'mouseover', this.mouseover.bindAsEventListener(this) );
    Event.observe(this.row, 'mouseout', this.mouseout.bindAsEventListener(this) );


    var j=0;
    for (var key in this.values)
    {
	if( ["mc_model", "mc_name", "mc_img", "mc_price"].indexOf(key) != -1 )
	{
	    var td = new Element('td', { 'class': 'suggest_column'} ).update(this.values[key]);

	    if(j == 0)
		td.addClassName("suggest_column_first");
	

	    td.addClassName(key);

	    this.row.insert( td );
	    j++;
	}
    }

 },

 getRowElement: function(){ return this.row; },

 click: function(e)
 {
    window.location.href = this.values.mc_link;
 },

 mouseover: function(e)
 {
    this.row.setAttribute('color_', this.row.style.color);
    this.row.style.backgroundColor = "#3366CC";
    this.row.style.cursor = "pointer";


    for(i=0; i<this.row.childNodes.length; i++)
    {
	this.row.childNodes[i].setAttribute('color_', this.row.childNodes[i].style.color);

        this.row.childNodes[i].style.color = "#ffffff";
	this.row.childNodes[i].style.cursor = "pointer";
    }
 },

 mouseout: function(e)
 {
    this.row.setAttribute('color_', this.row.style.color);
    this.row.style.backgroundColor = "transparent";

    for(i=0; i<this.row.childNodes.length; i++)
    	this.row.childNodes[i].style.color = this.row.childNodes[i].readAttribute("color_");

 }

});


function showSuggestBox(objects, idx)
{
    realCloseResultBox(idx);

    mc_result[idx] = new Element('div', { 'class': 'suggest_box'} );
    var inner_result = new Element('div', { 'class': 'suggest_box_inner'} );
    mc_result[idx].insert(inner_result);


    var resultsTable = new Element('table', { 'class': 'suggest_table', 'border': '0', 'cellspacing': '0', 'cellpadding': '0'} );
    var resultsTableBody = new Element('tbody', {});
    resultsTable.insert( resultsTableBody  );

    var closeButton = new Element('div', { 'class': 'suggest_close', 'mc_idx': idx} );
    var statusLine = new Element('div', { 'class': 'suggest_statusline'} ).update("Zu Ihrem Suchbegriff passende Angebote:");

    closeButton.observe('click', click_closeButton);

    inner_result.insert(statusLine);
    inner_result.insert(closeButton);

    if( objects.length > 0)
    {
	for ( var i = 0; i < objects.length; i++ )
	    resultsTableBody.insert( new McRow(objects[i]).getRowElement() );


        inner_result.insert(resultsTable);
	mc_result[idx].clonePosition(mc[idx]);

	mc_result[idx].style.height = "";
	mc_result[idx].style.top = parseInt(mc_result[idx].style.top) + mc[idx].getHeight() + "px";

        mc[idx].insert({'after': mc_result[idx]});
    }
}



function keypressMc(event)
{
    var	idx = getIdIdx(this.id);
    clearTimeout(closetout[idx]);

    //allowed keys
    var searchkeys = "abcdefghijklmnopqrstuvwxyz0123456789()#- ,.<>";
    var key = event.which || event.keyCode;

    var keychar = String.fromCharCode(key);
    keychar = keychar.toLowerCase();



    if(key == Event.KEY_ESC)
    {
	removeResultBox(idx);
    }

    else if ( searchkeys.indexOf(keychar) > -1 || key == Event.KEY_BACKSPACE || key == Event.KEY_DELETE)
    {
	if( this.value.length < 2 )
		return;
    
	clearTimeout(tout[idx]);
	tout[idx] = setTimeout("search('"+this.value+"', '/matchcode.php?lookfor="+this.getAttribute("lookfor")+"', "+idx+")", 800);
    }
}

function focusMc()
{
    for(i=0; i<mc.length; i = i+1)
	removeResultBox(i);
}

function getIdIdx(str)
{
	var out = "";
	
	for( var i = str.length; i > 0; i--)
	{
		c = str.charAt(i)
		if( !isNaN(parseInt(c)) )
			out += ''+c;
	}
	
	return parseInt(out);
}