//GLOBAL VARIABLES (Some of them are used only to reduce calls to '$ function' to improve javascript performance)
var shop = {};
shop.url = location.protocol +'//'+ location.host;
//NO MORE VARIABLES

$(window).addEvent('domready', function(){ initShop(); initPlugins(); } );

function initShop()
{
	initOverlay();
	initBuyForms();
	initLoginForms();
	if($('userInformationForm')) {initFormFields('userInformationForm');};
	if($('asyncBasketBox')) { initAsyncBasket(); };
	initAlert();
	initCheckout();
}

function initOverlay()
{
	shop.overlay = $('overlay');
	shop.overlay.show = function()
											{
												this.style.display = 'block';
												$(document.html).style.overflow = 'hidden';
												this.style.width = document.body.offsetWidth+'px';
												this.style.height = document.body.offsetHeight+'px';
											}
	
	shop.overlay.hide = function()
											{
												$(document.html).style.overflow = 'auto';
												this.style.display = 'none';
											}
	
	window.addEvent('scroll', function()
										{
												shop.overlay.style.top = 0 + document.documentElement.scrollTop + 'px';
												//shop.basketDiv.movement.start('top', parseInt(shop.basketDiv.style.top), 180 + document.documentElement.scrollTop );
										}
	);
}


function initLoginForms()
{
	$(window).addEvent('domready',function()
{
 if($('userControlPanelLoginForm')){
 																		initFormFields("userControlPanelLoginForm");
																		$('userControlPanelLoginForm').addEvent('submit', function()
																																		 {
																																			//overwrite form action
																																			this.action = shop.url + '/ajaxTemplates/checkoutActions.cfm?action=login';
																																			//autoDragImage(this);
																																			if( Spry.Widget.Form.validate(this) )
																																				{
																																				shop.overlay.show();
																																				return Spry.Utils.submitForm(this, validateLogin);
																																				}
																																		 }
																										 );
 																		}
});
	
}

function initBuyForms()
{
	$$('.buyForm').each(
											function(form)
											{
												getStockByCombination(form);
												form.addEvent('submit', function()
																												{
																													//overwrite form action
																													//this.action = shop.url + '/ecommerce/basket/asyncBasket.cfm';
																													this.action = shop.url + '/ajaxTemplates/addProduct.cfm';
																													//autoDragImage(this);
																													
																													if( Spry.Widget.Form.validate(this) )
																													{
																														//shop.overlay.show();
																														//return Spry.Utils.submitForm(this, reloadMiniBaskets );
																														return Spry.Utils.submitForm(this, validateAddProduct);
																													}
																												}
												);
											}
	);
}



function initAlert()//init vertical movement, transition... of the minibasket
{
	shop.alertDiv = $('alertFloater');
	//shop.basketDiv.movement = new Fx.Tween( shop.basketDiv , 'top', {duration:20, transition:new Fx.Transition(Fx.Transitions.linear) } );
	shop.alertDiv.style.top = '180px';
	
	window.addEvent('scroll', function()
										{
												shop.alertDiv.style.top = 180 + document.documentElement.scrollTop + 'px';
												//shop.basketDiv.movement.start('top', parseInt(shop.basketDiv.style.top), 180 + document.documentElement.scrollTop );
										}
	);
	
	shop.alertBox = $('alertBox');
	shop.alertBox.transition = new Fx.Tween( shop.alertBox , 'opacity', {duration:700, wait:true , transition:new Fx.Transition(Fx.Transitions.linear) } );
	
	shop.cuteAlert = new cuteAlert();
}



