
$(window).addEvent('domready', function(){ initShop(); initPlugins(); } );

/*$(window).addEvent('scroll'), function(){
	if(! $('basketTotals')) return;
	scrollBasketTotals = $('basketTotals');
});*/

//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;
var basketTime;
//NO MORE VARIABLES

function initShop()
{
	initBuyForms();
	initAsyncBasket();
	initAlert();
	initQuestion();
	initCheckout();
	initLoginForms();
}

function initBuyForms()
{
	$$('.buyForm').each(
	function(form)
	{
		getStockByCombination(form);
		form.addEvent('submit', function()
			{
				//overwrite form action
				this.action = shop.url + '/ajaxTemplates/addProduct.cfm';
				if( Spry.Widget.Form.validate(this) )
				{
					return Spry.Utils.submitForm(this, validateAddProduct );
				}
			}
		);
	}
	);
}

function initLoginForms()
{
	$$('.loginForm').each(
											function(form)
											{
													initFormFields(form);
													form.addEvent('submit', function()
																													{
																														//overwrite form action
																														this.action = shop.url + '/ajaxTemplates/checkoutActions.cfm?action=login';
																														//autoDragImage(this);
																														if( Spry.Widget.Form.validate(this) )
																														return Spry.Utils.submitForm(this, validateLogin);
																													}
													);
											}
	);
}

function initAsyncBasket()//init vertical movement, transition... of the minibasket
{
	if($('asyncBasketBox')){
		shop.asyncBasketBox = $('asyncBasketBox');
		shop.asyncBasketBox.transition = new Fx.Tween( shop.asyncBasketBox , 'opacity', {duration:700,transition:new Fx.Transition(Fx.Transitions.linear)});
	}
}

function initAlert()//init vertical movement, transition... of the minibasket
{
		if($('alertFloater')){
	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 initQuestion(){
	if($('questionBox')){
		shop.questionBox = $('questionBox');
		shop.questionBox.transition = new Fx.Tween( shop.questionBox , 'opacity', {duration:700, wait:true , transition:new Fx.Transition(Fx.Transitions.linear) } );
	
		shop.cuteQuestion = new cuteQuestion();
	}
}

function hideAsyncBasket()
{
	clearTimeout(basketTime);
	shop.asyncBasketBox.transition.start('opacity',1,0);
}

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+'/ecommerce/basket/asyncBasket.cfm', $('asyncBasketBox'), 'showMiniBasket();' );
		ajaxLoad(shop.url+ '/ajaxTemplates/basket.cfm', $('minibasket'), '' ,'');
		//reload asyncBasket
		//$('asyncBasket').innerHTML;		
		//showMiniBasket();
		if( objResponse.PRODUCTID == 33 ){
				shop.cuteAlert.addMessage(languageSheet.lblProductAddedTitle, languageSheet.lblFreeCanAdded, 0, 0);
				location.reload();
		}else{
				shop.cuteAlert.addMessage(languageSheet.lblProductAddedTitle, languageSheet.lblProductAdded, 0, 0);
		}
		
	}
	else
	{
		shop.cuteAlert.addMessage(languageSheet.lblError, languageSheet.lblProductNotAdded, 0, 0);
	}
	
}

function validateGiftCode(req)
{
	var url = shop.url+'/ajaxTemplates/checkoutActions.cfm?action=giftCode';
	var useGiftCodeCheck = document.getElementById('useGiftCodeCheckbox');
	var giftCode = document.getElementById('giftCodeTextBox').value;
	var useGiftCode = 0;
	if(useGiftCodeCheck && useGiftCodeCheck.checked) useGiftCode = 1;
	
	url += '&useGiftCode='+useGiftCode;
	url += '&giftCode='+giftCode;
	
	var responseText = ajaxLoadSync(url);
	
	var objResponse = eval('(' + responseText + ')');
	
	if( objResponse.ERROR )
	{
		switch (objResponse.ERROR)
		{
			case 'TLG1201':
				shop.cuteAlert.addMessage(languageSheet.lblError, languageSheet.lblCodeNotFound,0,0);
				break;
			case 'TLG1202':
				shop.cuteAlert.addMessage(languageSheet.lblError, languageSheet.lblErrorReadingCodes,0,0);
				break;
			case 'TLG1203':
				shop.cuteAlert.addMessage(languageSheet.lblError, languageSheet.lblCodeInUse,0,0);
				break;
			case 'TLG1204':
				shop.cuteAlert.addMessage(languageSheet.lblError, languageSheet.lblCodeInOtherSession,0,0);
				break;
		}
	}
	else
	{
		ajaxLoad(shop.url+'/ajaxTemplates/giftCode.cfm', $('giftCodeBox') );
		if( $('totalBasket') )
			ajaxLoad(shop.url+'/ajaxTemplates/basket/totalsBasket.cfm', $('totalBasket') );
	}
}

