function clear_survey_form()
{
    $('form[name=form_survey] input[name=block_id]').val('');
    $('form[name=form_survey] input[name=ml_id]').val('');
    $('form[name=form_survey] input[name=block_title]').val('');
    $('form[name=form_survey] input[name=ml_title]').val('');
    $('form[name=form_survey] textarea[name=description]').val('');
    $('form[name=form_survey] textarea[name=choices]').val('');
    $('form[name=form_survey] input[name=type]').attr('checked', false);
    on_change_survey_type();
}

function on_change_survey_type()
{
    var type = $('form[name=form_survey] input[name=type]:checked').val();
    
    if (type == undefined)
    {
        type = SURVEY_TYPE_PETITION;
    }
    
    if (type == SURVEY_TYPE_PETITION)
    {
        $('#survey_choices').hide();
        $('#survey_cut').hide();
    }

    else
    {
        $('#survey_choices').show();
        
        if (type == SURVEY_TYPE_BALLOT)
        {
            $('#survey_cut').show();
        }
        
        else
        {
            $('#survey_cut').hide();
        }
    }
}

function display_edit_survey_form(block_id)
{
    var f_in = document.forms['form_'+block_id];
    var f_out = document.forms['form_survey'];
    var f_import = document.forms['form_import_petition_votes'];

    f_out.block_id.value = block_id;
    f_import.block_id.value = block_id;
    f_out.block_title.value = $('#mblock_title_'+block_id).html();
    f_out.description.value = f_in.description.value;
    f_out.choices.value = f_in.choices.value;
    f_out.type.value = f_in.survey_type.value;
    $('#survey_type_'+f_in.survey_type.value).attr('checked', 'checked');
    $('#button_del_survey').show();
    
    if(f_in.votes.value == '[]') 
    {
        $('#link_edit_survey').show(); 
        $('#disabled_link_edit_survey').hide();
    } 
    
    else 
    {
        $('#link_edit_survey').hide(); 
        $('#disabled_link_edit_survey').show();
    }
    
    if(f_in.status.value == SURVEY_STATUS_CLOSED) 
    {
        $('#li_lock_survey').hide(); 
        $('#li_unlock_survey').show();
    } 
    
    else 
    {
        $('#li_lock_survey').show(); 
        $('#li_unlock_survey').hide();
    }
    
    (f_in.survey_type.value == SURVEY_TYPE_PETITION && f_in.status.value != SURVEY_STATUS_CLOSED) ?
        $('#li_import_survey').show():
        $('#li_import_survey').hide();
    
    if (f_in.survey_type.value == SURVEY_TYPE_BALLOT)
    {
        $('form[name=form_survey] select[name=ml_id]').val(f_in.ml_id.value);

        $('#li_switch_survey_ml').show();
        $('#href_survey_ml').attr('href', get_url_screen('ml')+'&ml_id='+f_in.ml_id.value+'&pid='+f_in.page_id.value);
    }
    
    else
    {
        $('#li_switch_survey_ml').hide();
    }
    
    $('#href_survey_votes').attr('href', get_url_screen('survey_votes')+'&'+FLD_SURVEY_ID+'='+f_in.survey_id.value);
    
    on_change_survey_type();
}

