<%@ include file="/portal/include/include_java.jsp" %>
<c:set var="ENTER_EXPRESSION_TEXT" value="Enter an Expression" scope="page"/>
<fieldset id="choicesSnippet">
  <div class="legend">Choices</div>
  <div id="choicesSnippet_importChoices" class="fields">
    <label for="choicesSnippet_importChoices_values" class="displayInline">
      <input value="literal" type="radio" class="radio" name="importChoices" data="importChoices" id="choicesSnippet_importChoices_values"/>Enter values below
    </label>
    <label for="choicesSnippet_importChoices_processData" class="displayInline" id="choicesSnippet_importChoices_label">
      <input value="data" type="radio" class="radio" name="importChoices" data="importChoices" id="choicesSnippet_importChoices_processData" />Choose process data
    </label>
  </div>
  <div class="fields">
  <label for="subType" class="displayInline">Data Type</label>
  <select data="subType" name="subType" id="subType">
    <option value="community">Community</option>
    <option value="content">Content</option>
    <!--<option value="date">Date</option>
    <option value="datetime">Date & Time</option>-->
    <option value="document">Document</option>
    <option value="email">Email Address</option>
    <option value="email_recipient">Email Recipient</option>
    <option value="folder">Folder</option>
    <option value="forum">Forum</option>
    <option value="group">Group</option>
    <option value="decimal">Number (Decimal)</option>
    <option value="integer">Number (Integer)</option>
    <option value="knowledge_center">Knowledge Center</option>
    <option value="message">Message</option>
    <option value="people">People</option>
    <option value="page">Portal page</option>
    <option value="text">Text</option>
    <!--<option value="time">Time</option>-->
    <option value="topic">Topic</option>
    <option value="user">User</option>
  </select>
  </div>
  <div id="choicesSnippet_specifyChoices">
    <table>
      <thead id="choicesSnippet_choicesHeader"><tr><th>&nbsp;</th><th>Display Label</th><th>Value</th><th>&nbsp;</th></tr></thead>
      <tbody id="choicesSnippet_options">
        <tr class="cloneable" exclude="true">
          <td>
            <img class="choicesSnippetDefaultButton" src="<asi:url value='/forms/img/light_off.gif' />" alt="Set as default" />
          </td>
          <td class="tableInput pickers">
            <input type="text" name="label" data="label" id="choicesSnippet_specifyChoices_label_"/>
          </td>
          <td class="tableInput pickers">
            <input type="text" name="id" data="id" id="choicesSnippet_specifyChoices_id_"/><button><p:img page="/components/toolbar/img/delete_toolbar.gif" alt="Delete this choice" /></button>
          </td>
        </tr>
      </tbody>
    </table>
    <a href="#" class="cloner snippetTool"><p:img page="/components/toolbar/img/add.gif" alt="Add a choice" />Add a choice</a>
    <p class="errorMessage"></p>
  </div>
  <div id="choicesSnippet_choicesFromData">
    <div class="fields">
      <label for="choicesSnippet_choicesFromData_displayLabels" class="displayInline">Display Label</label><input type="text" value="<c:out value='${ENTER_EXPRESSION_TEXT}'/>" name="displayLabels" data="displayLabels" id="choicesSnippet_choicesFromData_displayLabels"/><img src="<asi:url value='/components/expeditor/img/openEditor.gif' />" alt="Open Expression Editor" name="displayLabelsEE" expEdCaller="displayLabels"/>
     </div>
    <div class="fields">
      <label for="choicesSnippet_choicesFromData_displayValues" class="displayInline">Value</label><input type="text" name="displayValues" data="displayValues" value="<c:out value='${ENTER_EXPRESSION_TEXT}'/>" id="choicesSnippet_choicesFromData_displayValues"/><img src="<asi:url value='/components/expeditor/img/openEditor.gif' />" alt="Open Expression Editor" name="displayValuesEE" expEdCaller="displayValues"/>
    </div>
    <div class="fields">
      <label for="optionsSnippet_choicesFromData_defaultValue" class="displayInline">Default Value</label><input type="text" value="<c:out value='${ENTER_EXPRESSION_TEXT}'/>"  name="defaultChoice" data="defaultChoice" id="optionsSnippet_choicesFromData_defaultValue"/><img src="<asi:url value='/components/expeditor/img/openEditor.gif' />" alt="Open Expression Editor" name="defaultChoiceEE" expEdCaller="defaultChoice"/>
    </div>
    <p class="errorMessage"></p>
  </div>
