/*

	This should be used whenever we have a Yahoo Map
	on the page. It will need to be included in the head
	and started up in the page's domready event, like this:
	
window.addEvent('domready', function(){

	if ($('mapcontainer')) {
		new Map.withLocalSearch($('mapcontainer'));
	}

});

	There are five classes in this file. Here is the hierarchy:

	Map
		Base
			HomeLocation
				LocalSearch
					AreaPropsAndLocalSearch
			MultiProps

*/

var Map = {};

Map.Base = new Class({

	options: {},

	initialize: function(el, options){

		// apply any options that may be given when its started
		this.setOptions(options);

		// this is set to fix some weird bug in IE
		document._ymapset=1;

		// create a reference to Yahoo's map object
		this.map = new YMap(el);

		dis = this;
	},

	// this should be given the CSS selector for vcards
	// and will parse all elements in it for the
	// place's information, returning a new array or object
	parseVCard: function(selector){
		var dots = [];
		$$(selector).each( function(el){
			var dot = {};
			el.getElements('*').each( function(newEl){
				switch(newEl.className)
				{
				case 'fn':
					dot.fn = newEl.getText();
					break
				case 'url':
					dot.url = newEl.getProperty('href');
					break
				case 'propid':
					dot.propid = newEl.getText();
					break
				case 'tel':
					dot.tel = newEl.getText();
					break
				case 'street-address':
					dot.streetAddress = newEl.getText();
					break
				case 'extended-address':
					dot.extendedAddress = newEl.getText();
					break
				case 'locality':
					dot.locality = newEl.getText();
					break
				case 'region':
					dot.region = newEl.getText();
					break
				case 'postal-code':
					dot.postalCode = newEl.getText();
					break
				case 'latitude':
					dot.latitude = newEl.getText();
					break
				case 'longitude':
					dot.longitude = newEl.getText();
					break
				default:
					break
				}
			});
			dots.push(dot);
		});
		// check if there's only one, or return an array
		if (dots.length == 1) {
			return dots[0];
		} else {
			return dots;
		}
	},

	// Generates the HTML for the popup bubble window
	// only for objects pulled from vcards
	createMarkerText: function(obj){
		var ttl = '', phn = '', adr = '', last = '';
		if (obj.fn && obj.url) {
			ttl += '<h3><a href="' + obj.url + '">' + obj.fn + '</a></h3>';
		} else if (obj.fn) {
			ttl += '<h3>' + obj.fn + '</h3>';
		}
		if (obj.tel) phn += '<p class="phone">' + obj.tel + '</p>';
		if (obj.streetAddress) adr += obj.streetAddress;
		if (obj.extendedAddress) adr += ', ' + obj.extendedAddress;
		if (adr != '') adr = '<p>' + adr + '</p>';
		if (obj.locality) last += obj.locality;
		if (obj.region) last += ', ' + obj.region;
		if (obj.postalCode) last += ' ' + obj.postalCode;
		if (last != '') last = '<p>' + last + '</p>';
		return ttl + phn + adr + last;
	},


	// enter the name of the icon, and return a YImage for it
	createMarkerIcon: function(icon){
		var img = new YImage();
		img.src = '/images/icons/' + icon + '.png';
		img.size = new YSize(30,30);
		img.offset = new YCoordPoint(-15,15);
		img.offsetSmartWindow = new YCoordPoint(15,15);
		return img;
	},


	// this builds the marker and places it on the map
	plotMarker: function(obj, icon){
		var i = this.createMarkerIcon(icon);
		var p = new YGeoPoint(obj.latitude, obj.longitude);
		var m = new YMarker(p, i);
		m.setSmartWindowColor("blue");
		var win = this.createMarkerText(obj);
		YEvent.Capture(m, EventsList.MouseClick, function() { m.openSmartWindow(win) });
		this.map.addOverlay(m);
	}


});
// required for setting options and things
Map.Base.implement(new Events);
Map.Base.implement(new Options);


/*

	This one is for only showing the location of a single property.

*/
Map.HomeLocation = Map.Base.extend({

	options: {
		homeSelector: '.propinfo',
		homeZoom: 6,
		showExtraControls: true,
		homeIcon: 'house_zone'
	},

	initialize: function(el, options){
		this.parent(el, options);

		// save an object for the home location
		// if there isn't only one, this will be an array
		this.homedot = this.parseVCard(this.options.homeSelector);

		// this assumes that we'll have lat/long for every property
		this.homepoint = new YGeoPoint(this.homedot.latitude, this.homedot.longitude);

		this.map.drawZoomAndCenter(this.homepoint, this.options.homeZoom);
		this.map.addZoomLong();
		this.map.disableKeyControls();

		// for the smaller maps, these can be removed
		// by setting showExtraControls to false
		if (this.options.showExtraControls) {
			this.map.addPanControl();
			this.map.addTypeControl();
		}
		this.plotMarker(this.homedot, this.options.homeIcon);

	}

});

