﻿// OPEN A PAGE IN A NEW WINDOW
// Create the new window
function openInNewWindow(e) {
	var event;
	if (!e) event = window.event;
	else event = e;
	// Abort if a modifier key is pressed
	if (event.shiftKey || event.altKey || event.ctrlKey || event.metaKey) {
		return true;
	}
	else {
		var newWindow = window.open(this.getAttribute('href'), '', 'width=780, height=500, scrollbars=yes, resizable=yes, toolbar=yes, location=yes, directories=no, menubar=yes, copyhistory=no');
		if (newWindow) {
		    // For IE 8
			try {
		        if (newWindow.focus()) {
			        newWindow.focus();
			    }
		    }
		    catch(err) {		        
		        return false;		        
		    }	
		return false;
		}
	return true;
	}
}

// CALL THIS FUNCTION TO INITIATE FUNCTION THAT OPENS CERTAIN LINKS IN NEW WINDOWS
function getNewWindowLinks() {
	// Check that the browser is DOM compliant
	if (document.getElementById && document.createElement && document.appendChild) {			
		// Find all links
		var link;
		var links = document.getElementsByTagName('a');
		for (var i = 0; i < links.length; i++) {
			link = links[i];
			// Find all links with a class name of "non-html" - Use for PDF documents and the like
			if (/\bnon\-html\b/.test(link.className)) {				
				link.onclick = openInNewWindow;
			}
			// Find all links with a class name of "off-site" 
			else if (/\boff\-site\b/.test(link.className)) {				
				link.onclick = openInNewWindow;
			}			
		}	
	}
}

// ==============================================================
// PSEUDO-SELECT MENU version 3 - Greg Laycock, Fahlgren
// Emulate SELECT element so that search engines can follow links
// ==============================================================
// Initialize PSEUDO-SELECT elements (use on-load)
function initPseudoSelects() {
    // Check that the browser is DOM compliant
	if (document.getElementsByTagName) {
	    var theClass;
		var objDiv;
	    var aryDivs = document.getElementsByTagName('div');
	    for (var i = 0; i < aryDivs.length; i++) {
		    objDiv = aryDivs[i];
		    // Find all divs with a class name of "pseudo-select"
		    if (/\bpseudo\-select\b/.test(objDiv.className)) {
			   	theClass = objDiv.className;
				objDiv.className = theClass + '-active';
				objDiv.onclick = emulateSelectElement;
			}
	    }
    }
}
// Open and close PSEUDO-SELECT elements
function emulateSelectElement() {
	var on = 'pseudo-select-active on'
	var off = 'pseudo-select-active off'
	switch (this.className) {
		case on:	
			this.className = off;
			break;
		case off:
		default:			
			this.className = on;
			break;
	}
}
// ==============================================================
// ==============================================================

// LOOK FOR CLOAKED LINKS AND MAKE THEM CLICKABLE
// Hopefully this will help hide e-mail addresses from spam spiders
function createMailtoLinks() {
	// Check that the browser is DOM compliant
	if (document.getElementById && document.createElement && document.appendChild) {			
		var email; // E-mail address
		var mailto; // The mailto hyperlink
		var cloak; // The mailto span element
		var spans = document.getElementsByTagName('span'); // Array of span elements
		for (var i = 0; i < spans.length; i++) {
			cloak = spans[i];
			// Find all span elements with a class name of "cloak"
			if (/\bcloak\b/.test(cloak.className)) {				
				email = cloak.innerHTML;
				cloak.innerHTML = "";									
				mailto = document.createElement('a');															
				mailto.href = 'mailto:' + email;
				mailto.innerHTML = email;
				cloak.appendChild(mailto);			
			}
		}	
	}
}

// SET FOCUS ON PAGES WITH USER FORMS
// Look for inputs tags with the class name of "first"
function goToFirstInput() {		
	var objInput;		
	var aryInput = document.getElementsByTagName('input');
	for (var i = 0; i < aryInput.length; i++) {
		objInput = aryInput[i];
		// Find all inputs with a class name of "first"
		if (/\bfirst\b/.test(objInput.className)) {				
			objInput.focus();							
		}				
	}	
}

