var G_OFFSET = 0;
var OFFSET_GRANULARITY = 20;

// link the user search interactions
$().ready( function ()
{
    $( 'input' ).keyup( function () { search() } );
    $( '.prev' ).click( function () { search( G_OFFSET - OFFSET_GRANULARITY ) } );
    $( '.next' ).click( function () { search( G_OFFSET + OFFSET_GRANULARITY ) } );
} );

// do the search to the ASPX page
function search( offset )
{
    $( 'div.search' ).show();
    $( 'div.blurb' ).hide();

    if ( typeof ( offset ) == undefined || offset == null )
    {
        offset = 0;
    }

    if ( offset < 0 )
        offset = 0;

    if ( offset == 0 )
    {
        $( '.prev' ).hide()
    }
    else
    {
        $( '.prev' ).show();
    }
    G_OFFSET = offset;
    $.post( "search.aspx",
                { name: $( "#Name" ).val(),
                    primSpec: $( "#PrimarySpecialty" ).val(),
                    practice: $( "#PracticeName" ).val(),
                    zipCode: $( "#Address" ).val(),
                    OFFSET: offset,
                    OFFSET_GRAN: offset + OFFSET_GRANULARITY
                },
                function ( ret ) { results( ret ); } );
}

// process the results
function results( ret )
{
    // check if valid
    if ( $( "status", ret ).text() == "2" ) return;

    if ( $( "hasmore", ret ).text() == "0" )
        $( '.next' ).hide();
    else
        $( '.next' ).show();

    // clear old stuff
    $( 'tbody.results' ).empty();
    // put in new stuff
    $( "return", ret ).each( function ( id )
    {
        r = $( "return", ret ).get( id );
        $( 'tbody.results' ).append( 
            ( $( "n", r ).text() == "" ? '' : '<tr><td>' + $( "n", r ).text() + "</td></tr>" ) +
            ( $( "ps", r ).text() == "" ? '' : '<tr><td>' + $( "ps", r ).text() + "</td></tr>" ) +
            ( $( "prac", r ).text() == "" ? '' : '<tr><td>' + $( "prac", r ).text() + "</td></tr>" ) +
            ( $( "ph", r ).text() == "" ? '' : '<tr><td>' + $( "ph", r ).text() + "</td></tr>" ) +
            ( $( "addy", r ).text() == "" ? '' : '<tr><td>' + $( "addy", r ).text().replace( new RegExp( "@@@", "g" ), '</td></tr><tr><td>' ) + "</td></tr>" ) +
            "<tr><td><hr></td></tr>" );
    } );
    return;
}


