$(document).ready(function(){

/*********************************************************************************************
	IMPLEMENTATION OF BABW CUSTOM JQUERY PLUGINS
*********************************************************************************************/

	// default value clearing and repopulating
	$('input.filled').initialValue();

	// add product detail hover and modal
	$('li.product').productModalize();
	
	// more link animations for the category trays
	$(".show-rows").compressStore();
	
	// Homepage: tabset
	//	SDD:Commented this original HC code out.	
	//	$("#homepage-tabs-wrapper").babwTabs({selected:2});
    $("#homepage-tabs-wrapper").tabs();

	// activate chloe	
	//$("#chloe").chloe();

	// enhance selects
	$('select.enhance').enhancedSelect();
	
	// anypage that has a help icon
	$(".help").help();
	
	// any page with flowplayer playlist for audio or video
	$(".bear-media").bearMedia();

	//Setup Enter KeyPress on the Global Search textbox.
	$(".search_babw_input").keypress(function(e) 
	{
        if (e.which == 13)
        {
			$(".search-submit").click();
        }
	});
	
	$(".subnav").SubNav();
		
	var navDisabled = false;
	
/*********************************************************************************************
	IMPLEMENTATION OF JQUERY PLUGINS
*********************************************************************************************/	
	// Item Page: carousel on the item page at the bottom
	$('#style-boards ul').jcarousel();

	// Homepage: feature carousel 
	$('#home-feature #home-feature-list').jcarousel({
		//buttonNextHTML: '<a class="jcarousel-next">Next</a>',
		//buttonPrevHTML: '<a class="jcarousel-prev">Previous</a>'
	});

/*****************************************************************************
	cart specific items + dropdownToggle for primary nav
*****************************************************************************/	
	setCart = function() {
	// activate clicks on cart
	$("#cart-nav .cart-opener").each(function() {
		var cartLink = $(this);
		cartLink.click(function() {
			if ($("body").is('.no-cart-modal')==false) {
				cartOpen("basket");
			}		
			return false;
		})
	});
	
	$("#cart-dropdown").each(function() {
		var cartExit = $(this);
		cartExit.click(function() {
			cartClose();
			return false;
		})
	});
	
	$('#cart-dropdown .content-wrapper').click(function(e) {
    	e.stopPropagation();
    });
    
	$("#cart-nav #cart-close").each(function() {
		var cartExit = $(this);
		cartExit.click(function() {
			cartClose();
			return false;
		})
	});

	// activate tabs clicks
	$("#cart-tab-basket-link").each(function() {
		var cartLink = $(this);
		cartLink.click(function() {
			cartOpen("basket");
			return false;
		})
	});

	$("#cart-tab-just-added-link").each(function() {
		var cartLink = $(this);
		cartLink.click(function() {
			cartOpen("just-added");
			return false;
		})
	});
		
	// cart just added calendar picker
	$(".cart-name-task-birthday").datepicker({
		showOn: 'button', 
		buttonImage: '/Images/primary/cart/icon-calendar.png', 
		buttonImageOnly: true,
		dayNamesMin: ['S', 'M', 'T', 'W', 'T', 'F', 'S']
	})
	
	// adds event to checkbox in the cart, just added tab in the name your bear task to show the secondary form if it is a gift
	$('#cart-name-task-gift').click(function(evt){
		if ($(evt.target).is(':checked')){
			$("#cart-name-task-gift-form").slideDown("fast");
		} else {
			$("#cart-name-task-gift-form").slideUp("fast");
		}
		
	});
	}
	setCart();
	var navtimer;
	
	//default hover
	$('#play-nav').hover(function() {
		if(navtimer) {
        	clearTimeout(navtimer);
            navtimer = null;
        }
        navtimer = setTimeout(function() {
        	$('#play-nav').addClass("open");
        	$('#play-link').addClass("open");
        }, 500) 
	}, function() {
		clearTimeout(navtimer);
		$('#play-nav').removeClass("open");
		$('#play-link').removeClass("open");
	});
	
	$('#party-nav').hover(function() {
		if(navtimer) {
        	clearTimeout(navtimer);
            navtimer = null;
        }
        navtimer = setTimeout(function() {
        	$('#party-nav').addClass("open");
        	$('#party-link').addClass("open");
        }, 500) 
	}, function() {
		clearTimeout(navtimer);
		$('#party-nav').removeClass("open");
		$('#party-link').removeClass("open");
	});
	
	$('#shop-nav').hover(function() {
		if(navtimer) {
        	clearTimeout(navtimer);
            navtimer = null;
        }
        navtimer = setTimeout(function() {
        	$('#shop-nav').addClass("open");
        	$('#shop-link').addClass("open");
        }, 500) 
	}, function() {
		clearTimeout(navtimer);
		$('#shop-nav').removeClass("open");
		$('#shop-link').removeClass("open");
	});
	
	// methods to open the cart
	cartOpen = function(tabSelector) {

		$('#play-nav').unbind('mouseenter').unbind('mouseleave');
		$('#play-link').unbind('mouseenter').unbind('mouseleave');
		$('#party-nav').unbind('mouseenter').unbind('mouseleave');
		$('#party-link').unbind('mouseenter').unbind('mouseleave');
		$('#shop-nav').unbind('mouseenter').unbind('mouseleave');
		$('#shop-link').unbind('mouseenter').unbind('mouseleave');
		
		$("#cart-nav").each(function() {
			var cart = $(this);
			cart.find(".cart-tab").each(function(){
				var tab = $(this);
				if (tab.attr("id")=="cart-tab-"+tabSelector){
//sdd: Added Alert For Debugging
//sddalert(tab.attr("id") + ": setting class to open");
					tab.addClass("open");
				} else {
//sdd: Added Alert For Debugging
//alert(tab.attr("id") + ": removing class of open");
					tab.removeClass("open");
				}
			})
			cart.addClass("open");
			return false;
		});
	}
	
	// methods to close the cart
	cartClose = function() {
		
	$('#play-nav').hover(function() {
		if(navtimer) {
        	clearTimeout(navtimer);
            navtimer = null;
        }
        navtimer = setTimeout(function() {
        	$('#play-nav').addClass("open");
        	$('#play-link').addClass("open");
        }, 500) 
	}, function() {
		clearTimeout(navtimer);
		$('#play-nav').removeClass("open");
		$('#play-link').removeClass("open");
	});
	
	$('#party-nav').hover(function() {
		if(navtimer) {
        	clearTimeout(navtimer);
            navtimer = null;
        }
        navtimer = setTimeout(function() {
        	$('#party-nav').addClass("open");
        	$('#party-link').addClass("open");
        }, 500) 
	}, function() {
		clearTimeout(navtimer);
		$('#party-nav').removeClass("open");
		$('#party-link').removeClass("open");
	});
	
	$('#shop-nav').hover(function() {
		if(navtimer) {
        	clearTimeout(navtimer);
            navtimer = null;
        }
        navtimer = setTimeout(function() {
        	$('#shop-nav').addClass("open");
        	$('#shop-link').addClass("open");
        }, 500) 
	}, function() {
		clearTimeout(navtimer);
		$('#shop-nav').removeClass("open");
		$('#shop-link').removeClass("open");
	});
		
		$("#cart-nav").each(function(){
			var cart = $(this);
			cart.removeClass("open");
			return false;
		});
	}
	
	// helper to toggle the other dropdowns for debugging
	dropdownToggle = function(dropdownText) {
		$("#"+dropdownText+"-nav").each(function(){
			$(this).toggleClass("open");
			return false;
		});
	}
	
/****************************************************************************
	Find A Store Toggle
****************************************************************************/	
		$("#utility #store-finder-tab a.tab").click(function(i){
			if($("#utility #store-finder-tab a.tab").is(".open")){
				$("#store-finder-dropdown").hide();
				$("#utility #store-finder-tab a.tab").removeClass("open");
			} else {
				$("#store-finder-dropdown").show();
				$("#utility #store-finder-tab a.tab").addClass("open");
				$("#store-finder-widget-q").focus();
			}
			$('#store-finder-dropdown').click(function(e) {
           		e.stopPropagation();
        	});
			$(document).click(function() {
				$("#store-finder-dropdown").hide();
            	$("#utility #store-finder-tab a.tab").removeClass("open");
        	}); 
			return false;
		});
    



/*****************************************************************************
	Item page image gallery methods
*****************************************************************************/
	// view more images on item page
	$("#product-photos #product-thumbs .more a").each(function() {
	  var viewLink = $(this);
	  viewLink.click( function(){
			viewLink.parent().parent()
			if(viewLink.parent().hasClass("more")) {
				viewLink.parent().parent().animate({'height':'116px'}, 500);
				viewLink.text("Less Photos");
				viewLink.parent().toggleClass("more").addClass("less");
			} else if(viewLink.parent().hasClass("less")) {
				viewLink.parent().parent().animate({'height':'56px'}, 500);
				viewLink.text("More Photos");
				viewLink.parent().toggleClass("less").addClass("more");
			}
	      return false;
	  });
	});
	
	// image gallery on item page.
	var bucket = $("#main-image");
	$("#product-photos #product-thumbs li a").each(function() {
		var thumb = $(this);
		if(!thumb.parent().hasClass("more")) {
			thumb.click( function(){
				bucket.html('<img src="'+thumb.attr('href')+'" />');
				$("#product-photos #product-thumbs li").removeClass("on");
				thumb.parent().addClass("on");
				return false;
			});
		}
	});
	
/*****************************************************************************
Find a store columns
*****************************************************************************/
$(".column-full").each(function (i) {
    var regionItems = $(this).find('.region').size();
    var numItems = $(this).find('ul li ul li').size();
    if(regionItems > 1){
        var columnLength = Math.ceil(numItems/3);
        var itemIndex = columnLength-1;
        $(this).removeClass("column-full");

        $(this).find("ul li ul li:lt(" + columnLength + ")").parents(".region").wrapAll('<ul class="column column-left location-list"></ul>').parent().insertBefore($(this));
    }
    columnLeftItems = $(this).find('.column-left').size();
    regionItems = $(this).find('.region').size();
    if(regionItems > columnLeftItems) {
        $(this).find("ul li ul li:lt(" + columnLength + ")").parents(".region").wrapAll('<ul class="column location-list"></ul>').parent().insertBefore($(this));
    }
});
$(".section-location").css("display","block");

	
/*****************************************************************************
	Task specific items in the cart-just-added tab and item page
*****************************************************************************/
	// toggles the visibility of the item tasks
	toggleTasks = function(labelSelector, taskSelector) {
		var task = $(taskSelector);	
		$(labelSelector).each(function(){
			var label = $(this);
			label.click(function(){
				if ($(this).hasClass("open")) {
					task.slideUp("slow");
					$(this).removeClass("open");
				} else {
					task.slideDown("slow");
					$(this).addClass("open");
				}

			});
		});
	}
	
	// initializing items in the item panels
	// these are item page specific
	toggleTasks("#add-emb-toggle-label", "#embroidery-task");
	toggleTasks("#add-emb-toggle-label .edit-this", "#embroidery-task");
	//toggleTasks("#add-aud-toggle-label", "#sound-task");	
	//toggleTasks("#add-aud-toggle-label .edit-this", "#sound-task");	
	// these are for the just added tab
	toggleTasks("#cart-add-name-toggle-label", "#cart-name-task");
	toggleTasks("#cart-add-sound-toggle-label", "#cart-sound-task");
	toggleTasks("#cart-add-accessory-toggle-label", "#cart-accessory-task");

///////
///////
///////
///////
	
	$("#emb-inputs .inputcheck input").click(function() {

		//////HIDE/SHOW GREEK/REGULAR TEXT/////
		$(this).closest("li").find("div").toggle();
		
	});
	///////PRODUCTDETAIL.ASPX: EMBROIDERY///////
	if(typeof(embroideryAdded) !== "undefined") {

		if (embroideryAdded == "true") {
		
			//Modify The UI to indicate that the embroidery was added, and add the Remove Link.
			$("#add-emb").removeClass("add-emb-toggle");
			$("#add-emb").addClass("added");
			$("#add-emb-toggle-label").html("Embroidery added! <a href='#' id='remove-link'>Remove?</a>");
			$("#remove-link").addClass("remove-this");
			$("#embroideryprice").html("Embroidery Added $8.00");

			//Setup Click event on the Remove Link.
			$("#add-emb-toggle-label .remove-this").click(function() {
				$(this).parent().parent().removeClass("added");
				$(this).parent().parent().addClass("add-emb-toggle");
				$(this).parent().html("Add Embroidery?");
				//$("#embroideryprice").html("No Embroidery Added");
				$("#add-emb-toggle-label").html("Add Embroidery? <span>(only $8.00)</span>");
				//Set the hidden input's value to false.
				$("#EmbroideryAddedFlag").val("false");
				embroideryAdded = "false";
				embroideryText = "||";
				return false;
			}); 
		
		}
	}
	///////END EMBROIDERY///////
	
	// Proof of concept here for the remove link in the sound. More work will need to be done here.
	$("#add-aud-toggle-label .remove-this").click(function() {
		$(this).parent().parent().removeClass("added");
		$(this).parent().parent().addClass("add-aud-toggle");
		//$(this).parent().html("Add Sound?<span> (only $8.00)</span>");
		$(this).parent().html("Sound added! <a href='#' class='remove-this'>Remove?</a>");
		
		return false;
	});
	
	$(".basket-item > ul > li:last-child").each(function(){
      $(this).addClass("last");
	});
	
	$(".basket-item.enhanced > ul > li:first-child").each(function(){
	  $(this).css("min-height","115px");
	});
	
	//Form validation
	$(".Cart_Name_Task_Submit").click(function (i){
		var cartname = $( ".Cart_Name_Task_Name" );
		var cartbirthday = $( ".Cart_Name_Task_Birthday" );
	
		$("#cart-name-error").remove();
		cartname.removeClass("field-error");
		$("#cart-birthday-error").remove();
		cartbirthday.removeClass("field-error");
	
		var errornum = 0;
		if (cartname.val()==null||cartname.val()=="") {
			cartname.addClass("field-error");
			cartname.after("<p class='error-message' id='cart-name-error'>This field is required.</p>");
			errornum++;
		}
		if (isDate(cartbirthday.val()) == false) {
			cartbirthday.addClass("field-error");
			$(".ui-datepicker-trigger").after("<p class='error-message' id='cart-birthday-error'>A valid date is required (01/02/2010).</p>");
			errornum++;
		}
		if (errornum>0){
			errornum = 0;
			return false;
		} 
	});
	$(".category .category-header h3").each(function() {
    	var classAttribute = $(this).attr("id");
    	classAttribute = classAttribute.replace(/\s/g,"-");
    	classAttribute = classAttribute.replace("&","and");
    	$(this).attr("id",classAttribute);
	});

}); // document.ready?

