/* OPEN LINKS IN NEW WINDOW */
function externalLinks() {
	if (!document.getElementsByTagName) { return; }
	var anchors = document.getElementsByTagName("a");
	for (var i=0; i<anchors .length; i++) {
		var anchor = anchors[i];
		if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external") {
			anchor.target = "_blank";
		}
	}
}
window.onload = externalLinks;



/* HIGHTLIGHT ROWS ON TABLES */



var mrMac = (navigator.userAgent.indexOf('Mac') != -1);
if (!mrMac) {
	sfHover = function() {

		if (document.getElementById("highlightable")) {

		var sfEls = document.getElementById("highlightable").getElementsByTagName("TR");		
	
			for (var i=0; i<sfEls.length; i++) {
				sfEls[i].onmouseover=function() {
					this.className+=" over";
				};
				
				sfEls[i].onmouseout=function() {
					this.className=this.className.replace(new RegExp(" over\\b"), "");
				};
			}
		}
	};
	if (window.attachEvent) { window.attachEvent("onload", sfHover); }
}	


function checkEnter(e, fn){ //e is event object passed from function invocation
	var characterCode; // literal character code will be stored in this variable

	if(e && e.which){ //if which property of event object is supported (NN4)
		e = e;
		characterCode = e.which; //character code is contained in NN4's which property
	} else {
		e = event;
		characterCode = e.keyCode; //character code is contained in IE's keyCode property
	}

	if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
		fn();
		return false;
	} else {
		return true;
	}
}

/**** Enewsletter functions ***/
// new ajax mechanism for newsletter subscriptions
function newsletterSubscribe() {
		var textbox = $("div.tool-enews input");
		if (textbox.val() !== '' && textbox.val() != 'email') {
			$("div.tool-enews span").removeClass('btn-go').addClass('btn-go-load');
			$("div.tool-enews input").removeClass('errorInput');
			$("div.tool-enews p.enews-feedback").text('Processing...');
			$.ajax({
				 type: 'POST',
				 url: '/includes/subscribe.asmx/NewsletterSubscribe',
				 data: "{'emailAddress':'" + $(textbox).val() + "'}",
				 contentType: 'application/json; charset=utf-8',
				 dataType: 'json',
				 success: function(response) {
					$("div.tool-enews span").removeClass('btn-go-load').addClass('btn-go');
					if (response == 'SUCCESS') {
						$('#pnlEnewsMessage').show();
						$('div.tool-enews p.enews-inputs').hide();
						$("div.tool-enews p.enews-feedback").text('');
					} else {
						$('#pnlEnewsMessage').hide();
						$('div.tool-enews p.enews-inputs').show();
						$("div.tool-enews input").addClass('errorInput');
						$("div.tool-enews p.enews-feedback").text('Invalid email. Please try again.');
					}
				 },
				 error: function(msg) {
					//alert('AJAX Error: ' + msg.responseText);
					$("div.tool-enews span").removeClass('btn-go-load').addClass('btn-go');
					$("div.tool-enews p.enews-feedback").text('Unknown error.');
				 }
			});
		} else {
			$("div.tool-enews span").removeClass('btn-go-load').addClass('btn-go');
			$("div.tool-enews input").addClass('errorInput');
			$("div.tool-enews p.enews-feedback").text('Enter your email address.');
		}
}

// blur (losing focus) restores 'email' prompt text if textbox is empty
$(document).ready(function() {
	$("div.tool-enews input").focus(function() {
		if ($("div.tool-enews input").val() === 'email') {
			$("div.tool-enews input").val('');
		}
	});
	$("div.tool-enews input").blur(function() {
		if ($("div.tool-enews input").val() === '') {
			$("div.tool-enews input").val('email');
			$("div.tool-enews input").removeClass('errorInput');
		}
	});
	$("div.tool-enews span a").click(newsletterSubscribe);
});
	
