﻿$(document).ready(function() {
	
	// Setup cufon
	Cufon.replace('h1', { fontFamily: 'NeoSansPro-Light' });
	Cufon.replace('#tagline-text-sub h2', { fontFamily: 'NeoSansPro-Light' });
	Cufon.replace('#preamble h2, #prod-preamble h2', { fontFamily: 'NeoSansPro-Light' });
	
	// All input fields assigned with the class 'default' will
	// get their default values hidden when clicked, and reset again
	// if the user leaves the field empty or hasnt changed anything
	// The searchfields needs an accompanying hidden input with the
	// same id but suffixed "-default" that contains the default value.
	$("input.default, textarea.default").each(function() {
		var defaultVal = $(this).next(".defaultvalue").val();
		if (!$(this).val())
			$(this).val(defaultVal);
		$(this).focus(function() {
			if ($(this).val() == defaultVal)
				$(this).val("");
		});
		$(this).blur(function() {
			if ($(this).val() == "")
				$(this).val(defaultVal);
		});
	});
	
	// Trigger the search function when clicking the search button
	$(".search-submit")
	.click(function() {
		submitsearch($(this));
		return false;
	});
	
	// Trigger the search function when using the enter key
	$(".search-input").keydown(function(e) {
		if (e.keyCode == 13) {
			var valobj = $(this).siblings($("a.search-submit"));
			submitsearch($(valobj));
			return false;
		}
	});
	
	// Validate forms
	$(".validate-form .validate").click(function() {
		if(validate($(this).parent())) {
			setStatus($(this).parent().parent(), true);
		}
		else {
			setStatus($(this).parent().parent(), false);
			return false;
		}
	});
	
	// Clear graphical error on required fields when correcting it
	$("input.required, textarea.required")
	.keydown(function() {
		clearError($(this));			
	});
	
	// Toggle on products
	$(".toggle a:not(.toggle .content a)").click(function() {
		$(this).next(".content").slideToggle();
		$(this).parent("li").toggleClass("expanded");
		return false;
	});
	
	// Hook up family product images with tooltips
	$("#family .tip-trigger").tooltip({
	   offset: [100, 0],
	   relative: true,
	   effect: 'slide'

	}).dynamic({ bottom: { direction: 'down', bounce: true } });
	
	// Hook up environment tooltips
	$("#environment .tip-trigger").tooltip({
	   offset: [10, -15],
	   relative: true,
	   effect: 'slide'

	}).dynamic({ bottom: { direction: 'down', bounce: true }
	}).click(function() { return false; });;
	
	// Hook up mega-drops inspiration images with tooltips
	$(".mega-header .tip-trigger").tooltip({
	   offset: [40, 2],
	   relative: true,
	   effect: 'slide'

	}).dynamic({ bottom: { direction: 'down', bounce: true } });
	
	// Use javascript isntead of :hover for IE6 for megadrops
	if($.browser.msie && $.browser.version=="6.0") {
		$("#mega-drop li:not(#mega-drop li li)")
		.mouseover(function() {
			$(this).addClass("hover");
		})
		.mouseout(function() {
			$(this).removeClass("hover");
		});
	}
	
	// Convert option value to url and set location
	$("#filter select").change(function() {
		if ($(this).val())
		document.location = $(this).val();
    });
	
	// Init slideshow before fancybox
    slideshow();

    $("a.iframe").fancybox({
        'width': 660,
        'height': 560,
        'autoScale': false,
        'transitionIn': 'none',
        'transitionOut': 'none',
        'type': 'iframe',
        'scrolling': 'no'

    });

	
	// Init fancybox for iframes
	$("a.fancy-iframe").fancybox({
		'type'				: 'iframe',
		'width'				: 770,
		'height'			: 520
	});
	
	// Init fancybox for swf's
	$("a.fancy-swf").fancybox({
		'padding'			: 0,
		'autoScale'			: false,
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'swf'				: {
			'wmode'					: 'opaque',
			'allowfullscreen'		: 'true'
		}
	});
	
	// Init fancybox for inline content
	$("a.fancy-inline").fancybox({
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		/* Increase width of box so that the horizontal scrollbar won't show */
		'onComplete'		: function() { $("#fancybox-wrap").width(540); $("#fancybox-inner").width(520); }
	});
	
	// Init fancybox for images
    $("a.fancy").fancybox({
        'type'              : 'image',
		'transitionIn'		: 'fade',
		'transitionOut'		: 'none',
		'titlePosition' 	: 'over',
		'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) {
			if(title) {
				// Split the title into two strings, one for description and one for download url
				var titleText 		= title.substring(0,title.indexOf("|"));
				var highresImage 	= title.substring(title.indexOf("|")+1);
				
				if(title.indexOf("|") <= 0) {
					titleText = title;
					highresImage = "";
				}
				
				return '<span id="fancybox-title-over"><span class="fancybox-descr">' + imageText + ' ' + (currentIndex + 1) + 
				' / ' + currentArray.length + (titleText.length ? ' &nbsp; ' + titleText : '') + '</span>' + (highresImage.length ? 
				' <span class="fancybox-download"><a href="' + highresImage + '">' + downloadText + '</a></span> ' : '') + '</span>';
			}
			else {
				return '<span id="fancybox-title-over"><span class="fancybox-descr">' + imageText + ' ' + (currentIndex + 1) + 
				' / ' + currentArray.length + '</span></span>';
			}
		}
	});
	
});

//
// Search
//
function submitsearch(obj) {
	var url = $(obj).attr("href");
	url += url.indexOf("?") > -1 ? "&" : "?";
	url += "query=" + encodeURIComponent($(obj).siblings("input").val());
	document.location = url;
}

// 
// Clear error on required fields
//
function clearError(obj) {
	if (obj.val())
		obj.removeClass("has-error");
}

