﻿function e(i) { return document.getElementById(i); }

// this imports nodes from the returned XML - IE doesn't support it at all
// and Firefox and Safari don't display the images contained within
// the subnodes which suggests that they don't support it properly
// either. This hopefully works on all browsers.
function importNode(node)
{
    var newnode = null;

    if (node.nodeType == 1)
    {
        newnode = document.createElement(node.nodeName);
        if (node.attributes != null)
        {
            for (var i = 0; i < node.attributes.length; i++)
            {
                var attribute = node.attributes[i];

                if (attribute.nodeValue != null && attribute.nodeValue != '')
                {
                    newnode.setAttribute(attribute.name, attribute.nodeValue);
                    if (attribute.name == 'class')
                    {
                        newnode.className = attribute.nodeValue;
                    }
                    
                    if (attribute.name.substring(0, 2) == 'on')
                    {
                        try
                        {
                            compileScript(attribute.nodeValue);
                        }
                        catch (e)
                        {
                        }
                    }
                }
            }
        }
        
        if (node.style != null && node.style.cssText != null)
        {
            newnode.style.cssText = node.style.cssText;
        }

        if (node.hasChildNodes())
        {
            for (var i = 0; i < node.childNodes.length; i++)
            {
                if (node.childNodes[i].tagName != 'script')
                {
                    var newsub = importNode(node.childNodes[i]);
                    newnode.appendChild(newsub);
                }
            }
        }
    }
    else if (node.nodeType==3)
    {
        newnode = document.createTextNode(node.nodeValue);
    }
    
    return newnode;
}


function postForm(data, url, callback)
{
	var http_request = null;
	
	if (window.XMLHttpRequest)
	{
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType)
		{
			http_request.overrideMimeType('text/html');
		}
	}
	else if (window.ActiveXObject)
	{
		try
		{
			http_request = new ActiveXObject('Msxml2.XMLHTTP');
		}
		catch (e)
		{
			try
			{
				http_request = new ActiveXObject('Microsoft.XMLHTTP');
			}
			catch (e) 
			{
			}
		}
	}
	
	if (!http_request)
	{
		alert('Cannot create XMLHTTP instance');
		return false;
	}

	http_request.onreadystatechange = function()
	{
		if (http_request.readyState == 4)
		{
			if (http_request.status == 200)
			{
				if (window.execScript)
					window.execScript(callback + '()');
				else
					window.setTimeout(callback + '()', 0);
			}
			else
			{
				alert('There was a problem with the request. (' + http_request.status + ')');
			}
		}
	}

	http_request.open('POST', url, true);
	http_request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
	http_request.setRequestHeader('Content-length', data.length);
	http_request.setRequestHeader('Connection', 'close');
	http_request.send(data);
	
	return false; 
}

