// Store Locator file

function StoreLocator(map_div, form, error, info, more, prev, map_dia) {
	
	this.map_div = map_div;
	this.retailer_form = form;
	this.retailer_info = info;
	
	if(form != null) {
		this.response_url = form.readAttribute('action');
	}
	
	this.form_error = error;
	this.more_bttn = more;
	this.prev_bttn = prev;
	
	if(map_dia != null) {
		this.map_dia = map_dia.innerHTML;
	}
	
	this.current_page = 0;
	this.country = 'USA';
	this.citystatezip = '';
	
	this.map;
	this.bounds;
	this.geocoder = new google.maps.Geocoder();
	
	this.center;
	this.input;
	this.more;
	this.prev;
	this.points;
	
};


StoreLocator.prototype.init = function(jquery_rform) {
	var obj = this;
	
	jquery_rform.submit(function() {
		if(obj.formCheck()) {
			return false;
		}
		
		obj.current_page = 0;
		obj.initSearch();
		return false;
	});
};


StoreLocator.prototype.formCheck = function() {
	if($F(this.retailer_form['citystatezip']) === '' ||
		$F(this.retailer_form['citystatezip']) === 'City and State or Zip') {
			this.form_error.innerHTML = 'Please fill in a city and state, or a zip code.';
			this.form_error.show();
			return true;
	} else if ($F(this.retailer_form['citystatezip']).match(/\D+\d+|\d+\D+/g)) {
		this.form_error.innerHTML = 'Please fill in ONLY a city and state, or a zip code.';
		this.form_error.show();
		return true;
	}
	
	this.form_error.hide();
	return false;
};


StoreLocator.prototype.mapPan = function(evt, lat, lng) {
	this.map.panTo(new google.maps.LatLng(lat, lng));
};


StoreLocator.prototype.initSearch = function() {
	var obj = this;
	
	this.citystatezip = $F(this.retailer_form['citystatezip']);
	//this.country = $F(this.retailer_form['country']);
	
	this.geocode(function(results){
		obj.searchDb(results.geometry.location);
	});
};


StoreLocator.prototype.geocode = function(callback) {
	var obj = this;
	
	this.emptyVars();
	
	this.geocoder.geocode({'address' : obj.citystatezip + ' ' + obj.country}, function(results, status) {
		if(status == google.maps.GeocoderStatus.OK) {
			if(results[0]) {
				callback(results[0]);
			} else {
				// some validation
			}
		} else {
			obj.form_error.innerHTML = "That was not a valid location.";
			obj.form_error.show();
			return;
		}
	});
};


StoreLocator.prototype.searchDb = function(latlng) {
	var obj = this;
	
	jQuery.ajax({
		url: obj.response_url,
		type: "POST",
		dataType: "json",
		data: ({
			'page' : obj.current_page,
			'lat' : latlng.lat(),
			'lng' : latlng.lng(),
			'country' : obj.country,
			'citystatezip' : obj.citystatezip
		}),
		beforeSend: function() {
			obj.disableClicking(obj.prev_bttn);
			obj.disableClicking(obj.more_bttn);
		},
		error: function() {
			obj.renewClicking(obj.prev_bttn);
			obj.renewClicking(obj.more_bttn);
		},
		success: function(t) {
			obj.dbResult(t);
		},
		complete: function() {
			obj.renewClicking(obj.prev_bttn);
			obj.renewClicking(obj.more_bttn);
		}
	});
};


StoreLocator.prototype.dbResult = function(t) {
	if(typeof t.center != 'undefined' ) {
		this.center = new google.maps.LatLng(t.center.lat, t.center.lng);
	}
	
	if(typeof t.input != 'undefined') {
		this.input = t.input;
		this.more = t.more;
		this.prev = t.prev;
	}
	
	if(typeof t.points != 'undefined') {
		this.points = t.points;
	}
	
	this.makeMap();
};


StoreLocator.prototype.makeMap = function() {
	var obj = this;
	
	var my_options = { zoom: 13, center: obj.center, mapTypeId: google.maps.MapTypeId.ROADMAP, mapTypeControl: false };
    this.map = new google.maps.Map(this.map_div, my_options);
	
	this.displayResults();
	this.imageCurtain();
};


