$(function(){	

	//关闭微信微信二维码
	$(".yz-close").live("click",function(){
		$(this).parents(".yz-ewm").hide();
		$(".yz-full").hide();
	});

	//微信传图操作
	$(".yz-ewmp").live("click",function(){
		
		//当前微信传图类型，限制图片数量
		currentImageLimitNum = $(this).attr('imageLimitNum');

		//图片上传类型
		imageUploadType = $(this).attr('imageUploadType');

		//图片上传类型(转换数值)
		if(imageUploadType == 'doorin')
		{
			imageUploadTypeNum = '2';
		}
		else if(imageUploadType == 'doorout')
		{
			imageUploadTypeNum = '1';
		}
		else if(imageUploadType == 'layout')
		{
			imageUploadTypeNum = '0';
		}

		//微信二维码过期时间
		var lastTimeAttrVal = $(this).attr('lastTime');
		
		//过期时间
		last_time = lastTimeAttrVal;

		//唯一键值
		wechat_cache_key = $(this).attr('wechatCacheKey');
		
		//初始化点击，加载二维码
		var wechatImageSrc = $(this).attr('wechatImageSrc');
		
		if($('#'+imageUploadType+'WechatImage').attr('src') != wechatImageSrc)
		{
			$('#'+imageUploadType+'WechatImage').attr('src',wechatImageSrc)
		}
		
		//显示微信二维码HTML结构
		$(this).parents(".addBtn").next(".yz-ewm").fadeIn();

		//显示遮罩层
		$(".yz-full").show();

		//判断是否初始化
		if(!wechatImageSrc)
		{
			$("#"+imageUploadType+"WeicodeRefresh").click();
			return;
		}

		//二维码已过期，不去发起请求
		if($('#'+imageUploadType+'ImageWeiXinEwmExpiration').css('display') != 'none')
		{
			return;
		}

		//清空微信JS异常上传图片对象
		/*if(typeof ajaxWechatUploadImageObj == 'object')
		{
			ajaxWechatUploadImageObj.abort();
		}*/

        if(ajaxArrWechatUploadImageObj.length > 0)
        {
            for(key in ajaxArrWechatUploadImageObj)
            {
                ajaxArrWechatUploadImageObj[key].abort();
            }
        }

		/*
		//客户端当前时间(毫秒级)
		var nowTimestamp = new Date().getTime();

		//微信二维码过期时间(转换成毫秒级比较)
		var expirationTime = lastTimeAttrVal*1000;
		
		//判断微信二维码是否过期
		if(expirationTime < nowTimestamp)
		{
			$('#'+imageUploadType+'ImageWeiXinEwmValid').hide();
			$('#'+imageUploadType+'ImageWeiXinEwmExpiration').show();
			return;
		}
		*/
		
		//获取微信传图
		get_wechat_info();
	});

	//点击遮罩层，关闭微信
	$(".yz-full").live("click",function(){
		$(".yz-ewm,.yz-full").hide();
	});

	//二维码过期，重新生成
	//$(".JsweicodeRefresh").click(function(){
	$("#panoramaWeicodeRefresh,#doorinWeicodeRefresh,#dooroutWeicodeRefresh,#layoutWeicodeRefresh").click(function(){
		//重新加载二维码URL
		var url = 'http://'+$("#GB_CITY").val()+'.zsb.house365.com/sell/get_ajax_wechat_image';

		$.getJSON(url,{random:Math.random},function(data){
			if(data['status'] == 200)
			{
				last_time = data['last_time'];
				wechat_cache_key = data['wechat_cache_key'];

				$('#'+imageUploadType+'ImageWeiXinEwmExpiration').hide();
				$('#'+imageUploadType+'ImageWeiXinEwmValid').show();
				$('#'+imageUploadType+'WechatImage').attr('src',data['wechat_image']);
				$('#'+imageUploadType+'ImageWeiXinButton').attr({lastTime:last_time,wechatCacheKey:wechat_cache_key,wechatImageSrc:data['wechat_image']});
				
				//清空微信JS异常上传图片对象
				/*if(typeof ajaxWechatUploadImageObj == 'object')
				{
					ajaxWechatUploadImageObj.abort();
				}*/

                if(ajaxArrWechatUploadImageObj.length > 0)
                {
                    for(key in ajaxArrWechatUploadImageObj)
                    {
                        ajaxArrWechatUploadImageObj[key].abort();
                    }
                }

				//清空微信传图记录
				clearUploadImageData();

				//获取微信传图
				timing = setTimeout('get_wechat_info()',1000);
			}
		});		   
	});
});

