var pricedropdowns = new Array();
function pricedropdown(element, action) {
	var optiontext = new Array(
		" (< $60)",
		" ($61 - $150)",
		" ($151 - $350)",
		" ($351 - $1000)",
		" ($1001+)"
	);
	var theoptions = element.getElementsByTagName('option');

	if (navigator.userAgent.indexOf('MSIE') != -1) { action = ''; }

	switch (action) {
		case "focus":
			pricedropdowns[element.getAttribute('id')] = 1;
			for (var i=1; i<theoptions.length; i++) {
				if (theoptions[i].firstChild.nodeValue.indexOf(optiontext[i-1]) == -1) {
					theoptions[i].firstChild.nodeValue += optiontext[i-1];
				}
			}
		break;
		case "blur":
		case "change":
			pricedropdowns[element.getAttribute('id')] = 0;
			for (var i=1; i<theoptions.length; i++) {
				theoptions[i].firstChild.nodeValue = theoptions[i].firstChild.nodeValue.substring(0,i);
			}
		break;
		case "click":
			pricedropdowns[element.getAttribute('id')]++;
			if (pricedropdowns[element.getAttribute('id')] % 2 == 1) { // remove stuff only
				for (var i=1; i<theoptions.length; i++) {
					theoptions[i].firstChild.nodeValue = theoptions[i].firstChild.nodeValue.substring(0,i);
				}
			} else { // add stuff only
				for (var i=1; i<theoptions.length; i++) {
					if (theoptions[i].firstChild.nodeValue.indexOf(optiontext[i-1]) == -1) {
						theoptions[i].firstChild.nodeValue += optiontext[i-1];
					}
				}
			}
		break;
		default: break;
	}
}

function getQuerystring() {
	var buildstring = window.location.search.replace(/^\?/,"");
	if (buildstring.length > 0 && buildstring.charAt(buildstring.length-1) != "&") {
		buildstring = buildstring + '&';
		var regex = "/wineid=.*?&/";
		buildstring = buildstring.replace(eval(regex), "");
	}
	return buildstring;
}

function sendCrumb(element) {
	// Crumb handling was moved into sendselect
	var clickedcrumb = false;
	var lastcrumb = false;

	var crumbarray = document.getElementById('breadcrumbs').getElementsByTagName('li');
	for (var i=0; i<crumbarray.length; i++) {
		if (crumbarray[i] == element.parentNode) { clickedcrumb = i; }
		if (crumbarray[i].getAttribute('id').indexOf('_crumb') != -1) { lastcrumb = i; }
	}

	if (clickedcrumb != lastcrumb) {	
		var myselect = document.getElementById(element.parentNode.id.substring(0,element.parentNode.id.length-6));
		sendSelect(myselect);
		if (document.body.className.indexOf("detailopen") != -1) { collapsewine(); }
	} else {
		alert("That matches your present search.");
	}
}

function resetSearch() {
	sm.resetHash();
	document.getElementById('type').selectedIndex = 0;
	sendSelect(document.getElementById('type'));
	
	var area51selects = document.getElementById("area51").getElementsByTagName("select");
	for (i=0; i<area51selects.length; i++) { area51selects[i].selectedIndex = 0; }
}

function toggleVarietalBlend(element) {
	element = $(element);
	switch (element.getAttribute('id').split('_')[0]) {
		case "blend":
//			document.getElementById('head_varietal').style.backgroundPosition = 'left top';
//			document.getElementById('head_blend').style.backgroundPosition = '';
			document.getElementById('blend_radio').checked = true;
			document.getElementById('varietal_radio').checked = false;
			document.getElementById('blend').style.display = '';
			document.getElementById('varietal').style.display = 'none';

			if (document.getElementById('varietal').selectedIndex != 0) {
				document.getElementById('varietal').selectedIndex = 0;
				sendSelect(document.getElementById('varietal'));
			}

		break;
		case "varietal":
//			document.getElementById('head_varietal').style.backgroundPosition = '';
//			document.getElementById('head_blend').style.backgroundPosition = 'left top';
			document.getElementById('varietal_radio').checked = true;
			document.getElementById('blend_radio').checked = false;
			document.getElementById('varietal').style.display = '';
			document.getElementById('blend').style.display = 'none';

			if (document.getElementById('blend').selectedIndex != 0) {
				document.getElementById('blend').selectedIndex = 0;
				sendSelect(document.getElementById('blend'));
			}

		break;
	}
}

