var sj = {
    after_load_callbacks: [],
    execute_after_load_callbacks: function(data, status, selector) {
        if (data && !status && !selector) {
            selector = data;
        }
        for (var i = 0; i < sj.after_load_callbacks.length; i++) {
            if (selector == sj.after_load_callbacks[i].selector) {
                sj.after_load_callbacks[i].callback($(selector));
            }
        }
    },
    add_after_load_callback: function(selector, callback) {
        sj.after_load_callbacks.push({selector: selector, callback: callback});
    },
    before_load_callbacks: [],
    execute_before_load_callbacks: function(data, status, selector) {
        if (data && !status && !selector) {
            selector = data;
        }
        for (var i = 0; i < sj.before_load_callbacks.length; i++) {
            if (selector == sj.before_load_callbacks[i].selector) {
                sj.before_load_callbacks[i].callback($(selector));
            }
        }
    },
    add_before_load_callback: function(selector, callback) {
        sj.before_load_callbacks.push({selector: selector, callback: callback});
    },
    util: {
        htmlspecialchars_decode: function(string, quote_style) {
            string = string.toString();

            string = string.replace(/&amp;/g, '&');
            string = string.replace(/&lt;/g, '<');
            string = string.replace(/&gt;/g, '>');

            if (quote_style == 'ENT_QUOTES') {
                string = string.replace(/&quot;/g, '"');
                string = string.replace(/&#039;/g, '\'');
            } else if (quote_style != 'ENT_NOQUOTES') {
                string = string.replace(/&quot;/g, '"');
            }

            return string;
        },
        get_window_size_with_scroll: function() {
            var w = 0, h = 0;
            if (window.innerHeight && (window.scrollX || window.scrollY)) {
                w = window.innerWidth + window.scrollX;
                h = window.innerHeight + window.scrollY;
            } else {
                w = document.documentElement.clientWidth + document.documentElement.scrollLeft;
                h = document.documentElement.clientHeight + document.documentElement.scrollTop;
            }
            return new Array(w, h);
        },
        get_window_size: function() {
            var w = 0, h = 0;
            if (typeof(window.innerWidth) == 'number') {
                w = window.innerWidth;
                h = window.innerHeight;
            } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
                w = document.documentElement.clientWidth;
                h = document.documentElement.clientHeight;
            } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
                w = document.body.clientWidth;
                h = document.body.clientHeight;
            }
            return new Array(w, h);
        }
    }
};

