//****************************************************************************
var globalShoppingCartItems = new Array();
var search_max_chunks       = 4;
var search_limit_index      = 1;

function get_search_page( start ) {

    var domain_list_row = domElement( 'domain_list_row' );
    var list_tds        = domain_list_row.getElementsByTagName( 'TD' );

    for ( var i in list_tds ) {

        if ( !list_tds[i] ) continue;

        while ( list_tds[i].firstChild ) {

            list_tds[i].removeChild( list_tds[i].firstChild );
        }
    }

    perform_domain_search( null, start );

    return;
}

function perform_domain_search( rpc_id, start ) {

    var rpc_class = 'domain_search';
    var search_form = domElement( 'search_form' );

    if ( typeof( rpc_id ) == 'undefined' || rpc_id == null ) {
        rpc_id = unique_id();
    }

    if ( typeof( start ) == 'undefined' || start == null ) {
        start = 0;
        // clear out any obsolete page links
        var tnb = [ 'page_links', 'page_links_top', 'page_links_bottom' ];
        for ( var n in tnb ) {
            var page_links = domElement( tnb[n] );
            if ( page_links ) {
                while( page_links.firstChild ) {
                    page_links.removeChild( page_links.firstChild );
                }
            }
        }
    }

    // now assigned by send_rpc
    // window.current_rpc_id[rpc_class] = rpc_id;
    
    var search_parameter = [
        'main_category_index', 'domain_search_text', 'price_range',
        'match_style',         'tld[]',              'sort_by'
    ];

    var params = new Array();
    params.push( 'rpc_class=' + rpc_class );
    params.push( 'limit_index=' + escape( window.search_limit_index ) );
    params.push( 'rpc_id=' + escape( rpc_id ) );
    params.push( 'start=' + start );

    for ( var s in search_parameter ) {

        var param = domElement( search_parameter[s] );
        var value = get_value_for_field( param );

        // logit( 
        //     'prepping search: ' 
        //     + search_parameter[s] 
        //     + ' => ' 
        //     + param 
        //     + ' => [' + value + ']' 
        // );

        // skip the TLD requirement if ALL is selected
        if ( search_parameter[s] == 'tld[]' ) {
            if ( ( new String( value ) ).match( /ALL/ ) ) continue;
        }

        // skip index selectors of value zero 
        if ( search_parameter[s].match( /_index|sort_|_range/ ) ) {

            // ignore selections of Any/All
            if ( value == 0 ) continue;
            // decrement index to avoid Any/All offset
            else value--;
        }

        // skip the text if none is entered
        if ( search_parameter[s] == 'domain_search_text' ) { 
            if ( value == '' ) continue;
        }  

        search_parameter[s] = search_parameter[s].replace( /^main_/, '' );

        params.push( search_parameter[s] + '=' + escape( value ) );
    }
    send_rpc( params, add_domain_list );

    return false;
}

// DOM builder for the domains list ( a.k.a 'callback' )
function add_domain_list( domains ) {

    if ( !domains ) return false;

    // verify this invokation is in response to the most current request
    if ( domains.rpc_id != window.current_rpc_id[domains.rpc_class] ) {
        // abort: another rpc of the same class has taken priority
        return;
    }

    var current_limit = window.limits[ window.search_limit_index ];

    var results_per_page = (
        window.search_max_chunks * current_limit
    );

    var current_chunk_number = (
        (
            Math.round( domains.start / current_limit )
            %
            window.search_max_chunks
        )
        + 1
    );

    var current_page_number = (
        Math.floor(
            (
                parseInt( domains.start ) + parseInt( results_per_page )
            )
            / results_per_page
        )
    );

    var max_start_index = (
        current_page_number * results_per_page
    );  

    // issue the purge directive if this is the first data chunk
    // for the current rpc
    var purge_directive = null;
    if ( current_chunk_number == 1 ) {
        purge_directive = 'purge'; 
    }

    // add the current result set to the ui
    add_list_items( 
        'domain', 
        add_cart_links( domains ), 
        purge_directive 
    );

    // go back for more, if there is any
    if ( 
         domains.next         > 0 
      && domains.next         < max_start_index
      && current_chunk_number < window.search_max_chunks 
    ) {
        // use the proposed next as the start of the next chunk
        perform_domain_search( 
            domains.rpc_id, 
            domains.next 
        );
    }
    else {
        // this rpc is no longer active
        window.current_rpc_id[ domains.rpc_class ] = null;

        if (
            window.search_max_chunks
            <
            ( domains.total_found / current_limit )
        ) {

            generate_page_links(
                domains.start,
                current_page_number,
                results_per_page,
                domains.total_found,
                'javascript:get_search_page($start);'
            );
        }

        logit( 'completed final chunk for rpc call: ' + domains.rpc_id );
    }
    return;
}

