// WoodOption: Represents a possible wood option. Stored in WoodSelections.xml
// WoodSelectionOption: Represents a wood selection option for a particular product. Defined in product page

// Represents a possible option
function woodSelection(sourceNode) {
  this.mode = "wood";
  this.caption = this.getCaption(sourceNode);
  this.swatchImage = this.getSwatchImage(sourceNode);
  this.description = this.getDescription(sourceNode);
}
woodSelection.prototype.getCaption = function(node) {
  var val = node.getAttribute("woodType");
  if (!val || val == String.empty) {
    val = node.getAttribute("squareSize");
    this.mode = "square";
  }
  return val;
};
woodSelection.prototype.getSwatchImage = function(node) {
  return node.getAttribute("swatchImage");
};
woodSelection.prototype.getDescription = function(node) {
  return $("description:first", node).text();
};

// Represents an individual selection associated with a product
function woodSelectionOption(manager, itemTextInitializer) {
  this.manager = manager;
  this.price = 0;
  this.outOfStockFlag = false;
  this.uniqueId = String.empty;
  this.caption = String.empty;
  this.outOfStockMessage = String.empty;
  this.swatchImage = String.empty;
  this.description = String.empty;
  this.itemIndex = 0;
  this.woodSelectorNode = String.empty;
  this.captionEl = String.empty
  this.checkboxEl = String.empty;
  this.woodSelectorAltNode = String.empty;
  this.captionAltEl = String.empty
  this.checkboxAltEl = String.empty;
  this.priceEl = String.empty;
  this.priceAltEl = String.empty;
  this.isDefault = false;
  this.mode = String.empty;

  this.initializeMe(itemTextInitializer);

  return this;
}
woodSelectionOption.prototype.initializeMe = function(itemTextInitializer) {
  var oThis = this;
  if (itemTextInitializer.indexOf("*") != -1) {
    this.isDefault = true;
    itemTextInitializer = itemTextInitializer.replace("*", String.empty);
  }
  var item = itemTextInitializer.split(";")

  this.itemIndex  = item[0];
  this.price    = parseFloat(item[1]);
  this.outOfStockFlag = (item[2]) ? item[2] == 1 : false;
  this.outOfStockMessage = (item[3]) ? item[3] : String.empty;
  this.uniqueId  = "woodSelectionOption" + this.itemIndex;
  if (this.manager.allSelectionOptions.length > this.itemIndex) {
    this.caption   = this.manager.allSelectionOptions[this.itemIndex].caption;
    this.swatchImage = this.manager.allSelectionOptions[this.itemIndex].swatchImage;
    this.description = this.manager.allSelectionOptions[this.itemIndex].description;
    this.mode = this.manager.allSelectionOptions[this.itemIndex].mode;
  }

  if (this.manager.isMultiplePricing) {
    this.generateMultiSelectOption(false);
    this.generateMultiSelectOption(true);
    this.optionQuantityEl.blur(function() {
      oThis.optionQuantityAltEl.val(oThis.optionQuantityEl.val());
    });
    this.optionQuantityAltEl.blur(function() {
      oThis.optionQuantityEl.val(oThis.optionQuantityAltEl.val());
    });
  } else {
    this.generateSingleSelectOption(false);
    this.generateSingleSelectOption(true);
    this.deselect();
  }
};
woodSelectionOption.prototype.select = function() {
 if (!this.manager.isMultiplePricing) {
  this.checkboxEl.attr("checked", "checked");
  this.checkboxAltEl.attr("checked", "checked");
  this.checkboxEl.attr("id", "baseOptionSelected");
  this.captionEl.attr("for", "baseOptionSelected");
  this.manager.selectedOption = this;
 }
};
woodSelectionOption.prototype.deselect = function() {
  this.checkboxEl.removeAttr("checked");
  this.checkboxAltEl.removeAttr("checked");
  this.checkboxEl.attr("id", this.uniqueId);
  this.captionEl.attr("for", this.uniqueId);
};

