// CR10: Zoom
// CR11: PDP Matrix
var init = true;

function debug (debugValue) {
	//alert(debugValue);
}

var	pddsIsZoomEnabled = false;
function pddsSetZoom(isZoomEnabled) {
	debug("pddsSetZoom: isZoomEnabled=" + isZoomEnabled);
	pddsIsZoomEnabled = isZoomEnabled;
}

var	pddsPreOrderUrl			= "";
var pddsPreOrderSku			= "";
var pddsPreOrderDefinition	= "";
var pddsItemSelected		= false;
function pddsSetPreOrder(preOrderUrl, preOrderDefinition) {
	debug("pddsSetPreOrder: preOrderUrl=" + preOrderUrl + ", preOrderDefinition=" + preOrderDefinition);
	pddsPreOrderUrl			= preOrderUrl;
	pddsPreOrderDefinition	= preOrderDefinition;
	$('#btnadtocart').hide();
	$('#btnaddtowishlist').hide();
	$('#btnpreorder').hide();
	debug("pddsSetPreOrder: pddsPreOrderUrl=" + pddsPreOrderUrl + ", pddsPreOrderDefinition=" + pddsPreOrderDefinition);
}

// Matrix Item Clicked
function matrixItemClicked(pInStockId, pPreOrderId, pValue, pColour, pSize) {
	debug("matrixItemClicked: pInStockId=" + pInStockId + ", pPreOrderId=" + pPreOrderId + ", pValue=" + pValue + ", pColour=" + pColour + ", pSize=" + pSize);
	var inStock = $('#' + pInStockId).text();
	var preOrder = $('#' + pPreOrderId).text();
	if (inStock == "true") {
		matrixItemClickedInStock(pColour, pSize);
	} else if (preOrder == "true") {
		matrixItemClickedPreOrder(pValue, pColour, pSize);
	}
}

// Matrix Item Clicked (In Stock)
function matrixItemClickedInStock(pColour, pSize) {
	debug("matrixItemClickedInStock: pColour=" + pColour + ", pSize=" + pSize);
	$('#btnadtocart').show();
	$('#btnaddtowishlist').show();
	$('#btnpreorder').hide();
	pddsPreOrderSku = "";
	switchSkuSettings(pColour, pSize,'matrix');
	pddsItemSelected = true;
}

// Matrix Item Clicked (Pre-Order)
function matrixItemClickedPreOrder(pSku, pColour, pSize) {
	debug("matrixItemClickedPreOrder: pSku=" + pSku + ", pColour=" + pColour + ", pSize=" + pSize);
	$('#btnadtocart').hide();
	$('#btnaddtowishlist').hide();
	$('#btnpreorder').show();
	pddsPreOrderSku = pSku;
	switchSkuSettings(pColour, pSize,'matrix');
	pddsItemSelected = true;
}

// Matrix Row Clicked (Colour Name)
function matrixRowClicked(pColour) {
	debug("matrixRowClicked: pColour=" + pColour);
	switchSkuSettings(pColour, "", 'row');
}

