/**
 * Application namespace
 */
window.ecent = {};


window.ecent.search = new (function($) {
    /**
     * @var ecent.Search
     */
    var _self = this;


    /**
     * Returns the selected tags
     *
     * @return  Array
     */
    var _getSelectedTags = function() {
        var selectedTags    = $("#searchform fieldset.main_tag_field li input:checkbox[checked=true]");
        var result          = [];

        selectedTags.each(function(){
            result.push($(this).val());
        });

        return result;
    };


    /**
     * Returns the selected query
     *
     * @return String
     */
    var _getQueryString = function() {
        return $("#searchform #searchbox").val();
    };


    /**
     * Updates the count (visible button)
     *
     * @param   {int}  value
     * @return  void
     */
    var _updateCount = function(value) {
        var btn     = null;
        var title   = null;
        var label   = null;

        if ($.browser.msie && $.browser.version < 8) {
            btn = $(".btn-show-result .total");

            if (btn.length > 0) {
                title = $(btn).html();

                if (title.indexOf("&nbsp;") > 0) {
                    label = title.substring(title.indexOf("&nbsp;") + 6);
                }
                else {
                    label = title.substring(title.indexOf(" ") + 1);
                }
                
                $(btn).text(value + " " + label);
            }
        }
        else {
            btn = $(".btn-show-result .total");

            if (btn.length > 0) {
                title = $(btn).html();
                label = title.substring(title.indexOf("&nbsp;"));

                $(btn).html(value + label);
            }
        }
    };


    /**
     * Refreshes the search count and updates when the ajax request is done successfully
     *
     * @return void
     */
    this.refreshCount = function() {
        var query   = _getQueryString();
        var tags    = _getSelectedTags();

        $.ajax({
            url         : "zoeken/search-count.do",
            method      : "get",
            dataType    : "json",
            cache       : false,
            data        : {
                queryString: query,
                selectedTags: tags
            },
            success     : function(data){
                _updateCount(data.total);
            }
        });
    };
})(jQuery);

/**
 * Initialization of the ecent.Search class
 */
//ecent.search = new ecent.Search();


(function($){
    $(document).ready(function() {
        // Enable Uniform
        $("select.interface, .order select, #searchbar input:checkbox:visible").uniform();

        $("body#search .order select").change(function(){
            // Get all the parent forms
            var forms = $(this).parents("form");

            // When there is at least 1 form, submit the first child
            if (forms.length > 0) {
                $(forms[0]).submit();
            }
        });

        $('#searchform  .main_tag_field').each(function(){
            var checkboxes          = $('li', this);
            var checkedCheckboxes   = $('input:checked', checkboxes);
            
            if (checkboxes.length == checkedCheckboxes.length) {
                $('.select-all input', this).attr('checked', true);
                $('.select-all .checker span, .select-all label', this).addClass('checked');
            }
        });

        // On select all click, refresh the result count + check all the attached checkboxes
        $("#searchform .main_tag_field .header input[type='checkbox']").click(function(e){
            var isChecked = $(this).is(":checked");
            var fieldsets = $(this).parents("fieldset");

            if (fieldsets.length > 0) {
                var fieldset        = fieldsets[0];
                var checkBoxes      = $("li input[type='checkbox']", fieldset);
                var uniformBoxes    = $("li span, li label", fieldset);

                checkBoxes.attr("checked", isChecked);

                if (isChecked) {
                    uniformBoxes.addClass('checked');
                }
                else {
                    uniformBoxes.removeClass('checked');
                }

                window.ecent.search.refreshCount();
            }
        });

        // On single item click, refresh the result count
        $("#searchform .main_tag_field li input[type='checkbox']").click(function(e){
            window.ecent.search.refreshCount();
        });

        // Collapse the answers by default
        $(".answer-box").addClass("collapsed");

        $(".answer-box h3").click(function() {
            var parent = $(this).parent();
            if (parent.hasClass('collapsed')) {
                parent.removeClass("collapsed");
                parent.addClass("expanded");
            }
            else if (parent.hasClass('expanded')) {
                parent.addClass("collapsed");
                parent.removeClass("expanded");
            }
        });

        $(".answer-box h3 span").each(function(){
            // Obtain the proper height
            var height      = $(this).height();
            var attempts    = 0;
            var text        = $(this).text();
            var textLength  = text.length;

            // Obtain real height
            $(this).css('height', 'auto');

            while ($(this).height() > height && ++attempts < 50) {
                $(this).text(text.substr(0, textLength - attempts) + '...');
            }

            // Remove the auto set
            $(this).css('height', '');
        });

        // Quiz
        $("dl.quiz").each(function(i){
            var answers = $(".question li", this);
            var answerExplantionOrderList = $(".answer", this);
            var answerExplanations = $("li", answerExplantionOrderList);
            
            $("a", answers).click(function(e){
                var index = $(answers).index($(this).parent());

                $(answerExplanations).each(function(j){
                    $(answerExplantionOrderList).attr({"start" : index + 1});

                    $(this).css({"display" : (j === index) ? "list-item" : ""});
                });
            });
        });
    });
})(jQuery);
