$(document).ready(function() {
    valve.init();
	if ($('body').hasClass('people')) {
        people.init();
    };
    if ($('body').hasClass('careers')) {
        $('article.career-item a').fancybox({
            overlayShow: true,
            overlayColor: '#000',
            overlayOpacity: 0.7,
            title: false,
            autoDimensions: true,
            scrolling: 'no',
            padding: 48

        });
    };
    if ($('body').hasClass('work')) {
        $('a.fancybox').fancybox({
            autoDimensions: true,
            overlayShow: true,
            overlayColor: '#000',
            overlayOpacity: 0.7,
            scrolling: 'no',
            padding: 32,
            margin: 0,
            title: false,
            onCleanup: function() {
                var current = $('#case_scroll article.active'); 
                current.find('.case-fancybox-wrap').html($('#fancybox-content').children().html());
            }
        });
    };

    $('#open_showreel').fancybox({
        overlayShow: true,
        overlayColor: '#000',
        overlayOpacity: 1,
        scrolling: 'no',
        modal: false,
        width: 600,
        height: 338,
        padding: 0,
        margin: 0
    });

});

window.log = function(text) {
    if (this.console) {
        console.log(text);
    };
};

var valve = {
    
    slider : undefined,
    $scroll : undefined,
    prev_step : undefined,
    max_left : undefined,
    resizeTimer : undefined,
    scrollDirection : 0,
    scrollCounter : 0,
    scrollTimer : undefined,
    useCufon : false,
    workScrollTimer : undefined,
    addEventHandlers : function() {
        if (!$('body').hasClass('home')) {
            $('.scroll article').click($.proxy(this.articleClick, this));
        };
        if ($('body').hasClass('work')) {
            $('a.fancy_left').live('click', $.proxy(this.casePrev, this));
            $('a.fancy_right').live('click', $.proxy(this.caseNext, this));
            $(window).scroll($.proxy(function() {
                clearTimeout(this.workScrollTimer);
                this.workScrollTimer = setTimeout($.proxy(this.workScroll, this), 400);
            }, this));
        };
        
        ;
        $(window).resize($.proxy(function() {
            clearTimeout(this.resizeTimer);
            this.resizeTimer = setTimeout($.proxy(this.resize, this), 500);
        }, this));

        $(window).keydown($.proxy(this.keyHandler, this));
/*
        if (this.$scroll !== undefined) {
            this.$scroll.bind('mousewheel', $.proxy(function(event, delta, deltaX, deltaY) {
                var current, direction;

                if (this.scrollTimer === undefined) {
                    this.scrollHandler(event, delta, deltaX, deltaY);
                };

                if (this.scrollCounter == 0) {
                    this.scrollCounter = 1;

                    this.scrollTimer = setTimeout($.proxy(function() {
                        if (this.scrollCounter > 3) {
                            this.scrollHandler(event, delta, deltaX, deltaY);
                        };
                        this.scrollCounter = 0;
                        this.scrollTimer = undefined;
                    }, this), 100);

                    
                } else {
                    this.scrollCounter += 1;
                };
                
                current = this.getSliderStep();
                direction = delta > 0? -1 : 1;

                if (current + direction + 1 > 0 && current + direction + 1 <= this.slider.steps) {
                    return false;
                };

            }, this));
          
          
          */
//          $.proxy(this.scrollHandler, this));
        
    },

    addContentNavigation : function() {
        var $navigation = $('#main .content_navigation');

        if ($navigation.length == 0) {
            return;
        };

        $navigation.show();
        $navigation.find('a').bind('click', $.proxy(function(event) {
            var el = $(event.currentTarget),
                filtered, i, l,
                delay = 0,
                is_people_or_career_page = $('body').hasClass('people') || $('body').hasClass('careers');
            
            if (el.hasClass('active')) {
                return false;
            };

            if (this.$scroll === undefined) {
                this.$scroll = $('#main .scroll');
            };
            
            filter = el.data('filter'),
            only_scroll = el.hasClass('only_scroll');
            
            if (only_scroll) {
                $('#' + filter).click();
                return false;
            };

            this.$scroll.find('article.active').removeClass('active');
            
            if (filter === 'all') {
                filtered = this.$scroll.find('article');
            } else {
                filtered = this.$scroll.find('article.'+filter);
            };

            this.$scroll.find('article').hide();
            
            for (i = 0, l = filtered.length; i < l; i++) {
                $(filtered[i]).delay(delay).fadeTo(100, is_people_or_career_page?1:0.5);
                delay += 50;
            };

            filtered.first().addClass('active').fadeTo(100, 1);
            
            this.addScroll();
            this.updateContentNavigation(filter);
            this.updateMaxLeft();
            return false;
        }, this));
    },

    caseNext : function(event) {
        var current = $('#case_scroll article.active'),
        next, 
        fancybox = $('#fancybox-wrap');
        fancybox.data('protected', true);

        next = current.next(),

        next.click();
        $.fancybox.showActivity();

        current.find('.case-fancybox-wrap').html($('#fancybox-content').children().html());
        $('#fancybox-content').children().html(next.find('.case-fancybox'));
        $.fancybox.resize();
        $.fancybox.hideActivity();
        fancybox.data('protected', false);

        if (next.nextAll().length == 0) {
            $('a.fancy_next').hide();
        } else {
            $('a.fancy_next').show();
        };

        return false;
    },

    casePrev : function(event) {
        var current = $('#case_scroll article.active'),
        prev,
        fancybox = $('#fancybox-wrap');
        prev = $('#case_scroll article.active').prev();
        fancybox.data('protected', true);
        prev.click();
        $.fancybox.showActivity();

        current.find('.case-fancybox-wrap').html($('#fancybox-content').children().html());
        $('#fancybox-content').children().html(prev.find('.case-fancybox'));
        $.fancybox.resize();
        $.fancybox.hideActivity();

        if (prev.prevAll().length == 0) {
            $('a.fancy_prev').hide();
        } else {
            $('a.fancy_prev').show();
        };

        fancybox.data('protected', false);
        return false;
    },

    genericScroll : function(x, y) {
        
        if (this.slider === undefined) {
            return;
        };
        var new_step = Math.round(x * (this.slider.steps - 1)) + 1,
            left, company_page = $('body').hasClass('company');
                
        new_step = Math.min(this.slider.steps, new_step);

        if (new_step != this.prev_step) {
            if (company_page) {
                left = -1 * (new_step - 1) * 930;
            } else {
                left = -1 * (new_step - 1) * 720;
            };

            if ($('html').hasClass('csstransitions')) {
                this.$scroll.stopCssAnimation();
                this.$scroll.animateWithCss({left: left}, this.slider.speed * 1000, "ease-in-out");
            } else {
                this.$scroll.stop();
                this.$scroll.animate({left: left}, this.slider.speed * 2000, "easieEaseInOut");
            };
            this.$scroll.children().removeClass('active');
            
            this.prev_step = new_step;
            this.updateContentNavigation(new_step);
            $('article:visible', this.$scroll).each(function(i) {
                if (i == new_step -1) {
                    $(this).addClass('active');
                    return false;
                };
            });
        };
    },

    peopleScroll : function(x, y) {
        if (this.slider === undefined) {
            return;
        };
        var left, targetLeft, speed;

        if (this.slider.dragging) {
            targetLeft = x * (this.slider.steps - 1) * -182;
        } else {
            targetLeft = -1 * this.slider.value.target[0] * (this.slider.steps - 1) * 182;
        };
        
        targetLeft = Math.max(targetLeft, this.max_left);

        left = this.$scroll.css('left');
        if (left === 'auto') {
            left = 0;
        } else {
            left = left.substr(0, left.length - 2);
            left = parseInt(left, 10);
        };

        speed = Math.max(200, Math.min(750, Math.round(this.slider.speed * 3 * Math.abs(targetLeft - left))));

        if (this.slider.dragging && left != targetLeft) {
            this.$scroll.stop()
                        .animate({left: targetLeft}, speed, "easieEaseOutQuad");
//            this.$scroll.stopCssAnimation();
//            this.$scroll.animateWithCss({left: targetLeft}, speed, "ease-out");
        } else {
            if (!this.$scroll.data('animating') && targetLeft != left) {
                this.$scroll.stop()
                            .data('animating', true)
                            .animate({left: targetLeft}, speed, "easieEaseOutQuad", $.proxy(function() {
                                this.$scroll.data('animating', false); 
                            }, this));
            };
        };
    },

    homeScroll : function(x, y) {
         if (this.slider === undefined) {
            return;
        };

        var left = -1 * x * Math.abs($('html').width() - 1084 - 260);

        this.$scroll.stop()
                    .animate({left: left }, 340, "easieEaseOutQuad");
    },

    addScroll : function() {
        var slider_id = $('#main .dragdealer').attr('id'),
            steps = $('#main .scroll').children(':visible').length,
            speed, 
            people_page = $('body').hasClass('people'),
            careers_page = $('body').hasClass('careers'),
            home_page = $('body').hasClass('home'),
            callback;
        
        if (people_page) {
            steps = steps - Math.floor(($('html').width() - 260 - 182) / 182) + 1;
        };

        if (careers_page) {
            steps = steps - Math.floor(($('html').width() - 260 - 394) / 178);
        };

        if (home_page && $('html').width() > 1344) {
            steps = 1;
        };

        this.prev_step = 1;
        
        if (this.$scroll === undefined) {
            this.$scroll = $('#main .scroll');
        };

        if (this.slider !== undefined) {
            delete(this.slider);
            $('#main div.handle').removeAttr('style');
            if (this.$scroll.css('left') !== '0px') {
                this.$scroll.stopCssAnimation();
                this.$scroll.animate({left: 0}, 375);
            };
        };

        if (steps <= 1) {
            $('#main .dragdealer').hide();
            return;
        } else {
            $('#main .dragdealer').show();   
        };

        if (slider_id == '') {
            slider_id = 'drag_' + String( Math.round(Math.random() * 1000));
            $('#main .dragdealer').attr('id', slider_id);
        };

        /* speed from 15 to 40 with elements 10+ to 2 */
        speed = Math.min(40, Math.max(15, Math.round( 1 / steps * 62.5 + 8.75)));
        
        if (people_page || careers_page) {
            callback = this.peopleScroll;
        } else if (home_page) {
            callback = this.homeScroll;
        } else {
            callback = this.genericScroll;   
        };

        this.slider = new Dragdealer(slider_id, {
            steps: (home_page?0:steps),
            speed: speed,
            loose: (people_page || careers_page?false:true),
            slide: (people_page || careers_page?false:true),
            snap: false,
            animationCallback: $.proxy(callback, this)
        });

        /* first animate call is always istantaneous so let's get it over with */
        this.$scroll.stopCssAnimation();
        this.$scroll.animateWithCss({left: 0}, 0);
    },

    articleClick : function(event) {
        var index = $(event.currentTarget).prevAll(':visible').length + 1;

        if (!$('#fancybox-wrap').data('protected')) {
            $.fancybox.close();
        };

        if (this.slider !== undefined) {
            this.slider.setStep(index, 0, false);
        };

        event.stopPropagation();
    },

    getSliderStep : function() {
        var current, value, i, l;
        value = this.slider.value.target[0];
        for (i=0, l=this.slider.steps; i < l; i++) {
            if (this.slider.stepRatios[i] == value) {
                current = i;
                break;
            };
        };

        return current;
    },

    keyHandler : function(event) {
        
        var direction,l,current;
        if (this.slider === undefined || !$('.dragdealer .handle').is(':visible')) {
            
            return;
        };

        /* left arrow key */
        if (event.keyCode == '37') {
            direction = -1;
        } else if (event.keyCode == '39') {
            /* right arrow key */
            direction = 1;
        } else {
            return;   
        };
    
        current = this.getSliderStep();    
        if (current === undefined) {
            event.preventDefault();
            return;
        };

        if (current + direction >= 0 && current + direction <= this.slider.steps) {
            this.slider.setStep(current + direction + 1, 0, false);
        };
        event.preventDefault();
    },
/*
    loadPage : function(event) {
        var href = $(event.currentTarget);
        
        $.get(href)
            .complete(function() {
                this.addScroll();
                this.addContentNavigation();
            });
        
        event.preventDefault();
    },*/

    peopleFinder : function() {
        var found = false, pos, hash = window.location.hash, persons = [];

        if (hash) {
            hash = hash.substring(1);
            $('.scroll').find('article').each($.proxy(function(i, el) {
                if ($(el).data('nicename') == hash) {
                    pos = $(el).prevAll().length + 1;
                
                    this.slider.setStep(pos, 0, false);
                    found = true;
                    return false;
                };
            }, this));

            if (!found) {
                $('.scroll').find('article').each(function(i, el) {
                    if ($(el).data('firstname') == hash || $(el).data('display') == hash) {
                        persons.push(el);
                    };
                });

                if (persons.length == 1) {
                    pos = $(persons[0]).prevAll().length + 1;
                    this.slider.setStep(pos, 0, false);
                };
            };
        };
    },

    resize : function() {
        var left = this.$scroll.css('left'),
            old_max_left = this.max_left;
        if (left != 'auto') {
            left = left.substring(0, left.length - 2);
            left = parseInt(left, 10);
        } else {
            left = 0;
        };

        this.updateMaxLeft();


        if (this.max_left < 0 && (left < this.max_left || (Math.abs(old_max_left - left) <= 56) && left !=0)) {
            this.$scroll.animate({left: this.max_left}, 500, "easieEaseOutQuad");
        };

        if (this.max_left > 0 || (this.max_left < 0 && $('.dragdealer:visible').length == 0)) {
            this.addScroll();
        };
    },

    scrollHandler : function(event, delta, deltaX, deltaY) {
        var direction = 0, current;
/*
        if (delta > 0 && this.scrollDirection > 0) {
            direction = -1;
        };

        if (delta < 0 && this.scrollDirection < 0) {
            direction = 1;
        };
        */
        direction = delta > 0? -1: 1;
        this.scrollDirection = delta;

        current = this.getSliderStep();

        if (current + direction + 1 > 0 && current + direction + 1 <= this.slider.steps) {
            this.slider.setStep(current + direction + 1, 0);
            return false;
        };

        if (direction == 0) {
            return false;
        };
    },

    updateContentNavigation : function(filter) {
		function selectedNaviItem(){
			Cufon.replace($(this),{fontFamily: 'ITCAvantGardeBook',color:'#9B9B9B'});
		}
        var i = 1,
        isNumber = filter - 0 === filter;
        $('#main .content_navigation').find('a').each(function() {
		 $(this).bind('mouseleave', selectedNaviItem);
            if (isNumber && $(this).data('filter') == 'all' && $(this).hasClass('active')) {
                return false;
            };
            if ($(this).data('filter') === filter || i === filter) {
                $('#main .content_navigation a').removeClass('active');
				
               $(this).bind('mouseleave', selectedNaviItem);
				
				$(this).addClass('active');
				$(this).unbind('mouseleave');
            };
            i++;
        });

        if (this.useCufon) {
            Cufon.refresh('ul.content_navigation li a');
        };
    },

    updateMaxLeft : function() {
        if (!$('body').hasClass('people') && !$('body').hasClass('careers')
            && !$('body').hasClass('home')) {
            return;
        }
        var width = 0;
        this.$scroll.children(':visible').each(function() {
            width += $(this).width() + 24;
        });

        /* careers page has a wider text + margin in the beginning */
        if ($('body').hasClass('careers')) {
            width += 36;
        };
        if ($('body').hasClass('home')) {
            width += 20;
        };
        this.$scroll.width(width);

        // 260px = sidebar + scroll padding, 56px = scroll padding to right too
        this.max_left = -1 * this.$scroll.width() + $('html').width() - 260 - 56;
    },

    workScroll : function() {
        if ($('#fancybox-wrap').is(':visible'));
        var t = $(window).scrollTop();
//        t= t.substring(0, t.length -2);
        $('#fancybox-close').animate({top: t + 10}, 100);
        $('a.fancy_right').animate({top: t + 200}, 100);
        $('a.fancy_right').animate({top: t + 200}, 100);
    },

    init : function() {
        if (!$('#main').hasClass('blog')) {
            this.addContentNavigation();
            this.addScroll();
            this.updateMaxLeft();
            this.addEventHandlers();
        };

        if ($('body').hasClass('people')) {
            this.peopleFinder();
        };

//        if ($.browser.msie) {
            this.useCufon = true;
  //      };

        if (this.useCufon) {
            Cufon.replace('h1', {fontFamily: 'ITCAvantGardeBook'});
            Cufon.replace('.avantgarde', {fontFamily: 'ITCAvantGardeBook'});
            Cufon.replace('.scroll h2', {fontFamily: 'ITCAvantGardeBook'});
   	        Cufon.replace('article h1', {fontFamily: 'ITCAvantGardeBook'});
            Cufon.replace('ul.content_navigation li a', {fontFamily: 'ITCAvantGardeBook'});
            Cufon.replace('.widget_nav_menu ul li a', {fontFamily: 'ITCAvantGardeBook'});
            Cufon.replace('.career-fancybox h1 a', {fontFamily: 'ITCAvantGardeBook'});
			
			
			function naviOver(){
				
				if(!$(this).hasClass("active"))	{
					
					Cufon.replace($(this),{fontFamily: 'ITCAvantGardeBook',color:'#ffffff'});	
			
				}
				
			}

			function naviOut(){
				if(!$(this).hasClass("active"))	{
					Cufon.replace($(this),{fontFamily: 'ITCAvantGardeBook',color:'#9B9B9B'});
		
				}
			}
			
			$('.widget_nav_menu ul li:not(.current_page_item) a, ul.content_navigation li a').each(function() {
			 $(this).bind('mouseleave', naviOut);
			 $(this).bind('mouseenter', naviOver);
			});
			
			
			
			
        };

        Cufon.replace('article.drip p.content', {fontFamily: 'AGaramondPro'});
    }
};

var people = {

	init: function() {

    }
};

