var carousel = {
  init: function() {

    if($('#spotlight').length){

      $('#spotlight').css('overflow', 'hidden');

      $('#spotlight-items').css({
        'width': '9999px',
        'height': '331px'
      });
      // d = scrollable speed
      $.easing.custom = function (x, t, b, c, d) {
        if ((t/=d/2) < 1) return c/2*t*t + b;
        return -c/2 * ((--t)*(t-2) - 1) + b;
      }

      var spotlightApi = $('#spotlight')
        .scrollable({
          items: '#spotlight-items',
          size: 1,
          clickable: false,
          speed: 500,
          easing: 'custom'
        })
        .navigator({
          navi: '#spotlight-nav',
          activeClass: 'active',
          api: true
        });

      $('#spotlight-nav li').each(function(i){
        if($(this).hasClass('active'))
          spotlightApi.setPage(i, 0);
      });

      $(".spotlight-sub-content").each(function(){
        var id = $(this).attr('id');

        $(this).scrollable({
          items: '#' + id + '-items',
          vertical: true,
          size: 1,
          clickable: false,
          speed: 500,
          easing: 'custom'
        })
        .navigator({
          navi: '#' + id + '-nav',
          activeClass: 'active'
        });

      });

      /* Flash video visibility hack */
      $('.spotlight-sub-content-items')
        .find('li object')
        .wrap('<div class="spotlight-video" />')
        .end()
        .find('.spotlight-video')
        .css({'display': 'none'})
        .end()
        .find('li:first-child .spotlight-video')
        .css({'display': 'block'});

      $('.spotlight-sub-nav li').bind('click', function() {
        $('.spotlight-sub-nav li').each(function(i){
          if($(this).hasClass('active')) {
            $('#spotlight')
              .find('.spotlight-video')
              .css({'display': 'none'})
              .end()
              .find('.spotlight-sub-content-items li:eq(' + i + ') .spotlight-video')
              .css({'display': 'block'});
          }
        });
      });

      $('#spotlight-nav li').bind('click', function() {
        $('#spotlight-nav li').each(function(i){
          if($(this).hasClass('active')) {
            $('#spotlight')
              .find('.spotlight-video')
              .css({'display': 'none'})
              .end()
              .find('#spotlight-items li:eq(' + i + ') .spotlight-video')
              .css({'display': 'block'});
          }
        });
      });
    }
  }
}

var contentScroll = {
  classScrollable: '.scroll',
  classPrev: '.scroll-prev',
  classNext: '.scroll-next',
  classMore: '.scroll-more',
  classLess: '.scroll-less',
  border: 1,
  options: {
    api: true,
    speed: 500,
    size: 3,
    disabledClass: 'disabled',
    easing: 'linear',
    keyboard: false,
    clickable: false,
    vertical: true
  },

  init: function(){
    var _this = this;


    $('.scroll-container').each(function() {

      var scrollContainer = $(this);

      var id = $(this).attr('id');
      var options = $.extend({}, _this.options);

      switch(id){
        case 'potd':
          options.size = 1;
          options.vertical = false;
          break;
        case 'mostpopularartists':
        case 'upcomingevents':
        case 'birthdays':
        case 'lastaddedmedia':
        case 'shoutbox':
          options.size = 3;
          break;
        case 'top20':
        case 'social-stream-twitter':
        case 'social-stream-hyves':
        case 'social-stream-facebook':
          options.size = 4;
          break;
        case 'gallery-thumbs':
          options.size = 7;
          options.vertical = false;
          break;
      }


      // Remove scroll navigation when not enough items are present
      if(options.size >= $(this).find('.items > li').length) {
        $(this).find('.scroll-nav').remove();
      }

      var api = $(this)
        .find(contentScroll.classScrollable)

        .bind('mouseover', function(){
          $(this).next().addClass('hover');
        })
        .bind('mouseout', function(){
          $(this).next().removeClass('hover');
        })
        .scrollable(options)
        .onSeek(function() {
          disabledCheck.init();
        })

      $(this)
        // Next
        .find(contentScroll.classNext)
        .data('api', api)
        .bind('mousedown', function(e) {
          var $this = $(this);
          $this.data('api').nextPage();
          $this.data('interval', setInterval(function() {
            $this.data('api').nextPage();
          }, options.speed));
        })
        .bind('mouseup mouseout', function() {
          clearInterval($(this).data('interval'));
        })
        .end()

        // Previous
        .find(contentScroll.classPrev)
        .data('api', api)
        .bind('mousedown', function() {
          var $this = $(this);
          $(this).data('api').prevPage();
          $(this).data('interval', setInterval(function() {
            $this.data('api').prevPage();
          }, options.speed));
        })
        .bind('mouseup mouseout', function() {
          clearInterval($(this).data('interval'));
        })
        .end()

        // More
        .find(contentScroll.classMore)
        .data('api', api)
        .bind('click', function() {
          var $scrollable = $(this).parent().find(contentScroll.classScrollable);
          var $itemsVisible = $(this).data('api').getVisibleItems().length;

          // If visible items is less then max-size AND total amount of items in scrollable is greater then scrollable size
          if($(this).data('api').getVisibleItems().length < 10 && $(this).data('api').getSize() > $(this).data('api').getConf().size) {
            $scrollable.animate({
              // + 1 is the border, .height() won't measure border values
              height: $scrollable.height() + $(this).parent().find('.items li').height() + contentScroll.border
            }, options.speed);

            $(this).data('api').getConf().size++;
            if($(this).data('api').getVisibleItems().length < $(this).data('api').getConf().size) {
              $(this).data('api').end(options.speed);
            }
          }
        })
        .end()

        // Less
        .find(contentScroll.classLess)
        .data('api', api)
        .bind('click', function() {
          var $scrollable = $(this).parent().find(contentScroll.classScrollable);

          // If visible items is NOT 1
          if($(this).data('api').getVisibleItems().length != 1) {
            $scrollable.animate({
              height: $scrollable.height() - $(this).parent().find('.items li').height() - contentScroll.border
            }, options.speed);

            $(this).data('api').getConf().size--;

          }
        });

        var disabledCheck = {
          init: function() {
            if(api.getIndex() === scrollContainer.find('.items > li').length - options.size) {
              scrollContainer.find(contentScroll  .classNext).addClass('inactive');
            } else {
              scrollContainer.find(contentScroll.classNext).removeClass('inactive');
            }
            if(api.getIndex() === 0) {
              scrollContainer.find(contentScroll.classPrev).addClass('inactive');
            } else {
              scrollContainer.find(contentScroll.classPrev).removeClass('inactive');
            }
          }
        }

        disabledCheck.init();
    });
  }

}

