if (!Clip) var Clip = {};
if (!Clip.Blog) Clip.Blog = {};

Clip.Blog.Favorite = Class.create();
Clip.Blog.Favorite.apihost = 'http://www.shonan-clip.jp/';
Clip.Blog.Favorite.prototype = {
    history: [],

    initialize: function(params) {
        params = $H(params);
        this.id = params.id;
        this.schema = params.schema;
        this.path = '/image/blog/style_' + Clip.Blog.template;

        var _id = 'profile_bot_myclip_' + this.id;
        if (params.schema == 'Blog') {

            var create_img = (function(fn) {
                var img = document.createElement('img');
                img.name = "profile_bot_myclip";
                img.className = 'csrPOINT';
                img.id = 'profile_bot_myclip_' + this.id;
                Event.observe(img, 'click', this.openDialog.bindAsEventListener(this));
                Event.observe(img, 'mouseout', function() { MM_swapImgRestore(); });
                return fn.bind(this)(img);
            }).bind(this);

            this._image = {};
            this._image.unclip = create_img(function(img) {
                img.src = this.path + '/post_myclip.gif';
                img.alt = "MYクリップに入れる";
                var _path = this.path + '/post_myclip_f2.gif';
                Event.observe(img, 'mouseover', function() { MM_swapImage(_id, '', _path, 1); });
                return img;
            });
            this._image.cliped = create_img(function(img) {
                img.src = this.path + '/post_myclip_in.gif';
                img.alt = "MYクリップに入っています";
                var _path = this.path + '/post_myclip_in_f2.gif';
                Event.observe(img, 'mouseover', function() { MM_swapImage(_id, '', _path, 1); });
                return img;
            });
        }
        else {
            Event.observe($(_id), 'click', this.openDialog.bindAsEventListener(this));
        }

        try {
            new Flax.Request(
                Clip.Blog.Favorite.apihost+'rest/favorite?format=json&'+params.toQueryString()+'&t='+ new Date().getTime(),
                {
                    method: 'get',
                    onSuccess: this.initialized.bind(this)
                }
            );
        }
        catch (e) {
            Event.observe( window, 'load', (function() {
                new Flax.Request(
                    Clip.Blog.Favorite.apihost+'rest/favorite?format=json&'+params.toQueryString()+'&t='+ new Date().getTime(),
                    {
                        method: 'get',
                        onSuccess: this.initialized.bind(this)
                    }
                );
            }).bind(this) );
        }

        $('message_open_' + this.id).innerHTML = Jemplate.process('dialog.tt', { id: this.id });
        $('edit_' + this.id).innerHTML = this.loader = Jemplate.process('loading.tt');

        this.hide();
    },

    initialized: function(data) {
        var json = eval("(" + data + ")");
        if (json.favorite) {
            this.favorite_id = json.favorite.id;
            this.switchImage();
        }
        this.switchImage();
    },

    show: function() {
        $('message_open_' + this.id).style.display = 'block';
        $('message_open_' + this.id).style.visibility = 'inherit';
    },

    hide: function() {
        $('message_open_' + this.id).hide();
        this.reset();
    },

    reset: function() {
        this.history = [];
        $('edit_' + this.id).innerHTML = Jemplate.process('loading.tt');
    },

    back: function() {
        var back = this.history.pop();
        if (back) {
            this.update( back );
        }
        else {
            this.hide();
            this.reset();
        }
    },

    update: function(html) {
        var before = this.beforeloading || $('edit_'+this.id).innerHTML;
        this.history.push( before );
        $('edit_'+this.id).innerHTML = html;
        this.beforeloading = null;
    },

    loading: function() {
        this.beforeloading = $('edit_'+this.id).innseHTML;
        $('edit_'+this.id).innerHTML = this.loader;
    },

    openDialog: function(e) {
        this.show();

        new Flax.Request(
            Clip.Blog.Favorite.apihost+'rest/favorite/labels?format=json&' + new Date().getTime(),
            {
                method: 'get',
                onSuccess: this.labelsLoaded.bind(this)
            }
        );
    },

    labelsLoaded: function(data) {
        var json = eval("("+data+")");
        try {
            json.labels = json.labels.findAll( function(i) { return( i['id'] > 0 ); } );
        } catch (e) {}

        this.labels = json;
        this.change = true;

        if (json.error) {
            this.update( Jemplate.process('need_login.tt', { host: Clip.Blog.Favorite.apihost, back: document.location.href }) );
        }
        else {
            if (this.favorite_id) {
                json.id = this.id;
                this.update( Jemplate.process('remove_menu.tt', json) );
            }
            else {
                if (json.labels.length > 0) {
                    json.noback = true;
                    json.id = this.id;
                    this.update( Jemplate.process('categories.tt', json) );
                }
                else {
                    this.insert();
                }
            }
        }
    },

    insert: function() {
        var params = $H();
        params['type'] = this.schema;
        params['id'] = this.id;

        var form = $('labels_form'+this.id);
        var query = '';
        if (form) {
            query = Form.serialize(form);
        }

        new Flax.Request(
            Clip.Blog.Favorite.apihost+'rest/favorite?format=json&'+params.toQueryString()+'&'+query+'&t='+ new Date().getTime(),
            {
                method: 'post',
                onSuccess: this.inserted.bind(this)
            }
        );
    },

    inserted: function(data) {
        var json = eval("("+data+")");

        if (json.status == 'OK') {
            this.favorite_id = json.id;
            this.update( Jemplate.process('success.tt', { id: this.id }) );
            if (this.change) this.switchImage();
        }
    },

    categorize: function() {
        this.loading();
        this.change = false;

        var params = $H();
        params.id = this.id;
        params.schema = this.schema;

        new Flax.Request(
            Clip.Blog.Favorite.apihost+'rest/favorite/selected_label?format=json&'+params.toQueryString()+ '&t=' + new Date().getTime(),
            {
                method: 'get',
                onSuccess: this.categorized.bind(this)
            }
        );
    },

    categorized: function(data) {
        var json = eval("("+data+")");
        data = this.labels;
        data.selected = json.selected;
        this.update( Jemplate.process('categories.tt', data) );
    },

    remove_confirm: function() {
        this.update( Jemplate.process('remove_confirm.tt', { id: this.id }) );
    },

    remove: function() {
        if (this.favorite_id) {
            new Flax.Request(
                Clip.Blog.Favorite.apihost+'rest/favorite/delete/' + this.favorite_id + '?format=json&t=' + new Date().getTime(),
                {
                    method: "post",
                    onSuccess: this.removed.bind(this)
                }
            );
        }
    },

    removed: function(data) {
        var json = eval("("+data+")");
        if (json.status == 'OK') {
            this.favorite_id = null;
            this.hide(); this.reset();
            this.switchImage();
        }
    },

    switchImage: function() {
        var id = 'profile_bot_myclip_' + this.id;
        var bot = $(id);

        var flag = true;
        var _url = function(_f) { return 'url("' + this.path + '/bot_myclip_' + _f + '.gif")'; };
        if (!bot.init) {
            if (this.schema == 'Blog') {
                bot.parentNode.replaceChild(this._image.unclip, bot);
                bot = $(id);
            }
            else {
                bot.style.backgroundImage = _url.apply(this, ['out']);
            }
        }
        else {
            if (this.schema == 'Blog') {
                bot.parentNode.replaceChild(this._image.cliped, bot);
                bot = $(id);
            }
            else {
                bot.style.backgroundImage = _url.apply(this, ['in']);
            }
            flag = false;
        }
        if(!!bot) {
            bot.init = flag;
        }
    },

    dummy: null
};