function send_form_survey()
{
    var page_id = $('form[name=form_survey] input[name='+FLD_PAGE_ID+']').val(); 
    var block_id = $('form[name=form_survey] input[name='+FLD_BLOCK_ID+']').val(); 
    var type = $('form[name=form_survey] input:radio[name=type]:checked').val();
    var block_title = $('form[name=form_survey] input[name=block_title]').val(); 
    var description = $('form[name=form_survey] textarea[name=description]').val(); 
    var choices = $('form[name=form_survey] textarea[name=choices]').val(); 
    var ml_id = $('form[name=form_survey] select[name=ml_id]').val(); 
    
    var is_petition = type == SURVEY_TYPE_PETITION;
    var is_survey = (type == SURVEY_TYPE_UNID);
    var is_ballot = (type == SURVEY_TYPE_BALLOT);
    
    if (type == undefined || block_title == '' || description == '')
    {
        my_alert('all field are must');
        return false;
    }
    
    if (is_ballot || is_survey)
    {
        if (choices == '')
        {
            my_alert('all field are must');
            return false;
        }
    }

    if (is_ballot && ml_id == '')
    {
        my_alert('you should select a mailing list');
        return false;
    }
    
    if ( ! is_petition)
    {
        //choices = $.trim(choices.replace(/([\r\n])[\r\n]+/g, '$1')); // I should not do it, so I can identify blank lines.
        choices = $.trim(choices);
        choices_ary = choices.split(/[\r\n]/);
        
        for (var ind in choices_ary)
        {
            if ($.trim(choices_ary[ind]) == '')
            {
                my_alert('You have blank lines within your options');
                return false;
            }
        }
        
        if (choices_ary.length < 2)
        {
            my_alert('You need to specify at least two choices');
            return false;
        }
        
        if (choices_ary.length != jQuery.unique(choices_ary).length)
        {
            my_alert('you cannot define identical options');
            return false;
        }
    }
    
    var data = $("#form_survey").serialize();
    var code = "close_modals(); clear_survey_form(); display_media_blocks_sw_mode(%%%);";
    ajax(data, code, '', 'button_survey', 'saving_survey');
    
    //
    // Reset the form.
    //
    set_form_field('form_survey', 'block_id', '');
    
    return false;
}

function del_block_survey()
{                  
    var f = document.forms['form_survey'];
    var page_id = f.page_id.value;
    var block_id = f.block_id.value;
       
    if (confirm(translate('Should I delete the survey')+'?'))
    {
        var data = 'action=ajax_del_survey&'+FLD_BLOCK_ID+'='+block_id+'&'+FLD_PAGE_ID+'='+page_id;
        var code = "close_modals(); clear_survey_form();"; // close modal should come first - otherwise it did not work.
        code += "remove_block("+block_id+");"
        
        ajax(data, code, "", "button_del_survey", "saving_del_survey");
    }
    
    return false;
}

