// ATTENTION: parameterValue has to be escaped, will be unescaped internally
// TODO: escape()/unescape() is deprecated since ECMAScript v3.
var strFormID = "cartaddproduct";
function buildVariantRequestQuery(parameterName, parameterValueEscaped, parameterNameToIgnore) {
	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["cartaddproduct"];
	
	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;
}

// for choosing a new variant with Ajax, builds the HTTP call for Ajax
function swapVariantByAjax(parameterName, parameterValue, parameterNameToIgnore) {
	var pidQuery = "pid=" + document.forms.cartaddproduct.pid.value+"&cgid="+encodeURIComponent(document.forms.cartaddproduct.cgid.value); // now pid value should be updated
    var query1 = buildVariantRequestQuery(parameterName, parameterValue, parameterNameToIgnore);
    var url1 = document.forms.cartaddproduct.update_url_choose.value;
    //alert(url1 + ', query1:' + query1 + ', pidQuery:' + pidQuery);
	var ajax1 = new Ajax(url1 ,{method: "get", data: query1 , update: "productFeatures", evalScripts: true, onComplete: function(){swapVariantByAjaxOnComplete(parameterName)} }).request();
	
}

function swapProductTopDesc() {
    var topDesc = $("productTopDesc").innerHTML;
    //alert(topDesc);
    $("productRepeat").setHTML(topDesc); 
}
// 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 
// replace the text with images in the reloaded part of the page
function swapVariantByAjaxOnComplete(parameterName) {
    TB_init(); //!! We call TB_init() because the style guide event handler has to be initialized again, after Ajax call.
     //USC-984
     s7replaceText();
     swapProductTopDesc();
	 //USC-984
	// if colour change we request new images:
	if (parameterName == "colour") {
	    swapImagesByAjax();
	    sendCoremetrics();
	}
	//change the total price in case the colour variations have different prices
	calculateTotalProductPrice(document.forms.cartaddproduct.update_url_price.value, document.forms.cartaddproduct.pid.value, document.forms.cartaddproduct.Quantity.value);
	productIsInStock(document.forms.cartaddproduct.update_url_instock.value, document.forms.cartaddproduct.pid.value);
}

// 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.cartaddproduct.pid.value); // now pid value should be updated
	    // we change the images
	    var url2 = document.forms.cartaddproduct.update_url_images.value;
		var query2 = pidQuery; 
		var ajax2 = new Ajax(url2 ,{method: "get", data: query2 , update: "imageNavigator", onComplete: refreshThumbnailsAndImage }).request();
	}
}


// refresh the thumbnails and the image in scope
function refreshThumbnailsAndImage() {
	var thumbnails = $$('#imageNavigator a.thumbnail');
	if (thumbnails[0]) {
		for (var i = 0; i < thumbnails.length; i++) {
			thumbnails[i].addEvent(
				'click', 
				function(e) {
					e = new Event(e);
					var thumbLink = this.getProperty('href');
					$$("#productImage img").setProperty("src", thumbLink);
					thumbLink = thumbLink.substring(0).split("?");
					thumbLink = thumbLink[0] + "?wid=1256&hei=1480&resmode=sharp&scl=1.35";
					$$("#productImage img").setProperty('jqimg', thumbLink);
					e.stop();
				});
		}
		var thumbLen = thumbnails.length;
		var thumbLink = thumbnails[0].getProperty('href');
		$$('#productImage img').setProperty('src', thumbLink);
		thumbLink = thumbLink.substring(0).split("?");
		thumbLink = thumbLink[0] + "?wid=1256&hei=1480&resmode=sharp&scl=1.35";
		$$("#productImage img").setProperty('jqimg', thumbLink);
		
		//var thumbjqimg = $$("#productImage img").getProperty('jqimg');
		//alert(thumbnails);
		//new Asset.images(thumbjqimg, {onComplete: alert(thumbjqimg)});
		
		
	} else { // delete image in s7zoom, because there is no image available
		// TODO , but situation shouldn't occur
	}
}

// for update product quantity with Ajax, builds the HTTP call for Ajax
function calculateTotalProductPrice(url, productID, quantity) {
	var query = "pid=" + encodeURIComponent(productID) + "&Quantity=" + encodeURIComponent(quantity);
	var ajax = new Ajax(url ,{method: "post", data: query , update: "productprice-total", onComplete: doNothing }).request();
}

function productIsInStock(url, productID) {
	var query = "pid=" + encodeURIComponent(productID)+"&cgid="+encodeURIComponent(document.forms.cartaddproduct.cgid.value);
	var ajax = new Ajax(url ,{method: "post", data: query , update: "addToCartButton", onComplete: doNothing }).request();
}

// dummy method
function doNothing() {
	// we do nothing
}

// sent to friend
function submitSendToAFriend(form) {
	var ajax = new Ajax(form.action, {method: 'post', data: form, update: 'sendToFriend'}).request();
	return false;
}

//send to a friend close button title
window.addEvent('domready', function(){
	if ($('sendFriend')) {
		$('sendFriend').addEvent('click', function(){
			$('TB_closeAjaxWindow', 'a').setProperty('title', 'Close');
		});
	}	
})
