'use strict';
var ewzG;
var popupN;  // used for id of popup
/* Common code for admin area in both EntryWizard and  EWZ-Rating */

             /********* Javascript Utilities **************/


/* To stop IE from generating errors if a console.log call was left in */
function fixConsole()
{
   if ( console === undefined)
   {
      console = {}; // define it if it doesn't exist already
   }
   if ( console.log === undefined)
   {
      console.log = function() {
      };
   }
   if ( console.dir === undefined)
   {
      console.dir = function() {
      };
   }
}

/* Functions to fix older IE versions */
if (!Array.prototype.indexOf) {
   Array.prototype.indexOf = function(find, i /*opt*/) {
      var n, t, len, k, kstart;

      n = 0;
      t = Object (this);
      len = t.length >>> 0;
      if (len === 0) {
         return -1;
      }

      if (n >= len) {
         return -1;
      }
      k;
      kstart = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
      for ( k = kstart ; len > k; k++ ) {
         if (  t[k] !== undefined && t[k] === find) {
            return k;
         }
      }
      return -1;
   };
}

if (!Array.prototype.forEach) {
   Array.prototype.forEach = function(action, that /*opt*/) {
      var i, n;

      for ( i = 0, n = this.length; i < n; i++){
         if ( this[i] !== undefined){
            action.call(that, this[i], i, this);
         }
      }
   };
}

if (!Array.prototype.lastIndexOf)
{
   Array.prototype.lastIndexOf = function(searchElement, fromIndex/*opt*/)
   {
      var t, len,n, k;

      t = Object ( this );
      len = t.length >>> 0;
      if (len === 0){
         return -1;
      }
      n = len;
      if (arguments.length > 1)
      {
         n = Number(fromIndex);
         if (n != n){
            n = 0;
         }
         else if ( n != 0 && n != ( 1 / 0 ) && n != -( 1 / 0 ) ){
            n = (n > 0 || -1) * Math.floor(Math.abs(n));
         }
      }
      k = n >= 0 ? Math.min(n, len - 1)  : len - Math.abs(n);
      for ( ; k >= 0 ; k-- )
      {
         if (k in t && t[k] === searchElement){
            return k;
         }
      }
      return -1;
   };
}


/* find and return from an array of objects the index of the first one found that has the_key = the_value */
function js_find_by_key(the_array, the_key, the_value) {
   var k, len;

   if (null === the_array) {
      throw new TypeError();
   }
   len = the_array.length;
   if (len === 0) {
      return -1;
   }
   if (0 >= len) {
      return -1;
   }
   for (k = 0; k < len; k++) {
      if ( the_array[k] !== undefined && the_array[k][the_key] == the_value) {
         return k;
      }
   }
   return -1;
}

function isblank(string)
{
   if ( string === undefined) {
      return true;
   }
   if (null == string) {
      return true;
   }
   var blankre = /^\s*$/;
   return (blankre.test(string));
}

/********** Postbox Handlers ***************/


/* Opens the associated closed ewz_box, or closes the open one */
/* Toggles the "ewz_hndle" class so drag-drop will not work on an open box */
function toggle_ewz_box(handle) {
    var jhndle = jQuery(handle);
    jhndle.closest('.ewz_box').children(".inside").toggle();
    jhndle.toggleClass('ewz_hndle');
    jhndle.children('span.ewz_indicator').first().toggleClass('ewz_open');
}

/* Called on change of field column header to update postbox */
function update_title(textfield) {
    var jtext = jQuery(textfield);
    jtext.closest(jQuery('div[id$="field_mbox_"]')).find('h3[id^="field_title_"]').text(jtext.val());
}


/* Puts a link to 'Collapse All' and 'Expand All' at the top of the page */
/* Only used in EntryWizard, not EWZ-Rating.  Probably useless anyway  */
function add_expander() {
   var close_text, open_text, jopen_close;

   close_text = 'Collapse All';
   open_text = 'Expand All';
   jopen_close = jQuery('<a href="#" id="expandall" class="ewz_expand">' + open_text + '</a>');
   jopen_close.on("click", function(e) {
      e.preventDefault();
      if (jQuery(this).text() === close_text) {
         jQuery(".ewz_box").addClass('closed');
         jQuery(this).text(open_text);
      } else {
         jQuery(".ewz_box").removeClass('closed');
         jQuery(this).text(close_text);
      }
   });
   jQuery('#wpbody').prepend(jopen_close);
}

         /*********** Message Popups ***********/

function ewz_alert( alert_id, msg, pnum ){
  return  jQuery('<div></div>').html('[' + alert_id + '] &nbsp; ' + msg).dialog({
        title: '** Notice **',
        resizable: true,
        modal: true,
       classes: {"ui-dialog": "ewz-dialog ui-corner-all"},
       closeText: "",
        width: 500,
        maxHeight: 700,
        buttons:[ {
                    text:"Ok",
                    id: "ewz_alert" + pnum.toString(),
                    click: function(){
                              jQuery( this ).dialog( "close" );
                           }
                  }
                ]
    });
}

