$(function(){
	/*Add animation in the header*/
	$('#headerads').hover(
		function(){
			adAction('in');
		},
		function(){
			adAction('out');
		} 
	);

	/*navigation drop down menus*/
	$('#navigation li').hover(
		function(){
			$(this).find('ul').css('left','-5px');
		},function(){
			$(this).find('ul').css('left','-10000px');
		}
	);
	
	/*Clear any input field*/
	$('.clearform').focus(function(){
		if(this.value == this.defaultValue) { 
			this.value = '';
		}	
	});
	
	$('.clearform').blur(function(){
		if(this.value == '') { 
			this.value = this.defaultValue;
		}
	});
	
	/*Test for missing images can be removed on production*/
	$('.prodthumb img').error(function(){
		 this.src = '/images/common/missing-thumb.jpg';
	});

	$('.sliderboxprod img').error(function(){
		 this.src = '/images/common/missing-thumb.jpg';
	});
	
	$('.prodcat img').error(function(){
		 this.src = '/images/products/floral/category/missing.jpg';
	});
	
	$('.zoom').live('click',function(){
			lightBoxZoom(this);
			return false;
		});
		
	
	/*Attach images for the Lightbox if functionality is present*/
	if( ($('.zoom').length != 0) || ($('.ajaxbox').length != 0) || ($('.ajaxboxgen').length != 0) || ($('.ajaxboxgenNoSplitUrl').length != 0)|| ($('#lbforgotpw').length != 0) ) { 
		lightBoxLoader= new Image(); 
		lightBoxLoader.src="/images/lightbox/lightbox-load.gif";
		lightboxclose= new Image(); 
		lightboxclose.src="/images/lightbox/close.png"; 
		lightboxprev= new Image(); 
		lightboxprev.src="/images/lightbox/previous.png"; 
		lightboxnext= new Image(); 
		lightboxnext.src="/images/lightbox/next.png";
		
		
		$('.ajaxbox').click(function(){
			ajaxLightBox(this);
			return false;
		});
		
		$('.ajaxboxgen').click(function(){
			lbPage(this);
			return false;
		});

		$('#lbforgotpw').click(function(){
			lbForgot(this);
			return false;
		});		
	}
	
	$('li.tab').live('click',function(){
		tabAction(this);
	});
	

	
});
//After whole page loads call this.
$(window).load(function(){
		if(typeof heroPath != 'undefined'){
			if(heroPath.length > 0) { 
				loadSlideShow();
				setTimeout(function(){ slideShowAction(); }, 5000);
				$('#slideactionbtn').click(
					function(){
						playPause(this);
						return false;
					}
				);
			}
		}
});



/*----------------------------------------------

	Core Site Functions		
	
------------------------------------------------*/

function isEmpty(v) {
			if (v == undefined) { return true; }
			if (v == null) { return true; }
			if (v == "") { return true; }
			return false;
		}

var limitText = function(el,n) { 
	var areaContents = el.value;
	var idName = el.id;
	var contArray = areaContents.split('');
	var contLength = contArray.length;
	var contRemaining = n - contLength;
	if( contRemaining < 0 ) { 
		contRemaining = 0;
	}
	contRemaining += ' Characters Remaining';
	$('#'+idName+'counter').text(contRemaining);
	if (contLength > n) { 
		var contArrayTrunc = contArray.slice(0,n);
		var contTrunc = contArrayTrunc.join('');
		el.value = contTrunc;
	}
}


var scrollMe = function(el){
	currentPos = $(window).scrollTop();
	eOffset = $("#"+el).offset().top - 10;
	scrollPos = eOffset;
	$('html, body').animate({
	scrollTop: scrollPos
	}, 500);
}

var adAction = function(dir) { 
	if(dir == 'in'){
		$('#headerads').stop().animate(
			{height: '128px'},
			200
		);
	}
	else { 
		$('#headerads').stop().animate(
			{height: '112px'},
			600, 
			'easeOutBounce'
		);
	}
}

var tabAction = function(el){
	$('.tab').removeClass('active');
	$('.tabcontent').removeClass('active');
	$(el).addClass('active');
	var elID = el.id;
	$('#' + elID + 'content').addClass('active');
}

var hideButton = function(id) {
	var currentClass = $('#' + id).attr('class');
	var btnWidth = $('#' + id).css('width');
	//alert('CSS WIDTH: ' + btnWidth + '\nWIDTH: ' + $('#' + id).width());
	
	$('#' + id).addClass('disabled');
	$('#' + id).attr('disabled','disabled');
	var btnHTML = $('#' + id).html();
	$('#' + id).after('<div class="hidebuttonhtml">' + btnHTML + '</div>');
	$('#'+id).css('width',btnWidth);

	if(currentClass == 'secondary') { 
		$('#' + id).html('<img src="/images/common/button-load-secondary.gif" alt="loading" title="loading"/>');
	} 
	else { 
		$('#' + id).html('<img src="/images/common/button-load.gif" alt="loading" title="loading"/>');
	}
}


var showButton = function(id) {
	$('#' + id).removeClass('disabled');
	$('#' + id).removeAttr('style');
	$('#' + id).removeAttr('disabled');
	$('#' + id).html($('#' + id).next('.hidebuttonhtml').html());
	$('#' + id).next('.hidebuttonhtml').remove();
}


