/**
 *
 * This stuff is used on pretty much every page.
 *
 */

var slideheight = 300;
var slidetime   = 900;
var fadetime    = 300;

addresses = {
	"annalea": String.fromCharCode(97,110,110,97,108,101,97,64,116,104,101,99,104,97,110,103,101,46,99,111,109),
	"daniel":  String.fromCharCode(100,97,110,105,101,108,64,116,104,101,99,104,97,110,103,101,46,99,111,109),
	"brad":    String.fromCharCode(98,114,97,100,64,116,104,101,99,104,97,110,103,101,46,99,111,109),
	"saleem":    String.fromCharCode(115,97,108,101,101,109,64,116,104,101,99,104,97,110,103,101,46,99,111,109),
	"tim":    String.fromCharCode(116,105,109,64,116,104,101,99,104,97,110,103,101,46,99,111,109),
	"marionne":    String.fromCharCode(109,97,114,105,111,110,110,101,64,116,104,101,99,104,97,110,103,101,46,99,111,109)
}

$(document).ready(function() {


	$("a.fml").each(function(){
		$(this).attr("href", String.fromCharCode(109,97,105,108,116,111,58) + addresses[$(this).attr("title")]);
	});


	// Hide RSS Icon
	$('li.feed').siblings("li:last").find("a").css("border-right","none").css("padding-right", "1em");
	$('li.feed').css("display","none");


	// Realign images/video
	var found = $('.doctext').find('h4');
	if(found.length > 0) {
		$('.doctext').find('.video:first').css('margin-top','2.7em');
		$('.doctext').find('.photo:first').css('margin-top','2.7em');
	}


	// Locality switcher
	$("#locality select").change(function() {
		$(this).parent().submit();
	});


	// Mailchimp Button
	$('#subscribe-newsletter #mc-embedded-subscribe').click(function() {
		window.open('http://eepurl.com/ojCj','mywindow','width=800,height=600,resizable=no,scrollbars=no,menubar=no');
	});
	
	// Popup Notification
	$(".firstTime").load(function() {
		$("#wrapOverlay").fadeIn('slow');
	});
	
	$("#popupClose").click(function(ev) {
		$("#popupNotification").slideUp('fast').parent().fadeOut('slow');
		$("#popupNotification").removeClass('firstTime');
		ev.preventDefault();
	});


	// URL boxes should be friendly
	$("input:text.url").each(function(){
		if ($(this).val() == "") {
			$(this).val("http://");
			$(this).click(function(){
				$(this).val("http://");
			});
		}
	});
	
	// TweetMeme Title
	var cur_title = $("title").html();
	var new_title = cur_title.replace("TheChange | - ", "TheChange | ");
	$("title").html(new_title);
	$('head meta[name="tweetmeme-title"]').attr('content',new_title);
	//alert(new_title);
	

	var menuout = false;

	// Login Box Sticking
	$("#LogIn a:not(#forgotLink), .CommentMenu a[href='/accounts/login/']").click(function(ev) {

		// If javascript is enabled, stop link from going
		ev.preventDefault();

		if(menuout == false) {
			// Set focus
			menuout = true;
			$("#LogIn h3 a").css({
				'-moz-border-radius-bottomright': '0px',
				'-moz-border-radius-bottomleft': '0px',
				'-webkit-border-bottom-left-radius': '0px',
				'-webkit-border-bottom-right-radius': '0px',
				'border-bottom-left-radius': '0px',
				'border-bottom-right-radius': '0px'
			});
			// Slide the LoginBox down
			$("#LoginBox").slideDown('fast');
		} else {
			menuout = false;
			// Slide the LoginBox down
			$("#LoginBox").slideUp('fast', function() {
				$("#LogIn h3 a").css({
					'-moz-border-radius-bottomright': '15px',
					'-moz-border-radius-bottomleft': '15px',
					'-webkit-border-bottom-left-radius': '15px',
					'-webkit-border-bottom-right-radius': '15px',
					'border-bottom-left-radius': '15px',
					'border-bottom-right-radius': '15px'
				});
			});
		}

		

	});
	
	// Comment boxes become elastic
	$('.comments textarea').each(function() {
		$(this).elastic();
	});
	
	commentLinks();


	// Fake posting
	$("a.postable").click(function(){

		$("#workspace").append("<form id=\"tmpform\" method=\"post\" action=\"" + $(this).attr("href") + "\"></form>");

		// Crude version of CGI.pm
		var pairs = $(this).attr("alt").split("&");
		var args = {};
		for (pair in pairs) {
			var namevalue = pairs[pair].split("=");
			$("#tmpform").append("<input type=\"hidden\" name=\"" + namevalue[0] + "\" value=\"" + namevalue[1] + "\" />");
		}
		$("#tmpform").append("<input type=\"submit\" name=\"s\" value=\"Submit\" />");
		$("#tmpform").submit();

		return false;

	});


	// Partial show/hide
	$(".slider").each(slider_setup);
	$(".slider .slider_content").css("height", slideheight.toString() + "px");
	$(".slider .slider_toggle a").click(function() {
		slider_toggle($(this));
		return false;
	});


	// Follow buttons
	$(".BtnFollowed a").live("click", function(){
		return follow_handle($(this), true);
	});

	$(".BtnFollow a").live("click", function(){
		return follow_handle($(this), true);
	});

	$(".photo a.follow").live("click", function(){
		return follow_handle($(this), false);
	});


	// Like buttons
	$("a.like").live("click",function(){
		like_handle($(this));
		if($(this).html() == "Unlike") {
			$(this).before("<span class=\"numberoflikes\">One person likes this &#8226;</span> ");
		} else {
			$(this).parent().find('.numberoflikes').remove();
		}
		return false;
	});


	// Comments
	if (typeof window.comments_post == 'function') {

		comments_min();

		//$(".comments").css('display','none'); // Hides the comments by default
		$(".comments form").submit(comments_post);
		$("a.comment").click(comments_show);


		$(".more_comments").click(function(ev) {
			ev.preventDefault();
			comments_max(this);
		});
	}

	$("form.bounce textarea").html("You must be logged in to post a comment");
	$("form.bounce textarea").attr("disabled","disabled");
	$("form.bounce input").attr("disabled","disabled");
	
	
	
	// Comment Resizing
	$("#MainContent .sharing").siblings('.comments').css({
		'margin-left': '-20px',
		'left': '0px'
	});
	
	$("#MainContent .sharing").siblings('.comments').find('textarea').css({
		'width': '660px'
	});
	

});




