//================================================================================

if (typeof($) == "undefined")
{
	function $(id)
	{
		return document.getElementById(id);
	}
}

//================================================================================

	addArg = function( key, value, cur_loc )
	{
		if (typeof(cur_loc) != "undefined")
		{
			curLoc = cur_loc;
		}
		else
		{
			curLoc = location.href;
		}
		
		curLoc = curLoc.replace(new RegExp( key + '\=[^&]*', 'g' ), '');
		curLoc = curLoc.replace(new RegExp( '[^&]*\=&', 'g' ), '');
		curLoc += '&' + key + '=' + value;
		curLoc = curLoc.replace(new RegExp( '&{2,}', 'g' ), '&');
		return curLoc;
	};

//================================================================================

function setSelectionRange(input, selectionStart, selectionEnd)
{
	if (input.setSelectionRange)
	{
		input.focus();
		input.setSelectionRange(selectionStart, selectionEnd);
	}
	else if (input.createTextRange)
	{
		var range = input.createTextRange();
		range.collapse(true);
		range.moveEnd('character', selectionEnd);
		range.moveStart('character', selectionStart);
		range.select();
	}
};

//================================================================================

function Dump(d,l) {
    if (l == null) l = 1;
    var s = '';
    if (typeof(d) == "object") {
        s += typeof(d) + " {\n";
        for (var k in d) {
            for (var i=0; i<l; i++) s += "  ";
            s += k+": " + Dump(d[k],l+1);
        }
        for (var i=0; i<l-1; i++) s += "  ";
        s += "}\n"
    } else {
        s += "" + d + "\n";
    }
    return s;
};

//================================================================================

function evalidate(email)
{
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	if(reg.test(email) == false)
	{
		return false;
	}
	
	return true;
};

//================================================================================
			
function getTileUrl(tile_coords, oldzoom, btn)
{
	var currentProjection = G_NORMAL_MAP.getProjection();
	var tile_left_border = new GPoint();
	var tile_left_top_coord = new GLatLng();
	var tile_right_bottom_coord = new GLatLng();
		
	tile_left_border.x = tile_coords.x*256;
	tile_left_border.y = tile_coords.y*256;
	
	tile_left_top_coord = currentProjection.fromPixelToLatLng(tile_left_border, map.getZoom());
	
	tile_left_border.x += 256;
	tile_left_border.y += 256;
	
	tile_right_bottom_coord = currentProjection.fromPixelToLatLng(tile_left_border, map.getZoom());

	var _url = '/gmaps/ajax/create_tile.php?glat_start=' + tile_right_bottom_coord.y + '&glat_end=' + tile_left_top_coord.y +
	'&glong_start=' + tile_left_top_coord.x + '&glong_end=' + tile_right_bottom_coord.x + 
	'&code=' + tile_coords.x + '_' + tile_coords.y + '&btn=' + btn + '&zoom=' + map.getZoom();
	
	if (isWidget)
	{
		_url = 'http://fundrace.huffingtonpost.com' + _url;
	}
	
	return _url;
};

//================================================================================
			
function getTileLatLon(tile_coords, zoom)
{
	var currentProjection = G_NORMAL_MAP.getProjection();
	var tile_left_border = new GPoint();
	var tile_left_top_coord = new GLatLng();
	var tile_right_bottom_coord = new GLatLng();
		
	tile_left_border.x = tile_coords.x*256;
	tile_left_border.y = tile_coords.y*256;
	
	tile_left_top_coord = currentProjection.fromPixelToLatLng(tile_left_border, zoom);
	
	tile_left_border.x += 256;
	tile_left_border.y += 256;
	
	tile_right_bottom_coord = currentProjection.fromPixelToLatLng(tile_left_border, zoom);

	/*
	return {
			glat_start:tile_left_top_coord.y, glat_end:tile_right_bottom_coord.y,
			glong_start:tile_left_top_coord.x, glong_end:tile_right_bottom_coord.x,
			code: tile_coords.x + '_' + tile_coords.y,
			zoom:zoom
		};
	*/
	return '/gmaps/ajax/harvest_tile_coordinates.php?glat_start=' + tile_right_bottom_coord.y + '&glat_end=' + tile_left_top_coord.y +
	'&glong_start=' + tile_left_top_coord.x + '&glong_end=' + tile_right_bottom_coord.x + 
	'&code=' + tile_coords.x + '_' + tile_coords.y + '&zoom=' + zoom;
};
	
