var ua = $.browser;
var isIE6 = false;
if (ua.msie && ua.version.slice(0,1) == "6") {
	isIE6 = true;
}

var SELECT_PRODUCTTYPE = "selectProductType";
var UPDATE_PRODUCT = "updateProduct";
var ADD_PRODUCT_TO_BASKET = "addProductToBasket";

function unbindProductListeners() {
	$(".priceModifier").unbind("change");
	$(".productTab").unbind("click");
    //$(".frameDetailsOpener").unbind("click");
    //$(".frameDetailsContainer").unbind("click");
}

function bindProductListeners(currentImageId) {
	// product tab click listener
	$(".priceModifier").bind("change", function(e) {
		_target = $(this).parents("div.productFormDiv").first();
		_form = _target.find("form").first();
		updateProduct(_form, _target);
		e.stopPropagation();
	});
	$(".productModifier").bind("change", function(e) {
		_target = $(this).parents("div.productFormDiv").first();
		_form = _target.find("form").first();
		updateProduct(_form, _target);
		if ($(e.target).hasClass("previewModifier")) {
			updatePreviewImage(_form);
		}
		e.stopPropagation();
	});
	
	// prevent double submission
	$(".greetingsCardTab form").preventDoubleSubmit();
	
	$(".addToBasket").bind("click", function(e) {
		var _productForm = $(this).parents("form").first();
		if ($(e.target).hasClass("greetingsCardAddToBasket")) {
			_flash = getFlashMovieObject("GreetingsCardTool");
			$("#personalization_insidetext").attr('value', _flash.getText());
			$("#personalization_height").attr('value', _flash.getHeight());
			$("#personalization_width").attr('value', _flash.getWidth());
			$("#personalization_cropX1").attr('value', _flash.getCropValue('x1'));
			$("#personalization_cropY1").attr('value', _flash.getCropValue('y1'));
			// K&M want 2 crop coordinates but give us 4 in the flash so we take the first and last!
			$("#personalization_cropX2").attr('value', _flash.getCropValue('x4'));
			$("#personalization_cropY2").attr('value', _flash.getCropValue('y4'));

			$("#imageProductForm_10 :input[name='task']").val(ADD_PRODUCT_TO_BASKET);
			$("#imageProductForm_10").submit();
			
		}
		$(_productForm + ":input[name='task']").val(ADD_PRODUCT_TO_BASKET);
		_productForm.submit();
		e.stopPropagation();
	});
    $(".productTab").bind("click", function(e) {
    	if ($(this).hasClass("greetingsCardTab")) {
    		if ($(e.target).hasClass("greetingsCardQuantity")) {
    			// nothing to be done
    		} else if ($(e.target).hasClass("greetingsCardData")) {
				var _greetingsCardError = false;
				
				// listen for click on radio button
				if ($(e.target).hasClass("greetingsCardRadio")) {
					productUpdating = true;
					_rel =  $(e.target).attr("rel");
					if (_rel != undefined) {
						_relSplit = _rel.split("_");
						if (_relSplit != undefined && _relSplit.length == 4) {
							_relSplit[0]; // type id
							_relSplit[1]; // size id
							_relSplit[2]; // "orientation"
							_relSplit[3]; // option value
							$("#greetingscard_product_type").val(_relSplit[0]);
							$("#greetingscard_product_size").val(_relSplit[1]);
							$("#greetingscard_attributes_orientation").val(_relSplit[3]);

							// update flash interface
							_flash = getFlashMovieObject("GreetingsCardTool");
							if (_relSplit[0] == 10) {
								if (_relSplit[3] == "landscape") {
									_flash.setProductID("2");
								} else {
									_flash.setProductID("3");
								}
							} else if (_relSplit[0] == 11) {
								if (_relSplit[3] == "landscape") {
									_flash.setProductID("0");
								} else {
									_flash.setProductID("1");
								}
							} else {
								$("#greetingsCardError").html("Sorry. There was a problem updating the product information.");
								$("#greetingsCardError").show();
								window.setTimeout(function() { $("#greetingsCardError").hide(); }, 3000);
								_greetingsCardError = true;
							}
							
						}
					}
				}

				if (_greetingsCardError) {
					//e.stopPropagation();
					return false;
				}
				
				unbindProductListeners();
				
				// reload greetings card form
				_target = $(this).find("div.productFormDiv").first()
				_gcForm = _target.find("form").first();
				var query = _gcForm.serialize();
				
				_imageId = $(_gcForm + ":input[name='imageId']").val();
			
				$.ajax({
					type: "GET",
					url: "/ajax_image_product.php",
					data: query,
					success: function(html){
						_target.html(html);
						if (isIE6) {
					    	_gcForm.find(".productToolTipIcon a").tooltip({
								left: 10,
								top: -15,
								showURL: false
							});
						}
						
						// update greetings card flash
						var _checkedBox = _gcForm.find("input:radio:checked").first();
						
						bindProductListeners(_imageId);
				  	}
				});
			} else if ($(e.target).is("a") && !$(this).hasClass("ui-accordion-selected")) { // if the tab's not open
				$("#productPreviewDiv").hide();

				// set initial productID for flash
				_gcTypeId = $("#greetingscard_product_type").val();
				_gcOrientation = $("#greetingscard_attributes_orientation").val();
				_flashProductId = '0';

				if (_gcTypeId == 10) {
					if (_gcOrientation == "landscape") {
						_flashProductId = "2";
					} else {
						_flashProductId = "3";
					}
				} else if (_gcTypeId == 11) {
					if (_gcOrientation == "landscape") {
						_flashProductId = "0";
					} else {
						_flashProductId = "1";
					}
				} else {
					// unable to set flash productType
				}
				

				$('#ajaxFlashContent').load('/ajax_product_preview_greetingscard.php?id='+currentImageId+'&flashProductId='+_flashProductId);

				$("#ajaxFlashContent").css("height", "400px");
				$("#ajaxFlashContent").show();
			}
		} else if ($(this).hasClass("mugsTab")) {
			$("#productPreviewDiv").hide();
			$('#ajaxFlashContent').load('/product_preview_mug.php?id='+currentImageId);
			$("#ajaxFlashContent").show();
		} else {
			$("#ajaxFlashContent").hide();
			$("#ajaxFlashContent").html("");
			$("#productPreviewDiv").show();
			updatePreviewImage($(this).find("form"));
		}
    });
}

