/**
 *  Verify AP namespace
 *  
 */
if (typeof AP != 'object'){
    var AP = {};
}

AP.thumbnailbar = (function(TB){
    
    TB = TB || {};
    
    TB.createMarkup = function(id){
    
        var wrap = document.createElement('div');
        var list = document.createElement('ul');
        var back = document.createElement('div');
        var next = document.createElement('div');
        
        wrap.id = id + '_container';
        list.id = id + '_list';
        back.id = id + '_scanback';
        next.id = id + '_scanforward';

        wrap.className = 'thumbnailbar';
        list.className = 'thumbnailbar_list';
        back.className = 'thumbnailbar_scanback inactive';
        next.className = 'thumbnailbar_scanforward inactive';
        
        wrap.appendChild(list);
        wrap.appendChild(back);
        wrap.appendChild(next);
        
        return wrap;
    };
    
    /*
     * Thumbnail
     */
    TB.thumbnail = function(url,width,height,index,title,subtitle,my){
    
        my = my || {};
        my.url = url || ''; 
        my.index = index || 0;
        my.element = document.createElement('li');
        my.imgWrap = document.createElement('div');
        my.label = document.createElement('div');
        my.title = document.createElement('b');
        my.subtitle = document.createElement('span');
        
        my.title.innerHTML = title || '&nbsp;';
        my.subtitle.innerHTML = subtitle || '&nbsp;';
        
        my.image = new Image();
        my.image.className = 'loading';
        my.label.className = 'thumbnail-label';
        my.imgWrap.className = 'imgwrap';
        my.element.appendChild(my.imgWrap);
        my.imgWrap.appendChild(my.image);
        my.label.appendChild(my.title);
        my.label.appendChild(my.subtitle);
        my.element.appendChild(my.label);
        my.delayTime = (index * 170) + Math.floor(Math.random()*500);
        my.events = aFrame.event();
        
        my.handleClick = function(){
            my.events.fire('click',{
                index : my.index
            });
        };
        
        my.handleLoad = function(){
            my.image.className = ' ';
        };
        
        my.loadSrc = function(){
        
            var ratio = width / height;
            
            if (ratio > 1) {
                my.image.height = 60;
                my.image.width = Math.floor((60 * ratio));
                my.image.style.marginLeft = '-'+Math.floor(((60 * ratio) - 60) / 2)+'px';
            } else {
                my.image.width = 60;
                //console.log((60 / ratio));
                my.image.style.marginTop = '-'+Math.floor(((60 / ratio) - 60) / 2)+'px';
            }
        
            my.image.src = my.url;
            aFrame.addListener('load', my.image, my.handleLoad);
        };
        
        aFrame.addListener('click', my.element, my.handleClick);

        setTimeout(my.loadSrc,my.delayTime);
        
        return {
            on : my.events.on,
            
            getElement : function(){
                return my.element;
            },
            select : function(){
                my.element.className = 'selected';
            },
            deselect : function(){
                my.element.className = ' ';
            }
        };
    };
    
    /*
     * Scan Button
     */
    TB.scanButton = function(id,className,my){
        
        my = {};
        my.isActive = false;
        my.element = document.getElementById(id + '_' + className);
        my.baseClass = 'thumbnailbar_' + className;
        my.method = function(){};
        
        my.handleClick = function(){
            if (!my.isActive){ return; }
            my.method();
        };
        
        aFrame.addListener('click', my.element, my.handleClick);
        
        return {
            onClick : function(method){
                my.method = method;
            },
            setState : function(bool){
                if (bool === my.isActive){ return; }
                my.isActive = bool ? true : false;
                my.element.className = bool ? my.baseClass : my.baseClass + ' inactive';
            }  
        };
    };

    /*
     * Create Thumbnail Bar Instance
     */
    TB.create = function(p,my){
    
        var that = {};
        my = my || {};
        p = p || {};
        
        my.events = p.events || {};
        my.panel = p.panel || {};
        my.panel.append(TB.createMarkup(p.id));
        my.listEl = document.getElementById(p.id + '_list');
        my.listStyle = my.listEl.style;
        my.thumbnails = [];
        my.loaded = false;
        my.isMobile = (aFrame.browser === 'mobile');
        
        my.centeredX = 0;
        
        my.touchCanceled = false;
        my.touch = {
            init : 0,
            delta : 0,
            change: 0
        };
        
        my.curLeftPos = 0;
        my.curWidth = 0;
        my.curXposition = 0;
        my.selectedIndex = false;
        my.animTimeout = 0;
        
        my.isBackActive = false;
        my.isForwardActive = false;
        
        my.scanBack = TB.scanButton(p.id,'scanback');
        my.scanForward = TB.scanButton(p.id,'scanforward');
        
        my.animation = aFrame.animation(my.listEl);
        
        /*
         *  @param T = total thumbnails width
         *  @param W = viewable panel width
         *  @param X = center x position of selected thumbnail
         *
         *  @return (x) offset of thumbnails to panel
         */
        my.getOffset = function(T,W,X){
            
            /*
             * Assume that the back and forward
             * buttons are inactive
             */
            my.isBackActive = false;
            my.isForwardActive = false;
            
            /*
             * The thumbnails are less wide
             * than the viewable area, so
             * center them within the available
             * space.
             */
            if (T <= W) {
                my.centeredX = T / 2;
                return (W - T) / 2;
            }
            
            /*
             * Calculate half the viewable width
             */
            var H = W / 2;
            
            /*
             * The current thumbnail is to far to
             * the left to be centered without
             * leaving extra space in the left
             * gutter, so position the thumbnails
             * at thier maximum left position
             * and activate the forward button
             * only.
             */
            if (X <= H){
                my.centeredX = W / 2;
                my.isForwardActive = true;
                return 0;
            }
            
            /*
             * The current thumbnail is to far to
             * the right to be centered without
             * leaving extra space in the right
             * gutter, so position the thumbnails
             * at thier maximum right position
             * and activate the back button only
             */
            if (X >= (T - H)){
                my.centeredX = T - (W / 2);
                my.isBackActive = true;
                return W - T;
            }
            
            /*
             * Since we'll be positioning the current
             * thumbnail in the exact center with
             * the other thumbs overflowing the viewable
             * area on both the left and right,
             * we activate both the forward and back button
             * and return the new calculated position of
             * the thumbnails
             */
            my.centeredX = X;
            my.isBackActive = true;
            my.isForwardActive = true;
            return H - X;

        };
        
        my.updatePosition = function(targetX){
            
            my.curLeftPos = my.getOffset(
                my.listEl.offsetWidth,
                my.curWidth,
                targetX
            );

            my.animation.setLeft(Math.floor(my.curLeftPos));
            my.animation.run();
            
            my.scanBack.setState(my.isBackActive);
            my.scanForward.setState(my.isForwardActive);
        };
        
        /*
         * Scan Backwards
         * calculates a new 'centered target' as 100 pixels short
         * of 50% of the page width to the left
         */
        my.handleBackClick = function(){
            my.startAnimation();
            my.updatePosition(-my.curLeftPos - (my.curWidth * .5) + 150);
        };
        
        /*
         * Scan Forwards
         * calculates a new 'centered target' as 100 pixels short
         * of 50% of the page width to the right
         */
        my.handleForwardClick = function(e){
            my.startAnimation();
            my.updatePosition(-my.curLeftPos + (my.curWidth * 1.5) - 150);
        };
        
        /*
         * Sets the animateSlide class for half a second
         * so that the CSS transition will take effect.
         */
        my.startAnimation = function(){
            clearTimeout(my.animTimeout);
            my.listEl.className = 'thumbnailbar_list animateSlide';
            my.animTimeout = setTimeout(my.endAnimation,500);
        };
        
        my.endAnimation = function(){
            my.listEl.className = 'thumbnailbar_list';
        };
        
        my.handleItemSelected = function(e){
        
            var newIndex = e.get('index');
            var oldIndex = my.selectedIndex;
            
            if (newIndex === oldIndex){
                return;
            }
            
            if (false !== oldIndex){
                my.thumbnails[oldIndex].deselect();
            }
            
            var selectedItem = my.thumbnails[newIndex];
            var selectedEl = selectedItem.getElement();
            
            selectedItem.select();
            
            my.curXposition = selectedEl.offsetLeft + (selectedEl.offsetWidth / 2);
            my.selectedIndex = newIndex;
            
            if (my.loaded){
                my.startAnimation();
            }
            
            my.updatePosition(my.curXposition);
        };
        
        my.handleThumbClick = function(e){
            if (my.touchCanceled){ return; }
            my.events.fire('stopAutoPlay');
            my.events.fire('selectByIndex',{
                index : e.index
            });
        };
        
        my.addPlaylistItem = function(plItem){
            
            //console.log(plItem);
            
            var itemIndex = plItem.get('index');
            var tImage = plItem.getImage('t');
            //console.log(tImage);
            
            var thumbnail = TB.thumbnail(
                tImage.url,
                tImage.width,
                tImage.height,
                itemIndex,
                plItem.get('title'),
                plItem.get('client')
            );
            
            thumbnail.on('click',my.handleThumbClick);
            my.listEl.appendChild(thumbnail.getElement());
            my.thumbnails[itemIndex] = thumbnail;  
        };
        
        my.handleDataAvailable = function(playlistItems){
            
            var itemCount = playlistItems.length;
            
            my.listEl.innerHTML = "<span></span>";
                
            for (var i=0; i<itemCount; i++){
                my.addPlaylistItem(playlistItems[i]);
            }
            
            my.loaded = true;
            
        };
        
        my.handleResize = function(e){
            my.curWidth = parseInt(my.panel.getStyle('width').replace('px',''));
            my.updatePosition(my.curXposition);
        };
        
        my.touchStart = function(e){
            my.touchCanceled = false;
            if (1 < e.touches.length){return;}
            my.touch.init = e.targetTouches[0].pageX;
            my.touch.change = 0;
        };
        
        my.touchMove = function(e){   
            e.preventDefault();
            my.touchCanceled = true;
            if (1 < e.touches.length){return;}
            var newX = e.targetTouches[0].pageX - my.touch.init; 
            my.touch.delta = my.touch.change - newX;
            my.touch.change = newX;
            my.updatePosition(my.centeredX + my.touch.delta);
        };
        
        my.touchEnd = function(e){
            if (my.touchCanceled){
                e.preventDefault();
                my.startAnimation();
                my.updatePosition(my.centeredX + (my.touch.delta * 8));
            }
        };
        
        my.scanBack.onClick(my.handleBackClick);
        my.scanForward.onClick(my.handleForwardClick);
        my.events.on('playlist:dataAvailable',my.handleDataAvailable);
        my.events.on('playlist:itemSelected',my.handleItemSelected);
        
        aFrame.addListener("resize", window, my.handleResize);
        
        /*
         * Init touch listeners
         */        
        if (my.isMobile) {
            aFrame.addListener("touchstart", my.listEl, my.touchStart);
            aFrame.addListener("touchmove", my.listEl, my.touchMove);
            aFrame.addListener("touchend", my.listEl, my.touchEnd);
        }
        
        if (p.playlist) {
            my.handleDataAvailable(p.playlist);   
        }
        
        my.handleResize();
        
        return that;
    };
    
    /*
     * @return constructor method
     */
    return function(cfg){
        return TB.create(cfg);
    };
     
}());
