﻿
var Stock_NotSelected = 0;
var Stock_InStock = 1;
var Stock_LowStock = 2;
var Stock_Enquiries = 3;
var Stock_Unavailable = 4;
var ProductId = -1;
var PopupDialog;
var ProductName;
var ProductPrice;

$(document).ready(function () {
	/// <summary>On page load, set the zoom viewer and stock drop downs up.</summary>

	SetupJQZoom();

	if ($("#NoStockImage").length > 0) return; // No stock, so no need to load JS dropdowns.

	// Disable the colour drop down so that the size has to be changed before it is available (not disabled if non JS browser, which is how we want it.
	$("#ColourList").attr("disabled", true);
	// Remove the colours that would have been loaded up by databinding as they are for non-JS browsers.
	$("#ColourList >option").remove();
	$("#ColourList").append($('<option></option>').val("").html("Select Size First"));
	// Make sure the size drop down is set to the first element which is 'Select Size' (prevents problems with user refreshing browser).
	$("#SizeList")[0].selectedIndex = 0;
	// Disable the 'add to basket' and 'stock' buttons until a size / colour is selected.
	SetButtonState(Stock_NotSelected);

	// Create the wish list and basket popup.
	PopupDialog = CreateProductPopup();

	SetupTabs();
});

function SetupJQZoom() {
	var options = {
		zoomWidth: 460,
		zoomHeight: 460,
		xOffset: 15,
		yOffset: 0,
		showPreload: true,
		title: false,
		position: "right" //and MORE OPTIONS
	};
	$(".jqzoom").jqzoom(options);
}

function SetupTabs() {
	$("ul.tabs li").click(function () {
		$("ul.tabs li").removeClass("on"); //Remove any "active" class
		$(this).addClass("on"); //Add "active" class to selected tab

		// Hide all content panes.
		$("#BottomPanes > div").hide();

		// Remove the text 'Tab' off the end of the ID and replace it with 'Content' to get our container.
		var ContentDivId = "#" + this.id.replace("Tab", "Content");
		$(ContentDivId).show();

		return false;
	});
}

function SetButtonState(StockLevel) {
	var ButtonRef, WishLinkRef;

	ButtonRef = $("#AddToBasket");
	WishLinkRef = $("#AddToWishListButton");

	ButtonRef.unbind('click');
	WishLinkRef.unbind('click');
	if (Stock_Unavailable == StockLevel || Stock_Enquiries == StockLevel) {
		ButtonRef.attr("class", "bigbtn notice");
		ButtonRef.attr("value", "Email me when in stock ▶");
		//ButtonRef.css("color", "red");
		WishLinkRef.click(function () { AddToWishList(); return false; });
	}
	else if (Stock_LowStock == StockLevel || Stock_InStock == StockLevel) {
		ButtonRef.attr("class", "bigbtn");
		ButtonRef.attr("value", "Add to basket ▶");
		ButtonRef.css("color", "white");
		ButtonRef.click(function () { AddToBasket($("#SelectedPosCode").val()); return false; });
		WishLinkRef.click(function () { AddToWishList(); return false; });
	}
	else {
		ButtonRef.attr("class", "bigbtn off");
		ButtonRef.attr("value", "Add to basket ▶");
		ButtonRef.css("color", "white");
		ButtonRef.click(function () { alert('You need to select a size and colour combination first.'); return false; });
		WishLinkRef.click(function () { alert('You need to select a size and colour combination first.'); return false; });
	}
}

function showSelectedImage(ClickedImg) {
	/// <summary>Thumb selector/zoom.</summary>

	//a thumb was clicked - show it as the main pic
	$("#TheBigPicture").attr("src", ClickedImg.src);
	$("#BigPictureLink").attr("href", ClickedImg.src);

	if (ClickedImg.alt == null || ClickedImg.alt == undefined || ClickedImg.alt == '') {
		$('#ImgTitle').hide();
	}
	else {
		$('#ImgTitle').show();
		$('#ImgTitle').text(ClickedImg.alt);
	}
}

function SelectColourImage(DropdownList) {
	/// <summary>Shows the image appropriate for the selected dropdown PosCode colour selection.
	/// Also updates the delivery data in the tabbed part of the UI.
	/// </summary>

	// The dropdown for the list of colours has changed, see if we have a picture for the colour.
	var PosCode = DropdownList.options[DropdownList.selectedIndex].value;
	var StockLevel;

	StockLevel = Stock[PosCode];
	SetButtonState(StockLevel);

	// Remember the PosCode for postback and add to basket / wish list.
	$("#SelectedPosCode").val(PosCode);

	// Fire off a call to the web service to calculate how much the delivery options will be if this item is added.
	UpdateDelivery(PosCode);
	UpdateLinked(PosCode);

	// We don't want the size part of the POS code to lookup the colour image, so remove it.
	PosCode = PosCode.substr(0, 10);
	// Images are prefixed with 'ColourImage_' to keep them easily findable.
	var ColImg = $("#ColourImage_" + PosCode)[0];
	if (null != ColImg) {
		showSelectedImage(ColImg);
	}
}

