if (typeof Sitecore == "undefined") {
  Sitecore = new Object();
}

Sitecore.WebEdit = new function() {
  this.focused = false;
  this.loaded = false;
  
  Event.observe(window, "load", function() {  
    Event.observe(document, "keydown", Sitecore.WebEdit.keyDown.bindAsEventListener(Sitecore.WebEdit));
    Event.observe(document, "keyup", Sitecore.WebEdit.keyUp.bindAsEventListener(Sitecore.WebEdit));
    Event.observe(document, "click", Sitecore.WebEdit.globalClick.bindAsEventListener(Sitecore.WebEdit));
    Event.observe(window, "beforeunload", Sitecore.WebEdit.beforeUnload.bindAsEventListener(Sitecore.WebEdit));
    
    //TODO: move to dom:loaded
    Sitecore.WebEdit.load();
    
    Sitecore.WebEdit.loaded = true;
  });

  this.modified = false;
  this.selectedRendering = "";
}
  
Sitecore.WebEdit.keyDown = function(evt) {
  if (evt.keyCode == 83 && evt.ctrlKey) {
    this.save();
    return;
  }

  if (evt.keyCode == 27) {
    this.focused = false;
    this.hide();
    return;
  }
  
  if (evt.keyCode == 17) {
    // TODO: so slow that it's annoying.
    // this.showHighlight();
    return;
  }

  if (evt.keyCode == 18) {
    $$(".scPageDesignerDropZone").invoke('show');
    Event.stop(evt);
    return;
  }
  
  if (evt.keyCode == 13 && this.activeElement && this.activeElement.contentEditable() && this.activeElement.parameters["linebreak"] == "br") {
    var sel = document.selection.createRange();
    sel.pasteHTML('<br />');
    /*
      hack to move caret to a new line after we've inserted the <br /> 
      AR: disabled, doesn't work reliably. TODO: fix or throw away
      http://www.codingforums.com/showthread.php?t=61716
    */    
    //evt.keyCode = 40;
    evt.stop();
  }
}

Sitecore.WebEdit.keyUp = function(evt) {
  if (evt.keyCode == 17) {
    this.hideHighlight();
    return;
  }
  if (evt.keyCode == 18) {
    $$(".scPageDesignerDropZone").invoke('hide');
    Event.stop(evt);
    return;
  }
}

Sitecore.WebEdit.beforeUnload = function(evt) {
//  if (this.modified) {
//    evt.returnValue = "There are unsaved changes. If you press OK to continue, you will lose your changes.";
//  }
}

Sitecore.WebEdit.load = function(evt) {
  console.group("webedit load");
  
  // here we create a single holder for all webedit additional elements (such as frames and field value holders) that don't necessarily have to be near the wrapped element.
  // hence they are not affected by the content styles, we don't mess the original html as much, etc.
  
  var glueContainer = new Element("div", { id: "scGlueContainer" });
  $(document.body).insert({ top: glueContainer });
  
  this.elements().each(function(element) {
    $(glueContainer).insert(element.fieldValue);
  });
  
  this.elements().invoke('load');
  
  console.info("%s elements loaded", this.elements().length);
  console.groupEnd("webedit load");
}

Sitecore.WebEdit.mouseOver = function(element, evt) {
  if (this.highlightOn) {
    return;
  }
  if (evt.altKey) {
    return;
  }
  
  if (!this.focused) {
    this.show(element, evt);
  }
  
  Event.stop(evt);
}

Sitecore.WebEdit.mouseOut = function(element, evt) {
  if (evt.altKey) {
    return;
  }
  if (!this.focused && this.activeElement != null) {
    this.hide();
  }
  
  event.cancelBubble = true; 
}

Sitecore.WebEdit.focus = function(element, evt) {
  /* Disabled in firefox. Whenever a webedit element has a child element (like webedited image in a link), clicking a frame button fires focus event for the _parent_ element.
     This hides the child element that is being displayed, shows parent instead, and button action never gets executed, which is not what we want. */
  if (Prototype.Browser.Gecko) {
    return;
  }

  Sitecore.WebEdit.focused = true;
  return this.show(element, evt);
}

Sitecore.WebEdit.blur = function(element, evt) {
  if (this.activeElement && this.activeElement.element == element) {
    if (this.activeElement.contentEditable()) {
      this.activeElement.persistValue();
    }
      
    this.focused = false;
    this.hide();
  }
}

Sitecore.WebEdit.click = function(element, evt, uri) {
  this.postRequest('Update("' + uri + '")', true);
}