function removeCrumb(id, index) {
	switch (index) {
		case 0:
			document.getElementById('head_breadcrumbs').style.display = "none";
			document.getElementById(id + "_crumb").previousSibling.parentNode.removeChild(document.getElementById(id + "_crumb").previousSibling);
			document.getElementById(id + "_crumb").parentNode.parentNode.removeChild(document.getElementById(id + "_crumb").parentNode);
			document.getElementById('breadcrumbs_type').style.display = "none";
			document.getElementById('location1').parentNode.className = document.getElementById('location1').parentNode.className.replace(new RegExp(" highlight\\b"), "");
		break;
		case 1:
			document.getElementById(id + "_crumb").previousSibling.parentNode.removeChild(document.getElementById(id + "_crumb").previousSibling);
			document.getElementById(id + "_crumb").parentNode.parentNode.removeChild(document.getElementById(id + "_crumb").parentNode);
			document.getElementById('breadcrumbs_geography').style.display = "none";
			document.getElementById('varietal').parentNode.className = document.getElementById('varietal').parentNode.className.replace(new RegExp(" highlight\\b"), "");
			var radiobuttons = document.getElementById('varietal').parentNode.getElementsByTagName('input');
			for (var i=0; i < radiobuttons.length; i++) {
				radiobuttons[i].disabled = true;
			}
		break;
		case 2:
		case 3:
			document.getElementById(id + "_crumb").previousSibling.parentNode.removeChild(document.getElementById(id + "_crumb").previousSibling);
			document.getElementById(id + "_crumb").parentNode.removeChild(document.getElementById(id + "_crumb"));
		break;
		case 4:
		case 5:
			document.getElementById(id + "_crumb").previousSibling.parentNode.removeChild(document.getElementById(id + "_crumb").previousSibling);
			document.getElementById(id + "_crumb").parentNode.parentNode.removeChild(document.getElementById(id + "_crumb").parentNode);
			document.getElementById('breadcrumbs_varietal').style.display = "none";
			document.getElementById('breadcrumbs_blend').style.display = "none";
		break;
	}
}

function appendCrumb(i, crumb) {
	switch (i) {
		case 0:
			document.getElementById('head_breadcrumbs').style.display = "block";
			if (document.getElementById('breadcrumbs_type').getElementsByTagName('ul').length > 0) {
				var ul = document.getElementById('breadcrumbs_type').getElementsByTagName('ul')[0];
			} else {
				var ul = document.createElement('ul');
				ul.appendChild(document.createTextNode(" "));
			}
			ul.appendChild(crumb);
			document.getElementById('breadcrumbs_type').appendChild(ul);
			document.getElementById('breadcrumbs_type').style.display = "inline";
			document.getElementById('location1').parentNode.className += " highlight";
		break;
		case 1:
			if (document.getElementById('breadcrumbs_geography').getElementsByTagName('ul').length > 0) {
				var ul = document.getElementById('breadcrumbs_geography').getElementsByTagName('ul')[0];
			} else {
				var ul = document.createElement('ul');
				ul.appendChild(document.createTextNode(" "));
			}
			ul.appendChild(crumb);
			document.getElementById('breadcrumbs_geography').appendChild(ul);
			document.getElementById('breadcrumbs_geography').style.display = "inline";
			document.getElementById('varietal').parentNode.className += " highlight";
			var radiobuttons = document.getElementById('varietal').parentNode.getElementsByTagName('input');
			for (var i=0; i < radiobuttons.length; i++) {
				radiobuttons[i].disabled = false;
			}
		break;
		case 2:
		case 3:
			document.getElementById('breadcrumbs_geography').getElementsByTagName('ul')[0].appendChild(document.createTextNode(" "));
			document.getElementById('breadcrumbs_geography').getElementsByTagName('ul')[0].appendChild(crumb);
		break;
		case 4:
//			toggleVarietalBlend(document.getElementById('varietal_radio'));
			if (document.getElementById('breadcrumbs_varietal').getElementsByTagName('ul').length > 0) {
				var ul = document.getElementById('breadcrumbs_varietal').getElementsByTagName('ul')[0];
			} else {
				var ul = document.createElement('ul');
				ul.appendChild(document.createTextNode(" "));
			}
			ul.appendChild(crumb);
			document.getElementById('breadcrumbs_varietal').appendChild(ul);
			document.getElementById('breadcrumbs_varietal').style.display = "inline";
		break;
		case 5:
//			toggleVarietalBlend(document.getElementById('blend_radio'));
			if (document.getElementById('breadcrumbs_blend').getElementsByTagName('ul').length > 0) {
				var ul = document.getElementById('breadcrumbs_blend').getElementsByTagName('ul')[0];
			} else {
				var ul = document.createElement('ul');
				ul.appendChild(document.createTextNode(" "));
			}
			ul.appendChild(crumb);
			document.getElementById('breadcrumbs_blend').appendChild(ul);
			document.getElementById('breadcrumbs_blend').style.display = "inline";
		break;
	}
}