//================================================================================

function currentMapTypeIndex(aMap)
{
	var currentMap = aMap.getCurrentMapType();
	var mapTypes = aMap.getMapTypes();
	for (var i in mapTypes)
	{
		if (mapTypes[i] == currentMap)
		{
			return i;
		}
	}
	return -1;
};

//================================================================================

// Add all the layers to the map
function addHybridLayers(aMap, tile_urls, labels, centerPoint, zoom)
{
	var tilelayers = [];
	var hybridLayer = [];
	
	CustomMapTypes = [];
	
	for (var mapIndex = 0; mapIndex < tile_urls.length; mapIndex++)
	{
		tilelayers[mapIndex] = new GTileLayer(new GCopyrightCollection("Huffington Post"),5,15);
		tilelayers[mapIndex].getCopyright = function(a,b) { return {prefix:"Imagery: &#169; 2007", copyrightTexts:["Huffington Post"]}; }
		tilelayers[mapIndex].getTileUrl = tile_urls[mapIndex];
		
		hybridLayer[mapIndex] = [
		tilelayers[mapIndex],                  // a reference to the tile layer from the first custom map
		G_HYBRID_MAP.getTileLayers()[1] // a reference to the upper tile layer of the hybrid map
		];
		CustomMapTypes[mapIndex] = new GMapType(hybridLayer[mapIndex], G_SATELLITE_MAP.getProjection(), labels[mapIndex]);
		CustomMapTypes[mapIndex].getMinimumResolution = function() {return 3;};
		if (isWidget)
		{
			CustomMapTypes[mapIndex].getMaximumResolution = function() {return 16;};
		}
		aMap.addMapType(CustomMapTypes[mapIndex]);
	}
	
	aMap.removeMapType(G_SATELLITE_MAP);
	aMap.removeMapType(G_HYBRID_MAP);
	aMap.removeMapType(G_NORMAL_MAP);
	
};

//================================================================================

function RedrawMarkers(old_level, new_level)
{
	if (new_level > maxTileZoomLevel)
	{
		drawMarkers();
	}
};

//================================================================================

function MapTypeChanged()
{
	var types = map.getMapTypes();
	var current_type = map.getCurrentMapType();
	for (i in types)
	{
		if (types[i] == current_type)
		{
			mapTypeIndex = parseInt(i);
			current_btn = getCurrentBtn(mapTypeIndex);
		}
	}
	
	//clear donors
	//$('donor_search').innerHTML = '';
	drawMarkers();
};

//================================================================================

function addListeners(aMap)
{
	//GEvent.addListener(aMap, 'zoomend', listenerZoom);
	GEvent.addListener(aMap, 'zoomend', RedrawMarkers);
	GEvent.addListener(aMap, 'moveend', drawMarkers);
	GEvent.addListener(aMap, 'maptypechanged', MapTypeChanged);
	GEvent.addListener(map, 'click', MapClick);
};

//================================================================================

