var map = null;
var geocoder = null;
var blueIcon = null;
var orangeIcon = null;
var mapData = [];
var mgr = null;

$(document).ready(function()
{
	/*var queryString = (parent.window) ? parent.window.location.search : window.location.search;
	var matches = queryString.match("[?]id=([0-9]+)");
	if (matches)
	{
		eventId = matches[1];
	}*/		
	
	if (GBrowserIsCompatible()) 
	{
		map = new GMap2(document.getElementById('map'));
		geocoder = new GClientGeocoder();
	    map.addControl(new GSmallMapControl());
	    map.addControl(new GMapTypeControl());	    
	    
	    var baseIcon = new GIcon(G_DEFAULT_ICON);
	    baseIcon.iconSize = new GSize(30, 45);
	    baseIcon.shadowSize = new GSize(47, 45);
	    baseIcon.iconAnchor = new GPoint(9, 34);
	    baseIcon.infoWindowAnchor = new GPoint(11, 6);

	    orangeIcon = new GIcon(baseIcon);
	    orangeIcon.image = "http://www.globalactionnow.org/nbn_wmd/public/images/orange_marker.png";
	    
	    blueIcon = new GIcon(baseIcon);
	    blueIcon.image = "http://www.globalactionnow.org/nbn_wmd/public/images/blue_marker.png";
	    	    
	    map.checkResize();
	    map.setCenter(new GLatLng(50.4419, -66.1419), 4); //USA
	    
	    mgr = new MarkerManager(map);
	}
	
	$('#addEvent').click(showEventForm);
	
	$('#findEvent').click(function()
	{
		adjustHeight();
		$('#overlay').show();
		$('#content').load(baseUrl+'/default/index/event-search-form', function()
		{
			bindEventForm();
			$(this).show();
			$('#overlay').hide();
			$('#map').hide();
			$('#map-icons').hide();
		});
		return false;
	});
	
	$('.maptype').click(function()
	{
		map.clearOverlays();
		if ($(this).attr('rel') == 'camps')
			getRefugees(true);
		else	
			reloadMap($(this).attr('rel'));
		return false;
	});
		
	bindLoginButton();
	bindShare();
	getMapData();	
});

function bindLoginButton()
{
	$('#login').click(function()
	{
		adjustHeight();
		$('#overlay').show();
		$('#content').load(baseUrl+'/default/index/login', function()
		{
			$(this).show();
			$('#overlay').hide();
			$('#map').hide();
			$('#map-icons').hide();
			bindLoginForm();
			bindEventForm();
		});
		return false;
	});
}

var timeoutFlag = false;

function handleLoginTimeout()
{
	if (!timeoutFlag)
	{
		if ($('#login-error').length > 0) $('#login-error').remove();
		$('#fundraiser-login').after('<p class="error" id="login-error" style="padding-bottom:5px;"><strong>Incorrect email/password. Emails are case sensitive. Please check your CAPS lock key. Or, you can retrieve your password using the field below.</strong></p>');
	}
}

function bindLoginForm()
{	
	$('#lostpass').ajaxForm(
	{
		beforeSubmit: function()
		{
			setTimeout('handleLoginTimeout()', 15000);
			$('#overlay').show();
			adjustHeight();
		},
		success: function(data)
		{
			timeoutFlag = true;
			$('#overlay').hide();
			$('#content').html(data);	
			bindLoginForm();
		},
		timeout: 15000
	});
	
	$('#login-form').ajaxForm(
	{
		beforeSubmit: function()
		{
			$('#overlay').show();
			adjustHeight();
		},
		success: function(data)
		{
			$('#overlay').hide();
			$('#content').html(data);	
			bindLoginForm();
			bindEventForm();
		}
	});
}

function doLogout()
{
	$('#already-onmap').html('Already on the map? <a href="#" id="login">Log in!</a>');
	bindLoginButton();
	showMap();
}

function setLoginStatus(name)
{
	$('#already-onmap').html('Welcome, <a href="#" id="username">'+name+'</a> &#8212; <a href="#" id="logout">Log out</a>');
	$('#username').click(function()
	{
		adjustHeight();
		$('#overlay').show();
		$.get(baseUrl+'/default/index/get-profile', {}, function(data)
		{
			$('#overlay').hide();
			$('#content').html(data).show();
			$('#map').hide();
			$('#map-icons').hide();
			bindLoginForm();
			bindEventForm();
		});
		return false;
	});
	
	$('#logout').click(function()
	{
		$.get(baseUrl+'/default/index/logout', {}, doLogout);
		return false;
	});
}

function getMapData()
{
	$.get(baseUrl+'/default/index/get-refugees', {}, function(results)
	{
		if (results.length > 0)
		{
			for (var i = 0; i < results.length; i++)
			{
				results[i].isRefugee = true;
				mapData.push(results[i]);
			}						
		}
	},
	'json');
	
	$.get(baseUrl+'/default/index/get-map-data', {}, function(results)
	{
		if (results.length > 0)
		{
			for (var i = 0; i < results.length; i++)
			{
				results[i].isRefugee = false;
				mapData.push(results[i]);
			}
			
			$('#overlay').hide();
			reloadMap('us');
		}
	},
	'json');
}