function LoadColours(DropdownList) {
	/// <summary>Loads the list of colours according to the selected size, The dropdown is passed as a param.</summary>

	// The dropdown for the list of sizes has changed, we need to load up the colour list.
	var SizeCode = DropdownList.options[DropdownList.selectedIndex].value;

	$("#ColourList >option").remove();
	$("#ColourList").append($('<option></option>').val("").html("Select Colour"));
	for (Colour in PosCodes[SizeCode]) {
		var PosCode = PosCodes[SizeCode][Colour];
		var StockText;
		var StockLevel = '';

		StockLevel = Stock[PosCode];
		if (Stock_InStock == StockLevel) {
			StockText = 'Order Now';
		}
		else if (Stock_LowStock == StockLevel) {
			StockText = 'Order Now (Low Stock)';
		}
		else if (Stock_Unavailable == StockLevel) {
			StockText = 'Discontinued and Sold Out';
		}
		else {
			StockText = 'Out of Stock';
		}

		$("#ColourList").append($('<option></option>').val(PosCode).html(Colour + " - " + StockText));
	}

	if ($("#ColourList option").size() == 1) {
		if (SizeCode != 'Select Size') {
			$("#ColourList >option").remove();
			$("#ColourList").append($('<option></option>').val("").html("Discontinued and Sold Out"));
		}
		SetButtonState(Stock_NotSelected);
		return;
	}

	$("#ColourList").attr("disabled", false);
	// Disable the 'add to basket' and 'stock' buttons until a size / colour is selected.
	SetButtonState(Stock_NotSelected);
	ClearLinkedProductsTab();
}

function SetDialogToDefaultText() {
	/// <summary>Resets the popup dialog box back to the default product information text.</summary>

	PopupDialog.find("#PopupDialogTitle").text(ProductName);
	PopupDialog.find("#PopupDialogSubTitle").text(ProductPrice);
	PopupDialog.find("#PopupLink").attr("href", '/newbasket.aspx');
	PopupDialog.find("#PopupLink").text('Go To Checkout ▶');
	PopupDialog.find(".related").remove();
}

function AddToBasket(PosCode) {
	// Call the web service to add the item which will then ping back and call the success / fail function.
	Cart.AddToShoppingCart(PosCode, AddToShoppingCartSuccess, AddToShoppingCartFailed, PosCode);
}

function AddToShoppingCartSuccess(cartResult) {
	SetDialogToDefaultText();
	$("#BasketItemsCount").text(cartResult.ItemsCountText);
	PopupDialog.find('#PopupDialogHeader').text('Added to Basket');
	PopupDialog.find("#PopupDialogTitle").text(cartResult.MostRecentProductName);
	PopupDialog.find("#PopupDialogSubTitle").text(cartResult.MostRecentProductPrice);

	var appendAfterTr = PopupDialog.find("tbody > tr").eq(2);
	
	for (var i = 0; i < cartResult.LinkedProducts.length; i++) {
		var LinkedProduct = cartResult.LinkedProducts[i];
		var tr = "";

		if (i === 0)
			tr = "<tr class='related first'>";
		else
			tr = "<tr class='related'>";

		tr += "<td>" + LinkedProduct.Description + " - £" + LinkedProduct.Price + "</td>";
		tr += "<td class=\"addto\">";
		tr += "<a class=\"btn\" href=\"javascript:AddToBasket('" + $.trim(LinkedProduct.PosCode) + "');\">Add to Basket</a>";
		tr += "</td>";
		tr += "</tr>";
		appendAfterTr.before(tr);
	}

	PopupDialog.dialog('open');
}

function AddToShoppingCartFailed(err) {
	PopupDialog.find('#PopupDialogHeader').text('Unable to add to Basket');
	PopupDialog.find('#PopupDialogTitle').text('Sorry, we couldn\'t add this item.');
	PopupDialog.find("#PopupDialogSubTitle").text("");
	PopupDialog.dialog('open');
}

function AddToWishList() {
	var PosCode = $("#SelectedPosCode").val();

	// Call the web service to add the item which will then ping back and call the success / fail function.
	Cart.AddToWishList(PosCode, AddToWishListSuccess, AddToWishListFailed, PosCode);
}

function AddToWishListSuccess(ItemsCountText) {
	SetDialogToDefaultText();
	$("#BasketItemsCount").text(ItemsCountText);
	if ('' == ItemsCountText) {
		PopupDialog.find("#PopupLink").attr("href", '/sign_in.aspx');
		PopupDialog.find("#PopupLink").text('Please Sign In');
		PopupDialog.find('#PopupDialogHeader').text('Please Sign In');
		PopupDialog.find('#PopupDialogTitle').text('Please sign in or register.');
		PopupDialog.find("#PopupDialogSubTitle").text("");
		PopupDialog.dialog('open');
		return;
	}
	PopupDialog.find("#PopupLink").text('Go To Wish List');
	PopupDialog.find("#PopupLink").attr("href", '/WishList.aspx');
	PopupDialog.find('#PopupDialogHeader').text('Added to Wish List');
	PopupDialog.dialog('open');
}