function validateAddProduct(req)
{
	var objResponse = eval('('+req.xhRequest.responseText+')');
	
	if(objResponse.ADDED)//product added
	{
		$('loadingImage'+ objResponse.PRODUCTID).destroy();
	  $('addProduct'+objResponse.PRODUCTID).style.display = '';
		ajaxLoad(shop.url+'/ajaxTemplates/asyncBasket.cfm', $('asyncBasketBox') );
		ajaxLoad(shop.url+ '/ajaxTemplates/basket.cfm', $('minibasket'), '' ,'');

	}
	else
	{
		shop.cuteAlert.addMessage(languageSheet.lblError, languageSheet.lblProductNotAdded, 0, 0);
	}
	
}

//checkout initialization
var initCheckout = function()
{
	var titleDivs = $$('.checkoutTitle');
	shop.checkoutAccordion = new Accordion( titleDivs , $$('.checkoutContent'), {opacity:false, hideAll:true, show:100 , onActive:function(){ return; } } );
	titleDivs.each(
								 	function(el){ el.removeEvents('click'); el.addEvent('click', function(el){ var ev = new Event(el); ev.stop(); return false; } ); }
								 );
}

function autoDragImage(form)
{
	var images = form.getElements('img.mainProductImage');
	if(!images.length) return;
	
	var image = images[0]; //get the 1st image from the product
	
	var imageClone = image.clone(false, false);
	
	imageClone.style.position = 'absolute';
		
	imageClone.setStyles(image.getCoordinates());
	document.body.appendChild(imageClone);
	
	imageClone.transition = new Fx.Tween( imageClone , 'top', {duration:'long', fps:10, transition:new Fx.Transition(Fx.Transitions.Sine.easeInOut) } );
	imageClone.transition2 = new Fx.Tween( imageClone , 'left', {duration:'long', fps:10, transition:new Fx.Transition(Fx.Transitions.Sine.easeInOut) } );
	
	imageClone.transition.start('top', parseInt(image.getCoordinates().top) , parseInt($('basketContentModuleC').getCoordinates().top) );
	imageClone.transition2.start('left', parseInt(image.getCoordinates().left) , parseInt($('basketContentModuleC').getCoordinates().left) );
	
}

/**CHECKOUT FUNCTIONS************************/
function checkoutOptionSelected(field)
{
	
	field = $(field);
	if(parseInt(field.value) && field.value.length){
		return true;}
	else{
		return false;}
}


function validateAccount(req) //gets the response of the customer form and sends an error message or calls next screen.
{
	var objResponse = eval('(' + req.xhRequest.responseText + ')');
	
	if( objResponse.ERROR )
		{
			switch (objResponse.ERROR)
			{
				case 'TLG1000':
				case 'TLG1001':
					shop.cuteAlert.addMessage(languageSheet.lblError, languageSheet.lblUserNotFound,0,0);
					break;
				case 'TLG1002':
					shop.cuteAlert.addMessage(languageSheet.lblError, languageSheet.lblDifferentPassword,0,0);
					break;
				case 'TLG1003':
					shop.cuteAlert.addMessage(languageSheet.lblError, languageSheet.lblEmailInUse,0,0);
					break;
				case 'TLG1004':
					shop.cuteAlert.addMessage(languageSheet.lblError, languageSheet.lblDifferentEmail,0,0);
					break;
			}
		}
	else
		{
			if( objResponse.ACTION == 'login' )
			{
				location.reload();	
				//loadNextCheckoutScreen(1, shop.url+'/ajaxTemplates/shippingZone.cfm' , $('shippingMethodBox') );
			}
			else if( objResponse.ACTION == 'signIn' )
			{
				window.location.href = shop.url + '/ecommerce/checkout/checkout.cfm?action=signIn';
				/*$('loadingImage').destroy();
				if($('submitUserCheckoutForm'))$('submitUserCheckoutForm').style.display = '';
				loadNextCheckoutScreen(1, shop.url+'/ajaxTemplates/shippingZone.cfm' , $('shippingMethodBox') );*/
			}
			else
			{
				//$('loadingImage').destroy();
				//if($('submitUserCheckoutForm'))$('submitUserCheckoutForm').style.display = '';
				//loadNextCheckoutScreen(3, shop.url+'/ajaxTemplates/orderConfirm.cfm' , $('orderConfirmationBox') );
				loadNextCheckoutScreen(3, shop.url+'/ajaxTemplates/orderConfirm.cfm' , $('checkoutDiv'), "if($('userLogin'))$('userLogin').style.display = 'none';" );
			}
		}
}

