// = Apple.com Audio Gallery =
//
// Library for swapping between content in a single container element
// by triggers in the document, programmatically, or automatically over time.
AC.ViewMaster.AudioSection = Class.create();
Object.extend(AC.ViewMaster.AudioSection.prototype, AC.ViewMaster.Section.prototype);
if (Event.Listener) {
    Object.extend(AC.ViewMaster.AudioSection.prototype, Event.Listener);
}

// == AC.ViewMaster.AudioSection ==
//
// Class that wraps DOM content to swap into and out of a ViewMaster
Object.extend(AC.ViewMaster.AudioSection.prototype, {
    mediaType: function() {
        var src = this.movieLink.getAttribute('href', 2).split("."), extension;
        if(src.length === 2) {
            extension = src[1];
        }
        else {
            extension = "quicktime";
        }

        return this.movieLink ? "audio/"+extension : "text/html";
    },

    _superInitialize: AC.ViewMaster.Section.prototype.initialize,
    initialize: function(content, viewMaster) {
        this._superInitialize(content, viewMaster);
        if (Event.Listener) {
            this.listenForEvent(AC.ViewMaster, 'ViewMasterDidShowNotification', false, this.viewMasterDidShowNotificationCallback.bind(this));
        }

    },

    viewMasterDidShowNotificationCallback: function(evt) {
        var data = evt.event_data.data,
        incomingSection = data.incomingView;

        if (incomingSection === this && (incomingSection === this.viewMaster.currentSection)) {
            //We need to play now
            if(this._movieController && !this._movieController.isPlaying()) {
                //There's a bug if we do it right away, attaching the movie is out of bound and could happen after this
                if(this._movieController.movie) {
                    this._movieController.Play();
                }
                else {
                    Event.observe(document.getElementsByTagName('body')[0],'QuickTime:didAttach', this.controllerDidAttach.bind(this));
                }
            }

        }
    },

    controllerDidAttach: function(evt) {
        var controller = evt.memo.controller;
        if(controller === this._movieController && !this._movieController.isPlaying()) {
            this._movieController.Play();
        }
    },

    newMovieController: function() {
        return new AC.QuickTime.CircularController(null, {
            state: AC.QuickTime.States.Polling
        });
    },

    defaultMovieWidth: function() {
        return 1;
    },
    defaultMovieHeight: function() {
        return 1;
    },

    _isValidQTAvailable: undefined,
    isValidQTAvailable: function() {
         if(typeof this._isValidQTAvailable === "undefined") {
             this.constructor.prototype._isValidQTAvailable = AC.Detector.isValidQTAvailable(AC.QuickTime.minVersion());
         }
         return this._isValidQTAvailable;
    },

    _super_playMovie: AC.ViewMaster.Section.prototype._playMovie,
    _playMovie: function() {
        if (AC.Detector.isIEStrict() && !this.isValidQTAvailable()) {

            if (this.movieLink && this.moviePanel) {

                this.moviePanel.innerHTML = '';

                if (this.posterLink && this.posterLink.href) {
                    var posterFrame = this.posterLink.href;
                }

                this.moviePanel.appendChild(this._audioElement);
                this.movie = AC.HTMLPlusTimeSlideshow.create(this._audioElement, null, {autoplay:true,
                    controller: this._movieController,
                    listenForViewMasterWillShowNotification: false
                });
            }
        }

        else {
            this._super_playMovie();
        }

    },

    firstControllerTrigger: function() {
        var myTriggers = this.triggers(), i, iTrigger;
        if(!myTriggers) return null;

        for(i=0;(iTrigger = myTriggers[i]);i++) {
            if(iTrigger.hasClassName("controller")) {
                return iTrigger;
            }
        }
        return null;
    },

    _super_loadMovie: AC.ViewMaster.Section.prototype._loadMovie,
    _loadMovie: function() {
        this._super_loadMovie();

        if (AC.Detector.isIEStrict() && !this.isValidQTAvailable()) {
            //Build the audio tag:
            //<t:audio timeaction="display" begin="0" dur="68.98" id="audio0" src="http://images.apple.com/itunes/download/iTunes_installation.mp3" syncMaster="true" syncBehavior="locked"></t:audio>

            this._audioElement = document.createElement("t:AUDIO");
            this._audioElement.setAttribute("begin", "indefinite");

            //Convention for now, we look for an mp3 at the same name/location
            var src = this.movieLink.getAttribute('href', 2).split(".");
            if(src.length === 2) {
                src = src[0]+".mp3";
            }
            this._audioElement.setAttribute("src", src);

        }

        //Take out the controler panel and drop it in the document so I can move it
        if(this.controllerPanel.parentNode !== document.body) {
            document.body.appendChild(this.controllerPanel);
        }
    },

    _superWillClose: AC.ViewMaster.Section.prototype.willClose,
    willClose: function() {
        if(this.currentTriggerControllerElement) {
            this.currentTriggerControllerElement.style.visibility = "visible";
            this.controllerPanel.style.visibility = "hidden";
        }
        return this._superWillClose();
    },

    // ** {{{AC.ViewMaster.AudioSection.willShow()}}}
    // 
    // this is overriden from AC.ViewMaster.Section to deal with the class name audioLink. we'll need to re-factor that
    _superWillShow: AC.ViewMaster.Section.prototype.willShow,
    willShow: function() {
        this._superWillShow();

        if (this.hasShown && !this.moviePanel) {
            this.movieLink = this.content.getElementsByClassName('audioLink')[0];
            this.posterLink = this.content.getElementsByClassName('posterLink')[0];

            if (this.movieLink) {
                this._loadMovie();
            }
        }

        return this.content;
    },

    _superDidShow: AC.ViewMaster.Section.prototype.didShow,
    didShow: function() {

        if(!this.isMobile) {
            var currentTrigger = this.viewMaster.currentTrigger(),
            currentTriggerParentNode = currentTrigger.parentNode,
            position;
            //currentControllerElement = currentTriggerParentNode.select("."+this.viewMaster.triggerClassName+".controller");

            this.currentTriggerControllerElement = this.firstControllerTrigger();
            position = Element.cumulativeOffset(this.currentTriggerControllerElement);
            this.controllerPanel.style.left = position.left+"px";
            this.controllerPanel.style.top = position.top+"px";
            this.controllerPanel.style.position = "absolute";

            //I'm going to substitute my controller to the place holder:
            this.controllerPanel.style.visibility = "visible";
            this.currentTriggerControllerElement.style.visibility = "hidden";
            //this.currentTriggerControllerElement.style.border = "1px red solid";

            //this.currentTriggerControllerElement.parentNode.replaceChild(this.controllerPanel,this.currentTriggerControllerElement);
        }
        return this._superDidShow();
    },

    _closeMovie: function() {
        if ((!AC.Detector.isIEStrict() || this.isValidQTAvailable()) && this.movie && this.moviePanel) {
            this.moviePanel.removeChild(this.movie)
            this.movie = null;
            this.moviePanel.innerHTML = '';
        }
    }


});