function slider_setup() {

	var box  = $(this);
	var body = box.html();

	if (box.height() > slideheight) {
		box.attr("alt", box.height());
		box.html("\
			<div class=\"slider_content\">" + body + "</div>\
			<div class=\"slider_toggle\"><a href=\"#\" class=\"more\">More</a></div>\
		");
	}

}


function slider_toggle(box) {
	var action = (box.text() == "More") ? "open" : "close";
	var container = box.parents(".slider");
	if (action == "open") {
		var h = container.attr("alt");
		container.children(".slider_content").animate({"height": h}, {"duration": slidetime });
		box.removeClass("more");
		box.addClass("less");
		box.text("Less");
	} else {
		container.children(".slider_content").animate({"height": slideheight.toString() + "px"}, {"duration": slidetime });
		box.removeClass("less");
		box.addClass("more");
		box.text("More");
	}
}


function follow_handle(obj, classify) {

	follow_togglestatus(obj); // Hit the server to change the status *once*

	var lnk = obj.attr("href");
	$("a[href=" + lnk + "]").each(function(){
		follow_toggletext($(this),classify); // Toggle the strings everywhere
	});

	return false;

}

function follow_togglestatus(obj) {

	// Wether or not we should add/remove classes
	var tm = { // Togglemap
		"Follow": {
			"mth": "POST"
		},
		"Unfollow": {
			"mth": "DELETE"
		}
	}
	k = obj.html(); // Key

	$.ajax({
		type: tm[k]["mth"],
		url: obj.attr("href"),
		success: function(data) {
			// Bounce people who aren't logged in to the registration page
			if (data == "0") {
				location.href = "/accounts/registration/"
			}
		}
	});

}