/* NB: dialogClass is deprecated, but example in docs still shows its use */
/*     for removing the 'X' close button, which is rather ambiguous here  */
function ewz_confirm(  msg, truefunc, falsefunc, pnum ){
    return jQuery('<div></div>').html(msg).dialog({
        title: 'Please Confirm',
        resizable: true,
        modal: true,
       closeText: "",
       classes: {"ui-dialog": "ewz-dialog ui-corner-all"},
        buttons:[ {
                      text: "Yes, Go Ahead",
                      id: "ewz_confirm" + pnum.toString(),
                      click: function(){
                                          if (typeof  truefunc == 'function') {
                                              setTimeout(truefunc, 50);
                                          }
                                          jQuery(this).dialog('close');
                                       }
                  },
                  {
                      text: "No, Cancel",
                        id: "ewz_cancel" + pnum.toString(),
                      click: function(){
                                          if (typeof falsefunc == 'function') {
                                              setTimeout(falsefunc, 50);
                                          }
                                          jQuery(this).dialog('close');
                                       }
                 }
               ]
    });
}

/* show a help dialog */
function ewz_help(help_id) {
   jQuery('#' + help_id + '_help').dialog({
      title: 'EntryWizard Help',
      autoOpen: false,
      width: 500,
       classes: {"ui-dialog": "ewz-dialog ui-corner-all"},
       maxHeight: 700,
       closeText: "",
      resizable: true,
      closeOnEscape: true,
      modal         : false
          }).dialog('open');
}



         /******* Spreadsheet Column Functions **********/

/* Disables the selected spreadsheet columns in any other element of the same class */
/* Called on change of any element of class uniq_class                              */
function disable_ss_options(uniq_class) {
   var nowselected = [];
   // for each ss select list
   jQuery(uniq_class).each(function() {
      // enable all items
       var jthis = jQuery(this);
       jthis.children().prop( "disabled", false );
      // save the non-blank selected ones
      if (jthis.val() !== "-1") {
         nowselected[jthis.val()] = jthis.prop("selectedIndex");
      }
   });

   // for each ss select list
   jQuery(uniq_class).each(function() {
      // for each selected item
      var sel;
      for (sel in nowselected ) {
          if (!nowselected.hasOwnProperty(sel)) { continue; }
          // disable the same item in all the other select lists
          if (sel !== this.value) {
            jQuery(this.options[nowselected[sel]]).prop("disabled", "disabled");
          }
      }
   });
}

/* disable argument field and assign class="ewz_disabled" */
function disable_and_flag(jElement) {
    var w, h;
    jElement.prop("disabled", true);
    if (!jElement.parent().hasClass("ewz_disabled")) {
        w = jElement.outerWidth(true) + 12;
        h = jElement.outerHeight(true) + 12;
        jElement.wrap('<span  style="width: ' + w + 'px; height: ' + h + 'px;" class="ewz_disabled" >');
    }
}

function spread_col_rows(sid)
{
    var maxcol = 0;
    var str = '';
    var desc= new Array();
    var cls = '.ssc' + sid;
    jQuery(cls).each( function(index) {
        var jthis = jQuery(this);
        var v = parseInt(jthis.val());
        if( v > -1 ){
            if( v > maxcol ){ maxcol = v; }
            var is_input = (jthis.closest('div[id$="field_mbox_"]').find('[id $="_field_type_"]').length > 0);
            desc[v] = jthis.closest('div[id$="field_mbox_"]').find('h3').text();
            if( desc[v].length > 1 ){
                  desc[v] += ' ( ' + ( is_input ? 'Input ' : '' ) + 'Field )';
            }
            desc[v] += jthis.closest('tr').children().first().text();
            desc[v] = desc[v].replace('Spreadsheet Column for', ' - ').replace('Spreadsheet Column', '').replace(':','');
        }
    });
    for( var i = 0; i <= maxcol; ++i ){
        var i1 = i + 1;
        var j = i/26;
        var p = j >= 1 ? String.fromCharCode(j + 64) : '';
        var m = i%26;
        if( undefined === desc[i] || null ==  desc[i] ){
            str +=           '<tr><td>' + i1 + '(' + p + String.fromCharCode(m + 65) + ')' + "</td><td>--blank--</td></tr>";
        } else {
            str +=           '<tr><td>' + i1 + '(' + p + String.fromCharCode(m + 65) + ')' + "</td><td>" + desc[i] + "</td></tr>";
        }
    }
    return str;
}

/* Popup a display of the spreadsheet column assignments */
function show_spread_columns(lid, layout_name){

    var str = '<table  id="ewz_spr_col_f' + lid + '">';
    str +=         spread_col_rows(lid);
    str +=    '</table>';
    var tp = typeof ewz_added_spread_note;
    if( 'function' == tp ){
        str +=  ewz_added_spread_note();
    }
    jQuery('#spread_cols_display' + lid).html(str);
    jQuery('#spread_cols_display' + lid).dialog({
      title: 'Spreadsheet for ' + layout_name,
      autoOpen: false,
      dialogClass: "ewz-dialog",
      width: 500,
      maxHeight: 1000,
      resizable: true,
      closeOnEscape: true,
      modal         : false
          }).dialog('open');
}

         /****** Functions returning html strings for standard inputs ******/