function loadNextCheckoutScreen(step, path, targetDiv, callBack ){
	
	ajaxLoad(path, targetDiv, "ajaxLoad('"+shop.url+"/ajaxTemplates/steps.cfm?step="+step+"', $('stepsCheckout'));"+callBack);
}


function validateAccountNewUser(req) //gets the response of the customer form and sends an error message or calls next screen.
{
	
	var objResponse = eval('(' + req.xhRequest.responseText + ')');
	
	if( objResponse.ERROR )
		{
			switch (objResponse.ERROR)
			{
				case 'TLG1000':
				case 'TLG1001':
					shop.cuteAlert.addMessage(languageSheet.lblError, languageSheet.lblUserNotFound,0,0);
					break;
				case 'TLG1002':
					shop.cuteAlert.addMessage(languageSheet.lblError, languageSheet.lblDifferentPassword,0,0);
					break;
				case 'TLG1003':
					shop.cuteAlert.addMessage(languageSheet.lblError, languageSheet.lblEmailInUse,0,0);
					break;
				case 'TLG1004':
					shop.cuteAlert.addMessage(languageSheet.lblError, languageSheet.lblDifferentEmail,0,0);
					break;
			}
		}
	else{
//			loadNextCheckoutScreen(1, shop.url+'/users/userControlPanel.cfm' , $('shippingMethodBox') );
//			window.location = shop.url+'/ecommerce/users/userControlPanel.cfm';  
			window.location = shop.url+'/ecommerce/users/welcome.cfm';  //redirect to a welcome page when user registers (if not in checkout)
		}
}



function validateLogin(req) //gets the response of the small Login form and sends an error message or calls next screen.
{
	var objResponse = eval('(' + req.xhRequest.responseText + ')');

	
	if( objResponse.ERROR )
		{
			switch (objResponse.ERROR)
			{
				case 'TLG1000':
				case 'TLG1001':
					shop.cuteAlert.addMessage(languageSheet.lblError, languageSheet.lblUserNotFound,0,0);
					break;
				case 'TLG1002':
					shop.cuteAlert.addMessage(languageSheet.lblError, languageSheet.lblDifferentPassword,0,0);
					break;
				case 'TLG1003':
					shop.cuteAlert.addMessage(languageSheet.lblError, languageSheet.lblEmailInUse,0,0);
					break;
				case 'TLG1004':
					shop.cuteAlert.addMessage(languageSheet.lblError, languageSheet.lblDifferentEmail,0,0);
					break;
			}
		}
	else
		{
			if( objResponse.ACTION == 'login' )
			{
				location.reload();
				//location.href = shop.url+'/ecommerce/users/userControlPanel.cfm';	
			}			
		}
}




function requireShipTo(value)
{
	document.getElementById('firstNameShippingField').setAttribute('requiredField', value);
	document.getElementById('lastName1ShippingField').setAttribute('requiredField', value);
	document.getElementById('lastName2ShippingField').setAttribute('requiredField', value);
	document.getElementById('addressShippingField').setAttribute('requiredField', value);
	document.getElementById('cityShippingField').setAttribute('requiredField', value);
	document.getElementById('zipShippingField').setAttribute('requiredField', value);
	
	
	if(value == 1){
		$('userShipping').style.display = '';
		
		if($('countryTD')){
			//$('countryTD').style.display = 'none';
			$('country').style.display = 'none';
			$('subCountries').style.display = 'none';
			$('countryNoShipTo').style.display = '';
		}
	}
	else{
		$('userShipping').style.display = 'none';
		
		if($('countryTD')){
			//$('countryTD').style.display = '';
			$('country').style.display = '';
			$('subCountries').style.display = '';
			$('countryNoShipTo').style.display = 'none';
		}
	}
	if($('userInformationForm'))initFormFields('userInformationForm');
}

