$(function(){
  // Variables
  var channel_media_player = 'div#channelMediaPlayer';
  var offer = '.offer';
  var offer_undo = '.offer_undo';
  var offer_undo_link = offer_undo + ' a';  
  var undo_timeout = 10000;
  var no_thanks_link = '.no_thanks';
  var collapse_button = 'a.collapse_btn';
  var collapse_elem = '#collapse';
  var expand_style = 'expand_btn';
  var scrollable_area = "#channels";
  var scrollable_items = '.c1';
  var player_preview = '.mini_player.flash .small_play';
  var show_more_link = '.show_more a';
  var adCompanion = '#companion';
  var advert_panel = '#companion.advert';
  var description_panel = '.channel_area .description';
  var wideView = $.cookie('channelWideView') || "false";
  
  var premium_area = '#premium_area';
  var premium_link = '.premium_link';
  var default_area = '#default_area';
  var premium_timeout_1 = ((3 * 60) * 1000); // 3 minutes
  var premium_timeout_2 = ((4 * 60) * 1000); // 4 minutes


  if(CarouselPaginator != undefined){ 
    //CarouselPaginator.visibleItems = channels_number; - This is set by jquery.adaptive.js
    CarouselPaginator.advertVisible = $('.mpu_advert').length != 0;
    CarouselPaginator.paginationContainer = scrollable_area; 
    CarouselPaginator.paginationItems = scrollable_items;
    CarouselPaginator.currentItemSelector = scrollable_items + '.selected';
    CarouselPaginator.bindEvents();
  }
  
  function showPremiumArea(){
     $(premium_area).each(function(){
      $(default_area).slideUp().idle(premium_timeout_2).slideDown();
      $(this).slideDown().idle(premium_timeout_2).slideUp();
    });
  };
  
  function preventPremiumAreaHide(){
    $(default_area).stop(true);
    $(this).stop(true);
  };
  
  // Set up default for the offer panel
  $(offer_undo).hide();
  
  $('#toggle_auto_start').click(function(){
    $.post('/channels/toggle_auto_start');
    return false;
  });
  
  $.fn.toggleWideView = function(){
    if(wideView == "true"){
      $(this).makeNarrow();
    }else{
      $(this).makeWide();
    }
  }
  
  $.fn.makeWide = function(){
    $('head').append('<link rel="stylesheet" href="/stylesheets/restyle/big_video.css" type="text/css" id="big_video" />');
    CarouselPaginator.advertVisible = false;
    CarouselPaginator.setVisibleItems(12);
    $('div#media_player').css({"width":"850px"});
    $('div.wrapper').smartWidthEnabled(false);
    $.cookie('channelWideView', "true", {expires: 7});
    wideView = "true";
    _gaq.push(['_trackEvent', 'Channels', 'Wide View']);
  }
  
  $.fn.makeNarrow = function(){
    $('link#big_video').remove();
    $('div.wrapper').smartWidthEnabled(true);
    $.cookie('channelWideView', null, {expires: 7});  
    wideView = "false";
    $('div#media_player').css({"width":"630px"});
    _gaq.push(['_trackEvent', 'Channels', 'Narrow View']);
  }

  // Set up the media player for the channel using custom jQuery plugin
  if($('body.ipad').length == 0){
    $(channel_media_player).mediaPlayer(); 
  }
  // Set up hiding the offer panel, and hide the undo link after 10 seconds
  $(no_thanks_link).click(function(){ 
    $(offer).slideUp();
    $(offer_undo).slideDown().idle(undo_timeout).slideUp();
    return false;
  });
  
  // Show the premium area if it exists after n seconds
  setTimeout(function(){
   showPremiumArea();
  }, premium_timeout_1);
  
  // Override the Show premium link so it displays the sidebar
  $(premium_link).click(function(){
    showPremiumArea();
    return false;    
  });
  
  // Set up the undo link. Must stop the effect chain before adding new ones.
  $(offer_undo_link).click(function(){
    $(offer).slideDown();
    $(offer_undo).stop().slideUp();
    return false;
  })  
  
  // Channels list collapse
  $(collapse_button).toggle(
    function(){
      $(collapse_elem).slideUp();
      $(this).addClass(expand_style);
      return false;
    },
    function(){
      $(collapse_elem).slideDown();
      $(this).removeClass(expand_style);
      return false;
    }
  );
  
  // Dim the lights!
  $("a.dim_the_lights").click(function() { 
    try{
      // perform exposing for the clicked element 
      channel_expose = $(channel_media_player).expose({color: '#171717', api: true}).load(); 
    }catch(e){
      alert("Sorry, we can't do this on your browser yet" + e)
    }
  }); 

  //if(!ps3Browser() && !iPadBrowser()){
  //  $('ul#quality.switch li a').click(function(){
  //    // Unhighlight the deselected buttons
  //    $(this).parent('li').siblings().children('a').each(function(){
  //      $(this).removeClass('current');
  //    })
  //    $(this).addClass('current');
  //    preventPremiumAreaHide();
  //    $(channel_media_player).loadPlayer()
  //    return false;
  //  });
  //};

  
  try{
    $('ul#quality.switch li a.apple_overlay').unbind().overlay({mask:'#000'});    
  }catch(e){
    // skip overlay
  }


  $(show_more_link).toggle(
    function(){
      $(advert_panel).slideUp();
      $(description_panel).slideDown();
      $(this).html('Hide info...');
    },
    function(){
      $(advert_panel).slideDown();
      $(description_panel).slideUp();
      $(this).html('More info...');
    }
  );

  // Overwrite the document.write and writeln methods because they are evil
  var tmpDocWrite = document.write;
  var tmpDocWriteln = document.writeln;
  document.write = function(arg){ $('.mpu_advert').append(arg); };
  document.writeln = function(arg){ $('.mpu_advert').append(arg) + '\n'; };
  
  // Function to retrieve a new advert from the server.
  function getAdvert(){
    $.get('/advert.html', {}, function(data){
    $('.mpu_advert').html('');
    $('.mpu_advert').html(data);
    }, 'html');
  }
  

  // Reload the advert unit periodically
  var refreshId = setInterval(function() {
    //getAdvert();
  }, (60000 * 5));
  
  // Tabs
   $("ul.channel_tabs").tabs("div.channel_panes > div");
   
  // See what tabs were clicked in Google analytics
  var channel_tabs_api = $('ul.channel_tabs').data('tabs');
  if(channel_tabs_api != undefined){
    channel_tabs_api.onClick(function(index){
      try{
        var tabTxt = $(index.originalTarget).text();
        tabTxt = tabTxt.replace(/^\s+|\s+$/g,"");
        var channelName = $('#default_area h1').html();  
        _gaq.push(['_trackEvent', 'Channels', channelName, tabTxt]);
      }catch(e){
        //
      }  
    }); 
  }
  
  // Youtube loading
  var yt_url = $('#youtube_videos').attr('data-remote');
  $('#youtube_videos').load(yt_url);
  
  if(wideView == "true"){
    $(channel_media_player).makeWide();
  }
  
});