// Load Event Times data abstract
 require_once(GLM_MEMBERS_EVENTS_PLUGIN_CLASS_PATH.'/data/dataTimes.php');
+require_once GLM_MEMBERS_EVENTS_PLUGIN_CLASS_PATH . '/data/dataEvents.php';
+require_once GLM_MEMBERS_EVENTS_PLUGIN_PATH . '/models/front/events/baseAction.php';
 
 /*
  * This class performs the work of handling images passed to it via
  * an AJAX call that goes through the WorPress AJAX Handler.
  *
  */
-class GlmMembersAdmin_ajax_eventsCalMonthAJAX extends GlmDataEventsTimes
+class GlmMembersAdmin_ajax_eventsCalMonthAJAX extends GlmDataEvents
 {
 
     /**
         parent::__construct(false, false);
 
     }
+        /**
+     * getModelEventsData
+     *
+     * Return the array of events.
+     *
+     * @param integer $categoryId Id of the category for filtering events (optional)
+     * @param integer $limit      Number of events to return (optional)
+     * @param integer $memberID Member ID if filtering by member
+     *
+     * @access public
+     * @return array events
+     */
+    public function getModelTimesData(  )
+    {
+
+        $this->postAddTimes = true;
+        $where = '';
+
+        
+            $where .= "T.active = 1
+                AND T.event IN (
+                        SELECT event
+                          FROM " . GLM_MEMBERS_EVENTS_PLUGIN_DB_PREFIX . "times AS ET
+                         WHERE active
+                           AND " . $this->dateRange . "
+                    )
+                ";
+        
+            $times = $this->getList( $where );
+
+        $this->postAddTimes = false;
+        return $times;
+    }
+        /**
+     * getModelEventsData
+     *
+     * Return the array of events.
+     *
+     * @param integer $categoryId Id of the category for filtering events (optional)
+     * @param integer $limit      Number of events to return (optional)
+     * @param integer $memberID Member ID if filtering by member
+     *
+     * @access public
+     * @return array events
+     */
+    public function getModelEventsData(  )
+    {
+
+        $this->postAddTimes = true;
+        $where = '';
+
+        
+            $where .= "T.status = " . $this->config['status_numb']['Active'] . "
+                AND T.id IN (
+                        SELECT event
+                          FROM " . GLM_MEMBERS_EVENTS_PLUGIN_DB_PREFIX . "times AS ET
+                         WHERE active 
+                           AND " . $this->dateRange . "
+                    )
+                ";
+            
+            $events = $this->getList( $where );
+//            echo "<pre>", print_r($events), '</pre>';
+        $this->postAddTimes = false;
+        return $events;
+    }
+    
 
     /*
      * Perform Model Action
      * Echos JSON string as response and does not return
      */
     public function modelAction ($actionData = false)
-    {
+    {   
+        $event_data = [];
+        $month = $_POST['month'];
+        $from = date('Y-m-d', strtotime($month['start']));
+        $to   = date('Y-m-d', strtotime($month['last']));
+
+        $this->dateRange = "start_time BETWEEN CAST('{$from}' AS DATE) AND CAST('{$to}' as DATE)";
+        $this->dateRange = "id IN (
+            SELECT id
+              FROM " . GLM_MEMBERS_EVENTS_PLUGIN_DB_PREFIX . "times
+              WHERE DATE(start_time) BETWEEN '{$from}' AND '{$to}'
+        )";
+
+        $events= $this->getModelEventsData();
+
+        foreach ($events as $e=>$val){
+            $times[] = ($val['times']);
+            $event_data[$e]['title'] = $val['name'];
+            $event_data[$e]['url'] = GLM_MEMBERS_EVENTS_SITE_BASE_URL . "event-detail/" . $val['name_slug'] . "/";
+            
+            $start = date('Y-m-d h:i:s', strtotime($val['starting_date']));
+            $last = date('Y-m-d h:i:s', strtotime($val['ending_date']));
+            
+            $event_data[$e]['start'] = ($start);
+            $event_data[$e]['last'] = ($last);
+
+        }
+
+        foreach($times as $t=>$val){
+            foreach($val as $v){
+
+            }
+        }
+
 
         $return = array(
             'status' => false,       // Assume nothing works
-            'events' => false,       // Where our events list will go
-            'message' => ''
+            'events' => $event_data,       // Where our events list will go
+            'message' => '',
+            'times'  => ''
         );
 
-$return['message'] = 'Made it Here!';
-
         // Return stored image data
         echo json_encode($return);
         wp_die();
     }
-
-
 }
 
         var fullCalendarLoaded = false;
         var recurrencesInited = false;
         var locationsInited = false;
