
function toggleSubmitButton(type) {
	var suggestValid = true;
	var suggestPresent = false;
	var messageValid = false;
	var hasStopWord = false;

	var messageType = $('input[name=message_type]').val();
	if (messageType) {
		suggestPresent = true;
		if (messageType === "offer_prd" && !$('#request-prd-id').val()) {
			suggestValid = false;
    }
    /*
    } else if (messageType === "offer_custom_prd" && validateCustomDodji !== undefined && !validateCustomDodji()) {
			suggestValid = false;
		}
    */
	}

	var emptyExtraInputCount = $('input[name="customExtraName[]"]').filter(function() {
		return !$(this).val();
	}).length;
	if (emptyExtraInputCount > 0) {
		suggestValid = false;
	}

	if ($('#message_body').val() || dialogFiles.totalFiles()) {
		messageValid = true;
	}

	if ((messageValid || (suggestPresent && suggestValid)) && type !== 'disabled' && suggestValid) {
		$('.btn-send-message').removeClass('disabled').prop('disabled', false);
	} else {
		$('.btn-send-message').addClass('disabled').prop('disabled', true);
	}
	$('.message-form-control__error').text('');
}

$('#message_body').on('input keyup keydown', toggleSubmitButton);
$(window).on('changeFileCount.fileUploader', toggleSubmitButton);
$(document).on('input', 'input[name="customExtraName[]"]', toggleSubmitButton);

var dialogFiles = new FileUploader({
	files: {},
	selector: '#load-files-conversations',
	input: {
		name: 'conversations-files'
	},
  cot_ext: 'ds',
  cot_cat: IS_ACTIVE_DIALOG
});

function calc_input_text(obj) {
  if($(obj).length) {
  	var text = $(obj).val();
  	text = text.trim();
  	var len = text.length;
  	$("#message_body_len").text(len);
  }
}
$('#message_body').keyup(function() {
	calc_input_text(this);
});
$('#message_body').keydown(function() {
	calc_input_text(this);
});
calc_input_text('#message_body');

$(function() {
  var msgresults_scroll = $('#msgresults').prop('scrollHeight');

  /*
  if(!IS_MOBILE) {
    var DIALOG_BUSY_HEIGHT =
          //$('.header').prop('offsetHeight')
          $('#msgresults').prop('offsetTop')
        + $('#block_message').prop('offsetHeight') + 20
        //+ $('.footertop').prop('offsetHeight')
        + 90;
    var DIALOG_HEIGHT = (window.innerHeight - DIALOG_BUSY_HEIGHT);
    if(DIALOG_HEIGHT < 300) DIALOG_HEIGHT = 300;
    $('#msgresults').css({'height': DIALOG_HEIGHT + 'px', 'overflow-y': 'scroll'});

    if($('.conversation-message.conversation-message__in.unread').length) {
      msgresults_scroll = $('.conversation-message.conversation-message__in.unread').eq(0).prop('offsetTop')
                          - 190;
    }

    if(DIALOG_SCROLL_TO_MSG > 0) {
      var scroll_msg = $('.conversation-message[data-mid="' + DIALOG_SCROLL_TO_MSG + '"]');
      if(scroll_msg.length == 1) {
        msgresults_scroll = scroll_msg.eq(0).prop('offsetTop');
      }
    }

    $('#msgresults').stop().animate({
        'scrollTop': msgresults_scroll
      }, 500, 'swing', function () {
    });
  } else {
  */
    if($('.conversation-message.conversation-message__in.unread').length) {
      msgresults_scroll = $('.conversation-message.conversation-message__in.unread').eq(0).prop('offsetTop')
                          + $('#msgresults').prop('offsetTop')
                          - 180;
    } else {
      msgresults_scroll -= $('#block_message').prop('offsetHeight');
    }


    // if(DIALOG_SCROLL_TO_MSG !== undefined) {
    //   if(DIALOG_SCROLL_TO_MSG && DIALOG_SCROLL_TO_MSG > 0) {
    //     var scroll_msg = $('.conversation-message[data-mid="' + DIALOG_SCROLL_TO_MSG + '"]');
    //     if(scroll_msg.length == 1) {
    //       //msgresults_scroll = scroll_msg.eq(0).prop('offsetTop') - scroll_msg.eq(0).prop('offsetHeight') + $('#msgresults').prop('offsetTop') - 15;
    //       msgresults_scroll = scroll_msg.eq(0).prop('offsetTop') + 100;
    //       scroll_msg.eq(0).css('background-color', '#ffeec8');
    //       setTimeout(function() {
    //         scroll_msg.eq(0).css('background-color', '#transparent');
    //       }, 1500);
    //     }
    //   }
    // }

  

    $('html, body').stop().animate({
        'scrollTop': msgresults_scroll
      }, 500, 'swing', function () {

    });
  //}
});

