/*
    SPREAD jquery plugin for easy and nice Twitter & Facebook sharing + Directo email
    29.1.2010 //Antti

    USAGE
    1. load bit.ly javascript api
    2. load jquery
    3. load this plugin

    Then you are ready to rock:
    $("#your .selector").spread();

    or with options (see full list from script below):
    $("#your .selector").spread({email: false, twitterText: "Piippaa twitteriin", title: "My site is best", hashtags:"#mytag"});


    Since this is javascript-only, please hide your toggler-link as default and show it through javascript. Example below:

    HTML:
    <a href="#" id="share-toggler" style="display: none">Share this page</a>

    JS (jQuery):
    $("#share-toggler").show().spread();

*/

(function($) {



  $.fn.spread = function(options) {

    var defaults = {
      useToggler: true,
      twitter: true,
      facebook: true,
      email: true,
      nobitly: false,
      currentUrl: location.href,
      twitterText: "Jaa Twitterissä",
      facebookText: "Jaa Facebookissa",
      emailText: "Jaa sähköpostilla",
      title: document.title,
      tweetLength: 120,
      animationSpeed: "fast",
      closeText: "sulje",
      hashtags: ""
    };

    // Global options
    spreadOptions = $.extend(defaults, options);
    if (spreadOptions.tweetLength > 120)
      spreadOptions.tweetLength = 120;

    spreadOptions.tweetLength = spreadOptions.tweetLength - spreadOptions.hashtags.length - 20; // 20 is bitly url length. Ie. http://bit.ly/34tYab

    if (spreadOptions.useToggler) {
      $('<div class="sharebox share-nocontainer" id="sharebox" style="display: none"><span class="close">'+ spreadOptions.closeText +'</span> </div>').appendTo('body');
    } else {
      $(this).replaceWith('<div class="sharebox share-container" id="sharebox"></div>')
    }


    if (spreadOptions.email == true)
      $('#sharebox').prepend('<a href="#email" title="Email" class="email">' + spreadOptions.emailText + '</a>');

    if (spreadOptions.facebook == true)
      $('#sharebox').prepend('<a href="#facebook" title="Facebook" class="facebook">' + spreadOptions.facebookText + '</a>');

    if (spreadOptions.twitter == true)
      $('#sharebox').prepend('<a href="#twitter" title="Twitter" class="twitter">' + spreadOptions.twitterText + '</a>');

    return this.each(function(i) {

      $(this).addClass("jakowidget").show();


      $('a', '#sharebox').click(function(){
          go($(this).attr('class')); // Take the classname as a parameter for go function
          $('.share-nocontainer').addClass("sharebox-loading");
      });

      $('span', '.sharebox').click(function(){
          $(this).parent().slideUp(spreadOptions.animationSpeed);
          $(".toggler-open").removeClass("toggler-open");
      });




      // apply plugin functionality to each element
      $(this).click(function(){

        var offset = $(this).offset();
        offset.top = offset.top + $(this).height() + 4;
        $('.share-nocontainer').hide().css({'position': 'absolute', 'top': offset.top, 'left': offset.left}).removeClass("sharebox-loading");

        if($(this).hasClass("toggler-open")) {
          $(".toggler-open").removeClass("toggler-open");
        } else {
          $(".toggler-open").removeClass("toggler-open");
          $('.share-nocontainer').slideToggle(spreadOptions.animationSpeed);
          $(this).addClass("toggler-open");
          return false;
        }

      });
    });

    function go(service) {
      if (service == "twitter") {
        if (spreadOptions.noBitly == true) {
          title = crop_string(spreadOptions.title, spreadOptions.tweetLength);
          location.href = "http://twitter.com/home?status=" + location.href + " " + title;
        } else {
          BitlyClient.shorten(location.href, 'BitlyCB.tweet');
        }
      }

      if (service == "facebook")
        location.href = "http://www.facebook.com/sharer.php?u=" + encodeURIComponent(location.href) + "&t=" + encodeURIComponent(spreadOptions.title);

      if (service == "email") {
        $(".toggler-open").removeClass("toggler-open");
        $('.share-nocontainer').hide();
        return d4_open_edit_window("/@SendLink/Edit?lang=fi&link=" + spreadOptions.currentUrl, 480, 460);

      }

      return false;
    }
  }

  BitlyCB.tweet = function(data) {
      var s = '';
      var first_result;

      // Results are keyed by longUrl, so we need to grab the first one.
      for     (var r in data.results) {
              first_result = data.results[r]; break;
      }
      bitlyUrl = first_result.shortUrl;
      if(bitlyUrl == undefined)
          bitlyUrl = '';

      title = crop_string(spreadOptions.title, spreadOptions.tweetLength);
      redirect_url = title + " " + spreadOptions.hashtags + " " + bitlyUrl;
      redirect_url = encodeURIComponent(redirect_url);
      location.href = "http://twitter.com/home/?status=" + redirect_url;
    }

    // This is only for you dear 140 injured twitter
    function crop_string(source_string, string_length) {
      if (source_string.length > string_length) {
          while(string_length > 0) {

          // Break the loop if last char is space
          if (source_string.charAt(string_length) == ' ')
              break;

          // Make the string one char shorter
          source_string = spreadOptions.title.substring(0,string_length);
          string_length--;
          }
      }
      source_string = spreadOptions.title.substring(0,string_length);
      return source_string;
    }

    $(document).click(function(){
      if( $(".jakowidget").hasClass('toggler-open')) {
        $(".jakowidget").toggleClass('toggler-open');
        $(".share-nocontainer").hide();
      }

    });

})(jQuery);

