// NorthernLightGems.com Global Javascript Functions

// Hide the bottom gradient if the screen is small enough
function hideBottomGradient() {
	windowHeight = $(window).height();
	bodyHeight = $("body").height();
	gradientHeight = 16;
	
	if ((bodyHeight - gradientHeight + 1) > windowHeight) {
		$("div.MainContainerEnder").css("display", "none");
	}
}

// Home container toggle (splash page)
function homeToggle(speed, domEvent) {
	if (domEvent != null || domEvent != undefined) {
		// Prevent default action
		domEvent.preventDefault();
	}
	
	// Don't animate if they're already being animated
	if ($("div.InnerHomeContainer").is(":animated") != true) {
		$("div.InnerHomeContainer:visible").slideUp(speed);
		$("div.InnerHomeContainer:hidden").slideDown(speed);
	}
}

// Fix the address iframes
function delayOverlayIframe(caller) {
	// If not already called
	if (caller.is("[rev!=alreadyCalled]")) {
		// Get name of iframe
		iframeId = caller.attr("rel");
		iframe = $("div." + iframeId + " iframe");
		iframeSrcHelper = $("div." + iframeId + " a.iframeSrc");
		
		// If the iframe source helper exists
		if (iframeSrcHelper.length > 0) {
			// Get iframe src
			src = iframeSrcHelper.attr("href");
			
			// If there's any more data in the rev attribute, append it to the src
			if (iframeSrcHelper.is("[rev]")) {
				src = src + iframeSrcHelper.attr("rev");
			}
		}
		
		// If src already defined, it may have been called elsewhere, so don't reload
		if (iframe.attr("src") == undefined || iframe.attr("src") == "") {
			loadIframe(iframe, src);
		}
		caller.attr("rev", "alreadyCalled");
	}
}

// Load iframe function
function loadIframe(iframe, src) {
	// If no src provided, simply reload (set src variable as itself)
	if (src == null) {
		src = iframe.attr("src");
	}
	
	// Load iframe
	iframe.attr("src", src);
}

// Show inline errors function
function InlineError(action, error, divid) {
	// Set errorDiv
	errorDiv = $(".InlineError");
	
	// If custom div id is set
	if (divid != null) {
		errorDiv = $(".InlineError#" + divid);
	}
	
	if (action == "show") {
		// Update message
		errorDiv.html(error);
		
		// If success box is still shown, hide it
		if ($(".InlineSuccess").css("display") != "none" || $(".InlineSuccess").css("display") != "" || $(".InlineSuccess").css("display") != null || $(".InlineSuccess").css("display") == "block") {
			InlineSuccess("exit");
		}
		
		// If the box hasn't spawned yet, slide it down, otherwise fade the new info
		if (errorDiv.css("display") == "none" || errorDiv.css("display") == "" || errorDiv.css("display") == null) {
			// Slide down with JQuery
			errorDiv.slideDown("slow");
		}
		else {
			errorDiv.css("display", "none");
			// Fade in with JQuery
			errorDiv.fadeIn("slow");
		}
	}
	else if (action == "hide") {
		// Fade out with JQuery
		errorDiv.slideUp("slow");
	}
	else if (action == "exit") {
		// Exit
		errorDiv.stop(false, true);
		errorDiv.css("display", "none");
	}
}

// Show inline errors function
function InlineSuccess(action, message, divid) {
	// Set errorDiv
	successDiv = $(".InlineSuccess");
	
	// If custom div id is set
	if (divid != null) {
		errorDiv = $(".InlineError#" + divid);
	}
	
	if (action == "show") {
		// Update message
		successDiv.html(message);
		
		// If error box is still shown, hide it
		if ($(".InlineError").css("display") != "none" || $(".InlineError").css("display") != "" || $(".InlineError").css("display") != null || $(".InlineError").css("display") == "block") {
			InlineError("exit");
		}
		
		// If the box hasn't spawned yet, slide it down, otherwise fade the new info
		if (successDiv.css("display") == "none" || successDiv.css("display") == "" || successDiv.css("display") == null) {
			// Slide down with JQuery
			successDiv.slideDown("slow");
		}
		else {
			successDiv.css("display", "none");
			// Fade in with JQuery
			successDiv.fadeIn("slow");
		}
	}
	else if (action == "hide") {
		// Fade out with JQuery
		successDiv.slideUp("slow");
	}
	else if (action == "exit") {
		// Exit
		successDiv.stop(false, true);
		successDiv.css("display", "none");
	}
}

