const TRACKS_WRAPPER_ID = '#tracks-wrapper';
const TRACK_ID_PREFIX = "#track-id-";

const CS_CHECK_INTERVAL = 100;

const SLIDE_DURATION = 150;

var dialogFilesEdit;
var dialogFiles;

	var deleteTrackFileCallback = function(file, cb) {
		var html = '<div>' +
			'<h1 class="popup__title">Удаление файла</h1>' +
			'<hr class="gray">' +
			'<div style="display:inline-block;width:100%;">' +
			'<p class="ta-center f15 ml10 mt20 pb20">Вы действительно хотите удалить файл?</p>';

		html += '<button class="file-upload-delete-btn hoverMe white-btn w160 mt20  f16" style="height:40px;">Да</button>' +
			'<button class="hoverMe white-btn w160 mt20 pull-right popup-close-js f16" style="height:40px;">Нет</button></div>' +
			'</div>';

		show_popup(html);

		$('.file-upload-delete-btn').click(function() {
			remove_popup();
			$.ajax({
				type: "POST",
				url: '/api?method=deleteMav',
				dataType: 'json',
				data: {
					file_id: file.id,
          ext: 'marketorders'
				},
				success: function(data) {
					if (data.success === true) {
						cb();
					} else {
						popup_error('Ошибка удаления файла');
					}
				},
				error: function() {
					popup_error('Ошибка удаления файла');
				},
				processData: true
			});
		})
	};

jQuery(function() {
	dialogFiles = new FileUploader({
		files: {},
    deleteCallback: deleteTrackFileCallback,
		selector: '#load-files',
		input: {
			name: 'file-input'
		},
    cot_ext: 'marketorders',
    cot_cat: 'msg'
	});
});

PullOrderTrack = function () {
	this._waitHtmlInserting = false;
	this._waitTimer = 0;

	this.orderId = 0;
	this.lastItemId = 0;

	this.init();
};

PullOrderTrack.prototype._removeTracks = function (htmlObj) {
	for (var index in htmlObj) {
		$(TRACK_ID_PREFIX + index).remove();
	}
};

PullOrderTrack.prototype._replaceTracks = function (htmlObj) {
	for (var index in htmlObj) {
		$(TRACK_ID_PREFIX + index).replaceWith(htmlObj[index]);
	}
	this._dbgUpdateStyle();
};

PullOrderTrack.prototype._insertNewTracks = function (items) {
	var _self = this;
	// Критическая секция, чтобы избежать ситуации,
	// когда post отправляется с неактуальным lastTrackId,
	// потому что на страницу не успели добавиться все новые треки.
	_self._waitHtmlInserting = true;
	for (var itemId in items) {
		if (items[itemId].length) {
			_self._getLastItem().after(items[itemId]);
			_self.lastItemId = itemId;
			_self._dbgUpdateStyle();
		}
	}
	_self.setLastItemId();
	_self._waitHtmlInserting = false;
};

PullOrderTrack.prototype.setLastItemId = function () {
	this.lastItemId = $(TRACKS_WRAPPER_ID).find('.step-block-order_item').last().data("trackId");
	this._dbgUpdateStyle();
};

PullOrderTrack.prototype._dbgUpdateStyle = function () {
	// это пригодится, когда надо будет наглядно показывать последний трек.
	// $('.step-block-order_item', TRACKS_WRAPPER_ID).css('border-right-width', '0');
	// this._getLastItem().css('border-right', '5px solid blue');
};

PullOrderTrack.prototype._getLastItem = function () {
	// return $(TRACK_ID_PREFIX + this.lastItemId);
	return $(TRACKS_WRAPPER_ID).find('.step-block-order_item').last();
};

PullOrderTrack.prototype._setEvents = function () {
	var _self = this;
	//PullModule.on(PULL_EVENT_NEW_ORDER_TRACK, function (data) {
	//	_self._onNewTrack(data);
	//});
	hintInit();
};

PullOrderTrack.prototype.init = function () {
	var _self = this;

	$(document).ready(function () {
		_self.orderId = Track.orderId;
		_self._setEvents();
  });

	$(window).load(function () {
		_self.setLastItemId();
	});
};


PullOrderUpdated = function () {
	this.orderId = 0;

	this.init();
};

PullOrderUpdated.prototype._onUpdated = function (data) {
	var _self = this;

	if (data["order_id"] != _self.orderId) {
		return false;
	}

	var params = {
		orderId: _self.orderId,
		action: data['action']
	};
	$.extend(params, data);

	_self._getUpdates(params);
};

PullOrderUpdated.prototype._getUpdates = function (params) {
	$.post("api?method=Order.api_getUpdates", params, function (response) {
		if (response.success) {

			if (!Utils.isEmptyObject(response.orderHtml)) {
				var $orderData = $('#order-data').html(response.orderHtml);
				newContentProcess($orderData);
			}
		}
	}, "json");
};

PullOrderUpdated.prototype._setEvents = function () {
	var _self = this;
	PullModule.on(PULL_EVENT_ORDER_UPDATED, function (data) {
		_self._onUpdated(data);
	});
};

PullOrderUpdated.prototype.init = function () {
	var _self = this;

	$(document).ready(function () {
		_self.orderId = Track.orderId;
		_self._setEvents();
	});
};


PullTrackChanged = function () {
	this.init();
};

PullTrackChanged.prototype.init = function () {
	var _self = this;

	$(document).ready(function () {
		_self._setEvents();
	});
};

PullTrackChanged.prototype._setReportProgress = function (value, track_id, progress_index) {
  var parentWrapper = $('#track-id-' + track_id +' .js-phases-item[data-index="' + progress_index + '"]');

  var tirep = $('#track-inprogress_report'),
      toshowform = false;

	if (parentWrapper.find('.loadbar.enable').length) {
		parentWrapper.find("input[name='isExecutedOn']").val(value);
		parentWrapper.find(".current-percent-value").text(value);
		parentWrapper.find(".progress-bar").each(function () {
			var bar = $(this);
			if (bar.data("value") <= value) {
				bar.addClass('progress-bar-fill');
			} else {
				bar.removeClass('progress-bar-fill');
			}

      if (bar.data("value") == value) {
        tirep.find('input[name="steps[' +progress_index + ']"]').val(value);
      }
		})
	}

  tirep.find('[data-defaulsteptval]').each(function() {
    if($(this).val() - 0 > $(this).attr('data-defaulsteptval') - 0) toshowform = true;
  });
  if(toshowform) {
    tirep.show();
  } else {
    tirep.hide();
  }
}
PullTrackChanged.prototype._onChanged = function (data) {
	var trackId = data['trackId'];

	var params = {
		trackId: trackId,
		orderId: Track.orderId
	};
	$.extend(params, data);

	$.post("api?method=Track.api_getChangedTrack", params, function (response) {
		if (response.success) {
			var $track = $(TRACK_ID_PREFIX + trackId);
			// По изменениям работаем только с существующим на странице треком.
			if ($track.length) {
				if (!Utils.isEmptyObject(response.trackHtml)) {
					$track.replaceWith(response.trackHtml);
					newContentProcess($(TRACK_ID_PREFIX + trackId));
				}
				// Возможен вариант удаления, пока не прорабатывался.
				else {
					$track.remove();
					readTrackService.updateTitleUnreadCount();
				}
			}

			// Блок с файлами в сайдбаре.
			var $orderFilesBlock = $('#order-files');
			if (response.filesBlockHtml.length) {
				if ($orderFilesBlock.length) {
					$orderFilesBlock.replaceWith(response.filesBlockHtml);
				}
			}
			else if ($orderFilesBlock.length) {
				$orderFilesBlock.remove();
			}
		}
	}, "json");
};

PullTrackChanged.prototype._setEvents = function () {
	var _self = this;
	PullModule.on(PULL_EVENT_TRACK_CHANGED, function (data) {
		_self._onChanged(data);
	});
	$(document.body).on("click", ".progress-bar:not(.min-active-value)", function () {
		if ($(this).parents('.phases__progress').length) {
			return;
		}
		_self._setReportProgress($(this).data('value'), $(this).data('track-id'), $(this).data('progressindex'));
	});
};


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

var pullOrderTrack = new PullOrderTrack();
var pullOrderUpdated = new PullOrderUpdated();
var pullTrackChanged = new PullTrackChanged();

