window.cem = new (function() {
	// internal states
	this.prompts = '';
	this.hash = '';
	this.uri = '';
	this.lastQuery = '';
	this.showAutocomplete = false;
	this.useAutocomplete = false;
	this.firstBarClick = true;
	this.previewCache = {};

	// initialize events
	this.init = function() {
		// auto-completion
		jQuery("#searchTxt").autocomplete(
			'/ajax/ac',
			{
				scrollHeight: 250,
				selectFirst: false,
				autoFill: false,
				cacheLength: 100,
				multiple: false,
				dataType: 'json',
				parse: function(data) {
					window.cem.showAutocomplete = true;
					return jQuery.map(
						data,
						function(row) {
							var txt = '';

							switch (row.type) {
							case 'query':
								txt = row.prefix + (row.prefix.length > 0 ? ' ' : '') + row.query + ' ';
								break;

							case 'content':
								txt = row.content.title;
								break;
							}
							return {
								data: row,
								result: txt
							};
						}
					);
				},
				formatItem: function(row) {
					switch (row.type) {
					case 'query':
						return row.prefix + (row.prefix.length > 0 ? ' ' : '') + row.query + " (" + row.counter + ")";

					case 'content':
						switch (row.content.properties.contentType.value[0]) {
						case 'Produits':
						case 'Products':
							if (parseFloat(row.content.properties.price.value[0]) > parseFloat(row.content.properties.finalPrice.value[0])) {
								return (
									'<img src="/products/images/' + window.cem.lang + '/100/100/' + row.content.properties.externalId.value[0] + '.jpg" width="50" height="50"/>' +
									'<div>' + row.content.title + '<br/>' +
										'<span style="color: gray;" class="noReference">PTR: #' + row.content.properties.ptr.value[0] + '</span><br/>' +
										'<span style="color: gray; text-decoration: line-through;">' + window.cem.formatPrice(row.content.properties.price.value[0]) + '</span><br/>' +
										'<span style="color: red; font-weight: bold;">' + window.cem.formatPrice(row.content.properties.finalPrice.value[0]) + '</span>' +
									'</div>'
								);
							}
							return (
								'<img src="/products/images/' + window.cem.lang + '/100/100/' + row.content.properties.externalId.value[0] + '.jpg" width="50" height="50"/>' +
								'<div>' + row.content.title + '<br/>' +
									'<span style="color: gray;" class="noReference">PTR: #' + row.content.properties.ptr.value[0] + '</span><br/>' +
									'<span style="color: gray;">' + window.cem.formatPrice(row.content.properties.price.value[0]) + '</span>' +
								'</div>'
							);

						case 'Articles':
							return (
								'<img src="/magazine/images/' + window.cem.lang + '/134/84/' + row.content.properties.externalId.value[0] + '.jpg" width="50" height="32"/>' +
								'<div>' + row.content.title + '</div>'
							);

						case 'Questions fréquentes':
						case 'FAQs':
							return (
								'<img src="/rc/img/icon_help.gif"/>' +
								'<div>' + row.content.title + '</div>'
							);
						}
						return row.content.title;
					}
				}
			}
		).result(
			function(e, row, value, q) {
				var cgi = '?ac=' + encodeURIComponent(q);
				var ac = jQuery("#searchTxt");

				window.cem.useAutocomplete = true;
				switch (row.type) {
				case 'query':
					ac.redoAC();
					break;

				case 'content':
					switch (row.content.properties.contentType.value[0]) {
					case 'Produits':
					case 'Products':
						window.location = '/products/' + row.content.properties.externalId.value[0] + '/' + cgi;
						break;

					case 'Articles':
						window.location = '/magazine/' + row.content.properties.externalId.value[0] + '/' + cgi;
						break;

					case 'Questions fréquentes':
					case 'FAQs':
						window.location = '/support/faq/' + row.content.properties.externalId.value[0] + '/' + cgi;
						break;
					}
					break;
				}
			}
		);

		// reco overlay
		var previewRenderEvent = function(items, cgi) {
			if (items.length > 0) {
				var trigger = jQuery(this);
				var html = [];
				var cgi2 = (window.cem.uri.length > 0 ? '?' + window.cem.uri : '');

				html.push('<div style="float: right;">');
					html.push('<a href="#TB_inline?inlineId=ctxRecoHelp&modal=true" class="thickbox"><img src="/rc/img/icon_help.gif"/></a>');
					//html.push('<a href="#" onclick="jQuery(\'#cem-preview-window\').hide(200); return false;"><img src="/rc/img/icon_close.gif"/></a>');
				html.push('</div>');
	
				html.push('<div style="padding: 5px;">');
					html.push('<div style="font-weight: bold; font-size: 16px; padding: 5px;">');
						html.push(window.cem.lang == 'fr' ? 'Corbeil vous recommande' : 'Corbeil suggests');
					html.push('</div>');

					for (var i = 0; i < items.length; i++) {
						var c = items[i].content;
		
						html.push('<div style="float: left;">');
							html.push('<a href="/products/' + c.properties.externalId.value[0] + '/' + cgi2 + '"><img height="125" width="125" src="/products/images/' + window.cem.lang + '/100/100/' + c.properties.externalId.value[0] + '.jpg" alt=""/></a>');
							html.push('<div class="itemDesc">');
								html.push('<h4><a href="/products/' + c.properties.externalId.value[0] + '/' + cgi2 + '">' + c.title + '</a></h4>');
								html.push('<span class="noReference">PTR: #' + c.properties.ptr.value[0] + '</span><br/>');
								if (parseFloat(c.properties.price.value[0]) > parseFloat(c.properties.finalPrice.value[0])) {
									html.push('<span style="text-decoration: line-through;">' + window.cem.formatPrice(c.properties.price.value[0]) + '</span><br/>');
									html.push('<span style="color: red; font-weight: bold;">' + window.cem.formatPrice(c.properties.finalPrice.value[0]) + '</span>');
								} else {
									html.push(window.cem.formatPrice(c.properties.price.value[0]));
								}
							html.push('</div>');
						html.push('</div>');
					}
					html.push('<div style="padding-bottom: 5px; clear: both; float: right;">');
					html.push('<a href="/search/' + cgi + '">' + (window.cem.lang == 'fr' ? 'voir tous les produits' : 'see all products') + '</a>');
					html.push('</div>');
				html.push('</div>');

				jQuery('#cem-preview-window')
					.html(html.join(''))
					.css(
						{
							left: trigger.position().left + trigger.width() + 5,
							top: trigger.position().top + trigger.height() / 2 - 50,
							width: (items.length * 127 + 20) + 'px'
						}
					)
					.stopTime('preview')
					.fadeIn(200);
			} else {
				jQuery('#cem-preview-window').fadeOut(200);
			}
		};
		var previewShowEvent = function() {
			var trigger = jQuery(this);
			var clean = trigger.hasClass('cem-preview');
			var id = clean ? this.id : trigger.parent().attr('id')
			var parts = id.split('-');
			var cgi = clean ? '' : window.cem.uri;

			if (parts.length == 2) {
				if (cgi.length > 0) {
					cgi += '&';
				}
				cgi += 'k=+' + parts[1];
			} else if (parts.length == 3) {
				if (cgi.length > 0) {
					cgi += '&';
				}
				cgi += 'a=%2B' + parts[1] + '&v=' + parts[2];
			}
			if (cgi.length > 0) {
				cgi = '?' + cgi;
			}
			if (window.cem.previewCache[id]) {
				previewRenderEvent.call(this, window.cem.previewCache[id], cgi);
			} else {
				// attribute or keyword?
				var search = new Object({
					filters: [
						{ type: 'attribute', mode: 'any', attribute: 'contentType', values: [ 'products' ] }
					],
					scorers: [],
					ranking: [
						{ type: 'property', order: 'desc', property: 'purchaseCounter' }
					]
				});
				var el = this;

				if (parts.length == 2) {
					search.filters.push(
						{ type: 'keyword', mode: 'any', keywords: [ parts[1] ] }
					);
				} else if (parts.length == 3) {
					search.filters.push(
						{ type: 'attribute', mode: 'any', attribute: parts[1], values: [ parts[2] ] }
					);
				}
				jQuery.ajax(
					{
						dataType: "html",
						url: "/ajax/r" + (clean || window.cem.hash.length == 0 ? '' : '?cem=' + window.cem.hash),
						data: jQuery.json.encode(search),
						processData: false,
						type: 'POST',
						success: function(data) {
							window.cem.previewCache[id] = eval('(' + data + ')');
							previewRenderEvent.call(el, window.cem.previewCache[id], cgi);
						}
					}
				);
			}
		};
		var previewHideEvent = function() {
			jQuery('#cem-preview-window')
				.oneTime(
					1000,
					'preview',
					function() {
						jQuery(this).hide(200);
					}
				);
		};
		var previewCancelEvent = function() {
			jQuery(this).stopTime('preview');
		};

		jQuery("body").append('<div id="cem-preview-window" class="cem-popup"/>');
		jQuery(".cem-list .cem-preview, .cem-list .cem-preview-filter, .cem-filters .cem-preview-filter").hover(previewShowEvent, previewHideEvent);
		jQuery('#cem-preview-window').hover(previewCancelEvent, previewHideEvent);

		// guidance tabs
		jQuery(".cem-guidance .tab-button").click(
			function() {
				var parts = this.id.split('-');
				var attribute = parts[parts.length - 1];

				jQuery('#cem-guidance-popup-more').fadeOut(200);

				jQuery(".cem-guidance .tab-button:not(#" + this.id + ")").parent(".tab-on").addClass('tab-off').removeClass('tab-on');
				jQuery(".cem-guidance .tab-button#" + this.id).parent(".tab-off").addClass('tab-on').removeClass('tab-off');

				jQuery(".cem-guidance .tab-container:not(#cem-guidance-tab-" + attribute + ")").hide(50, function() {
					jQuery(".cem-guidance .tab-container#cem-guidance-tab-" + attribute).show(200);
				} );

				jQuery(".cem-guidance .prompt .prompt-text").text(window.cem.prompts[attribute]);

				if (jQuery(this).parent().hasClass('tab-other')) {
					jQuery(".cem-guidance #cem-guidance-bt-more").parent(".tab-off").addClass('tab-on').removeClass('tab-off');

					jQuery('.cem-guidance #cem-guidance-bt-more').html(
						'<img src="/rc/img/icon_plus_small.gif"/>' + jQuery(this).text()
					);
				} else {
					jQuery(".cem-guidance #cem-guidance-bt-more").parent(".tab-on").addClass('tab-off').removeClass('tab-on');

					jQuery('.cem-guidance #cem-guidance-bt-more').html(
						'<img src="/rc/img/icon_plus_small.gif"/>...'
					);
				}
				return false;
			}
		);

		// guidance popup control
		jQuery('.cem-guidance #cem-guidance-bt-more').each(
			function() {
				jQuery('.cem-guidance #cem-guidance-popup-more')
					.fadeOut(200)
					.css(
						{
							position: 'absolute',
							left: jQuery('#cem-guidance-bt-more:parent').position().left + 2,
							top: jQuery('#cem-guidance-bt-more:parent').position().top + 2
						}
					);
			}
		).click(
			function() {
				jQuery('.cem-guidance #cem-guidance-popup-more').fadeIn(200);
				return false;
			}
		);
		jQuery('.cem-guidance #cem-guidance-bt-close').click(
			function() {
				jQuery('.cem-guidance #cem-guidance-popup-more').fadeOut(200);
				return false;
			}
		);

		// guidance escalation form
		jQuery('.cem-guidance #cem-guidance-bt-escalate').click(
			function() {
				jQuery('.cem-guidance').hide(
					100,
					function() {
						jQuery('.cem-escalation').show(200);
					}
				);
				return false;
			}
		);
		jQuery('.cem-escalation #cem-guidance-bt-escalate').click(
			function() {
				jQuery('.cem-escalation').hide(
					100,
					function() {
						jQuery('.cem-guidance').show(200);
					}
				);
				return false;
			}
		);

		// guidance alternative values
		jQuery(".cem-guidance .bt-alternatives").click(
			function() {
				var t = jQuery(this);

				if (t.hasClass('opened')) {
					t.next().hide(
						200,
						function() {
							t.removeClass('opened');
							t.children('img').attr('src', '/rc/img/icon_plus.gif');
						}
					);
				} else {
					t.next().show(
						200,
						function() {
							t.addClass('opened');
							t.children('img').attr('src', '/rc/img/icon_minus.gif');
						}
					);
				}
				return false;
			}
		);

		// guidance suggestions
		jQuery(".cem-guidance .suggestions .bt-choice").click(
			function() {
				var parts = this.id.split('-');

				jQuery(".cem-guidance #cem-choice-" + parts[2]).submit();
				return false;
			}
		);

		// attribute filters
		jQuery(".cem-filters .attribute .header .open, .cem-filters .attribute .others-header .open").click(
			function() {
				var t = jQuery(this);
				var tp = t.parent();

				if (t.hasClass('opened')) {
					tp.next().hide(
						200,
						function() {
							t.removeClass('opened');
							t.children('img').attr('src', '/rc/img/icon_plus.gif');
						}
					);
					if (tp.hasClass('header')) {
						tp.children('.remove').fadeIn(200);
					}
				} else {
					if (tp.hasClass('header')) {
						tp.children('.remove').fadeOut(200);
					}
					tp.next().show(
						200,
						function() {
							t.addClass('opened');
							t.children('img').attr('src', '/rc/img/icon_minus.gif');
						}
					);
				}
				return false;
			}
		);
		jQuery(".cem-filters .attribute .value input, .cem-filters .boolean input").change(
			function() {
				var t = jQuery(this);
				var parts = t.parent()[0].id.split('-');
				var attributeId = parts[1];
				var valueId = parts[2];

				if (this.checked) {
					window.location = '?cem=' + window.cem.hash + '&a=%2B' + attributeId + '&v=' + valueId;
				} else {
					window.location = '?cem=' + window.cem.hash + '&a=-' + attributeId + '&v=' + valueId;
				}
			}
		);

		// refine (all)
		jQuery(".cem-refine #bt-all").click(
			function() {
				var t = jQuery(this);

				if (t.hasClass('opened')) {
					t.parent().next().hide(
						200,
						function() {
							t.removeClass('opened');
							t.children('img').attr('src', '/rc/img/icon_plus.gif');
						}
					);
				} else {
					t.parent().next().show(
						200,
						function() {
							t.addClass('opened');
							t.children('img').attr('src', '/rc/img/icon_minus.gif');
						}
					);
				}
				return false;
			}
		);

		// results
		jQuery(".cem-results .tab-button").click(
			function() {
				var t = jQuery(this);
				var parts = this.id.split('-');
				var section = parts[parts.length - 1];

				jQuery(".cem-results .tab-button:not(#" + this.id + ")").parent(".tab-on").addClass('tab-off').removeClass('tab-on');
				jQuery(".cem-results .tab-button#" + this.id).parent(".tab-off").addClass('tab-on').removeClass('tab-off');

				jQuery(".cem-results .tab-container:not(#cem-results-tab-" + section + ")").hide(1, function() {
					jQuery(".cem-results .tab-container#cem-results-tab-" + section).fadeIn(500);
				} );
				return false;
			}
		);
		jQuery("#cem-results-tab-faqs .bt-faq").click(
			function() {
				var t = jQuery(this);

				if (t.hasClass('opened')) {
					t.next().hide(
						50,
						function() {
							t.removeClass('opened');
						}
					);
				} else {
					t.next().show(
						50,
						function() {
							t.addClass('opened');
						}
					);
				}
				return false;
			}
		);
		// switch unit between cm and inch, kg and lbs
		jQuery(".unitswitch").click(
			function() {
				var parts = this.id.split('_');
				jQuery(this).hide();
				jQuery("#unitswitch_" + (parts[1]=='metric'?'imperial':'metric')).show();
				jQuery(".unitswitch-"+parts[1]).each(
					function() {
						jQuery(this).show();
					}
				)
				jQuery(".unitswitch-"+(parts[1]=='metric'?'imperial':'metric')).each(
					function() {
						jQuery(this).hide();
					}
				)
				return false;
			}
		);
	};

	// format price
	this.formatPrice = function(p) {
		var price = new Number(p).toFixed(2).split('.');
		var i = price[0];
		var f = price[1];

		if (i.length > 3) {
			i = i.substring(0, i.length - 3) + ' ' + i.substring(i.length - 3);
		}

		switch (this.lang) {
		case 'fr':
			return (i + ',' + f + ' $');

		case 'en':
			return ('$' + i + ',' + f);
		}
		return p;
	};

	// enable searchbar
	this.searchEnable = function() {
		if (this.firstBarClick) {
			this.firstBarClick = false;

			jQuery("#searchTxt")
				.css('font-style', 'normal')
				.css('color', 'black')
				.val('');
		}
	};

	// validate searchbar
	this.searchValidate = function() {
		var scope = this;

		jQuery("#search form input").each(
			function() {
				switch (this.name) {
				case 'showAC':
					jQuery(this).val(new String(scope.showAutocomplete));
					break;

				case 'useAC':
					jQuery(this).val(new String(scope.useAutocomplete));
					break;
				}
			}
		);
		this.searchEnable();
		return true;
	};

	// send test search
	this.searchTest = function(query) {
		jQuery("#searchTxt")
			.css('font-style', 'normal')
			.css('color', 'black')
			.val(query);

		jQuery("#search form").submit();
	};

	// validate refine searchbar
	this.refineValidate = function() {
		return (jQuery("#refineTxt").val().length > 0);
	};

	// validate escalation
	this.escalationValidate = function() {
		var form = jQuery(".cem-escalation form")[0];

		if (form['email'].value.length == 0) {
			alert(this.lang == 'fr' ? 'Veuillez inscrire votre adresse courriel' : 'Please enter your email address');
			return false;
		}
		if (!/^([a-zA-Z0-9_.+-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,6})+$/.test(form['email'].value)) {
			alert(this.lang == 'fr' ? 'Veuillez inscrire une adresse courriel valide' : 'Please enter a valid email address');
			return false;
		}
		if (form['firstName'].value.length == 0) {
			alert(this.lang == 'fr' ? 'Veuillez inscrire votre prénom' : 'Please enter your first name');
			return false;
		}
		if (form['lastName'].value.length == 0) {
			alert(this.lang == 'fr' ? 'Veuillez inscrire votre nom de famille' : 'Please enter your last name');
			return false;
		}
		if (form['phone'].value.length == 0) {
			alert(this.lang == 'fr' ? 'Veuillez inscrire votre numéro de téléphone' : 'Please enter your phone number');
			return false;
		}
		return true;
	};

	// compare products
	this.productsCompare = function() {
		var products = [];
	
		jQuery('.cem-results .cem-product-compare').each(
			function() {
				if (this.checked) {
					products.push(this.value);
				}
			}
		);
		if (products.length < 2) {
			alert('${texts.min2}');
		} else if (products.length > 4) {
			alert('${texts.max4}');
		}
		window.location = '/products/compare/' + products.join('/') + '?' + window.cem.uri;
		return false;
	};
} )();

jQuery(document).ready(
	function() {
		try {
			window.cem.init.call(window.cem);
		} catch (e) {
			alert(e);
		}
	}
);
