$(document).ready(function(){
	var ctx = $("#ctx").val();//获取服务器地址
	
	/***************************    活动列表页    ***************************/
	
	$("#btn-create").click(function(){
		if($("#campaignId").val() == "" || $("#campaignId").val() == -1){
			$(this).attr("href","javascript:void(0);");
			bootbox.alert("请选择活动！");
			$(this).attr("title","请选择活动");
			return false;
		}
	});

	$('ul#campaignul_son_ul li').live("click",function(){
		$("#myform").attr("action",ctx+"/advertiser/main/ad/target/ad-group/list?campaignId="+$("#campaignId").val()+"&orderId="+$("#orderId").val()+"&advertiserId="+$("#advertiserId").val());
		refreshData();
	});
	
 	//状态全部、开启、停用
 	if($("#status").val() == 0 || $("#status").val() == ""){
 		$("#selectBar_status a:first").addClass("selectBar_change");
 		$("#status").val(0);
	}
 	$("#selectBar_status a").each(function(){
 		var value = $(this).attr("value");
 		if($("#status").val() == value){
 			$(this).addClass("selectBar_change").siblings('.selectBar_change').removeClass('selectBar_change');
 		}
 	});
 	$("#selectBar_status a").click(function(){
 		$("#status").val($(this).attr("value"));
 		refreshData();
 	});
 
	//开启,暂停
	$("#btn-enable,#btn-disable,#btn-delete").click(function(){
		if($(this).attr("id") == "btn-enable"){
			url = ctx+"/advertiser/main/ad/target/ad-group/enable";
		}else if($(this).attr("id") == "btn-disable"){
			url = ctx+"/advertiser/main/ad/target/ad-group/disable";
		}else if($(this).attr("id") == "btn-delete"){
			url = ctx+"/advertiser/main/ad/target/ad-group/delete";
		}
		singleOper($(this),url);
	});
			
	//批量开启,批量暂停
	$("#all-btn-enable,#all-btn-disable,#all-btn-delete").click(function(){
		if($(this).attr("id") == "all-btn-enable"){
			url = ctx+"/advertiser/main/ad/target/ad-group/enable";
		}else if($(this).attr("id") == "all-btn-disable"){
			url = ctx+"/advertiser/main/ad/target/ad-group/disable";
		}else if($(this).attr("id") == "all-btn-delete"){
			url = ctx+"/advertiser/main/ad/target/ad-group/delete";
		}
		batchOpear($(this),url);
	});
	
	/***************************    创建，编辑投放    ***************************/
	
	//请选择点击类型
 	if($("#main_perClickul").html()){
 		if($("#perClickType").val() == 0 || $("#perClickType").val() == ""){
 			$("#perClickul_span").text("请选择点击类型");
 		}
 		$('ul#perClick_son_ul li').each(function(){
 			if($(this).attr("value") == $("#perClickType").val()){
 				$("#perClickul_span").text($(this).text());
 			}
 		});
 		$("#perClick_son_ul").hide();
 		$('ul#perClick_son_ul li').live("click",function(){
 			$(this).parents('li').find('span').text($(this).html());
 			$("#perClickType").val($(this).attr("value"));
 			$("#perClickTypeName").val($(this).text());
 			$('#perClick_son_ul').hide(); //ul隐藏
 		});
 		$("#perClickul_span").on("click",function(){
 	 		$('#perClick_son_ul').show(); //ul显示
 	 	});
 		$("#perClickul_box").mouseleave(function(){
 	 		$('#perClick_son_ul').hide(); //ul隐藏
 	 	});
 	}
 	
 	//请选择曝光类型
 	if($("#main_perImpressionul").html()){
 		if($("#perImpressionType").val() == 0 || $("#perImpressionType").val() == ""){
 			$("#perImpressionul_span").text("请选择曝光类型");
 		}
 		$('ul#perImpression_son_ul li').each(function(){
 			if($(this).attr("value") == $("#perImpressionType").val()){
 				$("#perImpressionul_span").text($(this).text());
 			}
 		});
 		$("#perImpression_son_ul").hide();
 		$('ul#perImpression_son_ul li').live("click",function(){
 			$(this).parents('li').find('span').text($(this).html());
 			$("#perImpressionType").val($(this).attr("value"));
 			$("#perImpressionTypeName").val($(this).html());
 			$('#perImpression_son_ul').hide(); //ul隐藏
 		});
 		$("#perImpressionul_span").on("click",function(){
 	 		$('#perImpression_son_ul').show(); //ul显示
 	 	});
 		$("#perImpressionul_box").mouseleave(function(){
 	 		$('#perImpression_son_ul').hide(); //ul隐藏
 	 	});
 	}
	
	if($("#areasDiv").html()){
		var areasgeoPopup = $("#areas_popup")[0];
		var GEO_list;
		$('#btn-areas').click(function () {
			if (!areasgeoPopup) {
	            areasgeoPopup = new areasPopup({
	                width: '746px',
	                height: '435px',
	                title: '地域定向设定'
	     		});
	            var defaultValue = "不限";
	            var input = $('#areas').trigger('change');
	            var selectedIds = input.val() ? input.val().split(',') : null;
	            $('#areasconfirm').click(function(){
	                var pop= areasgeoPopup;
	                areasgeoPopup.hide();
	                input.val(Area.save());
	                var id = 'areas',selected = Area.save();
	                parent.$('#'+id).val(selected);
	                if (selected && $('input[type=checkbox]:not(:checked)').length) {
	                    //有选择 且 非全选的
	                    parent.$('#count-'+id)[0].innerHTML = selected.split(',').length;
	                    parent.$('#geo-all-'+id).hide();
	                    parent.$('#geo-selected-'+id).show();
	                }else{
	                    if(!$('input[type=checkbox]:not(:checked)').length){
	                        parent.$('#geo-all-'+id).find('.default_text')[0].innerHTML=defaultValue;
	                    }else{
	                        var val = defaultValue;
	                        parent.$('#geo-all-'+id).find('.default_text')[0].innerHTML=decodeURIComponent(val);
	                    }
	                    parent.$('#geo-all-'+id).show();
	                    parent.$('#geo-selected-'+id).hide();
	                }
	                parent.$(parent.document).trigger('setData');
				
	            });
	            //Area.init(GEO_LIST,selectedIds);
	            $.ajax({
	            	url: ctx+'/advertiser/main/ad/target/ad-group/getLocations',
	            	dataType:'json',
	            	success:function(GEO_LIST){
	            		Area.init(GEO_LIST,selectedIds);
	            		areasgeoPopup.show();
	            		GEO_list = GEO_LIST;
	            	},
	            	error:function(){
	            		alert('数据拉取失败，请检查您的网络连接是否可用');
	            	}
	            });
    		}else{
    			areasgeoPopup.show();
            }
        });
        
        $('#count-areas').click(function () {
            $('#btn-areas').trigger('click');
        });
        
        if ($('#areas').val()) {
            $('#geo-selected-areas').show();
            $('#geo-all-areas').hide();
            $('#count-areas')[0].innerHTML = $('#areas').val().split(',').length;
        } else {
            $('#geo-selected-areas').hide();
            $('#geo-all-areas').show();
        }
	
	}
	
	//时间定向
	$('#setting_list').unbind("mousedown").bind("mousedown",function(){
	 	var date = $("#dateRangePicker").val().split('to');
		var s_date = date[0];
		var e_date = date[1];
		var len_box = $(".time_box").find(".time_item").length;
		if(len_box > 6){
			bootbox.alert("最多只能添加6个时段");
		}else{
			if(s_date!=""&&e_date!=""){
				var datePickerOptions = {
					"startDate":s_date,
					"endDate":e_date
				}
				$("#quantum_list1").find("p").removeClass("pitchon");
				$('#setting_list').unbind("datepicker-apply").bind('datepicker-apply',function(event,obj){
					var date = $("#dateRangePicker").val().split('to');
				    var s_date = date[0];
					var e_date = date[1];
					var checked_date = new Array();
					var len = $(".setting .time_item").length;
					for(var i=0;i<len;i++){
						var json_check = {"startDate":$(".time_item").eq(i).find(".start_date").val(),"endDate":$(".time_item").eq(i).find(".end_date").val()};
						checked_date.push(json_check);
					}
					var startDate = obj.value.split('to')[0];
			   		var endDate = obj.value.split('to')[1];
					var flag = true;
			   		for(var j=0;j<checked_date.length;j++){
			   			if(startDate < checked_date[j].startDate && endDate < checked_date[j].startDate){
			   				console.log(startDate+":"+endDate)
			   				console.log(flag+":1");
			   			}else if(startDate > checked_date[j].endDate && endDate > checked_date[j].endDate){
			   				console.log(flag+":2");
			   			}else{
			   				flag=false;
			   			}
			   		}
			   		if(flag){
				   		var obj = $("#quantum_list1");
				   		if(obj.find(".pitchon").length){
				           	var timeData = obj.find(".pitchon").map(function(i,span){
				        		return $(span).attr("title");
				        	}).toArray().join(',');
				        }else{
				           	var timeData = -1;
				        }
				   		var html = '<div class="time_item"><p class="tr_data"><span class="inp"><input type="" class="start_date edit_time" readonly="readonly" value="'+startDate+'"></span><span class="inp"><input type="" class="end_date edit_time" readonly="readonly" value = "'+endDate+'"></span></p><button class="btn_del">删除</button><input class="json_date" type="hidden" value = "'+timeData+'"></div>';
				   		$(".setting .time_box").append(html);
				   		$(".time_box .time_item .btn_del").bind("click",function(e){
				   			$(this).parents(".time_item").remove();
				   		});
				   		$(".setting .tr_data").unbind("mousedown").bind("mousedown",function(){
				   				var obj_tr = $(this);
				   				var datePickerOptions_td = {
									"startDate":s_date,
									"endDate":e_date,
									getValue: function(){
										if (obj_tr.find(".start_date").val() && obj_tr.find(".end_date").val() )
											return obj_tr.find(".start_date").val() + ' to ' + obj_tr.find(".end_date").val();
										else
											return '';
									},
									setValue: function(s,s1,s2){
										obj_tr.find(".start_date").val(s1);
										obj_tr.find(".end_date").val(s2);
									}
								}
								obj_tr.unbind("datepicker-apply").bind('datepicker-apply',function(event,obj){
										var date = $("#dateRangePicker").val().split('to');
									    var s_date = date[0];
										var e_date = date[1];
										var checked_date = new Array();
										var other_box =obj_tr.parent().siblings();
										var len = other_box.length;
										for(var i=0;i<len;i++){
											var json_check = {"startDate":other_box.eq(i).find(".start_date").val(),"endDate":other_box.eq(i).find(".end_date").val()};
											checked_date.push(json_check);
										}
										console.log(checked_date);									
										var startDate = obj.value.split('to')[0];
			   							var endDate = obj.value.split('to')[1];
			   							var flag = true;
							   			console.log(checked_date);
							   			
							   			if(flag){
							   				var obj = $("#quantum_list1");
								   			if(obj.find(".pitchon")){
								            	var timeData = obj.find(".pitchon").map(function(i,span){
								        			return $(span).attr("title");
								        		}).toArray().join(',');
								            }else{
								            	var timeData = -1;
								            }
								   			obj_tr.find(".start_date").val(startDate);
									   		obj_tr.find(".end_date").val(endDate);
									   		console.log(timeData);
									   		console.log(obj_tr);
									   		obj_tr.parent().find(".json_date").val(timeData);
							   			}else{bootbox.alert("请选择正确时间！");}
						        });
						        obj_tr.dateRangePicker1(datePickerOptions_td);
						        $("#quantum_list1").find("p").removeClass("pitchon");
						        var chose_time = obj_tr.parent().find(".json_date").val();
					        	console.log(chose_time);
					        	if(chose_time!=-1&&chose_time!=""){
					        		var chose_arr = chose_time.split(",");
					        		for(var n=0;n<chose_arr.length;n++){
					        			$("#quantum_list1 p").eq(chose_arr[n]).addClass("pitchon");
					        		}
					        	}
			   				})
			   		}else{
			   			bootbox.alert("请选择正确时间！");
			    	}
				});
				$('#setting_list').dateRangePicker1(datePickerOptions);
			}else{
				bootbox.alert("请选择活动周期，在进行操作！");
			}
		}
	});
	
	if($("#divLBS").html()){
		$('#city_custom').cxSelect({
			selects: ['prov', 'city'],
			required: true,
			url:ctx+'/advertiser/main/ad/target/ad-group/getLocations'
		});
	}
	
	//初始校验表单
 	if($("#validateForm").html()){
 		$('#dateRangePicker').dateRangePicker();
 		$("#validateForm").autovalidate();
 		$(".input-text").focus(function(){
 			$(this).parent("div.input-group").find("span.help-inline").text("").removeClass("help-inline").addClass("spanVaildate");
 		});
 	}
	
 	$("#create-btn-save,#edit-btn-save").click(function(){
 		$("div.input-group").find("span.help-inline").text("").removeClass("help-inline").addClass("spanVaildate");
 		if (!$("#validateForm").validate()) {
			return false;
		}
 		var checked_date = new Array();
		var len = $(".setting .time_item").length;
		var jsondata = "[";
		for(var i=0;i<len;i++){
			if(i == 0){
				jsondata += '{"startDate":\"'+$(".time_item").eq(i).find(".start_date").val()+'\","endDate":\"'+$(".time_item").eq(i).find(".end_date").val()+'\","dehours":\"'+$(".time_item").eq(i).find(".json_date").val()+'\"}';
			}else{
				jsondata += ',{"startDate":\"'+$(".time_item").eq(i).find(".start_date").val()+'\","endDate":\"'+$(".time_item").eq(i).find(".end_date").val()+'\","dehours":\"'+$(".time_item").eq(i).find(".json_date").val()+'\"}';
			}
		}
		jsondata += "]";
		$("#sdayParting").val(jsondata);
		var falg = validateMoney();
		if(falg == false){
			return false;
		}
		//提示场景选择
		var placelist = $("#placeDiv input[type='checkbox']:checked");
		if(placelist.length == 0){
			bootbox.alert("场景为必填项，请选择！");
			return false;
		}
		$("#validateForm").submit();
		return false;
	});
	
	$("#create-btn-cancel,#edit-btn-cancel").click(function(){
		window.location.href = ctx+"/advertiser/main/ad/target/ad-group/list?campaignId="+$("#campaignId").val()+"&orderId="+$("#orderId").val()+"&advertiserId="+$("#advertiserId").val();
	});
	
	$("#totalBudget").blur(function(){
		validateMoney();
	});
	
	//场景
	if($(".place-edit").html()){
		savewifi();//获取保存的WiFi
		setting_date();//获取排期时间
		var place = $("#edit-place").val();
		var authArr = place.split(",");
		var checkboxs = $("#placeDiv input[type='checkbox']");
		checkboxs.each(function(i){
			for(var i = 0;i<authArr.length;i++){
				if($(this).val() == authArr[i]){
					$(this).attr("checked","true");
				}
			}
		});
	}
	
	//位置
	if($(".position-edit").html()){
		var position = $("#edit-position").val();
		var authArr = position.split(",");
		var checkboxs = $("#positionDiv input[type='checkbox']");
		checkboxs.each(function(i){
			for(var i = 0;i<authArr.length;i++){
				if($(this).val() == authArr[i]){
					$(this).attr("checked","true");
				}
			}
		});
	}
});
		