Sitecore.WebEdit.elements = function() {
  if (!this._elements) {
    this._elements = $$(".scWebEditInput").collect(function(root) {
      return new Sitecore.WebEdit.Element(root);
    });
  }
  
  return this._elements;
}

Sitecore.WebEdit.getElement = function(root) {
  var result = this.elements().find(function(element) { return element.element == root; });
  if (!result) {
    console.error("couldn't find element by node: ");
    console.log(root);
  }
  
  return result;
}

Sitecore.WebEdit.globalClick = function(evt) {
  if (!this.activeElement) {
    return;
  }

  var eventSource = evt.target;
  
  if (!this.isDescendantOrSelf(eventSource, this.activeElement.element) && !this.isDescendantOrSelf(eventSource, this.activeElement.frame)) {
    this.hide();
  }
}

Sitecore.WebEdit.isDescendantOrSelf = function(element, parent) {
  if (element == parent) return true;
  return $(element).descendantOf(parent);
}

Sitecore.WebEdit.execute = function(command, userInterface, value) {
  document.execCommand(command, userInterface, value);
  Sitecore.WebEdit.setModifiedFlag(true);
}

Sitecore.WebEdit.editItem = function(itemid, language, version, fieldid, controlid) {
  var message = "webedit:open(id=" + itemid + ")";
  Sitecore.WebEdit.postRequest(message);
}

Sitecore.WebEdit.editControl = function(itemid, language, version, fieldid, controlid, message) {
  var control = document.getElementById(controlid);  
  var plainValue = control.value;
  
  control = document.getElementById(controlid + "_edit");
  var value = control.value;
  var parameters = control.getAttribute("sc_parameters");

  var ribbon = document.getElementById("scWebEditRibbon");

  if (ribbon != null) {
    ribbon.contentWindow.scForm.browser.getControl("scHtmlValue").value = value;
    ribbon.contentWindow.scForm.browser.getControl("scPlainValue").value = plainValue;
    this.postRequest(message + '(itemid=' + itemid + ',language=' + language + ',version=' + version + ',fieldid=' + fieldid + ',controlid=' + controlid + ',webeditparams=' + parameters + ')', false);
  }
  
  // stops the event
  return false;
}

Sitecore.WebEdit.insertLink = function(itemid, language, version, fieldid, controlid) {
  var selection = document.selection.createRange();
  if (!selection.text || selection.text.length == 0) {
    alert("Please select some text.");
    return;
  }
  
  this.editControl(itemid, language, version, fieldid, controlid, "webedit:insertlink");  
}

Sitecore.WebEdit.insertLinkResponse = function(url) {
  var selection = document.selection.createRange();
  var data = {html: selection.htmlText, url: url};
  
  // if link is selected, replace it with a new one, preserving link contents
  var htmlSelection = selection.htmlText.toLowerCase().strip() || "";
  if (htmlSelection.startsWith("<a ") && htmlSelection.endsWith("</a>")) {
    htmlSelection = data.html.substring(data.html.indexOf('>') + 1);
    htmlSelection = htmlSelection.substring(0, htmlSelection.length - "</a>".length);
    data.html = htmlSelection;
  }
  
  selection.pasteHTML("<a href='#{url}'>#{html}</a>".interpolate(data));
  
  Sitecore.WebEdit.setModifiedFlag(true);
}

Sitecore.WebEdit.insertImage = function(itemid, language, version, fieldid, controlid) {
  var placement = Sitecore.WebEdit.focused ? "cursor" : "bottom";
  
  var ribbon = document.getElementById("scWebEditRibbon");
  var control = document.getElementById(controlid + "_edit");
  var parameters = control.getAttribute("sc_parameters");

  if (ribbon != null) {
    this.postRequest("webedit:insertimage" + '(placement=' + placement + ',itemid=' + itemid + ',language=' + language + ',version=' + version + ',fieldid=' + fieldid + ',controlid=' + controlid + ',webeditparams=' + parameters + ')', false);
  }
  
  // stops the event
  return false;
}

Sitecore.WebEdit.insertImageResponse = function(tagHtml, placement) {
  if (placement == "cursor") {
    var selection = document.selection.createRange();
    selection.pasteHTML(tagHtml);
  }
  else {
    Sitecore.WebEdit.activeElement.element.innerHTML += tagHtml;
  }
  
  Sitecore.WebEdit.setModifiedFlag(true);
}