function loadMiniBasket(){
	clearTimeout(basketTime);
	ajaxLoad(shop.url+'/ecommerce/basket/asyncBasket.cfm', $('asyncBasketBox'));
	//ajaxLoad(shop.url+'/ecommerce/basket/asyncBasket.cfm', $('asyncBasketBox'), 'showMiniBasket();' );
}

/*function showMiniBasket(){
	clearTimeout(basketTime);
	shop.asyncBasketBox.transition.start('opacity',0,100);
	shop.asyncBasketBox.style.display = '';*/
	/*setTimeout("shop.asyncBasketBox.transition.start('opacity',100,0);", 4000);
	setTimeout("shop.asyncBasketBox.style.display = 'none';", 4700);*/
	//basketTime = setTimeout("shop.asyncBasketBox.transition.start('opacity',1,0);", 4000);
	
/*}*/

//checkout initialization
var initCheckout = function()
{
	var titleDivs = $$('.checkoutTitle');
	shop.checkoutAccordion = new Accordion( titleDivs , $$('.checkoutContent'), {
																												 												opacity:false,
																																								hideAll:true,
																																								show:100,
																																								onActive:function(toggler, element){ toggler.setStyle('display',''); },
																																								onBackground:function(toggler, element){ toggler.setStyle('display','none'); }
																																								} );
	titleDivs.each(
								 	function(el){ el.removeEvents('click'); el.addEvent('click', function(el){ var ev = new Event(el); ev.stop(); return false; } ); }
								 );
}

/**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' , $('orderConfirmationBox'), "if($('checkoutUserLogin'))$('checkoutUserLogin').style.display = 'none';" );
			}
		}
}

/**FUNCTIONS MK ********************/

function validateMKAccountNewUser(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;
				default:
				
				break;
			}
		}
	else{
			window.location = shop.url+'/mk/registerComplete.cfm';
		}
}



function validateMKAccountModifyUser(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;
				default:
				
				break;
			}
		}
	else{
			window.location = shop.url+'/mk/registerComplete.cfm';
		}
}

function validateMKAccountUser(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;
				default:
				
				break;
			}
		}
	else{
			window.location = shop.url+'/mk/modify2.cfm';
		}
}


function validateMKAccountRegalo(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;
				default:
				
				break;
			}
		}
	else{
			window.location = shop.url+'/mk/regalo2.cfm';
		}
}

/************************************************/






function validateShippingMethod(req){
	$('loadingImage').destroy();
	if($('submitShippingMethodCheckoutForm'))$('submitShippingMethodCheckoutForm').style.display = '';

	loadNextCheckoutScreen(2, shop.url + '/ajaxTemplates/paymentMethod.cfm' , $('paymentMethodBox') );
}

function validatePaymentMethod(rq){
	$('loadingImage').destroy();
	if($('submitPaymentMethodCheckoutForm'))$('submitPaymentMethodCheckoutForm').style.display = '';

	loadNextCheckoutScreen(3,  shop.url + '/ajaxTemplates/orderConfirm.cfm' , $('orderConfirmationBox') );
}

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';
		}
}

function loadNextCheckoutScreen(index, path, targetDiv, callBack )
{
	
	//if(index>1)ajaxLoad(shop.url+'/ajaxTemplates/checkoutBasket.cfm', $('checkoutBasketDiv') );
	ajaxLoad(path, targetDiv, 'shop.checkoutAccordion.display('+index+');'+callBack);
	if(callBack)
		eval(callBack);

}