//微信传图JS异步上传图片对象
var ajaxArrWechatUploadImageObj = [];

//图片上传类型
var imageUploadType;

//图片上传类型(转换数值)
var imageUploadTypeNum;

//过期时间
var last_time;

//唯一键值
var wechat_cache_key;

//定时变量
var timing;

//微信传全景图记录
var panoramaImgArr = [];

//微信传室内图记录
var doorinImgArr = [];

//微信传室外图记录
var dooroutImgArr = [];

//微信传户型图记录
var layoutImgArr = [];

//当前微信传图类型，限制图片数量
var currentImageLimitNum = 0;

//ID标记
//var mark = '<!--# echo $n;#-->';

//房源类型
var tbl = 'rent';

//获取微信传图
var get_wechat_info = function()
{
	//裁剪图片尺码类型
	var resizeSizeType = 1;
	if(imageUploadType == 'panorama')
	{
		resizeSizeType = 2;
	}

	//微信数据请求URL
	var url = 'http://weixinupload.house365.com/wechat_cache_image_new.php?callback=?';

	//获取已传图片，防止重复加载图片
	var image_arr = getUploadImageData();

    ajaxWechatUploadImageObj = $.ajax({
        dataType:'jsonp',
        jsonp: "callback",//传递给请求处理程序或页面的，用以获得jsonp回调函数名的参数名(默认为:callback)
        jsonpCallback:"callBackFun",//自定义的jsonp回调函数名称，默认为jQuery自动生成的随机函数名
        url : url,
        data : {last_time:last_time,key:wechat_cache_key,image_arr:image_arr,resizeSizeType:resizeSizeType,randmod:Math.random()},
        success : function(data){
            if(data['status'] == 200)
            {
                if(imageUploadType == 'panorama')
                {
                    //全景处理微信上传全景图HTML结构处理
                    panoramaWechatUploadImage(data);
                }
                else
                {
                    //公用处理微信上传图HTML结构
                    publicWechatUploadImage(data);
                }

                //定时30秒
                timing = setTimeout('get_wechat_info()',1000);
            }
            else
            {
                clearTimeout(timing);
                $('#'+imageUploadType+'ImageWeiXinEwmExpiration').show();
                $('#'+imageUploadType+'ImageWeiXinEwmValid').hide();
            }
        },
        error : function(){//alert('网络异常中断');
            //防止网络异常中断
            //get_wechat_info();
        }
    });

    ajaxArrWechatUploadImageObj.push(ajaxWechatUploadImageObj);

	/*ajaxWechatUploadImageObj = $.jsonp({
		url : url,
		data : {last_time:last_time,key:wechat_cache_key,image_arr:image_arr,resizeSizeType:resizeSizeType,randmod:Math.random()},
		success : function(data){
			if(data['status'] == 200)
			{
				if(imageUploadType == 'panorama')
				{
					//全景处理微信上传全景图HTML结构处理
					panoramaWechatUploadImage(data);
				}
				else
				{
					//公用处理微信上传图HTML结构
					publicWechatUploadImage(data);
				}
				
				//定时30秒
				timing = setTimeout('get_wechat_info()',1000);
			}
			else
			{
				clearTimeout(timing);
				$('#'+imageUploadType+'ImageWeiXinEwmExpiration').show();
				$('#'+imageUploadType+'ImageWeiXinEwmValid').hide();
			}
		},
		error : function(){
			//防止网络异常中断
			get_wechat_info();
		}
	});*/
}

