(function($) {
	var g = window.guidyu;
	var searchParameters = 'customer=' + encodeURIComponent(g.account) + '&l=' + encodeURIComponent(g.language);
	var searchUrl = g.baseUrl + '?' + searchParameters + '&cem_agent_url=' + encodeURIComponent(g.callbackUrl);

	// register frame callback
	g.callback = function(height) {
		if (!g.results.progress || $(g.results.progress).hasClass('guidyu-loaded')) {
			$(g.results.frame).height(height);
		} else {
			$(g.results.progress).addClass('guidyu-loaded').fadeOut(200, function() { $(g.results.frame).hide().height(height).fadeIn(750); } );
		}
	};

	$(document).ready(
		function() {
			var frame = $(g.results.frame);
			var triggerSearch = function(query) {
				if (frame.length > 0) {
					frame.attr('src', searchUrl + '&q=' + encodeURIComponent(query));
				} else {
					window.location = g.searchUrl + '?q=' + encodeURIComponent(query);
				}
			};

			// start searching
			if (frame.length > 0) {
				if (window.location.search.length > 0) {
					$(g.results.frame).attr('src', searchUrl + '&' + window.location.search.substring(1));
				} else {
					$(g.results.frame).attr('src', searchUrl);
				}
			}

			// setup search form
			$(g.searchbar.form).submit(
				function() {
					triggerSearch($(g.searchbar.query).val());
					return false;
				}
			);

			// setup search bar
			$(g.searchbar.query).autocomplete(
				g.baseUrl + 'cem-ac.php?' + searchParameters,
				{
					scrollHeight: 250,
					selectFirst: false,
					autoFill: false,
					cacheLength: 100,
					multiple: false,
					dataType: 'json',
					parse: function(data) {
						return $.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;
	
						case 'content':
							return row.content.title;
						}
					}
				}
			).result(
				function(e, row, value, q) {
					switch (row.type) {
					case 'query':
						triggerSearch($(g.searchbar.query).val());
						break;

					case 'content':
						window.location = g.remoteUrl + row.content.properties.ef_url.value[0];
						break;
					}
				}
			);
		}
	);
})(jQuery);