function requireSignIn(value)
{
	//if(document.getElementById('userSignInNick'))document.getElementById('userSignInNick').setAttribute('requiredField', value);
	document.getElementById('userSignInPassword').setAttribute('requiredField', value);
	document.getElementById('confirmPassword').setAttribute('requiredField', value);

	if(value == 0){
		document.getElementById('subscribeTable').style.display = 'none';
		document.getElementById('userSignInPasswordTable').style.display = 'none'; 
		document.getElementById('confirmPasswordTable').style.display = 'none';
		document.getElementById('userInformationTable').style.display = ''; 
		shop.checkoutAccordion.display(0);
		//document.getElementById('legalConditionsTable').style.display = 'none';
	}
	if(value == 1){
		document.getElementById('subscribeTable').style.display = '';
		document.getElementById('userSignInPasswordTable').style.display = ''; 
		document.getElementById('confirmPasswordTable').style.display = '';
		document.getElementById('userInformationTable').style.display = ''; 
		shop.checkoutAccordion.display(0);
		//document.getElementById('legalConditionsTable').style.display = '';
	}
	if($('checkoutUserForm'))initFormFields('checkoutUserForm');
	if($('userInformation'))initFormFields('userInformation');
}

function requireShipTo(value)
{
	document.getElementById('firstNameShippingField').setAttribute('requiredField', value);
	document.getElementById('lastNameShippingField').setAttribute('requiredField', value);
	document.getElementById('addressShippingField').setAttribute('requiredField', value);
	document.getElementById('cityShippingField').setAttribute('requiredField', value);
	document.getElementById('zipShippingField').setAttribute('requiredField', value);
	
	
	if(value == 1){
		if($('countryTD')){
			$('countryTD').style.display = 'none';
			$('country').style.display = 'none';
			$('countryNoShipTo').style.display = '';
			$('countryShipTo').style.display = '';
		}
	}
	else{
		if($('countryTD')){
			$('countryTD').style.display = '';
			$('country').style.display = '';
			$('countryNoShipTo').style.display = 'none';
			$('countryShipTo').style.display = 'none';
		}
	}
	if($('checkoutUserForm'))initFormFields('checkoutUserForm');
	if($('userInformation'))initFormFields('userInformation');
	//if($('userInformation'))initFormFields('userInformation');
}

/****************************************/
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') )
		{
			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
			//buyButton.value = languageSheet.lblReserve;
			buyButton.className = 'prodDetailBuyButton3';
			buyButton.disabled = false;
		}
		else
		{
			//disallow buy
			//buyButton.value = languageSheet.lblInexistentCombination;
			buyButton.className = 'prodDetailBuyButton2';
			buyButton.disabled = true;
		}
	}
	else if( stock == -1 )
	{
		//disallow buy
		//buyButton.value = languageSheet.lblInexistentCombination;
		buyButton.className = 'prodDetailBuyButton2';
		buyButton.disabled = true;
	}
	else
	{
		//stock available	
		//buyButton.value = languageSheet.lblBuy;
		if(productId==33){	
			buyButton.className = 'prodDetailBuyButton1';
		}else{ 
			buyButton.className = 'prodDetailBuyButton';
		}
		buyButton.disabled = false;
	}
	
	$('loadingImage' + productId).destroy();
	buyButton.style.display = '';
}

function initFormFields(form)
{
	var form = document.getElementById(form);
	if(form == null) return;
	
	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 )
			{
				$(element).addEvent('change', function(){ getStockByCombination(form); } );
			}*/
			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)
									{
										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);*/
										
										Shadowbox.open({
											player:     'html',
											content:    $('alertBox').innerHTML,
											title: 			message.title,
											width:      350,
											height: 		60
										},
										{
											animate: false,
											onClose: shop.cuteAlert.closeMessage()
										}
										);
										
										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);
								}
};

