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 redirectFunc=function(redirect){redirect&&("[reload]"===redirect?window.location.reload():"[root-reload]"==redirect?Util.getRootWindow().location.reload():"[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,t){t=t||null;var e=$(r);e.on("submit",function(){if(e.data("submiting"))return!1;var r=$(this).attr("action"),a=$(this).attr("method"),i=$(this).data("callbackValidate"),c=$(this).data("callback");if(i&&!i())return!1;c||(c=Form.defaultCallback),a||(a="get");var n=$(this).serializeArray();if(e.data("submiting",!0),t){var o=$(this).attr("data-form-loading");t.loadingOn(o)}return $.ajax({type:a,url:r,dataType:"json",timeout:6e5,data:n,success:function(r){return e.data("submiting",null),t&&t.loadingOff(),c(r,{},t)},error:function(){return e.data("submiting",null),t&&t.loadingOff(),c({code:-999,msg:"请求出现错误 T_T"},{},t)}}),!1})},initCommon:function(r,t){var e=$(r);e.on("submit",function(){if(e.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(e.data("submiting",!0),t){var a=$(this).attr("data-form-loading");t.loadingOn(a)}return!0})}};module.exports=Form;