var SLIDESHOWS_PER_PAGE = 20;
var owner_login = window.location.toString().split("/")[3];


var find_selected_tab = function(selected_tab) {
  var temp = selected_tab.siblings('div').filter(function(index) {
    return !$(this).hasClass("hide");
  });
  return temp;
};

var select_first_slideshow = function (){
  //Don't wory about the hard coded pptTab. Its just that we need a starting point from where we can iterate.'
  var selected_tab = find_selected_tab($('a.pptTab'));
  var temp = selected_tab.children('ul.clearfix').children(':first-child').children('a.j-imageanchor');
  temp.addClass('selected');
  return temp;
};

//Gloabal variable which stores what image is currently selected.
var selected_slideshow = select_first_slideshow();

var construct_slideshow_li = function(ss_type, element, slideshow) {
  var clone = element.prev().clone();
  clone.attr("id", ss_type + "_" + slideshow.id);
  var anchor_ele = clone.find("a");
  anchor_ele.attr("title", slideshow.title);
  var description = slideshow.description;
  if (slideshow.description.length > 200) {
    description = description.substr(0,200);
    description = description + "...";
  }
  anchor_ele.attr("data-description", description);
  anchor_ele.attr("data-hits", slideshow.hits_count);
  anchor_ele.attr("href", '/' +  owner_login + '/' + slideshow.stripped_title);
  var image_ele = clone.find("img");
  image_ele.attr("id", slideshow.id);
  image_ele.attr("alt", slideshow.title);
  image_ele.attr("src", slideshow.thumbnail_image);
  return clone;
};

var insert_slideshows = function(element, ss_type, slideshows) {
  $.each(slideshows, function(index, slideshow) {
    var slideshow_ele = construct_slideshow_li(ss_type, element, slideshow);
    element.before(slideshow_ele);
  });
};

var load_default_ss = function(data,selected_tab) {
  var first_child = selected_tab.next().children().children().children('a.j-imageanchor');
  if (first_child.length > 0) {
    var id = first_child.children().children('img').attr('id');
    var link = first_child.attr('href');
    var title = first_child.attr('title') || first_child.attr('original-title');
    var new_embed_link = "http://www.slideshare.net/slideshow/embed_code/" + id +
      "?hostedIn=" + hostedIn + "&referer=" + referer;
    var iframe = selected_tab.parents('div#main_div').children('div.pptOnDisplay').children('iframe');
    var old_embed_link = selected_tab.parents('div#main_div').children(
      'div.pptOnDisplay').children('iframe').attr('src');
    if (old_embed_link != new_embed_link) {
      var meta_data = iframe.next().children(':first-child');
      var meta_data_hits = meta_data.next();
      var meta_data_description = meta_data_hits.next();
      var hits = first_child.attr('data-hits');
      var description = first_child.attr('data-description');
      iframe.attr('src',new_embed_link);
      meta_data.attr('href', link);
      meta_data.attr('title', title);
      meta_data.text(title);
      meta_data_hits.text(hits + ' views');
      meta_data_description.text(description);
    }
  }
};

var show_hide_div = function(selected_tab) {
  var div_to_hide = find_selected_tab(selected_tab);
  var div_to_show = selected_tab.next();
  if(div_to_hide[0] == div_to_show[0]) {
    return;
  }

  var callback = function() {
    div_to_hide.addClass("hide");
    div_to_show.removeClass("hide");
  };

  div_to_hide.slideUp('slow');
  div_to_show.slideDown('slow', callback);
};

var show_embed = function() {
  $('.embed-overlay-container').toggle();
    $('a#j-iframe-copier').zclip({
    path: '/javascripts/plugins/ZeroClipboard.swf',
    copy: function() {
      return $('input#embed-iframe').val();
    },
    afterCopy:function(){
      $('#j-iframe-msg').css("display", "block");
    }
  });
  
};

$('.j-upload_cta').click(function(e) {
  top.set_window_location('/upload');
});

$('.j-pro_cta').click(function(e) {
  top.set_window_location('/business/premium/plans?cmp_src=slideshelf');
});


