$(document).ready(function(){
	/*suchbegriff*/
	$('#dSIbegiff').bind('focus blur',function(e){
		if(e.type=='focus'){
			$('#dSCbegiff')[0].checked=true;
		}else{
			this.value = $.trim(this.value);
			if(this.value.length == 0){
				$('#dSCbegiff')[0].checked=false;
			}	
		}
	});
	
	
	/*$('#dSIbegiff, #sBegriff').bind('blur',function(e){
		if(this.value.length>0)
		{
			$.ajax({
				type: "POST",
				url: "http://" + window.location.hostname + "/ajax_php/set_session_suchbegriff.php",
				data: "sBegriff="+this.value,
				dataType: "html"
			});
		}
	});*/
	
	/*plz ort*/
	$('#dSIplzOrt').bind('focus blur',function(e){
		if(e.type=='focus'){
			$('#dSCplzOrt')[0].checked=true;
		}else{
			this.value = $.trim(this.value);
			if(this.value.length == 0){
				$('#dSCplzOrt')[0].checked=false;
				$('#dSSumkreis, #dSCumkreis').attr('disabled','disabled');
			}else{
				$('#dSSumkreis, #dSCumkreis').attr('disabled','');
			}	
		}
	});	
	
	$('#dSCplzOrt').bind('click',function(e){
		if(this.checked==false){
			$('#dSSumkreis, #dSCumkreis').attr('disabled','disabled');
		}else{
			var check_str = $.trim($('#dSIplzOrt').val());
			if(check_str.length>0)
			{
				$('#dSSumkreis, #dSCumkreis').attr('disabled','');
			}
		}
	});	
	
	/*plz ort*/
	$('#sPlzOrt').bind('focus blur',function(e){
		this.value = $.trim(this.value);
		geoid = $('#geoid').val();
		
				
		if(this.value.length == 0 || geoid.split('#')[0] == 'BUN'){
			$('#sUmkreis').attr('disabled','disabled');
		}else{
			$('#sUmkreis').attr('disabled','');
		}	
	});	
	
	
	
	/*Umkreis*/
	$('#dSSumkreis').bind('click change blur',function(e){
		var sc = $('#dSCumkreis')[0];
		if(e.type=='click'){
			sc.checked=true;
		}else{		
			if(this.selectedIndex!=0){
				sc.checked=true;
			}else{
				sc.checked=false;}
		}
	});
	
	/*preis von, preis bis*/
	$('#dSIpreisVon, #dSIpreisBis').bind("focus blur", function(e){
		var sc = $('#dSCpreis')[0];
		var si_von = $('#dSIpreisVon')[0];
		var si_bis = $('#dSIpreisBis')[0];
		
		if(e.type=='focus'){
			sc.checked=true;
		}else{
			si_bis.value = $.trim(si_bis.value);
			si_von.val = $.trim(si_von.value);
			if(si_von.value.length==0 && si_bis.value.length==0){
				sc.checked=false;
			}else{
				sc.checked=true;}
		}
	});
	
	$('#dSIpreisVon, #dSIpreisBis').keyup(function(e){
		s = this.value;
		s = s.replace(/\D/ig,'');
		this.value = s;
	});
	
	var bCnt = $('#anzeigenCntBefore').attr("value");
	var aCnt = $('#anzeigenCntAct').attr("value");
	bCnt = parseInt(bCnt);
	aCnt = parseInt(aCnt);
	if (bCnt <= aCnt) {
		var diff = aCnt - bCnt;
		var cnt = diff / 10;		
		cnt = parseInt(Math.ceil(cnt));
		var timer = window.setInterval(function() {	
			if (bCnt <= aCnt) {
					bCnt+=cnt;
					if (bCnt >= aCnt) {
						$('span[id=anzeigenCnt]').each(function(){
							$(this).html('<b>'+aCnt+'</b>');
						});
						window.clearInterval(timer);	
					}else{
						$('span[id=anzeigenCnt]').each(function(){
							$(this).html('<b>'+bCnt+'</b>');
						});
					}
			} else {
				 window.clearInterval(timer);
			}
	 	}, 40);
	}
	
	if (bCnt >= aCnt) {
		var diff = bCnt - aCnt;
		var cnt = diff / 10;		
		cnt = parseInt(Math.ceil(cnt));
		var timer = window.setInterval(function() {	
			if (bCnt >= aCnt) {
					bCnt-=cnt;
					if (bCnt <= aCnt) {
						$('span[id=anzeigenCnt]').each(function(){
							$(this).html('<b>'+aCnt+'</b>');
						});
						window.clearInterval(timer);
					}else{
						$('span[id=anzeigenCnt]').each(function(){
							$(this).html('<b>'+bCnt+'</b>');
						});
					}
			} else {
				 window.clearInterval(timer);
			}
		}, 40);
	}
	
	$("#sPlzOrt, #dSIplzOrt").change(function(){
		$("input[id*='geoid']").val('');
	});
	
	/*PLZ ORT BUNDESLAND*/
	$("#sPlzOrt, #dSIplzOrt").autocomplete("http://"+window.location.hostname+"/ajax_php/suche_get_ortschaften.php",{ 
			inputClass:"slform",resultsClass:"ac_results",lineSeparator:"\n",cellSeparator:"|",minChars:2,
			delay:500,matchCase:0,matchSubset:true,matchContains:0,cacheLength:10,mustMatch:false,extraParams:{},
			loadingClass:"ac_loading",selectFirst:true,selectOnly:true,autoFill:false,width:250,scroll:true,
			scrollHeight:200
	});
		
	$("#sPlzOrt, #dSIplzOrt").result(function(event, data, formatted) {
		if (data)
			$("input[id*='geoid']").val(data[1]);
	});
	
});




