summaryrefslogtreecommitdiff
path: root/modules/organize/js/organize.js
blob: 9bfa71117b40a3709f366dc0bfe2844ad984b587 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
/*
 * @todo Trap resize of dialog and resize the child areas (tree, grid and edit form)
 */
var url;
var paused = false;
var task = null;
var transitItems = [];
var heightMicroThumbPanel;

// **************************************************************************
// JQuery UI Widgets
// Draggable
var draggable = {
  cancel: ".gMicroThumbContainer:not(.ui-selected)",
  handle: ".gMicroThumbContainer.ui-selected",
  revert: true,
  zindex: 2000,
  helper: function(event, ui) {
    $("#gMicroThumbPanel").append("<div id=\"gDragHelper\"><ul></ul></div>");
    var beginTop = event.pageY;
    var beginLeft = event.pageX;
    var zindex = $(".gMicroThumbContainer").draggable("option", "zindex");
    $("#gDragHelper").css('top', event.pageY - 22.5);
    $("#gDragHelper").css('left', event.pageX + 22.5);
    var placeHolder = $(this).clone();
    $(placeHolder).attr("id", "gPlaceHolder");
    $(placeHolder).css("visibility", "hidden");
    $(placeHolder).removeClass("ui-selected");
    $(placeHolder).removeClass("ui-draggable");
    $(this).after(placeHolder);

    $("li.ui-selected").each(function(i) {
      var clone = $(this).clone();
      $(clone).attr("id", "drag_clone_" + $(this).attr("ref"));
      $("#gDragHelper ul").append(clone);
      $(clone).css("position", "absolute");
      $(clone).css("top", beginTop);
      $(clone).css("left", beginLeft);
      $(clone).css("z-index", zindex--);
      $(this).hide();

      var children = $(clone).find(".gMicroThumb .gThumbnail");
      var width = new String(children.css("width")).replace(/[^0-9]/g,"") * .5;
      var height = new String(children.css("height")).replace(/[^0-9]/g,"") * .5;
      var marginTop = new String(children.css("margin-top")).replace(/[^\.0-9]/g,"") * .5;
      children.attr("width", width);
      children.attr("height", height);
      children.css("margin-top", marginTop);
      if (i < 9) {
        beginTop -= 5;
        beginLeft += 5;
      }
    });
    return $("#gDragHelper");
  },
  stop: function(event, ui) {
    $("#gDragHelper li").each(function(i) {
      $("#thumb_" + $(this).attr("ref")).show();
    });
    $(".gMicroThumbContainer.ui-selected").css("z-index", null);
    $("#gDragHelper").remove();
    $("#gPlaceHolder").remove();
  }
};

// Thumbnail Grid Droppable
var thumbDroppable =  {
  tolerance: "pointer",
  over: function(event, ui) {
    $("#gPlaceHolder").show();
  },
  out:  function(event, ui) {
    $("#gPlaceHolder").hide();
  },
  drop: function(event, ui) {
    $("#gDragHelper").hide();
    $("#gPlaceHolder").hide();
    var newOrder = "";
    $("#gMicroThumbGrid .gMicroThumbContainer").each(function(i) {
      if ($(this).attr("id") == "gPlaceHolder") {
        $("#gDragHelper li").each(function(i) {
          newOrder += "&item[]=" + $(this).attr("ref");
        });
      } else if ($(this).css("display") != "none") {
        newOrder += "&item[]=" + $(this).attr("ref");
      } else  {
        // If its not displayed then its one of the ones being moved so ignore.
      }
    });
    $("#gDragHelper li").each(function(i) {
      $("#gPlaceHolder").before($("#thumb_" + $(this).attr("ref")).show());
    });
    $.ajax({
      data: newOrder,
      dataType: "json",
      success: operationCallback,
      type: "POST",
      url: get_url("organize/startTask/rearrange", {item_id: item_id})
    });
  }
};

// Album Tree Droppable
var treeDroppable =  {
  tolerance: "pointer",
  greedy: true,
  hoverClass: "gBranchDroppable",
  drop: function(event, ui) {
    $("#gDragHelper").hide();
    var targetItemId = $(this).attr("ref");
    if ($(this).hasClass("gBranchSelected")) {
      $("#gMessage").empty().append(INVALID_DROP_TARGET);
      ui.draggable.trigger("stop", event);
      return false;
    }
    var postData = serializeItemIds("#gDragHelper li");
    var okToMove = true;
    $("#gDragHelper li").each(function(i) {
      okToMove &= targetItemId != $(this).attr("ref");
    });
    if (!okToMove) {
      $("#gMessage").empty().append(INVALID_DROP_TARGET);
      ui.draggable.trigger("stop", event);
      return false;
    }
    $("#gDragHelper li").each(function(i) {
      $("#thumb_" + $(this).attr("ref")).remove();
    });
    $.ajax({
      data: postData,
      dataType: "json",
      success: operationCallback,
      type: "POST",
      url: get_url("organize/startTask/move", {item_id: targetItemId})
    });
    return true;
  }
};

