/*
 *  BEGIN FLOCK GPL
 *
 *  Copyright Flock Inc. 2005-2009
 *  http://flock.com
 *
 *  This file may be used under the terms of the
 *  GNU General Public License Version 2 or later (the "GPL"),
 *  http://www.gnu.org/licenses/gpl.html
 *
 *  Software distributed under the License is distributed on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 *  for the specific language governing rights and limitations under the
 *  License.
 *
 *  END FLOCK GPL
 */

Components.utils.import("resource:///modules/FlockUploadUtils.jsm");

/*********************
 * object declarations
 *********************/
var photoProperties;
var photoCropper;
function OriginalData() {}


/*********************
 * constants
 *********************/
const MODE_DISPLAY_SINGLE = 0;
const MODE_DISPLAY_MULTI = 1;
const MODE_DISPLAY_NO_PHOTOS = 2;
const UPLOAD_TYPE_NORMAL = 0;
const UPLOAD_TYPE_DND = 1;

const BIG_THRESHOLD = 10;
const NORMAL_THRESHOLD = 26;
const SMALL_THRESHOLD = 37;

const SVG_NS = "http://www.w3.org/2000/svg";
const XLINK_NS = "http://www.w3.org/1999/xlink";

photoProperties = {
  mDisplayMode: null,
  mUploads: null,
  mOriginalData: null,
  mRotator: null,
  mUploadType: null,
  mInit: false,
  mValid: true,
  uploadSvc: Components.classes["@flock.com/media/upload-service;1"]
      .getService(Components.interfaces.flockIPhotoUploadService),
  mApiMgr: Components.classes['@flock.com/photo-api-manager;1?']
                              .getService(Components.interfaces.flockIPhotoAPIManager),
  
  invalidate: function() {
    this.mValid = false;
  },

  init: function() {
    if (this.mInit)
      return;
    this.mInit = true;
    var inst = this;
    var cropperListener = {
      onChange: function(aCropObj) {
        inst.updateCommands();
      }
    }
    $('image').setListener(cropperListener);
    this.setupUIFields($('servicesMenuList').selectedItem.svc,
                       $('servicesMenuList').value);
  },
  
  setDisplayMode: function(aDisplayMode) {
    this.mDisplayMode= aDisplayMode;
  },
  
  setUploadType: function(aUploadType) {
    this.mUploadType = aUploadType;
  },
  
  setSelection: function(aUploads, aSwitchTab) {
    this.init();
    this.mValid = true;
    // before changing to the next selection, save the previous
    if (this.mUploads != null && this.mUploads.length) this.synch();
    this.mUploads = aUploads;
    this.mOriginalData = new OriginalData();
    this.mRotator = new PhotoRotater();
    this.setupPreviewArea(aSwitchTab);
    $('flock-photoprops-disable').setAttribute('hidden', true);
    this.updateCommands();
  },
  
  getSelection: function() {
    return this.mUploads;
  },

  updateSelectedItem: function(aUpload) {
    var upload = null;
    if (!this.mUploads) return false;
    for (var i = 0; i < this.mUploads.length; ++i) {
      if (this.mUploads[i].id == aUpload.id) {
        this.mUploads[i] = aUpload;
        return true;
      }
    }
    return false;
  },
  
  clearSelection: function() {
    this.setDisplayMode(MODE_DISPLAY_NO_PHOTOS);
    this.mUploads = null;
    this.setupEmptyImage(true);
    this.updateCommands();
  },
  
  crop: function(aDegrees) {
    if (this.mUploads.length != 1) dump("crop assertion failure");
    var cropper = $("image");
    var x1 = cropper.x1;
    var y1 = cropper.y1;
    var x2 = cropper.x2;
    var y2 = cropper.y2;

    var rot = parseInt(this.mUploads[0].rotation);
    function rotateLeftNinetyDegrees() {
      var tmp = x1;
      x1 = y1;
      y1 = 1 - x2;
      x2 = y2;
      y2 = 1 - tmp;
    }

    var tmp = rot;
    while (!isNaN(tmp) && tmp % 360 != 0) {
      rotateLeftNinetyDegrees();
      tmp -= 90;
    }

    if (this.mUploads[0].crop) {
      var coords = this.mUploads[0].crop.split(",");
      var ox1 = parseFloat(coords[0]);
      var oy1 = parseFloat(coords[1]);
      var ox2 = parseFloat(coords[2]);
      var oy2 = parseFloat(coords[3]);
      x1 = (x1 * (ox2 - ox1)) + ox1;
      y1 = (y1 * (oy2 - oy1)) + oy1;
      x2 = (x2 * (ox2 - ox1)) + ox1;
      y2 = (y2 * (oy2 - oy1)) + oy1;
    }

    // Remove tags outside cropping region.
    var newNotes = $("notes").value;
    var notes = newNotes.match(/\{"x":"\d+\.\d","y":"\d+\.\d",[^}]+\}/g);
    var badTags = [];
    var goodTags = [];
    for (var i = 0; notes && i < notes.length; i++) {
      var arr = notes[i].match(/"x":"(\d+\.\d)","y":"(\d+\.\d)"/);
      var tagX = parseFloat(arr[1]) / 100.0;
      var tagY = parseFloat(arr[2]) / 100.0;
      if (tagX < x1 || tagX > x2 || tagY < y1 || tagY > y2) {
        badTags.push(notes[i]);
      } else {
        goodTags.push(notes[i]);
      }
    }
    var doCrop = true;
    if (badTags.length > 0) {
      const CC=Components.classes;
      const CI=Components.interfaces;
      var strBundleSvc = CC["@mozilla.org/intl/stringbundle;1"]
                         .getService(CI.nsIStringBundleService);
      var sb = strBundleSvc
               .createBundle("chrome://flock/locale/photo/photo.properties");
      var titleMessage = sb.GetStringFromName("flock.photo.upload.td.title");
      var dialogMessage = sb.GetStringFromName("flock.photo.upload.td.msg");
      var promptService = CC["@mozilla.org/embedcomp/prompt-service;1"]
                          .getService(CI.nsIPromptService);
      doCrop = promptService.confirm(null, titleMessage, dialogMessage);
      if (doCrop) {
        newNotes = "[" + goodTags.join(",") + "]";
      }
    }
    if (doCrop) {
      var cropstr = x1 + "," + y1 + "," + x2 + "," + y2;
      this.uploadSvc.cropPhotoUpload(this.mUploads[0], x1, y1, x2, y2);
      this.mUploads[0].crop = cropstr;
      this.mUploads[0].notes = newNotes;
      // Crop change will be saved (sync'ed) in setSelection
      this.setSelection(this.mUploads, true);
      $("notes").value = newNotes;
    }
  },

  rotate: function(aDegrees) {
    for (var i = 0; i < this.mUploads.length; i++) {
      this.mRotator.add(this.mUploads[i], aDegrees);
    }
  },
  
  tag: function() {
    var cropper = $("image");
    var tagButton = $("tagButton");
    if (cropper.mode == 0) {
      cropper.mode = 1;
    } else {
      cropper.mode = 0;
    }
    if (tagButton.getAttribute("isActive") == "true") {
      tagButton.setAttribute("isActive", false);
    } else {
      tagButton.setAttribute("isActive", true);    
    }
  },
  
  unsetTag: function pp_unsetTag() {
    var tagButton = $("tagButton");
    if (tagButton.getAttribute("isActive") == "true") {
      this.tag();
    }
  },
  
  revert: function() {
    //this.setSelection(this.mUploads);
    this.uploadSvc.revertPhotoUpload(this.mUploads[0]);
    this.mUploads[0].crop = "0,0,1,1";
    this.mUploads[0].rotation = "0";
    this.setSelection(this.mUploads, true);
  },
  
  setupPreviewArea: function(aSwitchTab) {
    if (this.mUploads.length > 1) {
      this.setDisplayMode(MODE_DISPLAY_MULTI);
      this.setupMultiImage(aSwitchTab);
    } 
    else if(this.mUploads.length==0) {
      this.clearSelection();
    }
    else {
      this.setDisplayMode(MODE_DISPLAY_SINGLE);
      this.setupSingleImage(aSwitchTab);
    }
  }, 
  
  setupEmptyImage: function(aSwitchTab) {
    if ($('batch-single') && aSwitchTab)
      $('batch-single').selectedIndex = 0;
    $("image").src = '';
    $("image-box").removeAttribute("collapsed");
    $("image-deck").selectedIndex = 0;
    $("title").value = '';
    $("filename").value = '';
    $("description").value = '';
    this.updateSpellchecker();
    $("tags").value = '';
    $("notes").value = '';
    $("flock-photoprops-disable").removeAttribute('hidden');
  },
  
  setupSingleImage: function(aSwitchTab) {
    if ($('batch-single') && aSwitchTab)
      $('batch-single').selectedIndex = 1;

    var path = this.mUploads[0].previewFilePath;
    // set the background of the canvas as the preview of the image
    var spec = this.mUploads[0].previewFileSpec;
        
    $("image").src = spec;
    $("image-box").removeAttribute("collapsed");
    $("image-deck").selectedIndex = 0;
    
    $("title").value = this.mUploads[0].title;
    if ($('batch-title') && $('batch-title').value != "" && $("title").value == "") {
      $("title").value = $('batch-title').value;
      $("title").setAttribute("empty", "true");
    }
    else {
      $("title").removeAttribute("empty");
    }
    $("filename").value = this.mUploads[0].fileName;
    $("description").value = this.mUploads[0].description;
     if ($('batch-description') && $('batch-description').value != "" && $("description").value == "") {
      $("description").value = $('batch-description').value;
      $("description").setAttribute("empty", "true");
    }
    else {
      $("description").removeAttribute("empty");
    }   
    this.updateSpellchecker();
    $("tags").value = this.mUploads[0].tags;
    $("notes").value = this.mUploads[0].notes;

    var is_public = this.mUploads[0].is_public;
    var privacy_use_batch = this.mUploads[0].privacy_use_batch;
    var is_family = this.mUploads[0].is_family;
    var is_friend = this.mUploads[0].is_friend;

    dump("is_public = "+this.mUploads[0].is_public+"\n");
    dump("privacy_use_batch = "+privacy_use_batch+"\n");

    if (privacy_use_batch == "true") {
      this.setPrivacy("batch");
    }
    else if (is_public == "false") {
      this.setPrivacy("private");
    }
    else {
      this.setPrivacy("public");
    }

    if(is_family == "true") {
      $("is_family").checked = true;
    } 
    else {
      $("is_family").checked = false;
    }
    if(is_friend == "true") {
      $("is_friend").checked = true;
    } 
    else {
      $("is_friend").checked = false;
    }
    
    this.mOriginalData.remember();
  },
  
  setupMultiImage: function(aSwitchTab) {
    if ($('batch-single') && aSwitchTab)
      $('batch-single').selectedIndex = 1;
    $("image-deck").selectedIndex = 1;
    $("image-box").setAttribute("collapsed", true);
    // clean up
    //flock_clearChildren($("multi-image"));
    var multiImageBox = $("multi-image");
    
    while (multiImageBox.hasChildNodes()) {
      multiImageBox.removeChild(multiImageBox.lastChild);
    }
    
    var title, description, tags, notes, friends, family, fileName;
    
    title = this.mUploads[0].getAttribute("title");
    fileName  = this.mUploads[0].getAttribute("fileName");
    description = this.mUploads[0].getAttribute("description");
    tags = this.mUploads[0].getAttribute("tags").split(",").sort().join(",");
    notes = this.mUploads[0].getAttribute("notes");
    
    var scale;
    // pick the scale for image sizes...
    if (this.mUploads.length < BIG_THRESHOLD) {
      scale = "big";
    } else if (this.mUploads.length < NORMAL_THRESHOLD) {
      scale = "normal";
    } else if (this.mUploads.length < SMALL_THRESHOLD) {
      scale = "small";
    } else {
      scale = "tiny";
    }

    for (var i = 0; i < this.mUploads.length; ++i) {
      var newElement = document.createElement("photopreview");
      newElement.setAttribute("src", this.mUploads[i].getAttribute("previewFileSpec"));
      newElement.setAttribute("class", scale);
      newElement.setAttribute("tooltip", "photoPreviewTooltip");
      newElement.setAttribute("title", this.mUploads[i].getAttribute("title"));
      newElement.setAttribute("onmouseover", "photoProperties.updateTooltip(this);");
      var refId = this.mUploads[i].getAttribute("id");
      newElement.setAttribute("onclick", "photoProperties.setSelectionFromId('" + refId + "')");
      $("multi-image").appendChild(newElement);

      // check for common group properties
      title = this.mUploads[i].getAttribute("title") == title ? title : null;
      description = this.mUploads[i].getAttribute("description") == description ? description : null;
      tags = this.mUploads[i].getAttribute("tags").split(",").sort().join(",") == tags ? tags : null;
      notes = this.mUploads[i].getAttribute("notes") == notes ? notes : null;
    }
    
    $("title").value = title;
    $("filename").value = '';
    $("filename").setAttribute('disabled', true)
    $("description").value = description;
    this.updateSpellchecker();
    $("tags").value = tags;
    $("notes").value = notes;

    // update layout for group edit
    $("title").setAttribute("oninput", "$('title_change').checked = true");
    $("description").setAttribute("oninput", "$('description_change').checked = true");
    $("tags").setAttribute("oninput", "$('tags_change').checked = true");
    $("notes").setAttribute("oninput", "$('notes_change').checked = true");

    $("title_change").checked = false;
    $("description_change").checked = false;
    $("tags_change").checked = false;
    $("notes_change").checked = false;
    $("permissions_change").checked = false;
  },
  
  setSelectionFromId: function (aUploadId) {
    var upload = $(aUploadId);
    var slideybox =  $('flock-photo-upload-slideybox');
    slideybox.clearSelection();
    slideybox.scrollTo(upload.boxObject.x - 200,0);
    
    upload.selected = true;
  
    var uploads = Array();
    uploads.push(upload.firstChild);
    this.setSelection(uploads, true);
  },

  togglePrivacyControls: function(aVal) {
    $('photo-privacy-controls').setAttribute('collapsed', !aVal);
  },
  
  setPrivacy: function (aVal) {
    $('is_public').value = aVal;
    if (aVal == "private") {
      $('is_friend').disabled = false;
      $('is_family').disabled = false;
    }
    else {
      $('is_friend').disabled = true;
      $('is_family').disabled = true;
    }
  },

  save: function() {
    if (this.mUploadType == UPLOAD_TYPE_DND)
      return;
    if(!this.mValid) 
      return;
    for each (var upload in this.mUploads) {
      if (!upload.is_public) {
        // is_public is a string; we're testing the existence of the attribute,
        // not the value
        continue;
      }
      this.uploadSvc.savePhotoUpload(upload);
    }
  },
    
  synch: function () {
    if(!this.mUploads || this.mUploads.length==0) return;
    var privacy_use_batch = $("is_public").value == "batch" ? "true" : "false";
    var is_public = $("is_public").value == "public" ? "true" : "false";
    var is_friend = $("is_friend").checked ? "true" : "false";
    var is_family = $("is_family").checked ? "true" : "false";
    if(this.mDisplayMode == MODE_DISPLAY_MULTI) {
      //var shouldSave = false;
      for (var i=0; i<this.mUploads.length; i++) {
        // encapsulating this is try catch, for sometimes the dom nodes
        // don't exist!
        try {
          if ($("title_change").checked) {
            var photoTitle;
            photoTitle = ($("title").value.length == 0) ? this.mUploads[i].fileName : $("title").value;
            this.mUploads[i].setAttribute("title", photoTitle);
          }
          if ($("description_change").checked) {
            this.mUploads[i].setAttribute("description", $("description").value);
          }

          if ($("notes_change").checked) {
            this.mUploads[i].setAttribute("notes", $("notes").value);
          }
          if ($("tags_change").checked) {
            this.mUploads[i].setAttribute("tags", $("tags").value);
          }
          if ($("permissions_change").checked) {
            this.mUploads[i].setAttribute("privacy_use_batch",
                                          privacy_use_batch);
            this.mUploads[i].setAttribute("is_public", is_public);
            this.mUploads[i].setAttribute("is_friend", is_friend);
            this.mUploads[i].setAttribute("is_family", is_family);
          }
        } catch(e) {
          dump (e);
        }
      }
    } else if (this.mUploads[0]) {
      if (this.mOriginalData.hasChanged("title"))
        this.mUploads[0].title =  $("title").value;
      if (this.mOriginalData.hasChanged("filename") && $("filename").value.length)
        this.mUploads[0].fileName = $("filename").value;
      if (this.mOriginalData.hasChanged("description"))
        this.mUploads[0].description = $("description").value;
      if (this.mOriginalData.hasChanged("tags"))
        this.mUploads[0].tags = $("tags").value;
      if (this.mOriginalData.hasChanged("notes"))
        this.mUploads[0].notes = $("notes").value;
      if (this.mOriginalData.hasChanged("is_public")) {
        this.mUploads[0].privacy_use_batch = privacy_use_batch;
      }
      if (this.mOriginalData.hasChanged("is_public")) {
        this.mUploads[0].is_public = is_public;
      }
      if (this.mOriginalData.hasChanged("is_friend")) {
        this.mUploads[0].is_friend = is_friend;
      }
      if (this.mOriginalData.hasChanged("is_family")) {
        this.mUploads[0].is_family = is_family;
      }
    }

    var formHistory = Components.classes["@mozilla.org/satchel/form-history;1"]
                                .getService(Components.interfaces.nsIFormHistory2);

    $("tags").pills.forEach(function (aPill) {
      formHistory.addEntry("flock-tags", aPill.value);
    });

    this.save();
  },
  
  updateCommands: function() {
    switch (this.mDisplayMode) {
      case MODE_DISPLAY_SINGLE:
        $("image").crop = this.mUploads[0].crop;
        $("image").rotationInt = parseInt(this.mUploads[0].rotation);
        if ($('image').hasCrop)
          $('cmdCrop').removeAttribute('disabled');
        else
          $('cmdCrop').setAttribute('disabled', true);

        $('cmdRotateLeft').removeAttribute('disabled');
        $('cmdRotateRight').removeAttribute('disabled');
        $('cmdRevert').removeAttribute('disabled');
        if(this.mUploads[0].crop=="0,0,1,1" && this.mUploads[0].rotation=="0") {
          $('cmdRevert').setAttribute('disabled', true);
        }
        else {
          $('cmdRevert').removeAttribute('disabled');
        }

        $("title_change").setAttribute('collapsed', true);
        $("description_change").setAttribute('collapsed', true);
        $("tags_change").setAttribute('collapsed', true);
        $("notes_change").setAttribute('collapsed', true);
        $("permissions_change").setAttribute('collapsed', true);

        if (this.mUploadType != UPLOAD_TYPE_DND)
          $('flock-photoprops-disable').setAttribute('hidden', true);
        break;

      case MODE_DISPLAY_MULTI:
        $('cmdCrop').setAttribute('disabled', true);
        if (this.mUploadType != UPLOAD_TYPE_DND)
          $('flock-photoprops-disable').setAttribute('hidden', true);
        break;
       
      case MODE_DISPLAY_NO_PHOTOS:
        //$('photoPropsCmds').setAttribute('disabled', true);
        $('cmdRotateLeft').setAttribute('disabled', true);
        $('cmdRotateRight').setAttribute('disabled', true);
        $('cmdCrop').setAttribute('disabled', true);
        $('cmdRevert').setAttribute('disabled', true);
        $('flock-photoprops-disable').removeAttribute('hidden');
        break;
      default:
    }
    switch (this.mDisplayMode) {
      case MODE_DISPLAY_NO_PHOTOS:
      case MODE_DISPLAY_SINGLE:
        $("title_change").setAttribute('collapsed', true);
        $("description_change").setAttribute('collapsed', true);
        $("tags_change").setAttribute('collapsed', true);
        $("notes_change").setAttribute('collapsed', true);
        $("permissions_change").setAttribute('collapsed', true);
      break;
      case MODE_DISPLAY_MULTI:
        $("title_change").setAttribute('collapsed', false);
        $("description_change").setAttribute('collapsed', false);
        $("tags_change").setAttribute('collapsed', false);
        $("notes_change").setAttribute('collapsed', false);
        $("permissions_change").setAttribute('collapsed', false);
      break;
    }
  },
  
  updateTooltip: function(aPhoto) {
    var src = aPhoto.getAttribute('src');
    if (src.length) {
      $('photoPreviewTooltipImage').setAttribute('src', src);
      $('photoPreviewTooltipTitle').setAttribute('value', aPhoto.getAttribute('title'));
    }
  },

  updateSpellchecker: function() {
    dump("Set spellcheck to: "+!($("description").getAttribute("empty") == "true")+"\n");
    $("description").spellcheck = !($("description").getAttribute("empty") == "true");
  },
  
  setupUIFields: function(aService, aAccountURN) {
    if (!aAccountURN) {
      this.setupUIFieldsForNoAccount();
      return;
    }
    this.uploadSvc.setDefaultService(aAccountURN);
    // Per photo attributes
    $('photo-description').hidden = !aService.supportsFeature('description');
    $('photo-title').hidden = !aService.supportsFeature('title');
    $('photo-filename').hidden = !aService.supportsFeature('fileName');
    $('photo-tags').hidden = !aService.supportsFeature('tags');
    var supports_notes = aService.supportsFeature('notes');
    $('tagButton').hidden = !supports_notes;
    if (!supports_notes) {
      this.unsetTag();
    }
    $('photo-notes').hidden = !supports_notes;
    $('photo-permissions').hidden = !aService.supportsFeature('privacy');
    // Batch attributes
    if ($('batch-properties-container'))
      $('batch-properties-container').hidden = !aService.supportsFeature('description');
    if ($('batch-title-container'))
      $('batch-title-container').hidden = !aService.supportsFeature('title');
    if ($('batch-tags-container'))
      $('batch-tags-container').hidden = !aService.supportsFeature('tags');
    if ($('batch-privacy-container'))
      $('batch-privacy-container').hidden = !aService.supportsFeature('privacy');
  },
  
  // Set the UI up for no account
  setupUIFieldsForNoAccount: function() {
     $('photo-title').hidden = true;
      $('photo-filename').hidden = true;
      $('photo-tags').hidden = true;
      $('tagButton').hidden = true;
      $('photo-notes').hidden = true;
      $('photo-permissions').hidden = true;
      // Batch attributes
      if ($('batch-title-container'))
        $('batch-title-container').hidden = true;
      if ($('batch-tags-container'))
        $('batch-tags-container').hidden = true;
      if ($('batch-privacy-container'))
        $('batch-privacy-container').hidden = true;
  }
}