function MapClick(overlay, latlng)
{
	if (!latlng || map.getZoom() > maxTileZoomLevel || map.getZoom() < minClickZoomLevel)
	{
		if (map.getZoom() < minClickZoomLevel)
		{
			alert('Please zoom in to use search by click');
		}
		
		return;
	}
	
	if (isWidget)
	{
		om.Set('loading...');
	}
	else
	{
		om.Set('loading new results... data refreshed to the right of map');
	}
	
	var tileCoordinate = new GPoint();
	var currentProjection = G_NORMAL_MAP.getProjection();
	
	var tilePoint = currentProjection.fromLatLngToPixel(latlng, map.getZoom());
	tileCoordinate.x = Math.floor(tilePoint.x / 256)*256;
	tileCoordinate.y = Math.floor(tilePoint.y / 256)*256;

	var top_left = currentProjection.fromPixelToLatLng(tileCoordinate, map.getZoom());
	
	tileCoordinate.x += 256;
	tileCoordinate.y += 256;
	var bottom_right = currentProjection.fromPixelToLatLng(tileCoordinate, map.getZoom());

	var url_query = '?g_lat=' + latlng.y + '&g_lon=' + latlng.x
						+ '&zoom=' + map.getZoom()
						+ '&width=' + (bottom_right.x - top_left.x) + '&height=' + (top_left.y - bottom_right.y)
						+ '&btn=' + current_btn;
	
	if (!mapClickRedirect)
	{
		var donor_url = '/gmaps/ajax/get_donors_click.php' + url_query;
		lastMapSearchUrl = donor_url;

		GDownloadUrl(donor_url, function(data, responseCode)
			{
				if(responseCode == 200)
				{
					$('donor_search').innerHTML = data;
					highlight_results();
				}
				else
				{
					alert('Sorry, unable to retrieve data');
				}
				
				om.Clear();
			}
		);
	}
	else
	{
		//do redirect
		var redirect_url = '/neighbors.php' + url_query;
		if (isWidget)
		{
			redirect_url = 'http://fundrace.huffingtonpost.com' + redirect_url;
		}
		if (map.getZoom() == 4)
		{
			redirect_url = addArg('zoom', 8, redirect_url);
		}
		
		top.location.href = redirect_url;
	}
	
	//alert(bottom_right.x - top_left.x);
	//alert(top_left.y - bottom_right.y);

};

//================================================================================

function drawMarkers()
{
	if (map.getZoom() <= maxTileZoomLevel || !mgr || markersProcessing) return;
	
	markersProcessing = true;
	om.Set('Please wait, loading...');
		
	//get coordinates of the viewport
	var bounds = map.getBounds();
	var southWest = bounds.getSouthWest();
	var northEast = bounds.getNorthEast();
	var marker_url = '/gmaps/ajax/get_markers.php?glat_start=' + southWest.y + '&glong_start=' + southWest.x + 
		'&glat_end=' + northEast.y + '&glong_end=' + northEast.x + '&btn=' + current_btn;
	if (isWidget)
	{
		marker_url = 'http://fundrace.huffingtonpost.com' + marker_url;
	}
	var marker_coords = [];
	
	mgr.clearMarkers();
	
	GDownloadUrl(marker_url, function(data, responseCode)
		{
			var markers = [];
			if(responseCode == 200)
			{
				om.Set('Retrieved, processing...');
				if (data)
				{
					eval(data);
					var myIcon = new GIcon(G_DEFAULT_ICON);
					myIcon = getMixedIcon(getCurrentBtn(mapTypeIndex), myIcon);
										
					// Set up our GMarkerOptions object
					markerOptions = { icon:myIcon };
					
					for (i = 0; i < markers_source.length; i++)
					{						
						markers.push(createMarker(markers_source[i], markerOptions));
					}
					delete markers_source;

					mgr.addMarkers(markers, maxTileZoomLevel + 1);
					mgr.refresh();
					delete markers;
				}
			}
			else
			{
				alert('Sorry, unable to retrieve data');
			}
			
			om.Clear();
			markersProcessing = false;
			return false;
    	}
    );
    
};

//================================================================================

function createMarker(params, options)
{
	var point = new GLatLng(params.g_lat, params.g_lon);
	
	var myIcon = new GIcon(G_DEFAULT_ICON);
	myIcon = getMixedIcon(params.party, myIcon);
	options.icon = myIcon;
	options.title = 'Click to search';
	
	marker = new GMarker(point, options);
	
	GEvent.addListener(marker, "click", function()
			{
				var url_query = '?g_lat=' + params.g_lat + '&g_lon=' + params.g_lon + '&btn=' + current_btn;
				if (!mapClickRedirect)
				{
					om.Set('loading new results... data refreshed to the right of map');
					
					var donor_url = '/gmaps/ajax/get_donors.php' + url_query;
					lastMapSearchUrl = donor_url;
					
						//retrieve donors
						GDownloadUrl(donor_url, function(data, responseCode)
							{
								if(responseCode == 200)
								{
									$('donor_search').innerHTML = data;
									highlight_results();
								}
								else
								{
									alert('Sorry, unable to retrieve data');
								}
								
								om.Clear();
					    	}
				    	);
				}
				else
				{
					//do redirect
					var redirect_url = '/neighbors.php' + url_query;
					if (isWidget)
					{
						redirect_url = 'http://fundrace.huffingtonpost.com' + redirect_url;
					}
					top.location.href = redirect_url;
				}
			}
		);
	
	return marker;
};