//
// Generates survey HTML form.
//
function gen_html_survey(block_id, code)
{
    var type = parseInt(code.type);
    var status = parseInt(code.status);
    var description = decode_from_json(code.description);
    var choices_str = decode_from_json(code.choices);
    var choices = choices_str != undefined ? choices_str.split('\n') : '';
    var votes_json = code.votes;
    var votes = eval('(' + votes_json + ')');
    var voter_turnout = code.voter_turnout;
    var date_created = code.date_created;
    var date_closed = code.date_closed;
    var ml_id = code.ml_id; 
    
    var is_petition = type == SURVEY_TYPE_PETITION;
    var is_survey = (type == SURVEY_TYPE_UNID);
    var is_ballot = (type == SURVEY_TYPE_BALLOT);
    var is_closed = (status == SURVEY_STATUS_CLOSED);
    var cb_id, cb_label_id, val;
    var num_votes;
    var str, choice_str, voter_turnout_str, html = '';
    
    if (is_petition)
    {
        num_votes = votes;
    }
    
    else
    {
        num_votes = 0;
        $.each(votes, function (ind, val) {num_votes += parseInt(val);});
    }
 
    if (num_votes > 0)
    {
        html += '<p style="border: 1px solid #ccc; padding : 5px 8px 5px 8px;">';
        
            str = is_petition ?
                translate('people have voted in this petition'):
                translate('people have voted in this survey');
        
            voter_turnout_str = (voter_turnout != 0 && voter_turnout != undefined) ?
                ' ('+voter_turnout+'%)':
                '';
            
            html += '<b>'+num_votes+'</b>'+voter_turnout_str+' '+str+'. &nbsp; ';
            
            if (num_votes > 1)
            {
                if ( is_survey || (is_ballot && (is_closed || IS_CLIENT)) )
                {
                    html += '<a href="#survey_results_'+block_id+'" onclick="$(\'#survey_results_'+block_id+'\').toggle(200)">'+translate('show results')+'</a>';
                }
            }
            
        html += '</p>';
    }

    html += '<p>' + description + '</p>';
    
    html += '<form class="no_labels" id="form_'+block_id+'" name="form_'+block_id+'" onsumbit="return false;" style="width: 100%">';
    html += '<input type="hidden" name="action" value="unid_add_survey_vote" />';
    html += '<input type="hidden" name="'+FLD_PAGE_ID+'" value="'+PAGE_ID+'" />';
    html += '<input type="hidden" name="'+FLD_BLOCK_ID+'" value="'+block_id+'" />';
    
        //
        // Used for editing the survey.
        //
        html += '<input type="hidden" name="survey_id" value="'+block_id+'" />';
        html += '<input type="hidden" name="survey_type" id="survey_type2_'+block_id+'" value="'+type+'" />';
        html += '<input type="hidden" name="status" value="'+status+'" />';
        html += '<input type="hidden" name="description" value="'+q_escape(description)+'" />';
        html += '<input type="hidden" name="choices" value="'+q_escape(choices_str)+'" />';
        html += '<input type="hidden" name="votes" value="'+votes_json+'" />';
        html += '<input type="hidden" name="ml_id" value="'+ml_id+'" />';
        
    if (is_survey || is_ballot)
    {
        html += '<p class="survey_options form_item" style="padding-bottom: 8px;">'; 

        val = 0;
        
        for (var ind in choices)
        {
            cb_id = 'survey_'+block_id+'_'+ind;
            cb_label_id = 'label_'+block_id+'_'+ind;
            choice_str = choices[ind];
            val++;
            
            html += '<input type="radio" class="cb" name="choice" id="'+cb_id+'" value="'+val+'" style="clear: both;" onclick="$(\'.label_'+block_id+'\').css({fontWeight: \'normal\', fontSize: \'1em\'}); $(\'#'+cb_label_id+'\').css({fontWeight: \'bold\', fontSize: \'1.1em\'})" /> ';
            html += '<label for="'+cb_id+'" id="'+cb_label_id+'" class="label_'+block_id+'" onclick="$(\''+cb_id+'\').attr(\'checked\', \'checked\');">'+choice_str+'</label><br>';
        }
        
        html += '</p>'; 
         
    }
    
    if (is_closed)
    {
        html += '<p>'+translate('The survey is closed')+'.</p>';
    }
    
    else
    {
        if ( ! is_ballot)
        {
            str = translate('Voter name');
            html += '<div class="form_item">'; 
            html += '<p class="field">'; 
            html += '<input type="text" name="name" id="survey_vote_name_'+block_id+'" class="mlm" alt="must" value="'+str+'" onfocus="clear_field(this, \''+str+'\'); $(\'#msg_'+block_id+'\').html(\'\');" onblur="reset_field(this, \''+str+'\');" style="width: 90%" />'; 
            html += '</p>';
            html += '</div>';
        }

        html += '<div class="form_item">'; 
        str = translate('Voter email');
        html += '<p class="field">';
        html += '<input type="email" name="email" id="survey_vote_email_'+block_id+'" class="ltr mlm" alt="must" value="'+str+'" onfocus="clear_field(this, \''+str+'\'); $(\'#msg_'+block_id+'\').html(\'\');" onblur="reset_field(this, \''+str+'\');" style="width: 90%" />'; 
        html += '</p>'; 
        html += '</div>'; 

        var cb_class = is_ballot ? 'hidden' : '';
        
        html += '<div class="form_item '+cb_class+'">';
        html += '<p class="field">';
        html += '<input type="checkbox" name="join_ml" class="cb" id="cb_survey_join_ml_'+block_id+'" />';
        html += '<span onclick="$(\'#cb_survey_join_ml_'+block_id+'\').is(\':checked\') ? $(\'#cb_survey_join_ml_'+block_id+'\').attr(\'checked\', false) : $(\'#cb_survey_join_ml_'+block_id+'\').attr(\'checked\', \'checked\');">'+translate('I agree to join this site mailing list')+'</span>';
        html += '</p>';
        html += '</div>';
         
        html += '<p>';

            html += is_closed ? 
                '<button title="'+translate('The survey is closed')+'" disabled="disabled">'+translate('send')+'</button>':
                '<button id="button_'+block_id+'" onclick="send_survey_vote('+block_id+', '+type+'); return false;">'+translate('Vote')+'</button>';

            html += '<img id="saving_'+block_id+'" class="image_saving hidden" src="'+CSS_IMAGE_SAVING+'" />';
            
        html += '</p>'; 
    }

    html += '</form>';
    
    
    //
    // Survey results.
    //
    if ( num_votes > 1 && (is_survey || is_ballot) )
    {
        html += '<a name="survey_results_'+block_id+'"></a>';
        html += '<div id="survey_results_'+block_id+'" class="frame hidden">';
        
        for (var ind in choices)
        {
            pct = parseInt(100 * votes[ind] / num_votes);
            html += '<p><b>'+choices[ind]+'</b> '+pct+'% ('+votes[ind]+' '+translate('votes')+')<br><div id="survey_pb_'+block_id+'_'+ind+'"></div></p>';
        }
        html += '</div>';
        
        $(document).ready(function() {
            for (var ind in choices)
            {
                pct = parseInt(100 * votes[ind] / num_votes);
                $('#survey_pb_'+block_id+'_'+ind).slider({value: pct, range: "min", min: 0, max: 100, disabled: true, text:"aa"});    
            }
        });

        html += '</div>';
    }
    
    return html;
}