var checkEmailSignUpValueSubmit = function(){
	if (document.getElementById('emailsignup').value == 'Please enter email'){
		alert ('Please enter your Email address');
		return false;
	}						
	var atIndexEmail = document.getElementById('emailsignup').value.indexOf('@');
	var dotIndexEmail = document.getElementById('emailsignup').value.lastIndexOf('.');
	if (atIndexEmail == -1 || dotIndexEmail == -1 || dotIndexEmail - atIndexEmail < 2){
		alert("The email address you entered is not valid.");
		return false;
	}
	//window.location = '/contact/?email=' + document.getElementById('emailsignup').value;
	window.location = '/email-signup/?email=' + document.getElementById('emailsignup').value;

}
/*----------------------------------------------

	Hero Slideshow
	set of functions that move the hero slider
	loads all the images after the page loads. 
	loadSlideShow() is call with $(window).load()
																								
------------------------------------------------*/
var heroImg = new Array();
var loadHeroX = 1;
var loadHeroN = 0;

//Load all the imageherosliderconts into divs for the slideshow
var loadSlideShow = function(){
	loadHeroN = loadHeroX - 1;
	nextHTML = '<div id="heroslide' + loadHeroX + '" class="heroslide"></div>';
	
	//append the next slide div
	$("#heroslide" + loadHeroN).after(nextHTML);
  
	if(loadHeroX < heroPath.length) { 
		var heroContWidth = (625 * heroPath.length) + 625;
		$('#heroslidercont').css('width',heroContWidth + 'px');

    
  	heroImg[loadHeroX] = new Image();
		$(heroImg[loadHeroX]).load(function() { 	

			//happens after the image is loaded
			$("#heroslide" + loadHeroX).html(this);
			if(heroLink[loadHeroX] !='') { 
				//$(this).wrap('<a href="' + heroLink[loadHeroX] + '"></a>');
			}  
			$(this).attr("alt",heroAlt[loadHeroX]);
			$(this).attr("title",heroAlt[loadHeroX]);
			heroLoaded[loadHeroX] = true;
			loadHeroX = loadHeroX+1;
			
			//add in the controller
			addSlideNav(loadHeroX);
			
			loadSlideShow();
		}).attr('src',heroPath[loadHeroX]).error(function () {
       alert('there was an error loading the image: '+heroPath[loadHeroX]);
    });
  }
	else { 
		//we are at the last one, append the first image to loop it. 
		$("#heroslide"+loadHeroX).html($('#heroslide0').html());
		
	}
}

var currIdx = 0;
var nextIdx = 1;
var autoplaying = true;

//Begin the crossfading slideshow action
var slideShowAction = function(idx) {
	var heroContX = $('#heroslidercont').position().left;
	if(idx) {
		//Go to Specific Slide
		$('#heroslidercont').stop();
		stopSlideShowAction();
		$('#control' + nextIdx).removeClass('active');
		$('#control' + idx).addClass('active');
		switchHeroLink(idx);
		nextIdx = idx;
		autoplaying = false;
		var newXPos = 10 + ((idx-1) *-625);
		$('#heroslidercont').animate({left: newXPos}, 1000	, 'easeInOutCubic', function(){
			
		});
	} 
	else {
		if(autoplaying) { 

			var imgCount = heroPath.length;
		
			if (nextIdx > imgCount) {
				nextIdx = 0;
			}
			var newXPos = 10 + (nextIdx *-625);
	
			switch (heroLoaded[nextIdx]) {
			case true:
				$('#control'+nextIdx).removeClass('active');
				currIdx = nextIdx;		
				nextIdx++;
				$('#control' + nextIdx).addClass('active');
				switchHeroLink(nextIdx);
				$('#heroslidercont').animate({left: newXPos}, 1000	, 'easeOutCubic', function(){
					if (autoplaying) {
						var t = setTimeout(function(){ slideShowAction(); }, 5000);
					}
				});
				break;
			case false:
				//Next image is not loaded - try again
				var t = setTimeout(function(){ slideShowAction(); }, 250);
				break;
			case 'notset':
				//At the last image, slide one more and then roll back to the beginning
				$('#control'+nextIdx).removeClass('active');
				currIdx = nextIdx;
				nextIdx = 1;
				$('#control'+nextIdx).addClass('active');	
				switchHeroLink(nextIdx);
				$('#heroslidercont').animate({left: newXPos}, 500, 'easeOutCubic', function(){
					$('#heroslidercont').css('left','10px');																					
					if (autoplaying) {
						var t = setTimeout(function(){ slideShowAction(); }, 5000);
					}
				});
				break;
			}
		}
	}
}

var stopSlideShowAction = function(){ 
	autoplaying = false;
	$('#slideactionbtn').removeClass('pause'); 	
	$('#slideactionbtn').addClass('play'); 	
	$('#slideactionbtn').text('play'); 	
}

var playPause = function(e) {
	if(autoplaying == true) { 
		autoplaying = false;
		$(e).removeClass('pause'); 	
		$(e).addClass('play'); 	
		$(e).text('play'); 	
	} 
	else { 
		autoplaying = true;
		$(e).removeClass('play'); 	
		$(e).addClass('pause'); 	
		$(e).text('pause'); 	
		slideShowAction();
	}
}

var addSlideNav = function(n) { 
	var slideNavHTML = '<a href="#" onclick="slideShowAction('+n+');return false;" id="control'+n+'">'+n+'</a>';
	$('#slideactionbtn').before(slideNavHTML);
}

var switchHeroLink = function(n) { 
	$('#heroslideraltlinks').empty();
	//n is the slideNumber switch it to index
	var linkIndex = n - 1;
	$('#herosliderlink').attr('href',heroLink[linkIndex]);
	if(heroLink[linkIndex] == '') { 
		document.getElementById('herosliderlink').style.display = "none";
	}
	else {
		document.getElementById('herosliderlink').style.display = "block";
	}
	$('#herosliderlink').attr('title',heroAlt[linkIndex]);
	if(heroLink2URL[linkIndex] != '' && heroLink2Alt[linkIndex] != '') { 
		$('#heroslideraltlinks').append('<a href="' + heroLink2URL[linkIndex] + '">' + heroLink2Alt[linkIndex]+ '</a>')
	}
	if(heroLink3URL[linkIndex] != '' && heroLink3Alt[linkIndex] != '') { 
		$('#heroslideraltlinks').append('<a href="' + heroLink3URL[linkIndex] + '">' + heroLink3Alt[linkIndex] + '</a>')
	}
}


