/**
 * main javascript for app
 */

if (!zoo) zoo = {};
zoo.app = {
    widgets: {
        language: function() {
            var list = window.jQuery ? $('#lang-list')[0] : $('lang-list');
            // move to bottom of doc so no index issues
            if (undefined === list.wgtOn) {
                var func = window.$$ || window.$;
                var el = func('.content-wrapper')[0];
                list.style.right = (document.body.clientWidth - el.clientWidth) / 2  + 'px' ;
                document.body.appendChild(list);
            }
            if (list.wgtOn) {
                list.style.display = 'none';
                list.wgtOn = false;
            } else {
                list.style.display = 'block';
                list.wgtOn = true;
            }
            return false;
        }
    },
    gotoPage: function(anchor) {
        if (!anchor) return true;
        var name = anchor.target;
        if (!name || window.name == name) return true;
        if (!document.windowList) document.windowList = [];
        var href = anchor.getAttribute('href');
        var d = document.viewport.getDimensions();
        document.windowList[name] = window.open(href, name,
                                                "scrollbars=yes,resizable=yes,toolbar=yes,status=yes,width=" + d.width + ", height" + d.height);
        document.windowList[name].focus();
        return false;
    },
    popUpPage: function(anchor) {
        var href = anchor.getAttribute('href');
        zoo.dom.popUp(href, 800, 400);
        return false;
    },
    popUpImg: function(anchor) {
        var href = anchor.getAttribute('href');
        zoo.dom.popUp(href, 800, 500, 'yes');
        return false;        
    },
    chatroom: {
        init: function() {
            
        },
        show: function(anchor) {
            var videoFeed = $('video-feed-embed');
            if (videoFeed) {
                videoFeed.style.visibility = 'hidden';
            }
            Modalbox.show($('chatroom-legend'), {
                title: 'Day Trading Radio Chatroom',
                width: 600,
                afterHide   : function() { $('video-feed-embed').style.visibility = 'visible' }
            });
            
            return false;
            
        },
        popup: function(anchor) {
            var href = anchor.getAttribute('href');
            zoo.dom.popUp(href, 800, 500, 'yes');
            zoo.app.chatroom.close();
            return false;
        },
        close: function() {
            var legend = $('chatroom-legend');
            legend.style.display = 'none';
            Modalbox.hide();
        }
    },
    eventsDesc: {
        init: function() {
            
        },
        show: function(li) {
            var videoFeed = $('video-feed-embed');
            if (videoFeed) {
                videoFeed.style.visibility = 'hidden';
            }

        	var href = li.getAttribute('href');            
            Modalbox.show(href, {
                title: 'Show Info',
                width: 600,
                afterHide   : function() { $('video-feed-embed').style.visibility = 'visible' }
            });
            
            return false;
            
        }
    },
    chat: {
        show: function(anchor) {
            if (this.chatOn) return false;
            var _startEffect = function(element) {
                new Effect.Opacity(element, {from: 1, to: .9, duration: 0 });
            }
        
            var _endEffect = function(element) {
                new Effect.Opacity(element, {from: .9, to: 1, duration: .3 }); 
            }
            
            var w = {
                hide: function() {
                    this.elm.style.display = 'none';
                    this.onScreen = false;
                },
                show: function() {
                    this.elm.style.display = 'block';
                    this.onScreen = true;
                },
                onScreen: false
            };
            
            w.elm = new Element('div', {'class': 'chat window', 'id': 'chat-window'}).update('<img style="margin: 40px" src="http://zooluimagelibrary-gz-e7.simplecdn.net/loading/bigrotation2.gif" />');
            w.elm.style.left = document.viewport.getWidth() / 4 - 225 + 'px';
            w.elm.style.top = document.viewport.getHeight() / 4 + 'px';
            
            document.body.appendChild(w.elm);
            
            var href = anchor.href;
            new Ajax.Updater(w.elm, href, {
                method: 'get',
                parameters: {
                },
                onComplete: function() {
                    new Draggable('chat-window', {
                        handle      : $('chat-title'),
                        starteffect : _startEffect,
                        endeffect   : _endEffect
                    });
                    return true;
                }
            });        

            this.chatOn = true;            
            return false;
                  
        }    
    },
    stocks: {       
        legend: {
            init: function() {
                $$('.legend-link').each(function(elm) {
                   elm.observe('click', zoo.app.stocks.legend.toggle);
                });
                return true;
            },
            toggle: function(e) {
                var legendObj = zoo.app.stocks.legend;
                var legend = $('watchlist-legend');
                document.body.appendChild(legend);
                if (legendObj.wgtOn) {
                    legend.style.display = 'none';
                    legendObj.wgtOn = false;
                } else {
                    legend.style.top = e.pointerY() + 'px';
                    legend.style.display = 'block';
                    legendObj.wgtOn = true;
                }                
            },
            close: function() {
                var legend = $('watchlist-legend');
                legend.style.display = 'none';           
                zoo.app.stocks.legend.wgtOn = false;
                return false;
            }
        },
        info: {
            init: function() {
                
            },
            show: function(anchor) {
                var videoFeed = $('video-feed-embed');
                if (videoFeed) {
                    videoFeed.style.visibility = 'hidden';
                }
                Modalbox.show(anchor.href, {
                    title: anchor.title,
                    width: 600,
                    afterHide   : function() { $('video-feed-embed').style.visibility = 'visible' }
                });
                
                return false;
                
            }
        },
        portfolio: {
            filter: function(anchor, filterBy, table) {
                var portfolio = zoo.app.stocks.portfolio;
                if (portfolio.selectedAnchor) {
                    portfolio.selectedAnchor.removeClassName('selected');
                } else {
                    $("default-portfolio-filter").removeClassName('selected');
                }
                portfolio.selectedAnchor = anchor;
                portfolio.filterBy = filterBy;
                anchor = $(anchor);
                anchor.addClassName('selected');
                portfolio.hideRows(filterBy, table);
                return false;
            },
            hideRows: function(filter, table) {
                table = table || $('currently-holding-list');
                table.select('tr.stock-row').each(function(row) {
                    if (!filter || row.hasClassName('owner-' + filter)) {
                        row.style.display = '';
                    } else {
                        row.style.display = 'none';
                    }
                });
            }
        }
    }
};

