// ATTENTION: parameterValue has to be escaped, will be unescaped internally
// TODO: escape()/unescape() is deprecated since ECMAScript v3.
function buildVariantRequestQuery(parameterName, parameterValueEscaped, parameterNameToIgnore, containingForm) {
	var queryString = null;
	var pid = null;
	var cgid = null;
	var quantity = null;
	var colour = null; // optional
	var size = null; // optional
	
	var parameterValue = unescape(parameterValueEscaped);
	var myForm = document.forms[containingForm];
	var allFormElements = myForm.elements;
	for (var k = 0; k < allFormElements.length; k++) {
		var element = allFormElements[k];
		
		if (element.name == "masterproduct_pid") { 
			// we use here the master product ID to reduce the pages which we have to cache!
			pid = element.value;
		} else if (element.name == "cgid") {
			cgid = element.value;
		} else if (element.name == "Quantity") {
			quantity = element.value;
		} else if (element.name == "Colour") {
			if (parameterName == "colour") {
				colour = parameterValue;
			} else if (element.value != null) {
				colour = element.value;
			}
		} else if (element.name == "Size") {
			if (parameterName == "size") {
				size = parameterValue;
			} else if (element.value != null) {
				size = element.value;
			}
		}
	}
	var colourUrlPart = "";
	if (parameterNameToIgnore != "colour" && colour != null) {
		colourUrlPart = "&dwvar_" + encodeURIComponent(pid) + "_colour=" + encodeURIComponent(colour);
	}
	var sizeUrlPart = "";
	if (parameterNameToIgnore != "size" && size != null) {
		sizeUrlPart = "&dwvar_" + encodeURIComponent(pid) + "_size=" + encodeURIComponent(size);
	}
	
	// dwvar-parameter names are variation attribute parameters for the Demandware pipelet "UpdateProductVariationSelections": 
	queryString = "pid=" + encodeURIComponent(pid) + "&cgid=" + encodeURIComponent(cgid) + "&Quantity=" + encodeURIComponent(quantity) + colourUrlPart + sizeUrlPart;
	return queryString;
}

function updateProductPresentation(parameterName, parameterValue, parameterNameToIgnore) {
	var url = null;
	var pid = null;
	var cgid = null;
	var quantity = null;
	var colour = null; // optional
	var size = null; // optional
	var character = null; // optional
	
	var myForm = document.forms["cartaddproduct"];
	
	var allFormElements = myForm.elements;
	for (var k = 0; k < allFormElements.length; k++) {
		var element = allFormElements[k];
		if (element.name == "update_url") { 
			url = element.value;
		} else if (element.name == "masterproduct_pid") { 
			// we use here the master product ID to reduce the pages which we have to cache!
			pid = element.value;
		} else if (element.name == "cgid") {
			cgid = element.value;
		} else if (element.name == "Quantity") {
			quantity = element.value;
		} else if (element.name == "colour") {
			if (parameterName == "colour") {
				colour = parameterValue;
			} else if (element.value != null) {
				colour = element.value;
			}
		} else if (element.name == "size") {
			if (parameterName == "size") {
				size = parameterValue;
			} else if (element.value != null) {
				size = element.value;
			}
		} else if (element.name == "character") {
			if (parameterName == "character") {
				character = parameterValue;
			} else if (element.value != null) {
				character = element.value;
			}
		}
	}
	var colourUrlPart = "";
	if (parameterNameToIgnore != "colour" && colour != null && colour != "@@@") {
		colourUrlPart = "&dwvar_" + pid + "_colour=" + colour;
	}
	var sizeUrlPart = "";
	if (parameterNameToIgnore != "size" && size != null && size != "@@@") {
		sizeUrlPart = "&dwvar_" + pid + "_size=" + size;
	}
	var characterUrlPart = "";
	if (parameterNameToIgnore != "character" && character != null && character != "@@@") {
		characterUrlPart = "&dwvar_" + pid + "_character=" + character;
	}

	// dwvar-parameter names are variation attribute parameters for the Demandware pipelet "UpdateProductVariationSelections": 
	url = url + "?pid=" + pid + "&cgid=" + cgid + "&Quantity=" + quantity + colourUrlPart + sizeUrlPart + characterUrlPart;
	window.location.href = url;
}

