var imported = new Hash();
if (document.cookie) {
	var cookies = document.cookie.split(";");
	for (var i=0; i < cookies.length; i++) {
		var cookie = cookies[i].split("=");
		imported[cookie[0].replace(/^\s+/, '')] = unescape(cookie[1]);
	}
}

var lengths = $H({
	M: [
		new Option("Men's minus 1 inch", "mm1"),
		new Option("Men's minus 1/2 inch", "mm.5"),
		new Option("Men's Standard", "m0", true),
		new Option("Men's plus 1/2 inch", "mp.5"),
		new Option("Men's plus 1 inch", "mp1"),
		new Option("Men's plus 1 1/2 inches", "mp1.5")
	],
	F: [
		new Option("Ladies' minus 1 inch", "wm1"),
		new Option("Ladies' minus 1/2 inch", "wm.5"),
		new Option("Ladies' Standard", "w0", true),
		new Option("Ladies' plus 1/2 inch", "wp.5"),
		new Option("Ladies' plus 1 inch", "wp1"),
		new Option("Ladies' plus 1 1/2 inches", "wp1.5")
	]
});

var flexes = $H({
	M: [new Option("Extra Stiff", "x"), new Option("Stiff", "s"), new Option("Regular", "r", true), new Option("Senior", "A")],
	F: [new Option("Ladies'", "l", true)]
});

// Set length and flex defaults based on cookies.
if (imported.gender) {
	if (imported.length) {
		var options = lengths[imported.gender];
		for (i=0; i < options.length; i++) options[i].defaultSelected = (options[i].value == imported.length);
	}
	
	if (imported.flex) {
		var options = flexes[imported.gender];
		for (i=0; i < options.length; i++) options[i].defaultSelected = (options[i].value.toUpperCase() == imported.flex);
	}
}			

var default_shaft = "";
var default_grip  = "";

function changeGender() {
	var theForm = document.purchase;	
	var gender  = theForm.gender.value;
	var selectedIndex;
	
	if (gender == "nogender") return;
	
	// Populate the flex selection box.
	if (theForm.customflex && theForm.customflex.type != "hidden") {
		theForm.customflex.options.length = 0;
		selectedIndex = 0;
		for (i = 0; i < flexes[gender].length; i++) {
			theForm.customflex.options[i] = flexes[gender][i];
			if (flexes[gender][i].defaultSelected) selectedIndex = i;
		}
		theForm.customflex.disabled = false;
		theForm.customflex.selectedIndex = selectedIndex;
		changeFlex();
	}
	
	// Populate the length selection box.
	if (theForm.customlength && theForm.customlength.type != "hidden") {
		theForm.customlength.options.length = 0;
		selectedIndex = 0;
		for(i = 0; i < lengths[gender].length; i++) {
			theForm.customlength.options[i] = lengths[gender][i];
			if (lengths[gender][i].defaultSelected) selectedIndex = i;
		}
		theForm.customlength.disabled = false;
		theForm.customlength.selectedIndex = selectedIndex;
	}
	
	// Populate grip selection box.
	if (theForm.customgrip && theForm.customgrip.type != "hidden") {
		theForm.customgrip.options.length = 0;
		selectedIndex = 0;
		for(var i=0, j=0; i < grips.length; i++) {
			if (grips[i].gender == gender) {
				var grip = grips[i];
				var display = grip.name;
				if (grip.price != 0) display += " +" + formatPrice(grip.price) + " ea.";
				if (grip.model == default_grip) selectedIndex = j;
				theForm.customgrip.options[j++] = new Option(display, grip.model);
			}
		}
		theForm.customgrip.disabled = false;
		theForm.customgrip.selectedIndex = selectedIndex;
	}
}

// Set the shaft selection options based on the selected flex.
function changeFlex() {
	var theForm = document.purchase;
	var gender  = theForm.gender.value;
	var flex    = theForm.customflex.value;
	
	// Clear shaft options.
	if (theForm.customshaft.type == "hidden") return;

	var children = theForm.customshaft.childNodes;
	while (theForm.customshaft.childNodes.length) {
		theForm.customshaft.removeChild(theForm.customshaft.lastChild);
	}
	
	if (gender == "nogender" || flex == "noflex") return;
	
	// Populate shaft selection options.
	var selectedIndex = 0;
	var j = 0;
	shafts.keys().each(function(material) {		
		// Create an optgroup for the material.
		var optGroup = document.createElement("optgroup");
		optGroup.setAttribute("label", material.charAt(0).toUpperCase() + material.substring(1));
		
		for (i=0; i < shafts[material].length; i++) {
			var shaft = shafts[material][i];
			if (shaft.gender == gender && shaft.flex == flex) {
				var display = shaft.name;
				if (shaft.price != 0) display += " +" + formatPrice(shaft.price) + " ea.";
				if (shaft.model == default_shaft) selectedIndex = j;
				
				// Create the option and add it t the group.
				var option = document.createElement("option");
				option.setAttribute("value", shaft.model);
				option.innerHTML = display;
				optGroup.appendChild(option);
				j++;
			}
		}
		
		theForm.customshaft.appendChild(optGroup);
	});
	theForm.customshaft.disabled = false;
	theForm.customshaft.selectedIndex = selectedIndex;
	try { theForm.customshaft.options[selectedIndex].selected = true; } catch (e) {}
	
	updateTotal();
}

