/*----------------------------------------------------------------------------
	After DOM is Loaded
----------------------------------------------------------------------------*/
/*	var showBanner,
		hideBanner;*/

	$(document).ready(function() {

		/* FLASH MESSAGE */
		$('#alert').hide().slideDown('slow');

		var root = $('#masthead > h1 a').attr('href');

		if($('body').hasClass('home')) {
			$("#container > div.bubble").show();

			/*----------------------------------------------------------------------------
				Virtual Protest
			----------------------------------------------------------------------------*/
				$("#virtual-protest #wall a").live('hover', function(evt) {
					if(evt.type == "mouseover") {
						$(this).find("img").stop().animate({ width: 189 }, 250);
					}
					else {
						$(this).find("img").stop().animate({ width: 175 }, 250);
					}
				});

				$("#virtual-protest #wall #refresh").live("click",function(){
					$.ajax({
					  url: root+"/ajax/vpr/",
					  cache: false,
					  success: function(result){
					  	$("#wall").html(result).prepend('<a href="#" id="refresh">Refresh</a>');
					  }
					});
					return false;
				});

			/*----------------------------------------------------------------------------
				Homepage Campaign Rollovers
			----------------------------------------------------------------------------*/

				var campaigners = $('#campaigners li:not(#the12th)').mouseenter(function(){
					var $this = $(this).trigger('mouseleave').addClass('active');
					$this.prev('li')
						.addClass('active-left')
					.prev('li')
						.addClass('active-next-left');
					$this.next('li').addClass('active-right');
				}).mouseleave(function(){
					campaigners.removeClass('active active-right active-left active-next-left');
				});
		}

		/*----------------------------------------------------------------------------
			Adopt Promo
		----------------------------------------------------------------------------*/
			var embed = $('#adopt #embed');
			embed.hide();

			$("#adopt .link a").live("click",function(){
				if(embed.is(':hidden')){
					embed.show("fast");
					$('#adopt .link a').text("Copy the code above to paste on your webpage");
				}else{
					embed.hide("fast");
					$('#adopt .link a').text("Take me Away");
				}
				return false;
			});

		/*----------------------------------------------------------------------------
			Dotmailer
		----------------------------------------------------------------------------*/
			$('#signup').live("submit", function() {
				var frm = $(this);
				var emailAddress = frm.find('input[name=Email]').val();
				var errorString = '';

				if (emailAddress == '' || emailAddress.indexOf('@') == -1) {
					errorString = 'Please enter your email address';
				}

				var els = frm[0].getElementsByTagName('input');
				for (var i = 0; i < els.length; i++) {
				    if (els[i].className == 'text' || els[i].className == 'date' || els[i].className == 'number') {
				        if (els[i].value == '')
				            errorString = 'Please complete all required fields.';
				    }
					else if (els[i].className == 'radio') {
				        var toCheck = document.getElementsByName(els[i].name);
				        var radioChecked = false;

				        for (var j = 0; j < toCheck.length; j++) {
				            if (toCheck[j].name == els[i].name && toCheck[j].checked)
				                radioChecked = true;
				        }
				        if (!radioChecked)
				            errorString = 'Please complete all required fields.';
				    }
				}

				var isError = (errorString.length > 0) ? true : false;

			    if (isError) {
					var target = frm.find('input[name=Email]').closest('div');
					var errors = "<ul class='errors'><li>" + errorString + "</li></ul>";

					target.find('ul.errors').remove();
					target.append(errors);
				}

				return !isError;
			});

		/*----------------------------------------------------------------------------
			Minimise Behaviour for Promos
		----------------------------------------------------------------------------*/
			jQuery.fn.toggleDetails = function(){
				return this.each(function(){
					var $this = $(this),
						$details = $this.find('.details').css('overflow','hidden'),
						originalHeight = parseInt($details.attr('scrollHeight'));

					if(originalHeight < 75)	return;

					// Set a cookie to automatically minimise on next visit
					var COOKIE = 'RETURNING'+ $this.attr("id")+window.location.pathname.replace(/\//g,'');

					var $button = $('<button>Less detail</button>').toggle(function(evt){
							evt.preventDefault();
							$button.text('More detail');
							$.cookie(COOKIE, '1', { path: window.location.pathname, expires: 1209600 });
							$details.animate({'height':30}, 500, function(){
								$this.removeClass('active');
							});
						},function(evt){
							evt.preventDefault();
							$button.text('Less detail');
							$.cookie(COOKIE, '0', { path: window.location.pathname, expires: 1209600 });
							$details.animate({'height':originalHeight}, function(){
								$this.addClass('active');
							});
						}).appendTo($this);

						if($.cookie(COOKIE) == '1'){
							$details.height(30);
							$button.trigger('click');
						}
				});
			};
			$('#secondary-content .togglable').toggleDetails();

		/*----------------------------------------------------------------------------
			TopBar Flash
		----------------------------------------------------------------------------*/
		/*	if(typeof(swfobject) !== 'undefined'){
				var $elsewhere = $('#elsewhere').addClass('enabled');
				showBanner = function() {
					$elsewhere.addClass('active');
				};
				hideBanner = function(){
					$elsewhere.removeClass('active');
				}
				swfobject.embedSWF(root + '/workspace/assets/swf/footerbanner/FooterBannerOpenClose_newXMLandPathConfig.swf', 'c4', 1256, 152, '9.0.0',  root + '/workspace/assets/js/expressInstall.swf', false, {
					wmode:'transparent',
					align:'middle',
					flashvars:'config=' + root + '/workspace/assets/swf/footerbanner/assets/config.xml'
				});
			}*/

		/*----------------------------------------------------------------------------
			Search Placeholder (uses a plugin, lets HTML5 capable browsers do it natively)
		----------------------------------------------------------------------------*/
			$("input[placeholder]").placeholder();

		/*----------------------------------------------------------------------------
			Become a Fan
		----------------------------------------------------------------------------*/
			$('#fans a.addfanbtn').live('click', function() {
				var self = $(this);

				$.post(self.attr("href"), {addFan: "add-fan"}, function(result) {
						$(result).find('fans').each(function(){
							msg = $(this).text();
							if(!isNaN(msg)){
								$('#fans em').text(msg);
								$('#fans').addClass('enabled');
								self.attr("href", "");
							}
						});

						$(result).find('filter').each(function() {
							filter = $(this);

							if(filter.attr('class') == "existing-fan") {
								$('#fans').addClass('enabled');
								self.attr("href", "");
							}
							else if(filter.attr('class') != "non-existant-campaign") {
								$('#fans nav').html("<span class='not-logged-in'>You own this campaign!</span>");
							}

						});
					},
					"xml"
				);

		 		return false;
		 	 });

		/*----------------------------------------------------------------------------
			Liking
		----------------------------------------------------------------------------*/
			$('#latest-activity a.likebtn').live('click', function(){
				var self= $(this),
					id = self.closest('.like').attr('rel'),
					_like = $('span.like[rel=' + id + ']');

		 		if($.cookie(id) == "voted"){
			 		_like.find('a').text("You have already liked this");
		 		}
				else{
		 			$.post(self.attr("href"), {like: "true"}, function(result) {
		 				$(result).find('likes').each(function() {
							msg = $(this).text();
							if(!isNaN(msg)) {
								_like.find('span.number').text(msg);
								_like.find('span.plural').text(
									(msg != 1) ? "likes" : "like"
								);

								_like.find('a')
									.text('You like this')
									.attr('href', false);

								$.cookie(id, "voted", {
									path: '/',
									expires: 365
								});
							}
						});
					},"xml");
		 		}

		 		return false;
		 	 });

		/*----------------------------------------------------------------------------
			AJAX Pagination
		----------------------------------------------------------------------------*/

			$("#latest-activity a.ajaxOlder").live("click", function(){
				var self= $(this),
					url = self.attr('rel');

				$.ajax({
					url: url,
					beforeSend: function() {
						$('#latest-activity > section div#ajaxReplace').addData('<div class="loading">Loading</div>');
					},
					success: function(data) {
						$("div.loading").fadeOut("fast", function() {
							$('#latest-activity > section div#ajaxReplace').addData(data);

							self.attr('rel', function() {
								if(url.search(/count:([1-9]+0)/) != -1) {
									count = url.match(/count:([1-9]+0)/)[1];
									return url.replace(/count:[1-9]+0/, "count:" + (parseInt(count) + 10));
								}
								else return url + "/count:20/";
							});
							refresh();
						}).remove();
					},
					error: function(data){
						$('div.loading').fadeOut("fast", function() {
							$('#latest-activity > section div#ajaxReplace').addData("<p class='activity-error'>There are no more posts</p>");
							$("#latest-activity a.ajaxOlder").fadeOut();
						}).remove();
					}
				});

		 	 	return false;
		 	 });

		/*----------------------------------------------------------------------------
			Nav Types
		----------------------------------------------------------------------------*/
			$("#latest-activity nav.types li a").live('click', function() {
				var self= $(this),
					url = self.attr('rel');

				if(url.search(/feed:[a-z]+/) != -1) {
					feed = url.match(/feed:[a-z]+/)[0];
				}
				else feed = "";

				$.ajax({
					url: url,
					beforeSend: function() {
						$("#latest-activity > section div#ajaxReplace").html('<div class="loading">Loading</div>');
					},
					success: function(data) {

						$("nav.types ul li.active").removeClass("active");
						self.parent().addClass("active");

						$("div.loading").fadeOut("fast", function() {
							$('#latest-activity > section div#ajaxReplace').addData(data);

							//	Scroll to the ID of the Item
							if(id = window.location.hash.match(/\/id:([0-9]+)\//)) {
								var target = $("#" + id[1]);
								if(target.length) { // There seems to be a 2000px offset...
									$('html').attr('scrollTop', target.offset().top - 2000);
								}
							}

							$("#latest-activity a.ajaxOlder").fadeIn().updateURL(feed, "rel");
							$("#latest-activity nav.chronological a").updateURL(feed, "href");
							refresh();

						}).remove();
					},
					error: function(data){
						$('div.loading').fadeOut("fast", function() {
							$("#latest-activity > section div#ajaxReplace").html("<p class='activity-error'>No Activity For This Feed</p>");
							$("#latest-activity a.ajaxOlder").fadeOut();
						}).remove();
					}
				});

				return false;
			});

			//	If a feed hash is detected, open that tab
			if(feed = window.location.hash.match(/\/feed:([a-zA-Z]+)\//)) {
				$("nav.types ul li a[href*=" + feed[0] + "]").trigger('click');
			}

	 	 	refresh();

		/*----------------------------------------------------------------------------
			Campaign Buzz O Meter
		----------------------------------------------------------------------------*/
			jQuery.fn.campaignMeter = (function(){
				var Meter = function(el, cfg){
					jQuery.extend(this.cfg, cfg);
					this.el = el.css('cursor', 'pointer');
					this.init();
				};
		 		Meter.prototype = {
					cfg: {
						maxAngle: 180
					},
					animated: false,
					init: function(){
						this.min = parseFloat(this.el.attr('min'), 10);
						this.max = parseFloat(this.el.attr('max'), 10);
						this.val = parseFloat(this.el.attr('value'), 10);
						this.increment = this.cfg.maxAngle/(this.max-this.min);
						this.height = this.el.height();
						this.width = this.el.width();
						this.canvas = Raphael(this.el.get(0), this.width, this.height);
						this.needle = this.canvas.image(this.cfg.needle.src, this.cfg.needle.x-this.cfg.needle.width, this.cfg.needle.y, this.cfg.needle.width, this.cfg.needle.height);

						var rotateHandler = jQuery.proxy(this, 'rotate');
						this.el.click(rotateHandler);
						$(window).load(function(){
							setTimeout(rotateHandler, 500);
						});
					},
					rotate: function(){
						if(this.animated){
							return;
						}
						var start = new Date,
							diff = this.val * this.increment,
							tick = 20,
							ms = diff * tick,
							i = 0,
							self = this,
							cx = this.cfg.needle.cx,
							cy = this.cfg.needle.cy,
							needle = self.needle.rotate(0, cx, cy),
							interval = setInterval(jQuery.proxy(function(){
								if(i >= diff){
									clearInterval(interval);
									this.animated = false;
									return;
								}
								i += 1;
								var pos = Raphael.easing_formulas.elastic((new Date - start) / ms);
								needle.rotate(pos * diff, cx, cy);
							}, this), tick);
							this.animated = true;
					}
				};

				return function(){
					var args = arguments;
					if(typeof(Raphael) == 'undefined'){
						return this;
					}
					return this.each(function(){
						if(typeof(args[0]) == 'object'){
							var $this = jQuery(this);
							$this.data('analogMeter', new Meter($this, args[0]));
						}
					});
				};
			})();

			if($('meter').length) {
				$('meter').campaignMeter({
					'needle': {
						src: root + '/workspace/assets/images/needle.png',
						width: 73,
						height: 17,
						x: 114,
						y: 61,
						cx: 106,
						cy: 70
					}
				});
			}

		/*----------------------------------------------------------------------------
			Campaign Background
		----------------------------------------------------------------------------*/
			if($('#campaign-background').length) {
				$('#campaign-background').each(function(){
					var $this = $(this),
						$labels = $this.find('label');

					$(this).find('li').click(function(evt){
						var $this = $(this),
							$label = $this.find('label');

						if(!$label.hasClass('active')){
							$labels.stop(true).removeClass('active').css({opacity:0});
							$label.addClass('active').animate({opacity:1}, 250);
							$this.find('input').attr('checked', true);
						}
					}).focus(function(){
						$(this).trigger('click');
					});
				});
			}
	});

	function refresh(when) {
		$('#latest-activity a.likebtn').each(function() {
 	 	  	var id = $(this).closest('.like').attr('rel'),
 	 	  		_like = $('span.like[rel=' + id + ']', $('#latest-activity'));

 	 	  	if($.cookie(id) == "voted"){
 	 	  		_like.find('a').text("You like this").attr('href', "");;
 	 	  	}
 	 	});

		$('#latest-activity article p, #quote q *').replaceURLWithHTMLLinks();

		$('#latest-activity .comments form.inline-comment-form').hide();
		if(typeof(Cufon) !== 'undefined') {
			Cufon.refresh();
		}

		//	Add a redirect #hash to the comments so when it's posted the correct tab will open
		if(feed = window.location.hash.match(/\/feed:[a-z]+\//)) {
			$('#latest-activity form.inline-comment-form input[name=redirect]').each(function() {
				var self = $(this);
				self.val('#' + feed[0] + 'id:' + self.val().slice(1) + "/");
			});
		}
	}

	jQuery.fn.addData = function(data) {
		return this.each(function() {
			if ($.browser.msie) {
				$(innerShiv(data), false).appendTo($(this));
			}
			else {
				$(this).append(data);
			}
		})
	}

	jQuery.fn.updateURL = function(feed, property){
		return this.each(function(){
			var self = $(this),
				url = self.attr(property),
				replace = "feed:";

			if(url === undefined) return;
			var spURL = url.split("/");

			if(url.search(replace) != -1){
				for(i=0; i < spURL.length; i++) {
					if(spURL[i].search(replace) != -1) spURL[i] = feed;
				}
				url = spURL.join("/");
			}
			else {
				url += feed;
			}

			if(url[url.length - 1] != "/") url = url + '/';
			window.location.hash = "#/" + feed + "/";

			self.attr(property, url);
		});
	};

	//	Thank you SO: http://stackoverflow.com/questions/37684/replace-url-with-html-links-javascript
	jQuery.fn.replaceURLWithHTMLLinks = function() {
		return this.each(function() {
			var self = $(this);
				exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;

			var child = self.children().clone();

			self.children().remove();

			self.html(
				self.html().replace(exp,"<a rel='external nofollow' href='$1' style='display: inline'>$1</a>")
			).append(child);
		});
	};

/*----------------------------------------------------------------------------
	While DOM is loading
----------------------------------------------------------------------------*/
	$(window).ready(function() {
		/*----------------------------------------------------------------------------
			Open external links in a new tab/window
		----------------------------------------------------------------------------*/
			$('a.external, a[rel*=external], article.album a:has(img), #petition a', $('body')[0]).live("click", function() {
				window.open($(this).attr('href'));
				return false;
			});
	});

/*!
* HTML5 Placeholder jQuery Plugin
* @link http://github.com/mathiasbynens/Placeholder-jQuery-Plugin
* @author Mathias Bynens <http://mathiasbynens.be/>
*/
;(function($){$.fn.placeholder=function(){if(this[0]&&'placeholder'in document.createElement('input')){return this;};function setPlaceholder($elem){if($elem.val()===''||$elem.val()===$elem.attr('placeholder')){$elem.addClass('placeholder').val($elem.attr('placeholder'));}else{$elem.removeClass('placeholder');};};$('form:has([placeholder]) *[type=submit]').bind('click', function(){if($(this.form).find('.placeholder').length){$(this.form).find('.placeholder').removeClass('placeholder').val('');};});return $(this).each(function(){var $input=$(this);if($input.attr('type') =='password'||!$input.attr('type') == 'input'){return;};setPlaceholder($input);$input.focusin(function(){if($input.val()===$input.attr('placeholder')){$input.val('').removeClass('placeholder');};}).focusout(function(){setPlaceholder($input);});});};})(jQuery);

/*!
* jQuery Cookie Plugin
*/
jQuery.cookie=function(name,value,options){if(typeof value!='undefined'){options=options||{};if(value===null){value='';options.expires=-1;}
var expires='';if(options.expires&&(typeof options.expires=='number'||options.expires.toUTCString)){var date;if(typeof options.expires=='number'){date=new Date();date.setTime(date.getTime()+(options.expires*24*60*60*1000));}else{date=options.expires;}
expires='; expires='+date.toUTCString();}
var path=options.path?'; path='+(options.path):'';var domain=options.domain?'; domain='+(options.domain):'';var secure=options.secure?'; secure':'';document.cookie=[name,'=',encodeURIComponent(value),expires,path,domain,secure].join('');}else{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]);if(cookie.substring(0,name.length+1)==(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break;}}}
return cookieValue;}};