if (typeof(Prototype) == "undefined") throw("prototype.js is required");
//if (typeof(Lightbox) == "undefined") throw("lightbox.js is required");
if (typeof(Flax) == "undefined") throw("Flax.js is required");

if (typeof(Clip) == "undefined") var Clip = {};
if (typeof(Clip.Blog) == "undefined") Clip.Blog = {};

Clip.Blog.Reference = Class.create();
Clip.Blog.Reference.prototype = {
    schema: null,
    id: null,
    order: 'date',
    reverse: 0,
    page: 1,
    perpage: 10,

    initialize: function(args) {
        this.schema = args["schema"];
        this.id = args["id"];
    },

    redirect: function() {
        var compose_url = this.uri_for("/compose/", "blog");
        document.location.href = compose_url+"?ref="+this.schema+"&id="+this.id;
    },

    host: function() {
        var me = arguments.callee;
        if(me["host"]) return me["host"];

        var m = document.location.href.match(/(https?:\/\/[^\/]+)/);
        if (m) {
            me["host"] = m[1];
        }

        return me["host"];
    },

    uri_for: function(path, service/* = null */) {
        var url = this.host()+path;
        return service ? url.replace(/(https?:\/\/)[^.]+/, "$1"+service) : url;
    },

    lightbox: function(params, no_centalize) {
        Object.extend(params, { ajax_class: "Flax.Request" });
        if (!no_centalize)
            Object.extend(params, { container_width: 670, container_height: 550 });

        if (params["url"]) params["url"] = this.addTimeQuery(params["url"]);
        return new Lightbox(params);
    },

    addTimeQuery: function(url) {
        var d = new Date().getTime();
        url += (url.match(/\?/) ? "&" : "?") + d;
        return url;
    },

    renderClips: function() {
        new Flax.Request(
            this.uri_for("/api/reference/clips_all?id="+this.id+"&schema="+this.schema+"&page="+this.page+"&order="+this.order+"&reverse="+this.reverse+"&perpage="+this.perpage, 'blog'),
            { onSuccess: this.renderClipsHandler.bind(this) }
        );
    },

    renderClipsHandler: function(data) {
        var json = eval("("+data+")");
        if (json.result) {
            $("blog_references").innerHTML = json.result;
        }
    },

    setOrder: function(order) {
        this.order = order;
        this.page = 1;
    },

    reverseReverse: function() {
        this.page = 1;
        this.reverse = this.reverse ? 0 : 1;
    },

    renderPrev: function() {
        this.page--;
        if (this.page <= 0) this.page = 1;
        this.renderClips();
    },

    renderNext: function() {
        this.page++;
        this.renderClips();
    }
};