function cot_resendmsg_clear() {
  $('[data-mid]._msg_to_resend').removeClass('_msg_to_resend');
  $('[data-replymsd]._selected').removeClass('_selected');

  $('.message_resend_info').hide().find('span').html('');
  $('#new_message [name="resend"]').val('');
}

function cot_resendmsg(btn) {
  btn.toggleClass('_selected');
  if(btn.hasClass('_selected')) {
    btn.closest('[data-mid]').addClass('_msg_to_resend');
  } else {
    btn.closest('[data-mid]').removeClass('_msg_to_resend');
  }
  var _toresend = new Array();
  $('[data-replymsd]._selected').each(function() {
    _toresend.push($(this).attr('data-replymsd'));
  });
  if(_toresend.length > 0) {
    $('.message_resend_info').show().find('span').html(' + прикрепить сообщения: ' + _toresend.length);
    $('#new_message [name="resend"]').val(_toresend.join(','));
  } else {
    cot_resendmsg_clear();
  }
}

$('.message__star[data-midstar]').click(function () {
    var tmstar = $(this),
        mid = tmstar.attr('data-midstar');
  $.get('index.php?e=ds&m=impotrant&id='+mid, function(data) {
    if(data == '2') {
      tmstar.closest('[data-mid]').addClass('_msg_in_star');
    } else {
      tmstar.closest('[data-mid]').removeClass('_msg_in_star');
    }
  });
});

var readTrackService = new ReadTrackService({
	'itemIdPrefix': 'message_'
});

$(window).load(function () {
	readTrackService.init({dialogId: IS_ACTIVE_DIALOG});
});

/** conservations **/

/* global requestProject, requestDodji, conversationImageUrl,
 conversationActorUserAvatar, conversationActorUserName, ordersBetweenUsers,
 dialogFilesEdit, dialogFiles, Utils */
var formData = new FormData;
var isViewOfferDodji = false;
var isShowOfferCustomDodji = false;
var messageSending = false;
var popup_ordersList = "";

$("#new_message").submit(function(e) {
  e.preventDefault();
  e.stopPropagation();

  showPopupOrdersList($(this), '#load-files-conversations', true);
  return false;
});

$("#suggestDodjiToggle").click(suggestDodjiToggle);
$("#suggestCustomDodjiToggle").click(suggestCustomDodjiToggle);

function showPopupOrdersList(form, file_wrap_selector, isNew) {
    $(".js-send-order-message-radio").off("change");
    var message_type = form.find("[name=message_type]").val();
    if (!message_type && ($('.ordersList').length > 0 || popup_ordersList.length > 0)) {
        if (!popup_ordersList.length) {
            popup_ordersList = $('.ordersList').children().html();
            $('.ordersList').remove();
        }
        show_popup(popup_ordersList);
        $('.popup_content #ordersBetweenChoose').click(function() {
            var hasSelectedOrderRadio = $(".js-popup-select-order-radio").find("input:radio:checked").length > 0;
            if (hasSelectedOrderRadio) {
                ajaxSendInboxMessage($('#new_message'), '#load-files-conversations', true);
            } else {
                $(".js-send-order-message-error").text("Выберите заказ для отправки сообщения");
                $(".js-send-order-message-radio").on("change", function() {
                    $(".js-send-order-message-error").text("");
                });
            }
            return false;
        });
    } else {
        ajaxSendInboxMessage(form, file_wrap_selector, isNew);
    }
}

