function MlyBlogApp() {
    this.initRequest();
    this.initStylesheets();
}

MlyBlogApp.prototype = {
    dialogState: 0,
    xsltManager: null,
    reqManager: null,
    lastSelectedUser: 0,
    lastEntryEdit: null,
    tagdialog: null,
    cookieMgr: null,
    draftview: 0,
    
    initStylesheets: function() {
        var baseuri = "http://" + MLY_BLOG_STYLEURI;
        var editblog = baseuri + "editblog.xsl";
        var viewblog = baseuri + "viewblog.xsl";
        
        var editentry = baseuri + "editentry.xsl"
            var viewentry = baseuri + "viewentry.xsl";
        var editperms = baseuri + "editpermissions.xsl"
            var archive   = baseuri + "archive.xsl";
        var tagcloud  = baseuri + "tagcloud.xsl";
        
        this.xsltManager = new MlyXSLTManager();
        this.xsltManager.addStyleURI( "editinfo", editblog);
        this.xsltManager.addStyleURI( "info", viewblog);
        this.xsltManager.addStyleURI( "editentry", editentry);
        this.xsltManager.addStyleURI( "viewentry", viewentry);
        this.xsltManager.addStyleURI( "editpermissions", editperms);
        this.xsltManager.addStyleURI( "archive", archive);
        this.xsltManager.addStyleURI( "tagcloud", tagcloud);
        
        this.xsltManager.addXSLParam( "servername", MLY_BLOG_BASEURI );
        this.xsltManager.addXSLParam( "imagepath", MLY_BLOG_IMAGEURI );
    },
    
    initRequest: function() {
        this.reqManager = new MlyRequestManager(MLY_BLOG_BASEURI);
    },
    
    editInfo: function() {
        // fetch edit information from the server
        this.reqManager.prepareURI("/-/info.raw", false);
        this.reqManager.request( null, false );
        
        var rpcdoc = this.reqManager.rpcresult;
        
        // fill the info dialog
        this.xsltManager.display( "editinfo", "bidialog", rpcdoc );
        
        // show info dialog
        this.xsltManager.changeStyle( 'bidialogframe', 
                                      'visibleinlinedialog'); 
        this.xsltManager.changeStyle( 'blogheader', 
                                      'invisibleblock');
        
        return false;
    },
    
    storeInfo: function() {
        // collect edited information from the form
        var fInfo = document.getElementById( "infoform" );
        if ( fInfo ) {
            this.reqManager.addToEnvelope( "id",    fInfo.blogid.value );
            this.reqManager.addToEnvelope( "name",  fInfo.blogname.value );
            this.reqManager.addToEnvelope( "title", fInfo.blogtitle.value );
            this.reqManager.addToEnvelope( "info",  fInfo.bloginfo.value );
            
            // post the data to the server
            // Store blog RAW has to return the bloginfo dataset
            this.reqManager.prepareURI("/-/info.xml", false); 
            this.reqManager.request( null, false );
            
            // reload server info
            var rpcdoc = this.reqManager.rpcresult;
            this.xsltManager.display( "info", "blogheader", rpcdoc );
        }
        
        // hide info dialog
        this.cancelInfo();

        return false;
    },
    
    cancelInfo: function() {
        // hide info dialog
        this.xsltManager.changeStyle( 'bidialogframe', 
                                      'invisibleblock'); 
        this.xsltManager.switchStyle( 'blogheader', 
                                      'visibleinline', 
                                      'invisibleblock');
        return false;
    },
    
    editEntry: function(name) {
        var datadoc;
        if ( name != null && name.length ) {
            // fetch edit information from the server
	    var urlext = "";

	    if ( this.draftview == 1 ) {
		urlext = "?published=0";
	    }

            this.reqManager.prepareURI("/"  + name + ".raw" + urlext, false)
            this.reqManager.request( null, false );
            datadoc = this.reqManager.rpcresult;
        }
        else {
            // create a dummy document
            datadoc = mlyCreateDocument();
            var theroot = datadoc.createElement( 'document' );
            datadoc.appendChild( theroot );
        }

        this.cancelEntry(this.lastEntryEdit);
        
        // fill the entry dialog
        if ( name != null && name.length ) {
            this.xsltManager.displayAfter( "editentry", 
                                           'view' + name , 
                                           datadoc );
        }
        else {
            this.xsltManager.displayList( "editentry", 
                                          'entrylist' , 
                                          datadoc, 
                                          1 );
        }

        // show entry dialog
        var cstate = this.cookieMgr.getCookiePart( 'widget', 'edit');

        if ( cstate != null && cstate.length > 0 && cstate == 1 ) {
            this.xsltManager.changeStyle( 'editframe', 
                                          'capturingblock'); 
        }
        else {
            this.xsltManager.changeStyle( 'editframe', 
                                          'visibleinlinedialog'); 
        }
        if ( name != null && name.length ) {
            this.xsltManager.switchStyle( 'view' + name, 
                                          'visibleinline', 
                                          'invisibleblock');
        }

        this.lastEntryEdit = name;

        return false;
    },
    
    storeEntry: function(name) {
        // collect edited information from the form and 
        // prepare the POST envelope
        var fInfo = document.getElementById( "entryform"  );
        if ( fInfo ) {
            this.reqManager.addToEnvelope( "id",    fInfo.entryid.value );
            this.reqManager.addToEnvelope( "name",  fInfo.entryname.value );
            this.reqManager.addToEnvelope( "title", fInfo.entrytitle.value );
            this.reqManager.addToEnvelope( "content",  fInfo.entrycontent.value );
	    var publ = 1;
	    if ( !fInfo.published.checked ) {
		publ = 0;
	    }
	    this.reqManager.addToEnvelope( "published", publ );
        }
        
        var tagid = "view" + name;
        var thename = name;
        if ( name == null || name.length == 0 ) {
            thename = '-';
        }

        this.reqManager.prepareURI("/" + thename + ".xml", false); 

        this.reqManager.request( null, false );
        var rpcdoc = this.reqManager.rpcresult;

        // alert( mlySerializeNode( rpcdoc ) );
        
        // fill the info dialog
        if ( thename == '-' ) {
            this.xsltManager.displayList( "viewentry", 'entrylist' , rpcdoc, 1 );
        }
        else {
            this.xsltManager.display( "viewentry", "view" +  name , rpcdoc );
        }
        
        // hide entry dialog
        this.xsltManager.undisplay( 'editframe' ); 

        // if ( name != null && name.length ) {
        // this.xsltManager.switchStyle( 'view' + name, 
        //			          'visibleinline', 
        //		          'invisibleblock');
        // }

        this.dialogState = 0;
        this.lastEntryEdit = null;
        return false;
    },

    deleteEntry: function(name) {
	// remove the entry from the blog
	this.reqManager.prepareURI("/" + name + ".xml", false); 
	this.reqManager.sendType = "DELETE";
	this.reqManager.request( null, false );
        var rpcdoc = this.reqManager.rpcresult;

	// if the entry was deleted, it is removed from the display
	// list
	
	if( rpcdoc != null && rpcdoc.documentElement != null ) {
	    var tstatus = rpcdoc.documentElement.getElementsByTagName('status');
	    if ( tstatus != null && 
		 tstatus.length && 
		 tstatus[0].textContent == "OK" ) {
		this.xsltManager.undisplay( "view"+name );
	    }
	}
	
    },
    
    cancelEntry: function(name) {
        // hide entry dialog
        var dframe;
        this.xsltManager.undisplay( 'editframe' ); 
        if ( name != null && name.length ) {
            this.xsltManager.switchStyle( 'view' + name, 
                                          'visibleinline', 
                                          'invisibleblock');
        }

        this.dialogState = 0;
        this.lastEntryEdit = null;
        return false;
    },
    
    resizeInfo: function() {
        this.xsltManager.switchStyle('bidialogframe', 
                                     'visibleinlinedialog', 
                                     'capturingblock');
        return false;
    },
    
    resizeEntry: function(name) {
        if ( name != null && name.length ) {
            this.xsltManager.switchStyle('editframe', 
                                         'visibleinlinedialog', 
                                         'capturingblock');
        }
        else {
            this.xsltManager.switchStyle('editframe', 
                                         'visibleinlinedialog', 
                                         'capturingblock');

        }
        var wstate = this.xsltManager.testStyle( 'editframe', 'capturingblock');
        this.cookieMgr.setCookiePart('widget', 'edit', wstate);
        this.cookieMgr.storeCookies(0);
        
        return false;
    },
    
    editPermissions: function(){
        // load user list 
        var te = document.getElementById( 'permdialogframe' );
        if ( te == null ) {
            this.reqManager.prepareURI(    "/-/privileges.raw", false);
            this.reqManager.request( null, false );

            var rpcdoc = this.reqManager.rpcresult;

            // var rpcdoc = mlyCreateDocument();
            // var theroot = rpcdoc.createElement( 'document' );
            // rpcdoc.appendChild( theroot );
            
            this.xsltManager.displayAfter( "editpermissions", 
                                           "blogtoolsblock", 
                                           rpcdoc );
            return false;
        }
    },

    storePermissions: function() {
        this.applyPermissions();
        this.cancelPermissions();
        return false;
    },

    applyPermissions: function() {
        if ( document.forms['permissions'].userid.value > 0 ) {
            this.reqManager.addToEnvelope( "grantid", document.forms['permissions'].userid.value );

            var getparam = 0;
            if ( document.forms['permissions'].GETPUB.checked ) {
                getparam = 1;
            }

            if ( document.forms['permissions'].GETPRIV.checked ) {
                getparam = 2;
                document.forms['permissions'].GETPUB.checked = true;
            }

            this.reqManager.addToEnvelope( "get", getparam );

            if ( document.forms['permissions'].STORE.checked ) {
                this.reqManager.addToEnvelope( "store", 1 );
            }
            else {
                this.reqManager.addToEnvelope( "store", 0 );
            }

            if ( document.forms['permissions'].DELETE.checked ) {
                this.reqManager.addToEnvelope( "delete", 1 );
            }
            else {
                this.reqManager.addToEnvelope( "delete", 0 );
            }

            if ( document.forms['permissions'].GRANT.checked ) {
                this.reqManager.addToEnvelope( "grant", 1 );
            }
            else {
                this.reqManager.addToEnvelope( "grant", 0 );
            }

            this.reqManager.prepareURI("/-/privileges.raw", false);
            this.reqManager.request( null, false );
        }

        return false;
    },

    cancelPermissions: function() {
        this.xsltManager.undisplay( 'permdialogframe' ); 
        return false;
    },

    selectUser: function(uid) {
        // fetch the permissions for the user
        // this.reqManager.addToEnvelope( "grantid", uid );

        this.reqManager.prepareURI( "/-/privileges.raw?grantid=" + uid,
                                    false);
        this.reqManager.request( null, false );

        var rpcdoc = this.reqManager.rpcresult;

        document.forms['permissions'].userid.value = uid;

        document.forms['permissions'].GETPUB.checked = false;
        document.forms['permissions'].GETPRIV.checked = false;
        document.forms['permissions'].STORE.checked = false;
        document.forms['permissions'].GRANT.checked = false;
        document.forms['permissions'].DELETE.checked = false;

        // update the dialog
        var perms = rpcdoc.getElementsByTagName( 'permission' );

        if ( perms != null && perms.length ) {
            var i;
            var name;
            var value;

            for ( i = 0; i < perms.length; i++ ) {
                if ( perms[i].firstChild.tagName == 'name' ) {
                    name = perms[i].firstChild.textContent;
                    value = perms[i].lastChild.textContent;
                }
                else {
                    name = perms[i].lastChild.textContent;
                    value = perms[i].firstChild.textContent;
                }

                switch (name) {
                case 'GET':
                    if ( value == 1 ) {
                        document.forms['permissions'].GETPUB.checked = true;
                    }
                    else if ( value == 2 ) {
                        document.forms['permissions'].GETPUB.checked = true;
                        document.forms['permissions'].GETPRIV.checked = true;
                    }
                    break;
                case 'STORE':
                    if ( value == 1 ) {
                        document.forms['permissions'].STORE.checked = true;
                    }
                    break;
                case 'GRANT':
                    if ( value == 1 ) {
                        document.forms['permissions'].GRANT.checked = true;
                    }
                    break;
                case 'DELETE':
                    if ( value == 1 ) {
                        document.forms['permissions'].DELETE.checked = true;
                    }
                    break;
                }
            }

        }

        this.xsltManager.changeStyle( 'user' + this.lastSelectedUser, 
                                      'user'); 
        
        this.lastSelectedUser = uid;

        this.xsltManager.changeStyle( 'user' + this.lastSelectedUser, 
                                      'selecteduser'); 

        return false;
    },

    fixTools: function() {
        var cstate = this.cookieMgr.getCookiePart( 'widget', 'tool');
        var wstate = this.xsltManager.testStyle( 'blogtools', 'tagcloud');

	// check which view is active (draft or public)
	var path = document.location.href;
	var md   = path.match(/\/-\/drafts/);

	if ( md != null && md.length > 0 ) {
	    this.draftview = 1;
	}

        if ( wstate != null ) {
            if ( cstate != null && cstate.length != 0 ) {
                if ( wstate != cstate ) {
                    this.toggleBlogtools();
                    this.cookieMgr.setCookiePart('widget', 'tool', cstate);
                }
            }
            else {
                this.cookieMgr.setCookiePart('widget', 'tool', wstate);
                this.cookieMgr.storeCookies(0);
            }
        }
    },

    displayArchive: function() {
        this.reqManager.prepareURI( "/-/archive.xml", false);
        this.reqManager.request( null, false );
        
        this.xsltManager.display( "archive", 
                                  "archive", 
                                  this.reqManager.rpcresult );
        // test the last state and toggle to that state
        var cstate = this.cookieMgr.getCookiePart( 'widget', 'arch');
        var wstate = this.xsltManager.testStyle( 'archivelist', 'tagcloud');


        if ( cstate != null && cstate.length != 0 ) {
            if ( wstate != cstate ) {
                this.toggleArchive();
                this.cookieMgr.setCookiePart('widget', 'arch', cstate);
            }
        }
        else {
            this.cookieMgr.setCookiePart('widget', 'arch', wstate);
            this.cookieMgr.storeCookies(0);
        }
    },

    displayTagcloud: function() {
        this.reqManager.prepareURI( "/-/tags.xml", false);
        this.reqManager.request( null, false );
        
        this.xsltManager.display( "tagcloud", 
                                  "tagcloud", 
                                  this.reqManager.rpcresult );
        // test the last state and toggle to that state
        var cstate = this.cookieMgr.getCookiePart( 'widget', 'tags');
        var wstate = this.xsltManager.testStyle( 'tagcloudlist', 'tagcloud');

        if ( cstate != null && cstate.length != 0 ) {
            if ( wstate != cstate ) {
                this.toggleTagcloud();
                this.cookieMgr.setCookiePart('widget', 'tags', cstate);
            }
        }
        else {
            this.cookieMgr.setCookiePart('widget', 'tags', wstate);
            this.cookieMgr.storeCookies(0);
        }
    },

    storeTag: function(ename) {
        if ( this.tagdialog && this.tagdialog != ename ) {
            this.toggleTagdialog( this.tagdialog );
        }
        
        var fname = ename + '_tagform';
        // alert( fname );
        var tags = document.getElementById(fname).taglist.value;
        
        var taglist = tags.split(' ');
        var i,t,len;
        len = taglist.length;
        t=0;
        for ( i=0; i<len;i++ ) {
            if ( taglist[i].length ) {
                this.reqManager.addToEnvelope('tag', taglist[i]);
                t++;
            }
        }

        if ( t > 0 ) {
            this.reqManager.prepareURI( "/"+ ename + "/-/tag.xml", false);
            this.reqManager.request(null, false);
            
            this.xsltManager.display( "viewentry", 
                                      "view" +  ename , 
                                      this.reqManager.rpcresult );
            this.tagdialog = null;
        }
        else {
            this.toggleTagdialog(ename);
            this.tagdialog = null;
        }
        return false;
    },
    

    toggleTagcloud: function() {
        this.xsltManager.switchStyle( 'tagcloudhidden',
                                      'invisibleblock',
                                      'tagcloud' ); 
        this.xsltManager.switchStyle( 'tagcloudlist',
                                      'invisibleblock',
                                      'tagcloud' );         
        var wstate = this.xsltManager.testStyle( 'tagcloudlist', 'tagcloud');
        this.cookieMgr.setCookiePart('widget', 'tags', wstate);
        this.cookieMgr.storeCookies(0);
    },


    toggleArchive: function() {
        this.xsltManager.switchStyle( 'archivelisthidden',
                                      'invisibleblock',
                                      'tagcloud' ); 
        this.xsltManager.switchStyle( 'archivelist',
                                      'invisibleblock',
                                      'tagcloud' );         
        var wstate = this.xsltManager.testStyle( 'archivelist', 'tagcloud');
        this.cookieMgr.setCookiePart('widget', 'arch', wstate);
        this.cookieMgr.storeCookies(0);

    },

    toggleBlogtools: function() {
        this.xsltManager.switchStyle( 'blogtoolshidden',
                                      'invisibleblock',
                                      'tagcloud' ); 
        this.xsltManager.switchStyle( 'blogtools',
                                      'invisibleblock',
                                      'tagcloud' );         
        var wstate = this.xsltManager.testStyle( 'blogtools', 'tagcloud');
        this.cookieMgr.setCookiePart('widget', 'tool', wstate);
        this.cookieMgr.storeCookies(0);
    },

    toggleTagdialog: function(ename) {
        if ( this.tagdialog && this.tagdialog != ename ) {
            this.toggleTagdialog( this.tagdialog );
        }
        
        this.xsltManager.switchStyle( ename + '_notagdialog',
                                      'invisibleblock',
                                      'dialogswitch' ); 
        this.xsltManager.switchStyle( ename + '_tagdialog',
                                      'invisibleblock',
                                      'visibleline' );  

        el = document.getElementById( ename + '_tagform' );

        if ( el.taglist.parentNode.className != 'invisileblock' ) {            
            el.taglist.focus();
            this.tagdialog= ename;
        }
        else {
            this.tagdialog= null;
        }
    }
};

var bapp = new MlyBlogApp();
bapp.cookieMgr = new CookieManager( 61, null, '/glahn/' );
if ( window.attachEvent ) {
    window.attachEvent( 'onload', function(e) { 
        bapp.fixTools(); 
        bapp.displayArchive(); 
        bapp.displayTagcloud();
        bapp.cookieMgr.storeCookies(0); } );
}
else if ( window.addEventListener ) {
    window.addEventListener( 'load', 
                             function(e) { bapp.fixTools();
                                           bapp.displayArchive(); 
                                           bapp.displayTagcloud(); 
                                           bapp.cookieMgr.storeCookies(0);},
                             false );
}