"use strict";

jQuery(function() {
    init_ewz_webforms();
});
jQuery(window).on("load", function() {
    do_webforms_setup();
});

var ewzG, ewzG1;
var ajaxurl;  // ajaxurl variable is available in admin
var popupN;   // used for id of popup
var nNew;
var wforms_done = new Object();



/* disable or toggle visibility of controls in the same form */
function toggle_hidden_controls(open_checkbox){
    fixConsole();
    var jopen_checkbox = jQuery(open_checkbox),
        jform = jopen_checkbox.closest('form');
    var jhide_open = jform.find('[class="ewz_hide_on_open"]');
    var jhide_close = jform.find('[class="ewz_hide_on_close"]');

    if(jopen_checkbox.prop("checked")){
        jhide_open.find('select').val('');
        jhide_open.find('input[type="text"]').val('');
        jhide_open.find('input[type="checkbox"]').prop("checked", false);
        jhide_open.hide();

        jhide_close.show();
    } else {
        jhide_close.find('select').val('');
        jhide_close.find('input[type="text"]').val('');
        jhide_close.find('input[type="checkbox"]').prop("checked", false);
        jhide_close.hide();

        jhide_open.show();
    }
}


/************************ The OnLoad Function  ****************************************/
/* called on load                                   */
/* generates the whole page from the ewzG structure */
function init_ewz_webforms(){
    var i, jthis;
    popupN = 0;
    nNew = 0;
    // ewzG is null if not logged in
    if( null !== ewzG1 ){
        ewzG = ewzG1.gvar;
        for( i = 0; i < ewzG.webforms.length; ++i){
            jQuery('#ewz_management').append( webform_str( ewzG.webforms[i].webform_id, ewzG.webforms[i] ) );
        }
        jQuery('#ewz_management').append('<br>');
        if( ewzG.message ){
            ewz_alert('W001',  ewzG.message.replace(/$/mg, '<br>'), ++popupN );
        }
        for (var wnum = 0; wnum < ewzG.webforms.length; ++wnum) {
            var wid = ewzG.webforms[wnum].webform_id;
            wforms_done[wid] = false;
        }


        jQuery( "#ewz_unhide" ).resizable({});

        add_expander();
   }
}

function do_webforms_setup(){
        // ( "clone" option needed for firefox to stop opening on drag-drop )
        jQuery('#ewz_management').sortable({
            containment: 'parent',
            items: "> div",
            handle: ".ewz_hndle",
            distance: 5,
            helper: "clone"
        });
}

function setup_webform( wf_id, wObj ){

    jQuery('#webform_title_ev' + wf_id + '_').on("change", function(){
        var jthis = jQuery(this);
        jthis.closest('div[id^="ewz-postbox-webform_ev"]').find('div[id^="wf_title_"]').text(jthis.val());
    });
    jQuery('#o_user_' + wf_id + '_').val(wObj.open_for);

    jQuery('#upload_open' + wf_id + '_').on("change", function() {
        toggle_hidden_controls(this);
    } );

   jQuery( "#auto_close_date_" + wf_id  ).datepicker( {
        showOtherMonths: true,
        selectOtherMonths: true,
        dateFormat:  ewzG.dateFormat,
        constrainInput: true,
        minDate: 0,
        maxDate: "+1y",
        nextText: ">",
        prevText: "<"
    });

    jQuery( "#auto_open_date_" + wf_id  ).datepicker( {
        showOtherMonths: true,
        selectOtherMonths: true,
        dateFormat:  ewzG.dateFormat,
        constrainInput: true,
        minDate: 0,
        maxDate: "+1y",
        nextText: ">",
        prevText: "<"
    });
    toggle_hidden_controls(document.getElementById('upload_open' + wf_id + '_'));

}

/************************ Functions Returning an HTML String ****************************************/