/****************************************/
function initFormFields(form)
{
//	var form = document.getElementById(form);
//	if(form == null) return;
	
	if(typeof form == "string")var form = document.getElementById(form);
	
	Spry.Widget.Form.destroy(form);

	for (var i = 0; i < form.elements.length; i++ )
	{
			element = form.elements[i];
			
			fieldType = element.getAttribute('fieldType');
			requiredField = element.getAttribute('requiredField');
			
			if( element.getAttribute('affectsstock') == 1 )
			{
				if($(element).type == "select-one")
					$(element).addEvent('change', function(){ getStockByCombination(form); } );
				else if($(element).type == "radio")
					$(element).addEvent('click', function(){ getStockByCombination(form); } );
			}
			
			if(fieldType)
			{
				try
				{
					if(requiredField == 1)
						required = true;
					else
						required = false;
				}
				catch(err){ required = false }
				
				switch(fieldType)
				{
					case 'natural':
						
						element.validate = new Spry.Widget.ValidationTextField(element, "integer", { isRequired:required, validateOn:['blur'], minValue:0 } );
						break;
						
					case 'integer':
						
						element.validate = new Spry.Widget.ValidationTextField(element, "integer", { isRequired:required, validateOn:['blur'] } );
						break;
					
					case 'float':	
					
						element.validate = new Spry.Widget.ValidationTextField(element, "real", { isRequired:required,validateOn:['blur'] } );
						break;
					
					case 'email':	
					
						element.validate = new Spry.Widget.ValidationTextField(element, "email", { isRequired:required,validateOn:["blur"] });
						break;
					
					case 'time':	
					
						element.validate = new Spry.Widget.ValidationTextField(element, "time", { isRequired:required, validateOn:['blur'] , useCharacterMasking:true , format:formats.timeFormat } );
						break;
					
					case 'date':	
					
						element.validate = new Spry.Widget.ValidationTextField(element, "date", { isRequired:required, useCharacterMasking:true, format:formats.dateFormat, hint:formats.dateFormat, validateOn:["blur"]} );
						
						Calendar.setup({inputField:element, button:element});
						
						break;
						
					case 'phone':	
					
						//element.validate = new Spry.Widget.ValidationTextField(element, "phone_number", { isRequired:required, validateOn:["blur"],format:"phone_custom" , pattern:"000000000"});
						element.validate = new Spry.Widget.ValidationTextField(element, "integer", { isRequired:required, validateOn:["blur"], allowNegative:false, minValue:10000000 });
						break;
					
					case 'url':	
					
						element.validate = new Spry.Widget.ValidationTextField(element, "url", { isRequired:required, validateOn:["blur"]});
						break;
					
					case 'creditcard':
					
						element.validate = new Spry.Widget.ValidationTextField(element, "zip_code", { isRequired:required, useCharacterMasking:true, pattern:'0000-0000-0000-0000' , validateOn:['blur'] } );
						break;
					
					case 'ip':	
					
						element.validate = new Spry.Widget.ValidationTextField(element, "ip", { isRequired:required, validateOn:['blur'] } );
						break;
						
					case 'shortmemo':	
					
						element.validate = new Spry.Widget.ValidationTextarea(element, { isRequired:required, validateOn:['blur'] } );
						break;
						
					case 'checkbox':
      
						var container = element.getAttribute('fieldContainerId')
						if( container )
						 container = $(container);
						else
						 container = $(element);
						
						new Spry.Widget.ValidationCheckbox(container,{isRequired:required});
						break;
					
					case 'checkbox_group':
      
						var container = element.getAttribute('fieldContainerId')

						var minSelections = element.getAttribute('minSelections')
						if( container )
						 container = $(container);
						else
						 container = $(element);
						
						new Spry.Widget.ValidationCheckbox(container,{isRequired:required, minSelections:minSelections});
						break;
						
					case 'radio':
      
						var container = element.getAttribute('fieldContainerId')
						if( container )
						 container = $(container);
						else
						 container = $(element);
						 
 						new Spry.Widget.ValidationRadio(container,{isRequired:required, validateOn:["blur", "change"]});
						break;
					/*case 'longmemo':	
					
						element.validate = new Spry.Widget.ValidationTextarea(element, { isRequired:required, validateOn:['blur'] } );
						break;*/
						
					default:
					
						element.validate = new Spry.Widget.ValidationTextField(element, "none", { isRequired:required, validateOn:['blur'] } );
						break;
					
				}
			}
			
	}
}


