"use strict";

/*globals deconcept, window, document, $, jQuery, DUMAS, SWFObject */

var getPlayerVersion = deconcept.SWFObjectUtil.getPlayerVersion;

/*globals getPlayerVersion */

DUMAS.EMUSIC_PLAYER = (function () {
    var prefix = '/images/samplePlayer/',
	    samplePlayerEnabled = false,
        swfURL, TARGET_VERSION = 9,
        playingHrefId,
        isPlaying = false, playAll = false, 
        playerInstance, currentClick;
	
	function toLog(msg) {
	}

	function toError(msg) {
		window.alert(msg);
	}

	function nextSample() {
		try {
			playerInstance.toFlashNextSample();
		} catch (e) {

        }

	}

	function prevSample() {
		try {
			playerInstance.toFlashPrevSample();
		} catch (e) {

        }
	}    

	function drawPlayerControl() {
		$('div.playerControl div.controls').css('width', '88px');

        var prevSpan = "<span class='prev left'><a href='#' class='prevLink' title='Listen to previous song'></a></span>",
		nextSpan = "<span class='next left'><a href='#' class='nextLink' title='Listen to next song'></a></span>";

        $("a.listenAll").each(function () {
			$(this).parents('span').before(prevSpan);
			$(this).parents('span').after(nextSpan);
		});

		$('span.next a.nextLink').click(function () {
			nextSample();
			return false;
		});
        
		$('span.prev a.prevLink').click(function () {
			prevSample();
			return false;
		});
	}

	function triggerPlayer(trackHref, albHref) {
        try {
            playerInstance.toFlashTriggerPlayer(trackHref, albHref, playAll);
        } catch (e) {

        }
	}

	function initEventHandlers(root) {
		if (samplePlayerEnabled) {
			var imgs;
			$("a:not(.samplePlayClick)[href$='.m3u']", root)
				.addClass('samplePlayClick')
				.bind('click.samplePlay', function (e) {
					var sampleLink = $(this), albHref;
					albHref = sampleLink.parents('div.r').find('a.listenAll').attr('href');
                    currentClick = e.target;

					triggerPlayer(sampleLink.attr('href'), albHref);
					return false;
				});
			$("a:not(.samplePlayDbl)[href^='/samples/m3u/album/']", root)
				.addClass('samplePlayDbl')
				.bind('dblclick.samplePlay', function () {
					try {
						playerInstance.toFlashNextSample();
					} catch (e) {

					}
					return false;
				});

			$("a:not(.sampleHover)[href$='.m3u']", root)
				.addClass('samplePlayHover')
				.mouseover(function () {
					imgs = $(this).children('img');

					if (imgs.attr('src') !== prefix + 'playThrob.gif' && (imgs.attr("src") !== prefix + 'pause.gif')) {
						imgs.attr('src', prefix + 'playOver.gif');
					}
				})
				.mouseout(function () {
					imgs = $(this).children('img');

					if (imgs.attr("src") !== prefix + 'playThrob.gif' && (imgs.attr("src") !== prefix + 'pause.gif')) {
						imgs.attr('src', prefix + 'play.gif');
					}
				});
		}

	}

	function registerFlash() {
		if (getPlayerVersion().major >= TARGET_VERSION && window.location.hostname.substring(0, 3) !== "wmp" && samplePlayerEnabled) {
			var playerObj = new SWFObject(swfURL, "player", "1", "1", "9", "#363634", false);
			$('body').prepend("<div id='soundSamplePlayer' style='position:absolute;top:-9000px'></div>");
			$("a[href^='/samples/m3u/album/']").attr('title', 'Listen to this album');
			$("a[href^='/samples/m3u/song/']").attr('title', 'Listen to this song');
			$("a[href^='/samples/m3u/book/']").attr('title', 'Listen to this book');
			playerObj.write("soundSamplePlayer");
			initEventHandlers();
			drawPlayerControl();
			playerInstance = document.getElementById("player");
		}
	}

	function initPlayer() {
		if ($.browser.opera) {
			window.setTimeout(registerFlash, 500);
		} else {
			registerFlash();
		}
	}

	function enableInlineFlash(swf) {
      if (swf) {
         samplePlayerEnabled = true;
         swfURL = swf;
         $(initPlayer);
      }
	}

	function setTooltip(action, hrefId) {
        var songTarget = $("a[href^='/samples/m3u/song/']"),
            albTarget = $("a[href^='/samples/m3u/album/']"),
            bookTarget = $("a[href^='/samples/m3u/book/']");        

		if (hrefId && action !== 'reset') {
			if (hrefId.indexOf('album') !== -1) {
				$("a[href*=" + hrefId + ".m3u]").attr('title', action + ' album');
				$("a[href*=" + hrefId + ".m3u]").children('img').attr('alt', action + ' album');
			} else if (hrefId.indexOf('book') !== -1) {
				$("a[href*=" + hrefId + ".m3u]").attr('title', action + ' book');
				$("a[href*=" + hrefId + ".m3u]").children('img').attr('alt', action + ' book');
			} else {
				$("a[href*=" + hrefId + ".m3u]").attr('title', action + ' song');
				$("a[href*=" + hrefId + ".m3u]").children('img').attr('alt', action + ' song');
			}
		} else if (action === 'reset') {
			//reset tooltips
			songTarget.attr('title', 'Listen to this song');
			songTarget.children('img').attr('alt', 'Listen to this song');
			albTarget.attr('title', 'Listen to this album');
			albTarget.children('img').attr('alt', 'Listen to this album');
			bookTarget.attr('title', 'Listen to this book');
			bookTarget.children('img').attr('alt', 'Listen to this book');
		}
	}

	function resetAllIcons() {
		//turn off all pause icons and reset tooltip and reset color
		$('p.songName, li').removeClass('selectedSong');
		$("img[src$='playThrob.gif']").attr('src', '/images/samplePlayer/play.gif');
		$("img[src$='pause.gif']").attr('src', '/images/samplePlayer/play.gif');
		setTooltip('reset');
	}      

	function turnOnPlayIcon(theHrefId) {
		$("a[href*=" + theHrefId + ".m3u]").children('img').attr('src', '/images/samplePlayer/play.gif');
	}

	function turnOnPlayAllPlaying(albHref) {
		//turns on the pause btn
		var discTarget = $("a.listenAll[href=" + albHref + "]");
		discTarget.addClass('pauseAll');
		discTarget.attr('title', 'Pause the current song');
	}

	function turnOnPlayAllPause(albHref, playAll) {
		//turns on the play btn, checks to see if alb is playing to display correct tooltip
		var discTarget = $("a.listenAll[href=" + albHref + "]");
		discTarget.removeClass('pauseAll');
		if (playAll) {
			discTarget.attr('title', 'Keep playing the current song');
		} else {
			discTarget.attr('title', 'Listen to all songs on this album');
		}
	}

	function turnOnPlayingIcon(theHrefId) {
		resetAllIcons();
		//color playing text
		if ($("body[id='previewPage']").length) {
			$("a[href*=" + theHrefId + ".m3u]").parent().addClass('selectedSong');
		} else {
			$("a[href*=" + theHrefId + ".m3u]").parents('td.listen').next().children('p.songName').addClass('selectedSong');
		}

        //turn on the correct one
 		$("a[href*=" + theHrefId + ".m3u]").children('img').attr('src', '/images/samplePlayer/playThrob.gif');


        // and give it the appro tooltip
		setTooltip('Pause this', theHrefId);

		$("img[src='/images/samplePlayer/playThrob.gif']").hover(
			function () {
				if ($(this).attr('src') === '/images/samplePlayer/playThrob.gif') {
					$(this).attr('src', '/images/samplePlayer/pause.gif');
				}
			}, function () {
				if ($(this).attr('src') === '/images/samplePlayer/pause.gif') {
					$(this).attr('src', '/images/samplePlayer/playThrob.gif');
			    }
            });
	}

	function turnOnPauseIcon(theHrefId) {
		resetAllIcons();
		//turn on the correct play/pause icon -not implemented now

		if ($("body[id='previewPage']").length) {
			$("a[href*=" + theHrefId + ".m3u]").parent().addClass('selectedSong');
		} else {
			$("a[href*=" + theHrefId + ".m3u]").parents('td.listen').next().children('p.songName').addClass('selectedSong');
		}
		$("a[href*=" + theHrefId + ".m3u]").children('img').attr('src', '/images/samplePlayer/play.gif');
		//tootip
		setTooltip('Keep playing this', theHrefId);
	}

	function resetPlayAll() {
		$('a.listenAll').removeClass('pauseAll');
		$('a.listenAll').attr('name', 'Listen to all songs on this album');
	}

	function reset() {
		if (playerInstance && playerInstance.toFlashReset) {
			playerInstance.toFlashReset();
		}
	}    

	function flashStatus(playStatus, hrefId, pAll, albumHref) {
//		console.log(playStatus, hrefId, pAll, albumHref)
		isPlaying = playStatus;
		playingHrefId = hrefId;
		playAll = pAll;
		if ( $(currentClick).closest('div.r').length && $('.playerControl').length ) { // if clicked in an album table
			if (isPlaying == 'true') {
				turnOnPlayingIcon(hrefId);
				turnOnPlayAllPlaying(albumHref);
			} else if (isPlaying == 'false') {
				turnOnPauseIcon(hrefId);
				turnOnPlayAllPause(albumHref, pAll);
			} else {
				resetAllIcons();
				resetPlayAll();
			}
		} else {
            hrefId = albumHref.substring(0, albumHref.length - 4);
			if ( $('#albumPage').length ){ //if on alb page reset playall
				resetPlayAll();
			}

            if (isPlaying == 'true' && hrefId !== '') {
                turnOnPlayingIcon(hrefId);
            } else if (isPlaying == 'false') {
                turnOnPauseIcon(hrefId);
            } else {
                resetAllIcons();
            }
			//homepage or contained pitch alb play all
			if ($('#currentAlbumMeta').length || $('#albumPitch').length) {
				if (isPlaying == 'true') {
					turnOnPlayAllPlaying(albumHref);
				} else if (isPlaying == 'false') {
					turnOnPlayAllPause(albumHref, pAll);
				} else {
					resetPlayAll();
				}
			}
		}
	}

    $(function () {
        var swfUrl = DUMAS.inlineFlash && DUMAS.inlineFlash.swfUrl;

        if (swfUrl) {
            enableInlineFlash(swfUrl);
        }
	});

	//public methods
	return {
		init: initEventHandlers,
		enable: enableInlineFlash,
		nextSample: nextSample,
		resetAllIcons: resetAllIcons,
		resetPlayAll: resetPlayAll,
		toLog: toLog,
		toError: toError,
		stop: reset,
		flashStatus: flashStatus
	};
}());
