/*
 * $Id: ajax.js 1047 2009-01-26 09:55:43Z root $
 *
 * AJAX calls are used to submit / retreive data without reloading the page.
 */

// We need to do this for IE <= 6...
if (!window.XMLHttpRequest) {
    window.XMLHttpRequest = function() {

        var types = [
            'MSXML2.XMLHTTP.6.0',
            'MSXML2.XMLHTTP.3.0',
            'Microsoft.XMLHTTP'
        ];

        for (var i = 0; i < types.length; i++) {
            try {
                // Internet Explorer (t/m 6) gebruikt een ActiveX Object
                return new ActiveXObject(types[i]);
            }
            catch(e) {}
        }

        return undefined;
    }
}

function submitAjaxForm(url, formName,target) {
    // WARNING FOR IE: if there is an input element in the form with the name 'id',
    // do not use form.getAttribute('id'), this will return the input element instead of the form's id!
	var obj,targetTag;
	if (!(obj = eId(formName))) { return; }
	if (!(targetTag = eId(target))) { return; }

	getstr="";

	for (i=0; i<obj.elements.length; i++) {

		if (obj.elements[i].name.length > 0 && (obj.elements[i].tagName == "INPUT" || obj.elements[i].tagName == "TEXTAREA")) {

			if (obj.elements[i].type == "checkbox") {
				if (obj.elements[i].checked) {
					getstr += obj.elements[i].name + "=" + encodeURIComponent(obj.elements[i].value) + "&";
				} else {
					getstr += obj.elements[i].name + "=&";
				}
			}
			else if (obj.elements[i].type == "radio") {
				if (obj.elements[i].checked) {
	      			getstr += obj.elements[i].name + "=" + encodeURIComponent(obj.elements[i].value) + "&";
				}
			}
			else  {
   				getstr += obj.elements[i].name + "=" + encodeURIComponent(obj.elements[i].value) + "&";
			}
 		}
		if (obj.elements[i].tagName == "SELECT") {
			var sel = obj.elements[i];
			getstr += sel.name + "=" + (sel.options.length > 0 ? encodeURIComponent(sel.options[sel.selectedIndex].value) : '') + "&";
		}

	}

	var divs = targetTag.getElementsByTagName('ul');
	for (i=divs.length-1; i>=0; i--) {
		if (divs[i].className == "errors") {
			divs[i].parentNode.removeChild(divs[i]);
		}
	}

	var xmlObj = new XMLRequestObject(url,getstr ,updateControl);
	xmlObj.setTarget(target);
	xmlObj.setLoadMethod('replacekids');

	xmlhttpPost(xmlObj);
}

/**
 * Toggle loading class and set wait cursor.
 */
function toggleLoading(className) {
    document.body.style.cursor = (className == 'show' ? 'wait' : '');
    var loadElement = eId('ajaxLoad');

    if (loadElement) { loadElement.className = className; }
}

