//DOM Ready
$(function(){
	miniAjaxLoad= new Image(); 
  miniAjaxLoad.src="/images/common/ajax-loader-mini.gif"; 
	
	//add class .inputfield to all text and pw inputs ie6 browsers
	if (jQuery.browser.msie) {
		if (parseInt(jQuery.browser.version) < 7) {
			$('input:text').addClass('inputfield');
			$('input:password').addClass('inputfield');
			$("#hamnavigation ul li").mouseover(
				function(){
					menuHover(this,1);
				});
			$("#hamnavigation ul li").mouseout(
				function(){
					menuHover(this,0);
				});
			}
		} 
		
		
		

	//mouseover images on all .swap classes
	$(".swap").mouseover(
		function(){
			swapIn(this);
		});
	$(".swap").mouseout(
		function(){
			swapOut(this);
		});
	
	
	//Clear the Search Terms on Focus
	$("#searchfield").focus(function(){
		if($("#searchfield").val() == 'Keyword, SKU or item #') { 
			$("#searchfield").val('');
		}
	});
	
	$("#homesignupfield").focus(function(){
		if($("#homesignupfield").val() == 'Enter your Email') { 
			$("#homesignupfield").val('');
		}
	});
	
	
	
	//Load all the images that need to be loaded.
	lightBoxLoader= new Image(); 
  lightBoxLoader.src="/images/lightbox/lightbox-load.gif";
	lightboxclose= new Image(); 
	lightboxclose.src="/images/lightbox/close.png"; 
	lightboxinfo= new Image(); 
	lightboxinfo.src="/images/lightbox/info.png"; 
	lightboxprev= new Image(); 
	lightboxprev.src="/images/lightbox/previous.png"; 
	lightboxnext= new Image(); 
	lightboxnext.src="/images/lightbox/next.png"; 
	
	//attach lightbox to the zoom class
	$('.zoom').click(function(){
		lightBoxZoom(this);
		return false;
	});
	
	$('.zoomdetail').click(function(){
		lightBoxDetail(this);
		return false;
	});
	
	$('.ajaxlink').click(function(){
		ajaxLightBox(this);
		return false;
	});
	
	
});

var menuHover = function(el,state){
	
	if(state == 1) { 
		
		$(el).addClass('navhover');
		//alert(el.className);
	} 
	else { 
		$(el).removeClass('navhover');
	}
}

var srcImg = '';
var imgExt = '';

var swapIn = function(lmnt) { 
		srcImg = $(lmnt).attr("src");
		imgExt = srcImg.split(".");
		imgExt = "."+imgExt.pop();
		srcImg = srcImg.replace(imgExt,"-on"+imgExt);
		$(lmnt).attr("src",srcImg);
}

var swapOut = function(lmnt) { 
	srcImg = srcImg.replace("-on"+imgExt,imgExt);
	$(lmnt).attr("src",srcImg);
}

/*
 * Product page tab switching
 */

var activeStory = '';
var showMeActive = ''; //for the pop embed email links
function closecollective() {
  $('#collectivestory').slideUp('fast');
  activeStory = '';
}

var imgVidInView = 'granthero'; 
function showViewer(id) {
  window.scrollTo(0,'#top');
  if (activeStory != id) { 
    showMeActive = ''; 
    document.getElementById('collectivestory').innerHTML = '';
    imgVidInView = 'granthero';
    $('#collectivestory').load('/frags/grant-nom-details.html?ajax=true&nomId=' + id,function() {
      $("#proddetinfobox ul li").click(function(){
        tabSwitch(this);
      });
    });
    $('#collectivestory').slideDown('fast');
    activeStory = id;
  } 
}

function pager(pageNum) {
  $('#collectivecontainer').load('/frags/grant-entries.html?ajax=true&p=' + pageNum);  
}

function showMe(id) { 
  if (showMeActive == id) { 
    $('#'+id).hide();
    showMeActive = '';
   } 
  else if (showMeActive != '') { 
    $('#'+showMeActive).hide();
    $('#'+id).show();
    showMeActive = id;
  } 
  else { 
    $('#'+id).show(); 
    showMeActive = id;
  }
}

//tabswitching 
$(function() {
  $("#proddetinfotab li").click(function(){
     tabImageSwitch(this);
     tabSwitch(this);
   });
});

