<?php require_once("inc/init.php"); ?>
<?php require_once("controller/calendarCode.php"); ?>
<div class="row">
	<div class="col-xs-12 col-sm-7 col-md-7 col-lg-4">
		<h1 class="page-title txt-color-blueDark"><i class="fa fa-calendar fa-fw "></i> 
			Calendar
			<span>>
			Add events
			</span>
		</h1>
	</div>
	<div class="col-xs-12 col-sm-5 col-md-5 col-lg-8">

	</div>
</div>
<!-- row -->

<div class="row">

	<div class="col-sm-12 col-md-12 col-lg-3">
		<!-- new widget -->
		<div class="jarviswidget jarviswidget-color-blueDark">
			<header>
				<h2> Add Events </h2>
			</header>

			<!-- widget div-->
			<div>

				<div class="widget-body">
					<!-- content goes here -->

					<form id="add-event-form">
						<fieldset>

							<div class="form-group">
								<label>Select Event Icon</label>
								<div class="btn-group btn-group-sm btn-group-justified" data-toggle="buttons">
									<label class="btn btn-default active">
										<input type="radio" name="iconselect" id="icon-1" value="fa-info" checked>
										<i class="fa fa-info text-muted"></i> </label>
									<label class="btn btn-default">
										<input type="radio" name="iconselect" id="icon-2" value="fa-warning">
										<i class="fa fa-warning text-muted"></i> </label>
									<label class="btn btn-default">
										<input type="radio" name="iconselect" id="icon-3" value="fa-check">
										<i class="fa fa-check text-muted"></i> </label>
									<label class="btn btn-default">
										<input type="radio" name="iconselect" id="icon-4" value="fa-user">
										<i class="fa fa-user text-muted"></i> </label>
									<label class="btn btn-default">
										<input type="radio" name="iconselect" id="icon-5" value="fa-lock">
										<i class="fa fa-lock text-muted"></i> </label>
									<label class="btn btn-default">
										<input type="radio" name="iconselect" id="icon-6" value="fa-clock-o">
										<i class="fa fa-clock-o text-muted"></i> </label>
								</div>
							</div>

							<div class="form-group">
								<label>Event Title</label>
								<input class="form-control"  id="title" name="title" maxlength="40" type="text" placeholder="Event Title">
							</div>
							<div class="form-group">
								<label>Event Description</label>
								<textarea class="form-control" placeholder="Please be brief" rows="3" maxlength="40" id="description"></textarea>
								<p class="note">Maxlength is set to 40 characters</p>
							</div>

							<div class="form-group">
								<label>Select Event Color</label>
								<div class="btn-group btn-group-justified btn-select-tick" data-toggle="buttons">
									<label class="btn bg-color-darken active">
										<input type="radio" name="priority" id="option1" value="bg-color-darken txt-color-white" checked>
										<i class="fa fa-check txt-color-white"></i> </label>
									<label class="btn bg-color-blue">
										<input type="radio" name="priority" id="option2" value="bg-color-blue txt-color-white">
										<i class="fa fa-check txt-color-white"></i> </label>
									<label class="btn bg-color-orange">
										<input type="radio" name="priority" id="option3" value="bg-color-orange txt-color-white">
										<i class="fa fa-check txt-color-white"></i> </label>
									<label class="btn bg-color-greenLight">
										<input type="radio" name="priority" id="option4" value="bg-color-greenLight txt-color-white">
										<i class="fa fa-check txt-color-white"></i> </label>
									<label class="btn bg-color-blueLight">
										<input type="radio" name="priority" id="option5" value="bg-color-blueLight txt-color-white">
										<i class="fa fa-check txt-color-white"></i> </label>
									<label class="btn bg-color-red">
										<input type="radio" name="priority" id="option6" value="bg-color-red txt-color-white">
										<i class="fa fa-check txt-color-white"></i> </label>
								</div>
							</div>

						</fieldset>
						<div class="form-actions">
							<div class="row">
								<div class="col-md-12">
									<button class="btn btn-default" type="button" id="add-event" >
										Add Event
									</button>
								</div>
							</div>
						</div>
					</form>

					<!-- end content -->
				</div>

			</div>
			<!-- end widget div -->
		</div>
		<!-- end widget -->

		<div class="well well-sm" id="event-container">
			<form>
				<legend>
					Draggable Events
				</legend>
				<ul id='external-events' class="list-unstyled">
					<?php 
					if ($get_all_events) {
						foreach($get_all_events as $events){
							?>
							<li>
						<span class="<?php echo $events['priority'] ?>" id="<?php echo $events['event_id'] ?>" data-description="<?php echo $events['event_title'] ?>" data-icon="<?php echo $events['icon'] ?>"><?php echo $events['event_description'] ?></span>
					</li>
							<?php
						}
					}
					 ?>
					
					
				</ul>
				<div class="checkbox">
					<label>
						<input type="checkbox" id="drop-remove" class="checkbox style-0" checked="checked">
						<span>remove after drop</span> </label>

				</div>
			</form>

		</div>
	</div>
	<div class="col-sm-12 col-md-12 col-lg-9">

		<!-- new widget -->
		<div class="jarviswidget jarviswidget-color-blueDark">

			<!-- widget options:
			usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false">

			data-widget-colorbutton="false"
			data-widget-editbutton="false"
			data-widget-togglebutton="false"
			data-widget-deletebutton="false"
			data-widget-fullscreenbutton="false"
			data-widget-custombutton="false"
			data-widget-collapsed="true"
			data-widget-sortable="false"

			-->
			<header>
				<span class="widget-icon"> <i class="fa fa-calendar"></i> </span>
				<h2> My Events </h2>
				<div class="widget-toolbar">
					<!-- add: non-hidden - to disable auto hide -->
					<div class="btn-group">
						<button class="btn dropdown-toggle btn-xs btn-default" data-toggle="dropdown">
							Showing <i class="fa fa-caret-down"></i>
						</button>
						<ul class="dropdown-menu js-status-update pull-right">
							<li>
								<a href="javascript:void(0);" id="mt">Month</a>
							</li>
							<li>
								<a href="javascript:void(0);" id="ag">Agenda</a>
							</li>
							<li>
								<a href="javascript:void(0);" id="td">Today</a>
							</li>
						</ul>
					</div>
				</div>
			</header>

			<!-- widget div-->
			<div>

				<div class="widget-body no-padding">
					<!-- content goes here -->
					<div class="widget-body-toolbar">

						<div id="calendar-buttons">

							<div class="btn-group">
								<a href="javascript:void(0)" class="btn btn-default btn-xs" id="btn-prev"><i class="fa fa-chevron-left"></i></a>
								<a href="javascript:void(0)" class="btn btn-default btn-xs" id="btn-next"><i class="fa fa-chevron-right"></i></a>
							</div>
						</div>
					</div>
					<div id="calendar"></div>

					<!-- end content -->
				</div>

			</div>
			<!-- end widget div -->
		</div>
		<!-- end widget -->

	</div>

