function Auctions() {
	this.urlbase = "http://www.trocadero.com/php/";
	//this.urlbase = "http://192.168.0.206/"

	this.auctions = {};
	this.auctionItemLists = {};
	this.auctionItemCounts = {};
	this.auctionItemBuckets;
	this.page = 1;
	this.maxPages = 1;
	this.itemsPerPage = 16;

	this.sort_field = 'title';
	this.sort_asc = true;
	
	this.hideNvOnClear = 0;
	
	/*
	$('pn-first').observe('click', this.prevPage.bind(this, -1));
	$('pn-prev').observe('click', this.prevPage.bind(this, 0));
	$('pn-next').observe('click', this.nextPage.bind(this, 0));
	$('pn-last').observe('click', this.nextPage.bind(this, -1));
	*/
	
	/*
	//CSS and DOM is a pain
	var headerElems = new Array();
	$('auction-list-header').childElements().each(function (elem) { headerElems.push(elem); });
	$('auction-list-header').update("");
	headerElems.each(function (elem) { $('auction-list-header').appendChild(elem); });
	*/
}

Auctions.prototype = {
	initialize: function() {
		/*
		$('auction-sort-title').observe('click', this.sortAuctions.bind(this, 'title'));
		$('auction-sort-lots').observe('click', this.sortAuctions.bind(this, 'lots'));
		$('auction-sort-close').observe('click', this.sortAuctions.bind(this, 'endtime'));
		$('auction-sort-group').observe('click', this.sortAuctions.bind(this, 'group'));
		
		this.auctionsPerPage = 16;
		this.search();
		*/
	},
	
	testload: function() {
	},

	clearSearch: function() {
	},
	updateNowViewing: function() {
	},
	
	searchKeyword: function() {
	},
	
	search: function() {
		/*
		var kw = this.keywords.join("|||");
		var cat = this.categories.join("|||");
		var dlr = this.dealers.join("|||");
		var grp = this.groups.join("|||");
		var auc = this.showAuctions;
		var sale = this.showSales;
		*/
		var data = encodeURIComponent("method=getUpcomingAuctions");
		
		//this.updateNowViewing();
		this.waitForData();
		
		// Get the item list from the server		
		var ajax = new jXHR();
		ajax.onerror = function (msg,url) {
			var message = msg;
			alert(msg);
		};
		ajax.onreadystatechange = function(result){
			if (ajax.readyState === 4) {
				if (result != null) {
					this.auctions = result;
					this.sort_field = "";
					this.sort_asc = true;
					this.populateAuctionsData();
				}
			}
		}.bind(this);
		
		ajax.open("GET", this.urlbase + "json/Auction.php?callback=?&data=" + data);
		ajax.send();
	},
	
	populateAuctionsData: function() {
		var auctionIds = [];
		this.auctions.each(function (auction) {
			auctionIds.push(auction.id);
		});
		
		var data = "method=listMultiAuctionItems" + "&auctionids=" + auctionIds.join(",");
		
		// Get the information for each item we want to view		
		var ajax = new jXHR();
		ajax.onerror = function (msg,url) {
			var message = msg;
			alert(msg);
		};
		ajax.onreadystatechange = function(result){
			if (ajax.readyState === 4) {
				if (result != null) {
					this.auctionItemData = [];
					result.each(function (itemAucData) {
						this.auctionItemData.push(itemAucData);
					}.bind(this));
					this.buildAuctionThumbs();
					
					this.sortAuctions("endtime");
					this.updateNav();
					this.showPage(1);
				}
			}
		}.bind(this);
		
		ajax.open("GET", this.urlbase + "json/AuctionItem.php?callback=?&data=" + data);
		ajax.send();
	},
	
	buildAuctionThumbs: function() {
		this.auctionItemBuckets = new Hash();
		this.auctionItemData.each(function (itemAucData) {
			var aucId = itemAucData.auction_id;
			var bkt = new Hash();
			if (this.auctionItemBuckets.get(aucId) != undefined) { bkt = this.auctionItemBuckets.get(aucId); }
			bkt.set(itemAucData.item_id, itemAucData);
			this.auctionItemBuckets.set(aucId, bkt);
		}.bind(this));
		
		this.auctionItemBuckets.each(function (auction) {
			var aucId = auction.key;
			var itemList = auction.value;
			this.auctionItemCounts[aucId] = 0;
			
			//Keep track of the items we want to display
			var selected_ids = [];
			
			//The meat of our algorithm
			var selected_storenames = [];
			var items_skipped = true;
			var items_added = false;
			while (selected_ids.size() < 7 && items_skipped) {
				items_skipped = false;
				items_added = false;
				itemList.each(function (item) {
					var itemId = item.key;
					var itemAucData = item.value;
					if (selected_ids.indexOf(itemId) != -1)
						return;
					if (selected_storenames.indexOf(itemAucData.storeName) != -1) {
						items_skipped = true;
						return;
					}
					
					if (selected_ids.size() < 7) {
						selected_ids.push(itemId);
						selected_storenames.push(itemAucData.storeName);
						items_added = true;
						this.auctionItemCounts[aucId]++;
					}
				}.bind(this));
				if (!items_added)
					selected_storenames = [];
			}
			
			//Now we've populated selected_ids, loop over them and build the links
			this.auctionItemLists[aucId] = '';
			selected_ids.each(function (id) {
				itemAucData = itemList.get(id);
				//var itemLink = '<a href="http://www.trocadero.com/' + itemAucData.storeName + '/items/' + itemAucData.item_id + '/item' + itemAucData.item_id + '.html">' + itemAucData.itemName + '</a>, ';
				var img = 'http://www.' + (itemAucData.isTroc == "true" ? 'trocadero' : 'cyberattic') + '.com/stores/' + itemAucData.storeName + '/items/' + itemAucData.item_id + '/thumb.jpg';
				var href = '';
				if (itemAucData.isTroc == "true") {
					var href = 'http://www.trocadero.com/' + itemAucData.storeName + '/items/' + itemAucData.item_id + '/item' + itemAucData.item_id + '.html';
				} else {
					var href = 'http://www.cyberattic.com/stores/' + itemAucData.storeName + '/items/' + itemAucData.item_id + '/item' + itemAucData.item_id + 'cyberattic.html';
				}
				var itemLink = '<a href="' + href + '"><img src="' + img + '" title="' + itemAucData.itemName + '" /></a>';
				this.auctionItemLists[aucId] = this.auctionItemLists[aucId] + itemLink;
			}.bind(this));
		}.bind(this));
	},
	
	/*
	populateCategoryData: function() {
		if (this.groups.length == 0 || this.groups.length > 1)
			return;
		
		var data = "method=listGroupCategories" + "&groupname=" + this.groups[0];
		var ajax = new jXHR();
		ajax.onerror = function (msg,url) {
			var message = msg;
			alert(msg);
		};
		ajax.onreadystatechange = function(result){
			if (ajax.readyState === 4) {
				if (result != null) {
					this.categoryList = new Hash();
					result.each(function (groupcat) {
						var catName = groupcat.categoryName;
						var cat = catName.split(":");
						var arr = this.categoryList;
						if (cat == "") return;
						cat.each(function(c) {
							if (arr.get(c) == undefined)
								arr.set(c, new Hash());
							arr = arr.get(c);
						});
					}.bind(this));
					$('sidebar-categories').show();
					$('sidebar-categories-browse').update("");
					this.displayCategories($('sidebar-categories-browse'), '', this.categoryList, 0);
				}
			}
		}.bind(this);
		
		ajax.open("GET", this.urlbase + "json/GroupCategory.php?callback=?&data=" + data);
		ajax.send();
	},
	displayCategories: function(parentElement, parentCat, categoryArray, depth) {
		categoryArray.each(function (cat) {
			var fullCatName = parentCat + (parentCat != '' ? ":" : "") + cat[0];
			var fcnid = fullCatName.replace(/ /g, "_");
			var div = new Element("div", { id : fcnid + '-wrap' });
			div.style.padding = "0px 0px 0px " + (10 * depth) + "px";
			if (depth > 0)
				div.hide();
			
			var exp = new Element("span", { id : fcnid + '-viz', class : 'catExpand' });
			if (cat[1].size() > 0) {
				exp.update(" + ");
				exp.observe('click', this.showHideCategory.bind(this, fcnid));
			} else {
				exp.update("");
			}
			
			var a = new Element("a");
			a.update(cat[0]);
			a.href = "javascript:return false;";
			a.observe('click', this.searchCategory.bind(this, fullCatName));
			
			div.appendChild(exp);
			div.appendChild(a);
			parentElement.appendChild(div);
			this.displayCategories(div, fullCatName, cat[1], depth + 1);
		}.bind(this));
	},
	showHideCategory: function(catName) {
		var show = ($(catName + '-viz').innerHTML == " + ");
		$(catName + '-wrap').select("div").each(function (div) {
			if (show)
				div.show();
			else
				div.hide();
		});
		$(catName + '-viz').update(show ? " - " : " + ");
	},
	*/
	
	updateNav: function() {
		if (this.auctions.length == undefined) { this.auctions = []; }
		this.maxPages = Math.ceil(this.auctions.length / this.itemsPerPage);
		$('totalPages').update(this.maxPages);
		
		if (this.maxPages == 0) { $('page-nav').hide(); }
						   else { $('page-nav').show(); }
	},
	updateNavArrows: function() {
		var first = (this.page == 1);
		var last = (this.page == this.maxPages);
		
		if (first) {
			$('pn-first').removeAttribute("href");
			$('pn-prev').removeAttribute("href");
		} else {
			$('pn-first').setAttribute("href", "#");
			$('pn-prev').setAttribute("href", "#");
		}
		if (last) {
			$('pn-next').removeAttribute("href");
			$('pn-last').removeAttribute("href");
		} else {
			$('pn-next').setAttribute("href", "#");
			$('pn-last').setAttribute("href", "#");
		}
		/*
		$('pn-first').setAttribute("href", (first ? "" : "#"));
		$('pn-prev').setAttribute("href", (first ? "" : "#"));
		$('pn-next').setAttribute("href", (last ? "" : "#"));
		$('pn-last').setAttribute("href", (last ? "" : "#"));
		*/
	},
	prevPage: function(goFirst) {
		if (goFirst == -1)
			this.showPage(1);
		else
			this.showPage(this.page - 1);
	},
	nextPage: function(goLast) {
		if (goLast == -1)
			this.showPage(this.maxPages);
		else
			this.showPage(this.page + 1);
	},
	
	
	waitForData: function() {
		var auctionListHeader = $('auction-list-header').remove();
		$('auctions-list').update("");
		$('auctions-list').appendChild(auctionListHeader);

		var auctionListRow = new Element("div");
		var auctionListNoitem = new Element("div");
		auctionListNoitem.addClassName("auction-list-noitem");
		auctionListNoitem.update("Please wait...");
		auctionListRow.appendChild(auctionListNoitem);			
		$('auctions-list').appendChild(auctionListRow);
		
		return;
	},
	
	showPage: function(pageNum) {
		if (pageNum == undefined) { pageNum = this.page; }
		if (pageNum < 1)
			pageNum = 1;
		if (pageNum > this.maxPages)
			pageNum = this.maxPages;
		
		this.page = pageNum;
		$('currPage').update(this.page);
		
		var auctionListHeader = $('auction-list-header').remove();
		$('auctions-list').update("");
		$('auctions-list').appendChild(auctionListHeader);
		
		//Special Case for No Items
		if (this.auctions.length == 0 || this.auctions.length == undefined) {
			var auctionListRow = new Element("div");
			var auctionListNoitem = new Element("div");
			auctionListNoitem.addClassName("auction-list-noitem");
			auctionListNoitem.update("No items matched your search terms.");
			auctionListRow.appendChild(auctionListNoitem);			
			$('auctions-list').appendChild(auctionListRow);
			
			return;
		}
		
		this.updateNavArrows();
		var offset = ((this.page-1) * this.itemsPerPage);
		var maxItems = this.itemsPerPage;
		if (this.auctions.length < (offset + this.itemsPerPage)) { maxItems = this.auctions.length - offset; }  
		for (var i = 0; i < maxItems; i++) {
			var auctionIdx = i + offset;
			var auctionID = this.auctions[auctionIdx].id;
			
			//Add initial Check to not display no-lot auctions
			if (this.auctionItemCounts[auctionID] > 0) {
			
				var linkUrl = "auction.php?group=" + this.auctions[auctionIdx].groupName;
				//First Row
				var auctionListRow = new Element("div");
				auctionListRow.addClassName((i % 2 == 1) ? "auction-list-even-row" : "auction-list-odd-row");
	
				var auctionListLogo = new Element("div");
				auctionListLogo.addClassName("auction-list-logo");
				var auctionListLogoLink = new Element("a");
				auctionListLogoLink.href = linkUrl;
				var auctionListLogoImg = new Element("img");
				auctionListLogoImg.src = "http://www.trocadero.com/groups/auctioneer_logos/" + this.auctions[auctionIdx].groupName + ".jpg";
				auctionListLogoLink.appendChild(auctionListLogoImg);
				auctionListLogo.appendChild(auctionListLogoLink);
				
				var auctionListTitle = new Element("div");
				auctionListTitle.addClassName("auction-list-title");
				auctionListTitle.update(this.auctions[auctionIdx].auctionName);
				
				var auctionListLots = new Element("div");
				auctionListLots.addClassName("auction-list-lots");
				auctionListLots.update(this.auctions[auctionIdx].lots == '' ? '0' : this.auctions[auctionIdx].lots);
				
				var auctionListClose = new Element("div");
				auctionListClose.addClassName("auction-list-close");
				//auctionListClose.update(this.auctions[auctionIdx].finalEndShort);
				auctionListClose.update(this.auctions[auctionIdx].firstEndShort);
	
				var auctionListGroup = new Element("div");
				auctionListGroup.addClassName("auction-list-group");
				var auctionListGroupLink = new Element("a");
				auctionListGroupLink.update(this.auctions[auctionIdx].groupTitle);
				auctionListGroupLink.href = linkUrl;
				auctionListGroup.appendChild(auctionListGroupLink);
				
				auctionListRow.appendChild(auctionListLogo);
				auctionListRow.appendChild(auctionListTitle);
				auctionListRow.appendChild(auctionListLots);
				auctionListRow.appendChild(auctionListClose);
				auctionListRow.appendChild(auctionListGroup);
				
				//Second Row
				var auctionItemListRow = new Element("div");
				auctionItemListRow.addClassName((i % 2 == 1) ? "auction-list-even-row" : "auction-list-odd-row");
				
				var auctionItemListTitles = new Element("div");
				auctionItemListTitles.addClassName("auction-list-itemtitles");
				//if (this.auctionItemLists[auctionID] != '') {
				if (this.auctionItemCounts[auctionID] > 0) {
					//var itemTitles = this.auctionItemLists[auctionID].substring(0, this.auctionItemLists[auctionID].length - 2);
					var itemTitles = this.auctionItemLists[auctionID];
					auctionItemListTitles.update(itemTitles);
				} else {
					//auctionItemListTitles.update("No items in this auction yet.");
				}
				
				auctionItemListRow.appendChild(auctionItemListTitles);
				
				//Append 'em
				$('auctions-list').appendChild(auctionListRow);
				$('auctions-list').appendChild(auctionItemListRow);
				
				var clr = new Element("br");
				clr.style.clear = "both";
				$('auctions-list').appendChild(clr);
			}
		}
	},
	
	compare: function(a, b) {
		var aVal = 0, bVal = 0;
		switch(this.sort_field) {
			case "title":
				aVal = a.auctionName.toLowerCase();
				bVal = b.auctionName.toLowerCase();
				break;
			case "lots":
				aVal = parseInt(a.lots == '' ? '0' : a.lots);
				bVal = parseInt(b.lots == '' ? '0' : b.lots);
				break;
			case "endtime":
				aVal = a.finalEnd;
				bVal = b.finalEnd;
				break;
			case "group":
				aVal = a.groupName;
				bVal = b.groupName;
				break;
		}
		return ((aVal < bVal) ? -1 : ((aVal > bVal) ? 1 : 0));
	},
	
	sortAuctions: function(field) {
		if (this.sort_field == field)
			this.sort_asc = !this.sort_asc;
		else
			this.sort_asc = true;
		
		this.sort_field = field;
		this.auctions.sort(this.compare.bind(this));
		if (!this.sort_asc) { this.auctions.reverse(); }
		this.showPage();
	}
};

