/*
 * 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();

    /*new Ext.Button({
        id:"addpackage",
        renderTo:"addpackagebutton",
        text: lang('Add Package'),
        iconAlign: 'left',
        handler:function(){
            window.location = 'index.php?fuse=clients&view=AddDomain';
             //ShowEditBillingTypeWindow(0);
        }
    })*/

    var gridstore = new Ext.data.JsonStore({
        id: "gridstore",
        root: 'data',
        totalProperty: 'totalcount',
        idProperty: 'domainid',
        remoteSort: true,
        fields: ['domainid','domainname','nextbilldate','packagetype','package','registrar','status','expirydate'],
        // 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=Admin_GetDomainList'
        })
    });
    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);

        }else{
            deletebutton.setDisabled(true);

        }
    }
    function getDomainItems(){
        var domainItems = "";
        rows = sm.getSelections();
        for(x=0;x<rows.length;x++){
            var commavar = " ";
            if(x !=0){
               domainItems += commavar;
            }
            domainItems += rows[x].data.domainid;
        }
        return domainItems;
    }

    function renderName(value,p,record){
        //name = "<span class='invoicelink'><a href='index.php?fuse=clients&view=Admin_Profile_Packages&selectedDomain="+record.data.domainid+"' qtip='"+ lang('View Package Details') +"'>" + record.data.domainname + "</a></span>"
        name = "<span class='invoicelink'><a href='javascript:ClientExec.AddDomain.ShowAddDomainWindow(" + record.data.domainid+ ");' qtip='"+ lang('View Package Details') +"'>" + record.data.domainname + "</a></span>"
        return name;
    }

    function renderType(value,p,record){
        type = "";
        if(record.data.registrar == ""){
            type = record.data.package+" / "+record.data.packagetype;
        }else{
            type = record.data.registrar;
        }
        return type;
    }

   // var nextBillDate =

    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,
			dataIndex : "domainsid",
            align:"left"
        },{
            id: 'domainname',
            header: lang("Domain Name"),
            renderer:renderName
        },{
			id: 'nextbilldate',
            header: lang("Next Bill Date"),
			dataIndex : "nextbilldate"
            //width: 90
        },{
			id: 'type',
            header: lang("Type"),
			renderer:renderType
            //width: 80
        },{
			id: 'status',
            header: lang("Status"),
			dataIndex : "status",
            width: 120
        }
        ],
        sm: sm
		,stripeRows: true,
        // customize view config
        viewConfig: {
            forceFit:true,
            enableRowBody:true,
            emptyText: lang("There are no products available to view at this time"),
            scrollOffset:1
        },
        buttonAlign: 'left',
        buttons:[ deletebutton = new Ext.Button({
                     id:'deletebutton',
                     autoHeight:true,
                     arrowAlign:'right',
                     xtype:'splitbutton',
                     text:lang('Delete'),
                     disabled: true

                 })
                 ],
        // paging bar on the bottom
        bbar: new Ext.PagingToolbar({
            id :"domaingridpagingbar",
            pageSize: 5,
            store: gridstore,
            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 products') +' {0} - {1}' + ' of ' + '{2}',from,to,data.total);
                }
            },
            emptyMsg: ""

        })





    });
    var storeItem = Ext.data.Record.create([{name:'myId',type:'string'},{name:'displayText',type:'string'}]);
    var statusfiltercombo = 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,
        hidden:true,
        displayField: 'displayText',
        applyTo: 'statusfilter',
        // all of your config options
        listeners:{
             'select': function(cb,record){
                statusFilterGrid(record.data.myId);
             }
        }

    });
    statusfiltercombo.wrap.addClass("x-form-field-float-left");

    var domainsfiltercombo = new Ext.form.ComboBox({
        triggerAction: 'all',
        lazyRender:true,
        editable:false,
        value:'All',
        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){
                domainsFilterGrid(record.data.myId);
             }
        }

    });
    domainsfiltercombo.wrap.addClass("x-form-field-float-left");

    var btnButtonActionHandler = function(button, event){
        if(domainsfiltercombo.value == "domains"){
            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,domainsfilter:"domains"}});
                            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)


               }
            });
        }else {
            requesturl = "index.php?fuse=clients&action=DeleteDomain";
            if(button.id == "deletebutton"){
                confirmmsg = "Click OK if you are sure you want to delete the selected items.";
                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())



               }
            });
        }
    }

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

    grid.render();

    gridstore.setBaseParam('limit', 10);
    // trigger the data store load
    gridstore.load({params:{start:0 , limit:10}});
    function domainsFilterGrid(filter){
        var statuslabel = document.getElementById("statuslabel");
        var data = gridstore.reader.jsonData;
        var cm = grid.getColumnModel();
        if(filter == "domains"){
            statuslabel.style.display = "block";
            statusfiltercombo.show();
        }else{
            statuslabel.style.display = "none";
            statusfiltercombo.hide();
        }
        if(filter!=null) gridstore.setBaseParam('domainsfilter', filter);
        gridstore.load({params:{start:0,limit:15}});
    }

    function statusFilterGrid(filter){
        if(filter!=null) gridstore.setBaseParam('statusfilter', filter);
        gridstore.load({params:{start:0,limit:15}});
    }

    function updateButtonsWithContent(data){
        if(data.type == "status"){
            if(data.private == undefined){
                data.private = 0;
            }
            var comboitem = new storeItem({myId:data.id,displayText:data.name,type:data.type, private:data.private});
            statusfiltercombo.getStore().insert(
                statusfiltercombo.getStore().getCount(),
                comboitem
            );
        }
        if(data.type == "domains"){
            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=clients&action=Admin_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' }
        });
    }
    PopulateDomainsFilters();
});
