(function($) {
	
	$.fn.autoSuggest = function(options) {
		var defaults = {
			pathPrefix: "",
			dataSource: "/files/Accraply-NEW/FileCabinet/Data_searchProduct_3290",
			defaultText: "Search ...",
			COOKIE_NAME: "language",
			callbackFunction: function callback(item) { window.location = item.url; }
		};
		var options = $.extend(defaults, options);
		
		$(".lang").click(function() {
			if(this.id != "en") {
				$.getJSON(options.pathPrefix+options.dataSource+"-"+this.id+".txt",
					function(data){
						obj.jsonSuggest(data, {maxResults:20, onSelect:options.callbackFunction});
					}
				);
			}
		});
		
		return this.each(function() {
			obj = $(this);
			
			// This sets the default text value of the input box 
			obj.val(options.defaultText);
			
			// This function removes the default value from the input box
			obj.focus(function() {
				if(this.value == options.defaultText) {
					$(this).val("");
				}
			});
			
			// This function re-inserts the default value into the input box if no text is entered
			obj.blur(function() {
				if(this.value == "") {
					$(this).val(options.defaultText);
				}
			});
			
			$.getScript(options.pathPrefix+"http://www.barry-wehmiller.com/custom/bwc/Accraply/js/jQuery-1.3.1/plugins/jsonSuggest/jquery.jsonSuggest.js", function() { 
				$.getScript(options.pathPrefix+"http://www.barry-wehmiller.com/custom/bwc/Accraply/js/jQuery-1.3.1/plugins/jsonSuggest/json2.js", function() { 
					$.getScript(options.pathPrefix+"http://www.barry-wehmiller.com/custom/bwc/Accraply/js/jQuery-1.3.1/plugins/jquery.cookie.js", init()); 
				});
			});

			// This function does the autosuggest
			function init() {
				try {
					if($.cookie(options.COOKIE_NAME) != null) {
						lang = $.cookie(options.COOKIE_NAME);
						$.getJSON(pathPrefix+options.dataSource+"-"+lang+".txt",
							function(data){
								obj.jsonSuggest(data, {maxResults:20, onSelect:options.callbackFunction});
							}
						);
					} else {
						$.getJSON(pathPrefix+options.dataSource+".txt",
							function(data){
								obj.jsonSuggest(data, {maxResults:20, onSelect:options.callbackFunction});
							}
						);
					}
				} catch(err) {
					$.getJSON(options.pathPrefix+options.dataSource+".txt",
						function(data){
							obj.jsonSuggest(data, {maxResults:20, onSelect:options.callbackFunction});
						}
					);
				}
			}
		});
	};

})(jQuery);