/*********************
 * Photo data store
 */
OriginalData.prototype.hasChanged = function(aID) {
  if ($(aID).nodeName == "checkbox") {
    return ((this[aID] == "true" && !$(aID).checked) ||
            (this[aID] == "false" && $(aID).checked));
  }
  else {
    return (this[aID] != $(aID).value);
  }
}

OriginalData.prototype.remember = function() {
  this.title = $("title").value;
  this.filename = $("filename").value
  this.tags = $("tags").value;
  this.notes = $("notes").value;
  this.description = $("description").value;
  this.privacy_use_batch = $("batch-radio").selected ? "true" : "false";
  this.is_public = $("is_public").value;
  this.is_friend = $("is_friend").checked ? "true" : "false";
  this.is_family = $("is_family").checked ? "true" : "false";
}


/*********************
 * Photo rotator object
 */

function PhotoRotater() {
  this.mRotateQ = new Array();
}
PhotoRotater.prototype.mRotateQ = null;
PhotoRotater.prototype.mIsRotating = false;

PhotoRotater.prototype.add = function(aElement, aDegrees) {
  var uploadObj = {
    element: aElement,
    degrees: aDegrees
  }
  this.mRotateQ.unshift(uploadObj);

  window.setTimeout(this.startRotateTimer, 0, this);
}