// for update product quantity with Ajax, but currently empty
function completeRequest() {
	// currently we do nothing
}

function submitSendToAFriend(form) {

	var ajax = new Request.HTML({url: form.action, method: 'post', data: form, update: 'MB_Container'}).send();
	return false;
}

function sendToFriend(url,sentUrl) {
	var ajax = new Request.HTML({url: url, method: "get", data: "sentUrl="+sentUrl , update: "sendToFriend", onComplete: completeRequest }).send();
}

/* ------------------------------ */

// for choosing a new variant with Ajax, builds the HTTP call for Ajax
function swapVariantByAjax(parameterName, parameterValue, parameterNameToIgnore, containingForm) {
	if(containingForm == null) {
		containingForm = "cartaddproduct";
	}
	var pidQuery = "pid=" + document.getElementById('pid').value; // now pid value should be updated
    var query1 = buildVariantRequestQuery(parameterName, parameterValue, parameterNameToIgnore, containingForm);
    var url1 = document.getElementById('update_url_choose').value;
    var container = ".variationsD";
    var ajax1 = jQuery(container).load(url1+'?'+query1, function(){ swapVariantByAjaxOnComplete(parameterName); });
}


// necessary work after the CHOOSE tab data (HTML source code) change for variant swap:
// initialize smoothbox new, swap images too if new colour was requested 
function swapVariantByAjaxOnComplete(parameterName) {
    TB_init(); //!! We call TB_init() because the style guide event handler has to be initialized again, after Ajax call.
	// if colour change we request new images:
	if (parameterName == "colour") {
		swapImagesByAjax();
		//sendCoremetrics(); //Such function cannot be found.
	}
	swapPriceByAjax();
	
	swapRecommendationsByAjax();
	
	//resetMiniCart();
	//recommendations 
	if (typeof recommendations != "undefined") {
		recommendations.setProductPid();
	}
	
}

// reset minicart agerestriction checkboxes need if we have different agerestriction for different variations
function resetMiniCart() {
	if(minicart) {
		minicart.checkbox = $$("div.terms input")[0] || null;
		if (minicart.checkbox != null) {
			minicart.assignAddStatus();
			minicart.checkbox.onclick = minicart.assignAddStatus;
			minicart.checkbox.onkeypress = minicart.assignAddStatus;
		}
	}
}
// changes the images with Ajax if necessary
function swapImagesByAjax() {
	var container = "#imageNavigator";
	if (jQuery(container).length > 0) { // viewer-area with div "imageSlideInner" is only available if a thumbnail was detected, otherwise it will be removed by javascript during the page load
		// derive new pid
		var pidQuery = "pid=" + encodeURIComponent(document.forms.colourForm.var_pid.value); // now pid value should be updated
	    // we change the images
	    var url2 = jQuery('#clr_update_url_images').val();
		var query2 = pidQuery; 
		var ajax2_1 = jQuery(container).load(url2+'?'+query2, function(){ createImageInfoMap(true); });
	}
}

//s7
var loadImageSizeErr = false;
var currentImageForLoad = 0;
var initLoadImageSize = true;

if(sjCallbacks == null) {
	var sjCallbacks = new Object();
}

if(sjErrCallbacks == null) {
	var sjErrCallbacks = new Object();
}


var as = 0;
var ft =0;
window.s7jsonError = function(inArg, inId) {
	(function($) {
		if ($("#pid").val() != null) {
			var pid = $("#pid").val();
		}
		cmCreatePageElementTag((pid) ? pid : cmCurrentMasterPID, "Image not found","","","","-_--_--_--_--_--_--_--_--_-");
	    })(jQuery);
	var noImgUrl = $('scene7_url').value+'no_image_available?resmode=sharp&op_usm=1.1,0.5,0,0'+$('defaultImageID').value;
	
	if (inId == 'loadImageSize') {
		loadImageSizeErr = true;
	} else {
			dynamicTag(noImgUrl,currentImageForLoad);
	}
	if(loadImageSizeErr) {
		//remove tags which is not in infomap
		var thumbnails = $$('#imageNavigator a.thumbnail');
		if (thumbnails[0]) {
			for (var i = 0; i < thumbnails.length; i++) {
				var href = thumbnails[i].getProperty('href');
				if((href in imageInfoMap) == false && currentImageForLoad == i) {
					thumbnails[i].destroy();
				} 
			}
		} else {
			dynamicTag(noImgUrl,currentImageForLoad);
		}
		
		//next image
		var thumbnails = $$('#imageNavigator a.thumbnail');
	
		//we have alternative images
		if(thumbnails.length > 0) {
			var nextItem = currentImageForLoad+1;
			var nextThumbnail = $('th_s'+nextItem);
			//we have next image
			if(nextThumbnail) {
				//load next image
				dynamicTag(nextThumbnail.getProperty('href'),nextItem);
			}
		}
		
		loadImageSizeErr = false;
	}
	
	initLoadImageSize = false;
}


