/*ajax URL for retrieving messages*/
var ajaxURL = "/admin/ajaxrequest.php"; 

// when set to true, display detailed error messages
var debugMode = true;

// function that displays an error message
function displayError(message)
{
    // display error message, with more technical details if debugMode is true
   //tijdelijk uitgezet door pieter
   // alert("Error accessing the server! " +(debugMode ? message : ""));
}

// function that displays a PHP error message
function displayPHPError(error)
{
  displayError ("Error number :" + error.errno + "\r\n" +
              "Text :"+ error.text + "\r\n" +
              "Location :" + error.location + "\r\n" +
              "Line :" + error.line + + "\r\n");
}

function retrieveAjaxMessage(mode, id, parameters)
{
    $.ajax({
        url: ajaxURL,
        type: 'POST',
        data: $.param({
            mode: mode,
            vars: parameters
        }),
        dataType: 'html',
        error: function(xhr, textStatus, errorThrown) {
            displayError(textStatus);
        },
        success: function(data, textStatus) {
            if(data.errno != null)
              displayPHPError(data);
            else{
              $(id).html(data);
              $(id).trigger('change');
            }
        }
    });
}

function retrieveAjaxMessageXtra(mode, Update, parameters,id)
{
    $.ajax({
        url: ajaxURL,
        type: 'POST',
        data: $.param({
            mode: mode,
            vars: parameters
        }),
        dataType: 'html',
        error: function(xhr, textStatus, errorThrown) {
            displayError(textStatus);
        },
        success: function(data) {
            if(data.errno != null)
              displayPHPError(data);
            else{
              Update(data,id);
            }
        }
    });
}

$(document).ready(function() {
    //als er een change is moet deze worden opgevangen door de volgende functie
    $.address.change(
        function ChangeInvoked(event){

            var parameter = $.address.parameterNames();
            //elke parameter langs lopen om ze elke javascript functie langs te gaan
            for (var i=0; i < parameter.length; i++ )
            {
                //Input uit elkaar trekken
                //3 waarde: 1e=modus, 2e=id waar data naartoe moet, 3e= vars
                var waardes = Base64.decode($.address.parameter(parameter[i])).split("|",3);
                var var1 = false; var var2 = false; var var3 = false;
                for (var j=1; j < waardes.length+1; j++ )
                {
                    //modus ophalen
                    if(j==1){var1 = waardes[j-1];}
                    //id ophalen van update element
                    if(j==2){var2 = waardes[j-1];}
                    //parameters strippen uit de string
                    if(j==3){var3 = waardes[j-1];}
                }
                //als alle parameters over zijn gekomen roepen we onze functie aan
                if(var1!=false && var2!=false && var3!=false){
                    retrieveAjaxMessage(var1,var2,var3);
                } else {
                    alert('ChangeInvoked error.\nModus: '+ var1 + '\nId: ' + var2+ '\nParameters: ' + var3);
                }
            }
        }
    );
});

//om gegevens in de url te kunnen zetten gebruiken we encryption. Hierdoor kunnen meedere variabele in de query string staan zonder de nadelen van meedere variabele
//http://www.webtoolkit.info/javascript-base64.html
var Base64 = {
	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
                input = Base64._compress(input);
		input = Base64._utf8_encode(input);

		while (i < input.length) {

			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);

			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;

			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}

			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

		}

		return output;
	},

	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;

		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

		while (i < input.length) {

			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));

			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;

			output = output + String.fromCharCode(chr1);

			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}

		}

		output = Base64._utf8_decode(output);

                output = Base64._decompress(output);
		
                return output;

	},

	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	},

	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length ) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
	},

        // private method for LZW-compressing a string
        _compress: function(s) {
            var dict = {};
            var data = (s + "").split("");
            var out = [];
            var currChar;
            var phrase = data[0];
            var code = 256;
            for (var i=1; i<data.length; i++) {
                currChar=data[i];
                if (dict[phrase + currChar] != null) {
                    phrase += currChar;
                }
                else {
                    out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
                    dict[phrase + currChar] = code;
                    code++;
                    phrase=currChar;
                }
            }
            out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
            for (var i=0; i<out.length; i++) {
                out[i] = String.fromCharCode(out[i]);
            }
            return out.join("");
        },

        // private method for Decompressing an LZW-encoded string
        _decompress: function(s) {
            var dict = {};
            var data = (s + "").split("");
            var currChar = data[0];
            var oldPhrase = currChar;
            var out = [currChar];
            var code = 256;
            var phrase;
            for (var i=1; i<data.length; i++) {
                var currCode = data[i].charCodeAt(0);
                if (currCode < 256) {
                    phrase = data[i];
                }
                else {
                   phrase = dict[currCode] ? dict[currCode] : (oldPhrase + currChar);
                }
                out.push(phrase);
                currChar = phrase.charAt(0);
                dict[code] = oldPhrase + currChar;
                code++;
                oldPhrase = phrase;
            }
            return out.join("");
        }


}
