$(function() {
    //initSplashAnimation();
    initCheckboxScrollbar();
    initSelectScrollbar();
    initHomeScroller();
    buttonClick();
    buttonClickIngredient();
    buttonHover();
    initOverlay();
    initProductScroller();
    initCtaProducts();
    initRecipeHomeCheckall();
    initRecipeHomeUncheckall();
    initExpandAll();
    initCollapseAll();
    initAccordions();
    initCustomSelect();
    initRhSearchButton();
    initUrlVarDetection();
   // initStoreLocator();
    intRecipeHomeMealOccassionUnCheckAll();
    intRecipeHomeMealOccassionCheckAll();
    intRecipeHomeCuisineCheckAll();
    intRecipeHomeCuisineUnCheckAll();
    intRecipeHomeIngredientUnCheckAll();
    intRecipeHomeIngredientCheckAll();
    intRecipeHomeProductUnCheckAll();
    intRecipeHomeProductCheckAll();
    initCheckAllProductOnLoad();
    ShowSignUpConfirmation();
   // initSendToPrint();
    initSendToCouponPage(); /* 31 -03-2011 */
    initClear();
    $.preloadCssImages();
});

initSplashAnimation = function() {
    $('#home #mainContainer').show();
    return;
//    if ($('#splashOverlay').length != 0) {
//        // if first time visitor, create cookie and show splash
//        if (readCookie('unclebens_splashpage') == null) {
//            createCookie('unclebens_splashpage', 'visited', 365);
//            $("#splashText").ready(function() {
//                $('#splashOverlay').show();
//                showSplash();
//            })
//        }
//        else {
//            $('#home #mainContainer').show();
//            $('#home #footerContainer #footerLinks ul').show();
//        }
//    }
//    else {
//        $('#home #mainContainer').show();
//    }

}


showSplash = function() {
	$('#home #mainContainer').show();
    var manager = new jsAnimManager();
    splash = document.getElementById("splashOverlay");
    splash.style.position = "absolute";
    var anim = manager.createAnimObject("splashOverlay");
    anim.add({ property: Prop.wait, duration: 6500 });
    anim.add({ property: Prop.top, from: 0, to: -1000, duration: 2500, onComplete: function() {
			$('#home #footerContainer #footerLinks ul').fadeIn('10000'); 
			$('#splashOverlay').hide();
			$('#footerContainer').css('width', '99%');
		}
	});
}


initHomeScroller = function() {
	$('#youtubeSlide').click(function(){
		$('#youtubeOverlayLink').click();
	});
	$('#recipeSlide').click(function(){
		window.location.href = $('#recipeLink').attr('href');
	});
	$('#couponSlide').click(function(){
		thisCouponUrl = $('#couponLink').attr('href');
		CheckLoginStatusandReturnUrl(thisCouponUrl);
		return false;
	});
	$('#clubSlide').click(function(){
		window.location.href = $('#clubLink').attr('href');
	});
    $('.scrollableHome').scrollable({
        circular: true,
        speed: 1500,
        easing: 'swing'
    }).navigator().autoscroll({
        autoplay: true, interval: 5000
    });
}

function onAfter(currSlideElement, nextSlideElement) {
    $(currSlideElement).css('display', 'block');
    if ($(nextSlideElement).next().html() != null) {
        $(nextSlideElement).next('div').css('display', 'block');
        $(nextSlideElement).next('div').css('left', '544px');
    }
    else {
        $('.slideshow div:first-child').css('display', 'block');
        $('.slideshow div:first-child').css('left', '544px');
    }
}

initProductScroller = function() {
    if ($('.scrollableProducts').length != 0) { // see if scrollers exist
        $('.scrollableProducts').each(function(i) {  // loop through scrollers
            var thisCarousel = $('.scrollableProducts:eq(' + i + ')');  // var this scroller
            var size = 4;
            var bucketCount = $(thisCarousel).find('.productLineBucket').length; // get number of buckets in this scroller
            var thisNext = $(thisCarousel).parent().find('a.next'); // var this next controller
            if (bucketCount < size + 1) { // hide next controller if less than size
                thisNext.addClass('disabled');
            }
            $(thisCarousel).scrollable();
            var scrollable = $(thisCarousel).data("scrollable");
            scrollable.onSeek(function() {
                if (this.getIndex() >= this.getSize() - size) {
                    thisNext.addClass('disabled');
                }
            });
            scrollable.onBeforeSeek(function(event, index) {
                if (this.getIndex() >= this.getSize() - size) {
                    if (index > this.getIndex()) {
                        return false;
                    }
                }
            });
			// position scroller to product selected
			var productId = getQString('p_id'); // get product ID from url
			if(productId.length){
			var carouselPosition = 1;
				$(thisCarousel).find('.productLineBucket').each(function(){ // loop through scroller buckets
					var thisHref = $(this).find('a').attr('href'); // get href string
					pos1 = thisHref.indexOf('p_id=');
					thisProductId = thisHref.substring(pos1+5); // find product ID of current bucket
					if(1*thisProductId == productId){
						productIdPos = carouselPosition; // if product ID of bucket equals product ID, set productIdPos to current position
					}
					carouselPosition = carouselPosition + 1;
				});
				scrollable.move(productIdPos-size); // move scroller to that position - size of carousel
			}
        });
    }
}
 
