/**
 * The "Base Icon" that all other icons are created from
 */
var gm_baseIcon = null;

/**
 * Handles all of the general interaction for the Island Map page
 */
ERMap = {
	isLoaded: false,
	fnContinue: function() {},
	_mapElementId: 'googleMap',
	gm_map: null,
	gm_currentPoint: null,
	
	el_infoBox: null,
	
	onDomReady: function() {
		var w1, h1, w2, h2, so;
		
		/* Import data */
		jQuery.extend(ERMap, ERMAPDATA);
		
		ERMap.el_infoBox = jQuery('#infoBox').remove();
		
		/* Calculate width/height of the flashmap */
		w1 = 640;                           /* Minimum width / height */
		h1 = 489;
		h2 = jQuery(window).height() - 115;  /* Auto width / height */
		w2 = jQuery(window).width() - 350 - 12;
//		w2 = parseInt(h2 * (w1/h1));
		h1 = h1 > h2 ? h1 : h2;            /* Choose the bigger of the two */
		w1 = w1 > w2 ? w1 : w2;
		
		/* Initialize and size the map */
		jQuery('#'+ERMap._mapElementId).css({width:w1+'px', height:h1+'px'});
		
		// Setup the Search sidebar
		ERMapSearch.init({height:h1});
		
		// Initialize Sales
		ERMapSales.init();
		
		// Initialize Pois
		ERMapPois.init();
		
		ERMapSearch.switchToTab(ERMapSales);
		
		ERMap.isLoaded = true;
		ERMap.fnContinue();
		// Add the Sales search tab
		
		// Add the POI search tab
		
		/* Initialize other things */
//		ERMap.REresults.init();
//		ERMap.POIresults.init();
	},
	
	onGoogleMapReady: function() {
		// Create base icon
		gm_baseIcon = new google.maps.Icon();
		gm_baseIcon.shadow = "http://www.edistorealty.com/map/images/mapIcons/shadow50.png";
		gm_baseIcon.shadowSize = new GSize(37, 34);
		gm_baseIcon.infoShadowAnchor = new GPoint(18, 25);
		gm_baseIcon.iconSize = new GSize(20, 34);
		gm_baseIcon.iconAnchor = new GPoint(9, 34);
		gm_baseIcon.infoWindowAnchor = new GPoint(9, 2);

		// Initialize the GoogleMap
		ERMap.gm_map = new google.maps.Map2(document.getElementById(ERMap._mapElementId));
		ERMap.gm_map.setCenter(new google.maps.LatLng(32.488588, -80.317417), 15);
		ERMap.gm_map.addControl(new google.maps.LargeMapControl());
		ERMap.gm_map.addControl(new google.maps.MapTypeControl());
		ERMap.gm_map.addControl(new google.maps.OverviewMapControl());
		
		// Place the Edisto logo
		var logo = new google.maps.Icon();
		logo.image = "http://www.edistorealty.com/map/images/edistoLogo.png";
		logo.iconSize = new GSize(45, 34);
		logo.iconAnchor = new GPoint(22, 17);
		logo.infoWindowAnchor = new GPoint(22, 3);
		var point  = new google.maps.LatLng(32.487435, -80.319858);
		var opts   = {'icon':logo, 'title':'Edisto Realty Office'};
		var logoMarker = new google.maps.Marker(point, opts);
		google.maps.Event.addListener(logoMarker,"click", function() { ERMap.showMapInfoWindow(logoMarker, 'Edisto Realty', '1405 Palmetto Boulevard', 'Edisto Island, SC 29438', '1-866-856 6538', '', '', '/map/images/edistoImg.jpg') });
		ERMap.gm_map.addOverlay(logoMarker);
		
		if (ERMap.isLoaded) ERMap.continueLoading();
		else ERMap.fnContinue = ERMap.continueLoading;
	},
	
	continueLoading: function() {
		// Create ERMapItem objects for each real estate item
		jQuery.each(ERMap.resItems, ERMapSales.addItem);
		
		ERMapSales.Results.stripe();
		
		// Create ERMapItem objects for each poi
		jQuery.each(ERMap.poiItems, ERMapPois.addItem);

		
		// Listen for changes to the sidebar
		jQuery('#type').change(ERMap.onChangeType);
		jQuery('#resPrice_min,#resPrice_max,#resBeds_min,#resBeds_max,#resBaths_min,#resBaths_max,#resSqft_min,#resSqft_max').add(ERMapSales.el_categories).change(ERMap.onClickSearch);
		jQuery('#updateBtn').click(ERMap.onClickSearch);
		
		ERMap.search('*');
		
		// If an item was passed to the page to load, load it
		if (matches = window.location.search.match(/res_id\=([0-9]+)/)) {
			ERMap.showInfo('sale', ERMapSales.itemIdMap[matches[1]]);
		}
	},
	
	/**
	 * Called when the property type (Sales or Rentals) is changed
	 * @param {Object} e
	 */
	onChangeType: function(e) {
console.info(this.selectedIndex, this.options[this.selectedIndex]);
	},
	
	onClickSearch: function(e) { ERMap.search(e.target.name); },
	
	/**
	 * Called when some element in the sidebar is changed.  Updates the search
	 * results and 
	 */
	search: function(type) {
		var queries = {};
		switch(type) {
			case '*':
			case 'cat':
				var cv = ERMapSales.el_categories.val() || [];
				queries.cat = "in\t" + cv.join("\t");
				if (type == 'cat') break;
			case 'price':
				queries.price = "btwn\t" + ERMapSales.els_priceMinMax.get(0).value + "\t" + ERMapSales.els_priceMinMax.get(1).value;
				if (type == 'price') break;
			case 'beds':
				queries.beds = "btwn\t" + ERMapSales.els_bedsMinMax.get(0).value + "\t" + ERMapSales.els_bedsMinMax.get(1).value;
				if (type == 'beds') break;
			case 'baths':
				queries.baths = "btwn\t" + ERMapSales.els_bathsMinMax.get(0).value + "\t" + ERMapSales.els_bathsMinMax.get(1).value;
				if (type == 'baths') break;
			case 'sqft':
				queries.sqft = "btwn\t" + ERMapSales.els_sqftMinMax.get(0).value + "\t" + ERMapSales.els_sqftMinMax.get(1).value;
				if (type == 'sqft') break;
		};
		jQuery.each(ERMapSales.items, function(i, n) { n.doSearch(queries); });
		ERMapSales.Results.stripe();
	},
	
	showInfo: function(type, obj) {
		var title, b1, b2, b3, b4, img, link;
		if (type == 'poi') {
			title = ERMAPDATA.poiCategories[obj.cat];
			b1 = obj.title;
			b2 = obj.address.split("\t").shift();
			b3 = obj.desc;
			b4 = '';
			img= '';
			link='';
		} else if (type == 'sale') {
			title = 'Sales - ' + ERMAPDATA.reCategories[obj.cat];
			b1 = obj.address.split("\t").shift();
			b2 = 'Price: <span class="highlight">'+obj.formattedPrice+'</span><br />MLS: <span class="highlight">'+obj.mls+'</span>';
			b3 = obj.desc;
			b4 = 'Sq. ft: <span class="highlight">'+obj.sqft+'</span><br />Bedrooms: <span class="highlight">'+obj.beds+'</span><br />Bathrooms: <span class="highlight">'+obj.baths+'</span><br />Stories: <span class="highlight">'+obj.stories+'</span>';
			img= obj.img;
			link='/sales/property.php?LID='+obj.id;
		}
		
		ERMap.showMapInfoWindow(obj.gm_marker, title, b1, b2, b3, b4, link, img);
	},
	
	showMapInfoWindow: function(marker, title, b1, b2, b3, b4, link, img) {
		ERMap.el_infoBox
			.find('#infoBoxHandle').html(title).end()
			.find('#infoBoxB1').html(b1).css('display', (b1 ? '' : 'none')).end()
			.find('#infoBoxB2').html(b2).css('display', (b2 ? '' : 'none')).end()
			.find('#infoBoxB3').html(b3).css('display', (b3 ? '' : 'none')).end()
			.find('#infoBoxB4').html(b4).css('display', (b4 ? '' : 'none')).end()
			.find('#infoBoxLink').attr('href', link).css('display', (link ? '' : 'none')).end()
			.find('#infoBoxImg').attr('src', img).css('display', (img ? '' : 'none')).end()
		;
		
		marker.openInfoWindow(ERMap.el_infoBox[0]);
	}
};

jQuery(ERMap.onDomReady);