StoreLocator.prototype.addMarker = function(lat, lng, num) {
	var point = new google.maps.LatLng(lat,lng);
	var obj = this;
	
	obj.bounds.extend(point);
	
	var marker = new google.maps.Marker({
		position: point,
		map: obj.map,
		icon: new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld="+num+"|EB8063|111111")
	});
};


StoreLocator.prototype.imageCurtain = function() {
	if(jQuery('#store-pic').css('left') == '0px') {
		var navWidth = jQuery('#map-container').css('width');
		jQuery('#store-pic').animate({ 'left' : navWidth }, 1000);
	}
};


StoreLocator.prototype.emptyResults = function() {
	if(this.retailer_info != null) {
		this.retailer_info.innerHTML = "";
	}
};


StoreLocator.prototype.lonePoint = function(lat, lng) {
	this.emptyResults();
	
	this.points = [{ 'lat' : lat, 'lng' : lng }];
	this.center = new google.maps.LatLng(lat, lng);
	this.more = "no";
	this.prev = "no";
};


StoreLocator.prototype.displayResults = function() {
	var obj = this;
	
	this.emptyResults();
	
	if(this.more_bttn != 'null' && this.prev_bttn != null) {
		if(typeof this.more != 'undefined' && typeof this.prev != 'undefined') {
			this.displayMorePrev();
		}
	}
	
	if(typeof this.points[0] != 'undefined') {
		this.bounds = new google.maps.LatLngBounds();
		
		for(var i=0,len=this.points.length; i<len; i++) {
			var j = i+1;
			var point = this.points[i];
			this.addMarker(point.lat, point.lng, j);
			
			if(typeof point["title"] != 'undefined') {
				var loc_div = new Element('div').update(this.formatStoreOutput(point,j));
				this.retailer_info.insert({ 'bottom' : loc_div });
				$('gmap_zoom_'+j).observe('click', obj.mapPan.bindAsEventListener(this, point.lat, point.lng));
			}
		}
		
		if(this.points.length > 1) {
			this.map.fitBounds(this.bounds);
		} else {
			this.map.setCenter(new google.maps.LatLng(this.points[0].lat, this.points[0].lng));
			this.map.setZoom(15);
		}
	} else {
		var loc_div = new Element('div').update("There are no retailers near you within "+this.map_dia+" miles.");
		this.retailer_info.insert({ 'bottom' : loc_div });
	}
};


StoreLocator.prototype.formatStoreOutput = function(point, num) {
	var store_div = new Element('div').addClassName('shop');
	
	store_div.appendChild(new Element('h3').update(point['title']));
	store_div.appendChild(new Element('p').update(point['addr'] + "<br />" + point['city'] + " " + point['state'] + " " + point['zip'] + "<br />T: " + point['phone']));
	store_div.appendChild(new Element('a').writeAttribute('href', '#').writeAttribute('id', 'gmap_zoom_' + num).writeAttribute('onclick', 'return false').update('Select this Jeweler'));

	return store_div;
};


StoreLocator.prototype.displayMorePrev = function() {
	if(this.more == 'yes') {
		this.more_bttn.setStyle({ display : "block" });
	} else {
		this.more_bttn.setStyle({ display : "none" });
	}
	
	if(this.prev == 'yes') {
		this.prev_bttn.setStyle({ display : "block" });
	} else {
		this.prev_bttn.setStyle({ display : "none"  });
	}
};


StoreLocator.prototype.renewClicking = function(el) {
	var obj = this;
	
	el.observe('click', function(evt) {
		if(el==obj.more_bttn) {
			obj.current_page++;
		} else if(el==obj.prev_bttn && obj.current_page > 0) {
			obj.current_page--;
		}
		
		obj.geocode(function(results){
			obj.searchDb(results.geometry.location);
		});
	});
};


StoreLocator.prototype.disableClicking = function(el) {
	el.stopObserving('click');
};


StoreLocator.prototype.emptyVars = function() {
	delete this.center;
	delete this.input;
	delete this.more;
	delete this.prev;
	delete this.points;
};




// Utility Functions

// converts array to object
function oc(a) {
  var o = {};
  for(var i=0;i<a.length;i++) { o[a[i]]=''; }
  return o;
}

