function onSetProductProperties(){}
function onAddProduct(){}
function changeOption(productId, sku, smallImage, largeImage){}

function formSubmit(isValid, form){if(isValid) form.submit();}

function reloadCaptcha(position,element,length) { 
	var imageElement = document.getElementById(element);
	var Data = new Request({
		url:'/templates/common/users/reloadCaptcha.cfm', 
		method:'get', noCache:true, link:'ignore', async:false,
		onSuccess: function(responseText) { if(responseText.length > 1) { imageElement.set('src', '/common/images/tmp/'+responseText); }}
	}).send('position='+position+'&length='+length);  
}

function initForm(form, callback, target, sync, disableValidationMessages)
{
	form = $(form);
	
	if(callback)
		form.callback = callback;
	
	if(target) form.asyncTarget = $(target);
	
	if(!sync)
		if(disableValidationMessages)
			form.validation = new Form.Validator(form, { onFormValidate:submitForm } );
		else
			form.validation = new Form.Validator.Inline(form, { onFormValidate:submitForm } );
	else
		if(disableValidationMessages)
			form.validation = new Form.Validator(form, { onFormValidate:formSubmit } );
		else
			form.validation = new Form.Validator.Inline(form, { onFormValidate:formSubmit } );
}
function submitForm(isValid, form, submitEvent)
{
	if(!isValid) return;
	
	var link = 'ignore'; if(form.hasClass('buyForm')) link = 'cancel';
	
	if(!form.submitRequest)
		form.submitRequest = new Request( {url:form.action, method:'post', link:link, isSuccess:function(code){return(code!=200)}, noCache:true, onFailure:callFormCallback} );

	if(form.callback)
		form.submitRequest.xhr.callback = form.callback;
	
	if(form.asyncTarget)
	{
		form.asyncTarget.addClass('loading');
	}
	
	form.submitRequest.xhr.form = form;
	form.submitRequest.send(extractFormParameters(form));
}
function callFormCallback(xhr)
{
	if(xhr.form.asyncTarget)
	{
		xhr.form.asyncTarget.removeClass('loading');
		xhr.form.asyncTarget.innerHTML = xhr.responseText;
	}
	if(xhr.callback)
		xhr.callback(xhr);		
}
function extractFormParameters(form, namesPrefix)
{
	var form = $(form);	var parameters = new Array();
	if(!namesPrefix) namesPrefix = '';
	
	for (var i = 0; i < form.elements.length; i++ )
	{
		el = form.elements[i];
		if (!el.type) continue;
		if (!el.name) continue;
		switch(el.type.toLowerCase())
		{
			case 'text':
			case 'password':
			case 'textarea':
			case 'hidden':
			case 'submit':
				parameters.push(encodeURIComponent(namesPrefix+el.name) + '=' + encodeURIComponent(el.value));
				break;
			case 'select-one':
				var value = '';
				var opt;
				if (el.selectedIndex >= 0)
				{
					opt = el.options[el.selectedIndex];
					value = opt.value || opt.text;
				}
				parameters.push(encodeURIComponent(namesPrefix+el.name) + '=' + encodeURIComponent(value));
				break;
			case 'select-multiple':
				for (var j = 0; j < el.length; j++)
				{
					if (el.options[j].selected)
					{
						value = el.options[j].value || el.options[j].text;
						parameters.push(encodeURIComponent(namesPrefix+el.name) + '=' + encodeURIComponent(value));
					}
				}
				break;
			case 'checkbox':
			case 'radio':
				if (el.checked)
					parameters.push(encodeURIComponent(namesPrefix+el.name) + '=' + encodeURIComponent(el.value));
				break;
			default:
			break;
		}
	}
	return parameters.join('&');
}

function EsetHTML(id, html){return Eset(id,'innerHTML', html)}
function Eset(id, property, value){var t = E(id); if(t){t[property]=value; return true} return false}

