/**
 *  Verify AP namespace
 *  
 *  @author : Adam Portilla
 */
 
if (typeof AP != 'object'){

    var AP = {};

}

/**
 *  Verify PAGE namespace
 */

if (typeof PAGE != 'object'){

    var PAGE = {};

}


YUI().use('anim','node', function(Y) {
          

  
  
    /**
     *  Return a reusable overlay object
     */
    AP.overlayView = function(p,my){
        
        var that = {};  // public
        my = my || {};  // private
        p = p || {};    // config
        
        /* configuration settings */
        my.active = false;
        my.loaded = false;
        my.image = {};
        my.metadataHeight = 0;
        my.imageNode = 0;
        my.imageSize = {};
        my.bgOpacity = 1;
        my.fadeTime = .4;
        my.playlist = [];
        my.playlisttotal = 0;
        
        
		/* Create a node reference to the doc body */
        my.documentNode = Y.get(document.body);
        
        /* Create Overlay Container Node */
        my.overlayNode = Y.get(document.createElement('div'));
        my.overlayNode.addClass('overlayContainer');
        
        /* Create Background Skrim Node */
        my.backgroundNode = Y.get(document.createElement('div'));
        my.backgroundNode.addClass('overlayBackground');
        
        /* Create Media Container Node */
        my.mediaContainerNode = Y.get(document.createElement('div'));
        my.mediaContainerNode.addClass('overlayMedia');
        
        /* Create Movie Node */
        my.movieNode = Y.get(document.createElement('div'));
        my.movieNode.addClass('movieNode');
        my.movieNode.set('id', 'soundwellqtplayer');

        /* Create Meta-Title Node */
        my.metaTitleNode = Y.get(document.createElement('div'));
        my.metaTitleNode.addClass('overlayTitle');

        /* Create Meta-Caption Node */
        my.metaCaptionNode = Y.get(document.createElement('div'));
        my.metaCaptionNode.addClass('overlayCaption');

        /* Create Loader Gif Node */
        my.loaderNode = Y.get(document.createElement('img'));
        my.loaderNode.addClass('mediaLoader');
        my.loaderNode.setAttribute('src','medialoader.gif');
        my.loaderNode.setAttribute('height',16);
        my.loaderNode.setAttribute('width',16);
        
        /* Create Button Nodes */
        my.closeBtnNode = Y.get(document.createElement('div'));
        my.closeBtnNode.addClass('overlayCloseBtn');
        my.closeBtnNode.setStyle('opacity',0);
        
        my.nextBtnNode = Y.get(document.createElement('div'));
        my.nextBtnNode.addClass('overlayNextBtn');
        my.nextBtnNode.setStyles('opacity',0);
        
        my.prevBtnNode = Y.get(document.createElement('div'));
        my.prevBtnNode.addClass('overlayPrevBtn');
        my.prevBtnNode.setStyle('opacity',0);

       	/* Place nodes into the overlay */            
        my.mediaContainerNode.append(my.movieNode);
        my.mediaContainerNode.append(my.metaTitleNode);
        my.mediaContainerNode.append(my.metaCaptionNode);
        my.mediaContainerNode.append(my.closeBtnNode); 
        my.overlayNode.append(my.backgroundNode);
        my.overlayNode.append(my.mediaContainerNode);
        my.overlayNode.append(my.prevBtnNode);
        my.overlayNode.append(my.nextBtnNode);
		
		/*
		 *  Get Scaled Image Dimensions
		 *  Takes an object literal with a height and width
		 *  property and returns an object literal with
		 *  a height and width property scaled down to fit
		 *  within a containerNodes width
		 */
        my.scaleDimensions = function(height,width,containerNode) {
            var imageHeight = height;
            var imageWidth = width;
            var imageRatio = imageWidth/imageHeight;
            var availWidth = containerNode.get('offsetWidth') - 40;
            var scaledSize = {};

            scaledSize.height = Math.floor(availWidth / imageRatio);
            scaledSize.width = availWidth;

            return scaledSize;
        };
 
        /* background animation */
        my.backgroundAnim = new Y.Anim({
            node:my.backgroundNode,
            duration:my.fadeTime,
            easing:Y.Easing.easeBoth,
            to:{opacity : my.bgOpacity}
        });
 
        /* media container animation */
        my.mediaContainerAnim = new Y.Anim({
            node:my.mediaContainerNode,
            duration:my.fadeTime,
            easing:Y.Easing.easeBoth,
            to:{opacity : 1}
        });

		/* decide which buttons should be displayed */
        my.resetNavBtns = function(){
            if (my.currentIndex > 0){
                my.showPrevBtn();
            } else {
                my.hidePrevBtn();
            }
            if (my.currentIndex < (my.playlisttotal - 1)){
                my.showNextBtn();
            } else {
                my.hideNextBtn();
            }
        };
        
  		/* first link of the overlay activation animation chain
  		 * append the overlaynode to document and animate
  		 * the background layers opacity
  		 */
        my.turnOverlayOn = function(){
            my.documentNode.append(my.overlayNode);
            my.backgroundNode.setStyle('zIndex',100);
            my.backgroundAnim.stop();
            my.backgroundAnim.set('to',{opacity:my.bgOpacity});
            my.backgroundAnim.on('end',my.activateMediaContainer);
            my.backgroundAnim.run();
        };
        
        /*
         *  Scale the media container for variable video height
         */
        my.scaleMediaContainerToHeight = function(height){
            height = height || 480;
            var mediaHeight = parseInt(my.playlist[my.currentIndex + 1].height) || 480;
            var containerHeight = mediaHeight + 80;
            var marginOffset = Math.floor(containerHeight / 2); 
            
            my.mediaContainerNode.setStyles({
                height : containerHeight + 'px',
                marginTop : '-' + marginOffset + 'px'
            });
        };
        
  		/* second link of the overlay activation animation chain
  		 * Get the media object, scale the media container to
  		 * the correct size, and show the nav buttons
  		 */
        my.activateMediaContainer = function(){
            my.backgroundAnim.detachAll();
            my.mediaContainerNode.setStyles({
                opacity: 1,
                zIndex: 200
            });

            my.showCurrentMedia();
            my.showCloseBtn();
            my.resetNavBtns();

        };
		
		/* once the media container has finished scaling to the media size
		 * append the media node into the container and
		 * display it
		 */
        my.onMediaContainerReady = function(){
            my.mediaContainerAnim.detachAll();

            /*
             *  ADD MOVIE TO MOVIENODE
             */
            var newUrl = my.playlist[my.currentIndex + 1].url || '';
            var newHeight = my.playlist[my.currentIndex + 1].height || 480;
            var newWidth = 640;
            my.scaleMediaContainerToHeight(newHeight);
            
    		AP.mediaplayer.create({
    		    uniqueId : "soundwellplayer",
                container : "soundwellqtplayer",
                movieUrl : newUrl,
                movieWidth : newWidth,
                movieHeight : newHeight,
                progressWidth : 553,
                controlOrder : ['PlayPause','Progress','Time']
    		});
            
            
            var mymovie = AP.quicktime.getMovie("soundwellplayer");
            mymovie.Events.on('ended',function(){
                my.playlistAdvanceOne(my.currentIndex);
            });
            
            my.loaded = true;
            my.showMetadata();
        };
        
        /* fist step in the deactivation sequence, hide all the buttons
         * and fade out the media
         */
        my.turnOverlayOff = function(){
            my.loaded = false;

            var mymovie = AP.quicktime.getMovie("soundwellplayer");
            mymovie.Stop();
            mymovie.destroy();
            
            my.hideCloseBtn();
            my.hidePrevBtn();
            my.hideNextBtn();
            my.hideMetadata();
            
            my.movieNode.setContent("&nbsp;");
            my.mediaContainerAnim.stop();
            my.mediaContainerAnim.set('to',{opacity:0});
            my.mediaContainerAnim.on('end',my.deactivateBackground);
            my.mediaContainerAnim.run();
        };
        
        /* second step in the deactivation sequence, remove image node
         * from the media container, and fade out the background skrim
         */
        my.deactivateBackground = function(){
            my.mediaContainerAnim.detachAll();
            my.backgroundAnim.stop();
            my.backgroundAnim.set('to',{opacity:0});
            my.backgroundAnim.on('end',my.deactivateOverlay);
            my.backgroundAnim.run();
        }
		
		/* final step in the deactivation sequence, remove the overlay
		 * node from the document
		 */
        my.deactivateOverlay = function(){
            my.backgroundAnim.detachAll();
            my.documentNode.removeChild(my.overlayNode);
            my.active = false;
            my.loaded = false;
        };
        
        
        /*  starting with an empty media container, scale the media container to the 
         *  correct size and trigger the mediaContainerReady function to show the image
         */
        my.showCurrentMedia = function(){
            my.hideMetadata();
            
            my.metaTitleNode.setContent(my.playlist[my.currentIndex + 1].title);
            my.metaTitleNode.setStyle('width','640px');
            my.metadataHeight = my.metaTitleNode.get('offsetHeight');

            if (my.playlist[my.currentIndex + 1].creditsMarkup != ""){
                my.metaCaptionNode.setContent(my.playlist[my.currentIndex + 1].creditsMarkup);
                my.metaCaptionNode.setStyle('width','640px');
                my.metadataHeight = my.metaTitleNode.get('offsetHeight') + my.metaCaptionNode.get('offsetHeight');
            } else {
                my.metaCaptionNode.setContent("&nbsp;");
            }
            
            my.onMediaContainerReady();

        };
        
        /**
         *  Go to next playlist item, looping if need be
         */
        my.playlistAdvanceOne = function(curr){
            var nextIndex = curr + 1;
            if (nextIndex >= my.playlisttotal){
                my.setMedia(0);
            } else {
                my.setMedia(nextIndex);
            }
        };
        
        /*
         *  switch the active media item to the one with
         *  the specified index
         */
        my.setMedia = function(newIndex){
        	/* only switch if the current item is loaded
        	 * ( this prevents click hammering the script )
        	 */
            my.currentIndex = newIndex;
            my.resetNavBtns();

            var mymovie = AP.quicktime.getMovie("soundwellplayer");
            
            var newUrl = my.playlist[my.currentIndex + 1].url || '';
            var newHeight = my.playlist[my.currentIndex + 1].height || 480;
            var newWidth = 640;
            
            var newMedia = {
                url : my.playlist[my.currentIndex + 1].url,
                height : newHeight,
                width : newWidth
            };
            
            my.scaleMediaContainerToHeight(newHeight);
            mymovie.changeMedia(newMedia);
            
            my.metaTitleNode.setContent(my.playlist[my.currentIndex + 1].title);
            my.metadataHeight = my.metaTitleNode.get('offsetHeight');

            if (my.playlist[my.currentIndex + 1].creditsMarkup != ""){
                my.metaCaptionNode.setContent(my.playlist[my.currentIndex + 1].creditsMarkup);
                my.metadataHeight = my.metaTitleNode.get('offsetHeight') + my.metaCaptionNode.get('offsetHeight'); 
            } else {
                my.metaCaptionNode.setContent("&nbsp;");
            }
                

        };
        
        /* show/hide the prev/next/close buttons */
        my.showPrevBtn = function(){my.prevBtnNode.setStyle('opacity',1);};
        my.hidePrevBtn = function(){my.prevBtnNode.setStyle('opacity',0);};
        my.showNextBtn = function(){my.nextBtnNode.setStyle('opacity',1);};
        my.hideNextBtn = function(){my.nextBtnNode.setStyle('opacity',0);};
        my.showCloseBtn = function(){my.closeBtnNode.setStyle('opacity',1);};
        my.hideCloseBtn = function(){my.closeBtnNode.setStyle('opacity',0);};
        my.showMetadata = function(){
            my.metaTitleNode.setStyle('opacity',1);
            my.metaCaptionNode.setStyle('opacity',1);
        };
        my.hideMetadata = function(){
            my.metaTitleNode.setStyle('opacity',0);
            my.metaCaptionNode.setStyle('opacity',0);
        };
        
        /* click event for background panel */	
        my.backgroundNode.on('click',function(){
            if (my.loaded){
                my.turnOverlayOff();
            }
        },this);
        
        /* click event for close button */	
        my.closeBtnNode.on('click',function(){
            if (my.loaded){
                my.turnOverlayOff();
            }
        },this);
        
        /* click event for next button */	
        my.nextBtnNode.on('click',function(){
            if (my.currentIndex < (my.playlisttotal - 1)){
                my.setMedia(my.currentIndex + 1);
            }
        },this);

        /* click event for prev button */	
        my.prevBtnNode.on('click',function(){
            if (my.currentIndex >= 1){
                my.setMedia(my.currentIndex - 1);
            }
        },this);

        /* display overlay with item passed in via media */
        that.show = function(index){
            /* default to the first item if no index is specified */
            index = index || 0;
               
            /* ignore show events when the current overlay is active */
            if (!my.active){
                my.active = true;
                my.currentIndex = index;
                my.turnOverlayOn();
            }
        };
        
        /*
         *  set the playlist used by the overlay, this is required
         *  since the 'show' function takes only an index
         */
        that.setPlaylist = function(list){
            my.playlist = list;
            
            var size = 0, key;
            for (key in list) {
                if (list.hasOwnProperty(key)) size++;
            }
            my.playlisttotal = size;
            
        };
        
        return that;
        
    };
    
    PAGE.overlay = AP.overlayView();

});
