var port = window.location.port;
var AppPath = window.location.protocol + "//" + window.location.host;



String.Format = function() {
	var args = arguments, argsCount = args.length;
	if( argsCount == 0 ) {
        return "";
    }
    if( argsCount == 1 ) {
        return args[0];
    }
    var reg = /{(\d+)?}/g, arg, result;    
    if( args[1] instanceof Array ) {
        arg = args[1];
        result = args[0].replace( reg, function( $0, $1 ) {
			return arg[parseInt($1)];
		} );
    } else {
        arg = args;
        result = args[0].replace( reg, function( $0, $1 ) {
			return arg[parseInt($1)+1];
		} );
    }
    return result;
};
String.format = String.Format;
/***
 * StringBuilder
 ***/
function StringBuilder() {
    this.strings = [];
}

StringBuilder.prototype.append = function ( text ) {
    this.strings.push( text );
};

StringBuilder.prototype.toString = function () {
    if ( arguments.length == 0 ) {
        return this.strings.join("");
	}
    else { 
		return this.strings.join( arguments[0] );
	}
};

StringBuilder.prototype.clear = function () {
    this.strings.clear();
};

StringBuilder.prototype.backspace = function () {
    this.strings.pop();
};




AJAXFrame = {};

AJAXFrame.Request = Class.create();
Object.extend( Object.extend( AJAXFrame.Request.prototype, Ajax.Request.prototype ), {

  setOptions: function(options) {
    this.options = {
      method:       'post',
      asynchronous: true,
      contentType:  'application/x-www-form-urlencoded',
      encoding:     'UTF-8',
      parameters:   '',
      timeout:      6000
    }
    Object.extend(this.options, options || {});
	if ( typeof( this.options.timeout ) == "undefined" ) {
		this.options.timeout = 6000;
	}
    this.options.method = this.options.method.toLowerCase();
    if (typeof this.options.parameters == 'string')
      this.options.parameters = this.options.parameters.toQueryParams();
  },
  
	initialize: function(url, options, jsonResult ) {
		this.jsonResult = jsonResult || false;
		this.transport = Ajax.getTransport();
		this.setOptions(options);
		this.request(url);
	},
	request: function( url ) {
		this.url = url;
		this.method = this.options.method;
		var params = this.options.parameters;
		if (!['get', 'post'].include(this.method)) {
			params['_method'] = this.method;
			this.method = 'post';
		}
		params = Hash.toQueryString(params);
		if (params && /Konqueror|Safari|KHTML/.test(navigator.userAgent)) params += '&_=';
		if (this.method == 'get' && params)
			this.url += (this.url.indexOf('?') > -1 ? '&' : '?') + params;
		if ( typeof( this.options['onComplete'] ) == "undefined" ) {
			this.options.asynchronous = false;
		}
//		//只用异步方法
//		this.options.asynchronous = true;
		try {
			Ajax.Responders.dispatch('onCreate', this, this.transport);
			this.transport.open(this.method.toUpperCase(), this.url, this.options.asynchronous);
			this.setRequestHeaders();
			if (this.options.asynchronous) {
				setTimeout(function() { this.respondToReadyState(1) }.bind(this), 10);
			}
			this.transport.onreadystatechange = this.onStateChange.bind(this);
			this.setRequestHeaders();
			var body = this.method == 'post' ? (this.options.postBody || params) : null;
			this.transport.send(body);
			if (!this.options.asynchronous && this.transport.overrideMimeType) {
				this.onStateChange();
			}
			this.result = null;
			if ( ! this.options.asynchronous ) {
				if ( this.jsonResult ) {
					this.result = eval("(" + this.transport.responseText + ")");
				} else {
					this.result = this.transport.responseText;
				}
				if ( this.transport.overrideMimeType ) {
					this.respondToReadyState(4);
				}
				delete this.transport;
			}
		}
		catch (e) {
 			//alert( "request:网站连接意外中断，请刷新页面后重试！" );
			this.dispatchException(e);
		}
	},
	
	respondToReadyState: function(readyState) {
		var state = Ajax.Request.Events[readyState];
		var transport = this.transport, json = this.evalJSON();
		var result = null;
		if ( state == 'Complete' && this.options.asynchronous ) {
			try {
				this._complete = true;
				(this.options['on' + this.transport.status] || this.options['on' + (this.success() ? 'Success' : 'Failure')] || Prototype.emptyFunction)(transport, json);
			} catch (e) {
				this.dispatchException(e);
			}
			if ((this.getHeader('Content-type') || 'text/javascript').strip().match(/^(text|application)\/(x-)?(java|ecma)script(;.*)?$/i)) {
				result = this.evalResponse();
			}
		}
		try {
			if ( this.options.asynchronous ) {
				if ( result ) {
					(this.options['on' + state] || Prototype.emptyFunction)(result);
				} else {
					(this.options['on' + state] || Prototype.emptyFunction)(transport, json);
				}
			}
			Ajax.Responders.dispatch('on' + state, this, transport, json);
		} catch (e) {
   			//alert( "respondToReadyState:网站连接意外中断，请刷新页面后重试！" );
			this.dispatchException(e);
		}
		if (state == 'Complete') {
			this.transport.onreadystatechange = Prototype.emptyFunction;
		}
	},

	evalResponse: function() {
		try {
			if ( this.transport.responseText && this.transport.responseText.length > 0 ) {
				return eval("("+this.transport.responseText+")");
			}
			return [];
		} catch (e) {
			this.dispatchException(e);
		}
	}
});




AJAXFrame.Ajax = {
	MAX_REREQUEST_COUNT: 2,
	_requestKeys: [],
	_requestErrorCounts: [],
	/*Ajax请求
	 *@serverType:服务器端的类型
	 *@serverMethod:服务器端的方法
	 *@args:Json形式的参数
	 *@clientCallBack:客户端回调的方法
	 *@url:请求的URL
	 *@httpMethod:请求的方法：get/post
	 */
	callBack: function( serverType, serverMethod, args, clientCallBack, url, httpMethod, timeout ) {
		var encodedDataBuilder = new StringBuilder();
		encodedDataBuilder.append( "Ajax_CallBackType=" );
		encodedDataBuilder.append( serverType );
		encodedDataBuilder.append( "&Ajax_CallBackMethod=" );
		encodedDataBuilder.append( serverMethod );
		if ( args ) {
			for ( var i = 0, count = args.length; i < count; i++ ) {
				encodedDataBuilder.append( "&Ajax_CallBackArgument" );
				encodedDataBuilder.append( i );
				encodedDataBuilder.append( "=" );
				encodedDataBuilder.append( encodeURIComponent( args[i] ) );
			}
		}
		httpMethod = httpMethod || "post";
		if ( url.indexOf( "http://" ) < 0 ) {
			url = AppPath + url;
		}
		var ajaxRequest = null;
		try {
			ajaxRequest = new AJAXFrame.Request( url, { "method": httpMethod, "timeout": timeout, "parameters":encodedDataBuilder.toString(), "onComplete": clientCallBack }, true );
		} catch ( e ) {
			if ( e.message.indexOf( "Component returned failure code: 0x80040111" ) != 0 ) {
				ajaxRequest = new AJAXFrame.Request( url, { "method": httpMethod, "timeout": timeout, "parameters":encodedDataBuilder.toString(), "onComplete": clientCallBack }, true );
			}
		}
		return ajaxRequest.result;
	}
};
