- Prize editor with movable tables. It's still a bit rough, more work needs to be done with turning on /offthings at the right time, but it's all there, and it all works.

This commit is contained in:
dave 2009-09-10 01:23:58 +00:00
parent 8b7a6e14b3
commit aa1d88f7d2
2 changed files with 583 additions and 65 deletions

View File

@ -27,7 +27,7 @@
user_auth_required('committee', 'admin');
switch($_GET['action']) {
case 'getawardinfo':
case 'awardinfo_load':
$id = intval($_GET['id']);
$q=mysql_query("SELECT award_awards.id,
award_awards.name,
@ -69,7 +69,7 @@
$ret['schedule_judges'] = $r['schedule_judges'];
echo json_encode($ret);
exit;
case 'saveawardinfo':
case 'awardinfo_save':
$id=intval($_GET['id']);
$q = "UPDATE award_awards SET
name='".mysql_escape_string(stripslashes($_GET['name']))."',
@ -119,7 +119,7 @@
*/
exit;
case 'geteligibility':
case 'eligibilty_load':
$id = intval($_GET['id']);
//select the current categories that this award is linked to
$reg = array();
@ -136,11 +136,63 @@
echo json_encode($ret);
exit;
case 'orderprizes':
foreach ($_GET['listItem'] as $position => $item) {
$sql[] = "UPDATE `table` SET `position` = $position WHERE `id` = $item";
case 'prize_order':
$order = 0;
foreach ($_GET['prizelist'] as $position=>$id) {
if($id == '') continue;
$order++;
mysql_query("UPDATE `award_prizes` SET `order`='$order' WHERE `id`='$id'");
}
print_r($sql);
echo happy(i18n("Order Updated."));
exit;
case 'prizeinfo_load':
$id = intval($_GET['id']);
$q = mysql_query("SELECT * FROM award_prizes WHERE award_awards_id='$id' ORDER BY `order`");
while($r=mysql_fetch_assoc($q)) {
$ret[] = $r;
}
echo json_encode($ret);
exit;
case 'prize_load':
$id = intval($_GET['id']);
$q = mysql_query("SELECT * FROM award_prizes WHERE id='$id'");
$ret=mysql_fetch_assoc($q);
echo json_encode($ret);
exit;
case 'prize_save':
print_R($_GET);
$id = intval($_GET['id']);
if($id == -1) {
$aaid = intval($_GET['award_awards_id']);
mysql_query("INSERT INTO award_prizes(award_awards_id,year) VALUES ('$aaid','{$config['FAIRYEAR']}');");
$id = mysql_insert_id();
echo happy(i18n("Created new prize"));
}
$q="UPDATE award_prizes SET
prize='".mysql_escape_string(stripslashes($_GET['prize']))."',
cash='".intval($_GET['cash'])."',
scholarship='".intval($_GET['scholarship'])."',
value='".intval($_GET['value'])."',
number='".intval($_GET['number'])."',
excludefromac='".(($_GET['excludefromac']==1)? 1 : 0)."',
trophystudentkeeper='".(($_GET['trophystudentkeeper']==1) ? 1 : 0)."',
trophystudentreturn='".(($_GET['trophystudentreturn']==1) ? 1 : 0)."',
trophyschoolkeeper='".(($_GET['trophyschoolkeeper']==1) ? 1 : 0)."',
trophyschoolreturn='".(($_GET['trophyschoolreturn']==1) ? 1 : 0)."'
WHERE id='$id'";
mysql_query($q);
echo $q;
echo mysql_error();
echo happy(i18n("Prize saved"));
exit;
case 'prize_delete':
$id = intval($_GET['id']);
mysql_query("DELETE FROM award_prizes WHERE id='$id'");
// echo "DELETE FROM award_prizes WHERE id='$id'";
echo happy(i18n("Prize deleted"));
exit;
}
@ -201,6 +253,7 @@
?>
<script type="text/javascript" src="../js/jquery.tablednd_0_5.js"></script>
<script type="text/javascript">
var award_id = 0;
@ -222,7 +275,7 @@ function update_awardinfo()
{
var id = award_id;
// alert("id="+award_id);
$.getJSON("<?=$_SERVER['PHP_SELF']?>?action=getawardinfo&id="+id,
$.getJSON("<?=$_SERVER['PHP_SELF']?>?action=awardinfo_load&id="+id,
function(json){
$("#awardinfo_id").val(json.id);
$("#awardinfo_name").val(json.name);
@ -243,48 +296,126 @@ function update_awardinfo()
function save_awardinfo()
{
$("#awardinfo_info").load("<?$_SERVER['PHP_SELF']?>?action=saveawardinfo", $("#awardinfo").serialize());
$("#awardinfo_info").load("<?$_SERVER['PHP_SELF']?>?action=awardinfo_save", $("#awardinfo").serialize());
return 0;
}
function update_eligibility()
{
var id = award_id;
$.getJSON("<?=$_SERVER['PHP_SELF']?>?action=geteligibility&id="+id,
$.getJSON("<?=$_SERVER['PHP_SELF']?>?action=eligibilty_load&id="+id,
function(json){
$("[name=eligiblecategories]").val(json.categories);
$("[name=eligibledivisions]").val(json.divisions);
});
}
function update_prizeinfo()
{
var id = award_id;
/* This is wasteful, but it saves inlining the code below */
$.getJSON("<?=$_SERVER['PHP_SELF']?>?action=prizeinfo_load&id="+id,
function(json) {
$("#prizelist").html("");
$("#prizelist").append( "<tr><th style=\"width:4em\"><?=i18n("Script Order")?></th>"+
"<th><?=i18n("# Available")?></th>"+
"<th style=\"width: 15em\"><?=i18n("Prize Description")?></th>"+
"<th><?=i18n("Cash")?></th>"+
"<th><?=i18n("Scholarship")?></th>"+
"<th><?=i18n("Value")?></th>"+
"<th><?=i18n("Actions")?></th></tr>");
for( var i in json ) {
var p = json[i];
$("#prizelist").append("<tr id=\""+p.id+"\"><td style=\"text-align:center;\">"+p.order+"</td>"+
"<td style=\"text-align:center;\">"+p.number+"</td>"+
"<td>"+p.prize+"</td>"+
"<td style=\"width:4em; text-align:right; padding-left:2em; padding-right:2em;\">"+p.cash+"</td>"+
"<td style=\"width:4em; text-align:right; padding-left:2em; padding-right:2em;\">"+p.scholarship+"</td>"+
"<td style=\"width:4em; text-align:right; padding-left:2em; padding-right:2em;\">"+p.value+"</td>"+
"<td style=\"text-align:center;\">"+
" <a onclick=\"edit_prize("+p.id+");\" href=\"#\"><img border=\"0\" src=\"<?=$config['SFIABDIRECTORY']?>/images/16/edit.<?=$config['icon_extension']?>\"></a>&nbsp;"+
"<a onclick=\"prize_delete("+p.id+");\" href=\"#\" ><img border=0 src=\"<?=$config['SFIABDIRECTORY']?>/images/16/button_cancel.<?=$config['icon_extension']?>\"></a>"+
"</td></tr>");
}
$("#prizelist").tableDnD({
onDrop: function(table, row) {
var order = $.tableDnD.serialize();
$("#prizeinfo_info").load("<?=$_SERVER['PHP_SELF']?>?action=prize_order&"+order);
update_prizeinfo();
}
});
});
}
function edit_prize(id)
{
$.getJSON("<?=$_SERVER['PHP_SELF']?>?action=prize_load&id="+id,
function(json){
$("#prizeinfo_edit_header").html("<?=i18n("Edit Prize")?>");
$("#prizeinfo_id").val(json.id);
$("#prizeinfo_prize").val(json.prize);
$("#prizeinfo_cash").val(json.cash);
$("#prizeinfo_scholarship").val(json.scholarship);
$("#prizeinfo_value").val(json.value);
$("#prizeinfo_number").val(json.number);
$("#prizeinfo_trophystudentkeeper").val([json.trophystudentkeeper]);
$("#prizeinfo_trophystudentreturn").val([json.trophystudentreturn]);
$("#prizeinfo_trophyschoolreturn").val([json.trophyschoolreturn]);
$("#prizeinfo_trophyschoolkeeper").val([json.trophyschoolkeeper]);
$("#prizeinfo_excludefromac").val([json.excludefromac]);
$(".prizeinfo").removeAttr("disabled");
$("#prizeinfo_save").removeAttr("disabled");
});
}
function prize_save()
{
$("#prizeinfo_info").load("<?$_SERVER['PHP_SELF']?>?action=prize_save", $("#prizeinfo").serialize());
update_prizeinfo();
return 0;
}
function prize_delete(id)
{
var confirm = confirmClick('Are you sure you want to delete this prize?');
if(confirm == true) {
$("#prizeinfo_info").load("<?$_SERVER['PHP_SELF']?>?action=prize_delete&id="+id);
update_prizeinfo();
}
return 0;
}
function prize_create()
{
var id = award_id;
$(".prizeinfo").val("");
$("#prizeinfo_id").val("-1");
$("#prizeinfo_award_awards_id").val(id);
$("#prizeinfo_edit_header").html("<?=i18n("New Prize")?>");
$(".prizeinfo").removeAttr("disabled");
$("#prizeinfo_save").removeAttr("disabled");
}
// When the document is ready set up our sortable with it's inherant function(s)
$(document).ready(function() {
$("#test-list").sortable({
handle : '.handle',
update : function () {
var order = $('#test-list').sortable('serialize');
$("#info").load("<?=$_SERVER['PHP_SELF']?>?action=orderprizes&order="+order);
}
});
$("#popup_editor").dialog({
bgiframe: true,
autoOpen: false,
height: 600,
width: 600,
modal: true,
resizable: false,
draggable: false
});
});
</script>
<?
/* Begin popup */
echo "<div id=\"popup_editor\" title=\"Award Editor\" >";
echo "<div id=\"popup_editor\" title=\"Award Editor\" style=\"display: none\">";
htabs_begin('editortabs', array('awardinfo' => array('label' =>'Award',
'title' => 'Award Info',
@ -294,19 +425,24 @@ htabs_begin('editortabs', array('awardinfo' => array('label' =>'Award',
'callback' => 'update_eligibility'),
'prizes'=> array('label' => 'Prizes',
'title' => 'Prizes',
'callback' => ''),
'callback' => 'update_prizeinfo'),
),'awardinfo');
htabs_tab_begin('awardinfo');
echo "<div id=\"awardinfo_info\"></div> ";
echo "<form id=\"awardinfo\">";
echo "<input type=\"hidden\" name=\"id\" id=\"awardinfo_id\" value=\"0\" />";
echo "<table class=\"tableedit\">\n";
// echo "<tr><td class=\"left\"><hr /></td><td class=\"right\"><hr /></td></tr>\n";
echo "<tr><td class=\"left\">".i18n("Name").":</td><td class=\"right\"><input type=\"text\" id=\"awardinfo_name\" name=\"name\" value=\"Loading...\" size=\"50\" maxlength=\"128\"><script type=\"text/javascript\">translateButton('name');</script></td></tr>\n";
echo "<tr><td class=\"left\">".i18n("Order").":</td><td class=\"right\"><input type=\"text\" id=\"awardinfo_order\" name=\"order\" value=\"\" size=\"5\" maxlength=\"5\" />(".i18n("presentation order").")</td></tr>\n";
echo "<tr><td class=\"left\">".i18n("Sponsor").":</td><td class=\"right\">";
?>
<div id="awardinfo_info"></div>
<form id="awardinfo">
<input type="hidden" name="id" id="awardinfo_id" value="0" />
<table class="tableedit">
<tr><td class="left"><?=i18n("Name")?>:</td>
<td class="right"><input type="text" id="awardinfo_name" name="name" value="Loading..." size="50" maxlength="128">
<script type="text/javascript">translateButton('name');</script>
</td></tr>
<tr><td class="left"><?=i18n("Order")?>:</td>
<td class="right"><input type="text" id="awardinfo_order" name="order" value="" size="5" maxlength="5" />(<?=i18n("presentation order")?>)
</td></tr>
<tr><td class="left"><?=i18n("Sponsor")?>:</td><td class="right">
<?
$sq=mysql_query("SELECT id,organization FROM sponsors ORDER BY organization");
echo "<select id=\"awardinfo_sponsors_id\" name=\"sponsors_id\">";
//only show the "choose a sponsor" option if we are adding,if we are editing, then they must have already chosen one.
@ -314,10 +450,13 @@ htabs_tab_begin('awardinfo');
while($sr=mysql_fetch_object($sq)) {
echo "<option value=\"$sr->id\">".i18n($sr->organization)."</option>";
}
echo "</select></td></tr>";
echo "<tr><td class=\"left\">".i18n("Presenter").":</td><td class=\"right\"><input type=\"text\" id=\"awardinfo_presenter\" name=\"presenter\" value=\"Loading...\" size=\"50\" maxlength=\"128\" /></td></tr>\n";
echo "<tr><td class=\"left\">".i18n("Type").":</td><td class=\"right\">";
?>
</select></td></tr>
<tr><td class="left"><?=i18n("Presenter")?>:</td>
<td class="right"><input type="text" id="awardinfo_presenter" name="presenter" value="Loading..." size="50" maxlength="128" />
</td></tr>
<tr><td class="left"><?=i18n("Type")?>:</td><td class="right">
<?
$tq=mysql_query("SELECT id,type FROM award_types WHERE year='{$config['FAIRYEAR']}' ORDER BY type");
echo "<select id=\"awardinfo_award_types_id\" name=\"award_types_id\">";
//only show the "choose a type" option if we are adding,if we are editing, then they must have already chosen one.
@ -378,60 +517,57 @@ htabs_tab_end();
htabs_tab_begin('prizes');
?>
<div id="prizes_info">Waiting for update</div>
<ul id="test-list">
<li id="listItem_1"><div class="handle">
<strong>Item 1 </strong>with a link to <a href="http://www.google.co.uk/" rel="nofollow">Google</a> </div>
</li>
<li id="listItem_2">
<img src="arrow.png" alt="move" width="16" height="16" class="handle" />
<strong>Item 2</strong>
</li>
<li id="listItem_3">
<img src="arrow.png" alt="move" width="16" height="16" class="handle" />
<strong>Item 3</strong>
</li>
<li id="listItem_4">
<img src="arrow.png" alt="move" width="16" height="16" class="handle" />
<strong>Item 4</strong>
</li>
</ul>
<hr>
<br />
<div id="prizeinfo_info"></div>
<table id="prizelist" class="tableview"> </table>
<br >
* <?=i18n("Click on the Script Order and drag to re-order the prizes")?>
<br >
<hr>
<br /><h2 id="prizeinfo_edit_header">Click on a prize to edit</h2><br />
<form id="prizeinfo">
<input type="hidden" id="prizeinfo_id" name="id" value=""/>
<input type="hidden" id="prizeinfo_award_awards_id" name="award_awards_id" value=""/>
<table class="tableedit">
<tr> <td class="left"><?=i18n("Prize Description")?>:</td>
<td class="right"><input type="text" id="prize" name="prize" value="" size="40" maxlength="128" /><script type="text/javascript">translateButton('prize');</script></td>
<td class="right"><input type="text" id="prizeinfo_prize" class="prizeinfo" name="prize" value="" size="40" maxlength="128" disabled="disabled"/><script type="text/javascript">translateButton('prize');</script></td>
</tr><tr>
<td class="left"><?=i18n("Cash Amount")?> ($):</td>
<td class="right"><input type="text" name="cash" value="" size="10" maxlength="10" /></td>
<td class="right"><input type="text" id="prizeinfo_cash" class="prizeinfo" name="cash" value="" size="10" maxlength="10" disabled="disabled" /></td>
</tr><tr>
<td class="left"><?=i18n("Scholarship Amount")?> ($):</td>
<td class="right"><input type="text" name="scholarship" value="" size="10" maxlength="10" /></td>
<td class="right"><input type="text" id="prizeinfo_scholarship" class="prizeinfo" name="scholarship" value="" size="10" maxlength="10" disabled="disabled" /></td>
</tr><tr>
<td class="left"><?=i18n("Prize Value")?> ($):</td>
<td class="right"><input type="text" name="value" value="" size="10" maxlength="10" /></td>
<td class="right"><input type="text" id="prizeinfo_value" class="prizeinfo" name="value" value="" size="10" maxlength="10" disabled="disabled" /></td>
</tr><tr>
<td class="left"><?=i18n("Number available")?>:</td>
<td class="right"><input type="text" name="number" value="" size="3" maxlength="5" /></td>
<td class="right"><input type="text" id="prizeinfo_number" class="prizeinfo" name="number" value="" size="3" maxlength="5" disabled="disabled" /></td>
</tr><tr>
<td class="left" valign="top"><?=i18n("Plaque/Trophy")?>:</td>
<td class="right">
<table class="tableedit" cols="4">
<tr> <td align="right"><input type="checkbox" name="trophystudentkeeper" value="1"></td>
<tr> <td align="right"><input type="checkbox" id="prizeinfo_trophystudentkeeper" class="prizeinfo" name="trophystudentkeeper" value="1" disabled="disabled"></td>
<td ><?=i18n("Student(s) keeper trophy")?></td>
<td align="right"><input type="checkbox" name="trophystudentreturn" value="1"></td>
<td align="right"><input type="checkbox" id="prizeinfo_trophystudentreturn" class="prizeinfo" name="trophystudentreturn" value="1" disabled="disabled"></td>
<td ><?=i18n("Student(s) annual return/reuse trophy")?></td>
</tr><tr>
<td align="right"><input type="checkbox" name="trophyschoolkeeper" value="1"></td>
<td align="right"><input type="checkbox" id="prizeinfo_trophyschoolkeeper" class="prizeinfo" name="trophyschoolkeeper" value="1" disabled="disabled"></td>
<td><?=i18n("School keeper trophy")?></td>
<td align="right"><input type="checkbox" name="trophyschoolreturn" value="1"></td>
<td align="right"><input type="checkbox" id="prizeinfo_trophyschoolreturn" class="prizeinfo" name="trophyschoolreturn" value="1" disabled="disabled"></td>
<td><?=i18n("School annual return/reuse trophy")?></td>
</tr></table></td>
</tr><tr>
<td class="left"><?=i18n("Awards Ceremony")?>:</td>
<td class="right"><input type="checkbox" name="excludefromac" value="1"><?=i18n("Exclude this prize from the award ceremony script")?></td>
<td class="right"><input type="checkbox" id="prizeinfo_excludefromac" class="prizeinfo" name="excludefromac" value="1" disabled="disabled"><?=i18n("Exclude this prize from the award ceremony script")?></td>
</tr>
</table>
</form>
<br />
<input type="submit" onClick="prize_create();" value="<?=i18n("Create New Prize")?>" />
<input type="submit" id="prizeinfo_save" onClick="prize_save();" value="<?=i18n("Save Prize")?>" disabled="disabled" />
<?
htabs_tab_end();

382
js/jquery.tablednd_0_5.js Normal file
View File

@ -0,0 +1,382 @@
/**
* TableDnD plug-in for JQuery, allows you to drag and drop table rows
* You can set up various options to control how the system will work
* Copyright (c) Denis Howlett <denish@isocra.com>
* Licensed like jQuery, see http://docs.jquery.com/License.
*
* Configuration options:
*
* onDragStyle
* This is the style that is assigned to the row during drag. There are limitations to the styles that can be
* associated with a row (such as you can't assign a border--well you can, but it won't be
* displayed). (So instead consider using onDragClass.) The CSS style to apply is specified as
* a map (as used in the jQuery css(...) function).
* onDropStyle
* This is the style that is assigned to the row when it is dropped. As for onDragStyle, there are limitations
* to what you can do. Also this replaces the original style, so again consider using onDragClass which
* is simply added and then removed on drop.
* onDragClass
* This class is added for the duration of the drag and then removed when the row is dropped. It is more
* flexible than using onDragStyle since it can be inherited by the row cells and other content. The default
* is class is tDnD_whileDrag. So to use the default, simply customise this CSS class in your
* stylesheet.
* onDrop
* Pass a function that will be called when the row is dropped. The function takes 2 parameters: the table
* and the row that was dropped. You can work out the new order of the rows by using
* table.rows.
* onDragStart
* Pass a function that will be called when the user starts dragging. The function takes 2 parameters: the
* table and the row which the user has started to drag.
* onAllowDrop
* Pass a function that will be called as a row is over another row. If the function returns true, allow
* dropping on that row, otherwise not. The function takes 2 parameters: the dragged row and the row under
* the cursor. It returns a boolean: true allows the drop, false doesn't allow it.
* scrollAmount
* This is the number of pixels to scroll if the user moves the mouse cursor to the top or bottom of the
* window. The page should automatically scroll up or down as appropriate (tested in IE6, IE7, Safari, FF2,
* FF3 beta
* dragHandle
* This is the name of a class that you assign to one or more cells in each row that is draggable. If you
* specify this class, then you are responsible for setting cursor: move in the CSS and only these cells
* will have the drag behaviour. If you do not specify a dragHandle, then you get the old behaviour where
* the whole row is draggable.
*
* Other ways to control behaviour:
*
* Add class="nodrop" to any rows for which you don't want to allow dropping, and class="nodrag" to any rows
* that you don't want to be draggable.
*
* Inside the onDrop method you can also call $.tableDnD.serialize() this returns a string of the form
* <tableID>[]=<rowID1>&<tableID>[]=<rowID2> so that you can send this back to the server. The table must have
* an ID as must all the rows.
*
* Other methods:
*
* $("...").tableDnDUpdate()
* Will update all the matching tables, that is it will reapply the mousedown method to the rows (or handle cells).
* This is useful if you have updated the table rows using Ajax and you want to make the table draggable again.
* The table maintains the original configuration (so you don't have to specify it again).
*
* $("...").tableDnDSerialize()
* Will serialize and return the serialized string as above, but for each of the matching tables--so it can be
* called from anywhere and isn't dependent on the currentTable being set up correctly before calling
*
* Known problems:
* - Auto-scoll has some problems with IE7 (it scrolls even when it shouldn't), work-around: set scrollAmount to 0
*
* Version 0.2: 2008-02-20 First public version
* Version 0.3: 2008-02-07 Added onDragStart option
* Made the scroll amount configurable (default is 5 as before)
* Version 0.4: 2008-03-15 Changed the noDrag/noDrop attributes to nodrag/nodrop classes
* Added onAllowDrop to control dropping
* Fixed a bug which meant that you couldn't set the scroll amount in both directions
* Added serialize method
* Version 0.5: 2008-05-16 Changed so that if you specify a dragHandle class it doesn't make the whole row
* draggable
* Improved the serialize method to use a default (and settable) regular expression.
* Added tableDnDupate() and tableDnDSerialize() to be called when you are outside the table
*/
jQuery.tableDnD = {
/** Keep hold of the current table being dragged */
currentTable : null,
/** Keep hold of the current drag object if any */
dragObject: null,
/** The current mouse offset */
mouseOffset: null,
/** Remember the old value of Y so that we don't do too much processing */
oldY: 0,
/** Actually build the structure */
build: function(options) {
// Set up the defaults if any
this.each(function() {
// This is bound to each matching table, set up the defaults and override with user options
this.tableDnDConfig = jQuery.extend({
onDragStyle: null,
onDropStyle: null,
// Add in the default class for whileDragging
onDragClass: "tDnD_whileDrag",
onDrop: null,
onDragStart: null,
scrollAmount: 5,
serializeRegexp: /[^\-]*$/, // The regular expression to use to trim row IDs
serializeParamName: null, // If you want to specify another parameter name instead of the table ID
dragHandle: null // If you give the name of a class here, then only Cells with this class will be draggable
}, options || {});
// Now make the rows draggable
jQuery.tableDnD.makeDraggable(this);
});
// Now we need to capture the mouse up and mouse move event
// We can use bind so that we don't interfere with other event handlers
jQuery(document)
.bind('mousemove', jQuery.tableDnD.mousemove)
.bind('mouseup', jQuery.tableDnD.mouseup);
// Don't break the chain
return this;
},
/** This function makes all the rows on the table draggable apart from those marked as "NoDrag" */
makeDraggable: function(table) {
var config = table.tableDnDConfig;
if (table.tableDnDConfig.dragHandle) {
// We only need to add the event to the specified cells
var cells = jQuery("td."+table.tableDnDConfig.dragHandle, table);
cells.each(function() {
// The cell is bound to "this"
jQuery(this).mousedown(function(ev) {
jQuery.tableDnD.dragObject = this.parentNode;
jQuery.tableDnD.currentTable = table;
jQuery.tableDnD.mouseOffset = jQuery.tableDnD.getMouseOffset(this, ev);
if (config.onDragStart) {
// Call the onDrop method if there is one
config.onDragStart(table, this);
}
return false;
});
})
} else {
// For backwards compatibility, we add the event to the whole row
var rows = jQuery("tr", table); // get all the rows as a wrapped set
rows.each(function() {
// Iterate through each row, the row is bound to "this"
var row = jQuery(this);
if (! row.hasClass("nodrag")) {
row.mousedown(function(ev) {
if (ev.target.tagName == "TD") {
jQuery.tableDnD.dragObject = this;
jQuery.tableDnD.currentTable = table;
jQuery.tableDnD.mouseOffset = jQuery.tableDnD.getMouseOffset(this, ev);
if (config.onDragStart) {
// Call the onDrop method if there is one
config.onDragStart(table, this);
}
return false;
}
}).css("cursor", "move"); // Store the tableDnD object
}
});
}
},
updateTables: function() {
this.each(function() {
// this is now bound to each matching table
if (this.tableDnDConfig) {
jQuery.tableDnD.makeDraggable(this);
}
})
},
/** Get the mouse coordinates from the event (allowing for browser differences) */
mouseCoords: function(ev){
if(ev.pageX || ev.pageY){
return {x:ev.pageX, y:ev.pageY};
}
return {
x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
y:ev.clientY + document.body.scrollTop - document.body.clientTop
};
},
/** Given a target element and a mouse event, get the mouse offset from that element.
To do this we need the element's position and the mouse position */
getMouseOffset: function(target, ev) {
ev = ev || window.event;
var docPos = this.getPosition(target);
var mousePos = this.mouseCoords(ev);
return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
},
/** Get the position of an element by going up the DOM tree and adding up all the offsets */
getPosition: function(e){
var left = 0;
var top = 0;
/** Safari fix -- thanks to Luis Chato for this! */
if (e.offsetHeight == 0) {
/** Safari 2 doesn't correctly grab the offsetTop of a table row
this is detailed here:
http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari/
the solution is likewise noted there, grab the offset of a table cell in the row - the firstChild.
note that firefox will return a text node as a first child, so designing a more thorough
solution may need to take that into account, for now this seems to work in firefox, safari, ie */
e = e.firstChild; // a table cell
}
while (e.offsetParent){
left += e.offsetLeft;
top += e.offsetTop;
e = e.offsetParent;
}
left += e.offsetLeft;
top += e.offsetTop;
return {x:left, y:top};
},
mousemove: function(ev) {
if (jQuery.tableDnD.dragObject == null) {
return;
}
var dragObj = jQuery(jQuery.tableDnD.dragObject);
var config = jQuery.tableDnD.currentTable.tableDnDConfig;
var mousePos = jQuery.tableDnD.mouseCoords(ev);
var y = mousePos.y - jQuery.tableDnD.mouseOffset.y;
//auto scroll the window
var yOffset = window.pageYOffset;
if (document.all) {
// Windows version
//yOffset=document.body.scrollTop;
if (typeof document.compatMode != 'undefined' &&
document.compatMode != 'BackCompat') {
yOffset = document.documentElement.scrollTop;
}
else if (typeof document.body != 'undefined') {
yOffset=document.body.scrollTop;
}
}
if (mousePos.y-yOffset < config.scrollAmount) {
window.scrollBy(0, -config.scrollAmount);
} else {
var windowHeight = window.innerHeight ? window.innerHeight
: document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
if (windowHeight-(mousePos.y-yOffset) < config.scrollAmount) {
window.scrollBy(0, config.scrollAmount);
}
}
if (y != jQuery.tableDnD.oldY) {
// work out if we're going up or down...
var movingDown = y > jQuery.tableDnD.oldY;
// update the old value
jQuery.tableDnD.oldY = y;
// update the style to show we're dragging
if (config.onDragClass) {
dragObj.addClass(config.onDragClass);
} else {
dragObj.css(config.onDragStyle);
}
// If we're over a row then move the dragged row to there so that the user sees the
// effect dynamically
var currentRow = jQuery.tableDnD.findDropTargetRow(dragObj, y);
if (currentRow) {
// TODO worry about what happens when there are multiple TBODIES
if (movingDown && jQuery.tableDnD.dragObject != currentRow) {
jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow.nextSibling);
} else if (! movingDown && jQuery.tableDnD.dragObject != currentRow) {
jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow);
}
}
}
return false;
},
/** We're only worried about the y position really, because we can only move rows up and down */
findDropTargetRow: function(draggedRow, y) {
var rows = jQuery.tableDnD.currentTable.rows;
for (var i=0; i<rows.length; i++) {
var row = rows[i];
var rowY = this.getPosition(row).y;
var rowHeight = parseInt(row.offsetHeight)/2;
if (row.offsetHeight == 0) {
rowY = this.getPosition(row.firstChild).y;
rowHeight = parseInt(row.firstChild.offsetHeight)/2;
}
// Because we always have to insert before, we need to offset the height a bit
if ((y > rowY - rowHeight) && (y < (rowY + rowHeight))) {
// that's the row we're over
// If it's the same as the current row, ignore it
if (row == draggedRow) {return null;}
var config = jQuery.tableDnD.currentTable.tableDnDConfig;
if (config.onAllowDrop) {
if (config.onAllowDrop(draggedRow, row)) {
return row;
} else {
return null;
}
} else {
// If a row has nodrop class, then don't allow dropping (inspired by John Tarr and Famic)
var nodrop = jQuery(row).hasClass("nodrop");
if (! nodrop) {
return row;
} else {
return null;
}
}
return row;
}
}
return null;
},
mouseup: function(e) {
if (jQuery.tableDnD.currentTable && jQuery.tableDnD.dragObject) {
var droppedRow = jQuery.tableDnD.dragObject;
var config = jQuery.tableDnD.currentTable.tableDnDConfig;
// If we have a dragObject, then we need to release it,
// The row will already have been moved to the right place so we just reset stuff
if (config.onDragClass) {
jQuery(droppedRow).removeClass(config.onDragClass);
} else {
jQuery(droppedRow).css(config.onDropStyle);
}
jQuery.tableDnD.dragObject = null;
if (config.onDrop) {
// Call the onDrop method if there is one
config.onDrop(jQuery.tableDnD.currentTable, droppedRow);
}
jQuery.tableDnD.currentTable = null; // let go of the table too
}
},
serialize: function() {
if (jQuery.tableDnD.currentTable) {
return jQuery.tableDnD.serializeTable(jQuery.tableDnD.currentTable);
} else {
return "Error: No Table id set, you need to set an id on your table and every row";
}
},
serializeTable: function(table) {
var result = "";
var tableId = table.id;
var rows = table.rows;
for (var i=0; i<rows.length; i++) {
if (result.length > 0) result += "&";
var rowId = rows[i].id;
if (rowId && rowId && table.tableDnDConfig && table.tableDnDConfig.serializeRegexp) {
rowId = rowId.match(table.tableDnDConfig.serializeRegexp)[0];
}
result += tableId + '[]=' + rowId;
}
return result;
},
serializeTables: function() {
var result = "";
this.each(function() {
// this is now bound to each matching table
result += jQuery.tableDnD.serializeTable(this);
});
return result;
}
}
jQuery.fn.extend(
{
tableDnD : jQuery.tableDnD.build,
tableDnDUpdate : jQuery.tableDnD.updateTables,
tableDnDSerialize: jQuery.tableDnD.serializeTables
}
);