var Soundlink = function () {

	var	player,
		assetsUrl,
		playImg,
		pauseImg,
		stopImg;

    var handleInit = function (selector, url) {
		assetsUrl = url;
		playImg = url + '/img/play.png';
		pauseImg = url + '/img/pause.png';
		stopImg = url + '/img/stop.png';
		
		$('body').append('<div id="jquery_jplayer"></div>');
		
		initPlayer(assetsUrl);
		handleLinkClick(selector);
		handlePauseClick(selector);
		handleStopClick(selector);
    };

	var handleLinkClick = function (selector) {
        $('body').on('click', '.' + selector, function (e) {
            e.preventDefault();
			handleDestroy(selector);
			playAudio($(this).prop('href'));
			displayController($(this), selector);
        });
	};

	var handlePauseClick = function (selector) {
        $('body').on('click', '#' + selector + '-pause', function (e) {
            e.preventDefault();
			if ($(this).prop('paused') == true) {
				player.jPlayer("play");
				$(this).prop('paused', false);
				$(this).children().first().prop('src', pauseImg);
			} else {
				player.jPlayer("pause");
				$(this).prop('paused', true);
				$(this).children().first().prop('src', playImg);
			}
        });
	};

	var handleStopClick = function (selector) {
        $('body').on('click', '#' + selector + '-stop', function (e) {
            e.preventDefault();
			player.jPlayer("stop");
			handleDestroy(selector);
        });
	};

    var playAudio = function (url) {
		player.jPlayer("setMedia", {
			mp3: url
		}).jPlayer("play");
    };

	var displayController = function (link, selector) {
		$(link).qtip({
			content: {
				text: '<a href="#" id="'+ selector +'-pause"><img src="' + pauseImg + '" alt="pause" title="Pauza" /></a> <a href="#" id="'+ selector +'-stop"><img src="' + stopImg + '" alt="stop" title="Stop" /></a>',
			},			
			show: true,
			hide: {
				fixed: true,
				delay: 300
			},
			position: {
				my: 'bottom center',
				at: 'top center',
				corner: 'rightMiddle'
			},
			style: {
				classes: 'qtip-bootstrap qtip-shadow'
			}		
		});			
	};
	
	var initPlayer = function () {
		player = $("#jquery_jplayer");
		player.jPlayer({
			ready: function () {
			},
			timeupdate: function(event) {
			},
			play: function(event) {
				$(this).jPlayer("pauseOthers");
			},
			pause: function(event) {
			},
			ended: function(event) {
			},
			solution:"html, flash",
			swfPath: assetsUrl + "/jPlayer.2.6.0",
			supplied: "mp3",
			wmode: "window",
			cssSelectorAncestor: "#jquery_jplayer"
		});
	};

	var handleDestroy = function (selector) {
		$('.' + selector).each(function(){
			$(this).qtip('destroy', true);
		})
	};

    return {

        init: function (selector, assetsUrl) {
            handleInit(selector, assetsUrl); 
        },
        reload: function(selector) {
            handleLinkClick(selector);
            handlePauseClick(selector);
            handleStopClick(selector);
        }

    };

}();