// Toggle form submit button function
function ToggleFormSubmitButton(formid, action) {
	if (action == "enable") {
		$("form#" + formid + " input[type=submit]").attr("disabled", false);
	}
	else if (action == "disable") {
		$("form#" + formid + " input[type=submit]").attr("disabled", true);
	}
}

// Contact Form Submission
function ContactFormSubmit() {
	// Declare variables
	var error = "";
	var success = "";
	
	// Make sure that the email address is in a valid format
	var regexp = /^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
	if ($("#contact-email").val().match(regexp) == null) {
		error = "Please enter a valid email address.";
	}
	
	// Check if all fields have been completed
	for (i = 0; i < $(document.ContactForm.elements).length; i++) {
		if ($(document.ContactForm.elements[i]).val() == "" && $(document.ContactForm.elements[i]).attr("name") != "phone") {
			error = "Please fill in all required fields.";
		}
	}
	
	if (error != "") {
		InlineError("show", error, "ContactError");
		
		// Don't submit
		return false;
	}
	else {
		InlineError("hide");
		ToggleFormSubmitButton("ContactForm", "disable");
		
		$.post("ewc_php_includes/mail.php?do=send&ajax", {name:$("#contact-name").val(), email:$("#contact-email").val(), phone:$("#contact-phone").val(), message:$("#contact-message").val()}, function(response){
			if (response == "Success") {
				success = "Success";
			}
			else if (response == "" || response == null) {
				error = "There was an error processing your request. Please try again later.";
			}
			else {
				error = response;
			}
			
			if (error != "") {
				InlineError("show", error, "ContactError");
				ToggleFormSubmitButton("ContactForm", "enable");
			}
			else if (success == "Success") {
				InlineSuccess("show", "Your message has been successfully sent.<br />Thank you!", "ContactSuccess");
				ToggleFormSubmitButton("ContactForm", "enable");
				
				// Clear form values, except for the submit button
				$(document.ContactForm.elements + ":not([type=submit])").val("")
			}
			else {
				InlineError("hide", null, "ContactError");
			}
		});
		
		// Don't submit the form. Let the javascript handle it.
		return false;
	}
}

// CJR Contact Form Submission
function CJRContactFormSubmit() {
	// Declare variables
	var error = "";
	var success = "";
	
	// Make sure that the email address is in a valid format
	var regexp = /^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
	if ($("#cjrcontact-email").val().match(regexp) == null) {
		error = "Please enter a valid email address.";
	}
	
	// Check if all fields have been completed
	for (i = 0; i < $(document.CJRContactForm.elements).length; i++) {
		if ($(document.CJRContactForm.elements[i]).val() == "") {
			error = "Please fill in all required fields.";
		}
	}
	
	if (error != "") {
		InlineError("show", error, "CJRContactError");
		
		// Don't submit
		return false;
	}
	else {
		InlineError("hide");
		ToggleFormSubmitButton("CJRContactForm", "disable");
		
		$.post("ewc_php_includes/cjrmail.php?do=send&ajax", {companyname:$("#cjrcontact-companyname").val(), agent:$("#cjrcontact-agent").val(), email:$("#cjrcontact-email").val(), phone:$("#cjrcontact-phone").val(), message:$("#cjrcontact-message").val()}, function(response){
			if (response == "Success") {
				success = "Success";
			}
			else if (response == "" || response == null) {
				error = "There was an error processing your request. Please try again later.";
			}
			else {
				error = response;
			}
			
			if (error != "") {
				InlineError("show", error, "CJRContactError");
				ToggleFormSubmitButton("CJRContactForm", "enable");
			}
			else if (success == "Success") {
				InlineSuccess("show", "Your message has been successfully sent.<br />Thank you!", "CJRContactSuccess");
				ToggleFormSubmitButton("CJRContactForm", "enable");
				
				// Clear form values, except for the submit button
				$(document.CJRContactForm.elements + ":not([type=submit])").val("")
			}
			else {
				InlineError("hide", null, "CJRContactError");
			}
		});
		
		// Don't submit the form. Let the javascript handle it.
		return false;
	}
}

