/**
 Object: load
 Version: 1.0
 Autor: Александр Хрищанович (dirmax@cosmostv.by)
 Description: Ajax библиотека
 Require: 
 	- function.js v.1.0
*/
var load = {

	/* массив включённых файлов */
	includedFiles : new Array( ),

	/* объект XMLHttp */
	request : null,

	/* использовать кэширование */
	useCache : true,

	/* использовать синхронные запросы */
	useSynchron : false,

	/* Функция, которая выполниться до начала запроса на сервер */
	callBackFunctionStart : null,

	/* Функция, которая выполниться после загрузки данных с сервера */
	callBackFunctionEnd : null,

	/* Url - путь к файлу-обработчику */
	urlFile : null,

	/* Использовать POST в запросе на сервер */
	typeQuery : 'GET',

	/* HTTP - заголовки к запросу */
	requestHeader : new Array( ),

	/* Массив данных для запроса */
	queryArray : new Array( ),
	
	/* Получаем textPlain */
	isTextPlain : true,

	/* Получение XMLHTTP объекта для ajax запроса на сервер */
	GetXMLHttpObject : function ( ) {

		var result = false;
		var i;
		var XMLHttpObjects = [
			function ( ) { return new XMLHttpRequest( ) },
			function ( ) { return new ActiveXObject( 'Msxml2.XMLHTTP' ) },
			function ( ) { return new ActiveXObject( 'Microsoft.XMLHTTP' ) }
		];

		for( i=0; i<XMLHttpObjects.length; i++ ) {

			try {
				result = XMLHttpObjects[i]( );
				break;
			}
			catch ( e ) { }

		}

		return result;

	},

	/* Включение запрошенного файла с сервера */
	Include : function ( urlFile, arrayQuery ) {

		this.queryArray = arrayQuery;
		
		this.urlFile = urlFile;

		var result = false;

		/* выполнение callback - функции до запроса на сервер */
		if ( this.callBackFunctionStart ) {
			this.callBackFunctionStart( );
		}

		/* проверка на использование кэширования */
		if ( this.useCache && this.includedFiles[this.urlFile] ) {
			result = this.includedFiles[this.urlFile];
		}
		else {

			result = this.Load( );

			if ( this.useSynchron ) {
				this.includedFiles[this.urlFile] = result;	
			}

		}

		/* выполнение callback - функции после запроса на сервер */
		if ( this.callBackFunctionEnd && result ) {

			var text = ( result.textResponse ) ? result.textResponse : result;
			var status = ( result.status ) ? result.status : 200;

			this.callBackFunctionEnd( text, status );
		}

		return result;

	},

	/* Запрос на сревер */
	Load : function ( ) {

		this.request = this.GetXMLHttpObject( );

		if ( !this.useSynchron ) {
			this.request.onreadystatechange = this.OnReadyStateChange.bindAjax( this );
		}	
		this.request.open( this.typeQuery, this.urlFile + ( this.typeQuery == 'GET' ? ('?' + this.MakeRequest( ))  : '' ), !this.useSynchron );

		if ( this.typeQuery == 'POST' ) {

			this.request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

		}
		
		if ( this.requestHeader.length ) {
			
			for ( var sProperty in this.requestHeader ) {
				
					this.request.setRequestHeader( sProperty, this.requestHeader[sProperty] );
				
			}

		}

		this.request.send( ( this.typeQuery == 'POST' ? this.MakeRequest( )  : null) );

		if ( this.useSynchron ) {

			var textResponse = false;

			if ( this.request.status == 200 ) {
				textResponse = (this.isTextPlain) ? this.request.responseText : this.request.responseXML;
			}

			return {
				textResponse : textResponse,
				status : this.request.status
			};

		}

		return false;

	},

	/* Подготовка строки запроса на сервер */
	MakeRequest : function ( ) {

		var string = '';

		for ( var sProperty in this.queryArray ) {
			string += sProperty + '=' + encodeURI( this.queryArray[sProperty] ) + '&';
		}

		return string.substr( 0, string.length - 1 );

	},

	/* Системная функция для AJAX */
	OnReadyStateChange : function ( ) {

		if ( this.request.readyState == 4 ) {

			var textResponse = false;

			if ( this.request.status == 200 ) {
				textResponse = (this.isTextPlain) ? this.request.responseText : this.request.responseXML;
			}

			this.includedFiles[this.urlFile] = textResponse;

			if ( this.callBackFunctionEnd ) {
				this.callBackFunctionEnd( this.includedFiles[this.urlFile], this.request.status );
			}

		}

	}

};

/**
 Class: Include
 Version: 1.0
 Autor: Александр Хрищанович (dirmax@cosmostv.by)
 Description: динамическое включение js файлов
 Для работы необходимы файлы : 
 	- load.prototype.js			v.1.0
*/
Include = function ( ) {

	this.useSynchron = true;

	this.useCache = true;
	
	this.callBackFunctionStart = null;

	this.requestHeader = null;
	
	this.typeQuery = 'GET';
	
	this.pathToLibruary = null,

	/* Включение js файла */
	this.js = function ( urlFile ) {

		var context = this;

		this.callBackFunctionEnd = function ( jsCode, status ) {

			if ( status == 200 ) {

				if ( IsIE( ) ) {
					window.execScript( jsCode );
				}
				else {

					var script_tag = document.createElement('script');
					script_tag.text = jsCode;
					if ( script_tag.getAttribute('text') ) {
						script_tag.removeAttribute('text');
						script_tag.innerText = jsCode;
					}
					script_tag.type = 'text/javascript';
					document.getElementsByTagName('head')[0].appendChild(script_tag);

				}
	
			}
			else {
				alert( 'File "' + context.pathToLibruary + urlFile + '" no found');
			}

		};

		if ( !this.pathToLibruary ) {

			this.pathToLibruary = this.GetPathLibryary( );

		}

		this.Include( this.pathToLibruary + urlFile );

	};

	this.GetPathLibryary = function ( ) {

		var locationFirstScript = document.getElementsByTagName('script')[0].src;	
		
		var index = locationFirstScript.lastIndexOf( '/' ) + 1;
		var dir = locationFirstScript.substr( 0, index );
		return dir;

	}

};

/* прототипом класса Include будет объект load */
Include.prototype = load;

/* публичный объект для включения js файлов */
var include = new Include( );

/* Производный класс от абстрактного объекта load */
Ajax = function ( ) { }
Ajax.prototype = load;
