/*
 *  Fix IE background image flicker (via http://www.mister-pixel.com/)
 */
try {
	document.execCommand('BackgroundImageCache', false, true);
} catch(e) {}

/*
 *	sIFR
 */
var SIFR = {
	init: function()
	{
		if (typeof sIFR != "function") return;
		
		sIFR.replaceElement("#product-tabs h1", named({sFlashSrc: "flash/minion-pro.swf", sColor: "#006940", sWmode: "transparent"}));
		sIFR.replaceElement("#copy h1", named({sFlashSrc: "flash/minion-pro.swf", sColor: "#006940", sWmode: "transparent"}));
		sIFR.replaceElement(".difference h2", named({sFlashSrc: "flash/minion-pro.swf", sColor: "#757575"}));
		sIFR.replaceElement("fieldset h2", named({sFlashSrc: "flash/minion-pro.swf", sColor: "#006940"}));
	}
};

/*
 *  Product hover
 */
var ProductHover = {
    init: function() {
        $("ul#product-list li").hover(function(){
            $(this).addClass("hover");
        }, function(){
            $(this).removeClass("hover");
        });
    }
};

/*
*  Product tabs
*/
var ProductTabs = {
	init: function()
	{
		$.address.change(function(event)
		{
			$.address.value($(this).attr('href'));

			$('#product-tabs li a').removeClass('active');
			$('.product-panel').hide();

			if (event.value == '/' || $('#' + event.value).length == 0)
			{
				$('#product-tabs li a:first').addClass('active');
				$('.product-panel:first').show();
			}
			else
			{
				$('a[href=#' + event.value + ']').addClass('active');
				$('#' + event.value).show();
			}
		});
		
		this.attachEvents();
	},
	attachEvents: function()
	{
        $("#product-tabs #product-nav #nav-overview a").click(function(){
            // Google Anaylitics event tracking
            if (pageTracker) pageTracker._trackEvent('Product', 'Description');
        });

        $("#product-tabs #product-nav #nav-recipe-list a").click(function(){
            // Google Anaylitics event tracking
            if (pageTracker) pageTracker._trackEvent('Product', 'Recipes');
        });

        $("#product-tabs #product-nav #nav-nutrition-facts a").click(function(){
            // Google Anaylitics event tracking
            if (pageTracker) pageTracker._trackEvent('Product', 'Ingredients');
        });
    }
};

/*
 *  Button hover, focus, blur effects. Print button click. Expand/Collapse buttons
 */
var Buttons = {
    init: function() {
        var thisClass = this;
        
        // hover, focus, blur, disabled
        $("#overview ul li a, #recipe-pagination li a, .paging ul li a, #sign-up a, #send a, #sign-up-page-2 a")
        .hover(thisClass.showOverImage(), thisClass.showOffImage())
        .focus(thisClass.showOverImage())
        .blur(thisClass.showOffImage());
        $("#overview ul li a[class=disabled], #recipe-pagination li a[class=disabled], .paging ul li a[class=disabled]")
        .each(thisClass.showDisabledImage())
        .hover(thisClass.showDisabledImage(), thisClass.showDisabledImage())
        .focus(thisClass.showDisabledImage())
        .blur(thisClass.showDisabledImage())
        .click(function(){return false;});
        
        // print
        $("#print a").click(function(){
            // Google Anaylitics event tracking
            if (pageTracker) pageTracker._trackEvent('Recipe', 'Print', window.location.href);
            
            window.print();

            return false;
        });
        
        // Culinary Corner sign up 
        $("#sign-up a").click(function(){ if (pageTracker) pageTracker._trackEvent('Registration', 'Page 1', 'Sign Up'); });
        $("#sign-up-page-2 a").click(function(){ if (pageTracker) pageTracker._trackEvent('Registration', 'Page 2', 'Submit'); });
        
        // search recipes Find button 
        $("#find input[type=submit]").click(function(){
            //used css classes here because id attribute used by .NET control
            var category =  $('.choose-a-category').find('option').filter(':selected').text(); 
            var ingredient =  $('.choose-an-ingredient').find('option').filter(':selected').text(); 

            // Google Anaylitics event tracking
            var data = category + ' - ' + ingredient;
            if (pageTracker) pageTracker._trackEvent('Find', data);
        });

        // expand/collapse
        $("div.site-map li ul").hide();
        $("div.site-map li:has(ul)").prepend("<strong class=\"col\">Collapsed</strong> ").addClass("parent");
        $("div.site-map li strong").click(function(){
            // toggle content visibility
            $(this).siblings("ul").toggle();
            
            // update UI
            $(this).empty();
            if ($(this).attr("class") == "col")
            {
                $(this).removeClass("col");
                $(this).html("Expanded");
                $(this).addClass("exp");
            }
            else
            {
                $(this).removeClass("exp");
                $(this).html("Collapsed");
                $(this).addClass("col");
            }
        });
    },
    
    showOffImage: function()
    {
        return (function(){$(this).parent().css("background-position", "0 0")});
    },
    
    showOverImage: function()
    {
        return (function(){$(this).parent().css("background-position", "0 50%")});
    },
    
    showDisabledImage: function()
    {
        return (function(){$(this).parent().css("background-position", "0 100%")});
    }
};

