
chat = {
	last_id : 0, 
	lock : false,

	color_list : [
        '#ff0000',
        '#037911',
        '#0005d4',
        '#21c4e7',
        '#e98d16',
        '#ea22de',
        '#5aea5a',
        '#d00b5f',
        '#00e4ff',
        '#9369e2'
    ],
    
    special_colors : {
        admin : '#000000',
        owners: '#000000'
    },
    
    texts : {
    	today : 'Сегодня',
    	yesterday : 'Вчера',
    	last_week : 'На прошлой неделе',
    	far_away : 'Старше недели'
    },
    
    explode_by_date : function (list) {
    	var groups = {}
    	var cnt = 0
    	for (var idx in list) {
    	    var gidx = list[idx][3]
    	    if (!groups[gidx]) {
        		groups[gidx] = []
        		cnt ++
    	    }
    	    groups[gidx].push(list[idx]) 
	   }
	   return {list : groups, count : cnt}
    },
    
    setbanned : function(id, value) {
	   jQuery.ajax({
            type : 'get',
            url : '/broadcast/chat/ban/' + id + '/' + value,
            dataType : 'json'
        });
	 
    },
    
    render_name_html : function(id, string) {
    	var color = this.special_colors[id]
        if (!color) {
            color = this.color_list[id % this.color_list.length]
        }
        return ('<div style="color:' + color + '">'+ string + '</div>')
    },
    
    render : function (list) {
    	var result = this.explode_by_date(list)
    	
    	var parts = result['list']
    	var size = result['count']
    	var cnt = 0
    	var is_new_flag
    	var $el = 0;
    	
    	for (var part_idx in parts) {
    	    if ($('.' + part_idx).length > 0) {
                $el = $('.' + part_idx)
                is_new_flag = false
    	    } else {
                $el = $(document.createElement('div'))
                $el.addClass('group')
                $el.addClass(part_idx)
                is_new_flag = true
    	    }
    	    var r_list = parts[part_idx]
    	    for (var item in r_list) {
    		
                var color = this.special_colors[r_list[item][2]]
                if (!color) {
                    color = this.color_list[r_list[item][2] % this.color_list.length]
    	        }
                $el.append(this.render_name_html(r_list[item][2], '<b>'+ r_list[item][1] +'</b>: ' + r_list[item][0]))
    	    }
    	
    	    if (!is_new_flag) {
                continue
    	    }
    	    var $title = $(document.createElement('div'))
    	    $title.html(this.texts[part_idx])
    	    $title.addClass('item_title')
    	    
    	    this.$messages.append($title)   
    
    	    if (part_idx != 'today') {
    	    	$el.expandCollapse({
        		    startHidden : cnt != size - 1,
        		    triggerElement : $title,
        		    updateText : false,
        		    expandDuration : "slow",
        		    collapseDuration : "slow"
                })
    	    }
    	    this.$messages.append($el)
    	    cnt++
    	}	
    },

    render_persons : function($node, online_list, add_class) {
    	var $el = $(document.createElement('div'))
    	for (var idx = 0; idx < online_list.length; idx++) {
    		var id = online_list[idx][0]
    		var id_parsed = online_list[idx][1]
    		var name = online_list[idx][2]
    		var add_html = ''
            if (add_class) {
            	add_html = add_class
            }
    		$el.append('<i class="person ' + add_html + '" id="' + id +'">' + this.render_name_html(id_parsed, name) + '</i>')
    		
    	}
    	$node.html($el)
    	$node.find('.person').click($.bind(this, function(el) {
    		var $node = $(el.target).parent()
    		if ($(el).hasClass('banned')) {
    			this.setbanned(el.id, 0);
    		} else {
    			this.setbanned(el.id, 1);
    		}
		}))
    },

    get_message_list : function(no_autocheck, url_load) {
    	if (!this.lock) {
    		this.lock = true
    	} else {
    		return
    	}

    	jQuery.ajax({
            type : 'get',
            url : url_load,
    	    dataType : 'json',
    	    data : { 'from' : this.last_id },
    	    success : $.bind(this, function(request, data) {
    	    	var has_new = this.last_id != data.last_id
                this.last_id = data.last_id
                
                this.render_persons(this.$onlines, data.online.not_banned, 'online')
    	    	this.render_persons(this.$onlines_banned, data.online.banned, 'online banned')
    	    	this.render(data.list)
                if (data.is_banned) {
                	this.$form.hide()
                } else {
                	this.$form.show()
                }
                if (has_new) {
            	   this.$messages.animate({
            	       scrollTop: this.$messages.scrollTop() + this.$messages.height()
            	   })
                }
           }),
           
	       complete : $.bind(this, function() {    
	           if (!no_autocheck) {
                   setTimeout( $.bind(this, function() { this.get_message_list(false, url_load) }), 5000)
    	   	   }
	           this.lock = false
    	   })
    	})
    },

	
    init : function($form, $messages, $onlines, $onlines_banned)
    {
    	this.$form = $form
    	this.$messages = $messages
    	this.$onlines = $onlines
    	this.$onlines_banned = $onlines_banned
     },
    
    run : function ($form, $messages, $onlines, $onlines_banned, url_load, url_post, url_offline) {
    	this.init($form, $messages, $onlines, $onlines_banned)
    	
    	this.get_message_list(false, url_load);
		
		this.$form.bind('submit', $.bind(this, function() {
			var $message = this.$form.find(':text')
	        if (!$message.val()) {
				return false
			}
			$message.attr('disabled', 'disabled')
	        jQuery.ajax({
	            type : 'post',
	            url : url_post,
	            dataType : 'json',
	            data: {'message' : $message.val()},
	            success : $.bind(this, function() {
	            	$message.val('')
	            	this.get_message_list(true, url_load)
	            }),
	            complete : function() {
	               $message.attr('disabled', '')
	            }
	        });
		    return false;
		}))
		$(window).bind('unload', function() {
			jQuery.ajax({
			   type : 'get',
	           url :url_offline
			})
		})
		
		
	}
		
}
