﻿var enterKeyButtonSearch = "";
var typeAheadParentID = "";
var typeAheadList = "#nameTypeAhead";
var AttorneyTypeAheadWS = "/FCWSite/HoganHartsonWS/HHWebServices.asmx";
var disableTypeAheadBlur = false;
// This must be one less than the actual minimum value since we are performing on the key down event
var minimumTypeAheadLength = 2; 
// USAGE
//$(document).ready(function() {
//
//Set up the Enter Search Button --
//       bindSearchButton(buttonID);
//
// Initialize Field Clear/Replace on focus/blur
//       InitializeTypeAhead(keywordTxtID, keywordTxtValue);
//
// Initialize Type Ahead and specific location and styling for TypeAhead Results Div
//       initializeTypeAhead(firstNameTxtID, firstNameTxtValue, "GetCompletionListFN", "#profsearch");
//
// Initialize Type Ahead and default location and styling for TypeAhead Results Div, or previously set location
//       initializeTypeAhead(lastNameTxtID, lastNameTxtValue, "GetCompletionListLN");
//
//       initializeTypeAhead(authorTxtID, authorTxtValue, "GetCompletionListAut", "#newssearch");
//});
function bindSearchButton(buttonID) {
    if (buttonID.indexOf("#") < 0) {
        buttonID = "#" + buttonID;
    }
    enterKeyButtonSearch = buttonID;
}
function initializeTypeAhead(fieldID, initialValue, operationName, parentID) {
    var currentInit = $(fieldID).attr("initialvalue");
    if (typeof (currentInit) == "undefined" || currentInit == "") {
        $(fieldID).attr("initialvalue", initialValue);
    }
    if (typeAheadParentID == "") {
        if (typeof (parentID) != "undefined") {
            typeAheadParentID = parentID;
        } else {
            typeAheadParentID = $(fieldID).parents("div[id]").attr("id");
            if (typeAheadParentID.indexOf("#") < 0) { typeAheadParentID = "#" + typeAheadParentID; }
        }
    }
    if (typeof (operationName) != "undefined") {
        bindTypeAhead(fieldID, operationName);
    }
    bindFocus(fieldID);
    bindBlur(fieldID);
}
function bindTypeAhead(fieldID, operationName) {
    $(fieldID).data("operation", operationName);
    $(fieldID).bind("keydown", function(event) {
        if (!isControlKey(event.keyCode)) {
            processTypeAhead(this, event.keyCode);
            return true;
        } else {
            return runControlKey(event.keyCode, this);
        }
    });
}
function bindFocus(fieldID) {
    $(fieldID).bind("focus", function() {
        clearTypeAhead();
        var initialValue = $(this).attr("initialvalue");
        var forceClear = false;
        if (typeof (initialValue) == "undefined" || initialValue == "") {
            forceClear = true;
        }
        if (forceClear || $(this).val() == initialValue) {
            $(this).val("");
        }
    });
}
function bindBlur(fieldID) {
    $(fieldID).bind("blur", function(event) {
        if (!disableTypeAheadBlur) {
            if ($(this).val() == "") {
                var initialValue = $(this).attr("initialvalue");
                if (typeof (initialValue) != "undefined" && initialValue != "") {
                    $(this).val(initialValue);
                }
            }
            clearTypeAhead();
        }
    });
}
function isControlKey(keyCode) {
    // 38 = up arrow
    if (keyCode == 38) { return true; }
    // 40 = down arrow
    if (keyCode == 40) { return true; }
    // 27  = esc key
    if (keyCode == 27) { return true; }
    // 13 = enter key
    if (keyCode == 13) { return true; }
    if (keyCode == 8) { return true; }
    if (((keyCode >= 48) && (keyCode <= 57)) ||  // Numbers 0-9
            ((keyCode >= 65) && (keyCode <= 90)) ||  // Upper case A-Z
            ((keyCode >= 97) && (keyCode <= 122)) ||  // Lower case a-z
            (keyCode == 189)) { // Hyphen
        return false;
    }
    return true;
}
function buildTypeAheadList(field, resultArray) {
    if ($(typeAheadList).length == 0) {
        $(typeAheadParentID).append("<div id='" + typeAheadList.replace("#", "") + "' class='typeaheadresults' onmouseout='enableblur();'></div>");
    }
    $(typeAheadList).data("field", field);
    var fieldPos = $(field).position();
    var displayX = fieldPos.left;
    var displayY = fieldPos.top;
    var fieldHeight = $(field).height();
    displayY += fieldHeight;
    var displayWidth = $(field).outerWidth()-2;
    $(typeAheadList).css("top", displayY).css("left", displayX).css("width", displayWidth).show();
    $(typeAheadList).empty();
    for (var i = 0; i < resultArray.length; i++) {
        $(typeAheadList).append("<div idx='" + i + "' onmouseover='mouseoverTA(this);' onclick='return mouseSelectTA(this);'><a href='#' onmouseover='mouseoverTA(this);' onclick='return mouseSelectTA(this);'>" + resultArray[i] + "</a></div>");
    }
}
function enableblur() {
    disableTypeAheadBlur = false;
}
function clearTypeAhead() {
    $(typeAheadList).empty();
    $(typeAheadList).hide();
}
function runControlKey(keyCode, field) {
    enableblur();
    var updateValue = 0;
    if (keyCode == 27) {
        clearTypeAhead();
        return false;
    }
    if (keyCode == 13) {
        if ($(typeAheadList).children().length == 0 && $(field).val() != $(field).attr("initialvalue")) {
            if (enterKeyButtonSearch != "") {
                $(enterKeyButtonSearch).click();
            }
        }
        if ($(typeAheadList).children(".selected").length > 0) {
            $($(typeAheadList).data("field")).val($(typeAheadList).children(".selected").text());
            clearTypeAhead();
        }
        return false;
    }
    if (keyCode == 38) { updateValue = -1; }
    if (keyCode == 40) { updateValue = 1; }
    var typeAheadLength = $(typeAheadList).children().length;
    if (typeAheadLength >= 1) {
        var currentSelected = -1;
        if ($(typeAheadList).children(".selected").length > 0) {
            currentSelected = new Number($(typeAheadList).children(".selected").attr("idx"));
        }
        $(typeAheadList).children(".selected[idx='" + currentSelected + "']").removeClass("selected");
        currentSelected += updateValue;
        if (currentSelected >= 0 && currentSelected <= typeAheadLength) {
            $(typeAheadList).children("[idx='" + currentSelected + "']").addClass("selected");
        }
    }
}
function mouseoverTA(TAField) {
    disableTypeAheadBlur = true;
    var taIdx = -1;
    if ($(TAField).is("div")) {
        taIdx = new Number($(TAField).attr("idx"));
    } else {
        taIdx = new Number($(TAField).parent().attr("idx"));
    }
    var typeAheadLength = $(typeAheadList).children().length;
    if (typeAheadLength >= 1) {
        var currentSelected = -1;
        if ($(typeAheadList).children(".selected").length > 0) {
            currentSelected = new Number($(typeAheadList).children(".selected").attr("idx"));
        }
        $(typeAheadList).children(".selected[idx='" + currentSelected + "']").removeClass("selected");
        currentSelected = taIdx;
        if (currentSelected >= 0 && currentSelected <= typeAheadLength) {
            $(typeAheadList).children("[idx='" + currentSelected + "']").addClass("selected");
        }
    }
}
function mouseSelectTA(TAField) {
    if ($(TAField).is("div")) {
        taIdx = new Number($(TAField).attr("idx"));
    } else {
        taIdx = new Number($(TAField).parent().attr("idx"));
    }
    if ($(typeAheadList).children(".selected").length > 0) {
        $($(typeAheadList).data("field")).val($(typeAheadList).children(".selected").text());
        clearTypeAhead();
    }
    enableblur();
    return false;
}
function processTypeAhead(field, keyCode, searchType) {
    if ($(field).val().length >= minimumTypeAheadLength) {
        var fieldValue = $(field).val();
        if (!isControlKey(keyCode)) {
            fieldValue += String.fromCharCode(keyCode);
        }
        var operation = $(field).data("operation");
        var ajaxData = createSoapCall(fieldValue, operation);
        $.ajax({
            async: true,
            type: "POST",
            datatype: "xml",
            url: AttorneyTypeAheadWS + "?op=" + operation,
            data: ajaxData,
            contentType: "text/xml; charset=utf-8",
            complete: function(xhr, status) {
                var dataString = new Array();
                try {
                    var responseTree = operation + "Response > " + operation + "Result > string";
                    if ($(xhr.responseXML).find(responseTree).length > 0) {
                        for (var i = 0; i < $(xhr.responseXML).find(responseTree).length; i++) {
                            dataString[i] = $(xhr.responseXML).find(responseTree)[i].childNodes[0].nodeValue;
                        }
                        buildTypeAheadList(field, dataString);
                    }
                } catch (ex) {
                    alert("search: " + ex.description);
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                clearTypeAhead();
//                        var errMsg = "";
//                        if (typeof (errorThrown) != "undefined") { errMsg += "error: " + errorThrown + "\n"; }
//                        if (typeof (textStatus) != "undefined") { errMsg += "status: " + textStatus + "\n"; }
//                        if (errMsg != "") {
//                            alert("search reqerr: " + errMsg);
//                        }
            }
        });
    } else {
        clearTypeAhead();
    }
}
function createSoapCall(searchString, operation) {
    var soapString = "";
    soapString += "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ";
    soapString += "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">";
    soapString += "<soap:Body>";
    soapString += "<" + operation + " xmlns=\"http://tempuri.org/\">";
    soapString += "<prefixText>" + searchString + "</prefixText>";
    soapString += "</" + operation + ">";
    soapString += "</soap:Body>";
    soapString += "</soap:Envelope>";
    return soapString;
}
