var liveChat = {"url": "/ajax/livechat/index.php"};

liveChat.ajaxDispatcher = function(jsonArr){
	if (!jsonArr) return;
	for (var i=0; i<jsonArr.length; i++){
		json = jsonArr[i];
		switch (json.action){
			case 'login':
				liveChat.sessionId = json.session_id
				liveChat.managerName = json.managername || "Менеджер Амиком";
				liveChat.startChat();
				break;
			case 'message':
				liveChat.logEntry(json.message, "in");
				liveChat.lastTimestamp = json.timestamp;
				break;
			case 'logoff':
				liveChat.logEntry("", "notice", "Конец чата");
				liveChat.loggedIn = false;
				break;
			case 'debug':
				alert(json.message);
				break;
		};
		switch (json.error){
			case "loginerror":
				liveChat.showLoginError("Извините, сервис временно недоступен");
				break;
			case "nomanager":
				liveChat.showLoginError("К сожалению, ни один из менеджеров не может Вам ответить.<br />Пожалуйста, попробуйте позже");
				break;
		}
	};
}

liveChat.disconnect = function(str){
	if (liveChat.loggedIn){
		jQuery.ajax({
			"data": {"action": "disconnect", "session_id": liveChat.sessionId},
			"dataType": "json",
			"type": "POST",
			"url": liveChat.url
		});
		liveChat.loggedIn = false;
	};
}

liveChat.showLoginError = function(str){
	$owner = liveChat.$owner;
	$owner.removeClass("js-livechat-spinner").addClass("js-livechat-error");
	$owner.html(str);
};

liveChat.cometQueue = function(){
	if (!liveChat.loggedIn) return;
	data = {"action": "query", "session_id": liveChat.sessionId};
	if (liveChat.lastTimestamp){
		data.timestamp = liveChat.lastTimestamp;
	};
	jQuery.ajax({
		"data": data,
		"dataType": "json",
		/* error(XMLHttpRequest, textStatus, errorThrown) */
		"success": liveChat.ajaxDispatcher,
		"complete": function(){setTimeout(function(){liveChat.cometQueue()}, 0)},
		"type": "POST",
		"url": liveChat.url
	});
};

liveChat.logEntry = function(text, type, title){
	/* type = in/out/notice */
	var messageLog = liveChat.messageLog;
	var entry = document.createElement("p");
	if (type == "in"){
		entry.className = "js-livechat-type-in";
	} else if (type == "out"){
		entry.className = "js-livechat-type-out";
	};
	var timestamp = document.createElement("span");
	timestamp.className = "js-livechat-log-timestamp";
	var now = new Date();
	timestamp.appendChild(document.createTextNode(now.getHours() + ":" + now.getMinutes().toString().replace(/^(.)$/, "0$1")  + " "));
	entry.appendChild(timestamp);
	var name = document.createElement("span");
	name.className = "js-livechat-log-name";
	if (title) {
		name.appendChild(document.createTextNode(title))
	}
	if (type == "in"){
		name.appendChild(document.createTextNode(liveChat.managerName))
	} else if (type == "out"){
		name.appendChild(document.createTextNode(liveChat.loginName))
	};
	entry.appendChild(name);
	if (text){
		entry.appendChild(document.createElement("br"));
		var textChunks = text.split(/(\r|\n)+/g);
		var firstLine = true;
		for (var i=0; i<textChunks.length; i++){
			if (textChunks[i] == "") continue;
			if (!firstLine){
				entry.appendChild(document.createElement("br"));
			} else {
				firstLine = false;
			};
			entry.appendChild(document.createTextNode(textChunks[i]));
		};
	};
	messageLog.appendChild(entry);
	messageLog.scrollTop = messageLog.scrollHeight;
}

liveChat.sendMessage = function(text){
	if (!liveChat.loggedIn) return;
	jQuery.ajax({
		"data": {"action": "message", "message": text, "session_id": liveChat.sessionId},
		"dataType": "json",
		"success": liveChat.ajaxDispatcher,
		"type": "POST",
		"url": liveChat.url
	});
	liveChat.logEntry(text, "out");
}

