$(function () {
    var st = new ShareThis({
        selector: '.actions .share a',
        urlAttr: 'href',
        titleAttr: 'title'
    });
});

function ShareThis(options) {
    var currentUrl = window.location.href;
    var index = currentUrl.indexOf("/artists");
    var subtitle = " | Radar Music";
    var subtitleTW = "Check this out - ";
    if (index != null && index > 0) {
        subtitle = " | Radar Artists";
        subtitleTW = "Check out this artist @radarnewmusic ";
    }
    options = $.extend({
        selector: '.actions .share a',
        urlAttr: 'href',
        titleAttr: 'title',
        shareId: 'share',
        hoverTimeout: 100,
        services: {
            facebook: {
                enabled: true,
                url: 'http://www.facebook.com/sharer/sharer.php?u={url}',
                //url: 'http://www.facebook.com/sharer.php?s=100&p[title]={title}' + subtitle + '&p[url]={url}&p[summary]=Radar Music - Artist Page. Latest songs, interviews, reviews and articles for Radar Music bands and artists. Upload your music and get added to Radar Music.',
                popup: {
                    w: 720,
                    h: 250
                }
            },
            twitter: {
                enabled: true,
                url: 'http://twitter.com/share?url={url}&text={title}&source=radarradiocomau',
                popup: {
                    w: 650,
                    h: 300
                }
            },
            googleplus: {
                enabled: true,
                url: '',
                //				url: 'https://m.google.com/app/plus/x/?v=compose&content={title}&url={url}',
                popup: {
                    w: 700,
                    h: 400
                }
            },
            stumbleupon: {
                enabled: true,
                url: 'http://www.stumbleupon.com/submit?url={url}&title={title}',
                popup: {
                    w: 750,
                    h: 900
                }
            },
            tumblr: {
                enabled: true,
                url: 'http://www.tumblr.com/share/link?url={url}&name={title}',
                popup: {
                    w: 750,
                    h: 900
                }
            }
        }
    }, options);

    var 
		self = this,
		shareTO;

    // constructor
    (function () {
        _initCreateDom();
        _initBindDom();
    })();

    function _initCreateDom() {
        var 
			$st = $('<div></div>'),
			service,
			serviceHtml = '';
        // build the container & behaviour
        $st
			.hide()
			.attr('id', options.shareId)
			.hover(function () {
			    clearTimeout(shareTO);
			}, function () {
			    shareTO = setTimeout(function () {
			        $('#' + options.shareId).hide();
			    }, options.hoverTimeout);
			});
        // build the services buttons
        for (var serviceName in options.services) {
            service = options.services[serviceName];
            if (service.enabled) {
                serviceHtml += '<button class="service service-' + serviceName + '" data-service="' + serviceName + '" data-service-url="' + service.url + '"></button>';
            }
        }
        $st.html(serviceHtml);
        $st.find('button').click(function () {
            var 
				$st = $(this).parent(),
				title = $st.attr('data-title'),
				link = $st.attr('data-link'),
				serviceName = $(this).attr('data-service'),
				url = $(this).attr('data-service-url'),
				buildUrl = socialBuildUrl(url, serviceName, link, title), //url.replace('{url}', socialMediaLink(serviceName, link)).replace('{title}', socialMediaTitle(serviceName, title, link)), //(serviceName=='tumblr'?encodeURIComponent(title):title)),
				service = options.services[serviceName];
            window.open(buildUrl, 'sharethis', 'width=' + service.popup.w + ', height=' + service.popup.h);
        });
        $st.appendTo('body');
    }
    function socialBuildUrl(url, serviceName, link, title) {
        var strReturn = '';        
        var currentUrl = window.location.href;
        var index = currentUrl.indexOf("/artists/");
        if (serviceName == 'twitter') {
            if (!((index != null && index > 0) || (link.indexOf("/artists/") != null && link.indexOf("/artists/") > 0)))
                url = url + '&via=radarnewmusic';
        }

        strReturn = url.replace('{url}', socialMediaLink(serviceName, link)).replace('{title}', socialMediaTitle(serviceName, title, link))

        return strReturn;
    }
    function socialMediaTitle(serviceName, title, link) {
        var strReturn = '';
        var currentUrl = window.location.href;
        var index = currentUrl.indexOf("/artists/");
        if ((index != null && index > 0) || (link.indexOf("/artists/") != null && link.indexOf("/artists/") > 0)) {
            if (serviceName == 'twitter')
                strReturn = "Check out this artist @radarnewmusic " + title;
            else if (serviceName == 'tumblr')
                strReturn = encodeURIComponent(title);
            else
                strReturn = title;
        }
        else {
            if (serviceName == 'twitter')
                strReturn = "Check this out -  " + title;
            else if (serviceName == 'tumblr')
                strReturn = encodeURIComponent(title);
            else
                strReturn = title;
        }
        
        return strReturn;
    }
    function socialMediaLink(serviceName, link) {
        var strReturn = '';
        var currentUrl = window.location.href;
        var index = currentUrl.indexOf("/artist");
        if ((index != null && index > 0) || (link.indexOf("/artist/") != null && link.indexOf("/artist/") > 0)) {
            if (serviceName == 'tumblr' || serviceName == 'twitter')
                strReturn = encodeURIComponent(link);
            else
                strReturn = link;
        }
        else {
            if (serviceName == 'tumblr')
                strReturn = encodeURIComponent(link);
            else
                strReturn = link;
        }
        return strReturn;
    }
    function _initBindDom() {
        $(options.selector)
			.hover(function () {
			    if ($(this).is('[disabled], .disabled')) return;
			    //clearTimeout(shareTo);
			    $('#' + options.shareId)
					.attr('data-title', $(this).attr(options.titleAttr))
					.attr('data-link', $(this).attr(options.urlAttr))
			    var o = $(this).offset();
			    var lft = o.left - 136;
			    if (lft < 0) {
			        lft = 0;
			    }
			    $('#share')
					.css({
					    top: o.top - 40,
					    left: lft
					}).show();
			}, function () {
			    // hide share bar!
			    shareTO = setTimeout(function () {
			        $('#share').hide();
			    }, options.hoverTimeout)

			})
			.click(function () {
			    return false; // prevent default
			});
    }
}
