﻿/*
	@author MiRacLe <miracle@cccmos.com>
	@sinse 04.10.2005
	@version 0.1
	@sinse 16.01,2006
	@version 0.1.1
	@changelog - fix bug with sharp-symbol (anchor) in url;
	@version 0.1.3
     @since 03.03.2006
     @changelog - fix readyState double exec;
     @changelog - added progress meter in window.status
*/
function ajaxRequest() {}
(function()
{
	var  timeoutDefault = 10 * 1000;
	ajaxRequest.prototype = {
		version: '0.1.3',
		info:	null,
		cached: true,
		isReady: true,
		isTimeOut: false,
		timeoutInterval: null,
    done: false,
    windowStatus: '',
		helpURL: '/rus/index/services/browsers',
		load: function (info)	{
			try { 
					if (!this.isReady) 
						throw new Error('Create new instanse for use ajaxRequest');
					this.isReady = false;
					if ('object' != typeof(info))
						throw new Error('Wrong parameters count for method');
					if (!(info.transport = this.getTransport()))
						throw new Error("Can't create connection.");
					var self = this;
					info.transport.onreadystatechange = function() { self.onReadyStateChange();}
					info.parent = this;
					if ('boolean' != typeof(info.async)) info.async = true;
					if ('string' != typeof(info.url) || !info.url.length) 
						throw new Error('URL not specified');
					if ('string' != typeof(info.method) || !info.method.length) info.method = 'post';
					info.method = info.method.toLowerCase();
					var queryString = ('object' == typeof(info.data)) ? this.serialize(info.data) : '';
					if (info.url.indexOf('?#') > 0) { info.url = info.url.replace(/#/gi,'');} // fix: remove anchor from url
					if ('post' != info.method) {
							if(!this.cached) info.url += (info.url.indexOf("?") < 0 ? "?" : "&") + "rn=" + parseInt(Math.random() * 1000000)
							if(queryString.length > 0) info.url += (info.url.indexOf("?") < 0 ? "?" : "&")	+ queryString;
					}
					info.timeout = ('number' == typeof(info.timeout)) ? Math.max(0, info.timeout) : timeoutDefault;
					this.isTimedOut = false;
					if(info.timeout > 0) this.timeoutInterval = setTimeout(function() { self.onTimeout(); }, info.timeout);
					info.result = {};
					this.info = info;
					info.transport.open(info.method, info.url, info.async);			
					try {
						info.transport.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
						info.transport.setRequestHeader("User-Agent", "ajaxRequest v" + this.version + " by MiRacLe (CCCMOS Group) 2005 - 2006");
						if('post' == info.method) {
//							info.transport.setRequestHeader("Content-length", queryString.length);
//							info.transport.setRequestHeader("Connection","close");
							}
					} catch(e) {}
					if ('function' == typeof(disableElements)) disableElements(1);
					info.transport.send('post' == info.method ? queryString : null);					
					if(!info.async)
					{
						this.info.result = this.getResult();
						return this.info.result;
					}
					
				} catch(e) {
					throw new Error("AjaxRequest error\n\n" + e.message);
				}		
		},
		onReadyStateChange: function() {
      switch (this.info.transport.readyState) {
        case 1 :
          this.windowStatus = window.defaultStatus;
          window.defaultStatus = 'Loading.';
          break;
        default :
          window.defaultStatus += '...';
      }
      if (this.info.transport.readyState == 4 && !this.done) {
				this.isReady = true;
				if(!this.isTimedOut) {
					if(this.timeoutInterval) {
						clearInterval(this.timeoutInterval);
						this.timeoutInterval = null;
					}
					switch(this.info.transport.status) {
						case 200 : 
							this.info.result = this.getResult();
							if (this.info.result == 'error###Access Denied') { 
								this.onAccessDenied(); // Patched for pages with lost session
							} else {	
                if(this.info.onSuccess) { 
                  this.info.onSuccess(this.info.result);
                  this.done = true;
                  window.defaultStatus = this.windowStatus;
                }  
              }  
							break;
		
						case 12029 : // timeout
							this.onTimeout();
							break;
						default :
							if(this.info.onError) this.info.onError(this.info);
					}				
				}
			}
		},
		onTimeout : function()		{
			if(this.timeoutInterval) {
				clearInterval(this.timeoutInterval);
				this.timeoutInterval = null;
			}
			this.isTimedOut = true;
			this.isReady = true;
			if ('function' == typeof('disableElements')) {
				disableElements(0);
			}
      window.defaultStatus = 'Connection timeout...';      
			try {
				this.info.transport.abort();
			} catch(e) {}
			if(this.info.onTimeout) this.info.onTimeout(this.info);
		},		
		getTransport : function() {
			var transport = null;
			if (window.XMLHttpRequest) {
				try {
					transport = new XMLHttpRequest;
				} catch(e) {}
			}
			if(!transport) try {
				transport = new ActiveXObject("Msxml2.XMLHTTP");
			} catch(e) {}
			if(!transport) try	{
				transport = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {}
			if(!transport) this.notSupported();
			return transport;
		},
		getResult : function() {
			return (this.info.getXML) ? this.info.transport.responseXML : this.info.transport.responseText;
		},
		serialize : function(data) {
			data['version'] = this.version;
			var result = '';
			for (str in data) {
				result += '&' + str + '=' + this.encode(data[str]);
			}
			return result;
		},
		encode: function(str) {
			return ('function' == typeof(encodeURIComponent)) ? encodeURIComponent(str) : escape(str);
		},
		notSupported: function() {
			top.location.href = this.helpURL;
		},
		onAccessDenied: function() {
			window.document.location.reload();
		}
	}
}) ();

