(function($) {
	$(document).ready(function($) {
		/* -------------------------------------------------------
		 * SLIDE DOWN BOX
		 * ----------------------------------------------------- */
		$(".slideDownContent").hide();

		$(".slideDown").click(function() {
			if($(this).hasClass('open')) {
				$(this).removeClass('open');
				$($(this).attr("rel")).slideUp('fast');
				$(this).find('.arrow').html('&darr;');
			}
			else {
				$(this).addClass('open');
				$($(this).attr("rel")).slideDown('fast');
				$(this).find('.arrow').html('&uarr;');
			}
			return false;
		});

		/* --------------------------------------------------------
		 * WALL IMAGES UPDATE
		 * ----------------------------------------------------- */
		updateWallTime($(".wallContainer img.active").attr('alt'));

		$(".wallInformation .newer, .wallInformation .older").click(function(){
			if($(this).hasClass('disabled')) return false;

			$('.wallContainer .overlay').show();
			var selected = $('.wallContainer .active');

			if($(this).hasClass('newer')) {
				// check to see if this is the last one or not
				var newSelected = selected.parents('li').next().find('img');

				if(newSelected) {
					selected.fadeOut(500, function() {
						$(this).removeClass('active');
						$('.wallContainer .overlay').hide();
					});

					newSelected.fadeIn(500, function() {
						$(this).addClass('active');
					});

					updateWallTime(newSelected.attr('alt'));
				}
				$(".wallInformation .older").removeClass('disabled');

				// check for the next one
				if(newSelected.parents('li').next().find('img').length <= 0) $(".wallInformation .newer").addClass('disabled');
			}
			else {
				if(selected.parents('li').prev().find('img').length > 0) {
					// previous elements exist
					var newSelected = selected.parents('li').prev().find('img');

					if(newSelected) {
						selected.fadeOut(500, function() {
							$(this).removeClass('active');
						});

						newSelected.fadeIn(500, function() {
							$(this).addClass('active');
							$('.wallContainer .overlay').hide();
						});

						updateWallTime(newSelected.attr('alt'));
					}
				}
				else {
					// load the image after this one off the server
					var prevImage = $('.wallContainer .active').attr('src');

					// IE fix for relative paths
					if(prevImage.indexOf('/assets')) prevImage = prevImage.substring(prevImage.indexOf('assets'));

					$.getJSON("home/retriveWallimage/", { lastFile: prevImage}, function(data) {
						var title = "The Wall - " + data.Created;
						$('.wallContainer ul').prepend('<li><img class="tofadein" src="'+ data.Filename +'" width="769" height="411" alt="'+ title +'" /></li>');

						$('.wallContainer .active').fadeOut(500, function() {
							$(this).removeClass('active');
						});

						$('.wallContainer .tofadein').fadeIn(500, function() {
							$(this).removeClass('tofadein').addClass('active');
							$('.wallContainer .overlay').hide();
						});

						updateWallTime(title);
					});
				}

				// check to see if we can go further back
				if(parseInt($('.wallContainer .totalImages').text()) <= $('.wallContainer li').length) $(".wallInformation .older").addClass('disabled');

				// since we're back in time we can move forward
				$(".wallInformation .newer").removeClass('disabled');
			}

			return false;
		});

		// Helper Function for updating the wall time
		function updateWallTime(latestImage) {
			$(".wallImageAgo").text(latestImage.substr(latestImage.indexOf(' - ') + 2));
		}

		/* --------------------------------------------------------
		 * FLICKR LOADING IMAGES AND CAROUSEL FUNCTIONS
		 * ----------------------------------------------------- */
		var imgs;
		var photoN = 0
	  	$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=bemorehuman&tagmode=any&format=json&jsoncallback=?",
	        function(data){
				imgs = data;
				$("#images li").remove();
				$("#images ul").width(data.items.length*320)
				$(".number .pages").text(data.items.length)
				$.each(data.items, function(i,item){
					var author = authorClean(item.description);

					// work out whether we uploaded the image through our account or not
					if(item.author.indexOf("Be More Human") < 0) {
						// use their version
						author = item.author.substring(item.author.indexOf('(')+1, item.author.lastIndexOf(')'));
					}

					var authorText = (author && author != "") ? '<i>by:</i> <span class="author">'+ author +'</span>' : "";
					$('#images ul').append('<li>\n' +
					'<div class="imageContainer">\n' +
						'<div class="crop">\n' +
							'<img src="'+biggerImg(item.media.m)+'" alt="'+titleClean(item.title)+'">\n' +
						'</div>\n' +
						'<div class="photoInfo">\n' +
							'<p class="imgTitle">'+titleClean(item.title)+'<p>\n' +
							'<p class="summary"><span class="date">'+dateNice(item.published)+'</span> ' + authorText + '</p> \n' +
						'</div>\n' +
					'</div>\n' +
				'</li>');
				afterLoad(i);
	            if(i == 20) return false;


			});

		});

		//resizes the image to fit into the polaroid
		function afterLoad(i){
			$("#images .older").addClass('disabled')
			var image = $(".imageContainer:eq("+i+") img")
				image.hide()

				image.load(function() {
					var contH = $(".imageContainer .crop").height();
					var contW = $(".imageContainer .crop").width();
				  	var h = image.height();
					var w = image.width();
					if (w < h){
						image.removeClass("hclip").addClass("vclip")
						var newH = image.height();
						var marginUp = (newH - contH) /2;
						image.css({marginTop: -marginUp, marginLeft: 0});

					}else{
						image.removeClass("vclip").addClass("hclip")
						var newW = image.width();
						var marginSide = (newW - contW) /2;
						image.css({marginLeft: -marginSide, marginTop: 0});
					}
					//console.log(image.attr('src')+","+h+","+w+"--"+contH+","+contW+"--"+newH+","+newW)
					image.show()
				});
		//	});
		}

		function biggerImg(current){
			return current.replace("_m", "");
		}

		/**
		 * Generate a clean version of the flickr images authors name
		 */
		function authorClean(auth){
			// auth = "<p>#USER: mmmmmm mmmmmmmmmm mmmmmmmm mmmmmmmm mmmmmmmmmmm mmmmmmmm mmmmmmmmmmm mmmmm</p>";

			var title = auth.substring(auth.lastIndexOf('<p>')+3 ,auth.lastIndexOf('</p>'));
			var user = title.indexOf('#USER:');

			if(user >= 0) {
				title = title.substring(user+7);

				return (title.length > 17) ? title.substring(0, 15) + "..." : title;
			}

			return false;
		}

		// Generate a clean version of the title. Max length of 60
		function titleClean(title) {
			//title = "mmmmmmmm mmm mmmmmm mmm mmmmmmm mmmmmmm mmmmmmmmm mmmm";

			return (title.length > 45) ? title.substring(0, 42) + "..." : title;
		}

		// Generate the date
		function dateNice(date){
			var day = date.substring(8,10)
			var hour = date.substring(11,13)
			var month = Number(date.substring(5,7) - 1)
			var publishDate = new Date(date.substring(0,4), month, day, hour, date.substring(14,16), 00)
			var nzDate = new Date(publishDate.getTime()+43200000)
			//console.log(publishDate.toString()+",  "+date+",  "+nzDate.toString()+",  "+ publishDate.getTimezoneOffset())
			var nzDay = nzDate.getDate()
			var nzMonth = nzDate.getMonth()
			var nzYear = nzDate.getFullYear()
			var nzMonthName = new Array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec')
			//console.log(nzDay + "." + nzMonth + "."+ nzYear)

			return nzDay + " " + nzMonthName[nzMonth] + " "+ nzYear;
		}

		$("#answers .pagination .btMore").click(function(){
			if($(this).hasClass('disabled')) return false;

			refreshTweetList();

			$('#answers .blocks').animate({scrollTop: "+="+360}, 1000, function() {
				$("#answers .pagination .btMore").text('more');
			});
		});

		function refreshTweetList() {
			$("#answers .pagination .btMore").text("loading...");
			var offset = $('#answers .blocksContainer li').length;

			$.get('home/giveTweets?offset='+offset+'&numrec=8', function(data) {
				if(data) {
					$('#answers .blocksContainer ul').append(data);

					// update the scroll panel
					$("#answers .blocksContainer").jScrollPane({
						showArrows: true
					});
				}
				else {
					$("#answers .pagination .btMore").addClass('disabled');
				}
			});

			if(($("#answers .blocksContainer li").length + 4) >= parseInt($("#answers .blocksContainer .totalTweets").text())) {
				$("#answers .pagination .btMore").addClass('disabled');
			}

		}


		/* --------------------------------------------------------
		 * PAGINATION FOR FLICKR
		 * ------------------------------------------------------- */

		$(".pagination").each(function() {
			var initcount = parseInt($(this).find(".number .count").text());
			var max = parseInt($(this).find(".number .pages").text());

			if(initcount == max) $(this).hide();
		});

		$(".paginatable .pagination .newer, .paginatable .pagination .older").click(function(){
			var count = parseInt($(this).siblings(".number").find(".count").text());
			var max = parseInt($(this).siblings(".number").find('.pages').text());
			if($(this).hasClass('disabled')) return false;

			// calculate the width we want to scroll to. Based on the pagination for the blocks container
			// the container should be within 1 level of the pagination
			var paginationContainer = $(this).parents(".paginatable");
			var blocksContainer = paginationContainer.find(" .blocksContainer");
			var method = (paginationContainer.hasClass('vertical')) ? 'vertical' : 'horizontal';

			if($(this).hasClass('older')) {
				var opposite = '.newer';

				if(count>0){
					$(this).siblings(opposite).removeClass('disabled');

					if(method == "vertical") {
						count++;
						blocksContainer.animate({ marginTop: '-='+blocksContainer.parent().height()}, 500);
					}
					else {
						count--;
						blocksContainer.animate({ marginLeft: '+='+blocksContainer.parent().width()}, 500);
					}
				}
			}
			else {
				// going right
				var opposite = '.older';
				if(count<=max){
					if(method == "vertical") {
						count--;
						blocksContainer.animate({ marginTop: '+='+blocksContainer.parent().height()}, 500);
					}
					else {
						count++;
						blocksContainer.animate({ marginLeft: '-='+blocksContainer.parent().width()}, 500);
					}
				}
			}

			// update the display of the pagination
			if(max != count) $(this).siblings(opposite).removeClass('disabled');
			$(this).siblings(".number").find(".count").text(count);
			if(count == max || count == 1) $(this).addClass('disabled');

			return false;
		});

		/* --------------------------------------------------------
		 * FORM INLINE VALIDATION
		 * ------------------------------------------------------ */
		var txVal = $('#Form_doThis_Name').val();
		var txareaVal = $('#Form_doThis textarea').val();
		var txH = $('#Form_doThis_Text').height();
		var currentArea = txareaVal;

		var maxTxArea = 160;
		$('#Form_doThis_Text').keyup(function() {
			var number =  $(this).val().length;
			if(number>maxTxArea){
				$('form .charLeft').text(maxTxArea - number).addClass('red')
			}else{
				$('form .charLeft').text(maxTxArea - number).removeClass('red')
			}

		})

		$('#Form_doThis_Imagefile').wrap('<label class="uploadButton" style="display:none"></label>');
		if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {
		}else{
			$('#Form_doThis #Form_doThis_Name').after('<a class="addImg" href="#">add an image</a>');
		}
		$('#Form_doThis button').appendTo('#Text .middleColumn');

		// change the field values when you type
		$('#Form_doThis_Name').focus(function(){
			if($(this).val() == txVal) $(this).val('');
		}).blur(function(){
			if($(this).val() == '') $(this).val(txVal);
		})
		$('#Form_doThis textarea').focus(function(){
			if($(this).val() == currentArea || $(this).val() == "Image title") {
				$(this).val('');
			}
		}).blur(function(){
			if($(this).val() =='') {
				if($('.addImg').val() == "no images") $(this).val("Image title");
				else $(this).val(currentArea);
			}
		})

		// image switcher
		$('#Form_doThis .addImg').live('click', function(){
			if($('#Form_doThis_Imagefile').is(':visible')){
				$('.uploadButton').fadeOut();
				$(this).text('add an image').animate({marginLeft:10})
				$('#Form_doThis_Text').height(txH).text(txareaVal)
				currentArea = txareaVal;
			}else{
				$('.uploadButton').fadeIn();
				$(this).text('no images').animate({marginLeft:"+="+100})
				$('#Form_doThis_Text').text('Image title');
				currentArea = 'image title';
			}

			return false;
		});

		$('#Form_doThis_Imagefile').change(function(e){
			var value = $(this).val();

			var title = (value.lastIndexOf("\\") > 0) ? value.substring(value.lastIndexOf('\\') + 1) : $(this).val();
			if(title.length > 30) title = title.substr(0, 27) + "...";

			$('.addImg').before("<span class='imgName'>"+ title +"</span>");
			$('.imgName').fadeIn('slow');
		});

		/* --------------------------------------------------------
		 * FORM AJAX VALIDATION
		 * ------------------------------------------------------ */
		$('#Form_doThis').ajaxForm({
			dataType: 'json',
			beforeSubmit: function() {
				var name = $('#Form_doThis_Name').val();
				var text = $('#Form_doThis_Text').val();
				var security = $('#Form_doThis_SecurityID').val();
				var image = $('#Form_doThis_Imagefile').val();
				var validationFail = false;

				if(!name || name == "" || name == "Your Twitter username (without @) or email address") {
					$('#Form_doThis_Name').parents('.middleColumn').addClass('validationError');
					validationFail = true;
				}
				else $('#Form_doThis_Name').parents('.middleColumn').removeClass('validationError');

				if(!text || text == "" || text == "How do humans win?") {
					$('#Form_doThis_Text').parents('.middleColumn').addClass('validationError');
					validationFail = true;
				}
				else $('#Form_doThis_Text').parents('.middleColumn').removeClass('validationError');

				if(validationFail) return false;

				if(image && image != "") {
					var extension = (/[.]/.exec(image)) ? "" + /[^.]+$/.exec(image) + "" : undefined;
					if(!(/^png|jpg|gif|jpeg$/.test(extension.toLowerCase()))) {

						validationFail = true;
						// clear the val
						hideImageUploaded();

						// show the overlay
						$('#Form_doThis .overlay').show();
						$('#Form_doThis .overlay .loading').hide();

						var message = "<h3>Please make sure your file is a jpg, png or gif file</h3>";
						message += "<p class='again'><a href='#'>Close Popup</a></p>";

						$('#Form_doThis .overlay .overlayContent').html(message);

						return false;
					}
				}
				$('#Form_doThis .overlay .overlayContent').html("");
			 	$('#Form_doThis .overlay').fadeIn();
				$('#Form_doThis .overlay .loading').show();
			},
			success: function(response) {
				$('#Form_doThis .overlay .loading').fadeOut();
				if(response.Error_Type == "OK") {
					$('#Form_doThis_Text, #Form_doThis_Imagefile').val('');
					hideImageUploaded();
				}
				var message = '<h3>'+ response.Error_Message +'</h3><p class="again"><a href="#">';
				message += (response.Error_Type != "OK") ? 'Try Again' : '';
				message += '</a></p>';

				$('#Form_doThis .overlay .overlayContent').html(message);

				// update the twitter or flickr feed with so that the users content is the most
				// recent posted
				$.get('home/retriveLatestPostHTML', function(data) {
					if(data) {
						$("#answers .blocksContainer ul").prepend("<li>"+data+"</li>");
					}
				});
			}
		});

		function hideImageUploaded() {
			$('#Form_doThis_Imagefile').val("");
			$('.imgName').fadeOut('slow');
			$('.addImg').click();
		}

		/**
		 * Close the popup
		 */
		$(".again a").live('click', function() {
			$('#Form_doThis .overlay').fadeOut();

			return false;
		})
	});

	/* --------------------------------------------------------
	 * SCROLL PANEL
	 * ------------------------------------------------------- */
	if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {

	}else{
		$('#answers .blocksContainer').jScrollPane({
			showArrows: true
		});
	}



	/* --------------------------------------------------------
	 * ANTISPAN MASK FOR EMAIL
	 * ------------------------------------------------------- */
	var email = "contact"+"@"+"bemorehuman"+"."+"org"
	$(".emailLink").attr("href","mailto:"+email).text(email)

})(jQuery);