/* Returns the html string for a postbox containing a single webform */
function webform_str(evnum, eObj){
    if(!eObj){
        eObj= {};
    }
    var str= '';

    str += '<div id="ewz_admin_webforms_ev' + evnum + '_" class="metabox-holder">';
    str +=     '<div id="ewz-postbox-webform_ev' + evnum + '_" ';
    if( eObj.webform_id == ewzG.openform_id ){
        str +=   '    class="ewz_box">';
    } else {
        str +=   '    class="ewz_box closed" >';
    }
    str +=        '<input type="checkbox" name="self' + evnum + '" id="self' + evnum + '">';
    str +=        '<div  class="ewz_hndle"  onClick="toggle_wform_box(this)" title="Click to toggle" id="tpg_header_ev' + evnum + '_"  >';
    str +=        '    <span class="ewz_indicator"></span>';
    str +=             '<div id="wf_title_' + evnum + '_">' + eObj.webform_title + '</div>';
    str +=             '<div  class="ewz_wfstatus">' + (eObj.upload_open ? 'Open' : (eObj.open_for_string ? 'Open for some users' : 'Closed'));
    str +=                    '&nbsp; ' + eObj.itemcount + ' items uploaded';
    str +=             '</div>';
    str +=        '</div>';
    str +=        '<div class="inside">';
    str +=            '<div class="ewz_formsetup">';
    str +=                '<div class="ewz_data ewz_scrollx">';
    str +=                    '<h4>Webform Setup</h4>';

    if(eObj.can_manage_webform){
        // Can manage webform, present the stored info in editable form
        str += webform_data_str( evnum, eObj );
    } else {
        // Cant manage webform, present the stored info read-only
        str += read_only_info_str( eObj );
    }
    str +=   '             </div>';   // end of ewz_data

    if( (eObj.can_download || eObj.can_manage_webform) && ( eObj.webform_id > 0 ) ){
        str +=   '             <div class="ewz_data ewz_scrollx">';
        str += data_management_str( evnum, eObj );
        str +=   '             </div>';   // end of ewz_data
    }
    str +=   '          </div>';      // end of ewz_formsetup
    str +=   '       </div>';         // end of inside
    str +=   '    </div>';           // ewz-postbox-webform_ev
    str +=   '</div>';               // ewz_admin_webforms_ev
    return str;
}
/* Return the html string for the data management section */
function data_management_str( evnum, eObj ){
    var str='';
    str +=   '<h4>Data Management</h4>';
    if(eObj.can_manage_webform){
        str +=  '<table class="ewz_csv_upload"><tr>';
        str +=  imgcsv_data_upload_str(  evnum, eObj );
        str +=  '</tr><tr>';
        str +=  itmcsv_data_upload_str(  evnum, eObj );
        str +=  '</tr><tr>';
        str +=  batch_entry_upload_str(  evnum, eObj );
        str +=  '</tr><tr>';
        str +=  file_report_str(  evnum, eObj );
        str +=  '</tr></table>';
    }
    /**** NB: action is item_list, not webform here, and requires 'get' method for pagination ********/
    str +=   '<form method="GET" action="' + ewzG.list_page  + '" id="data_form_ev' + evnum + '_">';
    str +=   '    <div class="ewzform">';
    str +=   '    <input type="hidden" name="page" value="entrywizlist">';
    str +=   '    <input type="hidden" name="ewzmode" value="list">';
    str +=   '    <input type="hidden" name="webform_id" value="' + eObj.webform_id + '">';
    str +=   '    <br>&nbsp;<img  class="ewz_ihelp" src="' +  ewzG.helpIcon + '" onClick="ewz_help(\'datasel\')">&nbsp; With selected items:';

    if( eObj.hasOwnProperty('field_options' )){

        str += field_options_str( eObj );
    }
    str += upload_date_str( evnum );

    str +=   '    <TABLE class="ewz_buttonrow">';
    var renameOnDownload = eObj.prefix.length && !eObj.apply_prefix;
    if( eObj.itemcount > 0 && eObj.can_manage_webform ){
        str +=   '  <TR> </TD><TD><button type="button" onClick="do_action(this,\'list\', ' + evnum + ',' + renameOnDownload  + ')"  id="list_' + evnum + '" class="button-secondary">Manage Items</button></TD>';
        str +=   '     <TD></TD>';
        str +=   '  </TR>';
    }
    if(eObj.can_download){
        str +=   '  <TR>';
        str +=   '    <TD><button type="button" onClick="do_action(this,\'spread\', ' + evnum + ', ' + renameOnDownload  + ')" id="spread_' + evnum + '" class="button-secondary">Download Spreadsheet</button></TD>';
        str +=   '    <TD><button type="button" onClick="do_action(this,\'images\', ' + evnum + ', ' + renameOnDownload  + ')" id="images_' + evnum + '" class="button-secondary">Download Images</button></TD>';
        str +=   '    <TD><button type="button" onClick="do_action(this,\'download\',' + evnum + ', ' + renameOnDownload  + ')" id="download_' + evnum + '" class="button-secondary">Download Images and Spreadsheet</button></TD>';
        str +=   '  </TR>';
    }
    str +=   '  </TABLE>';
    str +=   ' </div>';
    str +=   '</form>';

    return str;
}
function file_report_str(  evnum, eObj ){
    var str = '<img  class="ewz_ihelp" src="' +  ewzG.helpIcon + '" onClick="ewz_help(\'filereport\')"> &nbsp; ';
    str += 'Run a check for discrepancies between the database and the uploaded image files: &nbsp; <button  type="button" ';
    str += '   id="freport_' + evnum + '" onClick="run_freport(this,' + eObj.webform_id + ',\'' +  eObj.webform_ident +'\' )">Check Uploads Folder</button>';
    return '<td>' + str + '</td>';
}

function do_action(button, mode, evnum, renameOnDownload ){
    var jform = jQuery( button ).closest('form');
    var jmode = jform.find('input[name="ewzmode"]');
    var jwebform = jQuery( '#cfg_form_ev' + evnum + '_');
    var jbutton = jQuery(button);
    var doRenameOnDownload;
    if( jwebform.find('input[name="prefix"]').length ){
        doRenameOnDownload = jwebform.find('input[name="prefix"]').first().val().trim().length &&
        !jwebform.find('input[name="apply_prefix"]').is(':checked');  // have a prefix not applied on upload
    } else {
        doRenameOnDownload = renameOnDownload;
    }
    jform.append(jQuery('#ewz_numc').html() );
    switch( mode ){
        case 'spread':
        case 'list':
        jform.find('input[name="ewzmode"]').val(mode);
           jform.trigger('submit');
           break;
        case 'images':
           if( ewzG.canzip  && !doRenameOnDownload ){
               jmode.val('zimages');
               jform.trigger('submit');
           } else {
               jmode.val('images');
               gen_zipfile( jform, jbutton, 'images' );
           }
           break;
        case 'download':
           if( ewzG.canzip && !doRenameOnDownload ){
               jmode.val('zdownload');
               jform.trigger('submit');
           } else {
               jmode.val('download');
               gen_zipfile( jform, jbutton, 'download' );
           }
           break;
    }
}

function ewz_do_save( button, evnum, jsvalid ){
    var jbutton = jQuery(button);
    var jform = jbutton.closest('form[id^="cfg_form_ev"]');
    if( jsvalid && !ewz_check_webform_input( jform.get(0), evnum, jsvalid ) ){
        return;
    }
    jform.append('<input type="hidden" id="ajax_page" name="page" value="entrywizard" />');
    jform.append('<input type="hidden" id="ajax_action" name="action" value="ewz_save_webform" />');
    jform.append(jQuery('#ewz_numc').html() );
    jbutton.after('<span id="temp_msg" style="text-align:left"> Processing, please wait ... <img alt="Please Wait" src="' + ewzG.load_gif + '"/></span>');
     var jqxhr = jQuery.post( ajaxurl,
                         jform.serialize(),
                         function(response) {
                             jQuery('#temp_msg').remove();
                             if (response) {
                                 if( response.success ){
                                     var newid = response.data.webform_id;
                                     var index = js_find_by_key(ewzG.webforms, 'webform_id', newid);
                                     if( index >= 0 ){
                                         ewzG.webforms[index] = response.data;
                                     } else {
                                         ewzG.webforms.push(response.data);
                                     }
                                     ewzG.openform_id = 0;
                                     jQuery('#ewz_admin_webforms_ev' + evnum + '_').replaceWith( webform_str( newid, response.data ));
                                     setup_webform( newid, response.data);
                                     var loc = jQuery('#ewz_admin_webforms_ev' + newid + '_').position().top - 50;
                                     jQuery('html, body').scrollTop( loc );
                                     ewz_alert('W021', 'Saved Webform ' + response.data.webform_title, ++popupN );
                                 } else {
                                     ewz_alert('W023', response.data, ++popupN );
                                 }
                             } else {
                                 ewz_alert('W024','EWZ: ' + ewzG.errmsg.unknown, ++popupN);
                             }
                             // for( var wf in ewzG.webforms ){console.log('< ', ewzG.webforms[wf]['webform_id']);}

                         }
                       ).fail( function( jqXHr, textStatus, errorThrown ){
                           jQuery('#temp_msg').remove();
                           ewz_alert( 'W022', ewzG.errmsg.server + jqXHr.responseText, ++popupN );
                       } );
    jQuery('#ajax_action').remove();
    jQuery('#ajax_page').remove();
    jbutton.prop("disabled", false);
}