var genInputId = new IDGenerator('_id');

function ajaxSendTrackMessage(form, file_wrap_selector) {
	var uploader = isPopup === 1 ? dialogFilesEdit : dialogFiles;
	var isPopup = form.data('ispopup');
	var trackId = (isPopup) ? form.find('input[name=trackId]').val() : null;

	formData = new FormData(form[0]);
	formData = formDataFilter(formData);

	if (form.find('input[name=orderId]').length === 0) {
		formData.append('orderId', Track.orderId);
	}

	$("#list-files1", form).find(':hidden').each(function () {
		var $this = $(this);
		formData.append($this.attr("name"), $this.val());
	});

	var addedOptions = isSuggestOptionsFormOpened
		&& ($('[name="gextras[]"]:checked', form).length > 0
			|| $('.extrasping-settings').find('#extratime').length > 0);

	if (addedOptions) {
		formData.append('suggestextrassubmited', 1);
	}

	formData.append('is_ajax', 1);

	$(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);

	xhr.onload = function () {
		uploader.clear();
		form.find('#message_body_len').text(0);
		form.find('[type=button]').attr('type', 'submit');
		if (xhr.status == 200) {
			var result = xhr.responseText;

			if (isPopup) {
				$('.popup-close').click();
				$(TRACK_ID_PREFIX + trackId).replaceWith(result);
				newContentProcess($(TRACKS_WRAPPER_ID));
				return;
			}

			//Если были предложены существующие или кастомные опции
			if (addedOptions) {
				location.reload();
				return;
			}

			formData = new FormData;
			$('#list-files1', form).children().remove();
			$('.fileInputs', form).remove();
			haveFiles = false;
			$('#message_body1').val('').trigger('input');
      $(".trumbowyg-editor").html('');
			$("#track-send-message-button").removeAttr('disabled');
			try {
				result = JSON.parse(result);
				switch (result['status']) {
					case "error":
						if(result['response'] != '') alert(result['response']);
						break;
					case "success":
						if (result['type'] == "report_update") {
							editReport(result['trackId'], true, result['message']);
              newContentProcess($(TRACKS_WRAPPER_ID));
						}
						break;
				}

			}
			catch (e) {
				$(TRACKS_WRAPPER_ID).append(result);
				if (result.indexOf("report-message") >= 0) {
					removeReport();
					hintInit();
				}
				newContentProcess($(TRACKS_WRAPPER_ID));
				pullOrderTrack.setLastItemId();
			}
		}
	};

	xhr.send(formData);
}

function showArbitrageCheckPopupClick(event) {
	var $this = event;

	var action = $this.data('track_type');
	var orderId = $this.data('order_id');
  var trackId = $this.data('track_id');

	var html = '' +
		'<form action="/send_mk" method="post" enctype="multipart/form-data">' +
    '<input type="hidden" name="action" value="' + action + '" />' +
    '<input type="hidden" name="orderId" value="' + orderId + '" />' +
    '<input type="hidden" name="trackId" value="' + trackId + '" />' +
    '<input type="hidden" name="redirect" value="1" />' +
		'<h1 class="popup__title">Отправка заказа в арбитраж</h1>' +
		'<hr class="gray mt20" style="margin-bottom:20px;">' +
		'<div class=" m-center-block m-text-center">' +
		'Пожалуйста, четко и конкретно укажите суть жалобы. Приложите все аргументы и доказательства, подтверждающие вашу позицию. На основании этих данных арбитрами будет вынесено решение.' +
		'</div>' +
		'<div class="mt20">' +
		'<textarea class="text styled-input wMax f15" style="height: 165px;" id="message" name="message" type="text" placeholder="Опишите проблему" required></textarea>' +
		'</div>' +
		'<div class="clear"></div>' +
		'<div>' +
		'<div>' +
		'<div class="block-state-active">' +
		'<div id="list-files_popup" class="mt10"></div>' +
		'<progress max="100" value="0" class="hidden" style="width:100%;"></progress>' +
		'<div class="file-wrapper file-wrapper_inline sm-pull-reset">' +
		'<i class="icon dib ico-clip v-align-m"></i>' +
		'<input onchange="showNameFilesPopup(this);" name="mavatar_file[]" type="file" multiple/>' +
		'<span class="button f14 font-OpenSans dib v-align-m mt0 link-color ml5" data-init-text="Прикрепить файлы">Прикрепить файлы</span>' +
		'</div>' +
		'</div>' +
		'</div>' +
		'<div>' +
		'<button class="red-btn popup__button">В арбитраж</button>' +
		'<button class="white-btn popup__button popup-close-js pull-right" onclick="return false;">Отменить</button>' +
		'</div>' +
		'</div>' +
		'<div class="clear"></div>' +
		'</form>';
	show_popup(html, "arbitrage_popup-content");
}

var similarData = similarData || {'baseInput': false, 'lastAction': 'none', 'orderDataCache': {}};


similarData.getFileIcoType = function (fileName) {
	var len = fileName.length;
	var symb3 = fileName.substr(len - 3, len).toLowerCase();
	var symb4 = fileName.substr(len - 4, len).toLowerCase();
	var ico = '';
	var allow = true;
	if ($.inArray(symb3, ['doc', 'xls', 'rtf', 'txt']) != -1 || $.inArray(symb4, ['docx', 'xlsx']) != -1) {
		ico = 'doc';
	} else if ($.inArray(symb3, ['zip', 'rar']) != -1) {
		ico = 'zip';
	} else if ($.inArray(symb3, ['png', 'jpg', 'gif', 'psd']) != -1 || $.inArray(symb4, ['jpeg']) != -1) {
		ico = 'image';
	} else if ($.inArray(symb3, ['mp3', 'wav', 'avi']) != -1) {
		ico = 'audio';
	} else if ($.inArray(symb3, ["exe", "com", "dll", "sys", "drv", "bin", "ovl", "ovy", "dot"]) != -1) {
		ico = 'zip';
		allow = false;
	} else {
		ico = 'zip';
	}
	return ico;
}

similarData.showOrderData = function (data) {
	$('#message_body1').val(data.message).trigger('input');
	$('.similar_files_data').html('');
	$('#list-files1').html('');
	var $this = this;
	Object.keys(data.files).map(function (objectKey, index) {
		var fileName = data.files[objectKey];
		var html = '<div class="mb5 file-item" id="fileName_id' + objectKey + '"><i class="ico-file-' + $this.getFileIcoType(fileName) + ' dib v-align-m"></i><span class="dib v-align-m ml10">' + fileName + '</span><a class="remove-file-link" onclick="similarData.delSimilarFiles(\'_id' + objectKey + '\')"></a>\n\
		<input type="hidden" name="similar_files[]" value="' + objectKey + '">\n\
		</div>';
		$('.similar_files_data').append(html);

	});
};
similarData.loadOrderData = function (id) {
	if (typeof this.orderDataCache[id] !== 'undefined') {
		this.showOrderData(this.orderDataCache[id]);
	} else {
		var $this = this;
		$.post('/api?method=Order.api_getOrderProvidedData', {'orderId': id}, function (answer) {
			$this.orderDataCache[id] = answer;
			$this.showOrderData($this.orderDataCache[id]);
		}, 'JSON');
	}
};
similarData.loadInputData = function () {
	$('#message_body1').val(this.baseInput).trigger('input');
	$('.similar_files_data').html('');
};
similarData.saveInputData = function () {
	if (this.lastAction === 'none') {
		this.baseInput = $('#message_body1').val();
	}
};
similarData.saveLastAction = function (action) {
	this.lastAction = action;
};
similarData.delSimilarFiles = function (id) {
	var $fileName = $('#fileName' + id);
	if ($fileName.parent().find('.file-item').length) {
		$fileName.parents('form').find('textarea').prop('required', true);
	}
	$fileName.remove();
	$('#fileInput' + id).remove();
};


var SITE = SITE || {};

