var http_request = false;
var hund_suche_clicked = null;
var suggestObj = null;

var hiddenObj = null; // Inputfeld wo die ID rein kommt
var ajaxObj = null; // div wo das AJAX drin steckt
var ajaxTabName = "ajaxTab"; // div wo das AJAX drin steckt
var inputObj = null; // eigentliche Objekt dass alles ausgelöst hat
var phpscript = ""; // Ausführbare php script
var phpparams = ""; // php Parameter für GET mit & getrennt! OHNE "?"
var sql_command = ""; // sql synonym der verwendet wird
var fillajaxphpparams = null; // event zum bearbeiten der Variable phpparams (returnvalue!)
var selectedIndex = -1;
var trElements = new Array();
var isAJAXVisible = false;
var ajaxminval = 3;

        function printDropDown(cssclass, txt_name, txt_value, val_name, val_value, sql, valparam, php, params, htmlattribs){
            printDropDown_rasse(cssclass, txt_name, txt_value, val_name, val_value, sql, valparam, php, params, htmlattribs, false);
        }
        function printDropDown_rasse(cssclass, txt_name, txt_value, val_name, val_value, sql, valparam, php, params, htmlattribs, isRasse){
            var use_rassen_link = false;
            if(isRasse && typeof(print_rassen_dropdown) == "function") use_rassen_link = true;
            document.write('<div class="'+cssclass+'" style="display: block; vertical-align: middle;">')
            document.write('<input class="'+cssclass+'" style="" autocomplete="off" type="text" name="'+txt_name+'" id="'+txt_name+'" value="'+txt_value+'" ajaxvalue="'+txt_value+'" onmousedown="AJAXscan(this, false, event);" onkeyup="return !AJAXscan(this, false, event); " ajax_hiddenobj="'+val_name+'" ajax_div="AJAX_'+txt_name+'" ajax_php="'+php+'" ajax_valueparam="'+valparam+'" sql="'+sql+'" ajax_params="'+params+'" '+htmlattribs+' />');
            if(use_rassen_link) document.write('<div class="rassen_button_dropdown_div"><img class="rassen_button_dropdown_img" id="AJAX_rasse_dd_btn'+txt_name+'" height="16" width="16" ajax_params="'+params+'" /></div>');
            document.write('</div>');
            document.write('<input type="hidden" name="'+val_name+'" id="'+val_name+'" value="'+val_value+'" />');
            document.write('<div name="AJAX_'+txt_name+'" id="AJAX_'+txt_name+'" style="width: 2px; padding: 0x; z-index: 9 !important; display: none;"></div>');
            if(use_rassen_link){
                document.write('<div id="AJAX_'+txt_name+'_rasse_dd" ajax_params="'+params+'" ajax_hiddenobj="'+val_name+'" ajax_textobj="'+txt_name+'"  style="margin: 0px; padding: 0x; z-index: 9 !important; display: none;"></div>');
                print_rassen_dropdown('AJAX_rasse_dd_btn'+txt_name,'AJAX_'+txt_name+'_rasse_dd');
            }
        }



        document.onkeypress = function (e){
            e = e || window.event;
            if (e.keyCode == 13 && isAJAXVisible) {
                return false; // Return unterbinden um Submit zu verhindern
            }
            return true;
        }

        document.onclick = function (e){
            if (isAJAXVisible) hideAJAXObj();
        }

        function is_exists(_var){
            if (typeof _var != 'undefined'){
                if (_var != null) return true;
            }
            return false;
        }

        function trim(s) {
            while (s.substring(0,1) == ' ') {
                s = s.substring(1,s.length);
            }
                while (s.substring(s.length-1,s.length) == ' ') {
                s = s.substring(0,s.length-1);
            }
            return s;
        }

        function getAttribValue(obj, attribName){
            if (obj != null  && is_exists(obj) && is_exists(obj.attributes)){
                for (i = 0; i < obj.attributes.length; i++) {
                    if ( obj.attributes[i].name.toLowerCase() == attribName.toLowerCase()) return obj.attributes[i].value;
                }
            }
            return "";
        }

        function setAttribValue(obj, attribName, attribValue){
            if (obj != null){
                for (i = 0; i < obj.attributes.length; i++) {
                    if ( obj.attributes[i].name.toLowerCase() == attribName.toLowerCase()) obj.attributes[i].value = attribValue;
                }
            }
            return "";
        }

        function returnAjaxClicked(obj){
            var val = getAttribValue(obj, "value");
            var text = getAttribValue(obj, "text");
            if (is_exists(hiddenObj)){
                hiddenObj.value = val;
                hideAJAX(ajaxObj);
            }
            if (is_exists(inputObj)){
                if (text != ''){
                    inputObj.value = text;
                    setAttribValue(inputObj, "ajaxvalue", text);
                    hideAJAX(ajaxObj);
                }
            }
            if (typeof OnAjaxReturned == "function")  OnAjaxReturned(inputObj);
            if (typeof OnAjaxRowSelected == "function")  OnAjaxRowSelected(obj);
        }

        function returnAjaxKeySelected(obj){
            var val = getAttribValue(obj, "value");
            var text = getAttribValue(obj, "text");
            if (is_exists(hiddenObj)){
                hiddenObj.value = val;
            }
            if (is_exists(inputObj)){
                if (text != ''){
                    inputObj.value = text;
                    setAttribValue(inputObj, "ajaxvalue", text);
                }
            }
            if (typeof OnAjaxReturned == "function")  OnAjaxReturned(inputObj);
            if (typeof OnAjaxRowSelected == "function")  OnAjaxRowSelected(obj);
        }

        function getTRsByName(_name){
            _TR_Res = new Array();
            if (is_exists(ajaxObj)){
                _TRArr = ajaxObj.getElementsByTagName("TR");
                for (i_f = 0; i_f < _TRArr.length; i_f++) {
                    if (getAttribValue(_TRArr[i_f], "name") == _name){
                        _TR_Res.push(_TRArr[i_f]);
                    }
                }
            }
            return _TR_Res;
        }

        function AJAX_initTab(tab){
            trElements = new Array();
            ajaxTabName = tab;
            selectedIndex = -1;
        }

        function AJAX_initTR(TR){
            trElements[trElements.length] = TR;
        }


	function clean_up(dirty_string)
	{

		//clean_string = dirty_string.replace('[ ]+', '-');
		clean_string = dirty_string.replace(/ /g, '-');
		//clean_string = clean_string.replace('[ä]+', 'ae');
		//clean_string = clean_string.replace('[ö]+', 'oe');
		//clean_string = clean_string.replace('[ü]+', 'ue');
		//clean_string = clean_string.replace('[\']+', '');

		clean_string = clean_string.replace(/ä/g, 'ae');
		clean_string = clean_string.replace(/ö/g, 'oe');
		clean_string = clean_string.replace(/ü/g, 'ue');
	//	clean_string = clean_string.replace(/\/g, '');


		return clean_string;
	}

	function clean_up_hf(dirty_string)
	{
		clean_string = dirty_string.replace(/ /g, '_');

		return clean_string;
	}

        function hideAJAXObj(){
            hideAJAX(ajaxObj);
        }

        function hideAJAX(Obj)
	{
            if (is_exists(Obj)){
		Obj.style.visibility = "hidden";
                Obj.style.display = "none";
            }
            isAJAXVisible = false;
            ajaxObj = null;
            if (typeof OnAjaxClosed == "function")  OnAjaxClosed(inputObj);
	}

        function showAJAX(Obj)
	{
            if (is_exists(Obj)){
                Obj.style.visibility = "visible";
                Obj.style.display = "block";
            }
            isAJAXVisible = true;
	}

        function setAJAX(suggestions)
         {
            if(is_exists(ajaxObj)){
                visibled = false;
                ajaxObj.innerHTML = "";
                if (suggestions == "") {
                    hideAJAX(ajaxObj);
                    return;
                } else {
                    ajaxObj.innerHTML = suggestions;
                    trElements = getTRsByName(ajaxTabName+"_row");
                   if (trElements.length > 0){
                      els = trElements.length;
                        showAJAX(ajaxObj);

                        if (els == 1) {
                           AJAX_SelectIndex(0, false);
                           AJAX_initTab(ajaxTabName);
                           selectedIndex = 0;
                        } else {
                           AJAX_initTab(ajaxTabName);
                        }
                        visibled = true;
                    } else {
                        hideAJAX(ajaxObj);
                        return;
                    }
                }

                if (typeof OnAjaxLoaded == "function") OnAjaxLoaded(visibled);

                return;
            }
         }

	function doAJAXRequest()
	{
		http_request = false;

		if (window.XMLHttpRequest) // Opera, Mozilla, Safari, Netscape
		{
			http_request = new XMLHttpRequest();
			if (http_request.overrideMimeType)
			{
                http_request.overrideMimeType('text/xml');
            }
		}
		else if (window.ActiveXObject)  // IE
		{
			try
			{
				http_request = new ActiveXObject("Msxml2.XMLHTTP");
            }
			catch (e)
			{
				try
				{
					http_request = new ActiveXObject("Microsoft.XMLHTTP");
				}
				catch (e) {}
			}
		}
	}


	function doAjax()
	{
		doAJAXRequest();

//		inc = escape(document.getElementById(inputObjectID).value);
//                ajaxTabName = "ajaxTab";

		var url = phpscript+"?"+phpparams+"&sql="+sql_command+"&acache="+Math.round(Math.random()*100000)+"&tabname="+ajaxTabName;

		if (http_request)
		{
                        if(is_exists(ajaxObj)){
                            ajaxObj.innerHTML = "<div style=\"position: absolute;\"><img src=\"/layout/progress_bar_ajax.gif\"></div>";
                            showAJAX(ajaxObj);
                        }
			http_request.onreadystatechange = function() {if ((http_request.readyState == 4) && (http_request.status == 200)) setAJAX(http_request.responseText);}
			http_request.open('GET', url, true);
			http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			http_request.send(null);
		}
		else
		{
			document.getElementById('if').src=url+'&iframe=true';
		}
	}

	
