﻿(function () {
    $(document).ready(function () {
        var clicktodebug = $(".clicktodebug");
        if ($.data(clicktodebug, "debugmode_attached")) return;

        for (var i = 0; i < clicktodebug.length; ++i) {
            var bind = function (el) {
                var href = function (el, value) {
                    var is_a = el.nodeName == "a" || el.nodeName == "A";
                    if (!value) { return is_a ? el.href : null; }
                    else { if (is_a) el.href = value; }
                };

                var orig_href = href(el);
                href(el, "javascript:void(0)");

                $(el).click(function () {
                    var callbacks = window.toggledebugmode || [];
                    if (callbacks.length == 0) {
                        var startsWith = function (s, prefix) { return s.length >= prefix.length && s.substr(0, prefix.length) === prefix; };
                        var endsWith = function (s, postfix) { return s.length >= postfix.length && s.substr(s.length - postfix.length, postfix.length) === postfix; };
                        if (orig_href) {
                            if (startsWith(orig_href, "javascript:")) {
                                var code = orig_href.substr("javascript:".length, orig_href.length - "javascript:".length);
                                eval(code);
                            } else {
                                window.location = orig_href;
                            }
                        }
                    }
                    else {
                        $.each(callbacks, function (i, callback) { callback(); });
                    }
                });
            };

            var el = clicktodebug[i];
            var parent = el.parentElement || el.parentNode;
            var parent_name = parent ? parent.nodeName : null;
            if (parent_name == "a" || parent_name == "A") el = parent;
            bind(el);
        }

        $.data(clicktodebug, "debugmode_attached", true);
    });
})();