/* return the html string for the data specific to the field type - image size limits, options, text input length, etc */
/* appears to the right of the header, datatype, etc items that are common to all field types                          */
function type_data_field_str(lnum, fid, fld, field_type, fdata ) {
    var str, fdid, fdld;
    var is_layout_page = jQuery('#layouts_save1_').length;
    str = '<table id="data_fields_' + fid + '"  class="widefat ewz_shaded ewz_field">';
    fdid = fid + 'fdata_';
    fdld = fld + '[fdata]';
    switch (field_type) {
        case "lab":
            str += label_fields_str(lnum, fdid, fdld, fdata, ewzG.helpIcon);
            break;
        case "str":
            str += text_fields_str(lnum, fdid, fdld, fdata, ewzG.helpIcon);
            break;
        case "img":
            str += img_fields_str(lnum, fdid, fdld, fdata, ewzG.helpIcon, ewzG.maxUploadMb);
            break;
        case "opt":
            str += opt_fields_str(fdid, fdld, fdata, ewzG.helpIcon);
            break;
        case "rad":
            str += rad_fields_str(fdid, fdld, fdata, ewzG.helpIcon);
            break;
        case "chk":
            if( jQuery('#sch' + lnum + '_fields' + fdid + '_required_').is( ":checked" ) ){
                str += '';
            } else {
                str += chk_fields_str(fdid, fdld, fdata, ewzG.helpIcon);
            }
            break;
   }
    str += '</table>';
    if ('opt' === field_type) {
        str += '<p>Text for blank selection: <input type="text" maxlength="30" name="' + fdld + '[selecttext]"  id="' + fdid + '[selecttext]" value="' + fdata.selecttext + '"></p>';

        str += '<br /><button type="button" id="' + fid + 'add_" class="button-secondary" onClick="add_option(this)">Add an Option</button>';
        str += '<br /><br />Add a series of options:<div class="ewz_series">';
        str += '<label for="' + fid + 'optset_1">Start: </label><input type="text" id="' + fid + 'optset_1"  maxlength="10">&nbsp;&nbsp;';
        str += '<label for="' + fid + 'optset_2">Step: </label><input type="text" id="' + fid + 'optset_2"  maxlength="10">&nbsp;&nbsp;';
        str += '<label for="' + fid + 'optset_3">End: </label><input type="text" id="' + fid + 'optset_3"  maxlength="10">&nbsp;&nbsp;';
        if( is_layout_page ){
            str += '<label for="' + fid + 'optset_4">Max for all: </label>' + numinput_str(fid + "optset_maxnum_", '', 'no max', 1, 100, '');
        }
        str += '</div><button type="button" id="' + fid + 'optset_" class="button-secondary" onClick="add_option_set(this)">Add Series</button>';

     }
    return str;
}


/* return the html for setting the specific text field data - number of chars visible and max number of chars */
/* called by type_data_field_str */
function text_fields_str(lnum, fdid, fdld, tObj, helpIcon)
{
    var str = '';
    if (tObj) {

        str += '<tr><td><img  class="ewz_ihelp" src="' + helpIcon + '" onClick="ewz_help(\'maxchar\')">&nbsp;Maximum number of Characters: </td><td>' + numinput_str(fdid + 'maxstringchars_', fdld + '[maxstringchars]', '', 1, 5000, Number(tObj.maxstringchars)) + '</td></tr>';

        str += '<tr><td><img  class="ewz_ihelp" src="' + helpIcon + '" onClick="ewz_help(\'maxvis\')">&nbsp;Number of Characters Visible in One Line: </td><td>' + numinput_str(fdid + 'fieldwidth_', fdld + '[fieldwidth]', '', 1, 100, Number(tObj.fieldwidth)) + '</td></tr>';

        str += '<tr><td><img  class="ewz_ihelp" src="' + helpIcon + '" onClick="ewz_help(\'textrows\')">&nbsp;Number of Lines of Visible Text:';
        str += '</td><td>';
        str += numinput_str(fdid + 'textrows_', fdld + '[textrows]',  '', 1, 100, Number(tObj.textrows, 'ssc' + lnum )) + '</td></tr>';

        str += '<tr class="reformat"><td><img  class="ewz_ihelp" src="' + helpIcon + '" onClick="ewz_help(\'frmtstr\')">&nbsp;Spreadsheet Column for Formatted Text:</td>';
        str +=    '<td>' + colinput_str(fdid + 'ss_col_fmt_', fdld + '[ss_col_fmt]', tObj.ss_col_fmt, 'ssc' + lnum) + '</td>';
        str += '</tr>';
    }
    return str;
}

/* return the html for setting the specific label field data - the label text */
/* called by type_data_field_str */
function label_fields_str(lnum, fdid, fdld, tObj, helpIcon)
{
    var str = '';
    var is_layout_page = jQuery('#layouts_save1_').length;
    if (tObj) {

        str += '<tr><td><img  class="ewz_ihelp" src="' + helpIcon + '" onClick="ewz_help(\'textlabel\')">&nbsp;Label: </td><td>' + textinput_str(fdid + 'textlabel_', fdld + '[label]', 50,  tObj.label ? tObj.label : '' ) + '</td></tr>';
        if( is_layout_page ){
            str += '<tr><td><img  class="ewz_ihelp" src="' + helpIcon + '" onClick="ewz_help(\'showlabel\')">&nbsp;Display to User: </td><td>' + checkboxinput_str(fdid + 'showlabel_', fdld + '[showlabel]',  tObj.showlabel ? tObj.showlabel : false ) + '</td></tr>';
        }
    }
    return str;
}


/* return the html for setting the specific radio button data -- ie the label to display */
/* called by type_data_field_str */
function rad_fields_str(fdid, fdld, oObj, helpIcon)
{
    var str =  '<tr><td><img  class="ewz_ihelp" src="' + helpIcon + '" onClick="ewz_help(\'radlabel\')"> &nbsp; (optional) Label to display when checked</td>';
    str += '    <td>' + textinput_str(fdid + "radlabel_", fdld + "[radlabel]", 20, oObj.radlabel ?  oObj.radlabel : 'checked') + '</td></tr>';
    if( ewzG.empty_rad.xradlabel !== undefined ){
        str +=  '<tr><td> &nbsp; &nbsp; (optional) Label to display when not checked</td>';
        str += '    <td>' + textinput_str(fdid + "xradlabel_", fdld + "[xradlabel]", 20, oObj.xradlabel ?  oObj.xradlabel : '-') + '</td></tr>';
    }
    return str;

}


