var selectedProducts = new Array();
var tempProducts = $H();
var nTempProducts = 0;
var lastSearchResults;
var nProducts;
var commentsDialog, tempWineDialog, searchResultsDialog, feedbackDialog;
var starsAreLocked = false;
var selectedCycle = new Object();
var selectedRating = 0;
var commentsCalendar;
var commentsCalendarPanel;
var winelistId = null;
var DialogModes = { Add: 0, Edit: 1, AddTemp: 2 };
var moreTopRated = false;
var checkingMaxChars = false;
var checkProdCountOnExit = true;
selectedCycle.value = 1;

function showMore(pId) {
	$('comments_' + pId + '_less').hide();
	Effect.Appear('comments_' + pId + '_more');
}

function cycle(obj) { 
	var cycle = obj.value;
	var rowClass;

	if (cycle == 1) {
		rowClass = "grey_row";
	} else {
		rowClass = "white_row";
	}

	obj.value = (cycle+1)%2;

	return rowClass;
}

function decodeRating(rating) {
	var i = parseInt(rating);
	var f = parseFloat(rating);
	var className;

	var x = f - i; // the float part
	if ( x > .75 ) {
		// bump up to the next integer
		className = intToTxt(i+1) + 'StarsHighlighted';
	} else if ( x > .25 ) {
		// we are in half star territory
		if (i == 0) {
			className = 'oneHalfStar';
		} else {
			className = intToTxt(i) + 'AndHalfStars';
		}
	} else {
		// adding the 'highlighted' differentiates this
		// from the JS star selector used in the wine portfolio
		if (i != 0) {
			className = intToTxt(i) + 'StarsHighlighted';
		}
	}

	return className;
}

function intToTxt(i) {
	var intTxt;

	switch(i) {
	case 0:
		intTxt = "";
		break;
	case 1:
		intTxt = "one";
		break;
	case 2:
		intTxt = "two";
		break;
	case 3:
		intTxt = "three";
		break;
	case 4:
		intTxt = "four";
		break;
	case 5: 
		intTxt = "five";
		break;
	}

	return intTxt;
}

function searchFailed() {
	$('search_spinner').hide();
	alert('There was a problem processing your search. Please try again.');
}

function showCommentsDialog(title) {
	$('comments_dialog_header').update('Your Review of \'' + title + '\'');

	$('comments_form').reset();
	changeRating();
	$('comments_cal_container').style.display = "inline";
	commentsDialog.show();
	$('comments').focus();
}

function addToList(ev) {
	searchResultsDialog.hide();

	var elem = commentsDialog.productElement = Event.element(ev);
	var productId = commentsDialog.pId = elem.readAttribute('product_id');
	commentsDialog.mode = DialogModes.Add;

	if (selectedProducts.indexOf(productId) != -1) {
		alert('That product has already been added to your wine list.');
		return;
	}

	var prodInfo = commentsDialog.prodInfo = lastSearchResults.Result.find(function (h) {
		if ($H(h).get('product_id') == productId) {
			return true;
		} else {
			return false;
		}
	});
	
	var name = 'Selected Product';
	if (prodInfo) {
		name = prodInfo.product_name;
	}

	showCommentsDialog(name);
}