function setUserFormFields(userType)
{
	if(!userType)
	{
		if( E('userTypeField3') && E('userTypeField3').checked )
			userType = 3;
		else if( E('userTypeField2') && E('userTypeField2').checked )
			userType = 2;
		else
			userType = 1;
	}

	var fieldsMainContainer = $('userFormFieldsContainer');
	var userFormFields = window.formFields.userFields;

	for(var i=0; i < window.formFields.userFields[0].length; i++)
	{
		formField = $( 'user'+userFormFields[0][i]+'Field' );
		container = $('userField'+userFormFields[0][i]+'Container');

		if(formField)
			formField.removeClass('required');
		if(container)
		{
			container.style.display='none';
			//moving fields
			fieldsMainContainer.grab(container);
			container.getElements('span.required').each( function(el){el.setStyle('display', 'none');} );
		}
	}
	
	//destroying old blocks
	fieldsMainContainer.getElements('div.userFormFields').each( function(el){el.destroy();} );
	//creating a new fields block
	var currentFieldsContainer = new Element('div', {'class':'formFields userFormFields'} );
	fieldsMainContainer.adopt( currentFieldsContainer );
	
	for(i=0; i < userFormFields[userType].length; i++)
	{
		fieldInformation = userFormFields[userType];
		
		if(fieldInformation[i].name.toUpperCase() == 'BLOCK')
		{
			var currentFieldsContainer = new Element('div', {'class':'formFields userFormFields'} );
			fieldsMainContainer.adopt( currentFieldsContainer );
		}
		else
		{
			formField = $( 'user'+fieldInformation[i].name+'Field' );
			container = $('userField'+fieldInformation[i].name+'Container');
			
			if(formField && fieldInformation[i].required)
				formField.addClass('required');
			if(container)
			{
				container.style.display = '';
				currentFieldsContainer.grab( container , 'bottom');
				if(fieldInformation[i].required)
					container.getElements('span.required').each( function(el){el.setStyle('display', '');} );
			}
		}
		
	}	
	
	if(!window.formFields.shippingFields) return;
	
	fieldsMainContainer = $('shippingAddressFormFieldsContainer');
	userFormFields = window.formFields.shippingFields;

	for(var i=0; i < userFormFields[0].length; i++)
	{
		formField = $( 'user'+userFormFields[0][i]+'Field' );
		container = $('userField'+userFormFields[0][i]+'Container');
		
		if(formField)
			formField.removeClass('required');
		if(container)
		{
			container.style.display='none';
			//moving fields
			fieldsMainContainer.grab(container);
			container.getElements('span.required').each( function(el){el.setStyle('display', 'none');} );
		}
	}
	
	//destroying old blocks
	fieldsMainContainer.getElements('div.userFormFields').each( function(el){el.destroy();} );
	//creating a new fields block
	var currentFieldsContainer = new Element('div', {'class':'formFields userFormFields'} );
	fieldsMainContainer.adopt( currentFieldsContainer );
	
	for(i=0; i < userFormFields[userType].length; i++)
	{
		fieldInformation = userFormFields[userType];
		
		if(fieldInformation[i].name.toUpperCase() == 'BLOCK')
		{
			var currentFieldsContainer = new Element('div', {'class':'formFields userFormFields'} );
			fieldsMainContainer.adopt( currentFieldsContainer );
		}
		else
		{
			formField = $( 'user'+fieldInformation[i].name+'Field' );
			container = $('userField'+fieldInformation[i].name+'Container');
			
			if(formField && fieldInformation[i].required)
				formField.addClass('required');
			if(container)
			{
				container.style.display = '';
				currentFieldsContainer.grab( container , 'bottom');
				if(fieldInformation[i].required)
					container.getElements('span.required').each( function(el){el.setStyle('display', '');} );
			}
		}
		
	}
	
}

function getProductProperties(formElement)
{
	var forms;
	var form, formData, el;
	var postData = new Array();
	var uniqueId=0;
	
	if(formElement)
	{
		form = $(formElement);
		if(form.tagName.toUpperCase() != 'FORM') form = form.getParent('form');
		forms = new Array(); forms.push(form);
	}
	else
		forms = $$('form.buyForm')
	
	for(var i=0; i<forms.length; i++)
	{
		form = forms[i];
		if(form.uniqueId)
			uniqueId=form.uniqueId.value;
		else
			uniqueId=form.productId.value;

		formData = extractFormParameters(form, 'buyForm'+uniqueId+'_');
		formData += '&id='+uniqueId;
		postData.push( formData );
		for(var y=0; y<form.elements.length; y++)
		{
			el = form.elements[y];
			if(!el.type) continue;
			
			if(el.type.toUpperCase() == 'SUBMIT')
			{
				el.disabled = true;
				$(el).fade(0.10);
			}
			else if(el.type.toUpperCase() == 'RADIO')
			{
				if(el.checked)
				{
					$(el).getParent('.productOptionValues').getElements('.productOptionValue').each( function(elm){ elm.removeClass('productOptionSelected')} );
					el.getParent('.productOptionValue').addClass('productOptionSelected');
				}
			}
			
		}
	}
	
	if(forms.length == 1)
	{
		if(!forms[0].request)
			forms[0].request = new Request({url:'/templates/common/products/productProperties.cfm', method:'post', noCache:true, onSuccess:setProductProperties, link:'cancel' });
		forms[0].request.send( postData.join('&') );
	}
	else if(forms.length)
		new Request({url:'/templates/common/products/productProperties.cfm', method:'post', noCache:true, onSuccess:setProductProperties }).send( postData.join('&') );
	
}