/*----------------------------------------------

	Pager
	set of functions that move the Pager slider
	content loads on the page. 
																								
------------------------------------------------*/
var currPageIdx = 1;
var slideWidth = 310;
var pagerRunning = false;

var pagerAction = function(action){
	//Turn off all automatic sliding
	stopSlideShowAction();
	if(pagerRunning == false) { 
		pagerRunning = true;
		switch(action){
		case 'previous':
			currPageIdx--;
			pagerAnimation(currPageIdx);
			break;
		case 'next':
			currPageIdx++;
			pagerAnimation(currPageIdx);
			break;
		default:
			currPageIdx = action;
			pagerAnimation(currPageIdx);
		}
	}
}

var pagerAnimation = function(n){
	//get all the numbers from the html
	var slideCount = $('div#slidecount').text();
	var totalPromos = $('div#totalpromos').text();
	var totalPages = $('div#totalpages').text();
	var slidePageWidth = $('div#slidepagewidth').text();
	var totalPagesWidth = totalPages * slidePageWidth;
	var maxXPosition = totalPagesWidth * -1;
	var begXPos = slidePageWidth * -1;
	var pagerXPos = n * slidePageWidth * -1;
	
	if(n > totalPages) { 
		pagerNum(1);
	}
	else if (n < 1) { 
		pagerNum(totalPages);
	}
	else { 
		pagerNum(n);
	}
	
	$('#slider').animate({left: pagerXPos}, 1000	, 'easeInOutCubic', function(){
		pagerRunning = false;
		//alert("left position is:" + $('#slider').position().left + "\nmaxXPosition is:" + maxXPosition);						
		if($('#slider').position().left >= 0) { 
			//we are at the far left replace it with the last page
			$('#slider').css('left',maxXPosition + "px");
			currPageIdx = totalPages;
		} else if($('#slider').position().left < maxXPosition) { 
			//we are at the far right replace it with the first page
			$('#slider').css('left',begXPos + "px");
			currPageIdx = 1;
		}
	});
}

var pagerNum = function(n) {
 $('#slidercontrols a').removeClass('active');
 $('#slidercontrols a#control' + n).addClass('active');
}

/*-----------------------------------------

	ZR JQuery Lightbox zoom script 2.5	 
	basic image zoom and gallery functionality
	Loop will cycle through all links on the page
	with class="zoom." To create a different
	gallery set a rel attribute. 
	<a href="path/to/zoom.jpg" class="zoom" rel="galleryName"><img src="/path/to/thumb.jpg" alt="alt" title="alt"/></a>

------------------------------------------*/

var lbStage = 'ready';
var lbArray = new Array();
var lbTitleArray = new Array();
var lbGallery = 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 lbMaskHTML = '<div id="mask" onclick="closeLightBox();" title="Click to Close"></div>'+lbLoadHTML;
var lbHTML = '<div id="lightbox"><div id="lightboxutil"><img src="/images/lightbox/close.png" alt="Close" title="Close" onclick="closeLightBox();" id="lbclose" /></div></div>';
var lbCloseBtn = '<img src="/images/lightbox/mini-close.png" id="lbminiclose" onclick="captionFade();" alt="Hide Caption" title="Hide Caption" />';
var lbPrevLink = '';
var lbNextLink = '';

//core function that sets up the mask and the light box
var lightBoxZoom = function(el){
	var gallerySet = el.rel;
	lbMaskLoad();
	//Set up arrays for Lightbox Galleries Mode.
	var n = 0;
	$(".zoom").each(function(i) {
		if(this.rel == gallerySet) {
			lbArray[n] = this.href;
			lbSetImgCaption(this);
			lbTitleArray[n] = imgCaption;
			n++;
		}
	});
	if(lbArray.length > 1) { 
		lbGallery = true;
	}
	lbLoadContent(el);
}
//function to set up the backgound and preloader
var lbMaskLoad = function() { 
	lbLoadTopPos = (((Math.round( $(window).height())/2) + $(window).scrollTop() )-16);
	lbLoadLeftPos = ((Math.round($(window).width())/2)-16);
	lbStage = 'loading';
	$("body").prepend(lbMaskHTML);
	$("#mask").css("height",$(document).height());
	$("#lightboxload").css("top",lbLoadTopPos);
	$("#lightboxload").css("left",lbLoadLeftPos);
}

var lbSetTopPos = function() { 
	var lbTopPos = Math.round((($(window).height() - $('#lightbox').height())/2)) + $(window).scrollTop();
	$("#lightbox").css("top",lbTopPos);
}

var lbSetImgCaption = function(el){
	imgCaption = el.title;
	if(imgCaption == '') { 
		imgCaption = $(el).children('img').attr('title');
	} 
}

