function loadCalendar(div, startYear, startMonth) {
	startYear = parseInt(startYear, 10);
	startMonth = parseInt(startMonth, 10);
	
	baseYear = parseInt(window._data_baseMonth.year, 10);
	baseMonth = parseInt(window._data_baseMonth.month, 10);
	baseOffset = parseInt(window._data_baseMonth.offset, 10);
	
	baseMonthCount = (baseYear * 12) + baseMonth;
	startMonthCount = (startYear * 12) + startMonth;
	
	offset = startMonthCount - baseMonthCount + baseOffset;

	// Load Calendar
	new Ajax.Updater(div, '/calendar/display/' + offset + '/100',
		{
			//asynchronous: false,
			onComplete: function(request, json) {
				stopCalendarDayLinks();
				calenderShakeOnBadClick();
				calendarHighlightOnGoodClick();
			}
		}
	);

}

function loadClubSelections(startYear, startMonth) {
	if(typeof startYear == 'undefined' || startYear === null) startYear = window._data_baseMonth.year;
	if(typeof startMonth == 'undefined' || startMonth === null) startMonth = window._data_baseMonth.month;
	
	var clubProductId = $('ClubCartItemProductId').value;
	var url = '/storefront/club_selections/' + clubProductId + '/';
	if(!(typeof startYear == 'undefined' || startYear === null) && !startYear.toString().blank()) {
		url = url + startYear + '/';
		
		if(!(typeof startMonth == 'undefined' || startMonth === null) && !startMonth.toString().blank()) {
			url = url + startMonth + '/';
		}
	}
	
	new Ajax.Updater('clubSelectionsContainer', url,
		{
			method: 'get',
			onComplete: function(request, json) {
				observeClickInputs();
				observeClickInputContainers();
				clubSummary.setSelectedCount(countCheckedClubSelections(), true);
				//countCheckedClubSelections();
			},
			evalScripts: true
		}
	);
}

function findCheckedClubSelections() {
	return $$('tr.club_selection_container.selection_real.club-highlight input[type="radio"]');
}

function countCheckedClubSelections(inputs) {
	inputs = (typeof inputs == "undefined") ? findCheckedClubSelections() : inputs;
	return inputs.length;
}

function findCheckedClubSelectionIds(inputs) {
	inputs = (typeof inputs == "undefined") ? findCheckedClubSelections() : inputs;

	var selectionIds = new Array();
	inputs.each(function(input) {
		selectionIds.push($(input).getValue());
	});
	
	return selectionIds;
}

function findInput(inputContainer) {
	return $(inputContainer).down('input[type="radio"]');
}

function findInputContainer(input) {
	return $(input).up('.club_selection_container');
}

function findMonthContainer(child) {
	return $(child).up('.club_month_container');
}

function removeInputContainerHighlights(monthContainer) {
	$(monthContainer).select('.club_selection_container.club-highlight').invoke('removeClassName', 'club-highlight');
}

function observeClickInputs() {
	$$('.club_selection_container input[type="radio"]').invoke('observe', 'click',
		function(event) {
			event.stopPropagation();
			
			removeInputContainerHighlights(findMonthContainer(this));
			findInputContainer(this).addClassName('club-highlight');
			Effect.Queues.get('floating_box').invoke('cancel');
			new Effect.Highlight(
				$('floating_box_body'),
				{startcolor: '#ffff99', endcolor: '#ffffff', restorecolor: '#ffffff', afterSetup: function() {clubSummary.setSelectedCount(countCheckedClubSelections(), true)}, queue: {scope: 'floating_box'}}
			);
			// clubSummary.setSelectedCount(countCheckedClubSelections(), true);
		}
	);
}

function observeClickInputContainers() {
	$$('.club_selection_container').invoke('observe', 'click',
		function(event) {
			findInput(this).click();
		}
	);
}

