// ----------------------------------------------------------------
// Global functions
// ----------------------------------------------------------------

function showChangeLog() {
   var changeLogWindow = window.open('changelog.aspx', 'changelog',
                                     'width=500,height=525,scrollbars,resizable');
   if (window.focus) { changeLogWindow.focus(); }
}

function AutoComplete_Loading( source, eventArgs ) {
    $('#ithrob').css('visibility', 'visible');
}

function AutoComplete_Finished( source, eventArgs ) {
    $('#ithrob').css('visibility', 'hidden');
}

// ----------------------------------------------------------------
// Interaction code
// ----------------------------------------------------------------

$(document).ready(function() {

    // ----------------------------------------------------------------
    // Shared variables
    // ----------------------------------------------------------------
  
    var $ddlMunic = $('#ddlMunic');
    var $txtTaxMapNum = $('#txtTaxMapNum');
    var $txtPropNum = $('#txtPropNum');
    var $txtLastOwner = $('#txtLastOwner');
    var $txtFirstOwner = $('#txtFirstOwner');
    var $txtStreetNum = $('#txtStreetNum');
    var $txtStreetName = $('#txtStreetName');
    var $ddlSiteType = $('#ddlSiteType');
    var $ddlStatus = $('#ddlStatus');
    
    var currentTimerID = 0;
  
    // ----------------------------------------------------------------
    // Event handlers
    // ----------------------------------------------------------------
  
    $ddlMunic.change(updateSearchResultStatus);
    $txtTaxMapNum.keyup(startUpdateTimer);
    $txtPropNum.keyup(startUpdateTimer);
    $txtLastOwner.keyup(startUpdateTimer);
    $txtFirstOwner.keyup(startUpdateTimer);
    $txtStreetNum.keyup(startUpdateTimer);
    $ddlSiteType.change(updateSearchResultStatus);
    $ddlStatus.change(updateSearchResultStatus);
    
    // Need both keyup and change handlers for street name to correctly
    // update both when someone types in it and when they select an option
    // from the auto-complete list.
    $txtStreetName.keyup(startUpdateTimer);
    $txtStreetName.change(startUpdateTimer);
    
    // Override what happens when the Reset button is clicked.
    $('#btnReset').click(function() {
        resetForm();
        return false;
    });
    
    //call update unconditionally on page load, in case user
    //hits back button
    updateSearchResultStatus();
    
    // ----------------------------------------------------------------
    // Helper methods
    // ----------------------------------------------------------------
    
    // Starts a timer before calling the updateSearchResultStatus()
    // function to only query when the user pauses from typing.
    function startUpdateTimer() {
        // First clear any existing update timers
        window.clearTimeout(currentTimerID);
        
        // Now start a new timer
        currentTimerID = window.setTimeout(updateSearchResultStatus, 250);
    }
    
    function updateSearchResultStatus() {
        var params = getSearchParameters();
        
        // Don't run the query if there is no search criteria
        if (!params.isEmpty()) {
            PageMethods.GetSearchResultCount(params, onSuccess, onFailure);
        }
        else {
            $('#searchInfo #tips').show();
            $('#searchInfo #count').hide();
            $('#searchInfo #zerocount').hide();
        }
    }
    
    function getSearchParameters() {
        // Create a new params object
        var params = {};
        params.count = 0;
        
        params.add = function(key, value) {
            this[key] = value;
            this.count++;
        }
        
        params.isEmpty = function() {
            var swisIsEmpty = this['swis'] == 'all' || $ddlMunic.attr('disabled');
            var swisIsOnlyParam = this.count == 1;
            var statusDisabledButInParams = $ddlStatus.length == 0 && this.count == 2; 
            //statusDisabledButInParams is true during basic search, "active"
            //status is automatically chosen to prevent deleted/historic results
            return (swisIsEmpty && (swisIsOnlyParam || statusDisabledButInParams)); 
        }
        
        // Add the parameters to the params object
        params.add('swis', $ddlMunic.val());
        
        if ($txtTaxMapNum.length != 0 && $txtTaxMapNum.val() != '')
            params.add('pk', $txtTaxMapNum.val());
            
        if ($txtPropNum.length != 0 && $txtPropNum.val() != '')
            params.add('acctnum', $txtPropNum.val());
            
        if ($txtLastOwner.length != 0 && $txtLastOwner.val() != '')
            params.add('lastname', $txtLastOwner.val());
            
        if ($txtFirstOwner.length != 0 && $txtFirstOwner.val() != '')
            params.add('firstname', $txtFirstOwner.val());
            
        if ($txtStreetNum.length != 0 && $txtStreetNum.val() != '')
            params.add('streetnum', $txtStreetNum.val());
            
        if ($txtStreetName.length != 0 && $txtStreetName.val() != '')
            params.add('streetname', $txtStreetName.val());
            
        if ($ddlSiteType.length != 0 && $ddlSiteType.val() != 'any')
            params.add('sitetype', $ddlSiteType.val());
        
        if ($ddlStatus.length == 0) {
            params.add('status', 'active');
        }
        else {
            if ($ddlStatus.val() != 'any')
                params.add('status', $ddlStatus.val());
        }
        
        return params;
    }
    
    // Callback function for successfull Ajax search result count query.
    function onSuccess(result) {
        var propertyCount = new Number(result);
        if (propertyCount == 0) {
            $('#searchInfo #tips').hide();
            $('#searchInfo #zerocount').show();
            $('#searchInfo #count').hide();
        }
        else {
            $('#searchInfo #tips').hide();
            $('#searchInfo #zerocount').hide();
            $('#searchInfo #count').show();
            $('#searchResultCount').text(result);
            if(propertyCount == 1) {
                $('#btnSearch').val('Go to the Property');
            }
            else {
                $('#btnSearch').val('Search');
            }
        }
    }
    
    // Callback function for unsuccessfull Ajax search result count query. If
    // an error occurs, make sure the search button is enabled and reset the
    // search tips message back to the default.
    function onFailure() {
        $('#searchInfo #tips').show();
        $('#searchInfo #zerocount').hide();
        $('#searchInfo #count').hide();
    }
    
    // Resets all of the fields in the search form to their default values
    // and updates or hides all of the search info messages.
    function resetForm() {
        // Clear all of the text in the text boxes
        $('#tblSearch input[type=text]').val('');
        
        // Reset all drop-down lists to their initial values
        $('#tblSearch select').each(function() {
            this.selectedIndex = 0;
        });

        $('#btnSearch').val('Search');
        
        // Hide the "no results" message if it's shown
        $('#noResults').hide();
        
        updateSearchResultStatus();
    }
});