//Core function that loads the Image to the lightbox
var lbLoadContent = function(el){
	//Set up the Image properties
	var imgPath = el.href;
	//pick the title of the image if it exists then the a tag

	lbSetImgCaption(el);
	var lbImg = new Image();
	
	$(lbImg).load(function() { 
		//This all happens after the image loads
		var lbImgHeight = this.height;
		var lbImgWidth = this.width;
		var targetImgHeight = parseInt($(window).height() * .67);
		var targetImgWidth = parseInt($(window).width() * .8);
		var lbHeightDiff = lbImgHeight - targetImgHeight;
		var lbWidthDiff = lbImgWidth - targetImgWidth;
		$("#lightboxload").replaceWith(lbHTML);
		$(this).attr('id','lightboximage');
		$("#lightbox").append(this);
		
		//Resizing the image if it is too large for the browser window
		if (lbHeightDiff > 0 || lbWidthDiff > 0) { 
			if (lbHeightDiff > lbWidthDiff) { 
				this.height = targetImgHeight;
				if($.browser.msie == true) {  
					//set the other dim for IE
					var imgDimRatio = targetImgHeight / lbImgHeight;
					this.width = parseInt(lbImgWidth * imgDimRatio);
				}
			} else
			if (lbWidthDiff > lbHeightDiff) { 
				this.width = targetImgWidth;
				if($.browser.msie == true) {  
					//set the other dim for IE
					var imgDimRatio = targetImgWidth / lbImgWidth;
					this.height = parseInt(lbImgHeight * imgDimRatio);
				}
			}
		}

		//Set up Previous and next content for Lightbox Galleries
		var lbCaption = '';
		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];
					}
				}
			}
			var lbPrevLink = '<a href="'+prevImg+'" onclick="prevNextBox(this); return false;" title="'+prevCaption+'" class="lightboxprev"></a>';
			var lbNextLink = '<a href="'+nextImg+'" onclick="prevNextBox(this); return false;" title="'+nextCaption+'" class="lightboxnext"></a>';			
			$("#lightboxutil").prepend(lbPrevLink+lbNextLink);
			$("#lightboximage").wrap('<a href=' + nextImg + ' onclick="prevNextBox(this); return false;" />');
		}
		
		//Add in the caption if it exists
		if(lbCaption != '' && lbCaption != undefined) { 
			$("#lightbox").append('<div id="lightboxcaption"></div>');
			$("#lightboxcaption").width($('#lightbox').width()-12);
			$("#lightboxcaption").html(lbCaption);
		} 
		var lbwidth = $("#lightbox").width();
		var lbLeftPos = (Math.round($(window).width()/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';
		});
		
		
		//Set up the top position of the LB this should happen right after we have content 
		lbSetTopPos();
	}).attr('src',imgPath).error(function () {
			 alert('there was an error loading the image');
			 $("#lightboxload").remove();
				$("#mask").remove();
				lbImg = '';
				lbStage = 'ready';
	});
}

var prevNextBox = function(el){
	$("#lightbox").fadeOut('fast', function(){
		$("#lightbox").remove();
		$("#mask").after(lbLoadHTML);
		$("#lightboxload").css("top",lbLoadTopPos);
		$("#lightboxload").css("left",lbLoadLeftPos);
		lbStage = 'loading';
		lbLoadContent(el);
	});
}



/*-----------------------------------------

	ZR JQuery Ajax Lightbox  script 1.1	
	This takes the string between the last //'s
	in the URL and loads that refid into a lightbox

------------------------------------------*/

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 lbContentSetUp = function(){
	lbMaskLoad();
	$("#lightboxload").after(ajaxBoxHTML);
	var lbLeftPos = (Math.round($(window).width()/2))-260;
	$("#lightbox").css("left",lbLeftPos);
	$("#lightboxclose img").css("behavior","url(/iepngfix.htc)");
}

var lbContentMaxY = function(){
	var lbHeadHeight = $('#lightbox').height() - $('#ajaxboxcopy').height();
	var optimumLBHeight = $(window).height() * .8;
	var optimumLBCopy = Math.round(optimumLBHeight - lbHeadHeight);
	//Mid height should be 350, if user has a tiny monitor they can scroll
	
	if(optimumLBCopy < 350) { 
		optimumLBCopy = 350;
	}
	if($('#ajaxboxcopy').height() > optimumLBCopy) { 
		$('#ajaxboxcopy').css('height',optimumLBCopy+'px');
		$('#ajaxboxcopy').css('overflow','auto');
		$('#ajaxboxcopy').css('width','489px');
		$('#ajaxboxcopy').css('padding-right','10px');
	}
	lbSetTopPos();
}

var ajaxLightBox = function(el) { 
	var ajaxLink = el.href;
	lbparm = ajaxLink.split("/");
	lbparm = lbparm.reverse();
	
	lbContentSetUp();
	$("#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
		$("#mask").css("height",$(document).height());
		
		//show the content
		$("#lightbox").fadeIn('normal', function(){
			lbStage = 'loaded';
		});
		//set the max height;
		lbContentMaxY();
	});
}

//lbPage goes after a URL and loads the whole thing into the lightbox

var lbPage = function(el) { 
	//alert('got here');
  var ajaxLink = el.href;
	ajaxLink = ajaxLink.split('=');
	//alert(ajaxLink);
  lbContentSetUp();
  $("#ajaxboxcontent").load(ajaxLink[0] + escape(ajaxLink[1]), function(){
    $("#lightboxload").remove();
    //set the mask height again just to make sure we don't have the white space in the footer
    $("#mask").css("height",$(document).height());
    //show the content
    $("#lightbox").fadeIn('normal', function(){
      lbStage = 'loaded';
    });
    //set the max height;
    lbContentMaxY();
  });
}

//Loads an actual URL as the parameter, used onclick

var lbLoadPage = function(url,callback) { 
  lbContentSetUp();
  $("#ajaxboxcontent").load(url, function(){
    $("#lightboxload").remove();
    $("#mask").css("height",$(document).height());
    $("#lightbox").fadeIn('normal', function(){
      lbStage = 'loaded';
			if(callback) { 
				eval(callback + "();");
			}
    });
    lbContentMaxY();
  });
}