var timerID = 0;

function AJAX_SelectIndex(idx, selectNow){
   for (i_tr = 0; i_tr < trElements.length; i_tr++) {
        TRObj = trElements[i_tr];
        //console.log('idx='+idx+'; i_tr='+i_tr);
        if (idx == i_tr){
            setAttribValue(TRObj, "selected", true);
            setAttribValue(TRObj, "class", getAttribValue(TRObj, "selectedCSS"));
            if(selectNow) returnAjaxKeySelected(TRObj);
        } else {
            setAttribValue(TRObj, "selected", false);
            setAttribValue(TRObj, "class", getAttribValue(TRObj, "normalCSS"));
        }
    }
}

function AJAXscan(_inputObj, _removeKey, evt)
{
        if (_inputObj != inputObj){
            hideAJAXObj();
        }

        var _doAjax = true;
        if ((evt.type == "keyup") && isAJAXVisible){
            trElements = getTRsByName(ajaxTabName+"_row");
            if (evt.keyCode == 38){ // Cursor nach oben
                _removeKey = false;
                if (selectedIndex > -1) selectedIndex--;
                AJAX_SelectIndex(selectedIndex, false);
                _doAjax = false;
                if (evt && evt.stopPropagation) evt.preventDefault(); else evt.returnValue = false;
                return true;
            } else if (evt.keyCode == 40){ // Cursor nach unten
                _removeKey = false;
                if (selectedIndex < trElements.length -1) selectedIndex++;
                AJAX_SelectIndex(selectedIndex, false);
                _doAjax = false;
                evt.returnValue = false;
                if (evt && evt.stopPropagation) evt.preventDefault(); else evt.returnValue = false;
                return true;
            } else if (evt.keyCode == 13){ // Enter
                _removeKey = false;
                AJAX_SelectIndex(selectedIndex, true);
                hideAJAXObj();
                _doAjax = false;
                evt.returnValue = false;
                if (evt && evt.stopPropagation) evt.preventDefault(); else evt.returnValue = false;
                return true;
            } else if (evt.keyCode == 27){ // ESC
                _removeKey = false;
                hideAJAXObj();
                _doAjax = false;
                return true;
            } else if (evt.keyCode == 9){ // Tabulator
                _removeKey = false;
                AJAX_SelectIndex(selectedIndex, true);
                hideAJAXObj();
                _doAjax = false;
                return true;
            }
        }

        if (_doAjax == true){
            phpparams = "";
            doRemoveKey = _removeKey;
            inputObj = _inputObj; // wo kommts her
            ajaxTabName = "ajax_tab_" + inputObj.id;
            if (fillajaxphpparams != null) phpparams = fillajaxphpparams(inputObj);
            ajaxObj = document.getElementsByName(getAttribValue(inputObj, "ajax_div"))[0]; // wo wird die auswahl angezeigt
           // hiddenObj = document.getElementsByName(getAttribValue(inputObj, "ajax_hiddenobj"))[0]; // wo muss es hin
            hiddenObj = document.getElementById(getAttribValue(inputObj, "ajax_hiddenobj"));

            AJAXvalue = getAttribValue(inputObj, "ajaxvalue"); // Prüfen ob veränderung da ist oder nicht, nur dann auf 0 zücksetzen. Ist sicherer als key- oder Mousehooks
            if (AJAXvalue != inputObj.value){
                hiddenObj.value = 0;
            }
            hiddenObj.value = 0;
            if (typeof OnAjaxLoad == "function") OnAjaxLoad(inputObj);

            setAttribValue(inputObj, "ajaxvalue", inputObj.value);

            ajaxminval = 3;
            ajaxminval = getAttribValue(inputObj, "minval");

            //if (_removeKey) hiddenObj.value = 0;

            ajaxparams = getAttribValue(inputObj, "ajax_params");

            if (trim(phpparams) != "") phpparams = "&" + phpparams;
            if (trim(ajaxparams) != "") phpparams = ajaxparams + phpparams;
            if (trim(phpparams) != "") phpparams = "&" + phpparams;
            phpparams = getAttribValue(inputObj, "ajax_valueparam")+"="+inputObj.value+phpparams;
            phpscript = getAttribValue(inputObj, "ajax_php");
            
            sql_command = getAttribValue(inputObj, "sql");

            if(timerID) clearTimeout(timerID);
            if (inputObj.value.length > ajaxminval-1){ // Minimum 3 Zeichen Notwendig!
                timerID = setTimeout("doAjax()", 1000);
            } else {
                hideAJAXObj();
            }
        }
        //return false;
}

