 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 ajax1 = new Request({
        url: url1,
        method: 'get',
        data: query1,
        update: "productDetails",
        onComplete: function(){
			swapVariantByAjaxOnComplete(parameterName, this.response.text)
        }
    }).send();
	//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(){
		jQuery("#productDetails").html(response);
		var ffProductDetails = new tabset($$("div#productInformation ul.tabNavigation li a"), "productInformation", $("productInformation01"), $$("div#productInformation div.tab"));
		jQuery("#productInformation01").css("display","");
		sizeOptions.init();
		colourOptions.init();
		minicart.init();
	});
	swapImagesByAjax();
}


// changes the images with Ajax if necessary
function swapImagesByAjax(){
    if ($('productImage')) {
        // 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 , onComplete: function(){refreshThumbnailsAndImage(this.response.text)} }).request();
        var ajax2 = new Request({
            url: url2,
            method: 'get',
            data: query2,
            onComplete: function(){
                refreshThumbnailsAndImage(this.response.text)
            }
        }).send();
    }
}

// refresh the thumbnails and the image in scope
function refreshThumbnailsAndImage(response) {
	$('productImageHolder').innerHTML = response;
	fnImgSrc();
}

// 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();
    var ajax = new Request({
        url: url,
        method: 'post',
        data: "pid=" + productID + "&Quantity=" + quantity,
        update: "productprice-total",
        onComplete: completeRequest
    }).send();
}

// 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 ajax = new Request({
        url: url,
        method: 'get',
        data: "sentUrl=" + sentUrl,
        update: "sendToFriend",
        onComplete: completeRequest
    }).send();
}

var sizeOptions = {
	sizeOptionActivators: "",
	currentSelection: "",
	summarySize: "",
	init: function() {
		// Mootools dollar
		this.$ = document.id;
		
		if (!this.$("sizeOptions")) return;
		this.createCurrentSizeIndicator();
		this.setSummarySizeElement();
		sizeOptionActivators = this.get();
		for (i=0; i < sizeOptionActivators.length; i++) {
			this.$(sizeOptionActivators[i]).addClass("enhanced");
			sizeOptionActivators[i].radioButton = sizeOptionActivators[i].getElementsByTagName("input")[0];
			sizeOptionActivators[i].text = $$(sizeOptionActivators[i], "p.name").get('text');
			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 (!document.getElements("span.selected", "descriptionSummary")) return;
		this.summarySize = document.getElements("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.summarySize.set('text', 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++) {
			this.$(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() {
		// Mootools dollar
		this.$ = document.id;
		
		if (!this.$("colourOptions")) return;
		this.createCurrentIndicator();
		colourOptionActivators = this.get();
		for (i=0; i < colourOptionActivators.length; i++) {
			this.$(colourOptionActivators[i]).addClass("enhanced");
			colourOptionActivators[i].radioButton = colourOptionActivators[i].getElementsByTagName("input")[0];
			colourOptionActivators[i].text = document.getElements("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.$( 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).set('text', 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++) {
			this.$(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();
});
