RegisterIniter(ColorsSectionIniter);

function ColorsSectionIniter(aElt, aRuleset)
{
  deleteAllChildren(gDialog.backgroundsRichlistbox);
  var color = CssInspector.getCascadedValue(aRuleset, "color");
  gDialog.colorColorpicker.color = color;

  var bgColor = CssInspector.getCascadedValue(aRuleset, "background-color");
  gDialog.bgColorColorpicker.color = bgColor;

  var bgImages = CssInspector.getCascadedValue(aRuleset, "background-image");
  var parsedImages = CssInspector.parseBackgroundImages(bgImages);
  var bgAttachment = CssInspector.getCascadedValue(aRuleset, "background-attachment").split(",");
  var bgRepeat     = CssInspector.getCascadedValue(aRuleset, "background-repeat").split(",");
  var bgPosition   = CssInspector.getCascadedValue(aRuleset, "background-position").split(",");
  var bgSize       = CssInspector.getCascadedValue(aRuleset, "background-size").split(",");
  var bgClip       = CssInspector.getCascadedValue(aRuleset, "background-clip").split(",");
  var bgOrigin     = CssInspector.getCascadedValue(aRuleset, "background-origin").split(",");
  if (bgImages != "none") {
	  for (var i = 0; i < parsedImages.length; i++) {
	    var item = document.createElement("richlistitem");
	    item.className = "backgrounditem";
	    var type = parsedImages[i].type;
	    item.setAttribute("type", type);
	    gDialog.backgroundsRichlistbox.appendChild(item);
	
	    item.reset();
	    var button = item.getChild("backgrounditemButton");
	    item.parsedValue = parsedImages[i].value;
	    switch (type) {
	      case "image":
	        // pfff, find the real URL...
	        var match = item.parsedValue.match ( /^url\(\s*"([^"]*)"\s*\)|^url\(\s*'([^']*)'\s*\)|^url\(\s*([^\)]*)\s*\)/ );
	        if (match) {
	          if (match[1]) item.setAttribute("image", match[1]);
	          else if (match[2]) item.setAttribute("image", match[2]);
	          else if (match[3]) item.setAttribute("image", match[3]);
	        }
	        button.style.backgroundImage = "url('" + UrlUtils.makeAbsoluteUrl(item.getAttribute("image")) + "')";
	        break;
	      default:
	        button.style.backgroundImage =
	          CssInspector.serializeGradient(item.parsedValue);
	        break;
	    }
	    item.getChild("backgrounditem-attachment").value =
	      (i < bgAttachment.length ? bgAttachment[i].trim() : "");
	    item.getChild("backgrounditem-repeat").value =
	      (i < bgRepeat.length ? bgRepeat[i].trim() : "");
	    item.getChild("backgrounditem-position").value =
	      (i < bgPosition.length ? bgPosition[i].trim() : "");
	    item.getChild("backgrounditem-size").value =
	      (i < bgSize.length ? bgSize[i].trim() : "");
	    item.getChild("backgrounditem-clip").value =
	      (i < bgClip.length ? bgClip[i].trim() : "");
	    item.getChild("backgrounditem-origin").value =
	      (i < bgOrigin.length ? bgOrigin[i].trim() : "");
	  }
  }
}

function AddBackground(aEvent)
{
  var type = aEvent.originalTarget.value;
  var item = document.createElement("richlistitem");
  item.className = "backgrounditem";
  item.setAttribute("type", type);
  gDialog.backgroundsRichlistbox.appendChild(item);
  item.reset();
  item.openEditor();
}

function OnBackgroundSelect(aElt)
{
  var item = aElt.selectedItem;
  SetEnabledElement(gDialog.removeBackgroundButton, (item != null));    
}

function DeleteBackground()
{
  var item = gDialog.backgroundsRichlistbox.selectedItem;
  if (!item) return; // sanity check
  item.parentNode.removeChild(item);
  SetEnabledElement(gDialog.removeBackgroundButton, (gDialog.backgroundsRichlistbox.itemCount != 0));
  ReapplyBackgrounds();
}

function LoadImage()
{
  gDialog.previewBackgroundImage.style.backgroundImage =
    'url("' + UrlUtils.makeAbsoluteUrl(gDialog.imageURLTextbox.inputField.value) + '")';
}

function BackgroundImageSelected()
{
  gDialog.backgroundImagePanel.hidePopup();
  var item = gDialog.backgroundsRichlistbox.selectedItem;
  item.applyBackgroundImage(gDialog.imageURLTextbox.value);
}

function ReapplyBackgrounds()
{
  var items = gDialog.backgroundsRichlistbox.querySelectorAll("richlistitem");
  var bgColor = "", bgImages = [];
  for (var i = 0; i < items.length; i++) {
    var item = items[i];
    bgImages.push(item.serializedValue);
  }
  ApplyStyles([
                {
                  property: "background-image",
                  value: bgImages.join(", ")
                }
              ]);
  SelectionChanged(null, gCurrentElement, true);
}

