ark_require('js/tdialog.js');
ark_require('js/modules/tributeAdd.js');
ark_require('js/modules/tributeStories.js');
ark_require('js/modules/tributePhoto.js');
ark_require('js/modules/tributeDeadline.js');
ark_require('js/modules/tributeCredits.js');

var TributePage = { };

(function() {
    var Dom = YAHOO.util.Dom,
        Event = YAHOO.util.Event,
        CustomEvent = YAHOO.util.CustomEvent;
 
    TributePage = {
        oCache: null,
        bVerbose: false,

        log: function(mg) {
            if( "console" in window ) {
                if( this.bVerbose ) {
                    console.log(msg);
                }
            }
        },
        start: function() {
            this.log('TributePage starting...');
            if( typeof TributeAdd != 'undefined' ) {
                TributeAdd.start();
                TributeAdd.storyAddedEvent.subscribe(this.storyAdded,this,true);
            }
            if( typeof TributeStories != 'undefined' ) {
                TributeStories.start();
            }
            if( typeof TributePhoto != 'undefined' ) {
                TributePhoto.start();
            }
            if( typeof TributeDeadline != 'undefined' ) {
                TributeDeadline.start();
            }
            if( typeof TributeCredits != 'undefined' ) {
                TributeCredits.start();
            }
            var embeds = Dom.getElementsByClassName('ttEmbed','p');
            for( var i = 0; i < embeds.length; i++ ) {
                Dom.setStyle(embeds[i],'visibility','visible');
            }
        },
        storyAdded: function(type,args) {
            this.log('Story Added: '+type+' '+args);
            // refresh content
            this.fetchAllStories();
        },

        fetchAllStoriesFetched: function(type,args) {
            this.log('fetchAllStoriesFetched '+type+' '+args);
            var oContent = args[0];
            if( oContent.key == 'tribute_body' ) {
                this.log('this is content for tribute body');
                var html = oContent._html;
                if( html ) {
                var elt = YAHOO.util.Dom.get('tribute_body');
                if( elt ) {
                    this.log('updating content size ='+html.length);
                    elt.innerHTML = html;
                    //Dom.setStyle('tribute_body_loader','display','none');
                    //Dom.setStyle('tribute_body','display','block');
                    var e = { href: '#action_bar' };
                    ark.widget.Scroller.anchorScroll(e);
                }

                // re-attach events for all stories
                TributeStories.initStories();
                }
            }
        },
        fetchAllStories: function() {
            this.log('fetchAllStories');
            if( !this.oCache ) {
                this.oCache = new ark.util.LazyContent();
                this.oCache.LoadedEvent.subscribe(this.fetchAllStoriesFetched,this,true);
            }
            this.oCache.clearCache('tribute_body');
            // show loading stuff
            var sURL = '/tribute/fetch_tribute_body.json?t='+iTribute;
            if( typeof create_new != 'undefined' && create_new ) {
                sURL += '&incomplete=1';
            }
            this.oCache.load('tribute_body',sURL);
        },
        TemplateSavedEvent: new CustomEvent('TemplateSavedEvent', this),  
        TemplateOpenedEvent: new CustomEvent('TemplateOpenedEvent', this),  
        TemplateClosedEvent: new CustomEvent('TemplateClosedEvent', this),  
        bDesignLoaded:false,
        oTemplate: false,
        sCurrentDesignNode:false,
        sCurrentNode:false,
        sCurrentTemplate:false,
        sCurrentTemplateFile:false,
        sCurrentTemplateIcon:false,
        sCurrentTemplateIconTitle:false,
        closeTemplate: function(oE) {
            if (oE) {
                Event.stopEvent(oE);
            }
            this.oTemplate.collapse();
        },
        customizeDesignOpened: function() {
            this.oTemplate.ExpandedEvent.unsubscribe(this.customizeDesignOpened, this, true);
            this._selectDesignNode = function() {   
                this._currentNode = false;
                if (!this.sCurrentNode) {
                    var aA = Dom.get('tempNav').getElementsByTagName( 'a'); 
                    if (aA) {
                        for ( var i=0, len=aA.length ; i<len ; i++ ) { 
                            var oA = aA[i]; 
                            if (oA && oA.getAttribute('id')) {
                                this._sCurrentNode =  oA.getAttribute('id');
                                i = aA.length;
                            }
                        } 
                    }
                    this.openTemplates(this._sCurrentNode);
                }
            };
            Event.onContentReady('tempNav',  this._selectDesignNode, this, true); 
        },
        customizeDesignUpdateCurrent: function() {
            if (!this.sCurrentTemplate) {
                return false;
            }
            var aA= Dom.getElementsByClassName('skins', 'a', 'currentDesignTemplate'); 
            if (aA.length && aA[0]) {
                var oA = aA[0];
                Dom.setStyle('currentDesignTemplate', 'visibility', 'visible');
                if (oA.getAttribute('id') != this.sCurrentTemplate) {
                    var aIcon = Dom.getElementsByClassName('designIcon', 'img', 'currentDesignTemplate'); 
                    if (aIcon.length && aIcon[0]) {
                        var oIcon = aIcon[0];
                        oA.setAttribute('id', this.sCurrentTemplate);
                        oA.setAttribute('title', this.sCurrentTemplateIconTitle);
                        oA.setAttribute('skin', this.sCurrentTemplateFile);
                        oIcon.setAttribute('src', this.sCurrentTemplateIcon);
                        oIcon.setAttribute('title', this.sCurrentTemplateIconTitle);
                         
                        var aTitle = Dom.getElementsByClassName('templateTitle', 'strong', oA); 
                        if (aTitle.length && aTitle[0]) {
                            var oTitle = aTitle[0];
                            oTitle.innerHTML =  this.sCurrentTemplateIconTitle;
                        }
                    }
                }
            }
        },
        customizeClicked: function(oE) {
            Event.stopEvent(oE); 
            if( !this.oTemplate ) {
                this.oTemplate = new ark.widget.Collapsable("tW");
                this.oTemplate.content_url = '/edit_template/fetch_form.json?t='+iTribute;
                this.oTemplate.content_early = true;
                this._closeTemplates = function(){  Event.on('tempDone', 'click', this.closeTemplate, this, true); } 
                Event.onContentReady('tempDone', this._closeTemplates, this , true); 
                this.openedDesign = function(){ 
                    this.customizeDesignOpened(); 
                    this.TemplateOpenedEvent.fire();
                } 
                this.closedDesign = function() { 
                    this.customizeDesignUpdateCurrent();
                }
                this.closingDesign = function() { 
                    this.TemplateClosedEvent.fire();
                }
                
                this.oTemplate.ExpandedEvent.subscribe(this.openedDesign, this, true);
                this.oTemplate.CollapsedEvent.subscribe(this.closedDesign, this, true);
                this.oTemplate.CollapsingEvent.subscribe(this.closingDesign, this, true);
            }
            this.oTemplate.toggle();
        },
        openTemplates: function(sId) {
            if (sId != this.sCurrentNode) {
                var sNode = sId +'-templates';
                if (this.sCurrentNode) {
                    Dom.setStyle(this.sCurrentNode +'-templates', 'display', 'none');
                    Dom.removeClass(this.sCurrentNode, 'selected');
                }
                Dom.addClass(sId, 'selected');
                Dom.setStyle(sNode, 'display', 'block');
                this.sCurrentNode = sId;
            }
        },
        changeTemplate: function(sId) {
            if (sId != this.sCurrentTemplate) {
                if (this.sCurrentTemplate) {
                    Dom.removeClass(this.sCurrentTemplate, 'skinSelected');
                }
                Dom.addClass(sId, 'skinSelected');
                var oSkin = Dom.get(sId);
                var sFile = oSkin.getAttribute('skin');
                
                this.saveTemplateChange(sId, sFile);
                this.sCurrentTemplate = sId;
                this.sCurrentTemplateFile = sFile;
                var aIcon = Dom.getElementsByClassName('designIcon', 'img', sId); 
                if (aIcon.length && aIcon[0]) {
                    var oIcon = aIcon[0];
                    this.sCurrentTemplateIcon = oIcon.getAttribute('src');
                    this.sCurrentTemplateIconTitle = oIcon.getAttribute('title');
                }
            }
        },
        saveTemplateChange: function(sTemplate, sFile) {
            var oSkin = Dom.get('css_skin');
            if (oSkin) {
                oSkin.setAttribute('href',sFile);
            } else {
                var oHead = document.documentElement.getElementsByTagName("HEAD")[0];
                var oLink = document.createElement('link');
                oLink.setAttribute('id', 'css_skin');
                oLink.setAttribute('type', 'text/css');
                oLink.setAttribute('media', 'all');
                oLink.setAttribute('rel', 'stylesheet');
                oLink.setAttribute('href',sFile);
                oHead.appendChild(oLink);
            }
            var sQuery = 't='+iTribute +'&temp='+encodeURIComponent(sTemplate);
            var aCallback = {
                    success: function() {},
                    failure: function() {},
                    timeout: 5000
                };
            YAHOO.util.Connect.asyncRequest('POST','/edit_template/setTemplate.json',aCallback,sQuery);
            this.TemplateSavedEvent.fire();
        }
    };

})();


YAHOO.util.Event.onDOMReady(TributePage.start,TributePage,true);

