/**
 * 
 */
PSIConfig = {
	setImageRadioButtons : function (l) {	
		
		var parent = $(l).getParent();
		var img = parent.getElementsByTagName('img');
		var inputs = parent.getElementsByTagName('input');
		
		if ($$(inputs)[0].getProperty('disabled') == true)
			return;
			
		$$('#newSizeSwatches img').each(function(img) {
			var src = $(img).getProperty('src');
			$(img).setProperty('src', src.replace(/_select/, ''));		
		});
		
		$$(inputs)[0].setProperty('checked', 'checked');	
		
		var src = $$(img)[0].getProperty('src');
		var src2 = src.replace(/(size_button_)(\w+)/, "$1$2_select");
		$$(img)[0].setProperty('src', src2);
	}
}

window.addEvent('domready', function(){

});

// 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;
		} 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;
}

// TODO has to go in general library
function disableFormsAndItsElements(activatorName) {
	var allForms = document.forms;
	for (var i = 0; i < allForms.length; i++) {
		var aForm = allForms[i];
		if (aForm.name != activatorName) { 
			aForm.action = "javascript:void";
		}
		var allFormElements = aForm.elements;
		for (var k = 0; k < allFormElements.length; k++) {
			var aElement = allFormElements[k];
			if (aElement.name != activatorName && "disabled" in aElement) { 
				aElement.disabled = true;
			}
		}
	}
	return false;
}


// 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;
	var ajax1 = new Ajax(url1 ,{method: "get", data: query1 , update: "configuration", onComplete: function(){swapVariantByAjaxOnComplete(parameterName)} }).request();
}


// 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) {
	window.fireEvent('domready');
    TB_init(); //!! We call TB_init() because the style guide event handler has to be initialized again, after Ajax call.
	
	//HOF-1787
	onChangeToQuantity();
	
	// if colour change we request new images:
	if (parameterName == "Colour") {
	    swapImagesByAjax();
	}
	swapPriceByAjax();
	
	swapRecommendationsByAjax();
	
	if (parameterName == "Colour") {
		eval($("ColourChangeCoremetricsCode").innerHTML);
	}
}

// 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);
					fixSetImage(thumbLink,true);
					s7zoom.reset();
					e.stop();
				});
		}
		var thumbLink = thumbnails[0].getProperty('href');
		fixSetImage(thumbLink,true);
		//s7zoom.setImage(thumbLink,true);
		//s7zoom.reset();
		
	} else { // delete image in tszoom, 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);
	if ($("productprice-total"))
	{
		var ajax = new Ajax(url ,{method: "post", data: query , update: "productprice-total", onComplete: doNothing }).request();
	}
}

// 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;
		$("productRealPrice").style.visibility = "hidden"; 
		var ajax2 = new Ajax(url2 ,{method: "get", data: query2 , update: "productRealPrice", onComplete: function () {$("productRealPrice").style.visibility = "visible";} }).request();
		calculateTotalProductPrice(document.forms.cartaddproduct.update_url_totalprice.value,document.forms.cartaddproduct.pid.value,selEl.getValue());
}

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 Ajax(url2 ,{method: "get", data: query2 , update: "tab1", onComplete: doNothing }).request();
}

//HOF-1787
function onChangeToQuantity() {
	var selEl = $$("div.productQuantity select.quantity_select").addEvent( 'change', function() { calculateTotalProductPrice(document.forms.cartaddproduct.update_url_totalprice.value,document.forms.cartaddproduct.pid.value,selEl.getValue()) } );
}
