(function($) {
	// static constructs
	$.youplanet = $.youplanet || {};
	
	$.youplanet.globalsearch = {
		conf: {
			type: 'All',
			follow: false,
			update_fields: false,
			actions: null,
			search_url: '/searchglobal',
			default_text: 'Begin Your Search Here',
			create: {
				city: null,
				place: null
			},
			api: false
		},
		init: function() {
			$('input#search').live('focusin', function(a) {
				$(this).YpGlobalSearch({
					type: 'All',
					follow: true,
					actions: 'not_found add_new_country_city'
				});
			});
		},
		createCity: function() {
			if(!$.youplanet.globalsearch.conf.create.city) {
				pleaseLogin();
			}
			else {
				$.youplanet.overlay.click({}, { url: $.youplanet.globalsearch.conf.create.city });
			}
		},
		createPlace: function() {
			if(!$.youplanet.globalsearch.conf.create.place) {
				pleaseLogin();
			}
			else {
				$.youplanet.overlay.click({}, { url: $.youplanet.globalsearch.conf.create.place });
			}
		}
	};
	
	function _YpGlobalSearch(sel, conf) {
		var o = $(this);
		var d = $(sel);
		var node = d; // do zmiany na d
		var c = conf;

		$.extend(o, {
			cache: {},
			request: null,
			showingItems: false,
			loadingElement: null,
			bind: function() {
				d.attr('autocomplete', 'off');
				d.data('inputVal', d.val());
				
				var acconf = {
					position: {
						offset: '-49 0'
					},
					source: $.proxy(function(j,g) {
						if(o.request) {
							o.request.abort();
						}
						
						o.loading(true);
						
						//if(!o.showingItems) {
						//	d.data('autocomplete').response([{
						//		label: '<div class="message">Searching ...</div>'
						//	}]);
						//}
						
						var l = $.trim(j.term).toLowerCase().replace(/\s{2,}/g, ' ') + '_' + c.type;
						
						if(!o.cache[l]) {
							var k = {
								term: j.term,
								v: (new Date().valueOf())
							};
							
							if(c.type){
								k.type = c.type;
							}

							o.request = $.ajax({
								url: c.search_url,
								dataType: 'json',
								data: k,
								success: $.proxy(function(m) {
									o.dataSuccess(j.term, m, g, false);
									o.cache[l] = m;
								}, o),
								complete:$.proxy(o.dataComplete, o)}
							);
						}
						else {
							o.dataSuccess(j.term, o.cache[l], g, true);
							o.dataComplete();
						}
					}, o),
					delay: 250
				};
				
				var a=/[-\/()\\'";:,.!?=+`~@\[\]]/g;
				
				d.autocomplete(acconf).data('autocomplete')._renderItem = function(h, i) {
					var g = i.label;

					if(i.data != undefined) {
						var f = i.label.replace(new RegExp("("+o.escapeRegExp($.trim(d.val().replace(a, ' '))).replace(/\s+/g, "|") + ")", "ig"), '<strong>$1</strong>');
						var g = '<a><span class="search_global_list_icon_' + i.data.type.toLowerCase() + ' search_global_list_icon">';
						
						if(i.data.img) {
							g += '<img class="search_global_list_image" src="' + i.data.img + '" />';
						}
						
						g += '</span>' + f + '</a>';
					}
					
					return $('<li>').data('item.autocomplete', i).append(g).appendTo(h);
				};
				
				d.data('autocomplete').abortRequest = $.proxy(function(){
					if(o.request) {
						o.request.abort();
					}
				}, o);
				
				d.bind('autocompletechange', function(f, g) {
					if(d.val() == '') {
						d.trigger('autocomplete:clear', f, g);
					}
				}).bind('blur', $.proxy(function(f) {
					if(d.val() == '') {
						d.trigger('autocomplete:clear', f, null);
						d.val(c.default_text);
					}
					
					if(o.request) {
						o.request.abort();
					}
					
					o.loading(false);
					o.showingItems = false;
				}, o)).bind('keydown', function(f) {
					if(f.keyCode == 9 || f.keyCode == 13) {
						if(d.val() && d.hasClass("submit_on_enter") && ((!d.data('autocomplete:has_value') && d.hasClass('autocomplete_freetext')) || !d.hasClass('autocomplete_freetext'))) {
							d.closest('form').submit();
						}
						
						return false
					}
				}).bind('keyup', function(f) {
					if(d.val() != d.data('inputVal')) {
						d.trigger('autocomplete:clear');
					}
				}).bind('focus', function(f) {
					/*if(!d.val()) {
						setTimeout(function() {
							d.data('autocomplete').response([{
								label: '<div class="message">' + c.default_text + '</div>'
							}])
						}, 10);
					}*/
					if(c.default_text == d.val()) {
						d.val('');
					}
				}).bind('mousedown', function(f, g) {
					if(d.val() && d.val() != d.data('inputVal')) {
						d.data('autocomplete')._search(d.val());
					}
				}).bind('autocompleteselect', function(g, h) {
					d.data('autocomplete:has_value', true);
					
					//var f = '/search/autocompleteselect/' + d.attr('id');
					//_gaq.push(['_trackPageview', f]);
				}).bind('blur', function(f, g) {
					d.data('autocomplete:has_value', false);
				});
				
				if(c.follow){
					d.bind('autocompleteselect', function(f, g) {
						location.href = g.item.data.url;
					});
				}
				
				if(c.update_fields) {
					o.createUpdateField(d);
				}
			},
			dataSuccess: function(dd, f, a, e){
				if(f != null) {
					var cc = $.map(f, function(h) {
						return {
							data: h,
							value: h.name,
							label: h.name
						}
					});
				
					if(c.actions) {
						$.each(c.actions.split(' '), $.proxy(function(i, k) {
							if(k == 'not_found' && !f.length) {
								cc.push({
									label: '<div class="message">Sorry, no direct matches, hit the “Enter” key for broad search.</div>'
								});
							}
							if(k == 'add_new_country_city') {
								cc.push({
									label: '<div class="message">Can’t find what you are looking for?<br />' +
										'Add a new <span onclick="jQuery.youplanet.globalsearch.createCity()" class="link-city">city</span>' +
										' or a <span onclick="jQuery.youplanet.globalsearch.createPlace()" class="link-city">place</span> yourself!</div>'
								});
							}
						}, o));
					}
				
					a(cc);
				
					//if(!e && dd.length >= 3) {
					//	var b = '/globalsearch?paginate=false&term=' + dd;
					//	_gaq.push(['_setCustomVar', 3, 'Fetch_Type', 'AJAX', 3]);
					//	_gaq.push(['_trackPageview', encodeURIComponent(b)]);
					//}
				
					o.showingItems = true;
				}
			},
			dataComplete: function() {
				o.loading(false);
				o.request = null;
			},
			loading: function(b) {
				if(!b && !o.loadingElement) {
					return;
				}
				
				if(b) {
					if(!o.loadingElement) {
						o.loadingElement = $('<span>', { 'class': 'ui-autocomplete-loader'}).insertAfter(node);
						
						var a = node.position();
						
						a.left += node.outerWidth() - o.loadingElement.outerWidth() + 36;
						a.top += ((node.outerHeight() - o.loadingElement.outerHeight()) / 2) + 26;
						o.loadingElement.css(a);
					}
					else {
						o.loadingElement.show();
					}
				}
				else {
					o.loadingElement.hide();
				}
			},
			createUpdateField: function(a) {
				a.bind('autocompleteselect', function(cc, e) {
					var b = $.parseJSON(c.update_fields);
					
					for(var dd in b) {
						var f = b[dd];
						
						if(f && e.item.data && e.item.data[dd]) {
							$(f).val(e.item.data[dd]);
						}
					}
				});
			},
			escapeRegExp: function(a){
				return a.replace(/([-.*+?^${}()|[\]\/\\])/g, "\\$1");
			}
		});
		
		o.bind();
		o.loading(true);
	}
	
	$.fn.YpGlobalSearch = function(conf) {
		var f = null;
	    if(this.eq(0).data('YpGlobalSearch')){
	    	return this.eq(0).data('YpGlobalSearch');
	    }
	    
		conf = $.extend(true, {}, $.youplanet.globalsearch.conf, conf || {});

		this.each(function() {
			f = new _YpGlobalSearch(this, conf);
			$(this).data('YpGlobalSearch', f);
		});

		return conf.api?f:this;
	}
})(jQuery);

