$(function() {
	initialize_map();
	// Initialize main_center tabs.
	var is_loaded = { q_apt_all:true }; // Stores boolean values for div_ids; helps determine whether the map should be reloaded on select.
	$("#main_center_tabs").tabs({ cache:true, remote:true, select:function(e,ui){
		// Determine search_type by checking the number of created tabs: 3 are used on the sales page, 5 on rentals.
		var stype = $(this).tabs('length')>3 ? 'rental' : 'sale';
		// div_id should be set in global scope for it's used by other functions.
		switch(ui['index']) {
			case 1: 	div_id='q_apt_new'; break;
			case 2: 	div_id=stype=='sale'?'q_favorites':'q_nofee'; break;
			case 3: 	div_id='q_broker'; break;
			case 4: 	div_id='q_favorites'; break;
			default: 	div_id='q_apt_all'; break;
		} 
		$(this).tabs('option', 'ajaxOptions', {data:'div_id='+div_id+'&task=summon_tabs&search_type='+stype,type:'POST'});
		// Update the map.
		if (is_loaded[div_id]) { update_map('div_id='+div_id) }
	},
	// Once a tab's content is loaded, update the map.
	load:function(e,ui){ setTimeout("update_map('div_id='+div_id)", 500); is_loaded[div_id] = true; }});
	//$('#main_center_tabs').bind('tabsselect', function(e, ui) {});
	$('.Paginator #page').live( 'click', function() { handle_listings( $(this).attr('rel') ) } );
	$('select#perpage,select#sort').live( 'change', function() { handle_listings( $(this).val() ) } );
});

// Handles pagination, perpage.
function handle_listings(par) { 
	// Exctact the name of the query which is also the id of a div element encapsulating .Paginator and listings.
	var div_id = par.replace( /^[\S]*div_id=([0-9a-z_]+)[\S]*$/i, '$1');
	$('#'+div_id).html("<p style='text-align:center'><img src='/images/ajax-loader.gif'></img></p>");
	$.ajax({
		data: par,
		dataType: 'html',
		type: 'POST',
		//cache: false,
		success: function(data) { $('#'+div_id).html(data);	update_map('div_id='+div_id); },
		error: function(raw, textStatus, errorThrown) {alert('fail')},
		url: '/ajax_handler/listings.cfm',
	});
}

function update_map(div_id) {
	for (var marker in markers.refs) { markers.refs[marker].setMap(null) }
	$.ajax({
		url: '/ajax_handler/listings.cfm',
		data: div_id+'&task=get_map_data',
		type: 'POST',
		dataType: 'json',
		success: function(data, t){
			if (data.RECORDCOUNT) {
				// var info_window = {};
				// Setup markers.
				for (var aptid in data.RECORDS) {
					var mark_tmp = '_'+aptid;
					markers.refs[mark_tmp] = new google.maps.Marker({
						map: map_results,
						position: new google.maps.LatLng( data.RECORDS[aptid].LATLON[0], data.RECORDS[aptid].LATLON[1] ),
						icon: markers.image,
						shadow: markers.shadow,
						shape: markers.shape });
					add_info(markers.refs[mark_tmp], data.RECORDS[aptid].INFO_CONTENT);
				}
				map_results.panTo(new google.maps.LatLng( data.CENTER[0], data.CENTER[1] ));
			}
		},
		error: function(a,b,c){ alert(b,c); }
	});
}

function array_average(arr) {
	var sum = 0;
	for (var a in arr) {
		sum += arr[a];
	}
	return sum/arr.length;
}

function add_info(marker, content) {
	var info_window = new google.maps.InfoWindow({ content: content });
	google.maps.event.addListener(marker, 'click', function() {
		info_window.open(map_results, marker);
	}); 
}