function follow_toggletext(obj, classify) {

	// Wether or not we should add/remove classes
	var classify = (classify) ? true : false;
	
	var loggedOut = $("#UserInfo").find("#LogIn").length;
	if(loggedOut == 0) {
	
		var tm = { // Togglemap
			"Follow": {
				"add": "BtnFollowed",
				"rm":  "BtnFollow",
				"txt": "Unfollow"
			},
			"Unfollow": {
				"add": "",
				"rm":  "",
				"txt": "Follow"
			}
		}
	} else {
		var tm = { // Togglemap
			"Follow": {
				"add": "BtnFollowed",
				"rm":  "BtnFollow",
				"txt": "Follow"
			},
			"Unfollow": {
				"add": "",
				"rm":  "",
				"txt": "Unfollow"
			}
		}
	}
	k = obj.html(); // Key

	if (classify) {
		obj.parent().removeClass(tm[k]["rm"]);
		obj.parent().addClass(tm[k]["add"]);
	}
	obj.text(tm[k]["txt"]);

}


function like_handle(obj) {
	var loggedOut = $("#UserInfo").find("#LogIn").length;
	if(loggedOut == 0) {
	
		var tm = { // Togglemap
			"Like":   {
				"mth": "POST",
				"txt": "Unlike"
			},
			"Unlike": {
				"mth": "DELETE",
				"txt": "Like"
			}
		}
	} else {
		var tm = { // Togglemap
			"Like":   {
				"mth": "POST",
				"txt": "Like"
			},
			"Unlike": {
				"mth": "DELETE",
				"txt": "Unlike"
			}
		}
	}
	k = obj.html(); // Key

	$.ajax({
		type: tm[k]["mth"],
		url: obj.attr("href"),
		success: function(data) {
			// Bounce people who aren't logged in to the registration page
			if (data == "0") {
				location.href = "/accounts/registration/"
			}
		}
	});
	obj.html(tm[k]["txt"]);

}

function checkForLink(str) {
	var words = str.split(' ');
	var searchString;
	
	//alert(words);
	
	// Search for the http string, and save in variable
	$(words).each(function() {
		if(this.match('http://')) {
			searchString = this;
			//alert(this);
			//this = '<a href="' + thisText + '">' + thisText + '</a>';
		}
	});
	
	//alert(searchString);
	// Add anchor tags
	var replaceStr = str;
	replaceStr = replaceStr.replace(searchString,  '<a href="'+searchString+'">'+searchString+'</a>');
	
	return replaceStr;
}

function commentLinks() {
	// Make links linkable
	$('.comment p:contains(http://)').each(function() {
		// Remove the author link
		var link = $(this).find('strong');
		$(this).find('strong').remove();
		
		// Split the comment into words
		var words = $(this).text().split(' ');
		var searchString;
		
		//alert(words);
		
		// Search for the http string, and save in variable
		$(words).each(function() {
			if(this.match('http://')) {
				searchString = this;
				//this = '<a href="' + thisText + '">' + thisText + '</a>';
			}
		});
		
		//alert(searchString);
		// Add anchor tags
		var replaceStr = this;
		replaceStr = replaceStr.innerHTML.replace(searchString,  '<a href="'+searchString+'">'+searchString+'</a>');
		
		// Replace text, and add link back to beginning
		$(this).html(replaceStr);
		$(this).prepend(link);
		
		
	});
}

