/*
 * Ext JS Library 3.0 RC1
 * Copyright(c) 2006-2009, Ext JS, LLC.
 * licensing@extjs.com
 *
 * http://extjs.com/license
 */

Ext.onReady(function(){

    Ext.QuickTips.init();
    gridstore = new Ext.data.JsonStore({
        id: "gridstore",
                    root: 'data',
                    totalProperty: 'totalcount',
        idProperty: 'domainid',
                    remoteSort: true,
                    fields: [
                            'domainid','domainname','customer','expirydate','registrar', 'status', 'customerid', 'autorenew', 'period'
                    ],

                    // 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=domains&action=GetDomainsList'
                    })
    });
    gridstore.setDefaultSort('domainid', 'asc');

    var sm = new Ext.grid.CheckboxSelectionModel({
        listeners:{
             'rowdeselect': function(model, rowIndex, record){
                    toggleButtons();
              },
              'rowselect': function(model, rowIndex, record){
                    toggleButtons();
              }
        }
    });
    function toggleButtons(){
        var count = sm.getCount();
        if(count > 0){
            deletebutton.setDisabled(false);
            reminderbutton.setDisabled(false);
        }else{
            deletebutton.setDisabled(true);
            reminderbutton.setDisabled(true);
        }
    }
    function getDomainItems(){
        var domainItems = "";
        rows = sm.getSelections();
	    //var i = 0;
        for(x=0;x<rows.length;x++){
            var commavar = ",";
            if(x !=0){
               domainItems += commavar;
            }
            domainItems += rows[x].data.domainid;
          //  i++;
        }
        return domainItems;
    }

    // Function to put together the link for the open window
    function renderCustomerName(value,p,record){
        var link = "<a href='index.php?fuse=clients&view=Admin_Profile_Contact&frmClientID=" + record.data.customerid + "'>" + record.data.customer + "</a>";
        return link;
    }

    // Function to put together the link for the open window
    function renderDomainName(value,p,record){
        var link = "<a href='javascript:editDomain(" + record.data.domainid + ", 1);'>" + record.data.domainname + "</a>";
        return link;
    }

    var paginationbar = new Ext.PagingToolbar({
            id:'domaingridpagingbar',
            pageSize: 25,
            store: gridstore,
            height : 30,
            //displayInfo: true,
            //displayMsg: 'Displaying domains {0} - {1} of {2}                      a',
            //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;

				$('domaingridpagingbar').style.display = ( data.pages > 1 ) ? '' : 'none';
				$('domainlistlabel').innerHTML = String.format(lang('Displaying domains') +' {0} - {1}' + ' of ' + '{2}',from,to,data.total);
          }
        }

        });
    
    var grid = new Ext.grid.GridPanel({
        el:'domains-grid',
        autoHeight:true,
        title:'',
        store: gridstore,
        trackMouseOver:true,
        disableSelection:true,
        loadMask: true,
        buttonAlign:'left',
        // grid columns
        columns:[
            sm,
        {
            id: 'domainsid',
            header: lang("Domains Id"),
            hidden : true,
            width: 50,
			dataIndex : "domainid",
            align:"left"
        },{
            id: 'domainname',
            header: lang("Domain Name"),
            width: 150,
			dataIndex : "domainname",
			renderer: renderDomainName
        },{
			id: 'customer',
            header: lang("Customer"),
			dataIndex : "customer",
			renderer: renderCustomerName,
            width: 120
        },{
			id: 'period',
            header: lang("Period"),
			dataIndex : "period",
                        hidden:true,
            width: 70
        },{
			id: 'expirydate',
            header: lang("Expiration Date"),
			dataIndex : "expirydate",
            width: 70
        },{
			id: 'autorenew',
            header: lang("Auto Renew"),
			dataIndex : "autorenew",
                        hidden:true,
            width: 42
        },{
			id: 'status',
            header: lang("Status"),
			dataIndex : "status",
            width: 70
        },{
			id: 'registrar',
            header: lang("Registrar"),
			dataIndex : "registrar",
            width: 70
        }],
        sm: sm
		,stripeRows: true,
        // customize view config
        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            emptyText: lang("There are no domains available to view at this time"),
            scrollOffset:1
        },
        buttons:[ deletebutton = new Ext.Button({
                     id:'deletebutton',
                     autoHeight:true,
                     arrowAlign:'right',
                     xtype:'splitbutton',
                     text:'Delete Domain',
                     disabled: true

                 }),
                 reminderbutton = new Ext.Button({
                     id:'reminderbutton',
                     autoHeight:true,
                     arrowAlign:'right',
                     xtype:'splitbutton',
                     text:'Send Reminder',
                     disabled: true

                 })],
        //buttons:[validatebutton],
        // paging bar on the bottom
        bbar: paginationbar
    });
    var storeItem = Ext.data.Record.create([{name:'myId',type:'string'},{name:'displayText',type:'string'}]);
    var domainsfiltercombo = new Ext.form.ComboBox({
        triggerAction: 'all',
        lazyRender:true,
        editable:false,
        value:'All Domains',
        mode: 'local',
        store: new Ext.data.ArrayStore({
            idIndex: 0,
            fields: [
                'myId',
                'displayText',
                'type',
                'private'
            ]
        }),
        valueField: 'myId',
        width: 220,
        displayField: 'displayText',
        applyTo: 'domainsfilter',
        // all of your config options
        listeners:{
             'select': function(cb,record){

                FilterGrid(record.data.myId);
             }
        }

    });
   
    var btnButtonActionHandler = function(button, event){
        requesturl = "index.php?fuse=domains&action=ActOnDomainList";
	    if(button.id == "deletebutton"){
            confirmmsg = "Click OK if you are sure you want to delete the selected items.";
            var deleteItems = confirm(confirmmsg);
            if(deleteItems == false){
               return false;
            }
        }

        Ext.Ajax.request({
           url: requesturl,
           success: function(xhr) {
                        //refreshgrid
                        grid.enable()
                        gridstore.load({params:{start:0}});
                        var data = Ext.util.JSON.decode(xhr.responseText);
                        if(data.error){
                            //we do not need to repopulate the filters if there was a validation error
                           msg(lang("There was an error performing this action"),"");
                        }else if(data.message){
                            msg(data.message,"");
                        }else{
                            msg(lang("Ticket(s) have been updated"),"");
                        }
                    },
           failure: function() {
                grid.enable()
                Ext.Msg.alert("Fail");
           },
           params: { items: Ext.util.JSON.encode(getDomainItems()),
                     actionbutton: Ext.util.JSON.encode(button.id)
                     

           }
        });
	}
    function addButtonListeners(){
        reminderbutton.addListener("click",btnButtonActionHandler);
        deletebutton.addListener("click",btnButtonActionHandler);
    }
    addButtonListeners();

    grid.render();

    // trigger the data store load
    gridstore.load({params:{start:0 , limit:25}});
    function FilterGrid(filter){
        //these are set in the viewusers.tpl
	    //if(customerid!=null) gridstore.setBaseParam('customerid', customerid);
        if(filter!=null) gridstore.setBaseParam('domainsfilter', filter);

        gridstore.load({params:{start:0,limit:15}});
    }

    function updateButtonsWithContent(data){

        if(data.type == "filter"
           )
        {
            if(data.private == undefined){
                data.private = 0;
            }

            var comboitem = new storeItem({myId:data.id,displayText:data.name,type:data.type, private:data.private});
            domainsfiltercombo.getStore().insert(
                domainsfiltercombo.getStore().getCount(),
                comboitem
            );
        }

    }

    function PopulateDomainsFilters(){
        Ext.Ajax.request({
           url: 'index.php?fuse=domains&action=GetDomainsFilters',
           success: function(xhr) {
               
                        //clear the items from our combobox
                        domainsfiltercombo.getStore().removeAll();
                        //go through our options and add to the UI
                        var data = Ext.util.JSON.decode(xhr.responseText);
                        //data.options.forEach(updateButtonsWithContent);
                        for ( var i in data.options )
                        {
                            updateButtonsWithContent( data.options[i] );
                        }

                    },
           failure: function() {
                Ext.Msg.alert("Fail");
           },
           params: { foo: 'bar' }
        });
    }

 new Ext.form.ComboBox({
        tpl: '<tpl for="."><div ext:qtip="Display {displayText} items" class="x-combo-list-item">{displayText}</div></tpl>',
        triggerAction: 'all',
        lazyRender:true,
        editable:false,
        value: paginationbar.pageSize,
        mode: 'local',
        store: new Ext.data.ArrayStore({
            id: 0,
            fields: [
                'myId',
                'displayText'
            ],
            data: [[10, '10'], [25, '25'] ,[50, '50'], [150,'150'],[300,'300']]
        }),
        valueField: 'myId',
        width: 50,
        displayField: 'displayText',
        applyTo: 'local-states-with-qtip',
        // all of your config options
        listeners:{
             'select': function(cb,record){
                gridstore.setBaseParam('limit', record.data.myId);
                paginationbar.pageSize = record.data.myId;
                gridstore.load({params:{start:0}});
             }
        }
    });

    PopulateDomainsFilters();
});