Ajax = function(m, u, d)
{
	var xmlhttp = null;
	var method = m;
	var url = u;
	var el = d;
	var ajax = this;
	
	Ajax.prototype.callback = function()
	{
	}
		
	// code for Mozilla, etc.
	if (window.XMLHttpRequest)
	{
		xmlhttp=new XMLHttpRequest();
	}
	else if (window.ActiveXObject)
	{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	
	if (xmlhttp != null)
	{
		xmlhttp.onreadystatechange=function()
		{
			// if xmlhttp shows "loaded"
			if (xmlhttp.readyState==4)
			{
				// if "OK"
				if (xmlhttp.status==200)
				{
					if (xmlhttp.responseText.substr(0, 5) == 'ERROR')
					{
						alert(xmlhttp.responseText.substr(5));
					}
					else
					{
						if (d != null && d != '')
						{
							var el = document.getElementById(d);
							el.innerHTML = xmlhttp.responseText;
							updateDocument(xmlhttp);
						}
					
						if (ajax.callback) 
						{
							ajax.callback(xmlhttp.responseText);
						}
					}
				}
				else
				{
					document.getElementById('debug').innerHTML = xmlhttp.responseText;
				}
			}
		}
	}
	else
	{
		alert("Your browser does not support XMLHTTP.");
	}
	
	this.go = function()
	{
		xmlhttp.open(method, url, true);
		xmlhttp.send(null);
	}
	
	this.post = function(data)
	{
		xmlhttp.open(method, url, true);
		xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
		xmlhttp.setRequestHeader('Content-length', data.length);
		xmlhttp.setRequestHeader('Connection', 'close');
		xmlhttp.send(data);
	}
}

function loadXMLDoc(method, url, el)
{
	var xmlhttp = null;
	var element = el;
	
	// code for Mozilla, etc.
	if (window.XMLHttpRequest)
	{
		xmlhttp=new XMLHttpRequest();
	}
	else if (window.ActiveXObject)
	{
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	
	if (xmlhttp!=null)
	{
		xmlhttp.onreadystatechange=function()
		{
			// if xmlhttp shows "loaded"
			if (xmlhttp.readyState==4)
			{
				// if "OK"
				if (xmlhttp.status==200)
				{
					if (element != null && element != '')
					{
						var el = document.getElementById(element);
						el.innerHTML = xmlhttp.responseText;
						updateDocument(xmlhttp);
					}
				}
				else
				{
					alert("Problem talking to server.\r\n" + url);
				}
			}
		}
		
		xmlhttp.open(method, url, true);
		xmlhttp.send(null);
	}
	else
	{
		alert("Your browser does not support XMLHTTP.");
	}
}

function compileScript(script)
{
    if (window.execScript)
        window.execScript(script);
    else
        window.setTimeout(script, 0);
}

function updateDocument(req)
{
	var matchAll = new RegExp('(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)', 'img');
	var matchOne = new RegExp('(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)', 'im');

	var results = req.responseText.match(matchAll);
	if (results == null) return;

	for (var i = 0; i < results.length; i++)
	{
		compileScript(results[i].match(matchOne)[1]);
	}
}

function bc(name)
{
	var request = '<?xml version="1.0" encoding="utf-8" ?>\n';
	request += '<request>\n';
	request += '<function>' + name + '</function>\n';

	for (var i = 1; i < arguments.length; i++)
	{
		request += '<parameter>' + arguments[i] + '</parameter>\n';
	}

	request += '</request>';
    url = window.location.href;

	// code for Mozilla, etc.
	if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); } else if (window.ActiveXObject) { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");	}
	if (xmlhttp == null) { return;	}

	xmlhttp.open('post', url, false);
	xmlhttp.setRequestHeader('Content-type', 'text/xml');
	xmlhttp.setRequestHeader('Content-length', request.length);
	xmlhttp.setRequestHeader('Connection', 'close');
	xmlhttp.send(request);
	
    if (xmlhttp.status==200)
    {
        if (document.getElementById('ajax-debug') != null)
        {
            alert(xmlhttp.responseText);
//            document.getElementById('ajax-debug').innerHTML = xmlhttp.responseText;
        }

	    var xml = xmlhttp.responseXML;
        var ops = xml.getElementsByTagName('operation');

        for (var i = 0; i < ops.length; i++)
        {
            var optype = ops[i].attributes.getNamedItem('type').value;
            var parent = null;
            if (ops[i].attributes.getNamedItem('parent') != null)
            {
                parent = ops[i].attributes.getNamedItem('parent').value;
            }
            
            if (optype == 'redirect')
            {
                window.location.href = ops[i].childNodes[0].nodeValue;
            }
            else if (optype == 'insert')
            {
                var child = null;
                if (ops[i].attributes.getNamedItem('child') != null)
                {
                    child = ops[i].attributes.getNamedItem('child').value;
                }
                
                if (ops[i].childNodes[0] != null)
                {
                    var c = importNode(ops[i].childNodes[0]);
                    document.getElementById(parent).insertBefore(c, document.getElementById(child));
                }
            }
            else if (optype == 'append')
            {
                for (var c = 0; c < ops[i].childNodes.length; c++)
                {
                    if (ops[i].childNodes[0] != null)
                    {
                        var newnode = importNode(ops[i].childNodes[c]);
                        document.getElementById(parent).appendChild(newnode);
                    }
                }
            }
            else if (optype == 'remove')
            {
                var node = ops[i].attributes.getNamedItem('node').value;
                removeElementFromParent(document.getElementById(node));
            }
            else if (optype == 'replace')
            {
                var node = ops[i].attributes.getNamedItem('node').value;
                if (ops[i].childNodes[0] != null)
                {
                    var newnode = importNode(ops[i].childNodes[0]);
                    var parent = document.getElementById(node).parentNode;
                    parent.replaceChild(newnode, document.getElementById(node));
                }
            }
            else if (optype == 'clear')
            {
                var node = ops[i].attributes.getNamedItem('node').value;
                clearElement(document.getElementById(node));
            }
            else if (optype == 'dialog')
            {
                var title = ops[i].attributes.getNamedItem('title').value;
                var id = ops[i].attributes.getNamedItem('id').value;
                
                var dlg = new Dialog(title, id, -1, 100);

                if (ops[i].childNodes[0] != null)
                {                
                    var content = importNode(ops[i].childNodes[0]);
                    dlg.body.appendChild(content);
                }
                dlg.centre();
            }
        }

        var scripts = xml.getElementsByTagName('script');
        for (var i = 0; i < scripts.length; i++)
        {
            compileScript(scripts[i].childNodes[0].nodeValue);
        }
    }
    
    delete xmlhttp;
}