/*
 *  Sign Up form validation
 */
/*
var SignUpForm = {
    nameClientID: "",
    emailClientID: "",
    
    init: function()
    {
        var thisClass = this;
        var errors = [];
        
        $("#sign-up a").click(function(){
            $(":input.required").each(function(){
                if ($(this).val() == "")
                {
                    var id = $(this).attr("id");
                    var html = $("label[for=" + id + "]").html();
                    errors.push(html.split("<strong>")[0] + " is required");
                    $("label[for=" + id + "] strong").addClass("required");
                }
            });
            
            // no errors, allow submit
            if (errors.length == 0)
            {
                return true;
            }
            
            // generate error message and insert into page
            $("fieldset").prepend("<div id=\"errors\"><p>Please correct the following errors:</p><ul></ul></div>");
            $.each(errors, function(i, n){
                $("#errors ul").append("<li>" + errors[i] + "</li>");
            });
            
            return false;
        });
    },
    
    setNameClientID: function(val)
    {
        this.nameClientID = val;
    },
    
    setEmailClientID: function(val)
    {
        this.emailClientID = val;
    }
};
*/


/*
 * Checkbox validation (used by the venturafoods.core.Validation validation logic)
 */
 var CheckBoxValidation = {
    DisableSubmitButton : function(chkId, mustBeChecked, btnId)
    {
        var button = document.getElementById(btnId);
        var chkbox = document.getElementById(chkId);
        
        if (button && chkbox)
        {
            button.disabled = (chkbox.checked != mustBeChecked);
        }
    },
    
    EvaluateCheckBoxIsValid : function(val)
    {
        var control = document.getElementById(val.controltovalidate);
        var mustBeChecked = Boolean(val.mustBeChecked == 'true');

        return control.checked == mustBeChecked;
    },

    EvaluateCheckBoxListIsValid : function(val)
    {
        var control = document.getElementById(val.controltovalidate);
        var minimumNumberOfSelectedCheckBoxes = parseInt(val.minimumNumberOfSelectedCheckBoxes);
        var maximumNumberOfSelectedCheckBoxes = parseInt(val.maximumNumberOfSelectedCheckBoxes);

        var selectedItemCount = 0;
        var liIndex = 0;
        var currentListItem = document.getElementById(control.id + '_' + liIndex.toString());
        while (currentListItem != null)
        {
            if (currentListItem.checked) selectedItemCount++;
            liIndex++;
            currentListItem = document.getElementById(control.id + '_' + liIndex.toString());
        }
        
        return ((selectedItemCount >= minimumNumberOfSelectedCheckBoxes) && (selectedItemCount <= maximumNumberOfSelectedCheckBoxes));
    }
}