SITE.fileInputs = function () {

	var $this = $(this),
		$val = $this.val(),
		valArray = $val.split('\\'),
		newVal = valArray[valArray.length - 1],
		$button = $this.parents('.file-wrapper').find('.button'),
		$fakeFile = $this.parents('.file-wrapper').find('.file-holder span');
	if (newVal !== '') {
		$('.block-help-image-js').show();
		$button.text($('.file-wrapper label').attr('data-init-text'));
		if ($fakeFile.length === 0) {
			$button.parents('.file-wrapper').prepend('<span class="file-holder"><span>' + newVal + '</span></span>');
		} else {
			$fakeFile.text(newVal);
		}
	}
};

/**
 * Cancel order
 * @type {{init, load}}
 */
var trackCancelModule = (function () {

	var _initialButton;
	var _mainPopupTemplate;
	var _subTypePopupTemplate;
	var _mainPopup;
	var _subTypePopup;
	var _chosedReasonKey;

	var _mainPopupClass;
	var _subTypePopupClass;

	var _cancelReasons;

	var _init = function (params) {
		_initialButton = $(params["initialButton"]);
		_mainPopupTemplate = $(params["mainPopupTemplate"]);
		_subTypePopupTemplate = $(params["subTypePopupTemplate"]);

		_mainPopupClass = params["mainPopupClass"];
		_subTypePopupClass = params["subTypePopupClass"];

		_cancelReasons = params["reasons"];

		_setInitEvents();
	};

	var _setInitEvents = function () {
		_initialButton.on('click', function () {
			_showMainPopup.apply(this);
			$('.popup-order-cancel select').chosen({width: "100%", disable_search: true}).change(function () {
				$('.popup-order-cancel .chosen-single').removeClass('select-styled--error')
			});
		});
	};

	var _showMainPopup = function () {
		var content = _mainPopupTemplate.html();
		show_popup(content, _mainPopupClass);
		_mainPopup = $("." + _mainPopupClass);
		_mainPopup.find('.js-popup-cancel-order__action').val($(this).data('action'));
		_mainPopup.find("input[name='reason']").each(function () {
			$(this).attr("id", "reason-" + $(this).val());
		});
		_mainPopup.find(".js-tooltip").tooltip();

		if (_mainPopup.find('.js-popup-cancel-form__reason').length > 0) {
			if (!_mainPopup.find('.js-popup-cancel-form__reason').val().length) {
				$('.order-cancel-form__comment').hide();
			}
		}

		_mainPopup.find('.js-popup-cancel-form__reason').on('change', function () {
			var val = $(this).val();
			if (val.length > 0 && !_cancelReasons[val]["subtypes"]) {
				$('.order-cancel-form__comment').slideDown(50);
				var $textArea = $('.order-cancel-form__comment textarea');
				if ($(this).data('isPayer')) {
					if (val === 'payer_other_no_guilt') {
						$textArea.addClass('js-required');
					}
					else {
						$textArea.removeClass('js-required');
					}
				}
				else {
					$textArea.addClass('js-required');
				}
			}
			else {
				$('.order-cancel-form__comment').slideUp(50);
			}
		});

		_mainPopup.find(".js-cancel-order-submit").on("click", _mainPopupSubmited);
	};
	var _mainPopupSubmited = function (e) {
		var chosedReasonKey = _mainPopup.find(".js-cancel-order-reason-input:checked").val();
		var chosedReason = _cancelReasons[chosedReasonKey];
		if (chosedReason && chosedReason["subtypes"]) {
			//Есть подпричины
			_chosedReasonKey = chosedReasonKey;
			_showSubTypePopup(chosedReasonKey);
		}
		else {
			//Подпричин нет
			_mainPopup.find("form").submit();
		}
	};
	var _showSubTypePopup = function () {
		var content = _subTypePopupTemplate.html();
		show_popup(content, _subTypePopupClass + " popup-order-cancel-subtype", false);
		_subTypePopup = $("." + _subTypePopupClass);
		_subTypePopup.find(".js-subreasons").hide();
		_subTypePopup.find(".js-subreasons[data-parent-reason=" + _chosedReasonKey + "]").show();
		_subTypePopup.find("input[name='reason']").each(function () {
			$(this).attr("id", "reason-" + $(this).val());
		});
		_subTypePopup.find("input[name='reason']").on("click", _subReasonChosed);
		_subTypePopup.find(".js-tooltip").tooltip();
		_subTypePopup.find(".js-cancel-order-back").on("click", _showMainPopup);
		_subTypePopup.find(".js-cancel-order-parent-reason-input").val(_chosedReasonKey);
		//_subTypePopup.find(".js-link-back").on("click", _showMainPopup);
	};
	var _subReasonChosed = function (e) {
		_subTypePopup.find(".js-cancel-order-submit").removeClass("disabled");
		_subTypePopup.find(".js-cancel-order-submit").prop("disabled", false);
		_subTypePopup.find(".js-subreason-help").addClass("hidden");
		_subTypePopup.find(".js-subreason-help[data-subreason-help=" + e.target.value + "]").removeClass("hidden");
		if (_cancelReasons[_chosedReasonKey]["subtypes"][e.target.value]["additional"] && !_cancelReasons[_chosedReasonKey]["subtypes"][e.target.value]["allowed"]) {
			_subTypePopup.find(".js-cancel-order-additional i").text(_cancelReasons[_chosedReasonKey]["subtypes"][e.target.value]["additional"]);
		}
		else {
			_subTypePopup.find(".js-cancel-order-additional i").text("");
		}
		if (_cancelReasons[_chosedReasonKey]["subtypes"][e.target.value]["allowed"]) {
			_subTypePopup.find(".js-cancel-order-submit").show();
			_subTypePopup.find(".js-cancel-order-back").hide();
			_subTypePopup.find(".js-cancel-order-comment").show();
		}
		else {
			_subTypePopup.find(".js-cancel-order-back").show();
			_subTypePopup.find(".js-cancel-order-submit").hide();
			_subTypePopup.find(".js-cancel-order-comment").hide();
		}
		_subTypePopup.find(".popup__buttons").removeClass("hidden");
	};
	return {
		init: _init
	}
})();

var MessageFormModule = (function () {

	var _openMessageForm = function (el) {
		var $messageBlock = $('.js-comment-box');
		if (!$messageBlock.is(":visible")) {
			if (Utils.isSafariBrowser()) {
				$messageBlock.show(50);
			} else {
				$messageBlock.slideDown(50);
			}
		}

		if ($(el).data('action')) {
			$('.js-send-message-action').val($(el).data('action'));
			if ($(el).data('action') == 'instruction') {
				$('#is_instruction').show();
				$('#is_text').hide();
			} else {
				$('#is_instruction').hide();
				$('#is_text').show();
			}
		}
		$(el).parent().find('.js-toggle-message-button').addClass('inactive');
		$(el).removeClass('inactive');
	};

	var _init = function (params) {

	};
	return {
		init: _init,
		openMessageForm: _openMessageForm
	}
})();

