$.ajaxSetup({
	headers: {
		'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
		'token': $('meta[name="app-token"]').attr('content'),
	}
});

// translate('Ik spreek Engels', {to: 'en'}).then(res => {
//     console.log(res.text);
//     //=> I speak English
// }).catch(err => {
//     console.error(err);
// });

// 首页菜单
function menuToggleShow(li) 
{
	var height = li.find('.pony-menu__submenu-panel-menu-item').eq(0).height();
	var length = li.find('.pony-menu__submenu-panel-menu-item').length;

	$('.pony-menu__submenu-panel').height(0);
	li.addClass('active').children('.pony-menu__submenu-panel').height(height*length);
	li.siblings('li').removeClass('active');

	return li;
}
$(function() {
	menuToggleShow($('.pony-menu > li').eq(0));
	$('.pony-menu__submenu-panel-menu-item').eq(0).addClass('active');

	$('.pony-menu > li').on('click', '.pony-menu__submenu-title', function() {
		if (!$(this).parent('li').hasClass('active')) {
			menuToggleShow($(this).parent('li'));
		} else {
			$('.pony-menu__submenu-panel').height(0);
			$(this).parent('li').removeClass('active').siblings('li').removeClass('active');
		}	
	});

	$('.pony-menu__submenu-panel-menu-item > a').on('click', function() {
		var li = $(this).parents('.pony-menu__submenu');
		menuToggleShow(li);

		$('.pony-menu__submenu-panel-menu-item').removeClass('active');
		$(this).parent('li').addClass('active');
	});

	// $("#errors-div").delay(5000).fadeOut('slow');
});

// 重新刷新页面，使用location.reload()有可能导致重新提交
function reloadPage()
{
	var location  = window.location;
	location.href = location.pathname + location.search;
}

//图片缓冲效果
function JumpObj(elem, range, startFunc, endFunc) {
	var curMax = range = range || 6;
   	startFunc  = startFunc || function(){};
	endFunc    = endFunc || function(){};
	var drct   = 0;
	var step   = 1;

	init();

	function init() { elem.style.position = 'relative';active() }
	function active() { elem.onmouseover = function(e) {if(!drct)jump()} }
	function deactive() { elem.onmouseover = null }

	function jump() {
		var t = parseInt(elem.style.top);
		if (!drct) motionStart();
		else {
			var nextTop = t - step * drct;
			if (nextTop >= -curMax && nextTop <= 0) elem.style.top = nextTop + 'px';
			else if(nextTop < -curMax) drct = -1;
		    else {
				var nextMax = curMax / 2;
				if (nextMax < 1) {motionOver();return;}
				curMax = nextMax;
				drct = 1;
			}
		}
		setTimeout(function(){jump()}, 200 / (curMax+3) + drct * 3);
	 }
	function motionStart() {
		startFunc.apply(this);
		elem.style.top='0';
		drct = 1;
	}
	function motionOver() {
		endFunc.apply(this);
		curMax = range;
		drct = 0;
		elem.style.top = '0';
	}

	this.jump = jump;
	this.active = active;
	this.deactive = deactive;
}

// 图片删除
// $('body').on('click', '.attachments .thumbnail-remove', function(e) {
// 	e.preventDefault();
// 	const parent = $(this).parents('.attachments');
// 	$(this).parent('.thumbnail').remove();
// 	var name = $(this).attr('data-name');
// 	if (name) {
// 		parent.append($('<input type="hidden" name="'+name+'" />'));
// 	}
// 	if ($(this).parents('.attachments').find('li').length < 1 && $(this).data('id')) {
// 		$('#' + $(this).data('id')).show();
// 	}
// });

//鼠标经过抖动效果
$(".login-user-message span a").each(function(k,img){
	new JumpObj(img,8);
});

//信息全选控制
function checkAll(e, itemName){
	var aa = document.getElementsByName(itemName);
	for (var i=0; i<aa.length; i++) {
		aa[i].checked = e.checked;
	}
	var all = document.getElementsByName(e.name);
	for (var i=0; i<all.length; i++) {
		all[i].checked = e.checked;
	}
}