function gen_zipfile( jform, jbutton, mode ){

    jbutton.after('<span id="temp_gen" style="text-align:left"> Processing, please wait ... <img alt="Please Wait" src="' + ewzG.load_gif + '"/></span>');
    jform.append('<input type="hidden" id="ajax_action" name="action" value="ewz_gen_zipfile" />');
    jform.append(jQuery('#ewz_numc').html() );

    // ajaxurl variable is available in admin
    var jqxhr = jQuery.post( ajaxurl,
                         jform.serialize(),
                         function(response) {
                             jQuery('#temp_gen').remove();
                             if ( response.match(/^ewz_.*/) ) {
                                 jform.find('input[name="ewzmode"]').val(mode);
                                 download_zipfile( jform, response );
                             } else {
                                 ewz_alert('W002', response.replace(/$/mg, '<br>'), ++popupN );
                             }
                         }
                       ).fail( function( jqXHr, textStatus, errorThrown ){
                           jQuery('#temp_gen').remove();
                           ewz_alert( 'W015',  ewzG.errmsg.server + jqXHr.responseText, ++popupN );
                       } );
    jQuery('#ajax_action').remove();
}

function run_freport(button, webform_id, webform_ident){
    var jbutton = jQuery(button);
    jbutton.after('<span id="temp_gen" style="text-align:left"> Processing, please wait ... <img alt="Please Wait" src="' + ewzG.load_gif + '"/></span>');
    var the_nonce = jQuery('#ewznonce').val();

    // ajaxurl variable is available in admin
    var jqxhr = jQuery.post( ajaxurl,
                         {
                            action: 'ewz_file_report',
                            webform_id: webform_id,
                            webform_ident: webform_ident,
                            ewznonce: the_nonce
                         },
                         function(response) {
                             jQuery("#temp_gen").remove();
                             ewz_alert('W014', response.replace(/$/mg, '<br>'), ++popupN );
                         }
                       ).fail( function( jqXHr, textStatus, errorThrown ){
                           jQuery("#temp_gen").remove();
                           ewz_alert( 'W016',  ewzG.errmsg.server + jqXHr.responseText, ++popupN );
                       } );
}

function download_zipfile( jform, response ){
    jform.find('input[name="ewzmode"]').val('stored');
    jform.append( '<input type="hidden" name="archive_id" id="archive_id" value="' + response + '">');
    jform.trigger('submit');
    jQuery('#archive_id').remove();
}


function get_crons(button){
    var jbutton = jQuery(button);
    jbutton.after('<span id="temp_gen" style="text-align:left"> Processing, please wait ... <img alt="Please Wait" src="' + ewzG.load_gif + '"/></span>');
    var the_nonce = jQuery('#ewznonce').val();

    // ajaxurl variable is available in admin
    var jqxhr = jQuery.post( ajaxurl,
                         {
                            action: 'ewz_show_cron_events',
                            ewznonce: the_nonce
                         },
                         function(response) {
                             jQuery("#temp_gen").remove();
                             jQuery('<div></div>').html(response).dialog({
                                 title: 'Scheduled Automatic Open/Close Events',
                                 resizable: true,
                                 modal: true,
                                 dialogClass: "ewz-dialog",
                                 width: 500,
                                 maxHeight: 700
                             });

                         }
                       ).fail( function( jqXHr, textStatus, errorThrown ){
                           jQuery("#temp_gen").remove();
                           ewz_alert( 'W032',  ewzG.errmsg.server + jqXHr.responseText, ++popupN );
                       } );
}


