var AJAX_TAG = 'div';
var AJAX_HTML = 'AjaxHTML';
var AJAX_RENDER_BLOCKS = 'AjaxRenderBlocks';
var AJAX_NAME_LINK = 'AjaxCall';
var AJAX_POST_FUNCTION = 'AjaxCall';
var AJAX_POST_BLOCKS = 'AjaxCallBlocks';
var AJAX_POST_URL = 'AjaxCallURL';
var FORCE_UPDATE_BLOCKS = 'AjaxForceUpdateBlocks';

var AjaxCallURL = window.location.href;

function showAjaxError(str) {
	if(AJAX_DEBUG)
		alert(str);
}

function AjaxRunJS(Element)
{
	var arr_scripts = Element.getElementsByTagName("script");
	for(var i in arr_scripts) {
		var script = arr_scripts[i];
		var src = script.src;
		if(src!=null) {
			var has_question = (src.indexOf('?', 1)>0 ? true : false );
			if(src.length==0){
				script.setAttribute('src', '');}
			else{//alert(src);
				script.setAttribute('src', script.src + (has_question==true ? '&' : '?') + '1=1');}
		}
	}
}

function AjaxHrefCheck() {
	var link = new String(document.location);
	/*if(new String(document.location.hash).indexOf('#url=')>-1)
		link = document.location.protocol+'//'+document.location.host + new String(document.location.hash).replace('#url=','');
	else
		link = document.location.protocol+'//'+document.location.host+document.location.pathname+document.location.search+document.location.hash;*/
	if(link.indexOf('#url=')>-1)
		link = document.location.protocol+'//'+document.location.host + link.replace(/[^#]*#url=/,'');
	
	/*var as = document.getElementsByTagName('input');
	for(var i=0; i<as.length; i++)
		if(as[i].type='text') {
			as[i].value = (link+':'+decodeURI(AjaxCallURL));
			//as[i].value = (history.length+':'+document.body.AjaxHrefCheckHistory+' ');
			break;
		}*/
	
	if(link!=AjaxCallURL)
		AjaxAClick(link);
	
	if(window.navigator.userAgent.indexOf("MSIE") != -1)
		if(document.body.AjaxHrefCheckHistory && document.body.AjaxHrefCheckHistory!=history.length) {
			//alert(link);
			window.location = link;
		}
	setTimeout('AjaxHrefCheck()', 500);
}

function AjaxAClick(url) {
	var div = document.getElementById('AjaxAnchors');
	var a = document.createElement('a');
	a.href = url;
	a.AjaxCall = AJAX_RENDER_BLOCKS;
	div.appendChild(a);
	AjaxOnClick(a);
}

addEvent(window, 'load', AjaxInitLinks);
function AjaxInitLinks() {
	var add = '';
	var as = document.getElementsByTagName('a');
	for(var i=0; i<as.length; i++) {
		var a = as[i];
		var str = a.href.split('#');
		if(str[1]) {
			var str1 = str[1].split(':');
			if(str1[0]==AJAX_NAME_LINK && str1[1]) {
				add+= '<a name="url='+str[0].substr(str[0].indexOf('/', 8), str[0].length)+'"></a>';
			}
		}
	}
	var div = document.getElementById('AjaxAnchors');
	if(div)
		div.innerHTML = add;
	else {
		//document.body.innerHTML = '<div id="AjaxAnchors">'+add+'</div>'+document.body.innerHTML;
		var div = document.createElement('div');
		div.id = 'AjaxAnchors';
		div.innerHTML = add;
		document.body.insertBefore(div, document.body.firstChild);
	}
	
	var as = document.getElementsByTagName('a');
	for(var i=0; i<as.length; i++) {
		var a = as[i];
		var str = a.href.split('#');
		if(str[1]) {
			var str1 = str[1].split(':');
			if(str1[0]==AJAX_NAME_LINK && str1[1]) {
				a.href = str[0];
				a.AjaxCall = str1[1];
				addEvent(a, 'click', AjaxOnClick);
			}
		}
	}
	document.body.AjaxHrefCheckHistory = history.length;
	setTimeout('AjaxHrefCheck()', 500);
}

function AjaxOnClick(event) {
	/*if (window.event) {
		event = window.event;
		event.returnValue = false;
	} else
		event.preventDefault();*/
	
	var a;
	if(event.tagName=='A')
		a = event;
	else
		if(event.target)
			a = event.target; 
		else
			a = event.srcElement;
	
	if(a.tagName!='A')
		a = a.parentNode;
	if(a.tagName!='A' || !a.AjaxCall)
		return;
	
	if(AjaxCall(a.AjaxCall, null, a.href, a)) {
		if (window.event) {
			event = window.event;
			event.returnValue = false;
		} else
			event.preventDefault();
	}
}

function AjaxCall(Func, post, url, src) {
	url = url? url : AjaxCallURL;
	var post1 = AJAX_POST_FUNCTION + '=' + Func;
	post = post? ('&' + post1) : post1;
	
	if(Func==AJAX_RENDER_BLOCKS)
		post+= AjaxAddPostRenderBlocks();
	
	//document.body.style.cursor = 'wait';
	var link = new ajax(url, {method: 'post', postBody: post, update: src, onComplete: AjaxCallComplete});
	if(link.transport) {
		$(document.body).setOpacity(0.5);
		document.body.timeout = setTimeout('$(document.body).setOpacity(1)', 10000);
		return true;
	}
	return false;
}

function AjaxCallComplete(request, src) {
	//document.body.style.cursor = '';
	$(document.body).setOpacity(1);
	if(document.body.timeout)
		clearTimeout(document.body.timeout);
	if(request.status == 200) {
		if(src && src.AjaxCall==AJAX_RENDER_BLOCKS) {
			var responseTexts = request.responseText.split('\n\n');
			var div = null;
			for(var i=0; i<responseTexts.length; i++) {
				var responseText = responseTexts[i];
				if(responseText.substr(0, 8)=='Replace ') {
					var id = responseText.split('\n');
					id = id[0];
					var text = responseText.substr(id.length+1);
					var id = id.substr(8);
					div = document.getElementById(id);
					if(div) {
						AjaxCallURL = src.href;
						var span = document.createElement('span');
						span.innerHTML = ''+text+'';
						id = span.firstChild.id;
						div.parentNode.replaceChild(span.firstChild, div);
						setTimeout('AjaxRunJS(document.getElementById("'+id+'"))', 100);// Даем Ослу время на раздумья...
						//span.removeNode(true);
					}
				}
				if(responseText.substr(0, 9)=='Redirect ') {
					var id = responseText.split('\n');
					window.location = id[1];
					return;
				}
			}
			if(div) {
				window.location.hash = '#url='+src.href.substr(src.href.indexOf('/', 8), src.href.length);
				AjaxInitLinks();
				return;
			}
		}
		if(AJAX_DEBUG)
			document.body.innerHTML = request.responseText;
			
	} else if(AJAX_DEBUG)
		document.body.innerHTML = 'Error status: ' + request.status;
	if(src && src.AjaxCall==AJAX_RENDER_BLOCKS && !AJAX_DEBUG)
		window.location.href = src.href;
}

function AjaxAddPostRenderBlocks() {
	var Items = document.getElementsByTagName('div');
	var name = AJAX_HTML + '[Action:';// без $ModuleID и $ActionType
	for(var i=0; i<Items.length; i++) {
		if(Items[i].id.substr(0, name.length)==name) {
			var Items = Items[i].getElementsByTagName('div');
			var name = AJAX_HTML + '[ArticleBlock:';
			var ret = '&' + AJAX_POST_BLOCKS + '=';
			/*for(var i=0; i<Items.length; i++) {
				if(Items[i].id.substr(0, name.length)==name) {
					var id = Items[i].id;
					id = id.substr(name.length, id.length-name.length-1);
					ret+= id + '%2c';
				}
			}*/
			
			eval('var Forced = (typeof '+FORCE_UPDATE_BLOCKS+'=="undefined"? "" : '+FORCE_UPDATE_BLOCKS+')');
			if(Forced)
				ret+= escape(Forced) + '%2c';
			
			var href = AjaxCallURL.substr(7, AjaxCallURL.length);
			href = href.substr(href.indexOf('/'), AjaxCallURL.length);
			return (ret.substr(0, ret.length-3) + '&' + AJAX_POST_URL + '=' + href).replace(/\//g, '%2f');
		}
	}
	showAjaxError('Not find Action block!');
	return '';
}


ajax = function(url, options){return this.initialize(url, options)};
ajax.prototype = {
	initialize: function(url, options){
		this.transport = this.getTransport();
		this.postBody = options.postBody || '';
		this.method = options.method || 'post';
		this.onComplete = options.onComplete || null;
		this.update = $(options.update) || null;
		this.request(url);
	},

	request: function(url){
		this.transport.open(this.method, url, true);
		this.transport.onreadystatechange = this.onStateChange.bind(this);
		if (this.method == 'post') {
			this.transport.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
			if (this.transport.overrideMimeType) this.transport.setRequestHeader('Connection', 'close');
		}
		this.transport.send(this.postBody);
	},

	onStateChange: function(){
		if (this.transport.readyState == 4 && this.transport.status == 200) {
			if (this.onComplete) 
				setTimeout(function(){this.onComplete(this.transport, this.update);}.bind(this), 10);
			//if (this.update)
				//setTimeout(function(){this.update.innerHTML = this.transport.responseText;}.bind(this), 10);
			this.transport.onreadystatechange = function(){};
		}
	},

	getTransport: function() {
		if (window.ActiveXObject) return new ActiveXObject('Microsoft.XMLHTTP');
		else if (window.XMLHttpRequest) return new XMLHttpRequest();
		else return false;
	}
};