/* return the html for setting the specific checkbutton data -- ie max num allowed, "checked" display */
/* called by type_data_field_str */
function chk_fields_str(fdid, fdld, oObj, helpIcon)
{
    var chk_maxnum = oObj.chkmax ? Number(oObj.chkmax) : '';
    var str = '<tr><td><img  class="ewz_ihelp" src="' + helpIcon + '" onClick="ewz_help(\'chkmax\')"> &nbsp; (optional) Maximum number that may be checked</td>';
    str +=     '<td>' + numinput_str(fdid + "chkmax_", fdld + "[chkmax]", 'no max', 1, 100, chk_maxnum) + '</td></tr>';

    str += '<tr><td><img  class="ewz_ihelp" src="' + helpIcon + '" onClick="ewz_help(\'chklabel\')"> &nbsp; (optional) Label to display when checked</td>';
    str += '    <td>' + textinput_str(fdid + "chklabel_", fdld + "[chklabel]", 20, oObj.chklabel ?  oObj.chklabel : 'checked') + '</td></tr>';

    if( ewzG.empty_chk.xchklabel !== undefined ){
        str +=  '<tr><td> &nbsp; &nbsp; (optional) Label to display when not checked</td>';
        var lab = ( undefined !== oObj.xchklabel ) ? oObj.xchklabel : '-';
        str += '    <td>' + textinput_str(fdid + "xchklabel_", fdld + "[xchklabel]", 20, lab ) + '</td></tr>';
    }
    return str;
}
/* return the html for setting the specific image field data - dimensions, type, etc */
/* called by type_data_field_str */
function img_fields_str(lnum, fdid, fdld, iObj, helpIcon, maxUploadMb) {
    if (!iObj) {
        iObj = ewzG.empty_img;
    }
    var str = '';
    str = '<tr><td width="60%"><img  class="ewz_ihelp" src="' + helpIcon + '" onClick="ewz_help(\'imgdim\')">&nbsp;Maximum Image Width ( or max longest side if rotation is allowed )</td>';
    str += '    <td>' + textinput_str(fdid + 'max_img_w_', fdld + '[max_img_w]', 5, iObj.max_img_w) + 'Pixels</td>';
    str += '</tr>';
    str += '<tr><td>Spreadsheet Column for Image Width </td>';
    str += '    <td>' + colinput_str(fdid + 'ss_col_w_', fdld + '[ss_col_w]', iObj.ss_col_w, 'ssc' + lnum) + '</td>';
    str += '</tr>';
    str += '<tr><td><img  class="ewz_ihelp" src="' + helpIcon + '" onClick="ewz_help(\'imgdim\')">&nbsp;Maximum Image Height( or max shorter side if rotation is allowed )</td>';
    str += '    <td>' + textinput_str(fdid + 'max_img_h_', fdld + '[max_img_h]', 5, iObj.max_img_h) + 'Pixels</td>';
    str += '</tr>';
    str += '<tr><td>Spreadsheet Column for Image Height </td>';
    str += '    <td>' + colinput_str(fdid + 'ss_col_h_', fdld + '[ss_col_h]', iObj.ss_col_h, 'ssc' + lnum) + '</td>';
    str += '</tr>';
    str += '<tr><td><img  class="ewz_ihelp" src="' + helpIcon + '" onClick="ewz_help(\'rot\')">&nbsp;Can rotate to fit maxima</td>';
    str += '    <td>' + checkboxinput_str(fdid + 'canrotate_', fdld + '[canrotate]', iObj.canrotate) + '</td>';
    str += '</tr>';
    str += '<tr><td><img  class="ewz_ihelp" src="' + helpIcon + '" onClick="ewz_help(\'mustfill\')">&nbsp;Image must be as large as possible within the above maxima</td>';
    str += '    <td>' + checkboxinput_str(fdid + 'mustfill_', fdld + '[mustfill]', iObj.mustfill) + '</td>';
    str += '</tr>';
    str += '<tr><td>Spreadsheet Column for Image Orientation </td>';
    str += '    <td>' + colinput_str(fdid + 'ss_col_o_', fdld + '[ss_col_o]', iObj.ss_col_o, 'ssc' + lnum) + '</td>';
    str += '</tr>';
    str += '<tr><td><img  class="ewz_ihelp" src="' + helpIcon + '" onClick="ewz_help(\'imgsize\')">&nbsp;Maximum image size (cannot be over ' + maxUploadMb + 'M)</td>';
    str += '    <td>' + textinput_str(fdid + 'max_img_size_', fdld + '[max_img_size]', 10, iObj.max_img_size) + 'Megabytes</td>';
    str += '</tr>';
    str += '<tr><td><img  class="ewz_ihelp" src="' + helpIcon + '" onClick="ewz_help(\'longestdim\')">&nbsp;Minimum Longest Dimension</td>';
    str += '    <td>' + textinput_str(fdid + 'min_longest_dim_', fdld + '[min_longest_dim]', 5, iObj.min_longest_dim) + 'Pixels</td>';
    str += '</tr>';
    str += '<tr><td><img  class="ewz_ihelp" src="' + helpIcon + '" onClick="ewz_help(\'imgtype\')">&nbsp;Allowed image types<br />(control-click to select more than one)</td>';
    str += '    <td>' + imgformat_input_str(fdid + 'allowed_image_types_', fdld + '[allowed_image_types][]', iObj.allowed_image_types) + '</td>';
    str += '</tr>';
    return str;
}

