function log(message)
{
    if (window.console && typeof(console.log) == "function") 
        console.log(message); // firebug, safari
    else if (window.opera && typeof(opera.postError) == "function") 
        opera.postError(message);
}

var GLOBAL_INFO = 
{
    ACTION_URI: '/cmp_service/actionDispatcher.do',
    DEFAULT_ANCHOR: '#home',
    PAGE_CONTAINER: 'container',
    PROGRESS_CONTAINER: 'progressContainer',
    HOME_PAGE: 'index.html',
	PAGE_NAME : '页面'
};

var CALLBACK_TYPE = 
{
    NO_CALLBACK: 0,
    OPEN_URL: 1
};

var BmonPageEvents = 
{
    LOGIN: 'USER_LOGIN',
    LOGOUT: 'USER_LOGOUT',
    PAGELOAD: 'PAGELOAD',
    BROWSEHISTORY: 'BROWSEHISTORY'

};

var CDSResult = function()
{
};
CDSResult.prototype = 
{
    resultCode: '',
    errorCode: '',
    errorMessage: '',
    resultObj: {}
};

var $A = Array.from = function(iterable)
{
    if (!iterable) 
        return [];
    if (iterable.toArray) 
    {
        return iterable.toArray();
    }
    else 
    {
        var results = [];
        for (var i = 0, length = iterable.length; i < length; i++) 
            results.push(iterable[i]);
        return results;
    }
};

Function.prototype.bind = function()
{
    var __method = this, args = $A(arguments), object = args.shift();
    return function()
    {
        return __method.apply(object, args.concat($A(arguments)));
    }
};

$.extend(Array.prototype, 
{
    map: function(fn, bind)
    {
        var results = [];
        for (var i = 0, j = this.length; i < j; i++) 
            results[i] = fn.call(bind, this[i], i, this);
        return results;
    },
    
    filter: function(fn, bind)
    {
        var results = [];
        for (var i = 0, j = this.length; i < j; i++) 
        {
            if (fn.call(bind, this[i], i, this)) 
                results.push(this[i]);
        }
        return results;
    },
    
    indexOf: function(item, from)
    {
        var len = this.length;
        for (var i = (from < 0) ? Math.max(0, len + from) : from || 0; i < len; i++) 
        {
            if (this[i] === item) 
                return i;
        }
        return -1;
    }
});

