function fetchSelector() {
	$.ajax({
		url: "/diamonds/selector",
		cache: true,
		dataType: "html",
		success: function(html){
		var sd = $("#diamond-selector noscript");
		if(sd) { // If the element exists insert HTML into it
			sd.replaceWith(html);
		bindSelector();
		}
		else { // Otherwise save for later
			$().data("selector-html", html);
		}
	}
	});
}

fetchSelector(); // Fetch the selector whilst the page is loading

function insertSelector() {
	var sh = $().data("selector-html");
	if(sh) {
		$().removeData("selector-html");
		$("#diamond-selector noscript").replaceWith(sh);
		bindSelector(); 
	}
}

function setHiddenValue(item, field) {
	var id_re = /value_(\S+)/;
	var matches = id_re.exec( $(item).attr("class") );
	$(field).attr("value", matches[1]);	
}

function bindSelector() {

	$("#diamond-selector .dropdown").click( function() {
		$(this).find("ul").slideToggle("normal");
	});

	$("#shape-selector li").click( function() {
		setHiddenValue(this, "#DiamondShapeId");
		$("#shape-selector .selected").html( $(this).html() );
	});	

	$("#price-selector li").click( function() {
		setHiddenValue(this, "#DiamondPriceRange");
		$("#price-selector .selected").html( $(this).html() );
	});

	$("#selector-find").click( function() {
		
		// Get the values of the labels for search tracking
		var shape_label = $("#shape-selector .selected").text();
		var price_label = $("#price-selector .selected").text();
		
		// Strip out the diamond count ie (23)
		var matches = shape_label.match(/([A-Za-z]+)/);
		if(matches) { shape_label = matches[1]; }

		// Track search in Google events
		try {
			pageTracker._trackEvent('Diamonds', 'Search', shape_label+" - "+price_label); 
		}
		catch(err) { }		
		
		var form = $("form#DiamondIndexForm");

		$.ajax({
			type: "POST",
			url: form.attr('action'),
			data: form.serialize(),
			success: function(msg){
				var results = $(msg).find("#results");
				$("#results").fadeOut("fast", function(){ $(this).html(results.html()); bindResults(); } ).fadeIn();
			} 
		});		
	});

	domUpdated();
}

function bindResults() {

	$("#addDiamonds").click( function() {
		var form = $("form#DiamondEnquiryForm");

		$.ajax({
			type: "POST",
			url: form.attr('action'),
			cache: false,
			data: form.serialize(),
			dataType: "json",
			success: function(data){

				var addButton = $("#addDiamonds");	
				addButton.data('old_text', addButton.text() );  
				addButton.addClass("notify").text("Your selection has been added to the enquiry form").addClass("notify");

				function fadeOutAdded() {
					$("#addDiamonds").fadeOut("fast", function(){
						$(this).removeClass("notify").text( addButton.data('old_text') ).fadeIn();
					});	
				}

				setTimeout(fadeOutAdded, 3000);

				// Go through each diamond to see if they are in selection or not
				$("#results .diamond").each(function() {
					var d_id = Number( $(this).attr('id').replace(/diamondId/, '') );

					if(jQuery.inArray(d_id, data.selected) >= 0) {
						$(this).find(".name span").text("Added to enquiry form");
					}
					else {
						$(this).find(".name span").text("");
					}

				});


			}
		});

		return false;			
	});

}

$(document).ready(function() {
	insertSelector();
	$("#sectionDiamonds #results").attr("aria-live","polite");
});