-
-/* Temporarily dissable calendar display
-
-         // Get calendar month via AJAX
+        var table = 'glm-table-calendar';
+        var post_start, post_end, month_obj;
+        var rows = $(".glm-event-day-row");
+        var view_select = $("#glm-event-view-select");
+        var search = $("#glm-events-search-form");
+        var calendar = $("#eventCalendar");
+        var event_search = $(".glm-search-icon");
+        
+        calendar.hide();
+        
+        event_search.on("click", function (){
+            
+            rows.fadeIn("slow", function (){});
+            calendar.fadeOut("slow", function(){});
+            
+        });
+        // AJAX FUNCTION ************************************************
+        // Get calendar month via AJAX
         function eventsCalMonthAJAX(month) {
-            var data = {
+            var dat = {
+                
                 action: 'glm_members_admin_ajax',
-                glm_action: 'eventsCalMonthAJAX'
-                month: 'Month Stuff'
+                glm_action: 'eventsCalMonthAJAX',
+                month: month
+                
             };
-            jQuery.post('{$ajaxUrl}', data, function(response) {
-                alert(response);
-            });
-        }
-// Fire off for testing
-var x = eventsCalMonthAJAX('123');
-
-
-        if (table == 'glm-table-calendar' && !fullCalendarLoaded) {
-
-            // **** Should probably move all this to a function and check if it's been initialized already
-            $('#eventCalendar').fullCalendar({
-                events: [
-    {$sep = ''}
-    {foreach $calDates as $cDate}
-                    {$sep}{
-                        title : "{$cDate.event_name|unescape:'html'}",
-                        start : '{$cDate.start_time.datetime}',
-                        end   : '{$cDate.end_time.datetime}',
-                        allday : {$cDate.all_day.value}
-                    }
-                    {$sep = ','}
-    {/foreach}
-                ],
-                defaultDate : '{$firstTime.start_time.datetime}',
-                timeFormat  : 'h:mma',
-                fixedWeekCount : false,
-                eventClick: function(calEvent, jsEvent, view) {
-
-                    $("#occurrences").dialog();
-                    $(this).css('border-color', 'red');
+            $('.fc-event').remove();
+             jQuery.ajax({
+                type: 'POST',
+                url: '{$ajaxUrl}',
+                data: dat,
+                cache: false,
+                success: function (response){
+//                    console.log(response);
+                    var buildingEvents = [];
+                    var events_obj = jQuery.parseJSON(response);
+                    var events = events_obj.events;
+//                    console.log(events);
+
+                    buildingEvents = $.map(events, function(i, val) {   
+//                        console.log(i.start);
+                        return {   
+                            title:   i.title,
+                            start:   i.start,
+                            end:     i.last,
+//                            allDay:  i.allDay,
+                            url:     i.url
+                        };
+                    });
+                    $("#eventCalendar").fullCalendar('removeEvents');
+                    $("#eventCalendar").fullCalendar('addEventSource', buildingEvents);
                 }
             });
+        }
+        
+     // Calendar *****************************************************
+    $('#eventCalendar').fullCalendar({
+        viewRender: function (view, element){
+            post_start = view.start._d;
+            post_end = view.end._d;
+            {literal}month_obj = {start: view.start._d, last: view.end._d};{/literal}
+        },
+        header: {
+            left: 'prev,next today',
+            center: 'title',
+            right: 'month,agendaWeek,agendaDay'
+        },
+        dayClick: function(date, jsEvent, view) {
+            test = $('#eventCalendar').fullCalendar('getView').end;
+            console.log(test);
+            $('#eventCalendar').fullCalendar('changeView', 'agendaDay');
+            $('#eventCalendar').fullCalendar('gotoDate', date);
+        },
+        lazyFetching: true,
+        eventClick : function (event){
+            location.href = event.url;
+        },
+        nextDayThreshold: '00:00:00',
+        views: {
+            month: {
+                eventLimit: 4
+            }
+        }
+    });
+    $("#glm-event-view-select").on("change", function (){
+            if($("#glm-event-view-select option:selected").val() === "calendar"){
+                rows.fadeOut('slow', function(){});
+//                search.fadeOut('slow', function(){});
+                calendar.fadeIn('slow', function(){});
+                calendar.fullCalendar('render');
+                eventsCalMonthAJAX(month_obj);
+
+               
+            } else if ( $("#glm-event-view-select option:selected").val() === "agenda"){
+                rows.fadeIn('slow', function(){});
+//                search.fadeIn('slow', function(){});
+                calendar.fadeOut('slow', function(){});
+            }
+        });
+    // initialize calendar with AJAX calls *************************************
+    var x = eventsCalMonthAJAX(month_obj);
+    $(document).on("click", "button.fc-button", function () {
+        var x = eventsCalMonthAJAX(month_obj);
+    });
 
-            fullCalendarLoaded = true;
-//        }
-*/
+    if (table == 'glm-table-calendar' && !fullCalendarLoaded) {
 
+        fullCalendarLoaded = true;
+    }
 
     });
 </script>