/**
 * 
 * @authors Your Name (you@example.org)
 * @date    2017-06-28 11:39:08
 * @version $Id$
 */

var HomepageController = function () {
	// private data
	var imgList = $('.banner-item');
	var lastImg = $('.banner-inner').find('.current');

	var indicatorWrap = $('.banner-indicator-wrap');
	var indicatorList = $('.banner-indicator');
	var lastIndicator = $('.banner-indicator-wrap').find('.current');

	var index = 0;

	var marginLeftBegin = 0;

	// private api
	var carouselCompoInit = function (itemWrap, indicatorWrap, itemForm, indicatorForm, callback) {
		var itemList = itemWrap.children('li');
		var indicatorList = indicatorWrap.children('li');
		
		var lastItem = itemWrap.find('.current');
		var lastIndicator = indicatorWrap.find('.current');

		var index = 0;

		var getIndex = function (target, list) {
			for (i = 0; i < list.length; i++) {
				if (target === list[i]) {
					index = i;
				};
			};

			return index;
		};

		index = getIndex(lastItem, itemList);

		indicatorWrap.on('click',function (evt) {
			var evt = evt || window.event;
			var target = evt.target || evt.srcElement;

			function getNode(node) {
		        if (node.nodeName.toLowerCase() === 'li') {
		            return node;
		        } else if ($(node.parentNode) === $(this)) {
		            return 0;
		        } else {
		        	return getNode(node.parentNode);
		        }
		    }

		    var node = getNode(target);

			if (node) {
				// 排除二级菜单
				if ($(node).parent().hasClass('preview-thumb-sub')) {
					console.log('subthumb');
					return;
				}
				lastIndicator.hasClass('current') && lastIndicator.removeClass('current');
				$(node).hasClass('current') || $(node).addClass('current');

				index = getIndex(node, indicatorList);

				lastIndicator = $(node);

				// item animation select
				var itemFormApply = function () {
					var imgWidth = itemWrap.width();

					if (itemForm === 'slide') {

					}

					if (itemForm === 'crossSlide') {
						if (itemWrap.find('.preview-item>img').css('animation-name') === 'item-rightcome') {
							itemWrap.find('.preview-item>img').css('animation-name', 'item-leftcome');
							itemWrap.find('.current>img').css('animation-name', 'item-rightgo');
						} else {
							itemWrap.find('.preview-item>img').css('animation-name', 'item-rightcome');
							itemWrap.find('.current>img').css('animation-name', 'item-leftgo');
						}
					}
				};

				// indicator animation select
				var indicatorFormApply = function () {
					var indicatorHeight = itemWrap.height() * 0.136;

					if (indicatorForm === 'slide') {
						indicatorWrap.animate({
							top: (3 - index) * indicatorHeight
						}, 600, function () {

						});
					} else if (indicatorForm === 'fade') {

					} else if (indicatorForm === 'horizonSlide') {
						var mbPreviewThumbWrapWidth = $('.mb-preview-thumb-fixed').width();
						console.log(mbPreviewThumbWrapWidth)

						console.log(index, ((index - 7) * 33.3) + '%');
						indicatorWrap.animate({
							marginLeft: -index * mbPreviewThumbWrapWidth/3 + 'px'
						}, 600, function () {

						});

						marginLeftBegin = parseInt($('.mb-preview-thumb-wrap').css('margin-left').match(/\d+/)[0]);
					};
				}

				itemFormApply();
				indicatorFormApply();
				callback && callback(node);

				lastItem.hasClass('current') && lastItem.removeClass('current');
				$(itemList[index]).hasClass('current') || $(itemList[index]).addClass('current');

				lastItem = $(itemList[index]);
			}
		});
	}

	var previewSubItemHandler = function (seriesIndex, index) {
	    // 清除上一个产品定位
	    $('.preview-inner').find('.current').removeClass('current');
	    $('.preview-inner').find('.sub-current').removeClass('sub-current');

	    // 定位当前产品
	    var currentItem = $('.preview-item:nth-child(' + (seriesIndex+1) + ')')
	    var subcurrentItem = currentItem.find('.preview-item-subitem:nth-child(' + (index+1) + ')');

	    // 置为展示
	    currentItem.addClass('current');
	    subcurrentItem.addClass('sub-current');

	    // 灯光效果
	    var lightEl = currentItem.find('.preview-light-layer');
	    lightEl.css('opacity', 0);
	    lightEl.hasClass('light-effect') && lightEl.removeClass('light-effect');

	    setTimeout(function() {
	        lightEl.hasClass('light-effect') || lightEl.addClass('light-effect');
	    }, 300);
	}

	var previewSubThumbHandler = function () {
	    // 初始化选择第一类第一个为当前展示
	    var firstItemEl = $('.preview-item:nth-child(1)');
	    var firstThumbEl = $('.preview-thumb:nth-child(1)');
	    firstItemEl.addClass('current');
	    firstItemEl.find('.preview-item-subitem:nth-child(1)').addClass('sub-current');
	    firstThumbEl.addClass('current');
	    firstThumbEl.find('.preview-thumb-subitem:nth-child(1)').addClass('sub-current');
	    $('.preview-thumb-sub').css('marginTop', '0');

	    // 切换二级产品
	    $('.preview-thumb-subitem').on('click', function () {
	        var thumbWrapEL = $('.preview-thumb-wrap');

	        // 清除上一个定位
	        thumbWrapEL.find('.current').removeClass('current');
	        thumbWrapEL.find('.sub-current').removeClass('sub-current');

	        // 当前定位
	        $(this).parent().parent().addClass('current');
	        $(this).addClass('sub-current');

	        // 获取当前定位索引
	        var seriesIndex = thumbWrapEL.find('.current').index();
	        var index = $(this).parent().find('.sub-current').index();
	        console.log(thumbWrapEL.find('.current'))
	        
	        console.log(seriesIndex, index);
	        var thumbHeight = $('.preview-thumb-sub-fixed').height() * 0.136;
	        
	        $(this).parent().animate({
	            marginTop: (0 - index) * thumbHeight
	        }, 300, function () {

	        })

	        previewSubItemHandler(seriesIndex, index);
	    })
	}

	var previewSubThumbHandler2 = function () {
	    // 初始化选择第一类第一个为当前展示
	    var firstItemEl = $('.preview-item:nth-child(1)');
	    var firstThumbEl = $('.preview-thumb:nth-child(1)');
	    firstItemEl.addClass('current');
	    // firstItemEl.find('.preview-item-subitem:nth-child(1)').addClass('sub-current');
	    firstThumbEl.addClass('current');
	    // firstThumbEl.find('.preview-thumb-subitem:nth-child(1)').addClass('sub-current');
	    // $('.preview-thumb-sub').css('marginTop', '0');

	    // 切换二级产品
	    $('.preview-thumb').on('click', function () {
	        var thumbWrapEL = $('.preview-thumb-wrap');

	        // 清除上一个定位
	        thumbWrapEL.find('.current').removeClass('current');
	        // thumbWrapEL.find('.sub-current').removeClass('sub-current');

	        // 当前定位
	        $(this).parent().parent().addClass('current');
	        // $(this).addClass('sub-current');

	        // 获取当前定位索引
	        var seriesIndex = thumbWrapEL.find('.current').index();
	        // var index = $(this).parent().find('.sub-current').index();
	        console.log(thumbWrapEL.find('.current'))
	        
	        console.log(seriesIndex);
	        var thumbHeight = $('.preview-thumb-sub-fixed').height() * 0.136;
	        
	        // $(this).parent().animate({
	        //     marginTop: (0 - index) * thumbHeight
	        // }, 300, function () {

	        // })

	        // previewSubItemHandler(seriesIndex, index);
	    })
	}

	// 移动端ro产品选择处理
	var mobilePreviewSubHandler = function () {
		// 应对ip6以下的位置错乱
		// var topDis = $('.banner-item').height();
		// $('.mb-preview-thumb-fixed').css('top',topDis);
		

		// 暂时隐藏banner
		// $('.banner-wrap').hide();
		// $.fn.fullpage.destroy('all');

		// 应对ip6以下的位置错乱
		// var topDis = $(window).height() || $('.banner-wrap').height() || 'calc(100% - 375px)'; 
		// $('.mb-preview-thumb-fixed').css('top',topDis);

		// init
		$('.mb-preview-thumb-wrap').find('.current').removeClass('current');
		$('.mb-preview-thumb-wrap').find('.mb-preview-thumb').eq(0).addClass('current');
		$('.preview-inner').find('.preview-item').eq(0).addClass('current');
		$('.preview-inner').find('.current').find('.preview-item-subitem').eq(0).addClass('sub-current');

		$('.mb-preview-thumb').on('click', function (evt) {
			// 指示器定位
			$(this).parent().find('.current').removeClass('current');
			$(this).addClass('current');

			var seriesIndex = $(this).parent().find('.current').index();

			var mbPreviewThumbWrapWidth = $('.mb-preview-thumb-fixed').width();

			$(this).parent().animate({
				marginLeft: (-seriesIndex * mbPreviewThumbWrapWidth/3) + 'px'
			}, 600, function () {

			});

			marginLeftBegin = parseInt($('.mb-preview-thumb-wrap').css('margin-left').match(/\d+/)[0]);

			// 产品定位
			var currentItem = $('.preview-item:nth-child(' + (seriesIndex+1) + ')');

			$('.preview-inner').find('.current').removeClass('current');
			$('.preview-inner').find('.sub-current').removeClass('sub-current');

			currentItem.addClass('current');
			currentItem.find('.preview-item-subitem').eq(0).addClass('sub-current');

			//左右进出切换
			// var itemWrap = $('.preview-inner');
			// if (itemWrap.find('.preview-item-subitem>img').eq(0).css('animation-name') === 'item-rightcome') {
			// 	itemWrap.find('.preview-item-subitem>img').css('animation-name', 'item-leftcome');
			// 	itemWrap.find('.sub-current>img').css('animation-name', 'item-rightgo');
			// } else {
			// 	itemWrap.find('.preview-item-subitem>img').css('animation-name', 'item-rightcome');
			// 	itemWrap.find('.sub-current>img').css('animation-name', 'item-leftgo');
			// }

			// 灯光效果
		    var lightEl = currentItem.find('.preview-light-layer');
		    lightEl.css('opacity', 0);
		    lightEl.hasClass('light-effect') && lightEl.removeClass('light-effect');

		    setTimeout(function() {
		        lightEl.hasClass('light-effect') || lightEl.addClass('light-effect');
		    }, 300);
		})

		// 移动端二级切换
		var subItemChangeHandler = function () {
			var subItemEl = $('.preview-item-subitem');

			var subItemChange = function (direction) {
				var currentEl = $('.preview-inner').find('.current').find('.sub-current');
				var currentIndex = currentEl.index();
				var subItemNumber = currentEl.parent().children().length;

				// 只有一个子元素不需要继续执行
				if (subItemNumber === 1) {
					return;
				}

				var nextIndex;
				if (direction === 'last') {
					nextIndex = currentIndex - 1;
				} else if (direction === 'next') {
					nextIndex = currentIndex + 1;
				} else {
					return;
				}

				if (nextIndex < 0) {
					nextIndex = subItemNumber - 1;
				} else if (nextIndex > subItemNumber - 1) {
					nextIndex = 0;
				}

				if (nextIndex === currentIndex) {
					return;
				} else {
					console.log(nextIndex)
					currentEl.removeClass('sub-current');
					currentEl.parent().find('.preview-item-subitem').eq(nextIndex).addClass('sub-current');

					// 切换动画方向
					// if (direction === 'last') {
					// 	$('.preview-item img').css('animationName', 'item-rightgo');
					// 	$('.preview-item-sub>sub-current>img').css('animationName', 'item-leftcome');

					// 	$('.preview-item img').css('webkitAnimationName', 'item-rightgo');
					// 	$('.preview-item-sub>sub-current img').css('webkitAnimationName', 'item-leftcome');
					// } else if (direction === 'next') {
					// 	$('.preview-item img').css('animationName', 'item-leftgo');
					// 	$('.preview-item-sub>sub-current>img').css('animationName', 'item-rightcome');

					// 	$('.preview-item img').css('webkitAnimationName', 'item-leftgo');
					// 	$('.preview-item-sub>sub-current img').css('webkitAnimationName', 'item-rightcome');
					// }
				}
			}

			subItemEl.on('touchstart', function (evt) {
				var evt = evt || window.evt;
				//evt.preventDefault();

				var startPointX = evt.touches[0].clientX;
				var startPointY = evt.touches[0].clientY;
				var moveX, moveY, endPointX, endPointY;
				var isMoving = false;

				var touchmoveEventHandler = function (evt) {
					var evt = evt || window.evt;
					evt.preventDefault();

					if (isMoving) {
						return;
					}

					cliX = evt.touches[0].clientX;
					cliY = evt.touches[0].clientY;

					var moveDistance = cliX - startPointX;

					// console.log(moveDistance);

					if (moveDistance > 100) {
						isMoving = true;
						subItemEl.off('touchmove', touchmoveEventHandler);
						subItemChange('last');
					} else if (moveDistance < -100) {
						isMoving = true;
						subItemEl.off('touchmove', touchmoveEventHandler);
						subItemChange('next');
					} else {
						return;
					}
				}

				subItemEl.on('touchmove', touchmoveEventHandler);

				subItemEl.on('touchend', function (evt) {
					var evt = evt || window.evt;
					//evt.preventDefault();

					subItemEl.on('touchmove', touchmoveEventHandler);
				})
			})
		}

		subItemChangeHandler();
	}

	// 视频层处理
	var videoLayerHandler = function () {
        var videoObj = document.getElementById('videoObj');

        $('.video-tv').on('click', function () {
        	var videoSrc = $(this).data('video');

        	if (!videoSrc) {
    			console.log('视频不存在');
                alert('视频不存在');
                return;
	        }
	        
        	videoObj.src = videoSrc;

        	setTimeout(function () {
        		if (videoObj.networkState !== 3) {
	                $('.video-layer').show();
	                videoObj.play();
	            } else {
	                console.log('视频不存在');
	                alert('视频不存在');
	            }
        	}, 0)
        })

        $('.video-layer').on('click', function (evt) {
            var evt = evt || window.event;
            var target = evt.target || evt.srcElement;

            if (target.nodeName.toLowerCase() === 'video') {
                if (videoObj.paused === true) {
                    videoObj.play();
                } else {
                    videoObj.pause();
                }
            } else {
                videoObj.pause();
                videoObj.currentTime = 0;
                $(this).hide();
            }
        })
    }

    // mobile touchmove handler
    var mobileTouchmoveHandler = function () {
    	var mbPreviewThumbWrapEl = $('.mb-preview-thumb-wrap');

    	var touchStartX = 0;
    	var touchStartY = 0;
    	var disX = 0;
    	// var marginLeftBegin = mbPreviewThumbWrapEl.css('margin-left');
    	var translateX = marginLeftBegin;

    	var number = mbPreviewThumbWrapEl.children().length;
    	var index = 0;
    	var mbPreviewThumbWrapWidth = mbPreviewThumbWrapEl.width();

    	// var maxMarginLeft = mbPreviewThumbWrapWidth*index/number;
    	// var minMarginLeft = -mbPreviewThumbWrapWidth*(number-index-1)/number;
    	var maxMarginLeft = 0;
    	var minMarginLeft = -mbPreviewThumbWrapWidth*(number-1)/number;

    	var mbPreviewThumbReset = function () {
	    	var mbPreviewThumbWrapEl = $('.mb-preview-thumb-wrap');

	    	// mbPreviewThumbWrapEl.css('margin-left', '0px');
	    	// mbPreviewThumbWrapEl.css('margin-left', marginLeftBegin);
			mbPreviewThumbWrapEl.css('transform', 'translateX(0px)');
			mbPreviewThumbWrapEl.css('-webkit-transform', 'translateX(0px)');

			disX = 0;
			translateX = marginLeftBegin;
	    }

	  //   var mbPreventDefault = function (evt) {
			// evt.preventDefault();
	  //   }

    	mbPreviewThumbWrapEl.on('touchstart', function (evt) {
    		touchStartX = evt.touches[0].clientX;
			touchStartY = evt.touches[0].clientY;

			// $(document).on('touchmove', mbPreventDefault);
    	});

    	mbPreviewThumbWrapEl.on('touchmove', function (evt) {
    		// evt.stopPropagation();
    		evt.preventDefault();

    		disX = Math.ceil(evt.touches[0].clientX - touchStartX);
			//console.log(disX);

			if (disX > maxMarginLeft - translateX) {
				console.log('max', maxMarginLeft - translateX)
    			disX = maxMarginLeft - translateX;
    		} else if (disX < minMarginLeft - translateX) {
    			console.log('min', minMarginLeft - translateX)
    			disX = minMarginLeft - translateX;
    		}

			if (disX < -30) {
				mbPreviewThumbWrapEl.css('transform', 'translateX(' + disX + 'px)');
				mbPreviewThumbWrapEl.css('-webkit-transform', 'translateX(' + disX + 'px)');
				return;
			}

			if (disX > 30) {
				mbPreviewThumbWrapEl.css('transform', 'translateX(' + disX + 'px)');
				mbPreviewThumbWrapEl.css('-webkit-transform', 'translateX(' + disX + 'px)');
				return;
			}

			disX = 0;
    	});

    	mbPreviewThumbWrapEl.on('touchend', function (evt) {
    		// translateX = evt.changedTouches[0].clientX - touchStartX + translateX;
    		if (disX === 0) return;
    		console.log(translateX,disX,marginLeftBegin);
    		translateX += disX;
    		disX = 0;
    		console.log(translateX,disX,marginLeftBegin);
    		// if (translateX > mbPreviewThumbWrapWidth*index/7) {
    		// 	translateX = mbPreviewThumbWrapWidth*index/7;
    		// } else if (translateX < -mbPreviewThumbWrapWidth*(6-index)/7) {
    		// 	translateX = -mbPreviewThumbWrapWidth*(6-index)/7;
    		// }

    		mbPreviewThumbWrapEl.css('margin-left', translateX + 'px');
    		mbPreviewThumbWrapEl.css('transform', 'translateX(0px)');
    		mbPreviewThumbWrapEl.css('-webkit-transform', 'translateX(0px)');
    	});

    	// $('.mb-preview-thumb').on('click', function () {
    	// 	mbPreviewThumbReset();

    	// 	index = $(this).index();
    	// 	console.log(index);

    	// 	maxMarginLeft = mbPreviewThumbWrapWidth*index/number;
    	// 	minMarginLeft = -mbPreviewThumbWrapWidth*(number-index-1)/number;
    	// })

    	// $(document).off('touchmove', mbPreventDefault);
    }

	// public api
	this.defaultInit = function () {
		var inv = null;
		var browserType = TD.util.browserType();
		console.log(browserType);

		if (browserType !== 'Chrome' && browserType !=='Safari') {
			console.log('not webkit');
			$('.effect-layer').hide();
		}

		if ($('.nav-lang-current').find('.nav-lang-item').text() === '繁体') {
			$('.preview-item-name').css('font-family', '"LiSong Pro", "MingLiU", "Microsoft YaHei"');
			$('.preview-item-name').css('font-weight', '800');
		};

		$('.m-homepage').fullpage({
			slidesNavigation: true,
			slidesPosition: 'bottom',
			easingcss3: 'cubic-bezier(.62,.01,0,1)',
			scrollOverflow: true,
			normalScrollElements: '.preview-thumb-wrap',
			afterRender: function () {
				inv = setInterval(function () {
					$('.fp-next').click();
				}, 3000);

				$('.video-wrap').length && videoLayerHandler();
			},
			afterSlideLoad: function () {
				clearInterval(inv);
				inv = setInterval(function () {
					$('.fp-next').click();
				}, 3000);
			}
		});
	}

	this.preload = function () {
		TD.imgPreload(function () {
			$('.m-header').css('opacity', 1);
			$('.m-homepage').css('opacity', 1);
			$('.m-loading').fadeOut(300);
		})
	}

	this.mkPageInit = function () {
		carouselCompoInit($('.preview-inner'), $('.preview-thumb-wrap'), 'crossSlide', 'fade', function (target){
	        $('.preview-light-layer').css('opacity', 0);
	        $('.preview-light-layer').hasClass('light-effect') && $('.preview-light-layer').removeClass('light-effect');

	        setTimeout(function() {
	            $('.preview-light-layer').hasClass('light-effect') || $('.preview-light-layer').addClass('light-effect');
	        }, 300);
	    });
	}

	this.mkPageMobileInit = function () {
		// init 

		// 暂时隐藏banner
		// $('.banner-wrap').hide();
		// $.fn.fullpage.destroy('all');
		// $('.banner-item:nth-child(2)').hide();
		// $('.fp-slidesNav').hide();
		// $.fn.fullpage.reBuild();
		
		$('.preview-inner').find('.current').removeClass('current');
		$('.mb-preview-thumb-wrap').find('.mb-preview-thumb').eq(0).addClass('current');
		$('.preview-inner').find('.preview-item').eq(0).addClass('current');

		carouselCompoInit($('.preview-inner'), $('.mb-preview-thumb-wrap'), 'crossSlide', 'horizonSlide'), function () {
		}

		mobileTouchmoveHandler();
	}

	this.roPageInit = function () {
		// $('.preview-thumb-wrap').hover(function () {
	 //        $('.preview-thumb-wrap').css('paddingLeft', '1.6rem');
	 //        $('.preview-thumb-sub-fixed').css('right', '1.8rem');
	 //    }, function () {
	 //        $('.preview-thumb-wrap').css('paddingLeft', '0');
	 //        $('.preview-thumb-sub-fixed').css('right', '-1.6rem');
	 //    })

		// previewSubThumbHandler2();

		$('.preview-inner').find('.preview-item').eq(0).addClass('current');
		$('.preview-thumb-wrap').find('.preview-thumb').eq(0).addClass('current');

		carouselCompoInit($('.preview-inner'), $('.preview-thumb-wrap'), 'crossSlide', 'fade', function (target){
	        $('.preview-light-layer').css('opacity', 0);
	        $('.preview-light-layer').hasClass('light-effect') && $('.preview-light-layer').removeClass('light-effect');

	        setTimeout(function() {
	            $('.preview-light-layer').hasClass('light-effect') || $('.preview-light-layer').addClass('light-effect');
	        }, 300);
	    });
	}

	this.roPageMobileInit = function () {
		mobilePreviewSubHandler();
		mobileTouchmoveHandler();
	}
}