var tabId = "";
var tabSwitch = function(ele) {
  if(ele.className != 'active') { 
    $("#proddetinfotab li").removeClass("active");
    $(ele).addClass("active");
    tabId = ele.id;
    $("#proddetinfobox div").removeClass("active");
    contentId = tabId.replace(/tab/, "content");
    $('#'+contentId).addClass('active');
  } 
}    
var tabImageSwitch = function(ele) {
  var bg,newBg;
  $('#proddetinfotab li').each(function(){
    bg = $(this).css('background-image');
    newBg = bg.replace(/-on/, "");
    $(this).css('background-image',newBg);
  });
  bg = $(ele).css('background-image');
  newBg = bg.replace(/.gif/, "-on.gif");
  $(ele).css('background-image',newBg);
}
var doTabSwitch = function(eleName) {
  var it = document.getElementById(eleName);
  tabSwitch(it);
}

var hideCartButtonHTML = '<div id="addtocartloading" class="loadingbox"><img src="/images/product/detail/load-add-to-cart.gif" alt="Loading" title="Loading" /></div>';


var scrollMe = function(lmnt){
	currentPos = $(window).scrollTop();
	eOffset = $("#"+lmnt+"").offset().top - 10;
	scrollPos = eOffset;
	$('html, body').animate({
	scrollTop: scrollPos
	}, 500);
}


var hideButton = function(id){
	$('#'+id).hide();
	$('#' + id + ' + .loading').show();
}

var showButton = function(id){
	$('#'+id).show();
	$('#' + id + ' + .loading').hide();
}

var selectPage = function(e) { 
	curURL = window.location.href.split('?');
	window.location.href = curURL[0] + '?numOfOrders=' + e.value;
}


// ---------------------------------------------------
// form validation and basic email address check
// serialize form and store in zinformer
// ---------------------------------------------------
var zrGenericValidate = function(mandatoryvalues, formtosubmit, responsecontainer, hidebutton, postURL, callBack, optionhandler){
	// setup array with mandatory fields
	var mandatory = mandatoryvalues.split(',');
	// loop on mandatory fields and alert alt messages
	var mandatory_error = false;
	for (a = 0; a < mandatory.length; a++){
		if (document.getElementById(mandatory[a]).value == ''){
			alert(document.getElementById(mandatory[a]).alt);
			return;
		}
		else {
			if (mandatory[a].match('email') != null){
				if(document.getElementById(mandatory[a]).value.match('@') == null){
					alert ('Please enter a valid Email Address.');
					return;
				}
			}
		}
	}
	
	document.getElementById(hidebutton).style.display = 'none';
	document.getElementById(hidebutton + "loading").style.display = 'block';
	if (document.getElementById('setOption') ||optionhandler != '' ){
		document.getElementById('setOption').value = optionhandler;
	}
	myformelements = $("#" + formtosubmit).serialize();
	if (postURL != ''){
		$.post(postURL, myformelements,
			function(response){
				eval(callBack + "('" + responsecontainer +"')");
				return false;
			}
		);
	}
	else {
		$.post("/", myformelements,
			function(response){
				eval(callBack + "('" + responsecontainer +"')");
				return false;
			}
		);
	}
}

var requestCatalogComplete = function(responsecontainer){
	document.getElementById(responsecontainer).innerHTML = "<p>Thank you. Your catalog request has been received. Keep on browsing.</p>";
}

var feedbackSubmissionComplete = function(responsecontainer){
	document.getElementById(responsecontainer).innerHTML = '<p>Thank you for your feedback! Keep on browsing.</p>Here\'s what our <a href="/support/testimonials/">customers are saying about us</a>.';
}

var referralProgramComplete = function(responsecontainer){
	sendReferralEmail();
}

var mailToLink = function(el){
	var emailVal = $(el).html();
	emailVal = emailVal.replace("[at]", "@");
	emailLink = "mailto:"+emailVal;
	$(el).attr('href',emailLink);	
	$(el).html(emailVal);	
}

ZR = {
	preventBubble: function (event){
		if (!event){
			var event = window.event;
		}
		event.cancelBubble = true;
		if (event.stopPropagation){
			event.stopPropagation();
		}
	}
}

/****************************************************
	ZR JQuery Lightbox zoom script 2.0	 
****************************************************/
var lbStage = 'ready';
var lbArray = new Array();
var lbTitleArray = new Array();
var lbGallery = false;
var zoomDetail = false;

//Set up all the HTML for the lightbox
var lbLoadHTML = '<img src="/images/lightbox/lightbox-load.gif" alt="loading" title="loading" id="lightboxload" />'
var maskHTML = '<div id="mask" onclick="closeLightBox();" title="Click to Close"></div>'+lbLoadHTML;
var lightBoxHTML = '<div id="lightbox"><div id="lightboxutil"><img src="/images/lightbox/close.png" alt="Close" title="Close" onclick="closeLightBox();" id="lbclose" /></div><div id="lightboximage"></div></div>';
var lbCloseBtn = '<img src="/images/lightbox/mini-close.gif" id="lbminiclose" onclick="captionFade();" alt="Hide Caption" title="Hide Caption" />';
var prevLink = '';
var nextLink = '';
var captionLink = '';