function html_entity_decode (string, quote_style) {

    var hash_map = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();
    
    if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }

    for (symbol in hash_map) {
        entity = hash_map[symbol];
        tmp_str = tmp_str.split(entity).join(symbol);
    }
    tmp_str = tmp_str.split('&#039;').join("'");
    
    return tmp_str;
}

function htmlspecialchars (string, quote_style) {
    // Convert special characters to HTML entities  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/htmlspecialchars
    // +   original by: Mirek Slugen
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Nathan
    // +   bugfixed by: Arno
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Ratheous
    // -    depends on: get_html_translation_table
    // *     example 1: htmlspecialchars("<a href='test'>Test</a>", 'ENT_QUOTES');
    // *     returns 1: '&lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;'
    var hash_map = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();
    
    if (false === (hash_map = this.get_html_translation_table('HTML_SPECIALCHARS', quote_style))) {
        return false;
    }
    
    hash_map["'"] = '&#039;';
    for (symbol in hash_map) {
        entity = hash_map[symbol];
        tmp_str = tmp_str.split(symbol).join(entity);
    }
    
    return tmp_str;
}


function get_html_translation_table (table, quote_style) {
        
    var entities = {}, hash_map = {}, decimal = 0, symbol = '';
    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};
    
    // Translate arguments
    constMappingTable[0]      = 'HTML_SPECIALCHARS';
    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';

    useTable       = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';
    useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT';

    if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
        throw new Error("Table: "+useTable+' not supported');
        // return false;
    }

    entities['38'] = '&amp;';
    if (useTable === 'HTML_ENTITIES') {
        entities['160'] = '&nbsp;';
        entities['161'] = '&iexcl;';
        entities['162'] = '&cent;';
        entities['163'] = '&pound;';
        entities['164'] = '&curren;';
        entities['165'] = '&yen;';
        entities['166'] = '&brvbar;';
        entities['167'] = '&sect;';
        entities['168'] = '&uml;';
        entities['169'] = '&copy;';
        entities['170'] = '&ordf;';
        entities['171'] = '&laquo;';
        entities['172'] = '&not;';
        entities['173'] = '&shy;';
        entities['174'] = '&reg;';
        entities['175'] = '&macr;';
        entities['176'] = '&deg;';
        entities['177'] = '&plusmn;';
        entities['178'] = '&sup2;';
        entities['179'] = '&sup3;';
        entities['180'] = '&acute;';
        entities['181'] = '&micro;';
        entities['182'] = '&para;';
        entities['183'] = '&middot;';
        entities['184'] = '&cedil;';
        entities['185'] = '&sup1;';
        entities['186'] = '&ordm;';
        entities['187'] = '&raquo;';
        entities['188'] = '&frac14;';
        entities['189'] = '&frac12;';
        entities['190'] = '&frac34;';
        entities['191'] = '&iquest;';
        entities['192'] = '&Agrave;';
        entities['193'] = '&Aacute;';
        entities['194'] = '&Acirc;';
        entities['195'] = '&Atilde;';
        entities['196'] = '&Auml;';
        entities['197'] = '&Aring;';
        entities['198'] = '&AElig;';
        entities['199'] = '&Ccedil;';
        entities['200'] = '&Egrave;';
        entities['201'] = '&Eacute;';
        entities['202'] = '&Ecirc;';
        entities['203'] = '&Euml;';
        entities['204'] = '&Igrave;';
        entities['205'] = '&Iacute;';
        entities['206'] = '&Icirc;';
        entities['207'] = '&Iuml;';
        entities['208'] = '&ETH;';
        entities['209'] = '&Ntilde;';
        entities['210'] = '&Ograve;';
        entities['211'] = '&Oacute;';
        entities['212'] = '&Ocirc;';
        entities['213'] = '&Otilde;';
        entities['214'] = '&Ouml;';
        entities['215'] = '&times;';
        entities['216'] = '&Oslash;';
        entities['217'] = '&Ugrave;';
        entities['218'] = '&Uacute;';
        entities['219'] = '&Ucirc;';
        entities['220'] = '&Uuml;';
        entities['221'] = '&Yacute;';
        entities['222'] = '&THORN;';
        entities['223'] = '&szlig;';
        entities['224'] = '&agrave;';
        entities['225'] = '&aacute;';
        entities['226'] = '&acirc;';
        entities['227'] = '&atilde;';
        entities['228'] = '&auml;';
        entities['229'] = '&aring;';
        entities['230'] = '&aelig;';
        entities['231'] = '&ccedil;';
        entities['232'] = '&egrave;';
        entities['233'] = '&eacute;';
        entities['234'] = '&ecirc;';
        entities['235'] = '&euml;';
        entities['236'] = '&igrave;';
        entities['237'] = '&iacute;';
        entities['238'] = '&icirc;';
        entities['239'] = '&iuml;';
        entities['240'] = '&eth;';
        entities['241'] = '&ntilde;';
        entities['242'] = '&ograve;';
        entities['243'] = '&oacute;';
        entities['244'] = '&ocirc;';
        entities['245'] = '&otilde;';
        entities['246'] = '&ouml;';
        entities['247'] = '&divide;';
        entities['248'] = '&oslash;';
        entities['249'] = '&ugrave;';
        entities['250'] = '&uacute;';
        entities['251'] = '&ucirc;';
        entities['252'] = '&uuml;';
        entities['253'] = '&yacute;';
        entities['254'] = '&thorn;';
        entities['255'] = '&yuml;';
    }

    if (useQuoteStyle !== 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }
    if (useQuoteStyle === 'ENT_QUOTES') {
        entities['39'] = '&#39;';
    }
    entities['60'] = '&lt;';
    entities['62'] = '&gt;';


    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal);
        hash_map[symbol] = '&#'+decimal+';';
    }
    
    return hash_map;
}


