//代码中心处理脚本
var cnv_operate={
	//弹层编辑
	showCnvEditPopup:function(template){
		if (window.cnvEditPopup) {
			cnvEditPopup.hide();
		}
		window.cnvEditPopup = new Popup({
			forceRemove : true,
			width : '630px',
			height : '350px',
			html : template,
			title : '转化代码'
		});
		$('#conversion_form').submit(function() {
			var params = $(this).serializeObject();
			cnv_operate.createUpdate(params.advertiserId,params.entityId);
			return false;
		});		
	},

	//创建与更新转化代码
	createUpdateForm:function( advertiserId, id,queryStr) {
		var url =contextPath + '/code_center/conversion/' + advertiserId + '/form';
		if (id!=null){
			url = url + '?entityId='+id;
		}
		$.ajax({
			url : url,
			type : 'get',
			dataType : 'html',
			success : function(template) {
				cnv_operate.showCnvEditPopup(template);
			}
		});
	},
	
	//以ajax提交更新
	createUpdate:function(advertiserId,id,queryStr) {
		var data = $('#conversion_form').serialize();
		var url = contextPath + '/code_center/conversion/' + advertiserId + '/';		
		$.ajax({
			url : url,
			type : 'post',
			data : data,
			dataType : 'html',
			success : function(template) {
				if (window.cnvEditPopup) {
					cnvEditPopup.hide();
				}
				var lowIndex = template.indexOf('::::::json_result::::::');
				if (lowIndex >= 0){
					location.reload(true);
					return;
				}
				cnv_operate.showCnvEditPopup(template);
			}
		});
	}
};

function changeCode(code,type){	
	var pre =  '';
	var retargetingPara=['','_extend'];
	var conversionPara=['','_order','_extend','_order_extend'];
	var eleTypes = ['js','jsasy','img'];
	var tail= 0;
	if (code == 0) {
		pre = '#retargeting_';
		takingExtendInfoCode(type);
	};
	if (code == 1) {
		pre = '#conversion_';
		takingOrderExtendInfoCode(type);
	};
	
	$(pre+'text')[0].innerHTML = type == 0 ? 'JavaScript(同步)' : type == 1 ? 'JavaScript(异步)' : type == 2 ?'图片' : type == 3 ?'点击' : type == 4 ?'Flash(AS2)':'Flash(AS3)';	
	
}

function takingOrderExtendInfoCode(type){
	var pre = '#conversion_';
	var eleType=0;
	if (type==null){
		if ($(pre+'text')[0].innerHTML=='JavaScript(同步)'){
			eleType=0;
		}else if($(pre+'text')[0].innerHTML=='JavaScript(异步)'){
			eleType=1;
		}else if($(pre+'text')[0].innerHTML=='图片'){
			eleType=2;
		}else if($(pre+'text')[0].innerHTML=='点击'){
			eleType=3;
		}else if($(pre+'text')[0].innerHTML=='Flash(AS2)'){
			eleType=4;
		}else if($(pre+'text')[0].innerHTML=='Flash(AS3)'){
			eleType=5;
		}
	}else{
		eleType=type;
	}
	
	var conversionPara=['','_order','_extend','_order_extend'];
	var eleTypes = ['js','jsasy','img','click','flashAs2','flashAs3'];
	var tail=0;
	if ($('#extendParas').attr('checked')){
		if ($('#takingOrder').attr('checked')){
			tail=3;
		}else{
			tail=2;
		}
	}else{
		if ($('#takingOrder').attr('checked')){
			tail=1;
		}else{
			tail=0;
		}
	}
	for(var k=0;k<eleTypes.length;k++){
		for(var g=0;g<conversionPara.length;g++){
			if (k==eleType && tail==g){
				$(pre+eleTypes[k]+conversionPara[g]).show().select();
			}else{
				$(pre+eleTypes[k]+conversionPara[g]).hide();
			}
		}
	}	
}

/**
 * 显示如何编码帮助信息
 */