zoo.app.widgets.members = function() {
    var PeriodicalUpdater = Class.create(Ajax.PeriodicalUpdater, {
        initialize: function($super, container, url, options) {
            $super(container, url, options);
        },
        onTimerEvent: function() {
            // this.updater = new Ajax.Updater(this.container, this.url, this.options);
            $$('table th.loader').each(function(cell) {
               cell.addClassName('loading');
            });
            
            var nowPlaying = $('now-playing');
            if (nowPlaying) {
                nowPlaying.addClassName('loading');
            }
            var date = new Date();
            var uid = date.valueOf();
            this.updater = new Ajax.Request(this.url + '?_t_=' + uid, this.options);
        }
    });
    
    var MemberUI = function() {
        // this.interval = 60;
        this.interval = 90;
        this.decay    = 1;
        
        // create pre update container for stocks
        this.preUpdateContainer = $(document.createElement('div'));
        this.preUpdateContainer.style.position = 'absolute';
        this.preUpdateContainer.style.left = -9999 + 'px';
        this.preUpdateContainer.style.display = 'none';        
        document.body.appendChild(this.preUpdateContainer);

        // create pre update container for stocks
        this.preAlertUpdateContainer = $(document.createElement('div'));
        this.preAlertUpdateContainer.style.position = 'absolute';
        this.preAlertUpdateContainer.style.left = -9999 + 'px';
        this.preAlertUpdateContainer.style.display = 'none';        
        document.body.appendChild(this.preAlertUpdateContainer);        
        
        // create references to stock displays
        this.dtrPortfolio  = $('currently-holding-list-daytradi');
        this.gtoPortfolio  = $('currently-holding-list-gtotoys');
        this.dtrWatchList  = $('dtr-watch-list');
        this.gtoWatchList  = $('gto-watch-list');
        this.alertList     = $('trader-alert-list');
    }
    MemberUI.prototype = {
        poll: function() {
            var self = this;
            this.ajx = new PeriodicalUpdater('items', '/static/members.json', {
                method: 'get',
                frequency: this.interval,
                decay: this.decay,
                onSuccess: function(response){
                    self.update(response.responseJSON);
                }                                                                                                            
            });           
        },
        update: function(json) {
            
            // update stock
            // alert('we are back');
            var container = this.preUpdateContainer;
            container.update(json.stockHTML);
                      
            var newDtrPortfolioEl = $('currently-holding-list-daytradi-poll');
            // var newGtoPortfolioEl = $('currently-holding-list-gtotoys-poll')
            var newDtrWatchListEl = $('dtr-watch-list-poll');
            // var newGtoWatchListEl = $('gto-watch-list-poll');

/*
            var portfolio = zoo.app.stocks.portfolio;
            var anchor = portfolio.selectedAnchor || $('default-portfolio-filter');            
            portfolio.filter(anchor,
                             portfolio.filterBy,
                             newPortfolioEl);
*/                             
            if (newDtrPortfolioEl) {
                this.dtrPortfolio.update(newDtrPortfolioEl.innerHTML);
            }
            /*
            if (newGtoPortfolioEl) {
                this.gtoPortfolio.update(newGtoPortfolioEl.innerHTML);
            }
            */
            if (newDtrWatchListEl) {
                this.dtrWatchList.update(newDtrWatchListEl.innerHTML);
            }
            /*
            if (newGtoWatchListEl) {
                this.gtoWatchList.update(newGtoWatchListEl.innerHTML);
            }
            */
            
            // update now playing
            var nowPlaying = $('now-playing');
            if (nowPlaying) {
                $('current-song').update(json.nowPlaying);
                nowPlaying.removeClassName('loading');
            }
            
            this.updateAnnouncements(json.announcements);
            
            if (json.rssFeed) {
                var feedTpl = new Template(json.rssFeedTpl);
                this.updateTicker(json.rssFeed, feedTpl)
            }            
        },
        updateTicker: function(feed, template) {
            var html = '';
            feed.each(function(event) {
               html += template.evaluate(event);                
            });

            jQuery("#rss-feed")
                .parent()
                    .parent()
                        .next('.ticker-queue')                
                        .html(html);            
        },
        updateAnnouncements: function(alerts) {
            // update stock
            var container = this.preUpdateContainer;
            container.update(alerts);            
            var new_alerts = container.select('li');
            // alert(alerts);
            // alert(new_alerts);
            if (new_alerts.length) {
                // console.log(new_alerts);
                var self = this;
                new_alerts = $(new_alerts);
                // alert('iterate');
                new_alerts.each(function(alertItem) {
                    var id = alertItem.getAttribute('id').replace('-poll', '');
                    // alert(id);
                    // console.log(id);
                    var existing_alert = $(id);
                    if (!existing_alert) {
                        // alert('insert new alert');
                        // console.log('insert new alert');
                        alertItem.style.display = 'none';
                        self.alertList.insert({top: alertItem});
                        alertItem.setAttribute('id', id);
                        alertItem.slideDown();
                    }                    
                });
            }       
            
        }
        
    }

    return {
        init: function() {
            var memberPage = new MemberUI();
            memberPage.poll();
        }    
   }
}()

