/**
 * Magento initialization
 *
 * (C) 2011-2012 - Boxalino AG
 */

jQuery.noConflict();

(function($) {
	window._bxa = {
		trackUrl: '/cem/analytics',
		idleUrl: '/cem/analytics/idle',
		track: function(trackParameters, idleParameters) {
			trackParameters = trackParameters || {};
			idleParameters = idleParameters || {};
			try {
				var idleTime = 0;
				var idleTimeout = 10 * 1000;
				var idleTask = function() {
					if (window._bxa.idleUrl) {
						$.get(window._bxa.idleUrl, idleParameters);
	
						idleTime += idleTimeout;
						if (idleTime >= 3600 * 1000) {
							return;
						}
						if (idleTime >= 1800 * 1000) {
							idleTimeout = 300 * 1000;
						} else if (idleTime >= 300 * 1000) {
							idleTimeout = 60 * 1000;
						} else if (idleTime >= 60 * 1000) {
							idleTimeout = 15 * 1000;
						}
						setTimeout(idleTask, idleTimeout);
					}
				};
	
				if (window._bxa.trackUrl) {
					$.get(
						window._bxa.trackUrl,
						trackParameters,
						function(data, status, xhr) {
							try {
								if (data && data.enabled && data.idle) {
									setTimeout(idleTask, idleTimeout);
								}
							} catch (e) { }
						},
						'json'
					);
				}
			} catch (e) { }
		}
	};
	if (window._bxcookie) {
		window._bxa.track();
	}
})(jQuery);