function setProductProperties(responseText)
{
	var productsArray = JSON.decode(responseText);
	var productId, uniqueId, form, response;
	
	for(var j=0; j<productsArray.length; j++)
	{
			response = productsArray[j];
			productId = response.PRODUCTID;
			uniqueId = response.UNIQUEID;
			form = $('buyForm'+uniqueId);
			
			for(var i=0; i<form.elements.length; i++)
			{
				el = form.elements[i];
				if(!el.type) continue;
				
				if(el.type.toUpperCase() == 'SUBMIT')
				{
					el.disabled = response.BUTTON.DISABLED;
					el.value = response.BUTTON.VALUE;
					if(response.STOCK == 0)
						if(response.BACKORDER)
							el.addClass('reserveButton');
						else
							el.removeClass('reserveButton');
						
					$(el).fade(1);
				}
				
			}
						
			if(response.SHOWPRICE)
			{
				EsetHTML('alternativePrice'+uniqueId, response.PRICES.ALTERNATIVEPRICE.VALUE); EsetHTML('alternativeBasePrice'+uniqueId, response.PRICES.ALTERNATIVEBASEPRICE.VALUE);
				EsetHTML('price'+uniqueId, response.PRICES.PRICE.VALUE); EsetHTML('basePrice'+uniqueId, response.PRICES.BASEPRICE.VALUE);
				EsetHTML('salePercentDifference'+uniqueId, response.PRICEDISCOUNT.PERCENTDIFFERENCE.ROUNDEDPERCENTDIFFERENCE);
				EsetHTML('priceDifference'+uniqueId, response.PRICEDISCOUNT.PRICEDIFFERENCE.VALUE);
			}
			else
			{
				EsetHTML('price'+uniqueId, ''); EsetHTML('Price'+uniqueId, '');
			}
			
			if(response.AVAILABILITY)
			{
				EsetHTML('productAvailabilityName'+uniqueId, response.AVAILABILITY.DESCRIPTION);
				EsetHTML('productAvailabilityDescription'+uniqueId, response.AVAILABILITY.AVAILABILITYDESCRIPTION);
				Eset('productAvailabilityImage'+uniqueId, 'src', response.AVAILABILITY.IMAGE);
			}
			
			if(response.STOCK < 0)
				EsetHTML('productStock'+uniqueId, 0);
			else
				EsetHTML('productStock'+uniqueId, parseInt(response.STOCK) );

	}
	
	onSetProductProperties(productsArray);
		
}

function addProductCallback(xhr)
{
	var response = JSON.decode(xhr.responseText);
	
	if(!response.ADDED) return;
	
	$('miniBasketLayer').set('load', {noCache:true} ).load('/templates/template1/content/common/miniBasket/basket.cfm', {evalScripts:false} );
	if(!window.smoothScroll) window.smoothScroll = new Fx.Scroll(window, {wheelStops:true, onComplete:function(){if(window.miniBasketTransition) window.miniBasketTransition.showSubmenu();} });
	window.smoothScroll.toTop();
	
	onAddProduct( response );	
}

window.toTop = function()
{
	new Fx.Scroll(window).toTop();
}