function exportExcel_list(){
	var searchValue = $("#searchValue").val();
	if(searchValue == "请输入关键字"){
		searchValue = "";
	}
	var param = "?orderId="+$("#orderId").val()+"&advertiserId="+$("#advertiserId").val()+"&status="+$("#status").val()+"&searchValue="+searchValue;
	$("#exportExcel").attr("href",$("#ctx").val()+"/advertiser/main/ad/target/campaign/exportDataReportExcel"+param);
	return false;
}

function validateMoney(){
	var reg=/^\d{1,8}\.?\d{0,2}$/;
	var $this = $("#totalBudget");
	if($this.val().match(reg)!=null){
		if(($this.val().indexOf('.') == -1 && $this.val().length > 8) || $this.val() <= 0){
			$this.css("box-shadow","0 0 6px #ff0000").attr('title','总预算金额整数位最多8位');
			$this.parent("div").find("span.spanVaildate").html("总预算金额整数位最多8位");
			return false;
		}else if($this.val() > parseInt($("#budget").val())){
			$this.css("box-shadow","0 0 6px #ff0000").attr('title','总预算不能大于订单总预算');
			$this.parent("div").find("span.spanVaildate").html("总预算不能大于订单总预算");
			return false;
		}else{
			$this.css("box-shadow","none").attr('title','');
			$this.parent("div").find("span.spanVaildate").html("");
		}
	}else{
		$this.css("box-shadow","0 0 6px #ff0000").attr('title','总预算金额整数位最多8位且最多有2位小数');
		$this.parent("div").find("span.spanVaildate").html("总预算金额整数位最多8位且最多有2位小数");
		return false;
	}
}

