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){var e=r.location,t=[],a="_t_"+(new Date).getTime()+"_";t.push(e.protocol),t.push("//"),t.push(e.host),t.push(e.pathname),e.search?/_t_\d+_/.test(e.search)?t.push(e.search.replace(/_t_\d+_/,a)):(t.push(e.search),t.push("&"),t.push(a)):(t.push(e.search),t.push("?"),t.push(a)),t.push(e.hash),r.location.replace(t.join(""))},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"),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 s=$(this).serializeArray();if(t.data("submiting",!0),e){var n=$(this).attr("data-form-loading");e.loadingOn(n)}return $.ajax({type:a,url:r,dataType:"json",timeout:6e5,data:s,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 a=$(this).attr("data-form-loading");e.loadingOn(a)}return!0})}};module.exports=Form;