// 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 $ = document.id;
	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 + '?';
	var ajax1 = new Request.HTML({update: "productFeatures", evalScripts: true, onSuccess: function(){swapVariantByAjaxOnComplete(parameterName)} }).get( url1 + query1 );
}

function swapProductTopDesc() {
	var $ = document.id;
    var topDesc = $("productTopDesc").innerHTML;
    //alert(topDesc);
    $("productRepeat").set('html', 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) {
     //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);

    TB_init(); //!! We call TB_init() because the style guide event handler has to be initialized again, after Ajax call.
}

// changes the images with Ajax if necessary
function swapImagesByAjax() {
	var $ = document.id;
	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 Request.HTML({url: url2, method: "get", data: query2 , update: "imageNavigator", onComplete: refreshThumbnailsAndImage }).send();
	}
}


// refresh the thumbnails and the image in scope
function refreshThumbnailsAndImage() {
	jQuery("#imageNavigator > ul > li > a").each(function () { // preload each full size product image
		var imgToload = jQuery(this).attr("href");
	
		var sizeRegexp = new RegExp(imgSizes.normal.width + ',' + imgSizes.normal.width, 'gi');
		var imgToloadbig = imgToload.replace(sizeRegexp, imgSizes.big.width + ',' + imgSizes.big.width);
		
		var widRegexp = new RegExp('wid=' +imgSizes.normal.width, 'gi');
		var imgToloadbig = imgToloadbig.replace(widRegexp, 'wid=' + imgSizes.big.width);
	
		var heiRegexp = new RegExp('hei=' + imgSizes.normal.height, 'gi');
		var imgToloadbig = imgToloadbig.replace(heiRegexp, 'hei=' + imgSizes.big.height);

		var itsRegexp = new RegExp('sw=' + imgSizes.normal.width + '&sh=' + imgSizes.normal.height, 'gi');
		var imgToloadbig = imgToloadbig.replace(itsRegexp, 'sw=' + imgSizes.big.width + '&sh=' + imgSizes.big.height);		
		
		var imgToloadVerybig = imgToload.replace(imgSizes.normal.width + ',' + imgSizes.normal.width, imgSizes.veryBig.width + ',' + imgSizes.veryBig.width);
		var imgToloadVerybig = imgToloadVerybig.replace('wid=' +imgSizes.normal.width, 'wid=' + imgSizes.veryBig.width);
		var imgToloadVerybig = imgToloadVerybig.replace('hei=' + imgSizes.normal.height, 'hei=' + imgSizes.veryBig.height);
		
		jQuery(this).click(function() {
			jQuery('#productImage img').attr('src', this.href);
			
			fnImgSrc();
			
			return false;
		});
		
		jQuery.preloadImages(imgToload,imgToloadbig,imgToloadVerybig);
    });
	
	var thumbLink = jQuery("#imageNavigator > ul > li > a:first").attr('href');
	
	jQuery('#productImage img').attr('src', thumbLink);
	
	fnImgSrc();
}

// for update product quantity with Ajax, builds the HTTP call for Ajax
function calculateTotalProductPrice(url, productID, quantity) {
	var $ = document.id;
	var query = "pid=" + encodeURIComponent(productID) + "&Quantity=" + encodeURIComponent(quantity) + "&currencyConvert=1";
	var ajax = new Request.HTML({url: url, method: "post", data: query , update: "productprice-total", onComplete: doNothing }).send();
}

function productIsInStock(url, productID) {
	var $ = document.id;
	var query = "pid=" + encodeURIComponent(productID)+"&cgid="+encodeURIComponent(document.forms.cartaddproduct.cgid.value);
	var ajax = new Request.HTML({update: "addToCartButton", onComplete: doNothing }).post( url + '?' + query );
}

// dummy method
function doNothing() {
	// we do nothing
}

// sent to friend
function submitSendToAFriend(form) {
	var $ = document.id;
	var ajax = new Request.HTML({url: form.action, method: 'post', data: form, update: 'sendToFriend'}).send();
	return false;
}

//send to a friend close button title
window.addEvent('domready', function(){
	var $ = document.id;
	if ($('sendFriend')) {
		$('sendFriend').addEvent('click', function(){
			$('TB_closeAjaxWindow', 'a').setProperty('title', 'Close');
		});
	}	
})

