// JavaScript Document
// The Brolik Platform v3

(function( $ ){

//-------------------------------------------/ 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,noDim,callback) {
		
	var $thisPopUp = $(this);
	if (noDim) { //---- don't use browserDimmer
		$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);
				}																							  
			});
	} else { //---- use browserDimmer
		$(".browserDimmer").fadeIn(function() {
			$thisPopUp.html("<p class='close'><a href='#closePopUp'>X</a></p>"+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);
				}																							  
			});	
		});
	}
	
	$thisPopUp.find("a[href=#closePopUp]").live("click",function() {
		$thisPopUp.fadeOut(function() { $(".browserDimmer").fadeOut(function() { $thisPopUp.html(""); }); });
		return false;
	});
}

//-------------------------------------------/ Confirm-Style Pop Ups /--------------------------------------------------//

// hitting cancel returns false, hitting OK runs the callback function

$.fn.popUpConfirm = function(data,callback) {
	
	var $thisPopUp = $(this);
	$(".browserDimmer").fadeIn(function() {
		
		$thisPopUp.html(data+"<p style='text-align:center'><a class='confirmOK button' href='#confirmOK'>OK</a> <a class='confirmCancel button' href='#confirmCancel'>Cancel</a></p>"); // "<p class='close'><a href='#closePopUp'>X</a></p>"+
		
		var thisWidth = $thisPopUp.outerWidth();
		
		var scrollVal = $(window).scrollTop();
		
		$thisPopUp.css({"marginLeft":"-"+thisWidth/2+"px"}).fadeIn(function() {
			$thisPopUp.animate({"top":scrollVal+"px"},500);
		});
		
		$thisPopUp.find(".confirmOK").click(function() {
			
			$thisPopUp.fadeOut(function() {
				$(".browserDimmer").fadeOut(function() {
					
				});
				callback.call(this, data);
			});
			return false;
		});
		
		$thisPopUp.find(".confirmCancel").click(function() {
			$thisPopUp.fadeOut(function() {
				$(".browserDimmer").fadeOut();
			});
			return false;
		});
		
		var returnVal;
		
	});
	
	$thisPopUp.find("a[href=#closePopUp]").live("click",function() {
		$thisPopUp.fadeOut(function() { $(".browserDimmer").fadeOut(function() { $thisPopUp.html(""); }); });
		return false;
	});
}

//----------------------------------/ 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;
		});
	});
	
}

//----------------------------------/ 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(asteriskStyle) { // path to asterisk does NOT work yet
	var returnTrue;
	
	// either add a * after the input or append it to argument
	if (arguments[0]) {
		asteriskStyle = arguments[0];	
	} else {
		asteriskStyle = { "color":"#ca0202","position":"absolute","marginLeft":"0.5%" }
	}
	
	return this.each(function() {
		var $thisForm = $(this);
		
		$thisForm.find(".required").each(function() { //---- place asterisk
			
			if ($(this).next("div.chzn-container").length) {
				$(this).next("div.chzn-container").after("<span>*</span>").next("span").css(asteriskStyle);
			} else {
				$(this).after("<span>*</span>").next("span").css(asteriskStyle); // style='color:#CA0202; position:absolute; margin-left:-10px;'
			}
			
		});
		
		$thisForm.submit(function() { //---- prevent submit and add messaging if fields are not filled out
			$(this).find(".required").each(function() {
				//returnTrue = true;
				$(this).removeClass("requiredRed");
				if ( ($(this).val() == "" || $(this).hasClass("smartInputStart")) || ($(this).hasClass("chzn-done") && $(this).val() == null) ) {
					$(this).addClass("requiredRed");
					//returnTrue = false;
				}
			});
			//if (!returnTrue) {
			if ($thisForm.find(".requiredRed").length) {
				return false;
			}
		});
	});
}


//----------------------------------/ 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() {
	
	var longestLabel;
	return this.each(function() {
		
		var $thisForm = $(this);
		
		if ($thisForm.hasClass("sidebyside")) { //---- format labels
			longestLabel = 0;
			$thisForm.find("label").css({"display":"inline-block","textAlign":"right"}).each(function() {
				var thisLabel = $(this).outerWidth();
				if (thisLabel > longestLabel) {
					longestLabel = thisLabel;	
				}
			});
			$thisForm.find("label").css({"width":longestLabel+10+"px"}); //---- this probably won't work in IE 7 and below because of the inline-block
		}
		
		if ($thisForm.hasClass("stacked")) {
			$thisForm.find("label").each(function() {
				$(this).css({"display":"block","marginTop":"1%"});	
			});
			$thisForm.find("label:first").css({"marginTop":"0px"});
		}
		
		$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