backToTop = function(obj){
	$(obj).scrollTop(0);
	return false;
}

buttonHover = function() {
	$('.hoverType').hover(over, out);
	function over(event) {
		$(this).addClass('active');
		$(this).css('cursor', 'pointer');
	}
	function out(event) {
		$(this).removeClass('active');
	}
}

buttonClick = function() {
	$('.clickType').click(function(){
		if($(this).hasClass('active')){
			$(this).removeClass('active');
			
		}
		else{
			$(this).addClass('active');
			
		}
	});
}


buttonClickIngredient = function() {
    $('.clickTypeIngredient').click(function() {
        if ($(this).hasClass('active')) {
            $(this).removeClass('active');
            var childClassval = "." + $(this).val();
            $(childClassval).each(function() {
                $(this).attr('checked', false);
            });
			selectCheckboxes();
        }
        else {
            $(this).addClass('active');
            var childClassval = "." + $(this).val();
            $(childClassval).each(function() {
                $(this).attr('checked', true);
            });
			selectCheckboxes();
        }
    });
}

selectCheckboxes = function() {
	$('.clickTypeIngredient').each(function(){
		var thisClassval = "." + $(this).val();
		if($(this).hasClass('active')){
			$(thisClassval).parent('li').show();
		}
		else{	
			$(thisClassval).parent('li').hide();
		}
	});
}



initOverlay = function() { 
	if ($('.csOptions').length == 0) { 
		$('a[rel]').overlay({
			mask: { color: "#000", loadSpeed: 0, closeSpeed: 0 },
			onClose: function(){
				if($('.youtubeVideo').length != 0){
					var swfHtml = $('.youtubeVideo').html();
					$('.youtubeVideo').html('');
					if($('.youtubeVideo').html() == ''){
						$('.youtubeVideo').html(swfHtml);
					}
				}	
			}
		}); 
		$('input[rel]').overlay({
			mask: '#000'
		}); 
	} 
}


initCtaProducts = function() {
	$('.ctaProducts').hover(over, out);
	function over(event) {
		$(this).addClass('active');
	}
	function out(event) {
		$(this).removeClass('active');
	}
}

initExpandAll = function() {
    if ($('.expand').length != 0) {
        $('.expand').click(function() {
            $(this).addClass('active');
            $('.collapse').removeClass('active');
            // recipes home page - collapse first, then show (IE7 bug)
            $('#recipesHomeAccordion').find('.recipesHomeBucket').each(function() {
                $(this).hide();
            });
            $('#recipesHomeAccordion').find('.recipesHomeBucket').each(function() {
                $(this).show();
            });
			// recipes detail page - collapse first, then show (IE7 bug)
            $('#recipeDetailAccordion').find('.recipeDetailBucket').each(function() {
                $(this).hide();
            });
            $('#recipeDetailAccordion').find('.recipeDetailBucket').each(function() {
                $(this).show();
            });
			// product detail page
            $('#productDetailAccordion').find('.productDetailBucket').each(function() {
                $(this).show();
            });
            
            $('#recipesHomeAccordion').find('.accordionLink').each(function() {
                $(this).addClass('expanded');
            });
			$('#recipeDetailAccordion').find('.accordionLink').each(function() {
                $(this).addClass('expanded');
            });
            $('#productDetailAccordion').find('.accordionLink').each(function() {
                $(this).addClass('expanded');
            });
            return false;
        });
    }
}

initCollapseAll = function() {
	if($('.collapse').length != 0) {
		$('.collapse').click(function() {
			$(this).addClass('active');
			$('.expand').removeClass('active');
			// recipes home page
			$('#recipesHomeAccordion').find('.recipesHomeBucket').each(function(){
				$(this).hide();
			});
			// recipes detail page
			$('#recipeDetailAccordion').find('.recipeDetailBucket').each(function() {
                $(this).hide();
            });
			// product detail page
			$('#productDetailAccordion').find('.productDetailBucket').each(function(){
				$(this).hide();
			});
			
			$('#recipesHomeAccordion').find('.accordionLink').each(function(){
				$(this).removeClass('expanded');
			});
			$('#recipeDetailAccordion').find('.accordionLink').each(function() {
                $(this).removeClass('expanded');
            });
			$('#productDetailAccordion').find('.accordionLink').each(function(){
				$(this).removeClass('expanded');
			});
			return false;
		});
	}
}

