<?
/*
require_once "api.php";
$boardid = r('boardid');

$boards = getboards();
$cards = getmycards();
//we($mycards);
//$lists = getlists($boardid);
//$cards = getcards($boardid,array_keys($lists));
$users = getusers();

$list = array();
foreach($cards as $cid=>$card){
	$borderid = $card['boardId'];
	if($list[$borderid])continue;
	if(!$boards[ $borderid ]['title'])continue;
	$list[ $borderid ] = array(
		"archived"=>false,
		"title"=> $boards[ $borderid ]['title'],
		"_id"=> $borderid
	);
}

$DATA = array(
	'boardid' => $boardid,
	'boards' => $boards,
	'lists' => $list,
	'cards' => $cards,
	'users'=>$users
);
*/
?>

<!DOCTYPE html>
<html>
<head>
    <? require_once "header.html"; ?>
    <link rel="stylesheet" type="text/css" href="css/fullcalendar.css">
    <script src='fullcalendarjs/jquery-ui-1.10.2.custom.min.js'></script>
    <script src='fullcalendarjs/fullcalendar.min.js'></script>
</head>
<body>
<? require_once "leftbar.html"; ?>
<? require_once "projectheader.html"; ?>

<button id="opener">打开对话框</button>
<div id="dialog" title="事件管理">
	<form class=''>
		<label>输入事件内容 (<span id="dialog_date"></span>)</label><br/><br/>
		<input class='form-control' id='title' autocomplete=off type=text value='' style="line-height:25px;width:450px" />
	</form>
</div>
 
<script>
$( "#dialog" ).dialog({ autoOpen: false,modal: true,
minWidth: 500,
buttons: [
    {
      text: "保存",
      click: function() {
        //$( this ).dialog( "close" );
      }
    },
	{
      text: "关闭",
      click: function() {
        $( this ).dialog( "close" );
      }
    }
  ]
  
  });
</script>

<div id="wrap">
    <div id="calendar" style="margin:15px;">

    </div>
</div>

