// JavaScript Document


(function( $ ){

//----------------------------------/ Align Tables /-----------------------------------------------//

// Add css properties to first td in each row (in a row of two tds) 

$.fn.alignTable = function(properties) {
	
	// use css from arguments or default (default is aligned right and valigned top)
	if (arguments.length) {
		cssProperties = arguments[0];
	} else {
		cssProperties = { "textAlign":"right","verticalAlign":"top","paddingRight":"5px" };
	}
	
	$(this).find("td:even").each(function() {
		$(this).css(cssProperties);			
	});
	
	return this;
}

//----------------------------------/ Align Labels /-----------------------------------------------//

// Add css properties to tds with label tags in them 

$.fn.alignLabels = function(properties) {
	
	// use css from arguments or default (default is aligned right and valigned top)
	if (arguments.length) {
		cssProperties = arguments[0];
	} else {
		cssProperties = { "textAlign":"right","verticalAlign":"top","paddingRight":"5px" };
	}
	
	$(this).find("td:has(label)").each(function() {
		$(this).css(cssProperties);			
	});
	
	return this;
}


//----------------------------------/ Smart Password /-----------------------------------------------//

// Preview each letter as you type into a password input

$.fn.smartPassword = function() {
	if ($(this).next("span").length) {
		$(this).next("span").addClass("smartPasswordSpan");
	} else {
		$(this).after("<span class='smartPasswordSpan' style='padding-left:6px; position:absolute;'></span>");
	}
	var origPasswordSpanText = $(this).next("span.smartPasswordSpan").text();
	var t;
	$(this).keypress(function(e) {  
		clearTimeout(t);
		var lastLetter = " "+String.fromCharCode(e.which);
		var $thisSpan = $(this).next("span.smartPasswordSpan");
		$thisSpan.text(lastLetter);
		t = setTimeout(function() {
			$thisSpan.text(origPasswordSpanText);				
		}, 350);
	});
	
	return this;
}

//----------------------------------/ Smart Input /-----------------------------------------------//

// Input clears when clicked and returns to original value when blurred

$.fn.smartInput = function() {
	$(this).each(function() {
		var originalValue = $(this).val();
		$(this).addClass("smartInputStart").focus(function() {
			if ($(this).val() == originalValue) {
				$(this).removeClass("smartInputStart").val("");
			}
		}).blur(function() {
			if ($(this).val() == "") {
				$(this).addClass("smartInputStart").val(originalValue);	
			}
		});
	});
	
	return this;
}

//----------------------------------/ Validate Email /-----------------------------------------------//

// validate email in real time

$.fn.validateEmail = function() {
	
	return this.each(function() {
		$this = $(this);
		$this.keyup(function() {
			var thisVal = $this.val();
			if (thisVal.indexOf("@") < 1 || thisVal.indexOf(".") < 1) {
				$this.addClass("requiredRed");
			} else {
				$this.removeClass("requiredRed");
			}
		});
		$this.closest("form").submit(function() {
			var thisVal = $this.val();
			var returnVal = true;
			if (thisVal.indexOf("@") < 1 || thisVal.indexOf(".") < 1) {
				$this.addClass("requiredRed");
				alert("That email isn't valid");
				returnval = false;
				return false;
			}
			return returnVal;
		});
	});
	
}


//-------------------------------------------/ Pop Ups /--------------------------------------------------//

// Dim screen (with .browserDimmer) and fade in target div with 'data' as content
// Works well as the callback for an ajax function

$.fn.popUp = function(data,callback) {
	
	var thisPopUp = $(this);
	$(".browserDimmer").fadeIn(function() {
		thisPopUp.html(data);
		thisWidth = thisPopUp.outerWidth();
		
		scrollVal = $(window).scrollTop();
		
		thisPopUp.css({"marginLeft":"-"+thisWidth/2+"px"}).fadeIn(function() {
			thisPopUp.animate({"top":scrollVal+"px"},500);
			// callback
			if (typeof callback == 'function') {
				callback.call(this, data);
			}																							  
		});						
	});
	
	//return this;
}

$("a[href=#closePopup]").live("click",function() {
	$(".popup").fadeOut(function() { $(".browserDimmer").fadeOut(); });
	return false;
});

//----------------------------------/ Smart Button /-----------------------------------------------//

// Make an element move to the mouse when the mouse gets near it... take two optional arguments... hit area size and speed

$.fn.smartButton = function() {
	
	
	if (arguments[0] == parseInt(arguments[0])) { //---- set hit area size
		var padding = arguments[0];
	} else {
		var padding = 100;	
	}
	if (arguments[1] == parseInt(arguments[1])) { //---- set speed
		var speed = arguments[1];
	} else {
		var speed = 1;	
	}
	
	// create a dummy to maintain page positioning of other elements
	if ($(this).css("position") != "absolute" && $(this).css("position") != "fixed") {
		
		// method 1... clone div and remove all visual styles - to hold place of everything else because it's a relative position
		$(this).clone().css({ "background":"none","border":"none" }).html("").insertAfter($(this));
	}
	
	// wrap element in hit area and style hit area appropriately
	thisZindex = $(this).css("zIndex");
	$(this).wrap("<div class='smartButton' style='position:fixed; padding:"+padding+"px; margin-left:-"+padding+"px; margin-top:-"+padding+"px; z-index:"+thisZindex+";'></div>");
	$(this).css("position","relative");
	
	// set variable to call this button
	var thisSmartButton = $(this);
	
	// move to position when mouse is over hit area
	$(this).parent("div").mousemove(function(e) {
		
		// calculate offset values each time
		var offset = thisSmartButton.offset();
		offset.right = offset.left+thisSmartButton.width();
		offset.bottom = offset.top+thisSmartButton.height();
		
		// left side
		if (e.pageX < offset.left) {
			$(this).animate({"paddingLeft":"-="+speed},0);
		}
		// right side
		if (e.pageX > offset.right) {
			$(this).animate({"paddingLeft":"+="+speed,"paddingRight":"-="+speed},0);
		}
		// top side
		if (e.pageY < offset.top) {
			$(this).animate({"paddingTop":"-="+speed},0);
		}
		// bottom side
		if (e.pageY > offset.bottom) {
			$(this).animate({"paddingTop":"+="+speed,"paddingBottom":"-="+speed},0);
		}
		
	});
	
	// return to position on mouse leave
	$(this).parent("div").mouseleave(function() {
		$(this).stop().animate({"paddingLeft":padding+"px","paddingRight":padding+"px","paddingTop":padding+"px","paddingBottom":padding+"px"},500);
	});
	
	return this;

}

//----------------------------------/ Character Count /-----------------------------------------------//

// Set character limit, but let users keep typing with an error message

// update character count
$.fn.charCount = function(count) {
	$(this).after("<span class='charcountSpan' style='padding-left:6px'></span>");
	$(this).keyup(function() {
		var textcopy = $(this).val();
		var textcopyCount = textcopy.length;
		var $thisSpan = $(this).next("span.charcountSpan");
		$thisSpan.text(textcopyCount+"/"+count);
		if (textcopyCount > count) {
			$thisSpan.css({"color":"#990000"});
		} else {
			$thisSpan.css({"color":"#000"});
		}
	});
	
	return this;
}

//----------------------------------/ Create Permalink /-----------------------------------------------//

// Make Reader Friendly URL (Permalink)
// Call this on a form

$.fn.createPermalink = function(input,output) {
	
	return this.each(function() {
		var $thisForm = $(this);
		$thisForm.find("input[name="+input+"],input[name="+output+"]").keyup(function() {
			var origVal = $(this).val();
			permaVal = origVal.replace(/ /g,"-");
			permaVal = permaVal.replace(/\.|,|\/|\?|'|\!/g,"");
			permaVal = permaVal.replace(/&/g,"and");
			$thisForm.find("input[name="+output+"]").val(permaVal);
		});
	});
}

//----------------------------------/ Confirm Password /-----------------------------------------------//

// Confirm Password
// Call this on a form

$.fn.confirmPassword = function(password,confirm_password) {
	
	var passwordValue;
	var confirmValue;
	
	this.each(function() {
		var $thisForm = $(this);
		var t;
		var noDelay = false;
		$thisForm.find("input[name="+password+"],input[name="+confirm_password+"]").keyup(function() {
			clearTimeout(t);
			passwordValue = $thisForm.find("input[name="+password+"]").val();
			confirmValue = $thisForm.find("input[name="+confirm_password+"]").val();
			if (passwordValue == confirmValue) {
				$thisForm.find("input[name="+password+"],input[name="+confirm_password+"]").removeClass("requiredRed");
				noDelay = true; // next time, turn red instantly
			} else {
				if (noDelay) { d = 0; } else { d = 1000; } // either turn input red in one second or instantly
				t = setTimeout(function() {
					$thisForm.find("input[name="+password+"],input[name="+confirm_password+"]").addClass("requiredRed");
					noDelay = false; // from now on, turn red after a second
				},d);
			}
		});
	});
	
	this.submit(function() {
		if (passwordValue !== confirmValue) {
			alert("Your passwords don't match!");
			return false;
		}
	});
	
	return this;
}

//----------------------------------/ Required Fields /-----------------------------------------------//

// Call this on a form. Set any fields in a form with the class 'required' as required
// one parameter is a jQuery path to the element to place the asterisk after

$.fn.required = function(path_to_asterisk) { // path to asterisk does NOT work yet
	
	// either add a * after the input or append it to argument
	if (arguments[0]) {
		path_to_asterisk = arguments[0];	
	} else {
		path_to_asterisk = false;
	}
	
	return this.each(function() {
		var $thisForm = $(this);
		
		$thisForm.find(".required").each(function() {
			// choose where to put the asterisk
			if (path_to_asterisk) {
				$(this).path_to_asterisk.append("<span style='color:#CA0202;'> *</span>");
			} else {
				$(this).after("<span style='color:#CA0202;'> *</span>");	
			}
		});
		
		// prevent submit and show erro
		$thisForm.submit(function() {
			var returnVal = true;
			$(this).find(".required").each(function() {
				$(this).removeClass("requiredRed");
				if ($(this).val() == "" || $(this).hasClass("smartInputStart")) {
					$(this).addClass("requiredRed"); // .css("border","1px solid #FF0000");
					returnVal = false;
				}
				//return returnVal;
			});
			if (!returnVal) {
				return returnVal;
			}
		});
	});
}


//----------------------------------/ Smart Form /-----------------------------------------------//

// This bundles a number of form plugins into one plugin that is called on the form and uses classes to add plugins to specifc elements
// included plugins/classes:
//
// smartInput/.smartInput | smartPassword/.smartPassword | required/.required | validateEmail/.validateEmail
//

$.fn.smartForm = function() {
	
	return this.each(function() {
		var $thisForm = $(this);
		$thisForm.required();
		$thisForm.find(".smartInput").each(function() { $(this).smartInput(); });
		$thisForm.find(".smartPassword").each(function() { $(this).smartPassword(); });
		$thisForm.find(".validateEmail").each(function() { $(this).validateEmail(); });
	});
}

})( jQuery ); // this closes everything in the whole document