function str_replace (search, replace, subject, count) {
    
		var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
            f = [].concat(search),
            r = [].concat(replace),
            s = subject,
            ra = r instanceof Array, sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }

    for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {
            temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;}
        }
    }
    return sa ? s : s[0];
}

function explode (delimiter, string, limit) {

		var emptyArray = { 0: '' };
    
    // third argument is not required
    if ( arguments.length < 2 ||
        typeof arguments[0] == 'undefined' ||
        typeof arguments[1] == 'undefined' )
    {
        return null;
    }
 
    if ( delimiter === '' ||
        delimiter === false ||
        delimiter === null )
    {
        return false;
    }
 
    if ( typeof delimiter == 'function' ||
        typeof delimiter == 'object' ||
        typeof string == 'function' ||
        typeof string == 'object' )
    {
        return emptyArray;
    }
 
    if ( delimiter === true ) {
        delimiter = '1';
    }
    
    if (!limit) {
        return string.toString().split(delimiter.toString());
    } else {
        // support for limit argument
        var splitted = string.toString().split(delimiter.toString());
        var partA = splitted.splice(0, limit - 1);
        var partB = splitted.join(delimiter.toString());
        partA.push(partB);
        return partA;
    }
}


function split (delimiter, string) {
    return this.explode( delimiter, string );
}

function in_array (needle, haystack, argStrict) {
    var key = '', strict = !!argStrict;

    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }

    return false;
}

function trim (str, charlist) {
    
    var whitespace, l = 0, i = 0;
    str += '';
    
    if (!charlist) {
        // default list
        whitespace = " \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000";
    } else {
        // preg_quote custom list
        charlist += '';
        whitespace = charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1');
    }
    
    l = str.length;
    for (i = 0; i < l; i++) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(i);
            break;
        }
    }
    
    l = str.length;
    for (i = l - 1; i >= 0; i--) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(0, i + 1);
            break;
        }
    }
    
    return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}

function implode (glue, pieces) {
    return ( ( pieces instanceof Array ) ? pieces.join( glue ) : pieces );
}


