Ext.onReady(function(){

    Ext.BLANK_IMAGE_URL = "/includes/imgs/s.gif";
    Ext.SSL_SECURE_URL = "/includes/imgs/s.gif";
    Ext.QuickTips.init();
    Ext.form.Field.prototype.msgTarget = 'side';

    var tid = null;
    var clubId = null;
    var clubNum = null;

    var chkBoater = new Ext.grid.CheckColumn({ header: 'Angler (15-18)', dataIndex: 'boater', width: 87 });
    var chkNonBoater = new Ext.grid.CheckColumn({ header: 'Angler (11-14)', dataIndex: 'nonboater', width: 87 });

    var dsClubMembers = new Ext.data.Store(
        { proxy: new Ext.data.HttpProxy( { url: 'getClubMember.php' } )
        , baseParams: { data:'clubMember', club_id: clubId }
        , reader: new Ext.data.JsonReader({ root: 'clubMember', id: 'member_id', totalProperty: 'totalCount' }, ['member_id','name','tbf_number','voice','dob'] )
        });

    var dsClub = new Ext.data.Store(
        { proxy: new Ext.data.HttpProxy( { url: 'getJrClubList.php' } )
        , baseParams: { html:'getData', data:'clubList' }
        , reader: new Ext.data.JsonReader({ root: 'clubList', id: 'club_id', totalProperty: 'totalCount' }, ['club_id','name','club_num'] )
        , autoLoad: true
        });

    var cm = new Ext.grid.ColumnModel(
        [chkBoater
        ,chkNonBoater
        ,{
           id: 'tbf_number',
           header: 'TBF #',
           dataIndex: 'tbf_number',
           width: 53
        },{
           id: 'name',
           header: 'Name',
           dataIndex: 'name',
           width: 220
        },{
           id: 'phone',
           header: 'Phone',
           dataIndex: 'voice',
           width: 87
        },{
           id: 'dob',
           header: 'DoB',
           dataIndex: 'dob',
           width: 73
        }
    ]);
    cm.defaultSortable = false;



    var frmEntry = new Ext.FormPanel({
      labelWidth: 105,
      frame: true,
      title: ' Step 1 of 2:  Fill Out Form and Submit Entry. ',
	  bodyStyle:'padding:5px 5px 0',
	  width: 750,
      defaults: {width: 600},
      defaultType: 'textfield',
      items:
        [{
            xtype:'combo'
            ,id: 'cbTourney'
            ,typeAhead: true
            ,triggerAction: 'all'
            ,lazyRender:true
            ,mode: 'local'
            ,store: new Ext.data.ArrayStore({
                fields: ['id', 'name'],
                data : [['867','2011 TN State Jr Bass Tourney ( 6/3-4 )']]
            })
            ,fieldLabel: '<b>Tournament</b>'
            ,valueField: 'id'
            ,displayField: 'name'
            ,emptyText: 'Select a Tournament...'
            ,allowBlank: false
            ,onSelect:function(record) {
                tid = record.get('id');
                this.collapse();
                this.setValue(record.get('name'));
                //dsClub.baseParams = { data:'getData', data:'clubList', division: record.get('division') };
                //dsClub.load();
            }
        },{
            xtype:'textfield'
            ,id: 'txtEmail'
            ,fieldLabel: '<b>Email Address</b>'
            ,valueField: 'id'
            ,emptyText: 'Enter Email Address...'
            ,allowBlank: false
            ,vtype: 'email'
            ,maxLength: 100
        },{
            xtype:'combo'
            ,id: 'cbClub'
            ,fieldLabel: '<b>Club Name</b>'
            ,store: dsClub
            ,displayField:'name'
            ,valueField: 'club_id'
            ,typeAhead: true
            ,mode: 'local'
            ,forceSelection: true
            ,triggerAction: 'all'
            ,emptyText: 'Select a Club...'
            ,selectOnFocus: true
            ,allowBlank: false
            ,onSelect:function(record) {
                clubId = record.get('club_id');
                clubNum = record.get('club_num');
                this.collapse();
                this.setValue(record.get('name'));
                dsClubMembers.baseParams = { data:'clubMember', club_id: clubId };
                dsClubMembers.load();
            }
        },{
            xtype:'editorgrid'
            ,labelAlign: 'top'
            ,id:'gMembers'
            ,fieldLabel: '<b>Select Members</b>'
            ,store: dsClubMembers
            ,cm: cm
            ,width: 600
            ,height: 300
            ,autoExpandColumn: 'name'
            ,title: 'Select Team Members'
            ,frame: true
            ,plugins: [chkBoater,chkNonBoater]
            ,clicksToEdit: 1
            ,loadMask: {msg: 'Fetching Member Data...'}

        },{
            xtype:'textfield'
            ,id: 'bc1_name'
            ,fieldLabel: '<b>Boat Captain #1</b>'
            ,valueField: 'bc1_name'
            ,emptyText: 'Enter Name...'
            ,allowBlank: true
            ,maxLength: 100
        },{
            xtype:'textfield'
            ,id: 'bc2_name'
            ,fieldLabel: '<b>Boat Captain #2</b>'
            ,valueField: 'bc2_name'
            ,emptyText: 'Enter Name...'
            ,allowBlank: true
            ,maxLength: 100
        },{
            xtype:'textfield'
            ,id: 'bc3_name'
            ,fieldLabel: '<b>Boat Captain #3</b>'
            ,valueField: 'bc3_name'
            ,emptyText: 'Enter Name...'
            ,allowBlank: true
            ,maxLength: 100

        },{
            xtype:'textfield'
            ,id: 'txtStayPlace'
            ,fieldLabel: '<b>Stay Location</b>'
            ,valueField: 'id'
            ,emptyText: 'Enter Staying At...'
            ,allowBlank: true
            ,maxLength: 100
        },{
            xtype:'textfield'
            ,id: 'txtStayPhone'
            ,fieldLabel: '<b>Stay Phone</b>'
            ,valueField: 'id'
            ,emptyText: 'Enter Staying At Phone...'
            ,allowBlank: true
            ,maxLength: 20

        }]
        , buttons: [{ text: 'Submit Entry', handler: chkSubmit },{ text: 'Cancel' }]
        , buttonAlign: 'center'
    });

    frmEntry.render('frmEntry');

    function chkSubmit(btn) {

        if ( Ext.getCmp('cbTourney').getValue() == '' ) {
            Ext.Msg.alert('Tournament', 'Select a Tournament prior to submitting entry.');
            return;
        }

        if ( Ext.getCmp('txtEmail').getValue() == '' ) {
            Ext.Msg.alert('Email', 'Enter Email Address prior to submitting entry.');
            return;
        }

        if ( !Ext.getCmp('txtEmail').validate() ) {
            Ext.Msg.alert('Email', 'Enter a valid Email Address.');
            return;
        }

        if ( Ext.getCmp('cbClub').getValue() == '' ) {
            Ext.Msg.alert('Club', 'Select a Club prior to submitting entry.');
            return;
        }

        var bCnt = 0;
        var nbCnt = 0;
        var b1 = null;
        var b2 = null;
        var b3 = null;
        var nb1 = null;
        var nb2 = null;
        var nb3 = null;

        for ( i=0; i<dsClubMembers.getCount(); i++ ) {
            r = dsClubMembers.getAt(i);
            if ( r.get('boater') && r.get('nonboater') ) {
                Ext.Msg.alert('Team Member', r.get('name') + ' cannot be an Angler in both age groups.');
                return;
            }
            if ( r.get('boater') ) {
                bCnt = bCnt +1;
                if ( bCnt == 1 ) { b1 = r.get('member_id'); }
                if ( bCnt == 2 ) { b2 = r.get('member_id'); }
                if ( bCnt == 3 ) { b3 = r.get('member_id'); }
            }
            if ( r.get('nonboater') ) {
                nbCnt = nbCnt +1;
                if ( nbCnt == 1 ) { nb1 = r.get('member_id'); }
                if ( nbCnt == 2 ) { nb2 = r.get('member_id'); }
                if ( nbCnt == 3 ) { nb3 = r.get('member_id'); }
            }
        }


        if ( bCnt == 0 && nbCnt == 0 ) {
            Ext.Msg.alert('Angler Selection', 'Select at least one Angler to Submit Entry.');
            return;
        }
        if ( bCnt > 3 ) {
            Ext.Msg.alert('Anglers (15-18)', 'Select only 3 Anglers (15-18). You have selected ' + bCnt + '.');
            return;
        }
        if ( nbCnt > 3 ) {
            Ext.Msg.alert('Anglers (11-14)', 'Select only 3 Anglers (11-14). You have selected ' + nbCnt + '.');
            return;
        }


        new Ext.data.Connection().request(
            { url: 'submitentry.jr.php'
            , method: 'post'
            , scope: this
            , waitMsg: 'Please Wait, Saving Data...'
            , params:
                { event_id: Ext.getCmp('cbTourney').getValue()
                , club_id: clubId
                , b1_id: b1
                , b2_id: b2
                , b3_id: b3
                , nb1_id: nb1
                , nb2_id: nb2
                , nb3_id: nb3
                , c_email: Ext.getCmp('txtEmail').getValue()
                , stay_place: Ext.getCmp('txtStayPlace').getValue()
                , stay_phone: Ext.getCmp('txtStayPhone').getValue()
                }
            , callback: function ( options, bSuccess, response )
                {
                    var rs = Ext.decode(response.responseText);
                    if ( 'object' != typeof rs ) {
                        Ext.MessageBox.alert('Save Error', 'There was an error saving the .');
                    } else {
                        if ( true == rs.success ) {
                            //Ext.Msg.alert('Submit Entry', 'Entry Saved. Entry Id: ' + rs.entry_id );
                            window.location = 'viewentry.jr.php' + "?entry_id=" + rs.entry_id ;
                        } else {
                            Ext.MessageBox.alert('Save Error', rs.errmsg, this);
                        }
                    }
                }
            }
        );


    }

});