sjErrCallbacks.loadImageSize = function(inArr) {
	var nothing;
}

//callback function to load image sizes and set it to imageInfoMap
sjCallbacks.loadImageSize = function(inArr) {
	
	//make url id in imageInfoMap
    var ctx = decodeURIComponent(inArr["context.id"]);
	var imageURL = ctx.split('/');
	
	var imgID = imageURL[1].split('?');
	
	if(initLoadImageSize) {
		var currentItem = 0;
	} else {
	   	var currentItem = imgID[1].split("currentItem="); 
	   	var imageArr = currentItem[1].split("&"); currentItem = parseInt(imageArr[0]); 
   	}
   	initLoadImageSize = false;
   	
	var url = $('scene7_url').value+imgID[0]+'?resmode=sharp&op_usm=1.1,0.5,0,0'+$('defaultImageID').value;
	
	//get image sizes
	var rect = inArr["image.rect"].split(',');
	var imageInfo = new Object();
	imageInfo.width = rect[2];
	imageInfo.height = rect[3];
	imageInfo.iv = inArr["image.version"];
	//set image sizes to imageInfoMap
	imageInfoMap[url] = imageInfo;
	
	//call dynamicTag recursively
	dynamicTag(url ,currentItem);
}

//function to append script to html head where it return json and calling to loadImageSize
function dynamicTag(img,currentItem) {
	currentImageForLoad = currentItem;
	var url = img;
	
	//check if image is in imageInfoMap
	if(img in imageInfoMap) {		
		if(currentItem == 0) {
			var thumbnail = $('th_prImg');
			//set current image
			if (s7imageURL == null) {
				fixSetImage(url,true);
				if(s7zoom) {
					s7zoom.reset();
				}
			}
		} else {
			var thumbnail = $('th_s'+currentItem);
		}
		if (s7imageURL == url.split("?")[0]) {
			fixSetImage(url,true);
			s7zoom.reset();
		}
		//add click event on loaded thumbnail
		if(thumbnail) {
			thumbnail.addEvent(
				'click', 
				function(e) {
					e = new Event(e);
					var thumbLink = this.getProperty('href');
					jQuery('.thumbnail').removeClass('selected');
					jQuery(this).addClass('selected');
					fixSetImage(thumbLink,true);
					s7zoom.reset();
					e.stop();
				});
		}
				
		//the image is in imageInfoMap
		//check next image
		//we have alternative images
		var thumbnails = $$('#imageNavigator a.thumbnail');
		if(thumbnails.length > 0) {			
			var nextItem = currentItem+1;
			var nextThumbnail = $('th_s'+nextItem);
			//we have next iamge
			if(nextThumbnail) {
				//load next image
				dynamicTag(nextThumbnail.getProperty('href'),nextItem);
			}
		} 
	} else {
		//not in map go to load image sizes
		var imageURL = img.split('?');
	    var request = imageURL[0]+"?req=ctx,json&id=loadImageSize&currentItem="+currentImageForLoad;
	    var head = document.getElementsByTagName("head").item(0);
	    var script = document.createElement("script");
	    script.setAttribute("type", "text/javascript");
	    script.setAttribute("src", request);
	    head.appendChild(script);
	}	
}



function createImageInfoMap(changeColor) {
	if(changeColor) {
	//cm Image Change action
		sendCMColourChange();
		//remove current image url when changing colors
		s7imageURL = null;
	}	
	//clear array
	var thumbnails = $$('#imageNavigator a.thumbnail');
	if (thumbnails[0]) {
		dynamicTag(thumbnails[0].getProperty('href'),0);
	} else {
		//set primary image if there is
		if($('pPrImg')) {
			dynamicTag($('pPrImg').value,0);
		}
	}
}
//end s7