function ajaxSendInboxMessage(form, file_wrap_selector, isNew) {
    var msgresults = $('#msgresults'),
        msgresults_list = msgresults.find('.gig-reviews-list'),
        sendbtns = form.find('input[type="submit"]'),
        msgbody = form.find('[name="message_body"]');

    var islastpage = $('#msgresults').hasClass('islastpage'),
        lasthref = $('#msgresults').attr('data-lasthref');

    var isPopup = form.data('ispopup');
    var uploader = isPopup === 1 ? dialogFilesEdit : dialogFiles;
    var isOffer = false;
    if (form.find("[name=message_type]").val() === 'offer_prd' || form.find("[name=message_type]").val() === 'offer_custom_prd') {
        isOffer = true;
    }
    if (messageSending || (!form.find(".message_body").val() && !uploader.totalFiles() && !isOffer)) {
        return;
    }

    messageSending = true;
    var sendButton = isPopup === 1 ? $('.btn-send-message').eq(1) : $('.btn-send-message').eq(0);
    btnDisableToggle("on");
    formData.append('x', form.find('[name=x]').val());
    formData.append('message_body', form.find('.message_body').val());
    formData.append('submg', '1');

    formData.append('resend', form.find('[name="resend"]').val());

    formData.append('rmodername', form.find('[name="rmodername"]').val());
    formData.append('rmodertheme', form.find('[name="rmodertheme"]').val());
    if($('[name="rmodernameshide"]').length > 0 && $('[name="rmodernameshide"]').prop('checked')) formData.append('rmodernameshide', 1);
    if($('[name="rmoderfromauto"]').length > 0 && $('[name="rmoderfromauto"]').prop('checked')) formData.append('rmoderfromauto', 1);

    if (requestDodji > 0) {
        formData.append('prdId', requestDodji);
    }
    if (requestProject > 0) {
        formData.append('projectId', requestProject);
    }

    var message_type = form.find("[name=message_type]").val();
    formData.append('message_type', message_type);
    if (message_type === 'offer_prd') {

        formData.append('prd_id', form.find("select[name=prd_id]").val());
        formData.append('prd_count', form.find("select[name=prd_count]").val());
        formData.append('prd_package_type', form.find("[name=prd_package_type]").val());
        $(".js-order-extras__count").each(function() {
            formData.append($(this).attr("name"), $(this).val());
        });
        $(".order-extras__input:checked").each(function() {
            formData.append('gextras[]', $(this).val());
        });
        $(".order-new-extras__input").each(function() {
            formData.append('customExtraName[]', $(this).val());
        });
        $(".js-new-extra-count").each(function() {
            formData.append('customExtraCount[]', $(this).val());
        });
        $(".js-new-extra-days").each(function() {
            formData.append('customExtraTime[]', $(this).val());
        });
        $(".js-new-extra-price").each(function() {
            formData.append('customExtraPrice[]', $(this).val());
        });
    } else if (message_type === 'offer_custom_prd') {

        formData.append('prd_name', form.find("#request-prd-name").val());
        formData.append('prd_desc', form.find("#request-prd-desc").val());
        formData.append('prd_duration', form.find("#request-prd-duration").val());
        formData.append('prd_price', form.find("#request-prd-price").val());
    }

    formData.append('orderId', $(".js-popup_ordersList input[name=orderId]:checked").val());

    $(file_wrap_selector).find(':hidden').each(function() {
        formData.append($(this).attr("name"), $(this).val());
    });
    var xhr = new XMLHttpRequest();
    xhr.open('post', form.attr('action'), true);
    if (isPopup === 1) {
        var allFiles = $(file_wrap_selector).find('.file-uploader__item').length;
        var deletedFiles = $(file_wrap_selector).find('.file-item_type_deleted').length;
        var filesCount = parseInt(allFiles - deletedFiles);
    }
    if (isPopup === 1 && (form.find('.message_body').val() === "" && filesCount <= 0)) {
        form.find('.message_body').addClass('input-styled--error');
        if (!document.getElementById('error-popup-message')) {
            var $errorMessage = $('<div/>', {
                id: 'error-popup-message',
                text: 'Вы не можете отправить пустое сообщение',
                class: 'color-red'
            });
            $(file_wrap_selector).after($errorMessage);
        }
        btnDisableToggle("off");
        return false;
    }
    if (!uploader.canSave()) {
        var interval = setInterval(function() {
            if (uploader.canSave()) {
                clearInterval(interval);
                btnDisableToggle("off");
                messageSending = false;
                sendButton.trigger('click');
            }
        }, 100);
        sendButton.val('Загрузка файлов...');
        return false;
    }

    xhr.onload = function() {
        uploader.clear();
        form.find('[type=button]').attr('type', 'submit');
        if (xhr.status == 200) {
            formData = new FormData;
            var data = xhr.responseText;
            if (data) {
              if(islastpage) {
                msgresults_list.find('[data-dserror]').hide();
                msgresults_list.append(data);

                //$('[data-resendmsg]').remove();
                $('#load-files-conversations .load-file__list').html('');

                msgresults.stop().animate({
                    'scrollTop': msgresults.prop('scrollHeight')+1000
                 }, 500, 'swing', function () {
                });
                msgbody.val('');
                cot_resendmsg_clear();

                if (isViewOfferDodji) {
                  suggestDodjiToggle();
                }
                if (isShowOfferCustomDodji) {
                  suggestCustomDodjiToggle();
                }
              } else {
                location.href=lasthref;
              }
            }
          sendButton.val('Отправить');
        }
        messageSending = false;
    };
    xhr.send(formData);
}

