$(document).ready(function() {
    // virtual scrolling stuff
    var showTotal = 0;
    var page = 1;
    var loading = false;
    var allLoaded = false;
    var currentMode = 'grid';
    var controller = '';
    
    var doFade = function(force) {
        var items = $('li:not(.featured)', list);

        if(items.length == showTotal)
        {
            doneLoading();
            return;
        }

        var item = items.eq(showTotal);
        var img = $('img', item).get(0);

        if(typeof img == 'undefined' || img.complete || (typeof force != 'undefined' && force))
        {
            showTotal++;
            item.fadeIn(75, doFade);
        }
        else
        {
            img.onload = function() { doFade(true); };
            return;
        }
    };

    var checkBottom = function()
    {
        var elem = $('html');
        if(typeof searchParams.size != 'undefined' && searchParams.size == 'small')
            return false;
        
        if($(window).scrollTop() >= $(document).height() - $(window).height() - 30)
        {
            return true;
        }
        else
        {
            return false;
        }
    };
    
    var doneLoading = function() {
        loading = false;
        if(checkBottom())
        {
            loadPage();
        }
    }
    
    var setItemHover = function(item) {
        if($('ul.items.small').length > 0)
            var small = true;
        else
            var small = false;
        
        item.data('on', false);
        
        item.hover(function() {
            if(currentMode == 'list')
                return;
            var node = $(this);
            var content = $('.content', node);
            $('.wrapper', node).animate({height: small? 150 : 200 }, 200, 'easeOutCubic');
            //content.css('opacity', 0);
            node.data('on', true);
            //content.animate({bottom: 10, opacity: 1}, 200, 'easeOutCubic', function() {  });
            content.animate({opacity: 0}, 200, 'easeOutCubic', function() { if(!node.data('on')) return; content.hide(); });
            node.addClass('on');
        }, function() {
            if(currentMode == 'list')
                return;
            var node = $(this);
            node.data('on', false);
            var content = $('.content', node);
            content.show().animate({opacity: 1}, 200, 'easeOutCubic');
            $('.wrapper', node).animate({height: small? 113 : 150}, 200, 'easeOutCubic', function() {  /*if(node.data('on')) return;*/   node.removeClass('on');   });
            //content.animate({bottom: 0, opacity: 0}, 200, 'easeOutCubic', function() { if(node.data('on')) return; node.removeClass('on'); content.css('opacity', 1); });
            
        });
    };

    var buildProjectItem = function(data) {
        
        if($('body.people').length == 0)
            var people = false;
        else    
            var people = true;
            
        if(!people)
            var src = currentMode == 'list' || data.is_featured == 1? data.imgList : data.img;
        else
            var src = data.img;
            
        var category = 'id';
        if(typeof searchParams != 'undefined' && typeof searchParams.category != 'undefined' && searchParams.category)
        {
            category = searchParams.category;
        }
        
        var item = $('<li />');
        var wrapper = $('<div />').addClass('wrapper');
        var link = $('<a />').attr('href', '/' + controller + '/view/' + category + '/' + data.id).appendTo(wrapper);
        
        if(data.imgType == 'vimeo')
        {
            var width = data.imgMetaData['width'];
            var ratio = 630 / width;
            var height = data.imgMetaData['height'] * ratio;
            height = Math.floor(height);
            var img = $('<iframe width="630" height="' + height + '" frameborder="0" src="http://player.vimeo.com/video/' + data.imgList + '?title=0&amp;byline=0&amp;portrait=0"></iframe>').appendTo(link);
        }
        else
        {
            var img  = $('<img />').attr('alt', data.title).attr('src', src).appendTo(link);
        }
        
        if(people && currentMode == 'list')
            wrapper.hide();
        /*
        img.wrap(wrapper);
        img.wrap(link);*/
        
        wrapper.appendTo(item);
        
        var content = $('<div />').addClass('content').appendTo(item);

        if(data.name)
        {
            var name = $('<p />').addClass('title first').text(data.name).appendTo(content);
            name.wrap($('<a />').attr('href', '/' + controller + '/view/' + category + '/' + data.id));
            var title = $('<p />').addClass('position').text(data.title).appendTo(content);
        }
        else
        {
            var title = $('<p />').addClass('title first').text(data.title).appendTo(content);
            title.wrap($('<a />').attr('href', '/' + controller + '/view/' + category + '/' + data.id));
        }
        if(data.client)
            var client = $('<p />').addClass('client').text(data.client.title).appendTo(content);
        if(data.category)
            var category = $('<p />').addClass('category').text(data.category.title).appendTo(content);
        
        var desc = $('<div class="description" />').html(data.description).appendTo(content);

        if(people && currentMode == 'list')
            desc.hide();
        
        if(data.is_featured == 1)
        {
            item.addClass('featured');
        }
        else
        {
            setItemHover(item);
        }

        item.data('imgData', data);
        return item;
    }
    
    var loadPage = function() {
        if(loading || allLoaded)
            return;
        
        var params = $.extend({
            format : 'json',
            "page" : page
        }, searchParams);
        if(list.hasClass('small'))
        {
            params.size = 'small';
        }
        loading = true;
        list.append($('<li id="ajaxLoader" />').text('Loading...'));
        $.getJSON('/' + controller + '/list', params, function(data) {
            searchParams.withFeatured = false;
            $('#ajaxLoader').remove();
            $.each(data.items, function(i, item) {
                if($('ul.items li.featured').length > 0 || (typeof withFeatured != 'undefined' && withFeatured == false))
                {
                    item.is_featured = 0;
                }
                
                var node = buildProjectItem(item);
                if(typeof item.is_featured == 'undefined' || item.is_featured == 0)
                {
                    node.hide();
                }
                list.append(node);
            });
            if($('li:not(.featured)', list).length == data.totalItems)
            {
                allLoaded = true;
                $(document).unbind('scroll');
            }
            doFade();
        })
        page++;
    }
    
    var changeView = function(mode)
    {
        if(mode == currentMode)
            return;
        
        currentMode = mode;
        
        if($('body.people').length > 0)
            var people = true;
        else
            var people = false;
        
        $('#viewOptions a').removeClass('active');
        
        if(mode == 'list')
        {
            $('li:not(.featured)', list).each(function(i, item) {
                item = $(item);
                item.unbind('mouseenter');
                item.unbind('mouseleave');
                var data = item.data('imgData');
                var img = $('img', item);
                if(!people)
                {
                    img.attr('src', data.imgList);
                    $('.wrapper', item).css('height', 418);
                }
                else
                {
                    $('.wrapper', item).hide();
                    $('.description', item).hide();
                }
            })
            $('#viewOptions-list').addClass('active');
            list.addClass('listMode details');
        }
        else
        {
            $('#viewOptions-grid').addClass('active');
            list.removeClass('listMode').removeClass('details');
            $('li:not(.featured)', list).each(function(i, item) {
                item = $(item);
                setItemHover(item);
                var data = item.data('imgData');
                var img = $('img', item);
                if(!people)
                {
                    img.attr('src', data.img);
                    $('.wrapper', item).css('height', 150);
                }
                else
                {
                    $('.wrapper', item).show();
                }
            })
        }
        
        if(checkBottom())
            loadPage();
    }
    
    $('#viewOptions-grid').addClass('active');
    
    // apply functionality to lists
    var list = $('.items');
    if(list && list.length > 0 && typeof searchParams != 'undefined')
    {
        controller = (searchParams.controller == 'index')? 'projects' : searchParams.controller;
        loadPage();

        $(window).scroll(function() {
            if(checkBottom())
            {
                loadPage();
            }
        })
        if($('#viewOptions').length)
        {
            $('#viewOptions-list').click(function() { list.animate({opacity : 0}, 500, 'easeOutCubic', function() { changeView('list'); list.animate({opacity: 1}, 500, 'easeOutCubic'); }); return false; });
            $('#viewOptions-grid').click(function() { list.animate({opacity : 0}, 500, 'easeOutCubic', function() { changeView('grid'); list.animate({opacity: 1}, 500, 'easeOutCubic'); }); return false; });
        }
    }
    // end virtual scrolling stuff
    
    // image slider stuff
    var buildChanger = function(changer, current, total, animateFunction, imgHeight)
    {
        var controls = changer.find('span');
        var next = controls.eq(1).clone();
        var prev = controls.eq(0).clone();
        changer.html('');
        next.find('a').unbind('click');
        prev.find('a').unbind('click');
        prev.find('a').click(function(e) {
            animateFunction("prev", true);
        });
        next.find('a').click(function(e) {
            animateFunction("next", true);
        });
        
        if(total < 2)
            return;
        
        prev.show().find('a').text('Previous');
        next.show().find('a').text('Next Image');
        changer.append(prev).append(' / ').append(next);
        
        if(controls.length == 3)
        {
            changer.append($('<span class="summary"> (' + (current + 1) + ' of ' + total + ')</span>'));
        }
        else
        {
            changer.append($('<span class="summary"> (' + (current + 1) + ' of ' + total + ')</span>'));
        }
        
        var offset = 630 - imgHeight;
        /* uncomment to have changer animate up and down with height of image.
        changer.css({position: 'relative'});
        changer.animate({'top': -offset}, 500);
        */
    }
    
    var initSlider = function(i, node) {
        node.wrap('<div class="sliderContainer" />');
        node = node.parent();
        node.css('float', 'left');
        node.easySlider({
            controlsBefore : '<div class="imageChanger">', 
            controlsAfter : '</div>', 
            prevId : 'prevBtn' + i, 
            nextId: 'nextBtn' + i,
            continuous : true,
            controlsSetup : function(node, options, animateFunction) {
                var total = $('ul li img', node).length;
                
                var img = $('ul li img', node).eq(0);
                
                var changer = node.parents('.details').eq(0).find('.imageChanger');
                buildChanger(changer, 0, total, animateFunction, img.height());
                
                if(total < 2)
                    return;
        
                var initialHeight = img.height();// / 2 -39;
                var initialWidth = img.width();
                $('ul li', node).css('opacity', 1);
                $("<div class='nextArrow'>&gt;</div>").css({'padding-top': initialHeight, left: initialWidth / 2, width : initialWidth / 2, 'background-position': (initialWidth / 2 - 30 - 78) + 'px center'}).click(function(e) { animateFunction("next", true); }).appendTo(node);
                $("<div class='prevArrow'>&lt;</div>").css({'padding-top': initialHeight, width : initialWidth / 2}).click(function(e) { animateFunction("prev", true); }).appendTo(node);
                //$('.prevArrow', node).css('cursor', 'default');
                
                /*
                if($.support.opacity)
                {
                    $('.prevArrow', node).css('opacity', 0);
                }
                else
                {
                    $('.prevArrow', node).hide();
                }
                */
            },
            scroll : function(node, options, current, w, animateFunction)
            {
                var imgs = $('ul li img', node);
                var img = imgs.eq(current);
                var total = imgs.length;
                var height = img.height();// / 2 - 39;
                var width = img.width();

		imgs.css('opacity', 1);

        
                var prevTarget = current == 0 ? 0 : 1;
                var nextTarget = current == total - 1 ? 0 : 1;
                
                if($.support.opacity)
                {
                    $('.nextArrow', node).animate({'padding-top': height, left: parseInt(width / 2), width : width / 2 /* , opacity: nextTarget */, 'background-position': (width / 2 - 30 - 78) + 'px center' }, 750);
                    $('.prevArrow', node).animate({'padding-top': height, width : width / 2 /* , opacity: prevTarget */}, 750);
                    /*
                    if(nextTarget == 0) { $('.nextArrow', node).css('cursor', 'default'); } else { $('.nextArrow', node).css('cursor', 'pointer'); }
                    if(prevTarget == 0) { $('.prevArrow', node).css('cursor', 'default'); } else { $('.prevArrow', node).css('cursor', 'pointer'); }
                    */
                }
                else
                {
                    $('.nextArrow', node).animate({'padding-top': height, left: parseInt(width / 2), width : width / 2, 'background-position': (width / 2 - 30 - 78) + 'px center'}, 750);
                    $('.prevArrow', node).animate({'padding-top': height, width : width / 2}, 750);
                    /*
                    if(prevTarget == 0) { $('.prevArrow', node).hide(); } else { $('.prevArrow', node).show(); }
                    if(nextTarget == 0) { $('.nextArrow', node).hide(); } else { $('.nextArrow', node).show(); }
                    if(nextTarget == 0) { $('.nextArrow', node).css('cursor', 'default'); } else { $('.nextArrow', node).css('cursor', 'pointer'); }
                    if(prevTarget == 0) { $('.prevArrow', node).css('cursor', 'default'); } else { $('.prevArrow', node).css('cursor', 'pointer'); }
                    */
                }
                buildChanger(node.parents('.details').eq(0).find('.imageChanger'), current, total, animateFunction, img.height());
            }
        });
        $('.imageChanger', node.parent()).appendTo(node.parent());
    };
    
    var slideNode = $('ul.images.slider:not("ul.images.slider.videos")');
    slideNode.each(function(i, node) {
        node = $(node);
        var img = $('li img', node).get(0);
        $('li:first', node).css('opacity', 0);
        /*
        if(img.complete)
        {
            initSlider(i, node);
        }
        else
        {
            img.onload = function() { initSlider(i, node); };
        }
        */

	var hQueue = [];
	var fitting = false;

	var deQueue = function(slider) {
            var cont = slider.parents('.sliderContainer').eq(0);
	    var currentHeight = cont.height();

	    for(var i = 0; i < hQueue.length; i++)
	    {
	        var target = hQueue[i];
		if(currentHeight < target + 80)
		{
		    currentHeight = target + 80;
		}
		cont.height(currentHeight);
	    }
	    fitting = false;
	}
        
        var fitImage = function(image, slider) {
            var cont = slider.parents('.sliderContainer').eq(0);

	    if(cont.length == 0)
	    {
	      setTimeout(function() { fitImage(image, slider); }, 10);
	      return;
	    }
            var imageHeight = image.height();
	    image.parents('li').eq(0).hide().css('opacity', 1);

	    for(var i = 0; i < hQueue.length; i++)
	    {
	      if(imageHeight < hQueue[i])
	        return;
	    }
            hQueue.push(imageHeight);
	    cont.height(imageHeight + 80);
        }
        
        $('li img', node).each(function(i, img) {
            var image = $(img);
            
            if(img.complete)
            {
                if(i == 0)
		{
                    initSlider(i, node);
		    setTimeout(function() {fitImage(image, node); image.parents('li').eq(0).show();}, 1);
		    
		}
		else
		{

		    setTimeout(function() {
		        fitImage(image, node);
		        setTimeout(function() {image.parents('li').eq(0).css('opacity', 1);}, 1);
		    }, 1);
		}
            }
            else
            {
                if(i == 0)
                {
                    image.load(function(e) {
                        initSlider(i, node);
			setTimeout(function() {fitImage(image, node); image.parents('li').eq(0).show();}, 1);
			
                    });
                }
                else
                {
                    image.load(function(e) {
			setTimeout(function() {fitImage(image, node);}, 1);
		        setTimeout(function() {image.parents('li').eq(0).css('opacity', 1);}, 1);
                    });
                }
            }
        });
        
    });
    // end image slider stuff
    
    if($('#jobs').length)
        $('#jobs h3').each(function(i, item) { //accordion();
            $(item).next().hide();
            $(item).click(function() {
                $(item).next().slideToggle();
                return false;
            });
        });
    
    if($('#people').length)
    {
        var peopleList = $('#people');
        var personDetail = $('#personDetail');
        $('#people li a').each(function(i, link) {
            link = $(link);
            link.click(function(e) {
                var id = link.attr('href');
                
                personDetail.css('border-top', '1px solid #b2b2b2');
                $.get('/people/view', {'id': id, context: 'directory'}, function(html) {
                    personDetail.html(html);
                });
                
                return false;
            })
        })
    }
    
    $('.items.pressReleases li:last').addClass('last');
});


