 function radioValue(rObj) {
    for (var i=0; i<rObj.length; i++) if (rObj[i].checked) return rObj[i].value;
    return false;
 }
 
 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;
		} 
	}
	colour = myForm.colour != null ? radioValue(myForm.colour) : null;
	size = myForm.size != null ? radioValue(myForm.size) : null;
	var colourUrlPart = "";
	if (parameterNameToIgnore != "colour" && colour != null && colour != "@@@") {
		colourUrlPart = "&" + myForm.colourAttributeName.value + "=" + colour;
	}
	var sizeUrlPart = "";
	if (parameterNameToIgnore != "size" && size != null && size != "@@@") {
		sizeUrlPart = "&" + myForm.sizeAttributeName.value + "=" + size;
	}

	// dwvar-parameter names are variation attribute parameters for the Demandware pipelet "UpdateProductVariationSelections": 
	url = url + "?pid=" + pid + "&cgid=" + cgid + "&Quantity=" + quantity + colourUrlPart + sizeUrlPart;
	
	window.location.href = url;
}

// ATTENTION: parameterValue has to be escaped, will be unescaped internally
// TODO: escape()/unescape() is deprecated since ECMAScript v3.
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;
		} 
	}
	colour = myForm.colour != null ? radioValue(myForm.colour) : null;
	size = myForm.size != null ? radioValue(myForm.size) : null;
	var colourUrlPart = "";
	if (parameterNameToIgnore != "colour" && colour != null) {
		colourUrlPart = "&" + myForm.colourAttributeName.value + "=" + encodeURIComponent(colour);
	}
	var sizeUrlPart = "";
	if (parameterNameToIgnore != "size" && size != null) {
		sizeUrlPart = "&" + myForm.sizeAttributeName.value + "=" + 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; // 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: "productDetails", onComplete: function(){swapVariantByAjaxOnComplete(parameterName, this.response.text)} }).request();

	//var url1 = document.forms.cartaddproduct.update_url.value;
	//window.location.href = url1 + "?" + query1;
}

// 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, response) {
    TB_init(); //!! We call TB_init() because the style guide event handler has to be initialized again, after Ajax call.
    
	window.addEvent('domready', function(){
		var ffProductDetails = new tabset($$("div#productInformation ul.tabNavigation li a"), "productInformation", $("productInformation01"), $$("div#productInformation div.tab"));
		sizeOptions.init();
		colourOptions.init();
		minicart.init();
	});
	swapImagesByAjax();
}

// changes the images with Ajax if necessary
function swapImagesByAjax() {
	if ($('imageSlideInner')) { // 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: "imageSlideInner", 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');
					s7zoom.setImage(thumbLink,true);
					s7zoom.reset();
					e.stop();
				});
		}
		var thumbLink = thumbnails[0].getProperty('href');
		s7zoom.setImage(thumbLink,true);
		s7zoom.reset();
		
	} 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 ajax = new Ajax(url ,{method: "post", data: "pid="+productID+"&Quantity="+quantity , update: "productprice-total", onComplete: completeRequest }).request();
}

// for update product quantity with Ajax, but currently empty
function completeRequest() {
	// currently we do nothing
}

function sendToFriend(url,sentUrl) {
	var ajax = new Ajax(url ,{method: "get", data: "sentUrl="+sentUrl , update: "sendToFriend", onComplete: completeRequest }).request();
}

var sizeOptions = {
	sizeOptionActivators: "",
	currentSelection: "",
	summarySize: "",
	init: function() {
		if (!$("sizeOptions")) return;
		this.createCurrentSizeIndicator();
		this.setSummarySizeElement();
		sizeOptionActivators = this.get();
		for (i=0; i < sizeOptionActivators.length; i++) {
			$(sizeOptionActivators[i]).addClass("enhanced");
			sizeOptionActivators[i].radioButton = sizeOptionActivators[i].getElementsByTagName("input")[0];
			sizeOptionActivators[i].text = $ES("p.name", sizeOptionActivators[i]).getText();
			sizeOptionActivators[i].onclick = sizeOptions.click;
			sizeOptionActivators[i].onmouseover = sizeOptions.hover;
			sizeOptionActivators[i].onmouseout = sizeOptions.removeClass;
			if (sizeOptionActivators[i].radioButton.checked) {
				sizeOptionActivators[i].addClass("selected");
				this.currentSelection.appendText(sizeOptionActivators[i].text);
				this.summarySize.setText(sizeOptionActivators[i].text);
			}
		}
	},
	setSummarySizeElement: function() {
		if (!$ES("span.selected", "descriptionSummary")) return;
		this.summarySize = $ES("span.selected", "descriptionSummary")[0];
	},
	get: function() {
		return ($$("#sizeOptions ul.sizes li"));
	},
	click: function() {
		this.radioButton.checked = true;
		sizeOptions.removeAllClasses();
		this.addClass("selected");
		swapVariantByAjax('size',this.radioButton.value,null);
		sizeOptions.currentSelection.setText(this.text);
		sizeOptions.summarySize.setText(this.text);
	},
	hover: function() {
		$(this).addClass("selected");
	},
	removeClass: function() {
		if (this.radioButton.checked) return;
		$(this).removeClass("selected");
	},
	removeAllClasses: function() {
		for (i = 0; i < sizeOptionActivators.length; i++) {
			$(sizeOptionActivators[i]).removeClass("selected");
		}
	},
	createCurrentSizeIndicator: function() {
		var h4 = $$("#sizeOptions h4")[0];
		var p = new Element("p", { "class": "selected" });
		this.currentSelection = p;
		p.injectAfter( h4 );
		
	}
}

var colourOptions = {
	colourOptionActivators: "",
	currentSelection: "",
	init: function() {
		if (!$("colourOptions")) return;
		this.createCurrentIndicator();
		colourOptionActivators = this.get();
		for (i=0; i < colourOptionActivators.length; i++) {
			$(colourOptionActivators[i]).addClass("enhanced");
			colourOptionActivators[i].radioButton = colourOptionActivators[i].getElementsByTagName("input")[0];
			colourOptionActivators[i].text = $ES("div.image img", colourOptionActivators[i]).getProperty("alt");
			colourOptionActivators[i].onclick = colourOptions.click;
			colourOptionActivators[i].onmouseover = colourOptions.hover;
			colourOptionActivators[i].onmouseout = colourOptions.removeClass;
			if (colourOptionActivators[i].radioButton.checked) {
				$( this.currentSelection ).appendText(colourOptionActivators[i].text);
			}
		}
	},
	get: function() {
		return ($$("#colourOptions ul.colours li"));
	},
	click: function() {
		if (!this.radioButton.disabled) {
			this.radioButton.checked = true;
			colourOptions.removeAllClasses();
			swapVariantByAjax('colour',this.radioButton.value,null);
			$(this).addClass("selected");
			$(colourOptions.currentSelection).setText(this.text);
		}
	},
	hover: function() {
		if (this.radioButton.checked) return;
		$(this).addClass("selected");
	},
	removeClass: function() {
		if (this.radioButton.checked) return;
		$(this).removeClass("selected");
	},
	removeAllClasses: function() {
		for (i = 0; i < colourOptionActivators.length; i++) {
			$(colourOptionActivators[i]).removeClass("selected");
		}
	},
	createCurrentIndicator: function() {
		var h4 = $$("#colourOptions h4")[0];
		var p = new Element("p", { "class": "selected" });
		this.currentSelection = p;
		p.injectAfter( h4 );
	}
}

window.addEvent('domready', function() {
	 sizeOptions.init();
	 colourOptions.init();
});