//function to set up the backound and preloader
var maskLoad = function() { 
	//Set up all the positioning variables
	docHeight = $(document).height();
	winHeight = $(window).height();
	winHeightFrag = Math.round(winHeight*1)/14;
	winWidth = $(window).width();
	scrollTop = $(window).scrollTop();
	lbTopPos = scrollTop + winHeightFrag;
	lbLoadTopPos = (((Math.round(winHeight)/2)+scrollTop)-16);
	lbLoadLeftPos = ((Math.round(winWidth)/2)-16);
	lbStage = 'loading';
	
	$("body").prepend(maskHTML);
	$("#mask").css("height",docHeight);
	$("#lightboxload").css("top",lbLoadTopPos);
	$("#lightboxload").css("left",lbLoadLeftPos);
}

//core function that sets up the mask and the light box
var lightBoxZoom = function(lmnt){
	maskLoad();
	//Set up arrays for Lightbox Galleries Mode.
	$(".zoom").each(function (i) {
		lbArray[i] = this.href;
		lbTitleArray[i] = this.title;
		//$("#debug").append(lbTitleArray	[i]);
	});
	if(lbArray.length > 1) { 
		lbGallery = true;
	}
	lbLoadContent(lmnt);
}

//Core function that loads the Image to the lightbox
var lbLoadContent = function(lmnt){
	//Set up the Image properties
	imgPath = lmnt.href;
	if (zoomDetail == true) { 
		lbCaption = $(lmnt).next('div').html();
	} else { 
		lbCaption = lmnt.title;
	}
	var lbImg = new Image();
	$(lbImg).load(function() { 
		//This all happens after the image loads
		
		//Set up Previous and next content for Lightbox Galleries
		if(lbGallery == true){
			lbx=0;
			lastImg = lbArray.length - 1;
			for (lbx=0; lbx<lbArray.length; lbx++){
				if(imgPath == lbArray[lbx]){
					lbCaption = lbTitleArray[lbx];
					switch (lbx){
						case 0:
							prevImg = lbArray[lastImg];
							nextImg = lbArray[lbx+1];
							prevCaption = lbTitleArray[lastImg];
							nextCaption = lbTitleArray[lbx+1];
						break;
						case lastImg:
							prevImg = lbArray[lbx-1];
							nextImg = lbArray[0];
							prevCaption = lbTitleArray[lbx-1];
							nextCaption = lbTitleArray[0];
						break;
						default:
							prevImg = lbArray[lbx-1];
							nextImg = lbArray[lbx+1];
							prevCaption = lbTitleArray[lbx-1];
							nextCaption = lbTitleArray[lbx+1];
					}
				}
			}
			prevLink = '<a href="'+prevImg+'" onclick="prevNextBox(this); return false;" title="'+prevCaption+'" class="lightboxprev"><img src="/images/lightbox/previous.png" alt="previous" /></a>';
			nextLink = '<a href="'+nextImg+'" onclick="prevNextBox(this); return false;" title="'+nextCaption+'" class="lightboxnext"><img src="/images/lightbox/next.png" alt="next" /></a>';
		}
		
		$("#lightboxload").replaceWith(lightBoxHTML);
		$("#lightboximage").html(this);
		
		if(lbCaption != '') { 
			captionLink = '<img src="/images/lightbox/info.png" onclick="captionFade();" alt="Hide Caption" title="Hide Caption" id="lbcaptionicon" />';
		} else { 
			captionLink = '';
		}
		
		$("#lightboxutil").prepend(captionLink+prevLink+nextLink);
		
		$("#lightbox").css("top",lbTopPos);
		var lbwidth = $("#lightbox").width();
		lbLeftPos = (Math.round(winWidth/2))-(Math.round(lbwidth/2));
		$("#lightbox").css("left",lbLeftPos);
		//Must have PNG fix enabled to fix the close button PNG on the fly
		$("#lightboxutil img").css("behavior","url(/iepngfix.htc)");
		$("#lightbox").fadeIn('normal',function() {
		//set the docHeight again because the lightbox can push it down.
		docHeight = $(document).height();
		$("#mask").css("height",docHeight);
			lbStage = 'loaded';
			if(lbCaption != '') { 
				//caption width is width of the image - 20px for padding
				captionWidth = $('#lightboximage img').width() - 20;
				$("#lightbox").prepend('<div id="lightboxcaption">'+lbCaption+lbCloseBtn+'</div>');
				$("#lightboxcaption").css('width',captionWidth);
				$("#lightboxcaption").css('filter','alpha(opacity=0)');
				//$("#lightboxcaption").fadeTo(300,.8);
			}
		});
	}).attr('src',imgPath).error(function () {
			 alert('there was an error loading the image');
			 $("#lightboxload").remove();
				$("#mask").remove();
				lbImg = '';
				lbStage = 'ready';
	});
}

