var PECOSSearch = Class.create({
	initialize: function(inputForm, tableResults, resultsHelp){
		this.inputForm = inputForm;
		this.tableResults = tableResults;
		this.resultsHelp = resultsHelp;
		
		this.inputQuery = this.inputForm.down("input[name=q]");
		this.inputSubmit = this.inputForm.down("input[type=submit]");
		this.tableResultsHead = this.tableResults.down("thead");
		this.tableResultsBody = this.tableResults.down("tbody");
		this.tableResultsFoot = this.tableResults.down("tfoot");
		this.query = "";
		this.pageIndex = 1;
		
		this.tableResults.hide();
		this.resultsHelp.hide();
		
		this.inputForm.observe("submit", function(event){
			Event.stop(event);
			this.inputQuery.prototip.hide();
			this.query = $F(this.inputQuery);
			this.pageIndex = 1;
			this.doSearch();
		}.bind(this));
		
		new Tip(this.inputQuery, '<strong>Tip:</strong> Include a two-letter state abbreviation to limit result by state.', {stem: 'topMiddle', hook: {target: 'bottomMiddle', tip: 'topMiddle'}, offset:{x: 0, y: 0}, hideOthers: true});
		
		if ($F(this.inputQuery) != "") {
			this.inputSubmit.click();
		}
	},
	userID: '',
	doSearch: function(){
		if (Ajax.activeRequestCount <= 1) {
			if (this.query.strip().length > 2 || this.userID != '') {
				new Ajax.Request("pecos/service.asp", {
					method: "post",
					parameters: {
						q: this.query,
						p: this.pageIndex,
						u: this.userID
					},
					onCreate: function(){
						this.inputSubmit.value = "Searching..."
						this.inputSubmit.disabled = true;
					}.bind(this),
					onSuccess: function(transport){
						if (transport.responseJSON.searchResponse) {
							// Results were returned
							this.tableResults.className = "";
							this.tableResultsBody.childElements().invoke("remove");
							
							var searchResponse = transport.responseJSON.searchResponse;
							
							// Display results
							if (searchResponse.info.queryMode == "NPI") {
								// Exact NPI match found
								this.tableResultsBody.appendChild(this.createResultNode(searchResponse.results.result, "Result"));
							} else {
								// Name matches found
								if (Object.isArray(searchResponse.results)) {
									searchResponse.results.each(function(s){
										this.tableResultsBody.appendChild(this.createResultNode(s, "Result"));
									}.bind(this));
								} else {
									this.tableResultsBody.appendChild(this.createResultNode(searchResponse.results.result, "Result"));
								}
							}
							
							this.tableResultsHead.down("td").update("Result" + (Object.isArray(searchResponse.results) ? "s" : ""));
							this.tableResultsHead.show();
							
							// Display pager if necessary
							if (searchResponse.info.pageCount > 1) {
								var rowIndexStart = (((searchResponse.info.pageIndex - 1) * searchResponse.info.pageSize) + 1);
								var rowIndexEnd = (((searchResponse.info.pageIndex - 1) * searchResponse.info.pageSize) + searchResponse.info.pageSize);
								rowIndexEnd = rowIndexEnd < searchResponse.info.rowCount ? rowIndexEnd : searchResponse.info.rowCount;
								this.tableResultsFoot.down("td").update(
									(searchResponse.info.pageIndex > 1 ? "<a href=\"javascript:void(0);\" class=\"pecos-search-results-prev\">Previous</a> | " : "") +
									"Results " + rowIndexStart + " - " +  rowIndexEnd + " of " + searchResponse.info.rowCount +
									(searchResponse.info.pageIndex < searchResponse.info.pageCount ? " | <a href=\"javascript:void(0);\" class=\"pecos-search-results-next\">Next</a>" : "")
								);
								this.tableResultsFoot.show();
							} else {
								this.tableResultsFoot.hide();
							}
							
							// Bind result events
							this.tableResultsFoot.select(".pecos-search-results-prev").each(function(s){
								s.observe("click", function(){
									this.pageIndex--;
									this.doSearch();
								}.bind(this));
							}.bind(this));
							this.tableResultsFoot.select(".pecos-search-results-next").each(function(s){
								s.observe("click", function(){
									this.pageIndex++;
									this.doSearch();
								}.bind(this));
							}.bind(this));
							
							this.inputForm.show();
							this.tableResults.show();
							this.resultsHelp.show();
						} else {
							// No matches found
							this.tableResults.className = "";
							this.tableResults.addClassName("pecos-search-result-none");
							this.tableResultsBody.childElements().invoke("remove");
							this.tableResultsBody.appendChild(this.createResultNode(null, "NoResults"));
							this.tableResultsHead.hide();
							this.tableResultsFoot.hide();
							this.tableResults.show();
							this.resultsHelp.hide();
						}
						
						try {
							pageTracker._trackPageview("/pecos/default.asp");
							pageTracker._trackEvent("PECOS", "Search", this.query);
						} catch(err) {}
					}.bind(this),
					onComplete: function(transport){
						this.inputSubmit.disabled = false;
						this.inputSubmit.value = "Search"
					}.bind(this)
				});
			}
		}
	},
	createResultNode: function(result, type){
		switch(type) {
			case "NoResults":
				var tdMessage = new Element("td").addClassName("pecos-search-result-name").update("No results found.");
				var trResult = new Element("tr");
				trResult.appendChild(tdMessage);
				return trResult;
				break;
			case "Result":
				var tdName = new Element("td").addClassName("pecos-search-result-meta").addClassName(result.is_pecos_enrolled == "yes" ? "precos-search-result-enrolled" : "precos-search-result-not-enrolled").update("<span class='pecos-search-result-name'>" + result.name + "</span> <span class='pecos-search-result-location'>" + result.location + "</span>");
				if (result.is_pecos_pending_review == "yes") { tdName.down('span.pecos-search-result-location').addClassName('precos-search-result-pending-review'); }
				var tdNPI = new Element("td").addClassName("pecos-search-result-npi").update("<a href=\"javascript:void(0);\">" + result.npi + "</a>");
				var trResult = new Element("tr");
				trResult.appendChild(tdName);
				trResult.appendChild(tdNPI);
				new Tip(tdNPI.down('a'), {title: result.name + ' (' + result.npi + ')', ajax:{url: 'pecos/service.asp?id=' + result.npi}, stem: 'rightMiddle', hook: {target: 'leftMiddle', tip: 'rightMiddle'}, offset:{x: 16, y: 0}, hideOthers: true, showOn: 'click', hideOn: {element: 'closeButton', event: 'click'}, closeButton: true, width: 400});
				return trResult;
				break;
		}
	}
});
