var Site = {
    init: function () {
        Site.mainNav();
        if ($('.ourBreadNav').length > 0) {
            Site.ourBreadNav();
        }
        if ($('.productScroll').length > 0) {
            Site.productScroll();
        }
        if ($('.recipePage').length > 0) {
            Site.recipeToolBar();
        }
        if ($('.sectionNav').length > 0) {
            Site.sectionNav();
        }
        if ($('.breadPage').length > 0) {
            Site.nutritionPopUp();
        }
    },
    mainNav: function () {
        var activeInterval;
        var navOver = false;
        $('.mainNav ul.topNav li.mainNavItem').each(function () {
            var hideInterval;
            var self = $(this);
            var over = false;
            var link = $(this).children('a')[0];
            var box = $(this).children('.dd');
            var delay = 200;
            if ($(link).hasClass('active')) {
                $(self).children('.leftShadow').show();
                $(self).children('.rightShadow').show();
            }
            $(link).mouseover(function () { openDropDown(); over = true; navOver = true; });
            $(this).mouseover(function () { clearTimeout(hideInterval); clearTimeout(activeInterval); over = true; navOver = true; });
            $(this).mouseout(function () { hideInterval = setTimeout(closeDropDown, delay); over = false; navOver = false; });

            function openDropDown() {
                $(box).slideDown();
                if ($(link).hasClass('active')) {
                    $(self).children('.leftShadow').hide();
                    $(self).children('.rightShadow').hide();
                    $(link).removeClass('otherOver');
                    $(link).addClass('activeOver');
                } else {
                    $(link).addClass('regOver');
                    $('.mainNav ul.topNav li a.active').addClass('otherOver');
                    $('.mainNav ul.topNav li a.active').parent('li').children('.leftShadow').hide();
                    $('.mainNav ul.topNav li a.active').parent('li').children('.rightShadow').hide();

                }
            }
            function closeDropDown() {
                if (over === false) {
                    if ($(self).hasClass('home')) {
                        $(link).removeClass('regOver');
                        activeInterval = setTimeout(restateActiveItem, delay);
                    } else {
                        $(box).slideUp('normal', function () {
                            $(link).removeClass('regOver');
                            activeInterval = setTimeout(restateActiveItem, delay);
                        });
                    }
                }
            }
            function restateActiveItem() {
                if (navOver === false) {
                    $('.mainNav ul.topNav li a').each(function () {
                        if ($(this).hasClass('activeOver')) {
                            $(this).parent('li').children('.leftShadow').show();
                            $(this).parent('li').children('.rightShadow').show();
                            $(this).removeClass('activeOver');
                        }
                        if ($(this).hasClass('otherOver')) {
                            $(this).removeClass('otherOver');
                            $(this).parent('li').children('.leftShadow').show();
                            $(this).parent('li').children('.rightShadow').show();
                        }
                    });
                }
            }
        });
    },
    ourBreadNav: function () {
        /*if opened or closed*/
        $('ul.tierOne li a').each(function () {
            if ($(this).hasClass('closed')) {
                $(this).parent('li').children('ul').css('display', 'none');
            }
        });
        $('ul.tierOne li a.closed').toggle(function () {
            $(this).addClass('open');
            $(this).parent('li').children('ul').slideDown();
        }, function () {
            $(this).removeClass('open');
            $(this).parent('li').children('ul').slideUp();
        });
    },
    sectionNav: function () {
        var img1;
        $('.sectionNav li a').hover(function () {
            if (!$(this).hasClass('selected')) {
                img1 = $(this).children('img')[0];
                $(img1).hide();
            }
        }, function () {
            if (!$(this).hasClass('selected')) {
                $(img1).show();
            }
        });
        $('.sectionNav li.selected a').each(function () {
            img1 = $(this).children('img')[0];
            $(img1).hide();
        });
    },
    productScroll: function () {
        var scrollAmout = 412;
        var maxScrolls = Math.ceil($('.productScroll ul li').length / 4) - 1;
        var numOfScrolls = 0;

        var currentProduct = $('ul.products li.product').first();
        var selected;
        var index;
        var firstDone = false;
        /*check hash*/
        var hash = window.location.hash;
        if (hash) {
            var thisId = 'list-' + hash.split('#')[1];
            var prodId = 'content-' + hash.split('#')[1];
            if (prodId === $(currentProduct).attr('id')) {
                $(currentProduct).fadeIn().animate({ left: 0 }, function () { firstDone = true; });
            } 
            selectBread($('#' + thisId));
            updateNav($('#' + thisId));
        } else {
            /*display first*/
            $(currentProduct).fadeIn().animate({ left: 0 }, function () { firstDone = true; });
        }
        /*determine scroll buttons showing*/
        if (!hash) {
            if ($('ul.products li.product').length > 4) {
                $('.productScroll a.downArrow').show();
            }
        }

        /*updateNav from hash*/
        function updateNav(thisObj) {
            var index = $(thisObj).parent('li').index() + 1;
            var length = $('.productScroll ul').children('li').length;
            var toScroll;
            for (var i = 0; i < length; i++) {
                if (index > (i * 4)) {
                    numOfScrolls = i;
                    toScroll = scrollAmout * numOfScrolls;
                }
            }

            if (numOfScrolls < maxScrolls) {
                $('.productScroll ul').animate({
                    top: -toScroll
                });
                $('.productScroll a.downArrow').show();
            } else if (numOfScrolls == maxScrolls) {
                $('.productScroll ul').animate({
                    top: -toScroll
                });
                $('.productScroll a.downArrow').hide();
            }

            if (numOfScrolls > 0) {
                $('.productScroll a.upArrow').show();
            }
        }
        /*selectBread*/
        function selectBread(thisObj) {
            if (!$(thisObj).hasClass('active')) {
                $('.productScroll ul li a').each(function () {
                    $(this).removeClass('active');
                });
                $(thisObj).addClass('active');
                index = $(thisObj).parent('li').index();

                if (BrowserDetect.browser === 'Explorer' && BrowserDetect.version <= 7) {
                    $(currentProduct).animate({ left: -625 }).hide();
                } else {
                    $(currentProduct).animate({ left: -625 }).fadeOut('fast');
                }
                for (var i = 0; i < $('ul.products li.product').length; i++) {
                    if (i === index) {
                        $('ul.products li.product').css({ left: 625 });
                        $('ul.products li.product:eq(' + i + ')').show().animate({ left: 0 });
                        currentProduct = $('ul.products li.product:eq(' + i + ')');
                    }
                }
            }
            firstDone = true;
        }

        function makeTopActive(num) {
            var index = ((4 * (num + 1)) - 4);
            $('.productScroll ul li:eq(' + index + ') a').each(function () {
                selectBread(this);
            });
        }
        function scrollDown() {
            numOfScrolls += 1;
            var toScroll = scrollAmout * numOfScrolls;
            if (numOfScrolls < maxScrolls) {
                $('.productScroll ul').animate({
                    top: -toScroll
                });
                makeTopActive(numOfScrolls);
            } else if (numOfScrolls == maxScrolls) {
                $('.productScroll ul').animate({
                    top: -toScroll
                });
                makeTopActive(numOfScrolls);
                $('.productScroll a.downArrow').hide();
            }
            if (numOfScrolls > 0) {
                $('.productScroll a.upArrow').show();
            }
        }
        function scrollUp() {
            numOfScrolls -= 1;
            var toScroll = scrollAmout * numOfScrolls;
            var offset = $('.productScroll ul').offset();
            if (numOfScrolls > 0) {
                $('.productScroll ul').animate({
                    top: -toScroll
                });
                makeTopActive(numOfScrolls);
                $('.productScroll a.downArrow').show();
            } else if (numOfScrolls == 0) {
                $('.productScroll ul').animate({
                    top: toScroll
                });
                makeTopActive(numOfScrolls);
                $('.productScroll a.upArrow').hide();
                $('.productScroll a.downArrow').show();
            }
        }
        /*events*/
        $('.productScroll ul li a').click(function () {
            if (firstDone === true) {
                selectBread(this);
            }
        });
        $('.productScroll a.upArrow').click(function () {
            scrollUp();
        });
        $('.productScroll a.downArrow').click(function () {
            scrollDown();
        });
    },
    recipeToolBar: function () {
        //popup
        $('ul.recipeToolBar li.email a').click(function () {
            var markup = '<div class="email-pop-wrap"><div class="email-pop"><div class="close"></div><div class="emailPopUp"><ul class="clearfix">' +
						'<li class="clearfix"><label>Your name:</label> <input id="sendEmailName"><p class="error">Please enter a your name.</p></li>' +
						'<li class="clearfix"><label>Recipient&#39;s email:</label> <input id="sendEmailEmail"><p class="error">Please enter a valid email address.</p></li>' +
						'<li class="clearfix"><label>Your message:</label>  <textarea id="sendEmailMessage"></textarea></li>' +
						'<li class="clearfix"><input type="submit" value="" class="sendBtn" onclick="Site.sendEmail();"></li>' +
						'</ul></div></div>' +
						'<div class="emailSent"><div class="close"></div><p class="txt">Thank you. Your email has been sent.</p><a class="closeBtn close" href="javascript:void(0);"></a></div>' +
						'</div>';
            $(markup).lightbox_me({
                modalCSS: { 'position': 'absolute', 'top': '330px' },
                overlayCSS: { background: 'transparent' },
                destroyOnClose: true
            });
        });
        //print function
        $('ul.recipeToolBar li.print a').click(function () { window.print() });
    },
    sendEmail: function () {
        function validateEmailForm() {
            var name = /\w+/.test($('#sendEmailName').val());
            var email = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
            if (!name) {
                $('#sendEmailName').parent('li').children('p.error').show();
                return false;
            } else {
                $('#sendEmailName').parent('li').children('p.error').hide();
            }
            if (!email.test($('#sendEmailEmail').val())) {
                $('#sendEmailEmail').parent('li').children('p.error').show();
                return false;
            } else {
                $('#sendEmailEmail').parent('li').children('p.error').hide();
            }
            $('.email-pop').hide();
            $('.emailSent').show();
            postEmail($('#sendEmailName').val(), $('#sendEmailEmail').val(), $('#sendEmailMessage').val());
        }
        function postEmail(name, email, message) {
            var page = window.location.href;
            var submittedEmailObj = {
                'name': name,
                'email': email,
                'message': message,
                'page': page
            }
            var url = '/services/EmailService.asmx/send';
            $.post(url, submittedEmailObj, function (data) { }, 'json');
        }
        validateEmailForm();
    },
    nutritionPopUp: function () {
        //add alternate background colors to list
        $('.nutrition-info .bottom ul').each(function () {
            $(this).children('li').each(function (i) {
                if (i % 2 == 0) {
                    color = '#ececec';
                } else {
                    color = '#ffffff';
                }
                $(this).css('background', color);
            });
        });
        //popup
        $('a.nutritionBtn').click(function () {
            var titleImg = $(this).parent('.leftContent').children('img')[0];
            var parent = $(this).parent('.leftContent');
            var nutrition = $(parent).children('.nutrition-info-wrap');
            //$('.nutrition-info h5.title').html($(titleImg).attr('alt'));
            var clone = $(nutrition).clone();
            $(clone).lightbox_me({
                overlayCSS: { background: 'transparent' },
                destroyOnClose: true
            });
        });
    }
}
$(Site.init);





var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]
};
BrowserDetect.init();

















