 /*
 * iShare
 * Copyright 2011 Daniel Paul
 * www.danielpaul.me
 *
 * ishare - http://codecanyon.net/user/DanielPaul
 *
 * Version 1.5   -   Updated: July 27, 2011
 *
 * Licence: http://codecanyon.net/wiki/support/legal-terms/licensing-terms/
 *
 */

(function($){
	$.fn.ishare = function(options) {
		var defaults = {
			activation: "hover", // hover or click
			keepAlive: false, // true or false
			width: "370px",
			height: "115px",
			edgeOffset: 10, // how far should the tooltip be from the link
			position: "left", // top, bottom, left or right
			delay: 400, // how long till fadeIn
			fadeIn: 400, // fadeIn speed
			fadeOut: 600, // fadeOut speed
			fadeOut_delay: 500, // how long till fadeOut

			iconsDir: "templates/web/img/icons/",

			displayTitle: true, // true or flase
			title: "Compartir", // ishare box title

			sharetitle: "", // sharing page's title
			shareurl: "", // URL to share

			icons: "facebook,twitter,google,digg,delicious,stumbleupon,myspace,tumblr,linkedin,bebo,mixx,friendfeed",
			targetBlank: true, // open link in new tab? true or false

			fbLikebox: true, // display facebook like box? true or false
			fbAction: "like", // like or recommend?
			fbcolorscheme: "light", // light or dark

			tweets: true, // diaplay tweet button? true or false
			tweetText: "Check out this URL",
			tweetVia: "", // via twitter account
			twitterRelated: "_DanielPaul", // related twitter account
			tweetButton: "Tweet",

			gplus: true, // display Google Plus one button? true or false

		  	enter: function(){}, // ishare enter function
		  	exit: function(){} // ishare exit function
	  	};
	 	var opts = $.extend(defaults, options);




	 	// ***** Sharing services URL format list
	 	var iformat				=	new Object();
	 	iformat.digg			=	"http://digg.com/submit?phase=2&url={URL}&title={TITLE}";
	 	iformat.linkedin		=	"http://www.linkedin.com/shareArticle?mini=true&url={URL}&title={TITLE}&summary={DESCRIPTION}&source=";
	 	iformat.technorati		=	"http://www.technorati.com/faves?add={URL}";
	 	iformat.delicious		=	"http://del.icio.us/post?url={URL}&title={TITLE}";
	 	iformat.yahoo			=	"http://myweb2.search.yahoo.com/myresults/bookmarklet?u={URL}&t={TITLE}";
	 	iformat.google			=	"http://www.google.com/bookmarks/mark?op=edit&bkmk={URL}&title={TITLE}";
	 	iformat.newsvine		=	"http://www.newsvine.com/_wine/save?u={URL}&h={TITLE}";
	 	iformat.reddit			=	"http://reddit.com/submit?url={URL}&title={TITLE}";
	 	iformat.live			=	"https://favorites.live.com/quickadd.aspx?marklet=1&mkt=en-us&url={URL}&title={TITLE}&top=1";
	 	iformat.facebook		=	"http://www.facebook.com/share.php?u={URL}";
	 	iformat.twitter			=	"http://twitter.com/?status={TITLE}%20-%20{URL}";
	 	iformat.stumbleupon		=	"http://www.stumbleupon.com/submit?url={URL}&title={TITLE}";
	 	iformat.orkut			=	"http://promote.orkut.com/preview?nt=orkut.com&tt={TITLE}&du={URL}&cn={DESCRIPTION}";
	 	iformat.bebo			=	"http://www.bebo.com/c/share?Url={URL}&title={TITLE}";
	 	iformat.evernote		=	"http://s.evernote.com/grclip?url={URL}&title={TITLE}";
	 	iformat.mixx			=	"http://www.mixx.com/submit?page_url={URL}&title={TITLE}";
	 	iformat.myspace			=	"http://www.myspace.com/Modules/PostTo/Pages/?u={URL}&title={TITLE}";
	 	iformat.netvibes		=	"http://www.netvibes.com/share?title={TITLE}&url={URL}";
	 	iformat.tumblr			=	"http://www.tumblr.com/share?v=3&u={URL}&t={TITLE}&s=";
	 	iformat.google_buzz		=	"http://www.google.com/reader/link?url={URL}&title={TITLE}&srcURL={URL}";
	 	iformat.friendfeed		=	"http://friendfeed.com/share/bookmarklet/frame#title={TITLE}&url={URL}";
	 	iformat.design_moo		=	"http://www.designmoo.com/node/add/drigg/?url={URL}&title={TITLE}";
	 	iformat.designfloat	=	"http://www.designfloat.com/submit.php?url={URL}&title={TITLE}";
	 	iformat.design_bump		=	"http://www.designbump.com/node/add/drigg/?url={URL}&title={TITLE}";
	 	iformat.squidoo			=	"http://www.squidoo.com/lensmaster/bookmark?{URL}";
	 	iformat.yahoo_buzz		=	"http://buzz.yahoo.com/buzz?targetUrl={URL}&headline={TITLE}&summary={DESCRIPTION}";
	 	iformat.print			=	'javascript:void(0);" onClick="print_page();" target="_self';
	 	iformat.favorites		=	'javascript:void(0);" onClick="bookmark_us();" target="_self';


	 	if(opts.activation == 'hover'){
  	 	this.click(function(){
  	 	  return false;
  	 	});
  	}


  	var ishare = $('<div id="ishare_holder" style="width:'+ opts.width +';"></div>');
  	ishare.css({position: 'absolute', zIndex: 100000});

  	// * if display ishare title, set title
  	var title = '';
  	if (opts.displayTitle) {
  	  var title = $('<div id="ishare_title">'+ opts.title +'<span id="ishare_close"><a href="javascript:void(0);" class="ishare_close">X</a></span></div>');
  	}

  	// * add the share icons
  	var icons = $('<div id="ishare_icons" style="height:'+ opts.height +';"></div>');


  	var fbLikebox = '';
  	if(opts.fbLikebox) {
  	  var fbLikebox = '<iframe src="http://www.facebook.com/plugins/like.php?href='+ encodeURL(sharing_url()) +'&amp;layout=button_count&amp;width=100&amp;action='+ opts.fbAction +'&amp;colorscheme='+ opts.fbcolorscheme +'&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px; height:21px;" allowTransparency="true"></iframe>';
  	}


  	if(opts.tweetVia){
  	  var tweet_via = '&amp;via='+opts.tweetVia;
  	} else {
  	  var tweet_via = '';
  	}

  	var tweets = '';
  	if(opts.tweets) {
  	  var tweets = '<iframe allowtransparency="true" frameborder="0" scrolling="no" src="http://platform.twitter.com/widgets/tweet_button.html?url='+ encodeURL(sharing_url()) +'&amp;text='+ encodeURL(opts.tweetText) + '&amp;related='+ encodeURL(opts.twitterRelated) + tweet_via +'" style="width:100px; height:21px;"></iframe>';
  	}

  	var gplus = '';
  	if(opts.gplus) {
  	  var gplus = '<iframe allowtransparency="true" frameborder="0" scrolling="no" src="https://plusone.google.com/u/0/_/+1/fastbutton?url='+ encodeURL(sharing_url()) +'&amp;size=medium" style="width:70px; height:21px;"></iframe>';
  	}

  	// * if have any extras (fb likebox or tweet button)
  	var extras = '';
  	if (opts.fbLikebox || opts.tweets) {
  	  var extras = $('<div id="ishare_extras">' + gplus + tweets + fbLikebox +'</div>');
  	}


  	ishare.html(title); // add the title
  	ishare.append(icons, extras); // add the icons and extras


  	var share = opts.icons.split(","); // Get buttons
  			for ( var key in share ) {
  				var services = share[key];
  				var name = services.replace(/_/gi, " ");
  				var url = iformat[services];
  				if(opts.targetBlank){
  				  var target = '_blank';
  				} else {
  				  var target = '_self';
  				}
  				if(url){
  					url = url.replace("{TITLE}", encodeURL(sharing_title()));
  					url = url.replace("{URL}", encodeURL(sharing_url()));
  					url = url.replace("{KEYWORDS}", encodeURL(ishare_metakeywords()));
  					url = url.replace("{DESCRIPTION}", encodeURL(ishare_metadescription()));

  					var sharelink = '<a href="' + url + '" target="' + target + '"><div class="ishare_icon"><img src="'+ opts.iconsDir + name + '.png"><span>' + name + '</span></div></a>';
  					$(sharelink).appendTo(icons); // Add share buttons
  				}
  			}




	 	return this.each(function() {

      // * set activation method
      if(opts.activation == 'hover'){
        var activation_method = 'mouseenter click';
      } else {
        var activation_method = opts.activation;
      }

      // *** Action!
      $(this).bind(activation_method, function() {

        ishare.stop();

        opts.enter.call(this);

        // * get the position to display ishare in the right place
        var pos = $.extend({}, $(this).offset(), {width: this.offsetWidth, height: this.offsetHeight});

        ishare.get(0).className = 'ishare_ishare'; // reset classname in case of dynamic position
        ishare.remove().css({top: 0, left: 0, visibility: 'hidden', display: 'block'}).appendTo(document.body);

        var actualWidth = ishare[0].offsetWidth, actualHeight = ishare[0].offsetHeight;
        var position = (typeof opts.position == 'function') ? opts.position.call(this) : opts.position;

        switch (position) {
          case 'bottom':
            ishare.css({top: pos.top + pos.height + opts.edgeOffset, left: pos.left + pos.width / 2 - actualWidth / 2}).addClass('ishare_bottom');
            break;
          case 'top':
            ishare.css({top: pos.top - actualHeight - opts.edgeOffset, left: pos.left + pos.width / 2 - actualWidth / 2}).addClass('ishare_top');
            break;
          case 'left':
            ishare.css({top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth - opts.edgeOffset}).addClass('ishare_right');
            break;
          case 'right':
            ishare.css({top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width + opts.edgeOffset}).addClass('ishare_left');
            break;
        }

        ishare.css({opacity: 0, display: 'block', visibility: 'visible'}).animate({opacity: 1}, opts.fadeIn);

      }); // END action!


      // *** Clean up...
      $(this).bind('mouseleave', function() {

        var self = this;
        if(!opts.keepAlive){
          var fadeout = setTimeout(function() {
            opts.exit.call(this);
            ishare.animate({opacity: 0}, opts.fadeOut, function(){
              ishare.css({display: 'none', visibility: 'hidden'});
            });
          }, opts.fadeOut_delay);
        }

        ishare.hover(function(){
          if(!opts.keepAlive) clearTimeout(fadeout);
        }, function(){

          var fadeout = setTimeout(function() {
            opts.exit.call(this);
            ishare.animate({opacity: 0}, opts.fadeOut, function(){
              ishare.css({display: 'none', visibility: 'hidden'});
            });
          }, opts.fadeOut_delay);

        });

        $('#ishare_close').click(function(){
          opts.exit.call(this);
          ishare.animate({opacity: 0}, opts.fadeOut, function(){
            ishare.css({display: 'none', visibility: 'hidden'});
          });
        });

        $(this).bind(activation_method, function() {
         if(!opts.keepAlive) clearTimeout(fadeout);
        });

      }); // END clean up...

    }); // END this.function


    /***** Easy functions START */

    // * Encode url
    function encodeURL(string) {
    	if(!string){ // if there is nothing to process
    		return "";
    	}
    	return string.replace(/\s/g, '%20').replace('+', '%2B').replace('/%20/g', '+').replace('*', '%2A').replace('/', '%2F').replace('@', '%40');
    	// Encode URL by replacing the string's special characters
    }

    // * Get sharing title
    function sharing_title() {
      if(opts.sharetitle) { // if share title is set
      	return opts.sharetitle;
      } else { // if not, get the page title
      	return document.title; // Get page title
      }
    }

    // * Get URL to share
    function sharing_url(){
    	if(opts.shareurl) {// if sharing url is set
    		return opts.shareurl;
    	} else { // if not, get the page URL
    	return document.location.href; //Get the page URL
    	}
    }

    // * Get meta keywords
    var ishare_keywords = '';
    function ishare_metakeywords() {
    	if(ishare_keywords === ''){
    		metaCollection = document.getElementsByTagName('meta');
    		for (i=0;i<metaCollection.length;i++) {
    			nameAttribute = metaCollection[i].name.search(/keywords/);
    			if (nameAttribute!= -1) {
    				ishare_keywords = metaCollection[i].content;
    				return ishare_keywords;
    			}
    		}
    	}else{
    		return ishare_keywords;
    	}
    }

    // * Get meta description
    var ishare_description = '';
    function ishare_metadescription() {
    	if(ishare_description === ''){
    		metaCollection = document.getElementsByTagName('meta');
    		for (i=0;i<metaCollection.length;i++) {
    			nameAttribute = metaCollection[i].name.search(/description/);
    			if (nameAttribute!= -1) {
    				ishare_description = metaCollection[i].content;
    				return ishare_description;
    			}
    		}
    	}else{
    		return ishare_description;
    	}
    }

    /* END Easy Functions *****/

    function print_page(){
      window.print();
    }
    function bookmark_us() {
    	alert('Press ctrl + D to bookmark');
    }


	}
})(jQuery);