//================================================================================

function getMixedIcon(party, icon)
{
	switch (party)
	{
		case 'dem':
		case 'clinton':
		case 'obama':
			icon.image = "/gmaps/images/donkey.png";
			icon.shadow = "/gmaps/images/shadow_donk.png";
			icon.transparent = "/gmaps/images/donkey_trans.png";
			icon.imageMap = [4,8, 18,8, 23,3, 24,0, 26,2, 29,2, 28,5, 32,11, 31,13, 28,14, 25,12, 22,18, 21,26, 17,26, 17,23, 9,23, 9,26, 4,26, 4,17, 0,14];
			icon.iconSize = new GSize(32, 27);
			icon.shadowSize = new GSize(32, 27);
			icon.iconAnchor = new GPoint(16, 16);
		break;
		case 'mix':
		case 'mix_older':
			icon.image = "/gmaps/images/mix.png";
			icon.shadow = "/gmaps/images/shadow_mix.png";
			icon.transparent = "/gmaps/images/mix_trans.png";
			icon.imageMap = [10,26, 10,18, 6,12, 2,14, 0,10, 3,6, 2,2, 5,3, 7,1, 13,9, 17,7, 23,7, 29,10, 29,19, 33,19, 32,25, 30,26, 26,26, 26,20, 24,20, 24,26, 19,26, 19,22, 15,22, 15,26];
			icon.iconSize = new GSize(34, 27);
			icon.shadowSize = new GSize(42, 27);
			icon.iconAnchor = new GPoint(16, 16);
		break;
		default:
			icon.image = "/gmaps/images/elephant.png";
			icon.shadow = "/gmaps/images/shadow_elph.png";
			icon.transparent = "/gmaps/images/elephant_trans.png";
			icon.imageMap = [4,24, 4,8, 9,5, 18,5, 24,9, 24,17, 28,17, 27,23, 21,24, 21,18, 19,18, 19,24, 14,24, 14,20, 10,20, 10,24];
			icon.iconSize = new GSize(32, 27);
			icon.shadowSize = new GSize(36, 27);
			icon.iconAnchor = new GPoint(16, 16);
	}
	
	return icon;
};

//================================================================================

function getCurrentBtn(map_index)
{
	map_index = parseInt(map_index);
	switch (map_index)
	{
		case 0:
			return 'mix';
		case 1:
			return 'mixcand';
		case 2:
			return 'obama';
		case 3:
			return 'clinton';
		case 4:
			return 'mccain';
		case 5:
			return 'mix_older';
	}
	
	return 'mix';
};

//================================================================================

function getQueryVariable(variable)
{
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++)
	{
		var pair = vars[i].split("=");
		if (pair[0] == variable)
		{
			return pair[1];
		}
	} 
	return "NULL";
};

//================================================================================

function validateQueryLatLong(defaultLat, defaultLong)
{
	var latitude = parseFloat(getQueryVariable("g_lat"));
	var longitude = parseFloat(getQueryVariable("g_lon"));
	
	if(isNaN(longitude) || (longitude < -180) || (longitude > 180) || (isNaN(latitude) || (latitude < -90) || (latitude > 90)))
	{
		return new GLatLng(defaultLat, defaultLong);
	}
	
	return new GLatLng(latitude, longitude); 
};

//================================================================================

function validateQueryInt(key, min, max, defaultValue)
{
	var value = parseInt(getQueryVariable(key));
	if(isNaN(value) || value > max || value < min)
	{
		return defaultValue;
	}
	return value;
};

//================================================================================

function validateQueryFloat(key, min, max, defaultValue)
{
	var value = parseFloat(getQueryVariable(key));
	if(isNaN(value) || value > max || value < min)
	{
		return defaultValue;
	}
	return value;
};

//================================================================================