/*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, index)
{
		if(subCountryId != '')
		{
			ajaxLoadSync(shop.url + '/ajaxTemplates/subCountries.cfm?countryId='+countryId+'&subCountryId='+subCountryId+'&index='+index , $(divId) );
			shop.checkoutAccordion.display(100);
			shop.checkoutAccordion.display(1);
		}
}

function getCountriesInBasket(divId, countryId, subCountryId, level)
{
		if(countryId.length > 0)
		{
			var imageLoading = "<img src='" + shop.url + "/ecommerce/images/icons/smallLoading.gif'>"
			ajaxLoad(shop.url + '/ecommerce/basket/subCountries.cfm?countryId='+countryId+'&subCountryId='+subCountryId+'&level='+level+'&addToSession=1', $(divId), null, imageLoading);
			
		}
		else{
			selectCountryShippingMethod(0);
			$(divId).innerHTML = "";
			if($('shippingMethodDiv'))$('shippingMethodDiv').innerHTML = "";
			reloadBasket();
		}
}

function getCountriesInUserControlPanel(divId, countryId, subCountryId, level, extensName)
{
		if(countryId.length > 0)
		{
			var imageLoading = "<img src='" + shop.url + "/ecommerce/images/icons/smallLoading.gif'>"
			ajaxLoad(shop.url + '/ecommerce/users/userInformation/subCountries.cfm?countryId='+countryId+'&subCountryId='+subCountryId+'&level='+level+'&addToSession=0&extensName='+extensName, $(divId), null, imageLoading);
		}
		else{
			selectCountryShippingMethod(0);
			$(divId).innerHTML = "";
		}
}

function getSubCountriesInBasket(divId, countryId, subCountryId, level)
{
		if(checkSessionCountries() == false){window.location.href = shop.url + '/ecommerce/basket/basket.cfm'; return;}
		if(subCountryId.length > 0)
		{
			var imageLoading = "<img src='" + shop.url + "/ecommerce/images/icons/smallLoading.gif'>"
			var result = checkShippingMethod(countryId, subCountryId, level);
			if(result == false){ //more shipping countries
				ajaxLoad(shop.url + '/ecommerce/basket/subCountries.cfm?countryId='+countryId+'&subCountryId='+subCountryId+'&level='+level+'&addToSession=1' , $(divId), 'sameHeightBasket()', imageLoading);
				ajaxLoad(shop.url + '/ajaxTemplates/basket/checkoutScreen/shippingMethod.cfm?countryId='+countryId+'&subCountryId='+subCountryId+'&level='+level+'&addToSession=1' , $('shippingMethodDiv'), 'reloadBasket()', imageLoading);
				if($('shippingMethodDiv'))$('shippingMethodDiv').innerHTML = "";
			}
			else{ //show shipping method
				ajaxLoad(shop.url + '/ecommerce/basket/subCountries.cfm?countryId='+countryId+'&subCountryId='+subCountryId+'&level='+level+'&addToSession=1' ,  $(divId),  'reloadBasket()', imageLoading);
				ajaxLoad(shop.url + '/ajaxTemplates/basket/checkoutScreen/hippingMethod.cfm?countryId='+countryId+'&subCountryId='+subCountryId+'&level='+level+'&addToSession=1' , $('shippingMethodDiv'), 'reloadBasket()', imageLoading);
			}
		}
		else{
			$(divId).innerHTML = "";
			if($('shippingMethodDiv'))$('shippingMethodDiv').innerHTML = "";
			selectCountryShippingMethod(0);
			reloadBasket();
		}
}

function getSubCountriesInUserControlPanel(divId, countryId, subCountryId, level, extensName)
{
		if(subCountryId.length > 0)
		{
			var imageLoading = "<img src='" + shop.url + "/ecommerce/images/icons/smallLoading.gif'>"
			var result = checkShippingMethod(countryId, subCountryId, level);
			if(result == false){ //more shipping countries
				ajaxLoad(shop.url + '/ecommerce/users/userInformation/subCountries.cfm?countryId='+countryId+'&subCountryId='+subCountryId+'&level='+level+'&addToSession=0&extensName='+extensName , $(divId), null, imageLoading);
			}
		}
		else{
			$(divId).innerHTML = "";
		}
}

function checkSessionCountries(){
	var xmlObj = createXMLRequest();
	
	xmlObj.open('GET', shop.url + '/ecommerce/basket/checkSessionCountries.cfm?noCache='+getUniqueId(), false);
	xmlObj.send(null);
	if(xmlObj.responseText.indexOf('0') != -1)return false;
	return true;
}

function checkShippingMethod(countryId, subCountryId, level){
	var xmlObj = createXMLRequest();
	
	xmlObj.open('GET', shop.url + '/ecommerce/basket/checkShippingMethod.cfm?countryId='+countryId+'&subCountryId='+subCountryId+'&level='+level+'&noCache='+getUniqueId(), false);
	xmlObj.send(null);
	if(xmlObj.responseText.indexOf('0') == 0)return true;
	return false;
}

/*----------------------------------------------------------------------------------------------------*/