/* Return the html string for the editable form of the webform data */
function webform_data_str(evnum, eObj) {
    var divid = 'usel' + evnum + '_',
        str = '';
    str += '<form method="post" id="cfg_form_ev' + evnum + '_" onSubmit="return ewz_check_webform_input(this,' +  "'" + evnum +  "'"  + ', ewzG.jsvalid)">';
    str += '  <div class="ewzform">';
    str +=   '    <input type="hidden" name="webform_id" id="edit_wfid_' + evnum + '" value="' + eObj.webform_id + '">';
    str +=   '    <input type="hidden" name="ewzmode" value="webform">';
    str +=   '    <table class="ewz_padded">';
    str +=   '        <tr><td><img  class="ewz_ihelp" src="' +  ewzG.helpIcon + '" onClick="ewz_help(\'title\')">&nbsp;Title:</td>';
    str +=   '            <td>' + textinput_str('webform_title_ev' + evnum + '_', 'webform_title', 100, eObj.webform_title) + '</td>';
    str +=   '            <td></td>';
    str +=   '        </tr>';
    str +=   '        <tr><td><img  class="ewz_ihelp" src="' +  ewzG.helpIcon + '" onClick="ewz_help(\'ident\')">&nbsp;Identifier:</td>';
    str +=   '            <td>' + textinput_str('webform_ident_ev' + evnum + '_', 'webform_ident', 15, eObj.webform_ident);
    str +=   '            </td>';
    str +=   '            <td colspan="2" rowspan="2"><div class="ewz_warn">';
    if(eObj.itemcount > 0){
        str += ewzG.errmsg.hasdata + '<br>';
    }
    str += ewzG.errmsg.usedinrating + '</div>';
    str +=   '             </td>';

    str +=   '        </tr>';
    str +=   '        <tr><td><img  class="ewz_ihelp" src="' +  ewzG.helpIcon + '" onClick="ewz_help(\'wlayout\')">&nbsp;Webform layout: </td>';
if(eObj.can_edit_webform){
        str +=   select_layout_str( evnum, eObj );
} else {
        str +=   '        <td><input type="hidden" name="layout_id" value="' + eObj.layout_id + '">' + eObj.layout_name + '</td>';
}
    str +=   '            <td></td>';
    str +=   '        </tr>';

if(eObj.canOverride){
    str +=   '        <tr id="override' + evnum + '" >';
    str +=   '            <td><img  class="ewz_ihelp" src="' +  ewzG.helpIcon + '" onClick="ewz_help(\'numitems\')">&nbsp;Maximum number of items:</td> ';
    str +=   '            <td>' + numinput_str("num_items_" + evnum, "num_items", '', 1, 30, eObj.num_items ) + '</td>';
    str +=   '        </tr>';
}

    str +=   '        <tr><td><img  class="ewz_ihelp" src="' +  ewzG.helpIcon + '" onClick="ewz_help(\'prefix' + eObj.webform_id + '\')">&nbsp;Optional prefix:</td> ';
    str +=   '            <td><input type="text" name="prefix" id="prefix_' + evnum + '" value="' + eObj.prefix + '"  maxlength="75"></td>';
    str +=   '            <td>Apply prefix on upload &nbsp; ';
    str +=                  checkboxinput_str("apply_prefix_" + evnum, "apply_prefix", eObj.apply_prefix );
    str +=   '            </td>';
    str +=   '            <td>Generate the entire filename from the prefix &nbsp; ';
    str +=                  checkboxinput_str("gen_fname_" + evnum, "gen_fname", eObj.gen_fname );
    str +=   '            </td>';
    str +=   '        </tr>';

    str +=   '        <tr><td colspan ="4"  style="border-top: 1px solid black; font-size:1.2em; font-weight:bold">Opening And Closing</td></tr>';

    str +=   '        <tr><td><img  class="ewz_ihelp" src="' +  ewzG.helpIcon + '" onClick="ewz_help(\'open\')">&nbsp;Open for Uploads:</td>';
    str +=   '            <td>' + checkboxinput_str('upload_open' + evnum + '_', 'upload_open', eObj.upload_open ) + '</td>';
    str +=   '            <td colspan="2"><div id="open_for_' + evnum + '_" class="ewz_hide_on_open">' + eObj.open_for_string + '</div></td>';
    str +=   '        </tr>';

    str +=   '        <tr class="ewz_hide_on_open">';
    str +=   '             <td> <img  class="ewz_ihelp" src="' +  ewzG.helpIcon + '" onClick="ewz_help(\'autoopenclose\')">&nbsp;Open Automatically:</td>';
    str +=   '             <td>' + checkboxinput_str("auto_open" + evnum + '_', "auto_open", eObj.auto_open );
    str +=   '                     &nbsp;  &nbsp;  Date: ' + textinput_str("auto_open_date_" + evnum, "auto_open_date", 20, eObj.auto_open_date);
    str +=   '             </td>';
    str +=   '             <td>Time: <select name="auto_open_time" id="auto_open_time_' + evnum + '">' + eObj.time_opts_open + '</select></td>';
    str +=   '        </tr>';


    str +=   '        <tr>';
    str +=   '             <td> <img  class="ewz_ihelp" src="' +  ewzG.helpIcon + '" onClick="ewz_help(\'autoopenclose\')">&nbsp;Close Automatically:</td>';
    str +=   '             <td>' + checkboxinput_str('auto_close_' + evnum, 'auto_close', eObj.auto_close );
    str +=   '                     &nbsp;  &nbsp;  Date: ' + textinput_str("auto_close_date_" + evnum, "auto_close_date", 20, eObj.auto_close_date);
    str +=   '             </td>';
    str +=   '             <td>Time: <select name="auto_close_time" id="auto_close_time_' + evnum + '">' + eObj.time_opts_close + '</select></td>';
    str +=   '             <td>( Timezone ' + ewzG.tz + ' )  &nbsp; <br><i>Current date-time is ' + ewzG.now + '</i></td>';
    str +=   '        </tr>';

    if( eObj.webform_id ){
        str +=   '        <tr class="ewz_hide_on_open">';
        str +=   '            <td><img  class="ewz_ihelp" src="' +  ewzG.helpIcon + '" onClick="ewz_help(\'openfor\')">&nbsp;Show user selection list</td>';
        str +=   '            <td><input type="checkbox"  id="show_uselect_' + evnum + '" ';
        str +=                       'onChange="user_select('  + "'" + divid + "'," + eObj.webform_id  + ', ' + evnum + ')"></td>';
        str +=   '            <td  id="' + divid + '" colspan="2"></td>';
        str +=   '        </tr>';
    }

    str +=   '        <tr><td colspan ="4" style="text-align: center; border-top: 1px solid black;"> </td></tr>';

    str +=   '     </table>';


    str +=   '     <p><button id="cfg_form_wf' +  evnum + '_"  type="button" onClick="ewz_do_save(this,' + "'" + evnum + "'," + ewzG.jsvalid + ')" class="button-primary">';
    str +=   '        Save Changes</button>';
    str +=   ' &nbsp;  &nbsp;  &nbsp;  &nbsp; ';

if(ewzG.can_edit_all){
        str +=   '    <button type="button" id="wfdel_' + evnum + '_" class="button-secondary"';
        str +=   '            onClick="delete_webform( this, ' + eObj.itemcount + ')">Delete Web Form</button>';
        str +=   '    &nbsp;  &nbsp;  &nbsp;  &nbsp; <span class="ewz_waitmessage"></span>';
}
    str +=   '     </p>';
    str +=   ' </div>';
    str +=   '</form>';
    return str;

}

/* Return the html string for the read-only form of the webform data */
function read_only_info_str( eObj ){
    var str='';
    str +=   '             <table>';
    str +=   '                 <tr><td>Name for this webform:</td>';
    str +=   '                     <td>' + eObj.webform_title + '</td>';
    str +=   '                 </tr>';
    str +=   '                 <tr><td>Identifier for use in file names: &nbsp;</td>';
    str +=   '                     <td>' +  eObj.webform_ident + '</td>';
    str +=   '                 </tr>';
    str +=   '                 <tr><td>Webform layout: </td>';
    str +=   '                     <td>' +  eObj.layout_name + '</td></tr>';
    str +=   '                 <tr><td>';
    var when;
    if( eObj.apply_prefix ){
        when = ' on upload ';
    } else {
        when =  ' on download ';
    }
    if( eObj.gen_fname ){
        str += 'Filename generated <br> &nbsp;  &nbsp; ' + when + ' from formula: ';
    } else {
        str += 'Prefix formula applied <br> &nbsp;  &nbsp; to filename ' + when;
    }
    str +=                        '</td>';
    str +=   '                     <td>' +  eObj.prefix + '</td></tr>';

    str +=   '                 <tr><td>Open for Uploads: </td>';
    if(eObj.upload_open ){
        str +=   '                 <td>Yes</td>';
    } else {
        str +=   '                 <td>No</td>';
    }
    str +=   '                 </tr>';
    str +=   '              </table>';
    return str;
}