function observeChangeStartMonth() {
	$('ClubCartItemStartMonth').observe('change',
		function(event) {
			pieces = this.value.split('-');
			if(pieces.length >= 2) {
				month = parseInt(pieces[0], 10);
				year = parseInt(pieces[1], 10);
				loadCalendar('my_cal', month, year);
				loadClubSelections(month, year);
			}
		}
	);
}

function toggleDisplayCartRecipientNick() {
	var input = $('ClubCartItemMetaRecipientId');
	var container = $('CartRecipientNickContainer');
	
	if(input.value == "4::" && !container.visible()) {
		Effect.SlideDown(container, {duration: 0.25});
	} else if(container.visible()) {
		Effect.SlideUp(container, {duration: 0.25});
	}
}

function toggleDisplayCalendar() {
	var input = $('ClubCartItemStartMonth');
	var container = $('conditional_calendar');
	
	if(input.value != "" && !container.visible()) {
		Effect.SlideDown(container, {duration: 0.25});
	} else if(input.value == "" && container.visible()) {
		Effect.SlideUp(container, {duration: 0.25});
	}
}

function ClubSummary() {
	this.selectedCount = 0;
	this.priceEach = null;
	this.priceTotal = 0;
	this.tiers = null;
	this.countTiers = null;

	this.formatPrice = function(price) {
		var output = '';
		if(price === null) {
			output = '--';
		} else {
			output = '$' + (price/100).toFixed(2);
		}
		
		return output;
	}
	this.loadPricing = function(jsonPricing) {
		this.tiers = jsonPricing.tiers;
		this.countTiers = jsonPricing.countTiers;
	}
	this.setSelectedCount = function(count, publish) {
		if(typeof publish == 'undefined') publish = false;
		
		this.selectedCount = count;

		if(publish) this.publish();
	}
	this.calculate = function() {
		count = this.selectedCount
		if(count == 0) {
			priceEach = this.tiers[1].price_each;
			priceTotal = 0;
		} else {
			tierId = this.countTiers[count];
			tier = this.tiers[tierId];
			
			priceEach = tier.price_each;
			priceTotal = (tier.price_total === false) ? (count * priceEach) : tier.price_total;

		}
		
		this.priceEach = priceEach;
		this.priceTotal = priceTotal;
	}
	this.publish = function() {
		this.calculate();

		if(this.selectedCount == 0) {
			$('club_summary_price_each_comment').update('Starts at ');
		} else {
			$('club_summary_price_each_comment').update('');
		}
		
		$('club_summary_selected_count').update(this.selectedCount);
		$('club_summary_price_total').update(this.formatPrice(this.priceTotal));
		$('club_summary_price_each').update(this.formatPrice(this.priceEach));
		
	}
}

clubSummary = new ClubSummary();

function confirmSelections(inputs) {
	if(typeof inputs == 'undefined') inputs = findCheckedClubSelections();
	var selectionIds = findCheckedClubSelectionIds(inputs);
	var selections = $H(window._data_clubSelections);
	var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

	var header = '-[ Your Club Summary ]-';
	var body = '';
	var footer = 
	"Click 'Cancel' to stop and make changes.\n" +
	"Click 'OK' to accept these selections.";

	selectionIds.each(function(id) {
		selection = selections.get(id);

		body += (monthNames[(selection.month - 1)] + ": " + selection.name + "\n");
	});
	
	return confirm(header +  "\n\n" + body + "\n\n" + footer + "\n");
}

