
var Directory = Class.create();

Directory.prototype = {

	vCardURL: vCardURL,
	queryURL: queryURL,
	logoURL: logoURL,
	adThumbURL: adThumbURL,
	adFullURL: adFullURL,	

	bizCardFrontThumbURL: bizCardFrontThumbURL,
	bizCardFrontFullURL: bizCardFrontFullURL,
	bizCardBackThumbURL: bizCardBackThumbURL,
	bizCardBackFullURL: bizCardBackFullURL,
	
	selectedCity: '',
	selectedState: '',
	selectedZIP: '',
	selectedDistance: '',

	lastRequest: 0,
	currentCat: 0,

	newEl: function(type,cname,parent,hide,innerHTML){

		var e = $(document.createElement(type));
		e.className = cname;
		if(hide){
			e.hide();
		}
		if(innerHTML){
			e.innerHTML = innerHTML;
		}
		parent.appendChild(e);
		return e;
	},
				  
	initialize: function(handle) {

		this.selectedState = $F('selected_state');
		this.selectedZIP = $F('selected_zip');
		
		this.selectedDistance = $F('selected_distance');

		this.handle = handle;

		this.directoryInstance = this.handle.id;
		window[this.directoryInstance] = this;	
		
		this.global = ($F('global')=='1');

		/*
		this.ichiHeader = this.newEl('div','categoriesHeader',this.handle);
		this.niHeader = this.newEl('div','businessesHeader',this.handle);
		this.sanHeader = this.newEl('div','businessHeader',this.handle);
		*/

		this.ichi = this.newEl('div','categories container',this.handle);
			this.ichiFilter = this.newEl('div','filter',this.ichi);
				this.ichiFilterText = this.newEl('span','filterText',this.ichiFilter, false, 'filter: ');
			
				this.ichiFilterField = this.newEl('input','filterField',this.ichiFilter);
				this.ichiFilterField.observe('keyup', function(){
					this.getJson(this.queryURL, 1, 0);
				}.bind(this));
			
			this.ichiContent = this.newEl('div','dirContent',this.ichi,true);
			this.ichiLoader = this.newEl('div','loader',this.ichi,true);
			
		this.ni = this.newEl('div','businesses container',this.handle);
			this.niFilter = this.newEl('div','filter',this.ni);
				this.niFilterText = this.newEl('span','filterText',this.niFilter, false, 'filter: ');
					
				this.niFilterField = this.newEl('input','filterField',this.niFilter);
				this.niFilterField.observe('keyup', function(){
					this.getJson(this.queryURL, 2, this.currentCat);
				}.bind(this));
								
			this.niContent = this.newEl('div','dirContent',this.ni);
			this.niLoader = this.newEl('div','loader',this.ni,true);

		this.san = this.newEl('div','business container',this.handle);
			this.sanLoader = this.newEl('div','loader',this.san,true);
			this.sanContent = this.newEl('div','sanContent vcard',this.san,true);
			
				this.logo = this.newEl('img','logo',this.sanContent,true);
				
				this.bizNameLabel = this.newEl('div','bizNameLabel label',this.sanContent,true, 'name: ');
				this.bizName = this.newEl('div','bizName info fn org nickname n',this.sanContent,true,'unspecified');

				this.phoneLabel = this.newEl('div','phoneLabel label',this.sanContent,true, 'phone: ');
				this.phone = this.newEl('div','phone info tel work voice',this.sanContent,true);

				this.faxLabel = this.newEl('div','faxLabel label',this.sanContent,true, 'fax: ');
				this.fax = this.newEl('div','info tel fax work',this.sanContent,true);

				this.adrLabel = this.newEl('div','adrLabel label',this.sanContent,true,'address: ');
				this.adr = this.newEl('div','info adr work',this.sanContent);
				
					this.address1 = this.newEl('div','address1 street-address',this.adr,true);
					this.address2 = this.newEl('div','address2 street-address',this.adr,true);
					this.address3 = this.newEl('div','address3',this.adr);
					
						this.city = this.newEl('span','city locality',this.address3,true);
						this.stateComma = this.newEl('span','',this.address3,true,', ');
						this.state = this.newEl('span','state region',this.address3,true);
						this.countryComma = this.newEl('span','',this.address3,true,', ');						
						this.country = this.newEl('span','country',this.address3,true);						
						this.zip = this.newEl('span','zip postal-code',this.address3,true);

				this.mapContainer =  this.newEl('div','mapContainer',this.sanContent);
					this.map =  this.newEl('a','map info',this.mapContainer,true);
					this.map.setAttribute('target','_blank');

				this.emailLabel = this.newEl('div','emailLabel label',this.sanContent,true,'email: ');
				this.email =  this.newEl('a','email info',this.sanContent,true);
				
				this.urlLabel = this.newEl('div','urlLabel label',this.sanContent,true,'website: ');
				this.url =  this.newEl('a','url info',this.sanContent,true);

				this.vCardContainer = this.newEl('div','vCardContainer',this.sanContent);
					this.vCard = this.newEl('a','vCard info',this.sanContent,true);

				this.bizCardContainer = this.newEl('div','bizCardContainer',this.sanContent);
					this.bizCardLabel = this.newEl('span','bizCardLabel',this.bizCardContainer,true,'Click to see our business card:<br/>'); 

					this.bizCardFrontLink = this.newEl('a','bizCardFrontLink',this.bizCardContainer,true);
						this.bizCardFront = this.newEl('img','bizCardFront',this.bizCardFrontLink);
						
					this.bizCardBackLink = this.newEl('a','bizCardBackLink',this.bizCardContainer,true);
						this.bizCardBack = this.newEl('img','bizCardBack',this.bizCardBackLink);
			
				this.htmlArea = this.newEl('div','htmlArea',this.sanContent);
			
				this.adContainer = this.newEl('div','adContainer',this.sanContent);
					this.adLabel = this.newEl('span','adLabel',this.adContainer,true,'Click to see our print ad:<br/>'); 

					this.adLink = this.newEl('a','adLink',this.adContainer,true);
						this.ad = this.newEl('img','ad',this.adLink);
					
		this.lgc = this.newEl('a','lgc',this.handle);
			this.lgc.setAttribute('href','http://littlegreencube.com');
			this.lgc.setAttribute('target','_blank');

		this.getJson(this.queryURL,1,0);
	
	},
	
	emptyCont: function(cont){
		document.getElementsByClassName('listItem',cont).each(Element.hide);		
		document.getElementsByClassName('noresults',cont).each(Element.hide);
	},
	
	ichiLoadDelay: null,
	niLoadDelay: null,
	sanLoadDelay: null,
		
	showLoader: function(cont){
		
		if(cont=='ichi'){
			this.ichiContent.hide();
			this.hideLoader('ichi');
			this.ichiLoadDelay = window.setTimeout("window['"+this.directoryInstance+"'].ichiLoader.show()",500);
		}
		
		if(cont=='ni'){
			this.niContent.hide();
			this.hideLoader('ni');
			this.niLoadDelay = window.setTimeout("window['"+this.directoryInstance+"'].niLoader.show()",500);
		}
		
		if(cont=='san'){
			this.sanContent.hide();
			this.hideLoader('san');			
			this.sanLoadDelay = window.setTimeout("window['"+this.directoryInstance+"'].sanLoader.show()",500);
		}	
		
	},
	
	
	hideLoader: function(cont){
		if(cont=='ichi'){
			this.ichiLoader.hide();
			window.clearTimeout(this.ichiLoadDelay);
		}
		if(cont=='ni'){
			this.niLoader.hide();
			window.clearTimeout(this.niLoadDelay);
		}
		if(cont=='san'){
			this.sanLoader.hide();
			window.clearTimeout(this.sanLoadDelay);
		}	
	},
	
	getJson: function(url,level,val){

		var params='';

		if(level==1){
			this.emptyCont(this.ichiContent);
			this.showLoader('ichi');
						
			this.lastRequest++;
						
			params = this.global? 'countries='+val : 'cities='+this.selectedCity+'&state='+this.selectedState+'&zip='+this.selectedZIP+'&distance='+this.selectedDistance;
		
			params += '&request='+this.lastRequest+'&filter='+this.ichiFilterField.value;
		}

		if(level == 2){
			this.emptyCont(this.ni);
			this.showLoader('ni');
			
			this.sanContent.hide();
			this.hideLoader('san');

			this.lastRequest++;			
			
			params = this.global? 'country='+val : 'city='+this.selectedCity+'&state='+this.selectedState+'&zip='+this.selectedZIP+'&distance='+this.selectedDistance;
			params +='&request='+this.lastRequest+'&filter='+this.niFilterField.value;
		}

		if(level == 3){
			this.showLoader('san');

			this.lastRequest++;
			params='business_id='+val+'&request='+this.lastRequest;
		}

		new Ajax.Request(url, {
			method: 'get',
			parameters: params,
			onSuccess: function(t) {
				j = eval("("+t.responseText+")");
				this.parseResponse(j);
			}.bind(this)
		});
	},
	
	
	changeActive: function(container,newActiveEvt){

		//clear all active classes
		var activeLinks = document.getElementsByClassName('listItem',container);
		activeLinks.each(function(e,i){
			e.removeClassName('active');
		});
		
		//add active class to this item
		$(Event.element(newActiveEvt)).addClassName('active');

	},

	parseResponse: function(j){

		var res = {};
		var cont = {};
		var level = 0;		

		if( j.categories ){
			res = j.categories;
			cont = this.ichiContent;
			level = 1;
		}
		if( j.businesses ){
			res = j.businesses;
			cont = this.niContent;
			level = 2;
		}
		if( j.business ){
			res = j.business;
			cont = this.sanContent;
			level = 3;
		}
		
		if(j.request_id != this.lastRequest){
			return false;
		}

		if(level == 2){
			this.emptyCont(this.niContent);
		}

		this.hideLoader('ichi');
		this.hideLoader('ni');
		this.hideLoader('san');


		if(level < 3){
			
			if(res.length>0){
				
				if(level==1){
	
					var sp = this.newEl('a','listItem showAll',cont);
					sp.setAttribute('href', 'javascript:;');
					sp.innerHTML = 'All Dealers';
					sp.observe('click', function(evt){

						this.selectedCity='';
						if(this.selectedZIP){
							this.selectedState='';	
						}

						this.currentCat = 0;
						this.changeActive(cont,evt);
						this.getJson(this.queryURL, level+1, 0);

					}.bind(this));
				}
				
				res.each( function( e, i ){
													   
					var cname = ( (i+1) % 2 == 0 )? 'listItem' : 'listItem';
					var lnk = (level == 2)? e.business_id : e.city;
					var text = (level == 2)? e.business : e.city + (e.state? ', '+e.state : '');

					if (text!='' || lnk!=''){ 
						
						var sp = this.newEl('a',cname,cont);
						sp.setAttribute('href', 'javascript:;');
						sp.innerHTML = text;
						sp.observe('click', function(evt){

							if(e.city){
								this.selectedCity = e.city;
							}
							if(e.state){
								this.selectedState = e.state;
							}
	
							if(level==1){
								this.currentCat = lnk;
							}
							this.changeActive(cont,evt);
							
							this.getJson(this.queryURL, level+1, lnk);
						}.bind(this));
					}
					
				}.bind(this)); 
			
			}else{
				var sp = this.newEl('div','noresults',cont);
				sp.innerHTML = 'No results found.';
			}
			
			if(level == 1){
				this.ichiContent.show();
			}
			if(level == 2){
				this.niContent.show();
			}

		} else {
			this.buildSanContent(j);
		}
	},
	
	replaceInfo: function(container, text, label, href, prefix){
		
		container.hide();
		if(label != this.adrLabel && label != ''){
			label.hide();
		}

		container.innerHTML = '';
		container.setAttribute('href','');

		if(text != null && text != ''){
		
			prefix = (prefix != null && prefix !='')? prefix : '';
		
			container.innerHTML = prefix + text;
			
			if(href != null && href !=''){
				container.setAttribute('href',href);
			}

			container.show();

			if(label != ''){
				label.show();
			}
		}
	},
	
	replaceImage: function(lnk, img, condition, thumbURL, fullURL, business_id, label){
		
		if(condition==1){
			img.setAttribute('src', thumbURL + '/' + business_id + '.jpg');
			lnk.setAttribute('href', fullURL + '/' + business_id + '.jpg');
			lnk.setAttribute('rel', 'lightbox');

			myLightbox.updateImageList();

			lnk.show();
			
			if(label != null){
				label.show();
			}
			
		}else{
			img.setAttribute('src', '');
			lnk.setAttribute('href', '');
			lnk.setAttribute('rel', '');
			lnk.hide();
			
			if(label != null){
				label.hide();
			}			
		}		
	},
		
	buildSanContent: function(j) {
		
		this.sanContent.hide();
		this.adrLabel.hide();
		
		var v = j.business[0];
		
		this.replaceInfo(this.bizName, v.business, this.bizNameLabel);
		this.replaceInfo(this.address1, v.address1, this.adrLabel);
		this.replaceInfo(this.address2, v.address2, this.adrLabel);
		this.replaceInfo(this.city, v.city, this.adrLabel);
		
		if(v.state != ''){
			this.stateComma.show();
		}else{
			this.stateComma.hide();			
		}
		this.replaceInfo(this.state, v.state, this.adrLabel);

		if(v.country != ''){
			this.countryComma.show();
		}else{
			this.countryComma.hide();
		}
		this.replaceInfo(this.country, v.country, this.adrLabel);
		this.replaceInfo(this.zip, v.zip, this.adrLabel,'','&nbsp;&nbsp;');
		this.replaceInfo(this.phone, v.phone, this.phoneLabel);
		this.replaceInfo(this.fax, v.fax, this.faxLabel);
		this.replaceInfo(this.email, v.email, this.emailLabel, 'mailto:' + v.email );
		
		this.replaceInfo(this.htmlArea, v.html_area,'');

		this.replaceImage(this.adLink, this.ad, v.has_ad, this.adThumbURL, this.adFullURL, v.business_id, this.adLabel);
		this.replaceImage(this.bizCardFrontLink, this.bizCardFront, v.has_bc_front, this.bizCardFrontThumbURL, this.bizCardFrontFullURL, v.business_id, this.bizCardLabel);
		this.replaceImage(this.bizCardBackLink, this.bizCardBack, v.has_bc_back, this.bizCardBackThumbURL, this.bizCardBackFullURL, v.business_id, this.bizCardLabel);

		//Logo
		this.logo.hide();
		if(v.has_logo==1){
			this.logo.setAttribute('src', this.logoURL + '/' + v.business_id + '.jpg');
			this.logo.show();
		}
		
		
		//Map Link
		this.replaceInfo(this.map, '', this.adrLabel, '');
		if(v.address1 != '' && v.city != '' && v.state != ''){

			var mapurl = "http://maps.google.com/maps?q=";
			mapurl += encodeURIComponent(v.address1 + ' ' + v.city + ' ' + v.state);

			this.replaceInfo(this.map, 'map', '', mapurl);
		}
		
		
		//Website Link
		this.replaceInfo(this.url, '', this.urlLabel, v.url);
		if(v.url != ''){
			var newURL = v.url;
			
			if(v.url.substring(0,4) != 'http'){
				newURL = 'http://' + v.url;
			}
			this.replaceInfo(this.url, v.url, this.urlLabel, newURL);
		}


		//vCard
		var vcurl = this.vCardURL + '?';
		vcurl += 'business='+encodeURIComponent(v.business);
		vcurl += '&address1='+encodeURIComponent(v.address1);
		vcurl += '&address2='+encodeURIComponent(v.address2);
		vcurl += '&city='+encodeURIComponent(v.city);
		vcurl += '&state='+encodeURIComponent(v.state);
		vcurl += '&zip='+encodeURIComponent(v.zip);
		vcurl += '&country='+encodeURIComponent(v.country);
		vcurl += '&phone='+encodeURIComponent(v.phone);
		vcurl += '&fax='+encodeURIComponent(v.fax);
		vcurl += '&email='+encodeURIComponent(v.email);
		vcurl += '&url='+encodeURIComponent(v.url);
		this.replaceInfo(this.vCard, 'vCard', '', vcurl);

		this.sanContent.show();
	}	
};					

function directoryInit(){
	var directories = document.getElementsByClassName('directory');
	directories.each(function(e,i){
		e.id = 'directory'+i;
		new Directory(e);
	});
}

Event.observe(window,'load',directoryInit);