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

pendingorders = {};
pendingorders.ViewPendingOrdersInvoked = false;

pendingorders.ViewPendingOrders = function(){
    // Prevent this from being called twice
    if(document.getElementById('pendingitems') == null || pendingorders.ViewPendingOrdersInvoked){
        return;
    }
    
    pendingorders.gridstore = new Ext.data.JsonStore({
        id:             "ordersgridstore",
        root:           'data',
        totalProperty:  'totalcount',
        idProperty:     'pendingpackageid',
        remoteSort:     true,
        fields:         [
            'pendingcustomerurl',
            'pendingpackageid',
            'pendingpackagereference',
            'pendingpackagedate',
            'pendingpackagetype',
            'pendingpackagename',
            'packagepaidstatus',
            'pendingpackagecustomername',
            'pendingpackageuserid',
			'pendingpackagetypeid'
        ],
        proxy:          new Ext.data.HttpProxy({
            url:  'index.php?fuse=clients&action=getPendingOrdersList'
        })
    });
    
    pendingorders.sm = new Ext.grid.CheckboxSelectionModel({
        id:         'po-sm',
        width:      30,
        listeners:  {
            'rowdeselect':    function(model, rowIndex, record){
                pendingorders.toggleButtons();
            },
            'rowselect':      function(model, rowIndex, record){
                pendingorders.toggleButtons();
            }
        }
    });
    
    pendingorders.renderPackageUrl = function(value, p, record){
        return String.format('<a href="{0}" style="font-size:9px;">{1}</a>', record.data.pendingcustomerurl, record.data.pendingpackagereference);
    }

    pendingorders.renderCustomerName = function(value,p,record){
        return String.format('<a href="index.php?fuse=clients&view=Admin_Profile_Contact&frmClientID={0}" style="font-size:9px;">{1}</a>', record.data.pendingpackageuserid, record.data.pendingpackagecustomername);
    }
    
    pendingorders.renderDateUrl = function(value,p,record){
        return String.format('<a href="{0}" style="font-size:9px;">{1}</a>', record.data.pendingcustomerurl, record.data.pendingpackagedate);
    }
    pendingorders.renderPackageType = function(value,p,record){
        return String.format('<a href="{0}" style="font-size:9px;">{1}</a>', record.data.pendingcustomerurl, record.data.pendingpackagetype);
    }
    pendingorders.renderPackageName = function(value,p,record){
        return String.format('<a href="{0}&packageid={2}" style="font-size:9px;">{1}</a>', record.data.pendingcustomerurl, record.data.pendingpackagename, record.data.pendingpackageid);
    }
    pendingorders.renderPackageStatus = function(value,p,record){
        return String.format('<a href="{0}" style="font-size:9px;">{1}</a>', record.data.pendingcustomerurl, record.data.packagepaidstatus);
    }
    
    pendingorders.grid = new Ext.grid.GridPanel({
        el:               'pendingitems',
        autoHeight:       true,
        store:            pendingorders.gridstore,
        trackMouseOver:   true,
        disableSelection: true,
        loadMask:         true,
        
        
        // grid columns
        columns:          [
            pendingorders.sm,
            {
                id:         'package',
                header:     "Pkg",
                width:      150,
                renderer:   pendingorders.renderPackageUrl,
                hidden:     true,
                dataIndex:  "pendingpackagereference"
            },
            {
                id:         'customername',
                header:     "Name",
                width:      150,
                renderer:   pendingorders.renderCustomerName,
                hidden:     false,
                dataIndex:  "pendingpackagecustomername"
            }
            ,
            {
                id:         'date',
                header:     "Date",
                width:      170,
                renderer:   pendingorders.renderDateUrl,
                dataIndex:  "pendingpackagedate",
                hidden: true,
                align:      "center"
            },
            {
                id:         'type',
                header:     "Type",
                width:      150,
                hidden:     true,
                renderer:   pendingorders.renderPackageType,
                dataIndex:  "pendingpackagetype",
                align:      "center"
            },
            {
                id:         'name',
                header:     "Pkg Name",
                width:      150,
                dataIndex:  "pendingpackagename",
                renderer:   pendingorders.renderPackageName,
                align:      "center"
            },
            {
                id:         'status',
                header:     "Status",
                dataIndex:  "packagepaidstatus",
                renderer:   pendingorders.renderPackageStatus,
                width:      130,
                align:      "center"
                //sortable:   true
            }
        ],
        stripeRows:       true,
        // customize view config
        viewConfig:       {
            forceFit:       true,
            enableRowBody:  true,
            emptyText:         lang("There are currently no oustanding orders"),
            scrollOffset:   1
        },
        sm:               pendingorders.sm,
        buttons:          [
            pendingorders.activatebutton = new Ext.Button({
                id:         'activateorderbutton',
                autoHeight: true,
                arrowAlign: 'right',
                xtype:      'splitbutton',
                text:       "&nbsp;&nbsp;"+lang('Activate')+ "&nbsp;&nbsp;",
                disabled:   true
            }),
            pendingorders.deletebutton = new Ext.Button({
                id:         'deleteorderbutton',
                autoHeight: true,
                arrowAlign: 'right',
                xtype:      'splitbutton',
                text:       "&nbsp;&nbsp;"+lang('Delete')+ "&nbsp;&nbsp;",
                disabled:   true
            })
        ],
        buttonAlign:      'left'
    });
    
    pendingorders.GetSelectedRowIds = function(){
        var arrayofids = new Array();
        rows = pendingorders.sm.getSelections();
        for(x = 0; x < rows.length; x++){
           arrayofids[x] = rows[x].data.pendingpackageid;
        }
        return arrayofids;
    }
    
   pendingorders.btnButtonActionHandler = function(button, event){
        pendingorders.grid.disable();
        
        var usepackageplugin = 0;
        var useregistrarplugin = 0;
        var usedeletecustomer = 0;
        
        switch(button.id){
            case "activateorderbutton":
                requesturl = "index.php?fuse=clients&action=ActivateClientPackages";
				
				var isDomainPresent = false
				rows = pendingorders.sm.getSelections();
				for ( x = 0; x < rows.length; x++ ) {
					if ( rows[x].data.pendingpackagetypeid == 3 ) {
						isDomainPresent = true;
						break;
					}
				}

				if ( isDomainPresent == false ) {
					var msg = lang("Do you want to activate these packages using their respective plugins?");
				} else {
					var msg = lang("Do you want to activate these packages using their respective plugins (Warning: this will also register any domains)?");
				}

				// Ask about server plugin
				Ext.Msg.show({
					title:    "Use server plugins?",
					msg:      msg,
					buttons:  Ext.Msg.YESNOCANCEL,
					fn: function(btn, text){
						if(btn == 'yes'){
							usepackageplugin = 1;
							useregistrarplugin = 1;
						}else if(btn == 'cancel'){
							pendingorders.grid.enable();
							pendingitems.hideMask();
							return;
						}
						pendingorders.callAjax(usepackageplugin, useregistrarplugin, usedeletecustomer);
					},
					icon:     Ext.MessageBox.WARNING
				});
                break;
            case "deleteorderbutton":
                requesturl = "index.php?fuse=clients&action=DeleteClientPackages";
				// Confirm they want to delete
				Ext.Msg.show({
					title:    "Delete package(s)?",
					msg:      lang("Are you sure you want to delete these package(s)?"),
					buttons:  Ext.Msg.YESNOCANCEL,
					fn: function(btn, text){
						if(btn == 'cancel' || btn == 'no'){
							pendingorders.grid.enable();
							pendingitems.hideMask();
							return;
						}
						// Do we delete the customer if they have no other packages?
						Ext.Msg.show({
							title:    "Delete customer?",
							msg:      lang("Do you want to delete the customers of the selected packages if they don't have more packages?"),
							buttons:  Ext.Msg.YESNOCANCEL,
							fn: function(btn, text){
								if(btn == 'yes'){
									usedeletecustomer = 1;
								}else if(btn == 'cancel'){
									pendingorders.grid.enable();
									pendingitems.hideMask();
									return;
								}
								pendingorders.callAjax(usepackageplugin, useregistrarplugin, usedeletecustomer);
							},
							icon:     Ext.MessageBox.WARNING
						});
					},
					icon:     Ext.MessageBox.WARNING
				});
                break;
        }
        return true;
    }
	
	
	pendingorders.callAjax = function(usepackageplugin, useregistrarplugin, usedeletecustomer ) {
		pendingitems.showMask();
        Ext.Ajax.request({
            url:      requesturl,
            success:  function(xhr){
                pendingitems.hideMask();
                pendingorders.toggleButtons(0);
                pendingorders.grid.enable();
                pendingorders.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("The action has been performed"));
                }
            },
            failure:  function(){
                pendingitems.hideMask();
                pendingorders.grid.enable();
            },
            params:   {
                domainids:          Ext.util.JSON.encode(pendingorders.GetSelectedRowIds()),
                usepackageplugin:   usepackageplugin,
                useregistrarplugin: useregistrarplugin,
                usedeletecustomer:  usedeletecustomer
            }
        });
	}

    
    // option button code
    pendingorders.toggleButtons = function(count){
        if(count == undefined){
            count = pendingorders.sm.getCount();
        }
        
        if(count > 0){
            pendingorders.activatebutton.setDisabled(false);
            pendingorders.deletebutton.setDisabled(false);
        }else{
            pendingorders.activatebutton.setDisabled(true);
            pendingorders.deletebutton.setDisabled(true);
        }
    }
    
    pendingorders.addButtonListeners = function(){
        pendingorders.activatebutton.addListener("click",pendingorders.btnButtonActionHandler);
        pendingorders.deletebutton.addListener("click",pendingorders.btnButtonActionHandler);
    }
    
    pendingorders.addButtonListeners();
    // render it
    pendingorders.grid.render();
    // trigger the data store load
    pendingorders.gridstore.load({params:{start:0, limit:0}});
    pendingorders.ViewPendingOrdersInvoked = true;
}