function validateForm() {
	var inputs = findCheckedClubSelections();

	var metaRecipient = $('ClubCartItemMetaRecipientId');
	if(metaRecipient.getValue().empty()) {
		alert("Oops! You have not chosen a recipient!");
		return false;
	}
	
	var recipientNick = $('CartRecipientNick');
	if(metaRecipient.getValue() == '4::' && recipientNick.getValue().empty()) {
		alert("Oops! You forgot to give us a nickname for the new recipient!");
		return false;
	}

	if($('ClubCartItemStartMonth').getValue().empty()) {
		alert("Oops! You have not chosen a start month!");
		return false;
	}

	var deliveryDate = $('ClubCartItemDeliveryDate');
	if(deliveryDate.getValue().empty()) {
		alert("Oops! You have not chosen a delivery date!");
		return false;
	}

	if(countCheckedClubSelections(inputs) == 0) {
		alert("Oops! You haven't made any selections yet!");
		return false;
	}
	
	var datePieces = deliveryDate.getValue().split('-');
	var hasFirstSelection = false;
	var selections = $H(window._data_clubSelections);
	findCheckedClubSelectionIds(inputs).each(function(id) {
		selection = selections.get(id);
		year = datePieces[0];
		month = datePieces[1];

		if(parseInt(selection.month, 10) == parseInt(month, 10) && parseInt(selection.year, 10) == parseInt(year, 10)) {
			hasFirstSelection = true;
			throw $break;
		}
	});
	if(!hasFirstSelection) {
		alert("Oops! You haven't made a selection for the first month!");
		return false;
	}

	if(!confirmSelections(inputs)) return false;
	
	return true;
}

function adjustBoxPosition() {
	//if(window._isScrolling) return;

	var threshold = 15; // px
	var i = $('floating_box');
	var x = $('floating_box_rail');
	
	
	var posTop = document.viewport.getScrollOffsets().top + threshold;
	var posLeft = x.positionedOffset().left;

	if(posTop < x.positionedOffset().top) {
		posTop = x.positionedOffset().top;
	}

	i.setStyle({
		position: 'absolute',
		top: (posTop + 'px'),
		left: (posLeft + 'px')
	});

}

// Used in IE to avoid bizaar position values while resizing
function setResizeTimer(length) {
	if(length === null || typeof length === "undefined") length = 1;
	
	if(window._resizingTimer === false) {
		window._resizingTimer = true;
		new PeriodicalExecuter(
			function(pe) {
				if(!window._isResizing) {
					adjustBoxPosition(true);
					window._resizingTimer = false;
					pe.stop();
				}
			},
			length
		);
	}
}

// Used in IE to avoid bizaar position values while scrolling
function setScrollTimer(length) {
	if(length === null || typeof length === "undefined") length = 1;
	
	if(window._scrollingTimer === false) {
		window._scrollingTimer = true;
		new PeriodicalExecuter(
			function(pe) {
				if(!window._isScrolling) {
					adjustBoxPosition(true);
					window._scrollingTimer = false;
					pe.stop();
				}
			},
			length
		);
	}
}

// Things to do after the page loads
Event.observe(document, 'dom:loaded', function(event) {

	// Hide the container
	toggleDisplayCartRecipientNick();
	//toggleDisplayCalendar();
	
	// Set position of club summary box
	adjustBoxPosition();
	$('floating_box').show();

	// Load club selections
	loadClubSelections();
	
	// observe start month change
	observeChangeStartMonth();

	// On change, hide/show the container
	Event.observe($('ClubCartItemMetaRecipientId'), 'change', toggleDisplayCartRecipientNick);
	//Event.observe($('ClubCartItemStartMonth'), 'change', toggleDisplayCalendar);
	
	// On submit, display summary of selections as confirm dialogue
	$('ClubItemAddForm').observe('submit', function(event) {
		event.stop();

		if(!validateForm()) return;

		this.submit();
	});
	$('fake_add_to_cart').observe('click', function(event) {
		if(!validateForm()) return;
		
		$('ClubItemAddForm').submit();
	});

	if(Prototype.Browser.IE) {
		window._isResizing = false;
		window._resizingTimer = false;
		Event.observe(window, 'resize', function(event) {
			window._isResizing = true;
			setResizeTimer(.05);
			window._isResizing = false;
		});
		window._isScrolling = false;
		window._scrollingTimer = false;
		Event.observe(window, 'scroll', function(event) {
			window._isScrolling = true;
			setScrollTimer(.05);
			window._isScrolling = false;
		});
	} else {
		Event.observe(window, 'resize', function(event) {
			adjustBoxPosition();
		});
		Event.observe(window, 'scroll', function(event) {
			adjustBoxPosition();
		});
	}

});



