var today = new Date();
var dateToday = today.dateFormat(gDateFormat);
var hourToday = (today.dateFormat('H')).toString();
var minuteToday = (today.dateFormat('i')).toString();
var secondToday = (today.dateFormat('s')).toString();

Ext.QuickTips.init();

function ParseTimeFromTitle(title) {
    var retValue = new Array();
    var hr;
    var min;
    if (title.match("\\b([0-9]|1[012])(:([0-5][0-9]))?(pm|am)\\b")) {
        data = title.split(" ");
        retValue[0] = title.substr(title.indexOf(" ")+1);
        time = data[0];
        if (title.match(":")) {
            hr = parseInt(time.substr(0,title.indexOf(":")));
            min = time.substr(title.indexOf(":")+1);
        } else {
            hr = parseInt(time.substr(0,time.length-2));
            min = "00"+time.substr(time.length-2);
        }

        if (min.match("(p[mM]|P[mM])")) {
            min = min.replace("pm","");
            min = min.replace("PM","");
            min = min.replace("pM","");
            min = min.replace("Pm","");
            hr +=12;
        } else {
            min = min.replace("am","");
            min = min.replace("AM","");
            min = min.replace("Am","");
            min = min.replace("aM","");
        }
        retValue[1] = hr;
        retValue[2] = min;
    } else {
        retValue[0] = title;
        retValue[1] = "";
        retValue[2] = "";
    }
    return retValue;
}

