if( typeof( window.console ) === "undefined" ) {
  window.console = {log: $.noop, time:$.noop}
}

var gridConfig = {colsize: 58, rowsize:66, margin: 1};

$.run({

  "#content":function(){
    $.preloader.show();
  },
  
  ".update time":function(){
    this.addClass("timeago").timeago(); 
  },
  
  "*[data-embed]":function(){
    this.click( function(){
      if( $(this).data("embed") && !$(".video-player", this).length ) {
        var iframe = $('<iframe class="video-player" src="'+ $(this).data("embed")+'?autoplay=1&hd=1" frameborder="0"></iframe>');
        $(this).append(iframe)
        $(this).trigger("video.play");
        iframe.css({height: $(this).height(), width: $(this).width()});
      }
      return false;
    });
  },
  
  "#header nav":function(){
    var nav = this,
        header = this.closest("header");
    $(window).scroll( function(){
      var st = $(document).scrollTop()
        , wh = $(window).height();
    }).scroll();
  },
  
  "#client-filter":function(){
    var query = window.location.href.split("?");
    if( query.length > 1 ) {
      var selected = $("a[href*='"+query[1]+"']", this)
        , breadcrumb = $("<h2>"+selected.html()+"</h4>");

        selected.closest(".filter").append(breadcrumb);
    }

    var h = this.height();
    this.click(function(){
      $(".filter ul",this).slideDown(400, "quintEaseInOut");
      if( breadcrumb )
        breadcrumb.fadeOut(200, "quintEaseOut");
    }).mouseleave( function(){
      $(".filter ul",this).slideUp(400, "quintEaseInOut");
      if( breadcrumb)
        breadcrumb.delay(10).fadeIn(200, "quintEaseOut");
    })
    $(".filter ul",this).slideUp(0);
  },
  
  "#header nav a":function(){
    var path = window.location.pathname.split("/")[1];
    if( path == "" ) {
      this.eq(0).addClass("active");
    } else 
      this.filter("*[href*='"+path+"']").addClass("active");
  },
  
  "article img":function(){
    this.addClass("loading").load( function(){
      $(this).removeClass("loading");
    })
  },
  
  "article.photo.expand a":function(){
    var list = this;
    this.click( function(){
      var parentArticle = $(this).closest("article");
      var article = parentArticle.clone();
      article.removeAttr("style");
      $("img", article).remove();
      $("<img>")
        .attr("src", $(this).attr("href"))
        .prependTo($("figure",article));
      $("figure", article).prepend($("a.expand", article).html());
      $("figcaption", article).prepend($("figcaption a", article).html());
      
      $("a", article).remove();
      if( $("figcaption", article).children().length < 1 )
        $("figcaption",article).remove();
      
      var prev = parentArticle.prevAll(".photo.expand:first");
      var next = parentArticle.nextAll(".photo.expand:first");
      
      $.slideshow.open(article, {next: $("a:first", next), prev: $("a:first", prev) });
      
      return false;
    })
  },

  // Autostart the slideshow if #!/slideshow is in the url
  "/slideshow": function(){
    $("article.photo.expand a").first().click();
  },
  
  "#search input[type=text]":function(){
    this.bind("change focus", function(){
      $(this).addClass("active");
    }).bind("blur", function(){
      $(this).toggleClass("active", $(this).val() != "");
    }).blur();
  },
  
  "#featured":function(){
    var featured = this
      , media = $(".media", featured)
      , nav = $("<ol class=\"nav\"></ol>");
    
    if( $("> li", media).length > 1 ) {
      $(" li", media).each(function(i){
        nav.append( $('<li><a href="#'+i+'"></a></li>') );
      });
    
      $("a", nav).click( function(){
        $(".media", featured).stop(true, false);    
        var index = $(this).closest("li").index();
        var li = $(".media > li", featured).eq( index );
        $(".media", featured).animate({left: -li.position().left }, {duration: 900, easing: "quintEaseInOut"});
        $(this).addClass("current").closest("li").siblings().children().removeClass("current");
        if( $("iframe", featured).length )
          $("iframe", featured).parent().trigger("video.stop");
        
        if(t) clearTimeout(t);
        t = setTimeout(featureTick, delay);  
        return false;
      });
      
      var delay = 8000,
          t;
          
      var featureTick = function(){
        var li = $("#featured .nav a.current").parent().next()
        if( !li.length ) li = $("#featured .nav a.current").parent().siblings().first();
        li.children("a").click();
      }
      
      media.click(function(){
        if(t) clearTimeout(t);
        featureTick();
      })
      
      $("li:first a", nav).addClass("current");
      featured.prepend( nav );
      t = setTimeout(featureTick, delay);
      
      $("*[data-embed]").bind("video.play",function(){
        $("iframe",this).height(featured.height() - nav.height());
        $("img", this).hide();
      });
      
      $("*[data-embed]").bind("video.stop",function(){
        $("iframe",this).remove();
        $("img", this).show();
      });
      
      $("#featured").mouseenter( function(){
        if(t) clearTimeout(t);
      }).mouseleave( function(){
        t = setTimeout(featureTick, delay);
      });
    }
  }, 
  
  "article.plain, article.statement, article.news, .hire":function(){
    var l = this.length-1;
    var elements = this.addClass("autoheight");
    
    setTimeout( function(){
      elements.each( function(i){
        var b = $(this),
            articleBody = $(".body", b);

        // Added because of rendering
        var pt = parseInt( articleBody.css("paddingTop"))
          , mt = parseInt( articleBody.css("marginTop"));

        var h = $(".body", b).height()+(mt*2)+(pt*2);
        var r = Math.ceil(h/gridConfig.rowsize);
        b.data("rows", r);
        var height = r*gridConfig.rowsize-pt-(mt*2) + gridConfig.margin*r;
        $(".body", b).height(height);

        $("section#content").data("cols", 0);
        b.data("rendered", true);
      });
      $(window).resize();

    }, 1);
  },
  
  "article.client":function(){
    this.each( function(){
      var fc = $(this).data("foreground-color")
        , bc = $(this).data("background-color")
        , titleColor = $("h1",$(this)).css("color");
        
      $("h2",$(this)).css({color:bc});
      
      $(this).mouseenter( function(){
        $("h1 a",$(this)).css({color:fc});
      }).mouseleave(function(){
        $("h1 a",$(this)).css({color: titleColor});
      })
    })
  },
  
  ".clients .grid.client":function(){
    this.each( function(){
      if( $(this).children().length < 4)
        $(".sector a", $(this)).hide();
        
      $(this).data("elements", $("article:not(.sector):gt(2)", $(this)).remove() );
    });
  },
    
  "section#content":function(){
    var grid = Grid()
      , content = this;
    
    $("article, section",this).css({position: "absolute"});
    
    $(window).resize( function(){
      var dc = $("section#content").data("cols")
        , cols = parseInt( $("section#content").width() / ( gridConfig.colsize ) )
        , margin = 0
        , g;

      if( dc != cols ) {
        $("section#content").data("cols", cols);

        // Hiding to avoid reflows while rendering grid
        $("section#content").css("display", "none");
        
        var render = function(x,y,columns,rows){
          var pb = 0; 
          if( this.is(".grid") ) {
            margin += this.data("padding") || 0;
            margin += this.data("padding-top") || 0;
          }
 
          var marginLeft = marginTop = gridConfig.margin;
 
          this.css({
            left: x*(gridConfig.colsize+marginLeft),
            top:  y*(gridConfig.rowsize+marginTop ) + margin,
            width: (columns*gridConfig.colsize) + columns*marginLeft-(marginLeft),
            height: (rows*gridConfig.rowsize) + rows*marginTop-(marginTop)
          }).show();
 
          if( this.is(".grid") ) {
            margin += this.data("padding") || 0;
            margin += this.data("padding-bottom") || 0;
          }
 
          if( this.not(".grid") && this.closest("section").data("grid-type") == "overlapping" ){
          } else
            return 5;
        }
        
        $("section > section.grid").each( function(){
          var c = $(this).data("fixed") ? $(this).data("cols") : cols;
          g = new Grid().resize( c );
          g.render($("article",$(this)), render);
            $(this).data("rows", g.rows);
            $(this).data("cols", c);
        });
        
        // grid.resize(cols);
        grid.render($("body > section > article, body > section > section.grid"),render, cols);
        $("section#content").height( (grid.rowsCount() * gridConfig.rowsize + gridConfig.margin*grid.rowsCount()) + margin);
 
        // Now shows content again, now we avoided reflows
        $("section#content").css("display", "block");
      }
      
      $("#featured .media > li").width($("#featured").width());
      $("#featured .media > li").height($("#featured").height());
      $("#featured .media").width( $("#featured .media li").length * $("#featured").width() );
      
      //Removes preloader if the slideshow is visible, otherwise let it be handled by slideshow.
      if($("body").hasClass("preload") ||  $.slideshow().filter(":hidden").length) {
        if( $(".autoheight").length < 1 ) {
          $.preloader.hide(); 
          $("body").removeClass("preload");
        } else if( $(".autoheight:first").data("rendered") ) {
          $.preloader.hide();
          $("body").removeClass("preload");
        }
        
      }
   }).resize();
  }
});