// Selectable
var selectable = {
  filter: ".gMicroThumbContainer",
  selected: function(event, ui) {
    setDrawerButtonState();
  },
  unselected: function(event, ui) {
    setDrawerButtonState();
  }
};

// **************************************************************************
// Event Handlers
// MicroThumbContainer mouseup
var onMicroThumbContainerMouseup = function(event) {
  // For simplicity always remove the ui-selected class.  If it was unselected
  // it will get added back
  $(this).removeClass("ui-selected");

  setDrawerButtonState();
};

// MicroThumbContainer mousemove
var onMicroThumbContainerMousemove = function(event) {
  if ($("#gDragHelper").length > 0 && $(this).attr("id") != "gPlaceHolder") {
    if (event.pageX < $(this).offset().left + $(this).width() / 2) {
      $(this).before($("#gPlaceHolder"));
    } else {
      $(this).after($("#gPlaceHolder"));
    }
    var container = $("#gMicroThumbPanel").get(0);
    var scrollHeight = container.scrollHeight;
    var scrollTop = container.scrollTop;
    var height = $(container).height();
    if (event.pageY > height + scrollTop) {
      container.scrollTop = this.offsetTop;
    } else if (event.pageY < scrollTop) {
      container.scrollTop -= height;
    }
  }
};

// Handle click events on the buttons on the drawer handle
function drawerHandleButtonsClick(event) {
  event.preventDefault();
  if (!$(this).attr("disabled")) {
    var operation = $(this).attr("ref");
    switch (operation) {
    case "edit":
      $("#gOrganizeEditDrawerPanel").animate(
        {"height": "toggle", "display": "block"},
        {duration: "fast",
          step: function() {
            $("#gMicroThumbPanel").height(heightMicroThumbPanel - $(this).height());
          }
      });
      break;
    case "select-all":
      $(".gMicroThumbContainer").addClass("ui-selected");
      $("#gMicroThumbSelectAll").hide();
      $("#gMicroThumbUnselectAll").show();
      break;
    case "unselect-all":
      $(".gMicroThumbContainer").removeClass("ui-selected");
      $("#gMicroThumbSelectAll").show();
      $("#gMicroThumbUnselectAll").hide();
      break;
    case "close":
      $("#gDialog").dialog("close");
      break;
    default:
      var postData = serializeItemIds("#gMicroThumbPanel li.ui-selected");
      $.ajax({
        data: postData,
        dataType: "json",
        success: operationCallback,
        type: "POST",
        url: get_url("organize/startTask/" + operation, {item_id: item_id})
      });
      break;
    }
  }
};

// **************************************************************************
// AJAX Callbacks
// MicroThumbContainer click
var getMicroThumbsCallback = function(json, textStatus) {
  if (json.count > 0) {
    $("#gMicroThumbGrid").append(json.data);
    retrieveMicroThumbs();
    $(".gMicroThumbContainer").mouseup(onMicroThumbContainerMouseup);
    $(".gMicroThumbContainer").mousemove(onMicroThumbContainerMousemove);
    $(".gMicroThumbContainer").draggable(draggable);
  }
};

var operationCallback = function (data, textStatus) {
  var done = false;
  if (!paused) {
    createProgressDialog(data.runningMsg);
    task = data.task;
    task.pauseMsg = data.pauseMsg;
    task.resumeMsg = data.resumeMsg;
    done = data.task.done;
  }
  $(".gMicroThumbContainer").draggable("disable");
  paused = false;
  while (!done && !paused) {
    $.ajax({async: false,
      success: function(data, textStatus) {
        $(".gProgressBar").progressbar("value", data.task.percent_complete);
        done = data.task.done;
        if (data.task.post_process.reload) {
          $.each(data.task.post_process.reload, function() {
            var selector = "#gMicroThumb-" + this.id + " img";
            $(selector).attr("height", this.height);
            $(selector).attr("width", this.width);
            $(selector).attr("src", this.src);
            $(selector).css("margin-top", this.marginTop);
          });
        }
        if (data.task.post_process.remove) {
          $.each(data.task.post_process.remove, function() {
            $("#thumb_" + this.id).remove();
          });
        }
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        paused = true;
        displayAjaxError(XMLHttpRequest.responseText);
      },
      dataType: "json",
      type: "POST",
      url: get_url("organize/runTask", {task_id: task.id})
    });
  }
  if (!paused) {
    $("#gOrganizeProgressDialog").dialog("destroy").remove();
    $.ajax({async: false,
      success: function(data, textStatus) {
        setDrawerButtonState();
        task = null;
        $("#gMessage").empty().append("<div class='gSuccess'>" + data.task.status + "</div>");
      },
      dataType: "json",
      type: "POST",
      url: get_url("organize/finishTask", {task_id: task.id})
    });
  }
  $(".gMicroThumbContainer").draggable("enable");
};