function AddToWishListFailed(err) {
	SetDialogToDefaultText();
	$("#BasketItemsCount").text('');
	PopupDialog.find("#PopupLink").attr("href", '/WishList.aspx');
	PopupDialog.find("#PopupLink").text('Go To Wish List');
	PopupDialog.find('#PopupDialogHeader').text('Unable to add to Wish List');
	PopupDialog.find('#PopupDialogTitle').text('Sorry, we couldn\'t add this item.');
	PopupDialog.find("#PopupDialogSubTitle").text("");
	PopupDialog.dialog('open');
}

function CreateProductPopup() {
	var BasketDlg;
	var dialogOpts =
    {
    	modal: false,
    	closeText: '',
    	width: '391px',
    	autoOpen: false
    }

	BasketDlg = $("#PopupDialog");
	BasketDlg.dialog(dialogOpts);

	$(".ClosePopupDialog").click(function () { BasketDlg.dialog('close'); });

	// Save the product name and price so we can change the popup and then restore them.
	ProductName = $("#PopupDialogTitle").text();
	ProductPrice = $("#PopupDialogSubTitle").text();

	return BasketDlg;
}

function UpdateDelivery(PosCode) {
	$("#DeliveryMessage").text('Calculating delivery, please wait.');
	$("#DeliveryTable").visible = false;

	Cart.CalculateDelivery(PosCode, UpdateDeliverySuccess, UpdateDeliveryFailed, PosCode);
}

function UpdateDeliverySuccess(ShipOptionList) {
	if (ShipOptionList.length != 3) return;
	var RowsShown = 0;

	RowsShown += UpdateShippingUiRow('ShipExpressRow', 'ShipExpressChargeLabel', ShipOptionList[0].FormattedCharge);
	RowsShown += UpdateShippingUiRow('ShipStandardRow', 'ShipStandardChargeLabel', ShipOptionList[1].FormattedCharge);
	RowsShown += UpdateShippingUiRow('ShipEconomyRow', 'ShipEconomyChargeLabel', ShipOptionList[2].FormattedCharge);

	$('#DeliveryMessage').text('Based on this item, your basket and destination your delivery options are shown below.  Please note these are time to despatch estimates, actual delivery depends on the parcel transit time to your delivery address following despatch.');
	$('#DeliveryTable').show();
}

function UpdateShippingUiRow(TableRowId, LabelId, FormattedCharge) {
	TableRowRef = $('#' + TableRowId);
	LabelRef = $('#' + LabelId);
	if (FormattedCharge == null || FormattedCharge == '') {
		TableRowRef.hide();
		LabelRef.hide();
		return 0; // Indicate row is not visible.
	}
	else {
		TableRowRef.show();
		LabelRef.show();
		LabelRef.text(FormattedCharge);
		return 1; // Indicate row is visible.
	}
}

function UpdateDeliveryFailed(err) {
	$("#DeliveryMessage").text('Sorry, we could not calculate delivery as an error occurred. ' + err);
}

function UpdateLinked(PosCode) {
	ClearLinkedProductsTab();
	$("#LinkedProductsMessage").text('Checking for compatible products, please wait...');
	Cart.GetLinkedProducts(PosCode, UpdateLinkedSuccess, UpdateLinkedFailed, PosCode);
}

function UpdateLinkedSuccess(LinkedProductList) {
	var tableRef = $('#LinkedProductsTable');

	if (LinkedProductList.length == 0) {
		$('#LinkedProductsMessage').text('We don\'t have any in stock compatible items for this product.');
		return;
	}

	for (var i = 0; i < LinkedProductList.length; i++) {
		var LinkedProduct = LinkedProductList[i];
		var tr = "<tr class=\"related\">";
		tr += "<td>" + LinkedProduct.Description + " - £" + LinkedProduct.Price + "</td>";
		tr += "<td class=\"addto\">";
		tr += "<a class=\"btn\" href=\"javascript:AddToBasket('" + LinkedProduct.PosCode + "');\">Add to Basket</a>";
		tr += "</td>";
		tr += "</tr>";
		tableRef.append(tr);
	}

	$('#LinkedProductsMessage').text('Based on the selected item, these are the specific hoods and liners to fit the jacket:');
	tableRef.show();
}

function UpdateLinkedFailed(err) {
	$("#LinkedProductsMessage").text('Sorry, we could not find any compatible products. ' + err);
}

function ClearLinkedProductsTab() {
	var tableRef = $('#LinkedProductsTable');

	$("#LinkedProductsMessage").text('Please select a size and colour first.');
	tableRef.empty();
	tableRef.hide();
}