</div>

<!-- end row -->

<script type="text/javascript">
	/* DO NOT REMOVE : GLOBAL FUNCTIONS!
	 *
	 * pageSetUp(); WILL CALL THE FOLLOWING FUNCTIONS
	 *
	 * // activate tooltips
	 * $("[rel=tooltip]").tooltip();
	 *
	 * // activate popovers
	 * $("[rel=popover]").popover();
	 *
	 * // activate popovers with hover states
	 * $("[rel=popover-hover]").popover({ trigger: "hover" });
	 *
	 * // activate inline charts
	 * runAllCharts();
	 *
	 * // setup widgets
	 * setup_widgets_desktop();
	 *
	 * // run form elements
	 * runAllForms();
	 *
	 ********************************
	 *
	 * pageSetUp() is needed whenever you load a page.
	 * It initializes and checks for all basic elements of the page
	 * and makes rendering easier.
	 *
	 */

	pageSetUp();
	
	/*
	 * ALL PAGE RELATED SCRIPTS CAN GO BELOW HERE
	 * eg alert("my home function");
	 * 
	 * var pagefunction = function() {
	 *   ...
	 * }
	 * loadScript("js/plugin/_PLUGIN_NAME_.js", pagefunction);
	 * 
	 * TO LOAD A SCRIPT:
	 * var pagefunction = function (){ 
	 *  loadScript(".../plugin.js", run_after_loaded);	
	 * }
	 * 
	 * OR
	 * 
	 * loadScript(".../plugin.js", run_after_loaded);
	 */
	
	// PAGE RELATED SCRIPTS

	// pagefunction
	
	var fullviewcalendar;

	var pagefunction = function() {
		
		// full calendar
		
		var date = new Date();
	    var d = date.getDate();
	    var m = date.getMonth();
	    var y = date.getFullYear();
	
	    var hdr = {
	        left: 'title',
	        center: 'month,agendaWeek,agendaDay',
	        right: 'prev,today,next'
	    };
	
	    var initDrag = function (e) {
	        // create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
	        // it doesn't need to have a start or end
	
	        var eventObject = {
	        	id:$.trim(e.children('span').attr('id')),
	            title: $.trim(e.children().text()), // use the element's text as the event title
	            description: $.trim(e.children('span').attr('data-description')),
	            icon: $.trim(e.children('span').attr('data-icon')),
	            className: $.trim(e.children('span').attr('class')) // use the element's children as the event class
	        };
	        // store the Event Object in the DOM element so we can get to it later
	        e.data('eventObject', eventObject);
	
	        // make the event draggable using jQuery UI
	        e.draggable({
	            zIndex: 999,
	            revert: true, // will cause the event to go back to its
	            revertDuration: 0 //  original position after the drag
	        });
	    };
	
	    var addEvent = function (title, priority, description, icon) {
	        title = title.length === 0 ? "Untitled Event" : title;
	        description = description.length === 0 ? "No Description" : description;
	        icon = icon.length === 0 ? " " : icon;
	        priority = priority.length === 0 ? "label label-default" : priority;
	
	        var html = $('<li><span class="' + priority + '" data-description="' + description + '" data-icon="' +
	            icon + '">' + title + '</span></li>').prependTo('ul#external-events').hide().fadeIn();
	
	        $("#event-container").effect("highlight", 800);
	
	        initDrag(html);
	    };
	
	    /* initialize the external events
		 -----------------------------------------------------------------*/
	
	    $('#external-events > li').each(function () {
	        initDrag($(this));
	    });
	
	    $('#add-event').click(function () {
	        var title = $('#title').val(),
	            priority = $('input:radio[name=priority]:checked').val(),
	            description = $('#description').val(),
	            icon = $('input:radio[name=iconselect]:checked').val();
	
	        addEvent(title, priority, description, icon);
	        //Send data to server side
	        var data = {
	        	title:title,
	        	priority:priority,
	        	description:description,
	        	icon:icon,
	        	add_event:''
	        };
	        $.post('ajax/calendar.php',data,function(res){
	        	if (res.charAt(0)==0) {
	        		$.smallBox({
					title : "Event Added successfully",
					content : "<i class='fa fa-clock-o'></i> <i>just now...</i>",
					color : "#000000",
					iconSmall : "fa fa-check bounce animated",
					timeout : 4000
				});
	        	}
	        });
	        //End of severside transfer
	    });
	
	    /* initialize the calendar
		 -----------------------------------------------------------------*/
	
	    fullviewcalendar = $('#calendar').fullCalendar({
	
	        header: hdr,
	        buttonText: {
	            prev: '<i class="fa fa-chevron-left"></i>',
	            next: '<i class="fa fa-chevron-right"></i>'
	        },
	
	        editable: true,
	        droppable: true, // this allows things to be dropped onto the calendar !!!

	        
	        drop: function (date, allDay) { // this function is called when something is dropped
	
	            // retrieve the dropped element's stored Event Object
	            var originalEventObject = $(this).data('eventObject');
	
	            // we need to copy it, so that multiple events don't have a reference to the same object
	            var copiedEventObject = $.extend({}, originalEventObject);
	
	            // assign it the date that was reported
	            copiedEventObject.start = date;
	            copiedEventObject.allDay = allDay;
				var remove = 0;
	            // render the event on the calendar
	            // the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
	            $('#calendar').fullCalendar('renderEvent', copiedEventObject, true);
					
	            // is the "remove after drop" checkbox checked?
	            if ($('#drop-remove').is(':checked')) {
	                // if so, remove the element from the "Draggable Events" list
	                remove = 1;
	                $(this).remove();
	            }else{
	            	remove = 0;
	            }

	            var set_data = {
	            	event_id:copiedEventObject.id,
	            	remove:remove,
	            	set_remove:''
	            };

	            $.post('ajax/calendar.php',set_data,function(res){
	            	if (res.charAt(0)==0) {

	            	}
	            });
	            
	            var update_event = {
                updateEvent:"",
                event_id:copiedEventObject.id,
                start: copiedEventObject.start.format(),
                event_title:copiedEventObject.title,
                priority:copiedEventObject.className,
                all_day:"",
                icon:copiedEventObject.icon,
                removed: "no"
          };
          $.post('ajax/calendar.php',update_event,function(res){

          	});
      },
	        eventResize:function(event,delta,revertfunc){
	        	//revertfunc();
	        	//event.end.format();
				console.log(event.start);
				console.log(event.end);
	        	//alert(event.end.format('y-m-d'));
	        },
	
	
	        select: function (start, end, allDay) {
	            var title = prompt('Event Title:');
	            if (title) {
	                calendar.fullCalendar('renderEvent', {
	                        title: title,
	                        start: start,
	                        end: end,
	                        allDay: allDay
	                    }, true // make the event "stick"
	                );
	            }
	            calendar.fullCalendar('unselect');
	        },
	
	        events: [
	        <?php 
	        if($get_all_calendar_event){
	        	
	        	
	        	for($i = 0; $i<sizeof($get_all_calendar_event);$i++){

	        ?>
	      	<?php 
	      	if ($i<sizeof($get_all_calendar_event)) {
	      		?>
 			{
	            title: '<?php echo $get_all_calendar_event[$i]['title'] ?>',
	            start: '<?php echo $get_all_calendar_event[$i]['start'] ?>',
	            description: '<?php echo $get_all_calendar_event[$i]['description'] ?>',
	            className: ["event", "<?php echo $get_all_calendar_event[$i]['className'] ?>"],
	            icon: '<?php echo $get_all_calendar_event[$i]['icon'] ?>'
	        },
	      		<?php
	      	}else{
	      	 ?>
	      	{
	            title: '<?php echo $get_all_calendar_event[$i]['title'] ?>',
	            start: '<?php echo $get_all_calendar_event[$i]['start'] ?>',
	            description: '<?php echo $get_all_calendar_event[$i]['description'] ?>',
	            className: ["event", "<?php echo $get_all_calendar_event[$i]['className'] ?>"],
	            icon: '<?php echo $get_all_calendar_event[$i]['icon'] ?>'
	        }

	      	<?php
	      }
	      	?>
	      <?php 	}
	        }

	         ?>
	        
	        ],
	
	        eventRender: function (event, element, icon) {
	            if (!event.description == "") {
	                element.find('.fc-event-title').append("<br/><span class='ultra-light'>" + event.description +
	                    "</span>");
	            }
	            if (!event.icon == "") {
	                element.find('.fc-event-title').append("<i class='air air-top-right fa " + event.icon +
	                    " '></i>");
	            }
	        },
	
	        windowResize: function (event, ui) {
	            $('#calendar').fullCalendar('render');
	        }
	    });
	
	    /* hide default buttons */
	    $('.fc-header-right, .fc-header-center').hide();

	
	
		$('#calendar-buttons #btn-prev').click(function () {
		    $('.fc-button-prev').click();
		    return false;
		});
		
		$('#calendar-buttons #btn-next').click(function () {
		    $('.fc-button-next').click();
		    return false;
		});
		
		$('#calendar-buttons #btn-today').click(function () {
		    $('.fc-button-today').click();
		    return false;
		});
		
		$('#mt').click(function () {
		    $('#calendar').fullCalendar('changeView', 'month');
		});
		
		$('#ag').click(function () {
		    $('#calendar').fullCalendar('changeView', 'agendaWeek');
		});
		
		$('#td').click(function () {
		    $('#calendar').fullCalendar('changeView', 'agendaDay');
		});
		
	};
	
	// end pagefunction
	
	// destroy generated instances 

	// destroy generated instances 
	// pagedestroy is called automatically before loading a new page
	// only usable in AJAX version!

	var pagedestroy = function(){

		/*
		Example below:

		$("#calednar").fullCalendar( 'destroy' );
		if (debugState){
			root.console.log("✔ Calendar destroyed");
		} 

		For common instances, such as Jarviswidgets, Google maps, and Datatables, are automatically destroyed through the app.js loadURL mechanic

		*/
		
		fullviewcalendar.fullCalendar( 'destroy' );
		fullviewcalendar = null;
		$("#add-event").off();
		$("#add-event").remove();

		$('#external-events > li').off();
		$('#external-events > li').remove();
		$('#add-event').off();
		$('#add-event').remove();
		$('#calendar-buttons #btn-prev').off();
		$('#calendar-buttons #btn-prev').remove();
		$('#calendar-buttons #btn-next').off();
		$('#calendar-buttons #btn-next').remove();
		$('#calendar-buttons #btn-today').off();
		$('#calendar-buttons #btn-today').remove();
		$('#mt').off();
		$('#mt').remove();
		$('#ag').off();
		$('#ag').remove();
		$('#td').off();
		$('#td').remove();

		if (debugState){
			root.console.log("✔ Calendar destroyed");
		} 
	}

	// end destroy

	// loadscript and run pagefunction
	loadScript("js/plugin/moment/moment.min.js", function(){
		loadScript("js/plugin/fullcalendar/jquery.fullcalendar.min.js", pagefunction);
	});



</script>