/*

	This one is for activating Yahoo Local Search
	around the property. Extends from previous.

*/
Map.LocalSearch = Map.HomeLocation.extend({

	options: {
		loadId: 'loadme',
		hideClass: 'hideme',
		typeSelector: '#mapsearch select',
		querySelectId: 'qs',
		radiusSelectId: 'qr',
		homeZoom: 5
	},
	
	yahooMarkers: [],
	
	initialize: function(el, options){
		this.parent(el, options);

		// make reference to spinner
		this.loader = $(this.options.loadId);

		this.querySelect = $(this.options.querySelectId);
		this.radiusSelect = $(this.options.radiusSelectId);

		// apply the onchange even to the select boxes
		$$(this.options.typeSelector).each( function(el){
			el.addEvent('change', function(){
				dis.doYahooSearch();
			});
		});

		// go ahead and do a search on whatever is currently selected
		this.doYahooSearch();

	},

	doYahooSearch: function(){
		this.map.searchLocal( this.homepoint, this.querySelect.value, this.radiusSelect.value, '10');
		if (this.loader.hasClass(this.options.hideClass)) this.loader.removeClass(this.options.hideClass);
		YEvent.Capture( this.map, EventsList.onEndLocalSearch, this.handleYahooResults );
	},

	handleYahooResults: function(e){
		if (e.Data) {
			// clear old data
			dis.removeYahooMarkers();
			// start looping through results
			for (var a in e.Data.ITEMS) {
				var l = e.Data.ITEMS[a];
				//YLog.print(l);
				if (l.TITLE) {
					dis.createYahooSearchMarker(l, 'blahid' + a);
				}
			}
			dis.loader.addClass('hideme');
			e.Data = null;
		}
	},

	createYahooSearchMarker: function(l, disid){
		var p = new YGeoPoint(l.LATITUDE,l.LONGITUDE);
		if(l.URL){ var ttl = '<h3><a href="' + l.URL + '" target="_new">' + l.TITLE + '</a></h3>'; } else { var ttl = '<h3>' + l.TITLE + '</h3>'; }
		if(l.PHONE){ var phn = '<p class="phone">' + l.PHONE + '</p>'; } else { var phn = ''; }
		var t = ttl + phn + '<p>' + l.ADDRESS + '</p><p>' + l.CITY + ', ' + l.STATE + '</p>';
		var icon = 'flag_zone';
		for (var i = 0; i < l.CATEGORIES.length; i++) {
			if(typeof l.CATEGORIES[i] == 'object'){
				var g = l.CATEGORIES[i].ID;
					if(g == '96925947') icon = 'bank';
					if(g == '96934301') icon = 'bank';
					if(g == '96928068') icon = 'bank';

					if(g == '96926236') icon = 'restaurant';
					if(g == '96926164') icon = 'chinese';
					if(g == '96929155') icon = 'mexican';

					if(g == '96925828') icon = 'movie';
					if(g == '96612100') icon = 'movie';
					if(g == '96927240') icon = 'movie';

					if(g == '96925816') icon = 'nightclub';
					if(g == '96927238') icon = 'nightclub';
					if(g == '96926061') icon = 'nightclub';
					if(g == '96926057') icon = 'nightclub';

					if(g == '96925782') icon = 'school';
					if(g == '96928445') icon = 'school';
					if(g == '96928447') icon = 'school';
					if(g == '96928448') icon = 'school';
					if(g == '96928449') icon = 'school';
					if(g == '96925786') icon = 'school';
					if(g == '96928481') icon = 'school';

					if(g == '96926169') icon = 'coffee';

			}
		}
		this.plotYahooMarker(p, icon, t, disid);
	},

	plotYahooMarker: function(p, icon, win, disid){
		var i = this.createMarkerIcon(icon);
		var m = new YMarker(p, i, disid);
		m.setSmartWindowColor("blue");
		YEvent.Capture(m, EventsList.MouseClick, function() { m.openSmartWindow(win) });
		this.map.addOverlay(m);
		this.yahooMarkers.push(disid);
	},
	
	removeYahooMarkers: function(){
		this.yahooMarkers.each( function(el){
			dis.map.removeMarker(el);
		});
		this.yahooMarkers = [];
	}

});

/*

	This will set the home location, do the yahoo search
	and plot the area properties on the same map.
	
	You'll need to be sure to add the area selector.

*/
Map.AreaPropsAndLocalSearch = Map.LocalSearch.extend({

	options: {
		areaSelector: '.results .vcard',
		apartmentIcon: 'flag_zone'
	},

	initialize: function(el, options){
		this.parent(el, options);

		this.areaDots = this.parseVCard(this.options.areaSelector);

		// this checks if it isn't null, then if it's an array
		if (this.areaDots) {
			if (isArray(this.areaDots)) {
				this.areaDots.each( function(el){
					dis.plotMarker(el, dis.options.apartmentIcon);
				});
			} else {
				dis.plotMarker(this.areaDots, this.options.apartmentIcon);
			}
		}

	}

});


/*

	This is pretty much identical to the previous class,
	except that it doesn't inherit any other classes.

*/

Map.MultiProps = Map.Base.extend({

	options: {
		areaSelector: '.results .vcard',
		mapstart: '',
		mapzoom: 8,
		apartmentIcon: 'flag_zone'
	},
	
	initialize: function(el, options){
		this.parent(el, options);

		this.areaDots = this.parseVCard(this.options.areaSelector);

		this.map.drawZoomAndCenter(this.options.mapstart, this.options.mapzoom);
		this.map.addZoomLong();
		this.map.disableKeyControls();

		// this checks if it isn't null, then if it's an array
		if (this.areaDots) {
			if (isArray(this.areaDots)) {
				this.areaDots.each( function(el){
					dis.plotMarker(el, dis.options.apartmentIcon);
				});
			} else {
				this.plotMarker(this.areaDots, this.options.apartmentIcon);
			}
		}

	}

});

function isArray(obj) {
	if (obj.constructor.toString().indexOf("Array") == -1) return false;
	else return true;
}