var SignUpQuestions = {
    init: function()
    {
        this.setupDOMElements();
        this.setupEventHandlers();
    },
    
    setupDOMElements: function()
    {
        // hide all additional fields
        $('p.please-clarify').hide();
        // show additional fields if corresponding "other" field is checked
        $('.more-info-list-item input').each(function(){
            var input = $(this);
            if (!input.attr('checked')) return;
            $(input.parent().parent().nextAll("p.please-clarify")[0]).show();
        });
    },
    
    setupEventHandlers: function()
    {
        var thisClass = this;
        $('.radio-answer input, .checkbox-answer input').click(function(event){
            var target = $(event.target);
            var parent = target.parent();
            parent = (parent.hasClass('more-info-list-item')) ? parent.parent() : parent;
            if (parent.children('.more-info-list-item').size() == 0) return;
            // only toggle if answer group has "other" option
            thisClass.toggleAdditionalField(target, parent, event.target.type);
        });
    },
    
    toggleAdditionalField: function(el, parent, type)
    {
        var additionalField = $(parent.nextAll("p.please-clarify")[0]); // get first "please clarify/specify" field after answer group
        var isOtherField = el.parent().hasClass('more-info-list-item');
        
        if (isOtherField) // "other" field -> show if checked, hide otherwise
        {
            additionalField[(el.attr('checked')) ? 'show' : 'hide']("normal");
            return;
        }
        if (type == 'checkbox') return;
        additionalField.hide('normal');
    }
}

var VideoCarousel = {
    size: 4,
    pages: null,

    init: function()
    {
            
        $('#videocarousel').jcarousel({
            initCallback: VideoCarousel.setupEventHandlers,
            buttonPrevHTML: null,
            buttonNextHTML: null
        });
    },

    setupEventHandlers: function(carousel)
    {
        $('.jcarousel-control a').bind('click', function() {
            if( ($(this).attr('id') != 'videocarousel-next') && ($(this).attr('id') != 'videocarousel-show-all') )
            {
                $('.jcarousel-control a').removeClass('on');
                $(this).addClass('on');

                var pagination = (( jQuery.jcarousel.intval($(this).text()) - 1)*VideoCarousel.size) + 1; 
                carousel.scroll(pagination);
            }

            var total = $('ul.jcarousel-list li.jcarousel-item').length;
            VideoCarousel.pages = Math.ceil(total/VideoCarousel.size);
            var nextButton = $('#videocarousel-next');
            var currentlySelected = $('.jcarousel-control a').filter('.on'); 

            if ( parseInt(currentlySelected.text()) == VideoCarousel.pages ) nextButton.css('color', '#dddddd').css('cursor', 'default');
            else nextButton.css('color', '#971227').css('cursor', 'pointer'); 

            return false;
        });

        $('#videocarousel-next').bind('click', function() {
            var currentlySelected = $('.jcarousel-control a').filter('.on'); 
            var nextPage = parseInt(currentlySelected.text()) + 1;
            var pagination = ( jQuery.jcarousel.intval(nextPage - 1)*VideoCarousel.size ) + 1; 
            var nextItem = $('.jcarousel-control a.on + a');
            var nextButton = $('#videocarousel-next');

            if(nextItem.attr('id') != 'videocarousel-next')
            {
                $('.jcarousel-control a').removeClass('on');
                nextItem.addClass('on');
                carousel.scroll(pagination); 

                if(nextPage == VideoCarousel.pages) nextButton.css('color', '#dddddd').css('cursor', 'default');
                else nextButton.css('color', '#971227').css('cursor', 'pointer');
            }


            return false;
        }); 

        $('#videocarousel-show-all').bind('click', function() {
            $('.jcarousel-control a').removeClass('on');
            $('.jcarousel-list').css('width', '660px').css('left', '0'); 
            $('.jcarousel-control').remove();

            return false;
        }); 

    }
}



/*
 *  methods to run on DOM ready
 */
$(document).ready(function()
{
    SIFR.init();
    ProductHover.init();
    ProductTabs.init();
    Buttons.init();
    SignUpQuestions.init();

    if ( $('#videocarousel').length > 0 ) VideoCarousel.init();
});

/*
 *	detach all handlers
 */
$(window).unload(function(){
    $("*").unbind();
});