function showEventForm()
{
	adjustHeight();					
	$('#overlay').show();	
	$('#content').load(baseUrl+'/default/index/event-form', function()
	{
		bindEventForm();
		$(this).show();
		$('#overlay').hide();
		$('#map').hide();
		$('#map-icons').hide();
	});
	return false;
}

function adjustHeight()
{
	if ($('#map').is(':visible'))
	{
		$('#overlay').css({height:'400px'});
		$('#preloader').css({top:'193px'});
	}
	else
	{
		$('#overlay').css({height:'590px'});
		$('#preloader').css({top:'268px'});
	}
}

/**
 * Clean up google resources
 */
$(window).unload(GUnload);

function resizeIframe(height)
{
	try
	{
		var frame = document.getElementById("resizeFrame");
		frame.contentWindow.resizeFrame(300);
	}
	catch(e)
	{
		
	}
}

/**
 * Map a single address to the map
 * 
 * @param address  The actual address
 * @param data  The data to show in the info window
 */
function mapAddress(address, data)
{
	geocoder.getLocations(address, function(response)
    {
		if (response.Status.code == 200)
		{
			var place = response.Placemark[0];
			var marker = mapCoordinates(parseFloat(place.Point.coordinates[1]), parseFloat(place.Point.coordinates[0]), data.eventType == 'camp');
			bindMarkClick(marker, data, false);
			this.eventMarkers.push(marker);
		}
    });
}

function mapCoordinates(long, lat, isRefugee)
{
	var point = new GLatLng(long, lat);
	var marker = null;
	
	if (isRefugee)
		marker = (new GMarker(point, {icon:blueIcon}));
	else	
		marker = (new GMarker(point, {icon:orangeIcon}));
	
	//map.addOverlay(marker);
	return marker;
}

/**
 * Bind click event on a marker to open the info window
 * 
 * @param marker  The marker to bind
 * @param data  The data to show in the info window
 */
var initialOpen = false;
function bindMarkClick(marker, data, isRefugee)
{
	GEvent.addListener(marker, "click", function()
	{
		if (isRefugee)
		{
			marker.openInfoWindowHtml('<div class="info-left">'+
									  	'<img src="'+baseUrl+'/images/'+data.image+'" class="image-border" />'+
									  	'<a href="#" class="create-fundraiser">Create a Fundraiser</a>'+
									  	'<a href="https://secure.globalproblems-globalsolutions.org/site/Donation2?1340.donation=form1&df_id=1340" class="donate-now" target="_blank">Donate Now</a>'+
									  	'<div class="clear"></div>'+
									  '</div>'+
									  '<div class="info-right">'+
									  	'<p><strong class="title">'+data.headline+'</strong><br/>'+
									  	'<p class="description">'+data.description+'</p>'+
									  	'<div class="clear"></div>'+
									  '</div>'+
									  '<div class="clear"></div>');
		}
		else
		{
			var type = (data.imported != 1) ? ' -- '+data.eventType+' Event</p>' : '';
			marker.openInfoWindowHtml('<div class="info-left">'+
										  '<img src="'+baseUrl+'/uploads/'+data.photo+'" class="image-border" />'+
										  '<a href="#" class="bubble-share" rel="'+data.id+'">Share Event</a>'+
										  '<div class="clear"></div>'+
									  '</div>'+
									  '<div class="info-right">'+
									      '<p><strong class="title">'+data.fundraiser+'</strong><br/>'+
									  	      'Event By: '+data.firstName+' '+data.lastName+type+
									  	  '<p class="description">'+data.description+'</p>'+
									  	  '<p class="address"><strong>Event Address:</strong><br/>'+
									  	  	  data.city+', '+data.state+'<br/>'+
									  	  	  data.eventDate+' - '+data.eventTime+
										  '</p>'+
										  '<p><a href="#" class="report-content" rel="'+data.id+'">Report inappropriate content</a></p>'+
									  '</div>'+
									  '<div class="clear"></div>');
		}
		setTimeout('bindShare()', 1000);
	});
	
	if (data.id == eventId && !initialOpen)
	{
		GEvent.trigger(marker, "click");
		initialOpen = true;
	}
}

/**
 * Bind event form, captcha creation, and map click handler
 */
