﻿rules = {};

rules.listCommands = [];

rules.listCommand = function(root, actionsPrefix) {
    if ($.inArray(root, rules.listCommands) >= 0) {
        return;
    }

    rules.listCommands.push(root);

    if (actionsPrefix == null) {
        actionsPrefix = '';
    }

    var setUpFilter = function(filterGroup, filterId, orderId, orderAscending) {
        var parameters = [];

        if (filterGroup != null && filterId != null) {
            parameters.push({ name: 'filter-' + filterGroup, value: filterId });
        }
        if (orderId != null) {
            parameters.push({ name: 'order-id', value: orderId });
        }
        if (orderAscending != null) {
            parameters.push({ name: 'order-ascending', value: orderAscending });
        }

        parameters.push({ name: 'search-text', value: $(root + ' .command-search-text').length > 0 ? $(root + ' .command-search-text').val() : "" });
        page.pull(actionsPrefix + 'set-up-filter', parameters);
    };

    $(root + ' .command-filter select').live("change", function(e) {
        setUpFilter($(this).parents('.command-filter').attr('group'), $(this).attr('value'), null, null);
    });

    $(root + ' .command-search-text').live("keypress", function(e) {
        if (e.keyCode == 13) {
            setUpFilter();
            return false;   // no submit
        }
    });
    $(root + ' .command-apply-search').live("click", function(e) {
        setUpFilter();
    });
    $(root + ' .command-clear-search').live("click", function(e) {
        $(root + ' .command-search-text').val('');
        setUpFilter();
    });

    $(root + ' .command-order').live("change", function(e) {
        setUpFilter(null, null, $(this).val(), null);
    });

    $(root + ' .command-order-ascending').live("click", function(e) {
        setUpFilter(null, null, null, false);
    });
    $(root + ' .command-order-descending').live("click", function(e) {
        setUpFilter(null, null, null, true);
    });

    $(root + ' .pager .command-first-page').live("click", function(e) {
        if (!$(this).hasClass('disabled')) {
            page.pull(actionsPrefix + 'first-page');
        }
    });
    $(root + ' .pager .command-previous-page').live("click", function(e) {
        if (!$(this).hasClass('disabled')) {
            page.pull(actionsPrefix + 'previous-page');
        }
    });
    $(root + ' .pager .command-page').live("change", function(e) {
        page.pull(actionsPrefix + 'goto-page', [{ name: 'page', value: $(this).val()}]);
    });
    $(root + ' .pager .command-next-page').live("click", function(e) {
        if (!$(this).hasClass('disabled')) {
            page.pull(actionsPrefix + 'next-page');
        }
    });
    $(root + ' .pager .command-last-page').live("click", function(e) {
        if (!$(this).hasClass('disabled')) {
            page.pull(actionsPrefix + 'last-page');
        }
    });
};

rules.selectors = [];

rules.selector = function(root, prefix, confirmSelectionMessage, confirmSelectionColumn) {
    if ($.inArray(root, rules.selectors) >= 0) {
        return;
    }

    rules.selectors.push(root);

    if (prefix == null) {
        prefix = '';
    }

    page.addRule(function() {
        $(root + ' .vignette-link').live("click", function(e) {
            if (confirmSelectionMessage == null || confirmSelectionMessage == "" || confirm(confirmSelectionMessage.replace('{0}', $.trim($("td:eq(" + confirmSelectionColumn + ")", this).text())))) {
                var href = $('a', this).attr('href');

                if (href) {
                    document.location = $('a', this).attr('href');
                    return;
                }

                var id = $(this).attr('id');

                if (id) {
                    page.pull(prefix + 'select', [{ name: 'item-id', value: id}], function(ok) {
                        // Close dialog (in case of...)
                        $(root).parents(".dialog").dialog("close");
                    });
                }
            }
        });
    });
};

rules.vignette = function() {
    $('.vignette').live("click", function(e) {
        var href = $(':header a', this).attr('href');

        if (href != null) {
            document.location = href;
        }
    });
};

rules.gallery = function() {
    $('.gallery-item').live("click", function(e) {
        var href = $('a', this).attr('href');

        if (href != null) {
            document.location = href;
        }
    });
};

rules.tagChooser = function(root, prefix, newCategoryEditor, newTagEditor) {
    page.addRule(function() {
        $(root + ' .tag-selection .command-remove-all-tags').live("click", function(e) {
            page.pull(prefix + "-remove-all-tags");
        });

        $(root + ' .new-tag-category').live("click", function(e) {
            if (newCategoryEditor != null) {
                $(newCategoryEditor).dialog("open");
            }
        });
        $(root + ' .tag-chooser-categories span').live("click", function(e) {
            if (!$(this).hasClass("new-tag-category")) {
                var category = $(this).attr('category');

                if (category != null) {
                    // set server-side category
                    page.pull(prefix + "-open-tag-category", [{ name: 'category', value: $(this).attr('category')}]);
                }
            }
        });

        $(root + ' .new-tag').live("click", function(e) {
            if (newTagEditor != null) {
                $(newTagEditor).dialog("open");
            }
        });
        $(root + ' .tag-list span.tag').live("click", function(e) {
            if (!$(this).hasClass("new-tag")) {
                if ($(this).hasClass('selected')) {
                    page.pull(prefix + "-remove-tag", [{ name: 'tag', value: $(this).attr('tag')}]);
                }
                else {
                    page.pull(prefix + "-add-tag", [{ name: 'tag', value: $(this).attr('tag')}]);
                }
            }
        });
    });
};

rules.trendChooser = function(root) {
    page.addRule(function() {
        $(root + ' .new-tag').live("click", function(e) {
            $(root + ' .id-tag-chooser-vignettes').hide();
            $(root + ' .id-new-trend-editor').show();
        });
    });
};

rules.gridHeight = function() {
    page.addDynamicRule(function() {
        $('table.grid:visible > tbody > tr').each(function(rowIndex, rowElement) {
            var max = 0;

            $('> td', $(rowElement)).not('.grid-spacing').each(function(cellIndex, cellElement) {
                var height = $('> :first-child', cellElement).height();

                if (height > max) {
                    max = height;
                }
            });

            $('> td', $(rowElement)).not('.grid-spacing').each(function(cellIndex, cellElement) {
                $('> :first-child', cellElement).height(max);
            });
        });
    });
};

rules.global = function() {
    rules.vignette();
    //rules.gridHeight();
    rules.gallery();
};

//var CKEDITOR_BASEPATH = '/js/ckeditor/3.6/';
CKEDITOR.config.entities_processNumerical = 'force';

rules.ckeditor = function(editor, height) {
    page.addRule(function() {
        page.extraParametersBuilders.push(function(parameters) {
            try {
                if (CKEDITOR.instances[editor]) {
                    CKEDITOR.instances[editor].updateElement();
                }
            }
            catch (err) { }
        });
    });

    page.addDynamicRule(function() {
        // Beware of multi-declaration and errors: http://stackoverflow.com/questions/1794219/ckeditor-instance-already-exists
        if (CKEDITOR.instances[editor]) {
            CKEDITOR.instances[editor].destroy(true);
        }
        CKEDITOR.replace(
				editor,
				{
				    toolbar: CKEDITOR.config.toolbar_Basic,
				    height: height
				}
			);
    });
};