PhotoRotater.prototype.startRotateTimer = function (aInst) {
  var uploadSvc = Cc["@flock.com/media/upload-service;1"]
                  .getService(Ci.flockIPhotoUploadService);
  var rotateObj = aInst.mRotateQ.pop();
  uploadSvc.rotatePhotoUpload(rotateObj.element, rotateObj.degrees);
  if (!aInst.mRotateQ.length) {
    this.mIsRotating = false;
    // Rotation change will be saved (sync'ed) in setSelection
    photoProperties.setSelection(photoProperties.mUploads, true);
  }
}

function focusField(aField) {
  if ($(aField).getAttribute("empty") == "true") {
    $(aField).removeAttribute("empty");
    $(aField).value = "";
  }
  else {
    $(aField).select();
  }
  photoProperties.updateSpellchecker();
}

function blurField(aField) {
  if (!$("batch-" + aField))
    return; // Side-uploader
  if ($(aField).value == "") {
    $(aField).setAttribute("empty", "true");
    $(aField).value = $("batch-" + aField).value;
  }
  else {
    $(aField).removeAttribute("empty");
  }
  photoProperties.updateSpellchecker();
}

function blinkFrame(x, y) {
  $('image').clearBox();
  $('image').drawBox(x, y);

  var sync = {
    notify: function() {
      $('image').clearBox();
    }
  }

  var blinkTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
  blinkTimer.initWithCallback(sync, 500, Ci.nsITimer.TYPE_ONE_SHOT);
}