Sitecore.WebEdit.postRequest = function(request, async) {
  var ctl = document.getElementById("scWebEditRibbon");
  
  if (ctl != null) {
    async = (async == null ? false : async)
  
    ctl.contentWindow.scForm.postRequest("", "", "", request, null, async);
  }
}

Sitecore.WebEdit.show = function(element, evt) {
  if (!this.loaded) {
    return;
  }

  if (this.activeElement != null) {
    this.hide();
  }
  
  var webeditElement = element instanceof Sitecore.WebEdit.Element ? element : Sitecore.WebEdit.getElement(element);
  this.activeElement = webeditElement;  
  webeditElement.show();
  
  return false;
}

Sitecore.WebEdit.hide = function(element, highlight) {
  if (!this.loaded) {
    return;
  }

  element = element || this.activeElement;
  
  if (!element) {
    return;
  }
  
  element.hide(highlight);
}

Sitecore.WebEdit.resize = function(element) {
  if (this.activeElement == null) {
    return false;
  }
  
  return this.activeElement.resize();  
}

Sitecore.WebEdit.showHighlight = function() {
  if (this.highlightOn) {
    return;
  }
  
  if (this.activeElement) {
    this.hide();
  }
  
  this.elements().invoke('highlight');
  this.highlightOn = true;
}

Sitecore.WebEdit.hideHighlight = function() {
  if (!this.highlightOn) {
    return;    
  }

  this.elements().each(function(element) {
    Sitecore.WebEdit.hide(element, true);
  });
  
  this.highlightOn = false;
}

Sitecore.WebEdit.update = function(element) {
  var e = element.previousSibling;
  
  while (e != null && e.tagName != "SPAN") {
    e = e.previousSibling;
  }
  
  if (e == null) {
    return; 
  }

  var innerHTML = element.innerHTML;
  
  if (innerHTML != e.value) {
    Sitecore.WebEdit.setModifiedFlag(true);
  }

  e.value = innerHTML;
}

Sitecore.WebEdit.setModifiedFlag = function(modified) {
  Sitecore.WebEdit.modified = modified;

  var ribbon = $("scWebEditRibbon");
  ribbon.contentWindow.scForm.setModified(modified);
}

Sitecore.WebEdit.close = function() {
  var href = window.location.href;
  
  href = href.replace("sc_ce=1", "sc_ce=0");
  
  this.setCookie("sitecore_webedit_editing", "");

  window.location.href = href;
}

Sitecore.WebEdit.save = function() {
  this.postRequest("webedit:save");
}

Sitecore.WebEdit.changeContentEditorSize = function(element, evt, sign) {
  var iframe = element.parentNode.previousSibling.previousSibling;
  
  var height = iframe.offsetHeight - 48 * sign;
  
  if (height < 200) {
    height = 200;
  }
  
  iframe.style.height = "" + height + "px";
  
  this.setCookie("sitecore_webedit_contenteditorheight", height);
  
  return false;
}

Sitecore.WebEdit.setCookie = function(name, value, expires, path, domain, secure) {
  if (expires == null) {
    expires = new Date();
    expires.setMonth(expires.getMonth() + 3);
  }
  
  if (path == null) {
    path = "/";
  }

  document.cookie = name + "=" + escape(value) +
    (expires ? "; expires=" + expires.toGMTString() : "") +
    (path ? "; path=" + path : "") +
    (domain ? "; domain=" + domain : "") +
    (secure ? "; secure" : "");
}

Sitecore.WebEdit.setModified = function(controlId) {
  var control = document.getElementById(controlId);
  if (!control) {
    return;
  }
  
  this.elements().find(function(element) { return element.fieldValue == control; }).setModified();
  this.setModifiedFlag(true);
}

/* PALETTE */

Sitecore.WebEdit.showPalette = function() {
  this.focused = false;
  this.hide();

  var palette = $("scPalettePanel");
  
  palette.toggle();
  
  return palette.visible();
}

Sitecore.WebEdit.highlightPlaceholder = function(element, evt, id) {
  var placeholder = $(id);
  
  if (placeholder != null) {
    if (evt.type == "mouseover") {
      placeholder.show();
    }
    else {
      placeholder.hide();
    }
  }
  
  this.showTooltip(element, evt);
}

Sitecore.WebEdit.highlightRendering = function(element, evt, id) {
  var e = Event.element(evt);
  
  var rendering = $("r_" + id);
  if (rendering == null) {
    return;
  }
  
  if (evt.type == "mouseover") {
    Sitecore.WebEdit.renderingBackground = rendering.style.background;
    rendering.style.background = "#ffffcc";
  }
  else {
    rendering.style.background = Sitecore.WebEdit.renderingBackground;
  }
}