/*var lbPageNoSplitUrl = function(el) { 
  var ajaxLink = el.href;
  lbContentSetUp();
  $("#ajaxboxcontent").load(ajaxLink, function(){
    $("#lightboxload").remove();
    //set the mask height again just to make sure we don't have the white space in the footer
    $("#mask").css("height",$(document).height());
    //show the content
    $("#lightbox").fadeIn('normal', function(){
      lbStage = 'loaded';
    });
    //set the max height;
    lbContentMaxY();
  });
}*/


//Depricate? JJM 
var lbPageUrl = function(url) { 
  var ajaxLink = url;
  lbContentSetUp();
  $("#ajaxboxcontent").load(ajaxLink, function(){
    $("#lightboxload").remove();
    //set the mask height again just to make sure we don't have the white space in the footer
    $("#mask").css("height",$(document).height());
    //show the content
    $("#lightbox").fadeIn('normal', function(){
      lbStage = 'loaded';
    });
    //set the max height;
    lbContentMaxY();
  });
}


/*-----------------------------------------

	Lightbox Forgot Script

------------------------------------------*/

var lbForgot = function(el){
	lbContentSetUp();
	var forgotFrom = el.href;
	forgotFrom = forgotFrom.split('=');
	forgotFrom = forgotFrom[1];
	$("#ajaxboxcontent").load("/includes/forgot-password/",{from: forgotFrom}, function(){
		$("#lightboxload").remove();
		$("#forgotpasswordform").validate({
			errorPlacement: function(error, element) {
				error.prependTo( element.parent("div") );
			},
			submitHandler: function(form) {
				hideButton('forgotpwsubmit');
				//form.submit();
				lbForgotSubmit();
				
				return false;
			}
		});
		//set the mask height again just to make sure we don't have the white space in the footer
		var docHeight = $(document).height();
		$("#mask").css("height",docHeight);
		//show the content
		$("#lightbox").fadeIn('normal', function(){
			lbStage = 'loaded';
		});
		//set the max height;
		lbContentMaxY();
	});
}

var lbForgotSubmit = function(){
	var forgotEmail = $('#forgotemail').val();
	var forgotFrom = $('#forgotfrom').val();
	var forgotOption = $('#forgotoption').val();
	$('#ajaxboxcontent').load("/includes/forgot-password/", {
			email: forgotEmail,
			from: forgotFrom,
			OPTION: forgotOption
		});
}

var lbForgotPassEmail = function(email,from){
	if(from == 'checkout'){
		$('#cartusername').val(email);
	} else { 
		$('#useremail').val(email);
	}
	closeLightBox();
}




/*-----------------------------------------

	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';
		});
	}
}


/*-----------------------------------------

	Floral Section JS 

------------------------------------------*/

var floralShowForm = function() { 
	$('#floralbutton').slideUp(200,
	function(){
		$('#floralorderform').slideDown(350);
	});
}

var floralSelectSku = function(el) { 
	$('#productskuselect li').removeClass('active');
	$(el).addClass('active');
	var skuPrice = $(el).attr('price');
	var skuRef = $(el).attr('refid');
	var prodRef = $(el).attr('prodrefid');
	$('#productprice').html(skuPrice);
	$('#skuref-1').val(skuRef);
	
	//Load the Image without sticking it in the src til it is done
	var prodImgPath = '/images/products/floral/detail/' + prodRef + "-" + skuRef + '.jpg';
	
	var prodImg = new Image();
	$(prodImg).load(function() {
			$('#productheroimage').attr('src',prodImgPath);
	}).attr('src',prodImgPath).error(function () {
		alert('there was an error loading the image');
	});
}

/*-----------------------------------------

To Go Department Section JS 

------------------------------------------*/