/* Return the html string for the Extra Data Upload form */
function imgcsv_data_upload_str(  evnum, eObj ){
    var str = '',
        inputid = 'imgcsv_data_' + evnum + '_';
    str +=   '<td>';
    str +=   '<form method="post" enctype="multipart/form-data" action="" id="imgcsv_form_ev' + evnum + '_"> ';
    str += '  <div class="ewzform">';
    str +=   '    <input type="hidden" name="webform_id" value="' + eObj.webform_id + '">';
    str +=   '    <input type="hidden" name="ewzmode" value="imgcsvdata">';

    str +=   '    <img  class="ewz_ihelp" src="' +  ewzG.helpIcon + '" onClick="ewz_help(\'imgcsv\')">&nbsp; Upload extra <u>per-image</u> data for the webform: &nbsp; ';
    str +=   '    <input  id="' + inputid + '" name="imgcsv_data"  class="ewz_file" type="file" >';
    str +=   '    <button type="button" id="imgcsv_btn_' + evnum + '" name="imgcsv_btn" class="button-secondary" ';
    str +=   '            onClick="upload_csv(\'imgcsv\', this, ' + eObj.webform_id + ', ' + evnum  + ')">Upload <b>Image</b> Data</button>';
    str +=   ' </div>';
    str +=   '</form></td>';
    return str;
}
/* Return the html string for the Admin Data Upload form */
function itmcsv_data_upload_str(  evnum, eObj ){
    var str = '',
        inputid = 'itmcsv_data_' + evnum + '_';
    str +=   '<td>';
    str +=   '<form method="post" enctype="multipart/form-data" action="" id="itmcsv_form_ev' + evnum + '_">';
    str += '  <div class="ewzform">';
    str +=   '    <input type="hidden" name="webform_id" value="' + eObj.webform_id + '">';
    str +=   '    <input type="hidden" name="ewzmode" value="itmcsvdata">';

    str +=   '    <img  class="ewz_ihelp" src="' +  ewzG.helpIcon + '" onClick="ewz_help(\'itmcsv\')">&nbsp; Upload extra <u>per-item</u> &nbsp; data for the webform: &nbsp;';
    str +=   '    <input  id="' + inputid + '" name="itmcsv_data" class="ewz_file" type="file"  >';
    str +=   '    <button type="button" id="itmcsv_btn_' + evnum + '" name="itmcsv_btn" class="button-secondary" ';
    str +=   '            onClick="upload_csv(\'itmcsv\', this, ' + eObj.webform_id + ', ' + evnum  + ')">Upload <b>Item</b> Data</button>';
    str +=   ' </div>';
    str +=   '</form>';
    str +=   '</td>';
    return str;
}

function upload_csv( upload_type, button, webform_id, evnum ){
    var jbutton = jQuery(button);
    jbutton.prop("disabled",true);

    var file_input_id = jbutton.closest('form').find('input:file').first().attr('id');
    if( ewz_check_csv_input( upload_type, evnum, file_input_id ) ){

        jbutton.after('<span id="temp_gen" style="text-align:left"> Processing, please wait ... <img alt="Please Wait" src="' + ewzG.load_gif + '"/></span>');
        var the_nonce = jQuery('#ewznonce').val();
        var jform = jbutton.closest('form');
        jform.append(jQuery('#ewz_numc').html() );

        var formData=new FormData(document.getElementById( jform.attr('id') ));

        formData.append("action", "ewz_upload_csv");

        // ajaxurl variable is available in admin
        var jqxhr = jQuery.ajax({
                        url: ajaxurl,
                       type: 'POST',
                       data: formData,
                      cache: false,
                contentType: false,
                processData: false,
                    success: function(response) {
                        jQuery("#temp_gen").remove();
                        ewz_alert('W026', response.replace(/$/mg, '<br>'), ++popupN );
                    },
                      error: function( jqXHr, textStatus, errorThrown ){
                          jQuery("#temp_gen").remove();
                          ewz_alert( 'W027',  ewzG.errmsg.server + jqXHr.responseText, ++popupN );
                      }
        });
    }
    jbutton.prop("disabled",false);
}

/* Return the html string for the Batch Entry Upload form */
function batch_entry_upload_str(  evnum, eObj ){
    var str = '',
        inputid = 'entry_' + evnum + '_';
    str +=   '<td><form method="post" enctype="multipart/form-data" action="" id="entry_form_ev' + evnum + '_" >';
    str += '  <div class="ewzform">';
    str +=   '    <input type="hidden" name="webform_id" value="' + eObj.webform_id + '">';
    str +=   '    <input type="hidden" name="ewzmode" value="entrydata">';

    str +=   '    <img  class="ewz_ihelp" src="' +  ewzG.helpIcon + '" onClick="ewz_help(\'entry\')">&nbsp; Batch upload of entire <u>entries</u> &nbsp; for the webform: &nbsp;';
    str +=   '    <input  id="' + inputid + '" name="entry_data"  class="ewz_file" type="file" />';
    str +=   '    Check Data Only: <input type="radio" name="entry_radio" id="entry_btn_c' + evnum + '" checked="checked" value="check" /> &nbsp; ';
    str +=   '    Create Entries: <input type="radio" name="entry_radio" id="entry_btn_u' + evnum + '"  value="upload" /> &nbsp; ';
    str +=   '    <button type="button" id="entry_btn_s' + evnum + '" class="button-secondary" ';
    str +=   '            onClick="upload_csv(\'entrycsv\', this, ' + eObj.webform_id + ', ' + evnum  + ')">Upload <b>Entry</b> Data</button>';
    str +=   ' </div>';
    str +=   '</form></td>';
    return str;
}



/* Return the html string for the field options select boxes */
function field_options_str( eObj ){
    var field_id1,
        field_id2,
        data1,
        data2,
        fid,
        num  = 0,
        str  = '';
    for( fid in eObj.field_options ){
        if(eObj.field_options.hasOwnProperty(fid) && eObj.field_options[fid]){
            ++num;
        }
    }
    if( num > 0 ){
        str +=   '    <TABLE class="ewz_field_opts"><TBODY><TR>';
        for( field_id1 in eObj.field_options ){
           if(eObj.field_options.hasOwnProperty(field_id1)){
               str +=   '<TH>';
               if( eObj.field_options[field_id1] ){
                   str +=   eObj.field_names[field_id1];
               }
               str +=   '</TH>';
           }
        }
        for ( data1 in eObj.custom_header ){
           if(eObj.custom_header.hasOwnProperty(data1)){
               str +=   '<TH>';
               str +=   eObj.custom_header[data1];
               str +=   '</TH>';
           }
        }

        str +=   '</TR>';
        str +=   '<TR>';
        for( field_id2 in eObj.field_options ){
           if(eObj.field_options.hasOwnProperty(field_id2)){
               str +=   '      <TD>';
               if( eObj.field_options[field_id2] ){
                   str +=   '      <select name="fopt[' + field_id2 +']"  id="l'+ eObj.webform_id + 'f' + field_id2 + '_opt_">';
                   str +=              eObj.field_options[field_id2];
                   str +=   '      </select>';
               }
               str +=   '</TD>';
           }
        }
        for( data2 in eObj.custom_options ){
           if(eObj.custom_options.hasOwnProperty(data2)){
               str +=   '      <TD>';
                   str +=   '      <select name="copt[' + data2 +']"  id="l'+ eObj.webform_id + 'c' + data2 + '_opt_">';
                   str +=              eObj.custom_options[data2];
                   str +=   '      </select>';
               str +=   '</TD>';
           }
        }

        str +=   '</TR></TBODY></TABLE>';
    }
    return str;
}