Sitecore.WebEdit.onPlaceholderClick = function(element, evt, placeholder) {
  
  var layout = $F("scLayout");
  var deviceID = $F("scDeviceID");
  var itemID = $F("scItemID");
  
  var body = "command=" + escape("selectplaceholder") + 
    "&layout=" + escape(layout) + 
    "&placeholder=" + escape(placeholder) +
    "&itemid=" + escape(itemID) +
    "&deviceid=" + escape(deviceID) +
    "&selectedrendering=" + escape(Sitecore.WebEdit.selectedRendering);

    $("scPaletteContentList").innerHTML = "";
        
  new Ajax.Request("/sitecore/shell/Applications/WebEdit/Palette.aspx", {
      method:"post",
      postBody: body,
      onSuccess: function(transport) {  
        var data = eval('(' + transport.responseText + ')');
        
        $("scPaletteContentList").innerHTML = data.content;
      },
      onException: function(request, ex){ alert(ex.description) },
      onFailure: function(request){ alert("Failed") }
    });
    
  var e = $("ph_" + placeholder.replace(/[^a-zA-Z_0-9]/gi, "_"));
    
  $A($(e).up().childElements()).each(function(e) { 
    e.className = "scPalettePlaceholder";
  });
    
  e.className = "scPalettePlaceholderSelected";
  
  Sitecore.WebEdit.selectedPlaceholder = e.id.substr(3);
  Sitecore.WebEdit.selectedPlaceholderKey = placeholder;
  
  Sitecore.WebEdit.updatePaletteContentButtons();
    
  Event.stop(evt);
}

Sitecore.WebEdit.onEditPlaceholderClick = function(element, evt, placeholderKey) {
  var ribbon = $("scWebEditRibbon");

  ribbon.contentWindow.$("scLayoutDefinition").value = $F("scLayout");
  
  this.postRequest("webedit:editplaceholderproperties(placeholderkey=" + placeholderKey + ")");
  
  $("scLayout").value = ribbon.contentWindow.$("scLayoutDefinition").value;
}

Sitecore.WebEdit.onRenderingClick = function(element, evt, id) {
  var selector = $("ph_" + id);
  
  if (selector != null) {
    selector.click();
  }
  
  Event.stop(evt);
  
  return false;
}

Sitecore.WebEdit.onRenderingListClick = function(element, evt, id) {
  $A($(element).up().childElements()).each(function(e) { 
    e.className = "scPalettePlaceholder";
  });
    
  element.className = "scPalettePlaceholderSelected";
  
  Sitecore.WebEdit.updatePaletteContentButtons();
  
  Event.stop(evt);
}

Sitecore.WebEdit.updatePaletteContentButtons = function() {
  var selectedRendering = Sitecore.WebEdit.getSelectedRendering();
  
  var enabled = selectedRendering != null;
  
  var buttons = $("scPaletteContentButtons");
  
  $A(buttons.childElements()).each(function(e) { 
    if (e.hasClassName("scPlaceholderButton")) {
      e.disabled = !(Sitecore.WebEdit.selectedPlaceholderKey != "" && Sitecore.WebEdit.selectedPlaceholderKey != null);
    }
    else {
      e.disabled = !enabled;
    }
  });
}

Sitecore.WebEdit.onContentDeleteClick = function(element, event) {
  var e = Sitecore.WebEdit.getSelectedRendering();
  if (e == null) {
    return;
  }
  
  var rendering = $("r_" + e.id.substr(3));
  
  e.remove();
  rendering.remove();
  
  Sitecore.LayoutDefinition.remove(e.id.substr(3));

  Sitecore.WebEdit.updatePaletteContentButtons();
  Sitecore.WebEdit.setModifiedFlag(true);
}

