/*common.js*/
$(function() {

    // General method to get elements thanks to regex !
    // sample : $('div:regex(class,jqTable[0-9]_.*)'); */
    $.expr[':'].regex = function(elem, index, match) {
        var matchParams = match[3].split(','),
            validLabels = /^(data|css):/,
            attr = {
                method: matchParams[0].match(validLabels) ?
                    matchParams[0].split(':')[0] : 'attr',
                property: matchParams.shift().replace(validLabels, '')
            },
            regexFlags = 'ig',
            regex = new RegExp(matchParams.join('').replace(/^s+|s+$/g, ''), regexFlags);
        return regex.test(jQuery(elem)[attr.method](attr.property));
    }
    // End of General method to get elements thanks to regex !

    var $invisible = $('.invisible');
    $invisible.each(function() {
        if ($(this).find("textarea").text() == '') {
            $(this).hide();
        } else {
            $(this).show();
            $(this).find("div.content").addClass("errornotice");
        }
    });
    // End of Errors in profile have ...

    // Avoid html5 browser validation
    $('form.quixote').attr('novalidate', 'novalidate');
    // End of Avoid html5 browser ...

    // Set readonly attributes on "input, textarea and select"
    // element when meeting a .readonly css class on div parent*/
    var $form_divs_readonly = $('form.quixote div.readonly');
    $form_divs_readonly.each(function() {
        $("input", this).prop('readonly', true);
        $("textarea", this).prop('readonly', true);
        $("select", this).prop('readonly', true);
    });
    // End of Set readonly attributes on ...

    // Add this class on a comment field.
    // Remove all buttons except CANCEL button.
    var no_perm_page = $(".no_permission_page").parent().find("div.buttons.submit > .SubmitWidget button").each(function(){
	    if ($(this).attr("name") != "cancel") {
	        $(this).hide();
	    }
    });

    // hide page in backoffice
    var $bo_noshowpage = $('div#summary > div.dataview .bo_noshowpage')
    $bo_noshowpage.each(function() {
        $(this).parent().css('display', 'none');
    });

    // Add pointer cursor on "Demarche" title and "+ cursor"
    $(".more-items a").mouseover(function() {
        $(this).css('cursor', 'pointer');
    });

    $(".page-citoyens h2").mouseover(function() {
        $(this).css('cursor', 'pointer');
    });
    // End of Add pointer cursor ...

    // Adapt validation form when we want to jst download .pdf
    var $pdf_form_adapter = $('form[data-keywords="pdf"]');
    $pdf_form_adapter.each(function() {
        var $this_form = $(this);
        $(this).find('.cancel-button').hide();
        $(this).find('.submit-button input').attr('value', 'Télécharger');
        $(this).on('submit', function() {
            window.location = $this_form.find('a').attr('href');
            return false;
        });
    });
    // End of Adapt validation form ...

    // Skin basket page. Split item name and item number
    var $basket_name_item = $('.page-panier ul > li > label > a');
    $basket_name_item.each(function() {
        var item = $(this).html();
        var $href = $(this).attr('href');
        var $item_name = item.split(" - n°")[0];
        var $item_num = item.split(" - n°")[1];
        $(this).html($item_name);
        $(this).after("<a class='basket-number' href='" + $href + "'>n° " + $item_num + "</a>");
    });
    // End of Skin basket ...

    // Hide field's title
    var $hide_title = $('.hide_title');
    $hide_title.each(function() {
        $(this).children('.title').hide();
    });
    // End of Hide field's ...

    // Hide empty input text in validation form page
    var $empty_input_text = $(".form-validation form.quixote input:text");
    $empty_input_text.each(function() {
        if ($(this).val() == "") {
            $("label[for='" + $(this).attr("id") + "']").css('display', 'None');
            $(this).css('display', 'None');
        }
    });
    // End of Hide empty input text ...

    // Print empty basket page message
    var $basket_page = $('body.page-panier > div#page > div#main-content-wrapper div#columns')
    $basket_page.each(function() {
        if (!$('div.lingobasketcell').length) {
            $(this).append('<div id="empty_basket"><h2>Votre panier est actuellement vide.</h2></div>');
        }
    });
    // End of Print empty basket ...

    // Remove "Belgique" from select box.
    var $country_datasrc_without_belgium = $('.without_belgium select');
    $country_datasrc_without_belgium.each(function() {
        $(this).children('option[value="Belgique"]').remove();
    });
    // End of Remove "Belgique" from select box ...



    // Hide field's title
    var $hide_title = $('.hide_title')
    $hide_title.each(function() {
        $(this).children('.title').hide();
    });
    // End of Hide ...

    // Hide empty input text in validation form page
    var $empty_input_text = $(".form-validation form.quixote input:text");
    $empty_input_text.each(function() {
        if ($(this).val() == "") {
            $("label[for='" + $(this).attr("id") + "']").css('display', 'None');
            $(this).css('display', 'None');
        }
    });
    // End of Hide empty input text ...

    // textboxfield with var "txt_selected_motifs" + tablefield in the same page to manage multi motifs selection and number of copies.
    // Table MUST have n lines for n motivations max.
    // Table MUST have 2 columns "Motifs" keep motivation name and "Nb exemplaire" to input number of copies
    var $table_nb_motifs = $('span#txt_selected_motifs').parent().parent().next();
    $table_nb_motifs.attr("id", "var_table_nb_motifs");
    $table_nb_motifs = $('div#var_table_nb_motifs table')
    $table_nb_motifs.each(function() {
        var extraCol = false;
        $('span#txt_selected_motifs').hide();
        $lst_selected_motifs = $('span#txt_selected_motifs').text().split(', ');
        $tr = $('div#var_table_nb_motifs table > tbody > tr');
        $('div#var_table_nb_motifs table thead tr').find('th:nth-child(2)').toggle();
        $tr.each(function(tr) {
            var nbcol = $(this)[0].cells.length;
            if (nbcol > 3) {
                extraCol = true;
            }
            $name = $(this).find('input').attr('name');
            var new_motif_input_name = $name.split('-')[0] + '-' + tr + '-' + $name.split('-')[2];
            var new_nb_ex_input_name = $name.split('-')[0] + '-' + tr + '-' + (parseInt($name.split('-')[2]) + 1);
            var input_motif = "<input id=\"form_" + new_motif_input_name + "\" name=\"" + new_motif_input_name + "\" type=\"text\" value=\"" + $lst_selected_motifs[tr] + "\" />";
            /* Default value set to 1 but if we return back... this is a problem.*/
            var input_nb_ex = "<input id=\"form_" + new_nb_ex_input_name + "\" name=\"" + new_nb_ex_input_name + "\" type=\"text\" value='1' />";
            var new_td = "";
            if (tr < $lst_selected_motifs.length) {
                if (extraCol == true) {
                    for (var i = 3; i < nbcol; i++) {
                        var new_extra_col_name = $name.split('-')[0] + '-' + tr + '-' + (parseInt($name.split('-')[2]) + (i - 1));
                        new_td += "<td><input id=\"form_" + new_extra_col_name + "\" name=\"" + new_extra_col_name + "\" test='test' type=\"text\" value='' /></td>";
                    }
                }
                $(this).replaceWith("<tr><th style='text-align:left;'>" + $lst_selected_motifs[tr] + "</th><td style='display:none'>" + input_motif + "</td><td>" + input_nb_ex + "</td>" + new_td + "</tr>");
            } else {
                $(this).remove();
            }
        });
    });
    // END textboxfield with var "txt_selected_motifs" ...

    // GENERATE CSV FILE thanks to a table and a link .export
    function exportTableToCSV($table, filename) {
        var $rows = $table.find('tr:has(td)'),

            // Temporary delimiter characters unlikely to be typed by keyboard
            // This is to avoid accidentally splitting the actual contents
            tmpColDelim = String.fromCharCode(11), // vertical tab character
            tmpRowDelim = String.fromCharCode(0), // null character

            // actual delimiter characters for CSV format
            colDelim = '|',
            rowDelim = '\r\n',

            // Grab text from table into CSV formatted string
            // csv = '"' + $rows.map(function(i, row) {
            csv = $rows.map(function(i, row) {
                var $row = $(row),
                    $cols = $row.find('td');

                return $cols.map(function(j, col) {
                    var $col = $(col),
                        text = $col.text();

                    return text.replace(/"/g, '""'); // escape double quotes

                }).get().join(tmpColDelim);

            }).get().join(tmpRowDelim)
            .split(tmpRowDelim).join(rowDelim)
            .split(tmpColDelim).join(colDelim); // + '"';

        // Deliberate 'false', see comment below
        if (false && window.navigator.msSaveBlob) {

            var blob = new Blob([decodeURIComponent(csv)], {
                type: 'text/csv;charset=utf8'
            });

            // Crashes in IE 10, IE 11 and Microsoft Edge
            // See MS Edge Issue #10396033
            // Hence, the deliberate 'false'
            // This is here just for completeness
            // Remove the 'false' at your own risk
            window.navigator.msSaveBlob(blob, filename);

        } else if (window.Blob && window.URL) {
            // HTML5 Blob
            var blob = new Blob([csv], {
                type: 'text/csv;charset=utf-8'
            });
            var csvUrl = URL.createObjectURL(blob);

            $(this)
                .attr({
                    'download': filename,
                    'href': csvUrl
                });
        } else {
            // Data URI
            var csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);

            $(this)
                .attr({
                    'download': filename,
                    'href': csvData,
                    'target': '_blank'
                });
        }
    }

    // This must be a hyperlink
    $(".export").on('click', function(event) {
        // CSV
        var args = [$('table.stats'), 'export.csv'];
        exportTableToCSV.apply(this, args);
    });
    // End of GENERATE CSV FILE thanks to ...


    /* SPECIFIC USE-CASE !!! */

    /* LIEGE */
    // Call "nextAll" method when click on title (same effect than "+ cursor").
    // When more than max "demarche" are printing on "demarche" page, stretch to view all "demarches"
    $(document).on('click', '.page-citoyens h2', function() {
        $(this).parent().find('.more-items').hide();
        $(this).parent().find('.more-items').nextAll().show();
    });
    /* End of LIEGE*/


    $.fn.get_elem_by_inner_html = function(o) {
        var element = null;
        $(this).each(function() {
            $normalize_intitule = $(this).html().normalize('NFD').replace(/[\u0300-\u036f]/g, "").replace(' ', '-');
            if ($normalize_intitule.indexOf(o) != -1) {
                // !!! Only one row to replace ???
                element = $(this);
            }
        });
        return element;
    };

    $.fn.field_substitution = function(field, clone, marginbottom) {
        var old_table_input = $(this).find('input');
        var new_field = null;
        var new_table_div_field = field.clone(clone);
        new_table_div_field.find('label').attr('for', old_table_input.attr('id') + 'b');
        new_table_div_field.find('.title').css('display', 'none');
        new_table_div_field.css('margin-bottom', marginbottom);
        old_table_input.css('display', 'none');
        if (new_table_div_field.find('input').length > 0) {
            new_field = new_table_div_field.find('input');
    	}
    	if (new_table_div_field.find('select').length > 0) {
            new_field = new_table_div_field.find('select');
    	}
        try {
            new_field.val(old_table_input.val());
        } catch (e) {}
        new_field.attr('id', old_table_input.attr('id') + 'b');
        new_field.attr('name', old_table_input.attr('name') + 'b');
        new_field.bind('change', {
            input_table: old_table_input
        }, change_input_table_value);
        new_field.bind('click', {
            input_table: old_table_input,
            current_field: new_field
        }, click_input_table);
        $(this).append(new_table_div_field);
    };

    var click_input_table = function(event) {
        var offset = $(this).offset();
        // alert(JSON.stringify(event.data.input_table));
        $calendar = $('div.datetimepicker-dropdown');
        $calendar.css('left', offset.left);
        $calendar.css('top', offset.top);
        $calendar.bind('click', {
            input_table: event.data.input_table,
            current_field: event.data.current_field
        }, click_calendar);
    }
    var click_calendar = function(event) {
        event.data.current_field.val($(this).find('.switch').html());
        event.data.input_table.val($(this).find('.switch').html());
    }

    var change_input_table_value = function(event) {
        event.data.input_table.val($(this).val());
    }

    var more_row_mouseup = function(event) {
        var table = event.data.table;
        var nb_tr = table.find('tr').length + 1;
        if (nb_tr > event.data.nb_files) {
            $(this).hide();
        }
    }

    var jq_fields = $('div#rub_service > form.quixote div:regex(class,jqTable[0-9]_.*)');
    var jq_tables = $('div#rub_service > form.quixote div:regex(class,jqTable[0-9])');
    var add_more_table_row_button = $('div.widget-optional input[type=submit]');
    var cpt_table = 1;
    var jq_fields_files = jq_fields.find('input[type="file"]');
    var cpt_jq_field_file = jq_fields.find('input[type="file"]').length;
    jq_fields.each(function(i, field) {
        var current_field = $(field).detach();
        var html = current_field.html();
        if (html.indexOf('type="file"') == -1) {
            var jq_field_classname = get_css_class_name_by_prefix(current_field, "jqTable");
            var table_name = jq_field_classname.split("_")[0];
            var inserting_method = jq_field_classname.split("_")[1];
            var table_field = jq_field_classname.split("_")[2].replace(/[\n\r]/g, '');
            if (inserting_method == 'row') {
                var row_to_replace = $('div:regex(class,' + table_name + ')').find("th").get_elem_by_inner_html(table_field).parent();
                row_to_replace.find('td').field_substitution(current_field, false, '0px');
            }
            if (inserting_method == 'col') {
                var table = $('div:regex(class,' + table_name + ') table');
                var tr = table.find("tr");
                tr.each(function(t1, tr) {
                    var td = $(tr).find('td');
                    var cpt_td = 0;
                    td.each(function(t2, td) {
                        if (cpt_td == table_field) {
                            $(td).find('div').css('display', 'none');
                            $(td).field_substitution(current_field, true, '14px');
                        }
                        cpt_td++;
                    });
                });
            }
        }

        jq_tables.each(function() {
            if ($(this).has('table').length > 0) {
                var $current_table = $(this);
                // On recupere seulement les fields type "fichier" pour le tableau courant.
                var $jq_fields_files = $('div#rub_service > form.quixote div:regex(class,jqTable' + cpt_table + 'File_.*)');
                var nb_files = $jq_fields_files.length;
                if (nb_files > 0) {
                    add_more_table_row_button.bind('mouseup', {
                        nb_files: nb_files,
                        table: $current_table
                    }, more_row_mouseup);
                }
                var cpt_field_file = 1;
                $jq_fields_files.each(function() {
                    var $current_field_file = $(this).detach();
                    var jq_field_classname = get_css_class_name_by_prefix($(this), 'jqTable' + cpt_table + 'File');
                    var table_field = jq_field_classname.split("_")[2].replace(/[\n\r]/g, '');
                    var $td = $('tr:eq(' + cpt_field_file + ') td:eq(' + table_field + ')', $current_table);
                    $td.find('div').css('display', 'none');
                    $td.field_substitution($current_field_file, false);
                    cpt_field_file++;
                });
                var $tr = $current_table.find('tr');
                var cpt_tr = 0;
                $tr.on('custom', function(event, obj) {
                    if (cpt_tr > obj.extra && obj.extra > 0) {
                        $(this).hide();
                        // hide 'add new row'
                        $add_more_row.hide();
                    }
                    cpt_tr++;
                });
                $tr.trigger('custom', [{
                    extra: nb_files
                }]);
                cpt_table++;
            }
        });
    });
    /* hinge fields */
    var hinge_fields = $('div#rub_service > form.quixote div:regex(class,hinge_.*)');
    hinge_fields.each(function() {
        var jq_field_classname = get_css_class_name_by_prefix($(this), "hinge_");
        // Get the ID of the field that manage 'hinge' field.
        var master_field_id = 'var_' + jq_field_classname.split("_")[1];
        // the term to trigger
        var trigger_term = jq_field_classname.split("_")[2];
        var master_field = $('div#' + master_field_id);

        var selec_value = master_field.find('select').val();
        if (typeof selec_value === "undefined") {
            //searched_hinge_field RADIO BUTTONS LIST case :
            selec_value = master_field.find('input:checked').val();
        }
        if (typeof selec_value === "undefined") {
            $(this).hide();
        } else {
            if (selec_value.localeCompare(trigger_term == 0) != -1) {
                $(this).show();
            } else {
                $(this).hide();
            }
        }
        master_field.on('change', function() {
            // select LIST case :
            var selection_value = $(this).find('select').val();
            if (typeof selection_value === "undefined") {
                //searched_hinge_field RADIO BUTTONS LIST case :
                selection_value = $(this).find('input:checked').val();
            }
            var searched_hinge_field = $('div#rub_service > form.quixote div.hinge_' + jq_field_classname.split("_")[1] + '_' + selection_value);
            if (searched_hinge_field.length) {
                searched_hinge_field.show();
            } else {
                var erase_fields = $('div#rub_service > form.quixote div:regex(class,hinge_' + jq_field_classname.split("_")[1] + '_.*)');
                erase_fields.hide();
                erase_fields.each(function() {
                    $(this).find('div.content :first-child').val('');
                });
            }
        });
    });
    /* end of hinge fields */

    var table_width = $('div:regex(grid-.*)').find('table');
    table_width.each(function() {
        $(this).attr('width', '100%');
    });

    /*National Number formatting*/
    var input_nn = $('div.nn > div.content > input');
    var input_nn_masked = $('<input type="text" name="number">')
        .hide();
    input_nn.append(input_nn_masked);

    input_nn.on("keyup change", function() {
        $("input[name='number']").val(destroyMask(this.value, 11));
        this.value = createMask($("input[name='number']").val(), /(\d{2})(\d{2})(\d{2})(\d{3})(\d{2})/, "$1.$2.$3-$4.$5");
    });
    /*END National Number formatting*/

    /* Set last option in select with a extra css class.
     * sample : extra css = lastoption_autre ==> option with value "autre"
     * Will be the last item in select*/
    var lastoption_div = $('div:regex(class,lastoption)');
    lastoption_div.each(function() {
        var arr_classnames = $(this).prop('class').split(' ');
        var get_lastoption = '';
        for (elem = 0; elem in arr_classnames; elem++) {
            if (arr_classnames[elem].startsWith('lastoption')) {
                get_lastoption = arr_classnames[elem].split('_')[1];
                break;
            }
        }
        var option_to_deplace = $("select > option[value=" + get_lastoption + "]", this);
        $("select > option:last", this).after(option_to_deplace);
    });

    /* LI LIST on 4 columns ! */
    var num_cols = 4,
        container = $('.splitlist'),
        listItem = 'li',
        listClass = 'sub-list';
    container.each(function() {
        var items_per_col = new Array(),
            items = $(this).find(listItem),
            max_items_per_col = Math.ceil(items.length / num_cols),
            difference = (max_items_per_col * num_cols) - items.length;
        for (var i = 0; i < num_cols; i++) {
            if (i == num_cols - 1) {
                items_per_col[i] = max_items_per_col - difference;
            } else {
                items_per_col[i] = max_items_per_col;
            }
        }
        for (var i = 0; i < num_cols; i++) {
            $(this).append($('<ul ></ul>').addClass(listClass));
            for (var j = 0; j < items_per_col[i]; j++) {
                var pointer = 0;
                for (var k = 0; k < i; k++) {
                    pointer += items_per_col[k];
                }
                $(this).find('.' + listClass).last().append(items[j + pointer]);
            }
        }
    });
    /* END  LI LIST on 4 columns ! */
});


function get_css_class_name_by_prefix(elem, begin_with) {
    var element = null;
    var array_elem = elem.attr('class').split(" ");
    array_elem.forEach(function(e) {
        if (e.indexOf(begin_with) == 0) {
            element = e;
        }
    });
    return element;
}

function createMask(string, re, mask) {
    return string.replace(re, mask);
}

function destroyMask(string, max_len) {
    return string.replace(/\D/g, '').substring(0, max_len);
}