function showEncodeHelp(){
		if(window.encodeHelpPop){
			window.encodeHelpPop.hide();
		}
		var template =
					'<div class="ml1">'+
					'		<ul>'+
					'			<li>Javascript示例：encodeURIComponent("No.001订单");</li>'+
					'			<li>Java示例：java.net.URLEncoder.encode("No.001订单", "UTF-8");</li>'+
					'			<li>PHP示例：urlencode("No.001订单");</li>'+
					'			<li>Python示例：urllib.quote(u"No.001订单".encode("utf-8"));</li>'+
					'			<li>C#示例：HttpUtility.UrlEncode(u"No.001订单".encode("utf-8"));</li>'+
					'			<li>ASP示例：Server.URLEncode(u"No.001订单".encode("utf-8"));</li>'+
					'		</ul>'+
					'	</div>'+
					'</div>	';			
		window.encodeHelpPop = new Popup({
			forceRemove:true,
			width:'430px',
			height:'150px',
			html:template,
			title:'如何编码URL片断'
		});
}

function getRetargetingCode(advertiserId,paraValue,retargetId){
	
	var template ='<div class="vistor-cont">'+
				'<div class="vistor-section">'+
					'<div class="code-type">'+
						'<span>选择代码类型：</span>'+
						 '<div class="btn-group">'+
							'<button class="btn dropdown-toggle" data-toggle="dropdown">'+
								'<span id="retargeting_text">JavaScript(异步)</span>'+
							'<span class="caret"></span>'+
							'</button>'+
							'<ul class="dropdown-menu">'+
							//'<li><a href="javascript:changeCode(0,0);">JavaScript(同步)</a></li>'+
							'<li><a href="javascript:changeCode(0,1);">JavaScript(异步)</a></li>'+
							'<li><a href="javascript:changeCode(0,2);">图片</a></li>'+
							'</ul>'+
						'</div>'+
						'<span class="ml2" id="code_span_self_paras"><input type="checkbox" id="extendParas"><label for="extendParas">携带扩展参数信息</label></span>'+
					'</div>'+
					'<div id="retargeting_js" style="display:none;" class="code" readonly="readonly"></div>'+
					'<div id="retargeting_jsasy"  class="code" readonly="readonly"></div>'+
					'<div id="retargeting_img" style="display:none;" class="code" readonly="readonly"></div>'+
					'<div id="retargeting_jsasy_extend" style="display:none;" class="code" readonly="readonly"></div>'+
					'<div id="retargeting_js_extend" class="code" readonly="readonly" style="display:none;"></div>'+
					'<div id="retargeting_img_extend" style="display:none" class="code" readonly="readonly"></div>'+
					'<input id="copy-btn" class="btn" type="button" value="复制"/>'+
					'<div class="suggest">'+
						'<span>安装提示：</span>'+
						'<span>1、请在您待推广网站的所有页面&lt;/body&gt;标签之前插入上述代码。</span>'+
						'<span>2、若为动态代码，请在请求前将代码中所有红色字体替换为具体参数值或留空。</span>'+
						'<span>3、若扩展参数信息等，请将代码中红色字体部分替换为实际参数值或留空。</span>'+
					'</div>'+
				'</div>'+				
			'</div>';
	window.getRetargetingPopup = new Popup({
		forceRemove:true,
		width:'660px',
		height:'480px',
		html:template,
		title:'访客找回代码安装'
	});
	$('#copy-btn').zclip({
		path:contextPath+'/s/js/ZeroClipboard.swf',
		copy:function(){ return $('.code[readonly="readonly"]:visible').text();},
		afterCopy:function(){
			alert('复制成功');
		}
	});
	var parameters={};
	if(paraValue){
		parameters.para_value=paraValue;
	}
	var ajaxUrl = contextPath + '/code_center/retargeting/' + advertiserId + '/code';
	if(retargetId&&retargetId>0){
		ajaxUrl = contextPath + '/code_center/retargeting/' + advertiserId + '/code/'+retargetId;
	}
	$.ajax({
		url: ajaxUrl,
		data:parameters,
		dataType:'json',
		success:function(data){
			var reg= new RegExp(/\［(.*?)\］/g),
			newline = new RegExp(/\r\n|\n|\r/g),
			spanele = '<span style="color:#cc3433">$1</span>';
			$('#retargeting_js').text(data[0]).html($('#retargeting_js').html().replace(newline,'<br />\n'));

			$('#retargeting_jsasy').text(data[1]).html($('#retargeting_jsasy').html().replace(newline,'<br />\n'));
			$('#retargeting_img').text(data[2]).html($('#retargeting_img').html().replace(newline,'<br />\n'));

			$('#retargeting_js_extend').text(data[3]).html($('#retargeting_js_extend').html().replace(reg,spanele).replace(newline,'<br />\n'));

			$('#retargeting_jsasy_extend').text(data[4]).html($('#retargeting_jsasy_extend').html().replace(reg,spanele).replace(newline,'<br />\n'));

			$('#retargeting_img_extend').text(data[5]).html($('#retargeting_img_extend').html().replace(reg,spanele).replace(newline,'<br />\n'));
			$('#extendParas').change(function() {
				takingExtendInfoCode(null);//根据是否携带扩展展信息，生成新代码
			});
			$('#retargeting_js,#retargeting_jsasy,#retargeting_img').focus(function(e){
				try{
					// IE9这里会崩溃，原因未知
					$(this).select();
				}catch(e){
					
				}
			}).mouseup(function(e){
	 			e.preventDefault();
	 		}).each(function(i,item){
				try{
					// IE这里会崩溃，原因未知
					item.select();
				}catch(e){
					
				}
			});
		}
	});

	$('#retargeting_confirm').click(function(){
		getRetargetingPopup.hide();
	});
}

