#{extends 'main.html' /}
#{set title:'List' /}

<table>
	<thead>
		<tr>
			<th class="name">Name</th>
			<th class="firstname">First name</th>
			<th class="birthdate">Birth date</th>
			<th class="email">Email</th>
			<th class="edit"></th>
		</tr>
	</thead>
	<tbody>
	    #{list contacts, as:'contact'}
	    <tr class="contact" contactId="${contact.id}" draggable="true">
   			<td id="name-${contact.id}">${contact.name}</td>
   			<td id="firstname-${contact.id}">${contact.firstname}</td>
   			<td id="birthdate-${contact.id}">${contact.birthdate?.format('yyyy-MM-dd')}</td>
   			<td id="email-${contact.id}">${contact.email}</td>
   			<td><a href="@{form(contact.id)}">&gt;</a></td>
   		</tr>
	    #{/list}
	    <tr>
	        #{form @save()}
	        <td><input type="text" name="contact.name"></td>
	        <td><input type="text" name="contact.firstname"></td>
	        <td><input type="text" name="contact.birthdate"></td>
	        <td><input type="text" name="contact.email"></td>
	        <td><input type="submit" value="+"></td>
	        #{/form}
	    </tr>
	</tbody>
</table>

<script type="text/javascript" charset="utf-8">

    // In place edition
    $(".contact td").editInPlace({
        bg_over: 'transparent',
        callback: function(el, n, o) {
            var m = /([a-z]+)-(\d+)/.exec(el), data = {}
            data['contact.id'] = m[2]
            data['contact.' + m[1]] = n
            
            // Save result
            $.ajax({
                url: '@{save()}',
                type: 'POST',
                data: data,
                success: function() {$('#' + el).html(n)},
                error: function() {$('#' + el).html(o)}
            })
            
            return true
        }
    })
    
    // Drag & Drop
    var dragIcon = document.createElement('img')
    dragIcon.src = '@{'public/images/avatar.png'}'  
    var action = #{jsAction @form(':id') /}    
    var cancel = function cancel(e) {e.preventDefault()}
    
    $('#new')
        .bind('dragover', cancel)
        .bind('dragenter', cancel)
        .bind('drop', function(e) {
            document.location = action({id: e.originalEvent.dataTransfer.getData('contactId')})            
        })
      
    $('[draggable]').bind('dragstart', function(e) {
        e.originalEvent.dataTransfer.setData('contactId', $(this).attr('contactId'));
        e.originalEvent.dataTransfer.setDragImage(dragIcon, 0, -10);
    })
    
</script>