function didSearch(resp) {
	var resultInfo = lastSearchResults = resp.responseText.evalJSON(true);
	var results = resultInfo.Result;
	var rowCycle = new Object();
	rowCycle.value = 1;

	nProducts = results.length;


	$('search_results_container').update();

	for (var i = 0; i < results.length; i++) {
		var row = results[i];

		if (selectedProducts.indexOf(parseInt(row.product_id)) != -1) {
			// already selected
			nProducts--;
			continue;
		}

		// prepare expert review, if it exists
		var expert_review = "";
		if (row.has_review == "0") {
			expert_review = "";
		} else {
			expert_review = '<div class="avg_cust_rating_txt">Expert Rating:</div> ' + row.ugly_rating + ' points (' + row.newsletter_short_title + ')';
		}

		var price_html = '<div class="priced_from">';
		if (row.min_price) {
			price_html += 'Priced From: <span class="black">$' + row.min_price + '</span><br/><a href="/ecommerce/product-offer-search.tcl?product_id=' + row.product_id + '">Compare Prices</a>';
		} else {
			price_html += "Out of Stock";
		}
		price_html += '</div>';

		var html = '<div id="result_' + row.product_id + '" class="search_results ' + cycle(rowCycle) + '">';
		html += '<div class="list_right">' + price_html + '<button class="btn_short add_to_list" product_id="' + row.product_id + '" id="add_' + row.product_id + '">Add to List</button></div>';
		html += '<div class="list_left"><h3>' + row.product_name + '</h3><div class="avg_cust_rating_txt">Average Customer Rating: </div> <div class="modify starContainer ' + decodeRating(row.avg_rating) + ' yellowStars" style="display: inline; padding: 0px; float: left"></div> <span class="avg_cust_rating_txt" style="font-weight: normal">' + expert_review + '</div>';
		html += '</div>';

		$('search_results_container').insert({bottom: html});

		Event.observe('add_' + row.product_id, 'click', addToList);
	}

	var resultText = 'Showing <span id="n_results">' + nProducts + '</span>';
	if (resultInfo.Limit < resultInfo.Count) {
		resultText += ' of ' + resultInfo.Count + ' matching wines. Consider narrowing your search to return fewer results.';
	} else {
		resultText += ' matching wines.';
	}
	$('result_info').update(resultText);

	$('search_spinner').hide();
}

function doDialogSearch(ev) {
	ev.term = $F('dialog_search_term');
	ev.form = $('dialog_search_form');
	search(ev);
}

function doSearch(ev) {
	ev.term = $F('search_term');
	ev.form = $('modify_search_form');
	$('dialog_search_term').value = $F('search_term');
	searchResultsDialog.show();
	//$('dialog_search_term').focus();
	
	search(ev);
}

function search(ev) {
	Event.stop(ev);

	if (ev.term == '') {
		return;
	}

	var callback = {
		success: didSearch,
		failure: searchFailed	 
	}

	$('search_spinner').show();
	$('result_info').update('&nbsp;');
	$('search_results_header').show();

	YAHOO.util.Connect.setForm(ev.form);
	YAHOO.util.Connect.asyncRequest('GET','_product-search.adp',callback);
}

function updateComments() {
	var productId = commentsDialog.pId;
	var comments = $F('comments');
	var tastingDate = commentsCalendar.getSelectedDates()[0];
	var rating = selectedRating;
	var tastedAt = $F('tasted_at');

	// update div
	$('display_comments_for_' + productId).update(comments);
	$('display_tasting_info_for_' + productId).update(tastedDiv(tastingDate, tastedAt));
	var starContainer = $('display_rating_for_' + productId);
	var ratings = ['one','two','three','four','five'];
	for (var i = 0; i < ratings.length; i++) {
		starContainer.removeClassName(ratings[i] + 'StarsHighlighted');
	}
	starContainer.addClassName(decodeRating(selectedRating));	

	// update form
	selectedProducts = selectedProducts.without(productId);		
	var formElements = ['comments_for_', 'rating_for_', 'tasting_date_for_', 'tasted_at_for_'];
	for (var i = 0; i < formElements.length; i++) {
		$(formElements[i] + productId).remove();
	}
	addFormEntryForProduct(productId, comments, rating, tastingDate, tastedAt);

	$('comments_cal_container').hide();
	commentsCalendar.clear();
	commentsDialog.hide();

	autoSaveList();

	// show small arrow next to "Add Products" button
	$('add_products_arrow').show();
}