//
// Show and hide the status text for a form
//
function setStatus(obj, val) {
	obj.find(".status p").hide();
	if(val) {
		obj.find(".status .success").show();
	}
	else {
		obj.find(".status .error").show();
	}
}

//
// Validates all input and textarea children of the passed object.
// Adds a yellow background on required input/textareas that are not correctly filled.
//
function validate(obj) {
	
	var validated = true;
	
	// Dont send anything if one of the fields are equal to the default vaule
	obj.find("input, textarea").each(function() {
		if($(this).val() == $(this).next(".defaultvalue").val()) {
			validated = false;
		}
	});
	
	obj.find(".required").each(function() {
		if($(this).val() == "" || $(this).val() == $(this).next(".defaultvalue").val()) {
			$(this).addClass("has-error");	
			validated = false;
		}
	});

	if (!validated) {
		return false;
	}
	else {
		return true;
	}
}

//
// Animate entrances
//
$(function() {
	
	var complete = true;
	
	if($("#entrances").length > 0) {
		var animatespeed 	= 1200;
		var intervalspeed 	= 400;
		var count 			= 0;
		var numImages 		= $("#entrances li").length;
		complete			= false;
		
		// hide elements using js
		$("#entrances li .info").hide();
		$("#entrances li .img-container img").css('bottom', -220);
		
		function slideIn() {

			var item 		= $("#entrances li").eq(count);
			var img 		= item.find("img");
			var info 		= item.find(".info");
			
			count++;
			
			img.animate({ 
				bottom: [-40, 'easeOutBack']
			}, animatespeed, false, function() {
				info.slideDown("fast", function() {
					if(count >= numImages) complete = true;
				});
			});

			clearInterval(interval);
			interval = setInterval(slideIn, intervalspeed - (count * 100));
			
			if(count >= numImages) {
				clearInterval(interval);
			}
		}
		
		interval = setInterval(slideIn, intervalspeed);
	}
	
	$(".hover-list li")
	.mouseover(function() {
		if(complete) {
			var infoContent = $(this).find(".info-content");
			var targetHeight = infoContent.children("a").outerHeight();
			
			if(!infoContent.hasClass("hover")) {
				infoContent.addClass("hover");
				infoContent.animate({ 
					height: [targetHeight, 'easeInOutBack']
				}, 350, true);
			}
		}
	})
	.mouseleave(function() {
		if(complete) {
			var infoContent = $(this).find(".info-content");
			
			infoContent.animate({ 
				height: [22, 'easeOutQuad']
			}, 200, true, function() {
				infoContent.removeClass("hover");
			});
		}
	});
});

//
// Article slideshow
//
function slideshow() {

	var elms = [];
	var instantiated = false;
	var index = 0;

	var toggleTo = function(elm) {
		if ($(".slideshow").length == 0) {
			var wrapper = $(".slideshow-container ul").parent();
			wrapper.html("<div class=\"slideshow\"><div class='image-holder'><img src=\"" + elms[elm].src + "\"/></div><p class=\"image-description\">" + elms[elm].caption + "</p></div>");
			
			if(elms[elm].highres.length > 0) {
				$(".slideshow .image-holder").append("<a href='" + elms[elm].highres + "' class='fancy magnify' rel=\"slideshowimgsauto\" title='" + elms[elm].caption + "'>"+ zoomTitle + "</a>");
				$(".magnify").show();
			}
			else { $(".magnify").hide(); }
			
			$(".slideshow img").load( function() {
				if (instantiated) {
					$(".slideshow").fadeIn("slow");
					wrapper.animate({
						"height": $(".slideshow").outerHeight()
					}, "slow");
				} else {
					wrapper.css("height", $(".slideshow").outerHeight());
					instantiated = true;
				}
			});
			
		} else {
			$(".slideshow").stop(true, true);
			$(".slideshow").fadeOut("normal", function() {
				$(".slideshow img").attr("src", elms[elm].src);
				$(".slideshow p").html(elms[elm].caption);
				if(elms[elm].highres.length > 0) {
					$(".slideshow a.magnify").attr({
						href: elms[elm].highres,
						title: elms[elm].caption
					});
					$(".magnify").show();
				}
				else { $(".magnify").hide(); }	
			});
			
		}
		$(".slideshow-nav a").removeClass("current");
		$(".slide-" + elm).addClass("current");

		// Avoid showing the currently selected image twice in the slideshow
		$(".slideshow-nav li a").attr("rel", "slideshowimgsauto");
		$(".slideshow-nav li a:eq(" + elm + ")").attr("rel", "");
	};
			
	$(".slideshow-container li a").each( function() {
		elm = $(this);
		elms.push( {
			"src": elm.attr("href"),
			"caption": elm.text(),
			"thumb": $(elm.children("img")).attr("src"),
			"highres": elm.attr("title")
		} );
	});
	
	if (elms.length > 0) {
		var rows = 3;
		var firstInRow = "";
		
		$(".slideshow-container").addClass("loader");
		$("#related").prepend("<div class=\"slideshow-nav\"><ul></ul></div>");
		for (var i = 0, l = elms.length; i < l; i++) {
			if(i % rows == 0) firstInRow = "first";
			$(".slideshow-nav ul").append("<li class=\""+ firstInRow + "\"><a href=\"" + elms[i].src + "\" class=\"slide-" + i + "\" rel=\"slideshowimgsauto\" title=\"" + elms[i].caption + "\"><img src=\"" + elms[i].thumb + "\"/><span></span></a></li>");
			firstInRow = "";
		}
		
		toggleTo(0);
		$(".slideshow-nav li a").live("click", function() {
			index = $(this).parent("li").index();
			toggleTo(index);
			return false;
		});
	}
}
