﻿if(!Object.Try) Object.Try = function(){var returnValue;for (var i = 0; i < arguments.length; i++) {var lambda = arguments[i];try {returnValue = lambda();break;} catch (e) {}} return returnValue;};
if(!Object.Throw) Object.Throw = function(e,x){throw e; return (x || true);};
if(!Object.toArray) Object.toArray = function(iterable){if (!iterable){return [];}if (iterable.toArray){return iterable.toArray();}else{var results = [];for (var i = 0; i < iterable.length; i++){results.push(iterable[i]);}return results;}};
if (!Function.prototype.apply) Function.prototype.apply = function(object, parameters) {var parameterStrings = []; if (!object) object = window; if (!parameters) parameters = []; for (var i = 0; i < parameters.length; i++){ parameterStrings[i] = 'parameters[' + i + ']';} object.__apply__ = this; var result = eval('object.__apply__(' + parameterStrings.join(', ') + ')'); object.__apply__ = null; return result;};
if(!Function.prototype.bind) Function.prototype.bind = function(){var __method = this, args = Object.toArray(arguments), object = args.shift();return function() {return __method.apply(object, args.concat(Object.toArray(arguments)));}};
if(!Array.prototype.each) Array.prototype.each = function(iterator){for (var i = 0; i < this.length; i++){iterator(this[i]);}};
if(!Array.prototype.map) Array.prototype.map = function(iterator, context) {iterator = iterator ? iterator.bind(context) : function(){};var results = [];this.each(function(value, index) {results.push(iterator(value, index));});return results;};
if(!String.prototype.extractScripts) String.prototype.extractScripts = function(){var matchAll = new RegExp(Request.Regex.Script, 'img');var matchOne = new RegExp(Request.Regex.Script, 'im');return (this.match(matchAll) || []).map(function(scriptTag){return (scriptTag.match(matchOne) || ['', ''])[1];});};
if(!String.prototype.evalScripts) String.prototype.evalScripts = function(){return this.extractScripts().map(function(script) { return eval(script); });};
if(!RegExp.prototype.match) RegExp.prototype.match = RegExp.prototype.test;
if(!document.XML){
    document.XML = {
        GetNodeValue:function(node){var retValue='';if(navigator.userAgent.indexOf(' MSIE ')>-1){if(node.hasChildNodes())for(var i=0;i<node.childNodes.length;i++)retValue+=document.XML.GetNodeValue(node.childNodes[i]);else retValue+=node.text}else{if(node.hasChildNodes()){for(var i=0;i<node.childNodes.length;i++)retValue+=document.XML.GetNodeValue(node.childNodes[i])}else{try{retValue+=node.textContent}catch(e){try{retValue+=node.nodeValue}catch(e){}}}}return(retValue)}
    };
}
var Request;
if(!Request) Request = {};
if(!Request.Enums) Request.Enums = {};
Request.Enums.Method = {Get:1, Post:2};
Request.Enums.Response = {Text:1, Xml:2, Body:3};
Request.Enums.EnCoding = {UTF8:"utf-8", UTF7:"utf-7", GB2312:"gb2312", BIG5:"big5"};
Request.Enums.EnCoding.Codes= {UTF8:65001, UTF7:65000, GB2312:936, BIG5:950};
if(!Request.Regex) Request.Regex = {};
Request.Regex.Script = '<script[^>]*>([\\S\\s]*?)<\/script>';
Request.XMLHttp = function()
{
    var xmlHttp = null;
    if(window.ActiveXObject)
    {
        xmlHttp = Object.Try(
            function() {return new ActiveXObject("MSXML2.XMLHTTP.6.0");},
            function() {return new ActiveXObject("MSXML2.XMLHTTP.5.0");},
            function() {return new ActiveXObject("MSXML2.XMLHTTP.4.0");},
            function() {return new ActiveXObject("MSXML2.XMLHTTP.3.0");},
            function() {return new ActiveXObject("MSXML2.XMLHTTP");},
            function() {return new ActiveXObject("MICROSOFT.XMLHTTP.1.0");},
            function() {return new ActiveXObject("MICROSOFT.XMLHTTP.1");},
            function() {return new ActiveXObject("MICROSOFT.XMLHTTP");}
        );
    }
    else if(window.XMLHttpRequest) xmlHttp = new XMLHttpRequest();
    if (!xmlHttp) Object.Throw("不能创建XMLHTTP对象实例,请检查你的浏览器设置后重试！");
    else if (xmlHttp.overrideMimeType) xmlHttp.overrideMimeType("text/xml");
    return(xmlHttp);		
};
// var Req = new Request.GetResponse();
Request.GetResponse = function(){this.XmlHttp = Request.XMLHttp();if (window.ActiveXObject) this.XmlHttp.onreadystatechange = this.Completed.bind(this);else if (window.XMLHttpRequest) this.XmlHttp.onload = this.Completed.bind(this);};
Request.GetResponse.prototype.EnCoding = Request.Enums.EnCoding.UTF8;
Request.GetResponse.prototype.Referer = ("http://" + document.location.hostname);
Request.GetResponse.prototype.Cookies = "";
Request.GetResponse.prototype.ContentType = Request.Enums.Response.Text;
Request.GetResponse.prototype.CallBack = null;
Request.GetResponse.prototype.Params = {};
Request.GetResponse.prototype.SetParams = function(key, value){if (key != null) this.Params[key] = value;};
Request.GetResponse.prototype.GetParams = function(key){if (key != null) return this.Params[key];return null;};
Request.GetResponse.prototype.GetAllParams = function(){var key;var result = [];for(key in this.Params) if(Object.isArray(this.Params[key])) result.push((key + "=" + this.Params[key].join(","))); else result.push((key + "=" + this.Params[key]));return ((result.length > 0) ? result.join("&") : "");};
Request.GetResponse.prototype.Get = function(url)
{
    var _url = ((url.indexOf('?') == -1) ? (url + "?") : url);
    _url += this.GetAllParams();
    this.XmlHttp.open("GET", _url, true);
    this.XmlHttp.setRequestHeader("Method", "GET " + _url + " HTTP/1.1");
	this.XmlHttp.setRequestHeader("Charset", this.EnCoding);
	this.XmlHttp.setRequestHeader("Referer", this.Referer);
	//this.XmlHttp.setRequestHeader("Cookie", this.Cookies);
    this.XmlHttp.send(null);
};
Request.GetResponse.prototype.Post = function(url)
{
    this.XmlHttp.open("POST", url, true);
	this.XmlHttp.setRequestHeader("Method", "POST " + url + " HTTP/1.1");
	this.XmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	this.XmlHttp.setRequestHeader("Charset", this.EnCoding);
	this.XmlHttp.setRequestHeader("Referer", this.Referer);
	//this.XmlHttp.setRequestHeader("Cookie", this.Cookies);
	this.XmlHttp.send(this.GetAllParams());
};
Request.GetResponse.prototype.Completed = function()
{
    if(this.XmlHttp.readyState == 4)
    {
        var result = null, RequestStatus = this.XmlHttp.status;
	    if((RequestStatus == 200) && (this.XmlHttp.statusText == "OK"))
	    {
    	    if(this.ContentType == Request.Enums.Response.Text)
    	        result = this.XmlHttp.responseText;
	        else if(this.ContentType == Request.Enums.Response.Xml)
	            result = this.XmlHttp.responseXML;
            else if(this.ContentType == Request.Enums.Response.Body)
             result = this.XmlHttp.responseBody;
	    }
	    if(this.CallBack != null)
        {
	        if((typeof(this.CallBack) == 'function') && (this.CallBack.constructor == Function))
	            this.CallBack(result, RequestStatus);
            else if((typeof(this.CallBack) == 'string') && (this.CallBack.constructor == String))
            {
                if(this.CallBack.indexOf("{0}") != -1)
	                this.CallBack = this.CallBack.replace("{0}","result");
                if(this.CallBack.indexOf("{1}") != -1)
	                this.CallBack = this.CallBack.replace("{1}","RequestStatus");
                eval(this.CallBack);
            }
        }
    }
};
Request.GetResponse.prototype.Dispose = function(){this.XmlHttp = null;this.Params = null;this.Cookies = null;this.CallBack = null;};
//var Update = new Request.Update({Url:"Text.txt", Element:"zhang" });
//Update.Execute();
Request.Update = function(options)
{
    this.Response = null;
    this.Options = {
        Url         : "",
        Method      : Request.Enums.Method.Get,
        EnCoding    : Request.Enums.EnCoding.UTF8,
        ContentType : Request.Enums.Response.Text,
        XMLItem     : "item",
        Params      : {},
        Element     : null,
        Begin       : null,
        Finish      : null,
        OnError     : null
    };
    if((options != null) && (typeof(options) == 'object')){for(var key in options) this.Options[key] = options[key];}
    if((typeof(this.Options.Element) == 'string') && (this.Options.Element.constructor == String))
        this.Options.Element = document.getElementById(this.Options.Element);
};
Request.Update.prototype.Execute = function()
{
    if((this.Options.Url == null) || (this.Options.Url == "") || (this.Options.Element == null) || (this.Options.Element.nodeType != 1)) return;
    if((typeof(this.Options.Begin) == 'function') && (this.Options.Begin.constructor == Function)) this.Options.Begin();
    this.Response = new Request.GetResponse();
    this.Response.EnCoding = this.Options.EnCoding;
    this.Response.ContentType = this.Options.ContentType;
    this.Response.Params = this.Options.Params;
    this.Response.CallBack = this.Completed.bind(this);
    if(this.Options.Method == Request.Enums.Method.Get) this.Response.Get(this.Options.Url);
    if(this.Options.Method == Request.Enums.Method.Post) this.Response.Post(this.Options.Url);
};
Request.Update.prototype.Completed = function(content, RequestStatus)
{
    if(RequestStatus == 200)
    {
        if(this.Options.ContentType == Request.Enums.Response.Text)
        {
            if(content != null)
            {
                var contentText = content.replace(new RegExp(Request.Regex.Script, 'img'), '');
                if(contentText != '')
                    this.Options.Element.innerHTML = contentText;
                content.evalScripts();
                
            }
        }
        else if(this.Options.ContentType == Request.Enums.Response.Xml)
        {
            var nodes = Object.toArray(content.getElementsByTagName(this.Options.XMLItem));
            if(nodes.length > 0)
            {
                nodes.each(
                    function(node){
                        if(node == null) return;
                        var element = $(node.getAttribute("element"));
                        if(element != null)
                        {
                            var contents = document.XML.GetNodeValue(node);
                            var contentText = contents.replace(new RegExp(Request.Regex.Script, 'img'), '').replace(/^\s+/, '').replace(/\s+$/, '');
                            element.innerHTML = contentText;
                            contents.evalScripts();
                        }
                    }
                );
            }
        }
        if((typeof(this.Options.Finish) == 'function') && (this.Options.Finish.constructor == Function)) this.Options.Finish();
    }
    else
    {
        if((typeof(this.Options.OnError) == 'function') && (this.Options.OnError.constructor == Function)) this.Options.OnError(RequestStatus); 
        else window.status = "Happened error for request update: " + RequestStatus;
        if((typeof(this.Options.Finish) == 'function') && (this.Options.Finish.constructor == Function)) this.Options.Finish();
    }
    this.Response.Dispose();
    this.Response = null;
};