function submitComments() {
	if (selectedRating == 0) {
		alert('Please select a rating for this product.');
		return;
	}

	if (commentsDialog.mode == DialogModes.Edit) {
		updateComments();
		return;	
	}

	var elem = commentsDialog.productElement;
	var productId = commentsDialog.pId;

	var temp = false;
	if (commentsDialog.mode == DialogModes.AddTemp) {
		temp = true;
	}

	if ( (temp == false && selectedProducts.indexOf(productId) != -1) ) {
		alert('That product has already been added to your wine list.');
		return;
	}

	var prodInfo = commentsDialog.prodInfo;

	// generate the HTML row
	var tasting_date = commentsCalendar.getSelectedDates()[0];
	var row = '<div id="selected_' + productId + '" class="search_results ' + cycle(selectedCycle) + '" style="height: auto; padding: inherit 50px 0px; display: none">';
	row += '<div class="remove_link"><a href="#" onclick="editSelected(\'' + productId + '\'); return false">edit</a> <a href="#" onclick="removeSelected(\'' + productId + '\'); return false;">remove</a></div>';
	row += '<div class="list_left">';
	row += '<h3>' + prodInfo.product_name + '</h3>';
	row += '<div style="margin: 6px 0px 2px 0px"><div class="avg_cust_rating_txt">Your Rating: </div> <div id="display_rating_for_' + productId + '" class="modify starContainer ' + decodeRating(selectedRating) + '" style="float: left"></div><div id="display_tasting_info_for_' + productId + '">' + tastedDiv(tasting_date, $F('tasted_at')) + '</div><div class="clear"></div></div>';
	row += '</div>';
	row += '<div id="display_comments_for_' + productId + '" class="tastingnotes modify">' + $F('comments') + '</div>';
	row += '<div class="clear"></div>';
	row += '</div>';

	$('selected_products').insert({bottom: row});

	$('comments_cal_container').hide();
	commentsCalendar.clear();
	commentsDialog.hide();

	if (temp) {
		tempProducts.set(productId, [prodInfo.product_name, prodInfo.product_desc]);
	} else {
		Effect.Fade('result_' + productId, { duration: 0.7, queue: 'end' });
		$('n_results').update(--nProducts);
	}

	addFormEntryForProduct(productId, $F('comments'), selectedRating, tasting_date, $F('tasted_at'), temp);

	// auto-save AJAX call
	autoSaveList();

	$('selected_' + productId).show();

	if ($('no_products')) {
		$('no_products').remove();
	}

	if ($('preview_publish_buttons').style.display == "none") {
		Effect.Appear('preview_publish_buttons', { duration: 0.5});
	}
	
	// show small arrow next to "Add Products" button
	$('add_products_arrow').show();
}

function autoSaveList() {
	$('selected_products_form').request({ 
		parameters: {
			auto_save: 't'
		}
	});	
}

function publishList() {
	if (selectedProducts.length < 3) {
		if (confirm("Notice: Your Wine List needs at least *three* products before we can display it on our site.\n\nClick 'Cancel' below to continue adding products. If you'd prefer to finish later, click 'OK' -- you can continue working on this list at any time by clicking the 'My Wine Lists' link at the top of this page.")) {
			checkProdCountOnExit = false;	
			$('selected_products_form').submit();
		}
	} else {
		$('selected_products_form').submit();
	}
}