woodSelectionOption.prototype.generateMultiSelectOption = function(isAlt) {
  var wrapperEl = $("<div></div>");
  var imgEl = $("<img />");
  var captionEl = $("<span></span>");
  var optionQuantityEl = $("<input type=\"text\" />");
  var priceEl = $("<span></span>");

  wrapperEl.addClass("woodSelectionMultiItem");
  captionEl.addClass("woodSelectionMultiItemCaption");

  captionEl.text(this.caption);
  imgEl.attr("src", "http://houseofstaunton.com/KingCart/Common/Image/Swatch/" + this.swatchImage);
  imgEl.attr("alt", this.caption);

  wrapperEl.append(captionEl);
  wrapperEl.append(imgEl);
  wrapperEl.append("<br />");

  if (this.outOfStockFlag) {
    var oosEl = $("<span></span>");
    var oosMessage = "Out of Stock";
    if (this.outOfStockMessage != String.empty)
      oosMessage = " {0}: {1}".format(oosMessage, this.outOfStockMessage);
    else
      oosMessage = "  ({0}) ".format(oosMessage);
    oosEl.addClass("woodSelectionOutOfStock");
    oosEl.text(oosMessage);
    wrapperEl.append(oosEl);
  } else if (this.outOfStockMessage != String.empty) {
    var oosEl = $("<span></span>");
    var oosMessage = " {0}".format(this.outOfStockMessage);
    oosEl.addClass("woodSelectionOutOfStock");
    oosEl.text(oosMessage);
    wrapperEl.append(oosEl);
  } else {
   optionQuantityEl.attr("value", 0);
   optionQuantityEl.addClass("multiplePricingQuantityField");
   optionQuantityEl.blur(this.manager.getWoodSelectionClickFunction(this));

   if (!isAlt)
     optionQuantityEl.attr("name", "option|Material Selection-{0}|{1}".format(this.caption, this.manager.productInstance.parseProductId()));
   wrapperEl.append(document.createTextNode("Qty: "));
   wrapperEl.append(optionQuantityEl);
  }

  if (!isAlt) {
    this.woodSelectorNode = wrapperEl;
    this.captionEl = captionEl;
    this.optionQuantityEl = optionQuantityEl;
    this.priceEl = priceEl;
  }
  else {
    this.woodSelectorAltNode = wrapperEl;
    this.captionAltEl = captionEl;
    this.optionQuantityAltEl = optionQuantityEl;
    this.priceAltEl = priceEl;
  }
};


woodSelectionOption.prototype.generateSingleSelectOption = function(isAlt) {
  var wrapperEl = $("<div></div>");
  var captionEl = $("<label></label>");
  var priceEl = $("<span></span>");
  var checkboxEl = $("<input type=\"radio\"></input>");
  var prefix = "";

  wrapperEl.addClass("woodSelectionItem");

  captionEl.addClass("woodSelectionItemCaption");
  captionEl.text(this.caption + ": ");

  priceEl.addClass("woodSelectionPrice");

  prefix = (this.mode == "square") ? "Square Size" : "Material Selection";
  checkboxEl.val(prefix + " - " + this.caption + ": |" + formatDollar(this.price) + " ea");
  checkboxEl.click(this.manager.getWoodSelectionClickFunction(this));

  if (!isAlt)
    checkboxEl.attr("name", "option|1|" + this.manager.productInstance.parseProductId());

  captionEl.append(priceEl);

  if (this.outOfStockFlag) {
    var oosEl = $("<span></span>");
    var oosMessage = "Out of Stock";
    if (this.outOfStockMessage != String.empty)
     oosMessage = " {0}: {1}".format(oosMessage, this.outOfStockMessage);
    else
     oosMessage = "  ({0}) ".format(oosMessage);
    oosEl.addClass("woodSelectionOutOfStock");
    oosEl.text(oosMessage);
    captionEl.append(oosEl);
    checkboxEl.css("display", "none");
  } else if (this.outOfStockMessage != String.empty) {
    var oosEl = $("<span></span>");
    var oosMessage = " {0}".format(this.outOfStockMessage);
    oosEl.addClass("woodSelectionOutOfStock");
    oosEl.text(oosMessage);
    captionEl.append(oosEl);
    // checkboxEl.css("display", "none");
  }

  wrapperEl.append(captionEl);
  wrapperEl.append(checkboxEl);

  if (!isAlt) {
    this.woodSelectorNode = wrapperEl;
    this.captionEl = captionEl;
    this.checkboxEl = checkboxEl;
    this.priceEl = priceEl;
  }
  else {
    this.woodSelectorAltNode = wrapperEl;
    this.captionAltEl = captionEl;
    this.checkboxAltEl = checkboxEl;
    this.priceAltEl = priceEl;
  }
};
woodSelectionOption.prototype.updateDisplayPrice = function(basePrice) {
  var val = "$" + formatDollar(basePrice + this.price);
  this.priceAltEl.text(val);
  this.priceEl.text(val);
};

