﻿var searchAjaxTimeout;
var restSearchRequest;

function SubjectSearch(searchModalId, existingSubjectSelected, newSubjectCreated, isUserOnlySearch, displayUserIcon, includeTLCount) {
    this.searchModalId = searchModalId;
    this.existingSubjectSelected = existingSubjectSelected;
    this.newSubjectCreated = newSubjectCreated;

    $("#" + searchModalId).dialog({
        width: 363,
        autoOpen: false,
        modal: true,
        close: function(event, ui) {
            $($("input.hiddenReset")[0]).click();
        }
    }).parent().appendTo("#tempcont");

    // Show subject search modal
    this.show = function() {
        $('#' + searchModalId + ' #subjectSearchResults').html('');
        $('.searchOnChange').val('');
        this.bindToSearchOnChange();
        $("#" + searchModalId).dialog("open");
    }

    // Hide subject search modal
    this.hide = function() {
        $("#" + searchModalId).dialog("close");
    }

    this.handleCompanyCreate = function(sender, args) {
        try {
            if (sender._postBackSettings.sourceElement.id == $('#' + searchModalId + " .SubjectSearchActionLink")[0].id) {
                newSubjectCreated($('#' + searchModalId + " .createdCompanyId").val());
            }
        } catch (err) { }
    }

    function URLEncode(clearString) {
        var output = '';
        var x = 0;
        clearString = clearString.toString();
        var regex = /(^[a-zA-Z0-9_.]*)/;
        while (x < clearString.length) {
            var match = regex.exec(clearString.substr(x));
            if (match != null && match.length > 1 && match[1] != '') {
                output += match[1];
                x += match[1].length;
            } else {
                if (clearString[x] == ' ')
                    output += '+';
                else {
                    var charCode = clearString.charCodeAt(x);
                    var hexVal = charCode.toString(16);
                    output += '%' + (hexVal.length < 2 ? '0' : '') + hexVal.toUpperCase();
                }
                x++;
            }
        }
        return output;
    }

    var companiesPerPage = 25;
    function getCompanySearchData(callback) {
        restGetUrl = 'rest/Company.svc/'
            + '?name=' + URLEncode($('#' + searchModalId + " .searchCompanyName").val())
            + '&address=' + $.trim(URLEncode($('#' + searchModalId + " .searchAddress1").val()) + ' ' + URLEncode($('#' + searchModalId + " .searchAddress2").val()))
            + '&city=' + URLEncode($('#' + searchModalId + " .searchCity").val())
            + '&region=' + URLEncode($('#' + searchModalId + " .searchRegion").val())
            + '&postalCode=' + URLEncode($('#' + searchModalId + " .searchPostalCode").val())
            + '&page=' + companyListPage
            + '&itemsPerPage=' + companiesPerPage
            + '&isUserSearch=' + isUserOnlySearch.toString();


        if (restSearchRequest != null) restSearchRequest.abort();

        restSearchRequest = $.ajax({
            url: restGetUrl,
            type: 'GET',
            dataType: 'json',
            timeout: 8000,
            cache: false,
            error: function (error) {
                alert('Could not search companies.');
            },
            success: function (companies) {
                callback(companies);
            }
        });
    }

    function addCompaniesToResults(companies) {
        $(companies).each(function (i) {
            companyHtml = '<div style="clear: both; '
                    + ((displayUserIcon && companies[i].ActiveUserCount > 0) ? 'background-color: #DDD; ' : ' ')
                    + 'overflow: auto">'
                    + ((displayUserIcon && companies[i].ActiveUserCount > 0) ? '<span class="search-anscers-user-expl">This company is an active <span class="ans">anscers</span> user.</span><div style="float: left"><span class="search-anscers-user">' + companies[i].Name + '</span>' : '<div style="float: left">' + companies[i].Name + ' ')
                    + ((includeTLCount) ? '(' + companies[i].TradeLineCount + ' trade lines)' : '')
                    + '<br />'
                    + companies[i].Address
                    + '<br />'
                    + ((companies[i].AddressLine2 != null && $.trim(companies[i].AddressLine2) != '') ? companies[i].AddressLine2 + '<br />' : '')
                    + companies[i].City + ', ' + companies[i].Region + ' ' + companies[i].PostalCode + ' ' + (($.trim(companies[i].Country.toLowerCase()) != 'usa') ? companies[i].Country : '')
                    + '<br />'
                    + ((companies[i].CompanyDba != null && companies[i].CompanyDba != '') ? 'DBA: ' + companies[i].CompanyDba + '<br />' : '')
                    + ((companies[i].OwnerFirstName != null && companies[i].OwnerFirstName != '') ? 'Owner: ' + companies[i].OwnerFirstName + ' ' + companies[i].OwnerLastName + '<br />' : '')
                    + ((companies[i].PhoneNumber != null && companies[i].PhoneNumber != '') ? 'Phone: ' + companies[i].PhoneNumber + '<br />' : '')
                    + '</div><div style="float: right"><input type="button" class="btn subjectSelectButton' + companies[i].Id + '" value="Select" id="subjectSelect' + i + '" /></div></div><hr />';

            if (displayUserIcon && companies[i].ActiveUserCount > 0)
                $('#' + searchModalId).find("#subjectSearchResults").prepend(companyHtml);
            else
                $('#' + searchModalId).find("#subjectSearchResults").append(companyHtml);

            $('#' + searchModalId + " #subjectSelect" + i).click(function () {
                existingSubjectSelected(companies[i].Id, companies[i].Name, companies[i].Address, companies[i].City, companies[i].Region, companies[i].PostalCode, companies[i].OriginalMemberId);
            });
        });

        // Append "More" link
        var totalCompaniesCount = (companies.length > 0) ? companies[0].TotalCompaniesCount : 0;
        var showingCompaniesCount = (companiesPerPage * (companyListPage + 1) > totalCompaniesCount) ? totalCompaniesCount : companiesPerPage * (companyListPage + 1);
        var isMoreLinkNeeded = totalCompaniesCount > showingCompaniesCount;

        if (totalCompaniesCount == 0) {
            return;
        }

        var footerHtml = '<div class="company-search-more">';
        
        if (isMoreLinkNeeded) {
            footerHtml += '<a href="javascript:void(0)">More</a> ';
        }
            
        footerHtml += '<span class="company-counts">Showing ' + showingCompaniesCount + ' of ' + totalCompaniesCount + '</span></div>';

        $('#' + searchModalId).find("#subjectSearchResults").append(footerHtml);
        $(".company-search-more a").click(function () {
            $(".company-search-more").hide();
            companyListPage++;

            // Get needed companies
            // Prepend them to this DIV
            getCompanySearchData(function (companies) {
                addCompaniesToResults(companies);
            });
        });
    }

    var companyListPage = 0;
    this.bindToSearchOnChange = function () {
        // Bind to search initiating fields
        $('#' + searchModalId + " .searchOnChange").keyup(function () {
            if ($('#' + searchModalId + " .searchCompanyName").val().length < 3) return;

            getCompanySearchData(function (companies) {
                if ($(companies).length > 0)
                    $('#' + searchModalId).find("#subjectSearchResults").empty();
                else
                    $('#' + searchModalId).find("#subjectSearchResults").html('<div style="text-align: center; font-weight: bold; font-size: 13px; padding-top: 125px">No results found.</div>');

                companyListPage = 0;

                addCompaniesToResults(companies);
            });
        });
    }

    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(this.handleCompanyCreate);

    // Bind "No Match" selection
    $('#' + searchModalId + " #subjectSearchNoMatch").click(newSubjectCreated);

    this.bindToSearchOnChange();
}