// Pre-Order button Clicked
function PreOrder() {
	debug("PreOrder: Enter");
	var preOrderUrl = pddsPreOrderUrl + escape(pddsPreOrderSku);
	window.open(preOrderUrl, "w_notifyme", pddsPreOrderDefinition);
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

// The SKU item object
function AlternativeImage(name, altText, smallImage, largeImage, extraLargeImage, zoomImage) {
	debug("AlternativeImage: name=" + name + ", altText=" + altText + ", smallImage=" + smallImage + ", largeImage=" + largeImage + ", extraLargeImage=" + extraLargeImage + ", zoomImage=" + zoomImage);
	this.name 				= name;
	this.altText 			= altText;
	this.smallImage 		= smallImage;
	this.largeImage 		= largeImage;
	this.extraLargeImage 	= extraLargeImage;
	this.zoomImage 			= zoomImage;
}

AlternativeImage.prototype.getName 				= function() {return this.name;};
AlternativeImage.prototype.getAltText 			= function() {return this.altText;};
AlternativeImage.prototype.getLargeImage 		= function() {return this.largeImage;};
AlternativeImage.prototype.getExtraLargeImage 	= function() {return this.extraLargeImage;};
AlternativeImage.prototype.getSmallImage 		= function() {return this.smallImage;};
AlternativeImage.prototype.getZoomImage 		= function() {return this.zoomImage;};

function SkuAlternativeImages () {
	this.array = new Array();
}

SkuAlternativeImages.prototype.put = function( alternativeImage ) {
    if( ( typeof alternativeImage != "undefined" ) ) {
        this.array[this.array.length] = alternativeImage;
    }
}

function Price (nowPrice, wasPrice, savingPercentage, savingAmount, showWasPricePercentage, showWasPriceAmount ) {
	this.nowPrice 				= nowPrice;
	this.wasPrice 				= wasPrice;
	this.savingAmount 			= savingAmount;
	this.savingPercentage 		= savingPercentage;
	this.showWasPricePercentage = showWasPricePercentage;
	this.showWasPriceAmount 	= showWasPriceAmount;
}

Price.prototype.getNowPrice 				= function() {return this.nowPrice;};
Price.prototype.getWasPrice 				= function() {return this.wasPrice;};
Price.prototype.getSavingAmount 			= function() {return this.savingAmount;};
Price.prototype.getSavingPercentage 		= function() {return this.savingPercentage;};
Price.prototype.getShowWasPricePercentage 	= function() {return this.showWasPricePercentage;};
Price.prototype.getShowWasPriceAmount 		= function() {return this.showWasPriceAmount;};

function SkuSettings (price, alternativeImages) {
	this.alternativeImages = alternativeImages;
	this.price = price;
}

SkuSettings.prototype.getPrice = function() {return this.price;};
SkuSettings.prototype.getAlternativeImages = function() {this.alternativeImages;};

// KeyValue - Defines the keys for our hashmap
function KeyValue( key, value) {
    this.key = key;
    this.value = value;
}

// Map - defines the hash map array
function Map() {
    this.array = new Array();
}

Map.prototype.put = function( key, value ) {
    if( ( typeof key != "undefined" ) && ( typeof value != "undefined" ) ) {
        this.array[this.array.length] = new KeyValue( key, value);
    }
}

Map.prototype.get = function( key ) {
	debug("map.prototype.get: key=" + key);
    for( var k = 0 ; k < this.array.length ; k++ ) {
    	debug("map.get: stored key=" + this.array[k].key);
        if( this.array[k].key == key ) {
   			debug("map.prototype.get: result=" + key + " found");
            return this.array[k].value;
        }
    }
   	debug("map.prototype.get: result=" + key + " not found");
    return "";
}

Map.prototype.length = function() {
    return this.array.length;
}

// Define page level variables
var skuAlternativeImages 	= new Map();
var map 					= new Map();
var optionValueMap 			= new Map();		
var defaultPriceDetails 	= new Map();
var defaultMainImageSource 	= "";
var defaultMainImageAltText = "";
var defaultZoomImageSource 	= "";

//*******************************************************
// Refresh product details page when colour changes
// Only used for clients that do not load colour
// as a defning option
//*******************************************************
function refreshColour (aForm, aField) {

	// Construct url to refresh to
	var selIndex = aField.selectedIndex;
	var url = aField.options[selIndex].value;

	// Now add other field values so that we dont lose selected options
	var maxNoOfOptions = 10;
	for (i = 1; i <= maxNoOfOptions; i++) {
		// Append ant selected options to the url
		var elementId = "attrValue" + (i);		
		if (document.getElementById(elementId)) {
			var definingOption = document.getElementById(elementId);
			if (definingOption != "undefined") {
				var selIndex = definingOption.selectedIndex;
				if (selIndex > 0) {
					var selValue = definingOption.options[selIndex].value;
					var selName = definingOption.name;
					url += "&" + selName + "=" + selValue;
				}
			}
		}
	}
	
	if (document.getElementById("WC_CachedProductOnlyDisplay_FormInput_quantity_In_OrderItemAddForm_1")) {
		var qty = document.getElementById("WC_CachedProductOnlyDisplay_FormInput_quantity_In_OrderItemAddForm_1");
		url += "&" + qty.name + "=" + qty.value;
	}
	
	// TODO Add the current qty and any other selected options to the request
	window.location.href = url;
}

// Initial Load of Page
function initOptions(multipleProducts) {

	// Save the default price details for use later
	var priceElementId = 'priceelement';	
	if (document.getElementById(priceElementId)) {
		defaultPriceDetails.put(priceElementId.toUpperCase(), document.getElementById(priceElementId).innerHTML);
	}

	init = false;
}

// Set the images and prices based upon the supplied Colour / Size
function switchSkuSettings(pColour, pSize, pClickSource) {
	debug("switchSkuSettings: pColour=" + pColour + ", pSize=" + pSize);

	// Set Prices
	switchSkuSettingsPrices(pColour, pSize, true,pClickSource);
	
	// Set Images
	switchSkuSettingsImages(pColour, pSize);	
}

// Set Prices on selection of Colour or Matrix Item
function switchSkuSettingsPrices(pColour, pSize, pDisplayPriceLabel, pClickSource) {
	debug("switchSkuSettings: pColour=" + pColour + ", pSize=" + pSize + ", pDisplayPriceLabel=" + pDisplayPriceLabel);
	
	if (pSize == "" && pClickSource == 'row') {
		switchSkuSettingsPricesDefault();
	} else {
		switchSkuSettingsPricesItem(pColour, pSize, pDisplayPriceLabel);
	}

}

// Set Prices on selection of Colour
function switchSkuSettingsPricesDefault() {
	debug("switchSkuSettingsPricesDefault");
	
	var priceString = "";

	var priceElementId = 'priceelement';
	if (document.getElementById(priceElementId) !== null && document.getElementById(priceElementId) !== "undefined") {
		priceString = defaultPriceDetails.get(priceElementId.toUpperCase());
		document.getElementById(priceElementId).innerHTML=priceString;
	}

	debug("switchSkuSettingsPricesDefault: priceString=" + priceString);
}

function entify(string) {
	return String(string)
		.replace(/&/g, '&#038;')  // ampersand
		.replace(/"/g, '&#034;')  // quotation mark
		.replace(/'/g, '&#039;')  // apostrophe
		.replace(/</g, '&#060;')  // less-than
		.replace(/>/g, '&#062;'); // greater-than
}
	
// Set Prices on selection of Matrix Item
function switchSkuSettingsPricesItem(pColour, pSize, pDisplayPriceLabel) {
	debug("switchSkuSettingsPricesItem: pColour=" + pColour + ", pSize=" + pSize + ", pDisplayPriceLabel=" + pDisplayPriceLabel);

	// Set Key
	var keyValue = "";
	if (pSize == "") {
		keyValue = pColour;
	} else {
		keyValue = pColour + "_" + pSize;
	}
	// REG/02/000590
	// Make sure we escape any special characters in the key - as when we build the map in DynamicProductJavaScriptSetup.jspf we do the following:
	// map.put("<c:out value="${itemKeyPrefix}${skuSetting.key}" escapeXml="true" />", skuSettings);
	// - which escapes any special characters to html entities, so we must do the same here.
	keyValue = entify(keyValue);
	
	var priceElementId = 'priceelement';
	var priceString = "";
	var nowLabel = "";
	
	var skuSettings = map.get(keyValue);

	if (skuSettings.getPrice().getShowWasPricePercentage() === "true" || skuSettings.getPrice().getShowWasPriceAmount() === "true") {
		nowLabel = "Now&nbsp;";
	}
	
	priceString += "<ul><li>";

	// Add price label if required
	if(pDisplayPriceLabel) {
		priceString += "<span class='label'>Price&nbsp;" + nowLabel + "</span>";
	} else {
		priceString += "<span class='nowlabel'>" + nowLabel + "</span>";
	}
	
	priceString += "<span class='amount'>" + skuSettings.getPrice().getNowPrice() + "</span>";

	if (skuSettings.getPrice().getShowWasPricePercentage() === "true" || skuSettings.getPrice().getShowWasPriceAmount() === "true") {
		priceString += "<span class='price'><span class='waspricelabel'>Was </span><span class='wasprice'>" + skuSettings.getPrice().getWasPrice() + "</span></span>";
		if (skuSettings.getPrice().getShowWasPricePercentage() === "true") {
			priceString += "<span class='price'><span class='saveuptopercentlabel'>Save </span><span class='saveuptopercent'>" + skuSettings.getPrice().getSavingPercentage() + "%</span></span>";
		}
		if (skuSettings.getPrice().getShowWasPriceAmount() === "true") {
			priceString += "<span class='price'><span class='saveuptoamountlabel'>Save </span><span class='saveuptoamount'>" + skuSettings.getPrice().getSavingAmount() + "</span></span>";
		}
	}
	
	priceString += "</li></ul>";
	
	if (document.getElementById(priceElementId) !== null && document.getElementById(priceElementId) !== "undefined") {
		document.getElementById(priceElementId).innerHTML=priceString;
	}
	
	debug("switchSkuSettingsPrices: priceString=" + priceString);
}

// Set Images on selection of Colour or Matrix Item
function switchSkuSettingsImages(pColour, pSize) {
	debug("switchSkuSettingsImages: pColour=" + pColour + ", pSize=" + pSize);
	
	var mainImageElement = document.getElementById("mainimage");
	if (mainImageElement !== null && mainImageElement !== "undefined") {
        var mainImageLargeLinkElement 	= document.getElementById("pdlargerimagelink");
        var mainImageLargeImageElement 	= document.getElementById("pdlargerimage");	
        var zoomImageElement 			= document.getElementById("zoomItemImg")

        if (defaultMainImageSource === "") {
			defaultMainImageSource 			= mainImageElement.src;
			defaultMainImageAltText 		= mainImageElement.alt;
			defaultMainImageLargeLinkSource = getLinkSource(mainImageLargeLinkElement.href);
			defaultZoomImageSource 			= zoomImageElement.value;
		}

		currentMainImageLargeLinkSource = getLinkSource(mainImageLargeLinkElement.href);
		
		aSkuImage = skuAlternativeImages.get(pColour);
		if (aSkuImage !== "undefined" && aSkuImage !== null && aSkuImage !== "") {
			mainImageElement.src 			= aSkuImage.getLargeImage();
            mainImageElement.alt 			= aSkuImage.getAltText();
            mainImageLargeLinkElement.href 	= mainImageLargeLinkElement.href.replace(currentMainImageLargeLinkSource, aSkuImage.getExtraLargeImage());
            mainImageLargeImageElement.href = mainImageLargeImageElement.href.replace(currentMainImageLargeLinkSource, aSkuImage.getExtraLargeImage());
            zoomImageElement.value 			= aSkuImage.getZoomImage();
        } else {
            mainImageElement.src 			= defaultMainImageSource;
            mainImageElement.alt 			= defaultMainImageAltText;
            mainImageLargeLinkElement.href 	= mainImageLargeLinkElement.href.replace(currentMainImageLargeLinkSource, defaultMainImageLargeLinkSource);
            mainImageLargeImageElement.href = mainImageLargeImageElement.href.replace(currentMainImageLargeLinkSource, defaultMainImageLargeLinkSource);
            zoomImageElement.value 			= defaultZoomImageSource;
        }

		// Ensure the main image param is set - used to avoid flicker of page when reloading
		document.getElementById("itemImg").value = mainImageElement.src;
		document.getElementById("itemAlt").value = mainImageElement.alt;
		if (pddsIsZoomEnabled) {
			$('#mainimage').attr("jqimg", zoomImageElement.value);
		}
		debug("switchSkuSettingsImages: mainImageElement.src=" + mainImageElement.src + ", zoomImageElement.value=" + zoomImageElement.value);
	}
}

// Get Link Source
function getLinkSource(pValue) {
	debug("getLinkSource: pValue=" + pValue);
	var startPos = pValue.indexOf("imageName=");
	var lValue = pValue.substring(startPos + 10, pValue.length);
	var endPos = lValue.indexOf("&");
	lValue = lValue.substring(0, endPos);
	debug("getLinkSource: lValue=" + lValue);
	return lValue;
}

// Ensure that a Matrix Item has been selected
function validateSelectedOptions(aForm, multipleProducts) {
	debug("validateSelectedOptions: pddsItemSelected=" + pddsItemSelected);
	
	if (!pddsItemSelected) {
		alert("Please Select an item");
		return false;
	} else {
		pddsItemSelected = false;  
		return true;
	}

}

// e.g. doPopup(4000,'.jqmWindow',  ".jqmOverlay")
function doPopup(timeout, windowSelector, overlaySelector) {

	//*******************************************************
	// Modal Window on Product Details Page

    // Function to animate opening of modal window	
    var openModal=function(hash){
		hash.w.css('opacity',1)
			.show("slow")
			.animate({opacity: '+=0'}, timeout)
			.queue(function () {
		    	$(this).jqmHide(); 
		    	$(this).dequeue();
		    });
	};

    // Function to animate closing of modal window
    var closeModal = function(hash) {
        $(overlaySelector).fadeOut("slow");
        var $modalWindow = $(hash.w);
	    	$modalWindow.dequeue();
			$modalWindow.fadeOut("slow", function() {
			hash.o.remove();
        });
    };
	
	$(windowSelector).jqm({overlay: 50, modal: true, trigger: false, toTop: true, onShow: openModal, onHide: closeModal});
	$(windowSelector).jqmShow();

}
