/* (C) 2008 Musikhaus Thomann. Do not even think about copying, stealing or changing the code. Branntwein dunnit. */

var spConfig =
    {
        url: 'spreview_handler.html', input: '#fsearch-sw', active: true, isVisible: false, hover:'fsearch-hover',
        dpack: {
                    'bulb':     '<img src="http://a2.images6.thomann.de/pics/modpics/search_preview_smbulb2.gif" width="16" height="14">',
                    'close':    '<img src="http://a2.images6.thomann.de/pics/modpics/search_preview_smclosex.gif" id="fsearch-close" width="11" height="10" alt="switch off search suggestions">',
                    'pbegin':   '<span class="fs-add">',
                    'pend':     '</span>',
                    'headbg':   'http://a1.images6.thomann.de/pics/modpics/search_preview_headerbackground.gif'
                },
		lpack: {
                    P: 'products',
				    H: 'manufacturer',
                    W: 'categories',
				    C: 'product&nbsp;selections',
                    headline: 'suggestions for your search',
                    produkte: 'products',
                    produkt: 'product',
                    produktseite: 'product page',
                    close:  'The search suggestions have been deactivated. They can be reactivated at any time on the page "advanced search".'
                }
    };

var spCache = [];
var hl = false;
var $container  = null;

function spKey( key ) {

    if( !spConfig.active ) return;

    var max = $('li',$container).length-1;
    switch( key.keyCode ) {
        case 38:
            if( hl === false ) { hl = max; }
            else { hl = ( hl == 0 )? max : hl-1; }
        break;

        case 40:
            if( hl === false ) { hl = 0; }
            else { hl = ( hl == max)? 0 : hl+1; }
        break;

        case 13:
            if( hl !== false ) {
                spFollow( $('li', $container).eq(hl).data('location') );
                return false;
            }
        return true;

        case 27: spShow(); break;
        default:  return true;
    }

    if( hl !== false ) {
        $('li', $container).removeClass(spConfig.hover).eq(hl).addClass(spConfig.hover);
        return false;
    }

}

$(document).ready( function ( ) {

    $container = $('#fsearch-preview');
    $('#fsearch-sw').attr('autocomplete', 'off');
    var $wrapper   = $('<div></div>');
    
    try{
        $container.bgIframe();
    }catch(err){
    }

    $container
        .append( $('<h1>' + spConfig.lpack.headline + spConfig.dpack.close + '</h1>').css('background-image', 'url('+spConfig.dpack.headbg+')') )
        .append( $wrapper );

    $( spConfig.input )
        .bind( 'keyup', function ( key ) {

            key = key.keyCode;
            if( key == 38 || key == 40 || key == 13 || key == 27 ) {
                return;
            }

            if( !spConfig.active ) return;
            hl = false;

            var $bogus = $('<div id="fsearch-result"></div>');       
            var sWord = $(this).val();

            if( sWord && !spCache[ sWord ] ) {
                $.get( spConfig.url , { query: sWord, lanid: globals.lanid, awesum: Math.random()*1000 }, function ( s ) {
                    var cnt = spParse( sWord, s, $bogus );
                    spShow( $wrapper, $bogus, cnt );
                }, 'text' );
            } else if( !sWord ) {
               spShow();
            }else{
               var cnt = spParse( sWord, spCache[ sWord ], $bogus );
               spShow( $wrapper, $bogus, cnt );
            }

        })
        .bind('keydown', spKey );

    $('#fsearch-close').click( function() {
        spShow();
        spConfig.active = false;
        $.get('search_spdisable.html', { spturnoff: 1, sid: jsNCTrackingSID }, function() { alert( spConfig.lpack.close ); } );
    } );

    $(document).click( function() { spShow(); });
} );

function spShow( $wrapper, $bogus, cnt ) {

    if( cnt ) { $wrapper.html( $bogus ); }

    if( !spConfig.isVisible && cnt ) {
        $container.fadeIn( 210, function() { spConfig.isVisible = true; });
    }

    if( spConfig.isVisible && !cnt ) {
        $container.fadeOut( 210, function() { spConfig.isVisible = false; });
    }
}

function spFollow( href ) {
    if( jsNCTrackingSID !== '' ) {
        if( href.indexOf('?') >= 0 ) { href += '&sid='+jsNCTrackingSID;
        } else{ href += '?sid='+jsNCTrackingSID; }
    }
    document.location.href = href;
}

function spFormatTitle( title ) {
   return title.replace('<BU>', spConfig.dpack.bulb ); 
}

function spParse ( sWord, response, $container ) {

    spCache[ sWord ] = response;

    lines = response.split("\n");

    var lastHead = null;
    var $items = null;
    var cnt = 0;
    
    for( var row in lines ) {
        var tabs = lines[ row ].split("\t");

        if( tabs[0].length ) {

            var data = { title: tabs[0], link: tabs[1], head: tabs[2], hits: tabs[3] };
            if( data.head == 'S' ) continue;

            if( lastHead != data.head ) {
                $items = $('<ul></ul>');
                $container
                    .append('<h2>' + spConfig.lpack[ data.head ] + '</h2>')
                    .append( $items );

                lastHead = data.head;
            }

            var add =  spConfig.dpack.pbegin + data.hits + ' ' + spConfig.lpack.produkte + spConfig.dpack.pend;
            if ( data.head == 'P') {
                 add = spConfig.dpack.pbegin + spConfig.lpack.produktseite + spConfig.dpack.pend;
            } else if( data.hits == 1 ){
                add = spConfig.dpack.pbegin + '1 ' + spConfig.lpack.produkt + spConfig.dpack.pend;
            }

            var $item = $('<li><span class="fs-prod">' + spFormatTitle( data.title ) + '</span>' + add + '</li>').data('location', data.link);
            $items.append( $item );

            cnt++;
        }
    }

    $('li', $container)
        .hover( function() { $('li', $container).removeClass(spConfig.hover);
                             $(this).addClass( spConfig.hover );
                             hl = $('li', $container).index( this );
                           },
                function() { $(this).removeClass( spConfig.hover); }
              )
        .click( function() { spFollow( $(this).data('location') ); } );

    return cnt;
}