//TODO: Dry this function
var register_listeners = function(config) {
  //capture the click on the thumbnails
  $(".j-imageanchor").live('click', function(e){
    _gaq.push(['_trackEvent', 'slideshelf', 'thumbnail_clicked']);
    e.preventDefault();
    var selected_ppt = $(this);
    var iframe = selected_ppt.parents('div#main_div').children('div.pptOnDisplay').children('iframe');
    var link = selected_ppt.attr('href');
    var title = selected_ppt.attr('original-title');
    var new_embed_link = "http://www.slideshare.net/slideshow/embed_code/" +
      selected_ppt.children().children('img').attr('id') +
      "?hostedIn=" + hostedIn + "&referer=" + referer;
    var old_embed_link = selected_ppt.parents('div#main_div').children(
      'div.pptOnDisplay').children('iframe').attr('src');
    // if the link is the same, no need to load the iframe again.
    if (old_embed_link != new_embed_link) {
      //Don't parse DOM until and unless required
      var meta_data = iframe.next().children(':first-child');
      var meta_data_hits = meta_data.next();
      var meta_data_description = meta_data_hits.next();
      var hits = selected_ppt.attr('data-hits');
      var description = selected_ppt.attr('data-description');
      iframe.attr('src',new_embed_link);
      meta_data.attr('href', link);
      meta_data.attr('title', title);
      meta_data.text(title);
      selected_slideshow.removeClass('selected');
      selected_ppt.addClass('selected');
      selected_slideshow = selected_ppt;
      meta_data_hits.text(hits + ' views');
      meta_data_description.text(description);
    }
  });

  $.each({'.j-pptTab':'pptList', '.j-docTab':'docList', '.j-vidTab':'vidList'}, function (key, value) {
    $(key).bind('click', function(e){
      e.preventDefault();
      var selected_tab = $(this);
      show_hide_div(selected_tab);
      load_default_ss(value,selected_tab);
    });
  });

  //load more slideshows via ajax

  $.each(["presentations","documents","videos"], function(index, ss_type) {
    $("#show_more_" + ss_type).click(function(e) {
      return function(e) {
        $(e.target).next().show();
        $(e.target).hide();
        $.ajax({
          url: '/' + owner_login + '/slideshelf/load_more_slideshows',
          data: {
            slideshow_type: ss_type,
            offset: config.presentations_offset
          },
          success: function(response) {
            if(response["has_more_" + ss_type]) {
              $(e.target).show();
            }
            $(e.target).next().hide();
            insert_slideshows($(e.target).parent(), ss_type, response[ss_type]);
            config.presentations_offset += SLIDESHOWS_PER_PAGE;
          },
          dataType: 'json',
          async: true
        });
      }(e);
    });
  });

  //Tipsy tooltips
  $('.j-tooltip').tipsy({ gravity: 'n',live: true });
};

var register_sorting_listener = function() {
  $('#sorting_order').change(function(e) {
    // Submit the form whenever the order is changed to anything other than custom
    if(e.target.value !== "3") {
      $('form#sorting').submit();
    }
  });
};

var setup_edit_mode = function() {
  var sorting_menu = $('#sorting_order');
  sorting_menu.show();
  register_sorting_listener();
  //Using the jQuery UI's sortable
  $('.sortable').sortable({
    delay:'100',
    update: function(event, ui) {
      //If sorting has been used and dropdown is not custom - change it to custom
      if(sorting_menu.val() !== "3") {
        sorting_menu.val("3");
        $(".j-show_more").hide();
      }
    }
  });
  $('.sortable').disableSelection();
};

