/**** /js/deprecated/topics.js ****/

/**
 * Initiate voting routines on page. 
 * Send vote data to server, 
 * update voting results on page (including styles change), 
 * disable buttons, hide or show blocks.
 * @param {String} topMessage New tooltip value for top votable element on page.
 * @param {String} otherMessage New tooltip value for other votable elements on page, defaults to topMessage.
 */
function initVote(topMessage, otherMessage) {
    var VotingBlock = Class.create();
    VotingBlock.prototype = {
        initialize: function(forButton, againstButton, id, message) {
            // save data
            this.forButton = $(forButton);
            this.againstButton = $(againstButton);
            this.id = id;
            this.message = message;
            
            // create bound handlers
            this.forHandler = function(event){ 
                this.vote('recommend', event); 
            }.bindAsEventListener(this);
            
            this.againstHandler = function(event){ 
                this.vote('complain', event); 
                // hide bad comment
                var comment_oneitem = $(this.againstButton.parentNode.parentNode.parentNode);
                if (comment_oneitem.hasClassName('unhidable')) return;
                comment_oneitem.addClassName('hide_bad voted');
            }.bindAsEventListener(this);
            
            // attach handlers
            this.forButton.observe('click', this.forHandler);
            this.againstButton.observe('click', this.againstHandler);
        },
        disableButton: function(button, handler) {
            button.rel = '';
            Event.observe(button, 'click', Event.stop);
            Event.stopObserving(button, 'click', handler);
            button.setAttribute('title',  this.message);
            var img = button.getElementsByTagName('img')[0];
            if (img) {
                img.src = img.src.replace(/\.gif/i, '_no.gif');
            }
        },
        vote: function(action, event) {
            // prevent going to link
            Event.stop(event || window.event);
            
            // quit if already voted
            if (!this.id || this.id.length == 0) return;

            // disable both related buttons 
            this.disableButton(this.forButton,     this.forHandler);
            this.disableButton(this.againstButton, this.againstHandler);

            // send request
            var req = new JsHttpRequest();
            req.caching = false;
            req.open('GET', window.location.protocol + '//' + window.location.host + '/widgets/ajax/' + action, true);
            req.onreadystatechange = function () {
                if ( req.readyState != 4 ) return;
                if ( !req.responseJS || !req.responseJS.weight ) return;
                
                var weight = req.responseJS.weight;
                if (weight > 0) {
                    weight = '+' + weight;
                }

                // update voting data
                $$('span.weight' + this.id).each(function(hWeight) {
                    hWeight.innerHTML = weight;
                    if (weight > 0) {
                        hWeight.parentNode.className = 'vote_up_bg';
                    } else if (weight == 0) {
                        hWeight.parentNode.className = 'vote_no_bg';
                    } else {
                        hWeight.parentNode.className = 'vote_down_bg';
                    }
                });
            }.bind(this);
            req.send({q: this.id});
        }
    };

    otherMessage = otherMessage || topMessage;
    
    var forButtons = document.getElementsByName('votefor');
    var againstButtons = document.getElementsByName('voteagainst');
    
    // initiate voting block for every pair of buttons:
    for (var index = 0; index < forButtons.length; index++) {
        new VotingBlock(forButtons[index], againstButtons[index], forButtons[index].rel, (index == 0) ? topMessage : otherMessage);
    }
   
    // assign handlers to show hidden items
    var showersOfHidden = document.getElementsByName('show_hidden');
    $A(showersOfHidden).each(function(shower){
        $(shower).observe('click', function(event) {
            Event.stop(event);
            var comment_oneitem = $(shower.parentNode.parentNode.parentNode);
            comment_oneitem.removeClassName('hide_bad');
            comment_oneitem.addClassName('');
        }.bindAsEventListener(shower));
    })
    
    // assign handlers to hide again hidden items
    var hidersOfHidden = document.getElementsByName('hide_hidden');
    $A(hidersOfHidden).each(function(hider){
        $(hider).observe('click', function(event) {
            Event.stop(event);
            var comment_oneitem = $(hider.parentNode.parentNode.parentNode);
            comment_oneitem.removeClassName('show_bad');
            comment_oneitem.addClassName('hide_bad');
        }.bindAsEventListener(hider));
    })
    
    // assign handlers to hide viewed items
    var hideViewers = document.getElementsByName('hide_viewed');
    $A(hideViewers).each(function(hider){
        $(hider).observe('click', function(event) {
            var comment_oneitem = $(hider.parentNode.parentNode.parentNode.parentNode);
            comment_oneitem.removeClassName('show_bad');
            comment_oneitem.addClassName('hide_bad');
            comment_oneitem.addClassName('hide_viewed');
        }.bindAsEventListener(hider));
    })
}


