// JavaScript Document

	String.prototype.trim = function () {
		var str = this.replace(/^\s+/, '');
		for (var i = str.length - 1; i >= 0; i--) {
			if (/\S/.test(str.charAt(i))) { str = str.substring(0, i + 1); break; }
		} return str;
	}

	function flowText(top, left, cont) {
		var oText;
		// use the cached data if possible, slightly faster it appears
		if (cont.data("original") != null) { oText = cont.data("original");	} 
		else {
			oText = left.text();
			cont.data("original", oText);
		}
		top.show(); // make sure the top p is shown so it's intepreted by the dom correctly
		var c = 0; // the is the assumed number of characters fit in the box to speed up loop
		var lineheight = 20; // the explicitly set hieght of the lines !important to know
		var leftheight = left.height(); //this the closed height of the description box set w/ CSS
		var topheight = 0;
		left.toggleClass("closed", "open");
		
		// using the cached data in this case dramatically affects performance
		if (cont.data("top")) { 
			top.text(cont.data("top"));
			left.text(cont.data("leftalt"));
                        left.height(200);
		}
		else {
			// fit the bottom of the paragraph into the left box
			while (left.height() > 160) { c++; left.text(oText.substring(c)); }
			// this will get it close to right, the last line may be an orphan, aka ugly
			top.text(oText.substring(0, c));
			topheight = top.height() + lineheight;
			oText = top.text(); // we are now manipulating the text in the top box
			c = 0; // reset the counter
			
			while (top.height() < topheight && c < left.text().length) {
				top.text(oText + left.text().substring(0, ++c));
			}
			// this will always go 1 character too far
			top.text(top.text().substring(0, top.text().length - 1));
			left.text(left.text().substring(c - 1));
			
			cont.data("top", top.text());
			cont.data("leftalt", left.text());
                        left.height(200);
		}
		top.hide().slideDown("fast");
		// cont.text("[collapse]");
		// cont.show("fast");
	}
	
	function resetText(top, left, cont) {
//		left.text(cont.data('original')); // restore the text from the cache
//		top.slideUp("fast").text("");
//		left.addClass("closed");
//		cont.text("[read more]");
//		cont.show("fast");
	}
	
	function prepareTextFlow () {
	   $("#content > div.piece > div.content").each(function() {
      	// Determine the height of each body of text
         var left = $(this).children("p.left");
			var top = $("<p class='top'></p>");
			var cont = $("<div class='continue'>[read more]</div>");
			left.before(top);
			if (left.height() >= 160) { left.after(cont); left.addClass("closed"); }
			
                        flowText(top, left, cont);
			cont.toggle ( 
				function () { $(this).hide("fast", function () { flowText(top, left, cont); }) }, 
				function () { $(this).slideUp("fast", function () { resetText(top, left, cont); }) }
				);
		});
	}
	
	function resumeListen() {
		var openResume = $("a#openresume");
		var closeResume = $("a#closeresume");
		var wrapper = $("div#wrapper");
		var resumeWrapper = $("div#resumewrapper");
		
		openResume.click ( function () { wrapper.addClass("hideMonitors"); wrapper.slideUp("fast", function () {
			resumeWrapper.slideDown("fast");	
		}); });
		
		closeResume.click ( function () {
			resumeWrapper.slideUp("fast", function () {
			wrapper.slideDown("fast").removeClass("hideMonitors");	
		}); });
	}
	
	function contactListen() {
		var openContact = $("a#opencontact");
		var closeContact = $("a#closecontact");
		var wrapper = $("div#wrapper");
		var contactWrapper = $("div#contactwrapper");
		
		openContact.click ( function () { wrapper.addClass("hideMonitors"); wrapper.slideUp("fast", function () {
			$(document).clearQueue();
			contactWrapper.slideDown("fast", function () { $("#email").focus(); });	
		}); });
		
		closeContact.click ( function () {
			$(document).clearQueue();
			contactWrapper.slideUp("fast", function () {
			wrapper.slideDown("fast").removeClass("hideMonitors");	
		}); });
	}
	
	
	function isvalid (element) {
		if (element.hasClass("invalid")) { element.next("small").remove(); }
		if (!element.hasClass("valid")) { element.after("<small class='ok'>OK</small>"); }
		element.addClass("valid").removeClass("invalid");
	}
	
	function invalid (element) { 
		if (element.hasClass("valid")) { element.next("small").remove(); }
		if (!element.hasClass("invalid")) { element.after("<small class='nogood'>ERROR</small>"); }		
		element.addClass("invalid").removeClass("valid"); 
	}

	//Advanced Email Check credit - JavaScript Kit (http://www.javascriptkit.com)
	function checkemail(element){
		var str= element.val();
		var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
		if (filter.test(str)) {
			return true;
		} else{ return false; }
	}

        function checkURL () {
                if (window.location.hash == "#contact") { $("a#opencontact").click(); }
                else if (window.location.hash == "#resume") { $("a#openresume").click(); }
        }