function selectNote() {
  if (!$("notes").selectedItem) return;

  var json = $('notes').selectedItem.parentNode.value;

  var rex = /"x":"(.+?)"/;
  var arrx = rex.exec(json);
  var x = arrx[1];
  
  var rey = /"y":"(.+?)"/;
  var arry = rey.exec(json);
  var y = arry[1];
  
  blinkFrame(x, y);
}

function handlePopupKeyEvent(aEvent) {
  if (aEvent.keyCode == 13) {
    if ($("tagTextContent").value) {
      $("tagPopup").hidePopup();
      var xPercent = (($("image").mMouseDownX - $("image").boxObject.x) / $("image").boxObject.width) * 100;
      var yPercent = (($("image").mMouseDownY - $("image").boxObject.y) / $("image").boxObject.height) * 100;
      $("notes").add(xPercent.toFixed(1), yPercent.toFixed(1), "", $("tagTextContent").value);
    }
  } else if (aEvent.keyCode == KeyEvent.DOM_VK_ESCAPE) {
    $("tagPopup").hidePopup();
  } else {
    // Filter
    var search = $("tagTextContent").value;
    var children = $("tagPopupContent").childNodes;
    for (var i = 0; i < children.length; i++) {
      var child = children[i];
      if (i == 0 || i == 1) { 
        // Me or the separator
        if (search == "") { 
          child.removeAttribute("hidden");
        } else {
          child.setAttribute("hidden", "true");
        }
      } else {
        if (search == "" ||
            child.value.toLowerCase().match(search.toLowerCase()))
        {
          child.removeAttribute("hidden");
        } else {
          child.setAttribute("hidden", "true");
        }
      }
    }
  }
}