function ChangeFilter(list, arg)
{
	if (!lastMapSearchUrl)
	{
		//do reload - casual search
		window.location = addArg(arg, list.options[list.selectedIndex].value, addArg('off', 0))
	}
	else
	{
		om.Set('Please wait, loading...');
		
		lastMapSearchUrl = addArg('off', 0, lastMapSearchUrl);
		lastMapSearchUrl = addArg(arg, list.options[list.selectedIndex].value, lastMapSearchUrl);
		
		GDownloadUrl(lastMapSearchUrl, function(data, responseCode)
			{
				if(responseCode == 200)
				{
					$('donor_search').innerHTML = data;
					highlight_results();
				}
				else
				{
					alert('Sorry, unable to retrieve data');
				}
				
				om.Clear();
			}
		);
	}
};

//================================================================================

function highlight_results()
{
	var canim = new YAHOO.util.ColorAnim( 'result_search_head',
	    {
	        backgroundColor:{ 
	        	from:'#FFF',
	            to:'#000'
	        }
	    });
	    
	canim.animate();
};

//================================================================================

function ProcessSearchMarkers()
{
	//can't show search markers if we are on markers level now
	if (map.getZoom() > maxTileZoomLevel) return;

	markers = [];
	mgr.clearMarkers();
	
	if (searchMarkers.length)
	{
		for (k in searchMarkers)
		{
			markers.push(createMarker(searchMarkers[k], {}));
		}
	
		//alert(markers.length);
		if (markers.length)
		{
			mgr.addMarkers(markers, 10, 16);
			mgr.refresh();
			delete markers;
			
			if (highlight > 0 && infoWindows[highlight])
			{
				$('donor_row_' + highlight).scrollIntoView();
				HighlightResultOnMap(highlight);
			}
			else
			{
				//show info window in the first result
				first_id = 0;
				for (k in infoWindows)
				{
					first_id = parseInt(k);
					break;
				}
				if (first_id > 0)
				{
					HighlightResultOnMap(first_id);
				}
			}
		}
	}
};

//================================================================================

function HighlightResultOnMap(donor_id)
{
	if (typeof(lastHighlightedResult) != "undefined" && lastHighlightedResult != donor_id && infoWindows[donor_id])
	{
		if ($('donor_row_' + lastHighlightedResult))
		{
			//animation old row from yellow to white
			var canim_old = new YAHOO.util.ColorAnim( 'donor_row_' + lastHighlightedResult,
			    {
			        backgroundColor:{ 
			        	from:'#EEE8AA',
			            to:'#FFF'
			        }
			    });
			canim_old.animate();
		}
		
		//animate new row from white to yellow
		var canim_new = new YAHOO.util.ColorAnim( 'donor_row_' + donor_id,
		    {
		        backgroundColor:{ 
		        	from:'#FFF',
		            to:'#EEE8AA'
		        }
		    });
		canim_new.animate();
		//alert(donor_id);
		map.openInfoWindow(new GLatLng(infoWindows[donor_id].g_lat, infoWindows[donor_id].g_lon), $('search_result_' + donor_id).innerHTML);
		lastHighlightedResult = donor_id;
	}
	
	return false;
};

//================================================================================

function ShowShareMapArea()
{
	if (shareControl) return;
	
	shareControl = new ShareControl();
	map.addControl(shareControl);
	
	$('share_control_container').style.MozUserSelect = 'text';
	$('share_control_container').unselectable = 'off';
	$('share_control_container').onselectstart = function(){return true};;
	
	var input = $('share_control_input');
	setSelectionRange(input, 0, input.value.length);
	GEvent.addDomListener(input, "click", function()
		{
			setSelectionRange(input, 0, input.value.length);
		}
	);
	GEvent.addDomListener(input, "blur", function()
		{
			setSelectionRange(input, 0, input.value.length);
		}
	);
};

//================================================================================

function HideShareMapArea()
{
	if (!shareControl) return;
	
	map.removeControl(shareControl);
	shareControl = null;
};

//================================================================================