/* Return the html string for the upload date selection */
function upload_date_str( evnum ){
    var day,
        str  = '';

        str +=   '<TABLE class="ewz_field_opts">';
        str +=   '       <TR>';
        str +=   '          <TD>Initial upload occurred during the last &nbsp;';
        str +=   '             <SELECT id="uploaddays' + evnum  + '" name="uploaddays">';
        str +=   '                 <OPTION value="">  </OPTION>';
        for( day=1; day<=100; ++day ){
             str +=   '            <OPTION value="' + day + '">' + day + '</OPTION>';
        }
        str +=   '             </SELECT> days';
        str +=   '          </TD>';
        str +=   '       </TR>';
        str +=   '    </TABLE>';
    return str;
}




/* Return the html string for the layout selection */
function select_layout_str( evnum, eObj ){
    var str = '';
    str +=   '                 <td>';
    str +=   '                    <select id="layout_id' + evnum + '" name="layout_id" onChange=disable_override(' + evnum + ')>';
    str +=                           eObj.layouts_options;
    str += '                      </select>';
    str +=   '                 </td>';
    return str;
}


/************************ Functions That Change The Page  ****************************************/

function toggle_wform_box( handle){
    var jhndle = jQuery(handle);
    jhndle.closest('.ewz_box').children(".inside").toggle();

    var wf_id = get_wform_ident( handle );
    var wnum = js_find_by_key(ewzG.webforms, 'webform_id', wf_id);
    if( !wforms_done[wf_id] ){
        setup_webform( wf_id, ewzG.webforms[wnum] );
        wforms_done[wf_id] = true;
    }
    jhndle.toggleClass('ewz_hndle');
    jhndle.children('span.ewz_indicator').first().toggleClass('ewz_open');
}

function disable_override(evnum){
    jQuery("#override" + evnum).hide();
}

function user_select(td_id, webform_id, evnum){
    if( jQuery('#show_uselect_' + webform_id).prop("checked" ) ){

        if( !jQuery('#' + td_id).html().match("Open for") ){
            populate_user_select(td_id, webform_id, evnum);
        }
        jQuery('#' + td_id).show();
    } else {
        jQuery('#' + td_id).hide();
    }
}

function populate_user_select(td_id, webform_id, evnum){
    jQuery('#' + td_id ).prepend('<span id="temp_wait" style="text-align:left"> Processing, please wait ... <img alt="Please Wait" src="' + ewzG.load_gif + '"/></span>');
    var the_nonce = jQuery('#ewznonce').val();
    var sel_str = '<br><select  multiple="multiple" size="8" name="o_user[]" id="o_user_' + evnum + '_">';

    var jqxhr = jQuery.post( ajaxurl,
                             {
                                 ewzmode: 'wf_get_user_list',
                                 action: 'ewz_webform_get_user_list',
                                 webform_id: webform_id,
                                 ewznonce: the_nonce
                             },
                             function (response) {
                                 jQuery('#temp_wait').remove();
                                 jQuery('#' + td_id ).html(sel_str + response + '</select>' );
                                 jQuery('#o_user_' + webform_id + '_').multiSelect({ keepOrder: true,
                                                                                     selectionHeader: 'Open for these users only:',
                                                                                    selectableHeader: 'Click to select:'});
                             }
                           ).fail( function( jqXHr, textStatus, errorThrown ){
                               ewz_alert( 'W020',  ewzG.errmsg.server + jqXHr.responseText, ++popupN );
                               jQuery('#temp_wait').remove();
                           } );
}


function do_batch(){

    var the_nonce = jQuery('#ewznonce').val();

    var formlist = [];
    var titlelist =  '<br>';
    jQuery('#ewz_management').find('input[id^="self"]:checked').each(function() {
        var id = jQuery(this).attr('id').replace('self','');
        formlist.push( id );
        titlelist += ( '<br>* ' + jQuery('#wf_title_' + id + '_').text() );
    });

    var action = jQuery('#bulk-action-selector').val();
    switch( action ){
        case 'ewz_batch_delete_webforms':
        var r1 = ewzG['hasRating'] ? ', ratings ' : '';
        ewz_confirm( "Are you sure you want to delete all these webforms and <b>all their associated items" +
                             r1  + " and files, if any</b>? " +
                             titlelist + "<br><br><b>This action cannot be undone.</b>",
                     function(){ batch_action( action, formlist, the_nonce ); },
                     null,
                     ++popupN);
        break;
        case 'ewz_batch_delete_items':
        var r2 = ewzG['hasRating'] ? 'ratings and ' : '';
        ewz_confirm( "Are you sure you want to delete <b>all the items and their " +
                             r2 + "image files, if any</b> from these webforms?  " +
                             titlelist + "<br><br><b>This action cannot be undone.</b>",
                     function(){ batch_action( action, formlist, the_nonce ); },
                     null,
                     ++popupN);
        break;
        case 'ewz_hide_webforms':
        ewz_confirm( "The following webforms will be hidden, and will no longer appear on this page.<br> " + titlelist +
                     "<br><br>To unhide a webform ( and thus be able to edit or delete it), see the top of this page.",
                     function(){ hide_webforms( formlist, 'hide', the_nonce ); },
                     null,
                     ++popupN);
        break;
        case 'ewz_remove_zipfiles': batch_action( action, formlist, the_nonce );
        break;
    }
}

function batch_action( action_type, formlist, the_nonce ){
    var target = '';
    switch( action_type ){
    case 'ewz_batch_delete_webforms':
        target = 'forms';
        break;
    case 'ewz_batch_delete_items':
        target = 'items';
        break;
    case 'ewz_remove_zipfiles':
        target = 'zipfiles';
        break;
    }
    jQuery('#bulk-action-selector').prepend('<span id="temp_wait" style="text-align:left"> Processing, please wait ... <img alt="Please Wait" src="' + ewzG.load_gif + '"/></span>');
    var jqxhr = jQuery.post( ajaxurl,
                             {
                               ewzmode: 'wf_set',
                               action: 'ewz_webforms_batch_delete',
                               target: target,
                               webform_ids: formlist,
                               ewznonce: the_nonce
                             },
                             function (response) {
                                 jQuery('#temp_wait').remove();
                                 ewz_alert( 'W019', response.replace(/$/mg, '<br>'), ++popupN).on("dialogclose",
                                                                            function(){
                                                                                document.location.reload(true);
                                                                            }
                                                                          );
                             }
                            ).fail( function( jqXHr, textStatus, errorThrown ){
                                jQuery('#temp_wait').remove();
                                ewz_alert( 'W029', ewzG.errmsg.server + jqXHr.responseText, ++popupN );
                            } );
}


