String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

var Comments = {
	
	_item_id: null,
	_container: null,
		
	_: function(item_id, container, callback) {
		Comments._item_id = item_id;
		Comments._container = $(container);
		Comments._init(callback);
		
	},
	
	_init: function(callback) {

		// var xx = [{id:23,date:"Fri, 16 Jul 2010 14:38:38 +0400",user:{id:494,name:"svif"},msg:"Долго выбирал себе плеер, решил купить этот. Две недели пользования понял что этот плеер то что мне было нужно. Особенно мне понравилось то что есть запись на жесткий диск с моего старого видака. Сейчас практически все кассеты с домашними записями переписал. Поеду в отпуск покажу знакомым какие они были в молодости. Еще прикольная функция ТОРРЕНТ, с инета можно писать все что хочешь. СОВЕТУЮ. Хороший аппарат. Думаю тот кто купил такого же мнения."}];
		// alert(xx);
		// var x = [{id:14,date:"Thu, 01 Jul 2010 15:51:29 +0400",user:{id:4977,name:"sdsoft"},msg:"Не понятно какой это тюнер , в заголовке написанно DVB-C, в описании DVB-T. Как правильно?"}];
		// if(console) console.log(x);

		// alert("comments.get.start");

		new Ajax.Request("/products/comment.php?pid="+Comments._item_id, {
			method : "get",
			onException	: function(response, ex) { alert("Exception "+ex); },
			onFailure	: function(response) { alert("Fail"); },
			onSuccess	: function(response) {
				try {
					var list = eval('('+response.responseText+')');
					list.each(function(e) {
						Comments._append(e);
					});
					if(callback)callback();
				} catch(e) {
					if(console) {
						console.log(response.responseText);
						console.log(e);
					}
				}
			}
		});
	},
	
	_append: function(e) {

		var dt = e.date;
		try {
			e.ts = new Date(e.date);
			var d = e.ts.format('dd/mm/yy');
			var t = e.ts.format('hh:MM');
			dt = d+' в '+t;
		} catch(e) {
			if(console) console.log(e);
		}
		
		var lines = e.msg.split("\n");
		e.msg = "";
		for(var i=0; i<lines.length; i++)
			e.msg += lines[i]+"<br/>";
		
		var li = $(document.createElement('li'));
		li.innerHTML = '<small><b>'+e.user.name+'</b> сказал ('+dt+'):</small><p>'+e.msg+'</p>';
		Comments._container.appendChild(li);
		return li;
	},
	
	add: function(text, callback) {
		
		var params = $H({
				'pid':	Comments._item_id,
				'text':	text
			}).toQueryString();
			
		// console.log("add comment item_id=%d", Comments._item_id);
		// console.log("params: %s", params);
		
		if(!Comments._item_id) return;

		new Ajax.Request("/products/comment.php", {
			method : "post",
			parameters: params,
			onSuccess : function(response) {
				var status = eval('('+response.responseText+')');
				if(status&&callback) callback(status);
			},
			onFailure: function(response) {
				// console.log("error. %s", response);
			}
		});
	}
		
};