// ADD CLASSES
// Requires jQuery
function addClasses() {
	// Add classes to different types of links to control behavior
	$("a[href^=http://],a[href^=https://]").addClass("off-site");
	$("a[href$=pdf],a[href$=jpg],a[href$=gif],a[href$=png],a[href$=sflb]").addClass("non-html");
	$("a[href$=pdf],a[href*=PDFs]").addClass("pdf");
	// Build selector for current host check
	var currentDomainSelector = "a[href*=" + window.location.host + "]";
	// Exclude certain links from updated behavior
	$(currentDomainSelector).removeClass("off-site");
	$("a[rel~=lightbox]").removeClass("non-html");
}

// JAVASCRIPT CHECK
// Show elements that require JavaScript
function scriptCheck() {
	$(".req-js").addClass("have-js");
	$(".req-js").removeClass("req-js");	
}

// CUFON
function initCufon() {
	var theColor;
	var theImage;
	$.each($("h1, h2, h3, h4"), function() {
		theColor = $(this).css("color");
		if (theColor == "#fff" || theColor == "#ffffff") {
			theImage = "<img src='/product-catalog/images/icons/diamond-white.png' alt='Note' class='diamond' />";
		}
		else {
			theImage = "<img src='/product-catalog/images/icons/diamond-black.png' alt='Note' class='diamond' />";
		}
		theText = $(this).html();
		theText = theText.replace("♦",theImage);
		$(this).html(theText);
	});
	Cufon.replace('h1, h2, h3, h4');	
}

// LEGEND
// Position Legend
function initLegend() {
	// Figure out height of navigation (which is variable)
	var catalogNav = $("div#catalog_nav");
	var leftNavHeight = $(catalogNav).height();
	//var leftNavOffset = $(catalogNav).offset().top;
	var leftNavOffset = 100;
	var totalHeight = leftNavHeight + leftNavOffset;
	var totalHeightPx = totalHeight + "px";
	// Position legend just below left navigation
	$("div#legend").css("top", totalHeightPx);
	// Check to see if legend is outside of viewable area
	var contentHeight = $("div#content").height();	
	//var legendHeight = $("div#legend div.legend").height();	
	var contentBottom = $("div#content").height() + $(catalogNav).offset().top;
	var legendBottom = $("div#legend div.legend").height() + $("div#legend div.legend").offset().top;
	//var overflow = (legendHeight + totalHeight) - contentHeight;
	var overflow = legendBottom - contentBottom;
	// Increase height of content container element if necessary
	if (overflow >= 0) {	
		newContentHeightPx = (contentHeight + overflow + 200) + "px";
		$("div#content").css("height",newContentHeightPx);
	}
}
// Set Easing
$(function() {
	jQuery.easing.def = 'easeOutExpo';
	setTimeout(animateLegend, 3600);
});
// Animate Legend
function animateLegend() {	
	// Get width of legend
	var theTiming = 1000;
	var legendWidth = $("div#legend").width();
	var legendWidthPxNeg = "-" + legendWidth + "px";
	// Dock legend
	// Check for IE 6
	if ($("div#legend").css("clear") == "right") {
		// If IE 6, dock legend
		$("div#legend").css("left",legendWidthPxNeg);
	}
	// Set animation events
	$("div#legend a.open").click(function(){
		this.blur();
		$("div#legend").animate({
        	left: "0px"		
      	}, theTiming);		
		return false;
	});
	$("div#legend a.close").click(function(){
		this.blur();
		$("div#legend").animate({
        	left: legendWidthPxNeg		
      	}, theTiming);
		return false;
	});
}

// BOX-LIKE ORDERED LISTS ADJUSTED
function adjustBoxes() {
	// Remove numbers
	$("ol.boxes").css("list-style-type","none");
	var count = 1;
	var number;
	// Re-add numbers inside header so that alignment is correct
	$.each($("ol.boxes h3"), function() {		
		number = count + ". ";
		$(this).prepend(number);
		count = count + 1;		
	});	
}