function loadSubcountries(countryId, subcountryId, uniqueId, fieldName, className)
{
	var container = $('countriesSelectorContainer_'+uniqueId);
	container.set('html', 'loading...<input type="text" class="required" value="" style="border:none; width:1px; height:1px; display:inline; padding:0px; margin:0px;" />');
	container.set('load', {link:'cancel'} );
	var parameterEncoder = new urlParameterEncoder().addParameter('countryId',countryId).addParameter('subcountryId',subcountryId).addParameter('fieldName',fieldName).addParameter('className',className).addParameter('uniqueId', uniqueId);
	
	container.load('/templates/common/users/subcountriesSelector.cfm'+parameterEncoder.getParameters() );
	
	if(!subcountryId)
	{
		parameterEncoder.addParameter('itemId',countryId);
		container = $('subcountriesSearch_'+uniqueId);
		container.set('html', '');
		container.load('/templates/common/users/subcountriesSearch.cfm'+parameterEncoder.getParameters() );
	}
	
}

function loadPostalCodes(countryId, value, uniqueId, fieldName, className, exec)
{
	var container = $('postalCodes_'+uniqueId);
	
	if(exec)
	{
		container.set('load', {link:'cancel', onComplete:function(){ container.spinner.hide(); } } );
		var parameterEncoder = new urlParameterEncoder().addParameter('countryId',countryId).addParameter('zip',value).addParameter('uniqueId',uniqueId).addParameter('fieldName',fieldName).addParameter('className',className);
		container.load('/templates/common/users/postalCodesSelector.cfm'+parameterEncoder.getParameters() );
	}
	else if(value.length > 2)
	{
		if(container.timeout) clearTimeout(container.timeout);
		if(container.innerHTML.length < 30) container.innerHTML = '<div style="width:200px; height:150px;" />';
		if(!container.spinner) container.spinner = new Spinner(container);
		container.spinner.position().show();
		if(container.get('load').xhr.readyState != 0 && container.get('load').xhr.readyState != 4)
			loadPostalCodes(countryId, value, uniqueId, fieldName, className, true)
		else
			container.timeout = setTimeout('loadPostalCodes('+countryId+', "'+value+'", "'+uniqueId+'", "'+fieldName+'", "'+className+'", true)', 400);
	}
}

function selectPostalCode(countryId, subcountryId, uniqueId, fieldName, className)
{
	var field = E('zipField_'+uniqueId);
	var container = $('countriesSelectorContainer_'+uniqueId);
	var selectorContainer = $('postalCodes_'+uniqueId);
	
	//field.value = '';
	selectorContainer.set('html', '');
	
	var parameterEncoder = new urlParameterEncoder().addParameter('countryId',countryId).addParameter('subcountryId',subcountryId).addParameter('fieldName',fieldName).addParameter('className',className);
	
	container.set('html', 'loading...');
	container.set('load', {link:'cancel'} );
	container.load('/templates/common/users/selectPostalCode.cfm'+parameterEncoder.getParameters() );
}
function setResponseText(code, message, target)
{
	var target = $(target); if(!target) return false;
	
	if(code){target.addClass('OKMessage').removeClass('KOMessage')}
	else{target.addClass('KOMessage').removeClass('OKMessage')}
	target.setStyle('opacity',0).morph( {opacity:1});
	target.innerHTML = message;
	if(target.messageTimeout) clearTimeout(target.messageTimeout);
	target.messageTimeout = setTimeout( function(){ target.morph( {opacity:0} ); } , messagesTimeout);
	return true;
}
function loginUser(xhr)
{
	var response = JSON.decode(xhr.responseText);
	if(response.LOGGEDIN)
	{
		/*blueknow*/if(window.BlueknowTracker){BlueknowTracker.setUserLogged(parseInt(response.USERID)) }
		
		if(!response.REDIRECT || !response.REDIRECT.length) location.reload();
		else location.href = response.REDIRECT;
	}
	else
	{
		if( !setResponseText(0, response.MESSAGE, 'userLoginResponse') )
			setResponseText(0, response.MESSAGE, 'smallLoginResponse');
	}
}

function setFormResponse(xhr, target)
{
	var response = JSON.decode(xhr.responseText);
	setResponseText(response.SENT, response.MESSAGE, target);
	return response.SENT;
}

function smallNewsletterResponse(xhr)
{
	var response = JSON.decode(xhr.responseText);
	setResponseText(response.SUBSCRIBED, response.MESSAGE, 'smallNewsletterResponse');
}