function updateProduct(form, target) {
	var query = form.serialize();

	productUpdating = true;
	
	_imageId = $(form + ":input[name='imageId']").val();
	
	unbindProductListeners();

	$.ajax({
		type: "GET",
		url: "/ajax_image_product.php",
		data: query,
		success: function(html){
			target.html(html);
			if (isIE6) {
		    	target.find(".productToolTipIcon a").tooltip({
					left: 10,
					top: -15,
					showURL: false
				});
			}
			bindProductListeners(_imageId);		
	  	}
	});
}

function updatePreviewImage(form) {
	form.find(".hiddenTask").value = UPDATE_PRODUCT;
	var query = form.serialize();

	$.ajax({
		type: "GET",
		url: "/ajax_product_preview.php",
		data: query,
		success: function(html) {
			$("#productPreviewDiv").html(html);
	  	}
	});
}

function selectFrameColour(typeId, colour) {
	var _colourField = document.getElementById("frameColourField_" + typeId);
	_colourField.value = colour;
	updateProduct($('#imageProductForm_' + typeId), $('#productFormDiv_' + typeId));
	updatePreviewImage($("#imageProductForm_" + typeId));
}

function frameLeft(slider, currentField) {
	var lastVal = parseInt(currentField.val());
	slider.slider("value", (lastVal - 1));
}

function frameRight(slider, currentField) {
	var lastVal = parseInt(currentField.val());
	slider.slider("value", (lastVal + 1));
}

function showFrameDetails(targetDiv, frameColour) {
	$.ajax({
		type: "GET",
		url: "/frame_details_popup.php",
		data: "frame=" + frameColour + "&divId=" + targetDiv,
		success: function(html) {
			$("#"+targetDiv).html(html);
			$("#"+targetDiv).fadeIn("slow");
			if (isIE6) {
				$(".productFormData").hide();
			}
	  	}
	});
}

function hideFrameDetails(targetDiv) {
	$('#'+targetDiv).fadeOut('normal');
	if (isIE6) {
		$(".productFormData").show();
	}
}

$.fn.preventDoubleSubmit = function() {
	$(this).submit(function() {
		if (this.beenSubmitted) {
			return false;
		} else
			this.beenSubmitted = true;
	});
};

