{% extends "dashboard/base_site.html" %}
{% load i18n %}
{% load staticfiles i18n %}
{% load admin_urls %}






{% block extrastyle %}
	<link rel="stylesheet" href="{% static "radio/css/bootstrap.min.css" %}" type="text/css" />
{% endblock %}


{% block extrahead %}
	<meta charset='utf-8' />
	<link rel="stylesheet" href="{% static "fullcalendar/fullcalendar.min.css" %}" type="text/css" />
	<link rel="stylesheet" href="{% static "fullcalendar/fullcalendar.print.css" %}" type="text/css"  media='print'/>
	<link rel="stylesheet" href="{% static "radio/css/calendar.css" %}" type="text/css"/>
	<script src="{% static "lib/moment.min.js" %}" type="text/javascript"></script>
	<script src="{% static "lib/jquery.min.js" %}" type="text/javascript"></script>
	<script src="{% static "lib/jquery-ui.custom.min.js" %}" type="text/javascript"></script>
	<script src="{% static "radio/js/bootstrap.min.js" %}" type="text/javascript"></script>
	<script src="{% static "radio/js/jquery.form.min.js" %}" type="text/javascript"></script>
	<script src="{% static "fullcalendar/fullcalendar.min.js" %}" type="text/javascript"></script>
	<script src="{% static "fullcalendar/lang-all.js" %}" type="text/javascript"></script>
	<script>
	function loading(bool) {
	    if (bool) {
	        $('#loading').show();
	        $('#loading-ok').hide();
	    } else {
	        $('#loading').hide();
	        $('#loading-ok').show();

	    }
	}

	 // using jQuery
	function getCookie(name) {
	    var cookieValue = null;
	    if (document.cookie && document.cookie != '') {
	        var cookies = document.cookie.split(';');
	        for (var i = 0; i < cookies.length; i++) {
	            var cookie = jQuery.trim(cookies[i]);
	            // Does this cookie string begin with the name we want?
	            if (cookie.substring(0, name.length + 1) == (name + '=')) {
	                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
	                break;
	            }
	        }
	    }
	    return cookieValue;
	}
	var csrftoken = getCookie('csrftoken');

	function csrfSafeMethod(method) {
	    // these HTTP methods do not require CSRF protection
	    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
	}

	function sameOrigin(url) {
	    // test that a given url is a same-origin URL
	    // url could be relative or scheme relative or absolute
	    var host = document.location.host; // host + port
	    var protocol = document.location.protocol;
	    var sr_origin = '//' + host;
	    var origin = protocol + sr_origin;
	    // Allow absolute or scheme relative URLs to same origin
	    return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
	        (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
	    // or any other URL that isn't scheme relative or absolute i.e relative.
	    !(/^(\/\/|http:|https:).*/.test(url));
	}
	$.ajaxSetup({
	    beforeSend: function (xhr, settings) {
	        if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
	            // Send the token to same-origin, relative URLs only.
	            // Send the token only if the method warrants CSRF protection
	            // Using the CSRFToken value acquired earlier
	            xhr.setRequestHeader("X-CSRFToken", csrftoken);
	        }
	        loading(true);
	    },
	    complete: function (data) {
			loading(false);
		}
	});


	$(document).ready(function () {

	    var calendar = $('#calendar').fullCalendar({
	    	height: 'auto',
	    	contentHeight: 'auto',
	    	aspectRatio: 1.35,
	        lang: '{{language}}',
	        eventDurationEditable: false,
	        eventStartEditable: true,
	        allDaySlot: false,
	        firstDay: {{first_day}},
	        defaultDate: '2011-08-0{{first_day}}',
	        axisFormat: 'HH:mm',
	        timezone: false,
	        scrollTime: '{{scroll_time}}',
	        lazyFetching: false,
	        header: {
	            left: '',
	            center: '',
	            right: ''
	        },
	        columnFormat: {
	            month: 'ddd',    // Mon
	            week: 'dddd',	 // Monday
	            day: 'dddd'     
	        },
	        defaultView: 'agendaWeek',

	        events: {
	            url: 'all_events/',
	            data: function() { // a function that returns an object
	                return {
	                	scheduleBoardId: $( "#select-board" ).val(),
	                	firstDay: {{first_day}}
	                };
	            },
	            
	            error: function() {
	                alert('{% trans "There was an error while fetching programmes" %}');
	            },
	        },
	        droppable: true, // this allows things to be dropped onto the calendar !!!
	        drop: function (date) { // 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.end = moment(date).add('minutes', copiedEventObject.runtime);

	            // create the event 
	            $.ajax({
	                type: "POST",
	                url: "create_schedule",
	                data: 'programmeId=' + copiedEventObject.programmeId + '&start=' 
	                + moment(copiedEventObject.start.utc().toString().slice(0, copiedEventObject.start.utc().toString().indexOf("GMT")), 'ddd MMM DD YYYY HH:mm:ss')
	                + '&type=' +$("input[name='group1']:checked").val()
	                + '&scheduleBoardId=' +$( "#select-board" ).val(),
	                success: function (res) {
	                    if (res.error) {
	                        alert('{% trans "There was an error while creating schedule" %}: ' + res.error);
	                    } else {
	                    	response =  res.response
	                        copiedEventObject.id = response.scheduleId;
	                        copiedEventObject.backgroundColor = response.backgroundColor;
	                        copiedEventObject.textColor = response.textColor;
	                        copiedEventObject.type = response.type;
	                        // 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);
	                    }
	                },
	                error: function (data) {
	                    revertFunc();
	                    alert('{% trans "There was an error while creating schedule" %}');
	                },
	            });

	        },
	        
	        //remove all events (dropped events)
	        viewRender: function( view, element ){
	        	$('#calendar').fullCalendar( 'removeEvents')
	        },

	        eventClick: function (calEvent, jsEvent, view) {
	            // change the border color just for fun
	            // $(this).css('border-color', 'red');
	            
	            if (calEvent.type == 'B') {
		            $(".modal").load('change_broadcast/' + calEvent.id + '/', function(result){
		            	 $('#modal').modal('show');
		        	});
		            
		            jsEvent.preventDefault();
				}
	            
	        },


	        eventDrop: function (event, delta, revertFunc) {
	            $.ajax({
	                type: "POST",
	                url: "change_event",
	                data: 'id=' + event.id + '&start=' + moment(event.start.utc().toString().slice(0, event.start.utc().toString().indexOf("GMT")), 'ddd MMM DD YYYY HH:mm:ss'),
	                success: function (res) {
	                    if (res.error) {
	                        revertFunc();
	                        alert('{% trans "There was an error in the request" %} ' + res.error);
	                    }
	                },
	                error: function (data) {
	                    revertFunc();
	                    alert('{% trans "There was an error in the request" %}');
	                },
	            });
	        },
	        
	        eventDragStop: function(event, jsEvent, ui, view) { 
	            //console.log(event.id);
	             if (isElemOverDiv(jsEvent, $('div#external-events'))) {
	            	 $.ajax({
	                     type: "POST",
	                     url: "delete_schedule",
	                     data: 'scheduleId=' + event.id,
	                     success: function (res) {
	                         if (res.error) {
	                             alert("Error en la peticion " + res.error);
	                         } else {
	                        	 calendar.fullCalendar('removeEvents', event.id);
	                         }
	                     },
	                     error: function (data) {
	                         revertFunc();
	                         alert('{% trans "There was an error in the request" %}');
	                     },
	                 });
	             }
	         },

	        loading: function (bool) {
	            loading(bool)
	        }



	    })

	});

	function reloadProgrammes() {
		$('#external-events').empty();
		 $.ajax({
	         type: "POST",
	         url: "programmes",
	         data: 'scheduleBoardId=' + $( "#select-board" ).val(),
	         success: function (res) {
	             if (res.error) {
	                 alert('{% trans "There was an error in the request" %}' + res.error);
	             } else {
	             	info =  res.response
	             	for (var numero = 0; numero < info.length; numero++) {
	                    var eventObjectFromDB = info[numero];
	                    var eventToExternalEvents = {
	                        "title": eventObjectFromDB.title,
	                        "runtime": eventObjectFromDB.runtime,
	                        "programmeId": eventObjectFromDB.programmeId,
	                        "editable": true
	                    };

	                    $('#external-events').append("<div class='external-event' id='mec" + numero + "'>" + eventToExternalEvents.title + "</div>");
	                    var eventObject2 = {
	                        title: $.trim(eventToExternalEvents.title), // use the element's text as the event title
	                        runtime: eventToExternalEvents.runtime,
	                        programmeId: eventToExternalEvents.programmeId,
	                    };
	                    $('#mec' + numero).data('eventObject', eventObject2);
	                    
	                    $('.external-event').draggable({
	                        zIndex: 999,
	                        revert: true, // will cause the event to go back to its
	                        revertDuration: 0
	                    });
	                    //$('#calendar').fullCalendar('refetchEvents');
	                }
	             }
	         },
	         error: function (data) {
	             revertFunc();
	             alert('{% trans "There was an error in the request" %}');
	         },
	     });
	}

	window.onload = function () {
		reloadProgrammes();
		$( "#select-board" ).change(function() {
			$('#calendar').fullCalendar( 'removeEvents')
			$('#calendar').fullCalendar( 'refetchEvents')
			reloadProgrammes()
		});
	}


	var isElemOverDiv = function(draggedItem, dropArea) {
	    var draggedX = draggedItem.pageX;
	    var draggedY = draggedItem.pageY;

	    var b = $(dropArea);
	    var limitX = parseInt(b.offset().left) + parseInt(b.outerWidth());
	    var limitY = parseInt(b.offset().top) + parseInt(b.outerHeight());

	    // Compare
	    if ( limitY >=   parseInt(draggedY) 
	        && limitX >=   parseInt(draggedX) ) 
	    { 
	        return true; 
	    }
	    return false;
	}


	</script>
{% endblock %}