var TrackUtils = (function() {

	var _startShow = function(aTypeForm) {
		var ret;
		switch(aTypeForm) {
			case 'pass-work':
				ret = _startPassWork();
				break;

			case 'send-instruction':
        ret = _startSendInstruction();
				break;

			case 'only-message':
				ret = _startOnlyMessage();
				break;

			default:
				ret = false;
				break;
		}

		return ret;
	};

	var _onSendMessageButtonClick = function () {
		TrackUtils.sendMessageFromPassWorkForm(); return false;
	};

	var _onPassWorkButtonClick = function () {
		TrackUtils.submitWorkFromPassWorkForm();
	};

	var _startPassWork = function () {
		$('div[data-form=send-message-js]').hide();
		$('div[data-form=pass-work-js]').hide();
		$('.track-form-js').hide();

		$('#track-send-message-button')
			.off('click', _onSendMessageButtonClick)
			.on('click', _onSendMessageButtonClick)
			.off('mouseenter mouseleave')
			.show();

		$('#track-pass-work-button')
			.off('click', _onPassWorkButtonClick)
			.on('click', _onPassWorkButtonClick)
			.show();

		$('.send-message-js').show();
		return true;
	};

	var _onSendInstructionButtonClick = function () {
		TrackUtils.sendMessageFromInstructionForm(); return false;
	};

	var _onSendInstructionButtonMouseenter = function () {
		if($("#track-instruction-button").is(":visible")) {
			if ($("#is_instruction").is(":visible")) {
				$("#is_instruction").hide();
			}
			$("#is_text").fadeIn();
		}
	};

	var _onSendInstructionButtonMouseleave = function () {
		if($("#track-instruction-button").is(":visible")) {
			if ($(":hover").filter("#is_text").length === 0) $("#is_text").fadeOut();
		}
	};

	var _onTrackInstructionButtonClick = function () {
		TrackUtils.submitInstructionForm();
	};

	var _onTrackInstructionButtonMouseenter = function () {
		if ($('#is_text').is(":visible")) {
			$('#is_text').hide();
		}
		$('#is_instruction').fadeIn();
	};

	var _onTrackInstructionButtonMouseleave = function () {
		if ($(':hover').filter('#is_instruction').length===0) $('#is_instruction').fadeOut();
	};

	var _onIsTextMouseleave = function () {
		$(this).fadeOut();
	};

	var _onIsInstructionMouseleave = function () {
		$(this).fadeOut();
	};

	// _sendMessageFromInstructionForm
	var _startSendInstruction = function () {
		$('div[data-form=send-message-js]').hide();
		$('div[data-form=pass-work-js]').hide();
		$('.track-form-js').hide();

		if(!$("#track-instruction-button").is(":visible")) {
			$('#is_text').hide();
		}

		$('#track-send-message-button')
			.off('click', _onSendInstructionButtonClick)
			.on('click', _onSendInstructionButtonClick)
			.off('mouseenter', _onSendInstructionButtonMouseenter)
			.on('mouseenter', _onSendInstructionButtonMouseenter)
			.off('mouseleave', _onSendInstructionButtonMouseleave)
			.on('mouseleave', _onSendInstructionButtonMouseleave)
			.show();

		$('#is_text')
			.off('mouseleave', _onIsTextMouseleave)
			.on('mouseleave', _onIsTextMouseleave);

		$('#track-instruction-button')
			.off('click', _onTrackInstructionButtonClick)
			.on('click', _onTrackInstructionButtonClick)
			.off('mouseenter', _onTrackInstructionButtonMouseenter)
			.on('mouseenter', _onTrackInstructionButtonMouseenter)
			.off('mouseleave', _onTrackInstructionButtonMouseleave)
			.on('mouseleave', _onTrackInstructionButtonMouseleave)
			.show();

		$('#is_instruction')
			.off('mouseleave', _onIsInstructionMouseleave)
			.on('mouseleave', _onIsInstructionMouseleave);

		$('.send-message-js').show();
		return true;
	};

	var _onSendMessageFromPassWorkFormButtonClick = function () {
		TrackUtils.sendMessageFromPassWorkForm(); return false;
	};

	var _startOnlyMessage = function () {
		$('div[data-form=send-message-js]').hide();
		$('div[data-form=pass-work-js]').hide();
		$('.track-form-js').hide();

		$('#message_body1').removeClass('js-required');

		$('#track-pass-work-button').hide();
		$('#track-instruction-button').hide();
		$('#track-send-message-button')
			.off('click', _onSendMessageFromPassWorkFormButtonClick)
			.on('click', _onSendMessageFromPassWorkFormButtonClick)
			.show();

		$('.send-message-js').show();
		return true;
	};

	// start  pass-work
	var _sendMessageFromPassWorkForm = function () {
		var lastAction = $('#fm_pass_action').val();
		$('#fm_pass_action').val('text');
		$("#track-send-message-button").attr('disabled','disabled');
		if(!$("#track-send-message-button").hasClass("option-request")){
			ajaxSendTrackMessage($('#form_pass_work'));
		}else{
			if($('#message_send_ajax').val() == 1) {
				ajaxSendTrackMessage($('#form_pass_work'));
			} else {
				$('#form_pass_work').submit();
			}
		}
		$('#fm_pass_action').val(lastAction);
		$('#message_body1').val('').trigger('input');
    $(".trumbowyg-editor").html('');
	};

	var _submitWorkFromPassWorkForm = function () {
		haveFiles = dialogFiles.totalFiles();
		if($('#message_body1').val() == '' && !haveFiles) {
			$('#message_body1').trigger('input');
			return false;
		}
		var lastAction = $('#fm_pass_action').val();
		$('#fm_pass_action').val('seller_check_order');

		if($('#message_send_ajax').val() == 1) {
			ajaxSendTrackMessage($('#form_pass_work'));
		} else {
			$('#form_pass_work').submit();
		}

		$('#fm_pass_action').val(lastAction);
		$('#message_body1').val('').trigger('input');
    $(".trumbowyg-editor").html('');
		$('#track-pass-work-button').hide();
	};
	// end  pass-work

	// start  Instruction
	var _sendMessageFromInstructionForm = function () {
		if($('#message_body1').val() == '') {
			return false;
		}

		var lastAction = $('#fm_pass_action').val();
		$('#fm_pass_action').val('text');

		if($('#message_send_ajax').val() == 1) {
			ajaxSendTrackMessage($('#form_pass_work'));
		} else {
			$('#form_pass_work').submit();
		}

		$('#fm_pass_action').val(lastAction);
		$('#message_body1').val('').trigger('input');
    $(".trumbowyg-editor").html('');

	};

	var _submitInstructionForm = function () {
		if($('#message_body1').val() == '' && !haveFiles) {
			return false;
		}

		var lastAction = $('#fm_pass_action').val();
		$('#fm_pass_action').val('instruction');

		if($('#message_send_ajax').val() == 1) {
			ajaxSendTrackMessage($('#form_pass_work'));
		} else {
			$('#form_pass_work').submit();
		}

		$('#track-instruction-button').hide();
		$('#fm_pass_action').val(lastAction);
		$('#message_body1').val('').trigger('input');
    $(".trumbowyg-editor").html('');
		$("#track-send-message-button").removeClass("white-btn");
		$("#track-send-message-button").addClass("green-btn");
	};
	// end  Instruction

	var _defSubmitPassWorkForm = function () {
		var lastAction = $('#fm_pass_action').val();
		if ($('#message_body1').val()=='' && (lastAction == 'text' || lastAction =='instruction')) {
			ajaxSendTrackMessage($('#form_pass_work'));
			return false;
		} else {
			return true;
		}
	};

    var _init = function(params) {};
    return {
        init:_init,
	    startShow: _startShow,
	    sendMessageFromPassWorkForm: _sendMessageFromPassWorkForm,
	    submitWorkFromPassWorkForm: _submitWorkFromPassWorkForm,
	    sendMessageFromInstructionForm: _sendMessageFromInstructionForm,
	    submitInstructionForm: _submitInstructionForm,
	    defSubmitPassWorkForm: _defSubmitPassWorkForm
    }
})();