function addFormEntryForProduct(productId, comments, rating, tastingDate, tastedAt, temp) {
	selectedProducts.push(productId);
	$('selected_product_ids').value = selectedProducts.join(',');

	var c = Element.extend(document.createElement('input'));
	c.writeAttribute({type: 'hidden', name: 'comments_for_' + productId, id: 'comments_for_' + productId, value: comments});
	var r = Element.extend(document.createElement('input'));
	r.writeAttribute({type: 'hidden', name: 'rating_for_' + productId, id: 'rating_for_' + productId, value: rating});
	var tastingDateStr = "";
	if (tastingDate) {
		tastingDateStr = tastingDate.getFullYear() + '-' + (parseInt(tastingDate.getMonth()) + 1).toString() + '-' + tastingDate.getDate();
	} 
	var t1 = Element.extend(document.createElement('input'));
	t1.writeAttribute({type: 'hidden', name: 'tasting_date_for_' + productId, id: 'tasting_date_for_' + productId, value: tastingDateStr});
	var t2 = Element.extend(document.createElement('input'));
	t2.writeAttribute({type: 'hidden', name: 'tasted_at_for_' + productId, id: 'tasted_at_for_' + productId, value: tastedAt});

	$('selected_products_form').insert({bottom: c});	
	$('selected_products_form').insert({bottom: r});	
	$('selected_products_form').insert({bottom: t1});	
	$('selected_products_form').insert({bottom: t2});	

	// for temp (non-existent) products
	if (temp) {
		var t3 = Element.extend(document.createElement('input'));
		t3.writeAttribute({type: 'hidden', name: 'name_for_' + productId, id: 'name_for_' + productId, value: tempProducts.get(productId)[0]});

		var t4 = Element.extend(document.createElement('input'));
		t4.writeAttribute({type: 'hidden', name: 'desc_for_' + productId, id: 'desc_for_' + productId, value: tempProducts.get(productId)[1]});

		$('selected_products_form').insert({bottom: t3});
		$('selected_products_form').insert({bottom: t4});
	}
}

function tastedDiv(tastedOn, tastedAt) {
	var str = '';
	if (tastedOn || tastedAt != "") {       
		str = '<div class="avg_cust_rating_txt" style="">Tasting';
		if (tastedOn) {
			str += ' Date: ' + (parseInt(tastedOn.getMonth()) + 1).toString() + 
				'/' + tastedOn.getDate() + '/' + tastedOn.getFullYear();
			if (tastedAt) {
				str += ';';
			}
		}
		if (tastedAt) {
			str += ' Location: ' + tastedAt;
		}
		str += '</div>';
	}
	return str;
}

function editSelected(pId) {
	var temp = (pId[0] == 'T');

	var title;
	if (temp) {
		title = tempProducts.get(pId)[0];
	} else {
		title = $$('div#selected_' + pId + ' h3')[0].innerHTML.strip();
	}

	commentsDialog.mode = DialogModes.Edit;
	commentsDialog.pId = pId;

	$('comments_form').reset();

	$('comments').value = $F('comments_for_' + pId);
	var selectedDateStr = $F('tasting_date_for_' + pId);
	if (selectedDateStr != "") {
		var dateBits = selectedDateStr.split('-');
		var selectedDate = new Date(dateBits[0],(parseInt(dateBits[1]) - 1),dateBits[2]);
		commentsCalendar.select(selectedDate);
		commentsCalendar.setMonth(selectedDate.getMonth());
		commentsCalendar.setYear(selectedDate.getFullYear());
		commentsCalendar.render();
	}
	$('tasted_at').value = $F('tasted_at_for_' + pId);

	var rating = selectedRating = parseInt($F('rating_for_' + pId));
	if (rating > 0) {
		var container = $$('div#rateStarContainer div[stars=' + rating + ']')[0];
		container.addClassName(intToTxt(rating) + 'StarsHighlighted');
		starsAreLocked = true;	
		$('star_text').update('<a href="#" onclick="changeRating(); return false;">change</a>');
	}

	$('comments_cal_container').style.display = "inline";
	$('comments_dialog_header').update('Your Review of \'' + title + '\'');
	commentsDialog.show();
}

