var current = null;

// Picture switcher
var imagesLocation = 'images/orderitems/';
function setPicture(id, sizePrefix) {
	var imageSrc = imagesLocation + sizePrefix + '_' + id + '.jpg';
	$('#product-' + id + ' img').attr('src', imageSrc);
	$('#picture-' + id).text(sizePrefix == 'sm' ? 'Enlarge' : 'Reduce');
}

function enlargePicture() {
	setPicture(this.getAttribute('id').split('picture-')[1], 'lg');
	return false;
}

function reducePicture() {
	setPicture(this.getAttribute('id').split('picture-')[1], 'sm');
	return false;
}


$(document).ready(function() {

	// Product list group toggle
	if (!isSafari2() ) {
		if (undefined != $(".productsList h2 a")) {
			$(".productsList h2 a").click(function() {
				$(this).parent().parent().parent().show();
				if ($(this).parent().parent().parent().hasClass("on")) {
					$(this).parent().parent().parent().removeClass("on");
		 			current = null;	
				} else {
					if (current != null) { current.trigger("click"); };
					current = $(this);
					$(this).parent().parent().parent().addClass("on"); 				
				}
				return false;
			});
		}

		if (undefined != $("#frmOrderMaterials .initial input")){
			$('.conditional').hide();
			$('.conditional').removeClass('on');
			$('#btnNext').parent().show();
			$('#btnNext1').parent().show();
			
			function validate(fields) {
				var hasErrors = false;
				for(i = 0; i < fields.length; i++ ){
					$(fields[i]).parent().children("label").css("color", "#003145");
					if($(fields[i]).parent().hasClass("mandatory") && "" == $(fields[i]).val()){
						hasErrors = true;
						$(fields[i]).parent().children("label").css("color", "red");
					}
				}
				return hasErrors;
			}
			
			
			$('#btnNext').click( function(){
				var fields = $('#frmOrderMaterials .initial input, #frmOrderMaterials .initial select');
			
				if (validate(fields)){
					alert("Please fill in all mandatory fields.");
				} else {
					$(".productsList:first h2 a").trigger("click");
					$(".productsList:eq(1) h2 a").trigger("click");
					gaTrackEvent('order_materials', 'step1');
				}
				return false;
			});
			
			$("#btnNext1").parent().click(function() {
				var fields = $(this).parent().parent().find('input, select');

				if (validate(fields)){
					alert("Please fill in all mandatory fields.");
				} else {
					$(".productsList:eq(1) h2 a").trigger("click");
					$(".productsList:eq(2) h2 a").trigger("click");
					gaTrackEvent('order_materials', 'step2');
				}

				return false;
			});
			
			$("#btnSubmit").click(function() {
				gaTrackEvent('order_materials', 'place_order');
				gaTrackEvent('artemis', 'contactable', 'order_materials');
				return true;
			});
		}
	}
					
	// Product ordering
	if (undefined != $(".btnProductAdd")) {

		function addProductClick(element)
		{
			// Make ajax call to add item to basket
			$.ajax({
				type: "POST",
				url: "order_ajax_handler.php",
				data: element.parent().serialize()
			});

			// Update basket with item
			addBasketItem(element.parent().children("input[name='hiddenItemID']:eq(0)").val(), element.parent().children("input[name='hiddenItemName']:eq(0)").val())
			
			// Show 'max ordered' text and hide add button
			element.parent().children(".maxOrdered:eq(0)").show();
			element.hide();
			
			return false;
		}
		
		function removeProductClick(element)
		{
			// Make ajax call to add item to basket
			$.ajax({
				type: "POST",
				url: "order_ajax_handler.php",
				data: element.parent().serialize()
			});
			
			// Put back add button
			var ItemId = element.parent().children("input[name='remove']:eq(0)").val();
			
			if (undefined != ItemId)
			{
				var AddButton = $("#btnAdd"+ItemId);
				
				if (undefined != AddButton)
				{
					AddButton.show();
					AddButton.parent().children(".maxOrdered:eq(0)").hide();
				}
			}
			
			// Remove this item from list
			element.parent().parent().remove();
			
			// Check if there are anymore items left in the list
			if (1 > $("#cartItems .item").length)
			{
				$("#cartDetails").hide();
				$("#noitems").show();
			}
			
			return false;		
		}

		function addBasketItem(itemId, itemName, itemQty) {
			
			if (undefined == itemId) return false;
			
			var Name = itemName || "Product #" + itemId;
			var Qty = itemQty || 1;
			
			// Prepare basket display to display items if none yet		
			if (undefined != $("#noitems")) {
				$("#noitems").hide();
				$("#cartItems").show();
				$("#cartDetails").show();
			}

			// Create remove button element and bind click event
			var RemoveBtn = $("<input type=\"submit\" value=\"Remove\" class=\"newSearchBtn\" style=\"font-size: 1em\"></input>")
								.addClass("btn")
								.attr({'name':'btn_remove', 'value':'Remove', 'src':'/images/btnRemove.gif'})
								.click(function(){ return removeProductClick($(this)); });
			
			// Create form elements
			var Form = $("<form></form>").attr({'method':'post', 'action':''});
			Form.append("<input type=\"hidden\" name=\"remove\" value=\"" + itemId + "\" />");
			Form.append(RemoveBtn);
						
			// Create containing list element
			var Li = $("<li></li>").addClass("item");
			Li.append("<p><strong>" + Name + "</strong><span>x " + Qty + "</span></p>");
			Li.append(Form);
					
			$("#cartItems").append(Li);
			
			return true;
		}


		// Bind click events to add and remove buttons		
		$(".btnProductAdd").click(function () { return addProductClick($(this)); });
		$(".btnProductRemove").click(function () { return removeProductClick($(this)); });
	}
});