function cuteAlert(){
	
	this.timeOut = null;
	this.showing = false;
	this.messageQueue = new Array();
	this.addMessage = function(title, content, image, timeout)
								{
									this.messageQueue.push( {title:title, content:content, image:image, timeout:timeout} );
									if(!this.showing)
										this.showMessage();
								}
	this.showMessage = function()
								{
									if(this.messageQueue.length)
									{
										shop.overlay.show();
										this.showing = true;
										var message = this.messageQueue.shift();
										document.getElementById('alertTitle').innerHTML = message.title;
										document.getElementById('alertMessage').innerHTML = message.content;
										shop.alertBox.transition.start('opacity',0,1);
										
										if(message.timeout && message.timeout > 0)
										{
											var self = this;
											this.timeOut = setTimeout(function(){ self.closeMessage()}, message.timeout);
										}
										
									}
									else
									{
										this.showing = false;
									}
								}
	this.clear = function()
								{
									this.messageQueue = new Array();
									clearTimeout(this.timeOut);
								}
	this.closeMessage = function()
								{
									clearTimeout(this.timeOut);
									shop.alertBox.transition.start('opacity',1,0);
									var self = this;
									setTimeout(function(){self.showMessage();},700);
									shop.overlay.hide();
								}
};

/*CATEGORY FUNCTIONS*************************************/
function toggleSubcategories(parentId)
{
	var targetElement = document.getElementById('subcategories' + parentId);
	var togglerElement = document.getElementById('categoryToggler' + parentId);
	var mainTargetElement = document.getElementById('subcategoriesViewer');
	
	/*if(targetElement.style.display == 'none')//open subcategories
	{
		targetElement.style.display = '';
		togglerElement.className = 'categoryTogglerOpen'; mainTargetElement.slide.slideIn();
	}
	
	else */if(targetElement.innerHTML.length < 41)//load subcategories
	{
		targetElement.slide = new Fx.Slide( targetElement, {duration: 500, wait:false} );
		ajaxLoadSync(shop.url + '/ajaxTemplates/categories.cfm?parentId='+parentId+'&deepLevel=1&level=2', targetElement);
		togglerElement.className = 'categoryTogglerOpen'; targetElement.slide.slideIn();
		setTimeout(function(){ mainTargetElement.slide.slideIn(); }, 500);
	}
	else //close subcategories
	{
		targetElement.slide = new Fx.Slide( targetElement, {duration: 500, wait:false} );
		togglerElement.className = 'categoryTogglerClosed'; targetElement.slide.slideOut();
		setTimeout(function(){targetElement.innerHTML = '';}, 500);
	}
}
function showSubcategories(parentId)
{
	var targetElement = document.getElementById('subcategoriesViewer');
	//var togglerElement = document.getElementById('categoryToggler' + parentId);
	targetElement.slide = new Fx.Slide( targetElement, {duration: 500, wait:false} );
	
	targetElement.slide.slideOut();
	
	setTimeout(function(){ ajaxLoadSync(shop.url + '/ajaxTemplates/categories.cfm?parentId='+parentId+'&deepLevel=1', targetElement); targetElement.slide.slideIn(); } , 400 );
	/*
	if(targetElement.innerHTML.length < 15) //if no content
		return true; //follow links
	//togglerElement.className = 'categoryTogglerOpen';
	*/

	return false; //avoid href link
}

