﻿// ######## Init Chat  

  function showChat(baseUrl, currentUserId, currentGuestId, remoteUserId, remoteGuestId, showConfirm)
  {
//	alert('showChat(' + baseUrl + ',' + currentUserId + ',' + currentGuestId + ',' + remoteUserId + ',' + remoteGuestId + ',' + showConfirm + ')');
    if (remoteUserId == currentUserId)
    {
        alert('Вы не можете консультировать сами себя');
        return;
    }
    
    if ((currentUserId == 0) && (showConfirm))
    {
        if (!confirm('Поскольку Вы не зарегистрированы, Вы не сможете прочитать ответ после того как уйдете с сайта.\n'
            + 'Начать общение с экспертом без регистрации?'))
        {
            return;
        }
    }

    var wurl = baseUrl + '/chat?chatRemoteID=' + remoteUserId + '&remoteGuestId=' + remoteGuestId + '&nocache=' + ((new Date()).getTime());
    window.open(wurl, 'chat_'+remoteUserId+'_'+remoteGuestId, 'width=620,height=590,resizable=no,toolbar=no,location=no,scrollbars=no,menubar=no');
  }

  function showCall(baseUrl, currentUserId, remoteUserId)
  {
/*  
    if (remoteUserId == currentUserId)
    {
        alert('Вы не можете звонить сами себе');
        return;
    }
*/
/*    
    if (currentUserId == 0)
    {
        alert('Для того что бы звонить эксперту необходимо зарегистрироваться');
        return;
    }
*/
    var wurl = baseUrl + '/chat/call?chatRemoteID=' + remoteUserId + '&nocache=' + ((new Date()).getTime());
    window.open(wurl, 'chat_'+remoteUserId, 'width=410,height=330,resizable=no,toolbar=no,location=no,scrollbars=no,menubar=no');
  }


// ######## Messages/History

  function genMessageText(msg)
  {
    var msgText = '', nameclass = '', nametitle = '';

//    alert(msg['record_is_expert']);
    if (msg['record_is_expert'])
    {
        nameclass = 'chatnameexpert';
        nametitle = 'Эксперт';
    }
    else
    {
        nameclass = 'chatnameuser';
        nametitle = 'Клиент';
    }
  
    var text = textAreaFormat(msg['record_text_str']);
    if (msg['record_type'] > 0)
    {
        text = '<i>' + text + '</i>';
    }
    msgText = //'<div class="chatnametitmedate">' + nametitle + '</div>' + 
		'<div class="' + nameclass + '">' + msg['name_str'] + '</div>'
        + '<div class="chatdate">' + msg['record_time_str'] + '</div><br>'
        + '<div class="chatmsg">' + text + '</div>';   
        
    return msgText;
  }
  