function Timer(time, containerName, startTime, stop) {
	this.time = time;

	if ($('#' + containerName)) {
		this.container = containerName;
	} else {
		return false;
	}
	this.curTime = startTime;

	function execTimer(time, stop) {
		var amount = time - this.curTime;
		if (amount <= 0) {
			setExpire();
		} else {
			setTime(amount);
			if (stop !== true) {
				this.curTime++;
				var timer = setTimeout(function () {
					execTimer(time);
				}, 1e3);
				$('#' + containerName).data('timer', timer);
			}
			else {
				var timer = $('#' + containerName).data('timer');
				if (timer) {
					clearTimeout(timer);
				}
			}
		}
	}

	function setExpire() {
		var out = "<div class='countbox-num'><div id='countbox-days1' class='clockExpire'><span></span>0</div><div id='countbox-days2' class='clockExpire'><span></span>0</div><div id='countbox-days-text'>Дней</div><div class='colon'></div></div>" +
			"<div class='countbox-num'><div id='countbox-hours1' class='clockExpire'><span></span>0</div><div id='countbox-hours2' class='clockExpire'><span></span>0</div><div id='countbox-hours-text'>Часов</div><div class='colon'></div></div>" +
			"<div class='countbox-num'><div id='countbox-mins1' class='clockExpire'><span></span>0</div><div id='countbox-mins2' class='clockExpire'><span></span>0</div><div id='countbox-mins-text'>Минут</div><div class='colon'></div></div>" +
			"<div class='countbox-num' style='width: 137px;'><div id='countbox-secs1' class='clockExpire'><span></span>0</div><div id='countbox-secs2' class='clockExpire'><span></span>0</div><div id='countbox-secs-text'>Секунд</div></div>";
		document.getElementById(this.container).innerHTML = out;
	}

	function setTime(amount) {
		var out = "";
		var days = Math.floor(amount / 86400);
		var days1 = (days >= 10) ? days.toString().charAt(0) : '0';
		var days2 = (days >= 10) ? days.toString().charAt(1) : days.toString().charAt(0);
		amount = amount % 86400;
		var hours = Math.floor(amount / 3600);
		var hours1 = (hours >= 10) ? hours.toString().charAt(0) : '0';
		var hours2 = (hours >= 10) ? hours.toString().charAt(1) : hours.toString().charAt(0);
		amount = amount % 3600;
		var mins = Math.floor(amount / 60);
		var mins1 = (mins >= 10) ? mins.toString().charAt(0) : '0';
		var mins2 = (mins >= 10) ? mins.toString().charAt(1) : mins.toString().charAt(0);
		amount = amount % 60;
		var secs = Math.floor(amount);
		var secs1 = (secs >= 10) ? secs.toString().charAt(0) : '0';
		var secs2 = (secs >= 10) ? secs.toString().charAt(1) : secs.toString().charAt(0);
		out = "<div class='countbox-num'><div id='countbox-days1'><span></span>" + days1 + "</div><div id='countbox-days2'><span></span>" + days2 + "</div><div id='countbox-days-text'>Дней</div><div class='colon'></div></div>" +
			"" +
			"<div class='countbox-num'><div id='countbox-hours1'><span></span>" + hours1 + "</div><div id='countbox-hours2'><span></span>" + hours2 + "</div><div id='countbox-hours-text'>Часов</div><div class='colon'></div></div>" +
			"" +
			"<div class='countbox-num'><div id='countbox-mins1'><span></span>" + mins1 + "</div><div id='countbox-mins2'><span></span>" + mins2 + "</div><div id='countbox-mins-text'>Минут</div><div class='colon'></div></div>" +
			"" +
			"<div class='countbox-num' style='width: 137px;'><div id='countbox-secs1'><span></span>" + secs1 + "</div><div id='countbox-secs2'><span></span>" + secs2 + "</div><div id='countbox-secs-text'>Cекунд</div></div>";
		document.getElementById(this.container).innerHTML = out;
	}

	execTimer(this.time, stop);
}

function togglePortfolioItem(checkbox) {
	var $portfolioItem = $('.portfolio_item');
	if (checkbox.checked) {
		$portfolioItem.find('.portfolio_item_block').slideToggle("fast");
		$portfolioItem.find('.portfolio_item_description').slideToggle("fast");
		$portfolioItem.removeClass('portfolio_item--toggled');
	}
	else {
		$portfolioItem.find('.portfolio_item_block').slideToggle("fast");
		$portfolioItem.find('.portfolio_item_description').slideToggle("fast");
		$portfolioItem.addClass('portfolio_item--toggled');
	}
}

function showAgreeCancelReasonPopup() {
	var popupContent = $('.js-popup-confirm-cancel-reason__container').html();
	if (!popupContent) {
		return false;
	}
	show_popup(popupContent);
}

function showRemoveRatingPopup() {
	var popupContent = $('.js-popup-delete-rating__container').html();
	if (!popupContent) {
		return false;
	}
	show_popup(popupContent);
}

function confirmCancelReasonOrder(button) {
	var userSelect = parseInt(($(button).data('agree'))) === 1 ? 'agree' : 'disagree';
	$('input[name="agree_reason"]').val(userSelect);
	$('#confirm-cancel-reason-form').submit();
}

function removeOrderedExtraConfirmation(extraId) {
	var html = '' +
		'<div>' +
		'<form action="/send_mk" method="post">' +
		'<input type="hidden" name="extra_id" value="' + extraId + '" />' +
		'<input type="hidden" name="orderId" value="' + Track.orderId + '" />' +
		'<input type="hidden" name="action" value="remove_extra" />' +
		'<h1 class="popup__title f26">Подтверждение удаления</h1>' +
		'<hr class="gray" style="margin-bottom:32px;">' +
		'<div style="display:inline-block;width:100%;">' +
		'<p class="f15 pb50 ml10">Удалить дополнительную опцию?</p>' +
		'<button class="popup__button red-btn" onclick="$(this).closest(\'form\').submit();">Удалить</button>' +
		'<button class="popup__button white-btn pull-right popup-close-js" onclick="return false;">Отменить</button></div>' +
		'</div>' +
		'</form>' +
		'</div>';
	show_popup(html, 'popup_w500');
}

function customOptionsDaysSelectHtml() {
	return '<select id="extratime" class="js-new-extra-select js-new-extra-days textthree" name="customExtraTime[]" style="width:16%;">' +
		'<option value="0"> ' + t('{{0}} дней', [0]) + ' </option>' +
		'<option value="1"> ' + t('{{0}} день', [1]) + ' </option>' +
		'<option value="2"> ' + t('{{0}} дня', [2]) + ' </option>' +
		'<option value="3"> ' + t('{{0}} дня', [3]) + ' </option>' +
		'<option value="4"> ' + t('{{0}} дня', [4]) + ' </option>' +
		'<option value="5"> ' + t('{{0}} дней', [5]) + ' </option>' +
		'<option value="6"> ' + t('{{0}} дней', [6]) + ' </option>' +
		'<option value="7"> ' + t('{{0}} дней', [7]) + ' </option>' +
		'<option value="8"> ' + t('{{0}} дней', [8]) + ' </option>' +
		'<option value="9"> ' + t('{{0}} дней', [9]) + ' </option>' +
		'<option value="10"> ' + t('{{0}} дней', [10]) + ' </option>' +
		'</select>';
}

function customOptionsPricesSelectHtml() {
	var optionsHtml = '';

	$.each(optionPrices, function (i, opt) {
		optionsHtml += '<option data-seller-value="' + opt.priceWithComission + '" value="' + opt.id + '">';
		optionsHtml += opt.priceWithComissionStr;
		optionsHtml += '</option>';
	});

	return '<select name="customExtraPrice[]" class="js-new-extra-select js-new-extra-price textthree" style="width:16%;">' + optionsHtml + '</select>';
}

function addCustomOption() {
	if ('undefined' === typeof optionPrices || !optionPrices.length) {
		return;
	}

	var html =
		'<li class="order-extras__item extrasping-settings extra-field-block-css extra-edit-block-css custom">' +
		'<input name="customExtraName[]" maxlength="50" value="" style="width:378px;" class="textthree styled-input f14 pull-left m-wMax m-border-box" type="text">' +
		'<div class="new-order-extras__select-block">' +
		'<div class="pull-left">' + customOptionsPricesSelectHtml() + '</div>' +
		'<div class="pull-left">' + customOptionsDaysSelectHtml() + '</div>' +
		'<div class="dib pull-left" style="background-color:transparent;"></div>' +
		'<div class="new-order-extras__delete del-opt cur mt8 ml10 dib" data-id="0" title="Удалить">' +
		'<i class="ico-close-12"></i>' +
		'</div>' +
		'</div>' +
		'<div class="clear"></div>' +
		'</li>';

	var $html = $(html);

	$html.find('.js-new-extra-price').chosen({width: "100px", disable_search: true});
	$html.find('.js-new-extra-days').chosen({width: "90px", disable_search: true});
	$('.order-extras-list-bottom').append($html);
	newContentProcess($html);
}

function removeCustomOption(target) {
	$(target).closest('li').remove();
}

var isSuggestOptionsFormOpened = false;

function suggestOptionsToggle(target) {
	target.closest('#suggestExtras').find('.options').toggle();
	target.find('.icon').toggle();
	var $submitButton = $("#track-send-message-button");
	var $messageBody = $("#message_body1");
	if (isSuggestOptionsFormOpened) {
		$submitButton.val('Отправить сообщение');
		$submitButton.removeClass("option-request");
		$messageBody.prop('required', true);

    $('#foxPostForm input[type="checkbox"]').prop('checked', false);
    $('#foxPostForm .extrasping-settings.custom').remove();
	}
	else {
		$submitButton.val('Предложить');
		$submitButton.addClass("option-request");
		$messageBody.removeAttr('required');
	}
	isSuggestOptionsFormOpened = !isSuggestOptionsFormOpened;
}