function checkItem(e, allName){
	var all = document.getElementsByName(allName);
	if (!e.checked) {
		for (var i = 0; i < all.length; i++) {
			all[i].checked = false;
		}
	} else {
	    var aa = document.getElementsByName(e.name);
	    for (var i=0; i < aa.length; i++) {
	    	if (!aa[i].checked) {
	    		return false;
	    	};
	    }
	    for (var i = 0; i < all.length; i++) {
			all[i].checked = true;
		}
	}
}

//图片编辑-异步调取
$('body').on('click', '.attachments .thumbnail-edit', function(e) {
    e.preventDefault();
    $('#dialog-img').modal('show');
    var filename = $(this).parent('.thumbnail').data('name');
    var img      = $(this).parent('.thumbnail').data('img');
    var urlpath  = HOME_URL + "/admin/ad/imgget/" + filename;
    $('#filename').val(filename);
    $('#filepath').val(img);
	$.ajax({
		type: "GET",
		url: urlpath,
	   success: function(data) {
	        if(data){
	        	$('#adsname').val(data.adsname);
	        	$('#url').val(data.url);
	        	$('#detail').val(data.detail);
	        }
	   }
	});
});

//图片编辑-异步更新
$('body').on('click', '.btn-modal-confirm', function(e) {
	e.preventDefault();
	$(this).parents('#dialog-img').modal('hide');
	var urlpath  = HOME_URL + "/admin/ad/imgadd";
	var filename = $('#filename').val();
	var filepath = $('#filepath').val();
	var adsname  = $('#adsname').val();
	var url      = $('#url').val();
	var detail   = $('#detail').val();
	$.ajax({
		type: "POST",
		url: urlpath,
		data: {"filename":filename, "filepath":filepath, "adsname":adsname, "url":url, "detail":detail},
	    success: function(data) {
	        if (data.code == 200) {
	            $('#dialog-success').modal('show');
	        } else {
	            $('#dialog-tip').modal('show');
	        }
	   }
	});
});

// 图片删除-异步
$('body').on('click', '.attachments .thumbnail-flag-remove', function(e) {
    e.preventDefault();
    $(this).parent('.ads-thumbnail').remove();
});


//flag异部更新
function fetch_ajax(status, id, model)
{
	var requesturl = HOME_URL + '/admin/content/' + model;
    var operating  = $("#"+status+id).attr('data-operating');
    var obj = {
		status: status,
		id: id,
		operating: operating,
		rnd: new Date().toString()
	};
	$.post(requesturl, obj, function(data) {
		if (data.status == 'success') {
			var opt         = operating == 'open' ? 'close' : 'open';
			var removeClass = operating == 'open' ? 'changegray' : 'changegreen';
			var addClass    = operating == 'open' ? 'changegreen' : 'changegray';
			var text = $("#"+status+id).data(operating + '-text');
			$("#"+status+id).removeClass(removeClass).addClass(addClass).text(text);
			$("#"+status+id).attr('data-operating', opt); //重新赋值为 open
			if (data.content.enabled == 1 && model == 'lang') {
				var text = $("#enabled"+id).data(operating + '-text');
				$("#enabled"+id).removeClass(removeClass).addClass(addClass).text(text);
				$("#enabled"+id).attr('data-operating', opt);
				swal({ 
					title: "数据填充中...", 
					text: "请不要关闭当前窗口！",
					imageUrl: "../data/assets/images/loading6.gif",
					showConfirmButton: false,
				});
				var lang = $("#enabled"+id).data('slug');
				$.get(HOME_URL + '/admin/lang/add/' + lang, function(res) {
					if (res.status == 'success') {
						swal({ 
							title: "数据填充完成", 
							text: "3秒后自动关闭！",
							timer: 3000,
							type: "success",
							confirmButtonText: "关闭"
						});
					}
				});
			}
		}
	});
}

// Hiding Flash Messages
$('div.alert').not('.alert-important').delay(2000).fadeOut(350);

// var home = new Vue({
// 	el: '#home',
// 	data: {
// 		id: 0,
// 	},
// 	computed: {
// 		sidebar: function() {
// 			return navs[this.id].child;
// 		}
// 	},
// 	methods: {
// 		sidebarShow: function(id, event) {
// 			this.id = id;
// 			$('.topbar-nav-ul li').removeClass('active');
// 			$(event.target).parent().addClass('active');
// 		},
// 		navActive: function(event) {
// 			$(event.target).parent().addClass('active').siblings().removeClass('active');
// 		}
// 	}
// })


