/* LocationMap.js */
function LocationMap(m) {
	this.opts_ = {
		zoom: 3,
		center: new google.maps.LatLng(38.20548238814633, -94.69741712500002),
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		//draggable: false,
		disableDefaultUI: false
		//disableDoubleClickZoom: true,
		//scrollwheel: false
    };
	
	// privates
	this.map_ = new google.maps.Map(m, this.opts_);
	this.geocoder_ = new google.maps.Geocoder();
	this.overlay_ = null;
	this.markerData_ = null;
	this.markers_ = Array();
	this.infoBox_ = Array();
	
	// funcs
	this.events();  // bind events
	//this.overlay(true); // start the overlay
	this.getMarkers(); // get/set markers
	this.currentInfoWindow_ = null;
}
LocationMap.prototype.events = function(){
	var self = this;

	/* jQuery events */
	$('#zip_form').submit(function(e){
		e.preventDefault();
		self.focusResults();
	});
	
	$('#zip_input').click(function(e){
		$(this).attr('class', 'input-active');
		if ($(this).val() == 'Zip Code') $(this).val('');
	});
	
	google.maps.event.addListener(self.map_, 'idle', function() {
		$('#map-locations ul').empty();
		self.checkBoundsForLocations();
	});
	
	/*
	google.maps.event.addListener(self.map_, 'zoom_changed', function() {
		self.checkBoundsForLocations();
	});
	
	google.maps.event.addListener(self.map_, 'dragend', function() {
		self.checkBoundsForLocations();
	});
	*/

}
/*
 * overlay() - create the static overlay
 */
/*LocationMap.prototype.overlay = function(state){
	if (state)	this.overlay_ = new MapOverlay(new google.maps.LatLngBounds(new google.maps.LatLng(23.72714030453315, -136.97280775000002), new google.maps.LatLng(50.346944155578946, -52.422026500000015)),'startmap.jpg', this.map_);
	else this.overlay_.setMap(null);
}*/
/*
 * getMarkers() - load the marker data from XML, and upon completion, drop the markers
 */
LocationMap.prototype.getMarkers = function(){
	var self = this;
	// read from the file
	$.ajax({
	    type: "GET",
		url: "dealers.xml",
		dataType: "xml",
		success: function(xml) {
			self.markerData_ = Array();
			$(xml).find('Dealer').each(function(){
				self.markerData_.push({
					name: $(this).find('Name').text(),
					address1: $(this).find('Address1').text(),
					address2: $(this).find('Address2').text(),
					city: $(this).find('City').text(),
					state: $(this).find('State').text(),
					zip: $(this).find('Zip').text(),
					country: $(this).find('Country').text(),
					phone1: $(this).find('Phone1').text(),
					phone2: $(this).find('Phone2').text(),
					fax: $(this).find('Fax').text(),
					email: $(this).find('Email').text(),
					web: $(this).find('Webpage').text(),
					lat: $(this).find('Lat').text(),
					lng: $(this).find('Lng').text()
				});
			});
			self.markers();
		},
		error: function(){
		}
	});
}
/*
 * markers() - use the markerData to drop markers
 */
LocationMap.prototype.markers = function(){
	var self = this;
	if(this.markerData_){
		for (var x = 0; x < this.markerData_.length; x++){
			var me = this.markerData_[x];
			// TYPE is true if the marker is Frank's Official

			var addr = me.address1 + ' ' + me.city + ',' + me.state + ' ' + me.zip;
			var popcontent = '<div style="font-size:75%;"><strong>' + me.name + '</strong><br />';
			popcontent += me.address1 + '<br />';
			if (me.address2 != '') popcontent +=  me.address2 + '<br />';
			popcontent += me.city + ', ' + me.state + ' ' + me.zip + '<br />';
			if (me.phone1 != '') popcontent +=  'p. ' + me.phone1 + '<br />';
			if (me.phone2 != '') popcontent +=  'p. ' + me.phone2 + '<br />';
			//if (me.fax != '') popcontent +=  'F:' + me.fax + '<br />';
			if (me.email != '') popcontent +=  me.email + '<br />';
			if (me.web != '')
			{
				var web = me.web;
				if (me.web.indexOf('http') < 0) web = 'http://' + web;
				popcontent +=  '<a href="' + web + '" target="_blank">' + me.web + '</a><br />';
			}
			popcontent += '<a href="http://maps.google.com/maps?daddr=' + me.address1 + ' ' + me.city + ',' + me.state + ' ' + me.zip + '" target="_blank">Get Directions</a>';
			popcontent += '</div>';
			//alert(popcontent);
			
			/*this.geoAddress(addr, {content:popcontent,index:x}, function(results,status,args){
				self.dropMarker(results[0].geometry.location, args.content,args.index);
			});*/
			self.dropMarker(new google.maps.LatLng(me.lat, me.lng), popcontent, x);
		}
	}
}

