/*
 * Ext JS Library 3.0 RC1
 * Copyright(c) 2006-2009, Ext JS, LLC.
 * licensing@extjs.com
 *
 * http://extjs.com/license
 */
var intervalid = 0;
var intervalRate = 0;
var gridstore;

Ext.onReady(function(){

    //create the combo for refresh intervals
    new Ext.form.ComboBox({
        transform: 'refreshgridrate',
        typeAhead: true,
        triggerAction: 'all',
        width:135,
        editable: false,
        forceSelection:true,
        listeners: {
            'select' : function (cb, record) {
                intervalRate = parseInt(cb.getValue());
                if (intervalid!=0)  {
                    //cancel interval
                    clearInterval(intervalid);
                    intervalid = 0
                }

                if (intervalRate> 0) {
                    intervalRate = intervalRate * 60000;
                    intervalid = setInterval("gridstore.reload()",intervalRate);
                }
            }
        }
    });

    SearchBtn = new Ext.Button({
        text:     lang('search'),
        renderTo: 'ExtSearchBtn',
        type:     'submit',
        cls: 'x-box-text-small',
        width:    100,
        handler:  function(){
           gridstore.setBaseParam('eventtype', document.getElementById('eventtype').value);
           gridstore.setBaseParam('startdate', document.getElementById('startdate').value);
           gridstore.setBaseParam('enddate', document.getElementById('enddate').value);
           gridstore.load({params:{start:0}});
      }
    });

    var dh = Ext.DomHelper;
    var els=Ext.get(Ext.query("input.datefield"));
    els.each(function(el){
        var span = dh.insertBefore(el, {tag:"span"})
        var d = new Ext.form.DateField({
            el:            el.dom,
            hideLabel:     true,
            height:        "5px",
            selectOnFocus: true,
            format:        'm/d/Y'
        });
        d.render(span);
    });

    // create the combo instance
    var combo = new Ext.form.ComboBox({
        id:             'eventtype',
        name:           'eventtype',
        typeAhead:      false,
        editable:       false,
        triggerAction:  'all',
        transform:      'eventtype',
        forceSelection: true

    });

    Ext.QuickTips.init();
	gridstore = new Ext.data.JsonStore({
			id: "gridstore",
			root: 'data',
			totalProperty: 'totalcount',
			idProperty: 'entryid',
			remoteSort: true,
			fields: [
				'entryid','logdate','loguser','logmodifieduser', 'logaction','logipaddress','tpl'
			],

			// load using script tags for cross domain, if the data in on the same domain as
			// this page, an HttpProxy would be better
			proxy: new Ext.data.HttpProxy({
				url: 'index.php?fuse=home&action=GetEventList'
                //url: 'index.php?fuse=billing&action=GetInvoiceList'
			})
	});

        var gridbb = new Ext.PagingToolbar({
            id : 'eventgridpagingbar',
            pageSize: 15,
            store: gridstore,
            //displayInfo: true,
            //displayMsg: lang('Displaying tickets') +' {0} - {1}' + ' of ' + '{2}',
            emptyMsg: "",
            listeners:{
             'change': function(bb,data){
                    if(data.total == 0) { var addBy = 0;} else { var addBy = 1;}
                    from = (data.activePage * bb.pageSize) - bb.pageSize + addBy;
                    to = from+ bb.pageSize - 1;
                    if(to>data.total) to = data.total;
				
				document.getElementById('eventgridpagingbar').style.display = ( data.pages > 1 ) ? '' : 'none';

                    document.getElementById('eventlistlabel').innerHTML =  String.format(lang('Displaying events') +' {0} - {1}' + ' of ' + '{2}',from,to,data.total);
              }
            }
        });

        function renderLogAction(value,p,record){
            var returnString = record.data.logaction;
            if(record.data.tpl=="clickForBody"){
                //entryid
                returnString = String.format("{0} <a onclick=\"openWindow('index.php?fuse=clients&amp;view=HistoryFullEmail&amp;entryId={1}', 'email', 'scrollbars=yes,menubar=no,location=no,width=760,height=520,resizable=yes')\" href='#'>(view)</a>",
                                            record.data.logaction,record.data.entryid);
            }else if(record.data.tpl=="clickForFeedbackDetails"){
                returnString = String.format("{0} <a onclick=\"openWindow('index.php?fuse=support&view=HistoryShowComments&entryId={1}', 'email', 'scrollbars=yes,menubar=no,location=no,width=760,height=520,resizable=yes')\" href='#'>(view)</a>",
                                            record.data.logaction,record.data.entryid);
            }else if(record.data.tpl=="clickForStaffNote"){
                returnString = String.format("{0} <a onclick=\"openWindow('index.php?fuse=clients&amp;view=EventLogStaffNote&amp;entryId={1}', 'email', 'scrollbars=yes,menubar=no,location=no,width=760,height=520,resizable=yes')\" href='#'>(view)</a>",
                                            record.data.logaction,record.data.entryid);
            }else if(record.data.tpl=="clickForProfileDetails"){
                returnString = String.format("{0} <a onclick=\"openWindow('index.php?fuse=clients&amp;view=HistoryOriginalProfile&amp;entryId={1}', 'email', 'scrollbars=yes,menubar=no,location=no,width=760,height=520,resizable=yes')\" href='#'>(view)</a>",
                                            record.data.logaction,record.data.entryid);
            }else if(record.data.tpl=="clickForPaypalCallbackDetails"){
                returnString = String.format("{0} <a onclick=\"openWindow('index.php?fuse=billing&amp;view=ViewPaypalCallbackDetails&amp;entryId={1}', 'email', 'scrollbars=yes,menubar=no,location=no,width=760,height=520,resizable=yes')\" href='#'>(view)</a>",
                                            record.data.logaction,record.data.entryid);
            }else if(record.data.tpl=="clickForPackageDetails"){
                returnString = String.format("{0} <a onclick=\"openWindow('index.php?fuse=clients&view=HistoryOriginalPackage&entryId={1}', 'email', 'scrollbars=yes,menubar=no,location=no,width=760,height=520,resizable=yes')\" href='#'>(view)</a>",
                                            record.data.logaction,record.data.entryid);
            }
            return returnString;
        }


    var grid = new Ext.grid.GridPanel({
        el:'event-grid',
	autoHeight:true,
        store: gridstore,
        trackMouseOver:true,
        disableSelection:true,
        loadMask: true,

        // grid columns
        columns:[{
            id: 'logdate', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: "Date",
            width: 100,
			dataIndex : "logdate",
            sortable: true,
			align:"left"
        },{
            id: 'loguser', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: "User",
            width: 100,
			dataIndex : "loguser",
            sortable: true
        },{
			id: 'logmodifieduser',
            header: "Modified User",
			dataIndex : "logmodifieduser",
            width: 100,
            sortable: true
        },{
			id: 'logaction',
            header: "Action",
			dataIndex : "logaction",
                        renderer: renderLogAction,
            width: 250,
            sortable: true,
			align:"left"
        },{
            id: 'logipaddress', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
            header: "IP Address",
            width: 70,
            dataIndex : "logipaddress",
            align:"center",
            sortable: true
        }],
		stripeRows: true,
        // customize view config
        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            emptyText: lang("There are currently no events to view"),
            scrollOffset:1

        },
        // paging bar on the bottom
        bbar: gridbb


    });

    // render it
    grid.render();
    // trigger the data store load\
    gridstore.setBaseParam('eventtype','all');
    gridstore.setBaseParam('startdate', startDateValue);
    gridstore.setBaseParam('enddate', endDateValue);
    gridstore.load({params:{start:0 , limit:15}});
    /*gridstore.on('load',function(){
        
    });*/
   
});