var edit_slideshelf = function() {
    var width = $(window).width();
    var height = $(window).height();
    var iframe_large_width = 760;
    var iframe_large_height = 570;
    var iframe_small_width = 490;
    var iframe_small_height = 470;
    var width_topbar = 0;
    // When embeded in small size
    if ((width === iframe_small_width) && (height === iframe_small_height )){
      width_topbar = 480 - 11;
      //hide the side bar
      $('div.related-tab').hide();
      //udpate the embed button topnav
      $('.topbar').css('width', width_topbar);
      //update the embed window
      $('.embed-overlay-container').css('width',width_topbar - 30);
      $('.embed-overlay-container').css('height',349);
    }
    // when embeded in large size
    else if ((width === iframe_large_width) && (height === iframe_large_height)){

      var width_ppt_on_display = 595;
      var width_morerelated = 154;
      width_topbar = width_ppt_on_display + width_morerelated - 11;
      // set the height in which the slideshow is loaded.
      $('iframe.ssIframeLoader').css('width', width_ppt_on_display);
      $('.pptOnDisplay').css('width', width_ppt_on_display);
      $('iframe.ssIframeLoader').css('height', 497);
      
      //set the height of the embed bar and embed overlay
      $('.topbar').css('width', width_topbar);
      $('.embed-overlay-container').css('width',width_topbar - 30);
      $('.embed-overlay-container').css('height',457);
      
      //set the realted tab settings
      $('.moreRelated').css('width', width_morerelated);
      $('.moreRelated').css('height', 425);
      $('.related-tab').css('height', 495);

      //scale the images inside the related
      $('.j-accordionList').children('ul').children('li').children('a').children('span').css('width', 120);
      $('.j-accordionList').children('ul').children('li').children('a').children('span').css('height', 90);
      $('.j-accordionList').children('ul').children('li').children('a').children('span').children('img').css('min-height', 90);
      $('.j-accordionList').children('ul').children('li').children('a').children('span').children('img').css('width', 120);
      
    }
};

var get_params = function() {
  var list = "";
  var sorting_order = $('#sorting_order').val();
  if(sorting_order === "3") {
    $('.sortable').each(function(index, element) {
      list += $(element).sortable('serialize');
    });
    list = list.match(/[0-9]+/g);
  }
  return {sorting_order: sorting_order,
           slideshows: list};
};

var get_url_vars = function(url) {
  url = url ? url : window.location.href;
  var vars = [], hash;
  var hashes = url.slice(url.indexOf('?') + 1).split('&');
  for(var i = 0; i < hashes.length; i++)
  {
    hash = hashes[i].split('=');
    vars.push(hash[0]);
    vars[hash[0]] = hash[1];
  }
  return vars;
};

var embed_size_selected_toggle = function(object) {
  $('.embed-size-selected').removeClass('embed-size-selected');
  $(object).addClass('embed-size-selected');

};
$('.j-embed-cancel').click(function() {
  $('.embed-overlay-container').toggle();
  $('#j-iframe-msg').css("display", "none");
});


$('.j-embed-small').click(function(e) {
  embed_size_selected_toggle(this);
  var small = $('.h-embed-code').attr('embed_link_small');
  $('.h-embed-code').val(small);
  $('#j-iframe-msg').css("display", "none");
});

$('.j-embed-medium').click(function(e) {
  embed_size_selected_toggle(this);
  var medium = $('.h-embed-code').attr('embed_link_medium');
  $('.h-embed-code').val(medium);
  $('#j-iframe-msg').css("display", "none");
});

$('.j-embed-large').click(function(e) {
  embed_size_selected_toggle(this);
  var large = $('.h-embed-code').attr('embed_link_large');
  $('.h-embed-code').val(large);
  $('#j-iframe-msg').css("display", "none");
});

$(document).ready(function() {
  // Don't mess up if you are hosted within slidehsare
   if ((hostedIn !== "slideshare")){
     edit_slideshelf();
   }
    var config = {
      presentations_offset: SLIDESHOWS_PER_PAGE,
      documents_offset: SLIDESHOWS_PER_PAGE,
      videos_offset: SLIDESHOWS_PER_PAGE
    };
    register_listeners(config);
    if(get_url_vars(window.location.toString()).mode === 'edit') {
      setup_edit_mode();
    }
    window._gaq = _gaq || [];
    _gaq.push(['_trackPageview']);
    _gaq.push(['_trackEvent', 'slideshelf', 'load']);

});