// Manages all the wood selection options
function woodSelectionManager(kingCartProductInstance) {
  this.isMultiplePricing = false;
  this.allSelectionOptions = new Array();
  this.xmlDoc;
  this.woodSelectionOptions = new Array();
  this.selectionContainerEl = String.empty;
  this.previewElementEl = String.empty;
  this.descriptionEl = String.empty;
  this.selectionContainerAltEl = String.empty;
  this.previewElementAltEl = String.empty;
  this.productInstance = kingCartProductInstance;
  this.selectedOption;
  this.productBasePrice = 0;
  this.woodSelectionChanged = function() {};
  this.availableOptionList;
  this.target = "Wood";
  this.onReadyForUse = new ClassEvent();

  this.initialize();
}
woodSelectionManager.prototype.initialize = function() {
  var productDetails = $("#quantitySelector").attr("name").split("|");
  this.isMultiplePricing = productDetails[2].split(",").length > 1;

  var SelectionChoiceListEl = $("#WoodSelectionChoiceList");
  if (SelectionChoiceListEl.length == 0) {
    SelectionChoiceListEl = $("#SquareSizeSelectionChoiceList");
    this.target = "SquareSize";
  }

  if (!SelectionChoiceListEl)
    return;

  this.availableOptionList = SelectionChoiceListEl.text();
  $.get(domHelper.getXmlDataPath() + this.target + "SelectionOptions.xml", this.getallSelectionOptionsLoaderFunction());
};
woodSelectionManager.prototype.getallSelectionOptionsLoaderFunction = function() {
  oThis = this;
  return function(data) {
   $("selection", data).each(function(i) {
    oThis.allSelectionOptions[i] = new woodSelection(this);
   });
   oThis.initializeWoodSelectionOptions();
   oThis.onReadyForUse.fire();
  };
};
woodSelectionManager.prototype.initializeWoodSelectionOptions = function() {
  var defaultIndex = 0;
  var items = this.availableOptionList.split("|");
  var oThis = this;

  this.selectionContainerEl = $("#woodSelectionOptionsContainer");
  this.previewElementEl = $("#woodSelectionOptionPreview");
  this.descriptionEl = $("#woodSelectionOptionDescription");
  this.selectionContainerAltEl = $("#woodSelectionOptionsContainerAlt");
  this.previewElementAltEl = $("#woodSelectionOptionPreviewAlt");

  if (this.isMultiplePricing) {
   this.previewElementEl.parent().parent().remove();
   this.descriptionEl.parent().remove();
   this.selectionContainerEl.parent().attr({width: "100%", colspan: "3"});
   this.selectionContainerEl.parent().parent().prev().remove();
   this.selectionContainerAltEl.attr("width", "100%");
   this.selectionContainerAltEl.parent().prev().remove();
   var b = $('<div style="padding-top: 165px"></div>').append($("#border7").parent().clone());
   this.selectionContainerAltEl.after(b);
   this.selectionContainerAltEl.parent().attr("align", "center");
  }

  this.selectionContainerEl.empty();
  this.selectionContainerAltEl.empty();

  $(items).each(function(i) {
   if (this != String.empty && oThis.addWoodSelectionOption(this).isDefault)
    defaultIndex = i;
  });

  this.woodSelectionOptions[defaultIndex].select();
  this.updateWoodSelectionText(this.woodSelectionOptions[defaultIndex]);
  this.showPreview(this.woodSelectionOptions[defaultIndex]);
};
woodSelectionManager.prototype.getWoodSelectionClickFunction = function(item) {
  var oThis = this;
  return function() {
   if (!oThis.isMultiplePricing) {
    oThis.resetWoodSelections();
    item.select();
    oThis.updateWoodSelectionText(item);
    oThis.showPreview(item);
   }
   oThis.woodSelectionChanged();
  };
};
woodSelectionManager.prototype.addWoodSelectionOption = function(itemText) {
  var newNode = new woodSelectionOption(this, itemText);
  this.woodSelectionOptions[this.woodSelectionOptions.length] = newNode;

  try {
    this.selectionContainerEl.append(newNode.woodSelectorNode);
    this.selectionContainerAltEl.append(newNode.woodSelectorAltNode);
  } catch (err) { }
  return newNode;
};
woodSelectionManager.prototype.resetWoodSelections = function() {
 $(this.woodSelectionOptions).each(function() {
  this.deselect();
 });
};
woodSelectionManager.prototype.showPreview = function(item) {
  var src = "http://houseofstaunton.com/KingCart/Common/Image/Swatch/" + item.swatchImage;
  try { // Preview Element is optional
    this.previewElementEl.attr("src", src);
    this.previewElementEl.attr("alt", item.caption);
    this.previewElementAltEl.attr("src", src);
    this.previewElementAltEl.attr("alt", item.caption);
  }
  catch (err) { }
};
woodSelectionManager.prototype.updateWoodSelectionText = function(item) {
 $(this.descriptionEl).html(item.description);
};
woodSelectionManager.prototype.updateOptionDisplayPrice = function(basePrice) {
  // A product's base price *can* vary, so each time it changes we update the price displayed by each option
  if (this.productBasePrice != basePrice) {
    this.productBasePrice = basePrice;
    for (i = 0; i < this.woodSelectionOptions.length; i++)
      this.woodSelectionOptions[i].updateDisplayPrice(this.productBasePrice);
  }
};