/* return the html for setting the specific select-option data - options, labels and max of each allowed */
/* called by type_data_field_str */
function opt_fields_str(fdid, fdld, oObj, helpIcon)
{
    var is_layout_page = jQuery('#layouts_save1_').length;
    var str = '',
        len = 0,
        rownum;
    if (oObj.options) {
        len = oObj.options.length;
    }
    str += "<tr><th>Label&nbsp;for&nbsp;Web&nbsp;Page</th><th>Value Stored</th>";
    if( is_layout_page){
        str += "<th colspan='2'>Maximum number allowed</th>";
    } else {
        str += "<th>&nbsp;&nbsp;&nbsp;&nbsp;</th><th>&nbsp;&nbsp;&nbsp;&nbsp;</th>";
    }
    str += '<th><img  class="ewz_ihelp" src="' + helpIcon + '" onClick="ewz_help(\'opt\')"></th></tr>';
    for (rownum = 0; rownum < len; ++rownum) {
        str += opt_row_str(fdid, fdld, rownum, oObj.options[rownum], len );
    }
    return str;
}


/* returns html for a select element with positive integer options start .. end */
/* and a blank option with value "0",   with optional onChange function */
/**
 *  Returns html for a select element with positive integer options start .. end
 *
 * @param  idstring string   id of select element
 * @param  namestring string  name of  select element
 * @param  nosel     label for "no selection" item
 * @param  start    first selectable integer
 * @param  end    last  selectable integer
 * @param  vval   selected value
 * @return string
 */
function numinput_str(idstring, namestring, nosel, start, end, vval, func)
{
   var qidstring, qnmstring, code, sel, i;

   qidstring = "'" + idstring + "'";
   qnmstring = "'" + namestring + "'";
   code = '<select id=' + qidstring + 'name=' + qnmstring;
   if (   func  !== undefined ){
      code += ' ' + func + ' ';
   }
   code += '>';
   sel = '';
   if( nosel ){
        code = code + '<option value="0">' + nosel + '</option>';
   }
   for ( i = start; i < Math.min( 50, end ); ++i) {
      sel = (i == vval) ? 'selected="selected"' : '';
      code = code + '<option value="' + i + '" ' + sel + ">" + i + "</option>";
   }
   for ( i = 50 ; i < Math.min( 300, end ); i+=10 ) {
      sel = (i == vval) ? 'selected="selected"' : '';
      code = code + '<option value="' + i + '" ' + sel + ">" + i + "</option>";
   }
   for ( i = 300 ; i < end; i+= 100 ) {
      sel = (i == vval) ? 'selected="selected"' : '';
      code = code + '<option value="' + i + '" ' + sel + ">" + i + "</option>";
   }

   code = code + "</select>";
   return code;
}

/* returns html for a text input element,  max size mw, value vval  with optional onChange function */
function textinput_str(idstring, namestring, mw, vval, func) {
   var qqidstring, qqnmstring, qqmw, retstr;

   qqidstring = '"' + idstring + '"';
   qqnmstring = '"' + namestring + '"';
   qqmw = '"' + mw + '"';
   retstr = '<input type="text" ';
   if (   func  !== undefined ){
      retstr += ' ' + func + ' ';
   }
    if(   vval  === undefined ){
        vval = '';
    }
   retstr += ' id=' + qqidstring + ' name=' + qqnmstring + ' maxlength=' + qqmw + ' value="' + vval + '">';
   return retstr;
}



// returns html for a checkbox input element with optional onChange function
function checkboxinput_str(idstring, namestring, checked, func) {
   var qqidstring, qqnmstring, chkd, retstr, disabled;

   qqidstring = '"' + idstring + '"';
   qqnmstring = '"' + namestring + '"';

   disabled = '';
   if( checked == 'disabled' ){
       disabled = ' disabled="disabled" ';
   }
   chkd = ((true == checked) ? ' checked="checked"' : '');
   retstr = '<input type="checkbox" ';
   if (  func !== undefined) {
      retstr += ' ' + func + ' ';
   }
   retstr += ' value="1" id=' + qqidstring + ' name=' + qqnmstring + chkd + disabled + '>';
   return retstr;
}

/* Returns the html string for a drop-down to select a spreadsheet column */
/* including onClick call to disable_ss_options                              */
function colinput_str(idstring, namestring, vval, uniq_class) {
    var qidstring = "'" + idstring + "'",
        qnmstring = "'" + namestring + "'",
        qclass = "'." + uniq_class + "'",
        i, i1, j, j1,
        sel = '',
        display = '',
        str;
    str = '<select id=' + qidstring + 'name=' + qnmstring + ' class="' + uniq_class + '" onChange="disable_ss_options(' + qclass + ')">';
    str += '      <option value="-1">None</option>';
    for (i = 0; i <= 25; ++i) {
        sel = (i == vval) ? 'selected="selected"' : '';
        i1 = i + 1;
        display = i1 + '(' + String.fromCharCode(i + 65) + ')';
        str += '  <option value="' + i + '" ' + sel + '>' + display + '</option>';
    }
    for (i = 0; i <= 25; ++i) {
        j = 26 + i;
        sel = (j == vval) ? 'selected="selected"' : '';
        j1 = j + 1;
        display = j1 + '(A' + String.fromCharCode(i + 65) + ')';
        str += '  <option value="' + j + '" ' + sel + '>' + display + '</option>';
    }
    str += '</select>';
    return str;
}