function GetMapUrl()
{
	var map_url = addArg('search', '');
	map_url = addArg('zoom', map.getZoom(), map_url);
	map_url = addArg('g_lon', map.getCenter().x, map_url);
	map_url = addArg('g_lat', map.getCenter().y, map_url);
	map_url = addArg('highlight', lastHighlightedResult, map_url);
	map_url = addArg('mapIndex', mapTypeIndex, map_url);
	
	return map_url;
};

//================================================================================

// The current version of this code is always available at:
// http://www.acme.com/javascript/
//
//
// Copyright © 2006 by Jef Poskanzer <jef@mail.acme.com>.
// All rights reserved.

OverlayMessage = function ( container )
    {
    // Terminology:
    // +-----------------+
    // |wrapper          |
    // |+---------------+|
    // ||container      ||
    // ||   +-------+   ||
    // ||   |overlay|   ||
    // ||   +-------+   ||
    // ||               ||
    // |+---------------+|
    // +-----------------+

    // Get the parent.
    var parent = container.parentNode;

    // Make the wrapper div.
    var wrapper = document.createElement( 'div' );
    wrapper.style.cssText = container.style.cssText;
    parent.insertBefore( wrapper, container );

    // Move the container into the wrapper.
    parent.removeChild( container );
    wrapper.appendChild( container );
    container.style.cssText = 'position: relative; width: 100%; height: 100%;';

    // Add the overlay div.
    this.overlay = document.createElement( 'div' );
    wrapper.appendChild( this.overlay );
    this.visibleStyle = 'position: relative; top: -55%; color: ' + OverlayMessage.color + '; background-color: ' + OverlayMessage.backgroundColor + '; width: 25%; text-align: center; margin-left: auto; margin-right: auto; padding: 5px; border: 0' + OverlayMessage.borderColor + '; z-index: 100; opacity: .70; filter: alpha(opacity=70);';
    this.invisibleStyle = 'display: none;';
    this.overlay.style.cssText = this.invisibleStyle;
    };


OverlayMessage.backgroundColor = '#663300';
OverlayMessage.borderColor = '#330000';
OverlayMessage.color = '#fff';


OverlayMessage.prototype.Set = function ( message )
    {
    this.overlay.innerHTML = message;
    this.overlay.style.cssText = this.visibleStyle;
    };


OverlayMessage.prototype.Clear = function ()
    {
    this.overlay.style.cssText = this.invisibleStyle;
    };


OverlayMessage.SetBackgroundColor = function ( color )
    {
    OverlayMessage.backgroundColor = color;
    };


OverlayMessage.SetBorderColor = function ( color )
    {
    OverlayMessage.borderColor = color;
    };

//================================================================================

/*HuffPoMapTypeControl*/

function HuffPoMapTypeControl(shift_parties, older)
{
	this.ShiftParties = shift_parties;
	this.Older = false;
	if (typeof(older) != 'undefined')
	{
		this.Older = older;
	}
};

HuffPoMapTypeControl.prototype = new GControl();
HuffPoMapTypeControl.selectedMapButton = {};

//================================================================================

HuffPoMapTypeControl.prototype.initialize = function(map) {
	var container = document.createElement("div");

	var mapTypes = map.getMapTypes();
	
	// 2008 case
	var start = 0;
	var end = 5;
	
	if (this.Older)
	{
		// 2004 case
		start = 5;
		end = 6;
	}
	
	for (var i=start; i < end; i++)
	{
		var button = document.createElement("div");
		this.setButtonStyle_(button, i);
		if (mapTypeIndex == i)
		{
			HuffPoMapTypeControl.selectedMapButton = button;
			button.style.fontWeight = "bold";
			button.style.border = "1px solid #000";
		}
		
		button.appendChild(document.createTextNode(label[i]));
		
		this.addListeners_(button, mapTypes[i]);
		
		container.appendChild(button);

		if (this.ShiftParties && i == 1)
		{
			var button = document.createElement("div");
			this.setButtonStyle_hidden(button);
			button.appendChild(document.createTextNode(label[i]));
			container.appendChild(button);
		}
	}
	
	map.getContainer().appendChild(container);
	return container;
}

//================================================================================

