// Program logic
(function($) {
	var g = window.cem;

	function buildUrlParameters(parameters) {
		var query = '';

		if (parameters) {
			var i = 0;

			for (var key in parameters) {
				if (i++ > 0) {
					query += '&';
				}
				query += encodeURIComponent(key);
				query += '=';
				query += encodeURIComponent(parameters[key]);
			}
		}
		return query;
	}
	function buildUrl(url, parameters) {
		var i = url.indexOf('?');
		var uri = i >= 0 ? url.substring(0, i) : url;
		var query = i >= 0 ? url.substring(i + 1).split('&') : [];
		var kv = {};

		for (var i = 0; i < query.length; i++) {
			var item = query[i].split('=');

			if (item.length == 2) {
				kv[decodeURIComponent(item[0])] = decodeURIComponent(item[1]);
			}
		}
		if (parameters) {
			for (var key in parameters) {
				if (parameters[key] !== null) {
					kv[key] = parameters[key];
				} else {
					delete kv[key];
				}
			}
		}
		query = buildUrlParameters(kv);
		if (query.length > 0) {
			return (uri + '?' + query);
		}
		return uri;
	}

	// compat jquery 1.5
	$.sub = $.sub || function() {
		return $;
	};

	// register cross-domain
	try {
		var domain = window.location.hostname.split('.');

		if (domain.length >= 2) {
			if (!domain[domain.length - 1].match(/^\d+$/)) {
				document.domain = domain.slice(domain.length - 2).join('.');
			}
		}
	} catch (e) { }

	// register frame callback
	g.callback = function(height) {
		if (!g.results.progress || $(g.results.progress).hasClass('cem-loaded')) {
			$(g.results.frame).height(height);
			$(g.detail.frame).height(height);
		} else {
			$(g.results.progress).addClass('cem-loaded').fadeOut(200, function() { $(g.results.frame).hide().height(height).fadeIn(750); } );
		}
		$('div#wrapper').addClass('cem-iframe-loaded').show();
	};
	g.loadResults = function() {
		var frame = $(g.results.frame);

		try {
			if (frame.contents()[0].location.href.indexOf(g.results.url) != 0) {
				frame.attr('src', buildUrl(g.results.url + window.location.search, { gclid: null }) );
			}
		} catch (e) {
			frame.attr('src', buildUrl(g.results.url + window.location.search, { gclid: null }) );

			$('div#wrapper').addClass('cem-iframe-loaded').show();
		}
	};
	g.loadDetail = function() {
		var frame = $(g.detail.frame);

		try {
			if (frame.contents()[0].location.href.indexOf(g.detail.url) != 0) {
				frame.attr('src', g.detail.url + window.location.search);
			}
		} catch (e) {
			frame.attr('src', buildUrl(g.detail.url + window.location.search, { gclid: null }) );

			$('div#wrapper').addClass('cem-iframe-loaded').show();
		}
	};

	$(document).ready(
		function() {
			if ($(g.results.frame).length > 0) {
				if (!$('div#wrapper').hasClass('cem-iframe-loaded')) {
					$('div#wrapper').hide();
				}
			}

			$(g.searchbar.form).submit(
				function() {
					$(g.searchbar.query, this).cemComplete().cemSearch();
					return false;
				}
			);

			// setup auto-completion
			$(g.searchbar.query).cemComplete( {
				source: function(query, callback) {
					var cgi = {};

					cgi['query'] = query;
					var xhr = $.ajax( {
						url: g.searchbar.url,
						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;

					this.index = -1;
					this.size = data.suggestions.length;
					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.menu.empty()
						.css( {
							'top': this.input.offset().top + this.input.outerHeight() - 1,
							'left': this.input.offset().left + (this.input.outerWidth() - this.input.innerWidth()) / 2 - 1,
							'width': 'auto',
							'background-color': this.input.css('background-color')
						} );

					if (data.suggestions.length > 0) {
						this.menu.append(suggestions);
					}
					if (data.results.length > 0) {
						this.menu.append(products);
					}

					if (this.input.outerWidth() > this.menu.outerWidth()) {
						this.menu.css( {
							'width': this.input.outerWidth()
						} );
					} else if (this.input.outerWidth() < this.menu.outerWidth()) {
						$('<div class="cem-autocomplete-border"></div>')
							.append(
								$('<div></div>')
									.css( {
										'width': this.menu.outerWidth() - this.input.outerWidth()
									} )
							)
							.prependTo(this.menu);
					}
					return (data.suggestions.length > 0 || data.results.length > 0);
				},
				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('');
					}

					var cgi = '?query=' + encodeURIComponent(query);

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

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

