﻿// Add the suggest boxes to textboxes that have been loaded to the page
Event.observe(window, "load", function() {

    //look for textboxes with custom "suggest" attribute
    $$("input[suggest=true]").each(function(tb) {
        var filter = (tb.readAttribute("filter") || "all"); //custom attribute for filter
        var len = 2;
        if (tb.id.indexOf("State")>-1) len = 1;
        new FadSuggest.SuggestBox($(tb), {
	        cssClass : "suggestions", highlightedClass: "highlighted",
	        minWordLength: len, remotePage : "/findadoc/json.aspx?filter="+filter,
	        calcAdditionalQuery : function() {
				var retQStr = "";
				var cbxs = $$("input[type=checkbox]");
				if (cbxs.length > 0 && cbxs[0].id.indexOf("cbxCCPA")>-1 && cbxs[0].checked)
					retQStr = "&ccpa=1";

				return retQStr;
	        }
        });
        if (tb.id.indexOf("Query")>-1) tb.focus(); //give focus to top txtbx
    });

    //handle the "any" fields; not checking for 'any' class b/c don't want that present if can't be removed through js
	$$("input[any=true]").each(function(tb) {
	    tb.value = "Any";
        tb.addClassName("any");

		Event.observe(tb, "focus", function() {
		    if (isAny(tb.value)) {
		        tb.value = "";
		        tb.removeClassName("any");
		    }
		});
		Event.observe(tb, "blur", function() {
		    if (tb.value == "" || isAny(tb.value)) {
		        tb.value = "Any";
		        tb.addClassName("any");
		    }
		});
	});
});

function isAny(str) {
	var re = /\s*any\s*/i;
	return re.test(str);
}

function validateSearch(oSrc, args) {
	// issues with IE9 and prototype are causing $$ to fail to find any fields... count # of fields
    var fieldCount = 0,
		validCount = 0;

    //check all text boxes in fad form
	$$("#fad table.form input[type=text]").each(function (tb) {
		fieldCount++;
	    if (tb.value.length > 0 && !isAny(tb.value))
			validCount++;
	});

	//if we didn't find any fields (IE9), allow form to be submitted; otherwise, need at least 1 valid field
    var returnVal = (fieldCount == 0 || validCount > 0);

    args.IsValid = returnVal;
    return returnVal;
}

