(function($) {

  Sammy = Sammy || {};

  // A simple plugin that pings Google Analytics tracker
  // every time a route is triggered
  //
  // === Arguments
  //
  // +tracker+:: the Google Analytics pageTracker object.  Defaults to
  // the default object defined by the GA snippet, or pass your own if you
  // have a custom install
  Sammy.GoogleAnalytics = function(app, tracker) {
    var shouldTrack = true;

    this.helpers({
      noTrack: function() {
        disableTracking();
      }
    });

    this.bind('event-context-after', function() {
      var _tracker = tracker || window.pageTracker,
          full_path = window.location.pathname + this.path;
      if(typeof _tracker != 'undefined' && shouldTrack) {
        this.log('tracking ', full_path);
        _tracker._trackPageview(full_path);
      }
      enableTracking();
    });

    function disableTracking() {
      shouldTrack = false;
    }

    function enableTracking() {
      shouldTrack = true;
    }
  };
})(jQuery);

;(function($) {
  

  $.easing.def = "easeOutQuad";
  
  var version = "";
  
  var app = $.sammy(function() {
    this.element_selector = '#main';
    this.use(Sammy.JSON);
    this.use(Sammy.GoogleAnalytics);
    
    var current = {};
    
    this.helpers({
      setCurrent: function() {
        current.slug     = this.params['slug'];
        current.category = this.params['category'];
        current.image_id = this.params['image_id'];
      },
      loadCategory: function(after) {
        var context = this, 
            slug    = this.params['slug'],
            category = this.params['category'];
        this.log('current', current);
        if (slug != current.slug || category != current.category) {
          this.log('slug or category changed', slug, category);
          context.showLoading(function() {
          // then we have to load
            $.get(context.urlFor(slug, category), {no_layout: true}, function(html) {
              $(html).preloadImages();
              // set the navigation
              $('#nav')
                .find('a[rel="' + slug + '"]')
                  .trigger('open')
                  .siblings('ul')
                  .when(!!category, function() {
                    Sammy.log('triggering category open', category);
                    $(this).find('a[rel="' + category + '"]')
                      .trigger('open');
                  })
                  .when(!category, function() {
                    $(this).find('li a:first').trigger('open');
                  });
               var $updated = $(html);
               // $updated.find('.image img').css({opacity: 0.7});
               $('#content').html($updated);
               context.hideLoading();
               after.call(context);
               context.setCurrent();
            });
          });
        } else {
          after.call(context);
          context.setCurrent();
        }
      },
      showLoading: function(callback) {
        this.log('showLoading');
        $('#content .gallery').animate({backgroundColor: '#EFEFEF'}, 500, callback);
        // $('.loading').css({opacity: 0}).show().animate({opacity: 1}, 500, callback);
      },
      hideLoading: function() {
        this.log('hideLoading')
        $('#content .gallery').animate({backgroundColor: '#E1E1E1'}, 300, function() {
          // $(this).find('.image img').animate({opacity: 1}, 50);
        });
        // $('.loading').animate({opacity: 0}, 500, function() { $(this).hide() });
      },
      urlFor: function() {
        var args = ['', 'studio'].concat($.makeArray(arguments))
        return args.join('/');
      },
      imageURL: function(filename, size, video) {
        if (video) {
          var splits = filename.split('_'),
              slug = splits[0], 
              id = splits[2],
              filename = [slug, "_", id, "-poster"].join('');
        }
        if (!size && size != '') { size = '_main'};
        return ["http://pandsassets.s3.amazonaws.com/images/",filename,size,".jpg?", version].join('');
      },
      videoURL: function(filename) {
        var splits = filename.split('_'),
            slug = splits[0], 
            id = splits[2];
        return ["http://pandsassets.s3.amazonaws.com/videos/", slug, '_', id, '.mov'].join('');
      },
      setImage: function(image_id) {
        image_id = parseInt(image_id);
        // set the image id by getting the data
        var context = this,
            image = $('#content .grid-image a').eq(image_id),
            $image_holder = $('#content .content-display.image'),
            $video_holder = $('#content .content-display.video'),
            is_video,
            image_data,
            total = this.totalImages(),
            next_id, prev_id, has_images;
        if (image.length == 0) { return; } // no image, bail
        image_data = JSON.parse(image.attr('data'));
        is_video = !!image_data.width;
        next_id = ((image_id + 1) >= total) ? 0 : image_id + 1;
        prev_id = ((image_id - 1) < 0) ? total - 1 : image_id - 1;
        has_images = total > 1;
        this.log('is_video', is_video, 'next_id', next_id, 'prev_id', prev_id);
        context.showLoading(function() {});
        if (is_video) {
            // more complex video stuff
            var width = image_data.width, 
                height = image_data.height + 16,
                video_url = context.videoURL(image_data.filename),
                image_url = context.imageURL(image_data.filename, '', true);
                
            $image_holder.hide();
            $video_holder
              .hide()
              // set the holder width and height
              .find('.video-image').show().attr('src', image_url).end()
              .find('.play').show().end()
              .find('.video-player').hide().end()
              .find('.video-holder').css({width: width + 'px', height: height + 'px'}).end()
              // set video url
              .find('embed')
                .attr('width', width)
                .attr('height', height)
                // .attr('href', video_url)
                .attr('src', video_url).end()
              .find('object')
                .attr('width', width)
                .attr('height', height)
                // .find('param[name="href"]').val(video_url).end()
                .find('param[name="src"]').val(video_url).end();
            $video_holder.show();
            
          } else {
            $video_holder.hide();
            var $old_image = $image_holder.show().find('img'),
                $new_image = $old_image.clone();
            
            $new_image
              .attr('src', context.imageURL(image_data.filename))
              .attr('title', image_data.title)
              .soon(function() { 
                $old_image.remove(); 
                $new_image.appendTo($image_holder).show(); 
              });
          }
          $('#content')
            .find('.caption')
            .find('h3').html(image_data.title).end()
            .find('p').html(image_data.caption).end().end()
          .find('.next')
            .when(has_images, function() {
              $(this)
                .removeClass('disabled')
                .attr('href', ['#', 'studio', context.params['slug'], context.params['category'], next_id].join('/'));
            })
            .when(!has_images, function() {
              $(this).removeAttr('href').addClass('disabled');
            })
            .end()
          .find('.prev')
            .when(has_images, function() {
              $(this)
                .removeClass('disabled')
                .attr('href', ['#', 'studio', context.params['slug'], context.params['category'], prev_id].join('/'));
            })
            .when(!has_images, function() {
              $(this).removeAttr('href').addClass('disabled');
            }).end()
          .find('.gallery').removeClass('show-grid').addClass('show-image');
          context.hideLoading();
      },
      totalImages: function() {
        return $('#content .grid-image').length;
      },
      currentToURL: function(merge) {
        var to = $.extend({}, current, merge || {});
        return this.join('/', '#', to.slug, to.category, to.image_id)
      }  
    })
    
    this.get('#/studio/:slug/:category/:image_id', function() {
      this.loadCategory(function() {
        var image_id = this.params['image_id'];
        if (image_id != current.image_id) {
          if (image_id == 'grid') {
            $('#content .gallery')
              .removeClass('show-image').addClass('show-grid')
              .find('.content-display').hide();
          } else {
            this.setImage(image_id);
          }
        }
      });
    });
    
    this.get('#/studio/:slug/:category', function() {
      this.loadCategory(function() { });
    });
    
    this.get('#/studio/:slug', function() {
      this.loadCategory(function() { });
    });
    
    this.get('#/studio', function() {
      this.loadCategory(function() { });
    });
    
    this.bind('play', function() {
      $('.video .video-player').show();
      $('.video-image, .video-holder .play').hide();
      $(document).one('qt_canplay', function(e) {
        Sammy.log('qt_canplay', e);
        document.videoplayer.Play();
      }).one('qt_ended', function(e) {
        $('.navigation .next').click();
      });
    });
    
    this.bind('next', function() {
      var $next = $('.navigation .next'), 
          href = $next.attr('href');
      if (href && href != '' && !href.match(/^\//) && $next.not('.disabled')) {
        this.redirect(href);
      } else {
        $next.trigger('click');
      }
    });
    
    this.bind('run', function() {
      var context = this;
      
      version = $('body').attr('data-version');
      
      $('#nav>ul>li>a')
        .bind('open', function() {
          context.log(this, 'open');
          $(this).parents('#nav').find('li>a.active').not(this).trigger('close');
          $(this).addClass('active')
            .siblings('ul')
              .when(':hidden', function() { $(this).slideDown(); });
        })
        .bind('close', function() {
          context.log(this, 'close');
          $(this).removeClass('active').siblings('ul').slideUp();
        })
        .siblings('ul').find('li a')
          .bind('open', function() {
            $(this).parents('ul.categories').find('a').removeClass('active');
            // $(this).parents('li.client').trigger('open');
            $(this).addClass('active');
          });
        
      $('a[href^="/studio/"]').live('click', function(e) {
        e.preventDefault();
        if ($(this).not('.disabled')) {
          context.redirect('#' + $(this).attr('href'));
        }
      });
      
      $('.gallery .content-display img').live('click', function() {
        if($(this).is('.video-image') || $(this).is('.play')) {
          context.trigger('play');
        } else {
          context.trigger('next');
        }
      });
    });
  });

  $(function() {
    
    // Home page twitter
    if ($('.latest').length > 0) {
      var $latest = $('.latest'),
          updates = [],
          current = 0,
          animateLatest = function() {
            var text = updates[current % updates.length].split('').reverse(), 
                interval = 100;
            $latest.text('').css({left:0, opacity:1}).show();

            $.each(text, function(i, letter) {
              setTimeout(function() {
                $latest.text(function(i, current) {
                  return letter + current;
                });
                if (i == (text.length - 1)) {
                  setTimeout(function() {
                    $latest.hide();
                    current++;
                    animateLatest();
                  }, 10000);
                }
              }, (i * interval) + 10);
            });
         };
      $.getJSON('/latest.json', function(json) {
        updates = json;
        animateLatest();
      });
    }
    
    // Sammy gallery app
    if ($('#content.studio').length == 1) {
       if (window.location.pathname.toString().match(/studio\/.+/)) {
         window.location = '/studio#' + window.location.pathname;
       } else if($.trim(window.location.hash.toString()).length > 2) {
         // hide the initial image
         $('#content .gallery').hide();
       }
       app.run();
     }
     
    // Store
    
    $('#content.store .images a').click(function(e) {
      e.preventDefault();
      var src = $(this).attr('rel');
      $(this)
        .closest('.item').find('.image img').attr('src', src).end().end()
        .siblings('a').removeClass('active').end()
        .addClass('active');
    });
    
    $('#content.store .image.has-multiple').click(function(e) {
      var $active = $(this).closest('.item').find('.images a.active');
      if ($active.next('a').length) {
        $active.next('a').click();
      } else {
        $active.closest('.images').find('a:first').click();
      }
    });
    
    // homepage
    
    $('.hover-ani')
      .hover(function() {
        $(this).find('.hoverable').attr('src', function(i, src) {
          return src.replace(/reg/, 'rollover');
        });
      }, function() {
        $(this).find('.hoverable').attr('src', function(i, src) {
          return src.replace(/rollover/, 'reg');
        });
      });
      
    // footer rollovers
    $('#footer li img')
      .hover(function() {
        $(this).attr('src', function(i, src) {
          return src.replace(/\_?(active)?\.gif$/, '_active.gif');
        });
      }, function() {
        $(this).attr('src', function(i, src) {
          return src.replace(/\_active\.gif$/, '.gif');
        });
      });
      
    
  });

})(jQuery);