window.addEvent('domready', function() {

	setupTabs();
	setupAccordin();
	ac = new AutoCompelete();
	ac.start();
	setupForms();

	/*
	 * if(loadAssets()) { loadAssets(); }
	 */

});

function setupForms()
{
	msgbox  = $('message_form');
	if(msgbox)
	{
			msgbox.addEvent('submit', function(e) {
			e.stop();
			//var log = $('log_res').empty().addClass('ajax-loading');
			this.set('send', {onComplete: function(response) { 
				//log.removeClass('ajax-loading');
				//log.set('html', response);
				res = response.split(':');
				
				alert(res[1]);
				if(res[0]==1)
				{
					msgbox.getParent().destroy();
					return;
				}
				
				
				$('captcha').src = 'captcha/image.jpg?sid=' + Math.random();
				$('captcha_code').value='';
				$('captcha_code').focus();
				
				if(res[2])
				{
					//$(res[2]).addClass('highlight');
					$(res[2]).focus();
					
				}
				
			}});
			this.send();
		});

	}
}



var ac;
var lang_en={'tip':'Start typing your search to see instant results here',
			 'products':'Products',
			 'shops':'Shops',
			 'shop':'Shops',
			 'categories':'Categories',
			 'aed':'AED'
				 
			};

var lang_ar={'tip':'',
			 'products':'المنتجات',
			 'shops':'المحلات',
			 'shop':'محل',
			 'categories':'التصنيفات',
			 'aed':'درهم إماراتي'
			};

var cities_en=['','Abu Dhabi','Dubai','Sharjah','Ajman','UAQ','RAK','Fujairah','Al Ain'];
var cities_ar=['','\u0623\u0628\u0648\u0020\u0638\u0628\u064a','\u062f\u0628\u064a','\u0627\u0644\u0634\u0627\u0631\u0642\u0629','\u0627\u0645\u0020\u0627\u0644\u0642\u064a\u0648\u064a\u0646','\u0627\u0644\u0641\u062c\u064a\u0631\u0629','\u0627\u0644\u0639\u064a\u0646'];
var lang;
var cities;



