$(function() {
  // the datetimepicker has a bug that prevents the icon from appearing. So
  // instead, we add the image manually into the page and assign the open event
  // handler to the image
  var default_settings = {
    changeYear: true,
    changeMonth: true
  }
  $(".cf_datepicker").each(function() {
    var field_name = $(this).attr("name");
    var settings = default_settings;
    if ($("#" + field_name + "_id").length) {
      settings.dateFormat = $("#" + field_name + "_format").val();
    }
    $(this).datepicker(settings);
    $("#" + field_name + "_icon_id").bind("click", { field_id: "#" + field_name + "_id" }, function(e) {
      $.datepicker._showDatepicker($(e.data.field_id)[0]);
    });
  });
  
  $(".cf_datetimepicker").each(function() {
    var field_name = $(this).attr("name");
    var settings = default_settings;

    if ($("#" + field_name + "_id").length) {
      var settings_str = $("#" + field_name + "_format").val();
      settings_str = settings_str.replace(/datetime:/, "");
      var settings_list = settings_str.split("|");
      var settings = {};
      settings.dateFormat = settings_list[0];
      settings.timeFormat = settings_list[1];
      for (var i=2; i<settings_list.length; i++) {
        var parts = settings_list[i].split("`");
        if (parts[1] === "true") {
          parts[1] = true;
        }
        settings[parts[0]] = parts[1];
      }
    }
    
    $(this).datetimepicker(settings);
    $("#" + field_name + "_icon_id").bind("click", { 
      field_id: "#" + field_name + "_id"
    }, function(e) {
      $.datepicker._showDatepicker($(e.data.field_id)[0]);
    });
  });
});