

if(INDABA && INDABA.controls) {
(function() {    
  
  
    /* globalZ explanation:
     * IE7 has a horrible bug with its zindexing engine. It's had this since z-index's inception, but only came to light after people
     * switched from table layouts to css layouts. For a full explanation of the bug: http://tinyurl.com/57dyhz
     * The fix involves iterating through the event feed items and giving each one a successively lower z-index. 
     * This value, globalZ, is not in the global object tree. It is utilized only within this closure.
    */
    
    var globalZ = 512;
    
    
    /*******
     * EventFeed object - handles loading partials into the event feed container, initializing event items, and so forth
     * container: dom element to contain the contents of the event feed
     * options: object literal of options.
     *      + retainGlobalZIndex (bool): if false, the feed - when initialized - will return globalZ to 512. 
     *
     *  If you want to load in a filter partial, you can either fire the stream event EventFeedUpdated with the argument as the string
     *  of the event feed to load (e.g., 'people' or 'files'), or if you have a reference to the EventFeed object you can 
     *  call Feed.updateFromURI(string=uri) or Feed.setFilter(string=filterName).
     */
    INDABA.controls.EventFeed = function(container, options) {
        this.getContainer = function() {
            return container;
        };
        this.getOptions = function() { return options ? options : {}; };
        if(!this.isSubFeed) {
            Stream.observe("EventFeedUpdated",this.onStreamEvent_listener.bind(this));
        } 
        Stream.observe("EventFeed_rebind",this.rebind.bind(this));
        Stream.observe("Async:Page:load",function() {
          if(this.ajaxTransport && this.ajaxTransport.transport.readyState !== 4) {
            this.ajaxTransport.transport.abort();
          }
        }.bind(this));
        this.filter = "";
        this.rebind();
        this.onLoaded = new INDABA.util.Event("FeedLoaded",this);
    };
    INDABA.controls.EventFeed.prototype = {
        feedItems : [],
        onStreamEvent_listener : function(e) {
            try {
              if(e) {
                this.setFilter(e);
              } else {
                this.setFilter(this.filter);
              }
            }
            catch (error) {

            }
        },
        addFeedItem : function(item) {
            feedItems.push(item);
        },
        removeFeedItemByIndex : function(index) {
            feedItems.splice(index,1);
        },
        clearFeedItems : function() {
            delete this.feedItems;
            this.feedItems = [];
            
        },
        removeFeedItem : function(item) {
            for(var i = 0; i < feedItems.length; i++) {
                if(feedItems[i] == item) {
                    this.removeFeedItemByIndex(i);
                }
            }
        },
        load_onComplete_listener : function(withLoading,ev) {
            this.rebind();
            
            $(this.getContainer()).select('input.initialization').each(function(input) {
              try {
                INDABA.init[input.value]();
              }
              catch(e) {}
            });
            this.onLoaded.fire();
        },
        unbind : function() {
            
            for(var i = 0; i <this.feedItems.length; i++) {
                this.feedItems[i].retire();
                this.clearFeedItems();
            }
            
        },
        rebind : function() {
            try {
                this.feedItems = [];
                if(!this.getOptions().retainGlobalZIndex) {
                  globalZ = 512;
                }
                var uls = $(this.getContainer()).getElementsByClassName("events");
                var items = [];
                if(uls && uls.length > 0) {
                  for(var i = 0; i < uls.length; i++) {
                      for(var e = 0; e < uls[i].childNodes.length; e++) {
                          if(uls[i].childNodes[e].tagName == "LI") {
                              items.push(uls[i].childNodes[e]);
                          }
                      }
                  }
                }
                else {
                  var table = $(this.getContainer()).select('table')[0];
                  if(table) {
                    try {
                      table.select('.iteration').each(function(tr) {
                        items.push(tr);
                      });
                    } catch (e) {}
                  }
                }
                var item = null;
                for(i = 0; i < items.length; i++) {
                    item = INDABA.util.EventItemFactory(items[i]);
                    item.init();
                    this.feedItems.push(item);
                }
            
                if($(this.getContainer()).hasClassName('loading')) {
                    INDABA.util.toggleElementLoading(this.getContainer());
                    $(this.getContainer()).setStyle({
                        height: "auto"
                    });
                }
                INDABA.Page.initPage(this.getContainer());
            }
            catch(e) {

            }

        },
        setFilter : function(filter) {
            
          
            this.unbind();
            var href = (filter) ? "?filter="+filter : "?filter=all";
            if(href) {
                if(typeof filter !== "undefined") {
                    this.filter = filter;
                    try {
                      $('session_comment_form').select('form input[name=filter]')[0].value = filter;
                    }
                    catch(e) {}
                }
                if(null !== this.ajaxTransport && this.ajaxTransport.transport.readyState !== 4) {
                  this.ajaxTransport.transport.abort();
                }
                else {
                  if(!$(this.getContainer()).hasClassName('loading')) {
                     INDABA.util.toggleElementLoadingV2($(this.getContainer()));
                  }  
                }  
                try {
                
                    var c = function(args) {
                        this.load_onComplete_listener(args);
                    };
                    c = c.bind(this);

                    this.ajaxTransport = new Ajax.Updater(this.getContainer(),href,{
                        onComplete : c
                    });
                }
                catch(e) {
                    INDABA.log(e);
                }
            }

            
        },
        updateFromURI : function(uri,withLoading) {
            
            try {
                if(uri && uri.include('filter=')) {
                    var params = uri.split('?')[1].split('&');
                    var paramArr = [];
                    params.each(function(p) {
                        paramArr.push(p.split('='));
                    });
                    for(var i = 0; i < paramArr.length; i++) {
                        if(paramArr[i][0] == 'filter') {
                            this.filter = paramArr[i][1];
                            this.setFilter(paramArr[i][1]);
                            return;
                        }
                    }
                }
                else {
                    if(null !== this.ajaxTransport && this.ajaxTransport.transport.readyState !== 4) {
                      this.ajaxTransport.transport.abort();
                    }
                    this.ajaxTransport = new Ajax.Updater(this.getContainer(), uri, {
                        onComplete : this.load_onComplete_listener.bind(this)
                    });
                }
            } catch(error) {
            }
            
        },
        ajaxTransport : null
    };
    
    INDABA.controls.SubEventFeed = function(container) {
        this.subFeed = new INDABA.controls.EventFeed(container,{retainGlobalZIndex : false});
        
        var moreLink = $(this.subFeed.getContainer()).select('a.more_events')[0];
        if(moreLink) {
            moreLink.observe("click",this.moreLink_onClick_listener.bind(this));
        }
        
        this.subFeed.moreLink = moreLink;
        this.subFeed.feedLoaded.addListener(this.feedLoaded_listener);
        this.subFeed.isSubFeed = true;
        return this.subFeed;
    };
    INDABA.controls.SubEventFeed.prototype = {
        moreLink_onClick_listener : function(e) {            
            try {
                INDABA.util.toggleElementLoading(this.subFeed.moreLink);
                this.subFeed.updateFromURI(e.target.href,false);
            }
            catch (error) {

            }
            finally {
                Event.stop(e);
                return false;
            }
        },
        feedLoaded_listener : function(e) {
            if(this.subFeed.moreLink && this.subFeed.moreLink.hasClassName("loading")) {
                INDABA.util.toggleElementLoading(this.subFeed.moreLink,null,null,{
                    height : "20px !important",
                    width : "100%"
                });
            }
        }
    };

    INDABA.controls.EventItem = function(container) {
        $(container).setStyle({
          zIndex : globalZ
        });
        globalZ--;
        this.getContainer = function() {
            return container;
        };
    };
    INDABA.controls.EventItem.prototype = {
        init : function() {
            return;
        },
        retire : function() {
            return;
        }
    };
    
    INDABA.controls.EventItem_WithPlayButton = function(eventItem) {
        this.event = eventItem;
    };
    INDABA.controls.EventItem_WithPlayButton.prototype = {
        playButton : null,
        init : function() {
            var pb = $(this.event.getContainer()).down('.pbutton');
            if(pb) {
                var info = document.getElementById(pb.id + "_info");
                if(info) {
                    if (!pb.hasClassName('pbutton_initialized')) {
                        this.playButton = new PlayButton(pb);
                    }
                }
            }
            this.event.init();
        },
        retire : function() {
            if(this.playButton) {
                // this.playButton.retire();
            }
            this.event.retire();
        },
        getContainer : function() {
            return this.event.getContainer();
        }
    };
    
    INDABA.controls.EventItem_WithActionMenu = function(eventItem,button,options) {
        this.event = eventItem;
        this.getButton = function() { return button; };
        this.getOptions = function() { return options; };
        this.menuContainer = this.event.getContainer().select('.action_dropdown')[0];
        
        this.mouseOver = (function(e) {
            this.menuContainer.addClassName('over');
            this.menuContainer.removeClassName('waiting');
        }).bind(this);
        
        this.mouseOut = (function(e) {
            if(this.menu.isOpen) {
                this.menuContainer.addClassName('waiting');
            }
            else {

                this.menuContainer.removeClassName('over');
            }
        }).bind(this);
        
        this.menuClose = (function(e) {
            if(this.menuContainer.hasClassName('waiting')) {
                this.menuContainer.removeClassName('over');
                this.menuContainer.removeClassName('waiting');
            }
        }).bind(this);
    };
    INDABA.controls.EventItem_WithActionMenu.prototype = {
        menu : null,
        init : function() {
            this.menu = new INDABA.controls.DropDown(
                {
                    button : this.getButton(),
                    options : this.getOptions(),
                    orient : 'left'
                });
            this.menu.onClose.addListener(this.menuClose);
            var c = $(this.event.getContainer());
            c.observe('mouseover',this.mouseOver);
            c.observe('mouseout',this.mouseOut);
            this.event.init();
        },
        retire : function() {
            try {
                this.menu.onClose.removeListener(this.menuClose);
                var c = $(this.event.getContainer);
                Event.stopObserving(c,'mouseover');
                Event.stopObserving(c,'mouseout');
                this.event.retire();
            }
            catch(e) {

            }
        },
        getContainer : function() {
            return this.event.getContainer();
        }
    };
    
    INDABA.controls.EventItem_WithMore = function(eventItem,moreButton,moreContainer) {
        try {
            this.event = eventItem;
            this.getMoreButton = function() { return moreButton; };
            this.getMoreContainer = function() { return moreContainer; };
            this.onAjaxLoad = new INDABA.util.Event("AjaxLoad");
        }
        catch(e) {
            INDABA.log(e);
        }
    };
    INDABA.controls.EventItem_WithMore.prototype = {
        showLess : null,
        visible : false,
        loadMore_onComplete : function(e) {
            INDABA.util.toggleElementLoading(this.getMoreContainer());
            this.showLess = $(this.getMoreContainer()).select('.less a')[0];
            if (m = $(this.getMoreContainer()).up('li').down('.event_expander > .more')) {

                m.hide();
            }
            if (l = $(this.getMoreContainer()).up('li').down('.event_expander > .less')) {
                l.show();
            }
            this.registerLessLink();
            $(this.getMoreContainer()).setStyle({
                display : 'block'
            });
            this.onAjaxLoad.fire(this);
        },
        moreButton_onClick_listener : function(e) {
            try {
                var t = $(e.target);
                if($(this.getMoreContainer()).visible() && this.visible == false) {
                    this.hideMore();
                    if (t.down('.more')) {
                        t.down('.more').show();
                    }
                    if (t.down('.less')) {
                        t.down('.less').hide();
                    }
                    this.visible = false;
                } else {
                    this.showMore();
                    if (t.down('.more')) {
                        t.down('.more').hide();
                    }
                    if (t.down('.less')) {
                        t.down('.less').show();
                    }
                    this.visible = true;
                }
            }
            catch(error) { INDABA.log(error);}
            finally {
                Event.stop(e);
                return false;
            }
        },
        registerLessLink : function() {
            if(this.showLess) {
                this.showLess.observe("click",this.hideMore.bind(this));
                $(this.getMoreButton()).up('span').setStyle({
                    display:'none'
                });
                this.showLess.up('span').setStyle({
                    display:'inline'
                });
            }
        },
        showMore : function() {
            if(this.getMoreContainer().innerHTML === "") {
                INDABA.util.toggleElementLoadingV2(this.getMoreContainer(),null,null, {
                        height: "100px",
                        width: "100%",
                        clear: 'both'
                    });
                this.getMoreContainer().style.display = "block";
                var that = this;
                var c = this.loadMore_onComplete.bind(this);
                var a = new Ajax.Updater(this.getMoreContainer(),this.getMoreButton().href, {
                    onComplete : c
                });
            }
            else {
                $(this.getMoreContainer()).setStyle({
                    display : 'block'
                });
                this.registerLessLink();
            }
        },
        hideMore : function() {
            $(this.getMoreContainer()).setStyle({
                display : 'none'
            });
            if(this.showLess) {
                this.showLess.stopObserving("click");
                this.showLess.up('span').setStyle({
                    display:'none'
                });
                $(this.getMoreButton()).up('span').setStyle({
                    display:'inline'
                });
            }
        },
        getContainer : function() {
            return this.event.getContainer();
        },
        init : function() {
            Event.observe(this.getMoreButton(),"click",this.moreButton_onClick_listener.bind(this));            
            this.event.init();
        },
        retire : function() {
            Event.stopObserving(this.getMoreButton(),"click");
            this.event.retire();
        }
    };
    
    INDABA.controls.EventItem_WithSubItems = function(item) {
        try {
            var moreLink = $(item.getContainer()).getElementsByClassName('event_expander')[0];
            var divId = moreLink.id.replace('expand_events_','');
            
            if (moreLink) {
                var moreSection = document.getElementById('events_'+divId);
            
                this.event = new INDABA.controls.EventItem_WithMore(item, moreLink, moreSection);
                this.getMoreSection = function() { return moreSection; };
            }
        }
        catch (error) {
        }
    };
    INDABA.controls.EventItem_WithSubItems.prototype = {
        subFeed : null,
        ajaxLoad_listener : function(e) {
            if(this.subFeed === null) {
                this.subFeed = new INDABA.controls.SubEventFeed(this.getMoreSection());
                this.subFeed.rebind();
            }
        },
        init : function() {
            this.event.onAjaxLoad.addListener(this.ajaxLoad_listener.bind(this));
            this.event.init();
        },
        retire : function() {
            if(this.subFeed) {
                this.subFeed.unbind();
            }
            this.event.retire();
        },
        getContainer : function() {
            return this.event.getContainer();
        }
    };
    
    INDABA.controls.EventItem_WithPolling = function(item) {
        this.event = item;
        try {
            this.spinner = $(this.event.getContainer()).select('.sml_playbutton_disabled.pbutton')[0];
            this.spinner.observe('mouseover',function() { Tip("We're currently processing this file. It will be ready when it's ready!");});
            this.song_id = this.spinner.select('input[name=song_id]')[0].value;
            this.poll_timeout = setTimeout(this.poll.bind(this),this.poll_interval);
        }
        catch (e) {
        }
    };
    
    INDABA.controls.EventItem_WithPolling.prototype = {
        poll_interval : 10000,
        poll_timeout : null,
        poll_retry_count : 0,
        poll_retry_max : 5,
        poll : function() {
            var request = new Ajax.Request('/iterations/check_processing/'+this.song_id,{
                method : 'get',
                onSuccess : this.poll_success.bind(this),
                onFailure : this.poll_failure.bind(this)
            });
        },
        poll_success : function(response) {
            if(response.responseText !== "") {
                this.insert_playbutton(response.responseText);
            }
            else {
                this.poll_timeout = setTimeout(this.poll.bind(this),this.poll_interval);
            }
        },
        poll_failure : function(response) {
            if(this.poll_retry_count++ <= this.poll_retry_max) {
                this.poll_timeout = setTimeout(this.poll.bind(this),this.poll_interval);
            }
        },
        insert_playbutton : function(html) {
            this.spinner.insert({
                before : html
            });
            this.spinner.parentNode.removeChild(this.spinner);
            this.event = new INDABA.controls.EventItem_WithPlayButton(this.event);
            this.getContainer().removeClassName('processing');
            this.getContainer().removeClassName('polling');
            this.event.init();
            clearTimeout(this.poll_timeout);
        },
        disable_polling : function() {
            clearTimeout(this.poll_timeout);
        },
        init : function() {
            this.event.init();
        },
        retire : function() {
            clearTimeout(this.poll_timeout);
            this.event.retire();
        },        
        getContainer : function() {
            return this.event.getContainer();
        }
    };
    
    INDABA.controls.EventItem_WithInPlaceEdit = function(eventItem) {
        this.event = eventItem;
    };
    INDABA.controls.EventItem_WithInPlaceEdit.prototype = {
        inPlaceEdit : null,
        init : function() {
            try {
                var dom_id  = this.event.getContainer().select(".in_place_edit")[0].id;
                var file_id = dom_id.replace("file_name_", "");
                this.inPlaceEdit = new Ajax.InPlaceEditor(dom_id, '/iterations/update_name/' + file_id, {rows: 1, submitOnBlur:false, okText: 'save'});
            }   
            catch(err) {

            }
            finally {
                this.event.init();
            }
        },
        retire : function() {
            delete this.inPlaceEdit;
            this.event.retire();
        },
        getContainer : function() {
            return this.event.getContainer();
        }
    };
    
    INDABA.util.EventItemFactory = function(container) {

            var c = $(container);
            var item = new INDABA.controls.EventItem(c);
            if(c.hasClassName("iteration")) {
                try {
                    item = new INDABA.controls.EventItem_WithPlayButton(item);
                }
                catch(e) {
                    INDABA.log(e);
                }
            }
            if(c.getElementsByClassName("action_dropdown").length > 0) {
                try {
                    var dd = c.getElementsByClassName("action_dropdown")[0];
                    var b = dd.select('.activate_button')[0];
                    var o = dd.select('.options')[0];
                    if(b && o) {
                        item = new INDABA.controls.EventItem_WithActionMenu(item,b,o);
                    }
                }
                catch(e) {
                    INDABA.log(e);
                }
            }
            if(c.select('span.details').length > 0) {
                try {
                    var s = c.getElementsByClassName('details')[0];
                    if(s) {
                        var a = s.getElementsByTagName("A")[0];
                        var id = s.id.replace('event_details_more_',"");
                        var div = document.getElementById("event_details_"+id);
                        if(INDABA.util.isNode(s) && INDABA.util.isNode(div)) {
                            item = new INDABA.controls.EventItem_WithMore(item,a,div);
                        }
                    }
                }
                catch(e) {
                    INDABA.log(e);
                }
            }
            if(c.hasClassName("in_place_edit")) {
                try {
                    item = new INDABA.controls.EventItem_WithInPlaceEdit(item);
                }
                catch(e) {
                    INDABA.log(e);
                }
            }
            if(c.getElementsByClassName('event_expander').length > 0) {
                try {
                    item = new INDABA.controls.EventItem_WithSubItems(item);
                }
                catch(e) {
                    INDABA.log(e);
                }
            }
            if(c.hasClassName("polling")) {
                try {
                    item = new INDABA.controls.EventItem_WithPolling(item);
                }
                catch(e) {
                    INDABA.log(e);
                }
            }

            return item;
    };
    
    INDABA.init.files_table = function() {
      sorttable.makeSortable($("files_table"));
      INDABA.Page.initPage('files_table');
    };
    INDABA.init.mixes_table = function() {
      INDABA.Page.initPage('mixes_table');
    };
})();
}