/* Search & Enews Subscription - pressing Enter submits form */
$(document).ready(function() {
		$("#site-search input.search-words").keypress(function(eventObject) { 
			checkEnter(eventObject, function() {
				var cmd = $('#site-search span.btn-search a').attr('href').replace('javascript:', '');
				if (cmd.match(/^__doPostBack\('(.*)\$?([a-zA-Z1-9])+',''\)$/)) {
				  eval($('#site-search span.btn-search a').attr('href').replace('javascript:', ''));
				}
			}); 
		});
		$("div.tool-enews input").keypress(function(eventObject) { 
			checkEnter(eventObject, function() {
				newsletterSubscribe();
			}); 
		});
});

/* REFINE SEARCH SPECIAL DROPDOWN */
function selectReplacement(obj) {
  // append a class to the select
  obj.className += ' replaced';
  // create list for styling
  var ul = document.createElement('ul');
  ul.className = 'selectReplacement';
  var opts = obj.options;
  for (var i=0; i<opts.length; i++) {
	var selectedOpt;
	if (opts[i].selected) {
	  selectedOpt = i;
	  break;
	} else {
	  selectedOpt = 0;
	}
  }
  for (var j=0; j<opts.length; j++) {
	var li = document.createElement('li');
	var txt = document.createTextNode(opts[j].text);
	li.appendChild(txt);
	li.selIndex = opts[j].index;
	li.selectID = obj.id;
	li.onclick = function() {
	  selectMe(this);
	};
	if (j == selectedOpt) {
	  //li.className = 'selected';
	  $(li).addClass("selected");
	  li.onclick = function() {
		this.parentNode.className += ' selectOpen';
		this.onclick = function() {
		  selectMe(this);
		};
	  }
	}
	ul.appendChild(li);
  }
  // add the input and the ul
  obj.parentNode.appendChild(ul);
}
function setVal(objID, selIndex) {
  var obj = document.getElementById(objID);
  obj.selectedIndex = selIndex;
  $(".refine-search select").change();
}
function selectMe(obj) {
  var lis = obj.parentNode.getElementsByTagName('li');
  for (var i=0; i<lis.length; i++) {
	if (lis[i] != obj) { // not the selected list item
	  lis[i].className='';
	  lis[i].onclick = function() {
		selectMe(this);
	  }
   } else {
	  setVal(obj.selectID, obj.selIndex);
	  
	  obj.className='selected';
	  obj.parentNode.className = 
		obj.parentNode.className.replace(new RegExp(" selectOpen\\b"), '');
	  obj.onclick = function() {
		obj.parentNode.className += ' selectOpen';
		this.onclick = function() {
		  selectMe(this);
		}
	  }
	}
  }
}

function setForm() {
  var s = $(".refine-search select");
  for (var i=0; i<s.length; i++) {
	selectReplacement(s[i]);
  }
}
function closeSel(obj) {
  // close the ul
}

$(document).ready(function(){
	setForm();	
	
	$(".selectReplacement li").not(":first").hover(function(){
		$(this).addClass("hover");
	},function(){
		$(this).removeClass("hover");		
	});

	$(".selectReplacement li:first-child").addClass("first");
});


// Hide Issuu catalogue on thickbox
$(document).ready(function(){

	$(".link-email a").click(function(){
		$("#issuu-viewer").css("visibility","hidden");
	});

});

 
// Display Issuu catalogue.
$(document).ready(function(){
	if($("#issuu-wrapper").length) {
		$("#issuu-wrapper #issuu-viewer").slideDown("slow");
	}
});


// View Promo page based on drop down
$(document).ready(function(){
	// show the drop down div
	$("#jsDropDown").show();
	$("#viewpromo").click(function(){
		if ($("#state_dropdown").val() !== '') {
			document.location = "promotion-" + $("#state_dropdown").val() + ".aspx";
			return false;
		}
	});
	
	// also remove the js=false attribute from the store listings since we have javascript
	$(".par-stores li a, #store-list li a").each(function() {
		var curHref = $(this).attr("href");
		$(this).attr("href", curHref.replace(/&js=false/gi, ""));
	});
});

