if (typeof (Bolder) === 'undefined') Bolder = {};
Bolder.Base = (function () {
		
	var ajaxifyPaginationLink = function(link, func, args) {
		var href = $(link).attr('href');
		if(pageRegex.test(href)) {
			var pageNum = href.match(pageRegex)[1];
			$(link).click(function() {
				func(args, pageNum);
				return false;
			});
		}
	}
	
	return {
		ajaxifyPaginationLink: ajaxifyPaginationLink
	};
	
})();

Bolder.Comments = (function () {
	var initializeComments = function($container) {
		$container.find("span.comment-wrapper textarea")
					.attr("placeholder","Write a comment...")
					.val("Write a comment...")
					.addClass("placeholder-text");
				
		$container.find('a.leave-comment-link').click(function() {
			$(this).closest('.comment-parent').find('.comment-form').fadeIn('fast').find('textarea').focus();
			return false;
		});
		
		
		$container.find('a.previous-comments-link').click(function() {
			$(this).closest('.comments').find('.more-comments-bar').fadeOut('fast');
			$(this).closest('.comments').find('.hidden-comments').fadeIn('slow');
			return false;
		});		
		
		$container.find('button.comment-submit').debounce({
			onClick: function(button, event) { Bolder.Comments.postComment($(button).parent('form'), $(button)); },
			standardContent: 'Comment',
			processingContent: 'Posting...',
			finishedContent: 'Posted!'
		});
	};
	
	var postComment = function($comment_form, $comment_button) {
		$.post($comment_form.attr('action'), $comment_form.serialize(), function(data, textStatus) {
			$comment_button.debounce('reset');
			$comment_form.closest('.comments').find('.comment-list').append(data);
			$comment_form.find('textarea').val('');
			$comment_form.closest('.comment-form').hide();
		});	
	};
	
	return {
		initializeComments: initializeComments,
		postComment: postComment
	};
})();

Bolder.ActionShot = (function() {
	
	var $loading = $('<img style="position: absolute; top: 40%; left: 50%;" src="/site_media/images/ajax_loader_actionshot.gif" alt="loading">');
	
	var initializeActionshot = function(target) {
		if ($(target).data('initialized')) {
			return false;
		} else {
			$(target).data('initialized', true);
		}
		
		var $dialog = $('<div><div class="actionshot-wrapper"></div><div class="actionshot-title"><img style="position: absolute; top: 40%; left: 50%;" src="/site_media/images/ajax_loader_new.gif" alt="loading"></div>');
		$dialog.children('.actionshot-wrapper').html($loading.clone());
		
		$(target).one('click', function() {			
			$dialog.dialog({
				buttons: [{
					text: "Close",
				    click: function() { 
						$(this).dialog("close"); 
					} 
				}],
				autoOpen:false,
				resizable: false,
				modal: true,
				dialogClass: 'actionshot-dialog',	
				open: function(event, ui) {
					if( $(target).attr('shottype') == 'video'){
						var video_id = $(target).attr('videoid');
						var $wrapper = $dialog.children('.actionshot-wrapper').first();
						
						
						$.get('/actionshot_video/' + video_id + '/', function(response_data) {	
						
							$wrapper.html(response_data);							
						});
					}
					else{   // a photo definitely, I hope
						preLoader = new Image();
						preLoader.onload = function() {
							ratio = preLoader.width / preLoader.height;
							var $wrapper = $dialog.children('.actionshot-wrapper').first();
							if (preLoader.height > $wrapper.height()) {
								preLoader.height = $wrapper.height();
								preLoader.width = preLoader.height * ratio;
							}
							if (preLoader.width > $wrapper.width()) {
								preLoader.width = $wrapper.width();
								preLoader.height = preLoader.width / ratio;
							}
							$wrapper.html(preLoader);
						};
						preLoader.src = $(target).attr('href');
						
					}
					// Load the title
					var useraction_id = $(target).children('img').attr('title');
					$dialog.find('.actionshot-title').load('/useraction/actionshot_title/' + useraction_id);
					// fix for the stupid auto-focus, 
					// which should be fixed in jquery 1.9
					$(this).parent().find('.ui-button').blur();					
				}
			});
		}).click(function() {
			
			
			screen_width = $(window).width()-150;
			screen_height = $(window).height()-100;
			
			if(screen_width > 900) screen_width = 900;
			if(screen_width < 400) screen_width = 400;
			if(screen_height < 400) screen_height = 400;			
			
			if( $(target).attr('shottype') == 'video'){
				screen_height = 487;
				screen_width = 600;
			}

			$dialog.dialog('option', 'width', screen_width);
			$dialog.dialog('option', 'height', screen_height);
			
			$dialog.children('.actionshot-wrapper').height(screen_height - 160);
			$dialog.children('.actionshot-title').width(screen_width-20);
			
			$dialog.dialog('open');
			return false;
		});		
	}
	
	return {
		initializeActionshot: initializeActionshot
	}
	
})();