function takingExtendInfoCode(type){
	var pre = '#retargeting_';
	var eleType=0;
	if (type==null){
		if ($(pre+'text')[0].innerHTML=='JavaScript(同步)'){
			eleType=0;
		}else if($(pre+'text')[0].innerHTML=='JavaScript(异步)'){
			eleType=1;
		}else if($(pre+'text')[0].innerHTML=='图片'){
			eleType=2;
		}
	}else{
		eleType=type;
	}
	
	var retargetingPara=['','_extend'];
	var eleTypes = ['js','jsasy','img'];
	var tail=0;
	if ($('#extendParas').attr('checked')){
		tail=1;
	}
	for(var i=0;i<eleTypes.length;i++){
		for(var j=0;j<retargetingPara.length;j++){
			if (i==eleType && tail==j){
				$(pre+eleTypes[i]+retargetingPara[j]).show().select();
			}else{
				$(pre+eleTypes[i]+retargetingPara[j]).hide();
			}
		}
	}
}
function getConversionCode(advertiserId, conversionTargetId){
	
	var template = '<div class="vistor-cont">'+
		'<div class="vistor-section">'+
			'<div class="code-type">'+
				'<span>选择代码类型：</span>'+
				 '<div class="btn-group">'+
					'<button class="btn dropdown-toggle" data-toggle="dropdown">'+
						'<span id="conversion_text">JavaScript(异步)</span>'+
					'<span class="caret"></span>'+
					'</button>'+
					'<ul class="dropdown-menu">'+
					//'<li><a href="javascript:changeCode(1,0);">JavaScript(同步)</a></li>'+
					'<li><a href="javascript:changeCode(1,1);">JavaScript(异步)</a></li>'+
					'<li><a href="javascript:changeCode(1,2);">图片</a></li>'+
					'<li><a href="javascript:changeCode(1,3);">点击触发</a></li>'+
					'<li><a href="javascript:changeCode(1,4);">Flash(AS2)</a></li>'+
					'<li><a href="javascript:changeCode(1,5);">Flash(AS3)</a></li>'+
					'</ul>'+
				'</div>'+
				'<span class="ml2" id="code_span_self_paras_1"><input type="checkbox" id="takingOrder"><label for="takingOrder">携带订单信息</label></span>'+
				'<span class="ml2" id="code_span_self_paras_2"><input type="checkbox" id="extendParas"><label for="extendParas">携带扩展参数信息</label></span>'+
			'</div>'+ 
			'<div id="conversion_js" style="display:none" class="code" readonly="readonly"></div>'+
			'<div id="conversion_jsasy"  class="code" readonly="readonly"></div>'+
			'<div id="conversion_img" style="display:none;" class="code" readonly="readonly"></div>'+
			'<div id="conversion_click" style="display:none;" class="code" readonly="readonly"></div>'+
			'<div id="conversion_flashAs2" style="display:none;" class="code" readonly="readonly"></div>'+
			'<div id="conversion_flashAs3" style="display:none;" class="code" readonly="readonly"></div>'+
			
			'<div id="conversion_js_order" class="code" style="display:none;" readonly="readonly"></div>'+
			'<div id="conversion_jsasy_order" class="code" style="display:none;" readonly="readonly"></div>'+
			'<div id="conversion_img_order" class="code" style="display:none" readonly="readonly"></div>'+
			'<div id="conversion_click_order" class="code" style="display:none" readonly="readonly"></div>'+
			'<div id="conversion_flashAs2_order" class="code" style="display:none" readonly="readonly"></div>'+
			'<div id="conversion_flashAs3_order" class="code" style="display:none" readonly="readonly"></div>'+
			
			'<div id="conversion_js_extend" class="code" style="display:none;" readonly="readonly"></div>'+
			'<div id="conversion_jsasy_extend" class="code" style="display:none;" readonly="readonly"></div>'+
			'<div id="conversion_img_extend" class="code" style="display:none" readonly="readonly"></div>'+
			'<div id="conversion_click_extend" class="code" style="display:none" readonly="readonly"></div>'+
			'<div id="conversion_flashAs2_extend" class="code" style="display:none" readonly="readonly"></div>'+
			'<div id="conversion_flashAs3_extend" class="code" style="display:none" readonly="readonly"></div>'+
			
			'<div id="conversion_js_order_extend" class="code" style="display:none;" readonly="readonly"></div>'+
			'<div id="conversion_jsasy_order_extend" class="code" style="display:none;" readonly="readonly"></div>'+
			'<div id="conversion_img_order_extend" class="code" style="display:none" readonly="readonly"></div>'+
			'<div id="conversion_click_order_extend" class="code" style="display:none;" readonly="readonly"></div>'+
			'<div id="conversion_flashAs2_order_extend" class="code" style="display:none;" readonly="readonly"></div>'+
			'<div id="conversion_flashAs3_order_extend" class="code" style="display:none;" readonly="readonly"></div>'+
			
			'<input id="copy-btn" class="btn" type="button" value="复制"/>'+
			'<div class="suggest">'+
				'<span>安装提示：</span>'+
				'<span>1、在您指定的转化的页面如：注册成功、购买成功等页面</body>标签之前插入上述代码。</span>'+
				'<span>2、代码加入30分钟后，请点击页面上的"验证代码"进行确认，以保证代码被正确安装。</span>'+
				'<span >3、若携带订单信息、扩展参数信息等，请将代码中红色字体替换为实际参数值或留空（<a id="encodeHelp" >须做编码处理</a>）。</span>'+
			'</div>'+
		'</div>'+
	'</div>';
	window.getConversionPopup = new Popup({
		forceRemove:true,
		width:'660px',
		height:'474px',
		html:template,
		title:'转化代码安装'
	});
	$('#copy-btn').zclip({
		path:contextPath+'/s/js/ZeroClipboard.swf',
		copy:function(){ return $('.code[readonly="readonly"]:visible').text();},
		afterCopy:function(){
			alert('复制成功');
		}
	});
	$.ajax({
		url:contextPath + '/code_center/conversion/' + advertiserId + '/code/'+conversionTargetId,
		dataType:'json',
		success:function(data){
			var reg= new RegExp(/\［(.*?)\］/g),
			newline = new RegExp(/\r\n|\n|\r/g),
			spanele = '<span style="color:#cc3433">$1</span>';

			$('#conversion_js').text(data[0]).html($('#conversion_js').html().replace(newline,'<br />\n'));
			$('#conversion_jsasy').text(data[1]).html($('#conversion_jsasy').html().replace(newline,'<br />\n'));
			$('#conversion_img').text(data[2]).html($('#conversion_img').html().replace(newline,'<br />\n'));
			$('#conversion_click').text(data[12]).html($('#conversion_click').html().replace(newline,'<br />\n'));
			$('#conversion_flashAs2').text(data[16]).html($('#conversion_flashAs2').html().replace(newline,'<br />\n'));
			$('#conversion_flashAs3').text(data[20]).html($('#conversion_flashAs3').html().replace(newline,'<br />\n'));
			
			$('#conversion_js_order').text(data[3]).html($('#conversion_js_order').html().replace(reg,spanele).replace(newline,'<br />\n'));
			$('#conversion_jsasy_order').text(data[4]).html($('#conversion_jsasy_order').html().replace(reg,spanele).replace(newline,'<br />\n'));
			$('#conversion_img_order').text(data[5]).html($('#conversion_img_order').html().replace(reg,spanele).replace(newline,'<br />\n'));
			$('#conversion_click_order').text(data[13]).html($('#conversion_click_order').html().replace(reg,spanele).replace(newline,'<br />\n'));
			$('#conversion_flashAs2_order').text(data[17]).html($('#conversion_flashAs2_order').html().replace(reg,spanele).replace(newline,'<br />\n'));
			$('#conversion_flashAs3_order').text(data[21]).html($('#conversion_flashAs3_order').html().replace(reg,spanele).replace(newline,'<br />\n'));
			
			$('#conversion_js_extend').text(data[6]).html($('#conversion_js_extend').html().replace(reg,spanele).replace(newline,'<br />\n')); 
			$('#conversion_jsasy_extend').text(data[7]).html($('#conversion_jsasy_extend').html().replace(reg,spanele).replace(newline,'<br />\n'));
			$('#conversion_img_extend').text(data[8]).html($('#conversion_img_extend').html().replace(reg,spanele).replace(newline,'<br />\n'));
			$('#conversion_click_extend').text(data[14]).html($('#conversion_click_extend').html().replace(reg,spanele).replace(newline,'<br />\n'));
			$('#conversion_flashAs2_extend').text(data[18]).html($('#conversion_flashAs2_extend').html().replace(reg,spanele).replace(newline,'<br />\n'));
			$('#conversion_flashAs3_extend').text(data[22]).html($('#conversion_flashAs3_extend').html().replace(reg,spanele).replace(newline,'<br />\n'));
			
			$('#conversion_js_order_extend').text(data[9]).html($('#conversion_js_order_extend').html().replace(reg,spanele).replace(newline,'<br />\n'));
			$('#conversion_jsasy_order_extend').text(data[10]).html($('#conversion_jsasy_order_extend').html().replace(reg,spanele).replace(newline,'<br />\n'));
			$('#conversion_img_order_extend').text(data[11]).html($('#conversion_img_order_extend').html().replace(reg,spanele).replace(newline,'<br />\n'));
			$('#conversion_click_order_extend').text(data[15]).html($('#conversion_click_order_extend').html().replace(reg,spanele).replace(newline,'<br />\n'));
			$('#conversion_flashAs2_order_extend').text(data[19]).html($('#conversion_flashAs2_order_extend').html().replace(reg,spanele).replace(newline,'<br />\n'));
			$('#conversion_flashAs3_order_extend').text(data[23]).html($('#conversion_flashAs3_order_extend').html().replace(reg,spanele).replace(newline,'<br />\n'));
					
			$('#takingOrder').change(function() {
				takingOrderExtendInfoCode(null);//根据是否携带订单信息，生成新代码
			});
			$('#extendParas').change(function() {
				takingOrderExtendInfoCode(null);//根据是否携带订单信息，生成新代码
			});
			var helpInfo =
				'<div id="encodeHelpTipsy" class="mt1 ml1 mr1">'+
				'		<ul>'+
				'			<li>Javascript示例：encodeURIComponent("No.001订单");</li>'+
				'			<li>Java示例：java.net.URLEncoder.encode("No.001订单", "UTF-8");</li>'+
				'			<li>PHP示例：urlencode("No.001订单");</li>'+
				'			<li>Python示例：urllib.quote(u"No.001订单".encode("utf-8"));</li>'+
				'			<li>C#示例：HttpUtility.UrlEncode(u"No.001订单".encode("utf-8"));</li>'+
				'			<li>ASP示例：Server.URLEncode(u"No.001订单".encode("utf-8"));</li>'+
				'		</ul>'+
				'	</div>'+
				'</div>	';
			$('#encodeHelp').attr('title',helpInfo);
			$('#encodeHelp').tipsy({
				trigger: 'click', // 点击弹出tip
				clickHide: true, // 是否点击空白区隐藏tip，默认为true
				skin: 'wtipsy',
				html:true,
				gravity:'nw'
			});
			$('#conversion_js,#conversion_jsasy,#conversion_img').focus(function(e){
				try{
					$(this).select();
				}catch(e){
					
				}
			}).mouseup(function(e){
	 			e.preventDefault();
	 		}).focus();
		}
	});
	getConversionPopup.close.click(function(){
		$('#encodeHelpTipsy').remove();
	});
}

