function handleError(){
    return true;
}
window.onerror = handleError;

$('html').addClass("js");

Cufon.replace('h1', {fontFamily: 'Hermes'});
Cufon.replace('#main-nav li a', {fontFamily: 'Hermes Regular', hover: {color: '#000000'}});
Cufon.replace('#news-items h1', {fontFamily: 'Hermes'});
Cufon.replace('em.date', {fontFamily: 'Hermes'});
Cufon.replace('blockquote', {fontFamily: 'Hermes'});
Cufon.replace('.mentions h2', {fontFamily: 'Hermes'});
Cufon.replace('.mentions.clients_list', {fontFamily: 'Hermes', hover: {color: '#9c9c9c;'}});

(function($,sr){
  // debouncing function from John Hann
  // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
  var debounce = function (func, threshold, execAsap) {
      var timeout;

      return function debounced () {
          var obj = this, args = arguments;
          function delayed () {
              if (!execAsap)
                  func.apply(obj, args);
              timeout = null;
          };

          if (timeout)
              clearTimeout(timeout);
          else if (execAsap)
              func.apply(obj, args);

          timeout = setTimeout(delayed, threshold || 100);
      };
  }
    // smartresize
    jQuery.fn[sr] = function(fn){  return fn ? this.bind('scroll', debounce(fn)) : this.trigger(sr); };
})(jQuery, 'smartscroll');

$(document).ready(function(){
    /* fix for floating width-less issue on IE7 */
    if ($.browser.msie && $.browser.version.substr(0,1) == 7) {
        $(".projects_index ul li").each(function(){
            $(this).width($("img", this).width());
        });
    }

    slideshow.init("#home-window");
    slideshow.init(".introduction-window");

    $("ul.clients li a img").hover(
        function(){
            var hoverImg = $(this).attr('src').split(".").join('_hover.');
            $(this).attr('src', hoverImg);
        },
        function(){
            var hoverImg = $(this).attr('src').split("_hover").join('');
            $(this).attr('src', hoverImg);
        }
    )

    /* inits all the news and project stuff */
    if($("#news-items li img").length > 0){
        gallery.init($(".gallery"));
        if($.browser.safari){bodyelem = $("body")} else{ bodyelem = $("html")} bodyelem.animate({scrollTop:0}, 220);
        lazyLoader.init("#news-items li.item");
    }

    if($(".project_content").length > 0){
        gallery.init($(".gallery"));
        $('.project_content').css({'display':'block'});
        $('.project_content').condense({condensedLength: 350, lessText: 'Show less',  moreText: "Read more", ellipsis: "", moreSpeed: 200, lessSpeed: 200});
    }
    
    if($(".video a").length > 0){
        $(".video a").fancybox({'transitionIn':'fade', 'transitionOut':'fade', 'speedIn':600, 'speedOut':300, overlayOpacity:0.5});
    }

    if($(".projects_index ul li a").length > 0){
        $(".projects_index ul li a").each(function(){
            $(this).hover(
                function(){
                    var overPadding = Number($('em.overlay', this).css('padding-left').split('px')[0]) + Number($('em.overlay', this).css('padding-right').split('px')[0]);
                    var newWidth = $('em.overlay', this).parent().width() - overPadding;
                    $('em.overlay', this).width(newWidth);
                    $('em.overlay', this).stop().animate({bottom: "0px"}, {duration: 300});
                },
                function(){
                    $('em.overlay', this).stop().animate({bottom: "-141px"}, {duration: 1300});
                }
            )
        });
    }

    $("a[rel*=blank]").click(function(){
        window.open($(this).attr('href'), '_blank');
        return false;
    })
});

var lazyLoader = {
    items:null,
    currentPage: 1,
    totalPages: 0,
    doneLoading: false,

    init: function(items){
        $("#news-paginator").hide();
        $("#scroll_loader").hide();

        $(window).smartscroll(function(){
            if(($(document).height() - $(window).height()) <= $(this).scrollTop()){
                if((lazyLoader.currentPage) < lazyLoader.totalPages){
                    $("#scroll_loader").html("more news");
                    $("#scroll_loader").fadeIn('medium');
                }else{
                    $("#scroll_loader").hide();
                }
            }
        })

        $.ajax({
            url: '/news/returnTotalPages',
            type: 'POST',
            success: function(data, textStatus) {
                if(textStatus == "success"){
                    lazyLoader.totalPages = data;
                }
            }
        });

        $("#scroll_loader").click(function(){
            $(this).html("loading...");
            lazyLoader.loadNext();
            return false;
        });
    },
    loadNext: function(){
        lazyLoader.currentPage = lazyLoader.currentPage + 1;

        $.ajax({
            url: '/news/index',
            data: {'pageIndex' : lazyLoader.currentPage},
            type: 'POST',
            success: function(data, textStatus) {
                if(textStatus == "success"){
                    if(data != "done"){
                        $(data).appendTo("#news-items").hide().fadeIn(1200);

                        Cufon.replace('#news-items h1', {fontFamily: 'Hermes'});
                        Cufon.replace('em.date', {fontFamily: 'Hermes'});
                        gallery.init($(".gallery"));
                        $(".video a").fancybox({'transitionIn':'fade', 'transitionOut':'fade', 'speedIn':600, 'speedOut':300, overlayOpacity:0.5});
                    }else{
                        lazyLoader.doneLoading = true;
                    }
                    $("#scroll_loader").hide();
                }
            }
        });
    }
}

