var userAgent = navigator.userAgent.toLowerCase();
var usingJWebUnit = /jwebunit/.test( userAgent );

if(!usingJWebUnit){

var jsonparserCallback;
AJS.toInit(function ($) {
    var attr = {
        cache_size: 30,
        max_length: 1,
        effect: "appear" // TODO: add "fade" effect
    };
    var dd,
        cache = {},
        cache_stack = [],
        timer,
        timeout_timer;
    var hider = function (list) {
         $("a span", list).each(function () {
            var $a = $(this);
            this.realhtml = this.realhtml || $a.html();
            var words = this.realhtml.split(" ");
            $a.html("<label>" + words.join("</label><label> ") + "</label>");
            var elpss = AJS("var");
            elpss.html("&#8230;");
            $a.append(elpss);
            this.elpss = elpss;
            
            var elwidth = $a[0].elpss[0].offsetWidth,
                width = $a[0].parentNode.parentNode.parentNode.parentNode.offsetWidth,
                isLong = false;
            $("label", $a).each(function (i) {
                var $word = $(this);
                if (isLong) {
                    $word.hide();
                } else {
                    $word.show();
                    if (this.offsetLeft + this.offsetWidth + elwidth > width) {
                        $word.hide();
                        isLong = true;
                    }
                }
            });
            $a[0].elpss[isLong ? "show" : "hide"]();
        });
    };
    var searchBox = $("#quick-search-query");
    if ($.browser.safari) {
        searchBox[0].type = "search";
        searchBox[0].setAttribute("results", 10);
        searchBox[0].setAttribute("placeholder", "search");
    }

    var jsonparser = function (json, resultStatus) {
    	clearTimeout(timeout_timer);
    	var matches = json.statusMessage ? [[{html: json.statusMessage, className: "error"}]] : json.contentNameMatches;        

    	if (!cache[searchBox.oldval] && resultStatus == "success") {
        	cache[searchBox.oldval] = json;
            cache_stack.push(searchBox.oldval);
            if (cache_stack.length > attr.cache_size) {
                delete cache[cache_stack.shift()];
            }
    	}
    	
		var old_dd = dd;
		dd = AJS.dropDown(matches)[0];
        dd.$.attr("id", "quick-nav-drop-down").addClass("aui-dropdown"); // FE/CRU 2.2 quirk.

        dd.onhide = function (causer) {
			if (causer == "escape") {
				searchBox.focus();
			}
		};
		var spans = $("span", dd.$);
		for (var i = 0, ii = spans.length -1; i < ii; i++) {
			(function () {
	        	var $this = $(this),
	        	html = $this.html();
	        	// highlight matching tokens
	        	html = html.replace(new RegExp("(" + json.queryTokens.join("|") + ")", "gi"), "<strong>$1</strong>");
	        	$this.html(html);
	        }).call(spans[i]);
	    }
        hider(dd.$);
        dd.hider = function () {
            hider(dd.$);
        };
        AJS.onTextResize(dd.hider);
        if (old_dd) {
            dd.show();
            dd.method = attr.effect;
            AJS.unbindTextResize(old_dd.hider);
            old_dd.$.remove();
        } else {
            dd.show(attr.effect);
        }
    };

	jsonparserCallback = jsonparser;

    searchBox.oldval = searchBox.val();
    (function () {
        var val = searchBox.val();

        if (val != searchBox.oldval) {
            searchBox.oldval = val;
            if (!searchBox.hasClass("placeholded")) {
                clearTimeout(timer);

                if (/[\S]{2,}/.test(val)) {
                    timer = setTimeout(function () {
                        if (cache[val]) {
                            jsonparser(cache[val]);
                        } else {
                            timeout_timer = setTimeout(function () {
                            	jsonparser({statusMessage: "Timeout"}, true);
                            }, 5000);

					        AJS.$.getScript(studioData.jiraUrl+"/plugins/servlet/studio/quicknav?query=" + AJS.escape(val) + "&callback=jsonparserCallback&studio=true&searchAllUrl="+AJS.escape(studioData.jiraUrl+"/secure/StudioSearch.jspa?query="+val)+"&userProfileUrl="+AJS.escape(studioData.jiraUrl+"/secure/ViewProfile.jspa?name="));
//			                AJS.$.getJSON(contextPath + "/json/contentnamesearch.action?query=" + AJS.escape(val), jsonparser);
                        }
                    }, 400);
                } else {
                    dd && dd.hide();
                }
            }
        }
        setTimeout(arguments.callee, 0);
    })();
});
}