<script type="text/javascript">

	var canEdit = (MYINFO && MYINFO.extData && MYINFO.extData.admin)?true:false;
	var ORGID = "";
    $(function () {
        $('.projectheader h1').html('公共事件');

        var date = new Date();
        var d = date.getDate();
        var m = date.getMonth();
        var y = date.getFullYear();
		calendar = $('#calendar');
        $('#calendar').fullCalendar({
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'month,agendaWeek,agendaDay'
            },
            firstDay: 1,
            aspectRatio: 2.4,
            editable: false,
            timeFormat: 'H:mm',
            axisFormat: 'H:mm',

            events: function (start, end, callback) {
                var _start = Math.round(start.getTime() / 1000);
                var _end = Math.round(end.getTime() / 1000);

                $.ajax({
                    url: './?app=api&apiact=getEvents&orgid='+(ORGID||""),
                    dataType: 'json',
                    data: {
                        start: _start,
                        end: _end,
                    },
                    success: function (doc) {
                        callback(doc);
                    }
                });
            },

            eventRender: function (event, element) {
                //element.html('<i class="eventboardtitle">' + event.boardtitle + "</i> " + event.title.substr(0, 40)).css('background', //fmtColorByBID(event.boardid));
				element.html(event.title);
            },
			editable: canEdit, //canEdit?
			
			eventDrop: function(event,dayDelta,minuteDelta,allDay,revertFunc) {
				
				dict={id:event._id};
				dict.start = $.fullCalendar.formatDate(event.start,'yyyy-MM-dd');
				dict.end =  $.fullCalendar.formatDate(event.end,'yyyy-MM-dd');
				console.log(dict);
				//return;
				//loading.show();
				$.post('./?app=api&apiact=movepmcalendar',dict,function(txt){
					//loading.hide();
					if(txt=='1'){
						calendar.fullCalendar('refetchEvents'); 
					}
				});
				return false;
			},
			selectable: true,
			selectHelper: true,
			select: function(start, end, allDay) {
				if(!canEdit)return;

				dict = {};
				console.log('select',start, end, allDay);

				dict.start = $.fullCalendar.formatDate(start,'yyyy-MM-dd');
				dict.end =  $.fullCalendar.formatDate(end,'yyyy-MM-dd');

				showEventInfo(dict.start,{
					"save" : {
						"label" : "保存",
						"className" : "btn-sm btn-success",
						"callback": function() {
							dict.game = $('#game').val();
							dict.allday = 1;

							dict.title = $('#title').val();
							dict.event = $('#event').val();

							if(dict.game=='' || dict.title=='')return;
							
							$.post('./?app=api&apiact=newcalendar',dict,function(txt){
								if(txt=='1'){
									calendar.fullCalendar('refetchEvents'); 
								}
							});
							$('#dialog').dialog( "close" );
						}
					} ,
					"close" : {
						"label" : "关闭",
						"className" : "btn-sm",
						"callback" : function(){
							$('#dialog').dialog( "close" );
						}
					} 
				},'new');
				calendar.fullCalendar('unselect');
			}
			,
			eventClick: function(calEvent, jsEvent, view) {
				if(!canEdit)return;
				
				console.log('calEvent',calEvent,jsEvent,view);

				dict={};

				/*
				$.post('./?app=pmcalendar&act=getEventByid',{id:calEvent.id},function(txt){
					var j = JSON.parse(txt);
					dict.start = j.start;
					dict.end = j.end;
					dict.id = calEvent.id;
					$('#game').val(j.game);
					$('#hour').val(j.shour);
					$('#min').val(j.smin);
					$('#event').val(j.event);
					$('#title').val(j.title);
					hourChange($('#hour'));
				});
				*/


				var dstr = $.fullCalendar.formatDate(calEvent.start,'yyyy-MM-dd');

				dict.start = dstr;
				dict.end = dstr;
				dict.id = calEvent._id;
				$('#title').val(calEvent.title);

				console.log('dict',dict);


				showEventInfo(dstr,{
					"save" : {
						"label" : "保存",
						"className" : "btn-sm btn-success",
						"callback": function() {
							
							//dict.game = $('#game').val();
							//dict.allday = 1;

							//dict.event = $('#event').val();
							dict.title = $('#title').val();

							//if(dict.game=='' || dict.event=='')return;
							
							//loading.show();
							$.post('./?app=api&apiact=modipmcalendar',dict,function(txt){
								//loading.hide();
								if(txt=='1'){
									calendar.fullCalendar('refetchEvents');
								}
							});
							$('#dialog').dialog( "close" );
						}
					} ,
					"delete" : {
						"label" : "删除事件",
						"className" : "btn-sm btn-danger",
						"callback": function() {
							if(confirm('确认要【删除】这个事件吗？')){
								//loading.show();
								$.post('./?app=api&apiact=delpmcalendar',{id:calEvent._id},function(txt){
									//loading.hide();
									if(txt=='1'){
										calendar.fullCalendar('refetchEvents');
									}
								});
							}
							$('#dialog').dialog( "close" );
						}
					} ,
					
					"close" : {
						"label" : "关闭",
						"className" : "btn-sm",
						"callback" : function(){
							$('#dialog').dialog( "close" );
						}
					} 
				},'modify');
			}
        });

    });
	
	/*
    var bid2color = {};

    function fmtColorByBID(bid) {
        if (!bid2color[bid]) bid2color[bid] = getRandomSafeColor();
        return bid2color[bid];
    }

    function getRandomSafeColor() {
        var base = ['00', '11', '22', '33', '44', '55', '66', '77', '88', '99', 'aa', 'bb', 'cc'];//基础色代码
        var res = '#';
        for (var i = 0; i < 3; i++) {
            res += base[Math.floor(Math.random() * base.length)];
        }
        return res;
    }
	*/



function showEventInfo(start,btns,stype){
	$('#dialog_date').html(start);

	var nbtns = {};
	for(var id in btns){
		nbtns[ btns[id].label ] = btns[id].callback;
	}

	$('#dialog').dialog('option', 'buttons', nbtns);
	$( "#dialog" ).dialog( "open" );
	/*
	var form = $("<form class=''><label>选择游戏和事件类型 ("+ start +")</label><div class='space-1'></div></form>");
	form.append('&nbsp<select id="event"><option value="打包">打包</option><option value="版本更新">版本更新</option><option value="修复外网">修复外网</option><option value="上线">上线</option><option value="节点">节点</option></select>');
	form.append("<div class='space-5'></div><label for='form-field-mask-1'>事件内容</label><input class='form-control' id='title' autocomplete=off type=text value='' /> ");
	
	var div = bootbox.dialog({
		message: form,
		buttons: btns
	});
	

	form.on('submit', function(){
		//calEvent.title = form.find("input[type=text]").val();
		//calendar.fullCalendar('updateEvent', calEvent);
		div.modal("hide");
		return false;
	});
	*/
}

$('#selectorg').on('change',function(){
	ORGID = $(this).val();
	console.log(ORGID);
	calendar.fullCalendar('refetchEvents');
});

</script>

<style>
    .fc-week .fc-sun{
        color: red;
    }
    .fc-week .fc-sat{
        color: red;
    }



</style>

</body>
</html>