/* return the html for an image format selection box */
/* called by img_fields_str */
function imgformat_input_str(id, name, values) {
   var str = '<select multiple="multiple" id="' + id + '" name="' + name + '">';
   str += '   <option value="image/jpeg" ' + (values.lastIndexOf('image/jpeg') >= 0 ? " selected" : '') + '>jpeg/jpg</option>';
   str += '   <option value="image/gif" ' + (values.lastIndexOf('image/gif') >= 0 ? " selected" : '') + '>gif</option>';
   str += '   <option value="image/png" ' + (values.lastIndexOf('image/png') >= 0 ? " selected" : '') + '>png</option>';
   str += '</select> ';
   return str;
}



       /********** Functions for field-type lists and field option areas *****/

function get_empty_field_str( field_type ){
    var fdata;
    switch (field_type) {
        case "str":
            fdata = ewzG.empty_str;
            break;
        case "lab":
            fdata = ewzG.empty_lab;
            break;
       case "img":
            fdata = ewzG.empty_img;
            break;
        case "opt":
            fdata = ewzG.empty_opt;
            break;
        case "rad":
            fdata = ewzG.empty_rad;
            break;
        case "chk":
            fdata = ewzG.empty_chk;
            break;
    }
    return fdata;
}

/* Returns the html string for the field-type selection box */
/*    which on change, calls insert_blank_data_field       */
function type_opt_str(lnum, fid, fld, field_type ) {
    var is_layout_page = jQuery('#layouts_save1_').length;
    var sel = 'selected="selected"',
        str = '<select id="' + fid + 'field_type_" name="' + fld + '[field_type]" ';

    var qlnum = "'" + lnum + "'";
    str += '       onFocus="prev_val=this.options[this.selectedIndex].value" ';
    str += '       onChange="insert_blank_data_field(' + qlnum + ', this, this.options[this.selectedIndex].value)">';
    str += '   <option value="str" ' + (('str' === field_type) ? sel : '') + '>Text &nbsp; </option>';
    str += '   <option value="opt" ' + (('opt' === field_type) ? sel : '') + '>Option List &nbsp; </option>';
    if( is_layout_page ){
        str += '   <option value="img" ' + (('img' === field_type) ? sel : '') + '>Image File  &nbsp; </option>';
        str += '   <option value="rad" ' + (('rad' === field_type) ? sel : '') + '>Radio Button  &nbsp; </option>';
    }
    str +=    ' <option value="lab" ' + (('lab' === field_type) ? sel : '') + '>Fixed Text Label &nbsp; </option>';
    str += '   <option value="chk" ' + (('chk' === field_type) ? sel : '') + '>Check Box  &nbsp; </option>';
    str += '</select>';
    return str;
}

/* Formatted Text only available for 1-line text inputs */
function initcaps_for_1line(div_id){
    jQuery('#' + div_id).find('select[id$="fdata_textrows_"]').on("change", function(){
        var jthis = jQuery(this);
        var nlines = jthis.val();
        var jrf_row = jQuery(this).closest('tbody').find('tr.reformat');
        if( nlines > 1 ){
            var jsscol_sel = jrf_row.closest('tbody').find('select[id$="fdata_ss_col_fmt_"]');
            jsscol_sel.prop("selected", false);
            jsscol_sel.prop("disabled", 'disabled');
            jrf_row.hide();
        } else {
            jrf_row.find('select[id$="fdata_ss_col_fmt_"]').prop("disabled", false);
            var jsscol_sel = jrf_row.closest('tbody').find('select[id$="fdata_ss_col_fmt_"]');
            jsscol_sel.prop("selected", false);
            jrf_row.show();
        }
    });
    jQuery('select[id$="fdata_textrows_"]').trigger("change");
}


/* Called when the type of a field is changed.  Changes the right-hand side of the field area   */
/*    to a new, blank area of the relevant type, and enables/disables the "required" field      */
function insert_blank_data_field( lnum, type_sel, type) {
    var jsel, field_id, parenttable, datafield, tid, fdata;

    jsel = jQuery(type_sel);
    field_id = jsel.attr("name").replace('fields[', '').replace('][field_type]', '');
    parenttable = jsel.closest(jQuery('table[class$="field"]'));
    datafield = jQuery(parenttable).find('td[id^="special_"]');
    tid = datafield.attr("id").replace('special_', '');

    jsel.trigger("blur");
    // radio buttons cannot be required
    switch (type) {
        case "str":
            fdata = ewzG.empty_str;
            parenttable.find('input[id$="_required_"]').prop("checked", false).prop("disabled", false);
           break;
        case "lab":
            fdata = ewzG.empty_lab;
            parenttable.find('input[id$="_required_"]').prop("checked", true).prop("disabled", true );
           break;
        case "img":
            fdata = ewzG.empty_img;
            parenttable.find('input[id$="_required_"]').prop("checked", false).prop("disabled", false);
            break;
        case "opt":
            fdata = ewzG.empty_opt;
            parenttable.find('input[id$="_required_"]').prop("checked", false).prop("disabled", false);
            break;
        case "rad":
            fdata = ewzG.empty_rad;
            parenttable.find('input[id$="_required_"]').prop("value",'');
            parenttable.find('input[id$="_required_"]').prop("checked", false).prop("disabled", true  );
            break;
        case "chk":
            fdata = ewzG.empty_chk;
            parenttable.find('input[id$="_required_"]').prop("checked", false).prop("disabled", true );
            break;
    }
    datafield.html(type_data_field_str(lnum, tid, 'fields[' + field_id + ']', type, fdata ));
}


          /******** Functions for option-list generation **********/

