 /** 
    #########################################
    Author : JACKSON OATES jackson@summitprojects.com
    Company : Summit Projects - www.summitprojects.com
    Date: 09/15/2010 
    Updated: NA 
    * 
    #########################################
	
	DESCRIPTION:
    Rebuild of dealer locator, class conversion, addition of front-end result filtering.
    
    VERSION:
    2.0 
    
    IMPLEMENT:
    
      
    UPDATE LOG:
    9/15/2010 coinversion from loose functions to Dealer class
    
*/


function initDealer(){
	// get key
	var key = '';
	if(document.location.href.contains('dev')){
		// dev
		key = "ABQIAAAAOJ7GNgwrDhKnh75RquPIzRQ-LBdnH4dvHuPbo-Z-kd9k-MKtrhQdpIxcUW62sCdOy0tQQ-mKYaTv5Q";
	}else if(document.location.href.contains('stage')){
		// stage
		key = "ABQIAAAAQrCLhWWw0SoDZefq4Pbt2RT4t9uKTVnEU9EHIdUWJDLShFos8RQ1vFHiw17UnmNXeRRoLGRUFBsVag";
	}else{
	  	// live
		key = "ABQIAAAA3ZZCPOBTMSTIFVGXDi09PxT8TxpSGM15brkn0A7v0nf0E7l3yhT8xO8-_ICLKjN4tzvuUe8cQp8FUQ";
  	}
	
	var form = $('dealer-locator-search-form');
	var createDealer = new Dealer(form,{
		triggers:	'.filterResults',
		filter:		$('dealer-locator-results-filter'),
		result:		$('dealer-locator-results'),
		key:		key
	}).init()
}