function delNameFiles(id) {
	if ($('#fileName' + id).parent().find('.file-item').length == 1) {
		$('#fileName' + id).parent().parent().parent().find('textarea').prop('required', true);
	}
	$('#fileName' + id).remove();
	$('#fileInput' + id).remove();
}

function js_scrollToInstructions() {
	$('html, body').animate({
		scrollTop: $(".instruction-js").offset().top
	}, 200);
	$('a[data-action=instruction]').click();
}

function js_scrollToCheckWork() {
	var checkBlock = $(".checkWork-js:last");
	if (!checkBlock.is(':visible')) {
		$(".show-track-action").click();
	}
	$('html, body').animate({
		scrollTop: checkBlock.offset().top
	}, 200);
}

function js_sendInWork() {
	$('#sendInWork_js').submit();
}

function js_scrollToSendCheck() {
	$('html, body').animate({
		scrollTop: $("#track-pass-work-button").offset().top
	}, 200);
	// $('div[data-form=pass-work-js]').click();
}

function js_scrollToSendReview() {
	$('html, body').animate({
		scrollTop: $("[data-form=send-review-js]").offset().top
	}, 200);
}

function js_scrollToSendPortfolio() {
	$('html, body').animate({
		scrollTop: $("[data-form=send-portfolio-js]").offset().top
	}, 200);
	$('[data-form=send-portfolio-js]').click();
}

// @todo: conversations.js::scrollToFirstUnreadMessage() почти то же самое.
function scrollToFirstUnreadTrack() {
	// Если наверху есть уведомление то не скроллим
	if ($('#fox_notification_block').length) {
		return false;
	}

	var $firstUnread = $('.unread').first();

	var $trackToScroll = null;
	if ($firstUnread.length) {
		// Если есть непрочитанные то скроллим к первому непрочитанному
		$trackToScroll = $firstUnread;
	} else {
		// Иначе к последнему сообщению
		$trackToScroll = $('.step-block-order_item:last');
	}

	if ($trackToScroll && $trackToScroll.length) {
		var scrollTop = getElementTopToScroll($trackToScroll);
		window.scrollTo(0, scrollTop);
		return true;
	}

	return false;
}


function showNameFiles(input, form) {
	haveFiles = true;
	if (input.files && input.files[0]) {
		var counter = $(".file-item", "#list-files" + form).size();
		var cnt = Object.keys(input.files).length;
		// В safari Object.keys(input.files) добавляет в конец массива 'length'
		{
			if (Object.keys(input.files)[cnt - 1] == 'length') {
				cnt--;
			}
		}
		for (var i = 0; i < cnt; i++) {
			if (!(counter + i + 1 <= Track.maxFileCount)) {
				alert('Превышено максимальное количество файлов.');
				input.value = '';
				return false;
			}
			if (input.files[i].size > Track.maxFileSize) {
				alert('Размер файла не должен превышать 4Mb');
				input.value = '';
				return false;
			}
		}
		for (var i = 0; i < cnt; i++) {
			var fileName = input.files[i].name;
			var size = input.files[i].size;
			var len = fileName.length;
			var symb3 = fileName.substr(len - 3, len).toLowerCase();
			var symb4 = fileName.substr(len - 4, len).toLowerCase();
			var ico = '';
			var allow = true;
			if ($.inArray(symb3, ['doc', 'xls', 'rtf', 'txt']) != -1 || $.inArray(symb4, ['docx', 'xlsx']) != -1) {
				ico = 'doc';
			} else if ($.inArray(symb3, ['zip', 'rar']) != -1) {
				ico = 'zip';
			} else if ($.inArray(symb3, ['png', 'jpg', 'gif', 'psd']) != -1 || $.inArray(symb4, ['jpeg']) != -1) {
				ico = 'image';
			} else if ($.inArray(symb3, ['mp3', 'wav', 'avi']) != -1) {
				ico = 'audio';
			} else if ($.inArray(symb3, ["exe", "com", "dll", "sys", "drv", "bin", "ovl", "ovy", "dot"]) != -1) {
				ico = 'zip';
				allow = false;
			} else {
				ico = 'zip';
			}
			var id = genInputId.getID();
			input.id = 'fileInput' + id;
			input.className = 'fileInputs';
			var rightText = "";
			if (allow) {
				rightText = "<a class='remove-file-link' onclick=\"delNameFiles('" + id + "')\"></a>";
			}
			else {
				rightText = "<a class='ml10 cur color-red' style='display:block;float:right;' onclick=\"delNameFiles('" + id + "')\">Тип файла не поддерживается</a>";
			}
			html = "<div class='mb5 file-item' id='fileName" + id + "'><i class='ico-file-" + ico + " dib v-align-m'></i><span class='dib v-align-m ml10" + (allow ? "" : " color-red") + "'>" + fileName + "</span>" + rightText + "</div>";
			$("#list-files" + form).append(html);
			var listFileInput = document.createElement("input");
			listFileInput.type = "hidden";
			listFileInput.id = 'fileInput' + id;
			listFileInput.name = 'inputName_' + id;
			listFileInput.value = "sizeFile" + fileName.replace('"', '\"').replace("'", "\'") + size;
			$("#list-files" + form).append(listFileInput);
			formData.append('fileInput[]', input.files[i]);
		}
		$(input).after('<input onchange="showNameFiles(this, ' + form + ')" name="fileInput[]" type="file" multiple/>');
		$(input).hide();
		$('#message_body' + form).removeAttr('required');
	}
}

var deleteTrackFile = function ($target, fileId, msgId) {
	if (!confirm('Вы уверены?')) {
		return false;
	}

	$.ajax({
		type: "POST",
		url: '/api?method=track_file_delete',
		data: {'file_id': fileId, 'msgId': msgId},
		success: function (response) {
      if(response) {
        response = JSON.parse(response);
  			if (response.success == 1) {
  				var $track = $target.closest('.step-block-order_item');
  				$target.closest('.file-item').remove();

  				if ($track.hasClass('text_message')
  					&& !$track.find('.breakwords').text().length
  					&& !$track.find('.file-item').length) {
  					$track.remove();
  				}
  			}
      }
		}
	});
};

var toggleMessageButtonAction = function (event) {
	var $this = $(this);
	$this.parent().find('.js-toggle-message-button').addClass('inactive');
	$this.removeClass('inactive');
};

var sendMessageJsClick = function (event) {
	$('.send-review-js').hide();
	$('.send-portfolio-js').hide();
};

var sendPortfolioJsClick = function (event) {
	$("[data-form=send-portfolio-js]").show();
};

var hideConversationClick = function (event) {
	if ($('.show-conversation').hasClass('shown')) {
		$('.show-conversation img').removeClass('rotate180');
		$('.hidable-message').addClass('hide-by-conversation');
		$('.show-conversation').removeClass('shown');
	} else {
		$('.show-conversation img').addClass('rotate180');
		$('.hidable-message').removeClass('hide-by-conversation');
		$('.show-conversation').addClass('shown');
	}
};

var addCustomOptionClick = function (event) {
	event.stopImmediatePropagation();
	addCustomOption();
	return false;
};

var removeCustomOptionClick = function (event) {
	event.stopImmediatePropagation();
	removeCustomOption(this);
};

var addPackageStopClick = function (event) {
	$('#addpackagestop').submit();
};

var upgradePackageStopClick = function (event) {
	$('#upgradepackagestop').submit();
};

var prdDescriptionClick = function (event) {
	var $this = $(this).toggleClass('clicked');
	if ($this.hasClass('clicked')) {
		$this.text('Свернуть описание').next().slideDown(SLIDE_DURATION);
	}
	else {
		$this.text('Развернуть описание').next().slideUp(SLIDE_DURATION);
	}
};

var jsDodjiCommentEditClick = function (event) {
	$('.prd-comment-edit__link').trigger('click');
};

var prdCommentEditClick = function (event) {
	var $this = $(this).toggleClass('clicked');
	if ($this.hasClass('clicked')) {
		$this.text('Отменить редактирование').next().slideDown(SLIDE_DURATION);
	}
	else {
		$this.text('Редактировать отзыв').next().slideUp(SLIDE_DURATION);
	}
};

