(function (window, undefined) {
    //之所以不把以下的工具函数归类，是因为希望能够通过全局快捷的访问这些工具函数

    var StringBuffer = function (initStr) {
        /// <summary>
        ///     1: StringBuffer对象，需要在page.initial()方法中初始化本对象数据
        ///     &#10;    1.1 - StringBuffer() - 初始化字符串拼接对象
        ///     &#10;    1.2 - StringBuffer(initStr) - 根据指定的字符串初始化字符串拼接对象
        /// </summary>
        /// <param name="initStr" type="String">
        ///     初始化字符串
        /// </param>
        /// <returns type="void" />
        this._strings = new Array();
        if (initStr) {
            this._strings[0] = initStr;
        }
        return this.toString();
    };
    StringBuffer.prototype.append = function (str) {
        /// <summary>
        ///     1: 在StringBuffer对象中追加字符串
        ///     &#10;    1.1 - StringBuffer.append(str) - 在StringBuffer对象中追加字符串
        /// </summary>
        /// <param name="str" type="String">
        ///     追加的字符串
        /// </param>
        /// <returns type="StringBuffer" />
        this._strings.push(str);
        return this;
    };
    StringBuffer.prototype.toString = function () {
        /// <summary>
        ///     1: 获取StringBuffer现有的完整的字符串
        ///     &#10;    1.1 - StringBuffer.toString() - 获取StringBuffer现有的完整的字符串
        /// </summary>
        /// <returns type="String" />
        return this._strings.join('');
    };
    var $ = function (id) {
        /// <summary>
        ///     1: 根据ID获取DOM元素
        ///     &#10;    1.1 - $(id) - 根据ID获取DOM元素
        /// </summary>
        /// <returns type="DOM" />
        return document.getElementById(id);
    };
    var dateFormat = function (timestamp) {
        /// <summary>
        ///     1: 将json格式的时间戳转换为(格式为：/Date(xxxxxxxxxxx)/)标准时间
        ///     &#10;    1.1 - dateFormat(timestamp) - 将json格式的时间戳转换为(格式为：/Date(xxxxxxxxxxx)/)标准时间
        /// </summary>
        /// <param name="timestamp" type="String">
        ///     Json时间戳
        /// </param>
        /// <returns type="String" />
        if (timestamp) {
            var date;
            if (typeof timestamp === 'string') {
                date = new Date(parseInt(timestamp.replace("/Date(", "").replace(")/", ""), 10));
            } else if (typeof timestamp === 'number') {
                date = new Date(parseInt(timestamp, 10));
            }
            var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
            var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
            var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
            var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
            var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
            return date.getFullYear() + "-" + month + "-" + currentDate + " " + hours + ":" + minutes + ":" + seconds;
            //            return hours + ":" + minutes + ":" + seconds;
        }
        return "未知";
    }

    //——————————————————————————————————准备工作完毕
    var hisPage = function () {
        /// <summary>
        ///     1: 页面所有的事件和函数bind方法
        ///     &#10;    1.1 - hisPage() - 页面所有的事件和函数bind方法
        /// </summary>
        /// <returns type="void" />
        return new page.init();
    };
    hisPage.info = {
        version: '1.0',
        date: '2014-02-17 16:13:10',
        author: 'linkFly'
    };
    //页面全局数据
    var page = {};
    //所有$前缀命名的表示为DOM元素
    page.data = {
        _$all: undefined, //加载全部按钮
        _$data: undefined, //数据呈现的列表DOM
        _$proBar: undefined, //数据列表下面提示父容器
        _key: undefined,  //页面DataId
        _scrollObj: undefined,   //页面滚动条对象
        _pageIndex: 2,   //当前页码
        _sumPage: 2      //总页码
    };
    //-------------------------------------填补函数
    page.init = function () {
        page.data._key = page.getUrlPara('key');
        //注意，因为scroll插件会将页面所绑定的dataList元素替换，所以先初始化scroll插件，再获取这些dom，否则针对dataList的dom无效
        page.data._$proBar = $('bottomBar');
        if ($('pageError') || page.data._key.length < 1) {
            //没有加载数据
            page.data._$proBar.parentNode.removeChild(page.data._$proBar);
            return;
        }
        //页面正确
        page.data._scrollObj = window.so.scroll(document.getElementById('dataList'), { height: 500, roll: 15 });
        page.data._$all = $('loadAllData');
        page.data._$data = $('dataList');
        page.data._$proBar = $('bottomBar');
        $('linkLoad').onclick = function () {
            page.nextPage();
        };
        $('loadAllData').onclick = function () {
            page.loadAll();
        };
    };
    page.loadAll = function () {
        /// <summary>
        ///     1: 加载全部交互信息函数
        ///     &#10;    1.1 - page.loadAll() - 加载全部交互信息函数
        /// </summary>
        /// <returns type="void" />
        page.load();
    };
    page.nextPage = function () {
        /// <summary>
        ///     1: ajax请求方法
        ///     &#10;    1.1 - page.nextPage() - 呈现所有数据方法
        ///     &#10;    1.2 - page.nextPage(index) - 呈现指定的页码的数据方法
        /// </summary>
        /// <param name="index" type="Int">
        ///     指定的页码
        /// </param>
        /// <returns type="void" />
        if (page.data._pageIndex > page.data._sumPage) {//不能再加载
            return;
        }
        page.load(page.data._pageIndex);
    };
    //ajax请求
    page.ajax = function (url, data, callback, error, fn) {
        /// <summary>
        ///     1: ajax请求方法
        ///     &#10;    1.1 - page.ajax(url,data,callback,error,fn) - ajax请求方法
        /// </summary>
        /// <param name="url" type="String">
        ///     请求url
        /// </param>
        /// <param name="data" type="Json">
        ///     注意参数必须使用原生Json格式：{ "key":value }
        /// </param>
        /// <param name="callback" type="Function">
        ///     成功的回调函数
        /// </param>
        /// <param name="error" type="Function">
        ///     (可选)异常的回调函数
        /// </param>
        /// <param name="fn" type="Function">
        ///     (可选)当执行完异步后需要执行的函数，和callback、error不同。无论返回结果如何，当异步完成都会执行该函数。注意该函数的触发在error和callback之前。
        /// </param>
        /// <returns type="void" />
        var request = undefined;
        try {
            request = new XMLHttpRequest();
        } catch (trymicrosoft) {
            try {
                request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (othermicrosoft) {
                try {
                    request = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (failed) {
                    request = false;
                }
            }
        }
        if (!request) { return };
        request.open("POST", url, true);
        //request.setRequestHeader("Content-Type", "application/json");
        request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        request.setRequestHeader("Content-Length", data.length);
        request.onreadystatechange = function () {
            if (request.readyState == 4) {
                if (fn) fn(request); //通用事件触发在明细事件之前
                if (request.status == 200) {
                    var type = request.getResponseHeader('Content-Type');
                    if (type.indexOf('xml') !== -1 && request.responseXML) {
                        callback(request.responseXML);
                    } else if (type.indexOf('application/json') !== -1) {
                        //这里的返回值是json
                        callback(page.parseJson(request.responseText));
                    } else {
                        callback(page.parseJson(request.responseText));
                    }
                } else {
                    if (error) error(page.parseJson(request.responseText));
                }

            }
        };
        var dataInfo = page.parseJson(data);
        request.send(dataInfo);
    };
    page.parseJson = function (obj) {
        /// <summary>
        ///     1: json转换方法
        ///     &#10;    1.1 - page.parseJson(obj) - 将传入的String转换成Json或将Json转换成String
        ///     &#10;    - Json转字符串后为如下格式：key=TEST&index=1
        /// </summary>
        /// <param name="obj" type="JsonOrString">
        ///     需要转换成String的Json对象（或需要转换成Json的String对象）
        /// </param>
        /// <returns type="StringOrJson" />
        if (typeof (obj) === 'string') { //字符串转json
            return (new Function('return ' + obj))(); //效率有点恶心...
        } else { //json转字符串
            var result = new StringBuffer();
            for (var i in obj) {
                result.append(i);
                result.append('=');
                result.append(encodeURIComponent(obj[i]))
                result.append('&');
            }
            return result.toString().substring(0, result.toString().length - 1);
        }
    };
    page.load = function (index) {
        /// <summary>
        ///     1: ajax请求方法
        ///     &#10;    1.1 - page.load() - 加载全部数据
        ///     &#10;    1.2 - page.load(index) - 加载指定的页码的数据
        /// </summary>
        /// <param name="index" type="Int">
        ///     指定的页码
        /// </param>
        /// <returns type="void" />
        var pram = {
            url: '/LiveTelecast/GetLiveHistory.ashx', //异步url
            callback: function (data) {//加载【成功】后执行的函数
                if (data) {
                    var elem = index ? $('proCon') : $('loadAllBar'); //统一错误信息的展示
                    switch (data.code) {
                        case 0: //正确
                            {
                                page.data._pageIndex++; //累加页码
                                page.data._sumPage = data.count; //获取总页码
                                if (page.data._pageIndex > data.count) {//最后一页，不能再翻页
                                    var node = $('linkLoad');
                                    if (node) {
                                        node.parentNode.removeChild(node);
                                        page.showMsg($('proCon'), lgyijingmeiyougengduo);
                                    }
                                }
                                if (data.list && data.list.length > 0) {
                                    var html = document.createDocumentFragment(), item;
                                    for (var i = 0, len = data.list.length; i < len, item = data.list[i]; i++) {
                                        var tempParent = document.createElement('li'); //创建li容器
                                        tempParent.className = 'dataItem';
                                        var dataName = document.createElement('div'); //创建用户名信息的节点
                                        if (item.LiveInteract_IsManager == 1) {//管理员
                                            dataName.className = 'dataName dataAdmin';
                                        }
                                        else {//用户
                                            dataName.className = 'dataName';
                                        }
                                        //这个想追加到div中需要创建文本节点
                                        var dataDate = document.createElement('span'); //创建时间信息的节点
                                        dataDate.innerHTML = dateFormat(item.LiveInteract_Date); //时间格式化
                                        dataDate.className = 'dataDate';
                                        dataName.appendChild(document.createTextNode(item.LiveInteract_UserName)); //创建文本表示用户名同时追加到用户信息节点
                                        dataName.appendChild(dataDate); //追加到用户信息节点
                                        var dataContent = document.createElement('div'); //创建内容节点
                                        dataContent.innerHTML = item.LiveInteract_Context;
                                        dataContent.className = 'dataContent';
                                        tempParent.appendChild(dataName); //用户信息节点
                                        tempParent.appendChild(dataContent); //追加内容节点
                                        html.appendChild(tempParent); //追加到文档碎片
                                    }
                                    //插入通知栏的前面
                                    if (index)
                                        page.data._$data.insertBefore(html, page.data._$proBar);
                                    else {
                                        page.data._$data.innerHTML = '';
                                        //                                        for (var nodes = page.data._$data.childNodes - 1, i = nodes.length, item; i >= 0, item = nodes[i]; i--) {
                                        //                                            page.data._$data.removeChild(item);
                                        //                                        }
                                        page.data._$data.appendChild(html);
                                        page.showMsg($('loadAllBar'), lgquanbushujujiazaiwanbi, 2);
                                    }
                                    page.data._scrollObj.change();
                                }
                            }
                            break;
                        case 1: //参数不正确
                            page.showMsg(elem, lgcaozuoyichangchongxincaoshi);
                            break;
                        case 2: //没有检索到相关数据
                            page.showMsg(elem, lgmeiyoujiansuodaoxiangguan);
                            break;
                        default: //未知
                            page.showMsg(elem, lgcaozuoyichangweizhiyichang);
                            break;
                    }
                } else {//没有数据
                    page.showMsg(elem, lgcaozuoyichangweizhiyichang);
                }
            },
            data: { 'key': page.data._key }, //ajax数据
            error: function () {//加载【异常】后函数
                page.showMsg($('proCon'), lgtagyichang1);
            },
            loaded: function () {//加载【完成】后执行的函数
                page.showMsg($('proCon'));
            }
        };
        if (index) {
            //验证当前页码的合法性
            pram.data['index'] = index;
            page.showMsg($('proCon'), lgzhengzaijiazai, 1);
        } else {
            page.showMsg($('loadAllBar'), lgzhengzaijiazai, 1);
        }
        setTimeout(function () {
            page.ajax(pram.url, pram.data, pram.callback, pram.error, pram.loaded);
        }, 500);

    };
    page.showMsg = function (elem, msg, type, fn) {
        /// <summary>
        ///     1: 显示消息函数
        ///     &#10;    1.1 - page.showMsg(elem) - 隐藏该消息函数
        ///     &#10;    1.1 - page.showMsg(elem,msg,type,fn) - 显示消息函数
        /// </summary>
        /// <param name="elem" type="Element">
        ///     要操作的节点对象
        /// </param>
        /// <param name="msg" type="String">
        ///     要显示的消息内容
        /// </param>
        /// <param name="type" type="String">
        ///     消息类型：{ 0(默认) : 警告 , 1 : 正在加载  2:加载成功 }
        /// </param>
        /// <param name="fn" type="Function">
        ///     显示消息之后需要执行的函数
        /// </param>
        /// <returns type="void" />
        if (!elem) return;
        if (arguments.length === 1) {
            elem.style.visibility = 'hidden';
            return;
        }
        var nodes = page.childs(elem);
        switch (type) {
            case 1:
                nodes[0].setAttribute('src', '/LiveTelecast/Images/loading.gif');
                elem.className = 'prompt';
                break;
            case 2:
                nodes[0].setAttribute('src', '/LiveTelecast/Images/proOk.png');
                elem.className = 'prompt proOk';
                break;
            default:
                nodes[0].setAttribute('src', '/LiveTelecast/Images/proWarning.png');
                elem.className = 'prompt proWarning';
                break;
        }
        nodes[1].innerHTML = msg;
        elem.style.visibility = 'visible';
        if (fn) fn();
    };
    page.getUrlPara = function (fieldName) {
        /// <summary>
        ///     1: 获取地址栏参数方法
        ///     &#10;    1.1 - getUrlParameter(fieldName) - 在当前Url中查询指定的参数，返回查询得到的值
        /// </summary>
        /// <param name="fieldName" type="String">
        ///     要查询的字符串
        /// </param>
        /// <returns type="String" />
        var urlString = document.location.search;
        if (urlString != null) {
            var typeQu = fieldName + "=";
            var urlEnd = urlString.indexOf(typeQu);
            if (urlEnd != -1) {
                var paramsUrl = urlString.substring(urlEnd + typeQu.length);
                var isEnd = paramsUrl.indexOf('&');
                if (isEnd != -1) {
                    return paramsUrl.substring(0, isEnd);
                }
                else {
                    return paramsUrl;
                }
            }
            else {
                return "";
            }
        }
        else {
            return "";
        }
    }
    page.childs = function (elem) {
        /// <summary>
        ///     1: 获取DOM所有的【子元素】
        ///     &#10;    1.1 - page.childs(elem) - 获取DOM下所有的子元素（nodeType==1），不含文本或者注释节点的信息
        /// </summary>
        /// <param name="elem" type="Element">
        ///     要遍历的DOM
        /// </param>
        /// <returns type="String" />
        var result = [];
        for (var node = elem.firstChild; node; node = node.nextSibling) {
            if (node.nodeType === 1) {
                result.push(node);
            }
        }
        return result;
    };
    page.init.prototype.info = hisPage.info;
    window.hisPage = hisPage;
})(window);

