<?xml version="1.0" encoding="UTF-8"?>
<dynaForm name="additionalTables/additionalTablesNew" type="xmlform" width="900" enableTemplate="1">
  <TITLE1 type="title">
    <en><![CDATA[Table Information]]></en>
  </TITLE1>
  <ADD_TAB_UID type="hidden"/>
  <ADD_TAB_NAME type="text" size="60" maxlength="64" validate="Field" required="1">
    <en><![CDATA[Table Name]]></en>
  </ADD_TAB_NAME>
  <ADD_TAB_NAME_OLD type="hidden"/>
  <!-- renamed text by hidden -->
  <ADD_TAB_CLASS_NAME type="hidden" size="60" maxlength="100" validate="Field" required="0" readonly="1">
    <en>PHP Class Name</en>
  </ADD_TAB_CLASS_NAME>
  <ADD_TAB_CLASS_NAME_OLD type="hidden"/>
  <ADD_TAB_DESCRIPTION type="textarea" cols="70" rows="5" required="0">
    <en><![CDATA[Description]]></en>
  </ADD_TAB_DESCRIPTION>
  <TITLE2 type="title">
    <en><![CDATA[Log configuration]]></en>
  </TITLE2>
  <ADD_TAB_SDW_LOG_INSERT type="checkbox" defaultValue="on">
    <en><![CDATA[Save log for insert actions]]></en>
  </ADD_TAB_SDW_LOG_INSERT>
  <ADD_TAB_SDW_LOG_UPDATE type="checkbox" defaultValue="on">
    <en><![CDATA[Save log for update actions]]></en>
  </ADD_TAB_SDW_LOG_UPDATE>
  <ADD_TAB_SDW_LOG_DELETE type="checkbox" defaultValue="on">
    <en><![CDATA[Save log for delete actions]]></en>
  </ADD_TAB_SDW_LOG_DELETE>
  <!--<ADD_TAB_SDW_LOG_SELECT type="checkbox" defaultValue="off">
  <en>Save log for select actions</en>
</ADD_TAB_SDW_LOG_SELECT>

<ADD_TAB_SDW_MAX_LENGTH type="text" size="5" maxlength="10" required="1" defaultValue="-1">
  <en>Maximun rows to store (-1 for unlimited)</en>