// for update product quantity with Ajax, builds the HTTP call for Ajax
function calculateTotalProductPrice(url, productID, quantity, pom_string) {
	var query = "pid=" + encodeURIComponent(productID) + "&Quantity=" + encodeURIComponent(quantity) + pom_string;
	var ajax = new Request.HTML({url: url, method: "post", data: query , update: "productprice-total", onComplete: doNothing}).send();
}

// dummy method
function doNothing() {
	// we do nothing
}


function swapPriceByAjax()
{
		var pidQuery = "pid=" + encodeURIComponent(document.forms.cartaddproduct.pid.value); // now pid value should be updated
	    // we change the price
	    var url2 = document.forms.cartaddproduct.update_url_price.value;
		var query2 = pidQuery;
		var ajax2 = jQuery.get(url2, query2, function(data, textStatus, XMLHttpRequest){ swapPriceByAjaxOnComplete(data); });
}

function swapPriceByAjaxOnComplete(responseHTML)
{
	responseHTML = responseHTML.replace(/<div(.*?)dw-object dw-object-rinclude(.*?)<\/div>/gi,"");
	jQuery("#productPrice").html(responseHTML);
}

function swapRecommendationsByAjax()
{
	var container = "#productDetailUpsell";
	var pidQuery = "pid=" + encodeURIComponent(document.forms.cartaddproduct.pid.value) + "&cgid=" + encodeURIComponent(document.forms.cartaddproduct.cgid.value); // now pid value should be updated
	    // we change the price
	var url2 = document.forms.cartaddproduct.update_url_recommendations.value;
	var ajax2 = jQuery(container).load(url2+'?'+pidQuery);
}

function changeOption(optionLink) {
	window.location.href = optionLink+'&Quantity='+$('Quantity')[$('Quantity').selectedIndex].value;
}

//CM for usage of product images
var cmCurrentColour = "";
var cmCurrentMasterPID = "";
var cmCurrentPName = "";
var cmCurrentCat = "";
var cmEnabled = false;

function sendProductImagesCMData(action,cmColour) {
	var cmColour = cmColour == undefined ? cmCurrentColour : cmColour;
	if(cmColour == 'null') cmColour = '';
	cmCurrentColour = cmColour;
	//alert(" action: "+action + "\n Colour: " + cmColour+ "\n cmCat: "+cmCurrentCat+"\n PID: "+cmCurrentMasterPID+"\n Name: "+cmCurrentPName);
	cmCreatePageElementTag(action + ": "+cmCurrentCat, action, "", "", "", cmCurrentMasterPID + "|" + cmColour + "-_-" + cmCurrentPName);
}

function initCMProductImages() {
	//events to scene7 object
	if (typeof(s7zoom) != 'undefined' && s7zoom != null) {
		///s7zoom.onEvent.onImageZoomedIn = function(scale) {
			//sendProductImagesCMData("Image Zoom In");
		///};
		//s7zoom.onEvent.onImageZoomedOut = function(scale) {
			//sendProductImagesCMData("Image Zoom Out");
		//};
	}
	//events to alternative images
	initCMEventToImages();
}

function initCMEventToImages() {
	$$('#imageSlide a.thumbnail img').addEvent(
		'click', function() {
				var altImgId = this.getParent('a').id;
				var lastWord = altImgId.substring(altImgId.length - 1,altImgId.length);
				if(lastWord == 'g') lastWord = 0;
				var altNo = parseInt(lastWord)+1;
				sendProductImagesCMData("Image Alternate"+altNo);
		}
	);
}

function sendProductMediaCMData(action) {
	cmCreatePageElementTag(cmCurrentCat, action, "", "", "", cmCurrentMasterPID + "-_-" + cmCurrentPName + "-_-" + cmCurrentCat + "-_--_--_--_--_--_--_--_--_--_--_--_-");
}

function sendProductTabsCMData(tabLabel) {
	cmCreatePageElementTag(cmCurrentCat, "Product Tab: " + tabLabel, "", "", "", "-_--_--_--_--_--_--_--_--_--_--_--_--_--_-");
}