function initTopicsOneitem()
{
    var link = document.getElementsByName('topic_delete_link')[0];
    if (link) {
        Event.observe(link, 'click', function (e) {
            if (!confirm(DIC.topic_delete_link_confirm)) {
                Event.stop(e);
                return false;
            }
        })
    }
    var links = document.getElementsByName('comment_delete_link');
    for (var i = 0; i < links.length; i++) {
        Event.observe(links[i], 'click', function (e) {
            if (!confirm(DIC.comment_delete_link_confirm)) {
                Event.stop(e);
                return false;
            }
        })
    }
}


/**
 * Initialize topic watch/unwatch checkbox.
 */
function initObjWatch()
{
    var elts = document.getElementsByName('obj_checkbox_watch');
    for (var i = 0; i < elts.length; i++) { (function() { 
        var chk = elts[i];
        var div = chk.parentNode;
        var img = div.getElementsByTagName('img')[0];
        Event.observe(chk, 'click', function(event) {
            chk.blur();
            img.style.visibility = 'visible';
            // Do not use POST because of the MetaForm!
            JsHttpRequest.query(
                'GET ' + window.location.protocol + '//' + window.location.host + '/widgets/ajax/objWatch',
                { 
                    obj_id: chk.value, 
                    watch: (chk.checked? 1 : 0) 
                },
                function(js, err) {
                    img.style.visibility = 'hidden';
                },
                true
            );
        })
    })() }
    if ($('mark_as_read_button')) {
        Event.observe($('mark_as_read_button'), 'click', function(event) {
            if (!confirm(DIC.mark_all_as_read_confirm)) {
                Event.stop(e);
                return false;
            }
        });
    }
}

;

/**** /js/moikrug/ui/Tooltip.js ****/
Lang.module('moikrug.ui.Tooltip');
   
moikrug.ui.Tooltip = Lang.createClass(Widget, {
    init: function(node, options) {
        this.baseConstructor(node);
        this.ttl = options.ttl || 0;
        this.tellServer = options.tellServer || null;
        this.options = options;
        
        this.parse();
        this.bindEvents();
        this.restore();
       
        Postprocess.cleanNode(this.controlClose);
    },

    parse: function() {
        this.controlClose = this.node.down(this.options.controlCloseSelector || '.x_close');
    },

    bindEvents: function() {
        if(this.controlClose) {
            Event.observe(this.controlClose, 'click', this.onControlCloseClick.bindAsEventListener(this));
        }
        
        this.node.observe('tooltip:close:' + this.node.id, this.close.bind(this));
    },

    onControlCloseClick: function(event) {
        this.close();
        Event.stop(event);
        return false;
    },
    
    maybeTellServer: function() {
        if (this.tellServer) {
        	JsHttpRequest.query(this.tellServer);
            //new Ajax.Request(this.tellServer, {method: "GET"});
        }
    },

    close: function() {
        this.node.addClassName('hidden');
        var date = new Date();
        date.setTime(date.getTime()+(this.ttl * 24 * 60 * 60 * 1000 ));
        Cookie.set('[uid]_Tooltip#' + this.node.id, '1', this.ttl ? date : null);
        this.maybeTellServer();
    },

    restore: function() {
        var tmp = Cookie.get('[uid]_Tooltip#' + this.node.id);
        if(tmp) {
        	this.node.addClassName('hidden');
        }
    }

});

moikrug.ui.Tooltip.getInstance = function(node, options) {
     return Widget.getInstance(node) || Widget.registerInstance(node, new moikrug.ui.Tooltip(node, options));
};
;

/**** /js/moikrug/ChatNotificationManager.js ****/
Lang.module("moikrug.ChatNofiticationManager");