//全景处理微信上传全景图HTML结构处理
var panoramaWechatUploadImage = function(data)
{
	var panoramaImageNum = $('#showImage').find('.mItem').length;

	for(var key in data.data)
	{
		/*var wechat_imgarr = $("#thumbnails").find(".deltextFg3Img");
		
		if(wechat_imgarr.length >= 20)
		{
			break;
		}*/

		if(panoramaImageNum >= currentImageLimitNum)
		{
			break;
		}

		panoramaImageNum++;
			
		//mark++;
		imageNum++;

		var serverData = data.data[key]['host']+'/'+data.data[key]['url']+'_'+data['size']+'.'+data.data[key]['extension']+'?pid='+imageNum;

		//var width = data.data[key]['width'];
		//var height = data.data[key]['height'];
		//var image_source = data.data[key]['host']+'/'+data.data[key]['url']+'.'+data.data[key]['extension'];
		
		panoramaImgArr.push(key);


		//img[key] = key;

		imageArr['image_'+imageNum] = serverData;

		//租售宝360全景图片HTML结构
		var html = '';	
		html += '<div class="mItem" id="image_'+imageNum+'" imageNum="'+imageNum+'">';
		html += 	'<div class="mItemInner">';
		html +=			'<div class="mPic">';
		html +=				'<img width="130" height="100" alt="" src="'+serverData+'" style="opacity: 1;">';

		html +=				'<input type="hidden" name="imageUrl['+imageNum+']" value="'+serverData+'">';  
		
		//html +=             '<input type="hidden" name="p_sort[]" value="0" class="psort">';
		html +=				'<div class="funM" style="opacity: 0.6;"></div>';
		html +=				'<div class="funMtext" style="opacity: 1;">';
		html +=					'<label>';
		html +=					    '<a imageNum='+imageNum+' title="查看大图" href="javascript:void(0);" target="_balnk" style="bottom:84px;" class="bigPicLin bigPicLinpanorama"></a>';

		html +=						'<input type="radio" class="input_r Js_defaultPic" name="jsPicPreviewList" id="picPreview_'+imageNum+'" value="'+serverData+'">封面';

		html +=					'</label>';
		html +=					'<div class="delBtn delImage" imageNum="'+imageNum+'" title="删除"></div>';
		html +=				'</div>';
		html +=			'</div>';
		html +=		'</div>';
		html +=		'<div class="imitateSelect imitateSelect_new imageSelect mt10">';
		html +=			'<label class="labelImitate labelImitate_new" style="display: inline;">';
		html +=				'<i class="newred">*</i>选择全景图分类';
		html +=			'</label>';
		html +=			'<input type="text" class="imitate imitateIe" id="forward_'+imageNum+'" readonly="" value="" name="forwards">';
		html +=			'<input type="hidden" id="imageType_'+imageNum+'" name="imageType['+imageNum+']" value="">';
		html +=			'<div class="listImitate listImitate_new" style="display: none;">';
		html +=				'<dl class="inner">';
								for(var key in imageType)
								{
		html +=						'<dd>';
		html +=							'<a imageNum='+imageNum+' class="link imageType" oid="'+key+'" href="#">'+imageType[key]+'</a>';
		html +=						'</dd>';
								}
		html +=				'</dl>';
		html +=			'</div>';
		html +=		'</div>';
		html +=		'<div class="inputBoxM jsNameInput nameInput ">';

		html +=			'<input type="text" name="imageTitle['+imageNum+']" placeholder="图片描述10字" class="newaddTxt jsInputCount input_text w126" onclick="this.className=\'newaddTxt jsInputCount input_text w126 input_text_on\'" onblur="this.className=\'newaddTxt jsInputCount input_text w126\'" >';

		html +=			'<span class="cha_new" style="display: none"></span>';
		html +=		'</div>';
		html +=	  '</div>';

		$('#showImage').append(html);
		$('#imageInfo').show();
	}
}