// check date JavaScript function  
// if date is valid then function returns true, otherwise returns false  
function isDate(txtDate){  
   var objDate;  // date object initialized from the txtDate string  
   var mSeconds; // milliseconds from txtDate  
   
   // date length should be 10 characters - no more, no less  
   if (txtDate.length != 10) return false;  
   
   // extract day, month and year from the txtDate string  
   // expected format is mm/dd/yyyy  
   // subtraction will cast variables to integer implicitly  
   var day   = txtDate.substring(3,5)  - 0;  
   var month = txtDate.substring(0,2)  - 1; // because months in JS start with 0  
   var year  = txtDate.substring(6,10) - 0;  
   
   // third and sixth character should be /  
   if (txtDate.substring(2,3) != '/') return false;  
   if (txtDate.substring(5,6) != '/') return false;  
   
   // test year range  
   if (year < 999 || year > 3000) return false;  
   
   // convert txtDate to the milliseconds  
   mSeconds = (new Date(year, month, day)).getTime();  
   
   // set the date object from milliseconds  
   objDate = new Date();  
   objDate.setTime(mSeconds);  
   
   // if there exists difference then date isn't valid  
   if (objDate.getFullYear() != year)  return false;  
   if (objDate.getMonth()    != month) return false;  
   if (objDate.getDate()     != day)   return false;  
   
   // otherwise return true  
   return true;  
} 