// jCarousel Lite
(function($){$.fn.jCarouselLite=function(o){o=$.extend({btnPrev:null,btnNext:null,btnGo:null,mouseWheel:false,auto:null,speed:200,easing:null,vertical:false,circular:true,visible:3,start:0,scroll:1,beforeStart:null,afterEnd:null},o||{});return this.each(function(){var b=false,animCss=o.vertical?"top":"left",sizeCss=o.vertical?"height":"width";var c=$(this),ul=$("ul",c),tLi=$("li",ul),tl=tLi.size(),v=o.visible;if(o.circular){ul.prepend(tLi.slice(tl-v-1+1).clone()).append(tLi.slice(0,v).clone());o.start+=v}var f=$("li",ul),itemLength=f.size(),curr=o.start;c.css("visibility","visible");f.css({overflow:"hidden",float:o.vertical?"none":"left"});ul.css({margin:"0",padding:"0",position:"relative","list-style-type":"none","z-index":"1"});c.css({overflow:"hidden",position:"relative","z-index":"2",left:"0px"});var g=o.vertical?height(f):width(f);var h=g*itemLength;var j=g*v;f.css({width:f.width(),height:f.height()});ul.css(sizeCss,h+"px").css(animCss,-(curr*g));c.css(sizeCss,j+"px");if(o.btnPrev)$(o.btnPrev).click(function(){return go(curr-o.scroll)});if(o.btnNext)$(o.btnNext).click(function(){return go(curr+o.scroll)});if(o.btnGo)$.each(o.btnGo,function(i,a){$(a).click(function(){return go(o.circular?o.visible+i:i)})});if(o.mouseWheel&&c.mousewheel)c.mousewheel(function(e,d){return d>0?go(curr-o.scroll):go(curr+o.scroll)});if(o.auto)setInterval(function(){go(curr+o.scroll)},o.auto+o.speed);function vis(){return f.slice(curr).slice(0,v)};function go(a){if(!b){if(o.beforeStart)o.beforeStart.call(this,vis());if(o.circular){if(a<=o.start-v-1){ul.css(animCss,-((itemLength-(v*2))*g)+"px");curr=a==o.start-v-1?itemLength-(v*2)-1:itemLength-(v*2)-o.scroll}else if(a>=itemLength-v+1){ul.css(animCss,-((v)*g)+"px");curr=a==itemLength-v+1?v+1:v+o.scroll}else curr=a}else{if(a<0||a>itemLength-v)return;else curr=a}b=true;ul.animate(animCss=="left"?{left:-(curr*g)}:{top:-(curr*g)},o.speed,o.easing,function(){if(o.afterEnd)o.afterEnd.call(this,vis());b=false});if(!o.circular){$(o.btnPrev+","+o.btnNext).removeClass("disabled");$((curr-o.scroll<0&&o.btnPrev)||(curr+o.scroll>itemLength-v&&o.btnNext)||[]).addClass("disabled")}}return false}})};function css(a,b){return parseInt($.css(a[0],b))||0};function width(a){return a[0].offsetWidth+css(a,'marginLeft')+css(a,'marginRight')};function height(a){return a[0].offsetHeight+css(a,'marginTop')+css(a,'marginBottom')}})(jQuery);