Sitecore.WebEdit.onContentAddClick = function(element, evt) {
  var ribbon = $("scWebEditRibbon");
  
  ribbon.contentWindow.$("scLayoutDefinition").value = $F("scLayout");
  ribbon.contentWindow.$("scRendering").value = "";

  this.postRequest("webedit:addrendering(placeholder=" + Sitecore.WebEdit.selectedPlaceholderKey + ")");
  
  var id = ribbon.contentWindow.$("scRendering").value;
  if (id == "") {
    return;
  }
  
  var body = "command=" + escape("insert") + 
    "&rendering=" + escape(id) + 
    "&itemid=" + escape($F("scItemID")) + 
    "&language=" + escape($F("scLanguage")) + 
    "&placeholder=" + escape(Sitecore.WebEdit.selectedPlaceholder) + 
    "&placeholderKey=" + escape(Sitecore.WebEdit.selectedPlaceholderKey) + 
    "&deviceid=" + escape($F("scDeviceID")) +
    "&layout=" + escape($F("scLayout")) +
    "&url=" + escape(window.location.href);

  new Ajax.Request("/sitecore/shell/Applications/WebEdit/Palette.aspx", {
      method:"post",
      postBody: body,
      onSuccess: function(transport) {  
        var data = eval('(' + transport.responseText + ')');
        
        if (data.url != null) {
          Sitecore.WebEdit.setModifiedFlag(false);
          window.location.href = data.url;
          return;
        }
        
        var placeholder = Sitecore.WebEdit.getPlaceholder();
        if (placeholder == null) {
          return;
        }
        
        $("scLayout").value = data.layout;
        
        var outer = new Element("div");
        outer.innerHTML = data.html;
        
        Element.insert(placeholder, { after:outer.down() });
        
        outer = new Element("div");
        outer.innerHTML = data.rendering;
        
        var e = $("scPaletteContentList");
        if (e.down() != null) {
          Element.insert(e.down(), { before:outer.down() });
        }
        else {
          Element.insert(e, outer.down());
        }

        $A(e.childElements()).each(function(e) { 
          e.className = "scPalettePlaceholder";
        });
        e.down().className = "scPalettePlaceholderSelected";
        
        Sitecore.WebEdit.updatePaletteContentButtons();
        Sitecore.WebEdit.setModifiedFlag(true);
      },
      onException: function(request, ex){ alert(ex.description) },
      onFailure: function(request){ alert("Failed") }
    });
    
  Event.stop(evt);
}

Sitecore.WebEdit.moveUp = function(element, evt) {
  var e = Sitecore.WebEdit.getSelectedRendering();
  if (e == null) {
    return;
  }
  
  var previous = e.previous();
  if (previous == null) {
    return;
  }
  
  var r0 = $("r_" + e.id.substr(3));
  var r1 = $("r_" + previous.id.substr(3));
  
  Element.insert(previous, { before:e });
  Element.insert(r1, { before:r0 });
  Sitecore.LayoutDefinition.move(e.id.substr(3), previous.id.substr(3), null);

  Sitecore.WebEdit.setModifiedFlag(true);
}

Sitecore.WebEdit.moveDown = function(element, evt) {
  var e = Sitecore.WebEdit.getSelectedRendering();
  if (e == null) {
    return;
  }
  
  var next = e.next();
  if (next == null) {
    return;
  }

  var r0 = $("r_" + e.id.substr(3));
  var r1 = $("r_" + next.id.substr(3));
  
  Element.insert(next, { after:e });
  Element.insert(r1, { after:r0 });
  Sitecore.LayoutDefinition.move(e.id.substr(3), null, next.id.substr(3));

  Sitecore.WebEdit.setModifiedFlag(true);
}

Sitecore.WebEdit.getShortID = function(id) {
  return id.substr(1, 8) + id.substr(10, 4) + id.substr(15, 4) + id.substr(20, 4) + id.substr(25, 12);
}

Sitecore.WebEdit.getSelectedRendering = function() {
  var list = $("scPaletteContentList");
  var result = null;
  
  var elements = list.childElements();
  $A(elements).each(function(e) { 
    if (e.className == "scPalettePlaceholderSelected") {
      result = e;
      throw $break;
    }
  });
  
  return result;
}

Sitecore.WebEdit.getPlaceholder = function() {
  var placeholder = Sitecore.WebEdit.selectedPlaceholder;
  if (placeholder == null) {
    return;
  }
  
  return $(placeholder);
}

Sitecore.WebEdit.editRenderingProperties = function(element, evt) {
  var uniqueid;
    
  if (evt != null) {
    Event.stop(evt);
    uniqueid = element.id.substr(3);
  }
  else {
    var list = $("scPaletteContentList");
    
    var elements = list.childElements();
    $A(elements).each(function(e) { 
      if (e.className == "scPalettePlaceholderSelected") {
        uniqueid = e.id.substr(3);
        throw $break;
      }
    });
  }
  
  if (uniqueid == null) {
    return;
  }
  
  var ribbon = $("scWebEditRibbon");

  ribbon.contentWindow.$("scLayoutDefinition").value = $F("scLayout");
  
  this.postRequest("webedit:editrenderingproperties(uniqueid=" + uniqueid + ")");
  
  $("scLayout").value = ribbon.contentWindow.$("scLayoutDefinition").value;
}