//更新排序
function update_orders(model) {
	var url = HOME_URL + '/admin/content/' + model + '?action=orders';
	$('.form-ajax').attr('action', url);
	$(".form-ajax").submit();
}


//批量转移，以及复制
$(function() {
	$('.all-submit').on('click', function(){
		var text    = $(this).data('text');
		var model   = $(this).data('model');
		var pid     = $('#pid').val();
		var url = HOME_URL + '/admin/content/' + model + '?action=' + $(this).data('action');
		if(pid < 1){
			$('.common').text('请选择要'+text+'的分类!');
			$('#dialog-common').modal('show');
			return false;
		}
		if($('.id:checked').length == 0){
			$('.common').text('请选择要'+text+'的内容!');
			$('#dialog-common').modal('show');
			return false;
		}
		$('.form-ajax').attr('action', url);
		$(".form-ajax").submit();  
	});
});


// var app = new Vue({
// 	el: '#app',
// 	data: {},
// 	methods: {
// 		listDelete: function(event) {
// 			var action = $(event.target).attr('action');
// 			swal({
// 			  title: "您确定要删除吗？",
// 			  type: "warning",
// 			  cancelButtonText: '取消',
// 			  confirmButtonText: '确定',
// 			  showCancelButton: true,
// 			  showLoaderOnConfirm: true,
// 			  closeOnConfirm: false
// 			},
// 			function(){
// 				$.ajax({ type: 'DELETE', url: action, success: function(msg) {
// 						reloadPage();
// 					}
// 				});
// 			});
// 		}
// 	}
// });


// Autocomplete */
(function($) {
	$.fn.autocomplete = function(option) {
		return this.each(function() {
			var $this = $(this);
			var $dropdown = $('<ul class="dropdown-menu" />');
			
			this.timer = null;
			this.items = [];

			$.extend(this, option);

			$this.attr('autocomplete', 'off');

			// Focus
			$this.on('focus', function() {
				this.request();
			});

			// Blur
			$this.on('blur', function() {
				setTimeout(function(object) {
					object.hide();
				}, 200, this);
			});

			// Keydown
			$this.on('keydown', function(event) {
				switch(event.keyCode) {
					case 27: // escape
						this.hide();
						break;
					default:
						this.request();
						break;
				}
			});

			// Click
			this.click = function(event) {
				event.preventDefault();

				var value = $(event.target).parent().attr('data-value');

				if (value && this.items[value]) {
					this.select(this.items[value]);
				}
			}

			// Show
			this.show = function() {
				var pos = $this.position();

				$dropdown.css({
					top: pos.top + $this.outerHeight(),
					left: pos.left
				});

				$dropdown.show();
			}

			// Hide
			this.hide = function() {
				$dropdown.hide();
			}

			// Request
			this.request = function() {
				clearTimeout(this.timer);

				this.timer = setTimeout(function(object) {
					object.source($(object).val(), $.proxy(object.response, object));
				}, 200, this);
			}

			// Response
			this.response = function(json) {
				var html = '';
				var category = {};
				var name;
				var i = 0, j = 0;

				if (json.length) {
					for (i = 0; i < json.length; i++) {
						// update element items
						this.items[json[i]['value']] = json[i];

						if (!json[i]['category']) {
							// ungrouped items
							html += '<li data-value="' + json[i]['value'] + '"><a href="#">' + json[i]['label'] + '</a></li>';
						} else {
							// grouped items
							name = json[i]['category'];
							if (!category[name]) {
								category[name] = [];
							}

							category[name].push(json[i]);
						}
					}

					for (name in category) {
						html += '<li class="dropdown-header">' + name + '</li>';

						for (j = 0; j < category[name].length; j++) {
							html += '<li data-value="' + category[name][j]['value'] + '"><a href="#">&nbsp;&nbsp;&nbsp;' + category[name][j]['label'] + '</a></li>';
						}
					}
				}

				if (html) {
					this.show();
				} else {
					this.hide();
				}

				$dropdown.html(html);
			}

			$dropdown.on('click', '> li > a', $.proxy(this.click, this));
			$this.after($dropdown);
		});
	}
})(window.jQuery);