var fakeLazyScrollLoader = {
    items:null,
    increments: 0,
    totalPages: 0,
    totalItems: 0,
    currentPage: 1,
    totalHeight: 0,
    totalDocHeight: 0,
    scrollCheck: true,
    
    init: function(items, maxVisible){
        this.items      = items;
        this.totalItems = $(items).length;
        this.increments = maxVisible;
        this.totalPages = Math.ceil((this.totalItems / this.increments));
        this.totalDocHeight = ($(document).height() - $(window).height());

        $(this.items+":gt("+(this.increments - 1)+")").hide();
        
        $(window).smartscroll(function(){
            $("#scroll_loader").hide();
            if(($(document).height() - $(window).height()) <= $(this).scrollTop()){
                fakeLazyScrollLoader.showNext();
            }
        })
    },
    showNext: function(){
        $("#scroll_loader").hide();

        if(this.scrollCheck){
            this.currentPage += 1;
              
            if(this.currentPage <= this.totalPages){
                $("#scroll_loader").show().effect("pulsate", {times:5}, 1020);
                var displayItems = (this.currentPage * this.increments);

                $(this.items+":lt("+(displayItems)+")").delay(1020).fadeIn(0, function(){
                    fakeLazyScrollLoader.scrollCheck = true;
                });
                this.scrollCheck = false;
            }else{
                this.scrollCheck = false;
                $("#scroll_loader").hide();
            }
        }
    }
}

var gallery = {
    container: null,
    containerWidth: 0,
    viewportWidth: 0,
    totalImages: 0,
    activeImage: 0,

    init: function(container){
        if(container.length == 0) return;

        $(container).each(function(){
            if(!$(this).hasClass('loaded')){
                var gallery = this;
                var totalImages = $("li", gallery).length;
                var activeImage = 0;
                var viewportWidth = $(gallery).parent().width();
                var containerWidth = 0;

                // calculate and set container width
                $("li", gallery).each(function(){
                    containerWidth += Number($(this).width());
                });
                $(gallery).width(containerWidth);

                if($("li", gallery).length > 1){
                    $(gallery).addClass('loaded');

                    // events
                    $(gallery).closest("li.item, .project_detail").find('.image-paginator li.prev a').click(function(){
                        activeImage -= 1;
                        moveTo();
                        return false;
                    });

                    $(gallery).closest("li.item, .project_detail").find('.image-paginator li.next a').click(function(){
                        activeImage += 1;
                        moveTo();
                        return false;
                    });

                    $(gallery).click(function(){
                        activeImage += 1;
                        moveTo();
                        return false;
                    });

                    var moveTo = function(){
                        if(activeImage >= totalImages) {
                            activeImage = 0;
                        } else if(activeImage < 0) {
                            activeImage = totalImages - 1;
                        }

                        $(gallery).animate({left: (activeImage * viewportWidth) * -1 + "px"}, {easing: "easeOutQuint", duration: 720, queue: false });
                        updateCounter();
                    }

                    var updateCounter = function(){
                        $(gallery).closest("li.item, .project_detail").find('.image-paginator .counter').html(activeImage + 1);
                    }
                }
            }
        });
    }
};

var slideshow = {
    container: null,
    startInterval:null,
    intervalTime:5000,
    fadeTime:1000,
    totalItems:null,
    currentItem:null,
    currentKey:null,
    itemCounter:null,

    init: function(container){
        if($(container).length == 0) return;
        this.container = container;
        this.currentKey = this.setNextRandom();
        this.intervalTime = animationInterval;
        this.fadeTime = animationFade;

        slideshow.start();
    },
    start: function(){
        this.itemCounter = 0;
        this.totalItems = ($(this.container+" li").length - 1);

        $(this.container+" li").hide();
        
        if(this.totalItems > 0){
            this.currentItem = $(this.container+" li:eq("+this.currentKey+")").show();

            var intervalTime = this.intervalTime;
            this.startInterval = setInterval("slideshow.moveOut()", this.intervalTime);
        }else{
            $(this.container+" li:first").show();
        }
    },
    moveIn: function(){
        $(this.currentItem).fadeIn(this.fadeTime);

        var intervalTime = this.intervalTime;
        this.startInterval = setInterval("slideshow.moveOut()", this.intervalTime);
    },
    moveOut: function(){
        clearInterval(this.startInterval);
        $(this.currentItem).fadeOut(this.fadeTime);

        this.currentKey = (this.currentKey == this.totalItems) ? 0 : (this.currentKey + 1);
        this.currentItem = $(this.container+" li:eq("+this.currentKey+")");

        this.moveIn();
    },
    setNextRandom: function(){
        var newKey = Math.floor((Math.random() * $(this.container+" li").length));
        newKey = (this.currentKey == newKey) ? this.setNextRandom() : newKey;
        return newKey;
    }
};