/* Add set of numeric options with a fixed step */
function add_option_set(add_set_btn){
    var jBtn = jQuery(add_set_btn);
    var startStr = jQuery( '#' + jBtn.attr('id') + '1').val().trim();
    var stepStr = jQuery( '#' + jBtn.attr('id') + '2').val().trim();
    var endStr = jQuery( '#' + jBtn.attr('id') + '3').val().trim();
    var is_layout_page = jQuery('#layouts_save1_').length;

    var maxStr = '';
    if( is_layout_page ){
        maxStr = jQuery( '#' + jBtn.attr('id') + 'maxnum_').val().trim();
    }
    var start = parseFloat( startStr );
    var step  = parseFloat( stepStr );
    var end   = parseFloat( endStr );

    if( step === 0) { ewz_alert('C001', 'Step cannot be 0 ', ++popupN );}

    var dec1 = ewz_decimals( startStr, 'Start' );
    var dec2 = ewz_decimals( stepStr, 'Step' );
    var dec3 = ewz_decimals( endStr, 'End' );

    var dp = Math.max( dec1, dec2, dec3 );

    if( step > 0 ){
        for( var optval = start; optval <= end; optval += step ){
            add_option( add_set_btn, {label:optval.toFixed(dp).toString(), value: optval.toFixed(dp).toString(), maxnum: maxStr } );
        }
    } else {
        for( var optval = start; optval >= end; optval += step ){
            add_option( add_set_btn, {label:optval.toFixed(dp).toString(), value: optval.toFixed(dp).toString(), maxnum: maxStr} );
        }
    }
}

function ewz_decimals( string, name ){
    if( undefined == name ){
        name = string;
    }
    if( !jQuery.isNumeric( string )) {
        ewz_alert('C004', name + ' must be numeric', ++popupN );
    }
    var dotpos = string.indexOf('.');
    if ( dotpos == -1 ){
        return 0;
    }
    return string.length - dotpos - 1;
}


/* Adds a new option to the option list  */
function add_option(add_opt_btn, opt_obj ) {
    opt_obj = (typeof opt_obj !== 'undefined') ?  opt_obj : {label:'', value:''};
    var jQtable, tid, jQrows, row, re, fieldnum, fieldid, str, jLayout, nrows;
    var is_layout_page = jQuery('#layouts_save1_').length;

    jQtable = jQuery(add_opt_btn).parent().find('table[id^="data_fields_"]'); //data_fields_f0_fields1_
    tid = jQtable.attr("id");
    jQrows = jQtable.children().first().children();
    row = jQrows.length - 1;
    nrows = row + 1;
    re = new RegExp('^.*_fields');
    fieldnum = tid.replace(re, '').replace('_', ''); //1
    fieldid = tid.replace("data_fields_", '');
    str = opt_row_str(fieldid + 'fdata_', 'fields[' + fieldnum + '][fdata]', row, opt_obj, nrows );

    jQuery(str).insertAfter(jQrows.last());
    jQtable.find('td[rowspan]').attr('rowspan', nrows);
    jQtable.find('input[id$="_label_"]').on("change", function() {
        var jthis, the_label, jvalue;
        jthis = jQuery(this);
        the_label = jthis.val();
        jvalue = jQtable.find('#' + jthis.prop("id").replace("_label_", "_value_"));

        if (isblank(jvalue.val())) {
            jvalue.val(the_label);
        }
    });
    if( is_layout_page ){
        jLayout = jQtable.closest(jQuery('div[id^="ewz_postbox-layout_f"]'));
        jQtable.find('select[id$="_maxnum_"],select[id$="_chkmax_"]').on("change", function() {
            disable_max_vals(jLayout);
        });
        disable_max_vals(jLayout);
    }
}

function opt_row_str(fdid, fdld, rownum, opts, numrows ) {
    var is_layout_page = jQuery('#layouts_save1_').length;
    var label, value, maxnum, rowfid, rowfld, str;

    label = opts ? opts.label : '';
    value = opts ? opts.value : '';
    maxnum = opts ? Number(opts.maxnum) : '';
    rowfid = fdid + rownum + '_';
    rowfld = fdld + '[options][' + rownum + ']';
    str = '<tr id="' + rowfid + 'row_">';
    str += '   <td>' + textinput_str(rowfid + "label_", rowfld + "[label]", 20, label) + '</td>';

    if( is_layout_page){
        str += '<td>' + textinput_str(rowfid + "value_", rowfld + "[value]", 20, value) + '</td>';
        str += '<td>' + numinput_str(rowfid + "maxnum_", rowfld + "[maxnum]", 'no max', 1, 100, maxnum) + '</td>';
    } else {
        str += '<td>' + textinput_str(rowfid + "value_", rowfld + "[value]", 20, value) + '<input type="hidden" name="' + rowfld + '[maxnum]" value="0"></td>';
    }

    str += '   <td><input type="radio" name="' + fdid + '_optrow_" id="' + rowfid + 'optrow_"></td>';
    if( rownum == 0 ){
        str += '   <td rowspan = "' + numrows + '">';
        str += '       <button type="button" class="button-secondary" id="' + fdid + 'up_" onClick="option_up(this)">^</button><br>';
        str += '       <button type="button" class="button-secondary" id="' + fdid + 'dn_" onClick="option_down(this)">V</button>';
        str += '   </td>';
    }
    str += '   <td><button type="button" class="button-secondary" name="' + rowfld + '[del]" ';
    str += '        id="' + rowfid + 'del_" onClick="delete_option(this)">X</button>';
    str += '   </td>';

    str += '</tr>';
    return str;
}