function add_to_cart( domain_item_id ) {

    var domain_list_item = domElement( 'domain_' + domain_item_id );

    logit( 'add_to_cart(' + domain_item_id + ') => ' + domain_list_item );

    var cart_item_html = '<li '
        + 'id="'
        + 'cart_domain_' + domain_item_id
        + '">'
        + domain_list_item.firstChild.innerHTML
        + '</li>';

    var cart_item = {
        'list_items' : [ cart_item_html ]
    };

    var items_added_count = add_list_items(
        'cart_domain',
        cart_item,
        'no-purge',
        'inline-block-fix'
    );

    if ( items_added_count == 1 ) {

        // add a field to the form for submission to request
        var shopping_cart_form = domElement( 'shopping_cart_form' );
        if ( shopping_cart_form ) {
            window.globalShoppingCartItems.push( domain_item_id );
            // domain_ids will be CSV
            shopping_cart_form.domain_ids.value 
                = window.globalShoppingCartItems;
        }

        var shopping_cart_button = domElement( 'shopping_cart_button' );
        var shopping_cart_header = domElement( 'shopping_cart_header' );
        if ( shopping_cart_button && shopping_cart_header ) {

            shopping_cart_button.style.display = 'block';
            shopping_cart_header.style.display = 'block';
        }
    }
    else if ( items_added_count == 0 ) {
        set_temporary_status_message(
            '"' + domain_list_item.firstChild.innerHTML + '"'
            + ' is already in your shopping cart.'
        );
    }
    else {
        logit( 'error adding shopping cart item: ' + domain_list_item );
    }
    return;
}

// controls TLD checkbox grid behavior
function check( this_value ) {
    var tld_checkboxe = domElement( 'tld[]' );
    if ( tld_checkboxe ) {
        var this_checked = false;
        for ( var s in tld_checkboxe ) {

            if ( !tld_checkboxe[s] ) continue;

            // find the invoking checkbox and get its checked state
            if ( tld_checkboxe[s].value == this_value ) {
                this_checked = tld_checkboxe[s].checked;
                break;
            }
        }
        if ( this_value == 'ALL' ) {
            // unchecking all
            if ( this_checked == false ) {
                // leave the first item checked
                tld_checkboxe[0].checked = true;
                // uncheck all -- exluding the first and last items
                for ( var s = 1; s < ( tld_checkboxe.length - 1 ); s++ ) {
                    tld_checkboxe[s].checked = false;
                }
                // set the all checked flag for future reference
                window.all_tlds_checked = false;
            }
            // checking all
            else {
                // check all -- excluding the last item
                for ( var s = 0; s < ( tld_checkboxe.length - 1 ); s++ ) {
                    tld_checkboxe[s].checked = true;
                }
                // set the all checked flag for future reference
                window.all_tlds_checked = true;
            }
        }
        else {
            // case of unchecking on after all have been checked
            if ( window.all_tlds_checked == true ) {
                window.all_tlds_checked = false;
                tld_checkboxe[( tld_checkboxe.length - 1 )].checked = false; 
            }
        }
    }
    return;
}

// enhance results with links to the request page
function add_cart_links( domains ) {

    var domain_id_regex = new RegExp(/"domain_([\d]+)">([^<]+)</);

    for ( var n in domains.list_items ) {

        var domain_id_match = domains.list_items[n].match( domain_id_regex );

        if ( domain_id_match && domain_id_match[1] ) {

            domains.list_items[n] = 
                '<li id="domain_'
                + domain_id_match[1]
                + '"><a href="javascript:add_to_cart('
                + domain_id_match[1]
                + ');">'
                + domain_id_match[2]
                + '</a></li>';

            // domains.list_items[n] = '<li id="domain_'
            //     + domain_id_match[1]
            //     + '">'
            //     + '<a href="javascript:add_to_cart('
            //     + domain_id_match[1]
            //     + ');">'
            //     + domains.list_items[n]
            //     + '</a></li>';
        }
        else {
            logit(
                'add_cart_links: '
                + 'domains.list_items[' + n + '] => ' + domains.list_items[n]
                + ' -- there was a problem parsing the domain_id.'
            );
        }
    }
    return domains;
}


