//
// Generates HTML for displaying a form field  / title. 
//
// Field params:
// . id
// . type
// . title
// . helptext
// . required: 0/1
// . charlimit: 1..20
// . values (for radio, select, checkbox)
//
// Field type: 
//
// . subtitle
// . free text
// . text
// . textarea
// . digits
// . email
// . date
// . yesno
// . radio
// . select
// . checkbox
// . file
//
function display_form_fields(page_id, form_id, is_edit_form_mode)
{
    var data = 'action=ajax_get_form_fields&'+FLD_PAGE_ID+'='+page_id+'&'+FLD_FORM_ID+'='+form_id;
    var code = '$("#mblock_code_'+form_id+'").html(gen_html_form('+form_id+', %%%, '+is_edit_form_mode+', false));';
    
    if (is_edit_form_mode)
    {
        code += 'make_modals("#mblock_code_'+form_id+'");';
        code += 'make_form_items_sortable("'+page_id+'",'+form_id+');';
        ajax(data, code, '', "button_form_field", "saving_form_field");
    }
    
    else
    {
        ajax(data, code);
    }
}

function gen_html_form(form_id, fields, is_edit_form_mode, is_fields_json)
{
    var html = '';
    var ff_id, field, type, title, help, is_must, options, free_text;
    var help_str, options_ary, option, is_field, is_options, option_id;
    var attrs_str, fldinfo_str, onclick_str, onmouseover_str;
    var i;
    
    if (fields == null)
    {
        return '<p>'+translate('No fields were set for this form - click its title to edit')+'.</p>';
    }
    
    if (is_edit_form_mode)
    {
        html += '<form name="form_'+form_id+'">';
    }
    
    else
    {
        html += '<form name="form_'+form_id+'" id="form_'+form_id+'" action="'+get_url_action()+'" method="post" enctype="multipart/form-data" onsubmit="return false;">';
        html += '<input type="hidden" name="'+FLD_ACTION+'" value="unid_send_block_form" />';
        html += '<input type="hidden" name="'+FLD_FORM_ID+'" value="'+form_id+'" />';
    }
    
    var onfocus_str = is_edit_form_mode ?
        '': 
        'onfocus="$(this).removeClass(\'error\'); $(\'#form_'+form_id+' *\').removeClass(\'onfocus\'); $(this).parent().parent().addClass(\'onfocus\');" onblur="$(this).removeClass(\'error\'); $(this).parent().parent().removeClass(\'onfocus\');"'; 

    if (is_fields_json)
    {
        fields = jQuery.parseJSON(fields);
    }        
    
    for (var ff_ind in fields)
    {
        field = fields[ff_ind];
        type = field['type'];
        title = decode_from_json(field['title']);
        help = decode_from_json(field['help']);
        is_must = field['is_must'];
        options = decode_from_json(field['options']);
        free_text = decode_from_json(field['free_text']);
        
        attrs_str = '';
        
        is_field = type != FIELD_TYPE_FREE_TEXT;
        is_options = type == FIELD_TYPE_RADIO || type != FIELD_TYPE_SELECT || type != FIELD_TYPE_CHECKBOX;
 
        ff_id = form_id+'_'+ff_ind;
        
        if (is_options)
        {
            options_ary = options.split("\r\n");
        }
        
        onmouseover_str = is_field ?
            'onmouseover="$(this).addClass(\'onmouseover\');" onmouseout="$(this).removeClass(\'onmouseover\');"':
            '';           

        html += is_edit_form_mode ?
        
            '<div rel="#form_form_field" class="modal_input form_item edit handle" id="ff'+ff_ind+'" type="'+type+'" is_must="'+is_must+'" help="'+help+'" options="'+options+'" onclick="set_form_form_field('+form_id+', '+ff_ind+', 0)" title="'+translate('Click to edit')+' &#8226; '+translate('Drag to move')+'" '+onmouseover_str+'>': 
     
            '<div class="form_item" '+onmouseover_str+'>';
        
            if (is_field)
            {
                html += '<span class="label">';
                
                    if (is_edit_form_mode)
                    {
                        html += '<span id="ff_title_'+ff_ind+'">'+title+'</span>:';
                    }
                    
                    else
                    {
                        html += title+':';
                    }
                    
                    if (is_must)
                    {
                        html += '<span class="must" style="font-size: 0.9em;"> *</span> ';
                        attrs_str = 'is_must="1"';
                    }
                    else
                    {
                        attrs_str = 'is_must="0"';
                    }
                    
                    if (help != '')
                    {
                        html += '<span onclick="alert(\''+help+'\')" class="help" title="'+help+'">?</span>';
                    }
                    
                html += '</span>';
                
                html += '<p class="field">';
            }
            
            if (is_edit_form_mode)
            {
                attrs_str += ' disabled="disabled"';
            }

            onclick_str = is_edit_form_mode ?
                '': 
                '$(\'#form_'+form_id+' input[name=form_'+ff_id+']\').removeClass(\'error\'); $(\'#form_'+form_id+' *\').removeClass(\'onfocus\'); $(\'#form_'+form_id+' .form_'+ff_id+'\').parent().parent().addClass(\'onfocus\');'; 

            fldinfo_str = attrs_str+' '+onfocus_str;
            
            switch (type)
            {
                case FIELD_TYPE_FREE_TEXT:
                html += '<div id="free_text_'+ff_ind+'" class="free_text">'+free_text+'</div>';
                break;
                
                case FIELD_TYPE_TEXT:
                    html += '<input type="text" name="form_'+ff_id+'" '+fldinfo_str+' />';
                break;
                
                case FIELD_TYPE_TEXTAREA:
                html += '<textarea type="text" name="form_'+ff_id+'" '+fldinfo_str+'></textarea>';
                break;
                
                case FIELD_TYPE_DIGITS:
                html += '<input type="text" name="form_'+ff_id+'" '+fldinfo_str+' onkeyup="validate_number(this)" />';
                break;
                
                case FIELD_TYPE_EMAIL:
                html += '<input type="email" name="form_'+ff_id+'" '+fldinfo_str+' />';
                break;
                
                case FIELD_TYPE_DATE:
                html += '<input type="text" name="form_'+ff_id+'" '+fldinfo_str+' class="date" />';
                break;
                
                case FIELD_TYPE_YESNO:
                html += '<input type="radio" class="cb form_'+ff_id+'" name="form_'+ff_id+'" id="form_'+ff_id+'_yes" value="1" onchange="$(\'#label_'+ff_id+'_yes\').addClass(\'highlight\'); $(\'#label_'+ff_id+'_no\').removeClass(\'highlight\'); '+onclick_str+'" '+attrs_str+' />';
                html += '<label for="form_'+ff_id+'_yes" id="label_'+ff_id+'_yes">'+translate('Yes')+'</label>';
                html += '<input type="radio" class="cb form_'+ff_id+'" name="form_'+ff_id+'" id="form_'+ff_id+'_no" value="0"  onchange="$(\'#label_'+ff_id+'_yes\').removeClass(\'highlight\'); $(\'#label_'+ff_id+'_no\').addClass(\'highlight\'); '+onclick_str+'" '+attrs_str+' />';
                html += '<label for="form_'+ff_id+'_no" id="label_'+ff_id+'_no">'+translate('No')+'</label>';
                break;
                
                case FIELD_TYPE_RADIO:

                    for (var ind_option in options_ary)
                    {
                        option = options_ary[ind_option];
                        option_id = 'form_'+ff_id+'_'+ind_option;
                        label_id = 'label_'+ff_id+'_'+ind_option;
                        
                        html += '<input type="radio" class="cb form_'+ff_id+'" name="form_'+ff_id+'" id="'+option_id+'" value="'+ind_option+'" onchange="$(\'#form_'+form_id+' input[name=form_'+ff_id+'] + label\').removeClass(\'highlight\'); $(\'#'+label_id+'\').addClass(\'highlight\'); '+onclick_str+'" '+attrs_str+' />';
                        html += '<label for="'+option_id+'" id="'+label_id+'">'+option+'</label>';
                    }

                break;
                
                case FIELD_TYPE_SELECT:
                html += '<select type="select" name="form_'+ff_id+'" '+fldinfo_str+'>';
                    
                    html += '<option value="-1">---</option>';
                    
                    for (var ind_option in options_ary)
                    {
                        option = options_ary[ind_option];
                        html += '<option value="'+ind_option+'">'+option+'</option>';
                    }

                html += '</select>';
                break;
                
                case FIELD_TYPE_CHECKBOX:
                    
                    for (var ind_option in options_ary)
                    {
                        option = options_ary[ind_option];
                        option_id = 'form_'+ff_id+'_'+ind_option;
                        label_id = 'label_'+ff_id+'_'+ind_option;
                        
                        html += '<input type="checkbox" class="form_'+ff_id+'" name="form_'+ff_id+'_'+ind_option+'" id="'+option_id+'" value="1" onchange="$(\'#'+label_id+'\').toggleClass(\'highlight\'); $(\'#'+option_id+'\').removeClass(\'error\'); " onclick="'+onclick_str+'" '+attrs_str+' />';
                        html += '<label for="'+option_id+'" id="'+label_id+'">'+option+'</label>';
                    }

                break;

                case FIELD_TYPE_FILE:
                html += '<input type="file" name="form_'+ff_id+'" '+fldinfo_str+' onclick="$(this).removeClass(\'error\');" />';
                break;
            }

        if (is_field)
        {
            html += '</p>';
        }

        html += '</div>';
    }    
    
    html += '<div class="form_item">';
    
        html += is_edit_form_mode ?
            '<button onclick="return false;">'+translate('Send')+'</button>':
            '<button id="button_'+form_id+'"  onclick="send_block_form('+form_id+'); return false;">'+translate('Send')+'</button>'; 
        html += '<img id="saving_'+form_id+'" class="image_saving hidden" src="'+CSS_IMAGE_SAVING+'" />';
        
    html += '</div>';
    
    html += '</form>';
    
    html += '<script>$("#mblock_code_'+form_id+' .date").datepicker({ dateFormat: "yy-mm-dd", changeYear: true, yearRange: "-100:+2" });</script>'; // 
    
    return html;
}