window.boxalinocem = function(formSelector, querySelector, searchUrl, ajaxUrl, parameters) {
	(function($) {
		$(document).ready(
			function() {
				// setup search bar
				$(querySelector, $(formSelector)).cemComplete( {
					opacity: 0.98,
					allowDefaultQuery: $(querySelector, $(formSelector)).attr('allowDefaultQuery') == 'true',
					alwaysSearch: true,
					fillOnHighlight: true,
					allowEmptyQuery: true,
					clearOnSearch: false,

					source: function(query, callback) {
						var cgi = {};

						if (parameters) {
							for (var i in parameters) {
								cgi[i] = parameters[i];
							}
						}
						cgi['query'] = query;
						var xhr = $.ajax( {
							url: ajaxUrl,
							cache: true,
							data: cgi,
							dataType: 'jsonp',
							success: function(data, status, xhr) {
								callback(data);
							},
							error: function(xhr, status, e) {
							}
						} );

						return function() {
							if (xhr) {
								xhr.abort();
							}
						};
					},
					render: function(query, data) {
						var suggestions = $('<ul></ul>').addClass('queries');
						var products = $('<ul></ul>').addClass('products');
						var self = this;

						for (var i = 0; i < data.suggestions.length; i++) {
							var suggestion = data.suggestions[i];

							$('<li></li>')
								.data('index', i)
								.data('value', suggestion.value)
								.html(suggestion.html)
								.hover(
									function() {
										self.highlight('mouse', $(this).data('index'), true);
									},
									function() {
										self.highlight('mouse', -1, true);
									}
								).click(
									function() {
										self.highlight('mouse', $(this).data('index'), true);
										if (self.select('mouse')) {
											self.complete();
										}
									}
								).appendTo(suggestions);
						}
						for (var i = 0; i < data.results.length; i++) {
							var result = data.results[i];

							$('<li></li>')
								.data('index', i)
								.data('value', result.url)
								.html(result.html)
								.hover(
									function() {
										$(this).addClass('highlighted');
									},
									function() {
										$(this).removeClass('highlighted');
									}
								).click(
									function() {
										self.input.val('');
										self.close(true);
	
										window.location = $(this).data('value');
									}
								).appendTo(products);
						}

						this.index = -1;
						this.size = data.suggestions.length;
						this.menu.empty();
						if (data.suggestions.length > 0) {
							this.menu.append(suggestions);
						}
						if (data.results.length > 0) {
							this.menu.append(products);
						}
						return (data.suggestions.length > 0 || data.results.length > 0);
					},
					layout: function(displayed) {
						if (!displayed) {
							var marginTop = 0; //parseInt(this.input.css('margin-top'));
							var marginLeft = 0; //parseInt(this.input.css('margin-left'));
							var borderBottomWidth = parseInt(this.input.css('border-bottom-width'));
							var top = this.input.offset().top + (isNaN(marginTop) ? 0 : marginTop) + this.input.outerHeight() - (isNaN(borderBottomWidth) ? 0 : borderBottomWidth);
							var left = this.input.offset().left + (isNaN(marginLeft) ? 0 : marginLeft);
							var products = $('ul.products li', this.menu);
							var color = this.input.css('color');
							var backgroundColor = this.input.css('background-color');
	
							this.menu.css( {
								'width': products.length * products.outerWidth(true),
								'top': top,
								'left': left
							} );
							if (color != '' && color != 'transparent') {
								this.menu.css('color', color);
							}
							if (backgroundColor != '' && backgroundColor != 'transparent') {
								this.menu.css('background-color', backgroundColor);
							}

							if (this.input.outerWidth() >= this.menu.outerWidth()) {
								this.menu.width(this.input.innerWidth());
							} else if (this.input.outerWidth() < this.menu.outerWidth()) {
								this.menu.prepend($('<div class="cem-autocomplete-border"><div></div></div>'));

								$('div.cem-autocomplete-border div', this.menu).width(
									this.menu.outerWidth() - this.input.outerWidth()
								);
							}
						}
					},
					scroll: function(offset) {
						var queries = $('ul.queries', this.menu);
						var rowHeight = $('li:first', queries).outerHeight();
						var pageSize = parseInt(queries.innerHeight() / rowHeight) + 1;

						this.highlight('keyboard', offset * pageSize);
					},
					highlight: function(source, offset, absolute) {
						var queries = $('ul.queries', this.menu);

						$('li.highlighted', queries).removeClass('highlighted');

						this.highlightSource = source;
						if (absolute) {
							this.index = offset;
						} else {
							this.index += offset;
						}
						if (this.index < 0) {
							if (absolute) {
								this.index = -1;
								this.input.focus();
							} else {
								this.index = 0;
							}
						} else if (this.index >= this.size) {
							this.index = this.size - 1;
						}
						if (this.index >= 0) {
							var selection = $('li:eq(' + this.index + ')', queries);

							if (selection.length == 0) {
								queries.scrollTop(0);
								return;
							}
							selection.addClass('highlighted');

							var scrollPosition = queries.scrollTop();
							var position = selection.position().top;

							if (position < 0) {
								queries.scrollTop(scrollPosition + position);
							} else if (position + selection.outerHeight() > queries.innerHeight()) {
								queries.scrollTop(scrollPosition + position + selection.outerHeight() - queries.innerHeight());
							}

							this.highlightCounter++;
							if (source == 'keyboard' && this.options.fillOnHighlight) {
								this.highlightSource = 'none';
								this.selectCounter++;
								this.input.val(selection.data('value'));
							}
						}
					},
					select: function(source) {
						var selection = $('ul.queries > li.highlighted', this.menu);

						if (selection.length > 0) {
							this.selectCounter++;
						}
						if (source == 'keyboard') {
							if (selection.length == 0 ||
								this.input.val() == selection.data('value') ||
								this.highlightSource == 'mouse' ||
								this.highlightSource == 'none'
							) {
								this.search(this.input.val());
								return false;
							}
						} else if (source == 'mouse') {
							if (selection.length == 0) {
								return false;
							}
							if (this.input.val() == selection.data('value')) {
								this.search(this.input.val());
								return false;
							}
						}
						this.input.val(selection.data('value'));

						if (this.options.alwaysSearch) {
							this.search(this.input.val());
							return false;
						}
						return true;
					},
					search: function(query) {
						if (!this.options.allowEmptyQuery && query.length == 0) {
							return;
						}
						if (!this.options.allowDefaultQuery && query.length > 0 && query == this.defaultValue) {
							return;
						}
						if (this.options.clearOnSearch) {
							this.input.val('');
						}
						this.input.focus();

						var cgi = '?query=' + encodeURIComponent(query);
	
						if (this.selectCounter > 0) {
							cgi += '&ac=' + this.selectCounter;
						}
						window.location = searchUrl + cgi;

						this.highlightCounter = 0;
						this.selectCounter = 0;
					}
				} );

				// setup search form
				$(formSelector).submit(
					function() {
						$(querySelector, this).cemComplete().cemSearch();
						return false;
					}
				);
			}
		);
	})(jQuery);
};

