﻿GoodNitesBedtimeTheater.AudioPlayer = function(serverVars) {
    this.ServerVars = serverVars;
    this.Popup = null;
};
GoodNitesBedtimeTheater.AudioPlayer.prototype = {
    Initialize: function(container, options, chapters) {
        console.log("Initializing AudioPlayer in " + container + " with " + chapters.length + " chapters.");

        // Build the container HTML for every chapter in the given chapters list

        // If we are in the production or QA environment, 
        // we need to prepend the /na directory to root
        urlPrefix = '';

        var html = '<div class="mp3hr"></div>';
        for (var i = 0; i < chapters.length; i++) {
            html += '<div id="MP3Player' + (chapters[i].chapterNum) + '" class="mp3Container">\n';
            html += '	<div class="mp3ContainerInner">\n';
            html += '		<div id="MP3Player' + (chapters[i].chapterNum) + 'Flash"><img src="' + urlPrefix + '/Styles/Images/BedtimeTheater/btnPlaceholderListen.gif" alt="" /></div>\n';
            html += '		<a onclick="handleDownloadBtnClick(' + chapters[i].chapterNum + ',\'DownloadtoCD\')" href="' + urlPrefix + '/Bedtime-Games-Stories/Bedtime-Theater/Modals/DownloadForCD.aspx?chapter=' + chapters[i].chapterNum + '" class="Modal Download DownloadForCD">Download to Burn CD</a>\n';
            html += '		<a onclick="handleDownloadBtnClick(' + chapters[i].chapterNum + ',\'Downloadforipod\')" href="' + urlPrefix + '/Bedtime-Games-Stories/Bedtime-Theater/Modals/DownloadForMp3Player.aspx?chapter=' + chapters[i].chapterNum + '" class="Modal Download DownloadForMp3Player">Download for MP3 Player</a>\n';
            html += '		<a onclick="handleMainBtnClick(\'/Bedtimetheatre.html\',\'NeedHelp\',\'BTContent\')" href="' + urlPrefix + '/Bedtime-Games-Stories/Bedtime-Theater/Modals/Help.aspx" class="Modal Help HelpButton"><img src="' + urlPrefix + '/Styles/Images/UserStudy/btnNeedHelp.gif" alt="Need Help?" /></a>\n';
            html += '	</div>';
            html += '</div>';
            html += '<div class="mp3hr"></div>';
        }

        $(container).html(html);

        for (var i = 0; i < chapters.length; i++) {
            this.EmbedFlashForMP3Player(chapters[i]);
        }

        // Setup click handlers for events from HTML Button Clicks
        window.handleDownloadBtnClick = function(chapter, btn) {
            dcsMultiTrack('DCS.dcsuri', '/Bedtimetheatre.html', 'WT.ti', btn, 'WT.z_ll', 'BTChapter' + chapter, 'WT.z_ln', btn, 'WT.dl', '40');
            return true;
        }
        window.handleMainBtnClick = function(dcsuri, name, type) {
            dcsMultiTrack('DCS.dcsuri', dcsuri, 'WT.ti', name, 'WT.z_ll', type, 'WT.z_ln', name, 'WT.dl', '40');
            return true;
        }
        window.completeDownloadRequest = function(url) {
            window.popUpReference.close();
            window.popUpReference = null;
            window.location = url;
        }

        // Setup External Interface handlers for events from Flash
        var scope = this;
        window.handleTrackStart = function(chapter) {
            chapter = Number(chapter);

            // Prevent two or more tracks from playing at the same time
            for (var i = 0; i < chapters.length; i++) {
                if (chapters[i].chapterNum != chapter) {
                    scope.GetMP3PlayerByChapter(chapters[i].chapterNum).get(0).externalStopTrack();
                }
            }
        }
        window.handleTrackVolumeChange = function(chapter, volume) {
            chapter = Number(chapter);

            // Prevent two or more tracks from playing at the same time
            for (var i = 0; i < chapters.length; i++) {
                console.log("Comparing the number of the chapter at index " + i + ". " + chapters[i].chapterNum + " != " + chapter + ". Volume = " + volume);
                if (chapters[i].chapterNum != chapter) {
                    scope.GetMP3PlayerByChapter(chapters[i].chapterNum).get(0).externalSetVolume(volume);
                }
            }
        }
        window.handleTrackComplete = function(chapter) {
            chapter = Number(chapter);

            // Move to the next track and autoplay when a track completes           
            var needle = -1;
            for (var i = 0; i < chapters.length; i++) {
                if (chapters[i].chapterNum == chapter) {
                    needle = i;
                    break;
                }
            }
            needle++;

            if (options.loopChapters && needle == chapters.length) {
                needle = 0;
            }
            if (needle < chapters.length && options.continuousPlay) {
                scope.GetMP3PlayerByChapter(chapters[needle].chapterNum).get(0).externalPlayTrack();
            }
        }

        //$(document).ready(function() {

        /* * * Disabled, but left here in case I need it later. -CM
        $('.emailTextbox').each(function() {
        if (this.value.length == 0) {
        this.style.color = '#999';
        this.value = this.title;
        }
        });
        $('.emailTextbox').blur(function() {
        if (this.value.length == 0) {
        this.style.color = '#999';
        this.value = this.title;
        }
        });
        $('.emailTextbox').focus(function() {
        if (this.value == this.title) {
        this.style.color = '#000';
        this.value = '';
        }
        });
        */

        // Re-route all download links to use their modal equivalents
        $('a.Modal').click(function(event) {

            // Open the Download or DownloadAll content depending on the context
            if ($(this).hasClass('Download')) {
                scope.OpenModalWindow(this.href, 300, 300);
            }
            if ($(this).hasClass('Help')) {
                scope.OpenModalWindow(this.href, 480, 400, true);
            }

            // If the popup window failed we should just follow the link, otherwise cancel the event
            if (scope.Popup != null) {
                return false;
            }
        });
        // });



    },
    GetMP3PlayerContainerByChapter: function(chapter) {
        return $('#MP3Player' + chapter);
    },
    GetMP3PlayerByChapter: function(chapter) {
        return $('#MP3Player' + chapter + ' object');
    },
    EmbedFlashForMP3Player: function(chapterInfo) {
        if (chapterInfo.chapterSwf != null) {
            var playerPath = chapterInfo.chapterSwf;
        } else {
            var playerPath = '/Swf/BedtimeTheater/MP3Player.swf';
        }
        var mediaUrl = '/Bedtime-Games-Stories/Bedtime-Theater/';

        var player = this.GetMP3PlayerContainerByChapter(chapterInfo.chapterNum);
        if (player) {
            var flashvars = {
                chapterNum: chapterInfo.chapterNum,
                chapterDuration: chapterInfo.chapterDuration,
                chapterTitle: chapterInfo.chapterTitle,
                summary: chapterInfo.summary,
                mediaURL: mediaUrl,
                initialVolume: '70'
            };
            var params = {
                wmode: 'transparent'
            }

            swfobject.embedSWF(playerPath, 'MP3Player' + chapterInfo.chapterNum + 'Flash', 460, 106, '8.0.0', null, flashvars, params);
        }
    },
    OpenModalWindow: function(url, width, height, scrollable, resizable) {
        var features = '';
        features += 'width=' + width + ',';
        features += 'height=' + height + ',';
        features += 'scrollbars=' + ((scrollable) ? 1 : 0) + ',';
        features += 'resizable=' + ((resizable) ? 1 : 0) + ',';
        features += 'left=' + Math.round(screen.width / 2 - width / 2) + ',';
        features += 'top=' + Math.round(screen.height / 2 - height / 2) + ',';
        features += 'directories=no,location=no';
        if (this.Popup) {
            this.Popup.close();
        }
        this.Popup = window.open(url, 'AudioPlayerModal', features);
        window.popUpReference = this.Popup;
        this.Popup.focus();
    }
};
GoodNites.Extend(GoodNitesBedtimeTheater.AudioPlayer, GoodNites.Core);
