/**
 * 
 * @authors Your Name (you@example.org)
 * @date    2017-07-28 18:35:19
 * @version $Id$
 */

var commonPageInit = function () {
	var createScrollBar = function () {
		var indicatorEl = $('.scroll-indicator');
		var scrollHeight = $('.content-height').height();
		var contentWrapHeight = $('.content-wrap').height() - $('.top-wrap').css('margin-top').match(/\d+/)[0];

		// 页面滚动时，指示器同步移动
		$('.content-wrap').scroll(function () {
			var scrollTop = $(this).scrollTop();
			scrollHeight = $('.content-height').height();

			indicatorEl.css('top', scrollTop * 100/(scrollHeight - contentWrapHeight)  + '%');
		});

		var clientLastY = 0;

		var mouseMoveHandler = function (evt) {
			var eleTop = indicatorEl.css('top').match(/\d+/)[0];
			var distance = clientLastY - evt.clientY;

			// 边界判定
			if (eleTop >= $('.scroll-bar').height()) {
				$('body').off('mousemove', mouseMoveHandler);
				indicatorEl.css('top', '100%');
				return;
			} else if (eleTop < 0) {
				$('body').off('mousemove', mouseMoveHandler);
				indicatorEl.css('top', '0');
				return;
			}

			indicatorEl.css('top', parseInt(eleTop) - distance + 'px');

			// 内容移动距离：内容高度*（指示器距离顶端距离／指示器高度）
			$('.content-wrap').scrollTop((scrollHeight - contentWrapHeight) * (indicatorEl.css('top').match(/\d+/)[0] / $('.scroll-bar').height()));

			clientLastY = evt.clientY;
		}

		$('body').on('mousedown', function (evt) {
			clientLastY = evt.clientY;

			$('body').on('mousemove', mouseMoveHandler);
		})

		$('body').on('mouseup', function (evt) {
			$('body').off('mousemove', mouseMoveHandler)
		})

		$('.scroll-top').on('click', function () {
			$('.content-wrap').scrollTop(0);
			indicatorEl.css('top', '0');
		})
	}

	createScrollBar();
}

$(document).ready(function () {
	commonPageInit();

	TD.imgPreload(function () {
		$('.m-loading').fadeOut(300);
	})
});