//  var n = 0;
  
  function chatUpdateHistory(jsonObj)
  {
    var res; 
    var sound = false;
//    setElementText('debug', ++n);
    
//    alert(remoteStatus + ' -> ' + jsonObj['Remote']['online']);
    sound = setRemoteStatus(jsonObj['Remote']['online']);
    
    updateFinance(jsonObj);
    
    records = jsonObj['records'];
    if (records.length > 0)
    {
        currText = getElementText('msg');
        if ((jsonObj['lastId'] != 0) || (jsonObj['maxCnt'] != 0))
        {
            currText = getElementText('msg');
        }
        else
        {
            currText = '';
            chatLastMsgId = 0;
        }
        debug('currText: ' + currText);
        
        newText = '';
        for (i = 0 ; i < records.length ; i++)
        {
            if (records[i]['record_id'] > chatLastMsgId)
            { 
                newText = newText + genMessageText(records[i]);
            }    
        }
        debug('newText: ' + newText);
        
        setElementText('msg', newText + currText);
        
//        var intY = document.getElementById("msg").scrollTop;
//        alert(intY);
        document.getElementById("msg").scrollTop = 0;
    
        chatLastMsgId = records[0]['record_id'];
        debug('chatLastMsgId: ' + chatLastMsgId);
        
        if ((markable_canbe) && (!markable))
        {
//			alert(jsonObj['Remote']['msg_cnt'] + ":" + markable_min);
			if (jsonObj['Remote']['msg_cnt'] >= markable_min)
			{
			    if ((chatBlocked!=1) && (chatBlocked!=2))
			    {
					markable = true;
//  				alert('set mark');
					showElement("markable_no", false);
					showElement("markable_yes", true);
			    }
			}
        }
        

        if (jsonObj['remote_cnt'] > 0)
        {
            sound = true;
        }
        
        res = true;
    }
    else
    {
        res = false;
    }
    
    if (sound)
    {
        EvalSoundMsg();
    }
    return res;
  }
    
  function doSendMsg()
  {
    if (chatConsultId == null)
    {
        return false; //chat is not loaded yet
    }
    
    if (chatBlocked > 0)
    {
        var msg = 'Вы не можете отправлять сообщения Вашему собеседнику\n';
        if (chatBlocked == 2)
        {
            msg = 'Время бесплатной консультации истекло.\n'
                + 'Для того чтобы продолжить общение пополните счет и оплатите консультацию';
        }
        else
        if (chatBlocked == 4)
        {
            msg = 'Услуги данного эксперта - платные. Для того, чтобы получить консультацию,\n'
                + 'пополните счет на любую сумму в разделе Мой профиль - Счет (15 пособов оплаты).\n'
                + 'Окончательное решение об оплате консультации Вы можете принять, пообщавшись с экспертом.'
        }
        else
        {
            msg += BLOCKED_MSG[chatBlocked].replace('<br>', '\n');
        }
        alert(msg);
        return false;
    }
    var myform = document.forms['myform'];
    var val = myform['record_text'].value;
//    alert('doSendMsg: ' + val);
    if (val != '')
    {
        if (val.length > 10000)
        {
            alert('Длина сообщения не должна превышать 10000 символов.');
        }
        else 
        {
//			alert('sendMsg: ' + val)
            sendMsg(val);
            myform['record_text'].value = '';
        }
    }
    else
    {
//        alert('Введите сообщение');
    }
    return false;
  }
  
  function doUpdateAllHistory()
  {
    chatLastMsgId = 0;
    chatMaxCnt = 0;
//    setElementText('msg', '');
    checkChatMesages();
    return false;
  }
  
  
  // ######## Remote User Status
  function setRemoteStatus(status)
  {
    var elementText = null;
    var res = false;
    if (status != remoteStatus)
    {
        var elementText;
        if (status == 3)
        {
            elementText = '<img src="' + chatBaseUrl + '/public/images/online.gif" width="61" height="19" alt="" title="Ваш собеседник находится на сайте прямо сейчас">';
            res = true;
        }
        else
        {
            elementText = '<img src="' + chatBaseUrl + '/public/images/offline.gif" width="61" height="19" alt="" title="Вашего собеседника сейчас нет на сайте">';
        }
        setElementText('chatuserstatus', elementText);
        remoteStatus = status;
    }
    return res;
  }



// ######## Rate (comment) chat
function doCloseChatFunk()
{
    var myform = document.forms['myform'];
    var rate = '';
    if (myform['rate'] != null)
    {
        rate = myform['rate'].value;
    }
	window.opener.onCloseChatFunk(markable, chatBaseUrl, currentUserId, remoteUserId, rate);
}

function onCloseChatFunk(_markable, chatBaseUrl, currentUserId, remoteUserId, rate)
{
    setMsgTimerIfNo();
    if (_markable)
    {
		window.location = chatBaseUrl + '/consultation/rate?userId=' + currentUserId + '&expertId=' + remoteUserId + '&rate=' + rate;
	}
}

// ######## Payments
function updateFinance(jsonObj)
{
	var current = jsonObj.Current;
	var remote = jsonObj.Remote;
	
	if (currentUtype == 2)
	{
		setElementText('chat_remote_total', '<b>' + remote.total + '</b>' + ' руб.');
		setElementText('chat_remote_balance', '<b>' + remote.balance + '</b>' + ' руб.');
	}
	
	if (remoteUtype == 2)
	{
		setElementText('chat_current_total', '<b>' + current.total + '</b>' + ' руб.');
	}
    setElementText('chat_current_balance', '<b>' + current.balance + '</b>' + ' руб.');
    
    if (jsonObj.blocked > 0)
    {
        if (chatBlocked == 0)
        {
            chatBlocked = jsonObj.blocked;
            setElementText('chat_pay_status', '<b>' + BLOCKED_MSG[chatBlocked] + '</b>');
        }
    }
    else if (jsonObj.blocked == 0)
    {
        if (chatBlocked > 0)
        {
            chatBlocked = jsonObj.blocked;
            setElementText('chat_pay_status', '<b>Вы можете продолжить общение</b>');
        }
    }

    if (chatLimited)
    {
        setElementText('chat_msg_left', '<font class="textSmallRed">' + jsonObj.msg_left + '</font>');
    }
}
