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

Ext.onReady(function(){

    gridstore = new Ext.data.JsonStore({
        id: "gridstore",
        root: 'results',
        totalProperty: 'totalcount',
        idProperty: 'id',
        remoteSort: true,
        fields: [
                'id','domainname','customer','renewal','registrar', 'domain_status', 'customerid', 'autorenew', 'period', 'cycle_issue', 'expires'
        ],
        sortInfo: { field: "renewal", direction: "ASC" },
        // 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=clients&action=adminGetUserPackages&filter=3_all&domainsfilter=1'
        })
    });

    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.id;
          //  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 = '';
        if  ( record.data.cycle_issue == true ) { 
            link = "<a href='index.php?fuse=clients&view=Admin_Profile_Products&frmClientID=" + record.data.customerid + "&packageid=" +record.data.id + "'>"+record.data.domainname+"</a> <a href='index.php?fuse=clients&view=Admin_Profile_Products&frmClientID=" + record.data.customerid + "&packageid=" +record.data.id + "&tab=billing'><img style='padding-left:2px;margin-bottom:-3px;' qtip='" + lang('Invalid payment term for domain') + "' src='../templates/admin/images/icon_alert.gif' /></a>";
        } else {
            link = "<a href='index.php?fuse=clients&view=Admin_Profile_Products&frmClientID=" + record.data.customerid + "&packageid=" +record.data.id + "'>"+record.data.domainname+"</a>";
        }
        return link;
    }

    var paginationbar = new Ext.PagingToolbar({
        id:'domaingridpagingbar',
        store: gridstore,
        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('domaingridpagingbar').style.display = ( data.pages > 1 ) ? '' : 'none';
            document.getElementById('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,
        // grid columns
        columns:[
        sm,
        {
            id: 'domainsid',
            header: lang("Domains Id"),
            hidden : true,
            width: 50,
            sortable: false,
            dataIndex : "id",
            align:"left"
        },{
            id: 'domainname',
            header: lang("Domain Name"),
            width: 150,
            sortable: true,
            dataIndex : "domainname",
            renderer: renderDomainName
        },{
            id: 'customer',
            header: lang("Customer"),
            dataIndex : "customer",
            sortable: false,
            renderer: renderCustomerName,
            width: 120
        },{
            id: 'period',
            header: lang("Period"),
            dataIndex : "period",
            sortable: false,
            hidden:true,
            width: 70
        },{
            id: 'expirydate',
            header: lang("Expiration Date"),
            dataIndex : "expires",
            sortable: true,
            width: 70
        },{
            id: 'autorenew',
            header: lang("Auto Renew"),
            dataIndex : "autorenew",
            sortable: false,
            hidden:true,
            width: 42
        }/*,{
            id: 'status',
            header: lang("Status"),
            dataIndex : "domain_status",
            sortable: false,
            width: 70
        }*/,{
            id: 'registrar',
            header: lang("Registrar"),
            dataIndex : "registrar",
            sortable: false,
            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
        },
        // paging bar on the bottom
        bbar: paginationbar,
        buttonAlign:'left',
        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
                 })]
    });

    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:'Active 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){
        if ( button.id == "deletebutton" ) {
            Ext.Msg.show({
                title:    "Delete Domain(s)?",
                msg:      lang('Are you sure you want to delete the selected domains?'),
                buttons:  Ext.Msg.YESNOCANCEL,
                fn: function(btn, text){
                    if (btn == 'no' || btn == 'cancel') {
                        return false;
                    }
                    callAjaxRequest(button);
                },
                icon:     Ext.MessageBox.WARNING
            });
        } else {
            callAjaxRequest(button);
        }
    };


    function callAjaxRequest(button) {
        Ext.Ajax.request({
            url: "index.php?fuse=domains&action=ActOnDomainList",
            success: function(xhr) {
                grid.enable();
                gridstore.load({params:{start:0}});
                var data = Ext.util.JSON.decode(xhr.responseText);
                if (data.message){
                    msg(data.message);
                }  else if (data.error) {
                    msg(lang("There was an error performing this action"));
                }
            },
            failure: function() {
                grid.enable()
                Ext.Msg.alert('There was an issue performing this request');
            },
            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();
    paginationbar.pageSize = 10;

    // trigger the data store load
    gridstore.setBaseParam('limit', 10);
    gridstore.load({params:{start:0}});
    
    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() {
           },
           params: { foo: 'bar' }
        });
    }

 new Ext.form.ComboBox({
        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();
});