function checkPrice() {
	var optionval = sm.getHashValue('pricelow');
	var price = document.getElementById('pricelow');

	for (i=0; i<price.options.length; i++) {
		if (price.options[i].value == optionval) price.options[i].selected = true;
	}

	if (price.selectedIndex == -1) { price.options[0].selected = true; }

	optionval = sm.getHashValue('pricehigh');
	price = document.getElementById('pricehigh');

	for (i=0; i<price.options.length; i++) {
		if (price.options[i].value == optionval) price.options[i].selected = true;
	}

	if (price.selectedIndex == -1) { price.options[0].selected = true; }
}

function getResultsPage(elem, page) {
	// Create search loading block
	var preStart = sm;

	if (elem && elem.onclick && !page) {
		sm.setHashMultiple(elem.getAttribute("href"));
	} else {
		sm.setHashValue("page", page);
	}

	if (preStart != sm.getBuildstring()) {
		document.getElementById('loadingbottom').style.visibility = "visible";
		sm.commit();
	}
}

var elementindex = 0;
function sendSelect(element) {
	// Create search loading block.
	document.getElementById('loadingtop').getElementsByTagName('div')[0].style.visibility = "visible";
	document.getElementById('loadingbottom').style.visibility = "visible";

	var myselects = document.getElementById("selectform").getElementsByTagName("select");
	var breadcrumbs = document.getElementById('breadcrumbs');
	var lastwithvalue = 0;

	// Find out the last populated root value, but make sure not to pass the newly submitted element.
	for (elementindex = 0; elementindex < 6; elementindex++) {
		if (myselects[elementindex].value != "NOVAL") { lastwithvalue = elementindex; }
		if (myselects[elementindex] == element) { break; }
	}

	for (var submitindex = 0; submitindex < myselects.length; submitindex++) {
		if (myselects[submitindex] == element) { break; }
	}

	// Clean slate without screwing up.
	var restoresection = sm.getLocationHashValue('section');
	sm.resetHash(); 

	for (var i=0; i<myselects.length; i++) {

		if (i < 6) {
			// Within the recommended subset

			if (i > Math.max(lastwithvalue, elementindex) || myselects[i].options.length == 1) {
				myselects[i].className = "disabled"; myselects[i].options.length = 1;
				if (document.getElementById(myselects[i].id + "_crumb")) { removeCrumb(myselects[i].id, i); }
				if (i == 2 || i == 3) { myselects[i].style.display = 'none'; }
			} else if (myselects[i].value != "NOVAL") {
				sm.setHashValue(myselects[i].id, myselects[i].value);

				var crumb = document.createElement('li');
				crumb.id = myselects[i].id + "_crumb";
				
				var crumblink = document.createElement('a');
				crumblink.setAttribute('href', '#'+sm.getBuildstring());
				if (crumblink.attachEvent) {
					crumblink.onclick = function() { sendCrumb(this); return false; }
				} else {
					crumblink.setAttribute('onclick', "sendCrumb(this); return false;");
				}

				var linktext = myselects[i].options[myselects[i].selectedIndex].firstChild.nodeValue;
				linktext = linktext.substring(0, (linktext.lastIndexOf('(')-1));
				var linkelem = document.createTextNode(linktext);

				crumblink.appendChild(linkelem);
				crumb.appendChild(crumblink);

				if (document.getElementById(myselects[i].id + "_crumb")) {
					document.getElementById(myselects[i].id + "_crumb").parentNode.replaceChild(crumb, document.getElementById(myselects[i].id + "_crumb"));
				} else {
					appendCrumb(i, crumb);
				}
			} else if (i == elementindex) {
				// Remove the last crumb if type gets set back to no value.
				if (document.getElementById(myselects[i].id + "_crumb")) { removeCrumb(myselects[i].id, i); }
			}

		} else {
			// Optional selects. Add the select's value to the hash.
			if (myselects[i].value != "NOVAL" && (i <= submitindex || ((submitindex == 6 || submitindex == 7) && (i == 6 || i == 7)) || myselects[i].id.indexOf("price") != -1)) { sm.setHashValue(myselects[i].id, myselects[i].value); }
		}
	}

	if (restoresection != '') { sm.setHashValue('section', restoresection); }
	sm.commit();
}

function getAJAXresponse(poststring) {
	if (document.getElementsByTagName('body')[0].className != 'wineid' && document.getElementsByTagName('body')[0].className != 'open') {
		startCounter();
	}
	var url = "/queries.php";
	var pars = poststring + 'rand=' + Math.floor(Math.random() * 999);
	var myAjax = new Ajax.Request( 
		url,
		{
			method: 'post',
			parameters: pars,
			onComplete: refreshPage,
			onFailure: function() { alert("There was trouble getting your information from the server."); }
		}
   );
}