</fieldset>
<script type="text/javascript">
    //************** Initialize Variables ***********************//
    var processDataFields = $('#choicesSnippet_choicesFromData');
    var importChoices = $('[@data="importChoices"]', $('#choicesSnippet_importChoices').get(0));
    var appianTypeDropdown = $("select", $("#choicesSnippet").get(0));
    var namespace = window.FormDesigner.currentNamespace;
    var configData = window.FormData[namespace][window.componentKey];
    appianTypeDropdown.read(configData);

    if (!configData.choices.selected) {
      configData.choices.selected = [];
    }

    var choicesSnippet = {
      /**
      * The appian type of the values.
      */
      subType : appianTypeDropdown.val(),
      /**
      * Helper variable to keep track of how many rows have been added.
      */
      counter : 0,
      /**
      * Flag variable to enabling and disabling the call to window.Build.rebuild
      * in the onclone function.
      */
      rebuild : true,
      /**
      * Utility methods that turns off all default buttons, and resets defaultValue and selected.
      */
      turnOffAllDefaultButtons : function(){
        var defaultButtons = $(".choicesSnippetDefaultButton", $("#choicesSnippet_options").get(0));
        defaultButtons.attr("src", "<asi:url value='/forms/img/light_off.gif' />");
        defaultButtons.attr("status", "off");
        var namespace = window.FormDesigner.currentNamespace;
        var configData = window.FormData[namespace][window.componentKey];
        configData.choices.selected = [];
        choicesSnippet.updateDefaultValues();
      },
      /**
      * Updates the defaultValue property in configData.
      * When the user directly enters the values of the labels and values, the data is in
      * configData.choices. This is a JS object composed of two properties: entries and selected.
      * 'entries' is an array of JS objects, each object composed of three properties: label, id and type.
      * 'selected' is an array of integers with the indexes of the selected default values.
      * In this case, 'defaultValue' can have different formats
      * @see https://wiki.appian.com/index.php/Forms_Improvements_Supplement#Reference
      * When the user enters an expression, the expression is stored as a string in 'configData.defaultChoice'.
      * At runtime, 'configData.defaultChoice' will be a JS object with the expression evaluated.
      */
      updateDefaultValues : function(){
        var namespace = window.FormDesigner.currentNamespace;
        var configData = window.FormData[namespace][window.componentKey];
        if (configData.importChoices === "literal") {
          if (configData.choices.selected.length === 0) {
            configData.defaultValue = null;
            return;
          }
          var index, entry;
          if (eval(configData.multiple) === true){
            configData.defaultValue = [];
            if (PICKER.isCompound(Mappings.FEtoPickerType(choicesSnippet.subType))) {
              for (var i = 0; i < configData.choices.selected.length; i++) {
                index = configData.choices.selected[i];
                entry = configData.choices.entries[index];
                configData.defaultValue.push({id:entry.id, type:entry.type});
              }
            } else {
              for (i = 0; i < configData.choices.selected.length; i++) {
                index = configData.choices.selected[i];
                entry = configData.choices.entries[index];
                configData.defaultValue.push(entry.id);
              }
            }
          } else {
            index = configData.choices.selected[0];
            entry = configData.choices.entries[index];
            if (PICKER.isCompound(Mappings.FEtoPickerType(choicesSnippet.subType))) {
              configData.defaultValue = {id:entry.id, type:entry.type};
            } else {
              configData.defaultValue = entry.id;
            }
          }
        } else if (configData.importChoices === "data"){
          if (typeof configData.defaultChoice === "string") {
            configData.defaultValue = configData.defaultChoice;
          } else if (typeof configData.defaultChoice === "object") {
            // defaultChoice can't be an object at design time #34561
            delete configData.defaultChoice;
            delete configData.defaultValue;
          }
        }
      },
      isPickerType : function(){
        return !!Mappings.FEtoPickerType(choicesSnippet.subType);
      },
      /**
      * This function needs to get called to clean up the pickers.
      * Otherwise, there will be memory leaks in IE6.
      */
      destroyPickers : function(){
        if (choicesSnippet.isPickerType()) {
          for (var i = 0; i < choicesSnippet.counter; i++) {
            PICKER.destroy('asiFormPicker_choicesSnippet{0}_'.supplant(i));
          }
        }
      },
      displayHeader : function(){
        var configData = window.FormData[window.FormDesigner.currentNamespace][componentKey];
        $('#choicesSnippet_choicesHeader')[configData.choices.entries.length==0 ? 'hide' : 'show']();
      },
      displayChoiceValueErrors : function(){
        var configData = window.FormData[window.FormDesigner.currentNamespace][componentKey];
        if (configData.choices.error) {
          $("#choicesSnippet_specifyChoices .errorMessage").html(configData.choices.error.message).show();
        } else {
          $("#choicesSnippet_specifyChoices .errorMessage").hide();
        }
      }
    };

    //************** Initialize Data ***********************//
    importChoices.read(configData);
    toogleImportChoices(configData.importChoices);

    appianTypeDropdown.change(function(){
      var configData = window.FormData[window.FormDesigner.currentNamespace][componentKey];
      appianTypeDropdown.write(configData);
      choicesSnippet.subType = this.value;
      choicesSnippet.destroyPickers();
      $("#choicesSnippet_specifyChoices tbody").find(".clone").remove();
      choicesSnippet.counter = 0;
      configData.choices.selected = [];
      configData.defaultChoice = undefined;
      $("#optionsSnippet_choicesFromData_defaultValue").val("<asi:out value='${ENTER_EXPRESSION_TEXT}' encoding='js'/>");
      choicesSnippet.updateDefaultValues();
      var cloner = $("#choicesSnippet_specifyChoices .cloner");
      var numEntries = configData.choices.entries.length;
      choicesSnippet.rebuild = false;
      var i = 0;
      for(i=0; i<(numEntries-1); i++) {
        configData.choices.entries[i] = {
          label:configData.choices.entries[i].label
        };
        cloner.click();
      }
      choicesSnippet.rebuild = true;
      configData.choices.entries[i] = {
          label:configData.choices.entries[i].label
      };
      cloner.click(); // we just need to rebuild on the last row added
      $(this).trigger(EVENT_SUBTYPE_CHANGED);
      window.Build.rebuild(configData.namespace, configData.key);
    });

    processDataFields.find('[@data]').filter('[@type="text"]').each(function(){
      $(this).read(window.FormData[window.FormDesigner.currentNamespace][componentKey]);
      if(this.value==="" || this.value==='<asi:out value="${ENTER_EXPRESSION_TEXT}" encoding="js"/>'){
        this.value='<asi:out value="${ENTER_EXPRESSION_TEXT}" encoding="js"/>'; 
      } else{
        this.style.color="black";
      }
      $(this).change(function(){
        $(this).write(window.FormData[window.FormDesigner.currentNamespace][componentKey]);
        choicesSnippet.updateDefaultValues();
        window.Build.rebuild(window.FormDesigner.currentNamespace, componentKey);
      });
    });

    $('#choicesSnippet_specifyChoices .cloneable').Cloneable({
      cloner: '#choicesSnippet_specifyChoices .cloner',
      onclone: function () {
        var clone = this;

        $("#choicesSnippet_specifyChoices .errorMessage").hide();

        $(clone).removeClass('cloneable');
        var index = Object.getIndex(clone);

        var label = $(this).find("[@data=label]").get(0);
        var input = $(this).find("[@data=id]").get(0);

        label.id = label.id + choicesSnippet.counter;
        input.id = input.id + choicesSnippet.counter;

        // attach the delete functionality to delete button.
        $('button', clone).click(function () {
          index = Object.getIndex(this);
          var configData = window.FormData[window.FormDesigner.currentNamespace][componentKey];
          var idx = configData.choices.selected.indexOf(index);
          if(idx) {
            configData.choices.selected.splice(idx,1);
            choicesSnippet.updateDefaultValues();
          }
          configData.choices.entries.splice(index, 1);
          $(clone).unbind().remove();
          choicesSnippet.displayHeader();
          window.Build.rebuild(configData.namespace, configData.key);
        });

        // if no value present, create new entry in the configuration object
        var configData = window.FormData[window.FormDesigner.currentNamespace][componentKey];
        if (!configData.choices.entries[index]) {
          configData.choices.entries[index] = {};
        }

        // write the value to the configuration object onchange
        var clonedElements = $(clone).find("[@type='text']");
        clonedElements.change(function() {
          var self = $(this);
          var configData = window.FormData[window.FormDesigner.currentNamespace][componentKey];
          index = Object.getIndex(this);
          self.write(configData.choices.entries[index]);
          window.FormDesigner.DefaultConfValidation.choices(componentKey);
          choicesSnippet.displayChoiceValueErrors();
          if ((configData.choices.selected.contains(index)) && (self.attr("name") == "id")) {
            choicesSnippet.updateDefaultValues();
          }
          window.Build.rebuild(configData.namespace, configData.key);
        });
        // prepopulate
        clonedElements.read(configData.choices.entries[index]);

        var status = configData.choices.selected.contains(index) ? "on" : "off";
        var defaultButton = $(".choicesSnippetDefaultButton", $(clone));
        if (status == "on") {
          defaultButton.attr("src", "<asi:url value='/forms/img/light_on.gif' />");
        } else {
          defaultButton.attr("src", "<asi:url value='/forms/img/light_off.gif' />");
        }
        defaultButton.attr("status", status).click(function(){
          var self = $(this);
          var configData = window.FormData[window.FormDesigner.currentNamespace][componentKey];
          index = Object.getIndex(this);

          var newStatus = self.attr("status") == "on" ? "off" : "on";
          if (newStatus == "on") {
            if (eval(configData.multiple) !== true) {
              choicesSnippet.turnOffAllDefaultButtons();
            }

            self.attr("src", "<asi:url value='/forms/img/light_on.gif' />");

            configData.choices.selected.push(index);

          } else {
            self.attr("src", "<asi:url value='/forms/img/light_off.gif' />");

            var i = configData.choices.selected.indexOf(index);
            configData.choices.selected.splice(i,1);

          }
          choicesSnippet.updateDefaultValues();
          self.attr("status", newStatus);
          window.Build.rebuild(configData.namespace, configData.key);
        });

        var pickerType = Mappings.FEtoPickerType(choicesSnippet.subType);
        if (pickerType) {
          var entry = configData.choices.entries[index];
          var pickedItems;
          if (entry.id) {
            pickedItems = [entry];
            pickedItems[0].display = getDisplayNameForId(pickedItems[0].type, pickedItems[0].id);
          }
          var picker = PICKER.lazyLoad(input, {
            pickerType:pickerType,
            singlePicker:true,
            id:'choicesSnippet'+choicesSnippet.counter,
            textfield:input.id,
            pickedItems:pickedItems,
            onpickCallback : function(){
              var pickedItems = this.getDescriptorsArray();
              if (pickedItems.length == 1) {
                index = Object.getIndex($("#"+this.autocompleteReference.id));
                var configData = window.FormData[window.FormDesigner.currentNamespace][componentKey];
                configData.choices.entries[index].id = pickedItems[0].id;
                configData.choices.entries[index].type = pickedItems[0].type;
                setAppianDisplayName(pickedItems[0].type, pickedItems[0].id, pickedItems[0].display);
                if (configData.choices.selected.contains(index)) {
                  choicesSnippet.updateDefaultValues();
                }
              }
            }
          });
        }

        choicesSnippet.counter++;
        choicesSnippet.displayHeader();
        if(choicesSnippet.rebuild) {
          window.Build.rebuild(configData.namespace, configData.key);
        }
      }
    });

    Snippets.attachEELauncher($('#choicesSnippet_choicesFromData img'));

    //**************  Define Listeners (including necessary triggers) ***********************//
    importChoices.delegate({
      resolver: function (importChoices) {
        toogleImportChoices(importChoices);
        $(this).write(window.FormData[window.FormDesigner.currentNamespace][componentKey]);
        window.Build.rebuild(window.FormDesigner.currentNamespace, componentKey);
      }
    });

    var choicesFromDataInputs = $('#choicesSnippet_choicesFromData input');
    choicesFromDataInputs.click(function(){
      Snippets.clearDefaultExpressionValue(this);
    });
    choicesFromDataInputs.blur(function(){
      var problem = window.FormDesigner.DefaultConfValidation.choices(componentKey);
      var errorContainer = $("#choicesSnippet_choicesFromData .errorMessage");
      if (problem) {
        errorContainer.html(problem.message).show();
      } else {
        errorContainer.hide();
      }
    });

    // Click the cloner button for each element that already exists.
    var cloner = $("#choicesSnippet_specifyChoices .cloner");
    if (configData.choices.entries) {
      var numEntries = configData.choices.entries.length;
      if (numEntries === 0) {
        // add one empty entry.
        cloner.click();
      } else {
        choicesSnippet.rebuild = false;
        for(var i=0; i<(numEntries-1); i++) {
          cloner.click();
        }
        choicesSnippet.rebuild = true;
        cloner.click(); // we just need to rebuild on the last row added
      }
      choicesSnippet.displayChoiceValueErrors();
    } else {
      configData.choices.entries = [];
      // add one empty entry.
      cloner.click();
    }

    //************** Define Remote Listeners ***********************//
    //Listening for a change to the allow multiple value of the component
    $('#optionsSnippet [@name="multiple"]').bind(EVENT_MULTIPLE_CHANGED, function(){
      choicesSnippet.turnOffAllDefaultButtons();
      window.Build.rebuild(window.FormDesigner.currentNamespace, componentKey);
    });

    $('#configPane').bind("destroy", choicesSnippet.destroyPickers);
    //************** Utility Functions ***********************//
    function toogleImportChoices(value) {
      $('#choicesSnippet_choicesFromData')[value === 'data' ? 'show' : 'hide']();
      $('#choicesSnippet_specifyChoices')[value === 'literal' ? 'show' : 'hide']();
      choicesSnippet.updateDefaultValues();
    }

    choicesSnippet.displayHeader();
</script>
