KolizeoPushEvent = {
	'new_order': function(data) {
		var body = data.body;
		var orders_block = $('#new_orders_block');
		if(body){
			var orderList = orders_block.find('.newordera');
			var cnt = orderList.children().length;
			var elem = $("<a href='"+body.url+"'>"+body.text+"</a>");
			++cnt;
			orders_block.find('.neworder').attr('current', '0');
			orders_block.find('.neworder').attr('countnew', cnt);
			orders_block.find('.newcnt').html(cnt);
			orders_block.find('.newcntdeclension').html(Kolizeo.declension(cnt, ['заказ', 'заказа', 'заказов']));
			
			if(cnt > 1){
				orders_block.find('.nextnew').addClass('r_a').removeClass('r_t');
				orderList.children().hide();
			} else {
				orders_block.find('.nextnew').addClass('r_t').removeClass('r_a');
			}
			orderList.prepend(elem);
			orders_block.find('.prevnew').addClass('l_t').removeClass('l_a');
			orders_block.show();
		}
		return true;
	}
};

KolizeoChat = {
	warn_statuses: {waiting_start: true, start: true, balance_empty: true, no_activity: true},
	'said': function(data, self) {
		if (Kolizeo.chat_cost_id && Kolizeo.chat_cost_id == data.body.chat.id) {
			this.printMessage(data.body);
			self = self || 0;
			if (!self) {
				var parData = {'id':Kolizeo.chat_cost_id, 'msgid':data.body.msg.id};
				$.post('/profile/chat/message-received', parData);
			}
		}
		var now = new Date();
		ChatTimer.time.last_active = now.getTime();
		ChatTimer.reinit(data.body.time_cost.lost);
		return true;
	},
	
	'created': function(data) {
		return KolizeoPushEvent.new_order(data);
	},
	
	'terminated': function(data) {
		ChatTimer.stop();
		$('.button_close').html('Разговор завершен.');
		var msgContainer = $('#chat_msg_container');
		if (msgContainer.length && Kolizeo.chat_cost_id && Kolizeo.chat_cost_id == data.body.chat.id) {
			var msg = data.body.msg;
			var url = data.body.redirect_url || '/';
			if(data.body.status){
				KolizeoChat.setStatus(data.body.status);
			}
			if(data.body.chat){
				KolizeoChat.setTimes(data.body.chat);
			}
			if (msg.text) {
				oPopup.show({
					'caption': 'Чат завершен',
					'html':'<div class="f14">'+ msg.text + '</div>', 
					'buttons':[ {'text':'OK', 'handler': function(){
						//window.location = url;
						KolizeoChat.actionComment(url);
						return false;
					}}],
					'z_index': 10000,
					'blockSite': true});
			} else {
				KolizeoChat.actionComment(url);
				//window.location = url;
			}
			return false;
		} else {
			return true;
		}
	},
	
	'actionComment': function(url){
		$('#chat_id').attr('chat_id',url);
		$('#comment_form').show();
		$('#comment_form_before').hide();
		$('.warning_chat').show();
		$('.chat_warning').hide();
		oPopup.closeAll();
	},
	
	'runTimer': function(data) {
		var time_lost = data.body.time_lost;
		this.printMessage(data.body);
		if(data.body.status){
			this.setStatus(data.body.status);
		}
		ChatTimer.start();
		return true;
	},
	
	
	'printMessage': function(body) {
		var user = body.user;
		var msg = body.msg;
		var sess = body.sess;
		var msgContainer = $('#chat_msg_container');
		if (msgContainer.length) {
			var is_consultant = Kolizeo.user.is_consultant||false;
			var messageHtml = '';
			if (!is_consultant) {
				if(user.is_consultant == 0){
					var cls = "chat_g";
				}else{
					var cls = "chat_b";
				}
				messageHtml = '<div class="diary_item forp"><div class="'+ cls +'"><table width="597" cellspacing="0" cellpadding="0" border="0">'+
'<tr><td class="lt_b f0">&nbsp;</td><td class="f0">&nbsp;</td><td class="rt_b f0">&nbsp;</td></tr>'+
'<tr><td class="f0">&nbsp;</td><td><div style="padding:9px 5px">'+
'<div style="padding-bottom:3px"><b>' + user.name + ',</b><i>' + msg.dt + '</i></div>'+
'<div class="f13"><i>' + msg.text + '</i></div>'+
'</div></td><td class="f0">&nbsp;</td></tr>'+
'<tr><td class="lb_b f0">&nbsp;</td><td class="f0">&nbsp;</td><td class="rb_b f0">&nbsp;</td></tr>'+
'</table></div></div>';
			} else {
				messageHtml = '<div class="messages_item"><div class="messages_item_inner">'+
				'<div class="messages_title"><span class="bondi">'+user.name+'</span><br/><span class="grey">'+msg.dt+'</span></div>'+ 
				'<div class="messages_text" style="word-wrap:break-word;">'+msg.text+'</div></div></div><br/>';
			}
			msgContainer.prepend(messageHtml);
			$('#paneScroll').jScrollPane({arrowSize:18, showArrows:true});
		}
		return true;
	},
	
	'say': function() {
		var msg = $('#message_body');
		if(msg.val()==msg.attr("default")){
			return false;
		}

		if (!this.check_length(msg.val(), 1000)) {
			return false;
		}

		var chat_cost_id = $('#chat_cost_id').val();
		var sendData = {'message':msg.val(), 'chat_cost_id':chat_cost_id};
		msg.val('');
		$.post('/profile/chat/say/', sendData, function(data) {

			var chat = $('#chat_msg');
			if(data.errors) {
				var error = data.errors.pop();
				var errorMsg = error.msg || '';
				if (error.code == 302) {
					KolizeoChat.actionComment('/');
				} else {
					oPopup.alert(errorMsg);
				}
			} else if(data.result.msg) {
				KolizeoChat.said(data.result.msg, 1);
			}
		}, 'json');
		return false;
	},
	
	'create': function(id, no_photo, chat_sid) {
		var sendData = {'id': id};
		if (no_photo) {
			sendData['no_photo'] = no_photo;
		}
		if (chat_sid) {
			sendData['chat_sid'] = chat_sid;
		}
		if(!chat_sid){
			//oPopup.show({width:510, html:'<div style="padding:20px" align="center"><img src="/images/ajax32.gif" /></div>'});
		}
		$("#button_chat_start").hide();
		$("#chat_loading").show();
		$.post('/profile/chat/create/', sendData, function(data){
			$("#button_chat_start").show();
			$("#chat_loading").hide();
			if(data.result) {
				if (data.result.url) {
					window.location = data.result.url;
				}
				if(data.result && data.result.chat && data.result.chat.status){
					KolizeoChat.setStatus(data.result.chat.status);
					window.location = window.location.href;
				}
				if(data.result.order){
					Kolizeo.page_order = data.result.order.id;
				}
			} else if (data.errors) {
				var error = data.errors.pop();
				var errorMsg = error.msg || '';
				var errorCode = error.code || '';
				var url = window.location.pathname || '';
				if (errorCode == 309) {
					oPopup.show({
						action: "/profile/index/upload-avatar",
						width:510,
						html : "<div class='f14'>РџРµСЂРµРґ РЅР°С‡Р°Р»РѕРј С‡Р°С‚Р° Р·Р°РіСЂСѓР·РёС‚Рµ, РїРѕР¶Р°Р»СѓР№СЃС‚Р°, С„РѕС‚РѕРіСЂР°С„РёСЋ, С‡С‚РѕР±С‹ РєРѕРЅСЃСѓР»СЊС‚Р°РЅС‚ РјРѕРі СЂР°Р±РѕС‚Р°С‚СЊ СЌС„С„РµРєС‚РёРІРЅРµРµ.</div><br><input type='file' name='avatar' /><input type='hidden' name='url' value='"+url+"/#chat'/>",
						buttons: [{text:'Р—Р°РєР°С‡Р°С‚СЊ С„РѕС‚Рѕ', handler: function(){
							this.popup.submit();
							return false;
						}},{text:'РќР°С‡Р°С‚СЊ С‡Р°С‚ Р±РµР· С„РѕС‚Рѕ', handler: function(){
							KolizeoChat.create(id, 1);
							return false;
						}}]
					});
				} else if (errorCode && errorCode=='205'){
					oPopup.alert_with_block(errorMsg,{width:510, buttons: [{text:'РџРѕРїРѕР»РЅРёС‚СЊ СЃС‡РµС‚', handler: function(){
						return KolizeoChat.pay();
					}}]});
				} else {
					oPopup.alert_with_block(errorMsg);
				}	
			}
		}, 'json');
		return false;
	},

	'terminate': function(time_over, silent) {
		ChatTimer.stop();
		var chat_cost_id = $('#chat_cost_id').val();
		var sendData = {'chat_cost_id':chat_cost_id};
		if(time_over) sendData['time_over']='1';
		if(silent) sendData['silent']='1';
		//С„РѕСЂРјР° РґР»СЏ РѕС†РµРЅРєРё РїРѕР»СЊР·РѕРІР°С‚РµР»СЏ Рё РѕСЃС‚Р°РІРёС‚СЊ РєРѕРјРјРµРЅС‚Р°СЂРёР№
		$.post('/profile/chat/terminate/', sendData, function(data){
			//window.location = '/profile/chat/';
		});
		ChatTimer.stop();
		return false;
	},
	
	'check_length': function(msgText, length) {
		if (msgText.length > length) {
			oPopup.alert('РґР»РёРЅР° СЃРѕРѕР±С‰РµРЅРёСЏ РЅРµ РјРѕР¶РµС‚ РїСЂРµРІС‹С€Р°С‚СЊ '+length+' СЃРёРјРІРѕР»РѕРІ');
			return false;
		}
		if (msgText.length == 0) {
			oPopup.alert('РЎРѕРѕР±С‰РµРЅРёРµ РЅРµ РјРѕР¶РµС‚ Р±С‹С‚СЊ РїСѓСЃС‚С‹Рј');
			return false;
		}
		
		return true;
	},

	'setStatus': function(status){
		$(".warning_chat_inner").html(status.title);
		$(".to_users").hide();
		$(".warning_chat_inner2").html(status.comment);
		switch(status.key){
			case "waiting_consultant":
				$("#button_chat_start").hide();
				$("#button_chat_stop").show();
				var first_def = $('#message_body').attr('default');
				var first_val = $('#message_body').val();
				if(first_def == first_val){
					$('#message_body').attr('default','');
					$('#message_body').val('');
				}else{
					$('#message_body').attr('default','');
				}
				break;
			case "user_end":
				$(".user_end").show();
				break;
		}
		ChatTimer.warning = this.warn_statuses[status.key];
	},

	'setTimes': function(chat){
		if(chat.time_till!=''){
			$(".table_time").show();
			$(".time_till").html(chat.time_till);
			$(".time_start").html(chat.time_start);
			$(".time_end").html(chat.time_end);
		}
	},

	pay: function(){
		Cookie.set("backurl", "/consultant/index/id/" + Consultant.id +"#chat", "/");
		window.location = "/profile/wallet/?from_consultant=" + Consultant.id +"&chat=1";
		return false;
	}

};

