$(document).ready(function() {
	
	// submit lyrics
		$("body").append("<div id=\"filterBG\"></div>");
		$("div#submit").hide(); // hide the form
		$("div#submit").append("<a id=\"closeSubmit\" href=\"#\" title=\"close\">close</a>"); // add close link
		
		// character countdown
			function characterCountdown() {
				$("textarea#submitLyric").before("<span id=\"charCountdown\">140</span>"); // add countdown
				checkChars(); // check limit when page loads
				
				function checkChars() {
					var currentLength = $("textarea#submitLyric").val().length; // current char length
					var maxLength = 140; // max length
					
					var remainingChars = maxLength - currentLength; // calculate
					
					// if over the limit add error class
					if (remainingChars <= 0) {
						$("span#charCountdown").addClass("error");
					} else {
						$("span#charCountdown").removeClass("error");
					}
					
					// update user
					$("span#charCountdown").html(remainingChars);
				} 
				
				// on key up
				$("textarea#submitLyric").keyup(function() {
					checkChars();
					return false;
				});
			}
			if ($("textarea#submitLyric").length != 0) { characterCountdown(); } // only run if textare exists
		
		// submit click (show form)
		$("a#submitNav").click(function() {
			// set the height of overlay
			var docHeight = $(document).height();
			$("div#filterBG").css("height", docHeight);
			
			$("div#submit").show(); // show the form
			$("div#submit").center(); // center the form
			$("div#filterBG").show(); // show the bg
			
			// up the z-index
			$("div#submit").css("z-index", "9999");

			return false;
		});
		
		// close submit form
		$("a#closeSubmit").live('click', function() {
			$("div#submit").hide(); // hide the form
			$("div#filterBG").hide(); // hide the bg
			return false;
		});
		
		// setup contact form click
		function wireUp() {
			$("#submitForm").submit(function() {
				submitAjaxForm("#submitForm", "/include/submitLyrics.php", "#submit");
				return false;					  
			});
		}
		
		// form submitted, lets Ajax!
		function submitAjaxForm(formId, formUrl, containerToUpdate){
			//$("#ajaxLoader").css({'display' : 'inline'}); // show the ajax loader icon
			var inputs = $(formId).serialize(); // grab all the form inputs
			
			jQuery.ajax({
				type: "POST",
				data: inputs, 
				url: formUrl,
				error: function(html) {  
				},
				success: function(html) { 
					// load response to form 
					$(containerToUpdate).html(html);
					$("div#submit").append("<a id=\"closeSubmit\" href=\"#\" title=\"close\">close</a>"); // add close link
					if ($("textarea#submitLyric").length != 0) { characterCountdown(); } // only run if textare exists
					wireUp();
				}
			});
		}
		
		wireUp();
						   
	// show / hide about us
		$("div#about-us").hide();
		
		$("a#aboutNav").toggle( function() {
			$("div#about-us").show();	
			$(this).addClass("aboutActive");
			return false;	
		}, function() {
			$("div#about-us").hide();
			$(this).removeClass("aboutActive");
			return false;
		});
	
	// LN latest news
		
		// pull JSON data from twitter API
      	$.getJSON("http://search.twitter.com/search.json?from=lyricallynoted&rpp=2&ors=%23LNnews&callback=?", "", showTweets);
		
		// show the latest news
		function showTweets(data) {
			var newsTweets = ""; // setup news vars
			
			// setup date vars
			var tweetFullDate = "";

			var isoDay = "";
			var isoMonth = "";
			var isoYear = "";
			var isoTime = "";
			
			var finalDate = "";
			
			// cycle through each news tweet and append
			$.each(data.results, function(i,item) {
				var newsTweetsContent = item.text;
										  
				// format the date
					tweetFullDate = item.created_at.split(" ");

					isoDay = tweetFullDate[1];
					isoMonth = tweetFullDate[2];
					isoYear = tweetFullDate[3];
					isoTime = tweetFullDate[4];
					
					switch(isoMonth){
						case("Jan"):
							isoMonth = "01";
							break;
						case("Feb"):
							isoMonth = "02";
							break;
						case("Mar"):
							isoMonth = "03";
							break;
						case("Apr"):
							isoMonth = "04";
							break;
						case("May"):
							isoMonth = "05";
							break;
						case("Jun"):
							isoMonth = "06";
							break;
						case("Jul"):
							isoMonth = "07";
							break;
						case("Aug"):
							isoMonth = "08";
							break;
						case("Sep"):
							isoMonth = "09";
							break;
						case("Oct"):
							isoMonth = "10";
							break;
						case("Nov"):
							isoMonth = "11";
							break;
						default:
							isoMonth = "12";
					}
					// create ISO date
					finalDate = prettyDate(isoYear + "-" + isoMonth +"-" + isoDay + "T" + isoTime + "Z"); // with help from pretty.js http://ejohn.org/blog/javascript-pretty-date/
					if (!finalDate) { finalDate = "quite a while ago..."; }
					
					// sort out any links in the tweet
						// convert URLs
						newsTweetsContent = newsTweetsContent.replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href=\"$1\" title=\"$1\" target=\"_blank\">$1</a>");
						// convert twitter @s
						newsTweetsContent = newsTweetsContent.replace(/(^|\s)@(\w+)/g, "$1@<a href=\"http://www.twitter.com/$2\" title=\"@$2\" target=\"_blank\">$2</a>");
						
					// remove LNnews tag
					newsTweetsContent = newsTweetsContent.replace(/#LNNews/i, "");
					
					// add the tweet to the newslist			
					newsTweets += "<p class=\"newsTweet\">" + newsTweetsContent + "<a class=\"postedTime\" href=\"http://twitter.com/LyricallyNoted/status/" + item.id + "\" title=\"view this tweet\" target=\"_blank\">posted " + finalDate + "</a></p>";
			})
			
			// if we have latest news show it
			if(newsTweets != "") {
				$("#newsBoxInner").html(newsTweets);
			// no news so tell the user
			} else {
				$("#newsBoxInner").html("<p class=\"newsTweet\">Looks like we haven't posted any news lately, drop us an email to see what we are up to!</p>");
			}

		}
	
	// center div function
	jQuery.fn.center = function () {
    	this.css("position","absolute");
    	this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
    	this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() - 20 + "px");
    	return this;
	}
					   
});
