try { document.execCommand('BackgroundImageCache', false, true); } catch(e) {}; //ie 6 bg image fix
var SCROLL_SPEED = 400;
//$(function(){
//	$('.fillin').inputLabel();
//	$('.dropdown select').change(function(){
//		var val = $('option:selected', this).text();
//		$(this).prev().html(val);
//	})
//});

$(function(){
	$('.fillin').inputLabel();
	$('#sort_by').change(function(){
		$('#sort_by_value').html($('#sort_by :selected').text());
	});
	
	$('.scrollto').click(function(){
		var name = $(this).attr('href').substr(1);
		$.scrollTo($('a[name="' + name + '"]'), SCROLL_SPEED);
		return false;
	});
});

function clearForm(formID)
{
	var selector = "#" + formID;
	$(':input',selector)
		.not(':button, :submit, :reset, :hidden')
		.val('')
		.removeAttr('checked')
		.removeAttr('selected');
}

function buildFormSubmitUrl(formID, action)
{
	try
	{
		// Build a buffer of all the name/value pairs from the form
		var buffer = "";
		var selector = "#" + formID + " :input";
		$(selector).each(function(index, e) {
			var itype = $(e).attr('type');
			if (typeof(itype) != "undefined")
				itype = itype.toLowerCase();
			else
				itype = "other";
			if (itype == "checkbox")
			{
				if ($(e).attr('checked'))
				{
					buffer = addQueryParam(buffer, e.name, $(e).val());
				}
				else
				{
					buffer = addQueryParam(buffer, e.name, "false");
				}
			}
			else if (itype == "radio")
			{
				if ($(e).attr('checked'))
				{
					buffer = addQueryParam(buffer, e.name, $(e).val());
				}
			}
			else
			{
				buffer = addQueryParam(buffer, e.name, $(e).val());
			}
			
		});
		
		// Get the 'action' of the form
		if (!action)
			action = $("#" + formID).attr("action");
		
		// Build the URL... If the base action already has query-string params,
		// then use "&" as the separator...
		var url = (action.indexOf("?" < 0)) 
			? action + "?" + buffer
			: action + "&" + buffer;
		
		return url;
	}
	catch(ex)
	{
		alert("ERROR: " + ex);
	}
}

function addQueryParam(buffer, name, val)
{
	if (buffer.length > 0)
		buffer = buffer + "&";
	buffer = buffer + name + "=" + encodeURIComponent(val);
	return buffer;
}

function jsDecodeHtmlEntities(input)
{
	return input.replace(/&#(\d+);/g,
						 function(wholematch, parenmatch1)
						 {
							 return String.fromCharCode(+parenmatch1);
						 });
}

function initDialog(dialogId, isModal)
{
	var selector = "#" + dialogId;
	$(selector).jqm({
		toTop: true,
		modal: isModal,
		onShow: function(){
			$(selector).stop().show();
		},
		
		onHide: function(){
			$(selector).stop().hide();
			$('.jqmOverlay').stop().hide();
		}
	 
	});
}

function showDialog(dialogId)
{
	var selector = "#" + dialogId;
	$(selector).jqmShow();
}

function closeDialog(dialogId)
{
	var selector = "#" + dialogId;
	$(selector).jqmHide();
}

function jsSubmitForm(formId, overlayId)
{
	if (overlayId != null)
	{
		showDialog(overlayId);
	}
	
	var formSelector = "#" + formId;
	$(formSelector).submit();
	return false;
}

function jsValidateDate(elementId, errorMessage)
{
	//	Requires 1 or 2 digits for month and day. Day must be less than 32. Year must be 4 digits
	var reg_1 = new RegExp("^[0,1]?\\d{1}[\\.\\-/](([0-2]?\\d{1})|([3][0,1]{1}))[\\.\\-/](([1]{1}[9]{1}\\d{1}\\d{1})|([2-9]{1}\\d{3}))$");
	if ( reg_1.test($(elementId).val()) )
	{
		return null;
	}
	return errorMessage;
}