ChatTimer = {
	time: null,
	timer: null,
	warning: false,
	warning_timer: null,
	init: function(){
		this.time = {in_chat : eval($("#hid_time_in_chat").val()), last: eval($("#hid_time_last").val())};
		$("#time_on_chat").html(this.formatTime(this.time.in_chat));
		$("#time_chat_last").html(this.formatTime(this.time.last));
		if($("#last_time_started").val()=="1"){
			this.start();
		}
		this.warning_timer = setInterval("ChatTimer.warning_step()", 500);
		ChatTimer.warning = KolizeoChat.warn_statuses[KolizeoChat.status];
	},
	warning_step: function(){
		var j = $("#status_warning");
		var g = $("#warning_status");
		if(this.warning){
			if(j.hasClass("weak_warning")) j.removeClass("weak_warning"); else j.addClass("weak_warning");
			if(g.hasClass("warning_sel")) g.removeClass("warning_sel"); else g.addClass("warning_sel");
		} else {
			j.removeClass("weak_warning");
			g.removeClass("warning_sel");
		}
	},
	reinit: function(last_time){
		var now = new Date();
		var delta = Math.floor((now.getTime() - this.time.start_time)/1000);
		this.time.last = delta + last_time;
	},
	start: function(){
		var now = new Date();
		this.time.start_time = now.getTime();
		this.time.last_active = now.getTime();
		this.timer = setInterval("ChatTimer.step()", 200);
		$("#button_chat_start").hide();
		$("#button_chat_stop").show();
	},
	step: function(){
		var now = new Date();
		var delta = Math.floor((now.getTime() - this.time.start_time)/1000);
		var in_chat = this.time.in_chat + delta;
		var last = this.time.last - delta;
		$("#time_on_chat").html(this.formatTime(in_chat));
		var jLast = $("#time_chat_last");
		jLast.html(this.formatTime(last));
		if(last>120) jLast.removeClass("purple");
			else jLast.addClass("purple");
		if(last<=0){
			KolizeoChat.terminate(1);
		}
		var silence_time = Math.floor((now.getTime() - this.time.last_active)/1000);
		if(silence_time > 300){
			KolizeoChat.terminate(null, 1);
		}
	},
	formatTime: function(sec){
		var hours = Math.floor(sec / 3600);
		sec -= hours*3600;
		var mins = Math.floor(sec / 60);
		sec -= mins*60;
		return (this.dig2(hours) + ":" + this.dig2(mins) + ":" + this.dig2(sec));
	},
	
	dig2: function(i){
		var s = i + "";
		if(s.length>1) return s;
		return "0" + s;
	},
	stop: function(){
		clearTimeout(this.timer);
		//$("#button_chat_start").show();
		$("#button_chat_stop").hide();
	}
};

