var http_request = false;
var xmldoc;
var rssTmpl;
var maxItems = 10;

function makeRequest(url, tmpl, max) {
	rssTmpl = tmpl;
	if (max) maxItems = max;
	if (window.XMLHttpRequest) { // for mozilla and firefox
		http_request = false;
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType)
			http_request.overrideMimeType('text/xml');
	}
	else if (window.ActiveXObject) { //for ie
		try { http_request = new ActiveXObject("Msxml2.XMLHTTP"); }
		catch (e) { 
			try { http_request = new ActiveXObject("Microsoft.XMLHTTP"); } 
			catch (e) {}
		}
	}

	if (!http_request) {
		alert('Giving up :( Cannot create an XMLHTTP instance');
		return false;
	}

	http_request.onreadystatechange = alertContents;
	http_request.open('GET', url, true);
	http_request.send(null);
}

function alertContents(){ 
	if (http_request.readyState == 4) { 
		if (http_request.status == 200) { 
			var string = http_request.responseText;
			var xmldoc;
			if (window.ActiveXObject) { 
				var doc = new ActiveXObject("Microsoft.XMLDOM");
				doc.async=false;
				doc.loadXML(string);
				xmldoc = doc.documentElement;
			}
			else if (window.XMLHttpRequest) { 
				var parser = new DOMParser(); 
				var doc = parser.parseFromString(string, "text/xml");
				xmldoc = doc.documentElement;
			}
			
			if (rssTmpl = document.getElementById(rssTmpl)) {
				var elem = addElement(rssTmpl, 'div', 'CommonContentBox');
				addElement(elem, 'h4', 'CommonContentBoxHeader', 'Новости')
				elem = addElement(elem, 'div', 'CommonContentBoxContent');
				elem = addElement(elem, 'ul', 'CommonSidebarList');
				var items = xmldoc.getElementsByTagName('item');
				var l = items.length;
				for	(var i = 0; i < l && i < maxItems; i++) {
					var li = addElement(elem, 'li', 'CommonSidebarRssListItem');
					var title = items[i].getElementsByTagName('title')[0].firstChild.nodeValue;
					var tooltip = title;
					var link = items[i].getElementsByTagName('link')[0].firstChild.nodeValue;
					if (title.length > 50) title = title.substring(0, 49) + "...";
					addElement(li, 'a', null, title, link, tooltip);
				}
			}
		} 
		//else alert('There was a problem with the request.');
	}
}

function addElement(parent, name, cls, content, href, tooltip) {
	var elem = document.createElement(name);
	if (cls)	elem.className = cls;
	if (href)	elem.setAttribute('href', href);
	if (tooltip) elem.title = tooltip;
	if (content) elem.innerHTML = content;
	parent.appendChild(elem);
	return elem;
}