function setting_date(){
	var str_date = $("#sdayParting").val();
	console.log(str_date);  
	if(str_date!=""){
		var js_date = $.parseJSON(str_date);
		var html="";
		for(var i=0;i<js_date.length;i++){
			console.log(js_date[i].dehours);
			html += '<div class="time_item"><p class="tr_data"><span class="inp"><input type="text" class="start_date edit_time" readonly="readonly" value="'+js_date[i].startDate+'"></span><span class="inp"><input type="text" class="end_date edit_time" readonly="readonly" value = "'+js_date[i].endDate+'"></span></p><button class="btn_del">删除</button><input class="json_date" type="hidden" value = "'+js_date[i].dehours+'"></div>'; 
		}
		$(".setting .time_box").append(html);
		$(".time_box .time_item .btn_del").bind("click",function(e){
				$(this).parents(".time_item").remove();
			});
		var date = $("#id-date-picker-1").val().split('to');
		var s_date = date[0];
		var e_date = date[1];
		$(".setting .tr_data").unbind("mousedown").bind("mousedown",function(){
				var obj_tr = $(this);
				var th_date_s = $(this).find(".start_date").val();
				var th_date_e = $(this).find(".end_date").val();
				var datePickerOptions_td = {
				"startDate":th_date_s,
				"endDate":th_date_e,
				getValue: function(){
					if (obj_tr.find(".start_date").val() && obj_tr.find(".end_date").val() )
						return obj_tr.find(".start_date").val() + ' to ' + obj_tr.find(".end_date").val();
					else
						return '';
				},
				setValue: function(s,s1,s2){
					obj_tr.find(".start_date").val(s1);
					obj_tr.find(".end_date").val(s2);
				}
			}
			obj_tr.unbind("datepicker-apply").bind('datepicker-apply',function(event,obj){
				var date = $("#id-date-picker-1").val().split('to');
				var s_date = date[0];
				var e_date = date[1];
				var checked_date = new Array();
				var other_box =obj_tr.parent().siblings();
				var len = other_box.length;
				for(var i=0;i<len;i++){
					var json_check = {"startDate":other_box.eq(i).find(".start_date").val(),"endDate":other_box.eq(i).find(".end_date").val()};
					checked_date.push(json_check);
				}
				console.log(checked_date);									
				var startDate = obj.value.split('to')[0];
			   	var endDate = obj.value.split('to')[1];
		   		var flag = true;
		   		if(flag){
					var obj = $("#quantum_list1");
					if(obj.find(".pitchon")){
						var timeData = obj.find(".pitchon").map(function(i,span){
							return $(span).attr("title");
						}).toArray().join(',');
					}else{
						var timeData = -1;
					}
					obj_tr.find(".start_date").val(startDate);
					obj_tr.find(".end_date").val(endDate);
					obj_tr.parent().find(".json_date").val(timeData);
				}else{alert("请选择正确时间！");}
			});
			obj_tr.dateRangePicker1(datePickerOptions_td);
			$("#quantum_list1").find("p").removeClass("pitchon");
			var chose_time = obj_tr.parent().find(".json_date").val();
			console.log(chose_time);
			if(chose_time!=-1&&chose_time!=""){
				var chose_arr = chose_time.split(",");
				for(var n=0;n<chose_arr.length;n++){
					$("#quantum_list1 p").eq(chose_arr[n]).addClass("pitchon");
				}
			}
		});
	}
}