function removeSelected(pId) {
	$('comments_for_' + pId).remove();
	$('rating_for_' + pId).remove();
	$('tasting_date_for_' + pId).remove();
	$('tasted_at_for_' + pId).remove();

	if (pId[0] == "T") { 
		$('name_for_' + pId).remove();
		$('desc_for_' + pId).remove();
	}

	selectedProducts = selectedProducts.without(pId);
	$('selected_product_ids').value = selectedProducts.join(',');

	Effect.Fade('selected_' + pId, { duration: 0.3, queue: 'end', afterFinish: function(obj) {
	       obj.element.remove();
	}});
	if ($('result_' + pId)) {
		Effect.Appear('result_' + pId, { durationg: 0.3, queue: 'end'});
		$('n_results').update(++nProducts);
	}

	if (selectedProducts.length == 0) {
		Effect.Fade('preview_publish_buttons', { duration: 0.5 });
	}

	autoSaveList();
}

function cancelComments() {
	commentsCalendar.clear();
	$('comments_cal_container').hide();
	commentsDialog.cancel();
}

function changeRating() {
	var starGroup;
	var starContainers;

	starsAreLocked = false;
	if (winelistId) {
		$('star_text_' + winelistId).update();
		starGroup = $('starContainer_' + winelistId);
		starContainers = $$('div#starContainer_' + winelistId +' div');
	} else {
		$('star_text').update();	
		starGroup = $('rateStarContainer');
		starContainers = $$('div#rateStarContainer div');
	}
	selectedRating = 0;

	for (var i = 0; i < starContainers.length; i++) {
		var nStars = parseInt(starContainers[i].readAttribute('stars'));
		var className = intToTxt(nStars) + 'StarsHighlighted';
		starContainers[i].removeClassName(className);
		starGroup.removeClassName(className);
	}
}

function rateListFailed(resp) {
	starsAreLocked = false;
	var starText;
	if (winelistId) {
		starText = $('star_text_' + winelistId);
	} else {
		starText = $('star_text');
	}
	starText.update();

	alert('We\'re sorry, we couldn\'t save your rating at this time. Please try again later.');
}

function ratedList(resp) {
	// do nothing. we've already assumed that everything has gone through
}

function handleClick(ev) {
	var elem = Event.element(ev);
	var stars = selectedRating = parseInt(elem.readAttribute('stars'));

	var starText;
	if (winelistId) {
		var callback = {
			success: ratedList,
			failure: rateListFailed
		}
		var tx = YAHOO.util.Connect.asyncRequest('GET','/winelists/_list-rate?id=' + winelistId + '&rating=' + stars, callback, null);
		starText = $('star_text_' + winelistId);
	} else {
		starText = $('star_text');
	}
	starsAreLocked = true;
	starText.update('<a href="#" onclick="changeRating(); return false;">change</a>');
}

function handleHover(ev) {
	if (starsAreLocked) { return; }

	var elem = Event.element(ev);
	var stars = parseInt(elem.readAttribute('stars'));

	elem.addClassName(intToTxt(stars) + 'StarsHighlighted');

	var rateText;
	if (winelistId != null) {
		rateText = $('star_text_' + winelistId);
	} else {
		rateText = $('star_text');
	}

	switch (stars) {
	case 1:
		rateText.update("hate it");
		break;
	case 2: 
		rateText.update("dislike it");
		break;
	case 3:
		rateText.update("average");
		break;
	case 4:
		rateText.update("like it");
		break;
	case 5:
		rateText.update("love it");
		break;
	}
}

function handleLeave(ev) {
	if (starsAreLocked) { return; }

	var elem = Event.element(ev);
	var stars = parseInt(elem.readAttribute('stars'));

	elem.removeClassName(intToTxt(stars) + 'StarsHighlighted');

	if (winelistId != null) {
		$('star_text_' + winelistId).update();
	} else {
		$('star_text').update();
	}
}