function jsValidatePhone(elementId, errorMessage, emptyOk)
{
	var text = $(elementId).val();
	if (emptyOk && text.length == 0)
	{
		return null;
	}

	var reg_1 = new RegExp("(\\d{3})\\D*(\\d{3})\\D*(\\d{4})\\D*(\\d*)$");
	if ( reg_1.test(text))
	{
		return null;
	}
	return errorMessage;
}

function jsValidatePositiveInteger(elementId, errorMessage)
{
	var value = $(elementId).val();
	if (isNaN(value) || value < 0)
	{
		return errorMessage;
	}
}

function jsValidateAreNotEmpty(idList)
{
	//	Iterate through a list of element ids that are comma-separated
	var idArray = idList.split(",");
	for (var index = 0; index < idArray.length; index++)
	{
		var elementId = idArray[index];
		var valueLength = $(elementId).val().length;
		if (valueLength > 0)
		{
			//	If any of the specified elements have any data then this test fails
			return null;
		}
	}
	return "All fields are empty";
}

function jsValidateEqualIgnoreCase(elementId1, elementId2, errorMessage)
{
	var text1 = $(elementId1).val().toLowerCase();
	var text2 = $(elementId2).val().toLowerCase();

	if (text1 == text2)
		return null;
	return errorMessage;
}

function jsValidateBirthDate(dayId, monthId, yearId, errorMessage)
{
	var day = $(dayId).val();
	var month = $(monthId).val();
	var year = $(yearId).val();

	//	We subtract one from the month because months range from 0-11
	var birthdate = new Date(year, month - 1, day, 0, 0, 0, 0);

	//	Add 21 years to the birthdate and see if it is newer than today
	birthdate.setFullYear(birthdate.getFullYear() + 21);
	var todaysDate = new Date();
	if (birthdate > todaysDate)
	{
		return errorMessage;
	}
	return null;
}

function jsYav(formId, errorMessage, errorId)
{
	if (!errorId)
	{
		errorId = "#generalError";
	}

	//	Reset the errors from last time
	if (typeof(jsErrors) != "undefined")
	{
		for (index = 0; index < jsErrors.length; index++)
		{
			$(jsErrors[index]).removeClass("error");
		}
		$(errorId).addClass("hidden");
	}

//	alert(rules);
	var yavResult = yav.performCheck(formId, rules, 'jsVar');
//	alert(yavResult);

	if (yavResult == false)
	{
//		alert(jsErrors);
		for (index = 0; index < jsErrors.length; index++)
		{
			$(jsErrors[index]).addClass("error");
		}
		if (errorMessage)
		{
			$(errorId).text(errorMessage);
		}
		$(errorId).removeClass("hidden");

		//	Scroll to show the error message
		$('html, body').animate({ scrollTop: $(errorId).position().top }, 500);
	}
	else
	{
		return true;
	}
	return false;
}

function jsYavAndSubmitForm(formId, errorMessage, errorId)
{
	if (jsYav(formId, errorMessage, errorId))
	{
		return jsSubmitForm(formId);
	}
	return false;
}

function appendQueryParameter(url, name, value)
{
	// No parameter?  Fine - just return the URL we've got...
	if ((name == null) || (name == ""))
	{
		return url;
	}
	
	// Sanity check on the value...
	if (value == null)
	{
		value = "";
	}
	
	if (url.indexOf("?") > 0)
	{
		url = url + "&";
	}
	else
	{
		url = url + "?";
	}
	
	return url + name + "=" + encodeURIComponent(value);
}

function showGiftCardBalanceDialog()
{
	var url = httpsBase + "control/giftCardBalance";
	return popupCenteredWindow(url, 260, 400, "balance");
}