$(function(){ ChatTimer.init(); });



KolizeoSmsChat = {
	obj: null,
	
	'said': function(data) {
		if (Kolizeo.chat_sid && Kolizeo.chat_sid == data.body.sess.id) {
			Kolizeo.reload();
		}
//		var chat_sid = $('#chat_sid').val();
//		if (data.body.sess.id == chat_sid) {
//			KolizeoChat.printMessage(data.body);
//		}
		return true;
	},
	
	'say':function(reply_id, chat_sid, obj, sess_first_msg_id) {
		KolizeoSmsChat.obj = obj;
		var msg = $(obj).parents('.sms_answer').find('.message_chat');
		
		if (!KolizeoChat.check_length(msg.val(), 140)) {
			return false;
		}
		
//		var reply_id = $('#message_id').val();
//		var chat_sid = $('#chat_sid').val();
		if (!sess_first_msg_id) sess_first_msg_id = 0;
		var sendData = {'message':msg.val(), 'chat_sid':chat_sid, 'message_id': reply_id, 'sess_first_msg_id': sess_first_msg_id};
		$(obj).parents('.sms_answer').hide();
		var t = $(obj).parents('.sms_table').find('.gtf');
		$(obj).parents('.sms_table').find('.gtf').show();
		$.post('/cabinet/sms-chat/say/', sendData, function(data) {
			msg.val('');
			$('#sms_char_count-'+reply_id).html('0');
			var chat = $('#chat_msg');
			if(data.errors) {
				$('#answer-'+reply_id).show();
				$(KolizeoSmsChat.obj).parents('.sms_table').find('.gtf').hide();
				oPopup.alert(data.errors);
			}else{
				Kolizeo.reload();
			}
		}, 'json');
		return false;
	}
};