function suggestDodjiToggle() {
    var target = $('#suggestDodjiToggle');
    isViewOfferDodji = !isViewOfferDodji;
    $('#suggestDodji').find('.prd').toggle();

    if (!isViewOfferDodji) {
        btnDisableToggle('off');
        $('input[name=message_type]').val('');
        $('.btn-send-message').val('Отправить');
        toggleSubmitButton();
        $('#change-to-custom-prd, #change-to-prd-choose').addClass('hidden');
        target.text('Предложить ' + cot_sitename['padeg']['v']);
    } else {
        if (!$('#request-prd-id').val()) {
            btnDisableToggle('on');
        }
        $('input[name=message_type]').val('offer_prd');
        $('.btn-send-message').val('Предложить');
        $('#change-to-custom-prd').removeClass('hidden');
        target.text('Отменить');
    }
}

function suggestCustomDodjiToggle() {
    var target = $('#suggestCustomDodjiToggle');
    isShowOfferCustomDodji = !isShowOfferCustomDodji;
    $('#suggestDodji').find('.customDodji').toggle();
    /*
    if(isViewOfferDodji) {
      $('#suggestDodji > .prd').toggle();
      isViewOfferDodji = !isViewOfferDodji;
      $('#change-to-custom-prd').addClass('hidden');
    }
    */

    if (!isShowOfferCustomDodji) {
        btnDisableToggle('off');
        $('input[name=message_type]').val('');
        $('.btn-send-message').val('Отправить');
        toggleSubmitButton();
        $('#change-to-custom-prd, #change-to-prd-choose').addClass('hidden');
        target.text('Индивидуальное предложение');
    } else {
        btnDisableToggle('on');
        $('input[name=message_type]').val('offer_custom_prd');
        $('.btn-send-message').val('Предложить');
        $('#change-to-prd-choose').removeClass('hidden');
        target.text('Отменить');
    }
}

$(document).on('focus click', '#popup-textarea, #edit-files-conversations', function() {
    var textarea = document.getElementById('popup-textarea');
    if (textarea.classList.contains('input-styled--error')) {
        textarea.classList.remove('input-styled--error');
    }
    if ($('#error-popup-message')) {
        $('#error-popup-message').detach();
    }
});

//Переключение на предожить
$('#change-to-prd-choose').click(function() {
    suggestCustomDodjiToggle();
    suggestDodjiToggle();
});
//Переключение на индивидуальное предложение
$('#change-to-custom-prd').click(function() {
    suggestDodjiToggle();
    suggestCustomDodjiToggle();
});

