var Dialog=require("./dialogMobile.js"),Form=require("./form.js"),Widget={};Widget.WxImagesUploader=function(container){void 0==window.wx&&alert("wxImagesUploader must run in wechat");var $container=$(container),$valueHolder=$container.find("[data-value]"),$listHolder=$container.find(".list"),$me=this,uploadServer=$container.attr("data-upload-server");this.value=[];var init=function(){var initValue;try{try{initValue=JSON.parse($valueHolder.val())}catch(e){eval("initValue = "+$valueHolder.val())}}catch(e){initValue=[]}$me.val(initValue),$container.on("click",".item .close",function(){var e=$(this).closest(".item"),a=parseInt(e.attr("data-item-index"));return $me.value.splice(a,1),$me.val($me.value),!1}),$container.on("click",".uploader",function(){var e=[],a=function(i){var t=i.pop();wx.uploadImage({localId:t,isShowProgressTips:1,success:function(t){e.push(t.serverId),i.length>0?a(i):$.post(uploadServer,{serverIds:e},function(e){Dialog.loadingOff(),Form.defaultCallback(e,{success:function(e){for(var a=0;a<e.data.images.length;a++)$me.value.push(e.data.images[a]);$me.val($me.value)}},Dialog)})}})};wx.chooseImage({success:function(e){var i=e.localIds;i.length>0&&(Dialog.loadingOn(),a(i))}})})};this.val=function(e){if(void 0===e)return $me.value;$me.value=e,$listHolder.find(".item").remove();for(var a,i=$me.value.length-1;i>=0;i--){a=$(['<div class="item" data-image-preview>','   <a href="javascript:;" class="close">x</a>','   <div class="cover"></div>',"</div>"].join(""));var t=$me.value[i];0===t.indexOf("https://")||0===t.indexOf("http://")||0===t.indexOf("/")||(t="/"+t),a.attr("data-item-index",i),a.data("data",$me.value[i]),a.attr("href",t),a.find(".cover").css({backgroundImage:"url("+t+")"}),$listHolder.prepend(a)}$valueHolder.val(JSON.stringify($me.value)),$container.trigger("widget.images-uploader.change",[$me])},init()},Widget.init=function(){$(".widget-images-uploader").each(function(e,a){$(a).data("widget")||$(a).data("widget",new Widget.WxImagesUploader(a))})},module.exports=Widget;