﻿var searchAjaxTimeout;
var restSearchRequest;

function SubjectSearch(searchModalId, existingSubjectSelected, newSubjectCreated, isUserOnlySearch, displayUserIcon, includeTLCount) {
    this.searchModalId = searchModalId;
    this.existingSubjectSelected = existingSubjectSelected;
    this.newSubjectCreated = newSubjectCreated;

    $("#" + this.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() {
        $('#subjectSearchResults').html('');
        $('.searchOnChange').val('');
        this.bindToSearchOnChange();
        $("#" + this.searchModalId).dialog("open");
    }

    // Hide subject search modal
    this.hide = function() {
        $("#" + this.searchModalId).dialog("close");
    }

    this.handleCompanyCreate = function(sender, args) {
        try {
            if (sender._postBackSettings.sourceElement.id == $(".SubjectSearchActionLink")[0].id) {
                newSubjectCreated($(".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;
    }

    this.bindToSearchOnChange = function() {
        // Bind to search initiating fields
        $(".searchOnChange").keyup(function() {
            if ($(".searchCompanyName").val().length < 3) return;
            if (searchAjaxTimeout != null) clearTimeout(searchAjaxTimeout);

            searchAjaxTimeout = setTimeout(function() {
                restGetUrl = 'rest/Company.svc/'
                    + ((includeTLCount) ? 'includeTLCount' : '')
                    + '?name=' + URLEncode($(".searchCompanyName").val())
                    + '&address=' + URLEncode($(".searchAddress1").val())
                    + '&city=' + URLEncode($(".searchCity").val())
                    + '&region=' + URLEncode($(".searchRegion").val())
                    + '&postalCode=' + URLEncode($(".searchPostalCode").val())
                    + '&isUserSearch=' + isUserOnlySearch.toString();

                if (restSearchRequest != null) restSearchRequest.abort();

                $("#subjectSearchResults").html('<div style="text-align: center; padding-top: 125px"><img src="Assets/Images/loading.gif" alt="Loading..." /></div>');
                restSearchRequest = $.ajax({
                    url: restGetUrl,
                    type: 'GET',
                    dataType: 'json',
                    timeout: 8000,
                    error: function(error) {
                        alert('Could not search companies.');
                    },
                    success: function(companies) {                       
                        if ($(companies).length > 0) 
                            $("#subjectSearchResults").empty();
                        else 
                            $("#subjectSearchResults").html('<div style="text-align: center; font-weight: bold; font-size: 13px; padding-top: 125px">No results found.</div>');
                        
                        $(companies).each(function(i) {
                            companyHtml = '<div style="clear: both"><div style="float: left">'
                                + companies[i].Name
                                + ((displayUserIcon && companies[i].ActiveUserCount > 0) ? ' &nbsp;<a href="javascript:void(0)"><img src="Assets/Images/anscersUser.png" alt="anscers User" title="anscers User" style="position: relative; top: 1px" /></a> ' : ' ')
                                + ((includeTLCount) ? '(' + companies[i].TradeLineCount + ' trade lines)' : '')
                                + '<br />'
                                + companies[i].Address
                                + '<br />'
                                + companies[i].City + ', ' + companies[i].Region + ' ' + companies[i].PostalCode + ' ' + (($.trim(companies[i].Country.toLowerCase()) != 'usa') ? companies[i].Country : '')
                                + '</div><div style="float: right"><input type="button" class="btn subjectSelectButton' + companies[i].Id + '" value="Select" id="subjectSelect' + i + '" /></div></div><hr />';

                            $("#subjectSearchResults").append(companyHtml);
                            $("#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);
                            });
                        });

                        searchAjaxTimeout = null;
                    }
                });
            }, 500);
        });
    }

    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(this.handleCompanyCreate);

    // Bind "No Match" selection
    $("#subjectSearchNoMatch").click(newSubjectCreated);

    this.bindToSearchOnChange();
}