Bolder.Tabs =(function() {
	var selectTab = function(hash) {
		
		var tabContainers = $('ul.tabs').siblings('div.tab-container');
		tabContainers.hide().filter(hash).show();
		
		var tabLinks = $('ul.tabs a');
		tabLinks.removeClass('selected').filter('[href='+hash+']').addClass('selected');
		
	};
	
	return {
		selectTab: selectTab
	}

})();

// On Ready
$(document).ready(function() {
		
	$("a.bolder-educate").click(function(){
		$(".bolder-educate-content").dialog({
			height: 395,
			width: 640,
			modal: true,
			buttons: {
				Close: function() {
					$(this).dialog('close');
		 		}
		 	},
		 	resizable: false,
			dialogClass: 'educate-fools'
		});
	});
	
	$(".submit-link").click(function(){
		$(this).closest("form").submit();
	});
	
	/* Initialize comments across the board. This must come BEFORE
	   the code the configures the placeholder text, as part of 
	   what it does is to set the comment form placeholder text. */
	Bolder.Comments.initializeComments($('body'));
	
	
	$("a.actionshot-new").each(function(index) {
		Bolder.ActionShot.initializeActionshot(this);
	});
	
	$('*[placeholder]').focus(function() {
		if($(this).val() == $(this).attr('placeholder'))
		{
			$(this).val('').removeClass('placeholder-text');
		}
	});
	
	$('*[placeholder]').blur(function() {
		if($(this).val() == '') 
		{
			$(this).val($(this).attr('placeholder')).addClass('placeholder-text');
		}
	});
	
	$('*[placeholder]').each(function(index, value) {
		if($(value).val() == '' || $(value).val() == $(value).attr('placeholder')) 
		{
			$(value).val($(value).attr('placeholder')).addClass('placeholder-text');
		}
	});
	
	$(".fg-hover-button").hover(
		function(){ 
			$(this).addClass("ui-state-hover"); 
		},
		function(){ 
			$(this).removeClass("ui-state-hover"); 
		}
	);
	
	// $("#simple-dialog").dialog({
	// 	bgiframe: true,
	// 	autoOpen: false,
	// 	height: 450,
	// 	width: 450,
	// 	buttons: {
	// 		Close: function() {
	// 			$(this).dialog('close');
	// 		}
	// 	},
	// 	close: function(event, ui) {
	// 		$("#simple-dialog").html("<div style='margin:auto'><img src='/site_media/images/ajax_loader.gif'></div>");
	// 	}
	// });
	
	$("#feedback-dialog").dialog({
		bgiframe: true,
		autoOpen: false,
		height: 400,
		width: 340,
		modal: true,
		title: 'Please tell us what is on your mind',
		buttons:
		{
			'Be Heard': function() {
				pageTracker._trackEvent('Base', 'Talk To Us','Be Heard');
				$.post("/feedback/", $("#feedback-form").serialize());
				$(this).dialog('close');
			},
			Cancel: function() {
				$(this).dialog('close');
				pageTracker._trackEvent('Base', 'Talk To Us','Cancel');
			}
		}
	});
	
	var _menuShown = false;
	
	var hideAuthMenu = function() {
		$("#auth-dropdown").css('top','-999px');
		$("#auth-menu").removeClass('active');
		_menuShown = false;
	};
	
	var showAuthMenu = function() {
		$("#auth-menu").addClass('active');
		$("#auth-dropdown").css('top','56px');
		_menuShown = true;
	}
	
	// Auth menu hide/show
	$("#auth-menu").click(function(event) {
		if(event) event.stopPropagation(); 
		// if(event) event.preventDefault();
		if(_menuShown) {
			hideAuthMenu();
		} else {
			showAuthMenu();
		}
	});
	
	$("body").click(function() {
		hideAuthMenu();
	});
	
	$('ul.tabs li a').click(function() {
		Bolder.Tabs.selectTab(this.hash);
		return false;
	});
	
	/*
	$('input[type=text]').each(function() {
		var form = item.parents("form:first");
		form.submit(function() {
			if(item.val() == item.attr('placeholder')) {
				item.val('');
			}
		});
	});*/
	
	// First action banner
	/*
$('#firstaction-close').click(function() {
		$('#firstaction-banner').slideUp('fast');
		$.get('/user_prefs/disable_firstaction/');
	});
*/
});

