/**
 * Chat    
 * 
 * @author Alexey Yu Chuprina 
 * @version 1.0.0
 */

(function(){
	
var Chat = window.Chat = function(formId, windowId, loadUrl, refreshInterval) {
	if (!(this instanceof Chat)) return new Chat(formId, windowId, loadUrl, refreshInterval);
	
	// Construct
	var _this = this;

	this.form = jQuery('#' + formId);
	this.window = jQuery('#' + windowId);
	this.loadUrl = loadUrl;
	this.refreshInterval = refreshInterval;
	
	this.refresh();
	window.setInterval(function(){_this.refresh()}, refreshInterval);
	
	this.form
		.submit(function(){
			_this.submit();
			return false;
			})
		.keypress(function(event){
			if (event.ctrlKey && event.keyCode == 13) {
				_this.submit();
				return false;
			}
			});
}


Chat.prototype = {
	refresh: function() {
		var _this = this;
		jQuery.ajax({
			cache: false,
			type: 'get',
			url: this.loadUrl,
			success: function(data) {
				_this.window.html(data);
				_this.window[0].innerHTML = _this.window[0].innerHTML;}
			});
	},
	submit: function() {
		var _this = this;
		jQuery.ajax({
			cache: false,
			type: this.form.attr('method'),
			url: this.form.attr('action'),
			data: this.getFormData(),
			success: function() {_this.refresh()}
			});
		this.clearFormData();
	},
	submit2: function() {
		var _this = this;
		jQuery.ajax({
			cache: false,
			type: this.form.attr('method'),
			url: this.form.attr('action'),
			data: this.getFormData(),
			success: function(data) {_this.window.html(data)}
			});
		this.clearFormData();
	},
	getFormData: function() {
		var data = {};
		this.form.find('input, textarea, select').each(function(){
			data[this.name] = jQuery(this).val(); 
			});
		return data;
	},
	clearFormData: function() {
		this.form[0].reset();
	}
}
	


/**
 * Отправка данных формы #formId и обновление окна #windowId возвращаемыми данными    
 * 
 * @author 
 * @version 1.0.0
 */
	
var sendData = window.sendData = function(formId, windowId) {
	if (!(this instanceof sendData)) return new sendData(formId, windowId);
	
	// Construct
	var _this = this;

	this.form = jQuery('#' + formId);
	this.window = jQuery('#' + windowId);
	
	this.form
		.submit(function(){
			_this.submit2();
			return false;
			})
		.keypress(function(event){
			if (event.ctrlKey && event.keyCode == 13) {
				_this.submit2();
				return false;
			}
			});
}

sendData.prototype = Chat.prototype;
	
/**
 * Отправка данных формы #formId и обновление окна #windowId возвращаемыми данными в случае ошибки,
 * иначе отображение комментария в ленте сообщений
 * 
 * @author 
 * @version 1.0.0
 */
	
var sendComment = window.sendComment = function(formId, windowId) {
	if (!(this instanceof sendComment)) return new sendComment(formId, windowId);
	
	// Construct
	var _this = this;

	this.form = jQuery('#' + formId);
	this.window = jQuery('#' + windowId);
	this.parent_id = this.form[0].parent_id;
	this.site_msg_id = this.form[0].site_msg_id;
	
	this.form
		.submit(function(){ 
			_this.submit3();
			return false;
			})
		.keypress(function(event){
			if (event.ctrlKey && event.keyCode == 13) {
				_this.submit3();
				return false;
			}
			});
}

sendComment.prototype = Chat.prototype;

sendComment.prototype.updateTape = function(data) {
	var _this = this;
	var 
		msg_id = jQuery(_this.site_msg_id).val(),
		parent_id = jQuery(_this.parent_id).val(),
		ex = jQuery('#msg_' + msg_id + '_' +parent_id),
		newmsg = ex.clone();
	
	var level = parseInt(ex.attr('level')) + 1;
	
	newmsg.attr('id', 'msg_'+msg_id+'_'+data.id);
	newmsg.removeClass('indent_'+(level-1));
	newmsg.addClass('indent_'+level);
	newmsg.insertAfter('#msg_'+msg_id+"_"+parent_id); 
	newmsg.attr('level', level);
	
	jQuery('#msg_'+msg_id+'_'+data.id+' .title').html(data.user_name);
	jQuery('#msg_'+msg_id+'_'+data.id+' .info').html(data.info);
	jQuery('#msg_'+msg_id+'_'+data.id+' .date').html(data.date);
	jQuery('#msg_'+msg_id+'_'+data.id+' .reply a').click(function () { 
		getReplyForm(msg_id, data.id);
		})
		.attr('onclick', '');
	jQuery('#lj_chat #formadd').show();
	jQuery('#msg_tape').show();
	jQuery('#add_reply').hide();
	
	newmsg.find('.title')[0].inited = false;
	newmsg[0].opened = false;
	
	IdiotsTree.init();
	IdiotsTree.open(newmsg.attr('id'));
}

sendComment.prototype.submit3 = function() {
	var _this = this; 
	jQuery.ajax({
			cache: false,
			type: this.form.attr('method'),
			url: this.form.attr('action'),
			data: this.getFormData(),
			success: function(data) {
				res = _this.evalJSON(data);
				_this.window.html(res.error);
				if (res.error.length > 0)
					_this.window.show();
				else
				{
					_this.window.hide();
					_this.updateTape(res);
					_this.clearFormData();
				}
			}
	});
}

sendComment.prototype.evalJSON = function(json) {
	try {
		return eval('(' + json + ')');
	} catch (e) { }
	throw new SyntaxError('Badly formed JSON string');
}

/**
 * Отображение формы добавления комментария   
 * 
 * @author 
 * @version 1.0.0
 */
   
window.getReplyForm = function(id, comm_id) {
	var 
		title = jQuery('#msg_'+id+'_'+comm_id+' .title').html(),
		info = jQuery('#msg_'+id+'_'+comm_id+' .info').html(),
		date = jQuery('#msg_'+id+'_'+comm_id+' .date').html();
	
	jQuery('#site_msg_id').val(id);
	jQuery('#parent_id').val(comm_id);
	jQuery('#message .title').html(title);
	jQuery('#message .info').html(info);
	jQuery('#message .date').html(date);
	jQuery('#lj_chat #formadd').hide();
	jQuery('#msg_tape').hide();
	jQuery('#add_reply').show();
}

window.closeReplyForm = function()
{
	jQuery('#lj_chat #formadd').show();
	jQuery('#msg_tape').show();
	jQuery('#add_reply').hide();
}

/**
 * Обновление окна #windowId по таймеру    
 * 
 * @author 
 * @version 1.0.0
 */
	
var refreshWin = window.refreshWin = function(windowId, loadUrl, refreshInterval) {
	if (!(this instanceof refreshWin)) return new refreshWin(windowId, loadUrl, refreshInterval);
	
	// Construct
	var _this = this;
	this.updater = null;

	this.window = jQuery('#' + windowId);
	this.loadUrl = loadUrl;
	this.refreshInterval = refreshInterval;
	
	if (refreshInterval > 0)
		 this.startUpdate();
	else
		 this.refresh();
}

refreshWin.prototype = Chat.prototype;

refreshWin.prototype.startUpdate = function() {
	var _this = this;
	this.updater = window.setInterval(function(){_this.refresh()}, this.refreshInterval);
}

refreshWin.prototype.stopUpdate = function() {
	if (this.updater) window.clearInterval(this.updater);
}

// #########
window.ScrollChat = function(id, url, interval, msg) {
	var lastMsg = msg.split('\n');    
	var container = $('#' + id);
	
	$('.name', container).text(lastMsg[0] + ':');
	$('.message', container).text(lastMsg[1]);
	var moved = false;
	function setMsg(data) {        
		var msg = data.split('\n');
		if (msg[0] == lastMsg[0] && msg[1] == lastMsg[1]) return;
		
		container[0].innerHTML += '<span class="name">' + msg[0] + ':</span><span class="message">' + msg[1] + '</span>';
		
		lastMsg = msg;
		if (moved || container.height() > 75) {
			moved = true;
			move();
		}
	}
	
	var move = function() {
		move.first = $('.name:first, .message:first', container).css('position', 'relative');
		move.lim = move.first.eq(1).height() + 4;
		move.cur = 0;
		move.interval = setInterval(move.step, 100);
	}
	move.step = function() {
		container.css('top', -(move.cur += 2));
		if (move.cur >= move.lim) {
			clearInterval(move.interval);
			move.first.remove();
			container.css('top', 0);
		}
	}
	
	function loadMsg() {
		jQuery.ajax({ cache: false, type: 'get', url: url, success: setMsg});
	}
	
	$(function(){
		container.empty();
		container = $('<div style="position:absolute;">').appendTo(container);
		var t = lastMsg;
		lastMsg= [0,0];
		setMsg(t[0] + '\n' + t[1]);
		setInterval(loadMsg, interval);
	});
	
}
// #########

/**
 * Отправка данных формы #formId без обновления окна  
 * 
 * @author 
 * @version 1.0.0
 */
	
var simpleSendData = window.simpleSendData = function(formId) {
	if (!(this instanceof simpleSendData)) return new simpleSendData(formId);
	
	// Construct
	var _this = this;

	this.form = jQuery('#' + formId);
	
	this.form
		.submit(function(){
			_this.submit();
			return false;
			})
		.keypress(function(event){
			if (event.ctrlKey && event.keyCode == 13) {
				_this.submit();
				return false;
			}
			});
}

simpleSendData.prototype = Chat.prototype;

/*
jQuery(document).ready(function(){
	var e = jQuery('#textlinewrap');
	e.hover(
		function() {e.addClass('showall')},
		function() {e.removeClass('showall')}
	);
});
*/


// Вытягиваем последние блоки на думреди
window.fixBlockHeight = function() {	
	var 
	contentleft = jQuery('#contentleft'),
	contentcenter = jQuery('#contentcenter'),
	contentright = jQuery('#contentright'),
	s = [], m = 0, i = 0, h, f, ch;
	
	s.push(contentleft.height());
	s.push(contentcenter.height());
	s.push(contentright.height());
	
	for (i in s) {		
		if (s[i] > m) { m = s[i];}
	}
	
	
	
	function offset(e) {
		return (parseInt(e.css('border-top-width')) || 0) + (parseInt(e.css('border-bottom-width')) || 0)
			+ (parseInt(e.css('margin-top')) || 0) + (parseInt(e.css('margin-bottom')) || 0);
	}
	
	function check(e) {
		e = e.children(':last-child');
		ch = h = e.height();
		e.prevAll().each(function(){
			var t = jQuery(this);
			h += t.height() + offset(t);
		});
		if (h < m) e.height(m - h + ch - offset(e));
	}
	
	check(contentleft);
	check(contentcenter);
	check(contentright);
}


jQuery(document).ready(function(){
	if (not_fix_block_height) return;
	fixBlockHeight();
});
window.not_fix_block_height = false;


elems = new Array();
elems['contentleft'] = null;
elems['contentcenter'] = null;
elems['contentright'] = null;
childs = new Array();
childs['contentleft'] = null;
childs['contentcenter'] = null;
childs['contentright'] = null;

window.IdiotsTree = {
	init: function() {
		$('#msg_tape .blockitem:not(.indent_0) .title').each(function(){
			if (this.inited) return;
			this.inited = true;
			var self = $(this);
			self.hover(
				function(){ self.css('text-decoration', 'underline') },
				function(){ self.css('text-decoration', 'none') }
			);
			self[0].opened = false;
			self.click(function(){
				IdiotsTree.open(self.parent()[0].id);
			});
		})
		
	},
	open: function(id) {
		var self = $('#' + id);    
		if (self[0].opened) {
			self.find('.info, .date, .reply').hide()
			self.find('.title').css('background-image', 'url(/images/question_closed.gif)');
		} else {
			self.find('.info, .date, .reply').show()
			self.find('.title').css('background-image', 'url(/images/question_opened.gif)');
		}
		self[0].opened = !self[0].opened;
		el = IdiotsTree.getElemChild('contentleft');     el.css("height", ""); 
		ec = IdiotsTree.getElemChild('contentcenter');   ec.css("height", "");
		er = IdiotsTree.getElemChild('contentright');    er.css("height", "");
		fixBlockHeight();
	},
	getElem: function(name) {
		if (!(elems[name] instanceof jQuery))
			elems[name] = jQuery('#'+name);
		return elems[name];
			
	},
	getElemChild: function(name) {
		if (!(childs[name] instanceof jQuery))
		{
			var el = IdiotsTree.getElem(name);
			childs[name] = el.children(':last-child');
		}
		return childs[name];
	}
}

var CheckLength = window.CheckLength = {
    dataField: null,
    infoField: null,
    maxLenth: null,
    strLength: null,
    init: function(fieldId, infoId, maxLenth) {
        CheckLength.maxLenth = maxLenth;
        CheckLength.dataField = $('#' + fieldId);
        CheckLength.infoField = $('#' + infoId);
        var str = CheckLength.dataField.val();
        CheckLength.strLength = str.length;
        CheckLength.infoField.html(""+CheckLength.strLength+" "); 
            
        CheckLength.dataField.keydown(function (e) {
            if ((CheckLength.strLength >= CheckLength.maxLenth) && e.keyCode != 8 && 
                (e.keyCode != 45) && (e.keyCode != 46) && (e.keyCode < 33 || e.keyCode > 40))
                return false;
        });
        
        CheckLength.dataField.keyup(function (e) {
            var str = $(this).val();
            CheckLength.strLength = str.length;
            CheckLength.infoField.html(""+CheckLength.strLength+" "); 
            if ((CheckLength.strLength > CheckLength.maxLenth))
                CheckLength.infoField.addClass('errors');
            else CheckLength.infoField.removeClass('errors');
        });
    }    
}


})()


var page = 1;

function getData(url, container) {
	var container = $('#' + container);
	$.ajax({ cache: false, type: 'get',
		url: url,
		success: function(data) {
			container.html(data);
			container[0].innerHTML = container[0].innerHTML;
			IdiotsTree.init();
		}
	});
}

function getDataBySelect(select, container) {
	var s = $('#' + select);
	var c = $('#' + container);
	c.load(s.val());
	s.change(function(){
		c.load(s.val());
		c[0].innerHTML = c[0].innerHTML;
	});
}

function delMsg(type, id) {
	if (confirm('Запретить сообщение?'))
	{
		url = '/del_message/?type=' + type + '&msg_id=' + id;
		container = type + '_msg_' + id;
		getData(url, container);
	//    updt.refresh();
	}
}

function permitMsg(type, id) {
	url = '/permit_message/?type=' + type + '&msg_id=' + id;
	container = type + '_msg_' + id;
	getData(url, container);
//    updt.refresh();
}

function permitComment(type, id) {
	url = '/permit_comment/?type=' + type + '&msg_id=' + id;
	container = 'comment_' + id;
	getData(url, container);
//    updt.refresh();
}