// Fancybox
$(document).ready(function() {

			$("a.modal").fancybox({
				'overlayOpacity'	:	0.7,
				'overlayColor'		:	'#000',
				'frameWidth'		:	850,
				'frameHeight'		:	565,
				'hideOnContentClick'	: false
			});
			
	});
	
	
	
	
// Product Zoom

$(document).ready(function(){

	// For legacy products only. This can eventually be removed.
	$("#product-primary.legacy #large-product").jqzoom({
		zoomWidth: 285,
		zoomHeight: 375,
		xOffset: 80,
		yOffset: 0,
		position: "right",
		title: false,
		showEffect: "fadein",
		hideEffect: "fadeout",
		fadeoutSpeed: "fast"
	})
	
	
	var options = {
		zoomWidth: 285,
		zoomHeight: 375,
		xOffset: 22,
		yOffset: 0,
		position: "right",
		title: false,
		showEffect: "fadein",
		hideEffect: "fadeout",
		fadeoutSpeed: "fast"
	};
	
	$("#product-primary:not(.legacy) #large-product").jqzoom(options);
	
});


// Product Thumbnail swaps
$(document).ready(function(){

	// Clicking the first thumbnail should hide the additional image and the video - and show the zoomable image.
	$("#product-thumbs a:first-child").click(function(){
		$("#product-image").show();
		$("#additional-image, #video-holder").hide();
		return false;
	});

	// Clicking any other thumbnail should hide the zoomable image and the video - and show the larger image.
	$("#product-thumbs a:not(:first-child)").click(function(){
		var src = $(this).attr("href");
		$("#product-image, #video-holder").hide();
		if ( $("#additional-image").size() == 0 ) {
			$("#product-image").after("<div id='additional-image'><img src='' alt='' height='375' /></div>");
		}
		$("#additional-image img").attr("src",src).parent().show();
		
		return false;
	});

});

function showVideo(id){
	// If the video hasnt already been shown (doesn't exist yet, size()==0), create it.
	if ($("#video-holder").size() == 0){
		// Create embed
		var embed = '<object width="578" height="375"><param name="movie" value="http://www.youtube-nocookie.com/v/'+id+'?fs=1&amp;hl=en_US&amp;rel=0&amp;autoplay=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube-nocookie.com/v/'+id+'?fs=1&amp;hl=en_US&amp;rel=0&amp;autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="578" height="375"></embed></object>'
		// Show video
		$("#product-primary").prepend('<div id="video-holder"><div id="video-player">'+embed+'</div></div>');
	}
	else {
		// If it is already created, just show it.
		$("#video-holder").show();
	}
	// Either way, hide the zoomable image and additional image.
	$("#product-image, #additional-image").hide();
}


// Tabbed content

$(document).ready(function(){

	var $tabbedContent = $(".tabbed-content"),
	    $tabs = $(".tabs a"),
	    target;
	    
	$(".tab-panel:not(:first-child)").hide();

	$($tabs, $tabbedContent).click(function(){
		$tabs.removeClass("active")
		$(this).addClass("active");
		target = "#tab-" + $(this).attr("href").substring(1);
		$(".tab-panel", $tabbedContent).hide();
		$(target).show();
	
	});

});


// Split Lists in half
$(document).ready(function(){
	$('.splitlist').each(function() {
		if( $(this).is("ol") ) { var ordered = true; }
		var colsize = Math.round($(this).find("li").size() / 2);
		$(this).find("li").each(function(i) {
			if (i>=colsize) {
				$(this).addClass('right_col');
			}
		});
		if(ordered) {
			$(this).find('.right_col').insertAfter(this).wrapAll("<ol class='splitlist odd' start='" + (colsize+1) + "'></ol>").removeClass("right_col");
		} else {
			$(this).find('.right_col').insertAfter(this).wrapAll("<ul class='splitlist odd'></ul>").removeClass("right_col");
		}
	});
});

// Add to cart popup resizing
function addToCartPopupResize() {
	
	$("#TB_window").css({
		'marginTop': '-280px',
		'marginLeft': '-312px',
		'width':'624px',
	}).find("iframe").css({
		'height': '500px',
		'width': '624px'
	});

}



