$(function() {
	var picture_path = ''
	var act = 0
	var picture_li
	//检测表单
	var reg = /^\d+(\.\d+)?$/;
	//日期插件
	$(function() {
		$('.select_ch').change(function() {
			var input_val = $('.select_ch ').find("option:selected").text();
			$('.input_class').val(input_val);
		});
		var now = new Date();
		var time = now.getFullYear() + "-" + ((now.getMonth() + 1) < 10 ? "0" : "") + (now.getMonth() + 1) + "-" + (now.getDate() < 10 ? "0" : "") + now.getDate();
		$('#add-time').val(time);
		$.fn.datetimepicker.dates['zh-CN'] = {
			days: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"],
			daysShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六", "周日"],
			daysMin: ["日", "一", "二", "三", "四", "五", "六", "日"],
			months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
			monthsShort: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
			today: "今日",
			suffix: [],
			meridiem: ["上午", "下午"]
		};
		var $dpInput = $('.form-datetime-lang').datetimepicker({
			container: '#dateBox2',
			language: 'zh-CN',
			format: 'yyyy-mm-dd hh:ii',
			pickerPosition:'top-right',
		});
	});
	$('.forever').click(function() {
		if ($("#forever").prop('checked')) {
			$('.ty-time').hide();
		} else {
			$('.ty-time').show();
		}
	})
	if ($("#forever").prop('checked')) {
		$('.ty-time').hide();
	} else {
		$('.ty-time').show();
	}
	$("#ngad-Tjs-tianjia").click(function() {
		if ($.trim($('#code').val()) == '') {
			confirm('请输入广告位识别码');
			return false;
		}
		if ($.trim($('#name').val()) == '') {
			confirm('请输入广告名称');
			return false;
		}
		if ($('#sort').val() != '') {
			if (!reg.test($.trim($('#sort').val()))) {
				confirm('你输入的排序不合法，必须是一个数字');
				return false;
			}
		}
		// 拼接code
		var type = $('#ad_type').find('input');
		for(var i=0; i<3; i++){
			if(type.eq(i).prop('checked')){
				if(i == 1){
					var pictures = $('#picture_view').find('li');
					var code = ''
					for(var n=0; n<pictures.length; n++){
						var pic_inputs = pictures.eq(n).find('input')
						var img_code = '<a target="_blank" href="' +pic_inputs.eq(1).val() + '">' +
										'<img src="' +pic_inputs.eq(0).val() + '" width="' +pic_inputs.eq(3).val() + '" height="' +pic_inputs.eq(4).val() + '" alt="' +pic_inputs.eq(2).val() + '" title="' +pic_inputs.eq(2).val() + '" border="0" />' +
									'</a>'
						code += img_code;
					}
					$("#ad-code").val(code)
				}
				if(i == 2){
					var word_code = '<a target="_blank" href="' + $('#weburl').val() + '" style="color:' + $('#color').val() + '; font-size:' + $('#size').val() + '">' + $('#word').val() + '</a>'
					$("#ad-code").val(word_code)
				}
			}
		}

		var ad_code = $("#ad-code").val().replace(/;/gm, "%3B")
		ad_code = ad_code.replace(/&/gm, "%26")
		$("#ad-code").val(ad_code);
		$("#data").submit();
	})
	//必填提示 类名当作实参传进方法中
	//当输入框输入为空,失去焦点时,提示图标为交叉,
	//当输入框输入不为空,失去焦点时,提示图标为勾
	//广告位识别码必填标记
	ng_titian('ngco_Ojs_bitian');
	//广告名称必填标记
	ng_titian('ngco_Ojs_bitian2');
	//设置必填标记的方法
	function ng_titian(leiming) {
		var BiTianParent = $('.' + leiming).parent().parent('.am-form-group');
		var BiTianNext = $('.' + leiming).next('i');
		$(BiTianParent).addClass('am-form-error');
		$('.' + leiming).addClass('am-back-input');
		$('.' + leiming).blur(function() {
			if ($.trim($(this).val()) == '') {
				$(BiTianParent).removeClass('am-form-success');
				$(BiTianParent).addClass('am-form-error')
				$(BiTianNext).removeClass('am-icon-check');
				$(BiTianNext).addClass('am-icon-times');
				$('.' + leiming).removeClass('am-back-input');
			} else {
				$(BiTianParent).removeClass('am-form-error');
				$(BiTianParent).addClass('am-form-success')
				$(BiTianNext).removeClass('am-icon-times');
				$(BiTianNext).addClass('am-icon-check');
				$('.' + leiming).removeClass('am-back-input');
			}
		})
	}
	//页面中的input按钮事件
	$('.tpl-switch').find('.tpl-switch-btn-view').on('click', function() {
		$(this).prev('.tpl-switch-btn').prop("checked", function() {
			if ($(this).is(':checked')) {
				return false;
			} else {
				return true;
			}
		})
	})
	// 广告类型

	var type1 = $("#ad_type").find('input[checked]').attr('value')
	if (type1 == '1') {
		$('.ad_image').hide();
		$('.ad_word').hide();
		$('.ad_code').show();
		$('.weburl').show();
	}
	if (type1 == '2') {
		$('.ad_code').hide();
		$('.ad_image').show();
		$('.ad_word').hide();
		$('.weburl').hide();
	}
	if (type1 == '3') {
		$('.ad_code').hide();
		$('.ad_image').hide();
		$('.ad_word').show();
		$('.weburl').show();
	}
	// 添加图片用到
	// $('.am-no-layout').on('mouseover', 'li', function() {
	// 	$(this).find('.ty-button').show()
	// })
	// $('.am-no-layout').on('mouseout', 'li', function() {
	// 	$(this).find('.ty-button').hide()
	// })
	//模态框点击事件
	$('body').on('click', '[data-btn="add"],[data-btn="update"],[data-btn="remove"]', function() {
		picture_li = $(this).parents('.ewm-box')
		var btn = $(this).data('btn');
		switch (btn) {
			case 'remove':
				var parents = $(this).parents('li');
				var bool = confirm('确定要删除该图片吗？');
				if (bool) {
					parents.remove();
				}
				break;
			default:
				$('#imgInFo')[0].reset();
				switch (btn) {
					case 'update':
						$('.modal .am-modal-hd').text('更新图片信息');
						break;
					case 'add':
						$('.modal .am-modal-hd').text('图片上传管理');
						break;
				}
				if (btn == 'update') {
					var values = $(this).parents('.ewm-box').find('input')
					$('#picture_info').html(values.eq(2).val())
					$('#picture_url').attr('value', values.eq(1).val())
					$('#finalImg').attr('src', values.eq(0).val())
					picture_path = values.eq(0).val()
					$('#width').attr('value', values.eq(3).val())
					$('#height').attr('value', values.eq(4).val())
					act = 1
				} else {
					act = 0
				}
				$('.modal').modal({
					relatedElement: this,
					onConfirm: function() {
						var info = $('#picture_info').val()
						var url = $('#picture_url').val()
						var width = $('#width').val()
						var height = $('#height').val()
						var picture = '<li class="ewm-box">' +
							'<ul class="list-unstyled btn-box-group">' +
							'<li><button type="button" class="am-btn am-btn-success" data-btn="update"><i class="am-icon-pencil-square-o"></i>&nbsp;修改</button></li>' +
							'<li><button type="button" class="am-btn am-btn-danger" data-btn="remove"><i class="am-icon-remove ngsty-rem"></i>&nbsp;删除</button></li>' +
							'<li><button type="button" class="am-btn am-btn-secondary" data-btn="search"><span class="search1"><i class="am-icon-search ngsty-rem"></i>&nbsp;查看</span></button></li>' +
							'</ul>' +
							'<img src="' + picture_path + '" height="120" width="265" alt="' + info + '">' +
							'<input type="hidden" name="picture[]" value="' + picture_path + '"/>' +
							'<input type="hidden" name="picurl[]" value="' + url + '"/>' +
							'<input type="hidden" name="summary[]" value="' + info + '"/>' +
							'<input type="hidden" name="width[]" value="' + width + '"/>' +
							'<input type="hidden" name="height[]" value="' + height + '"/>' +
							'</li>'
						if (act == 1) {
							picture_li.replaceWith(picture);
						} else {
							if($("#finalImg").attr("src") != ""){
								$("#picture_view").append(picture);
							}else{
								confirm("请选择图片");
							}
							// 图片位置计算
							//img_position("ngar-uljs","ngar-Yjs");
						}
					}
				})
				break;
		}
	})
	//===========================
	//  在上传图片的弹出窗口,点击非图片区域,就隐藏窗口
	// ==========================
	$(".ngad-Jsj-click").on("click", function() {
		closeTailor(this);
	});
	$(".ngad-Ksj-change").on("change", function() {
		selectImg(this);
	});
	$(".ngad-Usj-click").on("click", function() {
		closeTailor(this);
	});
	//模态框， 右上角添加叉图标
	$("body").on("click", function() {
		var a_2 = "<a class='am-icon-close ngjs-a2' href='javascript: void(0)'  onclick='$(this).prev().click();'></a>";
		$(".am-pureview-actions").append(a_2);
		$(".ngjs-a2").addClass("ngph-a1");
		$(".ngjs-a2").prev().addClass("ngph-a2");
	})
	// 图片上传
	function imgChange(e1, e2) {
		e1.change(function() {
			$filePath = URL.createObjectURL(this.files[0]);
			$('#ngac_Nfu_box').find('img').attr('src', $filePath); //给此img元素的src重新赋值
			$("#ngac_Nfu_box").show(); // 选中图片后， 显示此box
			var reader = new FileReader();
			reader.readAsDataURL(this.files[0]); //读取文件
			// var fileName=this.files[0]['name']; //获取图片的名称
			reader.onload = function(e) { //读取完成回调
				imgBase = e.target.result;
				e2.val(imgBase);
			}
		})
	}
	$('body').on('click','[data-btn="search"]',function(){
		$(this).parents('.ewm-box').find('img').trigger('click');
	})
	//原始上传
	$('#originalImg').click(function() {
		$("#originalChoose").trigger('click');
	})
	// 上传进度
	function progressHandlingFunction(e) {
		var curr = e.loaded;
		var total = e.total;
		var process = Math.floor(curr / total * 100);
		$("#loading").show().text((process - 1) + '%');
		$("#true.am-modal-btn").addClass("true_active");
		$.AMUI.progress.set((process - 1) / 100);
	}
	$("#originalChoose").change(function() {
		$(this)[0].files[0]
		var formData = new FormData();
		formData.append("file", $(this)[0].files[0]);
		formData.append("action", 'upload');
		formData.append("dir", 'advertise');
		formData.append("filename", '');
		$.ajax({
			scriptCharset: 'UTF-8',
			type: 'post',
			url: '/api/admin_process',
			data: formData,
			cache: false,
			processData: false,
			contentType: false,
			dataType: 'json',
			xhr: function () {
				var myXhr = $.ajaxSettings.xhr();
				if (myXhr.upload) { //检查upload属性是否存在
					//绑定progress事件的回调函数
					myXhr.upload.addEventListener('progress', progressHandlingFunction, false);
				}
				return myXhr; //xhr对象返回给jQuery使用
			},
		}).success(function(data) {
			if(data.state == "FAILURE"){
				alert(data.msg)
			}else{
				var img = $('#tailoringImg').attr("src");
				$('#finalImg').attr('src', data.url)
				picture_path = data.url;
				$("#loading").text("100%").hide();
				        $.AMUI.progress.set(1);
				        $("#true.am-modal-btn").removeClass("true_active");
			}
		}).error(function() {
			alert("上传失败");
		});
	})
	//图片裁切
	function selectImg(file) {
		if (!file.files || !file.files[0]) {
			return;
		}
		var reader = new FileReader();
		reader.onload = function(evt) {
			var replaceSrc = evt.target.result;
			//更换cropper的图片
			$('#tailoringImg').cropper('replace', replaceSrc, false); //默认false，适应高度，不失真
		}
		reader.readAsDataURL(file.files[0]);
	}
	//关闭裁剪框
	function closeTailor() {
		$(".tailoring-container").toggle();
	}
	//弹出框水平垂直居中
	(window.onresize = function() {
		var win_height = $(window).height();
		var win_width = $(window).width();
		if (win_width <= 768) {
			$(".tailoring-content").css({
				"top": (win_height - $(".tailoring-content").outerHeight()) / 2,
				"left": 0
			});
		} else {
			$(".tailoring-content").css({
				"top": (win_height - $(".tailoring-content").outerHeight()) / 2,
				"left": (win_width - $(".tailoring-content").outerWidth()) / 2
			});
		}
	})();
	//弹出图片裁剪框
	$("#replaceImg").on("click", function() {
		$(".tailoring-container").toggle();
	});
	//图像上传
	//cropper图片裁剪
	$('#tailoringImg').cropper({
		aspectRatio: 1 / 1, //默认比例
		preview: '.previewImg', //预览视图
		guides: false, //裁剪框的虚线(九宫格)
		autoCropArea: 0.5, //0-1之间的数值，定义自动剪裁区域的大小，默认0.8
		movable: false, //是否允许移动图片
		dragCrop: true, //是否允许移除当前的剪裁框，并通过拖动来新建一个剪裁框区域
		movable: true, //是否允许移动剪裁框
		resizable: true, //是否允许改变裁剪框的大小
		zoomable: false, //是否允许缩放图片大小
		mouseWheelZoom: false, //是否允许通过鼠标滚轮来缩放图片
		touchDragZoom: true, //是否允许通过触摸移动来缩放图片
		rotatable: true, //是否允许旋转图片
		crop: function(e) {
			// 输出结果数据裁剪图像。
		}
	});
	//旋转
	$(".cropper-rotate-btn").on("click", function() {
		$('#tailoringImg').cropper("rotate", 45);
	});
	//复位
	$(".cropper-reset-btn").on("click", function() {
		$('#tailoringImg').cropper("reset");
	});
	//换向
	var flagX = true;
	$(".cropper-scaleX-btn").on("click", function() {
		if (flagX) {
			$('#tailoringImg').cropper("scaleX", -1);
			flagX = false;
		} else {
			$('#tailoringImg').cropper("scaleX", 1);
			flagX = true;
		}
		flagX != flagX;
	});
	//裁剪后的处理
	$("#sureCut").on("click", function() {
		if ($("#tailoringImg").attr("src") == null) {
			return false;
		} else {
			var cas = $('#tailoringImg').cropper('getCroppedCanvas'); //获取被裁剪后的canvas
			cas.toBlob(function(blob_url) {
				blob_url.lastModifiedDate = new Date();
				blob_url.name = 'picture.png';
				var formData = new FormData();
				formData.append("file", blob_url, 'picture.png');
				formData.append("action", 'upload');
				formData.append("dir", 'photo');
				formData.append("filename", '');
				$.ajax({
					type: 'post',
					url: '/api/admin_process',
					data: formData,
					cache: false,
					processData: false,
					contentType: false,
					dataType: 'json',
					xhr: function () {
						var myXhr = $.ajaxSettings.xhr();
						if (myXhr.upload) { //检查upload属性是否存在
							//绑定progress事件的回调函数
							myXhr.upload.addEventListener('progress', progressHandlingFunction, false);
						}
						return myXhr; //xhr对象返回给jQuery使用
					},
				}).success(function(data) {
					if(data.state == "FAILURE"){
						alert(data.msg)
					}else{
						var img = $('#tailoringImg').attr("src");
						$('#finalImg').attr('src', data.url)
						picture_path = data.url;
						$("#loading").text("100%").hide();
				        $.AMUI.progress.set(1);
				        $("#true.am-modal-btn").removeClass("true_active");
					}
				}).error(function() {
					alert("上传失败");
				});
			}); //转换为base64地址形式
			//关闭裁剪框
			closeTailor();
		}
	});
	//图片上传结束
	//底部调整
	var isChrome = navigator.userAgent.toLowerCase().match(/chrome/) != null;
	if (!isChrome) {
		$(".tpl-page-container .tpl-content-wrapper").addClass("R-wra");
		$(".tpl-page-container .tpl-left-nav").addClass("L-tpl");
	}
	// 点击上传图片按钮时，初始化模态框中的img
	$("#qrcodeUpload,#thumbnail,.addimg-js").on("click",function(){
		$("#finalImg").attr("src","");
		$("#true.am-modal-btn").addClass("true_active");
	})
})