function make_form_items_sortable(page_id, form_id)
{
    $("#mblock_code_"+form_id).sortable(
    { 
        items: '.handle',
        opacity: 0.6,
        revert: true,
        
        update : function () 
        { 
            close_modals(); // Since clicking the field also opens the overlay window.
            var field_ids = $('#mblock_code_'+form_id).sortable('toArray');
            var data = 'action=ajax_update_form_fields_order&form_id='+form_id+'&field_ids='+field_ids+'&'+FLD_PAGE_ID+'='+page_id; // Page ID is inputed for maintaining a client status (in case it is a client).
            var code = '';
            ajax(data, code);
        } 
    }); 
}

function send_block_form(form_id)
{
    var name, val, type, is_must, is_checked, cls, num_checked;
    var errs = new Array;
    var missing_values = new Array;
    var invalid_emails = new Array;
    
    var $inputs = $('#form_'+form_id+' :input');
    
    $inputs.each(function() {

        name = $(this).attr('name');
        
        if (name != undefined && name.indexOf('form_'+form_id+'_') == 0)
        {
            val = $.trim($(this).val());
            type = $(this).attr('type');
            is_must = $(this).attr("is_must");
            
            switch (type)
            {
                case 'text':
                case 'textarea':
                case 'file':

                    if (is_must == 1 && val == '')
                    {
                        missing_values.push(name);
                    }

                    break;
                
                case 'email':

                    if (is_must == 1 && val == '')
                    {
                        missing_values.push(name);
                    }
                
                    if (val != '' && ! is_valid_email_syntax(val))
                    {
                        invalid_emails.push(name);
                    }

                    break;
                
                case 'select':

                    if (is_must == 1 && val == -1)
                    {
                        missing_values.push(name);
                    }

                    break;
                
                case 'radio':

                    if (is_must == 1)
                    {
                        is_checked = $('#form_'+form_id+' input[name='+name+']:checked').val() != undefined;
                        
                        if ( ! is_checked)
                        {
                            missing_values.push(name);  
                        }
                    }

                    break;

                case 'checkbox':
                    
                    if (is_must == 1)
                    {
                        cls = $(this).attr('class');
                        num_checked = parseInt($('#form_'+form_id+' input.'+cls+':checked').length);
                        
                        is_checked = num_checked > 0;
                        
                        if ( ! is_checked)
                        {
                            missing_values.push(name); 
                        }
                    }

                    break;
            }
            
            
        }
    });
    
    if (missing_values.length > 0)
    {
        errs.push(translate('Fill in all must fields'));
        
        for (var ind in missing_values)
        {
            name = missing_values[ind];
            $('#form_'+form_id+' *[name='+name+']').addClass('error');
        }
    }
 
    if (invalid_emails.length > 0)
    {
        errs.push(translate('Invalid email syntax'));
        
        for (var ind in invalid_emails)
        {
            name = invalid_emails[ind];
            $('#form_'+form_id+' input[name='+name+']').addClass('error');
        }
    }
    
    if (errs.length > 0)
    {
        errs.length == 1 ?
            my_alert(errs[0]):
            my_alert(translate('There are some errors')+":\r\n\r\n - "+errs.join("\r\n - "));
            
        return false;
    }
 
    $('#button_'+form_id).hide();
    $('#saving_'+form_id).show();
    
    var f = document.forms['form_'+form_id];
    f.submit();

    return true;
}