var Dealer = new Class({
	Implements: [Options],	
    initialize: function(id, options){
    	this.setOptions(options);
    	this.form			= id;
		this.trigger		= this.options.triggers
    	this.filter		 	= this.options.filter; 
		this.resultTarget	= this.options.result;
		this.loader			= this.create_loader();
		this.title			= this.create_title();
		this.lenght			= 0;
		this.resultArray	= new Array();
		this.displayArray	= new Array();
		// filters //
		this.filterBlock	= $('dealer-locator-results-filter');
		this.ftrig			= this.get_triggers();
		this.currentFilter	= 'all';
		//this.filter		= this.create_filter();
		
		// google maps //
		this.g				= [];
		this.g.map			= [];
		this.g.key			= this.options.key
		this.g.api			= this.load_googleMaps()
		this.g.geocoder		= '';
	},
	init : function(){
		
		
		$('finder_search_btn').fade('.3');
		$('finder_search_btn').disabled = true;
		$('country').addEvent('change',this.toggle_location.bindWithEvent(this))
		this.form.addEvent('submit',this.request_json.bindWithEvent(this));
		//this.create_filter();
		
		this.ftrig.each(function(el,index){
			//console.log(this.ftrig[index], index);
			this.ftrig[index].store('filterid',this.ftrig[index].id);
			this.ftrig[index].addEvent('click',this.filter_event.bind(this,[index]));
		}.bind(this))
		
		
	},
	talk : function(){
		console.log('superfudge')
	},
	
	// togglers //
	toggle_filter : function(flag){
		var fx = new Fx.Morph(this.filterBlock,{duration:500,transition: Fx.Transitions.Quad.easeOut})
		if(flag == true){
			fx.start({'height':165,'opacity':1})
		}else{
			fx.start({'height':0,'opacity':0})
		}
	},
	toggle_location : function(e){
		var fx = new Fx.Morph($('usSearchOptions'),{duration:500,transition: Fx.Transitions.Quad.easeOut})
		if(e.target.value != 'US'){
			fx.start({'height': 0,'opacity':0})
		}else{
			fx.start({'height': 188,'opacity':1})
			
		}
	},
	toggle_loading : function(flag){
		this.create_empty();
		if(flag == true){
			this.loader.inject(this.resultTarget,'top');
			console.log('loading: ',this.loader)
		}
	},
	toggle_noResults : function(flag){
		this.create_empty();
		if(flag == true){
			var noresult = new Element('h3',{
				text:window.noResults,
				styles: ({'opacity':0,'text-align':'center'})
			}).inject(this.resultTarget).fade('in');
		}
	},
	// request //
	request_json : function(e){
		if($type(e) == 'event'){
			e.stop();
		}
		this.toggle_filter(true);
		var data = this.form.toQueryString()
		var jsonRequest = new Request.JSON({
			url:'/locate-dealer/results',
			method:'post',
			onRequest: this.toggle_loading.bind(this,[true]),
			//onComplete: this.load_results.bind(this)
			onComplete: function(req){
				this.req = req;
				this.load_results(this.req)
			}.bind(this)
		}).send(data);
	},
	
	// loading //
	load_googleMapsLoaded : function(){
		this.g.map = new google.maps.Map2(document.getElementById("map_canvas"));
		this.g.map.setUIToDefault();
		this.g.geocoder = new GClientGeocoder();
		this.g.markerCollection = [];
		//var map = window.map;
		GEvent.addListener(this.g.map, "click", function(overlay,latLng){
			
			
			if($('country').value != 'US'){return false;}
			
			this.g.geocoder.getLocations(latLng, function(response){
				if(response && response.Status.code == 200){
					place = response.Placemark[0];
					if(place.address.test('[0-9]{5}')){
						RE = new RegExp("[0-9]{5}");
						var zip = RE.exec(place.address)[0];
						$('postal_code').set('value',zip);
						
						$('dealer-locator-search-form').fireEvent('submit');
					}
				}
			});
		}.bind(this));
		if (google.loader.ClientLocation){
			this.map.setCenter(new google.maps.LatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude), 11);
		}
		else{
			this.g.geocoder.getLatLng('Portland, Oregon',function(point){
				if(!point) {
					return false
				}
				this.g.map.setCenter(point, 4);
			}.bind(this));
		}
	},
	load_googleMaps : function(){
		
		// url = 'http://www.google.com/jsapi?sensor=false&language=en&key=' + this.g.key + '&callback=this.load_googleMapsAPI';
		url = 'http://www.google.com/jsapi?sensor=false&language=en&key=' + this.g.key;
		var myScript = new Asset.javascript(url, {
		    id: 'loadMapApi', 
		    onload: function(){
				var enable = function(){
					$('finder_search_btn').fade('1');
					$('finder_search_btn').setStyle('cursor','pointer');
					$('finder_search_btn').disabled = false;
				}
				enable.delay(1500);
				
				// callback //
				google.load(
				  	"maps", 
					"2", 
					{
						"callback" : this.load_googleMapsLoaded.bind(this),
						"language" : document.getElement('meta[name=content-language]').content
					});
				
				return true;
		    }.bind(this)
		});
	},
	load_results: function(){
		console.log('----------LOAD RESULT SET------------')
		console.log(this.req)
		console.log('----------/LOAD RESULT SET-----------')
		/**
		 * this just formats then creates array
		 */
		// fresh arrays //
		this.resultArray.empty();
		this.displayArray.empty();
		
		this.lenght = this.req.dealers.length
		console.log('result.dealers.length',this.lenght)
		/**
		 * run display data 
		 */
		
		
		
		if(this.lenght > 0){
			console.log('++++++++++++++++')
			this.req.dealers.each(this.push_item.bind(this))
			this.toggle_loading(false);
		}else{
			console.log('----------------')
			this.toggle_noResults(true);
			return false;
		}
		console.log('-this',this);
		this.create_dealers_array();
		
		// chain load should be split out into own method
		// displayArray is now an array of dealer elements, pass them through chain to progressively load into dom
		
		var chainLoad = new Chain();
		this.displayArray.each(function(el, index){
			 chainLoad.chain(this.add_dealer.bind(this,[el, index]));
		}.bind(this))
		var runChain = function() { 
	        chainLoad.callChain();
	    };
	    var timer = runChain.periodical(150);
	},
	push_item : function(el, index){
		
		/**
		 * filter results based on current filter, or default to all results.
		 */
		switch(this.currentFilter)
		{
		case 'dealer_type1':
		  if(el.dealer_type1){
		  	
				this.resultArray.push(el);
		  }
		  break;
		case 'dealer_type2':
		  if(el.dealer_type2){
				this.resultArray.push(el);
		  }
		  break;
		default: // All
			this.resultArray.push(el);
		}
	},
	// add //
	add_dealer : function(el, index){
		// inject dealer //
		el.setStyle('opacity',0);
        el.inject(this.resultTarget,'bottom');
		var fx = new Fx.Tween(el,{onComplete:function(){
			// create dealer map marker //
			this.create_googleMarker(index)
		}.bind(this)})
		fx.start('opacity',1)
		
	},
	// filter //
	get_triggers : function(){
		var r = this.filterBlock.getElements(this.options.triggers);
		return r;	
	},
	filter_event : function(index){
		//console.log(this.ftrig[index], this.ftrig[index].retrieve('filterid'));
		this.ftrig.each(function(el){el.removeClass('active')});
		this.ftrig[index].addClass('active');
		
		this.currentFilter = this.ftrig[index].retrieve('filterid');
		console.log('this.currentFilter: ',this.currentFilter);
		
		
		this.toggle_loading.bind(true);
		
		this.load_results();
	},
	// create //
	create_filter : function(){
		//console.log(this.filterBlock);
	},
	
	create_dealers_array : function(){
		this.resultArray.each(this.create_dealer.bind(this));
	},
	create_dealer : function(el, index){
		var dealerEntry = new Element('div',{
			'class':'dealer dealer_'+index,
			'styles':{
				'background': "url(/resources/images/Google_Maps_Marker_Images/default.png) no-repeat left top",
				'cursor':'pointer'
			}
		})
		var dealerName = new Element('h2',{
			'class': 'dealerName',
			'text': el.dealer_name
		}).inject(dealerEntry);
		
		var dealerAddress = new Element('p',{
			'class': 'dealerAddress',
			'text': (el.dealer_address2 != null && el.dealer_address2.length > 0 ) ?
						el.dealer_address1 + ', ' + el.dealer_address2 :
						el.dealer_address1
		}).inject(dealerEntry);
		
		var dealerCity = new Element('p',{
			'class': 'dealerCityStateZip',
			'text':el.dealer_city+", "+el.dealer_state+" "+el.dealer_postal
		}).inject(dealerEntry);
		
		var dealerPhone = new Element('p',{
			'class':'dealerPhone',
			'text':el.dealer_phone
		}).inject(dealerEntry);
		
		// add options
		console.log('-> ',el.dealer_type1);
		if (el.dealer_type1 == 'x' || el.dealer_type2 == 'x') {
			var dealerTypeContainer = new Element('div',{
				'class':'dealerTypeContainer'
			})
			if (el.dealer_type1 == 'x') {
				new Element('span',{
					'class':'dealerTypePreferred'
				}).inject(dealerTypeContainer);
				
			}
			if (el.dealer_type2 == 'x') {
				new Element('span',{
					'class':'dealerTypeVSP'
				}).inject(dealerTypeContainer);
				
			}
			dealerTypeContainer.inject(dealerEntry);
		}
		
		// build array of display elements //
		this.displayArray.push(dealerEntry);
	},
	create_googleMarker : function(index){
		
		if(!this.displayArray[index]){return false;}
		var address = this.resultArray[index].dealer_address1 + " " + this.resultArray[index].dealer_city + ", " + this.resultArray[index].dealer_state + " " + this.resultArray[index].dealer_postal;
		
		this.g.geocoder.getLatLng(address, function(point){
			if(point){
				var marker = this.create_marker(point, index, this.displayArray[index]);
				var latLng = marker.getLatLng();
				this.g.map.addOverlay(marker);
				this.displayArray[index].addEvent('click',function(e){
					
					//console.log(index, latLng);
					this.g.map.panTo(latLng);
					marker.openInfoWindowHtml(this.displayArray[index].clone());
					
				}.bind(this))
				
				if(index == 0){
					this.g.map.setCenter(marker.getLatLng(),11);
					this.displayArray[index].fireEvent('click');
				}
			}else{
				// console.log('not found: ', this.displayArray[index])
				this.displayArray[index].setStyles({
					'background':'none',
					'cursor':'inherit',
					'opacity':0.6
				});
			}
		}.bind(this));
		
		
	},
	create_marker : function(point, index, dealer){
		
		var baseIcon = new GIcon(G_DEFAULT_ICON);
		baseIcon.shadow = "/resources/images/Google_Maps_Marker_Images/shadow50.png";
		baseIcon.iconSize = new GSize(9, 33);
		baseIcon.shadowSize = new GSize(37, 34);
		baseIcon.iconAnchor = new GPoint(9, 34);
		baseIcon.infoWindowAnchor = new GPoint(9, 2);
		
		var letteredIcon = new GIcon(baseIcon);
		letteredIcon.image = "/resources/images/Google_Maps_Marker_Images/default.png";
		
		// Set up our GMarkerOptions object
		markerOptions = { icon:letteredIcon };
		var marker = new GMarker(point, markerOptions);
		GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowHtml(this.displayArray[index].clone());
		}.bind(this));
		
		return marker;
	},
	create_loader : function(){
		return new Element('div',{
			'id':'dealer-locator-results-loader',
			'class':'dealer-locator-results-loader'
		});
	},
	create_title : function(){
		return new Element('h3',{
			'id':'results-title',
			'text':'Search Results'
		});
	},
	create_empty : function(){
		this.resultTarget.empty();
	},
	loading : function(){
		//this.loader.inject(this.resultTarget,'top');
	}
});
Dealer.implement(new Events, new Options);


window.addEvent('domready',initDealer);
