var JSON = 
{

    $defined: function(obj)
    {
        return (obj != undefined);
    },
    
    encode: function(obj)
    {
        switch (typeof obj)
        {
            case 'string':
                return '"' + obj.replace(/[\x00-\x1f\\"]/g, JSON.$replaceChars) + '"';
            case 'array':
                return '[' + String(obj.map(JSON.encode).filter(JSON.$defined)) + ']';
            case 'object':
                if (obj instanceof Array) 
                {
                    return '[' + String(obj.map(JSON.encode).filter(JSON.$defined)) + ']';
                }
                else 
                {
                    var string = [];
                    for (var key in obj) 
                    {
                        var json = JSON.encode(obj[key]);
                        if (json) 
                            string.push(JSON.encode(key) + ':' + json);
                    }
                    return '{' + String(string) + '}';
                }
            case 'number':
            case 'boolean':
                return String(obj);
            case false:
                return 'null';
        }
        return null;
    },
    
    $specialChars: 
    {
        '\b': '\\b',
        '\t': '\\t',
        '\n': '\\n',
        '\f': '\\f',
        '\r': '\\r',
        '"': '\\"',
        '\\': '\\\\'
    },
    
    $replaceChars: function(chr)
    {
        return JSON.$specialChars[chr] || '\\u00' + Math.floor(chr.charCodeAt() / 16).toString(16) + (chr.charCodeAt() % 16).toString(16);
    },
    
    decode: function(string, secure)
    {
        if (typeof string != 'string' || !string.length) 
            return null;
        if (secure && !(/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(string.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, ''))) 
            return null;
        return eval('(' + string + ')');
    }
};

ComponentDynRequestInfo = function()
{
};
ComponentDynRequestInfo.prototype = 
{
	activityCode:"",//设值时则调用findActivityCDS，否则调用findService生成请求的cds实例
    dynamicURI: "",
    dynamicParameter: [],
    dynamicDataNodeName: '',
    dynamicPriority: 1, //0或1, 0表示非必要请求, 1表求必要请求
    dynamicRequestCallback: null
};

var BmonHistory = 
{
    historyCache: null,
    
    init: function()
    {
        this.history = new Array();
    },
    
    saveHistory: function(hash, strContent)
    {
        this.history[hash] = strContent;
    },
    
    clear: function()
    {
        this.historyCache = new Array();
    },
    
    getHisStory: function(hash)
    {
        var strContent = this.history[hash];
        return strContent;
    }
};
var GlobalProgressBar = function()
{
};
GlobalProgressBar.prototype = 
{
    container: null,
    imgDiv: null,
    toogleCon: null,
    timer: null,
    counter: 0,
    color: ["#050626", "#0a0b44", "#0f1165", "#1a1d95", "#1c1fa7", "#1c20c8", "#060cff", "#2963f8", "#330099"],
    
    init: function(con, toogle)
    {
        this.container = con;
        this.toogleCon = toogle;
        this.imgDiv = $("#__globalProgressBarImg");
    },
    
    show: function(txt, hideToogle)
    {
        this.imgDiv.text(txt);
        this.container.show();
        if (this.toogleCon) 
        {
            if (hideToogle) 
            {
                this.toogleCon.hide();
            }
        }
        this.startAnimate();
    },
    
    startAnimate: function()
    {
        this.timer = setInterval(function()
        {
            this.imgDiv.css("color", this.color[this.counter++ % this.color.length]);
        }.bind(this), 200);
    },
    
    reset: function()
    {
        this.container.hide();
        if (this.toogleCon) 
        {
            this.toogleCon.show();
        }
        this.stopAnimate();
    },
    
    stopAnimate: function()
    {
        if (this.timer != null) 
        {
            clearInterval(this.timer);
        }
    }
};

var BmonPage = 
{
    components: new Array(),
    history: BmonHistory,
    requesting: false,
    syncAjax: true, //设置成true的时候将使页面的ajax请求串行
    currentHash: '',
    checkURLInterval: null,
    useHistory: false,
    cache: new Array(),
    transientParam: {},
    initState: false,
    fullHash: '',
    globalProgressBar: null,
    pageInit: true,
    subPages : new Array(),
    //pageHash : {},			//pageHash是保留给页面名用的, 请不要再使用此变量
    
    logout: function()
    {
        this.ajax(
        {
            dynamicURI: '/login',
            dynamicParameter: 
            {
                'method': 'logout'
            },
            dynamicDataNodeName: 'logoutNode',
            dynamicRequestCallback: function(obj)
            {
                if (obj.resultCode == "1") 
                {
                    this.reload();
                }
            }.bind(this)
        });
    },
    
    showDialog: function(html, dialogArgument)
    {
        return window.top.bmon_showBmonDialog(html, dialogArgument);
    },
    
    showSuccessfulDialog: function(msg, dialogArgument)
    {
        return window.top.bmon_showBmonSuccessfulDialog(msg, dialogArgument);
    },
    
    showFailureDialog: function(msg, dialogArgument)
    {
        return window.top.bmon_showBmonFailureDialog(msg, dialogArgument);
    },
    
    showConfirmDialog: function(msg, dialogArgument)
    {
        return window.top.bmon_showBmonConfirmDialog(msg, dialogArgument);
    },
    
    showIFrameDialog: function(src, dialogArgument)
    {
        return window.top.bmon_showIFrameDialog(src, dialogArgument);
    },
    
    showProcessingDialog: function(msg)
    {
    	
        if (msg == null) 
        {
            msg = '正在办理, 请稍候';
        }
        $("#__bmonWaitingTxt").html(msg);
        var dialogArgument = 
        {
            width: "100%",
            height: "75px",
            pageCoverAlpha: "0.5",
            position: "bottom" //position should be top/middle/bottom
        };
        var cssHTML = "<style type=\"text/css\">*{margin:0;padding:0}body{margin:0;font-size:12px; font-family:tahoma,sans-serif,Helvetica, Arial,\"Lucida Grande\";color:#666; }img{border:0px;}a{outline:none;}ul{list-style-type:none;}</style>";
        var html = cssHTML + $("#__bmonWaitingDiv").html();
        return window.top.bmon_showBmonDialog(html, dialogArgument);
    },
    
    showLoadingDialog: function(hash)
    {        
        hash = this.getPageNameFromHash(hash);
        var txt = "<div align='center'>正在加载" + hash + ", 请稍候...</div>";
        $("#__bmonWaitingTxt").html(txt);
        var dialogArgument = 
        {
            width: "100%",
            height: "75px",
            pageCoverAlpha: "0.5",
            position: "bottom"
        };
        var cssHTML = "<style type=\"text/css\">*{margin:0;padding:0}body{margin:0;font-size:12px; font-family:tahoma,sans-serif,Helvetica, Arial,\"Lucida Grande\";color:#666; }img{border:0px;}a{outline:none;}ul{list-style-type:none;}</style>";
        var html = '';
        var bmonWaitingDivObj = $("#__bmonWaitingDiv");
        if(bmonWaitingDivObj[0]){
        	html = cssHTML + $("#__bmonWaitingDiv").html();
        }else{
        	html = cssHTML + txt;
        }
        
        //var obj = window.top.bmon_showBmonDialog(html, dialogArgument)
        var obj = window.top.bmon_showBmonDialog(html, dialogArgument)        
        return obj;
    },
    
    showBmonFlashDialog: function(flashUrl, dialogArgument)
    {
        window.top.bmon_showBmonFlashDialog(flashUrl, dialogArgument);
    },
    
    getPageNameFromHash: function(hash)
    {
        if (hash == null) 
        {
            return "页面";
        }
        if (hash.indexOf("#") == 0) 
        {
            hash = hash.substring(1);
        }
        if (this.pageHash) 
        {
            var name = this.pageHash.hash;
            if (name == null) 
            {
                name = "页面";
            }
            return name;
        }
        return "页面";
    },
    
    forceCloseDialog: function()
    {
        window.top.forceCloseDialog();
    },
    
    goto: function(hash)
    {
        window.location.hash = hash;
    },
    
    registerComponent: function(component)
    {
        this.components.push(component);
    },
    
    unregisterComponent: function(component)
    {
        this.components.remove(component);
    },
    
    cache: function(key, obj)
    {
        this.cache[key] = obj;
    },
    
    uncache: function(key)
    {
        this.cache[key] = null;
    },
    
    getCached: function(key)
    {
        return this.cache[key];
    },
    
    createComponent: function()
    {
        var component = new BmonComponent();
        this.registerComponent(component);
        return component;
    },
    
    checkHash: function()
    {
        var hash = this.parseURL();
        var forceLoad = false;
        if (this.fullHash == null || this.fullHash == '') 
        {
            this.fullHash = hash;
        }
        else if (this.fullHash != hash) 
        {
            forceLoad = true;
            this.fullHash = hash;
            this.parseTransientParameter(hash);
        }
        if (hash.indexOf('@') > 0) 
        {
            hash = hash.substring(0, hash.indexOf('@'));
        }
        if (this.currentHash != hash && hash != null && hash != '' || forceLoad) 
        {
            if (this.useHistory) 
            {
                var hisContent = this.history.getHisStory(hash);
                if (hisContent != null) 
                {
                    this.currentHash = hash;
                    this.showContent(hisContent);
                    return;
                }
            }
            this.init(hash);
        }
    },
    
    createSubComponent : function()
    {
    	return this.createComponent();
    },
    
    registerSubPage : function(pageHash, containerName)
    {
    	this.subPages.push({
    		'page' : this.hashToPage(pageHash),
    		'container' : containerName
    	});
    },
    
    findComponent : function(name)
    {
    	for(var i = 0;i<this.components.length;i++)
    	{
    		if(this.components[i].id == name)
    		{
    			return this.components[i];
    		}
    	}
    },
    
    //参数形式: @paramName=;paramName1=;paramName2=;
    parseTransientParameter: function(hash)
    {
        var nIndex = hash.indexOf('@');
        if (nIndex > 0) 
        {
            hash = hash.substring(nIndex + 1);
            var groupArr = hash.split(';');
            for (var i = 0; i < groupArr.length; i++) 
            {
                var tempArr = groupArr[i].split('=');
                var key = tempArr[0];
                var val = tempArr[1];
                if (key != null && key != '') 
                {
                    this.transientParam[key] = val;
                }
            }
        }
    },
    
    getTransientParameter: function(name)
    {
        return this.transientParam[name];
    },
    
    clearTransientParameter: function()
    {
        this.transientParam = {};
    },
    
    setTransientParameter: function(obj)
    {
        $.extend(this.transientParam, obj);
    },
    
    setTransientParameterValue: function(key, value)
    {
        this.transientParam[key] = value;
    },
    
    reload: function()
    {
        this.init(this.currentHash);
    },
    
    clearSubPages : function()
    {
    	this.subPages = new Array();    	
    },
    
    clearComponents: function()
    {
        var loComponents = new Array();
        for (var i = 0; i < this.components.length; i++) 
        {
            if (this.components[i].loadOnce) 
            {
                loComponents.push(this.components[i]);
            }
            else
            {
            	try
            	{
            		this.components[i].destroy();
            	}
            	catch(e)
            	{
            		log("destrory error: " + this.components[i].id);
            	}	
            }
        }
        this.components = new Array();
        for (var i = 0; i < loComponents.length; i++) 
        {
            this.components.push(loComponents[i]);
        }
    },
    
    init: function(href, bCover)
    {
        if (this.syncAjax && this.requesting) 
        {
            //log("等待服务器响应, 请稍候操作!");
            return;
        }
        this.initState = true;
        if (this.globalProgressBar == null) 
        {
            this.globalProgressBar = new GlobalProgressBar();
            this.globalProgressBar.init($("#__globalProgressBar"), $("#__pageMain"));
        }
        this.clearComponents();
        this.clearSubPages();
        log('page initializing...');
        if (href == null)
        {
            var hash = this.parseURL();
            if (hash.indexOf('@') > 0) 
            {
                this.parseTransientParameter(hash);
                hash = hash.substring(0, hash.indexOf('@'));
            }
            this.loadPage(hash, bCover);
        }
        else 
        {

            this.loadPage(href, bCover);
        }
        if (this.checkURLInterval == null) 
        {
            setInterval(function()
            {
               
                this.checkHash();
                if(BmonPage.getPageTitle)
                {
	                if(document.title != BmonPage.getPageTitle())
	                {
	                	document.title = BmonPage.getPageTitle();
	                }
	            }
            }.bind(this), 100);
        }
    },
    
    reloadPageWithoutCover: function()
    {
        this.init(this.currentHash, 'false');
    },
    
    loadPage: function(hash, bCover)
    {
        if (hash != null && hash != '') 
        {
            if (!this.pageInit && !('false' == bCover)) 
            {
                this.showLoadingDialog(hash);
            }
            log('loading page: ' + hash);
            this.currentHash = hash;
            var pageName = this.hashToPage(hash);
//            if(pageName == "mmsBlessing.html" || pageName == "caixun.html" || pageName == "moblieNewspaper.html" || pageName == "moblieRead.html" || pageName == "song.html"){
//                pageName = "childpages/" + pageName;
//            }
            $.ajax(
            {
                url: pageName,
                type: "get",
                timeout: 60000,
                dataType: "text",
                success: function(ret)
                {
                    $("#" + GLOBAL_INFO.PAGE_CONTAINER).html(ret);
                    this.initSubPages();
                    this.initComponents();
                    this.clearTransientParameter();
                }.bind(this),
                error: function(ret, errorMsg)
                {
                    //出错统一处理
                    if ("timeout" == errorMsg) 
                    {
                        BmonPage.showProcessingDialog('连接超时, 请重试!');
                        setTimeout(function()
                        {
                            BmonPage.forceCloseDialog();
                        }, 2000);
                    }
                    else if ("error" == errorMsg) 
                    {
                        BmonPage.showProcessingDialog('操作失败, 请重试!');
                        setTimeout(function()
                        {
                            BmonPage.forceCloseDialog();
                        }, 2000);
                    }
                }.bind(this)
            });
        }
    },
    
    estimatePageLoadingTime: function()
    {
        var maxTime = 0;
        for (var i = 0; i < this.components.length; i++) 
        {
            if (this.components[i].pageLoadingTime > maxTime) 
            {
                maxTime = this.components[i].pageLoadingTime;
            }
        }
        return maxTime;
    },
    
    updateHistory: function()
    {
        this.history.saveHistory(this.currentHash, $("#" + GLOBAL_INFO.PAGE_CONTAINER).html());
    },
    
    showContent: function(content)
    {
        $("#" + GLOBAL_INFO.PAGE_CONTAINER).html(content);
    },
    
    hashToPage: function(hash)
    {
        return hash.substring(1) + ".html";
    },
    
    parseURL: function()
    {
        var hash = window.location.hash;
        if (hash == null || hash == '') 
        {
            hash = GLOBAL_INFO.DEFAULT_ANCHOR;
            window.location.hash = hash;
            this.currentHash = hash;
        }
        return hash;
    },
    
    initSubPages : function()
    {
    	for(var i = 0;i<this.subPages.length;i++)
    	{
    		//alert(this.subPages[i].page + "," + this.subPages[i].container);
    		$.ajax(
                    {
                        url: this.subPages[i].page,
                        type: "get",
                        timeout: 60000,
                        dataType: "text",
                        async : false,
                        success: function(ret)
                        {
                            $("#" + this.subPages[i].container).html(ret);
                        }.bind(this),
                        error: function(ret, errorMsg)
                        {
                            //出错统一处理
                            if ("timeout" == errorMsg) 
                            {
                                BmonPage.showProcessingDialog('连接超时, 请重试!');
                                setTimeout(function()
                                {
                                    BmonPage.forceCloseDialog();
                                }, 2000);
                            }
                            else if ("error" == errorMsg) 
                            {
                                BmonPage.showProcessingDialog('操作失败, 请重试!');
                                setTimeout(function()
                                {
                                    BmonPage.forceCloseDialog();
                                }, 2000);
                            }
                        }.bind(this)
                    }
                   );
    	}    	
    },
    
    initComponents: function()
    {
        log('init components...');
        var requests = new Array();
        for (var i = 0; i < this.components.length; i++) 
        {
            //如果没有load过则load之, 否则不再触发其init函数
            if (!this.components[i].isLoad) 
            {
                this.components[i].init();
                this.components[i].isLoad = true;
                if (!this.components[i].isStatic) 
                {
                    var req = this.components[i].initReqInfo;
                    if (req != null) 
                    {
                        requests.push(req);
                    }
                }
            }
        }
        this.composedAjaxRequest(requests);
    },
    
    ajax: function(requests, callbacks)
    {
        //callbacks.timeout, callbacks.error
        this.composedAjaxRequest(requests, callbacks);
    },
    
    composedAjaxRequest: function(requests, callbacks)
    {
        if (requests && requests.length) 
        {
            log('ajax call...');
            var arr = new Array();
            var jsonRequestStr = JSON.encode(requests);
            var params = 
            {
                'jsonParam': jsonRequestStr
            };
            if (this.syncAjax) 
            {
                //如果是同步ajax的, 则需要根据this.requesting状态决定是不是进行ajax请求
                if (!this.requesting) 
                {
                    this.requesting = true;
                    $.ajax(
                    {
                        url: GLOBAL_INFO.ACTION_URI,
                        type: 'POST',
                        dataType: 'text',
                        data: params,
                        success: function(ret)
                        {
                            this.requesting = false;
                            this.parseComposedAjaxResponse(ret, requests);
                            this.fireEvent(BmonPageEvents.PAGELOAD, {});
                        }.bind(this),
                        error: function(ret, errorMsg)
                        {
                        
                            if (errorMsg == "timeout") 
                            {
                                if (callbacks && callbacks.timeout) 
                                {
                                    callbacks.timeout(ret);
                                }
                                else 
                                {
                                    BmonPage.showProcessingDialog('连接超时, 请重试!');
                                    setTimeout(function()
                                    {
                                        BmonPage.forceCloseDialog();
                                    }, 2000);
                                }
                            }
                            else if (callbacks && callbacks.error) 
                            {
                                callbacks.error(ret);
                            }
                            else 
                            {
                                //统一处理
                                BmonPage.showProcessingDialog('操作失败, 请重试!');
                                setTimeout(function()
                                {
                                    BmonPage.forceCloseDialog();
                                }, 2000);
                            }
                        }.bind(this),
                        complete: function()
                        {
                            this.requesting = false;
                            this.firePageLoadEnd();
                        }.bind(this)
                    });
                }
                else 
                {
                    log('正在等待服务器响应, ajax请求被拒绝[' + jsonRequestStr + ']!');
                }
            }
            else 
            {
                $.post(GLOBAL_INFO.ACTION_URI, params, function(ret)
                {
                    this.parseComposedAjaxResponse(ret, requests);
                }.bind(this));
                this.firePageLoadEnd();
                this.fireEvent(BmonPageEvents.PAGELOAD, {});
            }
        }
        else 
        {
            this.firePageLoadEnd();
            this.fireEvent(BmonPageEvents.PAGELOAD, {});
        }
    },
    
    firePageLoadEnd: function()
    {
        if (this.initState) 
        {
            this.updateHistory();
            this.initState = false;
            //所有打开的对话框将被关闭, for loading dialog...
            this.forceCloseDialog();
        }
        if (this.pageInit) 
        {
        	if(this.globalProgressBar != null)
        	{
        		this.globalProgressBar.reset();
        	}
            this.pageInit = false;
        }
    },
    
    parseComposedAjaxResponse: function(retStr, requests)
    {
        log(retStr);
        var obj = JSON.decode(retStr);
        if (obj) 
        {
            for (var i = 0; i < requests.length; i++) 
            {
                if (requests[i].dynamicRequestCallback != null) 
                {
                    var result = new CDSResult();
                    $.extend(result, obj[requests[i].dynamicDataNodeName]);
                    requests[i].dynamicRequestCallback(result);
                    //执行cds客户端回调
                    var clientCallback = result.clientCallbackInfo;
                    if (clientCallback) 
                    {
                        if (clientCallback.callbackType == CALLBACK_TYPE.OPEN_URL) 
                        {
                            var url = clientCallback.openURL;
                            window.open(url);
                        }
                    }
                }
            }
        }
        else 
        {
            log('server no response');
        }
    },
    
    fireEvent: function(eventName, eventParam)
    {
        for (var i = 0; i < this.components.length; i++) 
        {
            this.components[i].fireEvent(eventName, eventParam);
        }
    }
};

BmonComponent = function()
{
};
BmonComponent.prototype = 
{
    id: '',
    name: '',
    isStatic: false,
    loadOnce: false,
    eventListeners: new Array(),
    initReqInfo: null,
    pageLoadingTime: 3000,
    isLoad: false,
    
    init: function()
    {
    },
    
    estimatePageLoadingTime: function(time)
    {
        this.pageLoadingTime = time;
    },
    
    ajax: function(requestInfo)
    {
        var requestArr = new Array();
        requestArr.push(requestInfo);
        BmonPage.ajax(requestArr);
    },
    
    addEventListener: function(eventName, fpCallback)
    {
        var arrEventListener = this.eventListeners[eventName];
        if (arrEventListener == null) 
        {
            this.eventListeners[eventName] = new Array();
        }
        this.eventListeners[eventName].push(fpCallback);
    },
    
    removeEventListener: function(eventName, fpCallback)
    {
        var arrEventListener = this.eventListeners[eventName];
        if (arrEventListener != null) 
        {
            var index = arrEventListener.indexOf(fpCallback);
            if (index >= 0) 
            {
                arrEventListener.splice(index, 1);
            }
        }
    },
    
    fireEvent: function(eventName, eObj)
    {
        var arrEventListener = this.eventListeners[eventName];
        if (arrEventListener != null) 
        {
            for (var i = 0; i < arrEventListener.length; i++) 
            {
                var fp = arrEventListener[i];
                try 
                {
                    fp(eObj);
                } 
                catch (e) 
                {
                    log("event callback: " + fp + e.message);
                }
            }
        }
    },
    
    firePageEvent: function(name, param)
    {
        BmonPage.fireEvent(name, param);
    },
    
    makeCacheKey: function(key)
    {
        return this.id + key;
    },
    
    cache: function(key, obj)
    {
        BmonPage.cache(this.makeCacheKey(key), obj);
    },
    
    uncache: function(key)
    {
        BmonPage.uncache(this.makeCacheKey(key));
    },
    
    getCached: function(key)
    {
        return BmonPage.getCached(this.makeCacheKey(key));
    },
    
    loadNextTime: function()
    {
        this.isLoad = false;
    },
    
    destroy: function()
    {
    }
};

//==========================================Page Load========================================
$(document).ready(function()
{
    try{
        if(defaultPage != ""){
            GLOBAL_INFO.DEFAULT_ANCHOR = defaultPage;
        }
    }catch(e){}
    BmonPage.history.init();
    BmonPage.init();
    try 
    {
        initFunctionsForTopWindow();
        if (document.all) 
        {
            window.top.attachEvent("onscroll", window.top.bmon_doOnscroll);
        }
        else 
        {
            window.top.addEventListener("scroll", window.top.bmon_doOnscroll, true);
        }
    } 
    catch (e) 
    {
        log(e.message);
    }
    try{
        //BmonPage.globalProgressBar.show("正在加载" + GLOBAL_INFO.PAGE_NAME + "，请稍候...", true);
    }catch(e){
        log(e.message);
    }
});


BmonDialogArgument = function()
{
};
BmonDialogArgument.prototype = 
{
    width: 427,
    height: 223,
    title: "",
    pageCoverAlpha: "0.5",
    closeDialog: true,
    yesCallback: function(){},
    noCallback: function(){},
    cancelCallback: function(){},
    yesCallbackArgument: {},
    noCallbackArgument: {},
    cancelCallbackArgument: {}
};

function initFunctionsForTopWindow()
{
    window.top.bmon_showTransparentCover = function(alpha)
    {
        if (alpha == null) 
        {
            alpha = "0.5";
        }
        var div = window.top.document.createElement("div");
        div.id = "__Bmon__Transparent_Cover_Div";
        div.style.position = 'absolute';
        div.style.backgroundColor = '#CCCCCC';
        div.style.filter = "alpha(opacity=50)";
        div.style.transparent = true;
        div.style.opacity = alpha;
        div.style.backgroudColor = "#000000";
        div.style.zIndex = 999;
        window.top.document.body.appendChild(div);
        var windowWidth = 0;
        var windowHeight = 0;
        if (!document.all) 
        {
            windowWidth = window.top.document.documentElement.clientWidth;
            windowHeight = window.top.document.body.clientHeight;
        }
        else 
        {
            windowWidth = window.top.document.body.clientWidth;
            windowHeight = window.top.document.body.clientHeight;
        }
        windowHeight = windowHeight + 20;
        div.style.width = windowWidth + "px";
        div.style.height = windowHeight + "px";
        div.style.left = "0px";
        div.style.top = "0px";
        window.top.bmon_centerElement(div, windowWidth, windowHeight);
    };
    
    window.top.bmon_hideTransparentCover = function()
    {
        if (window.top.document.getElementById('__Bmon__Transparent_Cover_Div')) 
        {
            window.top.document.body.removeChild(window.top.document.getElementById('__Bmon__Transparent_Cover_Div'));
        }
    };
    
    window.top.bmon_centerElement = function(el, width, height)
    {
        if (!width) 
        {
            width = parseInt(el.clientWidth);
        }
        else 
        {
            width = parseInt(width);
        }
        if (!height) 
        {
            height = parseInt(el.clientHeight);
        }
        else 
        {
            height = parseInt(height);
        }
        var windowWidth = 0;
        var windowHeight = 0;
        var scrollTop = 0;
        var x = 0;
        var y = 0;
        
        if (!document.all) 
        {
            windowWidth = window.top.document.documentElement.clientWidth;
            windowHeight = window.top.document.documentElement.clientHeight;
            scrollTop = window.top.document.documentElement.scrollTop;
            y = scrollTop + (windowHeight - height) / 2;
        }
        else 
        {
            windowWidth = window.top.document.documentElement.clientWidth;
            windowHeight = window.top.document.documentElement.clientHeight;
            scrollTop = window.top.document.documentElement.scrollTop;
            y = scrollTop + (windowHeight - height) / 2;
        }
        x = (windowWidth - width) / 2;
        if (parseInt(y + parseInt(height)) > window.top.document.body.clientHeight) 
        {
            y = window.top.document.body.clientHeight - height;
        }
        el.style.left = x + "px";
        el.style.top = y + "px";
    };
    
    window.top.bmon_topElement = function(el, width, height)
    {
        if (!width) 
        {
            width = parseInt(el.clientWidth);
        }
        else 
        {
            width = parseInt(width);
        }
        if (!height) 
        {
            height = parseInt(el.clientHeight);
        }
        else 
        {
            height = parseInt(height);
        }
        var windowWidth = 0;
        var windowHeight = 0;
        var scrollTop = 0;
        var x = 0;
        var y = 0;
        
        if (!document.all) 
        {
            windowWidth = window.top.document.documentElement.clientWidth;
            windowHeight = window.top.document.documentElement.clientHeight;
            scrollTop = window.top.document.documentElement.scrollTop;
            y = scrollTop;
        }
        else 
        {
            windowWidth = window.top.document.documentElement.clientWidth;
            windowHeight = window.top.document.documentElement.clientHeight;
            scrollTop = window.top.document.documentElement.scrollTop;
            y = scrollTop;
        }
        x = (windowWidth - width) / 2;
        if (parseInt(y + parseInt(height)) > window.top.document.body.clientHeight) 
        {
            y = window.top.document.body.clientHeight - height;
        }
        el.style.left = x + "px";
        el.style.top = y + "px";
    };
    
    window.top.bmon_bottomElement = function(el, width, height)
    {
        if (!width) 
        {
            width = parseInt(el.clientWidth);
        }
        else 
        {
            width = parseInt(width);
        }
        if (!height) 
        {
            height = parseInt(el.clientHeight);
        }
        else 
        {
            height = parseInt(height);
        }
        var windowWidth = 0;
        var windowHeight = 0;
        var scrollTop = 0;
        var x = 0;
        var y = 0;
        
        if (!document.all) 
        {
            windowWidth = window.top.document.documentElement.clientWidth;
            windowHeight = window.top.document.documentElement.clientHeight;
            scrollTop = window.top.document.documentElement.scrollTop;
            y = scrollTop + windowHeight - height;
        }
        else 
        {
            windowWidth = window.top.document.documentElement.clientWidth;
            windowHeight = window.top.document.documentElement.clientHeight;
            scrollTop = window.top.document.documentElement.scrollTop;
            y = scrollTop + windowHeight - height;
        }
        x = (windowWidth - width) / 2;
        if (parseInt(y + parseInt(height)) > window.top.document.body.clientHeight) 
        {
            y = window.top.document.body.clientHeight - height;
        }
        el.style.left = x + "px";
        el.style.top = y + "px";
    };
    
    window.top.bmon_doOnscroll = function()
    {
        if (window.top.document.getElementById('__Bmon__Transparent_Cover_Div')) 
        {
            var el = window.top.document.getElementById('__Bmon__Transparent_Cover_Div');
            if ("top" == el.dialogPosition) 
            {
                window.top.bmon_topElement(el);
            }
            else if ("bottom" == el.dialogPosition) 
            {
                window.top.bmon_bottomElement(el);
            }
            else 
            {
                window.top.bmon_centerElement(el);
            }
        }
        if (window.top.document.getElementById('__Bmon__Dialog__Div')) 
        {
            var el = window.top.document.getElementById('__Bmon__Dialog__Div');
            if ("top" == el.dialogPosition) 
            {
                window.top.bmon_topElement(el);
            }
            else if ("bottom" == el.dialogPosition) 
            {
                window.top.bmon_bottomElement(el);
            }
            else 
            {
                window.top.bmon_centerElement(el);
            }
        }
    };
    
    window.top.forceCloseDialog = function()
    {
        //close exists
        if (window.top.document.getElementById('__Bmon__Transparent_Cover_Div')) 
        {
            window.top.document.body.removeChild(window.top.document.getElementById('__Bmon__Transparent_Cover_Div'));
        }
        if (window.top.document.getElementById('__Bmon__Dialog__Div')) 
        {
            window.top.document.body.removeChild(window.top.document.getElementById('__Bmon__Dialog__Div'));
        }
    };
    
    window.top.bmon_showBmonDialog = function(html, dialogArgument)
    {
        dialogArgument = dialogArgument == null ? new BmonDialogArgument() : dialogArgument;
        if (!dialogArgument.width) 
        {
            dialogArgument.width = 427;
        }
        if (!dialogArgument.height) 
        {
            dialogArgument.height = 223;
        }
        if (!dialogArgument.pageCoverAlpha) 
        {
            dialogArgument.pageCoverAlpha = "0.5";
        }
        //set callback variables
        window.top.BMON_DIALOG_CALLBACK_YES = dialogArgument.yesCallback;
        window.top.BMON_DIALOG_CALLBACK_NO = dialogArgument.noCallback;
        window.top.BMON_DIALOG_CALLBACK_CANCEL = dialogArgument.cancelCallback;
        window.top.BMON_DIALOG_CALLBACK_YES_ARG = dialogArgument.yesCallbackArgument;
        window.top.BMON_DIALOG_CALLBACK_NO_ARG = dialogArgument.noCallbackArgument;
        window.top.BMON_DIALOG_CALLBACK_CANCEL_ARG = dialogArgument.noCallbackArgument;
        
        window.top.bmon_showTransparentCover(dialogArgument.pageCoverAlpha);
        
        var shouldCloseExists = window.top.document.getElementById("__Bmon__Dialog__Div") != null;
        
        var div = window.top.document.createElement("div");
        div.id = "__Bmon__Dialog__Div";
        div.style.overflow = "hidden";
        div.dialogPosition = dialogArgument.position; //write property for scrolling relocation
        if (dialogArgument.showCloseButton) 
        {
            var tb = window.top.document.createElement("table");
            tb.height = "20px";
            tb.width = "100%";
            var tr = tb.insertRow(0);
            var tdLeft = tr.insertCell(0);
            tdLeft.width = "90%";
            tdLeft.innerHTML = "&nbsp;";
            var tdRight = tr.insertCell(1);
            tdRight.align = "right";
            tdRight.innerHTML = "<a href='javascript:void(0);' onclick='window.top.forceCloseDialog();'>关闭</a>";
            div.appendChild(tb);
            dialogArgument.height = parseInt(dialogArgument.height) + 20;
        }
        var ifr = window.top.document.createElement("iframe");
        ifr.height = dialogArgument.height;
        ifr.width = dialogArgument.width;
        ifr.frameBorder = 0;
        ifr.id = "__Bmon__Dialog__FRAME";
        div.style.position = "absolute";
        div.style.zIndex = 9999;
        div.style.width = dialogArgument.width;
        div.style.height = dialogArgument.height;
        div.style.overflow = "hidden";
        ifr.src = "about:blank";
        div.appendChild(ifr);
        window.top.document.body.appendChild(div);
        ifr.scrolling = 'no';
        ifr.style.overflow = "hidden";
        try 
        {
            ifr.contentWindow.document.open();
            ifr.contentWindow.document.write(html);
            ifr.contentWindow.document.close();
        } 
        catch (e) 
        {
            log(e.message);
        }
        if ("top" == dialogArgument.position) 
        {
            window.top.bmon_topElement(div);
        }
        else if ("bottom" == dialogArgument.position) 
        {
            window.top.bmon_bottomElement(div);
        }
        else 
        {
            window.top.bmon_centerElement(div);
        }
        ifr.contentWindow.document.body.focus();
        if (shouldCloseExists) 
        {
            //close exists
            window.top.forceCloseDialog(); //uncomment will cause FF iframe document write security error!!!
        }
        
        return ifr;
    };
    
    //弹出窗口的CSS样式
    window.top.bmon_dialogCss = "<style type='text/css'>" +
    "*{margin:0px; padding:0px;}" +
    "body{font-size:12px;font-family:tahoma,sans-serif,Helvetica, Arial,'Lucida Grande';color:#666;overflow-x:hidden;overflow-y:hidden;}" +
    "img{border:0px;} a{outline:none;} ul{list-style-type:none;}" +
    ".open-tipdiv{width:427px;}" +
    ".optip-top{position:relative; width:427px; height:33px; background:url(cmpfiles/cmp/cmp_image/fucktipbg-top.jpg) no-repeat;}" +
    ".fucktipbody{position:relative; width:427px; background:url(cmpfiles/cmp/cmp_image/fucktipbg-body.jpg) repeat-y;}" +
    ".fucktipbottom{width:427px; height:7px; background:url(cmpfiles/cmp/cmp_image/fucktipbg-bottom.jpg) no-repeat; overflow:hidden;zoom:1;}" +
    ".fucktipbtns{position:relative;width:427px; height:65px; background:url(cmpfiles/cmp/cmp_image/fucktipbtns.jpg) no-repeat;}" +
    ".fucktipbtns2{position:relative;width:427px; height:65px; background:url(cmpfiles/cmp/cmp_image/fucktipbtns2.jpg) no-repeat;}" +
    ".fucktipbtns3{position:relative;width:427px; height:65px; background:url(cmpfiles/cmp/cmp_image/fucktipbtns3.jpg) no-repeat;}" +
    ".fucktipbtns4{position:relative;width:427px; height:65px; background:url(cmpfiles/cmp/cmp_image/fucktipbtns4.jpg) no-repeat;}" +
    ".optip-body{width:427px; background:url(cmpfiles/cmp/cmp_image/pmbg.jpg) repeat-y;}" +
    ".optip-bottom{width:427px; height:7px; background:url(cmpfiles/cmp/cmp_image/fuckmainbottom.jpg) no-repeat;  overflow:hidden;zoom:1;}" +
    "a.optip-close{ display:block; position:absolute; right:8px; top:7px; width:14px; height:14px; }" +
    ".optip-con{margin-left:116px; width:270px; height:97px;}" +
    ".optd1{width:215px; font-weight:bold; font-family:'微软雅黑'; color:#7d8c97; font-size:12px; line-height:20px;}" +
    ".optd2{width:55px; text-align:center;}" +
    ".optd2 img{display:block; margin:0 auto;}" +
    ".btngroup{position:absolute; left:106px; top:28px; width:220px; text-align:center;}" +
    ".btngroup2{position:absolute; left:76px; top:28px; width:270px; text-align:center;}" +
    "input.tipbtn{border:0px; width:71px; height:26px; background:url(cmpfiles/cmp/cmp_image/tipbtn.jpg) no-repeat; font-size:12px; font-weight:bold; cursor:pointer; color:#3d57a1;}" +
    "input.tipbtn2{border:0px; width:121px; height:26px; background:url(cmpfiles/cmp/cmp_image/tipbtn2.jpg) no-repeat; font-size:12px; font-weight:bold; cursor:pointer; color:#3d57a1;}" +
    ".business-banner{margin:0 auto; width:407px; border-top:1px dotted #ccc; padding:5px 0;font-weight:bold; font-family:'微软雅黑'; color:#7d8c97; font-size:14px; line-height:20px; text-align:center;}" +
    ".girl{position:absolute; left:39px; top:0px; width:65px; height:97px; background:url(cmpfiles/cmp/cmp_image/girl.jpg) no-repeat; }" +
    "</style>";
    
    window.top.bmon_dialogCallback = function(type)
    {
        var callbackRet = '';
        if ('yes' == type) 
        {
            try 
            {
                if (window.top.BMON_DIALOG_CALLBACK_YES_ARG == null) 
                {
                    window.top.BMON_DIALOG_CALLBACK_YES_ARG = {};
                }
                if (window.window.top.document.getElementById('__Bmon__Dialog__FRAME')) 
                {
                    window.top.BMON_DIALOG_CALLBACK_YES_ARG.document = window.top.document.getElementById('__Bmon__Dialog__FRAME').contentWindow.document;
                }
                callbackRet = window.top.BMON_DIALOG_CALLBACK_YES(window.top.BMON_DIALOG_CALLBACK_YES_ARG);
            } 
            catch (e) 
            {
            }
        }
        else if ('no' == type) 
        {
            try 
            {
                if (window.top.BMON_DIALOG_CALLBACK_NO_ARG == null) 
                {
                    window.top.BMON_DIALOG_CALLBACK_NO_ARG = {};
                }
                if (window.window.top.document.getElementById('__Bmon__Dialog__FRAME')) 
                {
                    window.top.BMON_DIALOG_CALLBACK_NO_ARG.document = window.top.document.getElementById('__Bmon__Dialog__FRAME').contentWindow.document;
                }
                callbackRet = window.top.BMON_DIALOG_CALLBACK_NO(window.top.BMON_DIALOG_CALLBACK_NO_ARG);
            } 
            catch (e) 
            {
            }
        }
        else if ('cancel' == type) 
        {
            try 
            {
                if (window.top.BMON_DIALOG_CALLBACK_CANCEL_ARG == null) 
                {
                    window.top.BMON_DIALOG_CALLBACK_CANCEL_ARG = {};
                }
                if (window.window.top.document.getElementById('__Bmon__Dialog__FRAME')) 
                {
                    window.top.BMON_DIALOG_CALLBACK_CANCEL_ARG.document = window.top.document.getElementById('__Bmon__Dialog__FRAME').contentWindow.document;
                }
                callbackRet = window.top.BMON_DIALOG_CALLBACK_CANCEL(window.top.BMON_DIALOG_CALLBACK_CANCEL_ARG);
            } 
            catch (e) 
            {
            }
        }
        if (!(('no_close') == callbackRet)) 
        {
            if (window.top.document.getElementById('__Bmon__Transparent_Cover_Div')) 
            {
                window.top.document.body.removeChild(window.top.document.getElementById('__Bmon__Transparent_Cover_Div'));
            }
            if (window.top.document.getElementById('__Bmon__Dialog__Div')) 
            {
                window.top.document.body.removeChild(window.top.document.getElementById('__Bmon__Dialog__Div'));
            }
        }
    };
    
    window.top.bmon_showBmonSuccessfulDialog = function(msg, dialogArgument)
    {
        dialogArgument = dialogArgument == null ? new BmonDialogArgument() : dialogArgument;
        var bodyHtml = "<div class='open-tipdiv'>" +
        "<div class='optip-top'><a href='javascript:window.top.bmon_dialogCallback(\"no\");' title='关闭' class='optip-close'></a></div>" +
        "<div class='fucktipbody'><div class='girl'></div>" +
        "<table cellpadding='0' cellspacing='0' class='optip-con'>" +
        "<tr><td class='optd1' valign='center'>" +
        msg +
        "</td><td class='optd2' valign='center'><img src='cmpfiles/cmp/cmp_image/right.jpg' /></td>" +
        "</tr></table></div><div class='fucktipbottom'></div>" +
        "<div class='fucktipbtns3'><div class='btngroup'><input type='button' class='tipbtn' value='确定' onclick=\"window.top.bmon_dialogCallback('yes');\" /></div></div>" +
        "<div class='optip-body'></div><div class='optip-bottom'></div></div>";
        return window.top.bmon_showBmonDialog(window.top.bmon_dialogCss + bodyHtml, dialogArgument);
    };
    
    window.top.bmon_showBmonFailureDialog = function(msg, dialogArgument)
    {
        dialogArgument = dialogArgument == null ? new BmonDialogArgument() : dialogArgument;
        var bodyHtml = "<div class='open-tipdiv'>" +
        "<div class='optip-top'><a href='javascript:window.top.bmon_dialogCallback(\"no\");' title='关闭' class='optip-close'></a></div>" +
        "<div class='fucktipbody'><div class='girl'></div>" +
        "<table cellpadding='0' cellspacing='0' class='optip-con'>" +
        "<tr><td class='optd1' valign='center'>" +
        msg +
        "</td><td class='optd2' valign='center'><img src='cmpfiles/cmp/cmp_image/error.jpg' /></td>" +
        "</tr></table></div><div class='fucktipbottom'></div>" +
        "<div class='fucktipbtns3'><div class='btngroup'><input type='button' class='tipbtn' value='确定' onclick=\"window.top.bmon_dialogCallback('yes');\" /></div></div>" +
        "<div class='optip-body'></div><div class='optip-bottom'></div></div>";
        
        return window.top.bmon_showBmonDialog(window.top.bmon_dialogCss + bodyHtml, dialogArgument);
    };
    
    window.top.bmon_showBmonConfirmDialog = function(msg, dialogArgument)
    {
        dialogArgument = dialogArgument == null ? new BmonDialogArgument() : dialogArgument;
        var bodyHtml = "<div class='open-tipdiv'>" +
        "<div class='optip-top'><a href='javascript:window.top.bmon_dialogCallback(\"no\");' title='关闭' class='optip-close'></a></div>" +
        "<div class='fucktipbody'><div class='girl'></div>" +
        "<table cellpadding='0' cellspacing='0' class='optip-con'>" +
        "<tr><td class='optd1' valign='center'>" +
        msg +
        "</td><td class='optd2' valign='center'><img src='cmpfiles/cmp/cmp_image/warning.jpg' /></td>" +
        "</tr></table></div><div class='fucktipbottom'></div>" +
        "<div class='fucktipbtns2'><div class='btngroup'><input type='button' class='tipbtn' value='确定' onclick=\"window.top.bmon_dialogCallback('yes');\"/><input type='button' class='tipbtn' value='取消' onclick=\"window.top.bmon_dialogCallback('no');\"/></div></div>" +
        "<div class='optip-body'></div><div class='optip-bottom'></div></div>";
        
        return window.top.bmon_showBmonDialog(window.top.bmon_dialogCss + bodyHtml, dialogArgument);
    };
    
    window.top.bmon_showIFrameDialog = function(src, dialogArgument)
    {
        dialogArgument = dialogArgument == null ? new BmonDialogArgument() : dialogArgument;
        var bodyHtml = "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'><html xmlns='http://www.w3.org/1999/xhtml'>" +
        "<head><style type='text/css'>*{margin:0px; padding:0px;}</style></head><body><iframe src='" +
        src +
        "' width='" +
        dialogArgument.width +
        "' height='" +
        dialogArgument.height +
        "' scrolling='no' frameborder = '0'></iframe></body></html>";
        return window.top.bmon_showBmonDialog(bodyHtml, dialogArgument);
    };
    
    window.top.bmon_showBmonFlashDialog = function(flashUrl, dialogArgument)
    {
        dialogArgument = dialogArgument == null ? new BmonDialogArgument() : dialogArgument;
        var bodyHtml = "<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" " +
        "codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0\" " +
        "width=\"" +
        dialogArgument.width +
        "\" height=\"" +
        dialogArgument.height +
        "\">" +
        "<param name=\"movie\" value=\"" +
        flashUrl +
        "\" />" +
        "<param name=\"quality\" value=\"high\" />" +
        "<param name=\"wmode\" value=\"transparent\" />" +
        "<embed src=\"" +
        flashUrl +
        "\" quality=\"high\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" " +
        "type=\"application/x-shockwave-flash\" width=\"" +
        dialogArgument.width +
        "\" height=\"" +
        dialogArgument.height +
        "\"></embed></object>";
        return window.top.bmon_showBmonDialog(bodyHtml, dialogArgument);
    };
    
    //window.top.bmon_BmonPage = BmonPage;
} //end of initFunctionsForTopWindow