/*
 * focusResults()
 */
LocationMap.prototype.focusResults = function(){
	var self = this;
	if ($('#zip_input').val() != '' && $('#zip_input').val() != 'Zip Code') self.focusZipResults($('#zip_input').val());
	else if ($('#state_input').val() != '') self.focusStateResults($('#state_input').val());
}

/*
 * focusZipResults() - focus the map on a searched location
 */
LocationMap.prototype.focusZipResults = function(query){
	var self = this;
	this.geoAddress(query, null, function(results,status){
		self.map_.setCenter(results[0].geometry.location);
		self.map_.setZoom(11);
	});
}

/*
 * focusStateResults() - focus the map on a searched location
 */
LocationMap.prototype.focusStateResults = function(query){
	//alert(query);
	var self = this;
	this.geoAddress(query, null, function(results,status){
		self.map_.setCenter(results[0].geometry.location);
		self.map_.setZoom(6);
	});
}
/*
 * dropMarker() - place a marker on the map with an infobox event displaying `content`
 * `x` is an index of the marker
 */
LocationMap.prototype.dropMarker = function(position,content,x){
	var self = this;
	
	this.markers_[x] = new google.maps.Marker({
	    position: position,
	    map: this.map_,
		icon: 'VTX_FindAStore-Icon.png',
		id: x
	});
	var infowindow = new google.maps.InfoWindow({
		content: content
	});
	var tempmarker = this.markers_[x];
	google.maps.event.addListener(tempmarker, "click", function() {
		if (self.currentInfoWindow_)
		{
			self.currentInfoWindow_.close();
			self.currentInfoWindow_ = null;
		}
		infowindow.open(self.map_, tempmarker);
		self.currentInfoWindow_ = infowindow;
	});
}

LocationMap.prototype.geoAddress = function(address, args, callback){
    if (this.geocoder_) {
		this.geocoder_.geocode({'address': address}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				callback.apply(this,[results,status,args]);
			} else {
				alert("Geocode was not successful for the following reason: " + status);
			}
		});
    }
}

LocationMap.prototype.checkBoundsForLocations = function()
{
	var self = this;
	var bounds = this.map_.getBounds();
	var southWest = bounds.getSouthWest();
	var northEast = bounds.getNorthEast();
	var neLng = northEast.lng();
	var swLng = southWest.lng();
	var neLat = northEast.lat();
	var swLat = southWest.lat();
	
	var count = 0;
	var textToInsert = [];
	var j = 0;
	for(var i=0; i < self.markerData_.length;i++)
	{
		//alert(self.markers_[i].name);
		if ((self.markerData_[i].lat > swLat && self.markerData_[i].lat < neLat)
			&& (self.markerData_[i].lng > swLng && self.markerData_[i].lng < neLng))
			//&& count < 4)
		{
			//alert(self.markerData_[i].city + ',' + self.markerData_[i].state + ': ' + neLng + ' ' + swLng + ' ' + self.markerData_[i].lng);
			//alert(self.markerData_[i].city + ',' + self.markerData_[i].state + ': ' + neLat + ' ' + swLat + ' ' + self.markerData_[i].lat);
			textToInsert[j++] = '<li id="location' + i + '"><strong>';
			textToInsert[j++] = self.markerData_[i].name + '</strong><br />';
			textToInsert[j++] = self.markerData_[i].address1 + '<br />';
			textToInsert[j++] = self.markerData_[i].city + ', ' + self.markerData_[i].state + ' ' + self.markerData_[i].zip + '<br />';
			if (self.markerData_[i].web != '')
			{
				var web = self.markerData_[i].web;
				if (self.markerData_[i].web.indexOf('http') < 0) web = 'http://' + web;
				textToInsert[j++] = '<a href="' + web + '" target="_blank">visit website</a>';
			}
			else textToInsert[j++] = self.markerData_[i].phone1;

			textToInsert[j++] = '</li>' ;
			count = count + 1;
		}
	}
	if (textToInsert.length > 0) $('#map-locations ul').append(textToInsert.join(''));
	
	for(var i=0; i < self.markerData_.length;i++)
	{
		$('#location' + i).click(function(e){
			var id = this.id.replace('location', "");
			var tempmarker = self.markers_[id];
			google.maps.event.trigger(tempmarker, "click");
		});
	}
}