function refreshPage(response) {
	var callbackfunctions = new Array();
	// for debugging
	//document.write(response.responseText);
	var ajaxResponse = Try.these(
		function() { return new DOMParser().parseFromString(response.responseText, 'text/xml'); },
		function() { var xmldom = new ActiveXObject('Microsoft.XMLDOM'); xmldom.loadXML(response.responseText); return xmldom; }
	);

	// Find out what content we got back (selects? item count? results?)
	for (i=0; i<ajaxResponse.getElementsByTagName("response").length; i++) {
		switch (ajaxResponse.getElementsByTagName("response")[i].getAttribute('id')) {
			case "breadcrumbs":
				var breadcrumbs = document.getElementById('breadcrumbs');
				var mycrumbs = ajaxResponse.getElementsByTagName("response")[i].getElementsByTagName("li");

				for (j=0; j<mycrumbs.length; j++) {
					var li = document.createElement('li');
						li.id = mycrumbs[j].getAttribute('id');
					var anchor = document.createElement('a');
						if (anchor.attachEvent) {
							anchor.onclick = function () { eval(mycrumbs[j].firstChild.getAttribute('onclick')); }
						} else {
							anchor.setAttribute('onclick', mycrumbs[j].firstChild.getAttribute('onclick'));
						}
						anchor.setAttribute('href', mycrumbs[j].firstChild.getAttribute('href'));
					var linktext = document.createTextNode(mycrumbs[j].firstChild.firstChild.nodeValue);

					anchor.appendChild(linktext);
					li.appendChild(anchor);

					if (document.getElementById(li.id)) {
						document.getElementById(li.id).parentNode.replaceChild(li, document.getElementById(li.id));
					} else {
						var crumbindex = j;
						switch (li.id) {
							case "location2_crumb": crumbindex = 2; break;
							case "location3_crumb": crumbindex = 3; break;
							case "varietal_crumb": crumbindex = 4; break;
							case "blend_crumb": crumbindex = 4; break;
						}
						appendCrumb(crumbindex, li);
					}

				}
			break;
			case "select":
				// Allows for infinite numbers of selects being returned
				var myselects = ajaxResponse.getElementsByTagName("response")[i].getElementsByTagName("select");
				var fields = new Array("type", "location1", "location2", "location3", "varietal", "blend");
				var fieldsindexarray = new Array()
				for (j=0; j<myselects.length; j++) {
					if (document.getElementById(myselects[j].getAttribute('id'))) {

						var fieldsindex = fields.inArray(myselects[j].getAttribute('id'));
						if (fieldsindex != -1) { fieldsindexarray.push(fieldsindex); }

						var pageElem = document.getElementById(myselects[j].getAttribute('id'))
						pageElem.options.length = 1;
						for (k=0; k<myselects[j].getElementsByTagName('option').length; k++) {
							pageElem.options[k] = new Option(myselects[j].getElementsByTagName('option')[k].firstChild.nodeValue, myselects[j].getElementsByTagName('option')[k].getAttribute('value'));
							if (myselects[j].getElementsByTagName('option')[k].getAttribute('selected')) { pageElem.options[k].selected = true; }
						}
						if (pageElem.className == "disabled") pageElem.className = "";
						if (pageElem.style.display == "none") {
							if ((pageElem.getAttribute('id') != 'blend' && pageElem.getAttribute('id') != 'varietal') || document.getElementById(pageElem.getAttribute('id') + '_radio').checked) {
								pageElem.style.display = "";
							}
						}
					}
				}

				fieldsindexarray.sort(function (a,b) { return b - a; });

				var lastsetcount = 0;
				while (fieldsindexarray[lastsetcount] >= 4 && lastsetcount < fieldsindexarray.length) { lastsetcount++; }
				var lastset = fieldsindexarray[lastsetcount];

				// reset the ones that follow this field, not varietal and blend
				for (j=lastset+1; j<4; j++) {
					if (document.getElementById(fields[j])) {
						var pageElem = document.getElementById(fields[j]);
						pageElem.options.length = 1;
						pageElem.className = "disabled";
						//if (j == 2 || j == 3) { pageElem.style.display = "none" }
					}
				}

			break;
			case "count":
				var num = ajaxResponse.getElementsByTagName("response")[i].getElementsByTagName("count")[0].getAttribute('value');
				
				var k = 1;
				var tempelem;
				while (tempelem = document.getElementById('count' + k)) {
					tempelem.firstChild.nodeValue = num;
					if (k==1 && num == 1) { document.getElementById("recordCheck").style.display = 'none'; } else { document.getElementById("recordCheck").style.display = 'inline'; }
					k++;
				}
				if (document.getElementsByTagName('body')[0].className != 'wineid' && document.getElementsByTagName('body')[0].className != 'open') {
					setFlashCount(num);
				}
				if (num < 250 && num > 0) {

					// Unhide the bottom bar, in case it is hidden.
					document.getElementById('results').getElementsByTagName('table')[0].style.display = "block";
					document.getElementById('results').getElementsByTagName('ul')[0].style.display = "block";
					document.getElementById('lower').style.display = "block";

					document.getElementById('viewresults').className = document.getElementById('viewresults').className.replace(new RegExp(" disabled\\b"), "");
					document.getElementById('viewresultstext').style.display = "none";
				} else {
					if (num == 0) {
						// Hide the bottom bar if 0 results.
						document.getElementById('results').getElementsByTagName('table')[0].style.display = "none";
						document.getElementById('results').getElementsByTagName('ul')[0].style.display = "none";
						document.getElementById('lower').style.display = "none";
					}
					if (document.getElementById('viewresults').className.indexOf(" disabled") == -1) {
						document.getElementById('viewresults').className += " disabled";
						document.getElementById('viewresultstext').style.display = "inline";
					}
				}
			break;
			case "results":
				var resultstable = document.getElementById('results').getElementsByTagName('table')[0];

				var trelems = resultstable.getElementsByTagName('tr');
				while (trelems.length > 0) { resultstable.deleteRow(0); }

				var resultsAr = ajaxResponse.getElementsByTagName("response")[i].getElementsByTagName("result");
				var querystring = getQuerystring();

				for (j=0; j<resultsAr.length; j++) {
					var tdAvail = document.createElement('td');
						tdAvail.className = 'availability';

					if (resultsAr[j].getAttribute('cases') > 0 && resultsAr[j].getAttribute('cases') <= 5000) {
						var imgAvail = document.createElement('img');
							if (resultsAr[j].getAttribute('cases') <= 2000) {
								imgAvail.setAttribute('src', '/_images/search/available_el.gif');
								imgAvail.setAttribute('alt', 'EL');
								imgAvail.setAttribute('title', 'Extremely Limited');
							} else {
								imgAvail.setAttribute('src', '/_images/search/available_l.gif');
								imgAvail.setAttribute('alt', 'L');
								imgAvail.setAttribute('title', 'Limited');
							}
					}

					var tdWineName = document.createElement('td');
						tdWineName.className = "winename";

					var aWineName = document.createElement('a');
						aWineName.setAttribute('href', '/browse/'+ resultsAr[j].getAttribute('id').substring(6) +'/');
						if (aWineName.attachEvent) {
							aWineName.onclick = function() { return displaywine(this); }
						} else {
							aWineName.setAttribute("onclick", "return displaywine(this);");
						}

					var tdPrice = document.createElement('td');
						tdPrice.className = 'price';

					var spanDollars = document.createElement('span');
						spanDollars.className = "dollar" + resultsAr[j].getAttribute('signs');

						var dollars = '';
						while (dollars.length < resultsAr[j].getAttribute('signs')) { dollars += '$'; }

						spanDollars.appendChild(document.createTextNode(dollars));

					var tdReserve = document.createElement('td');
						tdReserve.className = "reserve";

					var aReserve = document.createElement('a');
						aReserve.className = "reservewine";
						aReserve.setAttribute('href', '/browse/'+ resultsAr[j].getAttribute('id').substring(6) +'/');
						if (aReserve.attachEvent) {
							aReserve.onclick = function() { return displaywine(this); }
						} else {
							aReserve.setAttribute("onclick", "return displaywine(this);");
						}
					
					var tr = resultstable.insertRow(-1);
						tr.setAttribute('id', resultsAr[j].getAttribute('id'));
						if (j % 2 == 0) { tr.className = "alt" }

					aWineName.appendChild(document.createTextNode(resultsAr[j].firstChild.nodeValue));
					aReserve.appendChild(document.createTextNode("Reserve Wine"));
					tdWineName.appendChild(aWineName);
					if (imgAvail) { tdAvail.appendChild(imgAvail); }
					tdReserve.appendChild(aReserve);

					tdPrice.appendChild(spanDollars);
					tr.appendChild(tdAvail);
					tr.appendChild(tdWineName);
					tr.appendChild(tdPrice);
					tr.appendChild(tdReserve);

					tr = undefined;
					tdAvail = undefined;
					imgAvail = undefined;
					tdWineName = undefined;
					aWineName = undefined;
					tdPrice = undefined;
					spanDollars = undefined;
					dollars = undefined;
					tdReserve = undefined;
					aReserve = undefined;
				}

				var paginationUls = document.getElementById('results').getElementsByTagName('ul');
				var totalpages = ajaxResponse.getElementsByTagName("response")[i].getAttribute("totalpages");
				var currentpage = ajaxResponse.getElementsByTagName("response")[i].getAttribute("currentpage");

				var liAR = new Array();

				if (currentpage != 1) { // first element
					var li = document.createElement('li');
						li.className = "direction";
					var a = document.createElement('a');
						a.setAttribute("href","#section=results&" + sm.hashBuilder("page", (Number(currentpage)-1)));
						if (a.attachEvent) {
							a.onclick = function() { getResultsPage(this); return false; }
						} else {
							a.setAttribute("onclick", "getResultsPage(null, "+ (Number(currentpage)-1) +"); return false;");
						}
					var img = document.createElement('img');
						img.setAttribute("src", "/_images/search/pagination_left.gif");
						img.setAttribute("width", "10");
						img.setAttribute("height", "7");
						img.setAttribute("alt", "&lt;&lt;");

					a.appendChild(img);
					li.appendChild(a);
					liAR.push(li);
				}

				for (j=Math.max(0, (currentpage-5)); j < Math.min(totalpages, Number(currentpage)+4); j++) {
					if (totalpages != 1) {
						var li = document.createElement('li');
							if (j+1 == currentpage) { li.className = "focused"; }
						var a = document.createElement('a');
							a.setAttribute("href", "#section=results&" + sm.hashBuilder("page", (j+1)));
							if (a.attachEvent) {
								a.onclick = function() { getResultsPage(this); return false; }
							} else {
								a.setAttribute("onclick", "getResultsPage(null, "+ (j+1) +"); return false;");
							}
						a.appendChild(document.createTextNode(j+1));
						li.appendChild(a);
						liAR.push(li);
					}
				}

				if (currentpage != totalpages) { // last element
					var li = document.createElement('li');
						li.className = "direction";
					var a = document.createElement('a');
						a.setAttribute("href","#section=results&" + sm.hashBuilder("page", (Number(currentpage)+1)));
						if (a.attachEvent) {
							a.onclick = function() { getResultsPage(this); return false; }
						} else {
							a.setAttribute("onclick", "getResultsPage(null,"+ (Number(currentpage)+1) +"); return false;");
						}
					var img = document.createElement('img');
						img.setAttribute("src", "/_images/search/pagination_right.gif");
						img.setAttribute("width", "10");
						img.setAttribute("height", "7");
						img.setAttribute("alt", "&gt;&gt;");

					a.appendChild(img);
					li.appendChild(a);
					liAR.push(li);
				}

				for (j=0; j<paginationUls.length; j++) {
					// Remove existing pagination elements
					while (paginationUls[j].childNodes.length > 0) {
						paginationUls[j].removeChild(paginationUls[j].childNodes[0]);
					}

					// Add new pagination elements
					for (var k=0; k<liAR.length; k++) {
						if (j > 0) {
							paginationUls[j].appendChild(document.createTextNode(" "));
							paginationUls[j].appendChild(liAR[k].cloneNode(true));
						} else {
							paginationUls[j].appendChild(document.createTextNode(" "));
							paginationUls[j].appendChild(liAR[k]);
						}

					}
				}
			break;
		}
	}

	if ($('varietal').options.length == 1 && $('blend').options.length > 1) {
		toggleVarietalBlend('blend_radio');
	} else if ($('blend').options.length == 1 && $('varietal').options.length > 1) {
		toggleVarietalBlend('varietal_radio');
	}

	// Remove the search loading block
	document.getElementById('loadingtop').getElementsByTagName('div')[0].style.visibility = "hidden";
	document.getElementById('loadingbottom').style.visibility = "hidden";
}