</ADD_TAB_SDW_MAX_LENGTH>-->
  <ADD_TAB_SDW_AUTO_DELETE type="checkbox" defaultValue="off">
    <en><![CDATA[Delete related log when table is deleted]]></en>
  </ADD_TAB_SDW_AUTO_DELETE>
  <!--<ADD_TAB_STATUS type="hidden" defaultValue="ACTIVE" />-->
  <TITLE3 type="title">
    <en><![CDATA[Fields]]></en>
  </TITLE3>
  <FIELDS type="grid" xmlgrid="additionalTables/additionalTablesFields" addrow="1" deleterow="1" mode="edit"/>
  <btnSave type="button" onclick="verifyData(this.form);">
    <en><![CDATA[Save]]></en>
  </btnSave>
  <BTN_CANCEL type="button" onclick="cancel();">
    <en><![CDATA[Cancel]]></en>
  </BTN_CANCEL>
  <JS type="javascript"><![CDATA[
var onChangeType = function(iRow) {
  var iRow = iRow | this.name.split('][')[1];
  var oAux;
  switch (getGridField('FIELDS', iRow, 'FLD_TYPE').value) {
    case 'VARCHAR':
      oAux = getGridField('FIELDS', iRow, 'FLD_SIZE');
      oAux.readOnly = '';
      break;
    case 'TEXT':
      oAux = getGridField('FIELDS', iRow, 'FLD_SIZE');
      oAux.value = '';
      oAux.readOnly = 'readOnly';
      break;
    case 'DATE':
      oAux = getGridField('FIELDS', iRow, 'FLD_SIZE');
      oAux.value = '';
      oAux.readOnly = 'readOnly';
      break;
    case 'INT':
      oAux = getGridField('FIELDS', iRow, 'FLD_SIZE');
      oAux.readOnly = '';
      break;
    case 'FLOAT':
      oAux = getGridField('FIELDS', iRow, 'FLD_SIZE');
      oAux.readOnly = '';
      break;
  }
};

var onClickForeignKey = function(iRow) {
  var iRow = iRow | this.name.split('][')[1];
  var oAux = getGridField('FIELDS', iRow, 'FLD_FOREIGN_KEY_TABLE');
  if (getGridField('FIELDS', iRow, 'FLD_FOREIGN_KEY').checked) {
    oAux.disabled = false;
    oAux.value = '';
  }
  else {
    oAux.disabled = true;
    oAux.value = '';
  }
};
var aReservedWords = new Array('ADD','ALL','ALTER','ANALYZE','AND','AS','ASC','ASENSITIVE','BEFORE',
    'BETWEEN','BIGINT','BINARY','BLOB','BOTH','BY','CALL','CASCADE','CASE',
    'CHANGE','CHAR','CHARACTER','CHECK','COLLATE','COLUMN','CONDITION',
    'CONSTRAINT','CONTINUE','CONVERT','CREATE','CROSS','CURRENT_DATE',
    'CURRENT_TIME','CURRENT_TIMESTAMP','CURRENT_USER','CURSOR','DATABASE',
    'DATABASES','DAY_HOUR','DAY_MICROSECOND','DAY_MINUTE','DAY_SECOND','DEC',
    'DECIMAL','DECLARE','DEFAULT','DELAYED','DELETE','DESC','DESCRIBE',
    'DETERMINISTIC','DISTINCT','DISTINCTROW','DIV','DOUBLE','DROP','DUAL',
    'EACH','ELSE','ELSEIF','ENCLOSED','ESCAPED','EXISTS','EXIT','EXPLAIN',
    'FALSE','FETCH','FLOAT','FLOAT4','FLOAT8','FOR','FORCE','FOREIGN','FROM',
    'FULLTEXT','GRANT','GROUP','HAVING','HIGH_PRIORITY','HOUR_MICROSECOND',
    'HOUR_MINUTE','HOUR_SECOND','IF','IGNORE','IN','INDEX','INFILE','INNER',
    'INOUT','INSENSITIVE','INSERT','INT','INT1','INT2','INT3','INT4','INT8',
    'INTEGER','INTERVAL','INTO','IS','ITERATE','JOIN','KEY','KEYS','KILL',
    'LEADING','LEAVE','LEFT','LIKE','LIMIT','LINES','LOAD','LOCALTIME',
    'LOCALTIMESTAMP','LOCK','LONG','LONGBLOB','LONGTEXT','LOOP','LOW_PRIORITY',
    'MATCH','MEDIUMBLOB','MEDIUMINT','MEDIUMTEXT','MIDDLEINT','MINUTE_MICROSECOND',
    'MINUTE_SECOND','MOD','MODIFIES','NATURAL','NOT','NO_WRITE_TO_BINLOG','NULL',
    'NUMERIC','ON','OPTIMIZE','OPTION','OPTIONALLY','OR','ORDER','OUT','OUTER',
    'OUTFILE','PRECISION','PRIMARY','PROCEDURE','PURGE','READ','READS','REAL',
    'REFERENCES','REGEXP','RELEASE','RENAME','REPEAT','REPLACE','REQUIRE',
    'RESTRICT','RETURN','REVOKE','RIGHT','RLIKE','SCHEMA','SCHEMAS','SECOND_MICROSECOND',
    'SELECT','SENSITIVE','SEPARATOR','SET','SHOW','SMALLINT','SONAME','SPATIAL',
    'SPECIFIC','SQL','SQLEXCEPTION','SQLSTATE','SQLWARNING','SQL_BIG_RESULT',
    'SQL_CALC_FOUND_ROWS','SQL_SMALL_RESULT','SSL','STARTING','STRAIGHT_JOIN',
    'TABLE','TERMINATED','THEN','TINYBLOB','TINYINT','TINYTEXT','TO','TRAILING',
    'TRIGGER','TRUE','UNDO','UNION','UNIQUE','UNLOCK','UNSIGNED','UPDATE','USAGE',
    'USE','USING','UTC_DATE','UTC_TIME','UTC_TIMESTAMP','VALUES','VARBINARY',
    'VARCHAR','VARCHARACTER','VARYING','WHEN','WHERE','WHILE','WITH','WRITE',
    'XOR','YEAR_MONTH','ZEROFILL','ASENSITIVE','CALL','CONDITION','CONTINUE',
    'CURSOR','DECLARE','DETERMINISTIC','EACH','ELSEIF','EXIT','FETCH','INOUT',
    'INSENSITIVE','ITERATE','LEAVE','LOOP','MODIFIES','OUT','READS','RELEASE',
    'REPEAT','RETURN','SCHEMA','SCHEMAS','SENSITIVE','SPECIFIC','SQL',
    'SQLEXCEPTION','SQLSTATE','SQLWARNING','TRIGGER','UNDO','WHILE');
var verifyData = function(oForm) {
  if (oForm.onsubmit()) {
    var bContinue = true;
    var iMessage  = 0;
    var iRows     = Number_Rows_Grid('FIELDS', 'FLD_UID');
    var fieldsTmp = [];
    var words = '';
    for (var i = 1; i <= iRows; i++) {
      for(var j = 0; j < aReservedWords.length; j++ ) {
        if(getGridField('FIELDS', i, 'FLD_NAME').value == aReservedWords[j]) {
          words = words +" "+getGridField('FIELDS', i, 'FLD_NAME').value;
        }
      }
    }
    if (words != ''){
      new leimnud.module.app.alert().make({
        label:G_STRINGS.ID_FIELDS_RESERVED_WORDS + ' ' + words
      });
      words='';
      bContinue = false;
    }
    for (var i = 1; i <= iRows; i++) {
      if (getGridField('FIELDS', i, 'FLD_NAME').value == '') {
        bContinue = false;
        iMessage  = 1;
      }
      if (bContinue) {
        switch (getGridField('FIELDS', i, 'FLD_TYPE').value) {
          case 'VARCHAR':
            if (getGridField('FIELDS', i, 'FLD_SIZE').value == '') {
              bContinue = false;
              iMessage  = 2;
            }
            break;
          case 'TEXT':
            if (getGridField('FIELDS', i, 'FLD_KEY').checked ) {
              bContinue = false;
              iMessage  = 4;
            }
            break;
          case 'DATE':
            break;
          case 'INT':
            if (getGridField('FIELDS', i, 'FLD_SIZE').value == '') {
              bContinue = false;
              iMessage  = 2;
            }
            break;
          case 'FLOAT':
            if (getGridField('FIELDS', i, 'FLD_SIZE').value == '') {
              bContinue = false;
              iMessage  = 2;
            }
            break;
        }
      }
      // Check duplicate fields 
      if(bContinue) {
        if(!(getGridField('FIELDS', i, 'FLD_NAME').value.toUpperCase() in fieldsTmp)) {
          fieldsTmp[getGridField('FIELDS', i, 'FLD_NAME').value.toUpperCase()]++; 
        } else {
          bContinue = false;
          iMessage  = 5;
          sDuplicate = getGridField('FIELDS', i, 'FLD_NAME').value.toUpperCase();
        }
      }
      // Check invalid character
      if(bContinue){
        var sFld_name = getGridField('FIELDS', i, 'FLD_NAME').value;
        var firstChar = sFld_name.charAt(sFld_name);
        pattern =/[A-Za-z_]/; 
        if(pattern.test(firstChar) == false) {
          bContinue = false;
          iMessage  = 6;
          sInvalidCharacter = sFld_name;
        }
      }
      
    }
    
    var bContinueKey = false;
    for (var i = 1; i <= iRows; i++) {
      if (getGridField('FIELDS', i, 'FLD_KEY').checked) {
        bContinueKey = true;
      }
      if (getGridField('FIELDS', i, 'FLD_KEY').checked) {
        getGridField('FIELDS', i, 'FLD_KEY_HDN').value = "on" ;
      }
      if (getGridField('FIELDS', i, 'FLD_NULL').checked) {
        getGridField('FIELDS', i, 'FLD_NULL_HDN').value = "on" ;
      }
    }
    if (bContinue && bContinueKey) {
      oForm.submit();
    } else {
      if (!bContinue) {
        switch (iMessage) {
          case 1:
            new leimnud.module.app.alert().make({
              label:'@G::LoadTranslation(ID_FIELD_NAME_REQUIRED)'
            });
            break;
          case 2:
            new leimnud.module.app.alert().make({
              label:'@G::LoadTranslation(ID_FIELD_SIZE_REQUIRED)'
            });
            break;
          case 3:
            new leimnud.module.app.alert().make({
              label:G_STRINGS.ID_FIELD_FOREIGN_TABLE
            });
            break;
          case 4:
            new leimnud.module.app.alert().make({
              label:"@G::LoadTranslation(ID_FIELD_CANNOT_BE_PRIMARY_KEY)"
            });
            break;
          case 5:
            new leimnud.module.app.alert().make({
              label:"@G::LoadTranslation(ID_FIELD_DUPLICATE)" +  " " + sDuplicate
            });
            break;
          case 6:
            new leimnud.module.app.alert().make({
              label:"@G::LoadTranslation(ID_FIELD_INVALID)" + " " + sInvalidCharacter
            });
            break;
        }
      }
      else {
        new leimnud.module.app.alert().make({
          label:'@G::LoadTranslation(ID_FIELD_KEY_TABLE)' 
        });
      }
    }
    
  }
};

function LoadPMTable(){
  leimnud.event.add(getField('ADD_TAB_NAME'), 'change', function() {
    getField('ADD_TAB_NAME').value = getField('ADD_TAB_NAME').value.toUpperCase();
    var sTableNameOld = getField('ADD_TAB_NAME_OLD').value;
    var oSaveButton   = getField('btnSave');
    if (sTableNameOld != getField('ADD_TAB_NAME').value) {
      oSaveButton.disabled = true;
      var oRPC = new leimnud.module.rpc.xmlhttp({
        url   : '../additionalTables/additionalTablesAjax',
        async : false,
        method: 'POST',
        args  : 'action=tableExists&sTableName=' + getField('ADD_TAB_NAME').value
      });
      oRPC.make();
      if (oRPC.xmlhttp.responseText == '1') {
        new leimnud.module.app.alert().make({
          label:'@G::LoadTranslation(ID_TABLE_ALREADY_EXISTS)'
        });
      }
      else {
        oSaveButton.disabled = false;
      }
    }
    else {
      if (sTableNameOld != '') {
        oSaveButton.disabled = false;
      }
    }

    var aAux = getField('ADD_TAB_NAME').value.split('_');
    var sAux = '';
    var i;
    for (i = 0; i < aAux.length; i++) {
      var sChar = aAux[i].substring(0,1).toUpperCase();
      sAux += sChar + aAux[i].substring(1,aAux[i].length).toLowerCase();
    }
    pattern =/[A-Za-z_]/; 
    var first = sAux.charAt(sAux);
    if(pattern.test(first) == false) {
      sAux = '_' + sAux;;
    }
    getField('ADD_TAB_CLASS_NAME').value = sAux;

    
    // Validate ilegal character 
    var sTbl_name = getField('ADD_TAB_NAME').value.toUpperCase();
    var firstChar = sTbl_name.charAt(sTbl_name);
    pattern =/[A-Za-z_]/; 
    if(pattern.test(firstChar) == false) {
      new leimnud.module.app.alert().make({   
        label:'@G::LoadTranslation(ID_TABLE_INVALID_SYNTAX)' + ' ' + sTbl_name
      });
      oSaveButton.disabled = true;
    }
    
    // Reserved words
    var sTableName = getField('ADD_TAB_NAME').value.toUpperCase();
    
    for(var i = 0; i < aReservedWords.length; i++ ) {
      if(sTableName == aReservedWords[i]) {
        new leimnud.module.app.alert().make({
          label:G_STRINGS.ID_TABLE_RESERVED_WORDS + ' ' + sTableName
        });
        oSaveButton.disabled = true;
      }
    }
  });
  
  leimnud.event.add(getField('ADD_TAB_CLASS_NAME'), 'change', function() {
    var sClassNameOld = getField('ADD_TAB_CLASS_NAME_OLD').value;
    var oSaveButton   = getField('btnSave');
    if (sClassNameOld != getField('ADD_TAB_CLASS_NAME').value) {
      oSaveButton.disabled = true;
      var oRPC = new leimnud.module.rpc.xmlhttp({
        url   : '../additionalTables/additionalTablesAjax',
        async : false,
        method: 'POST',
        args  : 'action=classExists&sClassName=' + getField('ADD_TAB_CLASS_NAME').value
      });
      oRPC.make();
      if (oRPC.xmlhttp.responseText == '1') {
        new leimnud.module.app.alert().make({
          label:'@G::LoadTranslation(ID_CLASS_ALREADY_EXISTS)'
        });
      }
      else {
        oSaveButton.disabled = false;
      }
    }
    else {
      oSaveButton.disabled = false;
    }
  });
  
  //Adding events for the grid fields
  var iRows = Number_Rows_Grid('FIELDS', 'FLD_UID');
  var oAux;
  for (var i = 1; i <= iRows; i++) {
    oAux = getGridField('FIELDS', i, 'FLD_TYPE');
    leimnud.event.add(oAux, 'change', {method:onChangeType,instance:oAux,event:true});
    onChangeType(i);
  }
  getObject('FIELDS').onaddrow = function(iRow) {
    oAux = getGridField('FIELDS', iRow, 'FLD_TYPE');
    leimnud.event.add(oAux, 'change', {method:onChangeType,instance:oAux,event:true});
    onChangeType(iRow);
  }; 
};

function cancel(){
  window.location = 'additionalTablesList';
}

dynaformOnload = LoadPMTable;

]]></JS>
</dynaForm>
