/*global google $*/ // Comments for jsLint debugging tool

var gInfoWindow, gMarker, siteId, siteURL, siteListingResource, initialLatitude, initialLongditude, mapCanvas, mapOptions, googleMap, subArea, searchCity, listingsMarker, thumbnailHeight, thumbnailWidth;
gInfoWindow = null;
gMarker = null;

/*
 * Per-Site variables feel free to configure at will
 */

// The URL and id of the site and agent
agentId = 22;
siteId = 368;
siteURL = "http://shaughnessyproperties.com/";

// The ajax file that will generate the list of property listings
siteListingResource = "aj_listing_map.php?callback=?";

// The sub-area to search - blank means to search the whole city
if(typeof(subArea)==='undefined')
{
	subArea = 'Shaughnessy';
}

// The initial longditude and latitude that the map will be centered on
initialLatitude = 49.253464;
initialLongditude = -123.134959;

// The id of the div that will contain the map
mapCanvas = "map_canvas";

// The two images to use to mark listings with listings and those without
// These images are assumed to be in the /images directory off of the root directory
if(typeof(listingsMarker)==='undefined')
{
	listingsMarker = "pin-blue.png";
}

// The height and width of the thumbnail displayed in the popup
thumbnailHeight = 150;
thumbnailWidth = 200;

//This is the default map zoom, which is used if zoom is not defined outside of this file
if(typeof(mapZoom)==='undefined')
{
	mapZoom = 15;
}

//Filter Settings
if(typeof(filters)==='undefined') filters = {};
if(filters.area==null)
{
	filters.area = {
		'min_val':800,
		'max_val':9000
	};
}
if(filters.price==null)
{
	filters.price = {
		'min_val':300000,
		'max_val':1500000
	};
}

// The following will control the options for the google map
// Please refer to: http://code.google.com/apis/maps/documentation/v3/reference.html#MapOptions
mapOptions = {
    zoom: mapZoom,
    scrollwheel: true,
    draggable: true,
    center: new google.maps.LatLng(initialLatitude, initialLongditude),
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    mapTypeControl: false,
    scaleControl: false
};

mapMarkers = [];
ajaxStack = [];
if(typeof(loader_id)==='undefined')
{
	loader_id = 'map_loader';
}
/*
 * DO NOT EDIT BELOW THIS LINE!
 */

/*****************************************************************************/

function createMap(lat, lng) {
    return new google.maps.Map(document.getElementById(mapCanvas), mapOptions);
}

/*****************************************************************************/
function addAjaxLoader()
{
	ajaxStack.push('call');
	$('#'+loader_id).show();
}
function createMapLoader(div_holder, loader_id) {
	$('#'+div_holder).append('<div id="'+loader_id+'"><div class="round_box" id="'+loader_id+'_inner"><h5>Loading</h5><img src="images/loading_bar.gif" width="220" height="19" /></div></div>');
	$('#'+loader_id).hide();
	$('#'+loader_id).ajaxComplete(function() {
		ajaxStack.pop();
		if(ajaxStack.length==0)
		{
			$(this).hide();
		}
	});
}
/*****************************************************************************/
function changeSubArea(subArea_in, marker_in)
{
	subArea = subArea_in;
	listingsMarker = marker_in;
	addAjaxLoader();
	$.getJSON(siteURL + siteListingResource, {'subarea': subArea, 'city': searchCity, 'filters': filters}, populateMap);
}
/*****************************************************************************/
function createMapSlider(filter_type, slider_div, slider_value, bounds, is_currency)
{
	$("#"+slider_div).slider({
		range: true,
		min: bounds.min_val,
		max: bounds.max_val,
		step: (bounds.max_val-bounds.min_val)/200,
		values: [filters[filter_type].min_val, filters[filter_type].max_val],
		slide: function(event, ui) {
			var currency_char = $("#"+slider_div).data('is_currency')?'$':'';
			$("#"+slider_value).val(currency_char + $.currency(ui.values[0],{s:",",d:".",c:0}) + ' - '+ currency_char + $.currency(ui.values[1],{s:",",d:".",c:0}));
		},
		change: function(event, ui) {
			filters[$(this).data('filter_type')].min_val = ui.values[0];
			filters[$(this).data('filter_type')].max_val = ui.values[1];
			addAjaxLoader();
			$.getJSON(siteURL + siteListingResource, {'subarea': subArea, 'city': searchCity, 'filters': filters}, populateMap);
		}
	});
	//Slider Data
	$("#"+slider_div).data('filter_type', filter_type);
	$("#"+slider_div).data('is_currency', is_currency);
	//Set Default Values
	var currency_char = $("#"+slider_div).data('is_currency')?'$':'';
	$("#"+slider_value).val(currency_char + $.currency($("#"+slider_div).slider("values", 0),{s:",",d:".",c:0}) + ' - '+currency_char + $.currency($("#"+slider_div).slider("values", 1),{s:",",d:".",c:0}));
}