function sendProductSentFrinedCMData(action) {
	cmCreateConversionEventTag("Send to a friend", action, "Send to a friend", "10", cmCurrentMasterPID + "-_-" + cmCurrentCat + "-_--_--_--_--_--_--_--_--_--_--_--_--_-");
}

function initCMProductVideo() {
	jQuery('#video').bind('click', function() {
		sendProductMediaCMData("Video Click");
	});
}

function initCMProduct360() {
	jQuery('#video360').bind('click', function() {
		sendProductMediaCMData("360 Click");
	});
}

function initCMProductTabs() {
	jQuery('#tabHeaderProduct .tabHead').bind('click', function() {
		sendProductTabsCMData(jQuery(this).text());
	});
}

function initSentFrinedCMData() {
	jQuery('#tellafriend').bind('click', function(){
		sendProductSentFrinedCMData(1);
	});
	jQuery('#sendToFriend .rightSection a').live('click', function(){
		sendProductSentFrinedCMData(2);
	});	
}

function sendCMColourChange() {
	if(cmEnabled) {
		sendProductImagesCMData("Image Change",$('sz_currentcolour').value);
		//event to new images
		initCMEventToImages();
	}
}

jQuery(document).ready(function() {
	if(cmEnabled) {
		initCMProductVideo();
		initCMProduct360();
		initCMProductTabs();
		initSentFrinedCMData();
	}
});

window.addEvent('domready', function() {
	if(cmEnabled) {
		initCMProductImages();
	}
	bindEvents();
});
//end CM for usage of product images

function bindEvents () {
	
}

//stock notification
var StockNotification = {
	notificationLink: "",
	pid:'',
	url:'',
	form:'',
	button:'',
	sending:false,
	init: function () {
	   this.notificationLink = $('notificationLink');
	},
	
	addLinkClick: function(url,pid) {
		var stockNotificatonDiv  = $('stockNotification');
    	if(stockNotificatonDiv == null || stockNotificatonDiv.get('class').indexOf('hide') != -1) {
    		var pidQuery = "pid=" + encodeURIComponent(pid);
			StockNotification.url = url;
			StockNotification.pid = pid;
			var ajax = new Request.JSON({url:url, method: "post", data: pidQuery, 
				onSuccess:StockNotification.ajaxResponse
			}).send();
    	} else {
    		stockNotificatonDiv.addClass("hide");
    	}
	},
	
	ajaxResponse: function(json) {
		switch (json.action) {
		 	case 'login':               
		 		window.location = json.url;
		 		break; 				
			case 'edit': 
				StockNotification.notificationLink.set({'href':json.url, 'text': json.linkText});
		        break;
			case 'form': 
				StockNotification.formShow(StockNotification.url, StockNotification.pid);
				break;
			case 'ok':
				StockNotification.notificationLink.set({'href':json.url, 'text': json.linkText});				
				StockNotification.showAdded();
				StockNotification.hideBackInStockDialog();
				break;
			case 'error':
				StockNotification.showPropblem(json.message);
				break;
			default:
				StockNotification.showPropblem("Error found in form. Please review all your input data and try submitting the form again.");
				break;
		}				
	},
	
	formShow : function(url,pid) {		
    	var stockNotificatonDiv  = $('stockNotification');
    	if(stockNotificatonDiv.get('class').indexOf('hide') != -1) {
	    	stockNotificatonDiv.removeClass("hide");
	    	var stockNotificationMessageHeight = $("stockNotificationMessage").getSize().y;
	    	stockNotificatonDiv.setStyle('top', stockNotificationMessageHeight + $("stockNotificationMessage").getPosition($("stockNotificationMessage").getOffsetParent()).y);
	    	stockNotificatonDiv.setStyle('left', $("stockNotificationMessage").getPosition($("stockNotificationMessage").getOffsetParent()).x);
			sendProductImagesCMData("Notification form show");
    	}
	},
	
	hideBackInStockDialog : function() {
		jQuery("#stockNotification").hide();
	},
	
	addNotification: function(obj) {
		if(StockNotification.sending) {
			return;
		}
		var form = obj.form;
		var url = form.action; 
		StockNotification.form = form;
		StockNotification.button = obj;
		StockNotification.sending = true;
		StockNotification.showLoading();		
		var ajax = new Request.JSON({url:form.action, method: "post", data: form, onSuccess:StockNotification.ajaxResponse}).send();
		sendProductImagesCMData("Notification form send");
	},

	showLoading: function(){
		// change button. disable form?
		StockNotification.form.add		
		StockNotification.button.src = staticRoot+'img/asda_img/loading_addtobasket.gif';
	},
	
	showAdded : function(){
		//show item added for few seconds. change link. hide
		StockNotification.button.src = staticRoot+'img/asda_img/button_item_added_GM.gif';
		setTimeout(function(){
			var stockNotificatonDiv  = $('stockNotification');
			$('stockNotification').addClass("hide");
			StockNotification.sending = false;
			}, 3000 );		
		
	},
	
	showPropblem: function(message){
		StockNotification.sending = false;
		var stockNotificatonMessage  = $('stockNotificatonMessage');
		if (stockNotificatonMessage == null) {
			stockNotificatonMessage = new Element('span' , {'id':'stockNotificatonMessage'});
	    	stockNotificatonMessage.inject($('stockNotification') , 'top');
		}
		stockNotificatonMessage.set('text', message);
		StockNotification.button.src = staticRoot+'img/btn_update.gif';
	}	
}


