var advsearch = new Class({
	
	//Local variables
	ajaxSource: '../ajax/advsearch.ajax.php',
	updateResultsOnSelect: true,
	countryListID: 'country',
	stateListID: 'state',
	regionListID: 'region',
	activityListID: 'activity',
	
	//----------------------------------AJAX REQUESTS--------------------------------//
	
	initialize: function(searchPage) {
		this.updateResultsOnSelect = false;
		var _class = this;
		$$(".searchSelect").addEvent('change',function(){_class.update(this.id);});
		if ($defined($('searchSortField'))) {
			$('searchSortField').addEvent('change',_class.populateFilterDropDown.bind(_class));
			$('searchSortOrder').addEvent("change",_class.filterResults.bind(_class));
		}
		if ($defined($('findButton')))
			$('findButton').addEvent("click", _class.executeSearch.bind(_class));
		if ($defined($('resetForm')))
			$('resetForm').addEvent("click", function(){
				$('state').getChildren().dispose();
				$('state').grab(new Element("option", {value: "", text: "- All States -"}));
				$('adventureSearch').reset();
				_class.update("", false);
			});
		if ($defined($('pagenav')))
			$('pagenav').addEvent('change',function(){_class.newPage(this.value);});
		$$('.navLink').addEvent("click", function(e){if (e.target.get("alt") != null) _class.newPage(e.target.get("alt"));});
	},
	
	populateFilterDropDown: function(){
		var _class = this;
		filterFields = {price: 		{lowToHigh: "Low to High", highToLow: "High to Low", to100: "1 - 100", to500: "100 - 500", to1000: "500 - 1000", to3000: "1000 - 3000", to5000: "3000 - 5000", up: "5000 &amp; up"},
						difficulty:	{/*lowToHigh: "Easy to Hard", highToLow: "Hard to Easy", */easy: "Easy", moderate: "Moderate", intermediate: "Intermediate", difficult: "Difficult", extremelyDifficult: "Extremely Difficult"},
						duration:	{to1: "Less Than 1 Day", to3: "1 to 3 Days", to7: "4 to 7 Days", to15: "8 to 15 days", to21: "15 to 21 days", up: "More that 21 days"},
						outfitter:	{aZ: "A to Z", zA: "Z to A"}	}
		var field;
		switch ($('searchSortField').value) {
			case "price":
				field = filterFields.price;
				break;
			case "difficulty":
				field = filterFields.difficulty;
				break;
			case "duration":
				field = filterFields.duration;
				break;
			case "outfitter":
				field = filterFields.outfitter;
				break;
			default: return true;
		}
		$('searchSortOrder').getChildren().dispose();
		$('searchSortOrder').grab(new Element("option", {value: "", id: "chooseSort", text: "- Sort Order -"}));
		$H(field).each(function(title, value){$('searchSortOrder').grab(new Element("option", {value: value, html: title}));});
	},
	
	update: function(triggerfield, executeSearch){
		executeSearch = ($defined(executeSearch)) ? executeSearch : false;
		var postObj = {
			task: "update",
			country: $('country').value,
			state: (triggerfield == "country") ? "" : $('state').value,
			region: (triggerfield == "country") ? "" : $('region').value,
			activity: $('activity').value
		}
		var callback = (executeSearch) ? this.cb_updateAndExecute.bind(this) : this.cb_update.bind(this);
		this.request(postObj, callback);
	},
	
	searchQuery: function(country, state, region, activity) {
		var postObj = {
			task: "update",
			country: country,
			state: state,
			region: region,
			activity: activity
		}
		this.request(postObj, this.cb_updateAndExecute.bind(this));
	},
	
	searchVendor: function(partnerID) {
		var postObj = {
			task: "searchVendor",
			partnerID: partnerID
		}
		this.showAJAXLoading();
		this.request(postObj, this.cb_search.bind(this));
		return false;
	},
	
	executeSearch: function() {
		var postObj = {
			task: "search",
			dateStart: $('dateStart').value,
			dateEnd: $('dateEnd').value,
			country: $('country').value,
			state: $('state').value,
			region: $('region').value,
			activity: $('activity').value
		}
		this.showAJAXLoading();
		this.request(postObj, this.cb_search.bind(this));
		return false;
	},
	
	getPageInfo: function() {
		var postObj = {task: 'getPageInfo'}
		this.request(postObj, this.cb_pageInfo.bind(this));
	},
	
	newPage: function(page) {
		var _class = this;
		var postObj = {task: 'newPage', page: page};
		_class.showAJAXLoading();
		_class.request(postObj, this.cb_search.bind(this));
	},
	
	//------------------------------------POPULATE-----------------------------------//
	
	populateCountryList: function(countries, selectCountry) {
		var el = $(this.countryListID);
		el.getChildren().dispose();
		el.adopt(new Element("option", {value: "", html: "- All Countries -"}));
		$H(countries).each(function(country){
			var option = new Element("option", {value: country, id: "_c_"+country, html: country});
			if (country == selectCountry)
				option.set('selected','selected');
			el.adopt(option);
		});
	},
	
	populateStateList: function(states, selectState) {
		var el = $(this.stateListID);
		el.getChildren().dispose();
		var countriesWithStates = ["United States","Canada",""];
		el.adopt(new Element("option", {value: "", html: (countriesWithStates.contains($(this.countryListID).value)) ? "- All States -" : "- N/A -"}));
		if ($(this.countryListID).value == "")
			el.adopt(new Element("option", {value: "", text: "(please select a country first)", disabled: "disabled", styles: {"font-style": "italic"}}));
		$H(states).each(function(state, id){
			var option = new Element("option", {value: id, id: "_c_"+id, html: state});
			if (id == selectState)
				option.set('selected','selected');
			el.adopt(option);
		});
	},
	
	populateRegionList: function(regions, selectRegion) {
		var el = $(this.regionListID);
		el.getChildren().dispose();
		var countriesWithStates = ["United States","Canada",""];
		el.adopt(new Element("option", {value: "", html: "- All Regions -"}));
		if ($(this.countryListID).value == "")
			el.adopt(new Element("option", {value: "", text: "(please select a country first)", disabled: "disabled", styles: {"font-style": "italic"}}));
		else if ((countriesWithStates.contains($(this.countryListID).value)) && $(this.stateListID).value == "")
			el.adopt(new Element("option", {value: "", text: "(please select a state first)", disabled: "disabled", styles: {"font-style": "italic"}}));
		$H(regions).each(function(region, id){
			var option = new Element("option", {value: id, id: "_c_"+id, html: region});
			if (id == selectRegion)
				option.set('selected','selected');
			el.adopt(option);
		});
	},
	
	populateActivityList: function(activities, selectActivity) {
		var el = $(this.activityListID);
		el.getChildren().dispose();
		el.adopt(new Element("option", {value: "", html: "- All Activities -"}));
		$H(activities).each(function(activity, id){
			var option = new Element("option", {value: id, id: "_c_"+id, html: activity});
			if (id == selectActivity)
				option.set('selected','selected');
			el.adopt(option);
		});
	},
	
	filterVendor: function(partnerID) {
		var _class = this;
		var postObj = {
			task: "searchVendor",
			partnerID: partnerID,
			field: $('searchSortField').value,
			order: $('searchSortOrder').value
		}
		if ($defined($('chooseSort'))) $('chooseSort').dispose();
		this.showAJAXLoading();
		this.request(postObj, _class.cb_search.bind(this));
	},
	
	filterResults: function(){
		var _class = this;
		var postObj = {
			task: "filterResults",
			field: $('searchSortField').value,
			order: $('searchSortOrder').value,
			country: ($defined($('country')) ? $('country').value : ""),
			state: ($defined($('state')) ? $('state').value : ""),
			region: ($defined($('region')) ? $('region').value : ""),
			activity: ($defined($('activity')) ? $('activity').value : "")
		}
		if ($defined($('chooseSort'))) $('chooseSort').dispose();
		this.showAJAXLoading();
		this.request(postObj, _class.cb_search.bind(this));
	},
	
	//------------------------------------UTILITIES----------------------------------//

	setupVendor: function(partnerID) {
		var _class = this;
		$('searchSortOrder').removeEvents("change");
		$('searchSortOrder').addEvent("change", function(){_class.filterVendor(partnerID);}.bind(this));
	},

	request: function(postObj, callback){
		new Ajax(this.ajaxSource, {method: 'post', data: postObj, onComplete: callback}).request();
	},
	
	showAJAXLoading: function(){
		$('searchResults').set("html",'<div id="ajaxLoading"><img src="image/big-ajax-spinner.gif" alt="loading" /></div>');
	},
	
	submitResults: function() {
		var url = '?a=bya&c=setquery&country='+$('country').value+'&state='+$('state').value+'&region='+$('region').value+'&activity='+$('activity').value;
		window.location = url;
	},
	
	buildAdventureDiv: function(adv, isFirst) {
		var div = $(new Element("div", {"class": (isFirst ? "searchItem first" : "searchItem"), id: "s_"+adv.id})).adopt(
			new Element("div", {"class": "borderOverlay hide", text: " "}),
			new Element("img", {"src": adv.photoURL, "class": "advPhoto"}),
			new Element("img", {"src": "image/searchoverlay3.png", "class": "advOverlay"}),
			$(new Element("div", {"class": "advHeader"})).adopt(
				new Element("span", {"class": "title", html: adv.title}),
				new Element("span", {"class": "outfitter", id: "o_"+adv.partnerID, html: "by "+adv.outfitter})
			),
			$(new Element("div", {"class": "advFooter"})).adopt(
				new Element("span", {"class": "advLocationPrice", html: adv.locationString+"<br/>"+adv.priceString})
			)
		);
		return div;
	},
	
	setupPageNav: function(currentPage, maxPage) {
		$$('.currentPage').set("text", currentPage);
		$$('.gotoFirst').set("alt", 1);
		$$('.gotoLast').set("alt", maxPage);
		var prevPage = (parseInt(currentPage) > 1) ? parseInt(currentPage) - 1 : "";
		$$('.gotoPrevNumber').set({alt: prevPage, text: prevPage});
		$$('.gotoPrev').set("alt", prevPage);
		var nextPage = (parseInt(currentPage) < maxPage) ? parseInt(currentPage) + 1 : "";
		$$('.gotoNextNumber').set({alt: nextPage, text: nextPage});
		$$('.gotoNext').set("alt", nextPage);
	},
	
	//----------------------------------AJAX CALLBACKS-------------------------------//
	
	cb_update: function(data) {
		//console.log(data); return false;
		var _class = this;
		var obj = eval(data);
		if (!$defined(obj.success) || obj.success != 'true') {
			alert("Error: "+($defined(obj.error) ? obj.error : "Serverside error"));
			return false;
		} else {
			_class.populateCountryList(obj.countries, obj.request.country);
			_class.populateStateList(obj.states, obj.request.state);
			_class.populateRegionList(obj.regions, obj.request.region);
			_class.populateActivityList(obj.activities, obj.request.activity);
			if (this.updateResultsOnSelect)
				this.executeSearch();
		}
	},
	
	cb_updateAndExecute: function(data) {
		var _class = this;
		_class.cb_update(data);
		_class.executeSearch();
	},
	
	cb_search: function(data) {
		var _class = this;
		var obj = JSON.decode(data);
		$('searchResults').getChildren().dispose();
		if (obj.results.length == 0) {
			$('searchResults').grab(new Element("div", {"class": "searchNoData", text: "No Adventures Found"}));
		} else {
			for (i = 0; i < 9 && i < obj.results.length; i++) {
				var isFirst = ((i + 3) % 3 == 0);
				$('searchResults').grab(_class.buildAdventureDiv(obj.results[i], isFirst));
			}
			$$('.searchItem').addEvent("click", function(e){
				if (e.target.get("class") == "outfitter")
					window.location = "?a=vendorprofile&id="+e.target.id.substring(2);
				else
					window.location = "?a=viewadv&id="+e.target.getParent("div.searchItem").id.substring(2);
			});
			$$('.searchItem').addEvent("mouseover", function(e){this.getElement(".borderOverlay").removeClass("hide");});
			$$('.searchItem').addEvent("mouseout", function(e){this.getElement(".borderOverlay").addClass("hide");});
			
		}
		$('searchSettings').setStyle("display", "block");
		$$('.searchPages').setStyle("display", (obj.results.length == 0 ? "none" : "block"));
		$('searchTotalString').set("html", "Total Results: "+obj.totalResults);
		_class.setupPageNav(obj.currentPage, obj.maxPage);
	}
	
});