function addSocial() {
	$("#content > div.piece").each(function() {
var pId = $(this).attr("id");
var toTop = $(this).children("div.footer").children("div.helpLinks").children("a.toTop");

if (pId != null && pId != "") {
var socialElements = "";
//<a href='http://twitter.com/home?status=Reading+http://www.kylewiedman.com/&#35;" + pId + "' title='Tweet This' class='twShare social first' target='_blank'>Tweet This</a>";

socialElements += "<a href='http://www.facebook.com/sharer.php?u=http://www.kylewiedman.com/&#35;" + pId + "' title='Share on Facebook' class='fbShare social first' target='_blank'>Share on Facebook</a>";

socialElements += "<a href='http://www.google.com/reader/link?url=http://www.kylewiedman.com/&#35;" + pId + "&amp;imageurl=http://www.kylewiedman/images/preview/purduepress.jpg' title='Buzz This' class='buzzShare social last' target='_blank'>Buzz This!</a>";

toTop.before(socialElements );
}

        });
}

	$(document).ready(function() {

		prepareTextFlow();
		resumeListen();
		contactListen();
		checkURL();
		addSocial();
		$("a.enlarge").lightBox();
		var nowhere = $("a.nowhere, a.il, a.dw, a.fl, a.ps").fadeTo("slow", .75);
		nowhere.hover( function () { 
			$(this).stop();
			
			$(this).animate({
				 textIndent: 20
			  }, {
				 duration: 200,
				 complete: function() {
					 $(this).fadeTo("fast", 1)
				 }
			  });
			  return false;
		});
		nowhere.mouseout( function () {
			$(this).stop();
			$(this).animate({
				 textIndent: -200
			  }, {
				 duration: 75,
				 complete: function() {
					 $(this).fadeTo("slow", .75)
				 }
			  });
			  return false;
		});
		nowhere.click ( function () { return false; }); // prevent clicking on these links
		$("select").selectmenu({ maxHeight: 150});	// build select menus
		
		$("input.email").keyup( function () {
			if ($(this).val().length > 0) {
				if (checkemail($(this))) { isvalid($(this)); } else { invalid($(this)); }
			}  else { $(this).next("small").remove(); $(this).removeClass("invalid").removeClass("valid"); }
		}).blur(function () { $(this).keyup(); }).keyup();

		$("textarea").keyup( function () {
			if ($(this).val().length > 0) {
				isvalid($(this));
			}  else { $(this).next("small").remove(); $(this).removeClass("invalid").removeClass("valid"); }
		}).blur(function () { $(this).keyup(); }).keyup();
		
		$("#submitform").slideDown("fast").click ( function () {
			var valid = true;
			var reason = $("#reason");
			var email = $("#email");
			var comment = $("#comment");
			var button = $(this);
			var success = '<span class="success">Your message was successfully sent. <br /> Click this box to reset the form.</span>';
			var fail = '<span class="fail">An error occured, your message was not sent. Please try again or use a different method.</span>';
			try {
				if (comment.val().length == 0) { invalid(comment); valid = false;}
				if (email.val().length == 0 || !checkemail(email)) { invalid(email); valid = false; email.focus(); }
				
				if(valid == true) {
					$("#contactform div.cform").prev(".fail").remove();
					$(this).hide().after("<small class='ajaxwait'>sending message...</small>");
					$.post("mailme.php", {email: email.val(), reason: reason.val(), comment: comment.val()}, function(data){
						if (data == "success") {
							$("#contactform div.cform").slideUp("normal", function() {
								$("#contactform div.cform").prev(".fail").remove().end().before(success);
								$(".success").click( function () { 
									$("#contactform div.cform").slideDown("normal");
										email.val("").keyup().focus();
										comment.val("").keyup();
										button.next("small").remove().end().fadeIn("slow");
										$(this).remove();
									});
								});
						} else if (data == "fail") {
							$("#contactform div.cform").before(fail);
							button.next("small").remove().end().fadeIn("slow");
						} else {
							$("#contactform div.cform").before("<span class='fail'>" + data + "</span>");
							button.next("small").remove().end().fadeIn("slow");	
						}
					});
				}
			} catch (err) {
					$("#contactform div.cform").before(fail);
					button.next("small").remove().end().fadeIn("slow");
			}
			return false;	
		});
	});
