//ahCalls.createAhCall("[get],[post],[scriptTag],[proxyGet],[proxyPost]", "url to web service or local file", "[string],[jsonObject],[jsonString],[xmlObject],[xmlString]", callback function name, "parameters if using post, if not set as false", "proxy path, false, or leave blank");

var onstuimigPostbode = {
  id:0,
	group:0,
	fnc_subscribeCallback:null,
	fnc_unsubscribeCallBack:null,
	subscribeUrl:'http://postbode.onstuimig.nl/api/subscribe.asp',
	unSubscribeUrl:'http://postbode.onstuimig.nl/api/unsubscribe.asp',
	
 init:function(id, group, subscribeCallback, unsubscribeCallBack ) {
  this.id = id;
  this.group = group;
  this.fnc_subscribeCallback = subscribeCallback;
  this.fnc_unsubscribeCallBack = unsubscribeCallBack;
 },


 subscribe:function(strFirstName, strMidName, strLastName, strEmail, strSexe, blnIsHtml ) {
   //var ojbData = {group: this.group, id: this.id, firstname: strFirstName, midname: strMidName, lastname: strLastName, email: strEmail, sexe: strSexe, ishtml: blnIsHtml };
   //new Ajax(this.subscribeUrl, { method: "post", onComplete:this.subscribeCallBack, postBody:ojbData, obj:this }).request();
//   var foo = prompt('', this.subscribeUrl + '?group=' + this.group +'&id=' + this.id +'&firstname=' + encodeURIComponent(strFirstName) +'&midname=' + encodeURIComponent(strMidName) +'&lastname=' + encodeURIComponent(strLastName) +'&email=' + encodeURIComponent(strEmail) + '&sexe='+ encodeURIComponent(strSexe) + '&ishtml='+ blnIsHtml);
   ahCalls.createAhCall('scriptTag', this.subscribeUrl + '?group=' + this.group +'&id=' + this.id +'&firstname=' + encodeURIComponent(strFirstName) +'&midname=' + encodeURIComponent(strMidName) +'&lastname=' + encodeURIComponent(strLastName) +'&email=' + encodeURIComponent(strEmail) + '&sexe='+ encodeURIComponent(strSexe) + '&ishtml='+ blnIsHtml , 'jsonObject', this.fnc_subscribeCallback,  false );
 },
 
 unsubscribe:function(strEmail){
  //var ojbData = {group: this.group, id: this.id, email: strEmail};
  //new Ajax(this.unSubscribeUrl, {method: "post", onComplete:this.unsubscribeCallBack, postBody:ojbData, obj:this }).request();
  ahCalls.createAhCall('scriptTag', this.unSubscribeUrl + '?group=' + this.group +'&id=' + this.id +'&email=' + encodeURIComponent(strEmail), 'jsonObject', this.fnc_unsubscribeCallBack,  false );
 } 
};