function urlencode (str) {
	
    var hexStr = function (dec) {
        return '%' + dec.toString(16).toUpperCase();
    };

    var ret = '',
            unreserved = /[\w.-]/; // A-Za-z0-9_.- // Tilde is not here for historical reasons; to preserve it, use rawurlencode instead
    str = (str+'').toString();

    for (var i = 0, dl = str.length; i < dl; i++) {
        var ch = str.charAt(i);
        if (unreserved.test(ch)) {
            ret += ch;
        }
        else {
            var code = str.charCodeAt(i);
            // Reserved assumed to be in UTF-8, as in PHP
            if (code === 32) {
                ret += '+'; // %20 in rawurlencode
            }
            else if (code < 128) { // 1 byte
                ret += hexStr(code);
            }
            else if (code >= 128 && code < 2048) { // 2 bytes
                ret += hexStr((code >> 6) | 0xC0);
                ret += hexStr((code & 0x3F) | 0x80);
            }
            else if (code >= 2048 && code < 65536) { // 3 bytes
                ret += hexStr((code >> 12) | 0xE0);
                ret += hexStr(((code >> 6) & 0x3F) | 0x80);
                ret += hexStr((code & 0x3F) | 0x80);
            }
            else if (code >= 65536) { // 4 bytes
                ret += hexStr((code >> 18) | 0xF0);
                ret += hexStr(((code >> 12) & 0x3F) | 0x80);
                ret += hexStr(((code >> 6) & 0x3F) | 0x80);
                ret += hexStr((code & 0x3F) | 0x80);
            }
        }
    }
    return ret;
}


function array_unique (array) {
    var key = '', tmp_arr1 = {}, tmp_arr2 = {};
    var val = '';
    tmp_arr1 = array;
    
    var __array_search = function (needle, haystack) {
        var fkey = '';
        for (fkey in haystack) {
            if ((haystack[fkey] + '') === (needle + '')) {
                return fkey;
            }
        }
        return false;
    };

    for (key in tmp_arr1) {
        val = tmp_arr1[key];
        if (false === __array_search(val, tmp_arr2)) {
            tmp_arr2[key] = val;
        }
        
        delete tmp_arr1[key];
    }
    
    return tmp_arr2;
}


function makeEbaySearchQuery(value){

	var arrSigns = new Array('-','&','\\','!','"','§','$','%','@','(',')','=','?','*','#',"'",'[',']','{','}','´','`','~',':',';','|','^','°');
	var arrWords = new Array('AB', 'ALLEM', 'ALLEN', 'ALLER', 'ALLES', 'ALS', 'AM', 'AN', 'AUCH', 'AUF', 'AUS', 'BEI', 'BEIM', 'DA', 'DANN', 'DAS', 'DASS', 'DAVON', 'DEM', 'DEN', 'DENN', 'DER', 'DES', 'DIE', 'DURCH', 'EIN', 'EINE', 'EINEM', 'EINER', 'EINES', 'EINMAL', 'ER', 'ERSTEN', 
'ERSTER', 'ERSTES', 'ES', 'ETWA', 'ETWAS', 'FÜR', 'IHR', 'IM', 'IMMER', 'IN', 'IST', 'JE', 'JEDEM', 'JEDER', 'JEDES', 'JEGLICHES', 'KAUM', 'KEIN', 'KEINE', 'KEINES', 'MAN', 'MEHR', 'MIT', 'MÖGLICHST', 'NACH', 'NICHT', 'NOCH', 'ODER', 'OFT', 'OHNE', 'SEHR', 
'SICH', 'SIE', 'SO', 'SOLCHEN', 'SOLCHER', 'SOLCHES', 'UM', 'UND', 'UNTER', 'VOM', 'VON', 'VOR', 'WANN', 'WARUM', 'WAS', 'WELCHEM', 'WELCHEN', 'WELCHES', 'WENIG', 'WENIGER', 'WENIGES', 'WENNGLEICH', 'WER', 'WERDEN', 'WESHALB', 'WIE', 'WIEDER', 'WIESO', 'WIR',
'WIRD', 'WO', 'WOBEI', 'WOFÜR', 'WOHER', 'WURDE', 'WÜRDEN', 'ZU', 'ZUM', 'ZUR');
	
	var sign = 0, word = '', newWord = '';
	var tmp = value;
	var arrTmp = new Array();
	var arrNew = new Array();
		
	tmp = html_entity_decode(tmp);
	
	tmp = str_replace(arrSigns, ' ', tmp);
	tmp = tmp.toUpperCase();
	arrTmp = split(' ', tmp);
	
	arrTmp = array_unique(arrTmp);
	
	for(idx in arrTmp)
	{
		word = arrTmp[idx];
		
		if(!in_array(word, arrWords))
		{
			newWord = trim(word);
			if(newWord.length > 0){
				newWord = urlencode(newWord);
				arrNew.push(newWord);
			}
		}	
	}
	
	
	
	tmp = implode(",",arrNew); 
	
	
	return '(' + tmp + ')';
	
}