var deletePortfolioClick = function (event) {
	var content = $('.js-popup-delete-portfolio__container').html();
	show_popup(content, 'popup-delete-portfolio');
};

var ratingCommentEditClick = function (event) {
	var $this = $(this).toggleClass('clicked');
	if ($this.hasClass('clicked')) {
		$this.text('Отменить редактирование').next().slideDown(SLIDE_DURATION);
	}
	else {
		$this.text('Редактировать ответ').next().slideUp(SLIDE_DURATION);
	}
};

var trackExtrasItemClick = function (event) {
	var id = $(this).data('id');
	var $checkbox = $('.styled-checkbox[data-id=' + id + ']');

	if ($checkbox.prop('checked')) {
		var $target = $(event.target);
		if (!$target.is('.chosen-container') && $target.closest('.chosen-container').length === 0) {
			$checkbox.prop('checked', false);
		}
	}
	else {
		$checkbox.prop('checked', true);
	}

	var $addExtraStopSubmit = $('#addextrastop button.submit');
	if ($('.styled-checkbox:checked').length > 0) {
		$addExtraStopSubmit.removeClass('disabled').prop('type', 'submit');
	}
	else {
		$addExtraStopSubmit.addClass('disabled').prop('type', 'button');
	}
	var price = 0;
	var extras = $('.order-extras-list li input[type=checkbox]:checked');
	for (var i = 0; i < extras.length; i++) {
		var $extras = $(extras[i]);
		price += (clearPriceStr($extras.data('price')) * $('#extra_count' + $extras.data('id') + " option:checked").val());
	}
	$('#addextrastop button.submit span').text(price);
};

var ratingBlockReviewGoodClick = function (event) {
	$('.rating-block-review .active').removeClass('active');
	$(this).addClass('active');
	$('#rating-block-review_good-js').prop('checked', true);
};

var ratingBlockReviewBadClick = function (event) {
	$('.rating-block-review .active').removeClass('active');
	$(this).addClass('active');
	$('#rating-block-review_bad-js').prop('checked', true);
};

var trackGroupBtnDataFormClick = function (event) {
	$('.track-form-js').hide();
	$('.' + $(this).attr('data-form')).show();
};

var acceptOrderJsClick = function (event) {
	$('#accept-order').val('1');
	$('#accept-refuse-order-js').submit();
};

var attachClick = function ($el, fn) {
	if ($el.length) {
		var event = 'click';
		$el.off(event, fn).on(event, fn);
	}
};

var showTrackAll = function (event) {
	event.preventDefault();
	$('.step-block-order_item.hide').addClass('show-track-reset-hide').removeClass('hide');
	$('.show-track').addClass('hide');
  $('.show-track-hide').removeClass('hide');
};

var showTrackAllHide = function (event) {
	event.preventDefault();
	$('.step-block-order_item.show-track-reset-hide').addClass('hide').removeClass('show-track-reset-hide');
	$('.show-track-hide').addClass('hide');
  $('.show-track').removeClass('hide');
};

var formSubmited = false;

var newContentProcess = function (context) {
	// Добавляем действия над сообщениями.
	$('.text_message:not(.has-operations)', context).each(function () {
		addItemOperations($(this));
	});

	attachItemOperations(context);

	//attachClick($('.arbitrage-link', context), showArbitrageCheckPopupClick);
	attachClick($('#add-custom-option', context), addCustomOptionClick);
	attachClick($('.new-order-extras__delete', context), removeCustomOptionClick);

	attachClick($('.hide-conversation, .show-conversation', context), hideConversationClick);
	attachClick($('.show-track-action', context), showTrackAll);
  attachClick($('.show-track-action-hide', context), showTrackAllHide);
	attachClick($('.js-toggle-message-button', context), toggleMessageButtonAction);
	attachClick($("[data-form=send-message-js]", context), sendMessageJsClick);
	attachClick($("[data-form=send-portfolio-js]", context), sendPortfolioJsClick);

	attachClick($('#addpackagestop .submit', context), addPackageStopClick);
	attachClick($('#upgradepackagestop .submit', context), upgradePackageStopClick);

	attachClick($('.prd-description__link', context), prdDescriptionClick);

	attachClick($('.js-prd-comment-edit__link', context), jsDodjiCommentEditClick);
	attachClick($('.prd-comment-edit__link', context), prdCommentEditClick);

	attachClick($('.portfolio-edit__link', context), js_scrollToSendPortfolio);
	attachClick($('.js-track-form__delete-portfolio', context), deletePortfolioClick);


	attachClick($('.prd-rating-comment-edit__link', context), ratingCommentEditClick);

	attachClick($('.track-extras-list li', context), trackExtrasItemClick);

	attachClick($('.js-cancel-track__button', context), showAgreeCancelReasonPopup);

	attachClick($('.js-prd-comment-remove__link', context), showRemoveRatingPopup);

	attachClick($('.js-track-form__popup-confirm-link', context), show_popup_confurm);
  attachClick($('.js-track-form__popup-start-link', context), show_popup_startorder);

	attachClick($('.rating-block-review_good', context), ratingBlockReviewGoodClick);
	attachClick($('.rating-block-review_bad', context), ratingBlockReviewBadClick);

	attachClick($('.track-page-group-btn>[data-form]', context), trackGroupBtnDataFormClick);

	attachClick($('#accept-order-js', context), acceptOrderJsClick);

  attachClick($('.prd-count>div', context), prdExtrasPlusMinus);

  attachClick($('.question-block-track-page', context), questionBlockTrackPageMobileClickHide);

	$('.similar_data select', context).change(function () {
		var id = $(this).val();
		similarData.saveInputData();
		if ($.isNumeric(id)) {
			similarData.loadOrderData(id);
		} else {
			similarData.loadInputData(id);
		}
		similarData.saveLastAction(id);
	});

	$('.step-block-order', context)
		.on('click', '#track-send-to-completion', function () {
			if (!formSubmited) {
				formSubmited = true;
				var rejectName = 'reject' + $(this).data('track_id');
				document[rejectName].submit();
			}
		})
		.on('click', '#track-send-check-done', function () {
			if (!formSubmited) {
				formSubmited = true;
				var confirmName = 'confirm' + $(this).data('track_id');
				document[confirmName].submit();
			}
		});

	$('.track-packages-list select', context).change(function (e) {
		var $this = $(this);
		var price = $this.data('price') * $this.find('option:checked').val();
		$('#addpackagestop button.submit span').text(price);
	});

};

//фикс для разворачивающихся списков
var questionBlockTrackPageMobileClickHide = function (e) {
    if($(window).width() <= 767
        && !$(e.target).parents('.question-block-track-page_hidden').length
        && !$(e.target).hasClass('question-block-track-page_hidden'))
    {
        $(this).find('.question-block-track-page_hidden').toggleClass('m-db');
        $(this).find('.ico-arrow-down').toggleClass('m-rotate180');
    }
};

//Плюс/Минус для "Закажите дополнительно"
var prdExtrasPlusMinus = function (e) {

	e.stopPropagation();

	var input = $(this).siblings('input');

    if ($(this).hasClass('prd-count_minus')) {
        if (parseInt(input.val()) == 1) {
            return false;
        }
        input.val(parseInt(input.val()) - 1);
    } else {
        if (parseInt(input.val()) >= parseInt(input.attr('data-max'))) {
            return false;
        }
        input.val(parseInt(input.val()) + 1)
    }

    var parntLi = $(this).parents('li');

    parntLi.find('select').val(input.val());

    parntLi.find('.styled-checkbox').prop('checked', false);
    parntLi.click();

};

var countboxBehavior = function () {
	var $countbox = $('#countbox');

	if (Track.hasCountbox) {
		if (!$countbox.length) {
			$('#tracks-wrapper').prepend('<div id="countbox"></div>');
		}

		// Если обратный отсчет должен выводиться, но мы в состояние предложения отмены заказа,
		// то выводить выводим, но останавливаем.
		if (Track.isCancelRequest) {
			Timer(Track.deadline, "countbox", Track.stopedTimeCancelRequest, true);
		}
		else {
			Timer(Track.deadline, "countbox", Track.time, false);
		}
	}
	else {
		if ($countbox.length) {
			$countbox.remove();
		}
	}
};


