/* Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved. */
/* ------------------------------------------------------ */
/* ------------------- amx-inputDate.js ----------------- */
/* ------------------------------------------------------ */

(function() {
// TODO finish the migration from "amx.*" to "adf.mf.api.amx.*" and "adf.mf.internal.amx.*"

  var amxRenderers = {
    inputDate: function(amxNode) {
      amx.registerInputValue(amxNode, "value");
      // MDO - converters support is deprecated; remove any converters added by old apps
      delete amxNode.converter;
      var field = amx.createField(amxNode);
      var $node = field.$node;
      //var $dateLabel = $("<div class='dateLabel'></div>");
      var dateObject = new Date(amxNode.value);
      var value;
      var inputType = "date";
      if (amxNode.inputType === "time")
      {
        inputType = "time";
        value = adf.mf.internal.amx.extractTimeFromDateObject(dateObject);
      }
      else if (amxNode.inputType === "datetime")
      {
        inputType = "datetime";
        value = amxNode.value;
      }
      else
      {
        value = adf.mf.internal.amx.extractDateFromDateObject(dateObject);
      }
      
      var $dateLabel = $("<input></input>");
      $dateLabel.attr("type", inputType);
      field.$value.append($dateLabel);
      $dateLabel.attr("value", value);
      $dateLabel.data("value", dateObject);
      $dateLabel.blur(function(event)
      {
        var oldValue = $dateLabel.data("value");
        var newValue;
        if (inputType === "time")
        {
          newValue = new Date(oldValue.getTime());
          adf.mf.internal.amx.updateTime(newValue, $dateLabel.val());
        }
        else if (inputType === "date")
        {
          newValue = new Date(oldValue.getTime());
          adf.mf.internal.amx.updateDate(newValue, $dateLabel.val());
        }
        else
        {
          newValue = new Date($dateLabel.val());
          newValue.setMilliseconds(oldValue.getMilliseconds());
        }
        if (newValue.getTime() != oldValue.getTime())
        {
          var vce = new amx.ValueChangeEvent(oldValue.toISOString(), newValue.toISOString());
          amx.processAmxEvent($node, "valueChange", "value", newValue.toISOString(), vce);
        }
        $dateLabel.data("value", newValue);
      });
      
      //if readOnly
      if(amxNode.readOnly == true)
      {
        $dateLabel.attr("readOnly", "true");
      }
      
      //if disabled
      if(amxNode.disabled == true)
      {
        $dateLabel.attr("disabled", amxNode.disabled);
      }

      // calls applyRequiredMarker in amx-core.js to determine and implement required/showRequired style
      adf.mf.api.amx.applyRequiredMarker(amxNode, field);
      return $node;
    }

  }; // /var amxRenderers

  // add this renderer
  amx.registerRenderers("amx",amxRenderers);

})();