zoo.app.widgets.RightSidebarSlideShow = function() {
    var delay = 9000;
    var start_frame = 0;
    
    function start_slideshow(start_frame, end_frame, delay, lis) {
        setTimeout(fadeInOut(start_frame,start_frame,end_frame, delay, lis), delay);
    }
    
    function fadeInOut(frame, start_frame, end_frame, delay, lis) {
        return (function() {
            lis = $('slide-images').select('li.slide');
            Effect.Fade(lis[frame]);
            if (frame == end_frame) {
                frame = start_frame;
            } else {
                frame++;
            }
            lisAppear = lis[frame];
            setTimeout("Effect.Appear(lisAppear);", 0);
            setTimeout(fadeInOut(frame, start_frame, end_frame, delay), delay + 1850);
        })                
    }
    
    return {
        init: function _init() {
            var lis = $('slide-images').select('li.slide');
            
            for( i=0; i < lis.length; i++){
                    if(i!=0){
                            lis[i].style.display = 'none';
                    }
            }
            end_frame = lis.length -1;
            
            start_slideshow(start_frame, end_frame, delay, lis);	
        }
    }
}();

jQuery.fn.ticker = function() {

    var RssTicker = function(strip, config) {
        var self = this;
        this.strip = strip;
        this.queue = this.strip.next('.ticker-queue');
        this.settings = config;
        this.strip.addClass("newsticker");
        this.mask = strip.wrap("<div class='mask'></div>");
        this.tickercontainer = strip.parent().wrap("<div class='tickercontainer'></div>");
        this.containerWidth = strip.parent().parent().width();
        this.width = 0;
        this.controls = strip.parents().parents().parents().find('a.controls');
        
        
        this.controls.click(function(e) {
            var $control = jQuery(this);

            if ($control.hasClass('play')) {
                self.play();                
            } else {
                
                self.pause();
            }            
            
            $control.toggleClass('play');
            e.stopImmediatePropagation();
            return false;
        });
        
        this.strip.hover(
            function() {
                // if not paused
                if (!self.controls.hasClass('play')) {
                    self.pause();
                }
                // jQuery(this).stop();
            },
            function(){
                // if not paused                
                if (!self.controls.hasClass('play')) {
                    self.play();
                }
                /*
                var offset = jQuery(this).offset();
                self.travel = offset.left + self.width;
                self.tempo = self.travel / config.travelocity;
                self.animate();
                */
            }
        );		        
    }
    
    RssTicker.prototype = function() {
        var _calcAndSetWidth = function() {
            var self = this;
            self.width = 0;
            this.strip.find("li").each(function(i) {
                self.width += jQuery(this, i).width() + 20;
            });

            this.strip.width(this.width);
        }
        
        var _animate = function() {
            var self = this;
            self.strip.animate({
                    left: '-='+ self.travel
                },
                self.tempo,
                "linear",
                function() {
                    self.refresh();
                }
            );
        }
        
        var _setTravelAndTempo = function() {
            this.travel = this.width + this.containerWidth;
            this.tempo = this.travel / this.settings.travelocity;
        }
        
        var _checkAndUpdateQueue = function() {
            var queueItems = this.queue.children("li");
            if (queueItems.length) {
            
                if (this.settings.queueOverwrites) {
                    this.strip.empty();
                } 
                queueItems.prependTo(this.strip);                    

                this.queue.empty();
                _calcAndSetWidth.call(this);
                
            }            
        }
        
        return {
            scroll: function() {
                _calcAndSetWidth.call(this);
                _setTravelAndTempo.call(this);                
                _animate.call(this);                         
            },
            refresh: function() {
                _checkAndUpdateQueue.call(this);
            
                this.strip.css("left", this.containerWidth);
                _setTravelAndTempo.call(this);        
                _animate.call(this);            
            },
            animate: function() {
                _animate.call(this);                
            },
            pause: function() {
                this.strip.stop();
            },
            play: function() {
                var offset = this.strip.offset();
                this.travel = offset.left + this.width;
                this.tempo = this.travel / this.settings.travelocity;
                this.animate();                
            }
        }        
    }()
    
    return function(settings) {    
		settings = jQuery.extend({
            travelocity: 0.07,
            queueOverwrites: true
		}, settings);
        
		return this.each(function(){
            var strip = jQuery(this);
            
            var ticker = new RssTicker(strip, settings);            
            ticker.scroll();            
		});        
    }
}();