(function($) {
    $.fn.extend({
        mousedrag: function(o) {
            this.each(function() {
                var t = $(this);
                if (typeof(o) == "object" && o.cb) {
                    t.mousedown(function (e) {
                        var d = new Date();
                        var p = {st: d.getTime(), spx: e.pageX, spy: e.pageY, scx: e.clientX, scy: e.clientY, ssx: e.screenX, ssy: e.screenY};
                        t.data("sjMousedragEventData", p);
                        t.data("sjMousedragActive", true);
                        if (o.ondragable) {
                            o.ondragable(t);
                        }
                        e.stopPropagation();
                    }).mouseout(function (e) {
                        if (o.ignore_mouseout == undefined || o.ignore_mouseout == null || o.ignore_mouseout == false) {
                            t.data("sjMousedragActive", false);
                            if (o.onundragable) {
                                o.onundragable(t);
                            }
                            e.stopPropagation();
                        } else {
                            if (t.data("sjMousedragActive") == true) {
                                var mfcb = function(e) {
                                    t.trigger(e);
                                };
                                t.data("sjMousedragFirefrombody", mfcb);
                                $("body").mousemove(mfcb);
                                var mucb = function() {
                                    if (t.data("sjMousedragActive") === true) {
                                        t.data("sjMousedragActive", false);
                                        t.removeData("sjMousedragEventData");
                                        $("body").unbind("mousemove", t.data("sjMousedragFirefrombody")).unbind("mouseup", t.data("sjMousedragBodyMouseup"));
                                        t.removeData("sjMousedragFirefrombody");
                                        if (o.onundragable) {
                                            o.onundragable(t);
                                        }
                                    }
                                };
                                t.data("sjMousedragBodyMouseup", mucb);
                                $("body").mouseup(mucb);
                                e.stopPropagation();
                            }
                        }
                    }).mouseover(function (e) {
                        var p = t.data("sjMousedragEventData");
                        var f = t.data("sjMousedragFirefrombody");
                        var b = t.data("sjMousedragBodyMouseup");
                        if (t.data("sjMousedragActive") == true && f && b) {
                            $("body").unbind("mousemove", f).unbind("mouseup", b);
                            t.removeData("sjMousedragFirefrombody");
                            t.removeData("sjMousedragBodyMouseup");
                        }
                        if (p && p.st) {
                            t.data("sjMousedragActive", true);
                            if (o.ondragable) {
                                o.ondragable(t);
                            }
                            e.stopPropagation();
                        }
                    }).mouseup(function (e) {
                        if (t.data("sjMousedragActive") === true) {
                            t.data("sjMousedragActive", false);
                            t.removeData("sjMousedragEventData");
                            if (o.onundragable) {
                                o.onundragable(t);
                            }
                        }
                    }).mousemove(function (e) {
                        if (t.data("sjMousedragActive") == true) {
                            var p = t.data("sjMousedragEventData");
                            var ee = $.Event("mousedrag");
                            ee.target = e.target;
                            ee.relatedTarget = e.relatedTarget;
                            ee.currentTarget = e.currentTarget;
                            ee.lastPageX = p.spx;
                            ee.lastPageY = p.spy;
                            ee.lastClientX = p.scx;
                            ee.lastClientY = p.scy;
                            ee.lastScreenX = p.ssx;
                            ee.lastScreenY = p.ssy;
                            ee.pageX = e.pageX;
                            ee.pageY = e.pageY;
                            ee.clientX = e.clientX;
                            ee.clientY = e.clientY;
                            ee.screenX = e.screenX;
                            ee.screenY = e.screenY;
                            p.spx = e.pageX;
                            p.spy = e.pageY;
                            p.scx = e.clientX;
                            p.scy = e.clientY;
                            p.ssx = e.screenX;
                            p.ssy = e.screenY;
                            t.data("sjMousedragEventData", p);
                            e.stopPropagation();
                            t.trigger(ee);
                        }
                        e.stopPropagation();
                    }).select(function() {return false;})
                    .bind("mousedrag", o.cb);
                } else if (typeof(o) == "string" && o == "unbind") {
                    t.removeData("sjMousedragActive");
                    t.removeData("sjMousedragEventData");
                    t.unbind("mousedown").unbind("mouseup").unbind("mouseout").unbind("mousemove").unbind("mousedrag");
                    var f = t.data("sjMousedragFirefrombody");
                    var b = t.data("sjMousedragBodyMouseup");
                    if (f && b) {
                        $("body").unbind("mousemove", f).unbind("mouseup", b);
                        t.removeData("sjMousedragBodyMouseup");
                        t.removeData("sjMousedragFirefrombody");
                    }
                }
            });
            return $(this);
        },
        font_changer: function(o) {
            if (o.selector) {
                this.each(function() {
                    $(this)
                    .find("a.small").click(function(e) {
                        $.set_setting("fontsize","small");
                        $(o.selector).css("font-size", "16px");
                        $(this)
                        .find("img")
                        .attr("src", WEBROOT + "img/common/selected_font_small.gif")
                        .parents("li:first")
                        .siblings("li")
                        .find("a").each(function() {
                            var v = $(this);
                            if (v.hasClass("medium")) {
                                v.find("img").attr("src", WEBROOT + "img/common/font_medium.gif");
                            } else if (v.hasClass("large")) {
                                v.find("img").attr("src", WEBROOT + "img/common/font_large.gif");
                            }
                        });
                        e.preventDefault();
                        return false;
                    }).end()
                    .find("a.medium").click(function(e) {
                        $.set_setting("fontsize","medium");
                        $(o.selector).css("font-size", "18px");
                        $(this)
                        .find("img")
                        .attr("src", WEBROOT + "img/common/selected_font_medium.gif")
                        .parents("li:first")
                        .siblings("li")
                        .find("a").each(function() {
                            var v = $(this);
                            if (v.hasClass("small")) {
                                v.find("img").attr("src", WEBROOT + "img/common/font_small.gif");
                            } else if (v.hasClass("large")) {
                                v.find("img").attr("src", WEBROOT + "img/common/font_large.gif");
                            }
                        });
                        e.preventDefault();
                        return false;
                    }).end()
                    .find("a.large").click(function(e) {
                        $.set_setting("fontsize","large");
                        $(o.selector).css("font-size", "22px");
                        $(this)
                        .find("img")
                        .attr("src", WEBROOT + "img/common/selected_font_large.gif")
                        .parents("li:first")
                        .siblings("li")
                        .find("a").each(function() {
                            var v = $(this);
                            if (v.hasClass("medium")) {
                                v.find("img").attr("src", WEBROOT + "img/common/font_medium.gif");
                            } else if (v.hasClass("small")) {
                                v.find("img").attr("src", WEBROOT + "img/common/font_small.gif");
                            }
                        });
                        e.preventDefault();
                        return false;
                    });
                });
            }
            return $(this);
        },
        set_and_do_link: function(o) {
            this.each(function() {
                var t = $(this);
                var q = t.attr('href').split("?");
                var h = q[0];
                q = q[1];
                h = h.split("/");
                t.attr('href', '#');
                t.data("k", (o != null && o["key"] ? o["key"] : h[0]));
                t.data("v", (o != null && o["values"] ? o["values"] : new Array(h[1], h[2])));
                t.data("f", (o != null && o["first_string"] ? o["first_string"] : (h[3] ? h[3] : t.html())));
                t.data("s", (o != null && o["second_string"] ? o["second_string"] : (h[4] ? h[4] : t.html())));
                t.data("fi", (o != null && o["first_image"] ? o["first_image"] : (h[5] ? '<img src="' + WEBROOT + 'img/' + h[5].replace("|", "/") + '" alt="" />' : "")));
                t.data("si", (o != null && o["second_image"] ? o["second_image"] : (h[6] ? '<img src="' + WEBROOT + 'img/' + h[6].replace("|", "/") + '" alt="" />' : "")));
                t.data("o", (o != null && o["options"] ? o["options"] : eval('(' + sj.util.htmlspecialchars_decode(q.substring(2, q.indexOf("&", 2))) + ')')));
                t.data("q", q.substr(q.indexOf("&") + 1));
                t.addClass("sj_set_and_do_first");
                t.click($.set_and_do);
            });
            return $(this);
        }
    });

    $.fn.extend({
        move: function(left, top, options) {
            if (!options) {
                options = {
                    window_edge_bound: false,
                    left_edge_offset: 0,
                    top_edge_offset: 0
                };
            } else {
                if (!options.left_edge_offset) {
                    options.left_edge_offset = 0;
                }
                if (!options.top_edge_offset) {
                    options.top_edge_offset = 0;
                }
            }
            this.each(function() {
                var o = $(this);
                if (options.window_edge_bound != null && options.window_edge_bound != undefined && options.window_edge_bound == true) {
                    var a = o.css("position") == "fixed" ? sj.util.get_window_size() : sj.util.get_window_size_with_scroll();
                    if (left) {
                        if (left + options.left_edge_offset < 0) {
                            o.css("left", (0 + options.left_edge_offset) + "px");
                        } else if (left + o.outerWidth() > a[0] - options.left_edge_offset) {
                            o.css("left", (a[0] - o.outerWidth() - options.left_edge_offset) + "px");
                        } else {
                            o.css("left", left + "px");
                        }
                    } else {
                        if (o.offset().left + options.left_edge_offset < 0) {
                            o.css("left", (0 + options.left_edge_offset) + "px");
                        }
                        if (o.offset().left + o.outerWidth() > a[0] - options.left_edge_offset) {
                            o.css("left", (a[0] - o.outerWidth() - options.left_edge_offset) + "px");
                        }
                    }
                    if (top) {
                        if (top + options.top_edge_offset < 0) {
                            o.css("top", (0 + options.top_edge_offset) + "px");
                        } else if (top + o.outerHeight() > a[1] - options.top_edge_offset) {
                            o.css("top", (a[1] - o.outerHeight() - options.top_edge_offset) + "px");
                        } else {
                            o.css("top", top + "px");
                        }
                    } else {
                        if (top + options.top_edge_offset < 0) {
                            o.css("top", (0 + options.top_edge_offset) + "px");
                        } else if (top + o.outerHeight() > a[1] - options.top_edge_offset) {
                            o.css("top", (a[1] - o.outerHeight() - options.top_edge_offset) + "px");
                        }
                    }
                } else {
                    o.css({left:left+"px",top:top+"px"});
                }
            });
            return this;
        }
    });

    $.fn.extend({
        timer: function(c, o) {
            o = $.extend({}, $.fn.timer.defaults, o);
            var ret = this;
            this.each(function() {
                var t = $(this);
                if (c == "create") {
                    t.data("options", o);
                    t.data("timer_id", setInterval(function(){t.timer("update")}, o.interval));
                    t.data("current_time", o.start_time);
                    t.html($.time.create(o.start_time));
                } else if (c == "update") {
                    var d = t.data("options");
                    if (d.state == $.timer.state.run) {
                        var s = t.data("current_time") + (d.type == $.timer.type.up ? d.tick : ($.timer.type.down ? -(d.tick) : 0));
                        if (d.can_update_cb == null || d.can_update_cb(t, s) == true) {
                            t.html($.time.create(s));
                            t.data("current_time", s);
                            if (d.update_cb) {
                                d.update_cb(t, s);
                            }
                            for (var i = 0; i < d.warnings.length; i++) {
                                if (d.warnings[i].used == false) {
                                    if (d.type == $.timer.type.up && s >= d.warnings[i].time) {
                                        d.warnings[i].cb(t, d.warnings[i], s, d);
                                        d.warnings[i].used = true;
                                    } else if (d.type == $.timer.type.down && s <= d.warnings[i].time) {
                                        d.warnings[i].cb(t, d.warnings[i], s, d);
                                        d.warnings[i].used = true;
                                    }
                                }
                            }
                            if (d.type == $.timer.type.down && $.time.parse(t.html()) == 0) {
                                t.timer("finish");
                            }
                        }
                    }
                } else if (c == "start") {
                    var d = t.data("options");
                    d.state = $.timer.state.run;
                    t.data("options", d);
                    if (d.start_cb) {
                        d.start_cb(t);
                    }
                } else if (c == "finish") {
                    var d = t.data("options");
                    t.timer("stop");
                    if (d.finish_cb) {
                        d.finish_cb(t);
                    }
                } else if (c == "stop") {
                    var d = t.data("options");
                    d.state = $.timer.state.stop;
                    for (var i = 0; i < d.warnings; i++) {
                        d.warnings[i].used = false;
                    }
                    t.data("options", d);
                    t.data("current_time", d.start_time);
                    if (d.stop_cb) {
                        d.stop_cb(t);
                    }
                } else if (c == "pause") {
                    var d = t.data("options");
                    d.state = $.timer.state.pause;
                    t.data("options", d);
                    if (d.pause_cb) {
                        d.pause_cb(t, t.data("current_time"));
                    }
                } else if (c == "reset") {
                    var d = t.data("options");
                    t.data("current_time", t.data("options").start_time);
                    for (var i = 0; i < d.warnings; i++) {
                        d.warnings[i].used = false;
                    }
                    t.data("options", d);
                    if (d.reset_cb) {
                        d.reset_cb(t);
                    }
                } else if (c == "delete") {
                    clearInterval(t.data("timer_id"));
                    t.removeData("options");
                    t.removeData("timer_id");
                    t.removeData("current_time");
                    t.empty();
                    if (d.delete_cb) {
                        d.delete_cb(t);
                    }
                } else if (c == "options") {
                    ret = t.data("options");
                }
            });
            return ret;
        },
        sj_load: function(url, params, before_callback, after_callback) {
            if (typeof url !== "string")
                return this._load(url);

            var off = url.indexOf(" ");
            if (off >= 0) {
                var selector = url.slice(off, url.length);
                url = url.slice(0, off);
            }

            var type = "GET";

            if (params)
                if (typeof params === "object") {
                    params = $.param(params);
                    type = "POST";
                }

            var self = this;

            $.ajax({
                url: url,
                type: type,
                dataType: "html",
                data: params,
                complete: function(res, status){
                    if (before_callback) {
                        self.each(before_callback, [res.responseText, status, res]);
                    }
                    if (status == "success" || status == "notmodified") {
                        self.html(selector ? $("<div/>").append(res.responseText.replace(/<script(.|\s)*?\/script>/g, "")).find(selector) : res.responseText);
                    }
                    if (after_callback) {
                        self.each(after_callback, [res.responseText, status, res]);
                    }
                }
            });
            return this;
        }
    });
    $.extend({
        timer: {
            type: {
                up: 0,
                down: 1
            },
            state: {
                run: 0,
                pause: 1,
                stop: 2
            },
            accuracy: {
                second: 0,
                minute: 1,
                hour: 2,
                second_loose: 3,
                minute_loose: 4,
                hour_loose: 5
            }
        },
        time: {
            parse: function(t, a) {
                var hms = (/^(?:(\d{1,2}):)?(?:(\d{1,2}):)?(\d{1,2})$/).exec(t);
                var time = 0;
                if (hms.length > 0) {
                    for (var i = hms.length - 1, m = 0; i > 0; i--) {
                        if (hms[i] != undefined && hms[i] != null && hms[i] != "") {
                            time += (parseInt((hms[i].length > 1 ? hms[i].replace(/^0{1}/, "") : hms[i])) * Math.pow(60, m));
                            m++;
                        }
                    }
                    return time;
                }
                
                return null;
            },
            create: function(t, a) {
                var ret = "";

                if (a == null) {
                    a = $.timer.accuracy.second;
                }

                if (a == $.timer.accuracy.hour || a == $.timer.accuracy.minute || a == $.timer.accuracy.second) {
                    var hours = Math.floor(t / 3600);
                    if(hours > 0)
                    {
                        ret += hours.toString();
                    }
                }
                
                if (a == $.timer.accuracy.minute || a == $.timer.accuracy.second) {
                    var minutes = Math.floor((t / 60) % 60);
                    if (ret != "") {
                        ret += ":" + (minutes.toString().length == 1 ? "0" : "");
                    }
                    ret += minutes.toString();
                }

                if (a == $.timer.accuracy.second) {
                    var seconds = Math.floor(t % 60);
                    if (ret != "") {
                        ret += ":";
                    }

                    var w = new Array(Math.abs(seconds.toString().length - 2) + 1);
                    seconds = w.join("0") + seconds.toString();
                    ret += seconds.toString();
                }

                return ret;
            }
        }
    });
    $.fn.timer.defaults = {
        type: $.timer.type.up,
        state: $.timer.state.stop,
        start_time: 0,
        interval: 1000,
        tick: 1,
        accuracy: $.timer.accuracy.second,
        warnings: new Array()
    };
    $.set_and_do = function(e) {
        var t = $(this);
        var v = "";
        if (t.hasClass("sj_set_and_do_first")) {
            v = t.data("v")[0];
        } else if (t.hasClass("sj_set_and_do_second")) {
            v = t.data("v")[1];
        }

        t.before('<img class="sj_ajax_loader" src="' + WEBROOT + 'img/common/mini_loader.gif" alt="Loading" />');
        $.set_setting(t.data("k"), v, function() {
            t.prev("img.sj_ajax_loader").remove();
            if (t.hasClass("sj_set_and_do_first")) {
                t.removeClass("sj_set_and_do_first").addClass("sj_set_and_do_second").html(t.data("si") + " " + t.data("s"));
            } else if (t.hasClass("sj_set_and_do_second")) {
                t.removeClass("sj_set_and_do_second").addClass("sj_set_and_do_first").html(t.data("fi") + " " + t.data("f"));
            }
            var o = t.data("o");
            if (o.cb && typeof(o.cb) == "function") {
                o.cb(t, v);
            }
        });

        e.preventDefault();
        return false;
    };
    $.set_and_load = function(t, v) {
        var q = (t.data("q") != null ? "&" + t.data("q") : "");
        var g = window.location.href
        if (g.indexOf("?") != -1) {
            g = g.substring(0, g.indexOf("?"));
        }

        t.before('<img class="sj_ajax_loader" src="' + WEBROOT + 'img/common/mini_loader.gif" alt="Loading" />');
        $(t.data("o").did).sj_load(g + '?a=html&h=1' + q, null, function(){sj.execute_before_load_callbacks(t.data("o").did);}, function(){t.prev("img.sj_ajax_loader").remove();sj.execute_after_load_callbacks(t.data("o").did);});
    }
    $.set_setting = function(k, v, cb) {
        $.post(WEBROOT + 'set_setting' + '/' + k + '/' + v + '?a=none', null, cb);
    };
    $.go = function(e, d) {
        window.location.href = d;
    };
    $.popup = function(e, d) {
        window.open(d);
    }
    $.histback = function(e, d) {
        history.back(d);
    }
    $.expr[':'].regex = function(e, i, m) {
        var matchParams = m[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(e)[attr.method](attr.property));
    }
})(jQuery);