$(function() {
  
  $("#search input").placeholder();

  $.slideshow().bind("loaded close",function(){
    $.preloader.hide();
  });

  $.slideshow().bind("change",function(){
    $.preloader.show();
  });

  if( Modernizr.touch ) {
    var css = {left: 0, top: $(window).scrollTop(), width: $(window).width(), height: $(window).height(), position: "absolute" };
    $.slideshow().css( css );

    if (window.pageYOffset < 1)
      window.scrollTo(0, 1);

    var media = $("#featured .media")
      , x = media.position().left
      , nav = $("#featured .nav");

    if( media.children().length < 2 )
      return false;

    media.css("-webkit-transform", "translateZ(0)");      
    media.touchEvents({min_move_x:200});
    media.css("translateZ", 0);
    media.bind("touchMove touchEnd touchStart touchSwipeLeft touchSwipeRight", function(e, n, dx, dy){
      switch(e.type){
        case "touchStart":
          x = media.position().left
          break;
        case "touchMove":
          var w = $("#featured").width();
          $(this).css("left", x-dx);
          break;
        case "touchSwipeLeft":
          $(".current", nav).parent().next().children('a').click();
          break;
        case "touchSwipeRight":
          $(".current", nav).parent().prev().children('a').click();
          break;
        case "touchEnd":
          if( !media.is(":animated") )
            media.animate({left: x}, {duration: 300, easing: "quintEaseInOut"} );
          break;
      }
    })
  }
})