function newsletterFormResponse(xhr)
{
	var response = JSON.decode(xhr.responseText);
	setResponseText(response.SUBSCRIBED, response.MESSAGE, 'newsletterFormResponse');
}

function sponsorshipResponse(xhr)
{
	var OK = setFormResponse(xhr, 'sponsorshipResponse');
	if(OK) xhr.form.reset();
}

function deleteWishlistResponse(xhr)
{
	var response = JSON.decode(xhr.responseText);
	E('deleteWishlistResponse').innerHTML = '';
	if(response.SUCCEEDED) location.reload();
}

function sendWishlistResponse(xhr)
{
	var response = JSON.decode(xhr.responseText);
	setResponseText(response.SENT, response.MESSAGE, 'sendWishlistResponse');
}

function productRecommendResponse(xhr){setFormResponse(xhr, 'productRecommendResponse'); /*blueknow*/if(window.BlueknowTracker){BlueknowTracker.trackExamined(JSON.decode(xhr.responseText).PRODUCTID);} }
function contactResponse(xhr){ 
		setFormResponse(xhr, 'contactResponse');  
		setTimeout(function() {
			var response = JSON.decode(xhr.responseText);
			if(response.SENT == 1) { 
				document.getElementById("contactForm").reset(); 
				try { $$("img.reloadCaptchaImage")[0].click(); } catch(e) { /* No Captcha */ }
			} 
		},3000); 
}
function productContactResponse(xhr){setFormResponse(xhr, 'productContactResponse'); /*blueknow*/if(window.BlueknowTracker){BlueknowTracker.trackExamined(JSON.decode(xhr.responseText).PRODUCTID);} }
function productCommentResponse(xhr)
{
	var response = JSON.decode(xhr.responseText);
	E('productCommentResponse').innerHTML = response.MESSAGE;
	
	/*blueknow*/if(window.BlueknowTracker){BlueknowTracker.trackExamined(response.PRODUCTID); }
}
function productCommentResponse2(xhr)
{
	var response = JSON.decode(xhr.responseText);
	alert(response.MESSAGE);
	window.location.reload();
	
	/*blueknow*/if(window.BlueknowTracker){BlueknowTracker.trackExamined(response.PRODUCTID); }
}
function submitDiscountCode(responseText, responseXML)
{
	var field = $('discountCodeField');
	var container = $('discountCodeFieldContainer');
	
	if(responseText)
	{
		container.spinner.hide();
		if(responseText == '0')
			location.reload();
		/*else
			alert('Not found');*//*WARNING*/
	}
	else
	{
		if(!field) return;
		if(!field.value.length) return;
	
		if(!container.spinner)
		{
			container.spinner = new Spinner(container);
			container.request = new Request( {method:'get', url:'/templates/common/basket/addDiscountCode.cfm', onSuccess:submitDiscountCode, onFailure:submitDiscountCode} );
		}
		container.spinner.position().show();
		
		container.request.send('code='+field.value);
	}
	
}
function setPaymentSystem(id)
{
	if(!window.recalcRequest) window.recalcRequest = new Request.HTML( {method:'get', link:'cancel', noCache:true, evalScripts:false, onSuccess:reloadBasket} );
	window.recalcRequest.get('/templates/common/basket/setPaymentSystem.cfm?id='+id);
}

function setShippingSection(id)
{
	if(!window.recalcRequest) window.recalcRequest = new Request.HTML( {method:'get', link:'cancel', noCache:true, evalScripts:false, onSuccess:reloadBasket} );
	window.recalcRequest.get('/templates/common/basket/setShippingSection.cfm?id='+id);
}
function reloadBasket()
{
	//if(!window.recalcRequest) window.recalcRequest = new Request.HTML( {method:'get', link:'cancel', noCache:true, evalScripts:false, update:'basketContainer'} );
	location.reload();
}

function addToWishlist(itemType, itemId, button, addedText)
{
	var button = $(button);
	if(!button) return;
	button.addClass('wishlistButtonAdded');
	button.value = addedText; button.onclick = ""; button.disabled=true;
	try{button.innerHTML = addedText;}catch(e){}
	if(!button.request)	button.request = new Request({url:'/templates/common/users/addToWishlist.cfm', method:'get', noCache:true, link:'ignore' });
	button.request.send('itemId='+itemId+'&itemType='+itemType);
	
	/*blueknow*/if(window.BlueknowTracker){BlueknowTracker.trackExamined(itemId); }
	
}

