﻿function listOfExIds() {
    var s = "";
    $(initialExerciseIds).each(function(index, value) {
        if (value != null)
            s += value + ",";
    });

    if (s.length > 0)
        s = s.substring(0, s.length - 1);

    return s;
}

$(document).ready(function() {
    var selectedCategoryIds = new Array();
    var ajax;

    // SPECIFIC TO FILTER SCREEN
    if ($.browser.msie) {
        $('input[id^=category-]').click(checkboxChanged);
    } else {
        $('input[id^=category-]').change(checkboxChanged);
    }

    function initSearchModeButtons() {
        $('.select-bar .select-reset').click(function() {
            $('input', $(this).parent().parent().parent()).each(function() {
                var r = $(this).attr("id").match(/category-(\d+)/);
                removeCategory(r[1]);

                r = $(this).parent().parent().parent().parent().attr("class").match(/select\sgroup-(\d+)/);
                $('#summary-group-holder-' + r[1]).css("display", "none");
                $('#summary-group-' + r[1]).empty();
                $(this).attr("checked", false);

            });
            filterChanged();
            return false;
        });
    }

    function checkboxChanged() {
        updateSelectedCategories($(this));
    }

    function toggleCheckboxLabel(checkbox) {
        checkbox.next().css("color", "#ccc");
    }

    function updateSelectedCategories(checkbox) {
        var r = checkbox.attr("id").match(/category-(\d+)/);

        var changed = false;
        if (checkbox.attr("checked") && !categorySelected(r[1])) {
            selectedCategoryIds.push(parseInt(r[1]));
            changed = true;
        }

        if (!checkbox.attr("checked") && categorySelected(r[1])) {
            removeCategory(r[1]);
            changed = true;
        }

        if (changed) {
            toggleSummaryItem(checkbox, r[1]);
            filterChanged();
        }
    }

    function initTooltips() {
        // Help tooltips
        $('div.select-bar .select-help').each(function() {
            $(this).qtip({
                content: $('.help-text', $(this).parent()).text(),
                position: {
                    corner: {
                        target: 'topRight',
                        tooltip: 'bottomLeft'
                    }
                },
                style: {
                    textAlign: 'left',
                    border: {
                        width: 3,
                        radius: 7
                    },
                    tip: 'bottomLeft',
                    name: 'cream' // Inherit the rest of the attributes from the preset dark style
                }

            });
        });

        // Category tooltips
        $('div.select-container div.select-content div[class*=-checkbox]').each(function() {
            var text = $('.help-text', $(this)).text();
            if (text == "") return;

            $(this).qtip({
                content: text,
                position: {
                    corner: {
                        target: 'topLeft',
                        tooltip: 'bottomLeft'
                    },
                    adjust: { x: 18 }
                },
                style: {
                    textAlign: 'left',
                    border: {
                        width: 3,
                        radius: 7
                    },
                    tip: 'bottomLeft',
                    name: 'cream' // Inherit the rest of the attributes from the preset dark style
                }


            });
        });
    }


    function toggleSummaryItem(checkbox, catId) {
        var checked = checkbox.attr('checked');
        var groupClassName = checkbox.parent().parent().parent().parent().attr('class');
        var match = groupClassName.match(/select\sgroup-(\d+)/);
        var groupId = match[1];

        var groupContainer = $('#summary-group-' + groupId);

        // Remove existing items
        var existing = $('div[class^=item]', groupContainer).filter(function() {
            return $(this).data('id') == catId;
        });

        var item = createFilterButton((checked ? 'blue' : 'gray'), catId, checkbox).show();

        if (existing.length == 0)
            item.appendTo(groupContainer);
        else
            existing.remove();

        if (groupContainer.children().length > 0) {
            groupContainer.parent().show();
        } else {
            groupContainer.parent().hide();
        }

    }

    function createFilterButton(type, catId, checkbox) {
        var item = $('#cloneable-item-' + type).clone();
        item.data('id', catId);
        item.click(toggleCloneableItemClicked);
        $('div[class$=text]', item).text(checkbox.next().text());

        return item;
    }

    function filterChanged() {
        if (ajax != null)
            ajax.abort();

        ajax = $.getJSON("/resources/filter.aspx", { 't': new Date().getTime(), 'catids': listOfCatIds() }, function(data) {
            ajax = null;
            updateResultsCount(data.count + "");

            if (data.possible == null) {
                // Enable everything
                $('input[id^=category-]').attr('disabled', '').parent().removeClass("disabled");
            } else {
                // Disable everything that isn't checked
                $('input[id^=category-]').each(function() {
                    if (!$(this).attr("checked")) {
                        $(this).attr('disabled', 'disabled');
                        $(this).parent().addClass("disabled");
                    }
                });

                // Enable ones that are possible
                $(data.possible).each(function(index, item) {
                    var el = $("input#category-" + item);
                    el.parent().removeClass("disabled");
                    el.attr('disabled', '');
                });
            }
        });
    }

    function toggleCloneableItemClicked(event) {
        var catId = $(this).data('id');
        var box = $('input#category-' + catId);

        // Workaround to get this working in IE - we do things slightly differently
        if ($.browser.msie) {
            if (!box.attr('disabled')) {
                box.attr('checked', box.attr('checked') ? '' : true);
                updateSelectedCategories(box);
            }
        } else {
            box.click();
            box.trigger('change');
        }
    }


    function listOfCatIds() {
        var s = "";
        $(selectedCategoryIds).each(function(index, value) {
            if (value != null)
                s += value + ",";
        });

        if (s.length > 0)
            s = s.substring(0, s.length - 1);

        return s;
    }



    function categorySelected(id) {
        return $.inArray(parseInt(id), selectedCategoryIds) >= 0;
    }

    function removeCategory(id) {
        if (categorySelected(id))
            delete selectedCategoryIds[$.inArray(parseInt(id), selectedCategoryIds)];
    }

    function updateResultsCount(count) {
        var currDigit;
        var html = "";
        numResults = count;

        for (var i = 0; i < count.length; i++) {
            currDigit = count.substring(i, i + 1);
            html += '<img class="no' + (currDigit == "1" ? "1" : "") + '" src="images/search/' + currDigit + '.jpg" alt="' + currDigit + '" />';
        }

        $('#results-numbers-textonly').text(count);
        $('#results-numbers').fadeOut(100, function() {
            $(this).html(html);
            $(this).fadeIn(100);
        });
    }

    function selectedCategoryString() {
        var s = ""
        $(selectedCategoryIds).each(function(item, value) {
            if (value != null)
                s += value + ".";
        });
        return s;
    }

    function viewResults() {
        if (selectedCategoryString().length == 0) {
            alert('Please provide a search filter');
            //        }
            //        else if (numResults > 40) {
            //            alert('Please filter your results down further');
        } else {
            window.location.assign('search-results.aspx?categories=' + selectedCategoryString())
        }
    }


    // SPECIFIC TO FILTERS SCREEN
    function updateExerciseList() {
        if (ajax != null)
            ajax.abort();

        var container = $('#exercise-holder div.content');
        container.text('Loading...');

        container.load("/resources/exercises.aspx", { 'exids': listOfExIds() }, function(response) {
            attachExerciseEvents($(this));
        });
    }

    function exerciseSelected(id) {
        return $.inArray(parseInt(id), initialExerciseIds) >= 0;
    }

    function removeExercise(id) {
        if (exerciseSelected(id)) {
            delete initialExerciseIds[$.inArray(parseInt(id), initialExerciseIds)];
        }
    }

    function attachExerciseEvents(exercises) {
        // Show/hiding exercises
        exercises.click(function(event) {
            var button = $(event.target);
            if (button.attr("class") == "hide" || button.attr("class") == "show") {
                button = $('a', button);
            }
            var exerciseContainer = button.parent().parent().parent();

            if (button.parent().attr("class") == "show") {
                $('.exercise-detail', exerciseContainer).slideDown(200, function() {
                    button.text("HIDE EXERCISE DETAILS");
                    $(button.parent()).attr('class', 'hide');
                });
            } else if (button.parent().attr("class") == "hide") {
                $('.exercise-detail', exerciseContainer).slideUp(200, function() {
                    button.text("SHOW EXERCISE DETAILS");
                    $(button.parent()).attr('class', 'show');
                });
            }

            return false;
        });

        // Removing exercises
        exercises.click(function(event) {
            var button = $(event.target);
            if (button.attr("class") == "remove") {
                button = $('a', button);
            }
            if (button.parent().attr("class") == "remove") {
                var exercise = button.parent().parent().parent();
                exercise.fadeOut(400, function() {
                    var r = exercise.attr("id").match(/exercise-(\d+)/);
                    removeExercise(r[1]);
                    exercise.remove();
                    updateResultsCount((numResults - 1) + "");
                });
            }
        });

        // Hints
        $('.exercise-info-icons a.hint-icon-link').mouseover(function() {
            var link = $(this);

            var hint = $('.exercise-info-hint', link.parent().parent().parent().parent());
            hint.text($('span', link).text());
            hint.show();
        });

        $('.exercise-info-icons a.hint-icon-link').mouseout(function() {
            var link = $(this);
            var hint = $('.exercise-info-hint', link.parent().parent().parent().parent());
            hint.hide();
        });

    }



    function toggleResultFilterButton(button) {
        var activate = button.attr('class') != 'item-blue';
        if (!activate) {
            button.remove();
        }
        //        button.attr('class', !activate ? 'item-grey' : 'item-blue');
        //        $('img[name=remove-btn]', button).attr('src', !activate ? 'images/search/btn-item-reveal.png' : 'images/search/btn-item-remove.png');

    }

    function toggleFilter(button) {
        var activate = button.attr('class') == 'item-blue';
        var r = button.attr('id').match(/filter-category-(\d+)/);
        var catId = r[1];

        if (!activate) {
            $('#exercise-holder .exercise').each(function() {

                if ($(this).attr("rel").match(catId + ",") == null) {
                    $(this).remove();
                }
            });
        }
    }

    function attachFilterButtonEvents() {
        $('[id^=filter-category-]').click(function() {
            var button = $(this);
            toggleResultFilterButton(button);
            toggleFilter(button);
        });
    }

    // Refine current search button
    function refineSearch() {
        var catIds = listOfCatIds();
        if (catIds.length > 0)
            window.location.assign("/search-catalogue.aspx?catids=" + catIds);
        //        else if (selectedExerciseId!='')
        //            location.href = "/search-catalogue.aspx?exid=" + selectedExerciseId;
        else
            window.location.assign("/search-catalogue.aspx");
    }


    function init() {
        if (currentPage == "query") {
            // Restore checkbox state from URL parameter "catids"
            if (initialCategoryIds.length > 0) {
                var checkbox;
                $(initialCategoryIds).each(function(index, item) {
                    if (!categorySelected(item)) {
                        checkbox = $('input#category-' + item);
                        checkbox.click();

                        if (checkbox.parent().parent().parent().css("display") == "none") {
                            var button = $('div.select-arrow img', checkbox.parent().parent().parent().parent());
                            button.trigger("click");
                        }
                    }
                });
            }

            // Restore checkbox state from browser state (the state is restored from some browsers)
            $('input[id^=category-]').each(function() {
                if ($(this).attr('checked')) {
                    var r = $(this).attr("id").match(/category-(\d+)/);
                    if (!categorySelected(r[1]))
                        selectedCategoryIds.push(parseInt(r[1]));
                    toggleSummaryItem($(this), r[1]);
                }
            });


            // Button events
            $('#view-btn').click(viewResults);
            $('#textonly-view-btn').click(viewResults);

            initTooltips();
            initSearchModeButtons();
            filterChanged();
        } else if (currentPage == "results") {
            attachFilterButtonEvents();

            if (typeof attachEventsOnPageLoad != "undefined") {
                attachExerciseEvents($('#exercise-holder'));
            }

            if (initialExerciseIds.length > 0) {
                updateExerciseList();
            }

            $('#refine-btn').click(refineSearch);
            $('#textonly-refine-btn').click(refineSearch);

            $('#perform-btn').click(function() {
                window.location.assign("/search-catalogue.aspx");
            });

            $('#textonly-perform-btn').click(function() {
                window.location.assign("/search-catalogue.aspx");
            });

            if (initialCategoryIds.length > 0) {
                selectedCategoryIds = initialCategoryIds;
            }
        }
        
        var offset = ($('#region-banner:visible').length > 0) ? 100 : 0;
        $('#scroll-follow').scrollFollow({ 'offset': offset, 'offsetBottom': 242, 'speed': 100, 'container': $('body') });
    }

    // INITIALISE

    init();
});
