$(function() {
    $.getScript('/static/imio/common.js', function() {});
    $.getScript('/static/imio/dtp.js', function() {});
    // Hide meal list in resume (keep table).
    $("div.form-validation div.calendrier div.content").hide();

    var TEST = false;
    // Print buttons to go to previous or next month.
    var NAVIGATION = false;
    // To print previous month : -1, next month : 1, current month : 0
    var START_MONTH = 1;
    // background-color when we select an item.
    var BGCOLOR = "#def6db";
    // 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!
    function escapeRegExp(text) {
        return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
    }
    // navigation.
    if (NAVIGATION == true) {
        $("div.calendrier").append('<div class="nav_cal"><p><input type="button" id="cal_previous" value="previous" date="" />&nbsp;<input type="button" id="cal_today" value="today" date="" />&nbsp;<input type="button" id="cal_next" value="next" date="" /></p>');
    }
    var d = new Date();
    // Les items de la multiselect (chaque li contient chaque fois un input).
    var $multiselect_items = $("div.calendrier ul li");

    $.getScript("/static/imio/calendar.js")
        .done(function(script, textStatus) {
            var current_month = d.getMonth() + 1 + START_MONTH;
            var dan = d.getFullYear();
            var $calendar = calendrier(current_month, dan);
            $('div.calendrier').append($calendar);
            $("#cal_previous").attr("date", "01/" + current_month + "/" + dan);
            $("#cal_next").attr("date", "01/" + current_month + "/" + dan);
            if (TEST == false) {
                $('div.calendrier .content').css("display", "none");
            }
            $multiselect_items.each(function(index, value) {
                each_items(index, value, $multiselect_items)
            });
            $("#cal_previous").bind('click', {
                obj: $multiselect_items,
                month: current_month - 1
            }, nav_previous);
            $("#cal_next").bind('click', {
                obj: $multiselect_items,
                month: current_month + 1
            }, nav_next);
            $("#cal_today").bind('click', {
                obj: $multiselect_items,
                month: current_month
            }, nav_today);
            if($(".calendrier input:checkbox:checked").length == 0) {
                $("input:regex(name,.*nothing)").prop("checked", true);
            }
        })
        .fail(function(jqxhr, settings, exception) {
            $("div.log").text("Triggered ajaxError handler.");
        });

    /*
     * Est declanche quand on click sur une checkbox
     */
    var click_input = function(event) {
        //TEST if (event.data.obj == $multiselect_items) {alert("test");}
        var str_date = $(this).attr('name').split('_')[1];
        var $inputs = $("table.calendrier").children().find(':regex(name,.*' + str_date + '.*)');
        // Get all inputs for a date. Uncheck them. Remove background-color selection.
        $inputs.each(function(i, v) {
            var input = v;
            $(v).prop("checked", false);
            $("div.calendrier input[name='"+$(v).attr("name")+"']").prop("checked", false);
            $(v).closest("li").css("background-color", "transparent");
        });
        // Check clicked checkbox.
        $(this).prop("checked", true);
        // Add background-color on current selection.
        $(this).closest("li").css("background-color", BGCOLOR);
        var input_name = $(this).attr("name");
        // On check egalement la checkbox dans la select box cachee.
        $multiselect_items.find("input[name^='" + input_name + "']").prop("checked", true);
    }

    var click_mult_input = function(event) {
        var $checked_item = $(this);
        if ($checked_item.prop("checked") == true) {
            $checked_item.closest("li").css("background-color", BGCOLOR);
        }
        else {
            $checked_item.closest("li").css("background-color", "transparent");
        }
        $("div.calendrier input[name='"+$checked_item.attr("name")+"']").prop("checked", $checked_item.prop("checked"));
    }

    var nav_previous = function(event) {
        $mi = event.data.obj;
        // TEST : if ($mi == $multiselect_items) {alert("yolo");}
        //1. remove current calendar structure
        $("table.calendrier").remove();
        //2. build new calendar structure
        arrdate = $("#cal_previous").attr("date").split("/");
        var d = new Date(arrdate[2], arrdate[1], arrdate[0]);
        var previousDate = new Date(d.setMonth(d.getMonth() - 1))
        $("#cal_previous").attr("date", "01/" + previousDate.getMonth() + "/" + previousDate.getFullYear());
        $("#cal_next").attr("date", "01/" + previousDate.getMonth() + "/" + previousDate.getFullYear());
        var current_month = previousDate.getMonth();
        var $calendar = calendrier(current_month, previousDate.getFullYear());
        //3. print new calendar structure
        $('div.calendrier').append($calendar);
        //4. Place each list items in good day in calendar
        $mi.each(function(index, value) {
            each_items(index, value, $mi)
        });
    }

    var nav_today = function(event) {
        $mi = event.data.obj;
        // TEST : if ($mi == $multiselect_items) {alert("yolo");}
        //1. remove current calendar structure
        $("table.calendrier").remove();
        //2. build new calendar structure
        var current_month = d.getMonth() + 1;
        var dan = d.getFullYear();
        var $calendar = calendrier(current_month, dan);
        //3. print new calendar structure
        $('div.calendrier').append($calendar);
        //4. Place each list items in good day in calendar
        $mi.each(function(index, value) {
            each_items(index, value, $mi)
        });
    }

    var nav_next = function(event) {
        $mi = event.data.obj;
        //1. remove current calendar structure
        $("table.calendrier").remove();
        //2. build new calendar structure
        arrdate = $("#cal_next").attr("date").split("/");
        var d = new Date(arrdate[2], arrdate[1], arrdate[0]);
        var nextDate = new Date(d.setMonth(d.getMonth() + 1));
        $("#cal_previous").attr("date", "01/" + nextDate.getMonth() + "/" + nextDate.getFullYear());
        $("#cal_next").attr("date", "01/" + nextDate.getMonth() + "/" + nextDate.getFullYear());
        var current_month = nextDate.getMonth();
        var $calendar = calendrier(nextDate.getMonth(), nextDate.getFullYear());
        //3. print new calendar structure
        $('div.calendrier').append($calendar);
        //4. Place each list items in good day in calendar
        $mi.each(function(index, value) {
            each_items(index, value, $mi)
        });
    }

    // item  = $("div.calendrier ul li");
    var each_items = function(i, item, data) {
        var $that = $(item);
        var $input = $that.find("input");
        $that.css("display", "block");
        var allow_mult = $input.attr('name').indexOf('mult');
        // If we don't find mult in id so we can select only ONE item per date.
        if ($input.prop("checked") == true) {
            // Set background-color if they are already checked items
            $that.css("background-color", BGCOLOR);
            var input_name = $input.attr("name");
            $that.find("input[name^='" + input_name + "']").prop("checked", true);
        }
        if (allow_mult == -1) {
            $input.bind('click', {
                obj: $(item)
            }, click_input);
        }
        else {
            $input.bind('click', {
                obj: $(item)
            }, click_mult_input);
        }
        var item_date = $input.attr("name").split('_')[1];
        if ($input.attr("name").indexOf("exception") != -1) {
            $input.remove();
            $that.css({
                'color': 'red',
                'margin-top': '2em',
                'text-align': 'center'
            });
        }
        // Here, we add multi_select_input to our custom html calendar table
        if (TEST == true) {
            console.log("add");
        }
        $("table.calendrier td[td_date='" + item_date + "']").append($that.clone(true, true));
    }
}); /* end */