// PRODUCT DETAILS TAB CLASS
var Tab = new Class({

	/* set and create the tabs */
	initialize: function(t) {
		// hide the section titles because they are needed only when JS is off
		if($(t.getProperty('id') + "Content").getElement('h3')) {
			$(t.getProperty('id') + "Content").getElement('h3').addClass('hide');
		}
		
		// show the content of the active tab
		if(t.getParent().getProperty('class') == "active") {
			$(t.getProperty('id') + "Content").removeClass("hidden");
			t.isActive = true;
		} else if(t.getProperty('id') != "reviews"){
			// show the buttons that are not for the reviews
			$(t.getProperty('id') + "Btn").getParent().getParent().removeClass("hidden");
			t.isActive = false;
		}
		
		t.addEvent("click", this.create, false);
	},

	create: function(e) {
		var tab = e.target

		if(!tab.isActive) {
			focusTab(tab);
			e.stop();
			return false;
		}
	}

});

// PRODUCT DETAILS TAB RELATED BUTTONS CLASS
var ReadButton = new Class({

	/* set and create the buttons for the tabs */
	initialize: function(t){
		t.addEvent("click", this.create, false);
		t.addEvent("focus", this.create, false);
	},

	create: function(e) {
		var readBtn = e.target
		var tab = $(readBtn.getProperty('id').replace("Btn", ""));		
		focusTab(tab);
		$(document.body).scrollTo(tab.getPosition().x, tab.getPosition().y);
		e.stop();
	}

});

focusTab = function (tab)  {
	if(tab != null && !tab.isActive) {
		var oldTab;
		$$('div.tab a span').each( function(el){
			if(el.isActive) {
				oldTab = el;
			}
		})
		
		var oldSrc = "";
		var newSrc = "active";
		
		oldTab.isActive = false
		oldTab.getParent().setProperty('class', oldSrc);
		$(oldTab.getProperty('id') + 'Content').addClass('hidden');
		$(tab.getProperty('id') + 'Btn').getParent().getParent().addClass('hidden');
		
		$(oldTab.getProperty('id') + 'Btn').getParent().getParent().removeClass('hidden');
		tab.getParent().setProperty('class', newSrc);
		$(tab.getProperty('id') + 'Content').removeClass('hidden');
		tab.isActive = true;
	}
	return false;
}

function initTags()
{
	var thumbnails = $$("#imageSlideInnerSmall a.thumbnail")
	if(thumbnails) {
		if($("th_prImgSmall")) {
			dynamicTag($("th_prImgSmall").href ,0);
		} else if($("pPrImg")) {
			dynamicTag($("pPrImg").value ,0);
		}
		thumbnails.each(function(element) {
			var item = element.id.split("Small");
			item = item[0].split("th_s");
			item = item[1];
			if(item != undefined) {
				dynamicTag(element.href ,item);
			}
		})
	}
}

