window.addEvent('load', function() {
	// get the plugin configuration
	var $G = $Gavick['gk_ajax_search'];
	// if form exists
	if($($G['container_id'])) {
		// create an input handler
		var input =$($G['container_id']).getElement('#mod_search_searchword');
		input.setProperty('autocomplete', 'off');
		// create necessary HTML structures
		var html = '<div class="gk_ajax_search_wrap"><div class="gk_ajax_search_total"></div><span class="gk_ajax_search_close">'+$G['lang_close']+'</span><div class="gk_ajax_search_results"></div><div class="gk_ajax_search_more">'+$G['lang_all_results']+'</div></div>';
        var popup = new Element('div', {'id': 'gk_ajax_search'}).setHTML(html);
		popup.injectInside($(document.body));
		popup.setProperty('class','hide');
		// add events to the input and popup
		$('gk_ajax_search').getElement('.gk_ajax_search_more').addEvent('click', function() {
			input.getParent('form').submit();
		});
		
		$('gk_ajax_search').getElement('.gk_ajax_search_close').addEvent('click', function() {
			popup.addClass('hide');
			(function() { popup.setStyle('display', 'none') }).delay(350);
		});
		
		var overPopup = false;
		popup.addEvent('mouseenter', function() { overPopup = true; });
		popup.addEvent('mouseleave', function() { overPopup = false; });
		
		document.body.addEvent('click', function() {
			if(!overPopup) {
				$('gk_ajax_search').getElement('.gk_ajax_search_close').fireEvent('click');
			}
		});
		
		// AJAX request
		var HTMLReq;
		var ajaxRequestTimer = false;
		
		input.addEvent('keydown', function(event) {
			if(
				event.key != 'enter' &&
				event.key != 'up' &&
				event.key != 'down' &&
				event.key != 'left' &&
				event.key != 'right' &&
				event.key != 'delete' &&
				event.key != 'esc') {
				
				if(ajaxRequestTimer) { clearTimeout(ajaxRequestTimer);	}
				if(!input.hasClass('loader')) { input.addClass('loader'); } 
				
				ajaxRequestTimer = (function(){
					HTMLReq = new Ajax('index.php?limit=10&option=com_search&ordering=newest&searchphrase=any&searchword='+input.value+'&tmpl=ajax&view=search&Itemid=9999&limit='+$G['length'], { method: 'get', onComplete: ajaxHandler }); 
                    HTMLReq.request();
					ajaxRequestTimer = false;
				}).delay($G['delay']);
			}
		});
		
		input.addEvent('keyup', function(event) {
			if(
				event.key != 'enter' &&
				event.key != 'up' &&
				event.key != 'down' &&
				event.key != 'left' &&
				event.key != 'right' &&
				event.key != 'delete' &&
				event.key != 'esc') {
				
				if(ajaxRequestTimer) { clearTimeout(ajaxRequestTimer);	} 
				if(!input.hasClass('loader')) { input.addClass('loader'); } 
				
				ajaxRequestTimer = (function(){
                    HTMLReq = new Ajax('index.php?limit=10&option=com_search&ordering=newest&searchphrase=any&searchword='+input.value+'&tmpl=ajax&view=search&Itemid=9999&limit='+$G['length'], { method: 'get', onComplete: ajaxHandler }); 
                   	HTMLReq.request();
					ajaxRequestTimer = false;
				}).delay($G['delay']);
			}
		});
		
		// set position of the popup
		var position = {
			bottom: input.getCoordinates().bottom,
			right: input.getCoordinates().right - 300
		};
		
		popup.setStyles({
			top: position.bottom + "px",
			left: position.right + "px"
		});
	}
    
    function ajaxHandler( html ){
        
		$('gk_ajax_search').getElement('.gk_ajax_search_results').setHTML('');
		$('gk_ajax_search').getElement('.gk_ajax_search_total').setHTML('');
		// hidden wrapper for the results
		var res = new Element('div', {
			'class': 'gkHidden'
		});
        
        res.innerHTML = html;
        res.injectInside(
			$('gk_ajax_search').getElement('.gk_ajax_search_results')
		);
        
	     
		// results
        if(res.getElement('.results')) {
			var counter = res.getElement('.searchintro .search-count');
			$('gk_ajax_search').getElement('.gk_ajax_search_total').innerHTML = counter.innerHTML;
			counter.remove();
			
			[
				'ol.list', 
				'p.search-category', 
				'p.createdate', 
				'p.result-text'
			].each(function(selector){
				res.getElement('.results').getElements(selector).each(function(el, i){
					if(i > $G['length'] - 1) el.remove();
				});
			});
	
			if(res.getElement('.pagination')) res.getElement('.pagination').remove();
            if(res.getElement('.search_limit')) res.getElement('.search_limit').remove();            
           	if(res.getElement('.search_counter')) res.getElement('.search_counter').remove();
			res.getElement('.results').getElement('h3').remove();
			res.getElement('.results').injectInside(
				$('gk_ajax_search').getElement('.gk_ajax_search_results')
			);
		} else {
			var info = new Element('p');
			info.innerHTML = '<strong>'+$G['lang_no_results']+'</strong>';
			info.injectInside(
				$('gk_ajax_search').getElement('.gk_ajax_search_results')
			);	
		}
		// positioning the popup
		var position = {
			bottom: input.getCoordinates().bottom,
			right: input.getCoordinates().right - 300
		};
		
		popup.setStyles({
			top: position.bottom + "px",
			left: position.right + "px"
		});
		
		if(popup.hasClass('hide')) { popup.removeClass('hide'); popup.setStyle('display', 'block'); }
		if(input.hasClass('loader')) { input.removeClass('loader'); } 
    }
    
});