function submitTempWine() {
	if ($F('temp_prod_name').blank()) {
		alert('Please enter a value for \'Product Name\' before you continue.');
		return;
	}

	var prodName = $F('temp_prod_name');
	var prodDesc = $F('temp_prod_desc');

	// did we already add a fake product w/ this name?
	if (tempProducts.any(function(pair) { 
		return pair.value[0].toLowerCase() == prodName.toLowerCase(); 
	})) {
		alert('You have already added a product named \'' + prodName + '\' to your list.');
		return;
	}

	tempWineDialog.hide();

	commentsDialog.pId = 'T' + (nTempProducts++).toString();	
	commentsDialog.mode = DialogModes.AddTemp;
	commentsDialog.prodInfo = { product_name: prodName, product_desc: prodDesc };

	showCommentsDialog(prodName);
}

function cancelTempWine() {
	tempWineDialog.hide();
}

function checkMaxChars(ev) {
	// sadly, not thread safe
	if (checkingMaxChars) {
		checkingMaxChars = false;
		return;
	}
	checkingMaxChars = true;

	if (ev.charCode == 0) {
		return;
	}

	var el = Event.element(ev);
	var max = el.maxChars;
	var str = el.value;

	if (str.length > max) {
		el.value = str.substring(0,max);
		alert('You have exceeded this field\'s maximum of ' + max + ' characters.');
		Event.stop(ev);
	}

	checkingMaxChars = false;
}

function productAddLoaded() {
	// IE6 min-height workaround
	if ($('content_container').getHeight() < 450) {
		$('content_container').style.height = '450px';
	}

	YAHOO.util.Event.addListener('search_submit','click',doSearch);
	YAHOO.util.Event.addListener('search_term','keypress', function (ev) { if (ev.keyCode == 13) { doSearch(ev); } });
	YAHOO.util.Event.addListener('search_term','focus', function() { $('start_here_arrow_container').hide(); });
	
	YAHOO.util.Event.addListener('dialog_search_submit','click',doDialogSearch);
	YAHOO.util.Event.addListener('dialog_search_term','keypress', function (ev) { if (ev.keyCode == 13) { doDialogSearch(ev); } });

	// we do this here to avoid having to do it in the template
	$$('body')[0].addClassName('yui-skin-sam');	

	$('comments_dialog').style.display = "block";
	commentsDialog = new YAHOO.widget.Dialog('comments_dialog', { visible: false,
								      modal: true,
								      draggable: true,
								      fixedcenter: true,
								      postmethod: 'none',
								      hideaftersubmit: false,
								      constraintoviewport: true,
								      width: '540px',
								      buttons: [ {text: 'Add to List', handler: submitComments, isDefault: true},
								     		 {text: 'Cancel', handler: cancelComments } ] });
	commentsDialog.render();
	YAHOO.util.Event.addListener('tasted_at','keypress', function (ev) { if (ev.keyCode == 13) { submitComments(); } });
	
	$('temp_wine_dialog').style.display = 'block';
	tempWineDialog = new YAHOO.widget.Dialog('temp_wine_dialog', { visible: false,
								       modal: true,
								       draggable: true,
								       fixedcenter: true,
								       postmethod: 'none',
								       hideaftersubmit: true,
								       constraintoviewport: true,
								       width: '400px',
								       buttons: [ {text: 'Add to List', handler: submitTempWine, isDefault: true},
								     		  {text: 'Cancel', handler: cancelTempWine } ] });
	tempWineDialog.render();
	YAHOO.util.Event.addListener('temp_prod_name','keypress', function (ev) { if (ev.keyCode == 13) { submitTempWine(); } });

	// set up comment stars
	var starContainers = $$('div#rateStarContainer div');
	for (var i = 0; i < starContainers.length; i++) {
		Event.observe(starContainers[i],'mouseover',handleHover);
		Event.observe(starContainers[i],'mouseout',handleLeave);
		Event.observe(starContainers[i],'click',handleClick);
	}

	commentsCalendar = new YAHOO.widget.Calendar('comment_cal','comments_cal_container', {navigator: true, maxdate: new Date() });
	commentsCalendar.render();
	//commentsCalendar.hide();

	$('search_results_dialog').style.display = "block";
	searchResultsDialog = new YAHOO.widget.Panel('search_results_dialog', { visible: false,
								      		modal: true,
								      		fixedcenter: true,
								      		constraintoviewport: true,
									      	width: '800px' });
	searchResultsDialog.render();

	// max char checks
	$('wl_title').maxChars = 100;
	$('wl_description').maxChars = 1000;
	$('temp_prod_name').maxChars = 100;
	$('temp_prod_desc').maxChars = 200;
	$('tasted_at').maxChars = 100;
	$('comments').maxChars = 1000;

	var checkThese = ['wl_title','wl_description','temp_prod_name','temp_prod_desc','tasted_at','comments'];
	for (var i = 0; i < checkThese.length; i++) {
		YAHOO.util.Event.addListener(checkThese[i],'keypress', checkMaxChars);
		YAHOO.util.Event.addListener(checkThese[i],'blur', checkMaxChars);
	}
	
	// FF cursor hack
	var gecko = YAHOO.env.ua.gecko;
	var dialogs = [commentsDialog,tempWineDialog];
	if (gecko > 0 && gecko < 1.9) {
		for (var i = 0; i < dialogs.length; i++) {
			var dlg = dialogs[i];

			YAHOO.util.Dom.addClass(dlg.form, 'yui_caretfix');	
			dlg.showEvent.subscribe(function() {
				YAHOO.util.Dom.setStyle(dlg.form, "display", "none");
				var fixDisplay = function() {
					YAHOO.util.Dom.setStyle(dlg.form, "display", "block");
					try {
						dlg.firstFormElement.focus();	
					} catch (e) { 

					}
				}
				setTimeout(fixDisplay, 0);
			});
		}
	}

	var arrowAnimation = new YAHOO.util.Anim('start_here_arrow_container', { right: { from: 1000, to: 0 } }, 1, YAHOO.util.Easing.easeOutStrong);
	arrowAnimation.animate();	
}