function resultsToggle(callback) {
	if (document.body.className == "open") {
		sm.setHashValue("section", "topwrapper");
		sm.commit();
		new Effect.BlindUp('results', {
			duration: .5,
			afterFinish: function() {
				var area51 = document.getElementById('area51');
				var area52 = document.getElementById('area52');

				var tempelem;
				while(tempelem = area52.firstChild) {
					area52.removeChild(tempelem);
					area51.appendChild(tempelem);
				}

				new Effect.BlindDown('topwrapper', {
					duration: .5,
					afterFinish: function() {
						// Fade to closed state
						new Effect.Opacity('contentfooter', {
							duration: .3,
							from: 1.0,
							to: 0.0,
							afterFinish: function() {
								var table = document.getElementById('contentfooter');
								var contentfooter = table.parentNode;
								//contentfooter.removeChild(table);
								//contentfooter.appendChild(table);
								if (callback) { resetSearch(); }
								document.body.className = "";
								document.getElementById('breadcrumbs').parentNode.style.display = "none";

								new Effect.Opacity('contentfooter', {
									duration: .3,
									from: 0.0,
									to: 1.0,
									beforeStart: function () { flashMovie.style.display = "block"},
									afterFinish: function() { if (document.getElementsByTagName('body')[0].className != 'wineid' && document.getElementsByTagName('body')[0].className != 'open') { setFlashCount(document.getElementById('count1').childNodes[0].nodeValue); fadeFlash(100); } }
								} );
							}
						} );

					}
				} );

			}
		} );
	} else if (document.body.className == "wineid" || document.body.className.indexOf("detailopen") != -1) {
		new Effect.BlindUp('winedetail', {
			duration: .5,
			afterFinish: function() {
				var area51 = document.getElementById('area51');
				var area52 = document.getElementById('area52');

				if (sm.getHashValue('section') != 'results') {
					sm.setHashValue("section", "topwrapper");
					sm.commit();
					var tempelem;
					while(tempelem = area52.firstChild) {
						area52.removeChild(tempelem);
						area51.appendChild(tempelem);
					}
					new Effect.BlindDown('topwrapper', {
						duration: .5,
						afterFinish: function() {
							// Fade to closed state
							new Effect.Opacity('contentfooter', {
								duration: .3,
								from: 1.0,
								to: 0.0,
								afterFinish: function() {
									var table = document.getElementById('contentfooter');
									var contentfooter = table.parentNode;
									//contentfooter.removeChild(table);
									//contentfooter.appendChild(table);
									if (callback) { resetSearch(); }
									document.body.className = "";
									document.getElementById('breadcrumbs').parentNode.style.display = "none";

									new Effect.Opacity('contentfooter', {
										duration: .3,
										from: 0.0,
										to: 1.0,
										beforeStart: function () { flashMovie.style.display = "block"},
										afterFinish: function() { if (document.getElementsByTagName('body')[0].className != 'wineid' && document.getElementsByTagName('body')[0].className != 'open') { setFlashCount(document.getElementById('count1').childNodes[0].nodeValue); fadeFlash(100); } }
									} );
								}
							} );

						}
					} );
				} else {
					sm.setHashValue("section", "results");
					sm.commit();
					var tempelem;
					while(tempelem = area51.firstChild) {
						area51.removeChild(tempelem);
						area52.appendChild(tempelem);
					}

					new Effect.BlindDown('results', {
						duration: .5,
						afterFinish: function() {
							// Fade to open state
							new Effect.Opacity('contentfooter', {
								duration: .3,
								from: 1.0,
								to: 0.0,
								afterFinish: function() {
									document.body.className = "open";
									document.getElementById('breadcrumbs').parentNode.style.display = "table-cell";
									new Effect.Opacity('contentfooter', {
										duration: .3,
										from: 0.0,
										to: 1.0
									} );
								}
							} );
						}
					} );
				}
			}
		} );
	} else {
		sm.setHashValue("section", "results");
		sm.commit();
		fadeFlash(0);

		setTimeout('fromthetop();', 300);

	}
}