/*****************************************************************************/

function createInfoWindowDiv(data) {
	var div, found, i;

	if (!data) {
		return '';
	}

	found = false;
	for(var i=0;i<data.agent_id.length;++i) {
		if(agentId === data.agent_id[i]) {
			found = true;
			break;
		}
	}

	div =
	'<div style="width:425px;color:#000;">' +
    '<table cellspacing="0" border="0" cellpadding="2">' +
    	'<tr>' +
    		'<td>' + '<a href="' + data.link + '"><img border="0" width="' + thumbnailWidth + '" height="' + thumbnailHeight + '" src="' + data.img + '"/></a>' + '</td>' +
			'<td style="color:#000;">' +
				'<table width="100%" cellspacing="0" cellpadding="2" border="0">' +
					'<tr><td width="30%" style="color:#000;"><strong>Price</strong></td><td width="70%" style="color:#000;">' + data.price + '</td></tr>' +
					'<tr><td valign="top" style="color:#000;"><strong>Address</strong></td><td style="color:#000;">' + data.address + '</td></tr>' +
					'<tr><td valign="top" style="color:#000;"><strong>City</strong></td><td style="color:#000;">' + data.city + '</td></tr>' +
					'<tr><td valign="top" style="color:#000;"><strong>Bedrooms</strong></td><td style="color:#000;">' + data.bedrooms + '</td></tr>' +
					'<tr><td valign="top" style="color:#000;"><strong>Bathrooms</strong></td><td style="color:#000;">' + data.bathrooms + '</td></tr>' +
					'<tr><td valign="top" style="color:#000;"><strong>Sqft.</strong></td><td style="color:#000;">' + data.sqft + '</td></tr>' +
					'<tr><td valign="top" style="color:#000;"><strong>Type</strong></td><td style="color:#000;">' + data.type + '</td></tr>' +
					'<tr><td valign="top" style="color:#000;"><strong>Listed By</strong></td><td style="color:#000;">' + data.listed + '</td></tr>' +
				'</table>' +
			'</td>' +
		'</tr>' +
		'<tr>' +
			'<td align="left"><strong><a style="color:#007;font-size:12px;font-weight:bold;" href="' + data.link + '">More information</a></strong></td>' +
			'<td align="right">' + (found ? '&nbsp' : '<img src="images/reciprocity.gif" alt="" height="29" width="30">') + '</td>' +
		'</tr>' +
	'</table>' +
	'</div>';

	return div;
}

/*****************************************************************************/

function populateMap(json) {
	var i, m;

	if (json.success) {
		//Clear Markers
		if (mapMarkers) {
			for (i in mapMarkers) {
				mapMarkers[i].setMap(null);
			}
		}
		mapMarkers = [];

		for (i = 0; i < json.listings.length; ++i) {
			m = new google.maps.Marker({
			    position: new google.maps.LatLng(json.listings[i].lat, json.listings[i].lng),
			    title: json.listings[i].address,
				icon: 'images/' + listingsMarker,
			    map: googleMap
			});
			m.listing_id = json.listings[i].id;
			mapMarkers.push(m);

			google.maps.event.addListener(m, 'click', function () {
				gMarker = this;

				if(null !== gInfoWindow) {
					gInfoWindow.close();
					delete gInfoWindow;
					gInfoWindow = null;
				}

				$.getJSON(siteURL + siteListingResource, {listing: this.listing_id, height: thumbnailHeight, width: thumbnailWidth}, function(json) {
					if (json.success) {
						gInfoWindow = new google.maps.InfoWindow();
						gInfoWindow.setContent(createInfoWindowDiv(json.listing));
						gInfoWindow.open(googleMap, gMarker);
					}
				});
			});
		}
	}
}

/*****************************************************************************/

$(document).ready(function () {
	googleMap = createMap(initialLatitude, initialLongditude);
	addAjaxLoader();
    $.getJSON(siteURL + siteListingResource, {'subarea': subArea, 'city': searchCity, 'filters':filters}, populateMap);
});