// CATEGORY BREAKDOWN ADJUSTMENT
function adjustContent() {
	// Check to see if Breakdown table exists
	if ($("div#category-breakdown")) {
		// Get element heights for comparison
		var catalogNavHeight = $("div#catalog_nav").height();		
		var categoryOverviewHeight = $("div.category-overview").height();
		var categorySpecsHeight = $("div.category-specs").height();			
		// Check to see if nav floats on top of content - content too short
		var overflow = catalogNavHeight - (categoryOverviewHeight + categorySpecsHeight);
		if (overflow >= 0) {			
			// Include padding in calculation
			var categoryOverviewHeightPadding = parseInt($("div.category-overview").css("padding-top"));
			var categoryBreakdownPadding = parseInt($("div.category-breakdown").css("padding-top"));			
			// Increase height of Category Specs element
			var newCategorySpecsHeightPx = overflow + categorySpecsHeight - categoryOverviewHeightPadding - categoryBreakdownPadding + "px";
			$("div.category-specs").css("height",newCategorySpecsHeightPx);			
		}
	}	
}

// BOOKMARK THIS PAGE
// Buggy in Firefox, does not work in Opera - set to only display link in IE
function bookmarksite(title,url) {
	if (window.sidebar) { 
		window.sidebar.addPanel(title, url,""); 
	} else if( document.all ) {
		window.external.AddFavorite( url, title);
	} else if( window.opera && window.print ) {
	return true;
	}
}

// PAGE INDICATORS (NAVIGATION STATES)
function initIndicators() {
	// Get current URL
	var theURL = location.href;
	var theURLSplit = theURL.split("/");
	var thePath = "/" + theURLSplit[3];
	if (theURLSplit[4] != null) {
		thePath = thePath + "/" + theURLSplit[4];
	}
	if (theURLSplit[5] != null) {
		thePath = thePath + "/" + theURLSplit[5];
	}  
	var theHref;		
	$.each($("#catalog_nav a"), function() {		
		theHref = $(this).attr("href");			
		if (theHref == thePath) {
			$(this).addClass("selected");
			theLinkParents = $(this).parents("li");
			$(theLinkParents).addClass("selected");	
		}
	});
}

// CLOTHING GUIDE LINK
function initSizeGuideLink() {
	var theCategory = $("#product_detail").parent().attr("class");
	var theClass;
	if (theCategory != "clothing") {
		$("p#size-guide-link").addClass("hide");
	}
}

// OVERLAY - REDUNDANT NAVIGATION
function initOverlay() {
	var theTiming = 1000;
	var objOverlay = $("#product_overlay");
	// Get height of overlay	
	var theHeight = objOverlay.height();
	var thePosition = theHeight - (theHeight*3) + "px";	
	// Pre-position overlay
	objOverlay.css("top",thePosition);	
	$(".action-overlay").click(function() {
		// Make overlay visible
		objOverlay.addClass("visible");
		// Animate
		objOverlay.animate({
			top: "0px"
	    }, theTiming);			
		return false;
	});	
	$("#action_close_overlay").click(function() {
		objOverlay.removeClass("visible");
		objOverlay.css("top",thePosition);
		/* Firefox flickers badly
		objOverlay.animate({
			top: thePosition	
	    }, theTiming);
		*/
		
	});
}

// ACTIONS
// Bookmark
$("#action_bookmark").click(function() {
	 bookmarksite(document.title, window.location);
});
// Print
$("#action_print").click(function() {
	window.print();
});
// Email
$("#action_email").click(function() {
	$("div#invitation").addClass("visible");
	$("#yourname").focus();
});
$("#action_invitation_close").click(function() {
	$("div#invitation").removeClass("visible");
});

// ON-LOAD EVENTS 
// Requires jQuery
$(document).ready(function() {
	scriptCheck();
	addClasses();
	getNewWindowLinks();
	initCufon();	
	adjustBoxes();
	adjustContent();
	
	// Check to see if Legend is shown
	var theDisplay = $("div#legend").css("display");
	if (theDisplay != "none") {
		initLegend();
		animateLegend();
	}	
	
	//initOverlay();
	initIndicators();
	initSizeGuideLink();
});