function send_survey_vote(block_id, type)
{
    var type = $('#survey_type2_'+block_id).val();
    var name = $('#survey_vote_name_'+block_id).val();
    var email = $('#survey_vote_email_'+block_id).val();
    var is_join_ml = $('#cb_survey_join_ml_'+block_id+':checked').val() !== undefined;
    var is_survey = (type == SURVEY_TYPE_UNID);
    var is_ballot = (type == SURVEY_TYPE_BALLOT);
    
    var choice = '';

    if (is_ballot)
    {
        name = '';
    }
    
    else
    {
        if (name == '' || name == translate('Voter name'))
        {
            my_alert('You should fill in your name |'+name+'|');
            return false;
        }
    }
        
    if (email == '' || email == translate('Voter email'))
    {
        my_alert('You should fill in your email address');
        return false;
    }

    if ( ! is_valid_email_syntax(email))
    {
        my_alert('invalid email syntax');
        return false;
    }
    
    if (is_survey || is_ballot)
    {
        choice = $('input[name=choice]:checked', '#form_'+block_id).val(); // Referring to it as 'form input ...' failed.

        if (choice == undefined)
        {
            my_alert('You must make a selection');
            return false;
        }
    }   

    if ( ! is_join_ml && ! is_ballot)
    {
        if (confirm(translate('would you like to join the site mailing list?')))
        {
            $('form[name=form_'+block_id+'] input[name=join_ml]').attr('checked', true);
            is_join_ml = true;
        }
    }
    
    create_cookie('LOCALI_MLM_NAME', name, '1 years');
    create_cookie('LOCALI_MLM_EMAIL', email, '1 years');
    
    var data = '';
    
    data += '&'+FLD_BLOCK_ID+'='+block_id;
    data += '&'+FLD_PAGE_ID+'='+PAGE_ID;
    data += '&name='+name;
    data += '&email='+email;
    data += '&join_ml='+(is_join_ml ? 1 : 0);
    data += '&choice='+choice;
    
    $('#button_'+block_id).hide();
    $('#saving_'+block_id).show();
    
    location.href = get_url_action('unid_add_survey_vote')+data;
    
    return false;
}

//
// Toggles survey lock.
//
function lock_survey()
{
    var block_id = $('form[name=form_survey] input[name='+FLD_BLOCK_ID+']').val();
    var data = 'action=ajax_toggle_survey_status&'+FLD_BLOCK_ID+'='+block_id;  
    var code = "close_modals(); display_media_blocks_sw_mode(%%%);";
    ajax(data, code, '', 'button_lock_survey', 'saving_lock_survey');
}

function unlock_survey()
{
    var block_id = $('form[name=form_survey] input[name='+FLD_BLOCK_ID+']').val();
    var data = 'action=ajax_toggle_survey_status&'+FLD_BLOCK_ID+'='+block_id;
    var code = "close_modals(); display_media_blocks_sw_mode(%%%);";
    ajax(data, code, '', 'button_unlock_survey', 'saving_unlock_survey');
}

function send_form_import_petition_votes()
{
    var csv = $.trim($('form[name=form_import_petition_votes] textarea[name=votes_csv]').val());
    
    if (csv == '')
    {
        my_alert('all field are must');
        return false;
    }
    
    var data = $('form[name=form_import_petition_votes]').serialize();
    var code = "close_modals(); alert(%%%)";
    ajax(data, code, '', 'button_import_votes', 'saving_import_votes');
}