//公用处理微信上传图HTML结构
var publicWechatUploadImage = function(data)
{
	var publicImageNum = $('#thumbnails'+imageUploadTypeNum).find('.mItem').length;
	var html = '';
	for(var key in data.data)
	{
		if(publicImageNum >= currentImageLimitNum)
		{
			break;
		}

		publicImageNum++;

		if(imageUploadType == 'doorin')
		{
			doorinImgArr.push(key);
		}
		else if(imageUploadType == 'doorout')
		{
			dooroutImgArr.push(key);
		}
		else if(imageUploadType == 'layout')
		{
			layoutImgArr.push(key);
		}

		var imageSrc = data.data[key]['host']+'/'+data.data[key]['url']+'_'+data['size']+'.'+data.data[key]['extension']+'?pid='+publicImageNum;

		var imageSource = data.data[key]['host']+'/'+data.data[key]['url']+'.'+data.data[key]['extension'];

		html += '<div class="mItem" style="">';
		html +=    '<div class="mItemInner">';
		html +=	       '<div class="mPic">';
		html +=            '<img width="130" height="100"  src="'+imageSrc+'" alt="">';
		html +=            '<input type="hidden" value="'+imageSrc+'" name="p_filename[]">';
		html +=            '<input class="psort" type="hidden" value="'+imageUploadTypeNum+'" name="p_sort[]">';

		html +=	           '<div class="funM"></div>';
		html +=            '<div class="funMtext">';

		html +=                '<label><input type="radio" value="'+imageSrc+'" onclick="setIndexPic(this);" name="jsPicPreviewList" class="input_r">封面</label>';

		html +=                '<a class="bigPicLin" style="bottom:84px;" target="_balnk" href="'+imageSource+'" title="查看大图">查看大图</a>';

		html +=                '<div title="删除" id="'+imageUploadTypeNum+'" class="delBtn" imageSrc="'+imageSrc+'"></div>';

		html +=            '</div>';
		html +=         '</div>';
		html +=     '</div>';
		html +=     '<div class="inputBoxM jsNameInput nameInput ">';

		html +=         '<input type="text" onblur="if(this.value==\'\')this.value=\'图片描述30字\',this.className=\'jsInputCount input_text w126\'" onclick="if(this.value==\'图片描述30字\')this.value=\'\',this.className=\'jsInputCount input_text w126 input_text_on\'" class="jsInputCount input_text w126" value="图片描述30字" name="p_title[]">';

		html +=     '</div>';
		html += '</div>';
	}
	
	if(!html)
	{
		return;
	}
	
	$("#thumbnails"+imageUploadTypeNum).append(html);
	$("#picshow"+imageUploadTypeNum).show();
}

//获取已上传图片数据，防止图片重复
var getUploadImageData = function()
{
	var result = [];

	if(imageUploadType == 'panorama')
	{
		result = panoramaImgArr;
	}
	else if(imageUploadType == 'doorin')
	{
		result = doorinImgArr;
	}
	else if(imageUploadType == 'doorout')
	{
		result = dooroutImgArr;
	}
	else if(imageUploadType == 'layout')
	{
		result = layoutImgArr;
	}

	return result.join(',');
}

//清空上传图片数据，刷新过期二维码，防止图片加载不到
var clearUploadImageData = function()
{
	if(imageUploadType == 'panorama')
	{
		panoramaImgArr = [];
	}
	else if(imageUploadType == 'doorin')
	{
		doorinImgArr = [];
	}
	else if(imageUploadType == 'doorout')
	{
		dooroutImgArr = [];
	}
	else if(imageUploadType == 'layout')
	{
		layoutImgArr = [];
	}

	return true;
}

//初始化
var _initWechatUploadImage = function()
{
	//<!--微信二维码遮罩层-->
	$('body').append('<div class="yz-full" style="display: none;z-index: 9;height: 100%;width: 100%;position:fixed;top: 0;left: 0;background:url(http://esf.fz.house365.com/zsb/images/v1.0/yz-fbg.png)"></div>');
}

//初始化调用
_initWechatUploadImage();
