$(function() {

    var hide_bo_stat = $('div.bo-block li.stats');
    hide_bo_stat.parent().parent().remove();

    // 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 !


    // 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 ...

    $.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 = $('form.quixote div:regex(class,jqTable[0-9]_.*)');
    var jq_tables = $('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 = $('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++;
            }
        });
    });
});

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;
}