function RepaintGradient()
{
  var angle = gDialog.linearGradientAngleCheckbox.checked ? gDialog.linearGradientAngleRotator.value + "deg"
                                                          : "";
  var startingPoint = gDialog.linearGradientStartingPointCheckbox.checked ? gDialog.linearGradientStartingPointMenulist.value
                                                          : "";
  var hOffset = gDialog.linearGradientHorizOffsetCheckbox.checked ? gDialog.linearGradientHorizOffset.value
                                                          : "";
  var type = gDialog.shapeAndSizeTab.hidden
             ? (gDialog.repeatingGradientCheckbox.checked ? "-moz-repeating-linear-gradient(" : "-moz-linear-gradient(")
             : (gDialog.repeatingGradientCheckbox.checked ? "-moz-repeating--radial-gradient(" : "-moz-radial-gradient(");
  var str = type + ((angle || startingPoint) ? angle + " " + startingPoint + "," : "");
  if (!gDialog.shapeAndSizeTab.hidden) {
    var shape = gDialog.radialGradientShape.selectedItem.value;
    var size  = gDialog.radioGradientSize.value;
    str += ((shape || size) ? shape + " " + size + "," : "");
  }

  var stops = gDialog.colorStopsRichlistbox.querySelectorAll("richlistitem.colorstopitem");
  for (var i = 0; i < stops.length; i++) {
    if (i)
      str += ", ";
    var s = stops[i];
    str += s.color + (s.offset ? " " + s.offset : "");
  }
  str += ")";
  gDialog.linearGradientPreview.style.backgroundImage = str;
}

function SetLinearGradient()
{
  var gradient = gDialog.linearGradientPreview.style.backgroundImage;
  var item = gDialog.backgroundsRichlistbox.selectedItem;
  item.getChild("backgrounditemButton").style.backgroundImage = gradient;
  item.parsedValue = CssInspector.parseBackgroundImages(gradient)[0].value;
  gDialog.linearGradientPanel.hidePopup();
  ReapplyBackgrounds();
}

function UpdateColorStopsRichlistbox()
{
  var item = gDialog.colorStopsRichlistbox.selectedItem;
  if (gDialog.colorStopsRichlistbox.itemCount && item &&
      item.parentNode) {
    gDialog.removeColorStopButton.disabled = false;
    gDialog.upColorStopButton.disabled = !item.previousElementSibling;
    gDialog.downColorStopButton.disabled = !item.nextElementSibling;
  }
  else {
    gDialog.removeColorStopButton.disabled = true;
    gDialog.upColorStopButton.disabled = true;
    gDialog.downColorStopButton.disabled = true;
  }
  gDialog.linearGradientOkButton.disabled = (gDialog.colorStopsRichlistbox.itemCount < 2);
}

function AddColorStopToLinearGradient()
{
  var e = document.createElement("richlistitem");
  e.className = "colorstopitem";
  gDialog.colorStopsRichlistbox.appendChild(e);
  UpdateColorStopsRichlistbox();
  e.openEditor();
}

function DeleteColorStopFromLinearGradient()
{
  gDialog.colorStopsRichlistbox.removeChild(gDialog.colorStopsRichlistbox.selectedItem);
  UpdateColorStopsRichlistbox();
}

function FlushBackgroundProperties(aEvent)
{
  var target = aEvent.originalTarget;
  while (target && !target.hasAttribute("property"))
    target = target.parentNode;
  var property = target.getAttribute("property");
  var anonid = target.getAttribute("anonid");

  var valueArray = []
  var items = document.querySelectorAll("richlistitem.backgrounditem");
  for (var i = 0; i < items.length; i++) {
    var xulElt = items[i].getChild(anonid);
    valueArray.push( xulElt.value );
  }
  // cleanup
  for (var i = valueArray.length - 1 ; i >=0; i++)
    if (valueArray[i] == "")
      valueArray.pop();
    else
      break;
  ApplyStyles([
                {
                  property: property,
                  value: valueArray.join(", ")
                }
              ]);
}

function ToggleRelativeOrAbsoluteBackgroundImage()
{
  if (gDialog.relativeBackgroundImageCheckbox.checked) {
    MakeRelativeUrlBackgroundImage();
  }
  else {
    MakeAbsoluteUrlBackgroundImage();
  }
}

function MakeRelativeUrlBackgroundImage()
{
  var spec = gDialog.imageURLTextbox.value;
  var docUrl = EditorUtils.getDocumentUrl();
  var docUrlScheme = UrlUtils.getScheme(docUrl);
  if (docUrlScheme && docUrlScheme != "resource") {
    spec = UrlUtils.makeRelativeUrl(spec);
    gDialog.imageURLTextbox.value = spec;
    gDialog.relativeBackgroundImageCheckbox.checked = true;
  }
}

function MakeAbsoluteUrlBackgroundImage()
{
  var spec = gDialog.imageURLTextbox.value;
  var docUrl = EditorUtils.getDocumentUrl();
  var docUrlScheme = UrlUtils.getScheme(docUrl);
  if (docUrlScheme && docUrlScheme != "resource") {
    spec = UrlUtils.makeAbsoluteUrl(spec);
    gDialog.imageURLTextbox.value = spec;
    gDialog.relativeBackgroundImageCheckbox.checked = false;
  }
}
