// 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 /--------------------------------------------------//

// second parameter is true for automatic fadeOut, false for click to fadeOut
// Works well as the callback for an ajax function

$.fn.popUp = function(data,fadeout,callback) {
	
	var $thisPopUp = $(this);
	//$(".browserDimmer").fadeIn(function() {
		
		if (data) { 
			$thisPopUp.html("<img src='images/close.jpg' alt='close' class='close' />"+data);
		} else {
			$thisPopUp.prepend("<img src='images/close.jpg' alt='close' class='close' />");	
		}
		
		var thisWidth = $thisPopUp.outerWidth();
		
		var scrollVal = $(window).scrollTop();
		//$thisPopUp.css("top",-10);
		$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(".close").click(function() {
			$thisPopUp.fadeOut(function() {
				$(".browserDimmer,.browserDimmerWhite").fadeOut();
				//---- stop playing a video if there's a video
				if ($thisPopUp.find(".video-player").length) {
					$thisPopUp.html("");
				}
			});		
			clearTimeout(closePopUpTimeout);
		});
		
		var closePopUpTimeout;
		/* if (fadeout) {
			closePopUpTimeout = setTimeout(function() {
				$thisPopUp.find(".close").click();
			},2500);
		} */
	//});
	
	//return this;
}

$("a[href=#closePopup]").live("click",function() {
	$(".popup").fadeOut(function() {
		$(".browserDimmer").fadeOut();
	});
	return false;
});
//--------------------------------------------/ Custom popup /-----------------------------------------------------------
$.fn.popUp2 = function(data,fadeout,callback) {
	
	var $thisPopUp = $(this);
	//$(".browserDimmer").fadeIn(function() {
		
		if (data) { 
			$thisPopUp.html("<img src='images/close.jpg' alt='close' class='close' />"+data);
		} else {
			$thisPopUp.prepend("<img src='images/close.jpg' alt='close' class='close' />");	
		}
		
		var thisWidth = $thisPopUp.outerWidth();
		
		var scrollVal = $(window).scrollTop();
		$thisPopUp.css("top",-10);
		$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(".close").click(function() {
			$thisPopUp.fadeOut(function() {
				$(".browserDimmer,.browserDimmerWhite").fadeOut();
			});
			clearTimeout(closePopUpTimeout);
		});
		
		var closePopUpTimeout;
		/* if (fadeout) {
			closePopUpTimeout = setTimeout(function() {
				$thisPopUp.find(".close").click();
			},2500);
		} */
	//});
	
	//return this;
}

$("a[href=#closePopup]").live("click",function() {
	$(".popup").fadeOut(function() { $(".browserDimmer").fadeOut(); });
	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() {
		
		if (data) { 
			$thisPopUp.html("<img src='images/close.jpg' alt='close' class='close confirmCancel' />"+data+"<p style='text-align:center'><a class='confirmOK button buttonSM' href='#confirmOK'>OK</a> <a class='confirmCancel button buttonSM' href='#confirmCancel'>Cancel</a></p>");
		} else {
			$thisPopUp.prepend("<img src='images/close.jpg' alt='close' class='close confirmCancel' />").append("<a class='confirmOK' href='#confirmOK'>OK</a> <a class='confirmCancel' href='#confirmCancel'>Cancel</a>");	
		}
		
		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,.browserDimmerWhite").fadeOut(function() {
					
				});
				callback.call(this, data);
			});
			return false;
		});
		
		$thisPopUp.find(".confirmCancel").click(function() {
			$thisPopUp.fadeOut(function() {
				$(".browserDimmer,.browserDimmerWhite").fadeOut();
			});
			return false;
		});
		
		var returnVal;
		var closePopUpTimeout;
		/* if (fadeout) {
			closePopUpTimeout = setTimeout(function() {
				$thisPopUp.find(".close").click();
			},2500);
		} */
	//});
	/*
	return returnVal; */
}

//----------------------------------/ 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!");
			$(".popup").popUp("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,[data-smartform=required]").each(function() {
			// choose where to put the asterisk
			if (path_to_asterisk) {
				$(this).path_to_asterisk.append("<span style='color:#C33; font-size:16px; vertical-algin:bottom;'> *</span>");
			} else {
				$(this).after("<span style='color:#C33; font-size:16px; vertical-algin:bottom;'> *</span>");	
			}
		});
		
		// prevent submit and show erro
		$thisForm.submit(function() {
			var returnVal = true;
			$(this).find(".required,[data-smartform=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(); });
	});
}

//----------------------------------/ Image Zoom - custom Lagos /-----------------------------------------------//

$.fn.imageZoom = function() {
	
	this.each(function() {
		var $this = $(this);
		var $imageZoom = $this.find(".imageZoom");
		
		//---- initial setup
		var imageZoomWidth = $imageZoom.width();
		var imageZoomHeight = $imageZoom.height();
		
		$imageZoom.css({ "left":"50%","top":"50%","marginLeft":"-"+imageZoomWidth*.5+"px","marginTop":"-"+imageZoomHeight*.5+"px" });
		//---- rollover
		$this.hoverIntent(function() {
			$imageZoom.fadeIn(250);
			$imageZoom.prev("a").fadeOut(250);
		},function() {
			$imageZoom.fadeOut(function() {
				$imageZoom.css({ "left":"50%","top":"50%","marginLeft":"-"+imageZoomWidth*.5+"px","marginTop":"-"+imageZoomHeight*.5+"px" }); //---- reset to center on rollout
			});
			$imageZoom.prev("a").fadeIn();
		});
		
		//---- mousemove
		$this.bind("mousemove","mouseover",function(e) {
			var mainImagePos = $this.offset(); // .mainImage position
			var mouseX = e.pageX; // x mouse position
			var mouseY = e.pageY; // y mouse position
			var mainImageWidth = $this.width(); // .mainImage width
			var mainImageHeight = $this.height(); // .mainImage height
			
			var paddingX = imageZoomWidth-mainImageWidth; // ignore the imageZoom that's hidden
			var paddingY = imageZoomHeight-mainImageHeight;
			
			var percentageX = imageZoomWidth/mainImageWidth;
			var percentageY = imageZoomHeight/mainImageHeight;
			
			var moveX = mainImagePos.left-mouseX+imageZoomWidth*.5-paddingX*.5; // mouse position relative to center of .productMainImage
			var moveY = mainImagePos.top-mouseY+imageZoomHeight*.5-paddingY*.5;
			
			var marginLeft = -imageZoomWidth*.5+moveX*percentageX; // new margin left based on zoom image size and mouse position
			var marginTop = -imageZoomHeight*.5+moveY*percentageY;
			
			$imageZoom.animate({ "marginLeft":marginLeft+"px","marginTop":marginTop+"px" },{ duration:0 });
		});
		
	});
		
	return this;
}

//----------------------------------/ Info Popup - custom Lagos /-----------------------------------------------//

$.fn.infoPopup = function(popupElement) {
	
	var $popupElement = popupElement;
	$popupElement.hide();
	
	this.each(function() {
		
		var $this = $(this);
		$this.click(function() { return false; });
		
		$this.hoverIntent(function() {
			$popupElement.fadeIn();
		},function() {
			$popupElement.fadeOut();
		});
		
	});
		
	return this;
}

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