moikrug.ChatNotificationManager = Lang.createClass(Widget, {

	frameSize: null,
	msgCount: null,
	widgets: [],
	queen: null,
	msgContainer: null,

	closeNode: null,
	CLOSE_COOKIE: 'ChatNotificationManager_closed',

    init: function(node, options, limit, count) {
        this.baseConstructor(node, options);
        this.frameSize = limit;
        this.msgCount = count;
    },

    parse: function() {
        this.widgets = [];
        
        // Save sample (prototype) node and remove it from the container.
        this.queen = WidgetRegistry.get(this.node.down('.chat_notifier_item.hidden'));
        this.msgContainer = this.queen.node.parentNode;
        this.msgContainer.removeChild(this.queen.node);
        
        this.node.select('.chat_notifier_item').each((function(item) {
            this.widgets.push(WidgetRegistry.get(item));
        }).bind(this));
        
        this.closeNode = this.node.down('.chat_notifier_close');
        if (!this.isClosed()) {
        	this.setClosed(false);
        }

        this.limitFrame();
        return this;
    },

    bindEvents: function() {
        var markReadAndMaybeHide = (function(notification) {
            moikrug.Multiplexor.removeKey("Message", notification.getMessageId());
        }).bind(this);

        this.widgets.each((function(notification) {
            notification.observe("textClick", markReadAndMaybeHide.curry(notification));
        }).bind(this));
        
        Event.observe(this.closeNode, "click", (function(e) {
            e.stop();
            this.setClosed(true);
        }).bindAsEventListener(this));

        moikrug.Multiplexor.subscribe("Message", (function(messageData) {
            if (moikrug.ThreadPage && moikrug.ThreadPage.instance.threadId == messageData.threadId) {
                moikrug.Multiplexor.removeKey("Message", messageData.messageId);
                return;
            }
            var newNotification = this.queen.cloneCurrent();
            if (this.msgContainer.firstChild) {
		        this.msgContainer.insertBefore(newNotification.node, this.msgContainer.firstChild);
            } else {
		        this.msgContainer.appendChild(newNotification.node);
            }
            newNotification.setMessageId(messageData.messageId);
            newNotification.setPersonName(messageData.personName, messageData.personNameFull);
            newNotification.setPersonLink(messageData.personLink);
            newNotification.setMessageText(messageData.inlineText);
            newNotification.setMessageLink(messageData.url);
            newNotification.node.removeClassName("hidden");

            newNotification.observe("close", markReadAndMaybeHide.curry(newNotification));
            newNotification.observe("textClick", markReadAndMaybeHide.curry(newNotification));
            this.widgets.push(newNotification);
            this.msgCount++;
            this.limitFrame();

            this.setClosed(false);
            newNotification.blink();
            moikrug.TitleNotification.startBlink(messageData.personName + ' - ' + DIC.new_message_from);
            
        }).bind(this));
        return this;
    },
    
    limitFrame: function() {
		var f = $(this.msgContainer.parentNode).select('.chat_notifier_f')[0];
		var items = $(this.msgContainer).select('.chat_notifier_item');
		var nShown = 0;
		for (var i = 0; i < items.length; i++) {
			var item = items[i];
			var widget = WidgetRegistry.get(item);
			if (nShown < this.frameSize) {
	        	item.removeClassName("hidden");
				nShown++;
			} else {
	        	item.addClassName("hidden");
			}
        }
        if (this.msgCount <= nShown) {
        	f.style.display = 'none';
        } else {
        	f.style.display = '';
			$(f).select('a')[0].innerHTML = common.TextUtils.formatNumberTemplate(
				this.msgCount - nShown,
				DIC.chat_notifier_n_new_messages
			);
        }
    },
    
    setClosed: function(flag) {
        Cookie.set(this.CLOSE_COOKIE, flag? 1 : 0, null, "/");
        var allHidden = this.widgets.all(function(widget) {return widget.node.hasClassName("hidden");});
        if (!flag && !allHidden) {
        	this.node.removeClassName("hidden");
        } else {
        	this.node.addClassName("hidden");
        }
    },
    
    isClosed: function() {
        return parseInt(Cookie.get(this.CLOSE_COOKIE), 10);
    }
});
;