// **************************************************************************

/**
 * Dynamically initialize the organize dialog when it is displayed
 */
function organize_dialog_init() {
  var size = getViewportSize();
  heightMicroThumbPanel = size.height() - 100;
  var width = size.width() - 100;

  // Deal with ui.jquery bug: http://dev.jqueryui.com/ticket/4475
  $(".sf-menu li.sfHover ul").css("z-index", 70);

  $("#gDialog").dialog("option", "width", width);
  $("#gDialog").dialog("option", "height", heightMicroThumbPanel);

  $("#gDialog").dialog("open");
  if ($("#gDialog h1").length) {
    $("#gDialog").dialog('option', 'title', $("#gDialog h1:eq(0)").html());
  } else if ($("#gDialog fieldset legend").length) {
    $("#gDialog").dialog('option', 'title', $("#gDialog fieldset legend:eq(0)").html());
  }

  $("#gDialog").bind("organize_close", function(target) {
    document.location.reload();
  });

  heightMicroThumbPanel -= 2 * parseFloat($("#gDialog").css("padding-top"));
  heightMicroThumbPanel -= 2 * parseFloat($("#gDialog").css("padding-bottom"));
  heightMicroThumbPanel -= $("#gMicroThumbPanel").position().top;
  heightMicroThumbPanel -= $("#gDialog #ft").height();
  heightMicroThumbPanel -= $("#gOrganizeEditDrawerHandle").height();
  heightMicroThumbPanel = Math.round(heightMicroThumbPanel);

  $("#gMicroThumbPanel").height(heightMicroThumbPanel);
  $("#gOrganizeTreeContainer").height(heightMicroThumbPanel);

  $(".gOrganizeBranch .ui-icon").click(organizeToggleChildren);
  $(".gBranchText").droppable(treeDroppable);
  $(".gBranchText").click(organizeOpenFolder);
  retrieveMicroThumbs(item_id);
  //showLoading("#gDialog");

  $("#gMicroThumbPanel").droppable(thumbDroppable);
  $("#gMicroThumbPanel").selectable(selectable);
  $("#gOrganizeEditDrawerHandle a").click(drawerHandleButtonsClick);
}

function retrieveMicroThumbs() {
  var offset = $("#gMicroThumbGrid li").length;
  if (url == null) {
    var grid_width = $("#gMicroThumbPanel").width();
    url = $("#gMicroThumbPanel").attr("ref");
    url = url.replace("__WIDTH__", grid_width);
    url = url.replace("__HEIGHT__", heightMicroThumbPanel);
  }
  var url_data = url.replace("__OFFSET__", offset);
  url_data = url_data.replace("__ITEM_ID__", item_id);
  $.getJSON(url_data, getMicroThumbsCallback);
}

function organizeToggleChildren(event) {
  var id = $(this).attr("ref");
  var span_children = $("#gOrganizeChildren-" + id);
  if ($(this).hasClass("ui-icon-plus")) {
    $(this).removeClass("ui-icon-plus");
    $(this).addClass("ui-icon-minus");
    $("#gOrganizeChildren-" + id).removeClass("gBranchCollapsed");
  } else {
    $(this).removeClass("ui-icon-minus");
    $(this).addClass("ui-icon-plus");
    $("#gOrganizeChildren-" + id).addClass("gBranchCollapsed");
  }
  event.preventDefault();
}

function organizeOpenFolder(event) {
  var selected = $(".gBranchSelected");
  if ($(selected).attr("id") != $(this).attr("id")) {
    $(selected).removeClass("gBranchSelected");
    $(this).addClass("gBranchSelected");
    item_id = $(this).attr("ref");
    $("#gMicroThumbGrid").empty();
    retrieveMicroThumbs();
  }
  event.preventDefault();
}

