// 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: 'sendToFriend'}).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 ajax1 = new Request.HTML({url: url1, method: "get", data: query1, update: "buy_options", evalScripts: true, onComplete: function(){swapVariantByAjaxOnComplete(parameterName)} }).send();
}


// 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();
	}
	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() {
	
	if ($('imageNavigator')) { // 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 = $('clr_update_url_images').value;
		var query2 = pidQuery; 
		var ajax2_1 = new Request.HTML({url: url2, method: "get", data: query2, update: "imageNavigator", onComplete: createImageInfoMap }).send();
		
	}
}

//s7
var loadImageSizeErr = false;
var currentImageForLoad = 0;
var initLoadImageSize = true;

if(sjCallbacks == null) {
	var sjCallbacks = new Object();
}

if(sjErrCallbacks == null) {
	var sjErrCallbacks = new Object();
}

s7jsonResponse = function(inArr,inID) {
	sjCallbacks['loadImageSize'](inArr);
}

window.s7jsonError = function(inArg, inId) {
	
	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 {
		//var thumbnails = $$('#imageNavigator a.thumbnail');
		//if(thumbnails.length > 0) {
			//dynamicTag(thumbnails[0].getProperty('href'),true,false);
		//} else {
			dynamicTag(noImgUrl,currentImageForLoad);
		//}
	}
	//alert(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 iamge
			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;
	
	if(currentItem == 0) {
		var thumbnail = $('th_prImg');
		//set current image
		fixSetImage(url,true);
		s7zoom.reset();
	} else {
		var thumbnail = $('th_s'+currentItem);
	}
	
	//add click event on loaded thumbnail
	if(thumbnail) {
		thumbnail.addEvent(
			'click', 
			function(e) {
				e = new Event(e);
				var thumbLink = this.getProperty('href');
				fixSetImage(thumbLink,true);
				s7zoom.reset();
				e.stop();
			});
	}
	
	//recursive call to get next image size
	//get all thumbnails
	var thumbnails = $$('#imageNavigator a.thumbnail');
	
	//we have alternative images
	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);
		}
	}
}

//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) {
		//the image is in imageInfoMap
		//check next image
		//we have alternative images
		var thumbnails = $$('#imageNavigator a.thumbnail');
		if(thumbnails.length > 0) {
			
			if(currentItem == 0) {
				var thumbnail = $('th_prImg');
				//set current image
				fixSetImage(url,true);
				s7zoom.reset();
			} else {
				var thumbnail = $('th_s'+currentItem);
			}
			
			//add click event on loaded thumbnail
			if(thumbnail) {
				thumbnail.addEvent(
					'click', 
					function(e) {
						e = new Event(e);
						var thumbLink = this.getProperty('href');
						fixSetImage(thumbLink,true);
						s7zoom.reset();
						e.stop();
					});
			}
			
			var nextItem = currentItem+1;
			var nextThumbnail = $('th_s'+nextItem);
			//we have next iamge
			if(nextThumbnail) {
				//load next image
				dynamicTag(nextThumbnail.getProperty('href'),nextItem);
			}
		} else {
			fixSetImage(url,true);
			s7zoom.reset();
		}
	} 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() {
	//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);
		}
	}
	
	//cm Image Change action
	sendCMColourChange();
}
//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 = new Request.HTML({url: url2, method: "get", data: query2, update: "productPrice", onComplete: doNothing }).send();
}

function swapRecommendationsByAjax()
{
		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 query2 = pidQuery; 
		var ajax2 = new Request.HTML({url: url2, method: "get", data: query2, update: "productDetailUpsell", onComplete: doNothing }).send();
}

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 (s7zoom != undefined && s7zoom != null) {
		s7zoom.onEvent.onImageZoomedIn = function(scale) {
			sendProductImagesCMData("Image Zoom In");
		};
		s7zoom.onEvent.onImageZoomedOut = function(scale) {
			sendProductImagesCMData("Image Zoom Out");
		};
		$('resetButton').addEvent('click',function() {
			var imgController =$$('ul#imageController.zoomedIn'); 
			if($chk(imgController[0])) {
				sendProductImagesCMData("Image Reset");
				//alert('exists');
			}
		});
	}
	//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 sendCMColourChange() {
	if(cmEnabled) {
		sendProductImagesCMData("Image Change",$('sz_currentcolour').value);
		//event to new images
		initCMEventToImages();
	}
}

window.addEvent('domready', function() {
	if(cmEnabled) {
		initCMProductImages();
	}
});
//end CM for usage of product images