function setAjaxLocation(location) {
    window.location.href = window.location.href.replace(/#.*/, '') + '#' + location;
}

/**
 * Return the part after the # in the location
 */
function getAjaxLocation() {
    var res = window.location.href.split('#');
    if (res == window.location.href) {
        return false;
    }
    return res[1];
}

function getUrl(url, target, post) {

    var xmlObj = new XMLRequestObject(url,post ,updateControl);
    xmlObj.setTarget(target);
    xmlObj.setLoadMethod('replacekids');
    xmlhttpPost(xmlObj);
}

function UpdateControl() {
	this.executeUpdate = function(xmlObj) {
		var xmlData, doc, div, node;

        if (! (xmlData = xmlObj.getXMLData())) { alert('Invalid response received from server.');}
        var xml = xmlData.documentElement;

        // Enable the line below for debugging purposes
        // if (xml == null) { alert(xmlObj.getData()); }

        var data = xml.firstChild.data;
        doc = document.createElement('div');
        doc.innerHTML = data;

		if (xml.getAttribute('type') == "error") { alert("Er is een fout opgetreden!\nFoutmelding: " + data); return;}

		//target element
		var tar = document.getElementById(xmlObj.getTarget());
		//teller voor childnodes
		var i =0;

		switch(xmlObj.getLoadMethod()) {

			case "replacekids":
				tar.innerHTML = data;
	            this.parseTag(tar, true);
				break;
			case "firstkid":
				for (i=doc.childNodes.length-1;i>=0;i--) {
					node = tar.insertBefore(doc.childNodes[i].cloneNode(true),doc.childNodes[0]);
				}
				break;
			case "lastkid":
				for (i=0;i<doc.childNodes.length;i++) {
					node = tar.appendChild(doc.childNodes[i].cloneNode(true));
				}
				break;
			case "before":
				node = tar.parentNode.insertBefore(doc,tar);
				break;
			default: break;
		}
	};

    this.parseTag = function (doctree,script)  {
        if (! doctree) { return; }
        var node, i;
        var tagName, len = doctree.childNodes.length;

        node = doctree;
        if (node.tagName != null) {
            tagName = node.tagName.toUpperCase();
            // Please be aware that the script tag is not recognized
            // in IE if it is the first element in the HTML code
            if (tagName == "SCRIPT"  && script) {
                eval (node.innerHTML);
                node.parentNode.removeChild(node);
                return;
            }
        }

        for(i=0;i<len;i++) {
            this.parseTag(doctree.childNodes[i], script);
        }
    };
}

function XMLRequestObject(strUrl, strSubmit, updateObj) {
	this.url = strUrl;
	this.submitData = strSubmit;
	this.updateObj = updateObj;
	this.data = "";
    this.xmlData = "";
	this.target = "";
	this.loadMethod = "";

	this.getUrl = function() { return (this.url); };
	this.getSubmitData = function() { return (this.submitData); };
	this.getUpdateObj = function() { return (this.updateObj); };
	this.setData = function(data) { this.data = data; };
	this.getData = function() { return (this.data); };
    this.setXMLData = function(xmlData) { this.xmlData = xmlData; };
    this.getXMLData = function() { return (this.xmlData); };
	this.setTarget = function(target) { return (this.target = target); }
	this.getTarget = function() { return (this.target); }
	this.setLoadMethod = function(method) { this.loadMethod = method; }
	this.getLoadMethod = function () { return (this.loadMethod) ; }
}


function xmlhttpPost(xmlObj) {

	var xmlHttpReq = false;

	// Voor Mozilla, Opera en Safari gebruiken we XMLHttpRequest.
	if (window.XMLHttpRequest) {
	  xmlHttpReq = new XMLHttpRequest();
	}

	// We gebruiken de POST methode om gegevens te versturen.
	// T.o.v. de GET methode is het voordeel hierbij dat je de data
	// niet aan de url hoeft te plakken.
	xmlHttpReq.open('POST', xmlObj.getUrl(), true);
	xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

	// Callback functie die aangeroepen wordt wanneer de status van het HttpRequest object veranderd is.
	xmlHttpReq.onreadystatechange = function() {
		// readyState 4 betekent dat de request compleet is
		if (xmlHttpReq.readyState == 4) {
            toggleLoading('hide');

			if (xmlHttpReq.status == 200) {		// status 200 betekent dat de pagina goed ontvangen is
				xmlObj.setData(xmlHttpReq.responseText);
                xmlObj.setXMLData(xmlHttpReq.responseXML);
				xmlObj.getUpdateObj().executeUpdate(xmlObj);
			}
            else if(xmlHttpReq.status == 401) {
                //Page requested is not viewable, refresh page to show why
                window.location.reload()
            }
			else {
				// Pagina is niet goed ontvangen, response afhandelen;
			}
		}
	}
    toggleLoading('show');
    xmlHttpReq.send(xmlObj.getSubmitData());
}

String.prototype.unescapeXML = function () {
    return this.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&');
}
var updateControl = new UpdateControl();
