Share = function (el, options) {
	var t = this;
	this.options = $.extend({}, this.options, options || {});
	this.container = $(el);
	this.container.click(function (e) {
		var target = $(e.target);
		if (target.attr('tagName').toLowerCase() == "a") {
			// Does the links classname match any regex in t.jsLinks?
			if (!t.jsLinks.length || !($.grep(t.jsLinks, function (regex) { return regex.test(target.attr('class')); })).length) {
				// If not, open links href in new window
				e.preventDefault();
				window.open(e.target.href, '', t.options.windowOptions);
			}
			// Log event
			try {
				t.logEvent(target.attr('class').replace(/^service-/, ''));
			} catch (e) {};
		}
	});
	if (this.options.addToFavourites) {
		this.createAddToFavouritesLink();
	}
};
Share.prototype = {

	// Default options
	options: {
		addToFavourites: false,
		addToFavouritesText: 'Favoriter',
		windowOptions: 'toolbar=no,width=800,height=500,scrollbars=yes'
	},

	// Classnames matching special services, such as Add to favourites
	jsLinks: [],

	/**
	 * Log share event with Google Analytics
	 * @param  service  String  Name of sharing service
	 */
	logEvent: function (service) {
		if (window.pageTracker) {
			// TODO: behövs document.URL här, eller loggas det ändå?
			window.pageTracker._trackEvent('Share', service, document.URL);
		}
	},

	/**
	 * Add an 'add to favorites' link in supported browsers
	 */
	createAddToFavouritesLink: function () {
		this.jsLinks.push(/\bservice-add-favourite\b/);
		this.favouritesLink = $('<li><a href="' + document.URL + '" class="service-add-favourite" title="Lägg till i favoriter">' + this.options.addToFavouritesText + '</a></li>');
		this.container.prepend(this.favouritesLink);
		try {
			if (window.sidebar && window.sidebar.addPanel) {
				// Firefox
				this.favouritesLink.click(function (e) {
					e.preventDefault();
					window.sidebar.addPanel(document.title, document.URL, "");
				});
			} else if (document.all) {
				// Internet Explorer
				this.favouritesLink.click(function (e) {
					e.preventDefault();
					window.external.AddFavorite(document.URL, document.title);
				});
			} else if ($.browser.opera) {
				// Opera
				this.favouritesLink.find('a').attr({
					'rel': 'sidebar',
					'title': document.title
				});
			} else {
				// Other browsers get nothing :(
				this.favouritesLink.remove();
			}
		} catch (e) {
			// To prevent non working link, remove it if something breaks
			this.favouritesLink.remove();
		}
	}
};

$(function () {
	new Share($('.share ul'), {addToFavourites: true});
});