/*
 *  Fix IE background image flicker (via http://www.mister-pixel.com/)
 */
try {
	document.execCommand('BackgroundImageCache', false, true);
} catch(e) {}

/*
 * Cookie Handling
 */
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);
}

/*
 *	sIFR
 */
var SIFR = {
	init: function()
	{
		if (typeof sIFR != "function") return;
		
        sIFR.replaceElement(".men #copy h1, .women #copy h1, .family #copy h1, .holidays #copy h1, .snacking #copy h1", named({sFlashSrc: "flash/friz-quadrata-bold.swf", sColor: "#93BA2B", sWmode: "transparent"}));
        sIFR.replaceElement(".men #copy h2, .women #copy h2, .family #copy h2, .holidays #copy h2, .snacking #copy h2", named({sFlashSrc: "flash/friz-quadrata-bold.swf", sColor: "#FF6D00", sWmode: "transparent"}));
        sIFR.replaceElement("#copy h1", named({sFlashSrc: "flash/friz-quadrata-bold.swf", sColor: "#FF6D00", sWmode: "transparent"}));
        sIFR.replaceElement(".tips #copy h2, .tips #copy h3", named({sFlashSrc: "flash/friz-quadrata-bold.swf", sColor: "#93BA2B", sWmode: "transparent"}));
        sIFR.replaceElement(".about #copy h2", named({sFlashSrc: "flash/friz-quadrata-bold.swf", sColor: "#93BA2B", sWmode: "transparent"}));
	}
};

/*
 *  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();
			}
		});
	}
};

/*
 *  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, .paging ul li a, #sign-up a, #send a, #submit a")
        .hover(thisClass.showOverImage(), thisClass.showOffImage())
        .focus(thisClass.showOverImage())
        .blur(thisClass.showOffImage());
        
        $("#overview ul 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;
        });
        
        // expand/collapse
        $("#site-map li ul").hide();
        $("#site-map li:has(ul)").prepend("<strong class=\"col\">Collapsed</strong> ").addClass("parent");
        $("#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%")});
    }
};

/*
 * 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');
    }
}

/*
 *  methods to run on DOM ready
 */
$(document).ready(function()
{
	SIFR.init();
	ProductHover.init();
	ProductTabs.init();
	Buttons.init();
	SignUpQuestions.init();
});

/*
 *	detach all handlers
 */
$(window).unload(function(){
    $("*").unbind();
});