function addToComparer(itemType, itemId, button, addedText)
{
	var button = $(button);
	if(!button) return;
	button.addClass('comparerButtonAdded');
	button.value = addedText; button.onclick = ""; button.disabled=true;
	try{button.innerHTML = addedText;}catch(e){}
	if(!button.request)	button.request = new Request({url:'/templates/common/products/comparer.cfm', method:'get', noCache:true, link:'ignore' });
	button.request.send('add='+itemId+'&itemType='+itemType);
	
	/*blueknow*/if(window.BlueknowTracker){BlueknowTracker.trackExamined(itemId); }
}
function removeFromComparer(itemId)
{
	new Request({url:'/templates/common/products/comparer.cfm', method:'get', noCache:true, link:'ignore', async:false }).send('remove='+itemId+'&itemType='+1);
}

function wishlistAccountRequired(button)
{	
	Shadowbox.open( {content:'/templates/common/users/wishlistAccountRequired.cfm' , player:'ajax' } );
}

function viewOrder(orderId, token, pdf)
{
	var parameterEncoder = new urlParameterEncoder().addParameter('id',orderId).addParameter('token',token);
	if(pdf) parameterEncoder.addParameter('pdf',1);
	window.open('/ecommerce/orders/order.cfm'+parameterEncoder.getParameters(), 'viewOrder', 'menubar=1,resizable=1,scrollbars=1,width=800,height=600');
}

function getRefund(orderId, token)
{
	var parameterEncoder = new urlParameterEncoder().addParameter('id',orderId).addParameter('token',token);
	window.open('/ecommerce/orders/getRefund.cfm'+parameterEncoder.getParameters(), 'getRefund', 'menubar=1,resizable=1,scrollbars=1,width=800,height=600');
}

function openSubcategories(id, lv)
{
	var b = $('subCategoriesTree_'+id);
	if(!b) return true;
	
	var a = new urlParameterEncoder().addParameter('parentId',id).addParameter('level',lv);
	
	if(b.innerHTML.length < 50)	
	{
		ajaxLoad('/templates/template1/content/common/categoriesTree/tree.cfm'+a.getParameters() , b, null, true );
		if(b.innerHTML.length < 50) return true;
	}
	else
		b.innerHTML = '';
	
	return false;
}

function addGift(discountId, productId, quantity)
{
	if(!quantity) quantity=1;
	
	if(!window.addGiftRequest)
		window.addGiftRequest = new Request.JSON( {url:'/templates/common/basket/addGift.cfm', method:'get', link:'ignore', onSuccess:addGiftResponse } );
	
	window.addGiftRequest.send('discountId='+discountId+'&productId='+productId+'&quantity='+quantity);
}
function addGiftResponse(response)
{
	if(response.ADDED)
		location.reload();
	else
	{
		//Shadowbox.open({content:'<div style="padding:20px;">'+response.MESSAGE+'</div>', player:"html", title:response.MESSAGE });
		alert(response.MESSAGE);
		location.reload();
	}
}

function showPollSubquestions(questionId, checked, hideList)
{
	var element = null;
	/*hide other questions*/
	if(!hideList) hidelist = new Array();
	
	for(var i=0; i<hideList.length; i++)
	{
		element = $('pollQuestion_'+hideList[i]);
		if(element)
		{
			element.style.display = 'none';
		}
	}
	
	/*switch current question*/
	if(checked)
	{
		element = E('pollQuestion_'+questionId);
		if(element)
		{
			element.style.display = '';
		}
	}
	
}

function initPollForm(form, callback, target)
{
	form = $(form);	
	
	if(callback) form.callback = callback;
	
	if(target) form.asyncTarget = $(target);
	
	form.validation = new Form.Validator(form, { onFormValidate:submitPollForm } );

}

function submitPollForm(isValid, form)
{
	if(!isValid) return;
	
	if(form.submitRequest)
		form.submitRequest.cancel();
	
	form.submitRequest = new Request( {url:form.action, method:'post', link:'cancel', isSuccess:function(code){return(code!=200)}, noCache:true, onFailure:callFormCallback} );
	if(form.callback)
		form.submitRequest.xhr.callback = form.callback;
	
	if(form.asyncTarget)
	{
		form.asyncTarget.addClass('loading');
	}
	
	/*disabling hidden fields*/
	form.getElements('div.pollQuestion').each
	(
	 	function(innerDiv)
		{
			if(innerDiv.style.display == 'none')
			{
				innerDiv.getElements('input.PQL').each( function(input){ input.setAttribute('name', '') } );
			}
		}
	);
	
	form.submitRequest.xhr.form = form;
	form.submitRequest.send(extractFormParameters(form));
}