function bindEventForm()
{
	$('#event-form').ajaxForm(
	{
		beforeSubmit: function()
		{
			$('#overlay').show();
			adjustHeight();
		},
		success: function(data)
		{
			$('#overlay').hide();
			$('#content').html(data);
			bindEventForm();
		}
	});
	
	if ($('#captcha').length > 0)
	{
		Recaptcha.create(recaptchaKey, "captcha");
	}	
	$('#takemap, #takebackmap').click(function()
	{
		showMap();
		return false;
	});
	
	bindShare();
	
	$('#add-event, #big-share-event').hover(function()
	{
		$(this).addClass('over');
	},
	function()
	{
		$(this).removeClass('over');
	});	
	
	$('#results').jScrollPane({showArrows:true, scrollbarWidth:15, wheelSpeed:30, scrollbarMargin:10});
	$('.jScrollPaneDrag').css({width:"9px"});
	bindPagination();
	
	bindReportClick();
	
	$('.rsvp-now').click(function()
	{
		var id = $(this).attr('rel');
		adjustHeight();
		$('#overlay').show();
		$.get(baseUrl+'/default/index/rsvp', {id:id}, function(results)		
		{
			$('#content').html(results);
			$('#overlay').hide();
			$('#map').hide();	
			$('#map-icons').hide();
			bindRsvpForm();
		});
		return false;
	});
	
	$('#delete-event').click(function()
	{
		if (confirm('Deleting events cannot be undone. Are you sure?'))
		{
			$.post(baseUrl+"/default/index/user-delete", {id:$(this).attr('rel')}, function()
			{	
				$.get(baseUrl+'/default/index/logout', {}, doLogout);
			});	
		}
		return false;
	});
	
	$('#reload-map').click(function()
	{
		$('#overlay').show();
		map.clearOverlays();
		mapData = [];
		getMapData();
		showMap();
		return false;
	});
	
	tooltip();
}

function bindReportClick()
{
	$('.report-content').click(function()
	{
		var id = $(this).attr('rel');
		adjustHeight();
		$('#overlay').show();
		$.get(baseUrl+'/default/index/report', {id:id}, function(results)		
		{
			$('#content').html(results).show();
			$('#overlay').hide();
			$('#map').hide();	
			$('#map-icons').hide();
			bindEventForm();
			bindReportForm();
		});
		return false;
	});
}

function bindRsvpForm()
{
	$('#rsvp-form').ajaxForm(
	{
		beforeSubmit: function()
		{
			$('#overlay').show();
			adjustHeight();
		},
		success: function(data)
		{
			$('#overlay').hide();
			$('#content').html(data);	
			bindRsvpForm();
		}
	});	
}

function bindReportForm()
{
	$('#report-form').ajaxForm(
	{
		beforeSubmit: function()
		{
			$('#overlay').show();
			adjustHeight();
		},
		success: function(data)
		{
			$('#overlay').hide();
			$('#content').html(data);	
			bindReportForm();
			bindEventForm();
		}
	});
}

function bindPagination()
{
	$('.pager').click(function()
	{		
		posts.page = $(this).attr('rel');
		$.post(baseUrl+"/default/index/event-search-form", posts, function(result)
		{			
			$('#content').html(result);
			$('#overlay').hide();
			bindPagination();
		});
		
		return false;
	});
}

function bindShare()
{
	$('.share-event, .bubble-share, .event-share').click(function()
	{
		adjustHeight();		
		$('#overlay').show();		
		$.get(baseUrl+'/default/index/share-events', {id:$(this).attr('rel')}, function(result)
		{
			$('#map').hide();
			$('#map-icons').hide();
			$('#overlay').hide();
			$('#content').html(result).show();
			bindEventForm();			
		});

		return false;
	});
	
	$('.create-fundraiser').click(showEventForm);
	bindReportClick();
}

function getRefugees(center)
{	
	if (mapData.length > 0)
	{
		var campMarkers = [];
		mgr.clearMarkers();
		
		for (var i = 0; i < mapData.length; i++)
		{
			if (mapData[i].isRefugee)
			{				
				var marker = mapCoordinates(mapData[i].longitude, mapData[i].latitude, true);				
				bindMarkClick(marker, mapData[i], true);
				if (marker != null)
					campMarkers.push(marker);
			}
		}
		
		mgr.addMarkers(campMarkers, 4);
		mgr.refresh();
		
		if (center)
		{
			map.checkResize();
			map.setCenter(new GLatLng(4.667918, 34.013672), 4); //AFRICA
		}				
	}
}

function reloadMap(type)
{	
	if (mapData.length > 0)
	{
		var eventMarkers = [];
		mgr.clearMarkers();
		
		for (var i = 0; i < mapData.length; i++)
		{
			if (mapData[i].isRefugee == false)
			{			
				//mapAddress(mapData[i].address, mapData[i].data);
				if (mapData[i].data.geoCode.status == 200)
				{
					var marker = mapCoordinates(mapData[i].data.geoCode.longitude, mapData[i].data.geoCode.latitude, false);				
					bindMarkClick(marker, mapData[i].data, false);
					if (marker != null)
						eventMarkers.push(marker);
				}
			}
		}					
	}	
	
	map.checkResize();
	if (type == 'worldwide')
	{
		mgr.addMarkers(eventMarkers, 1);
		map.setCenter(new GLatLng(36.315125, -5.273437), 1); //WORLD
	}		
	else
	{
		mgr.addMarkers(eventMarkers, 4);
		map.setCenter(new GLatLng(39.368279, -100.283203), 4); //USA		
	}		
	
	mgr.refresh();
	return false;
}

function showMap()
{
	$('#map-icons').show();
	$('#map').show();
	$('#content').hide();
}