/*

# author - Fred Beckhusen
# Copyright 2008 Micro Technology Services Inc.
#
# NOTICE: THIS SOFTWARE IS LICENSED TO YOU SUBJECT TO THE TERMS AND CONDITIONS OF THE LEGALLY BINDING LICENCE AGREEMENT.
# Micro Technology Services, Inc. ("Licensor") retains ownership of the software ("the Software") including without limitation all copyright and
# other intellectual property rights, anywhere in the world.
# Licensor grants you the non-exclusive license to access, display, run and use the Software.
# This license is personal to you, and you may not sub-license, rent, lend or lease the Software to anyone else.
#
# All rights reserved.

 * Ext JS Library 2.2
 * Copyright(c) 2006-2008, Ext JS, LLC.
 * licensing@extjs.com
 *
 * http://extjs.com/license
 */

// reference local blank image
Ext.BLANK_IMAGE_URL = '/cgi/extjs/resources/images/default/s.gif';


Ext.onReady
(
    function()
    {
        function updateDBsection()
        {
            var jsonData = "[";
            for( i=0; i < store.getCount(); i++ )
            {
                record = store.getAt(i);
                if(record.data.newRecord || record.dirty)
                {
                    jsonData += Ext.util.JSON.encode(record.data) + ",";
                }
            }
            if(jsonData.length > 1)
            {
                jsonData = jsonData.substring(0,jsonData.length-1) + "]";
            }else{
                jsonData = jsonData + "]";
            }


            Ext.Ajax.request(
            {
                waitMsg: 'Saving changes, please wait...',
                url:'/cgi/comments.plx',
                method: 'POST',

                params:{
                    data:jsonData,
                    Mode:'Save',
                    URL: location.href
                    },
                success:function(form, action)
                {
                    if (this.readyState == 4 && this.status != 200)
                    {
                      // fetched the wrong page or network error...
                        Ext.Msg.alert('Not Saved', 'Save operation failed.');
                    }
                    else
                    {
                        Ext.Msg.alert('Status',form.responseText);   
                        store.load();
                    }
                },
                failure:function(form, action)
                {
                    Ext.Msg.alert('Not Saved', 'Save operation failed.');
                }
            });
        };

        Ext.QuickTips.init();

        // shorthand alias
        var fm = Ext.form;

         // the column model has information about grid columns
        // dataIndex maps the column to the specific data field in
        // the data store (created below)
        var cm = new Ext.grid.ColumnModel([
            {
                id:'Name',
                header: "Name",
                dataIndex: 'Name',
                width: 150,
                tooltip: 'Click to Sort by Name',
                sortable: true,
                editor: new fm.TextField({
                    allowBlank: true
               })
            },{
                id:'Comment',
                header: "Comment",
                dataIndex: 'Comment',
                width: 450,
                tooltip: 'Click to Sort by Comment',
                sortable: true,
                editor: new fm.TextField({
                    allowBlank: false
               })
            },{
                id:'DateMade',
                header: "DateMade",
                dataIndex: 'DateMade',
                width: 170,
                hidden: false,
                sortable: true,
                tooltip: 'Click to Sort by Date Joined',
                editor: new fm.DateField({
                    allowBlank: true
               })
            },{
                id:'ID',
                header: "ID",
                dataIndex: 'ID',
                width: 10,
                hidden: true,
                sortable: true,
                editor: new fm.TextField({
                    allowBlank: true
                })
            }
        ]);


        // by default columns are sortable
        cm.defaultSortable = true;

        // this could be inline, but we want to define the Group record
        // type so we can add records dynamically
        var Group = Ext.data.Record.create([
               {name: 'Name', type: 'string'},
               {name: 'Comment', type: 'string'},
               // In Ext Docs, Date
               //{name: 'DateMade', type: 'date', dateFormat: 'Y-m-d H:m:s.u'},
               {name: 'DateMade', type: 'string'},
               {name: 'ID', type: 'string'},
          ], 'ID');
        // create the Data Store
        var store = new Ext.data.Store({

            // load using HTTP
            url:'/cgi/comments.plx',
            baseParams:{
                    URL: location.href
                    },
            
            // the return will be JSON, so lets set up a reader
            reader: new Ext.data.JsonReader({

                   // records will have a "Group" tag
                   root: "Group"                // The property which contains an Array of row objects
                   
               }, Group),

            sortInfo:{field:'DateMade', direction:'ASC'}
        });



        // create the editor grid
        var grid = new Ext.grid.EditorGridPanel
        (
            {
                //sm: smGrid,
                store: store,
                cm: cm,
                renderTo: 'comment',
                width: '100%',
                //height: 200,
                //maxHeight: 200,
                autoHeight: true,
                autoExpandColumn:'Comment',
                title:'Comments',
                frame:true,
                clicksToEdit:1,
                stripeRows: true,
                tbar:[{
                        id: 'save',
                        text: 'Post Comment',
                        tooltip:'Save all changes to the grid',
                        handler: updateDBsection,
                        iconCls: 'save'
                    },'-', {
                        id: 'add',
                        text: 'Add a Comment',
                        tooltip:'Add a blank row',
                        iconCls: 'add',
                        // Ext does not keep track of new records, we have to do so manually with newRecord
                        handler : function(){
                        var p = new Group
                        (
                            {
                                Name: 'Your name (optional)',
                                Comment: 'Your comment',
                                ID:'',
                                newRecord: true
                            }
                        );
                        
                        grid.stopEditing();
                        store.insert(0, p);
                        grid.startEditing(0, 0);
                        }
                    }
                ],
                viewConfig: {
                    emptyText:'No comments to display'
                }
            }
        );

        // trigger the data store load
        store.load();
       // alert (ID);

    }
);