function showMoreTopRated() {
	Effect.toggle('more_top_rated','appear');
	if (moreTopRated) {
		moreTopRated = false;
		$('more_top_rated_link').update('See More Top Rated');
	} else {
		moreTopRated = true;
		$('more_top_rated_link').update('See Fewer Top Rated');
	}
}

function showTempWineDialog() {
	$('temp_prod_name').value = '';
	$('temp_prod_desc').value = '';	
	tempWineDialog.show();
}

function listViewLoaded(type,args,obj) {
	winelistId = obj;

	// set up comment stars
	var starContainers = $$('div#starContainer_' + winelistId +' div');
	for (var i = 0; i < starContainers.length; i++) {
		Event.observe(starContainers[i],'mouseover',handleHover);
		Event.observe(starContainers[i],'mouseout',handleLeave);
		Event.observe(starContainers[i],'click',handleClick);
	}

	if ($('changeLink_' + winelistId)) {
		starsAreLocked = true;
		Event.observe('changeLink_' + winelistId, 'click', changeRating);
	}
}

function checkProductCount() {
	if (checkProdCountOnExit && selectedProducts.length < 3) {
		return "--> Notice: Your Wine List needs at least *three* products before we can display it on our site.\n\nClick 'Cancel' below to continue adding products. If you'd prefer to finish later, click 'OK' -- you can continue working on this list at any time by clicking the 'My Wine Lists' link at the top of this page.\n\nIf you experienced difficulty in using this tool, we'd be most grateful if you'd use the 'Site Feedback' link in the footer of any WineAccess page to tell us about it.";
	}
}

function initWLSearch() {
	var input = $('q');

	var defText = input.readAttribute('deftext');
	if (input.value == '') {
		input.value = defText;
	}

	Event.observe('q', 'focus', function () { 
		$('q').value = ''; 
		Event.stopObserving('q','focus');
	});
}