{% block content %}
	<h1>{% trans "Schedule Editor"|upper %}</h1>
	
	<div id='loading' class="alert alert-warning">{% trans "Loading" %}...</div>
	<div id='loading-ok' class="alert alert-success">{% trans "All changes saved" %}</div>
	
	<div class="row">
		<div class="col-xs-2">
		</div>
		 <div class="col-xs-8">
			<select id='select-board' class="form-control">
				{% for scheduleBoard in scheduleBoards %}
				<option value="{{scheduleBoard.id}}"
					{% if scheduleBoard == current_scheduleBoard %}
						selected="selected"
					{% endif %}>
					{{scheduleBoard.name}}
				</option>
				{% endfor %}
			</select>
		</div>
	</div>
	<br >
	  <div>
	    <div class="col-xs-2">
	      <!--Sidebar content-->
	      
			<div id='external-events'></div>
			<div>
				<h4>{% trans "Programme type" %}</h4>
				<input type="radio" name="group1" value="L" checked>{% trans "live" %}<br>
				<input type="radio" name="group1" value="B">{% trans "broadcast" %}<br>
				<input type="radio" name="group1" value="S">{% trans "broadcast syndication" %}<br>
			</div>
	      
	      
	    </div>
	    <div class="col-xs-10" id='calendar'></div>
	  </div>



<!-- Modal -->
<div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->



{% endblock %}

