var today = new Date();
var promoteApp = function(){
    var stores = {
        available_slots: new Ext.data.JsonStore({
            url: '/promo/available_slots',
            method: 'POST',
            autoLoad: false
        })
    };
    
    var forms = {
        available_slots: new Ext.form.FormPanel({
            id: 'available_slots_form',
            title: 'Available promoted profile spaces',
            iconCls: 'btn-search',
            style: 'margin-bottom:10px',
            labelAlign: 'top',
            layout: 'column',
            width: 650,
            frame: true,
            defaults: {
                msgTarget: 'side'
            },
            items: [{
                columnWidth: '.3',
                layout: 'form',
                items: [{
                    xtype: 'datefield',
                    fieldLabel: 'Advertisement Start Day',
                    format: 'Y-m-d',
                    minValue: today,
                    maxValue: new Date(currentTime.setMonth(currentTime.getMonth() + 3)),
                    value: today,
                    name: 'showdate',
                    listeners: {
                        valid: function(){
                            var grid = Ext.getCmp('available_slots_grid');
                            grid.getStore().load({
                                params: Ext.getCmp('available_slots_form').form.getValues()
                            });
                        }
                    }
                }]
            }, {
                columnWidth: '.3',
                layout: 'form',
                items: [{
                    labelWidth: 300,
                    xtype: 'combo',
                    fieldLabel: 'Advertisement Start Time ( CST )',
                    hiddenName: 'timeframe',
                    displayField: 'display',
                    valueField: 'value',
                    valueField: 'value',
                    triggerAction: 'all',
                    mode: 'local',
                    selectOnFocus: true,
                    editable: false,
                    store: new Ext.data.SimpleStore({
                        fields: ['value', 'display'],
                        data: [[1, '8am - 12pm'], [2, '12pm - 4pm'], [3, '4pm - 8pm'], [4, '8pm - 12am'], [5, '12am - 8am']]
                    }),
                    listeners: {
                        select: function(a){
                            var grid = Ext.getCmp('available_slots_grid');
                            grid.getStore().load({
                                params: Ext.getCmp('available_slots_form').form.getValues()
                            });
                        }
                    }
                }]
            }, {
                columnWidth: '.3',
                items: [{
                    ctCls: 'promote-button-container',
                    xtype: 'button',
                    iconCls: 'btn-search',
                    text: 'Check Availability',
                    handler: function(){
                        var grid = Ext.getCmp('available_slots_grid');
                        grid.getStore().load({
                            params: Ext.getCmp('available_slots_form').form.getValues()
                        });
                    }
                }]
            }]
        })
    };
    
    var csm = new Ext.grid.CheckboxSelectionModel();
    var csm2 = new Ext.grid.CheckboxSelectionModel();
	
    var grids = {
        available_slots: {
            iconCls: 'btn-date',
            title: 'Available Spaces',
            id: 'available_slots_grid',
            xtype: 'grid',
            stripeRows: true,
            frames: true,
            loadMask: true,
            frame: true,
            width: 310,
            height: 330,
            viewConfig: {
                forceFit: true,
                deferEmptyText: false,
                emptyText: 'We\'re sorry, there are no available promoted profile spaces matching your criteria.'
            },
            sm: csm,
            autoExpandColumn: 'available_slots_grid_aec',
            cm: new Ext.grid.ColumnModel([csm, {
                id: 'purchase_slots_grid_aec',
                header: "Date",
                dataIndex: 'showdate',
                renderer: function(a, b, c){
                    return a;
                }
            }, {
                header: "Time Slot",
                dataIndex: 'timeslot',
                renderer: function(a, b, c){
                    var display = a > 12 ? a - 12 : a;
                    
                    if (a === 0) {
                        return '12:00 AM CST';
                    }
                    return display + ':00' + ((a >= 12) ? 'PM' : 'AM') + ' CST';
                }
            }, {
                header: "Available?",
                dataIndex: 'slotsavailable',
                renderer: function(a){
                    return a >= 1 ? '<font color="green">Yes</font>' : '<font color="red">No</font>';
                }
            }]),
            ds: stores.available_slots,
            bbar: [{
                iconCls: 'btn-cart-add',
                text: 'Add',
                handler: function(){
                	var selected = Ext.getCmp('available_slots_grid').getSelectionModel().getSelections();
					var store = Ext.getCmp('purchase_slots_grid').getStore();
					
					if(!selected.length) return false;
					
					for(var n=0;n<selected.length;n++) {
						var sr = selected[n];
						
						var ok = store.findBy(function(record){
							if(record.get('showdate')==sr.get('showdate')) {
								if(record.get('timeslot')==sr.get('timeslot')) {
									return true;
								}
							} 
						});
						
						Ext.each(ok,function(i) {
							if(i<0) store.add(sr);
						});					
					}
                }
            }]
        },
        purchase_slots: {
            iconCls: 'btn-cart',
            title: 'Shopping Cart',
            xtype: 'grid',
            id: 'purchase_slots_grid',
            xtype: 'grid',
            stripeRows: true,
            frames: true,
            loadMask: true,
            frame: true,
            width: 310,
            height: 330,
            viewConfig: {
                forceFit: true,
                deferEmptyText: false,
                emptyText: 'You have not added any items to your cart.  Select an available space from the box on the left.'
            },
            sm: csm2,
            autoExpandColumn: 'purchase_slots_grid_aec',
            cm: new Ext.grid.ColumnModel([
			csm2,
			{
                id: 'purchase_slots_grid_aec',
                header: "Date",
                dataIndex: 'showdate'
            }, {
                header: "Time Slot",
                dataIndex: 'timeslot',
                renderer: function(a, b, c){
                    if (a === 0) {
                        return '12:00 AM CST';
                    }
                    return a + ':00' + ((a >= 12) ? 'PM' : 'AM') + ' CST';
                }
            }, {
                header: "Amount",
                renderer: function(){
                    return '$5.00';
                }
            }]),
            ds: new Ext.data.JsonStore({
                data: cart.items.length ? cart.items : [],
                fields: ['promoteid','showdate', 'timeslot','slotsavailable']
            }),
            bbar: [{
                iconCls: 'btn-cart-delete',
                text: 'Remove',
				handler:function() {
					var data = [];
					var grid = Ext.getCmp('purchase_slots_grid');
					var selected = grid.getSelectionModel().getSelections();
					
					if(!selected.length) return false;
						
					for(var n=0;n<selected.length;n++) {
						var record = selected[n];
						
						data.push({
							timeslot: record.data.timeslot,
							showdate: record.data.showdate,
							promoteid: record.data.promoteid
						});
					};
					
                	Ext.Ajax	.request({
						url:'/payment/remove_from_cart',
						method:'POST',
						params:{
							data: Ext.encode(data)
						},
						success: function(r,o) {
							var oResponse = Ext.decode(r.responseText);
							for (var n = 0; n < selected.length; n++) {
								var record = selected[n];
								grid.getStore().remove(record);
							}
						}
					});					
				}
            }, {
                iconCls: 'btn-cart-go',
                text: 'Proceed to Checkout',
                handler: function(){
					var data = [];
					var grid = Ext.getCmp('purchase_slots_grid');
					
					grid.getStore().each(function(record){
						data.push({
							timeslot: record.data.timeslot,
							showdate: record.data.showdate,
							promoteid: record.data.promoteid
						});
					});
					
                	Ext.Ajax	.request({
						url:'/payment/add_to_cart',
						method:'POST',
						params:{
							data: Ext.encode(data)
						},
						success: function(r,o) {
							var oResponse = Ext.decode(r.responseText);
							
							if(oResponse.success) {
								window.location='/payment/checkout';
							}	
						}
					});
                }
            }]
        }
    };
    
    var mainLayout = new Ext.Panel({
        id: 'mainLayout',
        height: 350,
        width: 650,
        layout: 'column',
        frame: true,
        items: [{
            columnWidth: '.5',
            items: grids.available_slots
        }, {
            columnWidth: '.5',
            items: grids.purchase_slots
        }]
    });
    
    return {
        init: function(){
            Ext.QuickTips.init();
            forms.available_slots.render('filter');
            forms.available_slots.form.clearInvalid();
            
            mainLayout.on("render", function(){
                Ext.getCmp('available_slots_grid').getStore().load({
                    params: forms.available_slots.form.getValues()
                
                });
            });
            
            mainLayout.render('promoteAppContainer');
            
            
        }
    };
};