var ahCalls = {
	
	theReturnType:null,
	called:false,
	queryStr:null,
	counter:0,
	scriptTagCallBackFunction:null,
	scriptTagJsonType:null,
	
	createAhCall:function(httpType,url,returnType,callBackFunction,params,proxyPath)
	{
		if(!document.getElementById || !document.createTextNode){return;}
		this.theReturnType = returnType;
		
		if(httpType != 'scriptTag'){//is not using script tag
			this.queryStr = (!params) ? null : encodeURIComponent(params);
			var xmlHttp = ahCalls.createXmlHttpObject();
			if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0){// proceed only if the xmlHttp object isn't busy
				
				xmlHttp.onreadystatechange = function(){// define the method to handle server responses
				
					switch(xmlHttp.readyState){
						case 1: if(!this.called){/*alert('waiting on server!');*/this.called = true} break;
						case 2: break;
						case 3: break;
						case 4:
							if ( xmlHttp.status == 200 ){// only if "OK"
								try{
									responseObj = ahCalls.parseXmlHttpResponse(xmlHttp);
									success = true;
								}catch(e){ 
									alert('Parsing Error: The value returned could not be evaluated.');
									success = false;
								}
								if(success) callBackFunction( responseObj ); //if all is good send the response to the callback function
							}else{ 
								alert("There was a problem retrieving the data:\n" + xmlHttp.statusText);
							}
							break;
					}
				}
				
				if(httpType == 'get' || httpType == 'post'){
					xmlHttp.open(httpType, ahCalls.noCache(url), true);
				}else{
					if(httpType == 'proxyGet'){
						xmlHttp.open('get', (proxyPath+'?path='+(encodeURIComponent(url))), true);
					};
					if(httpType == 'proxyPost'){
						xmlHttp.open('put', (proxyPath+'?path='+(encodeURIComponent(url))), true);
					};
				}
				
				if(params){xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8")};
				xmlHttp.send(this.queryStr);// make the server request and send queryStr or null as an argument
				
			}else{// if the connection is busy, try again after one second 
				setTimeout('ahCalls.createAhCall();', 1000);
			}
		}else{//using scriptTag
			this.scriptTagCallBackFunction = callBackFunction;
			if(returnType == 'jsonObject' || returnType == 'jsonString'){//getting json return via script tag
				ahCalls.JsonXmlScriptRequest(ahCalls.noCache(url+'&callback=ahCalls.JsonXmlScriptHandleRequest'));
			}else{//getting xml return via script tag
				var xmlPath = encodeURIComponent(url);
				ahCalls.JsonXmlScriptRequest(proxyPath+'?path='+xmlPath);
			}
		}	
	},
	
	createXmlHttpObject:function()
	{
		var ahCalls; // will store the reference to the XMLHttpRequest Object
		
		try{
			ahCalls = new XMLHttpRequest();// this should work for all browsers except IE6 and older
		}catch(e){
			var XmlHttpVersions = new Array('MSXML2.XMLHTTP.6.0','MSXML2.XMLHTTP.5.0','MSXML2.XMLHTTP.4.0','MSXML2.XMLHTTP.3.0','MSXML2.XMLHTTP','Microsoft.XMLHTTP');
			for (var i=0; i<XmlHttpVersions.length && !ahCalls; i++) {
				try { 
					// try to create XMLHttpRequest object
					ahCalls = new ActiveXObject(XmlHttpVersions[i]);
				}catch (e) {}
			}
		}
		
		if(!ahCalls){alert("Error creating the XMLHttpRequest Object.")}else{return ahCalls};// return the created object or display an error message		
	},
	
	JsonXmlScriptRequest:function(fullUrl)
	{
		ahCalls.counter += 1;
		var scriptId = 'JscriptId' + ahCalls.counter;
		
		var scriptObj = document.createElement("script");// Create the script tag
		
    scriptObj.setAttribute("type", "text/javascript");   // Add script object attributes
		scriptObj.setAttribute("charset", "utf-8");
		scriptObj.setAttribute("src", fullUrl);
		scriptObj.setAttribute("id", scriptId);
		var headLoc = document.getElementsByTagName("head").item(0);
		headLoc.appendChild(scriptObj);
	},
	
	JsonXmlScriptHandleRequest:function(jsonData)
	{
		switch(ahCalls.theReturnType) {
		case "xmlObject": var xmlDataObject = ahCalls.xmlTextToObject(jsonData); ahCalls.scriptTagCallBackFunction(xmlDataObject);break;
		case "xmlString": ahCalls.scriptTagCallBackFunction(jsonData); break;
		case "jsonObject": ahCalls.scriptTagCallBackFunction(jsonData); break;
		case "jsonString": var jsonDataString = jsonData.toJSONString();ahCalls.scriptTagCallBackFunction(jsonDataString); break;
		default: 
			// if there is no case "*" match, execute this code
			alert("error")
		};
		
		var scriptElement;
		for (var i = 1; i < 10; i++) {
			scriptElement = document.getElementById('JscriptId' + i);
			if(scriptElement){
			 document.getElementsByTagName("head")[0].removeChild(scriptElement);
			}
		}
	},
	
	parseXmlHttpResponse:function(responseObject){
		var theType = ahCalls.theReturnType;
		
		if(theType != 'proxyPost' || theType != 'proxyGet'){//local xhr call
			switch(theType) {
			case "string": return responseObject.responseText; break;
			case "xmlObject": return responseObject.responseXML; break;
			case "xmlString": return responseObject.responseText; break;
			case "jsonObject": return responseObject.responseText.parseJSON();break;
			case "jsonString": return responseObject.responseText; break;
			default: 
				// if there is no case "*" match, execute this code
				alert("error")
			}
		}else{
			switch(theType) {//cross domain xhr to proxy and then back again
			case "xmlObject": return responseObject.responseXML; break;
			case "xmlString": return responseObject.responseText; break;
			case "jsonObject": return responseObject.responseText.parseJSON();break;
			case "jsonString": return responseObject.responseText; break;
			default: 
				// if there is no case "*" match, execute this code
				alert("error")
			}
		}
	},
	
	xmlTextToObject:function(text){
		if (typeof DOMParser != "undefined") {
		// Mozilla, Firefox, and related browsers
		return (new DOMParser()).parseFromString(text, "application/xml");
		}
		else if (typeof ActiveXObject != "undefined") {
			// Internet Explorer.
			var doc = new ActiveXObject("MSXML2.DOMDocument");  // Create an empty document
			doc.loadXML(text);            // Parse text into it
			return doc;                   // Return it
		}
		else {
			// As a last resort, try loading the document from a data: URL
			// This is supposed to work in Safari.
			var url = "data:text/xml;charset=utf-8," + encodeURIComponent(text);
			var request = new XMLHttpRequest();
			request.open("GET", url, false);
			request.send(null);
			return request.responseXML;
		}
	},
	
	noCache:function (url){
		var qs = new Array();
		var arr = url.split('?');
		var scr = arr[0];
		if(arr[1]) qs = arr[1].split('&');
		qs[qs.length]='nocache='+new Date().getTime();
		return scr+'?'+qs.join('&');
	}

};