function fromthetop() {
	if (flashMovie) { flashMovie.style.display = "none"; }

	new Effect.BlindUp('topwrapper', {
		duration: .5,
		afterFinish: function() {
			var area51 = document.getElementById('area51');
			var area52 = document.getElementById('area52');

			var tempelem;
			while(tempelem = area51.firstChild) {
				area51.removeChild(tempelem);
				area52.appendChild(tempelem);
			}

			new Effect.BlindDown('results', {
				duration: .5,
				afterFinish: function() {
					// Fade to open state
					new Effect.Opacity('contentfooter', {
						duration: .3,
						from: 1.0,
						to: 0.0,
						afterFinish: function() {
							document.body.className = "open";
							document.getElementById('breadcrumbs').parentNode.style.display = "block";
							new Effect.Opacity('contentfooter', {
								duration: .3,
								from: 0.0,
								to: 1.0
							} );
						}
					} );
				}
			} );
		}
	} );
}

function displaywine(element, value) {
	//todo
	return true;
	var id = 0;
	if (value || element.getAttribute('href').indexOf("wineid") != -1) {
		if (value) { id = value; } else {
			var regex = "/(.*)(wineid=)(.*?)/";
			id = element.getAttribute('href').replace(eval(regex), "$3");
		}
		setHashValue("wine",id,true);

		var section = 'results';
		if ($('topwrapper').style.display == "block") {
			section = 'topwrapper';
		}

		setHashValue("section", "winedetail",true);

		new Effect.BlindUp(section, {
			duration: .5,
			afterFinish: function() {
				new Effect.BlindDown('winedetail', {
					duration: .5,
					afterFinish: function() {
						document.body.className = "open detailopen";
					}
				} );
			}
		} );
	}
}

