function appendElement( elem_list, base_elem ) {
    // console.log( '%i elements left to load.', elem_list.length );
    if ( elem_list.length <= 0 ) return;
    var next_elem = elem_list.shift();   // take from top (FIFO)
    // console.log( 'Now loading "%s"...', next_elem );
    var xselect = getSelection();
    $.ez( 'ezjsctemplate::search/' + next_elem, xselect, function (x) {
        // console.log( 'Got XHR data: %o', x );
        base_elem.append( x.content );
        appendElement( elem_list, base_elem );
    } );
}

function saveSelection( parameters ) {
    var x = '';
    for ( var i in parameters ) {
        if ( !parameters.hasOwnProperty( i ) ) continue;
        if ( parameters[i].value.length == 0 ) continue;   // skip empty settings
        x += '&' + escape( parameters[i].name ) + '=' + escape( parameters[i].value );
    }
    x = x.substr(1);
    document.location.hash = x;
}

function getSelection() {
    var x = document.location.hash.substr( 1 );
    var splits = x.split( '&' );
    var result = [];
    for ( var i in splits ) {
        if ( !splits.hasOwnProperty( i ) ) continue;
        var pair = splits[i];
        var data = pair.split( '=' );
        result.push( { name: unescape( data[0] ), value: unescape( data[1] ) } );
    }
    // console.log( 'Decoded HASH parameters: %o', result );
    return result;
}

function ajaxReplaceControl( cname, params ) {
    $( '#select_' + cname ).replaceWith( '<img id="select_'+cname+'" src="/extension/silver.project/design/silver.project/images/loadingAnimation-flat.gif" />' );
    $.ez( 'ezjsctemplate::search/select_' + cname, params, function (x) {
        // console.log( 'Got XHR data for %s: %o', cname, x );
        $('#select_' + cname).replaceWith( x.content );
    } );
}

function ajaxReplace( id, template, params ) {
    $( id ).html( '<img src="/extension/silver.project/design/silver.project/images/loadingAnimation-large.gif" />' );
    // console.log( 'Starting XHR Request with params: %o', params );
    // console.time( 'ajaxReplace' );
    $.ez( 'ezjsctemplate::' + template, params, function (x) {
        // console.timeEnd( 'ajaxReplace' );
        // console.log( 'Got XHR data: %o', x );
        $( id ).html( x.content );
    } );
}

function reload_select( which, p ) {
    var xpage  = (p==undefined)?1:p;
    // build filter parameters
    var params = [];
    params.push( { name: 'p', value: xpage } );
    switch ( which ) {
        default:
            params.push( { name: 'productcategory', value: $('#select_cat2').val() } );
            params.push( { name: 'cat2', value: $('#select_cat2').val() } );
        case 'cat2':
            params.push( { name: 'cat1', value: $('#select_cat1').val() } );
        case 'cat1':
            params.push( { name: 'itemgroup', value: $('#select_itemgroup').val() } );
        case 'itemgroup':
            params.push( { name: 'model', value: $('#select_model').val() } );
        case 'model':
            // params.push( { name: 'systemseries', value: $('#select_systemseries').val() } );
            params.push( { name: 'systemtypeseries', value: $('#select_systemtypeseries').val() } );
        case 'systemseries':
            // params.push( { name: 'systemtype', value: $('#select_systemtype').val() } );
        case 'systemtype':
        case 'systemtypeseries':
            params.push( { name: 'manufacturer', value: $('#select_manufacturer').val() } );
    }
    saveSelection( params );

    if ( which ) {
        // load the actual select box
        // console.log( 'Starting XHR request with these parameters: %o', params );
        ajaxReplaceControl( which, params );
    }

    // reset later fields which now don't match anymore
    switch ( which ) {
        case 'systemtype':
            ajaxReplaceControl( 'systemseries', {} );
        case 'systemseries':
        case 'systemtypeseries':
            ajaxReplaceControl( 'model', {} );
        case 'model':
            ajaxReplaceControl( 'itemgroup', {} );
        case 'itemgroup':
            ajaxReplaceControl( 'cat1', {} );
        case 'cat1':
            ajaxReplaceControl( 'cat2', {} );
    }

    // if a model has been selected, reload result area (use params-variable from above)
    if ( which == 'itemgroup' || which == 'cat1' || which == 'cat2' || !which ) {
        // console.log( 'Reloading result area.' );
        ajaxReplace( '#resultlist', 'search/list_itemsbymodel', params );
    }
}

function doSearchPage( p ) {
    var xsubject = $('#product-search input[name=s]:checked').val();
    var xquery = $('#product-search input#query').val();
    var xpage  = (p==undefined)?1:p;
    // console.log( 'Search-Query: "%s" in subject "%s" on page %s', xquery, xsubject, xpage );

    var params = [];
    params.push( { name: 'q', value: xquery } );
    params.push( { name: 's', value: xsubject } );
    params.push( { name: 'p', value: xpage } );
    saveSelection( params );

    // console.log( 'Reloading result area.' );
    ajaxReplace( '#resultlist', 'search/list_itemsbysearch', params );

    return false;
}

function doSearch() {
    return doSearchPage( 1 );
}

jQuery( document ).ready( function($) {
    // console.log( 'Document loaded.' );
    var elements = [ 'select_manufacturer', 'select_systemtypeseries', 'select_model', 'select_itemgroup', 'select_cat1', 'select_cat2' ];
    appendElement( elements, $('#product-finder') );
    // directly call module-view: $.get( '/ezjscore/run/items/select_manufacturer', function (data) { $('#product-finder').html( data ); } );
    var xselect = getSelection();
    for ( var i in xselect ) {
        if ( !xselect.hasOwnProperty( i ) ) continue;
        switch ( xselect[i].name ) {
            case 'model':
                // console.log( 'HASH parameters contains model. Load list...: %o', xselect );
                $.ez( 'ezjsctemplate::search/list_itemsbymodel', xselect, function (x) { $('#resultlist').html( x.content ); } );
                break;
            case 'q':
                $( '#product-search input#query' ).val( xselect[i].value );
                break;
            case 's':
                $( '#product-search input[name=s][value=' + xselect[i].value +']' ).attr( 'checked', 'CHECKED' );
                break;
        }
    }
    $('#product-search form').submit( doSearch );
    if ( $('#product-search input#query' ).val().length > 0 ) doSearch();   // init search if query is already loaded
} );


