var Lvs;

if (Lvs === undefined) {
    Lvs = {};
}

Lvs.SearchCondSaver = {};

Lvs.SearchCondSaver.Util = {
    getScrollHeight: function () {
        return document.documentElement.scrollHeight || document.body.scrollHeight;
    },
    getScrollTop: function () {
        return document.documentElement.scrollTop || document.body.scrollTop;
    },
    getUserAgent: function () {
        return window.navigator.userAgent.toLowerCase();
    },
    getAppVersion: function () {
        return window.navigator.appVersion.toLowerCase();
    },
    selects: null,
    ie6: function (value) {
        if (Lvs.SearchCondSaver.Util.getUserAgent().indexOf('msie') == -1 || Lvs.SearchCondSaver.Util.getAppVersion().indexOf('msie 6.0') == -1) {
            return;
        }
        if (!Lvs.SearchCondSaver.Util.selects) {
            Lvs.SearchCondSaver.Util.selects = $$('select');
        }
        Lvs.SearchCondSaver.Util.selects.each(function (x) { x.setStyle({ visibility: value }); });
    }
};

/**
 *
 * @class Lvs.SearchCondSaver.Main
 */
Lvs.SearchCondSaver.Main = Class.create({

    /**
     * @type {Element}
     */
    elem: null,

    /**
     * @type {Form}
     */
    form: null,

    /**
     * @type {string}
     */
    uri: null,

    /**
     * @type {string}
     */
    modalInnerId: null,

    /**
     * @type {string}
     */
    modalCloseButtonId: null,

    /**
     * @param {Element} elem
     * @param {Form} form
     * @param {Object} config
     * @constructor
     * @protected
     */
    initialize: function (elem, form, config) {
        this.elem = elem;
        this.form = form;
        this.uri = config.ajaxUri;
        this.modalInnerId = config.innerId;
        this.modalCloseButtonId = config['closeButtonId'];
        this.setEventListener();
    },

    /**
     * @protected
     */
    save: function () {
        new Ajax.Request(this.uri, {
            method: 'post',
            parameters: this.form.serialize(true),
            onSuccess: function (response) {
                var compHtml = response.responseText;
                if (!compHtml) {
                    return;
                }
                var modal = new Element('div', { 'display': 'block' }).update(compHtml);
                document.body.insert(modal);
                if (this.modalCloseButtonId) {
                    var modalCloseButton = $(this.modalCloseButtonId);
                    Event.observe(modalCloseButton, 'click', function () {
                        Event.stopObserving(modalCloseButton, 'click', arguments.callee);
                        Lvs.SearchCondSaver.Util.ie6('visible');
                        modal.remove();
                    });
                }
                var modalInner = $(this.modalInnerId);
                modalInner.setStyle({
                    top: (50 + Lvs.SearchCondSaver.Util.getScrollTop()) + 'px'
                });
                new Lvs.SearchCondSaver.Modal(modal, function () { modalInner.show(); });
            }.bind(this)
        });
    },

    /**
     * @private
     */
    setEventListener: function () {
        this.elem.observe('click', this.save.bindAsEventListener(this));
    }
});

/**
 *
 * @class Lvs.SearchCondSaver.Modal
 */
Lvs.SearchCondSaver.Modal = Class.create({

    /**
     * @type {int}
     */
    timerId: null,

    /**
     * @type {Element}
     */
    back: null,

    /**
     * @type {Function}
     */
    callback: null,

    /**
     * @type {int}
     */
    opacity: 0,

    /**
     * @param {Element} parentElem
     * @param {Function} callback
     * @constructor
     * @protected
     */
    initialize: function (parentElem, callback) {
        Lvs.SearchCondSaver.Util.ie6('hidden');
        this.back = new Element('div').setStyle({
            display: 'block',
            position: 'absolute',
            zIndex: 1000,
            top: 0,
            left: 0,
            background: 'none repeat scroll 0 0 #333333',
            height: Lvs.SearchCondSaver.Util.getScrollHeight() + 'px',
            width: '100%',
            opacity: '0.0',
            filter: 'progid:DXImageTransform.Microsoft.Alpha(opacity=0)'
        });
        Event.observe(this.back, 'click', function () {
            Event.stopObserving(this.back, 'click', arguments.callee);
            Lvs.SearchCondSaver.Util.ie6('visible');
            parentElem.remove();
        });
        Event.observe(document.body, 'keyup', function (e) {
            if (e.keyCode == Event.KEY_ESC) {
                Event.stopObserving(document.body, 'keyup', arguments.callee);
                Lvs.SearchCondSaver.Util.ie6('visible');
                parentElem.remove(); 
            }
        });
        this.callback = callback;
        parentElem.insert(this.back);
        this.timerId = setInterval(this.launch.bind(this), 32);
    },

    /**
     * @private
     */
    launch: function () {
        if (this.opacity > 40) {
            clearInterval(this.timerId);
            this.callback.delay(0.2);
        }
        this.opacity += 10;
        this.back.setStyle({
            filter: 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + this.opacity + ')',
            opacity: '0.' + this.opacity
        });
    }
});

