request = {};

request.createRequestObject = function () {
	if ( window.XMLHttpRequest ) {
		try {
			return new XMLHttpRequest ();
		} catch ( e ) {}
	} else if ( window.ActiveXObject ) {
		try {
			return new ActiveXObject ( 'Msxml2.XMLHTTP' );
		} catch ( e ) {
			try {
				return new ActiveXObject ( 'Microsoft.XMLHTTP' );
			} catch ( e ) {}
		}
	}
	return null;
}

request.send = function ( obj, callback, responseType ) {
	xhr = request.createRequestObject ();

	obj.method = obj.method || 'GET';
	obj.async = obj.async || true;

	if ( obj.async ) {
		xhr.onreadystatechange = function () {
			try {
				if ( xhr.readyState == 4 ) {
					if ( xhr.status == 200 || xhr.status == 0 ) {
						var r;
						switch ( responseType ) {
							case 'text'	: r = xhr.responseText; break;
							case 'xml'	: r = xhr.responseXML; break;
							case 'json'	: r = eval ( '(' + xhr.responseText + ')' ); break;
						}
						callback ( r );
					} else {
						if ( xhr.statuText ) {
							alert ( 'Не удалось получить данные:\n' + xhr.statuText );
						} else {
							//alert ( 'Статус:\n' + xhr.status );
						}
					}
				}
			} catch ( e ) {
				alert ( 'Caught Exception: ' + e.description );
				// В связи с багом XMLHttpRequest в Firefox приходится отлавливать ошибку
				// Bugzilla Bug 238559 XMLHttpRequest needs a way to report networking errors
				// https://bugzilla.mozilla.org/show_bug.cgi?id=238559
			}
		}
	}

	xhr.open ( obj.method, obj.url, obj.async );

	if ( obj.method == 'POST' ) {
		xhr.setRequestHeader ( 'Content-Type', 'application/x-www-form-urlencoded' );
		//xhr.setRequestHeader ( 'Content-Length', ... );
		obj.params = obj.params || {};
		var pstr = '';
		var amp = '';
		for ( var k in obj.params ) {
			pstr = pstr + amp + escape ( k ) + '=' + escape ( obj.params[k] );
			amp = '&';
		}
		xhr.send ( pstr );
	} else {
		xhr.setRequestHeader ( "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" );
		xhr.send ( null );
	}
}

request.getText = function ( obj, callback ) { return request.send ( obj, callback, 'text' ) }
request.getXML  = function ( obj, callback ) { return request.send ( obj, callback, 'xml'  ) }
request.getJson = function ( obj, callback ) { return request.send ( obj, callback, 'json' ) }


function redirect ( url, params, method ) {
	method = method || "post";

	var form = document.createElement ( "form" );
	form.setAttribute ( "action", url );
	form.setAttribute ( "method", method );

	for ( var key in params ) {
		var hiddenField = document.createElement ( "input" );
		hiddenField.setAttribute ( "type", "hidden" );
		hiddenField.setAttribute ( "name", key );
		hiddenField.setAttribute ( "value", params[key] );
		form.appendChild ( hiddenField );
	}

	document.body.appendChild ( form );
	form.submit ();
}