// Image preloader
(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery)

// Image swapping function
function switchImage(object, image) {
	$(object).attr("src", image);
}

// Background image swapping function
function switchBGImage(object, image) {
	$(object).css("backgroundImage", "url(" + image + ")");
}

// Back to top
function backToTop() {
	var x1 = x2 = x3 = 0;
	var y1 = y2 = y3 = 0;
	
	if (document.documentElement) {
		x1 = document.documentElement.scrollLeft || 0;
		y1 = document.documentElement.scrollTop || 0;
	}
	if (document.body) {
		x2 = document.body.scrollLeft || 0;
		y2 = document.body.scrollTop || 0;
	}
	
	x3 = window.scrollX || 0;
	y3 = window.scrollY || 0;
	
	var x = Math.max(x1, Math.max(x2, x3));
	var y = Math.max(y1, Math.max(y2, y3));
	
	window.scrollTo(Math.floor(x / 2), Math.floor(y / 2));
	
	if (x > 0 || y > 0) {
		window.setTimeout("backToTop()", 25);
	}
}

// NorthernLightGems.com Global Action Handlers

$(document).ready(function(){
	// Hide the bottom gradient
	hideBottomGradient();
	
	// Navigation menu (superfish plugin)
	$("ul.MainNav").superfish({
		delay:       600,
		animation:   {height:'show'},
		speed:       'fast',
		autoArrows:  false,
		dropShadows: true
	});
	
	// Preload images
	$.preLoadImages("imgs/sitewidegraphics/NLGlogo_hover.png");
	
	// Only run these functions if transparent PNG's are supported
	if (typeof unitPNGFix != "function") {
		// jQuery Tools tooltips
		$("a.HeaderAddress").tooltip({
			tip: '#tooltip',
			position: 'bottom center',
			offset: [5, 0],
			effect: 'fade',
			opacity: 1,
			delay: 0,
			events: { 
				tooltip: 'mouseout'
			}
		});
		
		// Logo hover effects
		$("a.NLGLogo img").mouseover(function() { /* Function to execute: */ switchImage($(this), 'imgs/sitewidegraphics/NLGlogo_hover.png'); /* End of function */ });
		$("a.NLGLogo img").mouseout(function() { /* Function to execute: */ switchImage($(this), 'imgs/sitewidegraphics/NLGlogo.png'); /* End of function */ });
	}
	
	// Home container toggle
	$("a#HomeContainerToggle").click(function(event) { /* Function to execute: */ homeToggle("slow", event); /* End of function */ });
	
	// Address overlay
	$("a.HeaderAddress[rel]").overlay({
		onLoad: function() {
			triggerObj = this.getTrigger();
			delayOverlayIframe(triggerObj);
		}
	});
	
	// Address overlay
	$("a.StoreAddress[rel]").overlay({
		onLoad: function() {
			triggerObj = this.getTrigger();
			delayOverlayIframe(triggerObj);
		}
	});
	
	// Constant Contact overlay
	$("a.EmailButton[rel]").overlay({
		onLoad: function() {
			triggerObj = this.getTrigger();
			delayOverlayIframe(triggerObj);
		}
	});
	
	// Simon G Videos overlay
	$("a.videoPopUp[rel]").overlay();
	
	$("form#ContactForm").submit(function() { /* Function to execute: */ return ContactFormSubmit(); /* End of function */ });
	$("form#CJRContactForm").submit(function() { /* Function to execute: */ return CJRContactFormSubmit(); /* End of function */ });
	
	// Delay iframe load until called (now handled as a callback function)
	//$("a.HeaderAddress[rel]").click(function() { /* Function to execute: */ delayOverlayIframe($(this)); /* End of function */ });
	
});