function updateTotal() {
	var theForm = document.purchase;
	
	// Get product info
	var totalClubCount = 0;
	var totalPrice  = 0.00;
	
	// Get the products selected from the product lists.
	$$('.productlist input[type="checkbox"]').each(function(product_cbx) {
		if (product_cbx.checked) {
			var product = products[$F(product_cbx).split('~')[0]];
			totalClubCount += product.clubcount;
			totalPrice     += product.price;
		}
	});
	
	// Get shaft info
	var shaft;
	if (theForm.customshaft) shafts.keys().each(function (material) {
		shafts[material].each(function(s) {
			if (s.model == $F(theForm.customshaft)) {
				shaft = s; throw $break;
			}
		});
	});
	
	// Get grip info
	var grip;
	if (theForm.customgrip) grips.each(function(g) {
		if (g.model == $F(theForm.customgrip)) {
			grip = g; throw $break;
		}
	});
	
	if (totalClubCount) {
		if (shaft) totalPrice += shaft.price * totalClubCount;
		if (grip)  totalPrice += grip.price  * totalClubCount;
	}
	
	// Update the price display on the form.
	$('total').update(formatPrice(totalPrice));
	
	// Update the submit buttons state.
	enableSubmit();
}

function validate() {
	var theForm = document.purchase;
	var errorMsg = "";
	
	var somethingSelected = false;
	$$('.productlist input[type="checkbox"]').each(function(product) {
		if (product.checked) {
			somethingSelected = true;
			throw $break;
		}
	});
	
	if (!somethingSelected) errorMsg += "Please select a product.\n";
	
	if (theForm.gender && theForm.gender.value == "nogender") errorMsg += "Please select a gender.\n";
	return errorMsg;
}

var submit_img = {enabled: "/images/cart/add2cart.png", disabled: "/images/cart/add2cart_disabled.png"};
function enableSubmit() {
	var err = validate();
	var submitBtn = document.purchase.add2cart || document.getElementById("add2cart");
	if (err.length) {
		//submitBtn.disabled = true;
		submitBtn.className = "disabled";
	} else {
		//submitBtn.disabled = false;
		submitBtn.className = "";
	}
}

function verifySubmit() {
	var err = validate();
	if (err.length) {
		alert(err);
		return false;
	}
	return true;
}

/*** Navigation functions ***/
function gotoAnchor(name) {
	// Find the anchor specified.
	var theNode;
	for (var i = 0; i < document.anchors.length; i++) {
		if (document.anchors[i].getAttribute("name") == name) {
			theNode = document.anchors[i];
			break;
		}
	}
	
	// Determine the location of the anchor in the document.
	var dest_y = theNode.offsetTop;
	while (theNode.offsetParent && theNode.offsetParent != document.body) {
		theNode = theNode.offsetParent;
		dest_y += theNode.offsetTop;
	}
	
	window.scrollTo(0, dest_y);	
	return false;
}

function gotoTop() {
	window.scrollTo(0,0);
	return false;
}

/*** AJAX helper functions. ***/

/* Load a page of reviews on the page. */
function load_reviews(subcat, page, page_size) {
	page = page || 1;
	page_size = page_size || 10;
	
	new Ajax.Updater('review_contents', '/golf-clubs/_reviews.html', {
		parameters: { subcat: subcat, page: page, pg_size: page_size },
		onComplete: function() { gotoAnchor('reviews') }
	});
}

/* Vote on the helpfulness of a review. */
function review_vote(id, vote) {
	new Ajax.Updater('vote_' + id, '/golf-clubs/_vote.html', {
		parameters: { id: id, vote: vote }
	});
}

/* Load the review editor. */
function write_review(model) {
	new Ajax.Updater({success: 'add_review'}, '/golf-clubs/_write_review.html', {
		parameters: { model: model },
		onSuccess: function(req) {
			$('add_review_wrapper').hide();
		},
		onComplete: function() {
			Effect.BlindDown('add_review_wrapper');
		}
	});
}

function submit_review() {
	var submit_request = $('write_review').request({
		onSuccess: function(req) {			
			var children = req.responseXML.documentElement.childNodes;
			var response_txt = '';
			for (var i=0; i < children.length; i++) {
				response_txt = response_txt + children[i].data;
			}
			
			switch(req.responseXML.documentElement.tagName) {
				case "review":
					Effect.BlindUp('add_review_wrapper');
					load_reviews($('write_review').model.value);
					
					if (response_txt) {
						Effect.Highlight('review_' + response_txt);
					}
					break;
				case "error":
					alert(response_txt);
					break;
			}
		},
		onFailure: function(req) {
			alert("Status: " + req + "\n" +
				"Response: " + req.responseText
			);
		}
	});
	
	return false;
}

/*** Function to get called when the page loads. ***/
window.onload = function() {
	if (document.purchase) {
		changeGender();
	}
};
