/**
 * @author dmccuen
 *
 * MessageController is a singleton that manages all the MessagePanel
 * objects on the page.
 *
 * The MessagePanel is a private class of the controller and it relies
 * on html created in common/panel/message.tpl.  These objects are
 * normally create when the page loads.  However, the can be created
 * post-load.  For example, if 'id' is the id of a message panel
 * element that was added to the dom after the page loaded:
 *     MessagePanelController.createMessagePanel($(id));
 *
 * PBMessage is a public class that is used to display messages
 * post-load.  For example, if 'message' is a PBMessage:
 *     document.fire(PBMessage.EVENT.NOTIFY,{message : new PBMessage(cfg)});
 *
 *     cfg has the form {type : PBMessage.MESSAGE_TYPE.<type>, title : <string>, details : <string>}
 *
 */

// SINGLETON CONTROLLER
var MessagePanelController = Object.extend(Class.create({}),{
    INSTANCE: null,
    getInstance: function() {
        // Declare private classes
        var MessagePanel;
        var Controller;

        function createPrivateClasses() {
            // Private MessagePanel class
            MessagePanel = Class.create({
                pbType: "PBMessagePanel",
                titleClass: ".message",
                detailsClass: ".details",
                
                // redraw ids and/or classes for IE positioning issues due to toggling
                redrawList: ['.pbcontainer','.interstitial'],
                
                initialize: function(elem){
                    this.id = elem.id;
                    this.elem = elem;
                },
                notify: function(pbMessage){
                    var title = this.elem.down(this.titleClass);
                    // verify title exists as down fails sometimes in Safari
                    if(typeof title == 'undefined') title = this.loop(this.titleClass);
                    title.innerHTML = pbMessage.title || "";
                    if ((photobucket.browser.isIE6 || photobucket.browser.isIE7) && 
                            (typeof pbMessage.title == 'undefined' || pbMessage.title == ''))  {
                        title.hide();
                    } else {
                        title.show();
                    }

                    var details = this.elem.down(this.detailsClass);
                    // verify details exists as down fails sometimes in Safari
                    if(typeof details == 'undefined') details = this.loop(this.detailsClass);
                    details.innerHTML = pbMessage.details || "";

                    for (var i in PBMessage.MESSAGE_TYPE)
                        this.elem.removeClassName(PBMessage.MESSAGE_TYPE[i]);

                    this.elem.addClassName(pbMessage.type);
                    this.elem.show();
                    
                    // redraw specified elements for IE6 position issues when the message panel is toggled on
                    if (photobucket.browser.isIE) this.redraw();
                },
                close: function(){
                    this.elem.hide();

                    // redraw specified elements for IE6 position issues when the message panel is toggled off
                    if (photobucket.browser.isIE) this.redraw();
                },
                loop: function(search){
                    var tmp = $$('.message','.details');
                    for(var i=0;i<tmp.length;i++) {
                        if(tmp[i].hasClassName(search.replace(/./,''))) {
                            return tmp[i];
                            break;
                        }
                    }
                },
                redraw: function() {
                    for (var i=0;i<this.redrawList.length;i++) {
                        var redrawObj = jq(this.redrawList[i]).first();
                        if (typeof(redrawObj) != 'undefined') {
                            redrawObj.hide();
                            redrawObj.show();
                        }
                    }
                }
            });

            // Private Controller class
            Controller = Class.create({
                pbType: "PBMessagePanelController",
                cssClass: ".messagePanel",
                defaultPanelId: "MessagePanel",
                initialize: function(){
                    this.panel = {};
                    Event.observe(document, PB.EVENT.PAGE_LOADED, this.onDomLoaded.bindAsEventListener(this));
                    Event.observe(document, PBMessage.EVENT.NOTIFY, this.notify.bindAsEventListener(this));
                    Event.observe(document, PBMessage.EVENT.CLOSE, this.close.bindAsEventListener(this));
                    
                    if (typeof ThumbnailListManagerController != 'undefined') {
                        Event.observe(document, ThumbnailListManagerController.EVENT.CONTENTREFRESHED, this.closeForPagination.bindAsEventListener(this));
                    }
                    if (typeof CorePaginationController !== 'undefined') {
                        Event.observe(document, CorePaginationController.EVENT.UPDATE, this.closeForFullviewPagination.bindAsEventListener(this));
                    }
                },
                onDomLoaded: function(evt){
                    // find the MessagePanel elements in the DOM
                    var elem = $$(this.cssClass).toArray();
                    for (var i = 0; i < elem.length; i++) {
                        this.createMessagePanel(elem[i]);
                    }
                },
                createMessagePanel: function(elem){
                    if (elem != null) {
                        var p = new MessagePanel(elem);
                        this.panel[p.id] = p;
                    }
                },
                notify: function(evt){
                    var memo = evt.memo;
                    var id = memo.id || this.defaultPanelId;
                    
                    // create the message panel if it doesn't exist
                    // or if it's a lightbox message call to ensure it will exist if it was cloned
                    if (!this.panel[id] || memo.makeNewForLB) {
                        this.createMessagePanel($(id));
                    }
                    
                    if (!this.panel[id] || !memo.message ||
                    memo.message.pbType != PBMessage.TYPE)
                        return;
                    this.panel[id].notify(memo.message);
                    if (evt.memo.gotoHash)
                        var page = jq('html,body');
                        var hashOffset = jq('#'+id+'Hash').offset();
                        if(page){
                            page.animate({scrollTop: hashOffset.top},'slow');
                        }
                },
                close: function(evt){
                    var memo = evt.memo;
                    var id = memo.id || this.defaultPanelId;
                    if (!this.panel[id])
                        return;
                    this.panel[id].close();
                },
                closeForPagination: function(evt) {
                    // don't close message if on page #1 (initial album load)
                    if (evt.memo.start > 0) {
                        this.close(evt);
                    }
                },
                closeForFullviewPagination: function(evt) {
                    var memo ={
                        "id": "fullviewMessagePanel"
                    };
                    this.close({"memo": memo});
                },
                // BACKWARD COMPATABILITY
                printMessage: function(cfg) {
                    var m = new PBMessage(cfg);
                    this.notify({memo: {
                        message: m
                    }});
                },
                clearMessage: function() {
                    this.close({memo:{}})
                }
            });
        }

        if (MessagePanelController.INSTANCE == null) {
            createPrivateClasses();
            MessagePanelController.INSTANCE = new Controller();
        }

        return MessagePanelController.INSTANCE;
    }
});

var PBMessage = Class.create({
    initialize: function(cfg) {
        // ensure the type is valid
        if ($H(PBMessage.MESSAGE_TYPE).any(function(pair){return pair.value==cfg.type})) this.type = cfg.type;
        else this.type = PBMessage.MESSAGE_TYPE.SUCCESS;
        this.title = cfg.title||cfg.message;
        this.details = cfg.details;
        this.pbType = PBMessage.TYPE;
    }
});
PBMessage = Object.extend(PBMessage,{
    TYPE: "PBMessage",
    MESSAGE_TYPE: {ERROR:"error",ALERT:"alert",SUCCESS:"status",CONFIRM:"confirm",ROADBLOCK_ALERT:"roadblockAlert",ROADBLOCK_STATUS:"roadblockStatus",INFO:"info"},
    EVENT: {NOTIFY:"PBMessage:Notify",CLOSE:"PBMessage:Close"}
});

// TODO: Store the instance in the photobucket object
// storing the instance in this global variable for backward compatability
controllerMessagePanel = MessagePanelController.getInstance();

