var $=require("jquery"),Util=require("./util.js"),Form={defaultCallback:function(res,callback,Dialog){if(Dialog=Dialog||null,callback=callback||{},"object"!=typeof res)return void alert("ErrorResponse:"+res);if("code"in res){var code=res.code,msg="",redirect="",data=null;"msg"in res&&(msg=res.msg),"redirect"in res&&(redirect=res.redirect),"data"in res&&(data=res.data);var winReload=function(r){r.location.href=r.location.href},redirectFunc=function(redirect){redirect&&("[reload]"===redirect?winReload(window):"[root-reload]"==redirect?winReload(Util.getRootWindow()):"[back]"===redirect?window.history.back():0===redirect.indexOf("[js]")?eval(redirect.substr(4)):window.location.href=redirect)},successFunc=function(){"success"in callback?callback.success(res):redirect?msg?Dialog?Dialog.alertSuccess(msg,function(){redirectFunc(redirect)}):(alert(msg),redirectFunc(redirect)):redirectFunc(redirect):Dialog?Dialog.tipSuccess(msg):alert(msg)},errorFunc=function(){"error"in callback?callback.error(res):redirect?msg?Dialog?Dialog.alertError(msg,function(){redirectFunc(redirect)}):(alert(msg),redirectFunc(redirect)):redirectFunc(redirect):Dialog?Dialog.tipError(msg):alert(msg)};0==code?successFunc():errorFunc()}},initAjax:function(r,e){e=e||null;var t=$(r);t.on("submit",function(){if(t.data("submiting"))return!1;var r=$(this).attr("action"),i=$(this).attr("method"),a=$(this).data("callbackValidate"),c=$(this).data("callback");if(a&&!a())return!1;c||(c=Form.defaultCallback),i||(i="get");var n=$(this).serializeArray();if(t.data("submiting",!0),e){var o=$(this).attr("data-form-loading");e.loadingOn(o)}return $.ajax({type:i,url:r,dataType:"json",timeout:6e5,data:n,success:function(r){return t.data("submiting",null),e&&e.loadingOff(),c(r,{},e)},error:function(){return t.data("submiting",null),e&&e.loadingOff(),c({code:-999,msg:"请求出现错误 T_T"},{},e)}}),!1})},initCommon:function(r,e){var t=$(r);t.on("submit",function(){if(t.data("submiting"))return!1;var r=($(this).attr("action"),$(this).attr("method"),$(this).serializeArray(),$(this).data("callbackValidate"));$(this).data("callback");if(r&&!r())return!1;if(t.data("submiting",!0),e){var i=$(this).attr("data-form-loading");e.loadingOn(i)}return!0})}};module.exports=Form;