function initChat()
{
	Asset.javascript('/common/js/chat.js', {id:'chatScript', onLoad:function(){createChat()} } );
}

function Countdown(container, template, callback, year, month, day, hour, minute, second, year2, month2, day2, hour2, minute2, second2 )
{
	var me = this;
	this.container = $(container);
	if(!this.container) return;
	this.template = template;
	this.callback = callback;
	
	//get time difference between client and server
	this.offset = new Date().getTime() - new Date(year,month-1,day,hour,minute,second,0).getTime();
	this.limit = new Date(year2,month2-1,day2,hour2,minute2,second2,0).getTime();
	
	this.showTime = function()
	{
		var JSDate = new Date().getTime() - me.offset;
		var currentDate = me.limit - JSDate;
		
		if(currentDate < 0)
		{
			me.callback(); return;
		}
		
		var timeObj = formatTime(currentDate);
		
		me.container.innerHTML = template.replace("%days%", timeObj.days).replace("%hours%", timeObj.hours).replace("%minutes%", timeObj.minutes).replace("%seconds%", timeObj.seconds);
		
		setTimeout( me.showTime , 1000 );
	}
	
	me.container.innerHTML='';
	setTimeout( this.showTime , 1 );
	
}


function formatTime(ms)
{
	var two = function(x){return ((x>9)?"":"0")+x}
	var sec = Math.floor(ms/1000), hr, day;
	var t={};
	
	var min = Math.floor(sec/60)
	sec = sec % 60
	t.seconds = two(sec)
	
	var hr = Math.floor(min/60)
	min = min % 60
	t.minutes = two(min)
	
	var day = Math.floor(hr/24)
	hr=hr%60%24;
	t.hours=two(hr);
	t.days=day;
	
	return t
}

function getFactFinderSuggest(ev)
{
	var suggestDiv = $('smallSearchSuggest');
	var ev = new Event(ev);
	var searchField = ev.target;
	
	if(searchField.value == '') suggestDiv.fade('out');
	
	switch(ev.key)
	{
		case 'up': moveSuggest('up'); return false;
		case 'down': moveSuggest('down'); return false;
		case 'left':
		case 'right': return;
	}
	
	if(searchField.timeout) clearTimeout(searchField.timeout);
	
	searchField.timeout = setTimeout(function(){ loadFactFinderSuggest(suggestDiv, searchField) }, 500);
}

function moveSuggest(direction)
{
	var suggestDiv = $('smallSearchSuggest');
	var suggestions = suggestDiv.getElements('tr.suggest');
	var i, selectedSuggestion = -1;
	
	if(!suggestions.length) return;
	
	for(i=0; i<suggestions.length; i++)
	{
		if(suggestions[i].hasClass('suggestSelected'))
		{
			selectedSuggestion = i;
			suggestions[i].removeClass('suggestSelected');
			break;
		}
	}
	
	if(direction == 'up')
	{
		if(selectedSuggestion > 0)
			selectedSuggestion--;
		else
			selectedSuggestion = suggestions.length-1;
	}
	else
	{
		if(selectedSuggestion < suggestions.length-1)
			selectedSuggestion++;
		else
			selectedSuggestion = 0;
	}
	
	suggestions[selectedSuggestion].addClass('suggestSelected');	
	E('smallSearchCriteriaField').value = suggestions[selectedSuggestion].title;
}