var togoShowForm = function() { 
	$('#togobutton').slideUp(200,
	function(){
		$('#togoorderform').slideDown(350);
	});
}, togoSelectSku = function(el) {
	var skuChosen = $('option[refid="' + $(el).val() + '"]'),
		skuPrice = $(skuChosen).attr('price'),
		skuRef = $(skuChosen).attr('refid'),
		prodRef = $(skuChosen).attr('prodrefid'),
		turnAround = $(skuChosen).attr('turnaround'),
		turnAroundUnit = $(skuChosen).attr('turnaroundunit'),
		allowIcingSelection = $(skuChosen).attr('disableicing'),
		deptUrlRef = location.pathname,
		zoiSave = $(':input[name="zoi_save"]', '.togoform').val(),
		zoiItemId = $(':input[name="zoi_id-' + zoiSave + '"]', '.togoform'),
		storeExclusions = $(':input[name="storeExclusions"]').val();
	$('#productprice').html(skuPrice);
	// Update textual display using hidden attributes
	if(turnAround) {
		$('#turnaround').html('Ready for pickup in as little as ' + turnAround + 
			(turnAround > 1 ? turnAroundUnit.toLowerCase() + 's' : turnAroundUnit.toLowerCase()) +
			'!').addClass('copy');
	}
	if(allowIcingSelection == 'true') {
		$('#icingOption').addClass('inactive');
	}
	
	// Update the Order Form fields
	$('#skuref-' + zoiSave).val(skuRef);
	if(zoiItemId) {
		zoiItemId.val(skuRef);
	}
	if(storeExclusions.length > 0) {
		// Parse out the CSV and PIPE-DELIMITED values
		// Format: SKU|Store Code, SKU|Store Code, ...
		var codes = storeExclusions.split(","),
			numFound = codes.length, i = 0,
			subCodes = null,
			valuesToFind = new Array(),
			options = $('option', ':input[name="pickupLocation-' + zoiSave + '"]');
		for(; i < numFound; i++) {
			subCodes = codes[i].split("|");
			if(subCodes[0] === skuRef) {
				valuesToFind.push(subCodes[1]);
			}
		}
		if(valuesToFind.length > 0) {
			var c = 0, numSubcodes = valuesToFind.length;
				cursorCode = '';
			numFound = options.length;
			for(i = 0; i < numFound; i++) {
				cursorCode = options[i].value;
				for(; c < numSubcodes; c++) {
					if(valuesToFind[c] == cursorCode) {
						$(options[i]).addClass('hide');
					}
				}
			}
		} else {
			options.removeClass('hide');
		}
	}
	
	// Parse out the top-level directory in the URL
	deptUrlRef = deptUrlRef.substr(1, deptUrlRef.indexOf('/', 1) - 1);
	
	//Load the Image without sticking it in the src til it is done
	var prodImgPath = '/images/products/' + deptUrlRef + '/detail/' + prodRef + "-" + skuRef + '.jpg';
	
	var prodImg = new Image();
	$(prodImg).load(function() {
		$('#productheroimage').attr('src',prodImgPath);
	}).attr('src',prodImgPath);
	
	// Show Order Now Button if it's not visible already
	if($('.togobutton button[disabled], #togobutton button[disabled]').length) {
		$('.togobutton button[disabled], #togobutton button[disabled]').removeAttr('disabled');
	}
}, setupDecorations = function(el, index) {
	var userChoice = $(el).val().toLowerCase(),
		colorChooser = $('#cakeDecorationColor-' + index),
		cakeMessage = $('#cakeMessage-' + index);
	if(userChoice.indexOf('roses') !== -1 || userChoice.indexOf('border') !== -1) {
		colorChooser.removeClass('inactive');
		$('label[for="' + colorChooser.attr('id') + '"]').removeClass('inactive').show();
	} else if(userChoice.indexOf('writing') !== -1) {
		$('label[for="' + colorChooser.attr('id') + '"]').addClass('inactive').hide();
		colorChooser.addClass('inactive');
		cakeMessage.removeClass('inactive');
	} else {
		$('label[for="' + colorChooser.attr('id') + '"]').addClass('inactive').hide();
		colorChooser.addClass('inactive');
		cakeMessage.addClass('inactive');
	}
}, lookupTogoInventory = function(product) {
	var form = $('#togoform-1'),
		pickupStore = $('select[name="pickupLocation-1"]', form).val(),
		pickupDate = $('#pickupDate-1', form).val(),
		pickupTime = $('#pickupTime-1', form)
		options = {
			'OPTION': 'TOGO_INVENTORY_LOOKUP',
			'store_code': pickupStore,
			'product_id': product,
			'dept': 'Bakery',
			'date': pickupDate
		},
		newOptions = '';
	if(pickupStore === '') {
		return false;
	}
	if(pickupDate === '') {
		return false;
	}
	if($(':input[name="ITEM_TYPE"]', form).val() != 'MEALS') {
		return false;
	}
	$.getJSON('/', options, function(data, textStatus, jqXHR) {
		var time = '',
			i = 0,
			unitsOfTime = null,
			suffix = 'am',
			displayValue = '';
		if(data.inventory === undefined) {
			pickupTime.empty();
			pickupTime.append('<option value="">Sorry, no times available</option>');
			return false;
		}
		for(; i < data.inventory.length; i++) {
			time = data.inventory[i].time;
			if(time.length > 0) {
				unitsOfTime = time.split(':', 3);
				if(unitsOfTime[0] > 12) {
					unitsOfTime[0] -= 12;
					suffix = 'pm';
				} else if(unitsOfTime[0] == 12) {
					suffix = 'pm';
				}
				displayValue = unitsOfTime[0] + ':' + unitsOfTime[1];
				newOptions += '<option value="' + time + '">' + displayValue + suffix + '</option>';
			}
		}
		if(newOptions.length > 0) {
			pickupTime.empty();
			pickupTime.append(newOptions);
		}
	});
}

/*-----------------------------------------|
	
	Classes Section JS								

------------------------------------------*/
var classFilter = function(){
	var currentURL = encodeURI(window.location);
	var currentURLArr = new Array();
	currentURLArr = currentURL.split('?');
	window.location = decodeURI( currentURLArr[0] + '?filter=' + document.getElementById('classfilterselect').value );
}

/*-----------------------------------------

	crumbBuilder:
	Looks for a '#from-' in the URL, if this is
	present then it adds that value to the 
	breadcrumbs, used on product detail 
	pages.

------------------------------------------*/
var crumbBuilder = function(){
	var currentURL = encodeURI(window.location);
	var currentURLArr = new Array();
	currentURLArr = currentURL.split('#from-');
	if(currentURLArr.length > 1) {
		var crumbBuilderCode = currentURLArr.pop();
		var crumbBuilderTitle = $('#sub-' + crumbBuilderCode).html();
		$('#breadcrumbs a:last').after(' &gt; <a href="/cooking-school/' + crumbBuilderCode + '/">' + crumbBuilderTitle + '</a>');
	}
}


/*--------------------------------------------
	Shopping Lists Fuctions
--------------------------------------------*/

var shopListTitleEdit = function(mode,userMode,listID){
	if(mode == 'edit') { //Load the list for edit
		var zl_name = $('#shoplisttitle').text();
		var params =  'mode=edit&OPTION=LOAD_TEMP_LIST&zl_name=' + zl_name + '&zl_ID=' + listID;
	} 
	else { //Complete the form and save
		var shopListTitleText = $('#shoplisttitleinput').val();
		$('#zl_name').val(shopListTitleText);
		var params =  $('#shoplisttitleform').serialize();
	}
	if(shopListTitleText != '') { 
		$('#shoplistheader').load('/shopping-lists/includes/shop-list-title/', params, function(){
				//validateShopListTitle();
				if($('#shoplistcat').length > 0 ){
					$('.activelist').text(shopListTitleText);
				}
		});
	}
	else { 
		alert('You must enter a title for your List');
	}
}

