(function($) {
	$.autosuggest = function (input, url, obj) {
		/* objects must be declared with "var" because of the posibility of multiple autosuggest objects on one page */
		/* Also, in every child object (callback, display, search, etc. this.objects is a reference to the main object (the above "var objects")) */
		/* If you need the main object while extending this class you may reference it with this.objects in any child class */
		var objects; 

		if (obj.display.innerItems == 'undefined' || !obj.display.innerItems   ){
			throw new Error('display.innerItems must be defined for autosuggesting!');
		}
		if (!obj.callback.call){
			throw new Error('callback.call must be defined for autosuggesting!');
		}

		objects = $.extend({},obj); /* Bilo sto definirano u objektu koji je dobiven ce pregaziti(extendati ovaj objekt)*/

		objects.preLoadItems = obj.preLoadItems || []; /* Napuniti ovaj array sa itemima koji se trebaju prethodno suggestati...proslijedeni callbacku */
		objects.didIPreloadItems = 0;
		
		objects.separator = '---';

		objects.removeOnCallback = objects.removeOnCallback  || 0; // to remove the item from the collection after callback ?
		
		objects.showOnLoad = objects.showOnLoad || 0;
		
		objects.searchDelayTime = 250 ; //miliseconds
		
		objects.hideOnClickOut = objects.hideOnClickOut || 0;
		
		objects.independentList = objects.independentList || 0;
		
		objects.nonSelectOnType = objects.nonSelectOnType || 0;
		
		objects.partialDownload = objects.partialDownload  || 0;
		
		objects.partialDownloadDelayTime = 500 ;// miliseconds
		
		objects.__resultCache = objects.resultCacheOn || [];
		objects.resultCacheOn = objects.resultCacheOn || 0;
		
		objects.__htmlCache = objects.__htmlCache || [];
		objects.htmlCacheOn = objects.htmlCacheOn || 0;
		
		objects.minifyResult = objects.minifyResult || 1;
		objects.decreasedResults = objects.decreasedResults || [];
		
		
		
		objects.partialDownloadVarName  = 'q';
		
		objects.removedItems = []; /* Array koji se puni selectiranim itemima */
		
		objects.typingInProgress = 0;

		objects.JSONDataBlock = obj.JSONDataBlock || 'data'; /*Json block u kojem su itemi*/
		objects.idContainerNumber = obj.idContainerNumber || 'idContainerNumber'; 
		objects.idMatchContainer = obj.idMatchContainer || 'idMatchContainer';
		objects.limit = obj.limit || -1; /* Limit ispisa itema*/
		objects.selectLimit = obj.selectLimit || -1;
		
		objects.downloadOnClick = objects.downloadOnClick || false;
		objects.downloadOnFocus = objects.downloadOnFocus || false;

		objects.element = $(input); // object.element je jQuery referenca na input polje koje se cita

		objects.rawData = null;

		objects.clickArray = [];
	
		objects.optionShowAll = 0;
		
		objects.appendToSelector = objects.appendToSelector  || 'body'  ;

		/* Skup varijabli za pracenje mouseover selecta*/
		objects.currentResult = null;
		objects.displayPositionObject = [];
		objects.displayingElementIndex = 0;
		objects.displayingElementIndexTracker = 0;
		objects.displayingElementIndexMax = 0;
		
		/* Itemi koji se smatraju matchanim*/
		objects.matchedElements = [];

		objects.url = '';
		objects.url = url; /* URL koji treba piknuti za json*/

		objects.searchableField = obj.searchableField ||  []; /* Popis keyeva u json arrayu koji se pretrazuju*/
		objects.defaultShow = obj.deafultShow || objects.searchableField[0]; /* defaultni koji se prikazuje ako nije definirano*/

		/* JS isArray Funkcija */
		objects.isArray = function (variable){
			return (variable instanceof Array);
		}
		
		objects.getQ = function(){
				objects.q = $.trim(objects.element.val()) || '';  /* objects.q je string koji se searcha*/
				return objects.q;
		}

		/* Css klase koje se koriste*/
		objects.resultsClass = obj.resultsClass || 'ac_results'; /*Result box*/
		objects.selectClass = obj.selectClass || 'ac_over'; /* Item*/
		objects.matchClass = obj.matchClass || 'ac_match extend'; /* Selectirani item*/

		objects.containerMatchLettersClass = objects.containerMatchLettersClass || 'ac_matchLetters'; /* Selectirani tekst unutar itema*/
		
		objects.itemElement = objects.itemElement || 'div'
		objects.matchContainer = obj.matchContainer || 'div';
		objects.matchElement = obj.matchElement || 'div';
		objects.containerMatchLetters = obj.containerMatchLetters || 'span';
		objects.bigWrapper = obj.bigWrapper || '';
		
		objects.noDataElement = obj.noDataElement || 0;
		
		objects.tabOn = objects.tabOn || 0;

		objects.resultElementName = 'results';
		
		objects.preHtml = objects.preHtml || '';
		objects.postHtml = objects.postHtml || '';

		/* PRAZAN PRIMJER OBJEKTA ZA COPY/PASTE */
		objects.dummy = $.extend(  { 
				objects : objects,
				data : [],
				download : 
				function() {
				}
		}, objects.dummy );

		objects.internals = $.extend(  { 
		objects: objects,
			hasQ :
			function (){
					if (objects.showOnLoad == 1){
						return 1;
					} else {						
						return (objects.q != '');					
					}
			},

			hideOnClickOut:
			function(){
				return objects.hideOnClickOut;
			},
			
			onType:
			function () {
			},
			onTab:
			function () {
			},
			onBackspace:
			function(){
				
			},
			
			escape:
			function(){
				objects.results.hide();
				
			},
			noData:
			function(){
			}
			
		}, objects.internals );
		/* Callback object, funkcija call se poziva pri odabiru elementa i proslijeduje joj se item objekt, pri koristenju extendat call funckiju da bude unutar try catcha */
		objects.callback = $.extend({

				objects : objects,

				caught :
				function (error) {
					//throw new Error (error);
					window.console.log(error)
				},
				/* Poziva se pri odabiru elementa*/
				call : 
				function(item) {
						objects.element.attr('value', item.id);
				},
				/* Vraca item u collection*/
				returnItem:
				function (item){
					objects.collection.items[item['__PRIMARYKEY']] = item;
				},
			
				/* Poziva se pri odabiru elementa*/
				callback :
				function (item){
					if (objects.removeOnCallback == 1){
						objects.removedItems.push(item);
						objects.collection.remove(item);
					}
				
					objects.display.postShowHook();					
					try{

					if (objects.internals.hasQ() || objects.didIPreloadItems == 0){					
						this.call(item);
					}
					
						if (!objects.results.is(':visible'))
						{
							objects.displayingElementIndexTracker = 0;
						}
					} catch (e) {
					  		objects.callback.caught(e);
					}
				 }
		}, objects.callback );

		/* Handler za tipkanje*/
		objects.handler =  $.extend(  {
				objects : objects,		
				processKey :
					function(e) {
						/* up/down/escape requires results to be visible
						enter/tab requires that AND a result to be selected*/
						if (
								(/27$|38$|40$/.test(e.keyCode)
								&& 
								objects.results.is(':visible')) 
								||
								(/^13$|^9$/.test(e.keyCode)
								 /*&& getCurrentResult()*/)
						){
				            if (e.preventDefault)
				                e.preventDefault();
							if (e.stopPropagation)
				                e.stopPropagation();
		
			                e.cancelBubble = true;
			                e.returnValue = false;
						
							switch(e.keyCode) {
								case 38: /* up*/
									objects.display.prevResult();
									break;
									
								case 40: /*down*/
									objects.display.nextResult();
									break;
									
								case 09:/*tab*/  if (objects.internals.onTab() == 'break' && objects.tabOn) { // ako funkcija ne returna ne okida se callback koji se okida na enter
													 break;
											     } else {
												 }; 
								case 13: /* return*/
									/* Da se ne zbuni kad se koristi istovremeno i tipke i mis*/
									if ($('#' + objects.element.attr('id')+ objects.separator +  objects.idContainerNumber + objects.displayingElementIndexTracker).attr('class') != objects.selectClass ){ 
										try {
											objects.displayingElementIndexTracker = $('.' + objects.selectClass).attr('id').replace(objects.element.attr('id') + objects.separator + objects.idContainerNumber , '');
										} catch (e){
										}
									}
									
									if( objects.results.children(':first-child').attr('class') != objects.selectClass && objects.displayingElementIndexTracker == 0 ){
										objects.callback.caught();
									} else {
										objects.callback.callback(objects.displayPositionObject[objects.displayingElementIndexTracker]);										
									}
/*
									} else {									
										objects.callback.caught();
									}
*/
									objects.displayingElementIndexTracker = 0;

									break;
									
								case 27: /*	escape*/
									objects.internals.escape();
									break;
							}
				}
				/*ako nije stisnuta ni jedna od kontrol tipki*/
				else {
				
					if (e.keyCode == 8){
						objects.internals.onBackspace();
					}
					objects.internals.onType(this.objects);
					objects.getQ();

					if (objects.partialDownload && !objects.typingInProgress ){
						setTimeout(
							function(){
								objects.factory.getArray();
								objects.typingInProgress = 0;

							 }, objects.partialDownloadDelayTime);
						objects.typingInProgress = 1;
					} else {
					/**
					* Ovo samo daje prikaz lagganja pa sam zakomentiro				
					*
					*/
					
						//setTimeout(
							//function(){		
								objects.search.makeMatchedItems();
								objects.display.items();
							//}
						//, objects.searchDelayTime)								
					}
				}
			}
		}, objects.handler );

		/*FACTORY OBJEKT KOJI BARATA SA IZGRADNJOM OTALIH*/
		objects.factory = $.extend(  { 

					objects : objects,
					rawData : [],
					
					/* Ajax download*/
					getArray :
					function (){

						if (objects.collection.items.length == 0 && !objects.partialDownload ){
							$.ajax({
								url:objects.url,
								 type: "POST",
								 dataType: "json",
								 success:	function (data){objects.factory.getData(data)}
							});
						
							/*
							$.getJSON(
								objects.url,
								null,
								function (data){
									objects.factory.getData(data);
								}
							);
							*/
						} else if (objects.partialDownload){
									if (objects.q){
										if (objects.url.indexOf('?')== -1 ){
											andOrQuestionMark = '?';						
										} else {
											andOrQuestionMark = '&';						
										}
										
										$.getJSON(
											objects.url + andOrQuestionMark + objects.partialDownloadVarName + '=' + objects.q,
											null,
											function (data){
											objects.collection.items.length = 0;
												objects.factory.getData(data);
											}
										);
									}
						}
					},
					
					postGetData : function () {
					
						if (objects.showOnLoad == 1){
							objects.handler.processKey(' ');
							objects.element.focus(function(){objects.handler.processKey(' ')})
						}
						
						if (objects.partialDownload){
							objects.display.makeAndShow();
						}
					},
					
					setPreload : function (){
						items = [];
						return items;
				    },
					getData :
					function (data){
						objects.factory.rawData = data[objects.JSONDataBlock];
						objects.factory.arrangeData(objects.factory.rawData);
						
						objects.preLoadItems = objects.factory.setPreload();
						if (objects.preLoadItems.length > 0){
							objects.didIPreloadItems = 0;
								for (oneItem in objects.preLoadItems){
									objects.callback.callback(objects.preLoadItems[oneItem]);
								}
						}
	
						objects.factory.postGetData();
						if (objects.collection.items.length == 0){							
							objects.internals.noData();
						}
						objects.didIPreloadItems = 1;
					},
					/* key-anje i dodavanje Primary vrijednosti*/
					arrangeData :
					function (data){
						for (i in objects.factory.rawData){
						 	oneItem = objects.item.setValues(i, objects.factory.rawData[i]);
						 	oneItem['__PRIMARYKEY'] = i;
						 	
						 	/**
						 	*
						 	*	mijenjanje scarona u š
						 	*
						 	*/
						 	for (oneField in objects.searchableField){
						 		if (oneItem[objects.searchableField[oneField]]){
						 		
						 			if (oneItem[objects.searchableField[oneField]].indexOf('&scaron;')!= -1){
							 			oneItem[objects.searchableField[oneField]] = oneItem[objects.searchableField[oneField]].replace(/&scaron;/, '\u0161');											 			
						 			}
							 		if (oneItem[objects.searchableField[oneField]].indexOf('&Scaron;')!= -1){
							 			oneItem[objects.searchableField[oneField]] = oneItem[objects.searchableField[oneField]].replace(/&Scaron;/, '\u0160');
							 		}
					 			}
						 	}
						 	oneItem['__PRIMARYKEY'] = i;
						 	
						 	objects.collection.add(oneItem);
						}
						return objects.item;
					},
					
					download : 
					function() {
						/*download podataka*/
					if (objects.downloadOnClick){
							objects.element.click(function (){
								objects.factory.getArray();
							}
						)
					}
					if (objects.downloadOnFocus){
							objects.element.focus(function (){
								objects.factory.getArray();
							}
						)
					} 
					if (!objects.downloadOnClick && !objects.downloadOnFocus)
					{
						objects.factory.getArray();
					}
						return objects.collection;
					}
		}, objects.factory );

		/* COLLECTION OBJEKT U KOJEM STOJE SVI ITEMI*/
		objects.collection = $.extend( { 
					objects : 5,
					items : [],
					matchedItems : [],

					addItems:
					function (items){
						$.each(items, function (i){
							objects.collection.add(objects.collection.items[i]);
						});
					},
					
					add : 
					function (element){
						objects.collection.items.push( element);
					},
					/* Privremeno micanje iz arraya*/
					remove :
					function (item){
						try{
						for (key in this.items){
							if ( this.items[key] != null){
								if (this.items[key]['__PRIMARYKEY'] == item['__PRIMARYKEY']){
									//this.items.splice(key,1)
									this.items[key] = null;												
								}
							}
						}
						} catch (e){}
						},
					
					getData :
					function (key) {
						key = key || null;
						if (key === null){
							return this.items[key];
						} else {
							return this.items;
						}
					}
					
		}, objects.collection);
		
		/*OBJEKT ZA JEDAN ITEM*/
		objects.item = $.extend({
					objects : objects,		
					words : [],
					data : [],

					setValues :
					function (key, value) {
						objects.item.data[key] = value;
						return objects.item.data[key];
					},

					getData :
					function (key){
						key = key || null;
						if (key === null){
							return this.data;
						} else {
							return this.data[key];
						}
					}
		}, objects.item );

		/*SEARCH OBJEKT*/
		objects.search =  $.extend({
				objects : objects,
				searchString : '',
				/* Vraca rijeci koje treba pretrazivati kao string odvojen razmacima */
				getSearchString : 
				function (item){
					if (objects.isArray(objects.searchableField)){
						this.searchString = '';
						for (key in objects.searchableField){
							this.searchString  +=  item[objects.searchableField[key]] + ' ';
						}
						return this.searchString;
					} else {
						return objects.searchableField;
					} 
				},

				getItems : 
				function () {
					 $.each(objects.collection.items, 
						 function(i){
							 if (this.matches(objects.matchedItems[i]) && objects.collection.items[i] != null ){
							 	 	objects.matchedItems[i] = objects.collection.matchedItems[i] ;
							 }
						 }
					 );
				},

				startsWithQuery :
				function (word) {
					if 	(
							word.toLowerCase().indexOf(objects.q.toLowerCase()) == 0 
							|| 
							word.toUpperCase().indexOf(objects.q.toUpperCase()) == 0
							
						){
							return true;
						} else {
							return false;
						}
				},
				
				foundInOtherFields :
				function (item){
					for (i in objects.searchableField){
						if (!item[objects.searchableField[i]]) {throw Error('Undefined field in item : "' + objects.searchableField[i]+ '"' )}
						if(
							item[objects.searchableField[i]].toLowerCase().indexOf(objects.q.toLowerCase()) == 0 
							|| 
							item[objects.searchableField[i]].toUpperCase().indexOf(objects.q.toUpperCase()) == 0
							){
								return true;
							} else {
								return false;
							}
						}
				},

				matches :
				function (item){
						objects : objects,
						item.words = item.words || [];
						objects.getQ();
						secondWord = '';

						this.matches.returnItem = {};

								item.words = '';
								item.words = this.getSearchString(item).split(' ');


								$.each(item.words ,  function (oneWord) {
									if (
											(
												objects.internals.hasQ()
											)
											&& 
											(
												objects.search.startsWithQuery(item.words[oneWord])
												|| 
												objects.search.foundInOtherFields(item)
											)
										){		
											objects.search.matches.returnItem = item;
										} else {
									 		objects.returnItem = {};
										}
								});

						if (objects.isArray(objects.searchableField)){
						      if (this.matches.returnItem[objects.searchableField[0]]){
								  return this.matches.returnItem;						
						      } else {
						          return false;
						      }
						} else {
							throw new Error('Searchable fields must be in array format');
						}
					},

					makeMatchedItems:
					function (input){
						
						objects.collection.matchedItems = null;
						objects.collection.matchedItems = [];
						
						limitCounter = 0;
						Q = objects.getQ();
						
						/*
						if (objects.resultCacheOn == 1){
							if (objects.__resultCache[Q] && objects.collection.matchedItems != 0){
								objects.collection.matchedItems = objects.__resultCache[Q] ;
								//Ako ima u kešu postavi to i pici dalje
								return;							
							}						
						}
						*/
						
						/*
						if(objects.minifyResult && objects.decreasedResults.length > 0){
							objects.collection.items = objects.decreasedResults;
						} 
						*/

						$.each(objects.collection.items, function(i){
	
							for (j in objects.collection[i]){
								objects.collection.items[i][j] = objects.collection.items[i][j] || '';
							}
	
						 	if ( limitCounter >= objects.limit && objects.limit != -1){
								return false;
							}

							if (objects.collection.items[i] != null){
							
								if (objects.search.matches(objects.collection.items[i])!= false){								
									limitCounter++;
								 	objects.collection.matchedItems.push(objects.search.matches(objects.collection.items[i]));
								 	
							 	}
							 }
						})
						/*
						if(objects.minifyResult){
							objects.decreasedResults = objects.collection.matchedItems;
						}
						*/
						/*
						objects.__resultCache[Q] = objects.collection.matchedItems;
						*/
					}
		}, objects.search );

		/*DISPLAY OBJEKT*/
		objects.display = $.extend({

					objects : objects,

					offsetTop : obj.offsetTop || 0,
					offsetLeft : obj.offsetLeft || 0,

					resultsTop : function (){return (objects.element.offset().top + objects.element.height() + objects.display.offsetTop) + 'px'},
					resultsLeft : function () {return (objects.element.offset().left + objects.display.offsetLeft ) + 'px'},
					resultsPosition : function () {return 'absolute'},
					resultsWidth : function () {return(/*(objects.element.text().length * 10) || 100 ) */ 300 + 'px')},

			showAll:
			function (){
				if (objects.optionShowAll != 0){
					objects.collection.matchedItems = objects.collection.items;
				}
			},
			
			resetPosition :
			function () {
				if (objects.independentList != 1){
							objects.results.css({
							top: objects.display.resultsTop,
							left: objects.display.resultsLeft,
							position: objects.display.resultsPosition,
							width: objects.display.resultsWidth
						})
				}
			},

			getCurrentResult : 
			function () {
					if (!objects.results.is(':visible')){
						return false;
					}

					objects.currentResult = objects.results.children(objects.matchElement + '.' + objects.selectClass);
					
					if (!objects.currentResult.length){
						objects.displayingElementIndexTracker = 0;
						objects.currentResult = false;
					}
					return objects.currentResult;
			},
			
			selectCurrentResult:
			function(object)
			{
					objects.callback.callback(object);
			}, 

			nextResult :
			function () {
					objects.displayingElementIndexTracker++;

					if (objects.displayingElementIndexTracker == objects.displayingElementIndexMax ){
						objects.displayingElementIndexTracker = 0;
					}
					objects.currentResult = objects.display.getCurrentResult();
				
					if (objects.currentResult){
						objects.currentResult
							.removeClass(objects.selectClass)
							.next()
								.addClass(objects.selectClass);
					} else {
						objects.displayingElementIndexTracker = 0;
						objects.results.children(objects.matchElement + ':first-child').addClass(objects.selectClass);
					}
				},

			prevResult :
			function () {
					objects.displayingElementIndexTracker--;
					if (objects.displayingElementIndexTracker <= 0){
						objects.displayingElementIndexTracker = 0;
					}
 
					objects.currentResult = objects.display.getCurrentResult();
					if (objects.currentResult){
						objects.currentResult
							.removeClass(objects.selectClass)
							.prev()
								.addClass(objects.selectClass);
					} else {

						objects.displayingElementIndexTracker = objects.displayingElementIndexMax - 1 ;
						objects.results.children(objects.matchElement + ':last-child').addClass(objects.selectClass);
					}
				},
			/* Prikaz jednog itema, vecinom vremena  extendati*/
			innerItems :
			function (item){
					divContent = '';
					divContent += item[objects.defaultShow];
					return divContent;
			},
			/* Funkcija za selectiranje teksta*/
			highlight: function (item){

							r = $.extend({}, item);
							if (objects.q.length > objects.selectLimit && objects.q.length > 0 ){ // Drugi dio ifa ubacen 10.09. zbog toga jer je skido prvo slovo u chrome-u, Toni
								$.each(objects.searchableField, function (n){
								
								if (!item[objects.searchableField[n]]) {
									item[objects.searchableField[n]] = '';
								}
								
								pattern = '^' + objects.q + '|(?:\\s)' + objects.q;
									r[objects.searchableField[n]] = item[objects.searchableField[n]].replace(new RegExp(pattern, 'gi'), 
										 function(q) {
										 	if (q.indexOf(' ') == 0){
											 	addSpace = ' ';
										 	} else {
										 		addSpace = '';
										 	} 
											results = '';
											
											if (q != ''){
											
												results = addSpace + '<' + objects.containerMatchLetters + ' class="' + objects.containerMatchLettersClass + '">' + q +  '</span>' ;
											}
											return results;
										}
									);
								});
							}

					return r;
			},
			/*Funkcija koja se okida prije prikazivanja...nije baš da je korisna...*/
			
			postItemRender:
			function(){
			},
			
			outerElementAttributes:
			function (item){
			 return '';
			},
			
			matchedElementAttributes:
			function (item){
			 return '';
			},
			
			preShowHook:
			function (){
				objects.results.show();
			},
			
			/* Izvrsava se poslije callbacka, najbolje za visualne efekte */
			postShowHook:
			function (){
				//objects.results.fadeOut(500);
			},
			
			postEchoHook:
			function(){
			},			
			
			makeAndShow:
			function () {
					objects.search.makeMatchedItems();
					objects.display.items();						
			},
	
			items :
			function (){

					Q = objects.getQ();

					objects.results.hide();
					this.resetPosition();
					this.items.oneItem = [];
					
					
					if (!objects.collection.items){
						return;
					}
						
					if (!objects.collection.items.length  ) {
						objects.results.hide();
						return;
					}

					objects.displayPositionObject = null;
					objects.displayPositionObject = [];
					objects.displayingElementIndex = 0;
					
					html = '' + objects.preHtml;


					objects.display.showAll();

					if (objects.__htmlCache[Q] && objects.htmlCacheOn == 1){
						html = objects.__htmlCache[Q];
					} else {
						$.each(objects.collection.matchedItems, function (i) {
							innerElement = objects.display.innerItems(
											   objects.display.highlight(
												   objects.collection.matchedItems[i]
											   )
										   );
							objects.displayPositionObject[objects.displayingElementIndex++] = objects.collection.matchedItems[i];
							objects.collection.matchedItems[i]['displayI'] = i;
							
							html += 
							
							'<' + objects.itemElement + '  id="' + objects.element.attr('id') + objects.separator + objects.idContainerNumber + i + '"' +  objects.display.outerElementAttributes(objects.collection.matchedItems[i], objects.element.attr('id') + objects.separator + objects.idContainerNumber + i) +  '>\n'
							+
							'<' + objects.matchElement + ' id ="' + objects.element.attr('id') + objects.separator + objects.idMatchContainer + i + '" class = "' + objects.matchClass + '"' + objects.display.matchedElementAttributes(objects.collection.matchedItems[i], objects.element.attr('id') + objects.separator + objects.idMatchContainer + i) + '>\n'
							+
							innerElement
							+
							'</' + objects.matchElement +'>\n'
							+
							'</' + objects.itemElement + '>\n'
							+
							objects.postHtml;
							
							objects.clickArray.push(i);
						});
						
						html += objects.postHtml;
						
					}

					if (objects.collection.matchedItems.length != 0){
						objects.__htmlCache[Q] = html;					
					}
					
					objects.displayingElementIndexMax = objects.displayingElementIndex;

					this.resetPosition();

					this.preShowHook();
					objects.results.html(html);
					this.postEchoHook();

					if (!objects.nonSelectOnType){					
						objects.results
							.children(':first-child').addClass(objects.selectClass);
					}

					objects.results
						.children(objects.matchElement)
						.mouseover(function() {
							objects.results.children(objects.matchElement).removeClass(objects.selectClass);
							$(this).addClass(objects.selectClass);
						})

					if (objects.collection.matchedItems.length == 0){
										objects.results.hide();
					}
						$.each(objects.clickArray, function (i){
							$('#' + objects.element.attr('id')+ objects.separator + objects.idContainerNumber + i)
							.click(function(e) {
									e.preventDefault(); 
									e.stopPropagation();
									objects.display.selectCurrentResult(objects.collection.matchedItems[i]);
							});
						})
						
					if (objects.collection.matchedItems.length == 0 && objects.noDataElement instanceof jQuery){
						objects.noDataElement.appendTo(objects.results);
						objects.results.show();
					}
					objects.display.postItemRender(objects.collection.matchedItems);
				}
		}, objects.display);

		/*CONSTRUCTOR*/
		objects.constructor = $.extend( { 
		
			objects:objects,

			__construct :
			function (){
			
			$(document).ready(function(){ //ovo sve
				if (!objects.searchableField.length){
					throw new Error('You must extend the fields for searching (searchableField)');
				}
				objects.factory.download();
				
				if (objects.element.attr('id')){				
					resultMarker =  objects.element.attr('id');
				} else if (objects.element.attr('name')) {
					resultMarker = objects.element.attr('name');
				} else {
					throw new Error('Input element must have id or name(id is highly recommended)');
				}
	
				el = $('#' + objects.resultElementName + '-' + resultMarker.replace('[]', ''));
				if (el){
					el.remove();
				}
				
				if (!objects.element.attr('id')){
				
					randominium = Math.floor(Math.random(100000) * 1000);
					i = 0;
					while ($('#' + randominium).length > 0){
						i = i + 1;
						randominium = Math.floor(Math.random(100000) * 1000);
						if (i == 1000){
							break;
						}
					}
					objects.element.attr('id' , randominium)					
				}
				
				objects.results = $(document.createElement(objects.matchContainer)).attr('id', objects.resultElementName + '-' + objects.element.attr('id'));
				
				objects.results.addClass(objects.resultsClass).appendTo(objects.appendToSelector);
	
				try {
					//objects.results.bgiframe(); // disablano
				} catch(e) {}
				
					/*Disablanje entera*/
					objects.element.keypress(
					function (e){
							if(e.which == 13){
							          return false;
							} else {
							          return true;
							     }
					});
					
					if (objects.tabOn){
						objects.element.keyup(objects.handler.processKey);	
						objects.element.keypress(function () {objects.element.keyup()});	
						
					} else {					
						objects.element.keyup(objects.handler.processKey);	
					}

					objects.element.attr('autocomplete', 'off');

					objects.display.items();

					$(window)
						.load(objects.display.resetPosition) /*just in case user is changing size of page while loading*/
						.resize(objects.display.resetPosition);
					
					if (objects.internals.hideOnClickOut()){
						$('body').click(function(){objects.results.hide();})
					}
				}) //ovo sve
			}()
		}, objects.constructor);
return this;
}

$.fn.autosuggest =  function(url, obj) {
			this.each(function() {
				new $.autosuggest(this, url, obj);
			});
			return this;
	}
})(jQuery);