initRecipeHomeCheckall = function() {
    if ($('#recipesHomeAccordion').length != 0) {
        $('#recipesHomeAccordion .recipesHomeBucket').each(function() {
            var thisForm = this;
            $(this).find('.check').click(function() {
                $(thisForm).find(':checkbox').attr('checked', 'checked');
                return false;
            });
        });
    }
}

initRecipeHomeUncheckall = function() {
    if ($('#recipesHomeAccordion').length != 0) {
        $('#recipesHomeAccordion .recipesHomeBucket').each(function() {
            var thisForm = this;
            $(this).find('.uncheck').click(function() {
                $(thisForm).find(':checkbox').attr('checked', false);
                return false;
            });
        });
    }
}

intRecipeHomeMealOccassionUnCheckAll = function() {
if ($('#unChkAllMealOccassion').length != 0) {

    $('#unChkAllMealOccassion').click(function() {
        $('.mealOccasionType').each(function() { $(this).attr('checked', false); });
        return false;
    });

}
}

intRecipeHomeCuisineCheckAll = function() {

    if ($('#chkAllCuisine').length != 0) {

        $('#chkAllCuisine').click(function() {
            $('.cuisineType').each(function() { $(this).attr('checked', true); });
            return false;
        });

    }
}


intRecipeHomeCuisineUnCheckAll = function() {
    if ($('#unChkAllCuisine').length != 0) {

        $('#unChkAllCuisine').click(function() {
            $('.cuisineType').each(function() { $(this).attr('checked', false); });
            return false;
        });

    }
}

intRecipeHomeMealOccassionCheckAll = function() {

    if ($('#chkAllMealOccassion').length != 0) {

        $('#chkAllMealOccassion').click(function() {
            $('.mealOccasionType').each(function() { $(this).attr('checked', true); });
            return false;
        });
    }
}


intRecipeHomeProductCheckAll = function() {

if ($('#chkAllProducts').length != 0) {

    $('#chkAllProducts').click(function() {
        $('.productType').each(function() { $(this).attr('checked', true); });
            return false;
        });
    }
}

intRecipeHomeProductUnCheckAll = function() {

if ($('#unChkAllProducts').length != 0) {

    $('#unChkAllProducts').click(function() {
            $('.productType').each(function() { $(this).attr('checked', false); });
            return false;
        });
    }
}

initCheckAllProductOnLoad = function() {

    if ($('#chkAllProducts').length != 0) {

        $('#chkAllProducts').click();
    }
}




///
intRecipeHomeIngredientCheckAll = function() {

if ($('#chkIngCheckAll').length != 0) {

    $('#chkIngCheckAll').click(function() {
    $('.ingredientType').each(function() { $(this).attr('checked', true); });
            return false;
        });
    }
}

intRecipeHomeIngredientUnCheckAll = function() {

if ($('#unChkIngCheckAll').length != 0) {

    $('#unChkIngCheckAll').click(function() {
            $('.ingredientType').each(function() { $(this).attr('checked', false); });
            return false;
        });
    }
}




initAccordions = function() {
	$('#recipesHomeAccordion').find('.recipesHomeBucket').hide();
	$('#recipeDetailAccordion').find('.recipeDetailBucket').hide();
	$('#innerContentAccordion').find('.innerContentBucket').hide();
	$('#productDetailAccordion').find('.productDetailBucket').hide();
	$('.accordionLink').click(function(){
		$(this).toggleClass('expanded');
		$(this).next('.recipesHomeBucket').toggle('200');
		$(this).next('.recipeDetailBucket').toggle('200');
		$(this).next('.innerContentBucket').toggle('200');
		$(this).next('.productDetailBucket').toggle('200');
		return false;
	});
}

initCheckboxScrollbar = function() {
    if ($('.checkboxScrollbar').length != 0) {
        $('.checkboxScrollbar').each(function() {
            if (!$(this).hasClass('noScroll')) {
                $('.checkboxScrollbar').tinyscrollbar();
            }
            else {
                $(this).find('.scrollbar').hide();
            }
        });
    }
}

initSelectScrollbar = function() {
	if(navigator.appVersion.indexOf("MSIE 7.") == -1){
		if($('.csScrollbar').length != 0){
			$('.csScrollbar').tinyscrollbar();
		}
	}
}

function openCloseOverlay(linkId) {
	$(linkId).click();
}

