/**
 * Clears a text form element when it has the style 'clear-default'
 */
$.fn.clickClear = function() {
	return this.each(function() {
		this.defaultValue = $(this).val();
		$(this).click(function() {
			if ($(this).val() == this.defaultValue) {
				$(this).val('');
			};
		}).focus(function() {
			if ($(this).val() == this.defaultValue) {
				$(this).val('');
			};
		}).blur(function() {
			if ($(this).val() == "") {
				$(this).val(this.defaultValue);
			};
		});
		
		$('form').submit(function(event) {
			if ($(this).val() == this.defaultValue) {
				$(this).val('');
			};
		});
	});	
};

function prepareMarkup()
{
	$('> li:last', 'ul, ol').addClass('last');
}

var leadersMentioned = function(){	
	$("div.leaders-mentioned li a").mouseover(function(){
		var title = this.title;
		var top = $(this).position().top;
		var left = $(this).position().left;
		var topOffset = 34;
		var leftOffset = 40;
		
		$("div.head-rollover." + title)
			.css('display', 'block')
			.css("top",(top - topOffset - $("div.head-rollover." + title).height()) + "px")
			.css("left",(left - leftOffset) + "px");								 				
    }).mouseout(function() {
		$("div.head-rollover").css('display','none');
    });	
};

var homepageColumns = function()
{
	$('.column article:last-child').css({'border': 'none'});
	
	var height = 0;
	$('.column').each(function(index)
	{
		if ($(this).height() > height) height = $(this).height();
	});
	
	$('.column').height(height);
}

var allMarkers = new Array();

$(document).ready(function()
{
	$('input.clear-default').clickClear();
	$('ul.leader-photos a').lightBox();
	$('.lightbox').lightBox();
	prepareMarkup();
	leadersMentioned();
	homepageColumns();
	
	if ($('#map-canvas').size() > 0)
	{
		initializeMap();
		$('#carousel').innerFade({
			timeout: 5000,
			speed: 1000
		});
		
		allMarkers = addMarkers(points, allMarkers);
		filterMapBasedOnCheckboxes();
		
		$('#show-all-checkbox, #show-new-checkbox').click(function()
		{
			filterMapBasedOnCheckboxes();
		});
	}
});

function filterMapBasedOnCheckboxes()
{
	var status = ($('#show-all-checkbox').attr('checked') == 'checked') ? "old" : "new";
	
	if ($("#show-new-checkbox").size() > 0)
	{
		status = ($('#show-new-checkbox').attr('checked') == 'checked') ? "new" : "old";
	};
	
	for (var i=0; i < allMarkers.length; i++)
	{
		if ((status == 'new' && allMarkers[i].status == 'new') || status == 'old')
		{
			if (allMarkers[i].map != map)
				allMarkers[i].setMap(map);
		} else {
			allMarkers[i].setMap(null);
		}
	}
}

var popover = {
	
	openPopover: function(entry_id)
	{
		$('#darkbox').load('/popover/'+entry_id,function()
		{
			$('#darkbox .popover').click(function(event)
			{
				event.stopPropagation();
			});
			
			$('#darkbox, .popover a.close').click(function(event)
			{
				event.preventDefault();
				
				$('#darkbox').fadeOut('fast', function()
				{
					$('#darkbox > *').hide();
				});
			});
		});
		
		$('#darkbox').fadeIn('fast');
	}
}