/**
 * РїРѕР»СѓС‡Р°РµС‚ РґР°РЅРЅС‹Рµ РѕС‚ СЃРµСЂРІРµСЂР°
 */
 
Router = {};

Pusher = {
	'listen_url': null,
	'listen_handler': null,
	'init': function(psid){
		this.listen_url = psid ? '/act/?id='+psid : null;
	},
	'listen': function(result, error) {
		var pusher = this;
		if (this.listen_url) {
			this.listen_handler = $.ajax({
				'url': this.listen_url,
				'data': '',
				'ifModified': true,
				'dataType': 'json',
				'success': function(data) {
					result(data);
				},
				'error': function(xhr, errText, ex) {
					error(xhr, errText, ex);
			    }
			});
		}
	}
};
	

/**
 * РјР°СЂС€СЂСѓС‚РёР·Р°С‚РѕСЂ, РЅР° РѕСЃРЅРѕРІРµ РґР°РЅРЅС‹С… РїРѕР»СѓС‡РµРЅРЅС‹С… РѕС‚ СЃРµСЂРІРµСЂР°
 */
Router = {
	'is_started': false,
	'push': Pusher,
	'modules': {
		'Chat': KolizeoChat,
		'pushEvent': KolizeoPushEvent,
		'SmsChat': KolizeoSmsChat
	},
	
	'init': function() {
		if (!this.is_started) {
			psid = Kolizeo.user.sess_token;
			this.push.init(psid);
			this.is_started = true;
			$(window).unload(function() {
				if (Pusher.listen_handler) {
					Pusher.listen_handler.abort();
				}
			});
		}
	},
		
	'run': function() {
//		return false;
		this.init();
		var router = this;
		this.push.listen(
			function(data) {
				module = router.modules[data.module] || {};
				if(!module[data.action] || module[data.action](data)) {
					router.run();
				}
			}, 
			function(xhr, errText, ex) {
				if (errText == 'timeout' || errText == 'notmodified' ) {
					router.run();
				}
			}
		);
	}
};