function user_action_detail(user_action_id) {
	$("#simple-dialog").html("<div style='margin:auto'><img src='/site_media/images/ajax_loader.gif'></div>").dialog('option','title','Epic Action Summary').dialog('open');
	$.get('/action/id/' + user_action_id, function(data) {
	  $('#simple-dialog').html(data);
	});
}

function toggle_vote(button, user_action_id) {
	if($(button).hasClass("voted")) {
		undo_vote(button, user_action_id);
		$(button).removeClass("voted");
	} else {
		vote(button, user_action_id);
		$(button).addClass("voted");
	}
}

function toggle_flag(button, user_action_id) {
	if($(button).hasClass("flagged")) {
		undo_flag(button, user_action_id);
		$(button).removeClass("flagged");
	} else {
		flag(button, user_action_id);
		$(button).addClass("flagged");
	}
}

function vote(button, user_action_id) {
	//$($(button).parent().get(0)).html('Bold.');
	pageTracker._trackEvent('Action', 'Bold Vote',user_action_id);
	$.post("/action_vote/"+user_action_id+"/",
		function(data) {
			//location.reload();
		}
	);
	update_vote_count(1, user_action_id);
	toggle_icons("bold", user_action_id);
}

function undo_vote(button, user_action_id) {
	pageTracker._trackEvent('Action', 'Undo Bold Vote',user_action_id);
	$.post("/action_vote_undo/"+user_action_id+"/",
		function(data) {
			//location.reload();
		}
	);
	update_vote_count(-1, user_action_id);
	toggle_icons("bold", user_action_id);
}

function update_vote_count(delta, user_action_id) {
	$(".ua-bold-num-" + user_action_id).each(function(index, element) {
		var new_count = parseInt($(element).html()) + delta;
		var new_text = "Bolds";
		if(new_count == 1) {
			new_text = "Bold";
		}
		$(element).html(new_count);
		$(element).siblings(".ua-bold-text-" + user_action_id).html(new_text);
	});
}

function toggle_icons(type, user_action_id) {
	$(".ua-"+type+"-icon-"+user_action_id).each(function(index, element) {
		if($(element).attr("src").indexOf("_bw") != -1) {
			$(element).attr("src", $(element).attr("src").replace("_bw","_color"));
		} else {
			$(element).attr("src", $(element).attr("src").replace("_color","_bw"));
		}
	});
}

function flag(button, user_action_id) {
	//$($(button).parent().get(0)).html('Flagged!');
	pageTracker._trackEvent('Action', 'Flag',user_action_id);
	$.post("/action_flag/"+user_action_id+"/",
		function(data) {
			//location.reload();
		}
	);
	toggle_icons("flag", user_action_id);
}

function undo_flag(button, user_action_id) {
	pageTracker._trackEvent('Action', 'Undo Flag',user_action_id);
	$.post("/action_flag_undo/"+user_action_id+"/",
		function(data) {
			//location.reload();
		}
	);
	toggle_icons("flag", user_action_id);
}

function update_displayname(name, container, label) {
	var display_name = "";
	
	if(name) {
		container.show();
	} else {
		container.hide();
	}
	
	name = $.trim(name);

	if(name) {
		names = name.split(" ", 2);
				
		display_name = $.trim(names[0]);
			
		if (names.length > 1) {
			display_name += (" " + $.trim(names[1]).slice(0,1) + ".");
		}
	}	
	
	label.html(display_name);
}



// Global AJAX CSRF protection
$('html').ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
        // Only send the token to relative URLs i.e. locally.
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    } 
});
