/* LAYOUT DEFINITION */

Sitecore.LayoutDefinition = new function() {
}

Sitecore.LayoutDefinition.insert = function(placeholderKey, id) {
  var layoutDefinition = this.getLayoutDefinition();
  var device = this.getDevice(layoutDefinition);

  var r = new Object();
  r["@id"] = id;
  r["@ph"] = placeholderKey;
  
  device.r.splice(0, 0, r);
  
  this.setLayoutDefinition(layoutDefinition);
}

Sitecore.LayoutDefinition.remove = function(uid) {
  var layoutDefinition = this.getLayoutDefinition();
  var device = this.getDevice(layoutDefinition);
  
  this.removeRendering(device, uid);
  
  this.setLayoutDefinition(layoutDefinition);
}

Sitecore.LayoutDefinition.removeRendering = function(device, uid) {
  for(n = 0; n < device.r.length; n++) {
    if (Sitecore.WebEdit.getShortID(device.r[n]["@uid"]) == uid) {
      r = device.r[n];
      device.r.splice(n, 1);
      return r;
    }
  }
  return null;
}

Sitecore.LayoutDefinition.move = function(uid, before, after) {
  var layoutDefinition = this.getLayoutDefinition();
  var device = this.getDevice(layoutDefinition);

  var r = this.removeRendering(device, uid);
  if (r == null) {
    return;
  }
  
  for(n = 0; n < device.r.length; n++) {
    if (after != null && Sitecore.WebEdit.getShortID(device.r[n]["@uid"]) == after) {
      device.r.splice(n + 1, 0, r);
      break;
    }
    
    if (before != null && Sitecore.WebEdit.getShortID(device.r[n]["@uid"]) == before) {
      device.r.splice(n, 0, r);
      break;
    }
  }

  this.setLayoutDefinition(layoutDefinition);
}

Sitecore.LayoutDefinition.getRenderingIndex = function(placeholderKey, index) {
  var layoutDefinition = this.getLayoutDefinition();
  var device = this.getDevice(layoutDefinition);

  var i = 0;

  for(n = 0; n < device.r.length; n++) {
    if (device.r[n]["@ph"] == placeholderKey) {
      if (i == index) {
        return n;
      }
      
      i++;
    }
  }
  
  return -1;
}

Sitecore.LayoutDefinition.getLayoutDefinition = function() {
  return $F("scLayout").evalJSON(true);
}

Sitecore.LayoutDefinition.setLayoutDefinition = function(layoutDefinition) {
  $("scLayout").value = Object.toJSON(layoutDefinition);
}

Sitecore.LayoutDefinition.getDeviceID = function() {
  return $F("scDeviceID");
}

Sitecore.LayoutDefinition.getDevice = function(layoutDefinition) {
  var deviceID = this.getDeviceID();

  var device = layoutDefinition.r.d;
  if (!device.length) {
    var id = Sitecore.WebEdit.getShortID(device["@id"]);
    return id == deviceID ? device : null;
  }
  
  var list = layoutDefinition.r.d;
   
  for(var n = 0; n < list.length; n++) {
    var d = list[n];
    
    var id = Sitecore.WebEdit.getShortID(d["@id"]);
    
    if (id == deviceID) {
      return d;
    }
  }
  
  return null;
}

Sitecore.WebEdit.showTooltip = function(element, evt) {
  var tooltip = $(element.lastChild);
  var x = Event.pointerX(evt);
  var y = Event.pointerY(evt);
  
  if (evt.type == "mouseover") {
    if (tooltip.style.display == "none") {
      clearTimeout(this.tooltipTimer);
      
      this.tooltipTimer = setTimeout(function() {
        var html = tooltip.innerHTML;
        
        if (html == "") {
          return;
        }
      
        var t = $("scCurrentTooltip");
        if (t == null) {
          t = new Element("div", { "id":"scCurrentTooltip", "class": "scPalettePlaceholderTooltip", "style": "display:none" });
          document.body.appendChild(t);
        }
        
        t.innerHTML = html;
      
        t.style.left = x + "px";
        t.style.top = y + "px";
        t.style.display = "";
      }, 450);
    }
  }
  else {
    clearTimeout(this.tooltipTimer);
    var t = $("scCurrentTooltip");
    if (t != null) {
      t.style.display = "none";
    }
  }
}