function collapsewine() {
	//unsetHashValue("wine", true);

	sm.setHashValue("section", "results");
	sm.commit();
	new Effect.BlindUp('winedetail', {
		duration: .5,
		afterFinish: function() {
			new Effect.BlindDown('results', {
				duration: .5,
				afterFinish: function() {
					document.body.className = "open";
				}
			} );
		}
	} );
}

function chooserestaurant(element) {
	element.style.backgroundPosition = "left bottom";
	new Effect.Fade(element, {duration: .2, afterFinish: function() { element.style.backgroundPosition = ""; element.parentNode.style.verticalAlign = "top"; }, queue: 'end'} );

	var therow = element.parentNode.parentNode;
	var rows = therow.parentNode.getElementsByTagName('tr');


	for (i=0; i<rows.length; i++) {
		if (rows[i] != therow && rows[i].className != "submit") {
			new Effect.Fade(rows[i], { duration: .3 } );
		} else if (rows[i] == therow) {
			// it is presently on the element, skip the following row too.
			i++;
		}
	}

	var compstartcolor = (therow.className != "alt" ? "#F3ECE3" : '#E4DFD9');
	new Effect.Highlight(therow, { startcolor: compstartcolor, endcolor:'#E4DFD9', restorecolor: '#E4DFD9', duration: .3 } );

	new Effect.Appear(rows[therow.rowIndex+1], { duration: .5, queue: 'end'} );
	new Effect.Appear(element.nextSibling, {duration: .2, queue: 'end'} );

}

