/**
 * 流程建模
 * @author zhouwf
 */
(function (factory) {
    if (typeof define === 'function' && define.amd) {
        define(['jquery', 'horizonFlowtree'], factory);
    }else {
        factory(jQuery);
    }
}(function($) {
    "use strict";
    var frameListener = {
        frameLoadEvent:function () {
            var flowIframe =document.getElementById('flowframe');
            if(flowIframe){
                if(flowIframe.attachEvent){ //ie
                    flowIframe.onreadystatechange=function () {
                        if (this.readState == 'complete') {
                            frameListener.ajaxSend(this.contentWindow.XMLHttpRequest, frameListener.onAjaxSend);
                        }
                    };
                } else{  //other
                    flowIframe.onload = function () {
                        frameListener.ajaxSend(this.contentWindow.XMLHttpRequest, frameListener.onAjaxSend);
                    };

                }
            }
        },
        ajaxSend:function(objectOfXMLHttpRequest, callback) {
            if(!callback){
                return;
            }
            var s_ajaxListener = new Object();

            s_ajaxListener.tempOpen = objectOfXMLHttpRequest.prototype.open;

            s_ajaxListener.tempSend = objectOfXMLHttpRequest.prototype.send;

            s_ajaxListener.callback = function () {
                callback(this.method, this.url, this.data);
            }
            objectOfXMLHttpRequest.prototype.open = function(a,b) {
                if (!a) var a='';

                if (!b) var b='';
                s_ajaxListener.tempOpen.apply(this, arguments);
                s_ajaxListener.method = a;
                s_ajaxListener.url = b;
                if (a.toLowerCase() == 'get') {
                    s_ajaxListener.data = b.split('?');
                    s_ajaxListener.data = s_ajaxListener.data[1];
                }
            }
            objectOfXMLHttpRequest.prototype.send = function(a,b) {
                if (!a) var a='';
                if (!b) var b='';
                s_ajaxListener.tempSend.apply(this, arguments);
                if(s_ajaxListener.method.toLowerCase() == 'post') {
                    s_ajaxListener.data = a;
                }
                s_ajaxListener.callback();
            }

        },
        onAjaxSend:function (method, url, data) {
            if (url == horizon.tools.formatUrl('/flowchart/savedata') ) {
                //异步,等保存后再刷新右侧树,延迟执行
                setTimeout(function () {
                    $("#flow-tree").flowtree('reload');
                },500)
            }
        }
    };

    return horizon.engine['flowCreateListener'] = {
        init: function() {
            frameListener.frameLoadEvent();
        }
    };
}));