//same as lightbox but it pulls content from a hidden div
//directly after the <a> element for longer article driven images
/*var lightBoxDetail = function(lmnt){
	zoomDetail = true;
	maskLoad();
	//Set up arrays for Lightbox Galleries Mode.
	$(".zoomdetail").each(function (i) {
		lbArray[i] = this.href;
		lbTitleArray[i] = $(this).next('div').html();
	});
	if(lbArray.length > 1) { 
		lbGallery = true;
	}
	lbLoadContent(lmnt);
}*/



var prevNextBox = function(lmnt){
	if ($.browser.msie == true) {
		//hide the caption so it doesn't look like garbage in ie.
		$('#lightboxcaption').css('display','none');
	}
	$("#lightbox").fadeOut('fast', function(){
		$("#lightbox").remove();
		$("#mask").after(lbLoadHTML);
		$("#lightboxload").css("top",lbLoadTopPos);
		$("#lightboxload").css("left",lbLoadLeftPos);
		lbStage = 'loading';
		lbLoadContent(lmnt);
		captionVisible = false;
	});
}

var captionVisible = false;
var captionFade = function() { 
	if (captionVisible == false){
		$('#lbcaptionicon').attr('alt','Hide Caption');
		$('#lbcaptionicon').attr('title','Hide Caption');
		$('#lbminiclose').css('display','block');
		$('#lightboxcaption').fadeTo(500,.8);
		captionVisible = true;
	} else { 
		$('#lbcaptionicon').attr('alt','Show Caption');
		$('#lbcaptionicon').attr('title','Show Caption');
		$('#lightboxcaption').fadeTo(500,0, function(){
			$('#lbminiclose').css('display','none');
		});
		captionVisible = false;
	}
}



/****************************************************
	ZR JQuery Ajax Lightbox  script 1.0				 
****************************************************/

var ajaxBoxHTML = '<div id="lightbox" class="ajaxbox"><div id="lightboxutil"><img src="/images/lightbox/close.png" alt="close" title="close" onclick="closeLightBox();" /></div><div id="ajaxboxcontent"></div></div>';


var ajaxLightBox = function(lmnt) { 
	ajaxLink = lmnt.href;
	lbparm = ajaxLink.split("/");
	lbparm = lbparm.reverse();
	maskLoad();
	$("#lightboxload").after(ajaxBoxHTML);
	$("#lightbox").css("top",lbTopPos);
	lbLeftPos = (Math.round(winWidth/2))-260;
	$("#lightbox").css("left",lbLeftPos);
	$("#lightboxclose img").css("behavior","url(/iepngfix.htc)");
	$("#ajaxboxcontent").load("/includes/ajax-box/", {refid:lbparm[1]}, function(){
		$("#lightboxload").remove();
		//set the mask height again just to make sure we don't have the white space in the footer
		docHeight = $(document).height();
		$("#mask").css("height",docHeight);
		//show the content
		$("#lightboxutil img").css("behavior","url(/iepngfix.htc)");
		$("#lightbox").fadeIn('normal', function(){
			lbStage = 'loaded';
		});
		
		//set a max height
		if($('#ajaxboxcopy').height() > 400) { 
			$('#ajaxboxcopy').css('height','400px');
			$('#ajaxboxcopy').css('overflow','auto');
			$('#ajaxboxcopy').css('width','472px');
			$('#ajaxboxcopy').css('padding-right','10px');
		}
	});
	//alert(ajaxLink);
}

/****************************************************
	ZR Close Lightbox													
****************************************************/

var closeLightBox = function(){
	if (lbStage == 'loading') { 
		if ($.browser.msie == false) {
			//do nothing if it is IE until the window is done loading.
			stop();
			$("#lightboxload").remove();
			$("#lightbox").remove();
			$("#mask").remove();
			lbStage = 'ready';
		}
	} else {
		$("#lightbox").fadeOut('fast', function(){
			$("#lightbox").remove();
			$("#mask").remove();
			lbStage = 'ready';
		});
	}
}

/****************************************************
	Open lightbox													 		 
	arrive at the page with the lightbox open 
	just specify a param.lightbox and add this code:
	
	$(function(){
		openLightBox(${param.lightbox});
	});
****************************************************/


var openLightBox = function(num){
	$('.zoom:eq('+num+')').each(function(){
		lightBoxZoom(this);
	});
}


var openLightBoxDetail = function(num){
	$('.zoomdetail:eq('+num+')').each(function(){
		lightBoxDetail(this);
	});
}