// == AC.ViewMaster.AudioGallery ==
//
// The AudioGallery listens for triggers being activated on the page to show
// the trigger's content inside a {{{swapView}}}
AC.ViewMaster.AudioGallery = Class.create();
if (Event.Listener) {
    Object.extend(AC.ViewMaster.AudioGallery.prototype, Event.Listener);
}
Object.extend(AC.ViewMaster.AudioGallery.prototype, AC.ViewMaster.Viewer.prototype);
Object.extend(AC.ViewMaster.AudioGallery.prototype, {

    // ** {{{AC.ViewMaster.AudioGallery.viewMasterId}}} [string]
    // 
    // a unique id for the audio gallery, so we can quickly exit the event
    // listener if we don't match this id
    viewMasterId: 'AudioGallery',

    _superInitialize: AC.ViewMaster.Viewer.prototype.initialize,
    initialize: function(contents, view, triggerClassName, slideShowTriggerClassName, options) {
        //Let's make the view 1x1 and fixed.
        if(!view) {
            view = document.createElement("div");
            document.body.appendChild(view);
        }
        view.style.left = "0px";
        view.style.top = "0px";
        view.style.width = "1px";
        view.style.height = "1px";
        view.style.position = "fixed";

        if (!options) options = {};
        if (options.shouldAnimateContentChange == null) {
            options.shouldAnimateContentChange = false;
        }

        this._superInitialize(contents, view, triggerClassName, options);

        if (Event.Listener) {
            this.listenForEvent(AC.ViewMaster, 'ViewMasterWillShowNotification', false, this.viewMasterWillShowNotificationCallback.bind(this));
        }

        this.slideshow = new AC.ViewMaster.Slideshow(this, slideShowTriggerClassName, options);
    },

    createSectionForContent: function(content) {
        return new AC.ViewMaster.AudioSection(content,this);
    },

    // ** {{{AC.ViewMaster.AudioGallery.}}}
    // {{{viewMasterWillShowNotificationCallback(evt)}}}
    // 
    // Checks if the current section is part of a larger swap view.
    // If so, and make sure it's the current section of that parent swap view.
    // If it's not selected, go ahead and stop playing.
    viewMasterWillShowNotificationCallback: function(evt) {
        var data = evt.event_data.data,
        view = data.sender,
        incomingSection = data.incomingView;

        if (view && view.viewMasterId != 'AudioGallery' && this.currentSection) {
            if (incomingSection) {
                if (!incomingSection.content.down(this.currentSection.content) || !incomingSection.content.down(this.currentSection.movieLink)) {
                    this.show(null, true);
                }
            }
        }
    },

    // ** {{{AC.ViewMaster.triggerClicked(evt, element)}}}
    // 
    // In this AudioGallery case, if we are Mobile Safari, just use the
    // default browser functionality.
    _superTriggerClicked: AC.ViewMaster.Viewer.prototype.triggerClicked,
    triggerClicked: function(evt, element) {
        if(!AC.Detector.isMobile()) {
            this._superTriggerClicked(evt, element);
        }
    }

});