/**
*
* @class Lvs.SearchCondSaver.Tooltip
*/
Lvs.SearchCondSaver.Tooltip = Class.create({

    /**
     * @type {Element}
     */
    tooltips: null,

    /**
     * @type {string}
     */
    query: null,

    /**
     * @type {Element}
     */
    element: null,

    /**
     * @type {Element}
     */
    tooltip: null,

    /**
     * @type {Elements}
     */

    /**
     * @param {Element} tips
     * @param {Element} element
     * @constructor
     * @protected
     */
    initialize: function (tips, element) {
        tips.remove();
        document.body.insert(tips);
        tips.setStyle(this.getDefaultStyles());
        this.tooltips = tips;
        this.query = element.id.replace(/__anchor__/, '');
        this.element = element;
        this.tooltip = $('__tooltip__' + this.query);
        this.setEventListener();
    },

    /**
     * @protected
     */
    show: function (e) {
        this.tooltip.show();
        this.tooltips.show();
        this.tooltips.setStyle({
            top: e.pointerY() - this.tooltips.offsetHeight - 10 + 'px',
            left: e.pointerX() - 95 + 'px',
            zIndex: 2000,
            opacity: '1.0',
            filter: 'progid:DXImageTransform.Microsoft.Alpha(opacity=100)'
        });
    },

    /**
     * @protected
     */
    hide: function () {
        this.tooltips.setStyle(this.getDefaultStyles());
        this.tooltip.hide();
        this.tooltips.hide();
    },

    /**
     * @private
     */
    setEventListener: function () {
        this.element.observe('mousemove', this.show.bindAsEventListener(this));
        this.element.observe('mouseout', this.hide.bindAsEventListener(this));
    },

    /**
     * @private
     */
    getDefaultStyles: function () {
        return {
            top: '0px',
            left: '0px',
            position: 'absolute',
            zIndex: 0,
            opacity: '0.0',
            filter: 'progid:DXImageTransform.Microsoft.Alpha(opacity=0)'
        };
    }
});

Lvs.SearchCondSaver.Remove = function () {
    if (!confirm('保存した検索条件を削除します。よろしいですか？')) {
        return false;
    }
    new Ajax.Request('/member/removeSearchCond', {
        method: 'post',
        parameters: { query: this.id.replace(/__remove__/, '') },
        onSuccess: function (response) {
            var elem = this.parentNode.parentNode.parentNode.parentNode;
            new Effect.Fade(elem, { queue: { scope: '__remove__', position: 'front', limit: 2 }, from: 1, to: 0, duration: 1 });
        }.bind(this)
    });
};

Lvs.SearchCondSaver.Modify = function () {
    var query = this.id.replace(/__modify__/, '');
    Element.removeClassName(this, 'btnChange');
    Element.addClassName(this, 'btnSave');
    $('__msg__' + query).show();
    $('__text__' + query).show();
    $('__word__' + query).hide();
    Event.stopObserving(this);
    Event.observe(this, 'click', Lvs.SearchCondSaver.ModifyComp);
};

Lvs.SearchCondSaver.ModifyComp = function () {
    var query = this.id.replace(/__modify__/, '');
    var msg = $('__msg__' + query);
    var text = $('__text__' + query);
    var word = $('__word__' + query);
    new Ajax.Request('/member/updateSearchCond', {
        method: 'post',
        parameters: { query: query, title: text.value },
        onSuccess: function (response) {
            Element.removeClassName(this, 'btnSave');
            Element.addClassName(this, 'btnChange');
            var title = response.responseText;
            word.update(title);
            text.value = title;
            msg.hide();
            text.hide();
            word.show();
            Event.stopObserving(this);
            Event.observe(this, 'click', Lvs.SearchCondSaver.Modify);
        }.bind(this)
    });
};