HuffPoMapTypeControl.prototype.addListeners_ = function(button, map_type)
{
	GEvent.addDomListener(button, "click", function(el)
	{
		HuffPoMapTypeControl.selectedMapButton.style.fontWeight = "normal";
		HuffPoMapTypeControl.selectedMapButton.style.border = "1px solid #aaa";
		map.setMapType(map_type);
		HuffPoMapTypeControl.selectedMapButton = button;
		HuffPoMapTypeControl.selectedMapButton.style.fontWeight = "bold";
		HuffPoMapTypeControl.selectedMapButton.style.border = "1px solid #000";
	});
}

//================================================================================

HuffPoMapTypeControl.prototype.getDefaultPosition = function()
{
	return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 7));
}

//================================================================================

HuffPoMapTypeControl.prototype.setButtonStyle_ = function(button, i)
{
	button.style.textDecoration = "none";
	button.style.color = "#000";
	button.style.backgroundColor = "white";
	button.style.font = "small Arial";
	button.style.border = "1px solid #aaa";
	button.style.padding = "0 2px 0 2px";
	button.style.marginBottom = "3px";
	button.style.textAlign = "center";
	button.style.width = "6.5em";
	button.style.cursor = "pointer";
	button.setAttribute('id', 'top_map_button_'+i);
}

//================================================================================

HuffPoMapTypeControl.prototype.setButtonStyle_hidden = function(button)
{
	button.style.visibility = "hidden";
	button.style.width = "6.5em";
	button.style.padding = "2px";
	button.style.marginBottom = "3px";
	button.setAttribute('id', 'top_map_button_hidden');
}

//================================================================================

//================================================================================

/*HuffPo2004Control*/

function HuffPo2004Control(shift_parties)
{
	this.ShiftParties = shift_parties;
	this.Selected2004 = false;
};

HuffPo2004Control.prototype = new GControl();
HuffPo2004Control.ShiftParties = '';
HuffPo2004Control.Selected2004 = false;

//================================================================================

HuffPo2004Control.prototype.initialize = function(map)
{
	HuffPo2004Control.ShiftParties = this.ShiftParties;
	HuffPo2004Control.Selected2004 = this.Selected2004;
	
	var container = document.createElement("div");
	var button = document.createElement("div");
	var text = '';
	this.setButtonStyle_(button);
	
	if (this.Selected2004)
	{
		text = 'Click to see 2008 map';
	}
	else
	{
		text = 'Click to see 2004 map';
	}
	
	button.appendChild(document.createTextNode(text));
	this.addListeners_(button);	
	container.appendChild(button);
	
	map.getContainer().appendChild(container);
	return container;
}

//================================================================================

HuffPo2004Control.prototype.addListeners_ = function(button)
{
	GEvent.addDomListener(button, "click", function(el)
	{
		map.removeControl(MapButtonsControl);
		HuffPo2004Control.Selected2004 = !HuffPo2004Control.Selected2004;
		if (HuffPo2004Control.Selected2004)
		{
			button.innerHTML = 'Click to see 2008 map';
			button.style.background = 'yellow none repeat scroll 0%';
			mapTypeIndex = 5;
			MapButtonsControl = new HuffPoMapTypeControl(HuffPo2004Control.ShiftParties, true);
		}
		else
		{
			button.innerHTML = 'Click to see 2004 map';
			button.style.background = 'white none repeat scroll 0%';
			mapTypeIndex = 0;
			MapButtonsControl = new HuffPoMapTypeControl(HuffPo2004Control.ShiftParties);
		}
		
		map.setMapType(map.getMapTypes()[mapTypeIndex]);
		map.addControl(MapButtonsControl);
	});
}

//================================================================================

HuffPo2004Control.prototype.getDefaultPosition = function()
{
	return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7, 280));
}

//================================================================================

HuffPo2004Control.prototype.setButtonStyle_ = function(button)
{
	button.style.textDecoration = "none";
	button.style.color = "#000";
	button.style.backgroundColor = "white";
	button.style.font = "small Arial";
	button.style.border = "1px solid #aaa";
	button.style.marginBottom = "3px";
	button.style.textAlign = "center";
	button.style.width = "6.5em";
	button.style.cursor = "pointer";
	button.style.fontWeight = 'bold';
	button.setAttribute('id', 'map_button_2004');
}

//================================================================================