function changeCurrency(id)
{
	var loc = location.href.replace( /[\\?&]currencyId=([^&#]*)/ , '');
	
	if(location.pathname == '/')
		location.href = loc + '?currencyId=' + id;
	else if( loc.indexOf('.cfm') > -1)
	{
		if(loc.indexOf('?') == -1)
			location.href = loc + '?currencyId=' + id;
		else
			location.href = loc + '&currencyId=' + id;
	}
	else
		location.href = loc + '&currencyId=' + id;
}

function loadFactFinderSuggest(suggestDiv, searchField)
{
	suggestDiv.set('load', {link:'cancel', onComplete:function(){suggestDiv.fade('in')} } );
	suggestDiv.load('/templates/common/search/suggest.cfm?searchCriteria='+encodeURIComponent(searchField.value) );
}

function suggestSearch(searchCriteria)
{
	E('smallSearchCriteriaField').value = searchCriteria;
	E('smallSearchForm').fireEvent('submit');
}

function attachmentFields(target, fieldName, options)
{
	var me = this;
	this.target = $(target);
	
	if(!this.target) return;
	
	this.options = {}
	this.options.className = options.className || 'attachment';
	this.options.attachedClassName = options.attachedClassName || 'attached';
	this.options.minValues = options.minValues || 0;
	this.options.maxValues = options.maxValues || 0;
	
	if(this.options.minValues > this.options.maxValues)
	{
		var aux = this.options.maxValues;
		this.options.maxValues = this.options.minValues;
		this.options.minValues = aux;
	}
	
	if(this.options.maxValues == 0) this.options.maxValues = 100;
	
	this.fieldName = fieldName;
	this.attachments = new Element('input', {type:'text', 'class':'validate-numOfFiles minFiles:'+this.options.minValues+' maxFiles:'+this.options.maxValues} ).setStyles({width:10, height:10, border:'none', visibility:'hidden', position:'absolute'});
	
	this.attachments.value=0;
	this.target.grab(this.attachments);
	
	this.createUploadField = function()
	{
		if( me.options.maxValues > 0 && me.target.getElements('div.productOptionValue').length >= me.options.maxValues) return;
		//if( me.options.maxValues > 0 && me.attachments >= me.options.maxValues) return;
		
		var id = new Date().getMilliseconds();
		var div = new Element('div', {id:'DIV'+id, 'class':me.options.className} );
		var input = new Element('input', {type:'file', autocomplete:'off'});
		input.addEvent('change', function(){ me.uploadFile(this, 'DIV'+id, fieldName ); me.createUploadField; } );
		
		div.grab(input);
		
		me.target.grab(div);
		
	}
	
	this.deleteFile = function(field)
	{
		$(field).destroy();
		if(me.attachments.value == me.options.maxValues) me.createUploadField();
		me.attachments.value--;
	
	}
	
	this.uploadFile = function(field)
	{
		target = $( field.getParent() );
		field.setAttribute('name', 'file');
		var id = "frame" + new Date().getMilliseconds();
		var frame = new Element('iframe', {frameborder:'no', name:id, border:0, styles: {width:'0px', height:'0px', display:'none'} });
		var form = new Element('form', {action:'/templates/common/fileUpload/upload.cfm', method:'post', enctype:'multipart/form-data', target:id, styles: {width:'0px', height:'0px', display:'none'} });
		
		$(document.body).grab(frame);
		$(document.body).grab(form);
		form.grab( field );
		
		$(frame).addEvent('load', function()
															{
																var response = JSON.decode(frame.contentWindow.document.body.innerHTML);
																
																target.removeClass('attachmentUploading');
																target.addClass(me.options.attachedClassName);
																
																var deleteDiv = new Element('div', {'class':'deleteAttached'} );
																var filenameDiv = new Element('div', {'class':'attachmentFilename'} );
																var hiddenField = new Element('input', {type:'hidden', name:me.fieldName});
																
																target.grab(deleteDiv);
																target.grab(filenameDiv);
																
																filenameDiv.innerHTML = response.ORIGINALFILE;
																hiddenField.value = response.FILE;
																
																deleteDiv.grab(hiddenField);
																deleteDiv.addEvent('click', function(){ me.deleteFile( this.getParent() ); } );
																
																me.attachments.value++;
																
																me.createUploadField();
															}
		);
		
		target.removeClass('productOptionAttachmentValue');
		target.addClass('attachmentUploading');
		
		
		form.submit();
	}
	
	this.createUploadField();
	
}

function initProductValoration(DIVID,WIDTH,VOTES) {
	var mainContainer = "productRateContainer" + DIVID;
	var mainTopLayer = "productRateTopLayer" + DIVID;
	var mainBottomLayer = "productRateBottomLayer" + DIVID;
	var mainCommentsLayer = "productRateNumComments" + DIVID;
}