function getSubCountries(divId, countryId, subCountryId)
{
		if(subCountryId != '')
		{
			ajaxLoadSync(shop.url + '/ajaxTemplates/subCountries.cfm?countryId='+countryId+'&subCountryId='+subCountryId , $(divId) );
			shop.checkoutAccordion.display(100);
			shop.checkoutAccordion.display(1);
		}
}

function loadAjaxFile(nameFile, nameDiv, callBack, ajaxLoading) {
	if(ajaxLoading.length == 0)
		ajaxLoading = "<img src='" + shop.url + "/ecommerce/images/icons/loading.gif'>";
	var div_pointer = $(nameDiv);
	ajaxLoad(nameFile,div_pointer,callBack, ajaxLoading);
}

function closeContent(){
	$('informationBox').innerHTML = '';
	$('informationBox').style.visibility = 'hidden';
}

function loadContent(nameFile, nameDiv, callBack, ajaxLoading) {
	if(ajaxLoading.length == 0)
		ajaxLoading = "<img src='" + shop.url + "/ecommerce/images/icons/loading.gif'>";
	if($(nameDiv+'Floater'))$(nameDiv+'Floater').style.top = 30+ (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + 'px';
	loadAjaxFile(nameFile, nameDiv, callBack, ajaxLoading);
}

function submitForm(form, divId, callBack){
	Spry.Utils.submitForm(form, function(req){document.getElementById(divId).innerHTML = req.xhRequest.responseText; eval(callBack);} );
}

function showShadowboxCheckout(divId)
{
	Shadowbox.open({
        player:     'html',
        content:    $(divId).innerHTML,				
        width:      600,
				height: 		400
    },
		{
			animate: false
		}
		);

}

function restartShadowbox(){
	Shadowbox.setup(); 
}


function showArrowOption(objId){
	var obj = $(objId);
	
	$$('.productDetailOptionsImageArrow').each(
		function(el)
		{
			el.removeClass("productDetailOptionsImageArrow");
			el.removeClass("enabledOptions");
			el.addClass("productDetailOptionsImage");
			el.addClass("disabledOptions");
		}
	);
	
	$$('.productDetailOptionsImage').each(
		function(el)
		{
			el.removeClass("enabledOptions");
			el.addClass("disabledOptions");
		}
	);

	obj.removeClass("productDetailOptionsImage");
	obj.removeClass("disabledOptions");
	obj.addClass("enabledOptions");
	obj.addClass("productDetailOptionsImageArrow");
}

function selectOption(optionId, optionValueId){
		$('optionValue'+optionId).value = optionValueId;
		if($('optionValue'+optionId).getAttribute('affectsstock') && $('optionValue'+optionId).getAttribute('affectsstock') == 1){
			getStockByCombination($('prodDetailBuyForm'))
		}

}




function showArrowOptionGroup(objId){
	var obj = $(objId);
	
	if(obj.hasClass("productDetailOptionsGroupImage")){
		obj.removeClass("productDetailOptionsGroupImage");
		obj.addClass("productDetailOptionsGroupImageArrow");
	}
	else{
		obj.removeClass("productDetailOptionsGroupImageArrow");
		obj.addClass("productDetailOptionsGroupImage");
	}
	
}

function selectOptionGroup(id){
	if($('optionValue'+id).value == id)
		$('optionValue'+id).value = "";
	else
		$('optionValue'+id).value = id;
}

var basketTime;
var basketDisplay;

function initAsyncBasket()//init vertical movement, transition... of the minibasket
{
	/*shop.asyncBasketBox = $('asyncBasketBox');
	shop.asyncBasketBox.transition = new Fx.Tween( shop.asyncBasketBox , 'opacity', {duration:700, transition:new Fx.Transition(Fx.Transitions.linear) } );
	basketDisplay = "none";*/
	$('asyncBasketBox').style.display = 'none';
}

function showMiniBasket(){
	/*if(basketDisplay == "none"){
		basketDisplay = "";
		shop.asyncBasketBox.transition.start('opacity',0,100);*/
		$('asyncBasketBox').style.display = '';
	/*}*/
}

function hideMiniBasket() // hideMinibasket 
{
	/*if(basketDisplay == ""){
		basketDisplay = "none";
		shop.asyncBasketBox.transition.start('opacity',1,0);*/
		$('asyncBasketBox').style.display = 'none';
	/*}*/
}


function getStockByCombination(form)
{
	var element;
	var formParams = new Array();
	
	for (var i = 0; i < form.elements.length; i++ )
	{
		element = form.elements[i];
		if( element.getAttribute('affectsstock') && element.getAttribute('affectsstock') == 1)
		{
			formParams.push(encodeURIComponent(element.name) + '=' + encodeURIComponent(element.value));
		}
		else if(element.name.toUpperCase() == 'PRODUCTID')
		{
			formParams.push(encodeURIComponent(element.name) + '=' + encodeURIComponent(element.value));
			el = document.getElementById('addProduct'+element.value );
			el.style.display = 'none';
			var loadingImage = document.createElement('img');
			loadingImage.src = shop.url + '/ecommerce/images/icons/smallLoading.gif';
			loadingImage.id = 'loadingImage' + element.value;
			el.parentNode.appendChild(loadingImage);
		}
	}
	formParams = formParams.join("&");
	
	var frmOpts = {};
	frmOpts.method = 'POST';
	frmOpts.url = shop.url + '/ajaxTemplates/checkStockByCombination.cfm';
	frmOpts.headers = {};
	frmOpts.headers['Content-Type'] = 'application/x-www-form-urlencoded';
	frmOpts.postData = formParams;
	
	Spry.Utils.loadURL('post', frmOpts.url, true, setStockByCombination, frmOpts);
}

function setStockByCombination(response)
{
	var objResponse = eval('(' + response.xhRequest.responseText + ')');
	var productId = parseInt(objResponse.PRODUCTID);
	var buyButton = document.getElementById('addProduct'+productId );
	var stock = parseInt(objResponse.STOCK);
	
	if( stock == 0 )
	{
		//no stock
		if(objResponse.ALLOWRESERVE)
		{
			//allow reserve
			if(buyButton.className != "prodDetailBuyButton")
				buyButton.value = languageSheet.lblReserve;
			buyButton.disabled = false;
		}
		else
		{
			//disallow buy
			if(buyButton.className != "prodDetailBuyButton")
				buyButton.value = languageSheet.lblInexistentCombination;
			buyButton.disabled = true;
		}
	}
	else if( stock == -1 )
	{
		//disallow buy
		if(buyButton.className != "prodDetailBuyButton")
			buyButton.value = languageSheet.lblInexistentCombination;
		buyButton.disabled = true;
	}
	else
	{
		//stock available	
		if(buyButton.className != "prodDetailBuyButton")
			buyButton.value = languageSheet.lblBuy;
		buyButton.disabled = false;
	}
	
	$('loadingImage' + productId).destroy();
	buyButton.style.display = '';
}

function showPriceByOption(form){
	var productId = form.productId.value;
	var listOptions = "";
	if(form.options && form.options.length){
		for(var i=0; i<form.options.length; i++){
			optionId = form.options[i].value;
			if($('optionValue'+optionId).type == 'radio') {
				if(listOptions.length > 0) listOptions = listOptions + ",";
				radioValue = getRadioButtonSelectedValue(document.getElementsByName('optionValue'+optionId));
				listOptions = listOptions + radioValue;
			}
			else if($('optionValue'+optionId).type == 'select') {
				if(listOptions.length > 0) listOptions = listOptions + ",";
				listOptions = listOptions + $('optionValue'+optionId)[selectedIndex].value;
			}else{
				if($('optionValue'+optionId).type != 'text' && $('optionValue'+optionId).type !='textarea')
				{
					if(listOptions.length > 0) listOptions = listOptions + ",";
					listOptions = listOptions + $('optionValue'+optionId).value;				
					objOption = $('optionValue'+optionId);
					if(document.getElementById('optionImagePreview'+optionId)) { 
						prevImage = objOption[objOption.selectedIndex].getAttribute('smallImage');
						if (prevImage.length)	changePreviewImage(prevImage,optionId);
					}
				}
			} 
		}
	}
	else if(form.options){
		optionId = form.options.value;
		if($('optionValue'+optionId).type == 'radio') {
			radioValue = getRadioButtonSelectedValue(document.getElementsByName('optionValue'+optionId));
			listOptions = radioValue;
		}
		else if($('optionValue'+optionId).type == 'select') {
			listOptions = $('optionValue'+optionId)[selectedIndex].value;
		}else{
			if($('optionValue'+optionId).type != 'text' && $('optionValue'+optionId).type !='textarea') {
				listOptions = $('optionValue'+optionId).value;
				objOption = $('optionValue'+optionId);
				if(document.getElementById('optionImagePreview'+optionId)) { 
					prevImage = objOption[objOption.selectedIndex].getAttribute('smallImage');
					if (prevImage.length)	changePreviewImage(prevImage,optionId);
				}
			}
		} 
	}
	if(listOptions.length > 0){
		var url = shop.url + '/ajaxTemplates/showPriceByOptions.cfm?productId='+productId+'&listOptions='+listOptions;
		var responseText = ajaxLoadSync(url);
		var objResponse = eval('(' + responseText + ')');
		if(document.getElementById('prodDetailIntPrice'))document.getElementById('prodDetailIntPrice').innerHTML = objResponse.BASEPRICE;
		if(document.getElementById('prodDetailIntRetailPrice'))document.getElementById('prodDetailIntRetailPrice').innerHTML = objResponse.RETAILPRICE;
		
		quantity = parseInt(form.quantity.value);
		if (isNaN(quantity) || quantity < 1) { quantity = 1; }
		form.quantity.value = quantity;
		basePrice = parseFloat(objResponse.BASEPRICE);
		if (isNaN(basePrice)){
			var basePrice_array=objResponse.BASEPRICE.split(" ");
			basePrice = Number(basePrice_array[0]);
		}
	  basePrice = basePrice * quantity;
		basePrice = Math.round(basePrice*100)/100 ;
		basePrice = basePrice + ' &euro;'
		if(document.getElementById('prodDetailPrice1'))document.getElementById('prodDetailPrice1').innerHTML = basePrice;
	}
}

function getRadioButtonSelectedValue(ctrl) {
	for(i=0;i<ctrl.length;i++)
		if(ctrl[i].checked) return ctrl[i].value;
}

function modifyQuantity(form, action){
	if (action == 'add'){
		quantity = parseInt(form.quantity.value)
		if (isNaN(quantity)) { quantity = 1; }
		quantity = quantity + 1;
		form.quantity.value = quantity;
	} else if (action == 'remove') {
		quantity = parseInt(form.quantity.value)
		if (isNaN(quantity)) { quantity = 1; }
		if (quantity != 1) { quantity = quantity - 1;	}
		form.quantity.value = quantity;
	}
	showPriceByOption(form);	
}

function changePreviewImage(prevImg,optionId) {
	document.getElementById('optionImagePreview'+optionId).src = prevImg;
}