/*GLOBAL FUNCTIONS*/
function restartShadowbox(){
	Shadowbox.clearCache(); Shadowbox.setup(); 
}

function showShadowboxPage(urlPage)
{
	Shadowbox.open({
        player:     'ajax',
        content:    urlPage,
        width:      600,
				height: 		400
    },
		{
			animate: false
		}
		);

}


function changeClass(obj, nameClass, nameClass2){
	if(obj.className == nameClass) obj.className = nameClass2;
	else obj.className = nameClass;
}

/*END GLOBAL FUNCTIONS*/

/*SELECT ONLY BUY IN CHECKOUT FORM*/
function checkLogin(obj){
	shop.checkoutAccordion.display(100);
	if(obj.checked == true)setTimeout('requireSignIn(0)', 600);
	else setTimeout('requireSignIn(1)', 600);
}
/*END SELECT ONLY BY IN CHECKOUT FORM*/

/*AJAX FUNCTIONS */
function loadAjaxFile(nameFile, nameDiv, callBack, ajaxLoading) {
	var div_pointer = $(nameDiv);
	ajaxLoad(nameFile,div_pointer,callBack, ajaxLoading);
}

function loadContent(nameFile, nameDiv, callBack, ajaxLoading) {
	if(ajaxLoading != "")
		ajaxLoading = "<img src='" + shop.url + "/ecommerce/images/icons/"+ajaxLoading+"'>";
	if($(nameDiv+'Floater'))$(nameDiv+'Floater').style.top = 30+ (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + 'px';
	loadAjaxFile(nameFile, nameDiv, callBack, ajaxLoading);
}
/*END AJAX FUNCTIONS*/



/*SUBMIT FORMS BY SPRY UTILS*/
function submitForm(form, divId, callBack, imageLoading){
	if(imageLoading)
			document.getElementById(divId).innerHTML = "<img src='" + shop.url + "/ecommerce/images/icons/"+imageLoading+"'>";
	Spry.Utils.submitForm(form, function(req){document.getElementById(divId).innerHTML = req.xhRequest.responseText; eval(callBack);} );
}
/*END SUBMIT FORMS BY SPRY UTILS*/


/*FUNCTIONS TO CHECK SESSION IN USER CONRTOL PANEL*/
function checkSession()
{
	var xmlObj = createXMLRequest();
	
	xmlObj.open('GET', shop.url + '/ecommerce/users/checkSession.cfm?'+getUniqueId(), false);
	xmlObj.send(null);
	if(xmlObj.responseText.indexOf('0') != -1)return false;
	return true;
}

function loadUserContent(nameFile, nameDiv, callBack, ajaxLoading) {
	if(checkSession() == false){window.location.href = shop.url + '/ecommerce/users/userControlPanel.cfm'; return;}
	else loadContent(nameFile, nameDiv, callBack, ajaxLoading);
}

function checkSessionInUserOrder(){
	if(checkSession() == false){window.location.href = shop.url + '/ecommerce/users/userControlPanel.cfm'; Shadowbox.close(); return false;}
	return true;
}

function checkDeleteAccount(){
	if(checkSession() == false){window.location.href = shop.url + '/ecommerce/users/userControlPanel.cfm'; return false;}
	return true
}
/*END FUNCTIONS TO CHECK SESSION IN USER CONTROL PANEL*/


function closeContent(){
	$('informationBox').innerHTML = '';
	$('informationBox').style.visibility = 'hidden';
}





/*FUNCTIONS PRODUCT DETAIL*/
function addWishList(productId, nameImage){
		loadContent(shop.url + '/ajaxTemplates/wishlistActions.cfm?id='+productId+'&image='+nameImage, 'wishlistAction'+productId, "loadContent(shop.url + '/ajaxTemplates/wishlist.cfm', 'wishlistActual', '','')",'');
}

function addProduct(productId, form){
		//form.action = shop.url + '/ecommerce/basket/asyncBasket.cfm';
		return Spry.Utils.submitForm(form, reloadMiniBaskets );
}
/*END FUNCTIONS PRODUCT DETAIL*/


/*function deleteWishList(id){
		loadContent(shop.url + '/ajaxTemplates/wishlistDelete.cfm?id='+id, 'wishlistTable', "loadContent(shop.url + '/ajaxTemplates/wishlist.cfm', 'wishlistActual', '','')",'');
		
}
*/

/*FUNCTIONS IN WISHLIST USER CONTROL PANEL*/
function initWishlistTable(){
	//if($("contentUserControlPanel")) $("contentUserControlPanel").style.height = $("userControlPanelModule").offsetHeight + "px"; 
	//if($("wisthlistTable")) $("wisthlistTable").style.height = $("userControlPanelTable").offsetHeight + "px"; 
	//if($("divImatgesVerticalWishlist")) $("divImatgesVerticalWishlist").style.height = $("userControlPanelTable").offsetHeight -70 + "px"; 
	//if($("menuTabsVerticalWishlist")) $("menuTabsVerticalWishlist").style.height = $("divImatgesVerticalWishlist").offsetHeight + "px";
	if($('listWishlistDetailsId')) $('listWishlistDetailsId').value = "";
	if($('listProductsIdToEmail')) $('listProductsIdToEmail').value = "";
	if($('listProductsId')) $('listProductsId').value = "";
	$$('.checkWishlistDetail').each(function(el){el.checked = false;});
	
}

function initWishlistToEmail(obj){
	$('informationBox').style.visibility = 'visible';
	initFormFields("wishlistToEmail");
}

function findInArray(array, stringToSearch){
	for (var i = 0; i < array.length; i++){
		if(array[i] == stringToSearch) return i;
	}
	return -1;
}

function generateListProductsId(productId){
	var content = $('listProductsId').value;

	if(content.length > 0)var arrContent = content.split(',');
	else var arrContent = new Array();
	
	var pos = findInArray(arrContent, productId);
	if(pos >= 0)arrContent.splice(pos, 1);
	else arrContent.push(productId);
	
	content = arrContent.join(",");
	$('listProductsId').value = content;
	$('listProductsIdToEmail').value = content;

}

function emptyListListProductsId(){
	$('listProductsId').value = "";
	$('listProductsIdToEmail').value = "";

}

function generateListWishlistDetailsId(wishlistDetailId){
	var content = $('listWishlistDetailsId').value;

	if(content.length > 0)var arrContent = content.split(',');
	else var arrContent = new Array();
	
	var pos = findInArray(arrContent, wishlistDetailId);
	if(pos >= 0)arrContent.splice(pos, 1);
	else arrContent.push(wishlistDetailId);
	
	content = arrContent.join(",");
	$('listWishlistDetailsId').value = content;
}

function emptyListWishlistDetailsId(){
	$('listWishlistDetailsId').value = "";
}


function addProducts(form){
	$('productList').value = $('listProductsId').value;
//	loadContent(shop.url + '/ajaxTemplates/addProducts.cfm?listProductId='+content, 'wishlistTable', 'reloadMiniBaskets()','');
	return Spry.Utils.submitForm(form, reloadMiniBaskets );
}


function deleteWishList(){
	if(checkSession() == false){window.location.href = shop.url + '/ecommerce/users/userControlPanel.cfm'; return;}
	var content = $('listWishlistDetailsId').value;
	
	var arrContent = content.split(',');
	content = arrContent.join(',');
	if(content.length>0){
		loadContent(shop.url + '/ajaxTemplates/wishlistDelete.cfm?listWishlistDetailsId='+content, 'wishlistTable', "loadContent(shop.url + '/ajaxTemplates/wishlist.cfm', 'wishlistActual'); initWishlistTable()",'');
	}
	else{
		shop.cuteAlert.addMessage(languageSheet.lblError, languageSheet.lblSelectProducts,0,0);
	}

}

function generateEmail(){
	if(checkSession() == false){window.location.href = shop.url + '/ecommerce/users/userControlPanel.cfm'; return;}
	var content = $('listProductsIdToEmail').value;
	
	/*Shadowbox.open({
			player:     'ajax',
			content:    shop.url + '/ajaxTemplates/wishlistToEmail.cfm?listProductsId='+content,
			width:			470,
			height:			375
	}, {onFinish: function() {initWishlistToEmail();}}
	);	*/
	var arrContent = content.split(',');
	content = arrContent.join(',');
	if(content.length>0){
		loadContent(shop.url + '/ajaxTemplates/wishlistToEmail.cfm?listProductsId='+content, 'informationBox', 'initWishlistToEmail();', '');
	}
	else{
			shop.cuteAlert.addMessage(languageSheet.lblError, languageSheet.lblSelectProducts,0,0);
	}
}

function selectAllProductsWishlist(){
	$$('.checkWishlistDetail').each(
																	function(el){
																					 var arrId = el.id.split("_");
																					 if(el.checked == true){
																						 	el.checked = false;
																						 	emptyListWishlistDetailsId();
																							emptyListListProductsId();
																					 }
																					 else{
																						 generateListWishlistDetailsId(arrId[0]); 
																						 generateListProductsId(arrId[1]); 
																						 el.checked = true;
																					 }
																					 changeClass($('divWishlistDetail'+arrId[0]), 'selectRow', 'selectedRow');
																	});
}

/*END FUNCTIONS IN WISHLIST USER CONTROL PANEL*/


/*FUNCTIONS IN BASKET*/
function cuteQuestion(){
	
	this.timeOut = null;
	this.showing = false;
	this.messageQueue = new Array();
	this.addMessage = function(title, content, actionForm, image, timeout)
								{
									this.messageQueue.push( {title:title, content:content, actionForm:actionForm, image:image, timeout:timeout} );
									if(!this.showing)
										this.showMessage();
								}
	this.showMessage = function()
								{
									if(this.messageQueue.length)
									{
										this.showing = true;
										var message = this.messageQueue.shift();
										//document.getElementById('questionTitle').innerHTML = message.title;
										document.getElementById('questionMessage').innerHTML = message.content;
										document.getElementById('questionForm').action = message.actionForm;
										/*shop.questionBox.transition.start('opacity',0,1);*/
										
										Shadowbox.open({
											player:     'html',
											content:    $('questionBox').innerHTML,
											title: 			message.title,
											width:      350,
											height: 		70
										},
										{
											animate: false,
											onClose: shop.cuteQuestion.closeMessage()
										}
										);
										
										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.questionBox.transition.start('opacity',1,0);
									var self = this;
									setTimeout(function(){self.showMessage();},700);
								}
};
function showMessageClearBasket(){
	shop.cuteQuestion.addMessage('', languageSheet.lblClearBasket, shop.url + '/ecommerce/basket/updateBasket.cfm', 0,0);
}

function reloadBasket(){
	var file = "ajaxLoad(shop.url+'/ajaxTemplates/basket/basketButtons.cfm', $('basketButtons'), 'sameHeightBasket()')";
	ajaxLoad(shop.url+'/ajaxTemplates/basket/totalsBasket.cfm', $('totalBasket'), file);
	
}

function sameHeightBasket(){
	/*if($('basketCalculateBasket') && $('basketProductsTable').offsetHeight < $('basketCalculateBasket').offsetHeight)
			$('basketProductsTable').style.height = $('basketCalculateBasket').offsetHeight + 'px';*/
}

function selectCountryShippingMethod(value){
	ajaxLoad(shop.url+'/ajaxTemplates/checkoutActions.cfm?action=shipping&shippingMethodId='+value, null, '');
	ajaxLoad(shop.url+'/ajaxTemplates/checkoutActions.cfm?action=countryShippingMethod&countryShippingMethodId='+value, null, 'reloadBasket()');
}


function selectShippingMethod(value){
	ajaxLoad(shop.url+'/ajaxTemplates/checkoutActions.cfm?action=shipping&shippingMethodId='+value, null, 'reloadBasket()');
}

function selectPaymentMethod(value){
	ajaxLoad(shop.url+'/ajaxTemplates/checkoutActions.cfm?action=payment&paymentMethodId='+value, null, 'reloadBasket()');
}
/*END FUNCTIONS IN BASKET*/

/*FUNCTION IN CONTROL PANEL QUESTION*/
function showMessageDeleteAccount(){
	if(checkSession() == false){window.location.href = shop.url + '/ecommerce/users/userControlPanel.cfm'; return false;}
	shop.cuteQuestion.addMessage('', languageSheet.lblDeleteAccount, shop.url + '/ecommerce/users/deleteAccount.cfm', 0,0);
}

/*END FUNCTION IN CONTROL PANEL QUESTION*/