function ShowEventForm(eventid) {

    startDate = new Ext.form.DateField({
        id:               'startDate',
        format:           gDateFormat,
        //value:            dateToday,
        allowBlank:       false,
        name:             'startDate',
        fieldLabel:       lang("Start"),
        validationEvent:  false,
        height:           "5px",
        selectOnFocus:    true,
        format:           gDateFormat,
        allowBlank:       false,
        anchor:           '100%'
    });

    endDate = new Ext.form.DateField({
        id:               'endDate',
        format:           gDateFormat,
        //value:            dateToday,
        allowBlank:       false,
        name:             'endDate',
        fieldLabel:       lang("End"),
        validationEvent:  false,
        height:           "5px",
        selectOnFocus:    true,
        format:           gDateFormat,
        allowBlank:       false,
        anchor:           '100%'
    });

    endHour = new Ext.form.ComboBox({
        id:               'endHour',
        name:             'endHour',
        typeAhead:        true,
        triggerAction:    'all',
        lazyRender:       true,
        mode:             'local',
        hideLabel:        true,
        validationEvent:  false,
        width:            48,
        store:            new Ext.data.ArrayStore({
            idIndex:  0,
            fields:   [
                'id',
                'name'
            ],
            data:     [
                ['00', '00'],
                ['01', '01'],
                ['02', '02'],
                ['03', '03'],
                ['04', '04'],
                ['05', '05'],
                ['06', '06'],
                ['07', '07'],
                ['08', '08'],
                ['09', '09'],
                ['10', '10'],
                ['11', '11'],
                ['12', '12'],
                ['13', '13'],
                ['14', '14'],
                ['15', '15'],
                ['16', '16'],
                ['17', '17'],
                ['18', '18'],
                ['19', '19'],
                ['20', '20'],
                ['21', '21'],
                ['22', '22'],
                ['23', '23']
            ]
        }),
        valueField:       'id',
        displayField:     'name',
        value:            hourToday,
        hiddenId:         'endHourId',
        hiddenName:       'endHour',
        allowBlank:       false,
        blankText:        lang("This field is required"),
        forceSelection:   true,
        editable:         false
    });
    endHour.setDisabled(true);

    startHour = new Ext.form.ComboBox({
        id:               'startHour',
        name:             'startHour',
        typeAhead:        true,
        triggerAction:    'all',
        lazyRender:       true,
        mode:             'local',
        hideLabel:        true,
        validationEvent:  false,
        width:            48,
        store:            new Ext.data.ArrayStore({
            idIndex:  0,
            fields:   [
                'id',
                'name'
            ],
            data:     [
                ['00', '00'],
                ['01', '01'],
                ['02', '02'],
                ['03', '03'],
                ['04', '04'],
                ['05', '05'],
                ['06', '06'],
                ['07', '07'],
                ['08', '08'],
                ['09', '09'],
                ['10', '10'],
                ['11', '11'],
                ['12', '12'],
                ['13', '13'],
                ['14', '14'],
                ['15', '15'],
                ['16', '16'],
                ['17', '17'],
                ['18', '18'],
                ['19', '19'],
                ['20', '20'],
                ['21', '21'],
                ['22', '22'],
                ['23', '23']
            ]
        }),
        valueField:       'id',
        displayField:     'name',
        value:            hourToday,
        hiddenId:         'startHourId',
        hiddenName:       'startHour',
        allowBlank:       false,
        blankText:        lang("This field is required"),
        forceSelection:   true,
        editable:         false
    });
    startHour.setDisabled(true);

    startMinute = new Ext.form.ComboBox({
        id:               'startMinute',
        name:             'startMinute',
        typeAhead:        true,
        triggerAction:    'all',
        lazyRender:       true,
        mode:             'local',
        hideLabel:        true,
        validationEvent:  false,
        width:            48,
        store:            new Ext.data.ArrayStore({
            idIndex:  0,
            fields:   [
                'id',
                'name'
            ],
            data:     [
                ['00', '00'],
                ['01', '01'],
                ['02', '02'],
                ['03', '03'],
                ['04', '04'],
                ['05', '05'],
                ['06', '06'],
                ['07', '07'],
                ['08', '08'],
                ['09', '09'],
                ['10', '10'],
                ['11', '11'],
                ['12', '12'],
                ['13', '13'],
                ['14', '14'],
                ['15', '15'],
                ['16', '16'],
                ['17', '17'],
                ['18', '18'],
                ['19', '19'],
                ['20', '20'],
                ['21', '21'],
                ['22', '22'],
                ['23', '23'],
                ['24', '24'],
                ['25', '25'],
                ['26', '26'],
                ['27', '27'],
                ['28', '28'],
                ['29', '29'],
                ['30', '30'],
                ['31', '31'],
                ['32', '32'],
                ['33', '33'],
                ['34', '34'],
                ['35', '35'],
                ['36', '36'],
                ['37', '37'],
                ['38', '38'],
                ['39', '39'],
                ['40', '40'],
                ['41', '41'],
                ['42', '42'],
                ['43', '43'],
                ['44', '44'],
                ['45', '45'],
                ['46', '46'],
                ['47', '47'],
                ['48', '48'],
                ['49', '49'],
                ['50', '50'],
                ['51', '51'],
                ['52', '52'],
                ['53', '53'],
                ['54', '54'],
                ['55', '55'],
                ['56', '56'],
                ['57', '57'],
                ['58', '58'],
                ['59', '59']
            ]
        }),
        valueField:       'id',
        displayField:     'name',
        value:            minuteToday,
        hiddenId:         'startMinuteId',
        hiddenName:       'startMinute',
        allowBlank:       false,
        blankText:        lang("This field is required"),
        forceSelection:   true,
        editable:         false
    });
    startMinute.setDisabled(true);

    endMinute = new Ext.form.ComboBox({
        id:               'endMinute',
        name:             'endMinute',
        typeAhead:        true,
        triggerAction:    'all',
        lazyRender:       true,
        mode:             'local',
        hideLabel:        true,
        validationEvent:  false,
        width:            48,
        store:            new Ext.data.ArrayStore({
            idIndex:  0,
            fields:   [
                'id',
                'name'
            ],
            data:     [
                ['00', '00'],
                ['01', '01'],
                ['02', '02'],
                ['03', '03'],
                ['04', '04'],
                ['05', '05'],
                ['06', '06'],
                ['07', '07'],
                ['08', '08'],
                ['09', '09'],
                ['10', '10'],
                ['11', '11'],
                ['12', '12'],
                ['13', '13'],
                ['14', '14'],
                ['15', '15'],
                ['16', '16'],
                ['17', '17'],
                ['18', '18'],
                ['19', '19'],
                ['20', '20'],
                ['21', '21'],
                ['22', '22'],
                ['23', '23'],
                ['24', '24'],
                ['25', '25'],
                ['26', '26'],
                ['27', '27'],
                ['28', '28'],
                ['29', '29'],
                ['30', '30'],
                ['31', '31'],
                ['32', '32'],
                ['33', '33'],
                ['34', '34'],
                ['35', '35'],
                ['36', '36'],
                ['37', '37'],
                ['38', '38'],
                ['39', '39'],
                ['40', '40'],
                ['41', '41'],
                ['42', '42'],
                ['43', '43'],
                ['44', '44'],
                ['45', '45'],
                ['46', '46'],
                ['47', '47'],
                ['48', '48'],
                ['49', '49'],
                ['50', '50'],
                ['51', '51'],
                ['52', '52'],
                ['53', '53'],
                ['54', '54'],
                ['55', '55'],
                ['56', '56'],
                ['57', '57'],
                ['58', '58'],
                ['59', '59']
            ]
        }),
        valueField:       'id',
        displayField:     'name',
        value:            minuteToday,
        hiddenId:         'endMinuteId',
        hiddenName:       'endMinute',
        allowBlank:       false,
        blankText:        lang("This field is required"),
        forceSelection:   true,
        editable:         false
    });
    endMinute.setDisabled(true);

    endDateContainer = new Ext.Container({
        id:     'endDateContainer',
        width: 395,
        layout: 'form',
        items : [
            {
                layout: 'column',
                border: false,
                items:  [
                    {
                        columnWidth:  .5,
                        layout:       'form',
                        border:       false,
                        items:        [
                            endDate
                        ]
                    },
                    {
                        columnWidth:  .13,
                        layout:       'form',
                        border:       false,
                        items:        [
                            endHour
                        ]
                    },
                    {
                        columnWidth:  .02,
                        layout:       'form',
                        border:       false,
                        items:        [
                            {
                                xtype:      "label",
                                id:         'productFieldTimeSeparator1',
                                name:       'productFieldTimeSeparator1',
                                hideLabel:  true,
                                text:       ":  "
                            }
                        ]
                    },
                    {
                        columnWidth:  .13,
                        layout:       'form',
                        border:       false,
                        items:        [
                            endMinute
                        ]
                    }
                ]
            }
        ]
    });
    
    startDateContainer = new Ext.Container({
        id:     'startDateContainer',
        width: 395,
        layout: 'form',
        items : [
            {
                layout: 'column',
                border: false,
                items:  [
                    {
                        columnWidth:  .5,
                        layout:       'form',
                        border:       false,
                        items:        [
                            startDate
                        ]
                    },
                    {
                        columnWidth:  .13,
                        layout:       'form',
                        border:       false,
                        items:        [
                            startHour
                        ]
                    },
                    {
                        columnWidth:  .02,
                        layout:       'form',
                        border:       false,
                        items:        [
                            {
                                xtype:      "label",
                                id:         'productFieldTimeSeparator1',
                                name:       'productFieldTimeSeparator1',
                                hideLabel:  true,
                                text:       ":  "
                            }
                        ]
                    },
                    {
                        columnWidth:  .13,
                        layout:       'form',
                        border:       false,
                        items:        [
                            startMinute
                        ]
                    }
                ]
            }
        ]
    });

    //repeat options
    var repeatOptions = [
        ['0', lang('None')],
        ['1', lang('Every Day')],
        ['2', lang('Every Week')],
        ['3', lang('Every Month')],
        ['4', lang('Every Year')]
    ];
    var eventRepeat = new Ext.form.ComboBox({
        id: 'repeatable',
        store: new Ext.data.ArrayStore({
            fields: ['id', 'optionname'],
            data : repeatOptions // from states.js
        }),
        displayField:'optionname',
        typeAhead: true,
        mode: 'local',
        editable: false,
        fieldLabel: 'Repeat',
        forceSelection: true,
        name: 'repeat',
        triggerAction: 'all',
        value:'None',
        selectOnFocus:true,
        width:137
    });

    var notification = [
        ['None', lang('None')],
        ['15m', "15 "+lang('Mins Before')],
        ['30m', "30 "+lang('Mins Before')],
        ['1h', "1 "+lang('Hr Before')],
        ['1d', "1 "+lang('Day Before')]
    ];
    var emailNotification = new Ext.form.ComboBox({
        store: new Ext.data.ArrayStore({
            fields: ['abbr', 'optionname'],
            data : notification // from states.js
        }),
        displayField:'optionname',
        displayId: 'abbr',
        typeAhead: true,
        mode: 'local',
        editable: false,
        fieldLabel: 'E-Mail',
        forceSelection: true,
        name: 'notification',
        triggerAction: 'all',
        value:'None',
        selectOnFocus:true,
        width:137
    });

    //only will show if creator
    var privacyOptions = [
        ['0', lang('All Staff')],
        ['1', lang('Private')]
    ];
    var eventPrivacy = new Ext.form.ComboBox({
        id: 'isprivate',
        store: new Ext.data.ArrayStore({
            fields: ['id', 'optionname'],
            data : privacyOptions // from states.js
        }),
        displayField:'optionname',
        valueField : 'id',
        typeAhead: true,
        mode: 'local',
        editable: false,
        fieldLabel: 'Privacy',
        forceSelection: true,
        triggerAction: 'all',
        hiddenName : 'privacy',
        value:'Private',
        selectOnFocus:true,
        width:137
    });

    // Store for the list of TLD's
    var event_store = new Ext.data.JsonStore({
        id: "event_store",
        root: 'data',
        idProperty: 'id',
        remoteSort: true,
        fields: [ 'id','title','start','end','allday','url' ],
        proxy: new Ext.data.HttpProxy({url: "index.php?fuse=admin&action=AdminGetCalendarEvents&eventid="+eventid})
    });

    function DisableDates()
    {
        startHour.setDisabled(true);
        startMinute.setDisabled(true);
        startHour.setValue('00');
        startMinute.setValue('00');

        endHour.setDisabled(true);
        endMinute.setDisabled(true);
        endHour.setValue('00');
        endMinute.setValue('00');
    }

    function EnableDates()
    {
        startHour.setDisabled(false);
        startMinute.setDisabled(false);

        endHour.setDisabled(false);
        endMinute.setDisabled(false);
    }
    var eventform = new Ext.form.FormPanel({
        baseCls: 'x-plain',
        labelWidth: 55,
        url:'index.php?fuse=admin&action=AdminSaveCalendarEvent',
        defaultType: 'textfield',
        items: [
        {xtype: 'hidden',
         id: 'id',
         name: 'id',
         value : eventid
        },{
            fieldLabel: 'Title',
            name: 'title',
            id: 'title',
            anchor:'100%'  // anchor width by percentage
        },{
            // Use the default, automatic layout to distribute the controls evenly
            // across a single row
            xtype: 'checkboxgroup',
            fieldLabel: 'All Day',
            items: [{
                boxLabel: '&nbsp;',
                id: 'allDay',
                name: 'allday',
                checked: true,
                listeners: {
                    'check': function(cb, checked){
                        if (checked) {
                            DisableDates();
                        } else {
                            EnableDates();
                        }
                }
            }
            }]
        },
        startDateContainer,
        endDateContainer,
        //eventRepeat,
        //emailNotification,
        eventPrivacy, //only if you the creator
        {
            id: 'description',
            xtype: 'textarea',
            hideLabel: true,
            name: 'description',
            anchor: '100%'  // anchor width by percentage and height by raw adjustment
        }],
        listeners : {
            'actioncomplete' : function (form,action) 
            {
                if(action.type == "submit"){
                      eventwindow.close();
                      $('#calendar').fullCalendar( 'changeView', 'basicWeek' );
                      $('#calendar').fullCalendar( 'changeView', 'month' );
                }
            }
        }
    });

    var eventwindow = new Ext.Window({
        title: 'Calendar Event',
        width: 330,
        height:270,
        minWidth: 330,
        minHeight: 200,
        layout: 'fit',
        plain:true,
        bodyStyle:'padding:5px;',
        buttonAlign:'center',
        items: eventform,
        modal: true,
        buttons: [{
            text: 'Save',
            listeners: {
                'click' : function () {
                    eventform.getForm().submit();
                }
            }
        },{
            text: 'Cancel',
            listeners: {
                'click' : function () {
                    eventwindow.close();
                }
            }
        },{
            text: 'Delete',
            id: 'btnDelete',
            listeners: {
                'click' : function () {
                    Ext.MessageBox.confirm('Confirm', 'Are you sure you want to delete that event?', function(btn, text){
                        if (btn == 'yes'){
                            Ext.Ajax.request({
                               url: 'index.php?fuse=admin&action=AdminDeleteCalendarEvent',
                               success: function(xhr) {
                                   json = ce.parseAjaxResponse(xhr);
                                   if (!json.error) {
                                       eventwindow.close();
                                       $('#calendar').fullCalendar( 'changeView', 'basicWeek' );
                                       $('#calendar').fullCalendar( 'changeView', 'month' );
                                   }
                               },
                               failure: function() {
                                    Ext.Msg.alert("Fail");
                               },
                               params: {id: eventid}
                            });
                        }
                    });
                }
            }
        }]
    });

    eventwindow.show();

    eventform.getForm().load({
        url: "index.php?fuse=admin&action=AdminGetCalendarEvents&eventid="+eventid,
        waitMsg:lang('Loading'),
        success: function(form, action) {
            var response = Ext.util.JSON.decode(action.response.responseText);
            
            if (!response.data.allDay) {
                Ext.getCmp('allDay').setValue(0);
                startDateContainer.setDisabled(false);
                startHour.setDisabled(false);
                startMinute.setDisabled(false);
                endHour.setDisabled(false);
                endMinute.setDisabled(false);
            } else {
                Ext.getCmp('allDay').setValue(1);
                startHour.setDisabled(true);
                startMinute.setDisabled(true);
                //startHour.setValue('--');
                //startMinute.setValue('--');
                endHour.setDisabled(true);
                endMinute.setDisabled(true);
                //endHour.setValue('--');
                //endMinute.setValue('--');
            }

            //check to see if I can edit fields
            if (!response.data.editable) {
                Ext.getCmp('allDay').setDisabled(true);
                Ext.getCmp('isprivate').setDisabled(true);
                Ext.getCmp('title').setDisabled(true);
                Ext.getCmp('repeatable').setDisabled(true);
                Ext.getCmp('description').setDisabled(true);
                Ext.getCmp('btnDelete').setDisabled(true);
            }
        },
        failure: function(form, action) {alert('failure');},
        params: {id: id}
    });
}