function unchooserestaurant(element) {
	element.style.backgroundPosition = "left bottom";
	new Effect.Fade(element, {duration: .2, afterFinish: function() { element.style.backgroundPosition = ""; element.parentNode.style.verticalAlign = "middle"; }, queue: 'end'} );

	var therow = element.parentNode.parentNode;
	var rows = therow.parentNode.getElementsByTagName('tr');

	var compendcolor = (therow.className != "alt" ? "#F3ECE3" : '#E4DFD9');
	new Effect.Highlight(therow, { startcolor: '#E4DFD9', endcolor: compendcolor, restorecolor: compendcolor, duration: .5 } );

	for (i=0; i<rows.length; i++) {
		if (rows[i] == therow) { new Effect.Fade(rows[i+1], { queue: 'start', duration: .5, afterFinish: function() {
			for (i=0; i<rows.length; i++) {
				if (rows[i] != therow && rows[i].className != "submit") {
					new Effect.Appear(rows[i], { duration: .3 } );
				}
			}
		} } ); }
	}

	new Effect.Appear(element.previousSibling, {duration: .2, queue: 'end'} );

}

function toggledetails(element) {
	var extended = $('winedescription').nextSibling;

	if (element.className.indexOf("open") != -1) {
		Effect.toggle(extended, 'blind', { duration: .5, afterFinish: function () { element.className = "viewhide"; } } );
	} else {
		Effect.toggle(extended, 'blind', { duration: .5, afterFinish: function () { element.className = "viewhide open"; } } );
	}
}

function getWine() {

}

function getQty(element) {
	var qty = $("qty_" + element.getAttribute('id').split("_")[1]);
	var therow = element.parentNode.parentNode.parentNode.parentNode;
	var rootindex = Math.max((element.options.selectedIndex - 1), 0);
	if (bottles[(therow.rowIndex-1)/2][rootindex][0] == element.value) {

		qty.style.width = qty.getDimensions().width;

		qty.options.length = 1;
		var min = 1;
		var max = Math.min(bottles[(therow.rowIndex-1)/2][rootindex][1], 5);
		for (i=min; i<=max; i++) {
			var temp = document.createElement('option');
			temp.setAttribute('value', i);
			temp.appendChild(document.createTextNode(i));
			qty.appendChild(temp);
		}
		try {
			qty.options[1].selected = true;
		} catch (e) { /* Appears to work even with the error. Just prevent user from seeing it. */ }
	} else {
		qty.options[0].selected = true;
		qty.options.length = 1;
	}
}

function makereservation(restid) {
	if ($('qty_'+restid).value == 0 || $('bottlesize_'+restid).value == 0) {
		alert("You must select a Bottle Size and Quantity to make a reservation.");
	} else {
		$('frm_restselect_qty').value = $('qty_'+restid).value;
		$('frm_restselect_size').value = $('bottlesize_'+restid).value;
		$('frm_restselect_restaurantID').value = restid;
		var wineid = sm.getHashValue('wine');
		if (wineid) { $('frm_restselect_wineID').value = wineid; }

		$('restselect').submit();
	}
};

function getCityRests(element) {
	// create options based upon a for
	var restaurant = $('restaurant_Id');

	if (element.value != "NOVAL") {
		var theoptions = restaurant.getElementsByTagName('option');

		// remove options after index 2
		restaurant.style.width = restaurant.getDimensions().width;
		restaurant.options.length = 1;

		for (var i in cityrest[element.value]["restaurants"]) {
			var temp = document.createElement('option');
			temp.setAttribute('value', cityrest[element.value]["restaurants"][i]["id"]);
			temp.appendChild(document.createTextNode(cityrest[element.value]["restaurants"][i]["name"]));
			restaurant.appendChild(temp);
		}
	}
}