/*
    json.js
    2006-09-27

    This file adds these methods to JavaScript:

        object.toJSONString()

            This method produces a JSON text from an object. The
            object must not contain any cyclical references.

        array.toJSONString()

            This method produces a JSON text from an array. The
            array must not contain any cyclical references.

        string.parseJSON()

            This method parses a JSON text to produce an object or
            array. It will return false if there is an error.

    It is expected that these methods will formally become part of the
    JavaScript Programming Language in the Fourth Edition of the
    ECMAScript standard.
*/
(function () {
    var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        s = {
            array: function (x) {
                var a = ['['], b, f, i, l = x.length, v;
                for (i = 0; i < l; i += 1) {
                    v = x[i];
                    f = s[typeof v];
                    if (f) {
                        v = f(v);
                        if (typeof v == 'string') {
                            if (b) {
                                a[a.length] = ',';
                            }
                            a[a.length] = v;
                            b = true;
                        }
                    }
                }
                a[a.length] = ']';
                return a.join('');
            },
            'boolean': function (x) {
                return String(x);
            },
            'null': function (x) {
                return "null";
            },
            number: function (x) {
                return isFinite(x) ? String(x) : 'null';
            },
            object: function (x) {
                if (x) {
                    if (x instanceof Array) {
                        return s.array(x);
                    }
                    var a = ['{'], b, f, i, v;
                    for (i in x) {
                        v = x[i];
                        f = s[typeof v];
                        if (f) {
//                            v = f(v);
                            if (typeof v == 'string') {
                                if (b) {
                                    a[a.length] = ',';
                                }
                                a.push(s.string(i), ':', v);
                                b = true;
                            }
                        }
                    }
                    a[a.length] = '}';
                    return a.join('');
                }
                return 'null';
            },
            string: function (x) {
                if (/["\\\x00-\x1f]/.test(x)) {
                    x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                        var c = m[b];
                        if (c) {
                            return c;
                        }
                        c = b.charCodeAt();
                        return '\\u00' +
                            Math.floor(c / 16).toString(16) +
                            (c % 16).toString(16);
                    });
                }
                return '"' + x + '"';
            }
        };

    Object.prototype.toJSONString = function () {
        return s.object(this);
    };

    Array.prototype.toJSONString = function () {
        return s.array(this);
    };
})();

String.prototype.parseJSON = function () {
    try {
        return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
                this.replace(/"(\\.|[^"\\])*?"/g, ''))) &&
            eval('(' + this + ')');
    } catch (e) {
        return false;
    }
};