liveChat.startChat = function(name){
	name = liveChat.managerName;
	$owner = liveChat.$owner;
	$(".tpl-lightbox").animate({'width': 808});
	liveChat.$owner.animate({'width': 800, 'height': 400});
	$owner.removeClass("js-livechat-spinner");
	$owner.css({"position": "relative"});
	var owner = $owner.get(0);
	liveChat.messageLog = document.createElement("div");
	liveChat.messageLog.className = 'js-livechat-messagelog';
	owner.appendChild(liveChat.messageLog);
	var form = document.createElement("form");
	form.action = "javascript://";
	form.onsubmit = function(){
		if (liveChat.field.value == "") return;
		liveChat.sendMessage(liveChat.field.value);
		liveChat.field.value = "";
	}
	form.className = 'js-livechat-messageform';
	owner.appendChild(form);
	liveChat.field = document.createElement("textarea");
	liveChat.field.className = 'js-livechat-field';
	$(liveChat.field).bind("keypress", function(e){
		window.e = e;
		if ((e.keyCode == 0x0A || e.keyCode == 0x0D) && (e.ctrlKey || e.metaKey)){
			form.onsubmit();
			return false;
		};
	});
	
	
	form.appendChild(liveChat.field);
	liveChat.field.focus();
	var submitGroup = document.createElement("div");
	submitGroup.className = 'js-livechat-submit-group';
	form.appendChild(submitGroup);
	liveChat.submit = document.createElement("button");
	try {
		liveChat.submit.type = "submit";
	} catch (e){ /* focking IE */ };
	liveChat.submit.className = 'js-livechat-submit';
	liveChat.submit.innerHTML = 'Отправить';
	submitGroup.appendChild(liveChat.submit);
	var submitHint = document.createElement("small");
	submitHint.className = 'js-livechat-submit-hint';
	submitHint.innerHTML = 'Ctrl-Enter';
	submitGroup.appendChild(submitHint);

	var manInfo = document.createElement("div");
	manInfo.className = "js-livechat-manager-group";
	owner.appendChild(manInfo);
	
	var avatar = document.createElement("img");
	avatar.src = "/assets/templates/aminew/img/support.png";
	avatar.className = "js-livechat-manager-avatar";
	manInfo.appendChild(avatar);
	
	var manName = document.createElement("small");
	manName.className = 'js-livechat-manager-name';
	manName.appendChild(document.createTextNode(name));
	manInfo.appendChild(manName);
	
	liveChat.loggedIn = true;
	liveChat.logEntry("Вас приветствует Амиком", "notice", "Начало чата");
	
	$(lightbox.lbcontainer.sheld).unbind();
	$(lightbox.lbcontainer).bind("lightbox-close", function(){
		liveChat.disconnect();
	});
	
	liveChat.cometQueue();
}

$(".js-livechat-start").live("click", function(e){
	var input = $("input", this.parentNode).get(0);
	if (!input) return false;
	if (!input.value || !input.jsChanged){
		input.focus();
		return false;
	};
	var loginName = input.value;
	liveChat.loginName = loginName;
	var $owner = $(this).closest("form").parent();
	liveChat.$owner = $owner;
	$owner.height($owner.height());
	$owner.html("");
	$owner.addClass("js-livechat-spinner");
	
	jQuery.ajax({
		"data": {"action": "login", "name": loginName},
		"dataType": "json",
		/* error(XMLHttpRequest, textStatus, errorThrown) */
		"success": liveChat.ajaxDispatcher,
		"type": "POST",
		"url": liveChat.url
	});
	
	var $input = $(".js-livechat-container .js-livechat-login input");
	$input.addClass(".js-changed").val(loginName);
	($input.get(0)||{}).jsChanged = true;
	
	return false;
})