initRhSearchButton = function() {
	if($('#recipes_home_search').length != 0){
		var myTimoutID = '';
		$('#recipes_home_search').bind('keyup', function(){
			$('.recipesHomeDropdown').show();
			$('.recipesHomeDropdown li').hover(over, out);
				function over(event) {
					$(this).addClass('active');
					$(this).css('cursor', 'pointer');
				}
				function out(event) {
					$(this).removeClass('active');
				}
			 
		});
		// if user clicks outside the div, hide it
		$('body').click(function() {
		$('.recipesHomeDropdown').hide();
		//var myTimoutID = setTimeout(function(){$('.recipesHomeDropdown').slideUp('50')}, 10000);
		});
		$('.recipesHomeDropdown').click(function(event){
			 event.stopPropagation();
		});
	}
}

initCustomSelect = function() {
    $('.csOptions li').hover(over, out);
    function over(event) {
        $(this).addClass('active');
        $(this).css('cursor', 'pointer');
    }
    function out(event) {
        $(this).removeClass('active');
    }
    if (navigator.appVersion.indexOf("MSIE 7.") == -1 && $('.customSelect').length != 0) {
        $('.csReplace').show();
        $('.csReplace').click(function() {
            if ($('.csScrollbar').css('z-index') != -1) {
                $('.csOptions').css('display', 'none');
                $('.scrollbar').addClass('disable');
                $('.csScrollbar').css('z-index', '-1');
            }
            else {
                $('.csOptions').css('display', 'block');
                $('.scrollbar').removeClass('disable');
                $('.csScrollbar').css('z-index', '1');
            }
        });

        $('.csOptions li').click(function() {
            currOption = $(this).html();
            currVal = $(this).attr('rel');
            $('.csCurrent').html(currOption);
            $('.csSelect').val(currVal);
            $('.csOptions').slideToggle('fast', function() {
                $('.scrollbar').addClass('disable');
                $('.csScrollbar').css('z-index', '-1');
                parentForm = $('.csSelect').parent();

                submitCustomSelect(currVal, parentForm);


            });
            if ($(this).parent().hasClass('recipeFilter_Filter')) {
                SubmitOnFilter(currVal);
            }

        });
    }
    else {
        $('.customSelect').find('[name= select]').removeClass('csSelect').addClass('styled');
    }
    // if user clicks outside the div, hide it
    $('body').click(function() {
        $('.csScrollbar').css('z-index', '-1');
    });
    $('.csReplace').click(function(event) {
        event.stopPropagation();
    });
}



//registion page method

ShowSignUpConfirmation = function() {
    var message = $('#hdnSuccess').val();
    if (message != null && message.length > 0 && message.length) {
        openCloseOverlay('#openoverlay');
    }
    return false;
}



// cookie methods

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

// end cookie methods

  
getQString = function (name){
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

// open productDetailNutritionBucket from var 'showNutrition' in URL string
initUrlVarDetection = function() {
	if($('#productDetailNutritionBucket').length != 0){
		if(getQString('showNutrition')){
			divPosition = $('#productDetailNutritionBucket').position().top;
			$('#productDetailNutritionBucket').find('.accordionLink').addClass('expanded');
			$('#productDetailNutritionBucket').find('.productDetailBucket').show();

		}
	}
}




// use class submitOnChange for form that must be submitted when option selected
submitCustomSelect = function(thisValue,thisParentForm) {
	//alert('the value selected is: '+thisValue+'\nthe parent form id is: '+$(thisParentForm).attr('id'));
	if($(thisParentForm).hasClass('submitOnChange')){
		$(thisParentForm).submit();
	}
}


// function to count chars in a form element - updates element innerHTML with count and trims string when hits max
function countChars(elem,max,update){
	var curVal = document.getElementById(elem).value;
	var curCnt = curVal.length;
	if(curCnt > max){
		curVal = curVal.substring(0,max);
		document.getElementById(elem).value = curVal;
	}
	if(curCnt <= max){
		document.getElementById(update).innerHTML = curCnt;
	}
}


//initSendToPrint = function() {
//    if ($('#couponContent .coupons').length != 0) {
//        $('#couponContent .coupons').hover(function() {
//            $(this).css('cursor', 'pointer');
//        });
//        $('#couponContent .coupons').click(function() {
//            // location of coupon print page
//            var couponPrintPage = TheBestUrlInTheWorld;
//            window.open(couponPrintPage);
//            return false;
//        });
//    }
//}

initSendToCouponPage = function() {
    if ($('.home .coupons').length != 0) {
        $('.home .coupons').hover(function() {
            $(this).css('cursor', 'pointer');
        });
        $('.home .coupons').click(function() {
            // relocate to coupons page
            window.location.href = couponPageUrl;
        });
    }
}

initClear = function() {
    if ($('.clearButton').length != 0) {
        $('.clearButton').click(function() {
            $('#contact_charcount').html(0);
        });
    }
}



     
  






	



