var JacobyApp = function () {
    var bgImage,
        activePage,
        activeSubnav,
        projectType,
        navCookie,
        maxWidth = 0,
        speed = 1.5, // Lower is faster

        init = function () {
            bgImage = $('.bg-img');
            activePage = $('#active-page').val();
            activeSubnav = $('input#active-subnav').val();
            projectType = $('#active-projectType').val();
            navCookie = 'Jacoby_cNav';

            $('body').height(45 + ($(document).height() - $('#footer').height()));
            //adjustMain();

            setActivePage();
            setupScrollables();
            setupBranchAnimations();

            //$(window).resize(function () { resizeWindow() });
        },

        setActivePage = function () { // Adjust body class, header and project navigation elements

            switch (projectType) {
                case '0':
                    $('#nav li.projects li.first>a').addClass('active');
                    break;
                case '1':
                    $('#nav li.projects li.second>a').addClass('active');
                    break;
                case '2':
                    $('#nav li.projects li.third>a').addClass('active');
                    break;
                case '3':
                    $('#nav li.projects li.fourth>a').addClass('active');
                    break;
                default:
                    break;
            }

            if (activePage) {
                var bodyCache = $('body');
                bodyCache.removeClass('home');
                bodyCache.addClass(activePage);

                if (!bodyCache.hasClass('home')) {
                    $('#nav li').addClass('inactive'); // Don't set inactive on home page
                } else {
                    $.cookie(navCookie, null); // Reset active category cookie on home page
                }

                $('#nav li.' + activePage).removeClass('inactive').addClass('active');
            }

            if (activeSubnav) {
                $('#nav .nav-' + activeSubnav).addClass('active');
                $('#main').addClass(activeSubnav);
            }
        },

        setupScrollables = function () {
            $('.nav').each(function () {
                var nav = $(this),
                    scrollable = nav.siblings('.scrollable');

                nav.find('.of').text(pad(scrollable.find('.items div').length, 2));

                nav.find('a').click(function () {
                    var current = nav.find('.current'),
                        of = nav.find('.of');

                    if ($(this).hasClass('prev') && current.text() != '01') {
                        current.text(pad(parseInt(current.text()) - 1, 2));
                    } else if ($(this).hasClass('next') && current.text() != of.text()) {
                        current.text(pad(parseInt(current.text()) + 1, 2));
                    }

                    scrollable.find('.scroll').each(function () {
                        $(this).animate({ scrollTop: 0 }, 400);
                    });
                });
            });

            $('.tree .scrollable').scrollable({
                speed: 0,
                onSeek: function () {
                    $('.tree .scrollable').animate({ 'opacity': '1' }, 200);
                }
            });

            $('.thumbs .scrollable').scrollable();

            $('.scroll-nav a').click(function (e) {
                e.preventDefault();
                var scrollNav = $(this).parent('.scroll-nav');
                var scroll = scrollNav.parent('.scroller, .section').find('.scroll');
                var distance = scroll.height() / 3;
                var newTop = scroll.scrollTop();
                switch ($(this).attr('href')) {
                    case 'up':
                        newTop -= distance;
                        break;
                    case 'down':
                        newTop += distance;
                        break;
                }
                scroll.each(function () {
                    //console.log(this);
                    $(this).animate({ scrollTop: newTop }, distance * 2);
                });
            });
        },

        setupBranchAnimations = function () {
            $('#nav>li .tree .branch, #nav>li .tree .branch .sub-branch, #nav>li .tree .branch li a').css('display', 'none');

            $('#nav>li').each(function () {
                var li = $(this);
                if (li.hasClass('active')) {
                    showSubMenu(li.find('>a'), true);
                }
            });


            $('body.home #main a[href="toggle"]').click(function (e) {
                e.preventDefault();
                if ($(this).text() === '-') {
                    $(this).text('+');
                } else {
                    $(this).text('-');
                }

                $('#main').find('.section').slideToggle();
            });

            $('body.home #nav>li').hover(
		        function () {
		            $('.bg-img').stop().animate({ opacity: 0.5 }, 400);
		            $(this).css({
		                '-moz-transform': 'scale(1)',
		                '-ms-transform': 'scale(1)',
		                '-o-transform': 'scale(1)',
		                '-webkit-transform': 'scale(1)',
		                'transform': 'scale(1)',
		                'margin-top': '-8px'
		            });
		            $(this).find('.tree').css({
		                '-moz-transform': 'scale(1)',
		                '-ms-transform': 'scale(1)',
		                '-o-transform': 'scale(1)',
		                '-webkit-transform': 'scale(1)',
		                'transform': 'scale(1)',
		                'margin-top': '',
		                'margin-left': ''
		            });
		            showSubMenu($(this).find('>a'));
		        },
		        function () {
		            $('.bg-img').stop().animate({ opacity: 1 }, 400);
		            $(this).css({
		                '-moz-transform': 'scale(0.883)',
		                '-ms-transform': 'scale(0.883)',
		                '-o-transform': 'scale(0.883)',
		                '-webkit-transform': 'scale(0.883)',
		                'transform': 'scale(0.883)',
		                'margin-top': '-17px'
		            });
		            $(this).find('.tree').css({
		                '-moz-transform': 'scale(1.13)',
		                '-ms-transform': 'scale(1.13)',
		                '-o-transform': 'scale(1.13)',
		                '-webkit-transform': 'scale(1.13)',
		                'transform': 'scale(1.13)'
		            });
		            if (!$.browser.msie) {
		                $(this).find('.tree').css({
		                    'margin-top': '17px',
		                    'margin-left': '9px'
		                });
		            } else {
		                $(this).find('.tree').css({
		                    'margin-top': '9px'
		                });
		            }
		            hideSubMenu($(this).find('>a'));
		        }
	        );
        },

        resizeWindow = function () {
            $('#window-width').html($(window).width());
            adjustMain();
        },

        getCursorPosition = function (e) {
            e = e || window.event;
            var cursor = { x: 0, y: 0 };
            if (e.pageX || e.pageY) {
                cursor.x = e.pageX;
                cursor.y = e.pageY;
            }
            else {
                var de = document.documentElement;
                var b = document.body;
                cursor.x = e.clientX +
            (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
                cursor.y = e.clientY +
            (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
            }
            return cursor;
        },

        showSubMenu = function (a, showSub) {
            var item = $(a).parent('li');
            if (!item.hasClass('open')) {
                var tree = $(item).find('.tree');
                var branch1 = tree.find('>.branch');
                branch2 = branch1.find('>.branch');

                tree.css('display', 'block');
                tree.find('*:not(.sub-branch .branch)').css({ 'width': '', 'height': '', 'display': '' });
                //tree.find('ol>li a').css({ opacity: 0, display: 'block' });
                var oldWidth = branch1.width();
                var oldHeight = branch1.height();

                tree.find('*').css({
                    'overflow': '',
                    'overflow-x': '',
                    'overflow-y': ''
                });


                //  Don't animate menus on sub-category pages if category is already active
                var navCookie = 'Jacoby_cNav',
                    activePage = $('input#active-page').val(),
                    activeCat = $.cookie(navCookie);

                if (activePage != 'home' && activePage && activeCat && activeCat === activePage) {
                    item.find('.sub-branch').each(function () {
                        showSubNav(this);
                        item.addClass('open');
                    });
                    return; // Stop animation
                } else if (activePage != 'home' &&  $.cookie(navCookie) != activePage) {
                    $.cookie(navCookie, activePage);
                }


                item.find('.branch').css('display', 'none');
                branch1.css({ 'width': '0px' })
		        .slideDown(oldHeight * speed, 'linear', function () {
		            branch1.animate({ 'width': oldWidth + 'px' }, oldWidth * speed, 'linear', function () {
		                branch2.css({ 'width': '', 'height': '' });
		                oldWidth = branch2.width();
		                oldHeight = branch2.height();
		                branch2.css({ 'width': '0px', 'height': '0px', 'display': 'block' })
					        .animate({ 'height': '5px' }, oldHeight * speed, 'linear', function () {
					            branch2.animate({ 'width': oldWidth + 'px' }, oldWidth * speed, 'linear', function () {
					                branch2.find('ol').css('display', 'block');
					                branch2.find('ol>li').each(function (i) {
					                    var li = $(this);
					                    var branch3 = li.find('>.branch');
					                    oldWidth = branch3.width();
					                    oldHeight = branch3.height();
					                    branch3.css({ 'width': '0px', 'height': '0px' })
								        .delay(i * (speed * 100))
								        .css('display', 'block')
								        .animate({ 'height': oldHeight + 'px' }, oldHeight * speed, 'linear', function () {
								            branch3.animate({ 'width': oldWidth + 'px' }, oldWidth * speed, 'linear', function () {
								                li.find('>a:first').animate({ opacity: 1 }, 500, function () {
								                    if ($(this).hasClass('active') && showSub) {
								                        showSubNav(this);
								                    }
								                });
								                item.addClass('open');
								            });
								        });
					                });
					            });
					        });
		            });
		        });
            }
        },

        hideSubMenu = function (a) {
            var item = $(a).parent('li');
            item.removeClass('open');
            item.find('*:animated').stop();
            item.find('*').css({ opacity: '' });
            item.find('.tree').stop().fadeOut(400, function () {
                item.find('.tree *:not(.sub-branch .branch)').css({ 'width': '', 'height': '', 'display': '', 'opacity': '' });
                item.find('ol>li>a').css('display', 'none');
            });
        },

        showSubNav = function (a) {
            a = $(a);
            var item = a.parent('li');
            var old = item.parents('ol').find('>li>a.active').parent('li');

            if (!item.hasClass('open')) {

                var sub = item.find('.sub-branch');
                var branch = sub.find('>.branch');
                old.find('>a').removeClass('active');
                var oldSub = old.find('.sub-branch');
                oldSub.fadeOut(500);

                a.addClass('active');
                sub.find('*:not(.branch, .scrollable, span)').css('display', 'block');
                sub.find('.branch').css('display', 'none');
                sub.find('.nav a, .nav span').css('display', 'initial');
                sub.slideDown(speed * 100, 'linear', function () {
        	        sub.find('.branch').fadeIn();
        	        var div = sub.find('.scrollable');
        	        var oldHeight = div.height();
        	        div.slideDown((oldHeight * speed) / 2, 'linear');

        	        //updates project sub nav slider
        	        try {
        	            if (isProject) {
        	                //$.cookie('Jacoby_cNav', null); // Expire the active category cookie
        			        updateProjectSubNav(); //called method in _subProjects.cshtml 
        		        }
        	        } catch (e) {

        	        }
                });
            }
        }
        
        adjustMain = function(){
            var main = $('#main');

            if ($(window).width() > maxWidth) {
                main.removeAttr('style');
            }

            if (main.offset().left <= 300) {
                main.css({ 'margin': '185px 0 25px 300px' });
                maxWidth = $(window).width();
            }

            if ($('body').hasClass('projects')) {
                main.css({ 'margin': '55px 0 25px 300px' });
            }
        };

    return {
        init: init
    }
}

$(function () {

    var app = new JacobyApp();
    app.init();

    var $bgImage = $('.bg-img'),
        $body = $('body'),
        activePage = $('input#active-page').val(),
        navCookie = 'Jacoby_cNav';

});

//function adjustFooter() {
//    if ($(window).height() < ($(document).height())) {
//        $('#footer').css({ 'position': 'absolute', 'top': $(document).height() - $('#footer').height() });
//    } else {
//        $('#footer').css({ 'position': 'fixed', 'top': 'auto' });
//    }
//}

jQuery.fn.css2 = jQuery.fn.css;
jQuery.fn.css = function () {
    if (arguments.length) return jQuery.fn.css2.apply(this, arguments);
    var attr = ['font-family', 'font-size', 'font-weight', 'font-style', 'color',
        'text-transform', 'text-decoration', 'letter-spacing', 'word-spacing',
        'line-height', 'text-align', 'vertical-align', 'direction', 'background-color',
        'background-image', 'background-repeat', 'background-position',
        'background-attachment', 'opacity', 'width', 'height', 'top', 'right', 'bottom',
        'left', 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
        'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
        'border-top-width', 'border-right-width', 'border-bottom-width',
        'border-left-width', 'border-top-color', 'border-right-color',
        'border-bottom-color', 'border-left-color', 'border-top-style',
        'border-right-style', 'border-bottom-style', 'border-left-style', 'position',
        'display', 'visibility', 'z-index', 'overflow-x', 'overflow-y', 'white-space',
        'clip', 'float', 'clear', 'cursor', 'list-style-image', 'list-style-position',
        'list-style-type', 'marker-offset'];
    var len = attr.length, obj = {};
    for (var i = 0; i < len; i++)
        obj[attr[i]] = jQuery.fn.css2.call(this, attr[i]);
    return obj;
}

function pad(number, length) {
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }

    return str;
}
