/**

    isg.js
        Author : Hamilton Chua (ham@solutiongrove.com)
        Date Created : 6/05/2007

    Base javascript code for iSolutiongrove

**/

Ext.namespace('isg');
Ext.BLANK_IMAGE_URL = '/resources/ajaxhelper/ext2/resources/images/default/s.gif';

isg = function(initdata) {

    // *** properties ****

    // initial data in json format
    //  used to build the initial portal
    this.rawdata = initdata;

    // return_url
    this.return_url = '/isg/';

    // xmlhttp files
    this.xmlhttpurl = '/isg/xmlhttp/';

    // the id of this portal
    this.portalid = null

    // the id of the owner
    this.ownerid = null;

    // reference to the layout object
    this.layout = null;

    // window for user registration
    this.registerwindow = null;

    // does the user have a Chat tab
    this.apps = [];

    this.app_rec = Ext.data.Record.create([
           {name: 'type', type: 'string'},
           {name: 'fullname', type: 'string'}
      ]);

    // *** initialize ****

    this.initObj = function() {

        Ext.QuickTips.init();
        this.createLayout();

    }

    Ext.onReady(this.initObj,this,true);

}

// *** methods ***

isg.prototype = {

    // create the borderlayout
    //  north - holds the header
    //  west - holds the settings
    //  center - holds the tabpanel

    createLayout : function() {

        this.layout = new Ext.Viewport({
            id:'userportal',
            layout:'border',
            items: [this.createNorth(),this.createEast(),this.createCenter()]
        });

    },

    createNorth : function() {
        var panel = new Ext.Panel({
            id:'header',
            region:'north',
            titlebar:false,
            split:false,
            height:25,
            frame:false,
            bodyStyle:{'background-color':'#455940','font':'12px arial,verdana,helvetica,sans-serif'},
            contentEl:'headerpanel',
            listeners:{
                'render':{
                    fn:function() {
                        if(document.getElementById('usersidebarlink')) {
                            Ext.get('usersidebarlink').on("click",function() {
                                this.layout.findById('eastpanel').layout.setActiveItem(1);
                                this.layout.findById('eastpanel').expand();
                                var newtabform = this.layout.findById('new_tab_form');
                                newtabform.expand();
                            },this);
                        }
                        if(document.getElementById('userregisterlink')) {
                            Ext.get('userregisterlink').on("click",function() { 
                                this.registerUser();
                            },this);
                        }
                    },scope:this
                }
            }
        });
        return panel;
    },

    createEast : function() {
        var panel = new Ext.Panel({
            id:'eastpanel',
            region:'east',
            layout:'card',
            defaults: {
                bodyStyle: { 'padding':'5px'}
            }, layoutConfig: {
                animate: true,
                activeOnTop: true
            }, collapsible:true,
            collapsed:true,
            collapseMode:'mini',
            title:'',
            titlebar:false,
            split:true,
            width:300,
            activeItem:1,
            items:[
                this.createAddStuff(),
                this.createTabOptions()
            ]
        });
        return panel;
    },
    
    // creates panel with stuff user can add to portal page
    createAddStuff : function() {
        var urlfieldset = new Ext.form.FieldSet ( {
            id:'add_rssfeedurl',
            autoHeight:true,
            title:'Type the URL of your RSS Feed',
            layout:'form',
            items : [ {
                xtype:'textfield',
                fieldLabel:'URL',
                name:'rssfeedurlfield',
                id:'rssfeedurlfield',
                width:150,
                allowBlank:false,
                value:'http://',
                validator:isURL
            } ], buttons :[
                {text:'Add Feed',handler:function() {
                    var feedform = this.layout.findById('add_rssfeedurl');
                    var activepage = this.layout.findById('portalpages').activeTab;
                    var urlfield = this.layout.findById('rssfeedurlfield');
                    if(urlfield.isValid()) {
                        feedform.getEl().mask('One moment ...');
                        Ext.Ajax.request({
                            url:this.xmlhttpurl+'addportlet',
                            scope:this,
                            success: function(response) {
                                var isgdata = Ext.decode(response.responseText);
                                var col = activepage.items.items[0].id;
                                var portlet = this.addPortlet(activepage,col,isgdata);
                                portlet.ownerCt.doLayout();
                                urlfield.setRawValue('http://');
                                feedform.getEl().unmask();
                                portlet.getUpdater().on("update",function() { this.getEl().frame() },portlet,{single:true});
                            }, failure: function(response) {
                                Ext.Msg.alert('Error','Sorry, an error occurred. Something could be wrong with the url you pasted or our system was not able to fetch the feeds for that url.');
                                feedform.getEl().unmask();
                            }, params: { page_id:activepage.isgdata.id, type:'rssfeed', url:urlfield.getValue() }
                        })
                    }
                }, scope:this}
            ]
        });
        var libfieldset = new Ext.form.FieldSet ( {
            id:'add_rssfeed',
            autoHeight:true,
            title:'Feed Library',
            autoLoad: {url:this.xmlhttpurl+'listfeeds'}
        });
        var contentfieldset = new Ext.form.FieldSet ( {
            id:'add_xowikicontent',
            autoHeight:true,
            title:'Content Library',
            autoLoad: {url:this.xmlhttpurl+'listcontent'}
        });
        var panel = new Ext.Panel({
            id:'addstuffpanel',
            title:'Add Stuff',
            autoScroll:true,
            items:[urlfieldset,libfieldset,contentfieldset],
            listeners: {
                'render': {
                    fn:function(panelobj) {
                        panelobj.body.on('click',function(e,clickedEl) { 
                            if(Ext.get(clickedEl).hasClass('feeditem')) {
                                var clickedparent = Ext.get(clickedEl.parentNode);
                                clickedparent.mask('One moment ...');
                                Ext.get(clickedEl).setVisibilityMode(Ext.Element.DISPLAY);
                                var activepage = this.layout.findById('portalpages').activeTab;
                                var col = activepage.items.items[0].id;
                                Ext.Ajax.request({
                                    url:this.xmlhttpurl+'addportlet',
                                    scope:this,
                                    success: function(response) {
                                        var isgdata = Ext.decode(response.responseText);
                                        var portlet = this.addPortlet(activepage,col,isgdata);
                                        portlet.ownerCt.doLayout();
                                        Ext.get(clickedEl).remove();
                                        Ext.get('br'+clickedEl.id).remove();
                                        clickedparent.unmask();
                                        portlet.getUpdater().on("update",function() { this.getEl().frame() },portlet,{single:true});
                                    }, failure: function(response) {
                                        Ext.Msg.alert('Error','Sorry, an unexpected error occurred. Please try again later.');
                                        clickedparent.unmask();
                                    }, params: { page_id:activepage.isgdata.id,reference_id:clickedEl.id, type:clickedEl.parentNode.id }
                                })
                            }
                        },this)
                    }, scope:this
                }
            }
        });
        return panel;
    },
    
    // creates the taboptions panel
    
    createTabOptions : function() {
        var titlefield = new Ext.form.TextField({
            fieldLabel:'Title',
            name:'pagetitle',
            id:'newpagetitle',
            width:150,
            allowBlank:false
        });
        var renfield= new Ext.form.TextField({
            fieldLabel:'New Title',
            name:'newpagetitle',
            id:'editpagetitle',
            width:150,
            allowBlank:true,
            selectOnFocus:true,
            listeners: {
                'focus':{
                    fn:function(titlefield) {
                        titlefield.setValue(this.layout.findById("portalpages").activeTab.title)
                    }, scope:this
                }
            }
        });
        var typecombo = new Ext.form.ComboBox({
            id:'newpagetype',
            fieldLabel: 'Type',
            hiddenName:'pagetype',
            store: new Ext.data.SimpleStore({
                fields: ['type', 'fullname'],
                reader: new Ext.data.ArrayReader({ }, this.app_rec),
                data : [['portal','Ajax Portal'],['chat','Chat']]
            }),
            valueField:'type',
            displayField:'fullname',
            typeAhead: true,
            mode: 'local',
            allowBlank:false,
            triggerAction: 'all',
            emptyText:'Select a type ...',
            editable:false,
            selectOnFocus:true,
            width:150,
            listeners: {
                'select':{
                    fn:function(obj,record,i) {
                        if(record.get('type') == "chat") {
                            titlefield.setValue(record.get('fullname'));
                        }
                    },scope:this
                }
            }
        });
        var addfieldset = new Ext.form.FieldSet ( {
            id:'addtabfieldset',
            autoHeight:true,
            title:'Add a Tab',
            items: [titlefield,typecombo]
        });
        var delfieldset = new Ext.form.FieldSet ( {
            id:'deltabfieldset',
            autoHeight:true,
            title:'Delete a Tab',
            height:50,
            html:'<span style="font-size:12px;font-family:arial,verdana,sans-serif">Click <img src="/resources/ajaxhelper/ext2/resources/images/default/tabs/tab-close.gif"> on the tab you want to delete</span>'
        });
        var editfieldset = new Ext.form.FieldSet({
            id:'edittabfieldset',
            autoHeight:true,
            title:'Rename Active Tab',
            items: [renfield], buttons: [
                {text:'Rename',handler:function() { 
                    var panel = this.layout.findById('portalpages').activeTab;
                    if(renfield.getValue()!="") {
                        Ext.Ajax.request({
                            url:this.xmlhttpurl+'renamepage',
                            success: function() {
                                panel.setTitle(renfield.getValue());
                                renfield.setRawValue("");
                            }, failure: function(response) {
                                Ext.Msg.alert('Error','Sorry, an unexpected error occurred. Please try again later.');
                            }, params: { page_id:panel.isgdata.id, pagetitle:renfield.getValue()}
                        })
                    }
                }, scope:this}
            ]
        });
        var newpageform = new Ext.form.FormPanel({
            id:'new_tab_form',
            title:'Tab Options',
            labelWidth: 80,
            autoScroll:true,
            items:[addfieldset,editfieldset,delfieldset],
            listeners: {
                'activate':{
                    fn:function() {
                        // nothing to do here yet
                    },scope:this
                }
            }
        });
        addfieldset.addButton({text:'Add Tab'},function(){
            if(newpageform.form.isValid()) {
                newpageform.form.submit({
                    waitMsg: 'One moment. Creating page ....',
                    url:this.xmlhttpurl+'addpage',
                    params:{'portal_id':this.portalid},
                    success:function(form,o) { 
                        var pageobj = Ext.decode(o.response.responseText);
                        this.addPortalPage(pageobj);
                        var tabpanel = this.layout.findById('portalpages');
                        tabpanel.activate(tabpanel.items.getCount()-1);
                        form.reset();
                    }.createDelegate(this), failure:function(form,o) {
                        var errobj = Ext.decode(o.responseText);
                        newpageform.form.markInvalid(errobj);
                    }
                })
            }
        },this);
        addfieldset.addButton({text:'Reset'}, function() { this.reset() }, newpageform.form);
        return newpageform;
    },

    // create the tabpanel and process the initdata

    createCenter : function() {

        this.portalid = this.rawdata.id;
        this.ownerid = this.rawdata.owner_id;

        // when a new page is added
        //  process the stuff for that portal page
        //  a portal page will only contain portlets for now
        //  but we may want to load other stuff later on

        var panel = new Ext.TabPanel({
            id:'portalpages',
            region:'center',
            activeTab:0,
            enableTabScroll:true,
            listeners: {
                'add': {
                    fn:this.setupPortalPage, scope:this
                }, 'beforeremove': {
                    fn:this.removePortalPage, scope:this
                }
            }
        });

        // add the portal page tabs to the tabpanel

        for (var x=0;x<this.rawdata.pages.length;x++) {
            this.addPortalPage(this.rawdata.pages[x],panel);
        }

        return panel;
    },

    // adds a tabbed page to the portal

    addPortalPage : function(pagedata,tabpanel) {
        if(typeof tabpanel == 'undefined') {
            var tabpanel = this.layout.findById('portalpages');
        }
        switch (pagedata.page_type) {
            case 'portal' :
                var items = [];
                for (var x=0;x!=pagedata.column_count;x++) {
                    colcount = x+1;
                    items.push({
                        id:'col'+pagedata.id+'_'+colcount,
                        columnWidth:.33,
                        style:'padding:10px 0 10px 10px',
                        defaults : {
                            bodyStyle: { 'padding':'8px'}
                        }
                    });
                }
                tabpanel.add({
                    xtype:'portal',
                    id:'portalpage'+pagedata.id,
                    title:pagedata.pretty_name,
                    closable:true,
                    isgdata: pagedata,
                    autoScroll:true,
                    tbar: new Ext.Toolbar({
                        items:[
                            '->',
                            {   text:'Add Stuff',
                                icon:'/resources/ajaxhelper/icons/application_add.png',
                                cls : 'x-btn-text-icon',handler:function() {
                                    this.layout.findById('eastpanel').layout.setActiveItem(0);
                                    this.layout.findById('eastpanel').expand();
                                    this.layout.findById('add_rssfeedurl').expand();
                                } ,scope:this }
                    ]}),
                    bodyStyle:{'background-image':'url(/resources/isg/images/sgrove.jpg)','background-repeat':'no-repeat','background-attachment':'fixed','background-position':'center bottom'},
                    items: items
                });
                break;
            case 'chat' :
                var chatobj = new isgChat({s:chat_s});
                chatobj.layout.title = pagedata.pretty_name;
                chatobj.layout.isgdata = pagedata;
                chatobj.layout.closable = true;
                tabpanel.add(chatobj.layout);
                chatobj.layout.on('deactivate',function(panelobj) { 
                    // put stuff here to run if chat tab is not active
                    // we may want to create a popup that displays the last chat message
                },this);
                chatobj.layout.on('activate',function(panelobj) { 
                    this.layout.findById('eastpanel').collapse();
                    if(chatobj.poller != null) {
                        chatobj.initPolling();
                    }
                },this);
                this.apps.push("chat");
                this.updateTabsdropdown();
                break;
        }
    },

    // fires when a new page is added

    setupPortalPage : function(tabpanel,panel,idx) {
        
        switch (panel.isgdata.page_type) {
            case 'portal' :
                // set up the portlets
                if(panel.isgdata.portlets) {
                    for (var x=0;x<panel.isgdata.portlets.length;x++) {
                        this.addPortlet(panel,'col'+panel.isgdata.id+'_'+panel.isgdata.portlets[x].column_n,panel.isgdata.portlets[x]);
                    }
                }
                // add a listener to expand/collapse feed item contents
                panel.on('render',function(panelobj) {
                    panelobj.body.on('click',function(e,clickedEl) { 
                        if(Ext.get(clickedEl.parentNode).hasClass('onefeedtitle')) {
                            var feedbullet = Ext.get(clickedEl);
                            var feedid = feedbullet.id.substring(10);
                            var feedcontent = Ext.get('feedcontent'+feedid);
                            feedcontent.setVisibilityMode(Ext.Element.DISPLAY);
                            if(feedbullet.hasClass('x-tool-toggle')){
                                feedbullet.removeClass('x-tool-toggle');
                                feedcontent.hide(false);
                            } else {
                                feedbullet.addClass('x-tool-toggle');
                                feedcontent.show(false);
                            }
                        }
                    });
                });
                panel.on('drop',this.reorderPortlets,this);
                break;
        }
    },

    // fires when a portal page is removed

    removePortalPage : function(tabpanel,panel) {
        // console.log('remove page');
        if(tabpanel.items.getCount()<=1) {
            Ext.Msg.alert('Error','Sorry, you can not delete the last tab on this portal.');
            return false;
        } else {
            // issue a confirmation prompt
            var confirmprompt = confirm('Are you sure you want to remove '+panel.title+'? All the data associated with this page will be removed.');
            if(!confirmprompt) {
                return false;
            } else {
                // FIXME : if an error occurs on delpage, we need to rollback the remove
                Ext.Ajax.request({
                    url:this.xmlhttpurl+'delpage',
                    success: function(response) {
                        switch (panel.isgdata.page_type) {
                            case 'chat' :
                                for(var x=0; x<this.apps.length; x++) {
                                    if(this.apps[x] == "chat") {
                                        this.apps.splice(x,1);
                                        break;
                                    }
                                }
                                break;
                        }
                        this.updateTabsdropdown();
                    }, failure: function(response) {
                        Ext.Msg.alert('Error','Sorry, an unexpected error occurred. Please try again later.');
                    }, params: { page_id:panel.isgdata.id}, scope:this
                });
                return true;
            }
        }
    },
    
    // update the sort order in the db after a portlet has been moved
    reorderPortlets : function(portalpage) {
        var orderstring = [];
        var colobj;
        for (var x=0;x<portalpage.portal.items.items.length;x++) {
            orderstring.push(portalpage.portal.items.items[x].id);
            for (var y=0;y<portalpage.portal.items.items[x].items.items.length;y++ ) {
                orderstring.push(portalpage.portal.items.items[x].items.items[y].id);
            }
        }
        if (orderstring.length != 0) {
            Ext.Ajax.request({
                url:this.xmlhttpurl+'reorderportlets',
                failure: function(response) {
                    Ext.Msg.alert('Error','Sorry, an unexpected error occurred. Please try again later.');
                }, params: { order:orderstring, id:portalpage.portal.id}
            });
        }
    },

    // adds a portlet to the given page and column

    addPortlet : function(pagepanel,col,data) {

        var tools = [{
            id:'close',
            handler: function(e, target, panel){
                this.removePortlet(panel);
            },scope:this }];

        var portlet = pagepanel.findById(col).insert(data.order_n-1,{
            id:'portlet'+data.id,
            title:data.title,
            layout:'fit',
            tools:tools,
            isgdata:data,
            plain:true,
            autoScroll:true,
            autoLoad: {
                url:this.xmlhttpurl+'loadportletcontent',
                params:{id:data.id},
                discardUrl:true,
                nocache:false,
                text:'Loading ...',
                callback:function(e,success,response,options) {
                    if(!success) {
                        e.update('<font style="color:red">Sorry, we ecountered an error fetching content for this portlet</font>')
                    }
                }
            }, collapsed:(data.min_p === 't') ? true : false,
            listeners: {
                'collapse': {
                    fn:function(portlet) {
                        Ext.Ajax.request({
                            url:this.xmlhttpurl+'updateportlet',
                            failure: function(response) {
                            }, params: { min_p:'t', id:portlet.isgdata.id}
                        });
                    }, scope:this
                },
                'expand': {
                    fn:function(portlet) {
                        Ext.Ajax.request({
                            url:this.xmlhttpurl+'updateportlet',
                            failure: function(response) {
                            }, params: { min_p:'f', id:portlet.isgdata.id}
                        });
                    }, scope:this
                }
            }
        });

        return portlet;
    },

    // updates the contents of the portlet

    updatePortlet : function(panel) {

        panel.body.load({
            url:this.xmlhttpurl+'loadportletcontent',
            params:{id:panel.isgdata.id},
            discardUrl:true,
            nocache:false,
            text:'Loading ...',
            scope:this,
            callback:function(e,success,response,options) {
                if(!success) {
                    panel.body.update('<font style="color:red">Sorry, we ecountered an error fetching content for this portlet</font>')
                }
            }
        });

    },

    // remove the portlet

    removePortlet : function(panel) {

        Ext.Ajax.request({
            url:this.xmlhttpurl+'delportlet',
            scope:this,
            success: function(response) {
                panel.ownerCt.remove(panel, true);
                this.layout.findById('add_rssfeed').load({url:this.xmlhttpurl+'listfeeds'});
                this.layout.findById('add_xowikicontent').load({url:this.xmlhttpurl+'listcontent'});
            }, failure: function(response) {
                Ext.Msg.alert('Error','Sorry, an unexpected error occurred. Please try again later.');
            }, params: { id:panel.isgdata.id }
        });

        return true;

    },

    // user registration window
    
    registerUser : function() {

        if(this.registerWindow==null) {
            this.registerWindow = new Ext.Window({
                title:'Sign Up',
                id:'register-win',
                layout:'fit',
                width:300,
                height:280,
                closeAction:'hide',
                modal:true,
                resizable:false,
                draggable:false,
                items: new Ext.FormPanel({
                    id:'registerform',
                    align:'left',
                    autoScroll:true,
                    closable:true,
                    layout:'form',
                    title:'All fields are required.',
                    headerAsText:true,
                    frame:true,
                    buttonAlign:'right',
                    items: [
                        {xtype:'textfield',fieldLabel: 'Email',allowBlank:false,name:'email',tabIndex:1,validator:isEmail},
                        {xtype:'textfield',fieldLabel: 'First Name',allowBlank:false,name:'fnames',tabIndex:2},
                        {xtype:'textfield',fieldLabel: 'Last Name',allowBlank:false,name:'lname',tabIndex:3},
                        {xtype:'textfield',fieldLabel: 'Password',id:'pw',inputType:'password',allowBlank:false,name:'password',tabIndex:4,validator: function(value) {
                            var secondPw = document.getElementById('pw2').value;
                            if(secondPw.length == 0)return true;
                            if(value != secondPw) { this.registerWindow.findById('pw').validate() }
                            return true }.createDelegate(this) },
                        {xtype:'textfield',fieldLabel: 'Confirm Password',id:'pw2',inputType:'password',allowBlank:false,name:'passwordconfirm',tabIndex:5,validator: function(value) { return (value==document.getElementById("pw").value) || "Your passwords do not match" } },
                        {xtype:'textfield',fieldLabel: 'Username',allowBlank:false,name:'screen_name',tabIndex:6}
                    ]
                }),
                buttons: [
                    {text:'Register Now',handler:function() {
                        var registerform = this.registerWindow.findById('registerform').getForm();
                        if(registerform.isValid()) {
                            registerform.submit( {
                                url:this.xmlhttpurl+'register',
                                waitMsg:'Registering ...',
                                scope:this,
                                success : function(form,action) {
                                    Ext.get(document.body).mask("Reloading ....");
                                    this.registerWindow.hide();
                                    // window.location.href="/isg/portal";
                                }, failure:function(form,action) {
                                    if(action.result) {
                                        Ext.MessageBox.alert('Error',action.result.error);
                                    }
                                }
                            });
                        }
                    }, scope:this},
                    {text:'Later',handler:function() {
                        this.registerWindow.hide()
                    }, scope:this}
                ]
            });
        }

        this.registerWindow.show('userregisterlink');
    },

    updateTabsdropdown : function(panel) {

        if(this.layout) {

            var newtabform = this.layout.findById('new_tab_form');
            var combo_store = newtabform.findById('newpagetype').store;
            var appfound = false;
    
            for(var x=0; x<this.apps.length; x++) {
                if(this.apps[x] == "chat") {
                    appfound = true;
                    break;
                }
            }

            if(appfound) {
                var record = combo_store.getAt(1);
                combo_store.remove(record);
            } else {
                var record = new this.app_rec({
                    type:'chat',
                    fullname:'Chat'
                });
                combo_store.add(record);
            }
    
        }

    }

}