function AutoCompelete() {

	var myCookie = Cookie.read('lang');
	if(myCookie && myCookie=='ar'){lang=lang_ar;cities = cities_ar;}else{cities = cities_en;lang=lang_en;}

	this.field = $('search-box');
	this.main_container = $('autocomplete');
	this.container = $('auto-results');
	this.statusBar = $('auto-statusbar');
	this.statusLoading = $('auto-loading');		
	this.controller= $('tab-shop');
	if(this.controller.style.display=='none'){this.controller= $('tab-product');}
	this.select_index = null;
	this.select_temp_index=0;
	this.select;
	this.last_query = '';
	this.types=['p','s','c'];
	this.transport = new Request.JSON( {
		url :"auto.php",
		link: "cancel",
		onSuccess : function(json) {
			ac.procesResponce(json)
		}
	});

	this.start = function() {
		
		this.field.set('autocomplete','off');
		
		this.field.addEvent('keydown', function(e) {
			ac.processKeyDown(e)
		});
		this.field.addEvent('keyup', function(e) {
			ac.processKeyUp(e)
		});
		
		this.field.addEvent('focus',function(e){
			if(ac.field.value=='')
				{ac.showTip();}
			else
				{ac.refreshGUI();}
		});
		
		this.field.addEvent('blur',function(e){
			ac.close.delay(300);
		});
		
		this.setupGUI();
	}
	
	this.setupGUI = function(){
		
		

		var div = new Element('div', {
		    'id':   'autocomplete'});
		var results = new Element('div', {
		    'id': 'auto-results'});
		var statusBar = new Element('div',{
			'id':'auto-statusbar'});
		
		results.inject(div);
		statusBar.inject(div,'bottom')
		div.inject($(document.body));


		this.main_container = $('autocomplete');
		this.container = $('auto-results');
		this.statusBar = $('auto-statusbar');
		this.statusLoading = $('auto-loading');		
		
		
		var styles={};
		styles.left=this.controller.getCoordinates().left;
		styles.top= this.controller.getCoordinates().bottom;
		styles.width=this.controller.getCoordinates().width-2;
		this.main_container.setStyles(styles);
		
		
		
		
		
	}

	this.processKeyDown = function(e) {
		key = e.key;
		if (key == 'down') {
			if(this.select_index < (this.select.p.length + this.select.s.length + this.select.c.length-1))
			{
				if(this.select_index==null)
					{this.select_index=0;}
				else
					{this.select_index++;}
			this.refreshSelector();
			}
			
		}
		if (key == 'up') {
			if(this.select_index > 0 ){this.select_index--;this.refreshSelector();}
			
		}
		
		
	}
	this.showTip = function(){
	
		c=this.container;
		c.empty();
		var div = new Element('div', {
		    'class':   'auto-tip',
		    'text':lang['tip']
			});
		div.inject(c);	
	};
	
	this.refreshSelector = function(e)
	{
		if(e != null){this.select_index=e;}
		
		dropdowns = this.container.getElements('div.arow');
		dropdowns.each(function(e,i){
			if(ac.select_index==i)
			{
				e.addClass('auto-active');
			}else
			{
				e.removeClass('auto-active');
			}
		});

		//Update the field with text accoridng to selected index
		i=this.select_index;		
		if(this.select.p==null){pl=0;}else{pl = this.select.p.length;}
		if(this.select.s==null){sl=0;}else{sl = this.select.s.length;}
		if(this.select.c==null){cl=0;}else{cl = this.select.c.length;}
		if(i < pl){this.field.value= this.select.p[i].t;}
		if(i > pl & i < (pl+sl) ){this.field.value= this.select.s[i-pl].t;}
		if(i > (pl + sl) & i < (pl+sl+cl)){this.field.value= this.select.c[i-(pl+sl)].t;}
		
	}
	
	this.processKeyUp = function(e) {
		key = e.key;
		if ((this.last_query != this.field.value) && (key !='up' && key !='down')) {
			this.sendRequest();
		}
	}

	this.sendRequest = function() {
		//this.statusLoading.set('display','block');
		query = this.field.value;
		this.last_query = query;
		if(query.length)
		{
			this.transport.get( {
							'q' :query
				});
		}
		else
		{
			this.showTip();
		}

	}

	this.procesResponce = function(json) {
		//this.statusLoading.set('display','none');
		this.select = json;
		this.select_index=null;
		this.refreshGUI();
	}

	this.refreshGUI = function() {
		c = this.container;
		c.empty();
		this.select_temp_index=0;
		
		if(this.select.p)
		{
			ac.getSeperator(lang['products']).inject(c);
			this.select.p.each( function(e,i) {
				i = ac.select_temp_index;				
					if(ac.select_index ==i){active=1;}else{active=0;}
					ac.getProductList(e,i).inject(c);
				ac.select_temp_index++;
			})
		}

		if(this.select.s)
		{	
			ac.getSeperator(lang['shops']).inject(c);
			this.select.s.each( function(e,i) {
				i = ac.select_temp_index;				
					if(ac.select_index ==i){active=1;}else{active=0;}
					ac.getSimpleList(e,i).inject(c);
				ac.select_temp_index++;
			})
		}
		
		if(this.select.c)
		{	
			ac.getSeperator(lang['categories']).inject(c);
			this.select.c.each( function(e,i) {
				i = ac.select_temp_index;	
					if(ac.select_index ==i){active=1;}else{active=0;}
					ac.getCategoryList(e,i).inject(c);
				ac.select_temp_index++;
			})
		}
		
	 this.getStatusBar().inject(c,'bottom');

	}
	
	this.getSeperator = function(e)
	{
		var div = new Element('div', {
		    'class':   'auto-seperator',
		    'html': e
			});
		
		return div;
	}
	
	this.close = function()
	{
		ac.container.empty();
		
	}
	
	this.getStatusBar = function ()
	{
		var div = new Element('div', {
		    'class':   'auto-status'
			});
		
		/*var loading = new Element('img', {
			'src': 'template/system/public/images/loading1.gif',
			'class': 'auto-loading',
			'id':'auto-loading',
			'events':{'click':function(){alert('Please Wait while the Search Suggestion Loads');}}
				
			});		*/	
		var close = new Element('img', {
			'src': 'template/system/public/images/close.gif',
			'class': 'auto-close',
			'events':{'click':function(){ac.close();}}
				
			});	

		//loading.inject(div,'top');
		close.inject(div,'bottom');
		
		return div;
	}
	
	this.getProductList = function(e,i)
	{
	
		var div = new Element('div', {
		    'class':   'auto-search-pro arow',
		    'events': {'mouseover': function(){ac.refreshSelector(i);}}		
			});
		
		var link = new Element('a', {
		    'href': '?task=product-shops&shop='+e.r+'&product='+e.i,
		    'class': 'auto-shop-name',
		    'html': e.t});
		var img = new Element('img', {'src': 'http://www.uaeshops.com/media/shops/' + e.r + '/products/tiny_' + e.s});	

		img.inject(link,'top');
		link.inject(div);
		
		if(e.p){
			var price = new Element('span',{
									'class':'auto-price',
									'html': lang['aed'] + e.p});
			price.inject(div,'bottom')
		}
		

		
	
		return div;
	}
	
	this.getSimpleList = function(e,i)
	{
	
		var div = new Element('div', {
		    'class':   'auto-shops arow',
		    'events': {'mouseover': function(){ac.refreshSelector(i);}}
			});
		var link = new Element('a', {
		    'href': '?task=view-shops&shop='+e.i,
		    'class': 'auto-shop-name',
		    'html': e.t});
		var city = new Element('span',{
			'class':'auto-city',
			'html':cities[e.z]});
		var category = new Element('a',{
		    'href': '?task=view-category&cat='+e.x,
			'class':'auto-sub-cate',
			'html': e.y});
		
		link.inject(div);
		city.inject(div,'bottom')
		category.inject(div,'bottom')
	
		return div;
	}
	
	this.getCategoryList = function(e,i)
	{
	
		var div = new Element('div', {
		    'class':   'auto-shops arow',
		    'events': {'mouseover': function(){ac.refreshSelector(i);}}
			});
		var parent_cat = new Element('a', {
		    'href': '?task=view-category&cat='+e.j,
		    'class': 'auto-pcat-name',
		    'html': e.u});

		var sep = new Element('span',{
			'class':'auto-cat-sep',
			'html':'&gt;'});	
		
		var cat = new Element('a', {
		    'href': '?task=view-category&cat='+e.i,
		    'class': 'auto-cat-name',
		    'html': e.t});
		
	
		
		var shop_count = new Element('span',{
			'class':'auto-shop-count',
			'html':e.s + ' '+lang['shop']});
		
		if(e.u){
		parent_cat.inject(div);
		sep.inject(div,'bottom');
		}
		cat.inject(div,'bottom');	
		if(e.u){
			shop_count.inject(div,'bottom')
			}
	
		return div;
	}

}

function setupAccordin() {
	// create our Accordion instance
	var myAccordion = new Accordion($('categories'), '.RootCat', '.catlist', {
		opacity :false,
		onActive : function(toggler, element) {
			toggler.addClass('cat-active');
		},
		onBackground : function(toggler, element) {
			toggler.removeClass('cat-active');
		}
	});
}

function setupTabs() {

	tabs = $('navlist1').getElements('li');

	tabs.addEvent('click', function(e) {
		tabs.each( function(e) {
			e.getElement('a').id = null;
			$('tab-' + e.id).setStyle('display', 'none');
		}

		);

		$('tab-' + this.id).setStyle('display', 'block');
		this.getElement('a').id = this.id + '-current';
	})

}