function get_url(uri, parms) {
  var url = rearrangeUrl;
  url = url.replace("__URI__", uri);
  url = url.replace("__ITEM_ID__", !parms.item_id ? "" : parms.item_id);
  url += (parms.item_id && parms.task_id) ? "/" : "";
  url = url.replace("__TASK_ID__", !parms.task_id ? "" : parms.task_id);
  return url;
}

/**
 * Set the enabled/disabled state of the buttons.  The album cover is only enabled if
 * there is only 1 image selected
 */
function setDrawerButtonState() {
  switch ($("#gMicroThumbGrid li.ui-selected").length) {
  case 0:
    if ($("#gOrganizeEditDrawerPanel::visible").length) {
      $("#gOrganizeEditHandleButtonsLeft a[ref='edit']").trigger("click");
    }
    $("#gOrganizeEditHandleButtonsLeft a").attr("disabled", true);
    $("#gOrganizeEditHandleButtonsLeft a").addClass("ui-state-disabled");
    break;
  case 1:
    $("#gOrganizeEditHandleButtonsLeft a").removeAttr("disabled");
    $("#gOrganizeEditHandleButtonsLeft a").removeClass("ui-state-disabled");
   break;
  default:
    $("#gOrganizeEditHandleButtonsLeft a[ref='albumCover']").attr("disabled", true);
    $("#gOrganizeEditHandleButtonsLeft a[ref='albumCover']").addClass("ui-state-disabled");
  }
}

function serializeItemIds(selector) {
  var postData = "";
  $(selector).each(function(i) {
    postData += "&item[]=" + $(this).attr("ref");
  });

  return postData;
}

function createProgressDialog(title) {
  $("body").append("<div id='gOrganizeProgressDialog'>" +
      "<div class='gProgressBar'></div>" +
      "<button id='gOrganizeTaskPause' class='ui-state-default ui-corner-all'>" + PAUSE_BUTTON + "</button>" +
      "<button id='gOrganizeTaskResume' class='ui-state-default ui-corner-all' style='display: none'>" + RESUME_BUTTON + "</button>" +
      "<button id='gOrganizeTaskCancel' class='ui-state-default ui-corner-all' style='display: none'>" + CANCEL_BUTTON + "</button>" +
    "</div>");
  $("#gOrganizeProgressDialog").dialog({
    autoOpen: true,
    autoResize: false,
    modal: true,
    resizable: false,
    title: title
  });

  $(".gProgressBar").progressbar();
  $("#gOrganizeTaskPause").click(function(event) {
    paused = true;
    $("#gOrganizeTaskPause").hide();
    $("#gOrganizeTaskResume").show();
    $("#gOrganizeTaskCancel").show();
    $("#gMessage").empty().append(task.pauseMsg);
  });
  $("#gOrganizeTaskResume").click(function(event) {
    $("#gOrganizeTaskPause").show();
    $("#gOrganizeTaskResume").hide();
    $("#gOrganizeTaskCancel").hide();
    $("#gMessage").empty().append(task.resumeMsg);
    operationCallback();
    //startRearrangeCallback();
  });
  $("#gOrganizeTaskCancel").click(function(event) {
    $("#gOrganizeTaskPause").show();
    $("#gOrganizeTaskResume").hide();
    $("#gOrganizeTaskCancel").hide();

    $.ajax({async: false,
      success: function(data, textStatus) {
        task = null;
        paused = false;
        transitItems = [];
        $("#gMessage").empty().append("<div class='gWarning'>" + data.task.status + "</div>");
        $("#gOrganizeProgressDialog").dialog("destroy").remove();
      },
      dataType: "json",
      type: "POST",
      url: get_url("organize/cancelTask", {task_id: task.id})
    });
  });
}

// **************************************************************************
// Functions that should probably be in a gallery namespace
function getViewportSize() {
  return {
      width : function() {
        return window.innerWidth
          || document.documentElement && document.documentElement.clientWidth
          || document.body.clientWidth;
      },
      height : function() {
        return window.innerHeight
          || document.documentElement && document.documentElement.clientHeight
          || document.body.clientHeight;
      }
  };
}

function displayAjaxError(error) {
  $("body").append("<div id=\"gAjaxError\" title=\"" + FATAL_ERROR + "\">" + error + "</div>");
  $("#gAjaxError").dialog({
      autoOpen: true,
      autoResize: false,
      modal: true,
      resizable: true,
      width: 610,
      height: $("#gDialog").height()
    });
}