// dropdown plugin
(function($){
  var instances = [];

  function Dropdown(elem, opts) {
    this.elem = $(elem);
    this.opts = $.extend({}, $.fn.dropdown.options, opts);
    this.init();
  }

  Dropdown.prototype = {
    init: function() {
      this.elem.addClass("dropdown-menu").hide();

      // define some default states
      this.isOpen = false;
      this.isSubOpen = false;
      this.itemChosen = false;

      // create the button
      var button = this.button = $('<a>')
        .attr("href", "#")
        .addClass("dropdown-trigger")
        .text(this.opts.buttonLabel);

      // create a button arrow
      this.buttonArrow = $('<span>')
        .prependTo(this.button);

      // inject arrow into the DOM
      button.insertBefore(this.elem);

      // go through each top level nav and append a +/- icon
      /*
      this.elem.children("li").each(function(i, elem){
        elem = $(elem);

        if(elem.children("ul").length) {
          elem.addClass("submenu contracted");
        }
      });
      */

      this._registerEvents();
      this._setMenuWidth();

      instances[instances.length] = this;
    },

    _registerEvents: function() {
      this.button.bind("click", $.proxy(this.toggle, this));
      this.elem.delegate("li.submenu > a", "click", $.proxy(function(event){
        event.preventDefault();
        this._toggleSubMenu(event.currentTarget);
      }, this));
      
      this.elem.delegate("li:not(.submenu) a", "click", $.proxy(this.toggle, this));

      /*
      this.elem.delegate("a", "click", $.proxy(function(event) {
        var target = $(event.currentTarget);
        if(target.parent().hasClass("submenu")) return;
        this._setButtonText(target.text());
      }, this));
      */
  },

    _setMenuWidth: function() {
      this.elem.width( this.button.outerWidth(true) );
    },

    _toggleSubMenu: function(elem) {
      var li = $(elem).closest(".submenu");

      function toggle(li) {
        var menu = li.children("ul");
        var flag = menu.is(":visible");
        li.toggleClass("contracted", flag);
        menu[ flag ? "hide" : "show" ]();
      }

      toggle(li);

      li.siblings().each(function(){
        this.className.indexOf("contracted") === -1 && toggle( $(this) );
      });
    },

    _setButtonText: function(value) {
      !value && (value = this.startValue);

      this.startValue = this.button.text();

      this.button.contents().filter(function() {
        return this.nodeType === 3;
      })[0].nodeValue = value;
    },

    _restoreButtonText: function() {
      this._setButtonText(this.startValue || "");
    },

    toggle: function(event) {
      event && event.preventDefault();
      this[ this.isOpen ? "close" : "open" ]();
    },

    open: function() {
      this.isOpen = true;
      this.elem.show().addClass("expanded");
      this.button.addClass("expanded");
      this._setButtonText(this.elem.children().first().text());
    },

    close: function() {
      this.isOpen = false;
      this.elem.hide().removeClass("expanded");
      this.button.removeClass("expanded");
      if(!this.itemChosen) this._restoreButtonText();
    }
  };

  // close all instances when clicking outside
  $(document).bind("click", function(event){
    var target = $(event.target);

    if(target.closest(".dropdown").length === 0 && target.closest(".dropdown-trigger").length === 0) {
      $.each(instances, function(i, instance){
        instance.isOpen && instance.toggle();
      });
    }
  });

  $.fn.dropdown = function(opts) {
    return this.each(function(i, elem){
      elem = $(elem);
      var instance = elem.data("dropdown");
      !instance && elem.data("dropdown", new Dropdown(this, opts));
    });

    $.fn.dropdown.options = {
      buttonLabel: "Click to open"
    };
  };

})(jQuery);


// application wrapper
(function($) {

    var app = {
        init: function() {
            this.playlist.init();
            this.grid.init();

            $(".dropdown").dropdown({ buttonLabel: unescape(Resources.HPVideos).replace('{0}', sectionTitle) });
        }
    };

    // sidebar playlist module
    app.playlist = {
        init: function() {
            this.elem = $("#sidebar ul").delegate("li", "click", $.proxy(this.handler, this));
        },

        handler: function(event) {
            if ($(event.target).closest(".sub-grid").length) {
                return;
            }

            this.toggle(event.currentTarget);
            this.closeOthers(event.currentTarget);
        },

        toggle: function(elem) {
            elem = $(elem);
            var icon = elem.find(".toggle");
            var content = elem.find("ul");
            var isOpen = content.is(":visible");

            // toggle icon
            icon.toggleClass("expand", isOpen).toggleClass("contract", !isOpen);

            // show the drawer
            content[isOpen ? "slideUp" : "slideDown"]("fast");

            // toggle active class
            elem.toggleClass("active", !isOpen);

            // scroll to top
            elem.parent().scrollTop(0);
        },

        closeOthers: function(exclude) {
            this.elem.children("li.active").not(exclude).each($.proxy(function(i, elem) {
                this.toggle(elem);
            }, this));
        }
    };


    // video grid
    app.grid = {
        init: function() {
            var grid = this.grid = $("#grid");

            this.paginationLinks = $("#page-pagination-next, #page-pagination-prev")
        .live("click", $.proxy(this.spinner, this));

            $(".pagination")
        .delegate("a", "click", $.proxy(this.spinner, this));

            this.adjustHeight();
        },

        adjustHeight: function() {
            var height = this.height = this.grid.height();
            this.paginationLinks.height(height);
            $("#page-pagination-next-inactive, #page-pagination-prev-inactive").height(height);
        },

        spinner: function(event) {
            event.preventDefault();
            //var overlay = $("#grid-overlay").show();
            //overlay.css("padding-top", this.height/2 - 65);
        }
    };

    // init on document ready
    $(document).ready($.proxy(app.init, app));

    // expose
    window.app = app;

})(jQuery);