var elastic = {
  init: function() {
    $('#comment-form textarea').each(function() {

      var areaHeight = $(this).height();
      $(this)
      .data('originalHeight', areaHeight)
      .bind('focus', function() {
        $(this).elastic();
      })
      .bind('blur', function() {
        if($(this).val() == '')
        $(this).css({
          height: $(this).data('originalHeight')
        });
      });
    });
  }
}

var poll = {
  init : function() {
    if($('#poll-form').length > 0)
      $('#poll-form').submit(function(e) {
        e.preventDefault();

        $.post(
          $(this).attr('action'),
          $('#poll-form').serialize(),
          function(data) {
            $('#poll').html(data);
          }
        );
      });
  }
};

var pagination = {
  init: function() {
    $('.pagination a, .pagination-alphabet a').live('click', function(e) {
      e.preventDefault();
      var paginationAnimate = true
      if($(this).parent().hasClass('.pagination-alphabet')) var paginationAnimate = false;

      $.history.load(this.href.replace(/^.*#/, ''));
    });
  },

  loadContent: function(link, animate){
    $('#pagination-content').load(link, function(){
      if(animate) $('html, body').animate({scrollTop:$(this).offset().top}, 500);
      fhHover.init();
      fancybox.init();
      elastic.init();
    });
  }
}

var faq = {
  init: function() {

    // Scroll categories
    $('#faq-category-links a')
      .bind('click', function(e){
        e.preventDefault();
        $('html, body').animate({scrollTop:$('#' + $(this).attr('id') + '-holder').offset().top}, 500);
      });

    // Toggle questions
    $('.faq-list > li')
      .find('.wysiwyg')
      .hide()
      .end()

      .find('a')
      .bind('click', function(e){
        e.preventDefault();

        $this = $(this);
        $this
          .parent()
          .find('.wysiwyg')
          .slideToggle(function(){
            $this.parent().find('.more').toggleClass('less');
          });
      });

  }
}

var notification = {
  init: function(){
    $('#notification a.btn-close').live('click', function(e){
      e.preventDefault();
      $('#notification').fadeOut('slow', function(){
        $(this).remove();
      });
    });
  }
}

var fancybox = {
  social: null,
  init: function(){

    if(typeof(openFancybox) != 'undefined'){
      $.fancybox({
        'href': openFancybox,
        'type': 'iframe',
        'overlayOpacity': 0.7,
        'overlayColor': '#000000',
        'transitionIn': 'none',
        'padding': 0,
        'height': 185,
        'backgroundColor': 'none',
        'scrolling': 'no',
        'showNavArrows': false,
        'hideOnOverlayClick': false,
        'onCleanup': function() {
          fancybox.social = $('#fancybox-frame').contents().find('#share-popup').html();
        },
        'onClosed': function() {
          if (fancybox.social != null) {
            parent.window.scroll(0,0);
            parent.window.location = parent.window.location;
          }
        }
      });
    }

    $('a[rel*=fancybox]').each(function(){
      if($(this).hasClass('iframe')){
        $(this).attr('href', $(this).attr('href') + ($(this).attr('href').indexOf('?') > 0 ? '&' : '?') + 'fancybox=true')
      }
      $(this).fancybox({
        'overlayOpacity': 0.7,
        'overlayColor': '#000000',
        'padding': 0,
        'height': 185,
        'backgroundColor': 'none',
        'transitionIn': 'none',
        'scrolling': 'no',
        'showNavArrows': false,
        'hideOnOverlayClick': false,
        'onCleanup': function() {
          fancybox.social = $('#fancybox-frame').contents().find('#share-popup').html();
        },
        'onClosed': function() {
          if (fancybox.social != null) {
            parent.window.scroll(0,0);
            parent.window.location = parent.window.location;
          }
        }
      });
    });

    if($('#iframe').length > 0){
      parent.fancybox.resize($('#iframe').outerHeight());
    }
  },

  resize: function(height){
    if($('#potd-widget-container').length)
    {
      var width = 410;
    }
    else
    {
      var width = 560;
    }
      
    $('#fancybox-inner').css({
      'height': height + 'px',
      'width': width + 'px'
    });
    $('#fancybox-wrap').css({
      'height': height + 'px',
      'width': width + 'px'
    });

    $.fancybox.center();
  }
}

var qtip = {
  init: function(){
    $('.social-holder').each(function(){
      var text = $(this).next().html();
      $(this).qtip({
        content: {
          text: text
        },
        show: 'mouseover',
        hide: {
          fixed: true,
          delay: 500
        },
        position: {
          corner: {
             target: 'topMiddle',
             tooltip: 'bottomMiddle'
          }
        },
        style: {
          background: '#ffffff',
          border: {
            radius: 0,
            width: 3,
            color: '#f99900'
          },
          padding: 4,
          color: '#000000',
          tip: {
            corner: 'bottomMiddle',
            color: '#f99900',
            size: {
              x: 20,
              y : 6
            }
          },
          title: {
            'color': '#ffffff',
            'overflow': 'hidden',
            'background': '#7fc4f3',
            'font-size': '12px'
          }
        }
      });
    });
  }
};

var media = {
  ajaxCall: true,

  init: function() {
    // Prev next links
    $('#media a.prev, #media a.next').live('click', function(e) {
      e.preventDefault();
      if(media.ajaxCall){
        $.history.load(this.href.replace(/^.*#/, ''));
      }
    });

    // Key press handling
    $(document).keydown(function(e) {
      if(media.ajaxCall){
        if (e.keyCode == 37 && $('a.prev', '#media').length > 0) {
         $('a.prev', '#media').trigger('click')
        }
        if (e.keyCode == 39 && $('a.next', '#media').length > 0) {
         $('a.next', '#media').trigger('click');
        }
      }
    });

    // Gallery thumbs
    $('#gallery-thumbs .items', '#media')
      .find('a')
      .live('click', function(e) {
        e.preventDefault();
          $.history.load(this.href.replace(/^.*#/, ''));
      });

  },

  loadContent: function(link, animate){
    media.ajaxCall = false;

    $('#media').load(link, function(){
      if(animate) $('html, body').animate({scrollTop:$(this).offset().top}, 500);
      media.ajaxCall = true;
      fancybox.init();
      qtip.init();
      /*
        Bug: After ajax call textarea doesn't collapse
        Fix: Keep elastic infront of inputClear for now
      */
      elastic.init();
      inputClear.init();
      pagination.init();
      contentScroll.init();

      $('#gallery #gallery-item').css({
        'background': 'none'
      });

      media.thumbIndex();

    });
  },

  thumbIndex: function(){
    var $galleryScroll = $('#gallery-thumbs .scroll').scrollable();

    $('#gallery-thumbs .items a').each(function(i){
      if(i < $galleryScroll.getSize() - 3){
        if($(this).hasClass('active')){
          $galleryScroll.seekTo(i - 3, 0);
        }
      } else {
        if($(this).hasClass('active')){
          $galleryScroll.end(0);
        }
      }
    });
  }
}

var popup = {
  init: function() {
    if($('#tvlive, #radio, #top20-listen').length > 0) {
      $('#tvlive .btn-readmore, #radio .btn-readmore, #top20-listen').bind('click', function(e) {
        e.preventDefault();
        var $container = $('#tvlive, #radio');

        var $link = $(this).attr('href');
        var $width = 'width=' + $container.find('object').attr('width');
        var $height = 'height=' + $container.find('object').attr('height');

        if($(this).attr('id') === 'top20-listen') {
          var $width = 'width=450';
          var $height = 'height=300';
        }

        var $options = $width + ',' + $height + ', scrollbars=no, toolbar=no, location=no';

        window.open($link, '', $options);
      });
    }
  }
}

var inputClear = {
  init: function() {
    $('input, textarea').fhInputClear();
  }
}

var stHistory = {
  loaded: false,

  getContent: function(hash) {
    if(!hash && stHistory.loaded) {
      var hash = window.location.href;
    }
    if(hash) {
      var request = hash.indexOf('http');

      if(request > -1) {
        if($('#media').length){
          media.loadContent(hash, false);
        }
        if($('#pagination-content').length){
          pagination.loadContent(hash, true);
        }
      }
    }
    stHistory.loaded = true;
  }
}

var relatedArtist = {
  init: function() {
    $this = $('#medium_has_artist');

    if(!$this.is(':checked')) {
      $this.parent().next().hide();
      $this.parent().next().next().hide();
    }

    $this
      .bind('click', function() {
        if($(this).is(':checked')) {
          $this.parent().next().slideDown();
          $this.parent().next().next().slideDown();
          parent.fancybox.resize($('#iframe').outerHeight() + 24);
          $.fancybox.center();
        } else {
          $this.parent().next().slideUp();
          $this.parent().next().next().slideUp();
        }
      });
  }
}

var fhHover = {
  init: function() {
    $('.list, .list-related')
    .not('.fhNoHover')
    .find('li')
    .fhHover();
  }
}

var searchResults = {
  init: function() {
    $('#search-results .filter form')
      .find('input[type=checkbox]')
      .live('click', function() {
        $.ajax({
          data: $('#search-results .filter form').serialize(),
          url: $('#search-results .filter form').attr('action'),
          success: function(data) {
            $('#search-results').replaceWith(data);
            fhHover.init();
          }
        });
      });
  }
}

var socialStreams = {
  init: function() {
    $social = $('#social-streams');
    $tabs = $('.tabs li', $social);

    $('[class|=social-container]', $social).hide();

    $('.tabs li.current', $social).each(function() {
      $('.social-container-' + $(this).attr('rel'), $social).show();
    });

    $tabs.live('click', function(e) {
      e.preventDefault();

      $tabs.removeClass('current');
      $(this).addClass('current');

      $('[class|=social-container]', $social).hide();

      $('.social-container-' + $(this).attr('rel'), $social).show();
    });

  }
}

var selectVideo = {
  init: function() {
    $('#select-video-trigger').live('change', function() {
      $('#congrats-select-video').load($(this).attr('data-url') + $(this).val());
    });
    $('#congrats-select-video a.prev, #congrats-select-video a.next').live('click', function(e) {
      e.preventDefault();
      $('#congrats-select-video').load($(this).attr('href'));
    });
  }
}

var commentCharacterCount = {
  init: function() {
    if($('#shoutbox-comment-form'))
    {
      $('#shoutbox-comment-form #comment_text').live('keyup', function(e){
        var $commentFormLength = $(this).val().length;
        var $maxchar = $('#comment-form-maxchar').html() - 1;

        $('#comment-form-characterValue').html(0 + $commentFormLength);

        if($commentFormLength > $maxchar) {
          this.value = this.value.substr(0, $maxchar);
        }
      });
    }
  }
}

$(document).ready(function() {

  $('body').addClass('js');

  $.history.init(stHistory.getContent);

  carousel.init();
  socialStreams.init();
  contentScroll.init();
  elastic.init();
  poll.init();
  pagination.init();
  faq.init();
  notification.init();
  fancybox.init();
  qtip.init();
  relatedArtist.init();
  media.init();
  popup.init();
  searchResults.init();
  fhHover.init();
  selectVideo.init();
  commentCharacterCount.init();

  $('#media-upload-form input[type=file]').gzPrettyForms();

  inputClear.init();

  $('a[rel*=external]').attr('target', '_blank');

  $('a[rel*=external]').live('click', function(){
    $(this).attr('target', '_blank');
  });

});