function unhide_webforms( ){
    var formlist = jQuery('#ewz_unhide').val();

    var the_nonce = jQuery('#ewznonce').val();


    hide_webforms( formlist, 'show', the_nonce );
}


function hide_webforms( formlist, hide_webform, the_nonce ){
    var do_hide = (hide_webform == 'hide') ? 1 : 0;
    jQuery('#bulk-action-selector').prepend('<span id="temp_wait" style="text-align:left"> Processing, please wait ... <img alt="Please Wait" src="' + ewzG.load_gif + '"/></span>');
    var jqxhr = jQuery.post( ajaxurl,
                             {
                               ewzmode: 'wf_set',
                               action: 'ewz_hide_webforms',
                               hide_webform: do_hide,
                               webform_ids: formlist,
                               ewznonce: the_nonce
                             },
                             function (response) {
                                 jQuery('#temp_wait').remove();
                                 ewz_alert( 'W030', response.replace(/$/mg, '<br>'), ++popupN).on("dialogclose",
                                                                            function(){
                                                                                document.location.reload(true);
                                                                            }
                                                                                                 );
                             }
                            ).fail( function( jqXHr, textStatus, errorThrown ){
                                jQuery('#temp_wait').remove();
                                ewz_alert( 'W031', ewzG.errmsg.server + jqXHr.responseText, ++popupN );
                            } );
}

function toggle_all_forms(){

    if( jQuery('#ewz_all_forms').prop('checked') ){
        jQuery('input[id^="self"]').prop('checked', true );
    } else {
        jQuery('input[id^="self"]').prop('checked', false );
    }
}


/* Actually delete the form on the server via ajax.  If successful, delete it from the page. */
function delete_webform(button, itemcount){
    var jbutton = jQuery(button),
        lname = jbutton.closest('div[id^="ewz-postbox-webform_ev"]').find('div[id^="wf_title_"]').text(),
        confirmstring = '',
        thediv,id,del_nonce,jqxhr;

    thediv = jbutton.closest('div[id^="ewz_admin_webforms_ev"]');
    id = thediv.find('input[name="webform_id"]').first().attr("value");
    if( '' === id || null === id || undefined ===  id ){
        thediv.remove();
        return;
    }
    if(itemcount > 0){
        confirmstring +=  ewzG.errmsg.warn + "<br>"  + ewzG.errmsg.hasitems + "<br><br>";
    }
    confirmstring += ewzG.errmsg.reallydelete;
    confirmstring += "<br>" + ewzG.errmsg.noundo;

    ewz_confirm( confirmstring,
        function(){
            jbutton.after('<span id="temp_del" style="text-align:left"> Processing, please wait ... <img alt="Please Wait" src="' + ewzG.load_gif + '"/></span>');
            del_nonce = jQuery('#ewznonce').val();

            jqxhr = jQuery.post( ajaxurl,
                                     {
                                         action: 'ewz_del_webform',
                                         webform_id: id,
                                         webform_title: lname,
                                         ewznonce: del_nonce
                                     },
                                     function (response) {
                                         jQuery("#temp_del").remove();
                                         if( '1' == response ){
                                             thediv.remove();
                                             var index = js_find_by_key(ewzG.webforms, 'webform_id', id);
                                             ewzG.webforms.splice(index, 1);
                                         } else {
                                             ewz_alert('W003', response.replace(/$/mg, '<br>') + "<br>Refresh page to see current status.", ++popupN );
                                         }
                                         // for( var wf in ewzG.webforms ){console.log('<< ',ewzG.webforms[wf]['webform_id']);}
                                     }
                                   ).fail( function( jqXHr, textStatus, errorThrown ){
                                       jQuery("#temp_del").remove();
                                       ewz_alert( 'W017', ewzG.errmsg.server + jqXHr.responseText, ++popupN );
                                   } );
        },
        null, ++popupN );

}



function add_new_webform(){
    var jthis,
        newform = {},
        jQnew, newid;
    ++nNew;
    newform.can_manage_webform = true;
    newform.can_edit_webform = true;
    newform.can_download = true;
    newform.can_override = false;
    newform.itemcount = 0;
    newform.upload_open = false;
    newform.open_for_string = "";
    newform.layouts_options = ewzG.base_options;
    newform.webform_title = '';
    newform.webform_id = '';
    newform.webform_ident = '';
    newform.time_opts_close = ewzG['time_opts_nosel'];
    newform.time_opts_open = ewzG['time_opts_nosel'];
    newform.prefix = '';
    newform.apply_prefix = true;
    newform.gen_fname = false;
    newid = 'X' + nNew;
    jQnew = jQuery(webform_str(newid, newform));
    jQuery('#ewz_management').prepend(jQnew);
    jQnew.find('div[id^="wf_title_"]').first().html("New Web Form: <i>To make it permanent, set the options and save</i>");

    jQnew.find('input[name="webform_id"]').val('');
    setup_webform( newid, {open_for: []} );
}

function save_webform_order(){
    var wf_nonce = jQuery('#ewznonce').val();
    var data = {
        action: 'ewz_save_webform_order',
        ewznonce:   wf_nonce,
        ewzmode:  'wf_set',
        wforder: new Object()
    };
    if( jQuery('input[id^="edit_wfid"][value=""]').length > 0 ){
        ewz_alert('W004', ewzG.errmsg.saveforms, ++popupN);
        return;
    }

    jQuery('input[id^="edit_wfid"]').each(function(index){
        data['wforder'][jQuery(this).val()] = index;
    });
    data['action'] = 'ewz_save_webform_order';
    data['ewznonce'] = wf_nonce;
    jQuery('button[id^="webforms_save"]').after('<span class="temp_wait" style="text-align:left"> Processing, please wait ... <img alt="Please Wait" src="' + ewzG.load_gif + '"/></span>') ;
    // ajaxurl variable is available in admin
    var jqxhr = jQuery.post( ajaxurl,
                             data,
                             function (response) {
                                 jQuery(".temp_wait").remove();
                                 set_ewzG_webform_order(data['wforder']);
                                 ewz_alert('W005', response.replace(/$/mg, '<br>'), ++popupN );
                             }
                           ).fail( function( jqXHr, textStatus, errorThrown ){
                               jQuery(".temp_wait").remove();
                               ewz_alert( 'W018', ewzG.errmsg.server + jqXHr.responseText, ++popupN );
                           } );
}