function complainConversationMessage(id) {
    var extText;
    var $messagewrap = $('.conversation-message[data-mid=' + id + ']');
    var message_text = replaceTextMessage($messagewrap.find('.comment .comment-comment').html());
    var login = $messagewrap.find('.comment-meta .username').text().trim();
    if (extText = $('#message_' + id).find('.js-message-text').text()) {
        message_text = extText.trim();
    }

    show_popup('<h1 class="popup-mesage-complain__title f32">Отправить жалобу</h1>\
	<hr class="gray mt20" style="margin-bottom:20px;">\
	<div class="b-popup-content">\
	    <div class="mb15">\
	        <div class="ico-i-small" style="position: absolute;"></div>\
	        <div style="margin-left: 40px" class="f13">Вы можете пожаловаться на сообщение пользователя в случаях, если это несанкционированная реклама (СПАМ), сообщение содержит оскорбительные&nbsp;/&nbsp;грубые выражения, нарушает законодательство или правила сайта</div>\
	    </div>\
		<div class="b-popup__row">\
            <label>\
                <span style="font-weight: 600;">На пользователя</span>\
                <textarea readonly class="b-popup__row-field styled-input h30" style="overflow: auto;" rows="1">' + login + '</textarea>\
            </label>\
		</div>\
		<div class="b-popup__row">\
            <label>\
                <span style="font-weight: 600;">На сообщение</span>\
                <textarea readonly class="b-popup__row-field styled-input" style="overflow: auto;" rows="3">' + message_text + '</textarea>\
            </label>\
        </div>\
		<div class="b-popup__row">\
            <label>\
                <span style="font-weight: 600;">Ваш комментарий</span>\
		        <textarea class="b-popup__row-field styled-input complain_body" placeholder="Комментарий к жалобе" style="overflow: auto;" name="comment" rows="3"></textarea>\
		    </label>\
        </div>\
	</div>\
	<div class="wrap-action-button">\
	    <input type="button" class="green-btn popup__button" onclick="javascript:sendComplainConversationMessage(' + id + ');" value="Отправить">\
	</div>', 'popup-new popup-mesage-complain');
}
function sendComplainConversationMessage(id) {
    var text = $('.popup-mesage-complain .complain_body').val();
    var page = $('#currentPage').text();
    $.post('/api?method=banlist_banmsg', {'from': 'ds', 'id': id, 'comment': text, 'page': page}, function(data) {
    	if(data) {
    		data = JSON.parse(data);
        show_message((data.success == 1 ? 'success' : 'error'), "<p>" + data.error + "</p>");
      }
    });
    $('.popup-close').click();
    $("body").scrollTop(0);
}

function editConversationMessage(id) {
  var extText;
  var message_text = $('#message_' + id).find('.message-main-content .comment-comment.breakwords').text().trim();

  show_popup('<h1 class="popup-mesage-edit__title f32">Редактирование сообщения</h1>\
	<hr class="gray mt20" style="margin-bottom:20px;">\
	<div class="b-popup-content">\
		<div class="b-popup__row">\
            <label>\
                <span style="font-weight: 600;">Сообщение</span>\
		        <textarea class="b-popup__row-field styled-input edit_body" style="overflow: auto;" name="msg" rows="3">' + message_text + '</textarea>\
		    </label>\
        </div>\
	</div>\
	<div class="wrap-action-button">\
	    <input type="button" class="green-btn popup__button" onclick="javascript:sendEditConversationMessage(' + id + ');" value="Сохранить">\
	</div>', 'popup-new popup-mesage-edit');
}
function sendEditConversationMessage(id) {

    var scroll_msg = $('.conversation-message[data-mid="' + id + '"]'),
        scroll_msg_valprev = scroll_msg.find('.message-main-content .comment-comment.breakwords').text().trim();
        scroll_msg.find('.message-main-content .comment-comment.breakwords').html('Сохранение');

    var text = $('.popup-mesage-edit .edit_body').val();
    text = text.trim();
    $.post('/api?method=ds_editMsg', {'id': id, 'msg': text}, function(data) {
    	if(data) {
    		data = JSON.parse(data);

        if(data.success == 1) {
          scroll_msg.find('.message-main-content .comment-comment.breakwords').html(text);
        } else if(data.error != '') {
          scroll_msg.find('.message-main-content .comment-comment.breakwords').html(data.error);
        } else {
          scroll_msg.find('.message-main-content .comment-comment.breakwords').html(scroll_msg_valprev);
        }
        if(data.notfind == 1) scroll_msg.find('[data-editemsg]').remove();
      }
    });

    $('.popup-close').click();
}

console.log('sendindobas');