var deleteList = function(id){
	var r=confirm("Are you sure you would like to delete this list? ");
	if (r==true) {
		window.location = '/shopping-lists/?OPTION=DELETE_LIST&zl_id=' + id;
		return true;
	}
	else {
		return false;
	}
}

/*-----------------------------------------------------
	
	shopListEdit();
	a function to add, update, delete
	or add from the ads section
	params: 
	id: the id of the list you would like to ad too
	mode: add, edit, delete, addFromAd
	userMode: whether or not the user will be editing the temp list or the user list. vals user or temp
	liID: listitem count number or ID.

------------------------------------------------------*/

var shopListEdit = function(id,mode,userMode,liID){
	var zlID = $('#currentlistid').text();
	/*alert('ID: ' + id + 
				'\nMode: ' + mode + 
				'\nuserMode: ' + userMode + 
				'\nliID: ' + liID);*/
	switch(mode)
		{
		case 'edit': //Load the edit form
			$('#shoplistitemformadd').validate().resetForm();
			var zli_name = encodeURIComponent($('#shoplistitem' + id + ' span:first').text());
			var params = 'zl_id=' + zlID + '&zli_name-0=' + zli_name + '&mode=edit&zli_id=' + liID + '&listCount=' + id;
			var liMode = 'edit';
			break;
		case 'save': //Save the edit form
			hideButton('listbutton'+id);
			var params =  $('#shoplistitemform' + id).serialize();
			break;
		case 'add':
			hideButton('listbuttonadd');
			var params =  $('#shoplistitemformadd').serialize();
			var liMode = 'add';
			break;
		case 'addFromAd':
			//loading on the link.
			var addToListLink = $('#'+id).find('.addtolist')
			addToListLink.removeClass('added');
			addToListLink.addClass('loading');
			hideButton('listbuttonadd');
			var zli_name = encodeURIComponent($('#' + id + ' h3 a').text() + ' - ' + $('#' + id + ' .addesc').text() + ' - ' + $('#' + id + ' .adprice').text());
			//Get all the params from the form
			var params =  $('#shoplistitemformadd').serialize();
			var zliNamePos = params.indexOf('zli_name-0');
			//Replace "Item Name" with the ad item desc. 
			params = params.substr(0,zliNamePos)
			params += 'zli_name-0=' + zli_name;
			var liMode = 'add';
			break;
		case 'delete':
			var params = 'zli_save=0&zli_delete-0=true&OPTION=ADD_ITEM_TO_LIST&zli_id-0=' + liID + '&zl_id=' + zlID;
			var liMode = 'delete';
			break;
		default:
		}
		if(liMode == 'add') { 
		//Add another li with a number 1 more than the last list item
			var prevLiId = $('#shoplistadd').prev().attr('id');
			if(prevLiId != 'shoplistutil') { 
				var prevLiNum = Number(prevLiId.replace('shoplistitem',''));
				var nextLiNum = prevLiNum + 1;
				var nextLiId = 'shoplistitem' + nextLiNum;
			} else { 
				nextLiNum = 1;
				var nextLiId = 'shoplistitem1';
			}
			//add the list count to the add params
			params = params + '&listCount=' + nextLiNum;
			
			var nextLiHTML = '<li id="' + nextLiId + '" style="display: none" class="shoplistitem"></li>';
			$('#shoplistadd').before(nextLiHTML);
			id = nextLiNum;
	}	
	//alert(params);
	$('#shoplistitem'+id).load('/shopping-lists/includes/shop-list-item/', params, function(responseText, textStatus, XMLHttpRequest){
			$('#shoplistitem'+id).slideDown('fast');
			if(liMode == 'add') { 
				//have to set the hidden input on the add button to the current list if it is blank.
				if($('input#zl_id').val() == '' || $('input#zl_id').val() == 'null') { 
					var listIdNum = $('.listidnum').text();
					$('input#zl_id').val(listIdNum);
					//Also set it on the print and email dialog windows. 
					document.getElementById('listemaillink').onclick = function(){
							lbLoadPage('/shopping-lists/includes/shop-list-email-dialog/?id=' + listIdNum,'shopListValidate'); return false;
					}
					document.getElementById('listprintlink').onclick = function(){
							listLoadPrint(listIdNum); return false;
					}
				}
				showButton('listbuttonadd');
				document.getElementById('shoplistinputnameadd').value = document.getElementById('shoplistinputnameadd').defaultValue;
				//Change the option handler on the add form to add items w/o creating a list.
				$('#zloption').val('ADD_ITEM_TO_LIST');
			} else
			if (liMode == 'delete') {
				$('#shoplistitem'+id).slideUp('fast',function(){
					$('#shoplistitem'+id).remove();
				});
			}
			
			if(mode == 'addFromAd'){
				addToListLink.removeClass('loading');
				addToListLink.addClass('added');
				addToListLink.text('Item Added')
			}
			
		}
	);
}

var shopListEmailSend = function(){
	var params = $('#shoplistemailform').serialize();
	$('#ajaxboxcontent').load('/shopping-lists/includes/shop-list-email-dialog/',params,function(){
		
	});
}

var shopListValidate = function(){
	var emailMsg = "Please enter a valid email.";
	$("#shoplistemailform").validate({
			rules: {
				shoplistsenderemail: "email",
				shoplistemail: "email"
			},
			messages: {
				shoplistsenderemail: emailMsg,
				shoplistemail: emailMsg
			},
			submitHandler: function(form) {
				hideButton('shoplistemailbtn');
				//form.submit();
				shopListEmailSend();
				return false;
			}
		});
}

/*--------------------------------------------
	Ads Fuctions
--------------------------------------------*/

