var bgSearch =  {
    
    'lastPress' : 0,
    'charLimit' : 3,    
    'delay' : 300,
    'oldQuery' : '',
    'timer' : null,
    
    doSearch : function(query) {
        this.lastPress = (new Date()).getTime();              
        if (this.timer != null) {
            clearTimeout(this.timer);
        }
        this.timer = setTimeout("bgSearch.updateAll('"+query+"');", 500);                
    },
    
    updateArticleResults : function(object) {        
        var id = object.rel.replace(/.*_([a-z0-9]*)$/, '$1'); 
        
        var query  = document.getElementById('searchfield').value;        
        var params = {'query'           : query,
                      'searchType'      : 'article',
                      'articleType'     : id                      
                     };
            
        if (document.getElementById('articleresults_'+params.articleType).hasChildNodes() == true) {
            return;
        }        
        
        bgTools.doXmlHttpRequest(bgSearch.updateHook, '/suche/', 'POST', params);        
    },
    
    updateInstrumentResults : function(object) { 
        var id = object.rel.replace(/.*_([a-z0-9]*)$/, '$1'); 
              
        var query  = document.getElementById('searchfield').value;        
        var params = {'query'           : query,
                      'searchType'      : 'instrument',
                      'instrumentType'  : id                      
                     };
                                
        if (document.getElementById('instrumentresults_' + params.instrumentType).hasChildNodes() == true) {
            return;
        } 
        
        bgTools.doXmlHttpRequest(bgSearch.updateHook, '/suche/', 'POST', params);
    },
    
    updateAll : function(query) {   
        if (this.lastPress + this.delay > (new Date()).getTime() || query.length < this.charLimit 
            || query == this.oldQuery) {
            return;
        }
        
        document.getElementById('search-results-view').style.display = 'none';
           
        var query  = encodeURIComponent(document.getElementById('searchfield').value);                   
        var params = {'query'           : query,
                      'searchType'      : 'all',
                      'instrumentType'  : 0,
                      'articleType'     : 0                     
                     };
           
        var articleBodies = bgTools.getElementsByClassName('articlebody');   
                 
        for (i=0; i < articleBodies.length; i++) {            
            while (articleBodies[i].hasChildNodes()) {
                articleBodies[i].removeChild(articleBodies[i].firstChild);
            }                
        }                
        var instBoddies = bgTools.getElementsByClassName('instbody');
        for (i=0; i < instBoddies.length; i++) {
            while (instBoddies[i].hasChildNodes()) {
                instBoddies[i].removeChild(instBoddies[i].firstChild);
            }              
        }
        
        this.oldQuery = query;
        
        document.getElementById('search-headline').innerHTML = 'Suche wird ausgef&uuml;hrt...';
        document.getElementById('search-headline').style.display = '';
        document.getElementById('searchbar').style.display = '';
        
        bgTools.activate(document.getElementById('articles_firsttab'));
        bgTools.activate(document.getElementById('instruments_firsttab'));
               
        bgTools.doXmlHttpRequest(bgSearch.updateHook, '/suche/', 'POST', params);     
    },
    
    updateHook : function(response, params) {
        document.getElementById('searchsoundex').innerHTML = '';
               
        var records = eval('(' + response + ')');          
        var articlesAvailable = false;
        var instrumentsAvailable = false;
        var moreArticles = false;
        var moreInstruments = false;
             
        var articleBodies = bgTools.getElementsByClassName('articlebody');   

        if (params.searchType == 'article' || params.searchType == 'all') {                 
            for (i=0; i < articleBodies.length; i++) {            
                while (articleBodies[i].hasChildNodes()) {
                    articleBodies[i].removeChild(articleBodies[i].firstChild);
                }                
            }
        }
                        
        for(i=0; i<records.length; i++) {
              
              if (records[i].type == 'article' ) {        
                    title = records[i].title;
                    date = records[i].date_formatted;
                    id = records[i].id_article; 
                    signature = records[i].signature; 
                    typeDE = records[i].typeDE; 
                    moreArticles = records[i].more;
                    id_creator = records[i].id_creator;
                    id_type = records[i].id_type;
                          
                    if (signature == null) {
                        signature = '';
                    }
                    
                    var tr = document.createElement("tr");
                    var td = document.createElement("td");                    
                    td.innerHTML = date;                    
                    tr.appendChild(td);
                    
                    td = document.createElement("td");                    
                    td.innerHTML = '<a href="/artikel/zeigen/articleId/'+id+'">'+title+'</a>'; 
                  
                    tr.appendChild(td);
                    
                    
                    td = document.createElement("td");                    
                    if (typeDE != null) {
                        td.innerHTML = '<a href="/archiv/typeId/'+id_type+'">'+typeDE+'</a>';                   
                    } else {
                        td.innerHTML = '&nbsp;';
                    }
                    tr.appendChild(td);
                    
                    td = document.createElement("td");                    
                    td.innerHTML = '<a href="/archiv/authorId/'+id_creator+'">'+signature+'</a>';                  
                    tr.appendChild(td);
                                     
                    document.getElementById('articleresults_'+params.articleType).appendChild(tr);                    
                    articlesAvailable = true;
              }
              
              if( records[i].type == 'instrument' ) {              
                    id = records[i].id;
                    name = records[i].name;
                    isin = records[i].isin;
                    wkn = records[i].wkn;
                    tickerde = records[i].tickerde;
                    tickerus = records[i].tickerus;
                    sort = records[i].sortDE;               
                    moreInstruments = records[i].more;  
                    
                    var tr = document.createElement("tr");
                    var td = document.createElement("td");                    
                    td.innerHTML = '<a href="/suche/track/instrumentId/'+id+'/query/'+encodeURIComponent(params.query)+'">'+name+'</a>';                    
                    tr.appendChild(td);
                    
                    td = document.createElement("td");                    
                    td.innerHTML = sort;                    
                    tr.appendChild(td);
                    
                    td = document.createElement("td");                    
                    td.innerHTML = isin;                   
                    tr.appendChild(td);
                    
                    td = document.createElement("td");                    
                    td.innerHTML = wkn;                  
                    tr.appendChild(td);
                    
                    td = document.createElement("td");                    
                    td.innerHTML = tickerde;                  
                    tr.appendChild(td);
                    
                    td = document.createElement("td");                    
                    var aktion = '<a href=\"/profil/profichart/instrumentId/'+id+'\" title=\"Profichart starten\"><img src=\"/themes/default/media/content/icon_profichart.gif\" alt=\"Icon Profichart"></a>';
                    if (sort == 'Index') {
                        aktion += ' <a href=\"/kursliste/indexId/'+id+'/orderBy/change_percent/orderDirection/DESC\" title=\"Kursliste\"><img src=\"/themes/default/media/content/icon_kursliste.gif\" alt=\"Kursliste\" border=\"0\"></a>';
                    }                    
                    aktion += ' <a href=\"/suche/optionsscheine-zertifikate-anleihen-etfs-fonds/nach-basiswert/basiswert/'+id+'\" title=\"Produkte auf '+name+' &amp; suchen\"><img src=\"/themes/default/media/content/icon_productlist.gif\" alt=\"Produkte\" border=\"0\"></a>';                  
                    td.innerHTML = aktion;
                    tr.appendChild(td);
                    
                    
                                                        
                                     
                    document.getElementById('instrumentresults_'+params.instrumentType).appendChild(tr);    
                    instrumentsAvailable = true;
              }
         }   
         
         if (articlesAvailable == false && instrumentsAvailable == false && params.searchType == 'all') {
            document.getElementById('search-headline').innerHTML = "Keine Ergebnisse f&uuml;r '" + decodeURIComponent(params.query) +"'.";
            if( records[0].type == 'soundex' ) { 
                search = records[0].search;
            }
            search = '<a href="#" onclick="document.getElementById(\'searchfield\').value=\''+search+'\';bgSearch.updateAll(\''+search+'\');">'+search+'</a>'; 
            
            document.getElementById('searchsoundex').innerHTML = "Meinten Sie vielleicht '"+search+"'?";
            document.getElementById('searchsoundex').style.display = ''; 
            return;
         } 
         
         if (instrumentsAvailable  == false && (params.searchType == 'instrument' || params.searchType == 'all')) {
            var tr = document.createElement("tr");
            var td = document.createElement("td"); 
            td.innerHTML = 'Keine Ergebnisse.';
            td.setAttribute("colspan", 5, 0);      
            tr.appendChild(td);
            document.getElementById('instrumentresults_'+params.instrumentType).appendChild(tr);            
         }
          
         if (articlesAvailable == false && (params.searchType == 'article' || params.searchType == 'all')) {
            var tr = document.createElement("tr");
            var td = document.createElement("td"); 
            td.innerHTML = 'Keine Ergebnisse.';
            td.setAttribute("colspan", 4, 0);            
            tr.appendChild(td);
            document.getElementById('articleresults_'+params.articleType).appendChild(tr);            
         }    
         
         if (moreArticles == true && (params.searchType == 'article' || params.searchType == 'all')) {
            tr = document.createElement("tr");
            td = document.createElement("td");
            td.setAttribute('align', 'right', 0);
            var link = '<a href="/archiv/query/' + params.query;             
            if (typeof(params.articleType) != 'undefined' && params.articleType != 0) {
                link += '/typeId/'+params.articleType;
            }
            if (typeof(params.authorId) != 'undefined') {
                link += '/authorId/'+params.authorId;
            }
            link += '">Mehr Artikel...</a>';
            td.innerHTML = link;            
            td.setAttribute("colspan", 4, 0);
            tr.appendChild(td);
            document.getElementById('articleresults_'+params.articleType).appendChild(tr);            
         }      
         
         if (moreInstruments == true && (params.searchType == 'instrument' || params.searchType == 'all')) {
            tr = document.createElement("tr");
            td = document.createElement("td");
            td.setAttribute('align', 'right', 0);
            var link = '<a href="/suche/instrumente/wkn-isin-name/' + params.query;             
            if (typeof(params.instrumentType) != 'undefined' && params.instrumentType != 0) {
                var typ;
                switch (params.instrumentType) {
                    case 'index': {
                            typ = 'index';
                            break;
                        }
                    case 'stock': {
                            typ = 'aktie';
                            break;
                        }
                    case 'commodity': {
                            typ = 'rohstoff';
                            break;
                        }
                    case 'bond': {
                            typ = 'anleihe';
                            break;
                        }
                    case 'currency': {
                            typ = 'währung';
                            break;
                        }               
                }
                link += '/typ/'+typ;
            }        
            
            
            link += '">Mehr Instrumente...</a>';
            
            td.innerHTML = link;
            td.setAttribute("colspan", 6, 0);
            tr.appendChild(td);
            document.getElementById('instrumentresults_'+params.instrumentType).appendChild(tr);            
         } 
         document.getElementById('search-headline').innerHTML = 'Suchergebnisse';
         document.getElementById('search-results-view').style.display = 'block';         
}
}