function set_ewzG_webform_order(wforder){
   for( var webform_id in wforder ){
       if ( wforder.hasOwnProperty(webform_id) ){
           var ind = ewzG.webforms.findIndex( function(wf){ return wf.webform_id == webform_id; } );
           ewzG.webforms[ind].webform_order = wforder[webform_id];
        }
   }
}

/* Validation */
function ewz_check_csv_input(ftype, evnum, file_input_id){
    var  theFile = document.getElementById(file_input_id).files[0], mb;
    if( null == theFile || undefined == theFile ){
        ewz_alert('W025', ewzG.errmsg.nofile, ++popupN );
        return false;
    } else  {
        // get selected file element
        mb =  Math.floor( theFile.size / 1048576 );
        if( mb > ewzG.maxUploadMb ){
            jQuery('#'+ftype+'_btn_' + evnum ).prop("disabled", false);
            ewz_alert('W006', 'Sorry, your file size is ' + mb + 'M, which is bigger than the allowed maximum of ' + ewzG.maxUploadMb + 'M', ++popupN );
            return false;
        }
        var theType = theFile.type;
        var theName = theFile.name;
        if(  theName.length > 0 && !(/\.csv$/.test(theName) ) ){
            jQuery('#'+ftype+'_btn_' + evnum ).prop("disabled", false);
            ewz_alert('W007', theFile.name + ': Found filename: ' +  theName + ', detected type: ' + theType + '.  Sorry, the file must be of type "text/csv"', ++popupN );
            return false;
        }
    }
    jQuery('#' + ftype+'_btn_' + evnum ).prop("disabled", true);
    return true;
}


function ewz_check_webform_input(form, evnum, do_js_check){
    var jform, except, pref;
    jform = jQuery(form);
    if( jform.find('input[id^="apply_prefix"]').is(':checked') &&
        !jform.find('input[id^="prefix_"]').val().trim( ).length ){
        jform.find('input[id^="apply_prefix"]').prop('checked', false );
    }
    if( jform.find('input[id^="gen_fname"]').is(':checked') &&
        !jform.find('input[id^="prefix_"]').val().trim( ).length ){
        jform.find('input[id^="gen_fname"]').prop('checked', false );
    }

    if( do_js_check) {
        jQuery('#cfg_form_wf' +  evnum + '_').prop("disabled", true);
        try{
            if(!jform.find('input[id^="webform_title_ev"]').val().trim( )){
                err_alert('W008', evnum, ewzG.errmsg.formTitle);
                return false;
            }
            if(!jform.find('input[id^="webform_ident_ev"]').val()){
                err_alert('W009', evnum, ewzG.errmsg.formIdent);
                return false;
            }
            if(!jform.find('input[id^="webform_ident_ev"]').val().match(/^[a-z0-9_\-]+$/i)){
                err_alert('W010', evnum, ewzG.errmsg.formIdent);
                return false;
            }
            if(jform.find('input[id^="auto_open"]').is(':checked') ){
                var dt = jform.find('input[id^="auto_open_date"]').val();
                var tm = jform.find('select[id^="auto_open_time"]').val();
                if( !dt  || !tm ){
                    err_alert('W033', evnum, ewzG.errmsg.needopentime);
                    return false;
                }
            }
            if(jform.find('input[id^="auto_close"]').is(':checked') ){
                var dt = jform.find('input[id^="auto_close_date"]').val();
                var tm = jform.find('select[id^="auto_close_time"]').val();
                if( !dt  || !tm ){
                    err_alert('W034', evnum, ewzG.errmsg.needclosetime);
                    return false;
                }
            }

            pref = jform.find('input[id^="prefix_"]').val();
            if(!pref.match(/^[\[\]A-Z0-9~\-_ ]*$/i)){
                err_alert('W011', evnum, ewzG.errmsg.formPrefix);
                return false;
            }
            if( pref.match(/ /) && jform.find('input[id^="apply_prefix"]').is(':checked') ){
                err_alert('W028', evnum, ewzG.errmsg.spPrefix);
                return false;
            }
            if( pref.match(/\[~1\]/) && !(jform.find('input[id^="gen_fname"]').is(':checked'))){
                err_alert('W012', evnum, ewzG.errmsg.numPrefix);
                return false;
            }
            return true;
        } catch(except) {
            jQuery('#cfg_form_wf' +  evnum + '_').prop("disabled", false);
            err_alert( 'W013', evnum, ewzG.errmsg.unexpected + except.message);
            return false;
        }
    } else {
        return true;
    }
}

function get_wform_ident(element) {
    var id = jQuery(element).closest('div[id^="ewz_admin_webforms"]').attr('id');
    return id.replace('ewz_admin_webforms_ev','').replace('_','');
}



function err_alert(alertid, evnum, msg){
    jQuery('#cfg_form_wf' +  evnum + '_').prop("disabled", false);
    ewz_alert(alertid,  '( webform #' + evnum + ') ' + msg, ++popupN);
}

function sort_alpha(){
    var mylist = jQuery('#ewz_management');
    var listitems = mylist.children('div[id^="ewz_admin_webforms_"]').get();
    listitems.sort(function(a, b) {
        var ja = jQuery(a);
        var jb = jQuery(b);
        var ta = jQuery('#' + ja.attr('id').replace('ewz_postbox_webform_ev', 'wf_title') ).text();
        var tb = jQuery('#' + jb.attr('id').replace('ewz_postbox_webform_ev', 'wf_title') ).text();
        return (ta < tb) ? -1 : (ta > tb) ? 1 : 0;
    });
    jQuery.each(listitems, function(idx, itm) {
        mylist.append(itm);
    });
}

function wforms_compress_lines(checkbox){
    if(jQuery(checkbox).is(':checked')){
        jQuery('div[id^="tpg_header_ev"]').each(function(){
            jQuery(this).css( "padding", "1px" );
        });
        jQuery('div[id^="ewz-postbox-webform_ev"]').each(function(){
            jQuery(this).css( "margin-bottom", "0px" );
        });
    }  else {
        jQuery('div[id^="tpg_header_ev"]').each(function(){
            jQuery(this).css( "padding", "" );
        });
        jQuery('div[id^="ewz-postbox-webform_ev"]').each(function(){
            jQuery(this).css( "margin-bottom", "" );
        });
    }
}