var adLoadList = function(){
	var liID = $('#shoplistselector').val();
	var currentURL = encodeURI(window.location);
	var currentURLArr = new Array();
	currentURLArr = currentURL.split('?');
	window.location = decodeURI( currentURLArr[0] + '?id=' + liID );
	/*$("#adsidebarshoplist").load('/shopping-lists/includes/shop-list-detail/?id='+ liID, function(){
		alert('loaded' + liID);
	});*/
}

var listLoadPrint = function(id){
	if(id == 'null') { 
	 id = '';
	}
	window.open('/shopping-lists/print-list/?id='+ id,'printList','width=600,height=500');
}

var adLoadCat = function(el) {
  
	$('#adtabs li').removeClass('active');
	$(el).parent('li').addClass('active');
	
	var adLoadHTML = '<div id="adload"><img src="/images/common/loader-large.gif" alt="Loading" title="Loading"/></div>';
	$('#aditems').html(adLoadHTML);
	var adCatURL = el.href;
	var adCatTitle = $(el).text();
	var adCatArray = adCatURL.split('=');
	var adid = "";
	if ($('#adid').length) {
	  adid = $('#adid').html();
	}
  var p = "";
  if ($('#previewMode').length) {
    p = $('#previewMode').html();
  }	
	
	$('#aditems').load('/ads/includes/ad-item-loop/',
		{
			adcat: adCatArray[1],
			adCatTitle: adCatTitle,
			ajax: true,
			adid: adid,
			p: p
		},function(){
	});
	
}

var adSetStoreLoc = function(el) {
	var storeLocId = el.value;
	
	var p = $(el).attr('param_p');
	var adid = $(el).attr('param_adid');
  closeLightBox();
	window.location = "/ads/" + "?store=" + storeLocId + "&adid=" + adid + "&p=" + p;
}


var flickrFeedr = {
	feedURL: 'http://api.flickr.com/services/feeds/photos_public.gne?id=52236561@N03&lang=en-us&format=json&per_page=200&jsoncallback=?',
	feedLimit: 9,
	divID: 'photobox',
	init: function(maxIdx){
		$('#' + flickrFeedr.divID).empty();
		$('#' + flickrFeedr.divID).append('<div class="loading"><img src="/images/common/loader-large.gif" alt="Loading Photos" title="Loading Photos" /></div>');
		$.getJSON(flickrFeedr.feedURL,function(json) {
			var objPath = json.items;
			flickrFeedr.total = objPath.length;
			if(!maxIdx){
				maxIdx = flickrFeedr.feedLimit;
			}
			//Attaching More/Less links
			if(objPath.length > flickrFeedr.feedLimit){
				if($('#photomore').length == 0) {
					$('#photoless').remove();
					$('#viewmorephotos').prepend('<a href="#more" class="moreless" id="photomore">Show More &raquo;</a>');
					$('#photomore').live('click',function(){
						flickrFeedr.more();
						return false;
					});
				}
				else { 
					$('#photomore').remove();
					$('#viewmorephotos').prepend('<a href="#less" class="moreless" id="photoless">&laquo; Show Less</a>');
					$('#photoless').live('click',function(){
						flickrFeedr.less();
						return false;
					});
				}
			}
			
			var counter = 1;
			var counterLast = 3;
			var thumbClass = '';
			$.each(objPath,function(i,obj){
					$('#' + flickrFeedr.divID).empty();
				if (i < maxIdx){
					var newThumb = new Image();
					var imgAlt = '';
					var imgSrc = obj.media.m;
					var imgThumb = imgSrc.replace('m.jpg','s.jpg');
					var imgZoom = imgSrc.replace('m.jpg','b.jpg');
							imgAlt = obj.title;
					
					$(newThumb).load(
						function(){
							//call back once the image is loaded
							
							if(counter == counterLast) { 
									thumbClass=' last';
									counter = 1;
								}
								else { 
									thumbClass='';
									counter++;
								}
								
							if(imgAlt == undefined) { 
								imgAlt = '';
							}
							//$('#fbphotos').append('<img src="' + imgThumb + '"/>');
							$('#'+flickrFeedr.divID).append('<a href="' +imgZoom + '" class="zoom" rel="Flickr"><img src="/images/common/blank.gif" id="imgthumb' + i + '" style="background:url(' +imgThumb + ') no-repeat 50% 50%;" class="' + thumbClass + '" alt="' + imgAlt + '" title ="' + imgAlt + '"/></a>');
							$('#imgthumb' + i).fadeIn();
					}).attr('src',imgThumb).error(function(){
						alert('There was an error Loading the Image');
					});
				} //end if startIdx
			});
		});
	},
	more: function(){
		flickrFeedr.init(flickrFeedr.total);
	},
	less: function(){
		flickrFeedr.init(flickrFeedr.feedLimit);
	}
	
}
/* Provides a way to filter visible data from the calendar view for Cooking Classes */
function cookingClassCalendarFilter(locationName) {
	if(locationName === undefined) { return; }
	if(locationName === '') {
		$('#classcalendar .classicon').each(function(index, value) { $(this).show(); });
		$('.classblock').each(function(index, value) { $(this).show(); });
		return;
	}
	// Icon(s) in Calendar
	$('#classcalendar .classicon').each(function(index, value) {
		var location = $('.calendarinfocontent', this).attr('data-location'),
			className = $('.calendarinfocontent h4', this).text();
		if(location != locationName) {
			$(this).hide();
		} else {
			$(this).show();
		}
	});
	// Descriptive Text below Calendar
	$('.classblock').each(function(index, value) {
		var location = $(this).attr('data-location');
		if(locationName != location) {
			$(this).hide();
		} else {
			$(this).show();
		}
	});
}