/* Moves the option up by one */
function option_up( up_opt_btn ) {
    var jradio, jrow, jprev, ind, ind1;

    jradio =  jQuery(up_opt_btn).closest('table').find( 'input[id$="optrow_"]:checked' );
    if( !jradio ){
        return;
    }
    jrow = jradio.closest('tr');
    ind = jrow.prevAll().length - 1; // -1 because of header row
    if( ind < 1 ){
        ewz_alert('C002', 'cant move first up', ++popupN );
        return;
    }
    ind1 =  ind - 1;
    jprev = jrow.prev();

    renumber( jrow, ind, ind1 );
    renumber( jprev, ind1, ind );

    jrow.insertBefore(jprev);
    reset_colspan(jrow);
}

/* Moves the option down by one */
function option_down(down_opt_btn) {
    var jradio, jrow, jnext, ind, ind1;

    jradio =  jQuery(down_opt_btn).closest('table').find( 'input[id$="optrow_"]:checked' );
    if( !jradio ){
        return;
    }
    jrow = jradio.closest('tr');
    ind =  jrow.prevAll().length - 1; // -1 because of header row
    if( ind >= jrow.siblings().length - 1 ){
        ewz_alert('C003', 'cant move last down', ++popupN );
        return;
    }
    ind1 =  ind + 1;
    jnext = jrow.next();

    jrow = renumber( jrow, ind, ind1 );
    jnext = renumber( jnext, ind1, ind );

    jrow.insertAfter(jnext);
    reset_colspan(jrow);
}

function reset_colspan(jrow){
    var numrows =  jrow.siblings().length;
    var rowid = jrow.attr("id");
    var re = new RegExp('_[0-9][[0-9]*_row_$');

    var prefix = jrow.attr("id").replace( re, '' );
    jrow.find('td[rowspan]').remove();
    jrow.siblings().each( function() {
        jQuery(this).find('td[rowspan]').remove();
        });

    var str = '';
        str += '   <td rowspan = "' + numrows + '">';
        str += '       <button type="button" class="button-secondary" id="' + prefix + '_up_" onClick="option_up(this)">^</button><br>';
        str += '       <button type="button" class="button-secondary" id="' + prefix + '_dn_" onClick="option_down(this)">V</button>';
        str += '   </td>';

     jQuery(str).insertBefore(jrow.parent().children().eq(1).children().last());
}

function renumber( jrow, oldn, newn ){
        var oldid = jrow.attr("id");
        jrow.attr("id", oldid.replace('fdata_' + oldn + '_', 'fdata_' + newn + '_'));
        jrow.find('[id]').each(function() {
            jQuery(this).attr("id", jQuery(this).attr("id").replace('fdata_' + oldn + '_', 'fdata_' + newn + '_'));
        });
        jrow.find('[name]').each(function() {
            jQuery(this).attr("name", jQuery(this).attr("name").replace('[options][' + oldn + ']', '[options][' + newn + ']'));
        });

    return jrow;
}

/* Deletes the option        */
function delete_option(del_opt_btn) {
    var is_layout_page = jQuery('#layouts_save1_').length;
    var row, optnum, table, jtable, trows, jQrow, oldid, i, i1, i2;

    row = del_opt_btn.parentNode.parentNode;
    optnum = row.rowIndex;
    table = row.parentNode.parentNode;
    jtable = jQuery(table);
    trows = jtable.children("tbody").children("tr");
    var movecol = is_layout_page ? 4 : 3;

    var mover = table.rows[1].cells[movecol].outerHTML;
    var nrows = trows.length;
    for (i = optnum + 1; i < nrows; ++i) {
        jQrow = jQuery(trows[i]);
        i1 = i - 1;
        i2 = i - 2;
        oldid = jQrow.attr("id");

        jQrow.attr("id", oldid.replace('fdata_' + i1 + '_', 'fdata_' + i2 + '_'));
        jQrow.find('[id]').each(function() {
            jQuery(this).attr("id", jQuery(this).attr("id").replace('fdata_' + i1 + '_', 'fdata_' + i2 + '_'));
        });
        jQrow.find('[name]').each(function() {
            jQuery(this).attr("name", jQuery(this).attr("name").replace('[options][' + i1 + ']', '[options][' + i2 + ']'));
        });

    }
    table.deleteRow(optnum);
    var jFirstDataRow = jQuery(table).children("tbody").children('tr:nth-child(2)');
    if( optnum == 1 ){
        jFirstDataRow.children('td:nth-child(' + movecol + ')').after(mover);
    }
    jFirstDataRow.children('td:nth-child(' + ( movecol + 1 ) + ')').attr("rowspan", nrows - 2);

    if( is_layout_page ){
        disable_max_vals(jtable.closest('div[id^="ewz_admin_layouts_f"]'));
    }
}