function popupCenteredWindow(url, height, width, windowName) 
{
	var left   = (screen.width  - width)/2;
	var top    = (screen.height - height)/2;
	
	windowName = "_blank";
	
	var params = 'width='+width+', height='+height;
	params += ', top='+top+', left='+left;
	params += ', directories=no';
	params += ', location=no';
	params += ', menubar=no';
	params += ', resizable=no';
	params += ', scrollbars=no';
	params += ', status=no';
	params += ', toolbar=no';
	
	popup = window.open(url, windowName, params);
	if ((popup != null) && (popup.focus != null)) 
		popup.focus()

	return false;
}

function init_form_dialog_with_size(form_name, validateFn, width, height)
{
	var jname = "#" + form_name;

	$(jname).dialog({
		bgiframe: true,
		autoOpen: false,
		height: height,
		width: width,
		modal: true,
		resize: false,
		buttons: {
			OK: function() {
				var bValid = true;
				var xname = form_name + "_form";
				var htmlForm = document.forms[xname];

				if (validateFn != null)
					bValid = validateFn(htmlForm);

				if (bValid) {
					$(this).dialog('close');
					// submit the form!
					htmlForm.submit();
				}
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		},
		close: function() {
		}
	});
}

function show_form_dialog(form_name)
{
	var jname = "#" + form_name;
	$(jname).dialog('open');
}

// Tinybox specific method for embedding YouTube (ONLY) based videos
function handleVideoClick(link, label) {
	// Google analytics event tracking for all videos
	_gaq.push(['_trackEvent', 'Video', 'Play', label]);

	// Load the actual video
	TINY.box.show({
		iframe: 'http://www.youtube.com/embed/'+ link +'?autoplay=1&autohide=1&bcontrols=1&border=1&rel=0&probably_logged_in=0',
		width: 660,
		height: 450
	});
}

//Tinybox specific method for showing the zoomed version of product images
function handleImageZoom(image, label) {
	// Google analytics event tracking for all videos
	_gaq.push(['_trackEvent', 'Product', 'Image Zoom', label]);

	// Load the actual video
	TINY.box.show({
		image: image,
		width: 600,
		height: 600
	});
}

//Google Analytics event specific tracking
function handleGAClickEvent(generalCategory, clickType, label) {
	// Google analytics event tracking
	_gaq.push(['_trackEvent', generalCategory, clickType, label]);
}

//	Used for membership bottle selection pages
var gExtraBottleCount = 0;
function computeSubtotal()
{
	var subtotal = 0;
	var fullSubtotal = 0;
	var numItems = 0;

	$('.quantity_input').each(function(index)
	{
		var lineItems = parseInt($(this).val());
		if (isNaN(lineItems))
		{
			$(this).val("");

			lineTotalFullId = "#" + $(this).attr('lineTotalFullId');
			$(lineTotalFullId).text("");
			lineTotalId = "#" + $(this).attr('lineTotalId');
			$(lineTotalId).text("");
		}
		else
		{
			lineTotal = lineItems * $(this).attr('price');
			lineTotalFull = lineItems * $(this).attr('fullPrice');
			subtotal += lineTotal;
			fullSubtotal += lineTotalFull;
			numItems += lineItems;

			lineTotalFullId = "#" + $(this).attr('lineTotalFullId');
			$(lineTotalFullId).text("$" + lineTotalFull.toFixed(2));
			lineTotalId = "#" + $(this).attr('lineTotalId');
			$(lineTotalId).text("$" + lineTotal.toFixed(2));
		}
	});

	$('#subtotal').text("$" + subtotal.toFixed(2));

	gExtraBottleCount = numItems;
	return subtotal;
}

function areSelectionsMade(numBottles, errorMessage)
{
	for (index = 1; index <= numBottles; index++)
	{
		var selector = "input[name='choice[" + index + "]']:checked";
		var choice = $(selector).val();
		if (typeof(choice) == "undefined")
		{
			if (!errorMessage)
				errorMessage = "Please select your club wines.";
			alert(errorMessage);
			return false;
		}
	}
	return true;
}