function removeMessage() {
	var $msg = $(this).closest('.text_message');
	var itemId = $msg.data('track-id');
  var isAdmin = $msg.data('isadmin');
	var html = '' +
		'<div>' +
		'<form action = "/send_mk" class="js-remove-message-form" method="post">' +
		'<input type="hidden" name="itemId" class="js-form-field-id" value="' + itemId + '" />' +
		'<input type="hidden" name="orderId" class="js-form-field-id" value="' + Track.orderId + '" />' +
    (isAdmin == '1' ? '<input type="hidden" name="is_admin_get" class="js-form-field-id" value="1" />' : '') +
		'<input type="hidden" name="action" value="remove" />' +
		'<h1 class="popup__title f26">Подтверждение удаления</h1>' +
		'<hr class="gray" style="margin-bottom:32px;">' +
		'<div style="display:inline-block;width:100%;">' +
		'<p class="f15 pb50 ml10">Удалить сообщение?</p>' +
		'<button class="popup__button red-btn" onclick="$(this).closest(\'form\').submit(); return false;">Удалить</button>' +
		'<button class="popup__button white-btn pull-right popup-close-js" onclick="return false;">Отменить</button></div>' +
		'</div>' +
		'</form>' +
		'</div>';
	show_popup(html);
}

function editMessage() {
	var $msg = $(this).closest('.text_message');
	var trackId = $msg.data('track-id');
  var isAdmin = $msg.data('isadmin');

	var messageText = replaceTextMessage($msg.find('.breakwords').text());
	var messageFiles = $msg.find('.track-files').data('jsonFiles');
	var popupContent = '<h1 class="popup-mesage-edit__title f26">Редактирование</h1>\
			<hr class="gray mt20" style="margin-bottom:20px;">\
			<form action = "/send_mk" class="nonajaxy clearfix" enctype="multipart/form-data" method="post" data-ispopup="1" onsubmit="ajaxSendTrackMessage($(this), \'#edit-files-conversations\'); return false;">\
			<input type="hidden" class="js-send-message-action" name="action" value="edit" />' +
      (isAdmin == '1' ? '<input type="hidden" name="is_admin_get" class="js-form-field-id" value="1" />' : '') +
			'<input type="hidden" name="trackId" value="' + trackId + '">\
					<div class="b-popup-content">\
							<textarea  class="styled-input message_body" style="overflow: auto;" id="popup-textarea" name="message" rows="3">' + messageText + '</textarea>' +
              (!isAdmin ?
                '<div class="file-wrapper-list-edit">\
  									<div class="dialog__files mt10">\
  									<div id="edit-files-conversations" class="add-files"></div>\
  							</div>' : '') +
							'</div>\
							<div class="wrap-action-button">\
							<input class="btn-send-message-edit green-btn popup__button" name="commit" value="Сохранить" type="submit">\
							<input class="white-btn white-btn_no-hover btn-hover-red popup__button pull-right" name="commit" value="Отменить" type="button" onclick="$(\'.popup-close\').click(); return false;"></div>\
					</div>\
			</form>';
	show_popup(popupContent, 'popup-new popup-mesage-edit');
  if(!isAdmin) {
  	dialogFilesEdit = new FileUploader({
  		files: messageFiles ? messageFiles : {},
      deleteCallback: deleteTrackFileCallback,
      selector: '#edit-files-conversations',
  		input: {
  			name: 'conversations-files-edit'
  		},
      cot_ext: 'marketorders',
      cot_cat: 'msg'
  	});
  }
}

var addItemOperations = function ($item) {
	var isUnread = $item.hasClass('unread');
	var isOut = $item.hasClass('out');
	var isEditable = $item.hasClass('editable');
  var isEditableImp = $item.hasClass('edit-important');

	var html = '<div class="message-head_wrap">' +
		'<div class="message-icons floatright">';

	if (isEditableImp || (isOut && isUnread && isEditable)) {
		html += '<div class="floatright"><a href="javascript:void(0);" class="remove-item btn-edit mr10 dib" title="Удалить"><i class="icon ico-trash-18"></i></a></div>';
		html += '<div class="floatright"><a href="javascript:void(0);" class="edit-item btn-edit mr10 dib" title="Изменить"><i class="icon ico-edit"></i></a></div>';
	}

	html += '</div>'; // .message-icons
	html += '</div>'; // .message-head_wrap

	$item.prepend(html).addClass('has-operations');
};

var attachItemOperations = function (context) {
	$('.remove-item', context).on('click', removeMessage);
	$('.edit-item', context).on('click', editMessage);
};

$(document).on('submit', '.js-remove-message-form', function () {
	var $form = $(this);
	$.post($form.attr('action'), $form.serialize(), function (response) {
		var itemId = $form.find('.js-form-field-id').val();
		var $message = $(TRACK_ID_PREFIX + itemId);
		if (response.success) {
			$message.addClass('conversation-message-deleted');
			$message.find('.message-head_wrap').find('.message-icons').html('');
			$message.find('.breakwords').html('<span class="color-gray">Сообщение удалено пользователем</span>');
      $message.find('.track-files').remove();
		}
		else {
      $message.find('.breakwords').html('<span class="color-gray">Произошла ошибка при удалении сообщения</span>');
		}
		$('.popup-close-js').trigger('click');
	}, 'json');
	return false;
});

$(window).load(function () {
	countboxBehavior();

	readTrackService.init({orderId: Track.orderId, opponentId: Track.opponentId, actorType: Track.actorType});

	if (!scrollToFirstUnreadTrack()) {
		var needScroll = getGetParams()['scroll'] == '1';
		if (needScroll) {
			$('html, body').animate({
				scrollTop: $(".step-block-order_item:last").offset().top
			}, 200);
		}
	}

	isSuggestOptionsFormOpened = false;

	$('#is_text').hide();

	if ('undefined' !== typeof cancelReasons) {
		trackCancelModule.init({
			"initialButton": ".js-cancel-order-initial-button",
			"mainPopupTemplate": ".js-cancel-order-main-popup-template",
			"subTypePopupTemplate": ".js-cancel-order-subtype-popup-template",
			"mainPopupClass": "popup-order-cancel",
			"subTypePopupClass": "subtype-popup-order-cancel",
			"reasons": cancelReasons
		});
	}

	var portfolioPhoto = new DodjiPhotoModule();
	portfolioPhoto.init({
		maxCount: 1,
		fileWrapperClass: 'file-wrapper-block-rectangle',
		fileInputName: 'prd-photo',
		selectorBlock: '.portfolio-photo-block'
	});

	if ($('#worker_portfolio_form').length > 0) {
		document.getElementById('worker_portfolio_form').addEventListener('submit', portfolioPhoto.checkSubmitSize, false);
	}

	// одну пустую опцию мы должны иметь сразу.
	if (!$('#foxPostForm').find('li').length) {
		addCustomOption();
	}

	// @todo: пока мы не можем иметь несколько активных предложений в треках,
	// поскольку текущий механизм пушей не способен корректно обработать
	// действия пользователей в таких предложениях (кроме последнего).
	if ($('input[name=declineextrassuggestion]').length) {
		$('#suggestExtras').hide();
	}

	newContentProcess(document);

    $(document).on("input keyup keydown", "#message_body", function () {
    	var button = $(".btn-disable-toggle");
        //if (StopwordsModule._testContacts($(this).val()).length == 0) {
        //    button.removeClass('disabled').prop('disabled', false);
        //} else {
        //    button.addClass('disabled').prop('disabled', true);
        //};
    });
});

function editReport(trackId, lastEdit, message) {
  if(trackId > 0) {
  	$("#track-id-" + trackId).find(".hide-edit-action").toggleClass('hide');
  	$("#track-id-" + trackId).find(".loadbar").toggleClass('enable');

  	if (message) {
  		$("#track-id-" + trackId).find(".report-message-block").html(message);
  		$("#track-id-" + trackId).find("#prd_report_message").html(message);
  	}
  } else {
    $('#tracks-wrapper').append(message);
  }
}

function removeReport() {
	$(".new-report").remove();
}

function hintInit() {
	$('.report-message').each(function () {
		descAreaHint.init($(this).find(".js-field-input-description"), $(this).find(".js-field-input-hint"), 0, 350);
	});
}