/**** /js/moikrug/TitleNotification.js ****/
Lang.module("moikrug.TitleNotification");

moikrug.TitleNotification = {

    focusStatus: false,
    blinkStatus: false,
    oldTitle: false,
    timeout: null,
    
    bindEvents: function() {
        if (Prototype.Browser.IE) {
            document.observe('focusin', this._setFocus.bindAsEventListener(this));
            document.observe('focusout', this._clearFocus.bindAsEventListener(this));
        } else {
	        document.observe('focus', this._setFocus.bindAsEventListener(this));
	        document.observe('blur', this._clearFocus.bindAsEventListener(this));
        }
        return this;
    },
    
    _setFocus: function() {
        this.focusStatus = true;
    },
    
    _clearFocus: function() {
        this.focusStatus = false;
    },
    
    startBlink: function(msg) {
        this.oldTitle = document.title;
        msg = msg.stripTags();
        msg = msg.replace(/\&.*?;/,'');
        this._blinkTitle(msg);
    },
    
    stopBlink: function() {
        this._clearFocus();
    },
    
    _blinkTitle: function(msg) {
        
        if (this.blinkStatus) {
            document.title = msg;
        } else {
            document.title = this.oldTitle;
        }
        this.blinkStatus = !this.blinkStatus;
        if (!this.focusStatus) {
            this.timeout = setTimeout(function() { this._blinkTitle(msg); }.bind(this), 1500);
        } else {
            document.title = this.oldTitle;
        }
        
    }
    
};
moikrug.TitleNotification.bindEvents();

;

/**** /js/moikrug/ui/messaging/ChatNotification.js ****/
Lang.module('moikrug.ui.messaging.ChatNotification');

Lang.include('moikrug.widget.Clonable');

moikrug.ui.messaging.ChatNotification = Lang.createClass(moikrug.widget.Clonable, {
    init: function(node, options, name, className) {
        this.baseConstructor(node, options, name, className || "ChatNotification");
    },

    _createClonedWidget: function(node, options, name, className) {
        return new moikrug.ui.messaging.ChatNotification(node, options, name, className).parse().bindEvents();
    },
    
    parse: function() {
        this.personNameNode = this.node.down(".chat_notifier_person");
        this.messageTextNode = this.node.down(".chat_notifier_text");
        return this;
    },
    
    bindEvents: function() {
        Event.observe(this.node, "click", (function() {
            this.onTextClick();
        }).bind(this));
        return this;
    },

    blink: function() {
        var node = this.node;
        var delay = 400;
        node.addClassName("chat_notifier_item_dark");
        window.setTimeout(function() {node.removeClassName("chat_notifier_item_dark");}, delay);
        window.setTimeout(function() {node.addClassName("chat_notifier_item_dark");}, delay*2);
        window.setTimeout(function() {node.removeClassName("chat_notifier_item_dark");}, delay*3);
        window.setTimeout(function() {node.addClassName("chat_notifier_item_dark");}, delay*4);
        window.setTimeout(function() {node.removeClassName("chat_notifier_item_dark");}, delay*5);
        window.setTimeout(function() {node.addClassName("chat_notifier_item_dark");}, delay*6);
        window.setTimeout(function() {node.removeClassName("chat_notifier_item_dark");}, delay*7);
    },

    close: function() {
        this.node.addClassName("hidden");
    },

    getMessageId: function() {
        return this.options.messageId;
    },

    setMessageId: function(id) {
        this.options.messageId = id; 
    },

    /**
     * Setters
     */
    setPersonName: function(name, fullName) {
        this.personNameNode.title = fullName;
        this.personNameNode.innerHTML = common.TextUtils.highlightFirstLetterInName(name);
    },

    setPersonLink: function(link) {
        // No separated link for a person. 
        //this.personNameNode.href = link;
    },

    setMessageLink: function(link) {
    	// Note that yo CANNOT do up('a'), because this.messageTextNode
    	// is not in DOMDocument yet at this time. :-(
    	node = $(this.messageTextNode).up(); 
        node.href = link;
    },

    setMessageText: function(text) {
        this.messageTextNode.down("span").innerHTML = text;
    },

    /**
     * Events
     */
    onClose: function(){},
    onTextClick: function(){}

});
;