function changePage(page){
	if (page==0){
		$('#page_retargeting').removeClass('selected');		
		$('#page_conversion').removeClass('selected');
		$('#page_category').removeClass('selected');
		$('#page_retargeting').addClass('selected');
	}else if(page==1){
		$('#page_retargeting').removeClass('selected');		
		$('#page_conversion').removeClass('selected');
		$('#page_category').removeClass('selected');
		$('#page_category').addClass('selected')
	}else{
		$('#page_retargeting').removeClass('selected');
		$('#page_conversion').removeClass('selected');
		$('#page_category').removeClass('selected');
		$('#page_conversion').addClass('selected');
	}
}

var retarget_operate={

	//弹层编辑
	showRetargetEditPopup:function(template,height){
		if (window.retargetEditPopup) {
			retargetEditPopup.hide();
		}
		window.retargetEditPopup = new Popup({
			forceRemove : true,
			width : '630px',
			height : height,
			html : template,
			title : '访客找回代码'
		});
		$('#retarget_form').submit(function() {
			var params = $(this).serializeObject();
			retarget_operate.createUpdate(params.advertiserId,params.entityId);
			return false;
		});
	},
	//关闭弹层
	hide:function(){
		if (window.retargetEditPopup) {
			retargetEditPopup.hide();
		}		
	},
	//创建与更新转化代码
	createUpdateForm:function( advertiserId, id,queryStr) {
		var url =contextPath + '/code_center/retargeting/' + advertiserId + '/form';
		if (id!=null){
			url = url + '?entityId='+id;
		}
		$.ajax({
			url : url,
			type : 'get',
			dataType : 'html',
			success : function(template) {
				if(id){
					retarget_operate.showRetargetEditPopup(template,'320px');
				}else{
					retarget_operate.showRetargetEditPopup(template,'400px');
				}
			}
		});
	},
	
	//以ajax提交更新
	createUpdate:function(advertiserId,id,queryStr) {
		var data = $('#retarget_form').serialize();
		var url = contextPath + '/code_center/retargeting/' + advertiserId + '/';		
		$.ajax({
			url : url,
			type : 'post',
			data : data,
			dataType : 'html',
			success : function(template) {
				if (window.retargetEditPopup) {
					retargetEditPopup.hide();
				}
				var lowIndex = template.indexOf('::::::json_result::::::');
				if (lowIndex >= 0){
					location.reload(true);
					return;
				}
				if(id){
					retarget_operate.showRetargetEditPopup(template,'320px');
				}else{
					retarget_operate.showRetargetEditPopup(template,'400px');
				}
			}
		});
	}
};

function checkConversionCode(advertiserId,conversionTargetId){
	//走公共组件
	codechecker.checkConversionCode(advertiserId,conversionTargetId);
}
function checkRetargetingCode(companyId,retargetingTargetValue){
	//走公共组件
	codechecker.checkRetargetingCode(companyId,retargetingTargetValue,true);
}