
/*
    http://www.JSON.org/json2.js
    2008-05-25

    Public Domain.

    NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.

    See http://www.JSON.org/js.html

    This file creates a global JSON object containing two methods: stringify
    and parse.

        JSON.stringify(value, replacer, space)
            value       any JavaScript value, usually an object or array.

            replacer    an optional parameter that determines how object
                        values are stringified for objects without a toJSON
                        method. It can be a function or an array.

            space       an optional parameter that specifies the indentation
                        of nested structures. If it is omitted, the text will
                        be packed without extra whitespace. If it is a number,
                        it will specify the number of spaces to indent at each
                        level. If it is a string (such as '\t' or '&nbsp;'),
                        it contains the characters used to indent at each level.

            This method produces a JSON text from a JavaScript value.

            When an object value is found, if the object contains a toJSON
            method, its toJSON method will be called and the result will be
            stringified. A toJSON method does not serialize: it returns the
            value represented by the name/value pair that should be serialized,
            or undefined if nothing should be serialized. The toJSON method
            will be passed the key associated with the value, and this will be
            bound to the object holding the key.

            For example, this would serialize Dates as ISO strings.

                Date.prototype.toJSON = function (key) {
                    function f(n) {
                        // Format integers to have at least two digits.
                        return n < 10 ? '0' + n : n;
                    }

                    return this.getUTCFullYear()   + '-' +
                         f(this.getUTCMonth() + 1) + '-' +
                         f(this.getUTCDate())      + 'T' +
                         f(this.getUTCHours())     + ':' +
                         f(this.getUTCMinutes())   + ':' +
                         f(this.getUTCSeconds())   + 'Z';
                };

            You can provide an optional replacer method. It will be passed the
            key and value of each member, with this bound to the containing
            object. The value that is returned from your method will be
            serialized. If your method returns undefined, then the member will
            be excluded from the serialization.

            If the replacer parameter is an array, then it will be used to
            select the members to be serialized. It filters the results such
            that only members with keys listed in the replacer array are
            stringified.

            Values that do not have JSON representations, such as undefined or
            functions, will not be serialized. Such values in objects will be
            dropped; in arrays they will be replaced with null. You can use
            a replacer function to replace those with JSON values.
            JSON.stringify(undefined) returns undefined.

            The optional space parameter produces a stringification of the
            value that is filled with line breaks and indentation to make it
            easier to read.

            If the space parameter is a non-empty string, then that string will
            be used for indentation. If the space parameter is a number, then
            the indentation will be that many spaces.

            Example:

            text = JSON.stringify(['e', {pluribus: 'unum'}]);
            // text is '["e",{"pluribus":"unum"}]'


            text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
            // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'

            text = JSON.stringify([new Date()], function (key, value) {
                return this[key] instanceof Date ?
                    'Date(' + this[key] + ')' : value;
            });
            // text is '["Date(---current time---)"]'


        JSON.parse(text, reviver)
            This method parses a JSON text to produce an object or array.
            It can throw a SyntaxError exception.

            The optional reviver parameter is a function that can filter and
            transform the results. It receives each of the keys and values,
            and its return value is used instead of the original value.
            If it returns what it received, then the structure is not modified.
            If it returns undefined then the member is deleted.

            Example:

            // Parse the text. Values that look like ISO date strings will
            // be converted to Date objects.

            myData = JSON.parse(text, function (key, value) {
                var a;
                if (typeof value === 'string') {
                    a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
                    if (a) {
                        return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
                            +a[5], +a[6]));
                    }
                }
                return value;
            });

            myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
                var d;
                if (typeof value === 'string' &&
                        value.slice(0, 5) === 'Date(' &&
                        value.slice(-1) === ')') {
                    d = new Date(value.slice(5, -1));
                    if (d) {
                        return d;
                    }
                }
                return value;
            });


    This is a reference implementation. You are free to copy, modify, or
    redistribute.

    This code should be minified before deployment.
    See http://javascript.crockford.com/jsmin.html

    USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
    NOT CONTROL.
*/

/*jslint evil: true */

/*global JSON */

/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", call,
    charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes,
    getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length,
    parse, propertyIsEnumerable, prototype, push, replace, slice, stringify,
    test, toJSON, toString
*/

if (!this.JSON2) {

// Create a JSON object only if one does not already exist. We create the
// object in a closure to avoid creating global variables.

    JSON2 = function () {

        function f(n) {
            // Format integers to have at least two digits.
            return n < 10 ? '0' + n : n;
        }

        Date.prototype.toJSON = function (key) {

            return this.getUTCFullYear()   + '-' +
                 f(this.getUTCMonth() + 1) + '-' +
                 f(this.getUTCDate())      + 'T' +
                 f(this.getUTCHours())     + ':' +
                 f(this.getUTCMinutes())   + ':' +
                 f(this.getUTCSeconds())   + 'Z';
        };

        var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
            escapeable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
            gap,
            indent,
            meta = {    // table of character substitutions
                '\b': '\\b',
                '\t': '\\t',
                '\n': '\\n',
                '\f': '\\f',
                '\r': '\\r',
                '"' : '\\"',
                '\\': '\\\\'
            },
            rep;


        function quote(string) {

// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.

            escapeable.lastIndex = 0;
            return escapeable.test(string) ?
                '"' + string.replace(escapeable, function (a) {
                    var c = meta[a];
                    if (typeof c === 'string') {
                        return c;
                    }
                    return '\\u' + ('0000' +
                            (+(a.charCodeAt(0))).toString(16)).slice(-4);
                }) + '"' :
                '"' + string + '"';
        }


        function str(key, holder) {

// Produce a string from holder[key].

            var i,          // The loop counter.
                k,          // The member key.
                v,          // The member value.
                length,
                mind = gap,
                partial,
                value = holder[key];

// If the value has a toJSON method, call it to obtain a replacement value.

            if (value && typeof value === 'object' &&
                    typeof value.toJSON === 'function') {
                value = value.toJSON(key);
            }

// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.

            if (typeof rep === 'function') {
                value = rep.call(holder, key, value);
            }

// What happens next depends on the value's type.

            switch (typeof value) {
            case 'string':
                return quote(value);

            case 'number':

// JSON numbers must be finite. Encode non-finite numbers as null.

                return isFinite(value) ? String(value) : 'null';

            case 'boolean':
            case 'null':

// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.

                return String(value);

// If the type is 'object', we might be dealing with an object or an array or
// null.

            case 'object':

// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.

                if (!value) {
                    return 'null';
                }

// Make an array to hold the partial results of stringifying this object value.

                gap += indent;
                partial = [];

// If the object has a dontEnum length property, we'll treat it as an array.

                if (typeof value.length === 'number' &&
                        !(value.propertyIsEnumerable('length'))) {

// The object is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.

                    length = value.length;
                    for (i = 0; i < length; i += 1) {
                        partial[i] = str(i, value) || 'null';
                    }

// Join all of the elements together, separated with commas, and wrap them in
// brackets.

                    v = partial.length === 0 ? '[]' :
                        gap ? '[\n' + gap +
                                partial.join(',\n' + gap) + '\n' +
                                    mind + ']' :
                              '[' + partial.join(',') + ']';
                    gap = mind;
                    return v;
                }

// If the replacer is an array, use it to select the members to be stringified.

                if (rep && typeof rep === 'object') {
                    length = rep.length;
                    for (i = 0; i < length; i += 1) {
                        k = rep[i];
                        if (typeof k === 'string') {
                            v = str(k, value, rep);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                } else {

// Otherwise, iterate through all of the keys in the object.

                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = str(k, value, rep);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                }

// Join all of the member texts together, separated with commas,
// and wrap them in braces.

                v = partial.length === 0 ? '{}' :
                    gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                            mind + '}' : '{' + partial.join(',') + '}';
                gap = mind;
                return v;
            }
        }

// Return the JSON object containing the stringify and parse methods.

        return {
            stringify: function (value, replacer, space) {

// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.

                var i;
                gap = '';
                indent = '';

// If the space parameter is a number, make an indent string containing that
// many spaces.

                if (typeof space === 'number') {
                    for (i = 0; i < space; i += 1) {
                        indent += ' ';
                    }

// If the space parameter is a string, it will be used as the indent string.

                } else if (typeof space === 'string') {
                    indent = space;
                }

// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.

                rep = replacer;
                if (replacer && typeof replacer !== 'function' &&
                        (typeof replacer !== 'object' ||
                         typeof replacer.length !== 'number')) {
                    throw new Error('JSON.stringify');
                }

// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.

                return str('', {'': value});
            },


            parse: function (text, reviver) {

// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.

                var j;

                function walk(holder, key) {

// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.

                    var k, v, value = holder[key];
                    if (value && typeof value === 'object') {
                        for (k in value) {
                            if (Object.hasOwnProperty.call(value, k)) {
                                v = walk(value, k);
                                if (v !== undefined) {
                                    value[k] = v;
                                } else {
                                    delete value[k];
                                }
                            }
                        }
                    }
                    return reviver.call(holder, key, value);
                }


// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.

                cx.lastIndex = 0;
                if (cx.test(text)) {
                    text = text.replace(cx, function (a) {
                        return '\\u' + ('0000' +
                                (+(a.charCodeAt(0))).toString(16)).slice(-4);
                    });
                }

// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.

// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
				//added due to PHP bug.
				text = text.replace(/\\\\\\\\/g, '\\\\');
                if (/^[\],:{}\s]*$/.
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

                    j = eval('(' + text + ')');

// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.

                    return typeof reviver === 'function' ?
                        walk({'': j}, '') : j;
                }

// If the text is not JSON parseable, then a SyntaxError is thrown.

                throw new SyntaxError('JSON.parse');
            }
        };
    }();
    if(!this.JSON)
    {
    JSON=JSON2;
    }
}




//[PACKSEP]

/*
The tAJAX template
*/


/* base 64 encoding nodig voor de libary */
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="                                             ;
function isset(varname)  {
  if(typeof( window[ varname ] ) != "undefined") return true;
  else return false;
}
function encode64(input) {
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;
   

   do {
      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 + keyStr.charAt(enc1) + keyStr.charAt(enc2) +
         keyStr.charAt(enc3) + keyStr.charAt(enc4);
   } while (i < input.length);


   return output;
}
function decode64(inp)
{
var out = ""; //This is the output
var chr1, chr2, chr3 = ""; //These are the 3 decoded bytes
var enc1, enc2, enc3, enc4 = ""; //These are the 4 bytes to be decoded
var i = 0; //Position counter
// remove all characters that are not A-Z, a-z, 0-9, +, /, or =
var base64test = /[^A-Za-z0-9\+\/\=]/g;
if (base64test.exec(inp)) { //Do some error checking
alert("There were invalid base64 characters in the input text.\n" +
"Valid base64 characters are A-Z, a-z, 0-9, ?+?, ?/?, and ?=?\n" +
"Expect errors in decoding.");
}
inp = inp.replace(/[^A-Za-z0-9\+\/\=]/g, "");
do { //Here�s the decode loop.
//Grab 4 bytes of encoded content.
enc1 = keyStr.indexOf(inp.charAt(i++));
enc2 = keyStr.indexOf(inp.charAt(i++));
enc3 = keyStr.indexOf(inp.charAt(i++));
enc4 = keyStr.indexOf(inp.charAt(i++));
//Heres the decode part. There�s really only one way to do it.
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
//Start to output decoded content
out = out + String.fromCharCode(chr1);
if (enc3 != 64) {
out = out + String.fromCharCode(chr2);
}
if (enc4 != 64) {
out = out + String.fromCharCode(chr3);
}
//now clean out the variables used
chr1 = chr2 = chr3 = "";
enc1 = enc2 = enc3 = enc4 = "";
} while (i < inp.length); //finish off the loop
//Now return the decoded values.
return out;
}



/* wat hulp functietjes*/
function getFirstAncestorByClassName(target,className) {
    var parent = target;
    while (parent = parent.parentNode) {
        if (hasClassName(parent,className)) {
            return parent;
        }
    }
    return null;
}
/* een eval functie om de functie uit te voeren*/
function readyhandle(tclass)
{

  eval('t = '+tclass);

  t.ready();
}


var xhttppageencoding='';



function TAjax()
{
    this.Debug =0;
    this.Version ='1';
    this.xmlhttp=false;
    this.Sourcefile='empty.html';
    this.onReadyresponsecommand = 'this.doExecute(this.xmlhttp.responseText)';
    this.onFailresponsecommand = 'this.ReportFail(this.xmlhttp.responseText)';
    this.cn='';
    this.doctosend='';
   
    
    //if (!this.xmlhttp && typeof XMLHttpRequest!='undefined') {
      //  this.xmlhttp = new XMLHttpRequest();
    //}
    if (window.XMLHttpRequest) { // Non-IE browsers

      this.xmlhttp = new XMLHttpRequest();
      

  

    } else if (window.ActiveXObject) { // IE

      this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

     

    }
    // alert("text/html; charset="+this.getCharset()+"");
    
    
    
    
}
TAjax.prototype.getCharset = function()
{
	
	if(xhttppageencoding=='')
	{
	//head = window.document.firstChild.firstChild.innerHTML
	heads = document.getElementsByTagName('head');
	head = heads[0].innerHTML;
	start = head.indexOf('charset=')+8
	stop1 = head.indexOf('"', start)
	stop2 = head.indexOf('>', start)
	stop3 = head.indexOf("'", start)
	stop = head.length
	if (stop1 < stop && stop1 > 0) stop = stop1
	if (stop2 < stop && stop2 > 0) stop = stop2
	if (stop3 < stop && stop3 > 0) stop = stop3
	xhttppageencoding = head.substr(start, stop-start)
	
	}
	else
	{
	
	}
		return xhttppageencoding;
	
}

TAjax.prototype.doRequest = function()
{
 var url
 url = this.Sourcefile;
 //alert(this.cn+'->'+url);
 this.xmlhttp.open("GET", url,true);
 
 eval('this.xmlhttp.onreadystatechange= function() {\nreadyhandle(\''+this.cn+'\');\n }');

 this.xmlhttp.send(null);
 
}
TAjax.prototype.doPost = function()
{
 var url
 url = this.Sourcefile;
 //alert(this.cn+'->'+url);
 this.xmlhttp.open("POST", url,true);
 eval('this.xmlhttp.onreadystatechange= function() {\nreadyhandle(\''+this.cn+'\');\n }');
	
 this.xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset="+this.getCharset()); 
 
 this.xmlhttp.send(this.doctosend);
}

TAjax.prototype.ready = function()
{
  if (this.xmlhttp.readyState==4) {
  eval(this.onReadyresponsecommand);
  }
 }
TAjax.prototype.doExecute = function(source)
{
    eval(source);

}
TAjax.prototype.ReportFail = function(source)
{

    if(this.Debug==1)
    {
    alert('Request failed:'+this.xmlhttp.getAllResponseHeaders()+'\n===========\n'+source);
    }

}
function deleteresponse(nr)
{
	if(TA[nr].deleted!='yes')
	{
		delete(TA[nr].xmlhttp);
		TA[nr].deleted='yes';
	}
	
}
function getresponse(nr)
{
	
	if(typeof TA[nr]=='object')
	{
		TA[nr].doctosend='';
		if(typeof env== "undefined")
		{
			setTimeout('deleteresponse('+nr+')',2000);
		}
		return TA[nr].xmlhttp.responseText;
	}
	else
	{
		return '';
	}
	
	
}
function getresponsexml(nr)
{
	
	if(typeof TA[nr]=='object')
	{
		TA[nr].doctosend='';
		if(typeof env == "undefined")
		{	
			setTimeout('deleteresponse('+nr+')',2000);
		}
		return TA[nr].xmlhttp.responseXML;
	}
	else
	{
		return '';
	}
	
	
}




if(typeof loaderbar=='object'){loaderbar.loadedfile('ajax.js');}




//[PACKSEP]

/*
The tajax version 2.0

By John Bakker. me@johnbakker.name
Please ask me first before using this. its all work in progress
*/
function tajaxDefaultConfig()
{
	//Enable queueing (sorts requests according to weight)
	this.queing=true;
	this.autoabort=true;
	this.defaulttimeout=10;
	this.debugmode=false;
}
function tajaxDefaultCallConfig()
{
	this.method='GET';
	this.doc='';
	//the lighter the weight (negative numbers make them float, positive numbers makes them sink)
	this.weight=10;
	
	//the priority is used to boost it even though it is heavy.
	this.priority=0;
	//the call's priority is weight-priority
	this.onError='alert("error")';
	this.charset='UTF-8';
}

function tajax_container(cn,config)
{
	this.cn = cn;
	this.debugmessages = [];
	this.defaultconfig = new tajaxDefaultConfig;
	this.currentcalls = [];
	this.history = [];
	this.ajaxqueuea = [];
	this.ajaxqueueb = [];
	
	if(typeof config=='object')
	{
		this.config = config;
	}
	else
	{
		this.config = [];
	}
	
	for (var i in this.defaultconfig)
	{
		if(typeof this.config[i]=='undefined')
		{
			this.config[i] = this.defaultconfig[i];
		}
		
	}	
	
}

tajax_container.prototype.printdebugdata = function(out)
{
	if(typeof out=="undefined")
	{
		out ='ajaxdebugout';
	}
	var html = '';
	
	html+='<b>Debug output</b></br>';
	html+='<i>Queued items A:'+this.ajaxqueuea.length+'</i><br/>';
	for(var pq=0;pq<this.ajaxqueuea.length;pq++)
	{
		html+='<li>'+this.ajaxqueuea[pq].url+'</li>';	
	}
	html+='<i>Queued items B:'+this.ajaxqueueb.length+'</i><br/>';
	for(pq=0;pq<this.ajaxqueueb.length;pq++)
	{
		html+='<li>'+this.ajaxqueueb[pq].url+'</li>';	
	}	
	html+='<i>History:'+this.history.length+'</i><br/>';
	for(pq=0;pq<this.history.length;pq++)
	{
		html+='<li>'+this.history[pq].url+'</li>';	
	}		
	if(typeof this.currentcalls[0]!='object')
	{
		html+='<br/>feed A free';
	}
	else
	{
		html+='<br/>feed A busy';
	}
	if(typeof this.currentcalls[1]!='object')
	{
		html+='<br/>feed B free';
	}
	else
	{
		html+='<br/>feed B busy';
	}
	document.getElementById(out).innerHTML=html;
}
tajax_container.prototype.debug = function(text)
{
	this.debugmessages[this.debugmessages.length]= text;
	if(this.config.debugmode)
	{
		if(typeof this.config.debugout!='undefined')
		{
			document.getElementById(this.config.debugout).innerHTML+=text+'<br/>';
		}
		else
		{
			alert(text);
		}
	}
}

tajax_container.prototype.readyStateChangeA = function()
{
	_tajax.currentcalls[0].readyStateChange();
}
tajax_container.prototype.readyStateChangeB = function()
{
	_tajax.currentcalls[1].readyStateChange();
}
tajax_container.prototype.feedAReady = function()
{
	_tajax.feedReady('A');
}
tajax_container.prototype.feedBReady = function(feed)
{
	_tajax.feedReady('B');
}
tajax_container.prototype.feedReady = function(feed)
{
	
	

	var tmp =null;
	this.debug('feed ready'+feed);
	if(feed=="A")
	{
		tmp = this.currentcalls[0];
		this.currentcalls[0]='';
	}
	else
	{
		tmp = this.currentcalls[1];
		this.currentcalls[1]='';
	}
	
	var hcallnr = this.history.length;
	
	this.history[hcallnr]=tmp;
	if(typeof this.history[hcallnr].onFinish =='function')
	{
		this.history[hcallnr].onFinish(this.history[hcallnr].response);
	}
	
}
tajax_container.prototype.init = function()
{
	//interval starts every 200ms
	this.interval = setInterval(this.cn+".handleQueue()",200);
	
	
}
tajax_container.prototype.handleQueue = function()
{
	
	//check if there is a free space ... reorder the queue and add start a new request if possible.
	if(this.queuerunning)
	{
		return false;
	}
	this.queuerunning=true;
	afeedfree= false;
	bfeedfree= false;
	afeednext =-1;
	bfeednext = -1;
	bfeedbecameafeed = false;
	
	if(typeof this.currentcalls[0]!='object')
	{
		afeedfree= true;
	}
	if(typeof this.currentcalls[1]!='object')
	{
		bfeedfree= true;
	}
	lowestprir=false;
	for(tot=this.ajaxqueuea.length-1;tot>-1;tot--)
	{
		tprir = this.ajaxqueuea[tot].weight - this.ajaxqueuea[tot].priority;
		if(!lowestprir){lowestprir = tprir;afeednext=tot;}
		if(lowestprir>tprir)
		{
			lowestprir = tprir;
			afeednext=tot;
		}
	}
	lowestprir=false;
	for(tot=this.ajaxqueueb.length-1;tot>-1;tot--)
	{
		tprir = this.ajaxqueueb[tot].weight - this.ajaxqueueb[tot].priority;
		if(!lowestprir){lowestprir = tprir;bfeednext=tot;}
		if(lowestprir>tprir)
		{
			lowestprir = tprir;
			bfeednext=tot;
		}
	}
	
	
	/*		Now we got the next priority for each feed.		*/
	if(afeedfree)
	{
		if(afeednext>-1)
		{
			this.debug('starting the a feed with something from a queue ->'+afeednext);
			this.startafeed(this.ajaxqueuea[afeednext]);
			this.removefromqueuea(afeednext);
			this.debug('Queue length'+this.ajaxqueuea.length);
			
		}
		else
		{
			//this.debug('there is nothing in the A feed');
			
			if(bfeednext>-1)
			{
				bfeedbecameafeed=true;
				this.debug('starting the a feed with something from b queue ->'+bfeednext);
				this.startafeed(this.ajaxqueueb[bfeednext]);
				this.removefromqueueb(bfeednext);
				this.debug('Queue length'+this.ajaxqueueb.length);
			}
			else
			{
				
			//	this.debug('there is also nothing in the B feed so forget it');
			}

		}
		
	}
	if(bfeedfree)
	{
		if(!bfeedbecameafeed)
		{
			if(bfeednext>-1)
			{
				this.debug('starting the b feed with something from b queue ->'+bfeednext);
				this.startbfeed(this.ajaxqueueb[bfeednext]);
				this.removefromqueueb(bfeednext);
				this.debug('Queue length'+this.ajaxqueueb.length);
				
			}
			else
			{
				
			//	this.debug('nothing in b feed');
			}

		}
		else
		{

		}
	}
	this.queuerunning=false;

}

tajax_container.prototype.startafeed = function(call)
{
	
	this.currentcalls[0]=call;
	this.currentcalls[0].feed=0;
	this.currentcalls[0].doCall();
}

tajax_container.prototype.startbfeed = function(call)
{
	
	this.currentcalls[1]=call;
	this.currentcalls[1].feed=1;
	this.currentcalls[1].doCall();
}
tajax_container.prototype.removefromqueuea = function(queueaid)
{
	newar = [];
	for(hh=0;hh<this.ajaxqueuea.length;hh++)
	{
		if(hh!=queueaid)
		{
			newar[newar.length]=this.ajaxqueuea[hh];
		}
	}
	
	this.ajaxqueuea=newar;
}
tajax_container.prototype.removefromqueueb = function(queuebid)
{
	newar = [];
	for(hh=0;hh<this.ajaxqueueb.length;hh++)
	{
		if(hh!=queuebid)
		{
			newar[newar.length]=this.ajaxqueueb[hh];
		}
	}
	
	this.ajaxqueueb=newar;
}

tajax_container.prototype.makeCall = function(url,config)
{
	var tajaxcall  = new tAjaxCall(this,url,config);
	
	var lna=this.ajaxqueuea.length;
	var lnb=this.ajaxqueueb.length;
	var tprir = tajaxcall.weight - tajaxcall.priority;
	
	if(tprir<0)
	{
		this.ajaxqueuea[lna]=tajaxcall;
		this.debug('added to A queue'+url+ ' with priority'+tprir );
		this.debug('length of A queue is now '+this.ajaxqueueb.length);
	}
	else
	{
		this.ajaxqueueb[lnb]=tajaxcall;
		this.debug('added to B queue'+url+ ' with priority'+tprir );
		this.debug('length of B queue is now '+this.ajaxqueueb.length);
	}
}


function tAjaxCall(parent,url,config)
{
	this.parent= parent;
	this.url = url;
	this.defaultconfig = new tajaxDefaultCallConfig();
	if(typeof config=='object')
	{
		this.config = config;
	}
	else
	{
		this.config = [];
	}	
	for (var i in this.defaultconfig)
	{
		if(typeof this.config[i]=='undefined')
		{
			this.config[i] = this.defaultconfig[i];
		}
		
	}	
	this.parent.debug('recieved Call config');
	this.onFinish = this.config.onFinish;
	this.onAbort = this.config.onAbort;
	this.onFailure = this.config.onFailure;
	this.weight = this.config.weight;
	this.priority = this.config.priority;
	
}
tAjaxCall.prototype.readyStateChange = function()
{
	
	if (this.xmlhttp.readyState==4) {
  		this.parent.debug('done!');
		this.response= {xml:this.xmlhttp.responseXML,text:this.xmlhttp.responseText,url:this.url,config:this.config};
		if(this.feed==0)
		{
			this.parent.feedAReady();
		}
		else
		{
			this.parent.feedBReady();
		}
		
  	}
}
	

tAjaxCall.prototype.abort = function()
{
	this.onAbort();
}

tAjaxCall.prototype.doCall = function()
{
    if (window.XMLHttpRequest) 
    { // Non-IE browsers
      this.xmlhttp = new XMLHttpRequest();
    } 
    else if (window.ActiveXObject) 
    { // IE
      this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
	if (window.XMLHttpRequest) { // Non-IE browsers
      this.xmlhttp = new XMLHttpRequest();
    } else if (window.ActiveXObject) { // IE

	  	try {
	    	this.xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
	    }
	  	catch (e) {
	    	this.xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	    }
     

    }
    if(this.feed==0)
    {
   		this.xmlhttp.onreadystatechange=_tajax.readyStateChangeA;
    }
    else
    {
      	this.xmlhttp.onreadystatechange=_tajax.readyStateChangeB;
    }
    
    if(this.config.method=='GET')
    {
 		this.xmlhttp.open("GET", this.url,true);
    }
    else
    {
    	
    	this.xmlhttp.open("POST", this.url,true);
    	this.xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset="+this.config.charset);
    }
    var d = new Date();
    this.started = d.getTime();
    this.xmlhttp.send(this.config.doc);
}






_tajax = new tajax_container('_tajax',{debugmode:false,autoabort:true});
_tajax.init();


//[PACKSEP]

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera",
			versionSearch: "Version"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();



//[PACKSEP]

/** 
====================================================================================================
   	timagelib
    Copyright (C) 2012 John Bakker <me@johnbakker.name>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
===================================================================================================
 */

 window.requestAnimFrame = (function(){
      return  window.requestAnimationFrame       || 
              window.webkitRequestAnimationFrame || 
              window.mozRequestAnimationFrame    || 
              window.oRequestAnimationFrame      || 
              window.msRequestAnimationFrame     || 
              function(/* function */ callback, /* DOMElement */ element){
                window.setTimeout(callback, 1000 / 60);
              };
    })();



function _Tiv(){
	this.i = {
		canvas:false,
		imagecanvas:false,
		image:false,
		parentc:false,
		mask:false,
		loadedImage:false,
		loadedMask:false,
		canvasmoved:false,
		reloading:false,
		toolMode:'dragCanvas',
		
		//Basic config which is called in "initialize"
		baseconfig:{
						type:'normal',
						image:'timged/images/blocks.png',
						width:'parent',
						backgroundimage:'timged/images/blocks.png',
						loadingimage:'timged/images/loading.gif',
						height:'parent',
						autoCenter:true,
						autoScaleH:true
				},
		updateImage:function(newsrc)
		{
			this.config.image = newsrc;
			this.hasLoadedImage=false;
			this.reloading=true;
			this.image = new Image();
			this.image.onload = this.onloadf;
			
			this.image.src= this.config.image;
			
			var t = this;
			t.a.style.backgroundImage="url('"+this.config.loadingimage+"')";
			t.a.style.backgroundPosition="center";
			
			t.a.style.backgroundRepeat="no-repeat";			
		},
		rescale:function()
		{
			var ca = this.c;

			if(!ca)
			{
				return false;
			}
			clearTimeout(this.to); 
			ca.style.display="none";
			
			this.to= setTimeout("timg.i('"+this.id+"').i.rescaleDone()",10);
		},
		rescaleDone:function()
		{
			var t= this;
			var ca = this.c;
			
			var c = this.config;
			if(c.height=='parent')
			{
				
				ca.style.height = t.a.offsetHeight+'px';
				ca.height = t.a.offsetHeight;
				
			}
			if(c.width=='parent')
			{
				ca.style.width = t.a.offsetWidth+'px';
				ca.width = t.a.offsetWidth;
			}	
			//
			this.updateOffset();
			ca.style.display="block";
			this.hasChanged=true;	
		},
		updateOffset:function()
		{
			if(this.config.autoCenter )
			{
				//okay so calculate the left
				if(!this.canvasmoved)
				{
					
					this.canvasoffsetX=Math.floor((this.c.width/2)-(this.actualW/2));
					this.canvasoffsetY=Math.floor((this.c.height/2)-(this.actualH/2));
				 }

			}
		},
		isActive:function()
		{
			try
			{
				var tmpparent = timg._(this.parentid);
				if(typeof tmpparent.innerHTML == "undefined")
				{
					return false;
				}
				else
				{
					return true;
				}
			}
			catch(e)
			{
				
				return false;	
			}
			
		},
		initialize:function(parentclass,parent,id,config)
		{
			this.pos=0;
			this.canvasoffsetX=0;
			this.canvasoffsetY=0;	
			this.parentclass = parentclass;		
			this.parentid= parent;
			var t = this;
			
			if(typeof parent =='string')
			{
				parent = timg._(parent);
			}
			t.a=parent;
			t.id=id;
			t.initialConfig= config;
			t.config = {};
			for(var b in this.baseconfig)
			{
				this.config[b] = this.baseconfig[b];
			}
			for(var c in config)
			{

				this.config[c]=config[c];
	
			}
			
			var c = this.config;
			
			//create canvas!
			t.imagec = document.createElement('canvas');
			ctx1 = t.imagec.getContext('2d');
			t.c = document.createElement('canvas');
			var ca = this.c;
			ctx2 = t.c.getContext('2d');
			ctx1.scale(1,1);
			ctx2.scale(1,1);
			
			t.a.style.backgroundImage="url('"+this.config.loadingimage+"')";
			//t.a.style.backgroundAttachment;
			t.a.style.backgroundPosition="center";
			
			t.a.style.backgroundRepeat="no-repeat";
			
			if(c.height=='parent')
			{
				ca.style.height = t.a.offsetHeight+'px';
				ca.height = t.a.offsetHeight;
			}
			if(c.width=='parent')
			{
				ca.style.width = t.a.offsetWidth+'px';
				ca.width = t.a.offsetWidth;
			}

			t.a.appendChild(ca);
			
			
			
			
			
			t.image = new Image();
			var onloadfsrc = 'this.onloadf = function(){return timg.i("'+this.id+'").i.loadedImage()}';
			eval(onloadfsrc);
			
			
			t.image.onload = this.onloadf;
			t.image.src= c.image;

			if(typeof this.config.mask!="undefined")
			{
				eval('var onloadf = function(){return timg.i("'+this.id+'").i.loadedMask()}');
				t.mask = new Image();
				t.mask.onload = onloadf;
				t.mask.src= c.mask;
			}
			eval('var funcUp = function(e){return timg.i("'+this.id+'").i.onMup(e);}');
			eval('var funcDown = function(e){return timg.i("'+this.id+'").i.onMdown(e);}');
			this.c.onmouseup=funcUp;
			this.c.onmouseout=funcUp;
			this.c.onmousedown=funcDown;			
					
			
		},
		onMoveCanvas:function(e)
		{
			this.moveendPoint=[e.pageX,e.pageY];
			
			var diffX= this.moveendPoint[0]-this.movestartpoint[0];
			var diffY= this.moveendPoint[1]-this.movestartpoint[1];
			
			if(this.toolMode=='dragCanvas')
			{
				this.canvasoffsetX = this.origCanvasOffset[0]+diffX;
				this.canvasoffsetY = this.origCanvasOffset[1]+diffY;
				this.canvasmoved=true;
			}			
		},
		onMdown:function(e)
		{
			
			if(this.toolMode=='dragCanvas'||this.toolMode=='dragLayer')
			{
				eval('var func = function(e){return timg.i("'+this.id+'").i.onMoveCanvas(e);}');
				if(this.toolMode=='dragCanvas')
				{		
					this.canvasmoved=true;
					
					this.origCanvasOffset= [this.canvasoffsetX,this.canvasoffsetY];
				}


				this.movestartpoint=[e.pageX,e.pageY];
				this.c.onmousemove =func;
				this.dragging=true;
			}
		},
		onMup:function(e)
		{
			if(this.toolMode=='dragCanvas'||this.toolMode=='dragLayer')
			{
				this.dragging=false;
				this.c.onmousemove =null;
				this.movestartpoint=null;
			}
		},
		loadedImage:function()
		{
			this.hasLoadedImage=true;
			this.reloading=false;
			this.checkmoreloading();
		},
		checkmoreloading:function()
		{
			if(this.mask)
			{
				if(!this.loadedMask)
				{
					//still needs a mask loaded!
					return true;
				}
			}
			if(this.image)
			{
				if(!this.hasLoadedImage)
				{
					return true;
				}
			}
			
			//we're done
			this.initializeRender();
		},
		initializeRender:function()
		{
			var t= this;
			this.hasChanged=true;
			this.reloading=false;
			var c = this.imagec;
			var ctx =c.getContext('2d');
			this.actualW=this.image.width;
			this.actualH=this.image.height;
			
			c.width=this.image.width;
			c.height=this.image.height;
			ctx.scale(1,1);
			ctx.drawImage(this.image,0,0);
			
			t.a.style.backgroundImage="url("+this.config.backgroundimage+")";

			
			t.a.style.backgroundRepeat="repeat";
			//now initialise the ondraw thing
			this.rescaleDone();
			eval('this.renderfunc = function(){return timg.i("'+this.id+'").i.render();}');
			window.requestAnimFrame(this.renderfunc,this.c);			
		},
		
		needsReRender:function()
		{
			
			if(this.dragging)
			{
				return true;
			}
			if(this.hasChanged)
			{
				return true;
			}
		},
		calculatescale:function()
		{
			var w = this.imagec.width;
			var h = this.imagec.height;
			
			var o=0;
			if(this.config.autoScaleH)
			{
				o = this.c.height/h;
				
				h = Math.floor(h*o);
				w= Math.floor(w*o); 
			}
			else if(This.config.autoScaleW)
			{
				
			}
			
			
			return {w:w,h:h};
		},
		render:function()
		{
			if(!this.needsReRender())
			{
				window.requestAnimFrame(this.renderfunc,c);
				return true;
			}			

				
			this.ctx = this.c.getContext('2d');
			var c = this.c;
			this.ctx.clearRect(0,0,c.width,c.height);
			if(this.reloading)
			{
				return false;
			}			
			var w = this.imagec.width;
			var h = this.imagec.height;
			if(this.config.autoScaleH || this.config.autoScaleW)
			{
				var wh = this.calculatescale();
				w = wh.w;
				h = wh.h;
				this.actualW=w;
				this.actualH=h;
				this.updateOffset();
			}
			this.ctx.drawImage(this.imagec,this.canvasoffsetX,this.canvasoffsetY,w,h);
			this.hasChanged=false;
			if(!this.reloading)
			{
				window.requestAnimFrame(this.renderfunc,c);
			}
			else
			{
				
			}
		},

		addFilter:function(filter,params)
		{
			
		},
		createCanvas:function(parent,id)
		{
			
		},
		destroy:function()
		{
			//clean up any attached events and all subcanvasses.
			this.cleanUp();
		}
	};
}
function timgDisplay(parent,id,config)
{
	this.config =config;
	
	this._Tiv = _Tiv;
	
	this._Tiv();

	this.i.initialize(this,parent,id,config);

}


var timg ={
	initted:false,
	haltrenders:false,
	imgs:{},
	kickrescale:function(e)
	{
		this.needsrescale=true;
		clearTimeout(this.to);
		
		//wait a second to cool off..
		this.haltrenders=true;
		this.to = setTimeout("timg.rescale()",100);
	},
	
	rescale:function()
	{
		clearTimeout(this.to);
		
		var tc= false;
		for(var im in this.imgs)
		{
			tc = this.imgs[im].i.config;
			
			
			if((tc.width=='parent')||(tc.height=='parent'))
			{
				
				this.imgs[im].i.rescale();
			}
		}
	},
	
	ae:function(el,on,func)
	{
		if (el.addEventListener) 
		{ 
			el.addEventListener (on, func, false);
		}
		else 
		{
			if (el.attachEvent) 
			{
				//for ie pre 9    
				el.attachEvent ("on"+on, func);
			}
		}
	},
	init:function()
	{
		if(this.initted)
		{
			return false;
		}
		this.initted=true;
		this.ae(window,'resize',function(e){timg.kickrescale();});
	},
	_:function(id)
	{
		return document.getElementById(id);
	},
	i:function(id)
	{
		if(typeof this.imgs[id] !='undefined')
		{
			return this.imgs[id];
		}
	},
	
	addImage:function(parent,id,config)
	{
		this.init();
		if(typeof this.imgs[id]!='undefined')
		{
			delete this.imgs[id];
		}
		this.imgs[id] = new timgDisplay(parent,id,config);
	},
	destroyImage:function(id)
	{
		if(typeof this.img[id] !='undefined')
		{
			this.img[id].destroy();
		}
		delete this.img[id];
	}
}


//[PACKSEP]

function dimensions()
{
	
}

dimensions.prototype._getElementHeight = function(elem)
{
	var h;
	h = elem.scrollHeight;
	return h;
	if (this.isOpera) { 
		h = elem.style.pixelHeight;
	} else {
		h = elem.offsetHeight;
	}
	return h;
}
dimensions.prototype._getElementWidth = function(elem)
{
	var w;

	w = elem.scrollWidth;
	return w;
	if (this.isOpera) {
		w = elem.style.pixelWidth;
	} else {
		w = elem.offsetWidth;
	}
	return w;


}
dimensions.prototype.getPageOffsetLeft = function(el){
var x;x=el.offsetLeft;
if(el.offsetParent!=null)x+=this.getPageOffsetLeft(el.offsetParent);
return x;
}
dimensions.prototype.getPageOffsetTop = function(el){
	var y;y=el.offsetTop;
if(el.offsetParent!=null)y+=this.getPageOffsetTop(el.offsetParent);
return y;
}

dimensions.prototype.dimensions = function(el)
{

var dim = {};
dim.x = this.getPageOffsetLeft(el);
dim.y = this.getPageOffsetTop(el);
dim.w = this._getElementWidth(el);
dim.h = this._getElementHeight(el);
return dim;


}
function viewportinfo()
{
	
} 
viewportinfo.prototype.pageHeight = function()
{
	var docHeight;
	if (typeof document.height != 'undefined') {
	docHeight = document.height;

	
	}
	else if (document.compatMode && document.compatMode != 'BackCompat') {
	docHeight = document.documentElement.scrollHeight;
       
         	
	}
	else if (document.body && typeof document.body.scrollHeight !=
	'undefined') {
	docHeight = document.body.scrollHeight;
	}
	return docHeight;
}
viewportinfo.prototype.pageWidth = function()
{
	var docWidth;
	if (typeof document.Width != 'undefined') {
	docWidth = document.Width;

	
	}
	else if (document.compatMode && document.compatMode != 'BackCompat') {
	docWidth = document.documentElement.scrollWidth;
       
         	
	}
	else if (document.body && typeof document.body.scrollWidth !='undefined') {
	docWidth = document.body.scrollWidth;
	}
	return docWidth;
}
viewportinfo.prototype.getPageSizeWithScroll = function(){
	if (window.innerHeight && window.scrollMaxY) {// Firefox
		yWithScroll = window.innerHeight + window.scrollMaxY;
		xWithScroll = window.innerWidth + window.scrollMaxX;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		yWithScroll = document.body.scrollHeight;
		xWithScroll = document.body.scrollWidth;
	} else { // works in Explorer 6 Strict, Mozilla (not FF) and Safari
		yWithScroll = document.body.offsetHeight;
		xWithScroll = document.body.offsetWidth;
  	}
	arrayPageSizeWithScroll = new Array(xWithScroll,yWithScroll);
	//alert( 'The height is ' + yWithScroll + ' and the width is ' + xWithScroll );
	return arrayPageSizeWithScroll;
}

viewportinfo.prototype.getviewportsize = function()
{
	
	
	
 var viewportwidth;
 var viewportheight;
 var pagesizewithscroll = this.getPageSizeWithScroll(); 
 var viewprt = {};  
		
 var docwidth = pagesizewithscroll[0];
 var docheight = pagesizewithscroll[1];		
 
 if (typeof window.innerWidth != 'undefined')
 {
      viewportwidth = window.innerWidth;
      viewportheight = window.innerHeight;

 }
 else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0)
 {
       viewportwidth = document.documentElement.clientWidth;
       viewportheight = document.documentElement.clientHeight;

 }
 else
 {
       viewportwidth = document.getElementsByTagName('body')[0].clientWidth;
       viewportheight = document.getElementsByTagName('body')[0].clientHeight;
 }
 viewprt = {};
 viewprt.width=viewportwidth;
 viewprt.height=viewportheight;
 if(docheight<viewportheight)
 {
 	docheight = viewportheight;
 }
 viewprt.docheight=docheight;
 if(docwidth<viewportwidth)
 { 
 	docwidth = viewportwidth;
 }
 viewprt.docwidth=docwidth;

  
 return viewprt;
}








//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.org
//
viewportinfo.prototype.getPageScroll = function()
{

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}



//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
viewportinfo.prototype.getPageSize = function()
{
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

var _vp = new viewportinfo(); 




if(typeof loaderbar=='object'){loaderbar.loadedfile('dimensions.js');}


//[PACKSEP]



function md3debug(cn)
{
	this.cn = cn;
	this.messages			= {};
	this.messages.forms		= [];
	this.messages.treeview	= [];
	this.messages.other		= [];
	this.output				='debugoutputbox';
}
md3debug.prototype.send = function(from,type,message)
{
	
}
md3debug.prototype.printelem = function(type,elem,subelem,outelem)
{
	var out = '';
	if(type=='form')
	{
		document.getElementById('md3debug_elementprint').value = JSON.stringify(puntforms.forms[elem].elements[subelem]);
		document.getElementById('md3debug_elementprint').style.display='block';
	}
	else if(type=='list')
	{
		out +='<i><u><b>config</b></u></i><br/>';
		for (var i in md3lists.lists[elem].config)
		{
			out += '<b>'+i+'</b>:'+md3lists.lists[elem].config[i]+'<br/>';
		}
		out +='<i><u><b>sort</b></u></i><br/>';
		for (var i in md3lists.lists[elem].sort)
		{
			out += '<b>'+i+'</b>:'+md3lists.lists[elem].sort[i]+'<br/>';
		}		
		document.getElementById(outelem).innerHTML=out;		
	}
}
md3debug.prototype.show = function(elem)
{
	document.getElementById(elem).style.display='block';
}
md3debug.prototype.refresh = function()
{
	var html ='';
	html+= '<textarea id="md3debug_elementprint" style="display:none;font-size:10px;width:100%;height:100px;border:1px dashed green;"></textarea>';
	html+= '<div style="text-align:left;"><b>elements:</b><br/>';
	
	var tmpobj;
	html+='<div id="'+this.output+'_forms_clicker" style="font-size:9px;text-decoration:underline;cursor:pointer;" onclick="_md3debug.show(\''+this.output+'_forms_output\')">Forms</div>';
	html+='<div id="'+this.output+'_forms_output" style="font-size:9px;margin-left:5px;border-left:1px dashed black;display:none;">';
	var htmla='';
	var htmlb='';
	var thtml='';
	var available=false;
	for(var fo=0;fo<puntforms.forms.length;fo++)
	{
		//check if it exists:
		tmpobj = document.getElementById(puntforms.forms[fo].formid+'_formcheckelement');
		try
		{
			//it exists!
			if(typeof tmpobj.src!='undefined')
			{
				available=true;
			}
			else
			{
				available=false;
			}
		}
		catch(e)
		{
			//doesn't exist
			available=false;
			
		}
		thtml ='<div><b>'+puntforms.forms[fo].formid_sub+'<span onclick="_md3debug.show(\'debugdata_'+puntforms.forms[fo].formid+'\')" style="text-decoration:underline;cursor:pointer;">(open)</span></b><br/>';
		thtml+='<div id="debugdata_'+puntforms.forms[fo].formid+'" style="display:none;"><ul>';
		for(var fa=0;fa<puntforms.forms[fo].elements.length;fa++)
		{
			thtml+="<li><span onclick=\"_md3debug.printelem('form',"+fo+","+fa+")\" style='text-decoration:underline'>("+puntforms.forms[fo].elements[fa].itemtype+")"+puntforms.forms[fo].elements[fa].itemname+'</span></li>';
		}

		thtml+='</ul></div>';	
		thtml+='</div>';	
		if(available)
		{
			htmla+=thtml;
		}
		else
		{
			htmlb+=thtml;
		}
		
	}
	
	html+='<b>Existing forms:</b><hr>'+htmla;
	html+='<br/><b>Old forms:</b><hr>'+htmlb;
	html+='</div>';
	
	
	html+='<div id="'+this.output+'_lists_clicker" style="font-size:9px;text-decoration:underline;cursor:pointer;" onclick="_md3debug.show(\''+this.output+'_lists_output\')">Lists</div>';
	html+='<div id="'+this.output+'_lists_output" style="font-size:9px;margin-left:5px;border-left:1px dashed black;display:none;"><ul>';
	var lnr=0;
	for(lnr=0;lnr<md3lists.lists.length;lnr++)
	{
		html+="<li><span onclick=\"_md3debug.printelem('list',"+lnr+",0,'md3debug_list_config_"+lnr+"')\" style='text-decoration:underline;cursor:pointer;'>"+md3lists.lists[lnr].name+':'+md3lists.lists[lnr].config.type+"("+md3lists.lists[lnr].config.totalrows+")"+'</span><br/><span id="md3debug_list_config_'+lnr+'"></span></li>';
	}
	html+='</ul></div>';	
	

	
	//the end
	html+='</div>';	
	document.getElementById(this.output).innerHTML=html;
}

var _md3debug = new md3debug('_md3debug');



//[PACKSEP]



function print_r(variable,returnMe)
{
	if(typeof returnMe=='undefined')
	{
		returnMe=false;
	}
	if(returnMe)
	{
		return JSON2.stringify(variable);
	}
	else
	{
		alert(JSON2.stringify(variable));
	}
}



/* NODIG VOOR XML COMPATIBILITY MET IE6 en IE7*/


function stripenter(value) {
	val = value.split('\n');
	value = val.join('');
	return value ;
}
function trim(value) {
  value = value.replace(/^\s+/,'');
  value = value.replace(/\s+$/,'');
  return value;
}


/*
Punt2 interface Engine.

Door:JBA
info: Webdev@punt.nl

uses XSLT
*/

logging = true;
xsltdebug = true;
//de construct
var pi_statustimeout,pi_overlayertimeout;
var puntInterface_xsl=[];
var nr=0;
var TA = [];
var reloadcd;
var statuscd;
var foldout =0;
var foldout2 =0;
var loaded_notifications = [];


function jsGC()
{
       var bSaf = (navigator.userAgent.indexOf('Safari') != -1);
       var bOpera = (navigator.userAgent.indexOf('Opera') != -1);
       var bMoz = (navigator.appName == 'Netscape');	
	var html_doc = document.getElementsByTagName('head').item(0); 
	var scripts = html_doc.getElementsByTagName('script');
	var txt='';
	var pos=0;
	var parts='';
	var itemid;
	var st;
	for(var o=0;o<scripts.length;o++)
	{
	   st =scripts.item(o);
       if (bSaf) {
               txt = st.innerHTML;
       } else if (bOpera) {
               txt = st.text;
       } else if (bMoz) {
               txt = st.textContent;
       } else {
               txt = st.text;
       }		

		pos = txt.indexOf('/*JSGC::');
		if(pos>-1)
		{
			parts = txt.split('/*JSGC::',2);
			parts= parts[1].split('*/',2);
			if(document.getElementById(parts[0]))
			{
				if (typeof console != 'undefined') 
				{
				//	console.log('NOTGC', parts[0]);
				}
				continue;
			}
			else
			{
				//cleanup;
				html_doc.removeChild(scripts.item(o));
				if (typeof console != 'undefined') 
				{
				//	console.log('GC', parts[0]);
				}
			}
			
		}
	}
}
setInterval('jsGC();',10000);
function execJS(node) {
/*

Deze functie is gescreven door Kratorius
http://kratcode.wordpress.com/2006/02/23/javascript-script-execution-in-innerhtml/

*/

       var bSaf = (navigator.userAgent.indexOf('Safari') != -1);
	   var bChrome = (navigator.userAgent.indexOf('Chrome') != -1);
       var bOpera = (navigator.userAgent.indexOf('Opera') != -1);
       var bMoz = (navigator.appName == 'Netscape');
	   var bIE = (navigator.appName == 'MSIE');

var st = node.getElementsByTagName('script');

       var strExec;


for(var i=0;i<st.length; i++) {
var tmpsrc='';
               if (bSaf) {
                       strExec = st[i].innerHTML;
               } else if (bOpera) {
                       strExec = st[i].text;
               } else if (bMoz ||bChrome) {
                       strExec = st[i].textContent;
					   
               } else {
                       strExec = st[i].text;
					  // eval(strExec);
					
					   
               }
               tmpsrc= st[i].getAttribute('src');
               if(tmpsrc==null)
               {
               	 tmpsrc='';
               }
				try {
				
				if(strExec.indexOf('/*JSEV*/')>-1)
				{
					eval(strExec);
					/*if(typeof console !='undefined')
					{
						//console.log('exec',strExec);
					}*/
				}
				else
				{
				var html_doc = document.getElementsByTagName('head').item(0);
			    var js = document.createElement('script');
			    
   				js.setAttribute('language', 'javascript');
    			js.setAttribute('type', 'text/javascript');
    			js.text = strExec;
    			if(tmpsrc!='')
    			{
					js.setAttribute('src',tmpsrc);
				}
				html_doc.appendChild(js);
					
				}
			
						
						continue;				
				
				
			

               } catch(e) {


                       alert('execjs'+e.getMessage());
               }
       }
}



if(typeof loaderbar=='object'){loaderbar.loadedfile('main.js');}



//[PACKSEP]


var scalersizes = [];

tmpscale = {};
tmpscale.biggerthan=1280;
tmpscale.targetwidth=1200;
tmpscale.sidespacing='%';
tmpscale.showfullscreen=true;
scalersizes[scalersizes.length] = tmpscale;

tmpscale = {};
tmpscale.smallerthan=1000;
tmpscale.targetwidth='%';
tmpscale.sidespacing=0;
tmpscale.showfullscreen=false;
scalersizes[scalersizes.length]=tmpscale;

tmpscale = {};
tmpscale.isdefault=true;
tmpscale.targetwidth='%';
tmpscale.sidespacing=13;
tmpscale.showfullscreen=false;
scalersizes[scalersizes.length]=tmpscale;

var fullscreensize = tmpscale;


//[PACKSEP]

function punt_api(cn)
{
	this.cn = cn;
	this.msgboxes = [];
	this.widgets = [];
	this.hooks = [];
	this.timers = [];
	this.mydrag = [];
	this.totalWROteller=0;
	this.uplform=0;
	this.reporter=0;
	this.messagelist=[];
	this.stepspeed=10;
	this.icon1sizex=90;
	this.icon1sizex=80;
	this.icon2sizex=45;
	this.icon2sizey=40;
	this.actionButtons = [];
	this.actionButtons2 = [];
	this.actionButtontarget = 'main';
	this.defaulttarget='';
	this.debug=false;
	this.currentlang='';
	this.currentlangtags='';
	this.autoupdatelangtags=0;
	this.openchanges=false;
	this.keepNotificationsForTrip=0;
	this.isFullScreen=false;
	this.includeAlternativeTargets=false;
}
punt_api.prototype.selectLocaleDialog = function()
{
	puntdialog.startdialog('adminoverview','selectLocale','','');
}
punt_api.prototype.checkUnsavedChanges=function()
{
	var unsaved=false;
	
	
	if(typeof FUM!='undefined')
	{
		if(FUM.uploadIsHappening())
		{
			if(!unsaved)
			{
				unsaved ='';
			}
			else
			{
				unsaved +=',';
			}

			unsaved += 'global_still_uploading';
		}
	}
	return unsaved;
}
punt_api.prototype.attachEvent = function(element,ev,func)
{
	if(window.addEventListener){ // Mozilla, Netscape, Firefox
		element.addEventListener(ev, func, false);
	} else { // IE
		element.attachEvent('on'+ev, func);
	}

}
punt_api.prototype.befunload=function()
{
	var response ='';
	if (response = puntapi.checkUnsavedChanges()) {
		return response;
	}
	else
	{
		//return null;
	}
}
punt_api.prototype.rescale = function(e)
{
	//first rescale all wysiwyg editors
	
	puntforms.rescalestart();
	
	try{_lb.rescale();}catch(e){}//try to rescale or forget it 
	puntapi.redrawPositions();
	if(typeof FUM!='undefined')
	{
		FUM.rescale();
	}
	if (typeof _tW !='undefined') 
	{
		_tW.rescale();
	}
	puntforms.rescaledone();
	timg.rescale();
	
}
punt_api.prototype.toggleAlternativeTargets =function()
{
	if(this.includeAlternativeTargets)
	{
		this.includeAlternativeTargets=false;
	}
	else
	{
		this.includeAlternativeTargets=true;
	}
}
punt_api.prototype.saveLanguageWidgetdoneEXT = function (msg)
{
	var msgtxt = msg.text.split('^');
	var msgtxt2 = msgtxt[0].split('#');
	
	if(msgtxt[1]=='ok')
	{
		//its okay!
		var color='green';
		var displ='none';
	}
	else
	{
		var color='red';
		var displ='block';
		
	}
		var ltags2 =this.currentlangtags.split('/');
		var ltags =ltags2[1].split(',');	

		for(var lnr=0;lnr<ltags.length;lnr++)
		{		
			if(ltags[lnr]==msgtxt2[0])
			{
				puntapi._("langtagEXT_"+lnr+"_textclicker").style.color=color;
				puntapi._("langtagEXT_"+lnr+"_textcontainer").style.display=displ;
				puntapi._("langtagEXT_"+lnr+"_error").style.color=color;
				puntapi._("langtagEXT_"+lnr+"_error").innerHTML=msgtxt2[1];
				
			}
		}	
	
}
punt_api.prototype.saveLanguageWidgetdone = function (msg)
{
	var msgtxt = msg.text.split('^');
	var msgtxt2 = msgtxt[0].split('#');
	
	if(msgtxt[1]=='ok')
	{
		//its okay!
		var color='green';
		var displ='none';
	}
	else
	{
		var color='red';
		var displ='block';
		
	}
		var ltags2 =this.currentlangtags.split('/');
		var ltags =ltags2[0].split(',');	

		for(var lnr=0;lnr<ltags.length;lnr++)
		{		
			if(ltags[lnr]==msgtxt2[0])
			{
				puntapi._("langtag_"+lnr+"_textclicker").style.color=color;
				puntapi._("langtag_"+lnr+"_textcontainer").style.display=displ;
				puntapi._("langtag_"+lnr+"_error").style.color=color;
				puntapi._("langtag_"+lnr+"_error").innerHTML=msgtxt2[1];
				
			}
		}	
	
}
punt_api.prototype.saveLanguageWidget = function ()
{
	if(typeof basepath =='undefined')
	{
		var bpbasepath='/Admin';
	}
	else
	{
		var bpbasepath=basepath;
	}
	
	
	
	var ltags2 =this.currentlangtags.split('/');
	var ltags =ltags2[0].split(',');	
	var tmpdoc='';
	for(var lnr=0;lnr<ltags.length;lnr++)
	{
		if(ltags[lnr]!='')
		{
		tmpdoc='';
		tmpdoc='locale='+encodeURIComponent(this.currentlang);
		tmpdoc+='&tag='+encodeURIComponent(ltags[lnr]);
		tmpdoc+='&text='+encodeURIComponent(puntapi._('langtag_'+lnr+'_text').value);
		//alert(tmpdoc);
		_tajax.makeCall(basepath+'/API/languageeditor/writelocale',{method:'post',onFinish:function(resp){puntapi.saveLanguageWidgetdone(resp);},doc:tmpdoc,weight:10});
		}
	}
	
}
punt_api.prototype.printLanguageWidget = function ()
{
	this.autoupdatelangtags=1;
	var html='';
	var ltags2 =this.currentlangtags.split('/');
	var ltags =ltags2[0].split(',');
	
	html+= "<div style='text-align:left'><ul>";
	for(var lnr=0;lnr<ltags.length;lnr++)
	{
		if(ltags[lnr]!='')
		{
		html+= "<li><span id='langtag_"+lnr+"_textclicker' onclick=\"puntapi._('langtag_"+lnr+"_textcontainer').style.display='block';\">"+ltags[lnr]+"</span><div id='langtag_"+lnr+"_error' ></div><div id='langtag_"+lnr+"_textcontainer' style='display:none'><textarea id='langtag_"+lnr+"_text'></textarea></div></li>";
		}
	}
	html+= "</ul></div>";
	puntapi._('languageoutputbox').innerHTML=html;
}
punt_api.prototype.saveLanguageWidgetExistingChanged = function()
{
	var ltags2 =this.currentlangtags.split('/');
	var ltags =ltags2[1].split(',');
	
	if(!this.loadedTags)
	{
		return false;
	}
	var changedTags = [];
	for (var lnr = 0; lnr < ltags.length; lnr++) 
	{
		textelem = this._('langtagext_'+lnr+'_text');
		container = this._('langtagEXT_'+lnr+'_textcontainer');
		textelem2 = this._('langtagext_'+lnr+'_original');
		if(textelem.value!='')
		{
			if (textelem.value != textelem2.value) 
			{
				changedTags[changedTags.length] = {
					tagname: ltags[lnr],
					value: textelem.value,
					nr: lnr
				};
			}
			else 
			{
			
			}
		}
		else
		{
			puntapi._("langtagEXT_" + lnr + "_error").innerHTML = "This cannot be empty!";
		}
	}
	//console.log(changedTags);
	var ct={};
	for(var uu=0;uu<changedTags.length;uu++)
	{
		ct = changedTags[uu];
		tmpdoc='';
		tmpdoc='locale='+encodeURIComponent(this.currentlang);
		tmpdoc+='&tag='+encodeURIComponent(ct.tagname);
		tmpdoc+='&text='+encodeURIComponent(ct.value);
	
		_tajax.makeCall(basepath+'/API/languageeditor/writelocale',{method:'post',onFinish:function(resp){puntapi.saveLanguageWidgetdoneEXT(resp);},doc:tmpdoc,weight:10});
	 
		
	}
	

}
punt_api.prototype.loadLanguageTagExisting = function (tags)
{
	var tmpdoc='';	

		tmpdoc='locale='+encodeURIComponent(this.currentlang);
		tmpdoc+='&tags='+encodeURIComponent(tags);

	_tajax.makeCall(basepath+'/API/languageeditor/getTagValue',{method:'post',onFinish:function(resp){puntapi.loadLanguageTagsDone(resp);},doc:tmpdoc,weight:10});
}
punt_api.prototype.loadLanguageTagsDone = function(resp)
{
	var tmpdoc = resp.xml;
	var tags = tmpdoc.getElementsByTagName('tag');
	var totaltags = tags.length;
	var tagel='';
	var taglnr=0;
	var tagname='';
	var tagtext='';
	var textelem;
	var textelem2;
	var container;
	
	for(var oo=0;oo<totaltags;oo++)
	{
		tagel = tags.item(oo);
		textelem = this._('langtagext_'+tagel.getAttribute('id')+'_text');
		container = this._('langtagEXT_'+tagel.getAttribute('id')+'_textcontainer');
		textelem2 = this._('langtagext_'+tagel.getAttribute('id')+'_original');
		textelem.value=  tagel.getElementsByTagName('tagvalue').item(0).firstChild.nodeValue;
		textelem2.value=textelem.value;
		
		
	}
	this.loadedTags=true;
}
punt_api.prototype.printLanguageWidgetExisting = function ()
{
	this.loadedTags=false;
	//this.autoupdatelangtags=1;
	var html='';
	var ltags2 =this.currentlangtags.split('/');
	var ltags =ltags2[1].split(',');
	
	html+= "<div style='text-align:left'><ul>";
	for(var lnr=0;lnr<ltags.length;lnr++)
	{
		if(ltags[lnr]!='')
		{
		html+= "<div class='edittag_row'><span id='langtagEXT_"+lnr+"_textclicker' onclick=\"puntapi._('langtagEXT_"+lnr+"_textcontainer').style.display='block';\">"+ltags[lnr]+"</span><div id='langtagEXT_"+lnr+"_error' ></div>";
		html+= "<div id='langtagEXT_"+lnr+"_textcontainer' style='display:none'><textarea id='langtagext_"+lnr+"_text'></textarea></div>";
		html+= "<div id='langtagEXT_"+lnr+"_textcontainer2' style='display:none'><textarea id='langtagext_"+lnr+"_original'></textarea></div>";
		html+= "</div>";
		}
	}
	html+= "</ul></div>";
	this.loadLanguageTagExisting(ltags);
	puntapi._('languageoutputboxext').innerHTML=html;
}
punt_api.prototype.changeDefaultTarget = function (target)
{
	this.defaulttarget=target;
}

punt_api.prototype.changeActionbuttonTarget = function(target)
{
	this.actionButtontarget = target;
	
}
punt_api.prototype.touchActionbutton = function(id)
{
	
}
punt_api.prototype.startDownload = function(url)
{
	
}
punt_api.prototype.defineActionButton = function(id,title,icon,application,command,query,target,customscript)
{
	
}
punt_api.prototype.actionButtonHtml = function(title,icon,application,command,id,query,target,customscript)
{
	//adds an icon
	
	var bonclick = customscript;

	if((bonclick=='')||(typeof bonclick=='undefined'))
	{
		if(this.actionButtontarget =='dialog')
		{
			bonclick = 'puntdialog.changecommand(\''+application+'\',\''+command+'\',\''+id+'\',\''+query+'\')';
		}
		else
		{
			bonclick = this.cn+'.DoCommand(\''+application+'\',\''+command+'\',\''+id+'\',\''+query+'\',\'\',\'\',\''+target+'\')';
		}
		
	}

	html2 = _tT.parse('actionbutton_small_onclick',{title:title,icon:icon,onclick:bonclick});
	return html2;
	
}
punt_api.prototype.changehost = function(hostname)
{
	//window.location=hostname;
	
}

punt_api.prototype.findArrayElement = function(arr,name)
{
	for(var ay=0;ay<arr.length;ay++)
	{
		if(arr[ay].name==name)
		{
			return ay;
		}
	}
	return -1;
}

punt_api.prototype.delayedOnload = function()
{
	this.hidemainout();

	
}
punt_api.prototype.redrawActionButtons = function()
{
	var uy=-1;
	var outelements=[];
	if(this.actionButtontarget=='dialog')
	{
		target ='dialogactionbuttons';
		abbb = this.actionButtons2;
	}
	else
	{
		target ='PagetitleIconbox';	
		abbb = this.actionButtons;
	}
	
	for(tt=0;tt<abbb.length;tt++)
	{
		if(typeof abbb[tt].doubleposition!='undefined')
		{
			//check if allready exists....
			uy=this.findArrayElement(outelements,abbb[tt].doubleposition);
			if(uy==-1)
			{
				ulen = outelements.length;
				outelements[ulen] = [];
				outelements[ulen].name= abbb[tt].doubleposition;
				outelements[ulen].html= '<table  cellspacing="0" cellpadding="0" ><tr>';
			}
			else
			{
				//
			}
			
		}
	}
	
	html = '<table cellspacing="0" cellpadding="0" ><tr>';
	var hasbuttons=false;
	for(tt=0;tt<abbb.length;tt++)
	{
		if(typeof abbb[tt].doubleposition!='undefined')
		{
			
			uy=this.findArrayElement(outelements,abbb[tt].doubleposition);
			outelements[uy].html+='<td>&nbsp;</td><td>'+abbb[tt].html+'</td>';
			
		}
		else
		{
			html+='<td>&nbsp;</td><td>'+abbb[tt].html+'</td>';
			hasbuttons=true;
		}
		
	}
	
	html += '</tr></table>';
	for(tt=0;tt<outelements.length;tt++)
	{

			puntapi._(outelements[tt].name).innerHTML = outelements[tt].html + '</tr></table>';
	}
	//trigger the errorbox!
	//target+='RR';
	puntapi._(target).innerHTML =html;
	if (hasbuttons) 
	{
		puntapi._(target).style.display = 'block';
	}
	else 
	{
		puntapi._(target).style.display = 'none';
	}
}

punt_api.prototype.appendActionButton = function(title,icon,application,command,id,query,target,customscript)
{
	if(this.actionButtontarget=='dialog')
	{
		newpos=this.actionButtons2.length;
		this.actionButtons2[newpos]= new Array()
		this.actionButtons2[newpos].html =   this.actionButtonHtml(title,icon,application,command,id,query,target,customscript);
		this.redrawActionButtons();
	}
	else
	{
		newpos=this.actionButtons.length;
		this.actionButtons[newpos]= new Array()
		this.actionButtons[newpos].html =   this.actionButtonHtml(title,icon,application,command,id,query,target,customscript);
		this.redrawActionButtons();		
	}
}
punt_api.prototype.addActionButton = function(title,icon,application,command,id,query,target,customscript,doubleposition)
{
	var yy;
	var nab;
	nab= [];
	newpos=0;
	
	
	if(this.actionButtontarget=='dialog')
	{
		
		abbb = this.actionButtons2;
	}
	else
	{
		abbb = this.actionButtons;
	}
	
		
		nab[newpos]= new Array()
		nab[newpos].html =   this.actionButtonHtml(title,icon,application,command,id,query,target,customscript);
		nab[newpos].doubleposition= doubleposition;
		for(yy=1;yy<abbb.length+1;yy++)
		{
			nab[yy]=abbb[yy-1];
			
		}
	if(this.actionButtontarget=='dialog')
	{
		this.actionButtons2=nab;
	}
	else
	{
		this.actionButtons=nab;
	}
	
	
	this.redrawActionButtons();
}

punt_api.prototype.resetActionButtons = function()
{
	if(this.actionButtontarget=='dialog')
	{
		this.actionButtons2 = [];
	}
	else
	{
		this.actionButtons = [];
	}
	
}
punt_api.prototype.createActionButtons = function(elem,target)
{

	
	
	html = '';
	
	newactionButtons = [];
	
	
	try
	{	
		abuttons = elem.getElementsByTagName('actionbutton');
		for(tt=0;tt<abuttons.length;tt++)
		{
			
			title =''; try{title = abuttons.item(tt).getElementsByTagName('description').item(0).firstChild.nodeValue;}catch(e){}
			id =''; try{id = abuttons.item(tt).getElementsByTagName('id').item(0).firstChild.nodeValue;}catch(e){}
			query =''; try{query = abuttons.item(tt).getElementsByTagName('query').item(0).firstChild.nodeValue;}catch(e){}
			customjs =''; try{customjs = abuttons.item(tt).getElementsByTagName('customjs').item(0).firstChild.nodeValue;}catch(e){}
			customscript=customjs;
			newpos = newactionButtons.length;
			newactionButtons[newpos]= new Array()
			newactionButtons[newpos].html =  this.actionButtonHtml(title,abuttons.item(tt).getAttribute('icon'),abuttons.item(tt).getAttribute('application'),abuttons.item(tt).getAttribute('command'),id,query,abuttons.item(tt).getAttribute('target'),customscript)
		}
	
	}
	catch(e)
	{
		//whoa there it sploded...
	
	}
	if(this.actionButtontarget=='dialog')
	{
		this.actionButtons2 = newactionButtons;
	}
	else
	{
		this.actionButtons = newactionButtons;
	}
	//puntapi._(target).innerHTML =html;
	this.redrawActionButtons();
	
}
punt_api.prototype.uirefresh = function()
{
	bp = basepath.split('/');
	
	

	this.getmenu(bp[1]);
}
punt_api.prototype.triggerhook = function(hook,msg)
{
		hookcommands = this.hooks[hook].split('|');
		
		for(i=0;i<hookcommands.length;i++)
		{
			
		}
}

punt_api.prototype.pageHeight = function()
{
	var docHeight;
	if (typeof document.height != 'undefined') {
	docHeight = document.height;

	
	}
	else if (document.compatMode && document.compatMode != 'BackCompat') {
	docHeight = document.documentElement.scrollHeight;
       
         	
	}
	else if (document.body && typeof document.body.scrollHeight !=
	'undefined') {
	docHeight = document.body.scrollHeight;
	}
	return docHeight;
}


punt_api.prototype.getviewportsize = function()
{
 var viewportwidth;
 var viewportheight;
 
 
 var dh = this.pageHeight();
 if (typeof window.innerWidth != 'undefined')
 {
      viewportwidth = window.innerWidth;
      viewportheight = window.innerHeight;

 }
 else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0)
 {
       viewportwidth = document.documentElement.clientWidth;
       viewportheight = document.documentElement.clientHeight;

 }
 else
 {
       viewportwidth = document.getElementsByTagName('body')[0].clientWidth;
       viewportheight = document.getElementsByTagName('body')[0].clientHeight;
 }
 viewprt = [];
 viewprt.width=viewportwidth;
 viewprt.height=viewportheight;
 if(dh<viewportheight)
 {
 	dh = viewportheight;
 }
 viewprt.docheight=dh;
 
 return viewprt;
}
punt_api.prototype.newMessagebox = function(title,data,onok,width,nook)
{
	var msgboxlayer = puntapi._('msgboxlayer');
	
	max = this.msgboxes.length+1;
	
	var div_new = document.createElement('div');
	div_new.setAttribute('id', 'msgbox_'+max);
	div_new.setAttribute('class', 'punt_msgbox_wrapper');
	
	if(typeof width!='undefined')
	{
		if(width!='')
		{
		if(typeof width!='number')
		{
			if(width.indexOf('%')>0)
			{
			
			}
			else
			{
				width+='px';
			}
		}
		else
		{
				width = width+'px';
		}
		div_new.setAttribute('style', 'width:'+width+';');
		}
	}
	else
	{
		width='';
	}
	
	
	msg = '<div class="punt_msgbox" >';
	msg += '<div class="punt_msgbox_head" style="text-align:right;">'+title+'&nbsp; &nbsp;&nbsp;&nbsp;<span style="cursor:pointer;" onclick="'+this.cn+'.closeMsgbox('+max+');">X</span>&nbsp;&nbsp;</div>';
	msg += data;
	msg +='<center>';
	if(nook!='yes')
	{
		msg +='<input type="button" onclick="'+this.cn+'.closeMsgbox('+max+');'+onok+'" value="ok">';
	}
	msg +='</center>';
	msg += '<div class="punt_msgbox_footer" style="text-align:right;">'+title+'&nbsp; &nbsp;&nbsp;&nbsp;<span style="cursor:pointer;" onclick="'+this.cn+'.closeMsgbox('+max+');">X</span></div>';	
	msg +='</div>';
	div_new.innerHTML =msg;
	msgboxlayer.appendChild(div_new);
    this.mydrag[max] = new Draggable('msgbox_'+max,{})

 

}
punt_api.prototype.writeToMessagebox = function(id,data)
{
	msgboxid= 'msgbox_'+id;
	msg = '<div class="punt_msgbox" >';
	msg += '<div class="punt_msgbox_head" style="text-align:right;">'+title+'&nbsp; &nbsp;&nbsp;&nbsp;<span style="cursor:pointer;" onclick="'+this.cn+'.closeMsgbox('+max+');">X</span></div>';
	msg += data;
	msg += '<div class="punt_msgbox_footer" style="text-align:right;">'+title+'&nbsp; &nbsp;&nbsp;&nbsp;<span style="cursor:pointer;" onclick="'+this.cn+'.closeMsgbox('+max+');">X</span></div>';	
	msg +='<center>';
	puntapi._(msgboxid).innerHTML=msg;	
}
punt_api.prototype.uploadBox = function(formid,formfield)
{
	this.uplform++;
	data = '<form method="POST" enctype="multipart/form-data" method="post" action="'+basepath+'/filemanager/douploadfile" target="'+formid+'_'+formfield+'_'+(this.msgboxes.length+1)+'_formupload" onSubmit="'+this.cn+'.startUploadSequence();">';
	data +='<br/>';
	data += '<input type="hidden" name="uplerdid" value="'+(this.msgboxes.length+1)+'"/>';
	data += '<input type="hidden" name="formid" value="'+formid+'"/>';
	data += '<input type="hidden" name="formfield" value="'+formfield+'"/>';
	data += '<input type="file" name="p2upload"/><br/>';
	data +='<br/>';
	data += '<input type="submit" name="submit" value="Submit">';
	data +='<br/>';
	data +='<br/>';
	data += '</form>';
	data += '<iframe name="'+formid+'_'+formfield+'_'+(this.msgboxes.length+1)+'_formupload" id="'+formid+'_'+formfield+'_'+(this.msgboxes.length+1)+'_formupload" style="width:200px;height:200px;display:none;">';
	data += '</iframe>';	
	this.newMessagebox('Upload file',data,'',300,'yes');
}
punt_api.prototype.reportform = function()
{
	this.reporter++;
	data = '<div style="text-align:left;padding-left:15px;" class="reportbox"><form>';
	data +='<br/>';
	data += 'Report type:<br/><select id="reporttype'+this.reporter+'"><option value="bug" selected>An error occurred</option><option value="feature">Want a new feature</option></select><br/>';
	data += 'Short description:<br/><input type="text" name="report" id="reportbox'+this.reporter+'"/><br/>';
	data += 'Describe the problem of feature:<br/><textarea name="reporttext" id="reporttext'+this.reporter+'"></textarea><br/>';
	data +='<br/>';
	data += '<input type="button" name="submit" value="Send report" onclick="puntapi.report(\'reporttype'+this.reporter+'\',\'reportbox'+this.reporter+'\',\'reporttext'+this.reporter+'\','+(this.msgboxes.length+1)+')">';
	data +='<br/>';
	data +='<br/>';
	data += '</form></div>';	
	closeid = this.newMessagebox('Report a problem or request a feature',data,'',300,'yes');
}
punt_api.prototype.report = function(typeid,titleid,textid,msgbox)
{
	title = puntapi._(titleid).value;
	type = puntapi._(typeid).value;
	text = puntapi._(textid).value;
	//rawdata = dump(puntapi);
	//rawdata2 = dump(TA);
	
	rawdata = '=====REPORT=====\n';
	rawdata +='window.location:\n'+window.location+'\n';
	
	rawdata +='ajax calls:\n'
	for(u=1;u<nr;u++)
	{
		try
		{
			rawdata +=u+':'+TA[u].Sourcefile+'\n';
		}
		catch(e)
		{
			
		}
	}



	doc = 'title='+encodeURIComponent(title);
	doc += '&text='+encodeURIComponent(text);
	doc += '&rawdata='+encodeURIComponent(rawdata);
	
	//doc += '&rawdata2='+escape(rawdata2);
	nr++
	TA[nr] = new TAjax();
	TA[nr].cn = 'TA['+nr+']';

	TA[nr].Sourcefile= basepath+'/adminoverview/report/'+type+'?AJAX_REQ=yes';
	TA[nr].doctosend = doc;
	//TA[nr].onReadyresponsecommand = this.cn+'.closeMsgbox('+msgbox+')';
	TA[nr].onReadyresponsecommand = this.cn+'.reportsent(getresponse('+nr+'),'+msgbox+')';
	this.writeToMessagebox(msgbox,'Sending data...');
	TA[nr].doPost();	
	

}


punt_api.prototype.reportsent = function(response,msgbox)
{
	
	msg = "Report sent. You will soon be able to see updates of your reports in the main menu under bug reports.<br/><span>Report ID:"+response+"</span><br/><input type=\"button\" onclick=\""+this.cn+".closeMsgbox("+msgbox+");\" value=\"Close this box\"/>";
	this.writeToMessagebox(msgbox,msg);
}
punt_api.prototype.endUploadSequence = function(nr,formid,formfield,id,filenr)
{
	puntapi._(formid+'_'+formfield).value +='^$'+escape(id)+'|'+escape(filenr);
	
	this.filelistRepaint(formid,formfield);
	this.closeMsgbox(nr);
}
punt_api.prototype.filelistRepaint = function(formid,formfield)
{
	html = '';
	data = puntapi._(formid+'_'+formfield).value;
	
	data2 = data.split('^$');
	if(data2.length>0)
	{
		for(u=1;u<data2.length;u++)
		{
			data3=data2[u].split('|');
			
			html +='<div>'+data3[1]+'</div>\n';
		}
		
	}
	puntapi._(formid+'_'+formfield+'_filelist').innerHTML=html;
	
}
punt_api.prototype.startUploadSequence = function(nr)
{
	
}
punt_api.prototype.closeMsgbox = function(nr)
{
	this.mydrag[nr].destroy();
	var  msgboxlayer = puntapi._('msgboxlayer');
	msgboxlayer.removeChild(puntapi._('msgbox_'+nr));
}


punt_api.prototype.registerTimers = function(timers)
{

	total = timers.length;
	for(i=0;i<total;i++)
	{
		mx = this.timers.length;
		this.timers[mx]=timers[i];
		this.runTime(mx);
		 
	}	
}
punt_api.prototype.checkForced = function()
{
	d1 = new Date();
	rand = d1.getTime();
	nr++
	TA[nr] = new TAjax();
	TA[nr].cn = 'TA['+nr+']';

	TA[nr].Sourcefile= basepath+'/API/adminoverview/Notifications?AJAX_REQ=yes&randomizer='+rand;

	TA[nr].onReadyresponsecommand = this.cn+'.checkforceddone(getresponse('+nr+'))';
	TA[nr].doPost();
}
punt_api.prototype.hasreadforced = function(nrs)
{
	nr++
	TA[nr] = new TAjax();
	TA[nr].cn = 'TA['+nr+']';

	TA[nr].Sourcefile= basepath+'/API/adminoverview/Notificationread/'+nrs+'?AJAX_REQ=yes';

	TA[nr].onReadyresponsecommand = '';
	TA[nr].doPost();	
}
punt_api.prototype.debugscreen = function()
{
	//show debug screen
	strt = '<div class="dialogbox" style="padding:20px;font-size:11px;font-family:courier;"><b>ajax requests:></b><br/>';
	for(o=0;o<nr+1;o++)
	{
		try
		{
			strt += '-> '+o+'- <span class="clickable" onclick="'+this.cn+'.debugshowrequest('+o+');">'+TA[o].Sourcefile.substring(0,70)+'</span><br/>';
		}
		catch(e)
		{
		}
	}
	strt +='</div>';
	this.setlightbox(strt);	
}
punt_api.prototype.debugshowrequest = function(reqnr)
{
	strt = '<div class="dialogbox" style="padding:20px;font-size:11px;font-family:courier;"><span class="clickable" onclick="'+this.cn+'.debugscreen('+o+');" style="color:darkgreen;font-size:26px;">back to debugscreen</span><br/><b>Request '+reqnr+':<br/>'+TA[reqnr].Sourcefile+'</b><br/><textarea style="width:90%;height:40%;font-size:11px;font-family:courier;">';
	strtxt = TA[reqnr].xmlhttp.responseText
	
	strt+=  strtxt.replace(/\"/,'&quot;');
	strt +='</textarea></div>';
	this.setlightbox(strt);		
}


punt_api.prototype.checkforceddone = function(data2)
{

	list = data2.split('[SEPP]');
	for(i=0;i<list.length;i++)
	{
		
		split2 = list[i].split('[PPES]');
		
		if(split2[0]=='wizard')
		{
			onok=this.cn+".hasreadforced("+split2[1]+")";
			wizard.loadwizard(split2[2],onok,'yes');
		}
		else if(split2[0]=='logout')
		{
			title = 'Notification';
		
			data = unescape(split2[2]);
	
			width=400;
			
			nook=false;
			this.addAlert(title,data,true,5);
			this.hasreadforced(split2[1]);
			setTimeout(this.cn+".DoCommand('adminoverview','logout','','','','');",5000);
			
		}		
		else if(split2[0]=='msgbox')
		{
		title = 'Notification';
		
		data = unescape(split2[2]);
	
		width=400;
		onok=this.cn+".hasreadforced("+split2[1]+")";
		nook=false;
		//this.newMessagebox(title,data,onok,width,nook);
		this.addNotification(title,data,true);
		this.hasreadforced(split2[1]);
		
		}
		else if(split2[0]=='alertbox')
		{
		title = 'Notification';
		
		data = unescape(split2[2]);
	
		width=400;
		onok=this.cn+".hasreadforced("+split2[1]+")";
		nook=false;
		//this.newMessagebox(title,data,onok,width,nook);
		this.addAlert(title,data,true);
		this.hasreadforced(split2[1]);
		
		}		
	}
	setTimeout(this.cn+".checkForced()",60000);

}

punt_api.prototype.runTime = function(id)
{
	
	var widgetlayer = puntapi._('widgetlayer');
	data = this.timers[id];
	timeout= data[0];
	command= data[1];
   	
	eval(command);
	setTimeout(this.cn+'.runTime('+id+')',timeout);
}



/*
for filemanager:
*/



punt_api.prototype.fman_editfile = function(path,file)
{
	this.DoCommand('filemanager','editfile',file,'path='+path+file);
}
punt_api.prototype.fman_setpath = function(path,file,w,h)
{
	
	path = path+file;
	path = document.location.protocol+'//'+document.domain+path;
	puntapi._('fileman_selectedfile').value=path;
	puntapi._('fman_imagew').value=w;
	puntapi._('fman_imageh').value=h;
	this.fman_pathchange(path);
}

punt_api.prototype.fman_pathchange = function(path)
{
	imageext= [];
	imageext[0]='mbp';
	imageext[1]='jpg';
	imageext[2]='png';
	imageext[3]='gif';
	imageext[4]='jpeg';
	splitted = path.split('.');
	extension = splitted[splitted.length-1];
	//check if its an image
	
	if(!this.fman_validateextention(imageext,extension))
	{
		//is an image
		
		this.fman_toggleimagesettings('off');
		this.fman_togglefilesettings('on');		
	}
	else
	{
		//not an image
		
		this.fman_toggleimagesettings('on');
		this.fman_togglefilesettings('off');
		
	}
	
	
}
punt_api.prototype.fman_validateextention = function(extensions,extension)
{
	for(o=0;o<extensions.length;o++)
	{
		
		if(extensions[o]==extension)
		{
			return true;
		}
		else
		{
			
		}
		
	}
	return false;
}

punt_api.prototype.fman_toggleimagesettings = function(val)
{
	if(val=='off')
	{
		display='none';
	}
	else
	{
		display="block";
	}
	
	puntapi._('fman_imagesettings').style.display=display;
}
punt_api.prototype.fman_togglefilesettings = function(val)
{
	if(val=='off')
	{
		display='none';
	}
	else
	{
		display="block";
	}
	
	puntapi._('fman_filesettings').style.display=display;
}
punt_api.prototype.adminZoneDataReciever = function(app,what,value)
{
	
	
	if(app=='wsp')
	{
		this._('zone_stats_'+app+'_'+what+'1').innerHTML=value.text.split('/')[0];
		this._('zone_stats_'+app+'_'+what+'2').innerHTML=value.text.split('/')[1];
		//this._('zone_stats_'+app+'_'+what+'3').innerHTML=value.text.split('/')[1];
		
	}
	else
	{
		this._('zone_stats_'+app+'_'+what).innerHTML=parseInt(value.text);
	}
}
punt_api.prototype.adminZoneDataLoader = function()
{
	this._('hostname').innerHTML = "<a href='http://" + window.location.hostname + "' target='wspnewwindow' style='text-decoration:none'>" + window.location.hostname + "</a>";
	if (this._('adminzone_output_topright').innerHTML == '') {
		
		var html = "<table border='0' id='wspstats'><tr>";

		html += "<td align='right'><a class='clickable' onclick=\"puntapi.DoCommand('content','','','','')\">Articles</a>:&nbsp;</td>";
		html += "<td align='right'><span id='zone_stats_content_total' class='admintoprightvalue'>loading</span></td>";
		html += "<td>&nbsp;</td>";
		html += "<td align='right'><a class='clickable' onclick=\"puntapi.DoCommand('mediaalbum','','','','')\">Albums</a>:&nbsp;</td>";
		html += "<td align='right'><span id='zone_stats_mediaalbum_total' class='admintoprightvalue'>loading</span></td>";
		html += "<td>&nbsp;</td>";		

		html += "<td align='right'><a class='clickable' onclick=\"puntapi.DoCommand('filemanager','','','','')\">space used</a>:&nbsp;</td>";
		html += "<td align='right'><span id='zone_stats_wsp_diskUsage1' class='admintoprightvalue'>loading</span></td>";
		html += "<td>&nbsp;</td>";		
		html += "</tr>";
		html += "<tr>";
		html += "<td></td><td></td>";

		//html += "<td align='right'><a class='clickable' onclick=\"puntapi.DoCommand('comment','listComments','spam','','')\">spam</a>:&nbsp;</td>";
		//html += "<td align='right'><span id='zone_stats_comment_spam' class='admintoprightvalue'>loading</span></td>";
		html += "<td>&nbsp;</td>";
		html += "<td align='right'><a class='clickable' onclick=\"puntapi.DoCommand('comment','','','','')\">comments</a>:&nbsp;</td>";
		html += "<td align='right'><span id='zone_stats_comment_total' class='admintoprightvalue'>loading</span></td>";
		html += "<td>&nbsp;</td>";
		html += "<td align='right'><a class='clickable' onclick=\"puntapi.DoCommand('filemanager','','','','')\">space left</a>:&nbsp;</td>";
		html += "<td align='right'><span id='zone_stats_wsp_diskUsage2' class='admintoprightvalue'>loading</span></td>";
		html += "<td>&nbsp;</td>";
		html += "</tr>";
		html += "</table>";
		this._('adminzone_output_topright').innerHTML = html;
	}
	
	var func1 = function(response){
		puntapi.adminZoneDataReciever('comment','total',response);
	}
	_tajax.makeCall(basepath+'/API/comment/getstats/total',{method:'POST',onFinish:func1});
	/*var func2 = function(response){
		puntapi.adminZoneDataReciever('comment','spam',response);
	}
	_tajax.makeCall(basepath+'/API/comment/getstats/spam',{method:'POST',onFinish:func2});*/	
	var func3 = function(response){
		puntapi.adminZoneDataReciever('content','total',response);
	}
	_tajax.makeCall(basepath+'/API/content/getstats/total',{method:'POST',onFinish:func3});	
	var func4 = function(response){
		puntapi.adminZoneDataReciever('mediaalbum','total',response);
	}
	_tajax.makeCall(basepath+'/API/mediaalbum/getstats/total',{method:'POST',onFinish:func4});
	var func5 = function(response){
		puntapi.adminZoneDataReciever('wsp','diskUsage',response);
	}
	_tajax.makeCall(basepath+'/API/wsp/diskUsage',{method:'POST',onFinish:func5});	
	var timeout = 1000* 60 *5;	
	if (!this.intervaladminzonedataloader) 
	{
		this.intervaladminzonedataloader = setInterval('puntapi.adminZoneDataLoader();', timeout);
	}


}
punt_api.prototype.sendForm = function(formname,url,formelements)
{
	doctosend= '';
}

punt_api.prototype.updateSystembox = function()
{
	
	nr++
	TA[nr] = new TAjax();
	TA[nr].cn = 'TA['+nr+']';

	TA[nr].Sourcefile= basepath+'/API/messenger/messages?AJAX_REQ=yes';

	TA[nr].onReadyresponsecommand = this.cn+'.updateSystembox_Write(getresponse('+nr+'),getresponsexml('+nr+'))';
	TA[nr].doPost();	
	
}
punt_api.prototype.updateSystembox_Write = function(msg,message)
{
	
	try
	{
	var root = message.getElementsByTagName('messages').item(0);
 	totaalmessages=0;
 	messagelist = [];
	 	if(root)
		{
			
			messages = root.getElementsByTagName('message');
			
			for(o=0;o<messages.length;o++)
			{
				ttitlevalue = messages[o].getElementsByTagName('title').item(0).firstChild.nodeValue;
				ttextvalue 	= messages[o].getElementsByTagName('data').item(0).firstChild.nodeValue;
				msgid 		= messages[o].getAttribute('msgid');
				msgtype 	= messages[o].getAttribute('type');
				messagelist[totaalmessages]= [];
				messagelist[totaalmessages].titlevalue=ttitlevalue;
				messagelist[totaalmessages].textvalue=ttextvalue;
				messagelist[totaalmessages].msgid=msgid;
				messagelist[totaalmessages].msgtype=msgtype;
	
				totaalmessages++;
			}
			
			html ='';
			if(totaalmessages>0)
			{
				html+='<div class="imlist">';	
				alternator = 'a';
				for(u=0;u<totaalmessages;u++)
				{
					html += '<div class="imbox'+messagelist[u].msgtype+'_top" >&nbsp;</div><div class="imbox'+messagelist[u].msgtype+'" id="imboxid_'+messagelist[u].msgid+'" onclick="'+this.cn+'.opensystemmessage('+u+')">&nbsp;&nbsp;'+messagelist[u].titlevalue+'</div><div class="imbox'+messagelist[u].msgtype+'_bottom" >&nbsp;</div>';
				}
				html+='</table>';
			}
			
			
			puntapi._('systemmessagebox').innerHTML=html;
			//now check for new messages and make them blink;
			
			this.checknewmessages(messagelist);
			
			
			this.messagelist = messagelist;
			
			
		}
		else
		{
			
		}
	}
	catch(e)
	{
		
	}
	setTimeout(this.cn+'.updateSystembox();',60000);
}

punt_api.prototype.checknewmessages = function(messagelist)
{
	//this.blink('imbox'+messagelist[u].msgtype);
	try
	{
		for(o=0;o<messagelist.length;o++)
		{
			try
			{
				
				if(this.findmessageid(messagelist[o].msgid)!=-1)
				{
					
				}
				else
				{
					this.blinkmessagetitle('imboxid_'+messagelist[o].msgid,40,100,0);
				}
				
			}
			catch(e)
			{
				
			}
						
		}
	}
	catch(e)
	{
		
	}
	
}
punt_api.prototype.findmessageid = function(msgid)
{
	for(i=0;i<this.messagelist.length;i++)
	{
		try
		{
			if(this.messagelist[i].msgid==msgid)
			{
				return i;
			}
		}
		catch(e)
		{
			
		}
	}
	return -1;
}
punt_api.prototype.opensystemmessage = function(idnr)
{
	if(messagelist[idnr].msgtype=='DEVERRORREPORT')
	{
		//get the message and display the results in a docommand!
		this.DoCommand('messenger','readdebugmessage',messagelist[idnr].textvalue);
	}
	else if(messagelist[idnr].msgtype=="ERRORREPORT_USER")
	{
		this.DoCommand('adminoverview','viewreport',messagelist[idnr].msgid);
	}
	else
	{
		this.newMessagebox(messagelist[idnr].titlevalue,messagelist[idnr].textvalue,this.cn+'.systemmessageclose(\''+messagelist[idnr].msgid+'\');');
	}

}
punt_api.prototype.systemmessageclose = function(idnr)
{
	
}
punt_api.prototype.blinkmessagetitle = function(id,ammount,blinkspeed,state)
{
	if(state==0)
	{
		
		puntapi._(id).style.color='';
		state=1;
	}
	else
	{
		
		puntapi._(id).style.color='red';
		state=0;
	}
	ammount = ammount-1
	
	
	
	if(ammount>=0)
	{
		setTimeout(this.cn+'.blinkmessagetitle(\''+id+'\','+ammount+','+(blinkspeed)+','+state+')',blinkspeed);
	}

}




punt_api.prototype.showlightbox = function(var1,var2,contents)
{
	if (typeof contents != 'undefined') {
		_lb.open(contents);
	}
	else 
	{
		_lb.open('loading_lightbox');
	}
	
}

punt_api.prototype.hidelightbox = function()
{
	
	_lb.hide();
}
punt_api.prototype.showlightbox_old = function(step,noonclick)
{
	step=step+1;
	step=0;
	if(step==0)
	{
		viewprt = puntapi.getviewportsize();	
		
		try
		{
			puntapi._('Application').style.overflow='hidden';	
			puntapi._('Application').style.display='none';	
		}
		catch(e)
		{
			puntapi._('websitecontent').style.overflow='hidden';		
				
		}
		
		puntapi._('lightbox').style.display='block';		
		/*puntapi._('lightbox').style.width=viewprt.width+'px';
		puntapi._('lightbox').style.height=viewprt.docheight+'px';*/
		if(noonclick)
		{
			puntapi._('lightbox').onclick= '';
		}
		else
		{
			puntapi._('lightbox').onClick= function(){puntapi.hidelightbox(7);}
			
		}
		
		puntapi._('lightbox_underlay').style.display='block';		
		
		puntapi._('lightbox_underlay').style.width='100%';
		puntapi._('lightbox_underlay').style.height=viewprt.docheight+'px';
		
		
		
	}
	
	
//	this.lightup(puntapi._('lightbox_underlay'),(step*10));
//	this.lightup(puntapi._('lightbox'),(step*20)+40);
	
	this.lightup(puntapi._('lightbox_underlay'),70);
	this.lightup(puntapi._('lightbox'),100);
	step=4;

	if(step<3)
	{
		setTimeout(this.cn+'.showlightbox('+step+')',this.stepspeed);
	}
	

}
punt_api.prototype.hidelightbox_old = function(step)
{
	step=0;
	
	/*
	this.lightup(puntapi._('lightbox_underlay'),(step*10));
	this.lightup(puntapi._('lightbox'),(step*20)+40);
	*/
	/*this.lightup(puntapi._('lightbox_underlay'),0);
	this.lightup(puntapi._('lightbox'),0);
	*/
	if(step>0)
	{
		setTimeout(this.cn+'.hidelightbox('+step+')',this.stepspeed);
		
	}	
	else
	{
		
		puntapi._('lightbox_underlay').style.display='none';	
		puntapi._('lightbox').style.display='none';	
		try
		{
			puntapi._('Application').style.overflow='';	
			puntapi._('Application').style.display='';	
			puntapi._('lightbox').style.width='';
		}
		catch(e)
		{
			puntapi._('websitecontent').style.overflow='';			
			puntapi._('lightbox').style.width='';
		}
	}
	
}

punt_api.prototype.setlightbox = function(msg,noonclick,lbwidth,lbheight)
{
	if(typeof lbwidth!='undefined')
	{
		puntapi._('lightbox').style.width=lbwidth;
		puntapi._('lightbox').style.height=lbheight;
	}
	//puntapi._('lightbox').innerHTML=msg;
	this.showlightbox(-1,noonclick,msg);
	
}




punt_api.prototype.fillintags = function(){
	ppos = arguments.length;
	for(o=0;o<arguments.length;o++)
	{
		this.tagmsgbox(arguments[o]);
	}
}
punt_api.prototype.encodetagmsgbox = function(tag)
{
	
	rettag = tag.replace(' ','');
	rettag = rettag.replace('-','');
	rettag = rettag.replace('_','');
	return rettag;
}
punt_api.prototype.tagmsgbox = function(tag)
{
	encodedtag = this.encodetagmsgbox(tag);
	title = 'New tag:'+tag;
	html='<textarea id=\'trans_'+encodedtag+'\' style="width:90%;"></textarea>';
	onok= 'puntapi.translatedtag(\''+tag+'\')';
	this.newMessagebox(title,html,onok,'800');
	
	
}

punt_api.prototype.translatedtag = function(tag){
	encodedtag = this.encodetagmsgbox(tag);
	
	
}
punt_api.prototype.lightup = function(imageobject, opacity){
	
	
	
 if (navigator.appName.indexOf("Netscape")!=-1
  &&parseInt(navigator.appVersion)>=5)
  {
    imageobject.style.MozOpacity=opacity/100;
    
  }
 else if (navigator.appName.indexOf("Microsoft")!= -1 
  &&parseInt(navigator.appVersion)>=4)
  {
    imageobject.style.filter ='alpha(opacity='+opacity+')';
  }
}



punt_api.prototype.setHelp = function(msg,length)
{	
	if(length<1)
	{
	/*puntapi._('helpboxtxt').style.display='none';
	puntapi._('helpbox').style.display='none';	*/
	this.currenthelptext='';
	}
	else
	{
		this.helpopen=0;
	this.currenthelptext=msg;
	this.appendActionButton('Help','help','','','','','',this.cn+'.showhelp(this)');

	
	}
}
punt_api.prototype.showhelp = function(closeaction)
{
	
	if(closeaction=='closed')
	{
		this.helpopen=0;
		//_toolTip.hidesticky();
		puntapi._('Pagehelp').innerHTML='';
		puntapi._('Pagehelp').style.display='none';
	}
	else
	{
		if(this.helpopen==1)
		{
			this.helpopen=0;
			puntapi._('Pagehelp').innerHTML='';
			puntapi._('Pagehelp').style.display='none';
		}
		else
		{
			
			this.helpopen=1;
			var istyle = 'color:#555555;background-color:#eeecbe;padding-left:2px;padding-right:2px;';
			puntapi._('Pagehelp').innerHTML=_tT.parse('helpbox',{style:istyle,color:'d4d2d2',text:this.currenthelptext,height:200});	
			puntapi._('Pagehelp').style.display='block';
		}
		
	}
	
}

punt_api.prototype.resizehelp = function(direction)
{
	originalheight = puntapi._('pagehelpinner').style.height.split('px');
	if(direction=='bigger')
	{
		var newheight = parseInt(originalheight[0])+100;
		puntapi._('pagehelpinner').style.height= newheight+'px';
	}
	else
	{
		
		var newheight = parseInt(originalheight[0])-100;
		if(newheight>=100)
		{
			puntapi._('pagehelpinner').style.height= newheight+'px';
		}
	}
}
punt_api.prototype.closehelp = function()
{
	this.showhelp('closed');
}
punt_api.prototype.onclose = function()
{
	
	if(!mayclose){return confirm('Are you sure you want to close this window?')}
}
punt_api.prototype.preventclose = function(state)
{
	if(state=='on')
	{
		mayclose = false;
	}
	else
	{
		mayclose = true;
	}
	
	
}
punt_api.prototype.showhelptexts = function()
{

	if(puntapi._('helpboxtxt').style.display=='')
	{
		puntapi._('helpboxtxt').style.display='block';
		puntapi._('helpboxtitle').innerHTML='Fold the helpscreen back in';
	}
	else if(puntapi._('helpboxtxt').style.display=='block')
	{
		puntapi._('helpboxtxt').style.display='none';
		puntapi._('helpboxtitle').innerHTML='Show help for this screen';
	}
	else
	{
		puntapi._('helpboxtxt').style.display='block';
		puntapi._('helpboxtitle').innerHTML='Fold the helpscreen back in';
	}
	
	
	
}

/**
 * 
 * @param {string} application
 * @param {string} command
 * @param {xmlObject} returndata
 */
punt_api.prototype.togglehelp = function(id)
{

	
	
}
punt_api.prototype.gethelp = function(application,command,returndat)
{
	try {
		if (helpenabled == 'yes') {
		
			if (typeof returndat == 'object') {
			
			
			
				helpelement = returndat.getElementsByTagName('help').item(0);
				//helpboxout='<div class="helpboxtitle clickable" onclick="puntapi.showhelptexts();">Fold the helpscreen back in</div>';
				helpboxout = '';
				if (helpelement) {
					commands = helpelement.getElementsByTagName('command');
					
					for (o = 0; o < commands.length; o++) {
					
						title = commands.item(o).getElementsByTagName('title').item(0).firstChild.nodeValue;
						text = commands.item(o).getElementsByTagName('text').item(0).firstChild.nodeValue;
						cmd = commands.item(o).getAttribute('cmd');
						
						helpboxout += '<div class="simpletext">';
						helpboxout += '<div class="title" id="helptitle' + cmd + '" >' + title + '</span><br/>';
						if (o == 0) {
						
							helpboxout += '<span class="text" style="display:block" id="helptext' + cmd + '">' + text + '</span>';
							
						}
						else {
							helpboxout += '<span class="text" style="display:none" id="helptext' + cmd + '">' + text + '</span>';
						}
						
						helpboxout += '</div></div>';
						
					}
				}
				this.setHelp(helpboxout, commands.length);
				
				
			}
			else {
				//no returndata specified.. so get it then...
				
				nr++
				TA[nr] = new TAjax();
				TA[nr].cn = 'TA[' + nr + ']';
				
				TA[nr].Sourcefile = basepath + '/API/help/' + application + '/' + command + '?AJAX_REQ=yes&bp=' + encodeURIComponent(basepath);
				
				TA[nr].onReadyresponsecommand = this.cn + '.gethelp(\'' + application + '\',\'' + command + '\',getresponsexml(' + nr + '))';
				TA[nr].doPost();
				
				
			}
			
		}
	}
	catch(e)
	{
		
	}
}



/*Ajax callbacks etc.*/
punt_api.prototype.DoCommand_delay = function(app,command,id,query,confirmation,doc)
{
	cmd = 'this.DoCommand(\''+app+'\',\''+command+'\',\''+id+'\',\''+query+'\',\''+confirmation+'\',\''+doc+'\');';

	setTimeout(cmd,300);
}

punt_api.prototype.repeatCommand = function()
{
	if(typeof this.lr=='object')
	{
		if(this.lr.app=='command2')
		{
			
			this.DoCommand2(this.lr.path,this.lr.doc,this.lr.resulttarget);
		}
		else
		{
			
			this.DoCommand(this.lr.app,this.lr.command,this.lr.id,this.lr.query,this.lr.confirmation,this.lr.doc,this.lr.resulttarget);
		}
	}
}
punt_api.prototype.doRefresh = function(id)
{
	if (this._(id)) {
		this.DoCommand2(this.refreshUrl);
	}
}
punt_api.prototype.refresh = function(id,url,delay)
{
	
	this.refreshUrl=url.replace('&amp;','&');
	
	setTimeout('puntapi.doRefresh("'+id+'")',(1000*delay));
}
punt_api.prototype.DoCommand = function(app,command,id,query,confirmation,doc,resulttarget,callback)
{
	
	var confirmed = true;
	if(this.openchanges)
	{
		confirmed = confirm('global_openchanges_form');
	}
	else if ((typeof confirmation != 'undefined') && (confirmation!=''))
    {
    	confirmed = confirm(confirmation);
    }	
	this.lr = [];
	this.lr.type 			= 'command';
	this.lr.app 			= app;
	this.lr.command 		= command;
	this.lr.id 				= id;
	this.lr.query 			= query;
	this.lr.confirmation 	= confirmation;
	this.lr.doc 			= doc;
	this.lr.resulttarget 	= resulttarget;
	if(this.defaulttarget==resulttarget)
	{
		mdunloadUnloadable=true;
	}
	if((typeof resulttarget=='undefined')||(resulttarget ==''))
	{
		if(this.defaulttarget!='')
		{
			resulttarget = this.defaulttarget;
			
		}
		else
		{
			resulttarget='';
		}

	}

	
	key=app+'_'+command+'_'+id+'_'+query;
	puntMedia.reloaditem=0;
	if(resulttarget==this.defaulttarget)
	{
		
		if (resulttarget != 'dialogoutput') {
			window.scrollTo(0, 0);
		}	
	}
	else
	{
		if (resulttarget == 'wizard_pageoutput') {
			window.scrollTo(0, 0);
		}	
	}
	
	_toolTip.disabled=true;
	_toolTip.hide();
	
	
	if((this.notificationsticky!='yes')&&(this.notificationtimeout==-1))
	{
		if (this.keepNotificationsForTrip > 0) {
			this.keepNotificationsForTrip--;
		}
		else {
			this.hideNotification();
		}
	}
	if((this.alertsticky!='yes')&&(this.alerttimeout==-1))
	{
	this.hideAlert();
	}	
	mayclose=true;
	
	

	if (confirmed)
	{
		
		var lastpart ="'"+key+"'";
		var CB ="";
		
		if(typeof resulttarget!= 'undefined')
    	{
			if(resulttarget!='')
			{
				lastpart= "'"+key+"','"+resulttarget+"'";
			}
		}
		
		
        if(typeof callback!='undefined')
		{
			
			CB = "\n"+callback;
			
		}
		eval("var func = function(resp){puntapi.WriteAppresponse(resp.xml,resp.text,"+lastpart+");"+CB+"};");
		
		var url = basepath;
		
		
		var targetdiv='';
		if(typeof resulttarget!= 'undefined')
		{
			if(resulttarget!='')
			{
				targetdiv='formtargetdiv='+resulttarget+'&';
			
			}
		}
		
		if(command=='')
		{
			url=basepath+'/'+app+'?AJAX_REQ=yes&'+targetdiv+query;
		}
		else
		{
	
	
			if(id!='')
			{
				url=basepath+'/'+app+'/'+command+'/'+id+'?AJAX_REQ=yes&'+targetdiv+query;
	
			}
			else
			{
				url=basepath+'/'+app+'/'+command+'?AJAX_REQ=yes&'+targetdiv+query;
	
	
			}
		}
		
		this.start_hidercount();
		if(typeof doc =='undefined')
		{
			doc='';
		}
		_tajax.makeCall(url,{method:'post',onFinish:func,doc:doc,weight:1});
	}
	return false;

}

punt_api.prototype.DoCommand2 = function(path,doc,resulttarget,callback,noscroll)
{
	this.lr = {};
	this.lr.type 			= 'command2';
	this.lr.path 			= path;
	this.lr.doc 			= doc;
	this.lr.resulttarget 	= resulttarget;	
	mdunloadUnloadable=true;
	var st=0;
	var splitpath  = path.split('?');
	//explode it again
	
	var sp2 = splitpath[0].split('/');
	
	if((sp2[0]=='http:')||(sp2[0]=='https:'))
	{
		if((sp2[3]=='Profile')||(sp2[3]=='Admin')||(sp2[3]=='Service')||(sp2[3]=='Supplier')||(sp2[3]=='Control'))
		{
			st=3;
		}
		else
		{
			st=2;
		}
		
	}
	else if((sp2[1]=='Profile')||(sp2[1]=='Admin')||(sp2[1]=='Service')||(sp2[1]=='Supplier')||(sp2[1]=='Control'))
	{
		//the start is 1
		st=1;
	}
	else
	{
		st=0;
	}
	var qapplication=sp2[st+1];
	var qcommand=sp2[st+2];
	var qid=sp2[st+3];
	var qquery=splitpath[1];
	if((qapplication=='undefined')||(typeof qapplication =='undefined'))
	{
		qapplication='';
	}	
	if((qcommand=='undefined')||(typeof qcommand =='undefined'))
	{
		qcommand='';
	}	
	if((qid=='undefined')||(typeof qid =='undefined'))
	{
		qid='';
	}
	if((qquery=='undefined')||(typeof qquery =='undefined'))
	{
		qquery='';
	}
	
	
	
	
	
	this.DoCommand(qapplication,qcommand,qid,qquery,'',doc,resulttarget,callback);
	
	return true;
	
	
	mayclose=true;
	if(resulttarget==this.defaulttarget)
	{
		window.scrollTo(0,0);
	}
	_toolTip.hide();
	_toolTip.disabled=true;	

	
	var lastpart ="''";
		var CB ="";
		
		if(typeof resulttarget!= 'undefined')
    	{
			if(resulttarget!='')
			{
				lastpart= "'','"+resulttarget+"'";
			}
		}
		
		
        if(typeof callback!='undefined')
		{
			
			CB = "\n"+callback;
			
		}
		eval("var func = function(resp){puntapi.WriteAppresponse(resp.xml,resp.text,"+lastpart+");"+CB+"};");
		
		var url = basepath;
		
		
		var targetdiv='';
		if(typeof resulttarget=='undefined')
		{
			url=splitpath[0]+'?AJAX_REQ=yes&'+splitpath[1];
		}
		else
		{
			url=splitpath[0]+'?AJAX_REQ=yes&formtargetdiv='+encodeURIComponent(resulttarget)+'&'+splitpath[1];
		}

		
		this.start_hidercount();
		if(typeof doc =='undefined')
		{
			doc='';
		}
		_tajax.makeCall(url,{method:'post',onFinish:func,doc:doc,weight:1});
}

punt_api.prototype.start_hidercount = function()
{
	clearTimeout(reloadcd);
	clearTimeout(statuscd);
	reloadcd = setTimeout(this.cn+".start_hider()",750);

	
	
}
punt_api.prototype.start_hider = function()
{
	clearTimeout(reloadcd);
	try 
	{
		if (puntapi._("statuslayer").style.display != 'block') 
		{
			puntapi._("statuslayer").innerHTML = '<center><div class="statuslayer_inside">Busy retrieving data<br/><img src="/Layout/Mijndomein/images/loader_small.gif"></div></center>';
			
			$('#statuslayer').slideDown('fast', function()
			{
			
			});
		}
		
	}
	catch(e)
	{
		alert(e);
	}
		
}
punt_api.prototype.stop_hider = function()
{
	clearTimeout(reloadcd);
	
	try
	{
		//puntapi._("statuslayer").innerHTML='global_loaded';
		if (puntapi._("statuslayer").style.display != 'none') 
		{
			$('#statuslayer').slideUp('fast', function()
			{
				puntapi._("statuslayer").style.display = 'none';
			});
		}
		
		//statuscd = setTimeout(this.cn+".hide_status()",1000);
	}
	catch(e)
	{
		
	}
}

punt_api.prototype.hide_status = function()
{
	
	puntapi._("statuslayer").style.display='none';	
}



punt_api.prototype.openCurrentSelectedDomain = function()
{
	puntapi.DoCommand('domainmanager','selectdomain',this.currentselecteddomain);
}

punt_api.prototype.replaceDots = function(str)
{
	var newVersion = str.replace('.', '<span style="color: #ed2024">.</span>');
	return newVersion;
}

punt_api.prototype.setrdomtitle = function(title,id)
{
	try
	{
		if(puntapi.currentselecteddomain!=id)
		{
			if((id!='')&&(title!='')&&(id!=false)&&(title!=false))
			{
				tautocompletecontainer.update('selectdomainbox',id,title);
				if(title.length>35)
				{
					title = title.substring(0,15)+'...'+title.substring(title.length-15);
				}
				this.currentselecteddomain=id;
				if (basepath != '/Admin') {
					puntapi._('hostname').innerHTML = "<a href='http://www." + title + "' target='blank' style='text-decoration:none'>" + this.replaceDots(title) + "</a>";
				}
				else
				{
					puntapi._('hostname').innerHTML = "<a href='"+document.location.protocol+"//" + window.location.hostname + "' target='blank' style='text-decoration:none'>" + this.replaceDots(window.location.hostname) + "</a>";
				}
				
			}
		}
	}
	catch(e)
	{
		
	}

}
punt_api.prototype.pagePrepend = function(source)
{
	var tmp_data = puntapi._(source).value;
	if(tmp_data.length>0)
	{
		puntapi._('contentprepend').innerHTML=tmp_data;
		puntapi._('contentprepend').style.display='block';	
	}
	else
	{
		puntapi._('contentprepend').innerHTML='';
		puntapi._('contentprepend').style.display='none';
	}
	
}

punt_api.prototype.mustRefreshPage = function(url,target)
{
	
	return "to refresh go to: <span onclick=\"puntapi.DoCommand2('"+url+"','','"+target+"');\">global_reload_now</span>";
}

punt_api.prototype.WriteAppresponse = function(response,responsetxt,key,resulttarget,fromhistory)
{	
	//explode the key
	var resp='';
	var app='';
	var command='';
	var id='';
	var query='';
	var tkey='';
	var xmlDoc='';
	var applicationpath='';
	var rtitle='';
	var rdomtitles='';
	var rdomtitle='';
	
	if(typeof resulttarget!='undefined')
	{
		
		if((resulttarget =='Application_Output')||(resulttarget==''))
		{
			resulttarget=undefined;
		}
	}
	
	
	
	
	if(this.debug)
	{
		resp = responsetxt.replace(/[<]/g,'&lt;');
		
		try
		{
		puntapi._('debugdatafield').innerHTML = 'Last response<br/><textarea style="width:99%;height:250px;">'+resp+'</textarea>';
		}
		catch(e)
		{
			
		}
		
		
	}	
	try
	{
		//_mdm.dohidesubs();
		
	}
	catch(e)
	{
		
	}
	
	_toolTip.disabled=false;

	if (typeof ajaxhist != 'undefined') 
	{
		if (responsetxt.indexOf('<!--HASREDIRECTURL-->') == -1) 
		{
		
		
			if (typeof resulttarget == 'undefined') 
			{
				//skip the register of a history
				if (typeof key != 'undefined') 
				{
					key = key.replace('#', '');
					if (key != '') 
					{
						if (typeof fromhistory == 'undefined') 
						{
							var targs = [];
							for (var ttval = 0; ttval < 5; ttval++) 
							{
								targs[ttval] = arguments[ttval];
							}
							ajaxhist.registerhistory(key, targs);
						}
						tkey = key.split('_');
						app = '';
						command = '';
						id = '';
						if (typeof tkey[0] != 'undefined') 
						{
							app = tkey[0];
						}
						if (typeof tkey[1] != 'undefined') 
						{
							command = tkey[1];
						}
						if (typeof tkey[2] != 'undefined') 
						{
							id = tkey[2];
						}
						if (typeof tkey[3] != 'undefined') 
						{
							query = tkey[3];
						}
						//md3nav.displaynav(app, command, id);
						md3nav.highlight(app,command,id,query);
						puntapi.gethelp(app, command, 0);
						this.currentapp = app;
						this.currentcommand = command;
					}
				}
			}
			else 
			{
				if (typeof key != 'undefined') 
				{
					key = key.replace('#', '');
					if ((resulttarget == 'dialogoutput') || (resulttarget.indexOf('list_page') > -1)) 
					{
					
						if (key != '') 
						{
							if (typeof fromhistory == 'undefined') 
							{
								var targs = [];
								for (var ttval = 0; ttval < 5; ttval++) 
								{
									targs[ttval] = arguments[ttval];
								}
								ajaxhist.registerhistory(key, targs);
							}
							tkey = key.split('_');
							app = '';
							command = '';
							id = '';
							if (typeof tkey[0] != 'undefined') 
							{
								app = tkey[0];
							}
							if (typeof tkey[1] != 'undefined') 
							{
								command = tkey[1];
							}
							if (typeof tkey[2] != 'undefined') 
							{
								id = tkey[2];
							}
							if (typeof tkey[3] != 'undefined') 
							{
								query = tkey[3];
							}
							this.currentapp = app;
							this.currentcommand = command;
							this.currentid = id;
							this.currentquery = query;
						}
					}
				}
			}
		}
	}
	try
	{
    
	//xmlDoc = newxmldoc(response);
	xmlDoc = response;
	
	var x = xmlDoc.getElementsByTagName('page').item(0);
	
	
	
	applicationpath ='';try{applicationpath= x.getElementsByTagName('applicationpath').item(0).firstChild.nodeValue;}catch(e){}
	rtitle='';try{rtitle = x.getElementsByTagName('title').item(0).firstChild.nodeValue;}catch(e){}
	try{
	rdomtitles =  x.getElementsByTagName('domaintitle');
	
	if(rdomtitles.length>0)
	{
	
		
		rdomtitle = rdomtitles.item(0).firstChild.nodeValue;
	
	}
	else
	{
		rdomtitle='';
	}
	}catch(e){rdomtitle='';}
	//load data!
	var rdomtitle='';try{rdomtitle = x.getElementsByTagName('domaintitle').item(0).firstChild.nodeValue;}catch(e){}
	var rdomid='';try{rdomid = x.getElementsByTagName('domaintitleid').item(0).firstChild.nodeValue;}catch(e){}
	var content='';try{content = x.getElementsByTagName('content').item(0).firstChild.nodeValue;}catch(e){}
	var sideinfo='';try{sideinfo = x.getElementsByTagName('sideinfo').item(0).firstChild.nodeValue;}catch(e){}
	var nootherwidgets='';try{nootherwidgets = x.getElementsByTagName('widgets').item(0).getAttribute('nootherwidgets');}catch(e){}
	var widgets='';try{widgets = x.getElementsByTagName('widgets').item(0).firstChild.nodeValue;}catch(e){}
	var actionbuttons='';try{actionbuttons = x.getElementsByTagName('actionbuttons').item(0);}catch(e){}
	var notifications='';try{notifications = x.getElementsByTagName('notifications').item(0);}catch(e){}
	var errormessages='';try{errormessages = x.getElementsByTagName('errormessages').item(0);}catch(e){}
	var redirecturl='';try{redirecturl = x.getElementsByTagName('redirecturl').item(0).firstChild.nodeValue;}catch(e){}
	
	var debugmessages='';try{debugmessages = x.getElementsByTagName('debugmessages').item(0).firstChild.nodeValue;}catch(e){}
	var appicon='';try{appicon = x.getElementsByTagName('appicon').item(0).firstChild.nodeValue;}catch(e){}
	var mustrefresh='';try{mustrefresh = x.getElementsByTagName('mustrefresh').item(0).firstChild.nodeValue;}catch(e){}
	var refreshUrl='';try{refreshUrl = x.getElementsByTagName('refreshUrl').item(0).firstChild.nodeValue;}catch(e){}
	var tmplangtags ='';
	var tmplang ='';

	try{tmplangtags = x.getElementsByTagName('notreplacedtags').item(0).firstChild.nodeValue;}catch(e){}
	if (tmplangtags != '') 
	{
		
		if ((typeof resulttarget == 'undefined')||this.includeAlternativeTargets) 
		{
			
			this.currentlangtags = tmplangtags;
		}
	}
	
	
	try{tmplang = x.getElementsByTagName('notreplacedtags').item(0).getAttribute('lang');}catch(e){}
	if (tmplang != '') 
	{
		this.currentlang = tmplang;
	}	
	var tracedata='';try{tracedata = x.getElementsByTagName('trace').item(0).firstChild.nodeValue;}catch(e){}


	if(typeof fromhistory!='undefined')
	{
	
		if(mustrefresh=='yes')
		{
			
			content = puntapi.DoCommand2(refreshUrl,'',resulttarget);
			return false;
		}
	}
	//attempt to load widgets...
	//try{_tW.demandWidgets(widgets);}catch(e){} 
	
	
	if(debugmessages!='')
	{
		//append the debug messages
		try
		{
			puntapi._('debugtextdata').value+=debugmessages;
			this.blinkmessagetitle('debugtogglefield',20,200,0);
			// show console messages in the firebug console if its available
			if(typeof console != 'undefined')
			{
				console.log(debugmessages);
			}
		}
		catch(e)
		{
			
		}
	}


	if((typeof resulttarget=='undefined')||(resulttarget==''))
	{
		//demand some widgets 
		if(this.autoupdatelangtags==1)
		{
			this.printLanguageWidget();
		}
		try
		{
			_tW.demandWidgets(widgets,nootherwidgets);
		}
		catch(err)
		{
			
		}
		try {
			tracedata = JSON2.parse(tracedata);
		}
		catch(e)
		{
            
		}
		if (typeof tracedata == 'object') 
		{
			
			
			//this.handleTrace(tracedata);
		}
		else
		{
			//this._('tracecontainer').style.display='none';
				
		}

		//now add the notifcations! 
		this.readNotifications(notifications,errormessages);
		 		
		if(typeof redirecturl!='undefined')
		{
			if((redirecturl != '')&& (redirecturl != null))
			{
				this.keepNotificationsForTrip=1;
				this.DoCommand2(redirecturl);
				return true;
			}
		}		
		
		//create the action buttons
		this.createActionButtons(actionbuttons);

		
		
	
		
		this.setrdomtitle(rdomtitle,rdomid);
		
		//clearcontrolls();
		var application_elem = puntapi._('Application');
		
		try
		{
			puntapi._('contentprepend').innerHTML = '';
			puntapi._('contentprepend').style.display='none';		
		}
		catch(e)
		{
		}
		
		//puntapi._('appicondiv').className='ICON2_'+appicon+' appicon';
		var appout = document.getElementById('Application_Output');
		//var div_new = document.createElement('div');
		//div_new.innerHTML = content
		appout.innerHTML = content;
		//appout.appendChild(div_new);

		
		puntapi._('Applicationpath').innerHTML = applicationpath;
		if (applicationpath.length > 0) 
		{
			puntapi._('Applicationpath').style.display = 'block';
		}
		else 
		{
				puntapi._('Applicationpath').style.display = 'none';
		}
		
		puntapi._('Pagetitle').innerHTML = rtitle;
		puntapi._('Pagehelp').innerHTML = '';	

        var bSaf = (navigator.userAgent.indexOf('Safari') != -1);
        var bOpera = (navigator.userAgent.indexOf('Opera') != -1);
        var bMoz = (navigator.appName == 'Netscape');
               if (bSaf) {
                     execJS(puntapi._('Application_Output'));
               } else if (bOpera) {
                     execJS(puntapi._('Application_Output'));
               } else if (bMoz) {
                     execJS(puntapi._('Application_Output'));   
               } else {
                      execJS(puntapi._('Application_Output'));
               }
	}
	else
	{
		
		if(resulttarget=='dialogoutput')
		{
		   this.createActionButtons(actionbuttons);

		}
			
		   var application_elem = puntapi._(resulttarget);
		   
		   //	var div_new = document.createElement('div');
		   	//div_new.innerHTML = content
		   	application_elem.innerHTML = content;
		   //	application_elem.appendChild(div_new);
		   
	       var bSaf = (navigator.userAgent.indexOf('Safari') != -1);
	       var bOpera = (navigator.userAgent.indexOf('Opera') != -1);
	       var bMoz = (navigator.appName == 'Netscape');
	               if (bSaf) {
	                    execJS(application_elem);
	               } else if (bOpera) {
	                    execJS(application_elem);  
	               } else if (bMoz) {
	                    execJS(application_elem); 
	               } else {
	                    execJS(application_elem);
	               }			
	               
		if (resulttarget=='dialogoutput')
		{
			var content = md3._('loadercontainer');
			if (content)
			{				
				var progress = md3._('loaderprogressbar');
				progress.style.display = 'none';
				content.style.display = 'block';
			}
		}
	}
 	
	
	}
	catch(errorz)
	{
		//	alert(errorz);
		//	console.log("we can has errorz",errorz);
			//puntapi.newMessagebox('Oops something went wrong','Something went wrong on the server side. Please try again. If the problem persists please use the feedback button in the right top of your screen to send a possible bug report to the system developers. ');
			this.addAlert('Oops something went wrong','Something went wrong on the server side. Please try again. If the problem persists please use the feedback button in the right top of your screen to send a possible bug report to the system developers. ');//+errorz);
		
	}
	this.rescale();
	this.stop_hider();	


}


punt_api.prototype._ = function(id)
{
	return document.getElementById(id);
}

punt_api.prototype.handleTrace = function(data)
{
	if(data.length>0)
	{
		//this.renderTrace(data);
		this._('tracecontainer').style.display='block';		
	}
	else
	{
		//hide the trace
		this._('tracecontainer').style.display='none';
		
	}
	
}
punt_api.prototype.renderTrace = function(data)
{
	var parts=[];
	var sep='<span class="breadcrumbspacer">></span>';
	for(var uu=0;uu<data.length;uu++)
	{
		parts[parts.length]=_tT.parse('breadcrumb',data[uu]);
	}
	var html = parts.join(sep);
	this._('tracecontainer_contents').innerHTML=html;
	
}
punt_api.prototype.determineSizes = function()
{
	var vp = this.getviewportsize();
	var defaultsize = {};
	var usedsize = {};
	var returnsizedata = {};
	var usedwidth =0;
	
	for(var ssnr=0;ssnr<scalersizes.length;ssnr++)
	{
		if(scalersizes[ssnr].isdefault)
		{
			defaultsize= scalersizes[ssnr];
		}
		if(typeof scalersizes[ssnr].biggerthan!='undefined')
		{
			if(vp.width>scalersizes[ssnr].biggerthan)
			{
				
				usedsize =  scalersizes[ssnr];
			}
		}
		if(typeof scalersizes[ssnr].smallerthan!='undefined')
		{
			if(vp.width<scalersizes[ssnr].smallerthan)
			{
				
				usedsize =  scalersizes[ssnr];
			}
		}		
	}
	try
	{
		if(usedsize.showfullscreen)
		{
			this._('fullscreen_interface_toggler').style.display='block';
		}
		else
		{
			this._('fullscreen_interface_toggler').style.display='none';
		}
	}
	catch(e)
	{
		
	}
	if(this.isFullscreen)
	{
		
		usedsize = fullscreensize;
	}
	if(typeof usedsize.targetwidth=='undefined')
	{
	
		usedsize = defaultsize;
	}
	if(usedsize.targetwidth=='%')
	{
		//use whats left after sidespacing is removed twice;
		usedwidth = vp.width-(usedsize.sidespacing*2);
	}
	else
	{
		usedwidth = usedsize.targetwidth;
		
	}
	returnsizedata.width=usedwidth;
	returnsizedata.actualwidth=vp.width;
	
	if(usedsize.sidespacing=='%')
	{
		//use everything you can - maxwidth
		
		returnsizedata.sidespacing=Math.floor((vp.width-usedwidth)/2);
	}
	else
	{
		//absolute size
		returnsizedata.sidespacing=usedsize.sidespacing;
	}
	
	
	return returnsizedata;
	
}
punt_api.prototype.redrawPositions = function()
{
	var scalersize = this.determineSizes();
	if (typeof _tW !='undefined') 
	{
		var widgetinfo = _tW.widgetsVisible();
	}
	else
	{
		var widgetinfo =false;
	}

	try
	{
	var allWrapperLeft = puntapi._('wrapper');
	var contentwapperElement = puntapi._('contentwrapper');

	
	//calculate how big the content element is supposed to be
	var spacer = 10;
	var leftsize=285+spacer;
	var rightsize=285+spacer;
	var menusize = 200+spacer;
	var mainsize = scalersize.actualwidth;
	var scrollbar = 15;
	var hasScrollbar=false;
	if ($(document).height() > $(window).height()) 
	{
		hasScrollbar=true;
	}

	if(!hasScrollbar)
	{
		scrollbar=0;
	}
	var osfactor = 0;
	var hasVScroll = document.body.scrollHeight > document.body.clientHeight;


	if(typeof md3nav !='undefined')
	{
		if(md3nav.getMode()=='small')
		{
			menusize = 45+spacer;
		}
		
	}
	
	allWrapperLeft.style.marginLeft=menusize+'px';

	if((widgetinfo.left>0)||(widgetinfo.right>0))
	{
		
		
		if(widgetinfo.left>0 && widgetinfo.right>0)
		{
			//its the size - (left size - right size  + (3x 10))
			mainsize = scalersize.actualwidth - (menusize+leftsize+rightsize+spacer+scrollbar+osfactor);
		}
		else if(widgetinfo.left>0)
		{
			//its the size - (left size   + (2x 10))
			mainsize = scalersize.actualwidth - (menusize+leftsize+spacer+scrollbar+osfactor);
		}
		else if(widgetinfo.right>0)
		{
			
			//its the size - (right size   + (2x 10))
			mainsize = scalersize.actualwidth - (menusize+rightsize+spacer+scrollbar+osfactor);
		}
		else
		{
			//eek!
			
		}
		contentwapperElement.style.width=mainsize+'px';
	}
	else
	{
		//just the main thing
		mainsize = scalersize.actualwidth - menusize;
		contentwapperElement.style.width='100%';
	}
	
	
	}
	catch(e)
	{
	
	}
}
punt_api.prototype.redrawPositionsOld = function()
{
	
	var scalersize = this.determineSizes();
	if (typeof _tW !='undefined') 
	{
		var widgetinfo = _tW.widgetsVisible();
	}
	else
	{
		var widgetinfo =false;
	}
	return false;
	
	var sep = 10 ;//px seperation
	var targetelem=null;
	var bgcontainer = puntapi._('backgroundcontainer');
	var menubarelem = puntapi._('menubar');
	var topbarelem = puntapi._('topbar');
	var alertcontainerElement = puntapi._('alertcontainer');
	var notificationcontainerElement = puntapi._('notificationcontainer');
	var contentwapperElement = puntapi._('contentwrapper');
	//elem5= puntapi._('pagetitlecontainer');
	var widgetLeftElement = puntapi._('leftcolumn');	
	var widgetFarLeftElement = puntapi._('farleftcolumn');	
	var widgetRightElement = puntapi._('rightcolumn');	
	var topbar = puntapi._('topbar');	
		
	var _dim = new dimensions();	
	
try
{	
	
	
	if((this.alertenabled)&&(this.notificationenabled))
	{
		//if the notification is enabled as well as the alert then...
		alertcontainerElement.style.display="block";
		notificationcontainerElement.style.display="block";
		
		
		dim = _dim.dimensions(topbar);
		alertcontainerElement.style.top=(dim.y+dim.h+sep)+'px';	
		dima = _dim.dimensions(alertcontainerElement);
		notificationcontainerElement.style.top=(dima.y+dima.h+sep)+'px';
		targetelem = notificationcontainerElement;
		
	}
	else if(this.alertenabled)
	{
		//if just the alert is on...
		alertcontainerElement.style.display="block";
		notificationcontainerElement.style.display='';
		alertcontainerElement.style.top='';
		notificationcontainerElement.style.top='';		
		dim = _dim.dimensions(topbar);
		alertcontainerElement.style.top=(dim.y+dim.h+sep)+'px';
		targetelem = alertcontainerElement;
		//elem5.style.top=(dim.y+dim.h+13)+'px';
	}
	else if(this.notificationenabled)
	{
		
		alertcontainerElement.style.display='';
		notificationcontainerElement.style.display='block';
		alertcontainerElement.style.top='';
		notificationcontainerElement.style.top='';		
		
		dim = _dim.dimensions(topbar);
		notificationcontainerElement.style.top=(dim.y+dim.h+sep)+'px';
		//elem5.style.top=(dim.y+dim.h+13)+'px';		
		targetelem = notificationcontainerElement;
	}
	else
	{
		//forget it !
		alertcontainerElement.style.display='';			
		notificationcontainerElement.style.display='';			

		contentwapperElement.style.top='';
		//elem5.style.top='';
		widgetLeftElement.style.top='';
		targetelem = topbar;
	}
	//now the targetelem is set so orient it according to that !
	dim2 = _dim.dimensions(targetelem);
	var farleftsize=200;
	
	alertcontainerElement.style.left=(scalersize.sidespacing+farleftsize)+'px';
	alertcontainerElement.style.right=scalersize.sidespacing+'px';
	if(scalersize.sidespacing>0)
	{
		bgcontainer.style.right=(scalersize.sidespacing - 13)+'px';
	}
	else
	{
		bgcontainer.style.right=scalersize.sidespacing+'px';
	}

	
	notificationcontainerElement.style.left=(scalersize.sidespacing+farleftsize)+'px';
	notificationcontainerElement.style.right=scalersize.sidespacing+'px';	
	/*menubarelem.style.left=(scalersize.sidespacing+farleftsize)+'px';
	menubarelem.style.right=scalersize.sidespacing+'px';			
	
	topbarelem.style.left=(scalersize.sidespacing+farleftsize)+'px';
	topbarelem.style.right=scalersize.sidespacing+'px';	*/	
	contentwapperElement.style.top=(dim2.y+dim2.h+sep)+'px';
	widgetLeftElement.style.left=(scalersize.sidespacing+farleftsize)+'px';
	widgetRightElement.style.right=scalersize.sidespacing+'px';
	widgetLeftElement.style.top=(dim2.y+dim2.h+sep)+'px';	
	widgetRightElement.style.top=(dim2.y+dim2.h+sep)+'px';	
	var leftcontentspacing =285+sep+farleftsize;
	if (widgetinfo.left == 0) 
	{
		leftcontentspacing=0;
	}
	
	var rightcontentspacing = 285+sep+farleftsize;
	if(widgetinfo.right==0)
	{
		rightcontentspacing=0;
	}
	/*
	 * commented out because there is always something on the left(the navigation, for now)
	 * 
	 if (widgetinfo.loaded) {
		if (widgetinfo.left == 0) {
			leftcontentspacing = 0;
		}
	}*/
	contentwapperElement.style.left=(scalersize.sidespacing+leftcontentspacing)+'px';
	contentwapperElement.style.right=(scalersize.sidespacing+rightcontentspacing)+'px';
	if(isie6=='yes')
	{
		topbarelem.style.width=scalersize.width+'px';
		menubarelem.style.width=scalersize.width+'px';
		bgcontainer.style.width=scalersize.width+'px';
		alertcontainerElement.style.width=scalersize.width+'px';
		notificationcontainerElement.style.width=scalersize.width+'px';
		contentwapperElement.style.width=(scalersize.width-(rightcontentspacing+leftcontentspacing))+'px';
	}	
	
}
catch(e)
{
}
	
}
punt_api.prototype.updateAlertCounter = function()
{
	this.alerttimeout--;
	var seconds ='';
	if(this.alerttimeout>1)
	{
		seconds = ' seconds';
	}
	else
	{
		seconds = ' second';
	}
	puntapi._('alerttimeroutput').innerHTML='This alert will be automatically hidden in '+this.alerttimeout+seconds;
	if(this.alerttimeout<=0)
	{
		this.hideAlert();
	}
}
punt_api.prototype.updateNotificationCounter = function()
{
	this.notificationtimeout--;
	var seconds ='';
	if(this.notificationtimeout>1)
	{
		seconds = ' seconds';
	}
	else
	{
		seconds = ' second';
	}
	puntapi._('notificationtimeroutput').innerHTML='This notification will be automatically hidden in '+this.notificationtimeout+seconds;
	if(this.notificationtimeout<=0)
	{
		this.hideNotification();
	}
	
}
punt_api.prototype.hideAlert = function()
{
	//reset all others
	clearTimeout(this.alerttimer);
	clearInterval(this.alertinterval);	
	this.alertenabled=false;
	this.redrawPositions();
	puntapi._('alerttimeroutput').innerHTML='';	
	puntapi.rescale();
}

punt_api.prototype.hideNotification = function()
{
	//reset all others
	clearTimeout(this.notificationtimer);
	clearInterval(this.notificationinterval);		
	this.notificationenabled=false;
	this.redrawPositions();
	puntapi.rescale();
	puntapi._('notificationtimeroutput').innerHTML='';
}
punt_api.prototype.readNotifications = function(notifications,errormessages)
{
	var notifs=null;
	var errormsgs=null;
	var sticky='no';
	var timeout=-1;
	if(typeof notifications=='object')
	{	
		try
		{
			notifs = notifications.getElementsByTagName('notification');
			for(tt=0;tt<notifs.length;tt++)
			{
				title ='';try{title = notifs.item(tt).getElementsByTagName('title').item(0).firstChild.nodeValue;}catch(e){}
				text ='';try{text = notifs.item(tt).getElementsByTagName('text').item(0).firstChild.nodeValue;}catch(e){}
				sticky ='no';try{sticky = notifs.item(tt).getAttribute('sticky');}catch(e){}
				timeout =-1;try{timeout = notifs.item(tt).getAttribute('timeout');}catch(e){}
				this.addNotification(title,text,sticky,timeout);
			}
		
		}
		catch(e)
		{
			//whoa there it sploded...
		
		}
	}
	if(typeof errormessages=='object')
	{	
		try
		{
			errormsgs = errormessages.getElementsByTagName('errormessage');
			for(tt=0;tt<errormsgs.length;tt++)
			{
				title ='';try{title = errormsgs.item(tt).getElementsByTagName('title').item(0).firstChild.nodeValue;}catch(e){}
				text ='';try{text = errormsgs.item(tt).getElementsByTagName('text').item(0).firstChild.nodeValue;}catch(e){}
				sticky ='no';try{sticky = errormsgs.item(tt).getAttribute('sticky');}catch(e){}
				timeout =-1;try{timeout = notifs.item(tt).getAttribute('timeout');}catch(e){}
				this.addAlert(title,text,sticky,timeout);
			}
		
		}
		catch(e)
		{
			//whoa there it sploded...
		
		}
	}	
	
}




punt_api.prototype.addAlert = function(title,text,sticky,timeout)
{
	var notification = mdnotify.buildNotification('apinotification',{title:title,text:text},defaultAlertNotificationConfig);
	mdnotify.send(notification);
}
punt_api.prototype.addNotification = function(title,text,sticky,timeout)
{
	var notification = mdnotify.buildNotification('apinotification',{title:title,text:text},defaultNotificationConfig);
	mdnotify.send(notification);
}

punt_api.prototype.addAlertOld = function(title,text,sticky,timeout)
{
	//fill the elements
	try
	{
		clearTimeout(this.alerttimer);
		clearInterval(this.alertinterval);
		elem2 = puntapi._('alerttitle');
		elem3 = puntapi._('alerttext');
		elem2.innerHTML=title;
		elem3.innerHTML=text;
		this.alertenabled=true;
		this.alertsticky=sticky;
		this.alerttimeout=timeout;
		if(timeout>-1)
		{
			
			this.alerttimer = setTimeout(this.cn+'.hideAlert()',timeout*1000);
			this.alertinterval = setInterval(this.cn+'.updateAlertCounter()',1000);
		}
		//now redraw
		this.redrawPositions();
	}
	catch(e)
	{
		
	}
}
punt_api.prototype.addNotificationOld = function(title,text,sticky,timeout)
{
	//fill the elements
	try
	{
		clearTimeout(this.notificationtimer);
		clearInterval(this.notificationinterval);
		elem2 = puntapi._('notificationtitle');
		elem3 = puntapi._('notificationtext');
		elem2.innerHTML=title;
		elem3.innerHTML=text;
		this.notificationenabled=true;
		this.notificationsticky=sticky;
		this.notificationtimeout=timeout;
		if(timeout>-1)
		
		{
			
			this.notificationtimer = setTimeout(this.cn+'.hideNotification()',timeout*1000);
			this.notificationinterval = setInterval(this.cn+'.updateNotificationCounter()',1000);
		}	
		this.redrawPositions();
	}
	catch(e)
	{
		
	}
}

punt_api.prototype.insertHTML = function(html, n,returnselection,returnrange)
{
	 var bSaf = (navigator.userAgent.indexOf('Safari') != -1);
	 

  var browserName = navigator.appName;

	if (browserName == "Microsoft Internet Explorer") {	  
		
		
		
		if((typeof returnrange=='undefined')||(returnselection==''))
		{
			
			puntapi._(n+'_ifr').contentWindow.document.body.setActive() ;
	  		returnselection = puntapi._(n+'_ifr').contentWindow.document.selection.createRange();
	  		returnselection.pasteHTML(html);   
	  		
		}
		else
		{
			
			//returnselection.pasteHTML(html);
			returnrange.pasteHTML(html);
			
		}
		
	} 
	 
	else {
	  var div = puntapi._(n+'_ifr').contentWindow.document.createElement("span");
	  //var div = puntapi._(n+'_ifr').contentWindow.document.createDocumentFragment();
		 
		div.innerHTML = html;
		
		
		div2 = div.firstChild;
		
		if(typeof returnselection=='undefined')
		{
			var node = this.insertNodeAtSelection(div2, n);		
		}
		else
		{
			var node = this.insertNodeAtSelection(div2, n,returnselection);		
		}
		
	}
	
}
punt_api.prototype.insertNodeAtSelection = function(insertNode, n,overrideselection)
{
	
  // get current selection
  
  if(typeof overrideselection =='undefined')
  {
  		var sel = puntapi._(n+'_ifr').contentWindow.getSelection();
  }
  else
  {
  		var sel = overrideselection;
  }
  

  // get the first range of the selection
  // (there's almost always only one range)
  var range = sel.getRangeAt(0);

  // deselect everything
  sel.removeAllRanges();

  // remove content of current selection from document
  range.deleteContents();

  // get location of current selection
  var container = range.startContainer;
  var pos = range.startOffset;

  // make a new range for the new selection
  range=document.createRange();

  if (container.nodeType==3 && insertNode.nodeType==3) {

    // if we insert text in a textnode, do optimized insertion
    container.insertData(pos, insertNode.nodeValue);

    // put cursor after inserted text
    range.setEnd(container, pos+insertNode.length);
    range.setStart(container, pos+insertNode.length);
  } 
	
	else {
    var afterNode;
    
		if (container.nodeType==3) {
      // when inserting into a textnode
      // we create 2 new textnodes
      // and put the insertNode in between

      var textNode = container;
      container = textNode.parentNode;
      var text = textNode.nodeValue;

      // text before the split
      var textBefore = text.substr(0,pos);
      // text after the split
      var textAfter = text.substr(pos);

      var beforeNode = document.createTextNode(textBefore);
      afterNode = document.createTextNode(textAfter);

      // insert the 3 new nodes before the old one
      container.insertBefore(afterNode, textNode);
      container.insertBefore(insertNode, afterNode);
      container.insertBefore(beforeNode, insertNode);

      // remove the old node
      container.removeChild(textNode);
    } 
	
	  else {
      // else simply insert the node
      afterNode = container.childNodes[pos];
      container.insertBefore(insertNode, afterNode);
    }

    range.setEnd(afterNode, 0);
    range.setStart(afterNode, 0);
  }

  sel.addRange(range);
};
punt_api.prototype.writeOptionsToId = function(utarget,data)
{
		var itemselected='';
		puntapi._(utarget).options.length = 0;
		if(data)
		{
			var root = data.getElementsByTagName('options').item(0);
			
			
			
			if(root)
			{
			options = root.getElementsByTagName('option');
			
			
			
			
			
			for(o=0;o<options.length;o++)
			{
				value ='';
				try{
					value = options.item(o).getElementsByTagName('value').item(0).firstChild.nodeValue;
				}
				catch(e)
				{
					
				}
			
			
				
				description = options.item(o).getElementsByTagName('description').item(0).firstChild.nodeValue;
				itemselected='';
				try{
					itemselected = options.item(o).getAttribute('selected');
				}
				catch(e)
				{
				
				}
			
				if(itemselected=='true')
				{
					puntapi._(utarget).options[o]=new Option(description,value,true);
				}
				else
				{
					puntapi._(utarget).options[o]=new Option(description,value,false);
				}
				
				
				
			}
			}
		}

	
}


punt_api.prototype.hidemainout = function()
{
	//_mdm.hidemenus();
	
	puntapi._('wrapper').style.display="none";
	puntapi._('menubar').style.display="none";
	puntapi._('menubar').style.display="none";
	puntapi._('outerwrapper').style.display="none";
	puntapi._('upperrightcolumncontainer').style.display="none";
	
}

punt_api.prototype.showmainout = function()
{
	//_mdm.showmenus();
	puntapi._('wrapper').style.display="block";
	puntapi._('menubar').style.display="block";
	puntapi._('outerwrapper').style.display="block";
	puntapi._('upperrightcolumncontainer').style.display="block";

}

punt_api.prototype.feedbackonhide = function()
{
	//send data 
}
punt_api.prototype.feedback = function()
{
	//puntdialog.startdialog('adminoverview','feedback','','',this.cn+'.returnfeedback','','','')
	var html='';
	html +='<div id="feedbackform" style="margin:5px" >';
	
	html += '<table cellspacing="0" cellpadding="0"><tr><td valign="middle"><div class="ICON2_help">&#160;</div></td>';
	html += '<td  valign="middle"><div class="title">Searching for help?</div></td></tr></table>';	
	html +='<div class="simpletext"><div class="text">Unfortunatly this is not the helpdesk. If you need help please follow the link below to open the helpdesk in a new screen or tab.</div></div>';
	html +='<a href="'+document.location.protocol+'//www.mijndomein.nl/Profile/helpdesk" target="_blank">';
	html += '<table><tr><td valign="middle"><div class="ICON3_help">&#160;</div></td>';
	html += '<td  valign="middle"><div class="text">Click here for support</div></td></tr></table></a><br/><br/>';	
	
	html += '<table  cellspacing="0" cellpadding="0"><tr><td valign="middle"><div class="ICON2_microphone">&#160;</div></td>';
	html += '<td  valign="middle"><div class="title">Please give us your feedback about our Websitecreator</div></td></tr></table>';
	html +='<select id="feedback_topic" style="width:100%; display: none">\n<option value="select" style="width:100%">wsp_feedback_select</option>\n	<option value="interface">wsp_feedback_interface</option>\n<option value="usage">wsp_feedback_usage</option>\n<option value="speed">wsp_feedback_speed</option>\n<option value="other">wsp_feedback_other</option>\n</select>';
	html +='<div style="display:none;">wsp_shortdescription<br/>\n<input type="text" id="feedback_title" style="width:100%"/><br/></div>\nGive a description of your feedback.<br/>\n<textarea id="feedback_descr" style="width:100%;height:150px;"></textarea>\n<br/>';
	html += '<div style="display:inline-block" class="clickable">'+_tT.parse('actionbutton',{onclick:'puntapi.feedbacksubmit()',title:'Submit feedback',icon:'ok'})+'</div>';
	html +='</div>';
	//<input type="button" onclick="puntapi.feedbacksubmit()" id="feedback_submit" value="Send"/>\n</div>';
	_lb.open(html,'60%','60%',undefined,undefined,function(){puntapi.feedbackonhide()});
	
}
punt_api.prototype.feedbackrestore = function()
{
	_lb.hide();
}
punt_api.prototype.feedbacksent = function()
{
	/*
	puntapi._('feedback_title').disabled=false;
	puntapi._('feedback_descr').disabled=false;
	puntapi._('feedback_topic').disabled=false;
	
	puntapi._('feedback_title').value='';
	puntapi._('feedback_descr').value='';
	puntapi._('feedback_topic').value='';*/
	//puntapi._('feedbackform').style.display='block';
	/*puntapi._('feedbackform_notsubmitted').style.display='none';
	puntapi._('feedbackform_submitting').style.display='none';	
	puntapi._('feedbackform_submitted').style.display='block';	*/
	setTimeout(this.cn+'.feedbackrestore()',2000);
	
}
punt_api.prototype.createRequestObject = function()
{
	var sourcefiles = [];
	for(var nn=0;nn<TA.length;nn++)
	{
		sourcefiles[nn].Sourcefile = TA[nn].Sourcefile;
	}
	return sourcefiles;
}
punt_api.prototype.feedbacksubmit = function()
{
	
	var ftitle =puntapi._('feedback_title').value;
	var fdescr =puntapi._('feedback_descr').value;
	var ftopic = puntapi._('feedback_topic').value;
	if(fdescr=='')
	{
		alert('Please fill in the short and the long description.');
		return false;
	}
	puntapi._('feedback_title').disabled=true;
	puntapi._('feedback_descr').disabled=true;
	puntapi._('feedback_topic').disabled=true;
	
	var ajcalls ='';
	try {
		var ajcalls = encodeURIComponent(JSON2.stringify(TA));
		//var ajcalls = encodeURIComponent(JSON2.stringify(this.createRequestObject()));
	}
	catch(e)
	{
		
	
	}

	nr++;
	TA[nr] = new TAjax();
	TA[nr].onReadyresponsecommand = this.cn+'.feedbacksent(getresponsexml('+nr+'),getresponse('+nr+'))';
	TA[nr].cn = 'TA['+nr+']';
	doctosend = 'title='+encodeURIComponent(ftitle);
	doctosend +='&fdescr='+encodeURIComponent(fdescr);
	doctosend +='&ftopic='+encodeURIComponent(ftopic);
	doctosend +='&screeninfo='+encodeURIComponent(screen.width+'x'+screen.height+'x'+screen.colorDepth);
	
	doctosend += '&AJAXCALLS='+ajcalls;
	doctosend += '&URL='+window.location;
	
	
	TA[nr].doctosend=doctosend;
	application ='adminoverview';
	command='sendfeedback';
	if(basepath=='/')
	{
	 	TA[nr].Sourcefile='/sendfeedback';
	}
	else
	{		
		TA[nr].Sourcefile=basepath+'/API/'+application+'/'+command;
	}
	
	TA[nr].doPost();
	var html='';
	html += '<table><tr><td valign="top"><div class="ICON2_microphone">&#160;</div></td>';
	html += '<td  valign="top"><div class="title">Thank you for your feedback!</div><div class="text">Thank you for completing the feedback frm. We greatly appreciate the testing of our software.</div></td></tr></table>';	
	puntapi._('feedbackform').innerHTML=html;
	//puntapi._('feedbackform').style.display='none';
	/*puntapi._('feedbackform_notsubmitted').style.display='none';
	puntapi._('feedbackform_submitting').style.display='block';
	puntapi._('feedbackform_submitted').style.display='none';*/
	
}
punt_api.prototype.activatemenu = function(item,color)
{
	this.activemenuitem=item;
}

punt_api.prototype.loadSites = function(utarget)
{
	
	
	nr++;
	TA[nr] = new TAjax();
	TA[nr].onReadyresponsecommand = this.cn+'.loadSitesRecieve(\''+utarget+'\',getresponsexml('+nr+'),getresponse('+nr+'))';
	TA[nr].cn = 'TA['+nr+']';
	
	application ='domainmanager';
	command='domainlistxml';
	TA[nr].Sourcefile=basepath+'/API/'+application+'/'+command;
	
	TA[nr].doPost();
	
}
punt_api.prototype.loadSitesRecieve = function(yutarget,xml,text)
{
	
 	try{this.writeOptionsToId(yutarget,xml);}catch(e){}
 	
}
punt_api.prototype.doneselectdomain = function(id,description,responsexml,responsetext)
{
	puntapi.setrdomtitle(description,id);
	puntapi.DoCommand('domainmanager','selectdomain',this.currentselecteddomain);
}
punt_api.prototype.selectdomain = function(id,description)
{
	nr++;
	TA[nr] = new TAjax();
	TA[nr].onReadyresponsecommand = 'puntapi.doneselectdomain(\''+id+'\',\''+description+'\',getresponsexml('+nr+'),getresponse('+nr+'))';
	TA[nr].cn = 'TA['+nr+']';
	TA[nr].Sourcefile=basepath+'/API/domainmanager/selectdomain/'+id;
	TA[nr].doPost();	
}
punt_api.prototype.selectdomainonload = function(id,description)
{
	puntapi.setrdomtitle(description,id);
}
punt_api.prototype.restartmenu = function()
{
	startmenu();
	
}
punt_api.prototype.widgetreinit = function()
{
	_tW.init({
		testconfig:'test'
	});
	
}
punt_api.prototype.afterWizardRefresh=function()
{
	this.isAfterWizard=true;
}
punt_api.prototype.init2 = function()
{
	if(this.isAfterWizard)
	{
		if(document.location)
		{
			document.location.reload();
		}
		else
		{
			location.reload(true);	
		}
		
		return false;
	}
	//initialise widgets
	//startmenu();
	_tW.init({
					testconfig:'test',
					zone: basepath
			});
	//this.checkForced();
}
punt_api.prototype.toggleAllWidgets = function()
{
	
}

punt_api.prototype.toggleFullscreen = function()
{

	if(!this.isFullscreen)
	{
		this.isFullscreen=true;	
	}
	else
	{
		this.isFullscreen=false;
	}
	this.rescale();
	
}
punt_api.prototype.init = function()
{
	this.init2();
	
	return true;
	
	this.foldoutright(0);
	this.checkForced();
	if(Dialogframe!='yes')
	{
	this.getWidgets();
	}
	puntapi.updateSystembox();
	puntapi.gethelp('content','content','');
	
	//this.ToggleFoldoutApplication();
	
}




var puntapi = new punt_api('puntapi');
if((basepath == '/Admin') || (basepath == '/Profile') || (basepath == '/Service')|| (basepath == '/Supplier')||(basepath == '/Control')) 
{
	window.onresize = puntapi.rescale;
	window.onbeforeunload = function(){return puntapi.befunload()};
}



//[PACKSEP]


function bc_md3()
{
	
}
bc_md3.prototype._ = function(id)
{
	return document.getElementById(id);
}
bc_md3.prototype._h = function(id,html)
{
	return document.getElementById(id).innerHTML=html;
}
bc_md3.prototype.setCookie = function(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}
bc_md3.prototype.getCookie = function (c_name)
{
	if (document.cookie.length>0)
	  {
	  c_start=document.cookie.indexOf(c_name + "=");
	  if (c_start!=-1)
	    {
	    c_start=c_start + c_name.length+1;
	    c_end=document.cookie.indexOf(";",c_start);
	    if (c_end==-1) c_end=document.cookie.length;
	    return unescape(document.cookie.substring(c_start,c_end));
	    }
	  }
	return "";
}
bc_md3.prototype.shortenText = function(text,mleng)
{
	
	var maxlength=30;
	
	if(typeof mleng!='undefined')
	{
		maxlength = mleng;
	}
	var maxlengthhalf = Math.floor(maxlength/2);
	if(text.length>maxlength)
	{
		
		var textnew = text.substr(0,maxlengthhalf-3)+'...';
		textnew += text.substr(text.length-maxlengthhalf);

		text =textnew;
	}
	return text;
}


bc_md3.prototype.get_html_translation_table =function (table, quote_style) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: noname
    // +   bugfixed by: Alex
    // +   bugfixed by: Marco
    // +   bugfixed by: madipta
    // +   improved by: KELAN
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Frank Forte
    // +   bugfixed by: T.Wild
    // +      input by: Ratheous
    // %          note: It has been decided that we're not going to add global
    // %          note: dependencies to php.js, meaning the constants are not
    // %          note: real constants, but strings instead. Integers are also supported if someone
    // %          note: chooses to create the constants themselves.
    // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
    // *     returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}
    var entities = {},
        hash_map = {},
        decimal = 0,
        symbol = '';
    var constMappingTable = {},
        constMappingQuoteStyle = {};
    var useTable = {},
        useQuoteStyle = {};

    // Translate arguments
    constMappingTable[0] = 'HTML_SPECIALCHARS';
    constMappingTable[1] = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';

    useTable = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';
    useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT';

    if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
        throw new Error("Table: " + useTable + ' not supported');
        // return false;
    }

    entities['38'] = '&amp;';
    if (useTable === 'HTML_ENTITIES') {
        entities['160'] = '&nbsp;';
        entities['161'] = '&iexcl;';
        entities['162'] = '&cent;';
        entities['163'] = '&pound;';
        entities['164'] = '&curren;';
        entities['165'] = '&yen;';
        entities['166'] = '&brvbar;';
        entities['167'] = '&sect;';
        entities['168'] = '&uml;';
        entities['169'] = '&copy;';
        entities['170'] = '&ordf;';
        entities['171'] = '&laquo;';
        entities['172'] = '&not;';
        entities['173'] = '&shy;';
        entities['174'] = '&reg;';
        entities['175'] = '&macr;';
        entities['176'] = '&deg;';
        entities['177'] = '&plusmn;';
        entities['178'] = '&sup2;';
        entities['179'] = '&sup3;';
        entities['180'] = '&acute;';
        entities['181'] = '&micro;';
        entities['182'] = '&para;';
        entities['183'] = '&middot;';
        entities['184'] = '&cedil;';
        entities['185'] = '&sup1;';
        entities['186'] = '&ordm;';
        entities['187'] = '&raquo;';
        entities['188'] = '&frac14;';
        entities['189'] = '&frac12;';
        entities['190'] = '&frac34;';
        entities['191'] = '&iquest;';
        entities['192'] = '&Agrave;';
        entities['193'] = '&Aacute;';
        entities['194'] = '&Acirc;';
        entities['195'] = '&Atilde;';
        entities['196'] = '&Auml;';
        entities['197'] = '&Aring;';
        entities['198'] = '&AElig;';
        entities['199'] = '&Ccedil;';
        entities['200'] = '&Egrave;';
        entities['201'] = '&Eacute;';
        entities['202'] = '&Ecirc;';
        entities['203'] = '&Euml;';
        entities['204'] = '&Igrave;';
        entities['205'] = '&Iacute;';
        entities['206'] = '&Icirc;';
        entities['207'] = '&Iuml;';
        entities['208'] = '&ETH;';
        entities['209'] = '&Ntilde;';
        entities['210'] = '&Ograve;';
        entities['211'] = '&Oacute;';
        entities['212'] = '&Ocirc;';
        entities['213'] = '&Otilde;';
        entities['214'] = '&Ouml;';
        entities['215'] = '&times;';
        entities['216'] = '&Oslash;';
        entities['217'] = '&Ugrave;';
        entities['218'] = '&Uacute;';
        entities['219'] = '&Ucirc;';
        entities['220'] = '&Uuml;';
        entities['221'] = '&Yacute;';
        entities['222'] = '&THORN;';
        entities['223'] = '&szlig;';
        entities['224'] = '&agrave;';
        entities['225'] = '&aacute;';
        entities['226'] = '&acirc;';
        entities['227'] = '&atilde;';
        entities['228'] = '&auml;';
        entities['229'] = '&aring;';
        entities['230'] = '&aelig;';
        entities['231'] = '&ccedil;';
        entities['232'] = '&egrave;';
        entities['233'] = '&eacute;';
        entities['234'] = '&ecirc;';
        entities['235'] = '&euml;';
        entities['236'] = '&igrave;';
        entities['237'] = '&iacute;';
        entities['238'] = '&icirc;';
        entities['239'] = '&iuml;';
        entities['240'] = '&eth;';
        entities['241'] = '&ntilde;';
        entities['242'] = '&ograve;';
        entities['243'] = '&oacute;';
        entities['244'] = '&ocirc;';
        entities['245'] = '&otilde;';
        entities['246'] = '&ouml;';
        entities['247'] = '&divide;';
        entities['248'] = '&oslash;';
        entities['249'] = '&ugrave;';
        entities['250'] = '&uacute;';
        entities['251'] = '&ucirc;';
        entities['252'] = '&uuml;';
        entities['253'] = '&yacute;';
        entities['254'] = '&thorn;';
        entities['255'] = '&yuml;';
    }

    if (useQuoteStyle !== 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }
    if (useQuoteStyle === 'ENT_QUOTES') {
        entities['39'] = '&#39;';
    }
    entities['60'] = '&lt;';
    entities['62'] = '&gt;';


    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal);
        hash_map[symbol] = entities[decimal];
    }

    return hash_map;
}
bc_md3.prototype.base_convert = function (number, frombase, tobase) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philippe Baumann
    // +   improved by: Rafał Kukawski (http://blog.kukawski.pl)
    // *     example 1: base_convert('A37334', 16, 2);
    // *     returns 1: '101000110111001100110100'
    return parseInt(number + '', frombase | 0).toString(tobase | 0);
}

bc_md3.prototype.html_entity_decode =function(string, quote_style) {
    // http://kevin.vanzonneveld.net
    // +   original by: john (http://www.jd-tech.net)
    // +      input by: ger
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   improved by: marc andreu
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Ratheous
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Nick Kolosov (http://sammy.ru)
    // +   bugfixed by: Fox
    // -    depends on: get_html_translation_table
    // *     example 1: html_entity_decode('Kevin &amp; van Zonneveld');
    // *     returns 1: 'Kevin & van Zonneveld'
    // *     example 2: html_entity_decode('&amp;lt;');
    // *     returns 2: '&lt;'
    var hash_map = {},
        symbol = '',
        tmp_str = '',
        entity = '';
    tmp_str = string.toString();

    if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }

    // fix &amp; problem
    // http://phpjs.org/functions/get_html_translation_table:416#comment_97660
    delete(hash_map['&']);
    hash_map['&'] = '&amp;';

    for (symbol in hash_map) {
        entity = hash_map[symbol];
        tmp_str = tmp_str.split(entity).join(symbol);
    }
    tmp_str = tmp_str.split('&#039;').join("'");

    return tmp_str;
}



var md3 = new bc_md3();



//[PACKSEP]



function md3_UIsettingmanager()
{


}
md3_UIsettingmanager.prototype.init = function()
{
	//get settings from cookies
}

md3_UIsettingmanager.prototype.getValue =function(itemname,defaultvalue)
{
	
	var tmpval = md3.getCookie('md3setting_'+itemname);
	if(tmpval=='')
	{
		return defaultvalue
	}
	return tmpval;
}
md3_UIsettingmanager.prototype.setValue =function(itemname,val)
{
	md3.setCookie('md3setting_'+itemname,val,365);
}

md3_UIsettingmanager.delayedRead = function()
{
	
}

md3_UIsettingmanager.delayedWrite = function()
{
	
}

md3.settings = new md3_UIsettingmanager();
md3.settings.init();


//[PACKSEP]



function punt_dialog(cn)
{
	this.cn = cn;
	this.returnfunction = '';
	this.application	= '';
	this.command		= '';
	this.idval 			= '';
	this.query 			= '';
	this.query2 		= '';
	this.returndata 	= '';
	this.returndata2 	= '';
	this.semi			= false;
}
punt_dialog.prototype.changecommand = function(application,command,id,query)
{
	this.application = application;
	this.command = command;
	this.idval=id
	this.query=query+'&dialog=yes'; 

	puntapi.DoCommand(this.application,this.command,this.idval,this.query+this.query2,'','','dialogoutput');
	
	
}
punt_dialog.prototype.startSemiDialog = function(htmlpre,htmlpost,returnfunction,returndata,returndata2,query2,notclosable,useloading)
{
	this.returnfunction = returnfunction;
	this.returndata = returndata;
	this.returndata2 = returndata2;	
	this.semi=true;
	this.query2=query2;
	this.onCloseMethod=false;
	if(typeof notclosable !='undefined')
	{
		notclosable=notclosable;
		this.notclosable=notclosable;
	}
	else
	{
		notclosable=false;
		this.notclosable=false;
	}
	
	if (typeof useloading == 'undefined')
	{
		useloading=false
	}
	if (!useloading)
	{
		this.useloading = false;	
		_lb.open(htmlpre+'<div id="dialogcontainer"><div id="dialogactionbuttons">&nbsp;</div><div id="dialogoutput" class="dialogboxoutput"></div><div style="clear:both;"/></div>'+htmlpost,'60%','90%',undefined,undefined,function(){puntdialog.onhide()},notclosable);
	}
	else
	{
		this.useloading = true;
		_lb.open('<div id="loaderprogressbar" style="width: 250px; height: 150px; padding-top: 100px; text-align: center"><img src="/Layout/Mijndomein/images/loading.gif" /></div><div id="loadercontainer" style="display: none">' + htmlpre + '<div id="dialogcontainer"><div id="dialogactionbuttons">&nbsp;</div><div id="dialogoutput" class="dialogboxoutput"></div><div style="clear:both;"/></div>'+htmlpost+'</div>','60%','90%',undefined,undefined,function(){puntdialog.onhide()},notclosable);		
	}
	
	puntapi.changeActionbuttonTarget('dialog');
	puntapi.defaulttarget='dialogoutput';
	//puntapi.DoCommand(this.application,this.command,this.idval,this.query+this.query2,'','','dialogoutput');
	puntapi.defaulttarget='dialogoutput';
}
punt_dialog.prototype.hideLoading = function()
{
	try
	{
		var content = md3._('loadercontainer');
		if (content)
		{				
			var progress = md3._('loaderprogressbar');
			progress.style.display = 'none';
			content.style.display = 'block';
		}
	}
	catch(e)
	{
		
	}
}
punt_dialog.prototype.startdialog = function(application,command,id,query,returnfunction,returndata,returndata2,query2)
{
	this.onCloseMethod=false;
	this.semi=false;
	this.application = application;
	this.command=command;
	this.idval =id;
	this.query=query+'&dialog=yes';
	//var query2 ='';
	//alert(query2);
	this.notclosable=false;
	if(typeof query2=='undefined')
	{
		query2='';
	}
	else
	{
		query3 = query2.split('&');
		query2 = '';
		for(u=0;u<query3.length;u++)
		{
		query2+= '&'+query3[u];
		}
	}
	this.query2=query2;
	this.returnfunction = returnfunction;
	this.returndata = returndata;
	this.returndata2 = returndata2;
	_lb.open('<div id="dialogcontainer"><div id="dialogactionbuttons">&nbsp;</div><div id="dialogoutput" class="dialogboxoutput"><center><div class="title">Please wait</div><div class="text">Please wait while the dialog is loading</div></center></div><div style="clear:both;"/></div>','60%',undefined,undefined,undefined,function(){puntdialog.onhide()});
	puntapi.changeActionbuttonTarget('dialog');
	puntapi.defaulttarget='dialogoutput';
	puntapi.DoCommand(this.application,this.command,this.idval,this.query+this.query2,'','','dialogoutput');
	puntapi.defaulttarget='dialogoutput';
	
	
}
punt_dialog.prototype.addslashes= function(str) 
{
	str=str.replace(/\'/g,'\\\'');
	str=str.replace(/\"/g,'\\"');
	str=str.replace(/\\/g,'\\\\');
	str=str.replace(/\0/g,'\\0');
	return str;
}
punt_dialog.prototype.stripslashes= function(str) 
{
	str=str.replace(/\\'/g,'\'');
	str=str.replace(/\\"/g,'"');
	str=str.replace(/\\0/g,'\0');
	str=str.replace(/\\\\/g,'\\');
	return str;
}

punt_dialog.prototype.returnval = function()
{

	this.returnArguments=arguments;
	var returndata 		= this.returndata;
	var returndata2 	= this.returndata2;
	if(typeof returndata =='undefined')
	{
		returndata ='';
	}
	if(typeof returndata2 =='undefined')
	{
		returndata2 ='';
	}
	
	var argumentlist = [];
	for(var i=0; i<arguments.length; i++) 
	{
		if(typeof arguments[i] =='undefined')
		{
			continue;
		}
    	argumentlist[argumentlist.length] ='\''+this.addslashes(arguments[i])+'\'';
    	
	}
	argumentlist[argumentlist.length] ='\''+this.addslashes(returndata)+'\'';
	argumentlist[argumentlist.length] ='\''+this.addslashes(returndata2)+'\'';
	//puntapi.hidelightbox(0);
	if (!this.semi) {
		puntapi.changeActionbuttonTarget('main');
		_lb.hide();
	}
	
	var cmd = this.returnfunction+'('+argumentlist.join(',')+')';

	setTimeout(cmd,100);

	
}
punt_dialog.prototype.onhide = function()
{
		if(typeof this.onCloseMethod =='function')
		{
			this.onCloseMethod();
		}
		puntapi.changeActionbuttonTarget('main');
		puntapi.defaulttarget='';
}
punt_dialog.prototype.close = function()
{

		if(typeof this.onCloseMethod =='function')
		{
			this.onCloseMethod();
		}
		puntapi.changeActionbuttonTarget('main');
		_lb.hide();
		puntapi.defaulttarget='';
}
punt_dialog.prototype.cancelEsc = function()
{
	if(this.notclosable)
	{
		
	}
	else
	{
		this.cancel();
	}
}
punt_dialog.prototype.cancel = function()
{
		if(typeof this.onCloseMethod =='function')
		{
			this.onCloseMethod();
		}
		puntapi.changeActionbuttonTarget('main');
		_lb.hide();
		puntapi.defaulttarget='';
}


puntdialog = new punt_dialog('puntdialog');

//[PACKSEP]


/*
A Lightbox/Dialog window by John Bakker
*/

function lightbox(cn)
{
	this.cn = cn;
	this.defaultHeight=400;
	this.defaultWidth=300;
	this.defaultCornerSize='5';
	this.defaultCornerColor='858585';
	this.defaultContainerStyle = 'background-color:white;overflow:none;margin:0 auto;text-align:center;position:relative;behavior:url(/Layout/Mijndomein/PIE.htc);width:auto;';
	this.defaultInnerStyle = 'font-family:Trebuchet MS;font-size:10px;padding:4px;text-align:left;';//overflow:auto';
	this.cornerBasePath = '/Layout/corners/';
	this.disableautohide=false;
	this.disabled=false;
	this.savescrolltop=0;
	this.tmpOuterWidth='';
	this.addborderradius=true;
}
lightbox.prototype.hide = function()
{
	this.onClose();
	bdy = document.getElementsByTagName('body').item(0);
	
	var UL = _lb._('LB_underlay');
	var OL = _lb._('LB_overlay');
	UL.style.display='none';
	OL.style.display='none';
	
	
	window.scrollTo(0,this.savescrolltop);
	this.opened=false;
}


lightbox.prototype.scrolltop = function()
{
	var ScrollTop = document.body.scrollTop;
	if (ScrollTop == 0)
	{
	
	    if (window.pageYOffset)
	
	        ScrollTop = window.pageYOffset;
	
	    else
	
	        ScrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
	
	}

	return ScrollTop;
}
lightbox.prototype.checkpresent = function()
{
	var UL = _lb._('LB_underlay');
	var OL = _lb._('LB_overlay');
	
	var bdy = document.getElementsByTagName('body').item(0);
	//check if the lightbox is already there.
	
	if(!UL)
	{
		
		//if not ... add it
		var UL = document.createElement('div');
	   				UL.setAttribute('id', 'LB_underlay');
	    			UL.setAttribute('class', 'LB_underlay');
		var OL = document.createElement('div');
	   				OL.setAttribute('id', 'LB_overlay');
	    			OL.setAttribute('class', 'LB_overlay');	  
	    UL.innerHTML = '.';
		UL.style.color='#000000';
	    OL.innerHTML = 'b';
	    	
	    bdy.appendChild(UL);
	    bdy.appendChild(OL);				
		UL = _lb._('LB_underlay');
		OL = _lb._('LB_overlay');	    	
	    
	}	
	else
	{
		
	}
	    
}
lightbox.prototype._ = function(id)
{
	return document.getElementById(id);
}
lightbox.prototype.poller= function()
{
	//polls thelightbox 
}
lightbox.prototype.rescale = function()
{
	var viewprt = {};
	var iContainer = puntapi._('lbInsideContainer');
	var iContainer2 = puntapi._('dialogbox_output');
	
	if(!iContainer)
	{
		return false;
	}
	if(!this.opened)
	{
		return false;
	}
	if(this.resaleinprogress)
	{
		//alert('no-re-rescale');
		return false;
	}
	try {
		
		
		
		this.rescaleinprogress = true;


		this.checkpresent(); 
	
		var UL = _lb._('LB_underlay');
		var OL = _lb._('LB_overlay');	
		
		OL.style.top='0px';
		OL.style.left='0px';
		
		var dimen = new dimensions();
		
		
		var containerDim = dimen.dimensions(iContainer);
		var containerDim2 = dimen.dimensions(iContainer2);
		var ua = navigator.userAgent;
		
		var isbadie = /MSIE [567]/.test(ua);
		if (isbadie) 
		{
			iContainer.style.width ='612px';
		}
		var container2Dim = dimen.dimensions(iContainer2);
		var oldim = dimen.dimensions(OL);
		//alert(JSON.stringify(container2Dim));
		pagesz = this.getPageSize();
		viewprt = {};
		viewprt.height = pagesz[3];
		viewprt.width = pagesz[2];
		viewprt.docheight = pagesz[1];
		viewprt.docwidth = pagesz[0];
	 	viewprt = this.getviewportsize();

		UL.style.width=viewprt.width+'px';
		UL.style.height=viewprt.height+'px';
		

		//alert('rescale_LB' + JSON.stringify(containerDim)+'\n'+JSON.stringify(viewprt));
		//reposition the window...
		var leftRemain =0;
		var remainderW = viewprt.width-oldim.w;
		if (remainderW > 0) {
			leftRemain = Math.floor(remainderW / 2);			
		}
		var topRemain =0;
		var remainderH = viewprt.height-oldim.h;
		if (remainderH > 0) {
			topRemain = Math.floor(remainderH / 2);			
		}
		OL.style.left=+(leftRemain)+'px';		
		OL.style.top=+(this.savescrolltop+topRemain)+'px';
		
		
		pagesz = this.getPageSize();
		viewprt = {};
		viewprt.height = pagesz[3];
		viewprt.width = pagesz[2];
		viewprt.docheight = pagesz[1];
		viewprt.docwidth = pagesz[0];
	 	viewprt = this.getviewportsize();

		if(oldim.w>viewprt.width)
		{
			iContainer.width=viewprt.width-40;
		}

		UL.style.width='100%';
		UL.style.height='100%';

		UL.style.position='fixed';

		UL.style.top='0px';
		UL.style.left='0px';

		//UL.style.height=viewprt.docheight+'px';

		//alert('rescale_LB' + JSON.stringify(containerDim)+'\n'+JSON.stringify(viewprt));		 

	}
	catch(e)
	{
		alert('exception in rescaling'+JSON.stringify(e.message));
	}
	
	this.rescaleinprogress=false;
	
}
lightbox.prototype.open = function(contents,width,height,cornercolor,cornersize,onClose,notclosable)
{
	if(typeof window.onresize!='function')
	{
		window.onresize = function(){_lb.rescale();};
	}
	if(typeof onClose =='function')
	{
		this.onClose = onClose;
	}
	else
	{
		this.onClose = function(){}
	}
	if(typeof notclosable !='undefined')
	{
		if(typeof notclosable =='boolean')
		{
			this.notclosable=notclosable;
			this.disableautohide=notclosable;
		}
		else
		{
			this.notclosable=true;
			this.disableautohide=true;
		}
	}
	else
	{
		this.notclosable=false;
		this.disableautohide=false;
	}
	
	var UL = _lb._('LB_underlay');
	var OL = _lb._('LB_overlay');	
	
	pagesz=this.getPageSize();	
 	viewprt = {};
 	viewprt.height=pagesz[3];
 	viewprt.width=pagesz[2];
 	viewprt.docheight=pagesz[1];
 	viewprt.docwidth=pagesz[0];	
	this.savescrolltop = this.scrolltop();
 	this.currentheightvar=height;
 	this.currentwidthvar=width; 			
	//get the body
	var bdy = document.getElementsByTagName('body').item(0);

	
	
    var browserName = navigator.appName;	
	//check if the lightbox is already there.

	this.checkpresent(); 

	var UL = _lb._('LB_underlay');
	var OL = _lb._('LB_overlay');	
	
		UL.style.position='absolute';
		UL.style.top='0px';
		UL.style.left='0px';
			
		UL.style.width='100%';
		UL.style.height=(viewprt.docheight)+'px';
	
		
		UL.style.zIndex='250';
		
		UL.style.backgroundColor='black';
	
		if (browserName == "Microsoft Internet Explorer") {	  
		    
		    UL.style.filter ='alpha(opacity='+60+')';
		    
		}
		else
		{
			UL.style.opacity =0.6;
		}	
		
		
		//move it to the top....
		OL.style.zIndex = '251';
		OL.style.position='absolute';
		OL.style.top='0px';


		
		
		
		
	
		
	
	
	//show them for a second
	UL.style.display='block';
	OL.style.display='block';	
	
	
	var roundboxhtml = this.generateRoundBox('dialogbox_output',cornercolor,cornersize);
	OL.innerHTML=roundboxhtml;
	_lb._('dialogbox_output').innerHTML = contents;
	
	if(!this.disableautohide)
	{
		var onC = this.cn+'.hide()';
		UL.onclick= new Function(onC);

	}
	else
	{
		UL.onclick= function(){};
	}
			
	this.opened=true;
	
	this.rescale();
}
lightbox.prototype.rescalebackup = function()
{
	var toppos=0;
	var leftpos=0;
	try {
		var wasshown = false;
		if (!this.disabled) {
			var UL = _lb._('LB_underlay');
			var OL = _lb._('LB_overlay');
			try {
				if (UL) {
					if (UL.style.display == 'block') {
						UL.style.display = 'none';
						OL.style.display = 'none';
						//was shown
						wasshown = true;
					}
				}
			} 
			catch (e) {
				
				return false;
			}
			height = this.currentheightvar;
			width = this.currentwidthvar;
			
			
//			viewprt = this.getviewportsize();
			pagesz = this.getPageSize();
//			viewprt = this.getviewportsize();

			viewprt = {};
			viewprt.height = pagesz[3];
			viewprt.width = pagesz[2];
			viewprt.docheight = pagesz[1];
			viewprt.docwidth = pagesz[0];
			
			
			
			
			
			
			//this.savescrolltop = this.scrolltop();
			
			if ((typeof height != 'undefined')) {
				if (height.indexOf('%')) {
					height2 = height.split('%');
					height = Math.floor((viewprt.height / 100) * height2[0]);
				}
			}
			else {
				height = this.defaultHeight;
			}
			
			if (typeof width != 'undefined') {
				//check if height and width are set
				
				if (width.indexOf('%')) {
					width2 = width.split('%');
					width = Math.floor((viewprt.width / 100) * width2[0]);
				}
			}
			else {
				//set em manually
				
				width = this.defaultWidth;
				
			}
			try {
				heightspace = (viewprt.height - height);
				widthspace = (viewprt.docwidth - width);
				
				if (heightspace > 0) {
					//calculate the spacing from top left
					toppos = heightspace / 2;
				}
				else {
					toppos = 0;
				}
				
				if (widthspace > 0) {
					leftpos = widthspace / 2;
				}
				else {
					leftpos = 0;
				}
				if (typeof cornercolor == 'undefined') {
					cornercolor = this.defaultCornerColor;
				}
				if (typeof cornersize == 'undefined') {
					cornersize = this.defaultCornerSize;
				}
				if (typeof innerstyle == 'undefined') {
					innerstyle = this.defaultInnerStyle;
				}
				
				
			//calculate the size of the box.
			
			
			}
			catch(e)
			{
				
			}
			//get the body
			bdy = document.getElementsByTagName('body').item(0);
			
			
			
				var browserName = navigator.appName;
				//check if the lightbox is already there.
				this.checkpresent();
				UL = _lb._('LB_underlay');
				OL = _lb._('LB_overlay');
				
				
				
				UL.style.position = 'absolute';
				UL.style.top = '0px';
				UL.style.left = '0px';
				
				UL.style.width = '100%';
				UL.style.height = (viewprt.docheight) + 'px';
				
				
				UL.style.zIndex = '250';
				
				UL.style.backgroundColor = 'black';
				
				if (browserName == "Microsoft Internet Explorer") {
				
					UL.style.filter = 'alpha(opacity=' + 60 + ')';
					
				}
				else {
					UL.style.opacity = 0.6;
				}
				
				//UL.style.fontSize = '0px;';
			try {	
				
				
				
				OL.style.zIndex = '250';
				OL.style.position = 'absolute';
				OL.style.top = (toppos + this.savescrolltop) + 'px';
				OL.style.left = leftpos + 'px';
				
				OL.style.width = width + 'px';
				OL.style.height = height + 'px';
				if (wasshown) {

					UL.style.display = 'block';
					OL.style.display = 'block';
				}
				else
				{					
					UL.style.display = 'none';
					OL.style.display = 'none';
				}
			}
			catch(e)
			{
				
			}
		}
	}
	catch(e)
	{
		
	}
}
lightbox.prototype.openBackup = function(contents,width,height,cornercolor,cornersize,onClose)
{

	if(typeof onClose =='function')
	{
		this.onClose = onClose;
	}
	else
	{
		this.onClose = function(){}
	}
	//get the screen dimensions
	if(!this.disabled)
	{
		
	pagesz=this.getPageSize();
 	viewprt = this.getviewportsize();
 	/*
 	var dimen = new dimensions();
 //	bdy = document.getElementsByTagName('body').item(0);
 	afm = dimen.dimensions(_lb._('wrapper'));*/

 	viewprt = {};
 	viewprt.height=pagesz[3];
 	viewprt.width=pagesz[2];
 	viewprt.docheight=pagesz[1];
 	viewprt.docwidth=pagesz[0];
	
	
 	

 	this.savescrolltop = this.scrolltop();
 	
 	this.currentheightvar=height;
 	this.currentwidthvar=width; 		
	if(typeof height!='undefined')
	{
		if(height.indexOf('%')!=-1){height2 = height.split('%');height = (viewprt.height/100)*height2[0];}
		else if(height.indexOf('px'))
		{
			var heightparts = height.split('px');
			height=heightparts[0];
		}
		
	}
	else
	{
		height = this.defaultHeight;
	}

 	if(typeof width!='undefined')
 	{
 		//check if height and width are set
 		
 		if(width.indexOf('%')!=-1){width2 = width.split('%');width = (viewprt.width/100)*width2[0];}
		else if(width.indexOf('px'))
		{
			var widthparts = width.split('px');
			width=widthparts[0];
		}
 	}
 	else
 	{
 		
 		width = this.defaultWidth;
 		
 		
 	}

 	heightspace =  (viewprt.height-height);
 	widthspace =  (viewprt.width-width);
 	
 	if(heightspace>0)
 	{
 		//calculate the spacing from top left
 		toppos = heightspace/2;
 	}
 	else
 	{
 		toppos = 0;
 	}
 	
 	if(widthspace>0)
 	{
 		leftpos = widthspace/2;
 	}
 	else
 	{
 		leftpos = 0;
 	}
	if(typeof cornercolor=='undefined')
	{
		cornercolor=this.defaultCornerColor;
	}
	if(typeof cornersize=='undefined')
	{
		cornersize=this.defaultCornerSize;
	}
	if(typeof innerstyle=='undefined')
	{
		if (typeof this.tmpInnerStyle != 'undefined') 
		{
			innerstyle = this.tmpInnerStyle;
			this.tmpInnerStyle=undefined;
		}
		else
		{
			innerstyle = this.defaultInnerStyle;
		}
	}	
 	
 	
 	//calculate the size of the box.
 	
 	

	//get the body
	bdy = document.getElementsByTagName('body').item(0);

	
	
    var browserName = navigator.appName;	
	//check if the lightbox is already there.

	this.checkpresent(); 

	var UL = _lb._('LB_underlay');
	var OL = _lb._('LB_overlay');	
	
		
		
		 
	    			UL.style.position='absolute';
	    			UL.style.top='0px';
	    			UL.style.left='0px';
	    				
	    			UL.style.width='100%';
	    			UL.style.height=(viewprt.docheight)+'px';

	    			
	    			UL.style.zIndex='250';
	    			
	    			UL.style.backgroundColor='black';
	
					if (browserName == "Microsoft Internet Explorer") {	  
	  			    
       			    UL.style.filter ='alpha(opacity='+60+')';
       			    
					}
					else
					{
						UL.style.opacity =0.6;
					}
					
       			    //UL.style.fontSize='0px;';
       			    
 					
 			
					
	    			OL.style.zIndex='250';	    			
	    			OL.style.position='absolute';
	    			OL.style.top=(toppos+this.savescrolltop)+'px';
	    			OL.style.left=leftpos+'px';
	    			
	    			OL.style.width=width+'px';
	    			OL.style.height=height+'px';  
	    			
	    			  			
	    			OL.innerHTML = this.generateRoundBox('dialogbox_output',cornercolor,cornersize);
					
	    			
	    			
	    	
	    UL.style.display='none';
		OL.style.display='none';
	    	
	    	


		

	if(!this.disableautohide)
	{
		var onC = this.cn+'.hide()';
		UL.onclick= new Function(onC);
		_lb._('dialogbox_output').style.width=width-(cornersize*2)+'px';
		_lb._('dialogbox_output').style.height=height-((cornersize*2)+20)+'px';
	}
	else
	{
		_lb._('dialogbox_output').style.width=width-(cornersize*2)+'px';
		_lb._('dialogbox_output').style.height=height-(cornersize*2)+'px';
	}
	
		_lb._('dialogbox_output').innerHTML = contents;
	
	
	UL.style.display='block';
	
	OL.style.display='block';
	
	pagesz=this.getPageSize();
		
	
	}
	
	
}
lightbox.prototype.generateRoundBox = function(id,cornercolor,cornersize,innerstyle)
{
	if(typeof cornercolor=='undefined')
	{
		cornercolor=this.defaultCornerColor;
	}
	if(typeof cornersize=='undefined')
	{
		if (typeof this.cornersize != 'undefined') 
		{
			cornersize = this.cornersize;
		}
		else
		{
			cornersize=this.defaultCornerSize;
		}
	}
	if(typeof innerstyle=='undefined')
	{
		if (typeof this.tmpInnerStyle != 'undefined') 
		{
			innerstyle = this.tmpInnerStyle;
			this.tmpInnerStyle=undefined;
		}
		else
		{
			innerstyle = this.defaultInnerStyle;
		}		
	}	
	if(typeof containerstyle=='undefined')
	{
		if (typeof this.containerstyle != 'undefined') 
		{
			containerstyle = 'overflow:none;margin:0 auto;text-align:center;'+this.containerstyle;
			this.containerstyle=undefined;
		}
		else
		{
			containerstyle=this.defaultContainerStyle;
		}
	}
	if ((this.addborderradius==true) && (cornersize > 0))
	{
		containerstyle+='-moz-border-radius:'+cornersize+'px;border-radius:'+cornersize+'px;';
		this.addborderradius = undefined;
	}

	if(this.tmpOuterWidth!='')
	{
		containerstyle+='width:'+this.tmpOuterWidth;
		this.tmpOuterWidth='';
	}
	//now generate the html...
	filetl = this.cornerBasePath+'images/corner_'+cornersize+'_'+cornercolor+'_tl.png';
	filetr = this.cornerBasePath+'images/corner_'+cornersize+'_'+cornercolor+'_tr.png';
	filebl = this.cornerBasePath+'images/corner_'+cornersize+'_'+cornercolor+'_bl.png';
	filebr = this.cornerBasePath+'images/corner_'+cornersize+'_'+cornercolor+'_br.png';
	fileblank = this.cornerBasePath+'images/blank.gif';
	if(this.notclosable)
	{
		var fileclose = this.cornerBasePath+'images/blank.gif';
	}
	else
	{
		var fileclose = this.cornerBasePath+'images/close2.png';	
	}
	
	
	
	stylehoriz = 'width:'+cornersize+'px;font-size:0px;background-color:#'+cornercolor;
	stylevert = 'height:'+cornersize+'px;font-size:0px;background-color:#'+cornercolor;
	ht='';
	ht+='';
	ht+='<div class="lightboxContainer" id="lbOutsideContainer" style="'+containerstyle+'">'
	ht+='<div id="lbInsideContainer"><div style="float:right;margin-top:5px;margin-bottom:5px;margin-right:5px;cursor:pointer" onclick="'+this.cn+'.hide();'+'"><img src="'+fileclose+'"/></div><div class="lightboxInsideContainer" style="'+innerstyle+'" id="'+id+'"></div></div>';
	ht+='</div>';
/*	ht+='<style>.lightboxContainer{-moz-border-radius:5px;border-radius:5px;position:relative;behavior:url(/Layout/Mijndomein/PIE.htc);width:auto;}</style>';
	ht+='<table cellspacing="0" cellpadding="0">'// width="100%" >';
	ht+='<tr><td ><img src="'+filetl+'"/></td><td style="'+stylevert+'"><img src="'+fileblank+'" width="100%" height="100%"/></td><td><img src="'+filetr+'"/></td></tr>';
	ht+='<tr><td style="'+stylehoriz+'" ><img src="'+fileblank+'" width="'+cornersize+'px" /></td><td  valign="top" style="'+containerstyle+'">';*/
	
	/*ht+='</td><td style="'+stylehoriz+'"><img src="'+fileblank+'" width="'+cornersize+'px" height="100%"/></div></td></tr>';
	ht+='<tr><td><img src="'+filebl+'"/></td><td  style="'+stylevert+'"><img src="'+fileblank+'" width="100%" height="100%"/></td><td><img src="'+filebr+'"/></td></tr>';
	ht+='</table>';*/
	return ht;
	
}
lightbox.prototype.pageHeight = function()
{
	var docHeight;
	if (typeof document.height != 'undefined') {
	docHeight = document.height;

	
	}
	else if (document.compatMode && document.compatMode != 'BackCompat') {
	docHeight = document.documentElement.scrollHeight;
       
         	
	}
	else if (document.body && typeof document.body.scrollHeight !=
	'undefined') {
	docHeight = document.body.scrollHeight;
	}
	return docHeight;
}
lightbox.prototype.pageWidth = function()
{
	var docWidth;
	if (typeof document.Width != 'undefined') {
	docWidth = document.Width;

	
	}
	else if (document.compatMode && document.compatMode != 'BackCompat') {
	docWidth = document.documentElement.scrollWidth;
       
         	
	}
	else if (document.body && typeof document.body.scrollWidth !='undefined') {
	docWidth = document.body.scrollWidth;
	}
	return docWidth;
}
lightbox.prototype.getPageSizeWithScroll = function(){
	if (window.innerHeight && window.scrollMaxY) {// Firefox
		yWithScroll = window.innerHeight + window.scrollMaxY;
		xWithScroll = window.innerWidth + window.scrollMaxX;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		yWithScroll = document.body.scrollHeight;
		xWithScroll = document.body.scrollWidth;
	} else { // works in Explorer 6 Strict, Mozilla (not FF) and Safari
		yWithScroll = document.body.offsetHeight;
		xWithScroll = document.body.offsetWidth;
  	}
	arrayPageSizeWithScroll = new Array(xWithScroll,yWithScroll);
	//alert( 'The height is ' + yWithScroll + ' and the width is ' + xWithScroll );
	return arrayPageSizeWithScroll;
}

lightbox.prototype.getviewportsize = function()
{
	
	
	
 var viewportwidth;
 var viewportheight;
 var pagesizewithscroll = this.getPageSizeWithScroll(); 
 var viewprt = {};  
		
 var docwidth = pagesizewithscroll[0];
 var docheight = pagesizewithscroll[1];		
 
 if (typeof window.innerWidth != 'undefined')
 {
      viewportwidth = window.innerWidth;
      viewportheight = window.innerHeight;

 }
 else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0)
 {
       viewportwidth = document.documentElement.clientWidth;
       viewportheight = document.documentElement.clientHeight;

 }
 else
 {
       viewportwidth = document.getElementsByTagName('body')[0].clientWidth;
       viewportheight = document.getElementsByTagName('body')[0].clientHeight;
 }
 viewprt = {};
 viewprt.width=viewportwidth;
 viewprt.height=viewportheight;
 if(docheight<viewportheight)
 {
 	docheight = viewportheight;
 }
 viewprt.docheight=docheight;
 if(docwidth<viewportwidth)
 { 
 	docwidth = viewportwidth;
 }
 viewprt.docwidth=docwidth;

  
 return viewprt;
}








//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.org
//
lightbox.prototype.getPageScroll = function()
{

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}



//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
lightbox.prototype.getPageSize = function()
{
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}







lightbox.prototype.screeninfo = function()
{
	var tmpdata = this.getPageSize();
	var tmpdata2 = this.getPageScroll();
	/*alert(tmpdata);
	alert(tmpdata2);*/
}








_lb = new lightbox('_lb');




//[PACKSEP]



function punt_media(cn)
{
	this.cn = cn;
	this.reloaditem=0;
	this.appname='mediaalbum';
	this.minithumbsize=40;
	this.buttons = [];
	Tu=0;
	this.buttons[Tu]= [];
	this.buttons[Tu].descr='Albums';
	this.buttons[Tu].command='viewalbumslist';
	this.buttons[Tu].local='openalbumlist';
	this.buttons[Tu].target='';
	this.buttons[Tu].enabled=true;
	this.buttons[Tu].icon='Properties';
	this.buttons[Tu].usesid=false;
	this.buttons[Tu].ask='';
	Tu++;
	this.buttons[Tu]= [];
	this.buttons[Tu].descr='New album';
	this.buttons[Tu].command='editalbum';
	this.buttons[Tu].local='newalbum';
	
	this.buttons[Tu].target='';
	this.buttons[Tu].enabled=true;
	this.buttons[Tu].icon='New';
	this.buttons[Tu].usesid=false;
	this.buttons[Tu].local='';
	this.buttons[Tu].ask='';
	Tu++;
	this.buttons[Tu]= [];
	this.buttons[Tu].descr='Upload items';
	this.buttons[Tu].command='uploadmedia';
	this.buttons[Tu].target='';
	this.buttons[Tu].icon='Plus';
	this.buttons[Tu].usesid=true;
	this.buttons[Tu].enabled=true;
	this.buttons[Tu].local='';
	this.buttons[Tu].ask='';
	Tu++;
	this.buttons[Tu]= [];
	this.buttons[Tu].descr='Edit';
	this.buttons[Tu].command='editalbum';
	this.buttons[Tu].target='';
	this.buttons[Tu].icon='Edit';
	this.buttons[Tu].usesid=true;
	this.buttons[Tu].local='';	
	this.buttons[Tu].enabled=false;
	this.buttons[Tu].ask='';	
	Tu++;		
	this.buttons[Tu]= [];
	this.buttons[Tu].descr='Remove album';
	this.buttons[Tu].command='deletealbum';
	this.buttons[Tu].target='';
	this.buttons[Tu].icon='Delete';
	this.buttons[Tu].usesid=true;
	this.buttons[Tu].local='';	
	this.buttons[Tu].ask='Are you sure?';
	this.buttons[Tu].enabled=false;
	Tu++;	
	this.buttons[Tu]= [];
	this.buttons[Tu].descr='(re)move media';
	this.buttons[Tu].command='multidoalbumitems';
	this.buttons[Tu].target='';
	this.buttons[Tu].icon='Redo';
	this.buttons[Tu].usesid=true;
	this.buttons[Tu].local='';	
	this.buttons[Tu].ask='';
	this.buttons[Tu].enabled=false;
	Tu++;		
	
	this.stepspeed=50;
}


punt_media.prototype.displayfullscreen = function(basepath,id,ext,refkey,w,h)
{
	//due to the automatic conversion to jpg and not saving the png or gifs I hard change the extension to 'jpg' ~webdev
	//ext ='jpg';
	if(refkey!='')
	{
		refkey='?refkey='+refkey;
	}
	else
	{
		refkey='';
	}
	var oclick = 'onclick="puntapi.hidelightbox(3);"';

	// get window size
	var viewport = puntapi.getviewportsize();
	// set max size
	var maxWidth = Math.round((viewport['width']/100)*90);
	var maxHeight = Math.round((viewport['height']/100)*90);
	// default image sizes
	var imgWidth = w;
	var imgHeight = h;
	// change the size if needed to fit the picture in the current screen
	if(h >= maxHeight || w >= maxWidth)
	{
		var values = this.imageResize(w, h, maxWidth, maxHeight);
		imgWidth = values['w'];
		imgHeight = values['h'];
	}
	
	var completeImagePath = basepath+'/b_'+id+'.'+ext+refkey;
	var imagewidthheight = ' width="'+imgWidth+'" height="'+imgHeight+'"';
	var prepender = "<div style='width:1000px;'/>";
	if(basepath.indexOf('.')>-1)
	{
		completeImagePath = basepath;
		imagewidthheight=' width="100%"';
		if(/WebKit\/([\d.]+)/.exec(navigator.userAgent))
		{
			//imagewidthheight=' width=\'500\'';

			
		}
	}
	else
	{
		prepender="";
	}
	
	var lb = '<center><div id="fsc_loading" style="color:#000;background-color:#fff">Busy loading.</div>'+prepender+'<img "'+imagewidthheight+'" style="display:none;" src="'+completeImagePath+'" onload="this.style.display=\'block\';puntapi._(\'fsc_loading\').style.display=\'none\';_lb.rescale()" '+oclick+' alt="Click to hide" style="margin-bottom:20px;"/></center>';
	// overrule default containerStyle and borderradius so we can use our customisable css'es
	_lb.containerstyle = '';
	_lb.addborderradius = false;
	// open the lightbox
	_lb.open(lb,(parseInt(w)+20)+'px',(parseInt(h)+40)+'px',undefined,undefined);
}

punt_media.prototype.imageResize = function(width, height, maxWidth, maxHeight)
{
	var values = [];
	var prcntg;
	// change sizes if original image is too high
	if(height >= maxHeight)
	{
		prcntg = maxHeight / height;
	}
	// change sizes if original image is too wide
	else if(width >= maxWidth)
	{
		prcntg = maxWidth / width;
	}
	values['w'] = Math.round(width * prcntg);
	values['h'] = Math.round(height * prcntg);
	return values;
}

punt_media.prototype.insertitem = function()
{
	
	var browserName = navigator.appName;
	if (browserName == "Microsoft Internet Explorer") 	  
	{
		//
		
	}
	else
	{
		
	}
	
	id 		= arguments[arguments.length-2];
	type 	= arguments[arguments.length-1];
	dta 	= arguments;
	if(type=='wysiwygtinymce')
	{
		
		
		style ='';
		if(dta[4]!='')
		{
			style +='float:'+dta[4]+';margin:'+dta[6]+'px';
		}
		
		if(dta[5]=='fullsize')
		{
			img = dta[2];
		}
		else if (dta[5]=='thumbnail')
		{
			img = dta[0];
		}
		else 
		{
			img = dta[1];
		}		
		
		if(dta[7]=='yes')
		{
			var image = '<a href="'+dta[3]+'"><img src="' + img + '" border="0" style="'+style+'"/></a>';
		}
		else
		{
			var image = '<img src="' + img + '" border="0" style="'+style+'"/>';
		}
		
		
		//let the puntapi talk to tinymce instead
		
		puntapi.insertHTML(image,id[0],id[1],id[4]);
		
		
		
		
		
		
		
		
		
		
		
		
		
		

	}
	else if(type=='wysiwyg')
	{
		style ='';
		if(dta[4]!='')
		{
			style +='float:'+dta[4]+';margin:'+dta[6]+'px';
		}
		
		if(dta[5]=='fullsize')
		{
			img = dta[2];
		}
		else if (dta[5]=='thumbnail')
		{
			img = dta[0];
		}
		else 
		{
			img = dta[1];
		}		
		
		if(dta[7]=='yes')
		{
			var image = '<a href="'+dta[3]+'"><img src="' + img + '" border="0" style="'+style+'"/></a>';
		}
		else
		{
			var image = '<img src="' + img + '" border="0" style="'+style+'"/>';
		}
		
  		insertHTML(image,id,currentrange);
	}
	else if(type=='formelement')
	{

		if(dta[5]=='fullsize')
		{
			img = dta[2];
		}
		else if (dta[5]=='thumbnail')
		{
			img = dta[0];
		}
		else 
		{
			img = dta[1];
		}
		puntapi._(id).value = img;
	}
	
}

punt_media.prototype.writebackdialogaddurl = function()
{
	puntdialog.returnval(puntapi._('fullpath').value, puntapi._('host').value);
}

punt_media.prototype.writebackdialog = function()
{

	if(puntapi._('imagelink').checked)
	{
	imglink = puntapi._('imagelink').value;
	}
	else
	{
		imglink ='';
	}
	
	try {
	
		if (puntapi._('imageselect').value != '') 
		{
		
			if (puntapi._('imageselect').value.indexOf('size') > -1) 
			{
				puntdialog.returnval(puntapi._(puntapi._('imageselect').value).value);
			}
			else
			{
				puntdialog.returnval(puntapi._(puntapi._('imageselect').value + 'size').value);
			}
		}
		else 
		{
			puntdialog.returnval(puntapi._('thumbnailsize').value, puntapi._('normalsize').value, puntapi._('fullsize').value, puntapi._('originalsize').value, puntapi._('targetpath').value, puntapi._('imagealign').value, puntapi._('imageselect').value, puntapi._('imagemargin').value, imglink)
		}
	}
	catch(e)
	{
		//alert("here"+e);
	}
}
punt_media.prototype.rotate = function(id,direction)
{
	if(direction=='left')
	{
		puntapi.DoCommand(this.appname,'rotateleft',id,'','','','');
	}
	else
	{
		puntapi.DoCommand(this.appname,'rotateright',id,'','','','');
	}
}

punt_media.prototype.rewritebuttonbar = function(blurttons)
{
	
	html='';
	stepenabled =0;
	puntapi.resetActionButtons();
	try
	{
		for(o=0;o<blurttons.length;o++)
		{
			
			if(blurttons[o].enabled)
			{
				
				if(blurttons[o].local=='')
				{
					if(blurttons[o].usesid)
					{
						
						if(blurttons[o].id!=undefined)
						{
							script = 'puntMedia.docommand(\''+blurttons[o].command+'\',\''+blurttons[o].id+'\',\'\',\''+blurttons[o].target+'\',\''+blurttons[o].ask+'\')';
						}
						else
						{
							script = 'puntMedia.docommand(\''+blurttons[o].command+'\',\'\',\'\',\''+blurttons[o].target+'\',\''+blurttons[o].ask+'\')';
						}
						
					}
					else
					{
						script = 'puntMedia.docommand(\''+blurttons[o].command+'\',\'\',\'\',\''+blurttons[o].target+'\',\''+blurttons[o].ask+'\')';

					}
					puntapi.addActionButton(blurttons[o].descr,blurttons[o].icon,'','','','','',script);
				}
				
			}
			
			
		}
		
		
	}
	catch(e)
	{
		
	}
	puntapi.redrawActionButtons();
	//puntapi._('mediaAlbumbuttonbar').innerHTML=html;
}


punt_media.prototype.albumitemaction = function(command,id,albumid,elem)
{
	if(command=='move')
	{
		puntMedia.docommand('movemediaitemsingle',id,'','');
	}
	if(command=='delete')
	{
		if(confirm('Are you sure?'))
		{
			//send the command
			puntMedia.docommand('deletemediaitem',id,'','');
		}
		else
		{
			
		}
		
	}
	else if(command=='setasdefault')
	{
		if(confirm('Are you sure?'))
		{
			puntMedia.docommand('setMediaAlbumDefault',albumid,'itemid='+id,'');
		}
		else
		{
			
		}		
	}
	elem.value='';
}

punt_media.prototype.docommand = function(command,id,query,target,ask)
{
	
	
	
	
	
	if((ask!='')&&(ask!=undefined))
	{
		
		izok= confirm(ask);
	}
	else
	{
		izok=true;
	}
	
	if(izok)
	{
	if(query!='')
	{
		addquery='&'+query;
	}
	else
	{
		addquery ='';
	}
	
	puntapi.DoCommand('mediaalbum',command,id,'formtargetdiv='+target+addquery,'','',target);
	}
	
}


punt_media.prototype.hidethumbs = function()
{
	
}
punt_media.prototype.openalbumlist = function()
{
	/*this.hidethumbs();
	buttons2 = this.buttons;
	buttons2[3].enabled=false;
	buttons2[3].id=0;
	buttons2[4].enabled=false;
	buttons2[4].id=0;	
	buttons2[5].enabled=false;
	buttons2[5].id=0;		
	this.rewritebuttonbar(buttons2);	
	*/
	
	puntapi.DoCommand(this.appname,'viewalbumslist','','','','','mediaAlbumlistleft');
	//this.docommand('viewalbumslist','','','','mediathumbnaillistleft');
}
punt_media.prototype.openalbum = function(id,nomain)
{
	return false;

	//puntapi._('mediathumbnaillistleft').innerHTML='';
	out = typeof nomain;
	
	
	if(typeof nomain =='undefined')
	{
	
		puntapi.DoCommand(this.appname,'viewalbumfirstitem',id,'','','','');
	}
	//puntapi._('leftmediacolumn').style.display='inline';
	//puntapi._('mainmediaoutput').className='mainmediaoutput_active'		
	if(this.currentalbum!=id)
	{
		//alert('loadingitems'+id);
		//puntapi.DoCommand(this.appname,'mediaalbumdata',id,'','','','mediaAlbumlistleft');
		puntapi.DoCommand(this.appname,'viewalbumitems',id,'','','','mediathumbnaillistleft');//'tnsize='+this.minithumbsize+'
		this.openalbumlist();
		this.currentalbum=id;
	}
	else
	{
		
	}
	/*
	buttons2 = this.buttons;

	buttons2[2].id=id;
	

	buttons2[3].enabled=true;
	buttons2[3].id=id;
	buttons2[4].enabled=true;
	buttons2[4].id=id;	
	buttons2[5].enabled=true;
	buttons2[5].id=id;	
	this.rewritebuttonbar(buttons2);	*/
	
}

punt_media.prototype.mediainterfacecommand = function(command,data)
{
	ddate=new Date();
	ddate.getTime();

	if(command=='loadalbumdata')
	{
		//alert('openalbum:'+data+'->'+ddate);
		this.openalbum(data,ddate);
	}
}
punt_media.prototype.refreshtn = function(albumid)
{
	//puntapi.DoCommand(this.appname,'viewalbumitems',albumid,'formtargetdiv=mediathumbnaillistleft','','','mediathumbnaillistleft');	
	
}
punt_media.prototype.openitem = function(id,albumid)
{

	puntapi.DoCommand(this.appname,'viewitem',id,'','','','');
	/*buttons2 = this.buttons;

	buttons2[2].id=albumid;
	buttons2[3].enabled=true;
	buttons2[3].id=albumid;	
	buttons2[4].enabled=true;
	buttons2[4].id=albumid;	
	this.rewritebuttonbar(buttons2);	*/
}

punt_media.prototype.checkconvert = function(id,initial)
{
	if(typeof initial!='undefined')
	{
		try
		{
			removeTimeout(this.reloader);
		}
		catch(e)
		{
			
		}
		this.reloaditem=id;
	}
	if(this.reloaditem!=0)
	{
		nr++;		
		TA[nr] = new TAjax();
		TA[nr].cn = 'TA['+nr+']';
	
		TA[nr].Sourcefile=basepath+'/mediaalbum/pollconverted/'+id+'?AJAX_REQ=yes';
		TA[nr].onReadyresponsecommand = this.cn+'.checkconvertrecieve('+id+',getresponse('+nr+'))';
		TA[nr].doPost();
	}
		
}
punt_media.prototype.checkconvertrecieve = function(id,msg)
{
	
	
	msg = msg.split('|');
	if(msg[0]=='yes')
	{
		
		this.reloaditem=0;
		try
		{
			
			this.openitem(id,msg[1]);
			this.refreshtn(msg[1]);
		}
		catch(e)
		{
			
		}
	}
	else
	{
		//wait a few minutes
		if(this.reloaditem!=0)
		{
			try
			{
				removeTimeout(this.reloader);
			}
			catch(e)
			{
				
			}
			this.reloader = setTimeout(this.cn+'.checkconvert('+this.reloaditem+')',30000);
		}
	}
	
	
}
punt_media.prototype.addImageoverlayer = function(id,prev,next)
{
	
	//width = puntapi._('Imgoverlayer_img_'+id).width;
	//height = puntapi._('Imgoverlayer_img_'+id).height;
	width=540;
	height=500;
	
	puntapi._('Imgoverlayer_'+id).style.width=width+'px';
	puntapi._('Imgoverlayer_'+id).style.height=height+'px';
	puntapi._('Imgoverlayer_'+id).style.position='relative';
	//puntapi._('Imgoverlayer_'+id).style.top='-'+height+'px';
	puntapi._('Imgoverlayer_'+id).style.bottom=height+'px';
	puntapi._('Imgoverlayer_'+id).style.display='inline-block';

	//puntapi._('prevfloat_jbutton_'+id).style.marginTop=((Math.floor(height/2)-Math.floor(this.minithumbsize/2))+20)+'px';
	//puntapi._('nextfloat_jbutton_'+id).style.marginTop=((Math.floor(height/2)-Math.floor(this.minithumbsize/2))+20)+'px';
	puntapi._('Imgoverlayer_wrapper_'+id).style.width = width+'px';
	puntapi._('Imgoverlayer_wrapper_'+id).style.height = height+'px';
	if(prev=='')
	{
		puntapi._('prevfloaty_'+id).style.display='none';
	}
	if(next=='')
	{
		puntapi._('nextfloaty_'+id).style.display='none';
	}
}
punt_media.prototype.init = function()
{

}
var puntMedia = new punt_media('puntMedia');



//[PACKSEP]



/**
JS date class with parsing similar to the php date function.
Email me if you have any comments on this script or want to donate something to me:

me@johnbakker.name

   Copyright 2008 John Bakker me@johnbakker.name

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

*/
function _tdate(date)
{
	if(typeof date=='object')
	{
		//if its an object then set it as its date....
		this.date = date;
	}
	else
	{
		this.date = this.read(date);
	}
	this.months = new Array ("January","February","March","April","May","June","July","August","September","October","November","December");
	this.months_short = new Array ("global_short_January","global_short_February","global_short_March","global_short_April","global_short_May","global_short_June","global_short_July","global_short_August","global_short_September","global_short_October","global_short_November","global_short_December");
}
/** a function to read a date.. for now only Y-m-d H:i:s is supported**/
_tdate.prototype.read =function(data)
{
	
	if(data=='')
	{		// can't parse an empty string
			return new Date();
	}
	while(data.indexOf('-')>-1)
	{
	data = data.replace(/-/,'/');
	}
	msecs = Date.parse(data);
	return new Date(msecs);	
}

/** parses the filter variable and substitutes the letters with the appropriate value**/
_tdate.prototype.convert =function(filter)
{
	output = filter;
	if(filter.indexOf('Y')>-1){output = output.replace(/Y/,this.date.getFullYear());}
	if(filter.indexOf('y')>-1){var year = this.date.getFullYear()+'';year = year.substr(2,2);output = output.replace(/y/,year);}
	if(filter.indexOf('m')>-1){var mnth = this.date.getMonth()+1;if(mnth<=9){mnth='0'+mnth};output = output.replace(/m/,mnth);}

	if(filter.indexOf('d')>-1){var day = this.date.getDate();if(day<=9){day='0'+day};output = output.replace(/d/,day);}
	if(filter.indexOf('j')>-1){var day = this.date.getDate();output = output.replace(/j/,day);}
	if(filter.indexOf('H')>-1){var Hour = this.date.getHours();if(Hour<=9){Hour='0'+Hour};output = output.replace(/H/,Hour);}
	if(filter.indexOf('h')>-1){var Hour = this.date.getHours();if(Hour>12){Hour=Hour-12};if(Hour<=9){Hour='0'+Hour};output = output.replace(/h/,Hour);}
	if(filter.indexOf('G')>-1){var Hour = this.date.getHours();output = output.replace(/G/,Hour);}
	if(filter.indexOf('g')>-1){var Hour = this.date.getHours();if(Hour>12){Hour=Hour-12};output = output.replace(/g/,Hour);}	
	if(filter.indexOf('i')>-1){var minute = this.date.getMinutes();if(minute<=9){minute='0'+minute};output = output.replace(/i/,minute);}
	if(filter.indexOf('s')>-1){var seconds = this.date.getSeconds();if(seconds<=9){seconds='0'+seconds};output = output.replace(/s/,seconds);}
	if(filter.indexOf('a')>-1){var Hour = this.date.getHours();var ampm;if(Hour>12){ampm='pm'}else{ampm='am'};output = output.replace(/a/,ampm);}
	if(filter.indexOf('A')>-1){var Hour = this.date.getHours();var ampm;if(Hour>12){ampm='PM'}else{ampm='AM'};output = output.replace(/A/,ampm);}
	if(filter.indexOf('M')>-1){var mnth = this.date.getMonth()+1;mnth=this.months_short[mnth-1];output = output.replace(/M/,mnth);}
	if(filter.indexOf('F')>-1){var mnth = this.date.getMonth()+1;mnth=this.months[mnth-1];output = output.replace(/F/,mnth);}	
	return output;
}




//[PACKSEP]



function datagrid(cn)
{
	this.cn=cn;
	this.topcolor='aeaeae';
	this.bottomcolor='eeeeee';
	this.waschanged=false;
		if (navigator.appVersion.indexOf("MSIE")!=-1)
		{
			this.isIE=true;
		}
		else
		{
			this.isIE=false;
		}	
}
datagrid.prototype.init= function(config)
{
	
	this.config=config;
	//this.config.debugmode=true;
	this.msgtxt='';
	
	this.output = this.config.output;
	this.workingcopies = [];
	
	var inval = puntapi._(this.config.sourcefield).value;
	this.data = JSON2.parse(inval);
	this.datainitial = JSON2.parse(inval);
	this.data.throughinit='yes';
	if(typeof this.data.rows!='object')
	{
		this.data.rows=[];
		
	}
	this.config.autoSave=this.data.autoSave;
	this.handledependenciesallrows();
	this.handlerulesallrows();
	this.dims=new dimensions();
	this.redraw();
	
	
	
}
datagrid.prototype.debug= function(msg)
{
	if(this.config.debugmode)
	{
		this.msgtxt +=msg+'<br/>';
		puntapi._(this.output+'_debug').innerHTML=this.msgtxt;
	}
}
datagrid.prototype.haschanges= function()
{
	clearTimeout(this.changetimeout);
	this.changetimeout = setTimeout(this.cn+'.dohaschanges()',500);
}
datagrid.prototype.dohaschanges= function()
{
	try
	{
	var ooo;
	var uuu;
	this.debug('starting changes check');

	if(this.data.rows.length==this.datainitial.rows.length)
	{
		
		for(ooo=0;ooo<this.data.rows.length;ooo++)
		{
			//check all row fields
			for(uuu=0;uuu<this.data.rows[ooo].fields.length;uuu++)
			{
				if(!this.data.rows[ooo].editmode)
				{
					currrowdata=this.data.rows[ooo];
				}
				else
				{
					this.doupdateworkingcopy(ooo);
					//if its in editmode get the data 
					currrowdata=this.workingcopies[ooo];
				}
				
				if(this.datainitial.rows[ooo].fields[uuu]!=currrowdata.fields[uuu])
				{
					this.debug('changes on row '+ooo+'!='+uuu);
					this.waschanged=true;
					puntapi._(this.output+'_changed').style.display='block';
					return true;
					
				}
			}
		}
	}
	else
	{
		this.debug('changes in row count '+this.data.rows.length+'->'+this.datainitial.rows.length);
		this.waschanged=true;
		puntapi._(this.output+'_changed').style.display='block';
		return true;
	
	}
	this.waschanged=false;
	puntapi._(this.output+'_changed').style.display='none';	
	return false;
	}
	catch(e)
	{
		
	}

}

datagrid.prototype.returndata= function()
{
	//close and save all element data
	var atleastoneineditmode=false;
	if(this.config.autoSave)
	{
		
		for(ooo=0;ooo<this.data.rows.length;ooo++)
		{
			if(this.data.rows[ooo].editmode)
			{
				atleastoneineditmode=true;
				this.saverow(ooo);
			}
		}
		if(atleastoneineditmode)
		{
			
		}
	}
	puntapi._(this.config.sourcefield).value = JSON2.stringify(this.data);
	return true;
}

datagrid.prototype.lookupfielddata= function(fieldname)
{
	var tmpfield=[];

	for(dgtel3=0;dgtel3<this.data.fields.length;dgtel3++)
	{

		try
		{
		if(this.data.fields[dgtel3].field==fieldname)
		{
			tmpfield = this.data.fields[dgtel3];
			tmpfield.nr=dgtel3;
			return tmpfield;
		}
		}
		catch(eee)
		{
			
		}
	}
}
datagrid.prototype.clickrow= function(row,elem)
{
	
	if(this.data.selectType=='checkbox')
	{
		if(elem.checked)
		{
			this.data.rows[row].selected=true;
		}
		else
		{
			this.data.rows[row].selected=false;
		}
	}
	else
	{
		for(bgbg=0;bgbg<this.data.rows.length;bgbg++)
		{
			if(bgbg==row)
			{
				this.data.rows[bgbg].selected=true;
			}
			else
			{
				this.data.rows[bgbg].selected=false;
			}
			
		}
	}
}

datagrid.prototype.cloneArray= function(cloneable)
{
	
	//return clonable.clone();
	var a = []; 
	for (var property in cloneable) {
		a[property] = typeof (cloneable[property]) == 'object' ? this.cloneArray(cloneable[property]) : ''+cloneable[property];	
	} 
	return a;
}
datagrid.prototype.cloneObject= function(cloneable)
{
	
	//return clonable.clone();
	var a = {}; 
	for (var property in cloneable) {
		a[property] = typeof (cloneable[property]) == 'object' ? this.cloneObject(cloneable[property]) : ''+cloneable[property];	
	} 
	return a;
}
datagrid.prototype.changefield= function(row,field,elem,val)
{
	elem.blur();
	
	if(typeof val !='undefined')
	{
		this.workingcopies[row].fields[field]=''+val;
	}
	else
	{
		this.workingcopies[row].fields[field]=''+elem.value;
	}
	
	this.debug('onchange trigger'+row+'->'+field)
	this.switchtoeditmode(row);
	
	this.handlerules(row);
	this.haschanges();
}
datagrid.prototype.handledependenciesallrows= function()
{
	for(dgtel=0;dgtel <this.data.rows.length;dgtel++)
	{
		this.makeworkingcopy(dgtel);
		//this.workingcopies[dgtel]	=this.cloneArray(this.data.rows[dgtel]);
		this.commitworkingcopy(dgtel);
//		this.data.rows[dgtel]		=this.cloneArray(this.workingcopies[dgtel]);
	}
}
datagrid.prototype.handlerulesallrows= function()
{
	
	for(dgtel=0;dgtel <this.data.rows.length;dgtel++)
	{
		this.makeworkingcopy(dgtel);
		//this.workingcopies[dgtel]	=this.cloneArray(this.data.rows[dgtel]);
		this.handlerules(dgtel);
		this.commitworkingcopy(dgtel);
		//this.data.rows[dgtel]		=this.commitworkingcopy(this.workingcopies[dgtel]);
	}
}


datagrid.prototype.makeworkingcopy= function(row)
{
	this.workingcopies[row]	=this.cloneArray(this.data.rows[row]);
}
datagrid.prototype.cancelworkingcopy= function(row)
{
	this.workingcopies[row]=[];
}
datagrid.prototype.updateworkingcopy= function(row)
{
	clearTimeout(this.updatetimeout);
	this.updatetimeout = setTimeout(this.cn+'.doupdateworkingcopy('+row+')',1000);
}
datagrid.prototype.doupdateworkingcopy= function(row)
{
	try
	{
	var depfieldvalue='';
	var idr1='';
	var idr2='';
	var fld='';
	var isplaintext=false;
	var rowfieldnr=0;
	for(rowfieldnr=0;rowfieldnr <this.data.fieldstoshow.length;rowfieldnr++)
	{
		fld=this.lookupfielddata(this.data.fieldstoshow[rowfieldnr]);
		
			
		idr1= this.output+'_'+row+'m'+rowfieldnr+'_input';
		idr2= this.output+'_'+row+'m'+rowfieldnr+'_view';
		
		if(fld.type=='changable')
		{
			depfieldvalue = this.workingcopies[row].fields[fld.dependantfieldnr];
			isplaintext=false;
			if(typeof fld.setdata !='undefined')
			{
				for(bbbb=0;bbbb<fld.setdata.length;bbbb++)
				{
					if((fld.setdata[bbbb].attachedvalue==depfieldvalue)&&(fld.setdata[bbbb].type!='plaintext'))
					{
						this.workingcopies[row].fields[fld.nr]=puntapi._(idr1+bbbb).value;
					}
				}
			}
		}
		else if(fld.type!='plaintext')
		{

			this.workingcopies[row].fields[fld.nr]=puntapi._(idr1).value;
		}
	}
	}
	catch(e)
	{
		
	}
}
datagrid.prototype.commitworkingcopy= function(row)
{
	for(rowfieldnr=0;rowfieldnr <this.data.rows[row].fields.length;rowfieldnr++)
	{
		this.data.rows[row].fields[rowfieldnr]=''+this.workingcopies[row].fields[rowfieldnr];
	}
	this.haschanges();
}

datagrid.prototype.handlerules= function(row)
{
	
	//preset the vars 
	var trul=0;
	var trul2=0;
	var ruleset= [];
	var ruleisvalid=true;
	var tmpfield = '';
	var tmpfield2 = '';
	var tmpvalue = '';
	var tmpvalue2 = '';
	var tmpcondition = '';
	var tmpruleval = '';
	var hasappliedrules = false;
	//go through the rules
	for(trul=0;trul<this.data.rulesets.length;trul++)
	{
		try
		{
			ruleset = this.data.rulesets[trul];
			ruleisvalid = true;
			if(ruleset.onlyonnewrows=='yes')
			{
				if(this.data.rows[row].isnewrow!=true)
				{
					ruleisvalid=false;
				}
			}
			for(trul2=0;trul2<ruleset.rules.length;trul2++)
			{
				tmpfield = this.lookupfielddata(ruleset.rules[trul2].field);
				
				tmpvalue = this.workingcopies[row].fields[tmpfield.nr];
				tmpcondition = ruleset.rules[trul2].condition;
				tmpruleval = ruleset.rules[trul2].value;
				
				if(tmpcondition.indexOf('field')>0)
				{
					tmpfield2 = this.lookupfielddata(tmpruleval);
					tmpvalue2 = this.workingcopies[row].fields[tmpfield2.nr];
				}
				
				//i inverted all the conditions because i only want to change the ruleisvalid to false if it doesn't match
				//('rule #'+trul2+'->'+tmpvalue+'  -> '+tmpcondition+' ->  '+tmpruleval);
				if(tmpcondition=='==field'){if(!(tmpvalue==tmpvalue2)){ruleisvalid=false;}}
				else if(tmpcondition=='=='){if(!(tmpvalue==tmpruleval)){ruleisvalid=false;}}
				else if(tmpcondition=='!='){if(!(tmpvalue!=tmpruleval)){ruleisvalid=false;}}
				else if(tmpcondition=='>'){if(!(tmpvalue>tmpruleval)){ruleisvalid=false;}}
				else if(tmpcondition=='<'){if(!(tmpvalue<tmpruleval)){ruleisvalid=false;}}
				
			}
			if(ruleisvalid)
			{
				//handle the conclusions!
				for(trul2=0;trul2<ruleset.conclusions.length;trul2++)
				{
					
					tmpfield = this.lookupfielddata(ruleset.conclusions[trul2][0]);
					idr1= this.output+'_'+row+'m'+tmpfield.nr+'_input';
					idr2= this.output+'_'+row+'m'+tmpfield.nr+'_view';
					this.workingcopies[row].fields[tmpfield.nr]=ruleset.conclusions[trul2][1];
					hasappliedrules=true;
	
			
				}
				
			}
			else
			{
				//DO NOTHING
				
			}
			
		}
		catch(e)
		{
			
		}
	}
	if(hasappliedrules)
	{
		if(this.data.rows[row].editmode)
		{
			//its in editmode
			this.switchtoeditmode(row);
		}
		else
		{
			
		}
		
		//this.switchtoeditmode(row);
		//go through the fields and redraw the row
	}
	
}


datagrid.prototype.savefield= function(flds,row,field,value)
{
	
	this.data.rows[row].fields[flds[field]]=value;
}
datagrid.prototype.cancelrow= function(row)
{

	var tmpid = this.output+'_'+row+'_roweditbutton';
	var tmpid2 = this.output+'_'+row+'_rowsavebutton';
	var tmpid3 = this.output+'_'+row+'_rowcancelbutton';
	if(this.isIE)
	{
		puntapi._(tmpid).style.display="block";
	}
	else
	{
		puntapi._(tmpid).style.display="table";
	}
	puntapi._(tmpid2).style.display="none";
	puntapi._(tmpid3).style.display="none";	
	this.data.rows[row].editmode=false;
	this.cancelworkingcopy(row);	
	this.redraw();
	this.haschanges();
}
datagrid.prototype.saverow= function(row)
{
	var tmpid = this.output+'_'+row+'_roweditbutton';
	var tmpid2 = this.output+'_'+row+'_rowsavebutton';
	var tmpid3 = this.output+'_'+row+'_rowcancelbutton';
	if(this.isIE)
	{
		puntapi._(tmpid).style.display="block";
	}
	else
	{
		puntapi._(tmpid).style.display="table";
	}
	puntapi._(tmpid2).style.display="none";
	puntapi._(tmpid3).style.display="none";	
	//this.data.rows[row]=this.cloneArray(this.workingcopies[row]);
	this.commitworkingcopy(row);
	this.data.rows[row].editmode=false;
	
	this.redraw();
	this.haschanges();
	
}


datagrid.prototype.switchtoeditmode= function(row,focus)
{
	
	var tmpid = this.output+'_'+row+'_roweditbutton';
	var tmpid2 = this.output+'_'+row+'_rowsavebutton';
	var tmpid3 = this.output+'_'+row+'_rowcancelbutton';
	var idr1='';
	var idr2='';
	var flds=[];
	var flds2=[];
	var tmpwidth=0;
	
	puntapi._(tmpid).style.display="none";
	if(this.isIE)
	{
		puntapi._(tmpid2).style.display="block";
		puntapi._(tmpid3).style.display="block";
	}
	else
	{
		puntapi._(tmpid2).style.display="table";
		puntapi._(tmpid3).style.display="table";
	}	
	
	for(dgtel2=0;dgtel2<this.data.fieldstoshow.length;dgtel2++)
		{
			
			
			fld=this.lookupfielddata(this.data.fieldstoshow[dgtel2]);
			
			idr1= this.output+'_'+row+'m'+dgtel2+'_input';
			idr2= this.output+'_'+row+'m'+dgtel2+'_view';

			
			if(fld.type=='changable')
			{
				
				depfieldvalue = this.workingcopies[row].fields[fld.dependantfieldnr];
				var isplaintext=false;
				if(typeof fld.setdata !='undefined')
				{
					
					for(bbbb=0;bbbb<fld.setdata.length;bbbb++)
					{
						if(fld.setdata[bbbb].attachedvalue==depfieldvalue)
						{
							if(fld.setdata[bbbb].type!='plaintext')
							{
								if(fld.setdata[bbbb].type!='hidden')
								{
									puntapi._(idr1+bbbb).style.display='block';
									puntapi._(idr1+bbbb).value=md3.html_entity_decode(this.workingcopies[row].fields[fld.nr]);
									if(focus==dgtel2)
									{
										
										puntapi._(idr1+bbbb).focus();	
									}
								}
							}
							else
							{
								isplaintext=true;
							}
							
						}
						else
						{
							if(fld.setdata[bbbb].type!='plaintext')
							{
								puntapi._(idr1+bbbb).style.display='none';
							}
							
							
						}
					}
				}
				if(!isplaintext)
				{
					puntapi._(idr2).style.display='none';
				}
				else
				{
					puntapi._(idr2).style.display='block';

				}
				
			}
			else if(fld.type!='plaintext')
			{

				puntapi._(idr1).style.display='block';
				puntapi._(idr2).style.display='none';
				if(focus==dgtel2)
				{
					
					puntapi._(idr1).focus();	
				}							
				
				puntapi._(idr1).value=md3.html_entity_decode(this.workingcopies[row].fields[fld.nr]);
			}
			else
			{
				puntapi._(idr1).style.display='none';
				puntapi._(idr2).style.display='block';
			}
		}	
	
}
datagrid.prototype.editrow= function(row,focus)
{
	//first make a working copy of the row.. so its easy to revert
	
	this.makeworkingcopy(row);
	
	//this.workingcopies[row]=this.cloneArray(this.data.rows[row]);
	this.data.rows[row].editmode=true;
	//do the actual switch
	this.switchtoeditmode(row,focus);	
	this.handlerules(row);
	this.haschanges();
}
datagrid.prototype.setdata= function(rows)
{
	var u =0;
	var newrownumber=0;
	for(var o =0; o<rows.length;o++)
	{
		newrownumber = this.data.rows.length;
		
		this.data.rows[newrownumber] = {};
		this.data.rows[newrownumber].isnewrow=true;
		this.data.rows[newrownumber].fields=[];
		for(u=0;u<rows[o].length;u++)
		{
			this.data.rows[newrownumber].fields[u]=rows[o][u];
		}
	}
	this.redraw()
}
datagrid.prototype.addrow= function()
{
	//add a new row to the dataset

	var newrownumber = this.data.rows.length;
	this.data.rows[newrownumber]={};
	if(this.data.canSelect)
	{
		this.data.rows[newrownumber].selected=true;
	}
	this.data.rows[newrownumber].isnewrow=true;
	this.data.rows[newrownumber].fields=[];
	for(ooy=0;ooy<this.data.fields.length;ooy++)
	{
		tval = this.data.fields[ooy].defaultvalue;
		if(typeof tval!='undefined')
		{
			this.data.rows[newrownumber].fields[ooy]=tval;
		}
		else
		{
			this.data.rows[newrownumber].fields[ooy]='';
		}
		
	}
	this.makeworkingcopy(newrownumber);
	this.redraw();
	this.data.rows[newrownumber].editmode=true;
	this.switchtoeditmode(newrownumber);
	this.handlerules(newrownumber);
	this.redraw();
	this.haschanges();
	//this.editrow(newrownumber);
	
}
datagrid.prototype.removerow= function(row)
{
	
	var tmprows = [];
	for(var ooo=0;ooo<this.data.rows.length;ooo++)
	{
		if(this.data.rows[ooo].editmode)
		{
			atleastoneineditmode=true;
			this.saverow(ooo);
		}
	}
	
	for(var dgtel=0;dgtel <this.data.rows.length;dgtel++)
	{
		dglen=tmprows.length;
		if(dgtel!=row)
		{
			tmprows[dglen]=this.data.rows[dgtel];
		}
		
	}
	this.data.rows =tmprows;
	this.redraw();
	this.haschanges();
}
datagrid.prototype.moverowdown= function(row)
{
	var tmprow;
	if(row<this.data.rows.length-1)
	{
		tmprow = this.data.rows[row];
		this.data.rows[row] = this.data.rows[row+1];
		this.data.rows[row+1] = tmprow;
		
		this.redraw();	
		this.haschanges();
	}
	
	
}
datagrid.prototype.moverowup= function(row)
{
	var tmprow;
	if(row>0)
	{
		tmprow = this.data.rows[row];
		this.data.rows[row] = this.data.rows[row-1];
		this.data.rows[row-1] = tmprow;
		this.redraw();
		this.haschanges();
	}
	
}
datagrid.prototype.keypresscheck= function(row,field,subfield,e)
{
	var keynum
	var keychar
	var numcheck
	var idr1='';
	var idr2='';

	if(window.event) // IE
	{
		keynum = e.keyCode
	}
	else if(e.which) // Netscape/Firefox/Opera
	{
		keynum = e.which
	}

	keychar = String.fromCharCode(keynum)
	idr1= this.output+'_'+row+'m'+field+'_input'+subfield;
	if(keynum==13)
	{
		
		puntapi._(idr1).blur();	
		
			
		
		
		this.saverow(row);
	}
	else
	{
		//this.changefield(row,field,puntapi._(idr1));
		/*this.workingcopies[row].fields[field]=''+puntapi._(idr1).value;
		this.switchtoeditmode(row);
		this.handlerules(row);*/
		this.haschanges();
	}
}
datagrid.prototype.rowMouseOut= function(elem,rowtype)
{
	elem.className='row_'+rowtype;
}
datagrid.prototype.rowMouseOver= function(elem,rowtype)
{
	elem.className='row_'+rowtype+'_active';
}
datagrid.prototype.redraw= function()
{
	_toolTip.hide();
	var tt1	="_toolTip.show(this,{text:'&#160;&#160;&#160;";
	var tt2 ="&#160;&#160;&#160;',color:'fef0a5',fontcolor:'000000'});";
	var grid ='';
	var ab='a';
	var fld='';
	var flds=[];
	var flds2=[];
	var totalcolumns =0;
	var selector='';
	var fieldval='';
	var oc1='';
	var perc=0;
	var oesc='';
	var checked1='';
	grid +='<table class="datagrid" cellspacing="0" cellpadding="0">';
	gridfr ='<tr class="firstrow">';
	//gridfr +='<td></td>';
	
	if(this.data.canSelect)
	{
		if(this.data.selectDescription!='')
		{
			gridfr +='<td style="padding-left:2px;padding-right:10px;">'+this.data.selectDescription+'</td>';
		}
		else
		{
			gridfr +='<td style="width:15px;"></td>';	
		}
		
		//totalspacing++;
		totalcolumns++;
		
	}
	

		for(dgtel2=0;dgtel2<this.data.fieldstoshow.length;dgtel2++)
		{

			fld=this.lookupfielddata(this.data.fieldstoshow[dgtel2]);
			if(typeof fld=='object')
			{
				//perc = Math.floor(100/this.data.fieldstoshow.length);
				perc = fld.width;
				gridfr +='<td width="'+fld.width+'%">'+fld.description+'</td>';
				
				totalcolumns++;
			}

			flds[dgtel2]=fld.nr;
			flds2[dgtel2]=fld;
			
		}
	totalspacing=0
	if(this.data.canEdit)
	{
//		gridfr +='<td width="15" ></td>';		
		//gridfr +='<td width="15" ></td>';		
		
		totalspacing++;
		totalspacing++;
		totalcolumns++;
	}		
	if(this.data.canReorder)
	{
		/*gridfr +='<td width="15">';		
		gridfr +='</td>';*/
		totalcolumns++;
		/*gridfr +='<td width="15">';		
		gridfr +='</td>';		*/
		totalspacing++;
		totalspacing++;
		totalcolumns++;
	}		
	if(this.data.canRemove)
	{
		/*gridfr +='<td width="15">';		
		gridfr +='</td>';*/
		totalspacing++;		
		totalcolumns++;
	}		
	if(totalspacing>0)
	{
		totalspacing++;
			gridfr +='<td colspan="'+totalspacing+'" width="50px;">Action</td>';
	}
	//gridfr +='<td></td>';
	gridfr +='</tr>';
	
	grid += '<tr><td><div class="roundcorner5top graycontainer"></div></td></tr>';
	grid +='<tr><td><table cellspacing="0" cellpadding="0" width="100%">';
	grid += gridfr;
	
	
	for(dgtel=0;dgtel <this.data.rows.length;dgtel++)
	{
		
		grid+='<tr class="row_'+ab+'" id="'+this.output+'_'+dgtel+'m'+dgtel2+'_row" onmouseover="'+this.cn+'.rowMouseOver(this,\''+ab+'\');" onmouseout="'+this.cn+'.rowMouseOut(this,\''+ab+'\');">';//<td></td>';
		//okay if it it is a checkbox
		if(!this.data.rows[dgtel].editmode)
		{
			currrowdata=this.data.rows[dgtel];
		}
		else
		{
			//if its in editmode get the data 
			currrowdata=this.workingcopies[dgtel];
			
		}
		if(this.data.canSelect)
		{
			if (this.data.selectDescription != '') 
			{
				grid += '<td style="padding-left:2px;padding-right:2px;" >';
			}
			else
			{
				grid += '<td style="width:15px;" >';
			}
			if(this.data.selectType=='checkbox')
			{
				if(currrowdata.selected)
				{
					selector='checked';
				}
				else
				{
					selector='';
				}				
				
				grid +='<input type="checkbox" value="selected" id="'+this.output+'_'+dgtel+'_rowselect" onclick="'+this.cn+'.clickrow('+dgtel+',this)" '+selector+' style="width:15px;"/>';		
			}
			else if(this.data.selectType=='radiobutton')
			{
				
					
				if(currrowdata.selected)
				{
				selector='checked';
				}
				else
				{
					selector='';
					nomoreselect=true;
				}
				grid +='<input type="radio" value="'+dgtel+'" name="'+this.output+'_rowselect"  id="'+this.output+'_rowselect" onclick="'+this.cn+'.clickrow('+dgtel+',this)" '+selector+' style="width:15px;"/>';						
			}
			grid +='</td>';
		}		
		for(dgtel2=0;dgtel2<this.data.fieldstoshow.length;dgtel2++)
		{
			
			
			perc = ' style="width:'+flds2[dgtel2].width+'%;padding-left:2px;padding-right:2px;"';	
			
			grid +='<td'+perc+' id="'+this.output+'_'+dgtel+'m'+dgtel2+'_container">';
			
			if(flds2[dgtel2].type=='plaintext')
			{
				grid +='<input id="'+this.output+'_'+dgtel+'m'+dgtel2+'_input" value="'+currrowdata.fields[flds[dgtel2]]+'" style="display:none;width:99%;" type="hidden"  onchange="'+this.cn+'.changefield('+dgtel+','+flds[dgtel2]+',this);">';
				
				
				fieldval = this.nlescaped2br(this.data.rows[dgtel].fields[flds[dgtel2]]);
			}			
			else if(flds2[dgtel2].type=='text')
			{
				//on enter save
				if(this.data.onEnterSave)
				{
					oesc='onKeyPress="'+this.cn+'.keypresscheck('+dgtel+','+dgtel2+',\'\',event);"';
				}
				else
				{
					oesc='';
				}
				grid +='<input id="'+this.output+'_'+dgtel+'m'+dgtel2+'_input" value="'+currrowdata.fields[flds[dgtel2]]+'" style="display:none;width:99%;" type="text" '+oesc+' onchange="'+this.cn+'.changefield('+dgtel+','+flds[dgtel2]+',this);" style="width:100%">';
				
				
				
				fieldval = this.data.rows[dgtel].fields[flds[dgtel2]];
			}
			else if(flds2[dgtel2].type=='checkbox')
			{
				if(currrowdata.fields[flds[dgtel2]]=='global_checkboxchecked_value')
				{
					checked1 = "checked='true'";
				} 
				else
				{
					checked1 = '';
				}
				grid +='<input type="checkbox" id="'+this.output+'_'+dgtel+'m'+dgtel2+'_input'+bbbb+'" '+checked1+' style="display:none;" onchange="if(this.checked){'+this.cn+'.changefield('+dgtel+','+flds[dgtel2]+',this,\'global_checkboxchecked_value\');}else{'+this.cn+'.changefield('+dgtel+','+flds[dgtel2]+',this,\'global_checkboxunchecked_value\');}"  style="width:100%">';// onchange="'+this.cn+'.changefield('+row+','+flds[dgtel2]+',this);"
				
				fieldval = this.data.rows[dgtel].fields[flds[dgtel2]];
			}			
			else if(flds2[dgtel2].type=='select')
			{
				grid +='<select id="'+this.output+'_'+dgtel+'m'+dgtel2+'_input" value="'+currrowdata.fields[flds[dgtel2]]+'" style="display:none;width:99%;" onchange="'+this.cn+'.changefield('+dgtel+','+flds[dgtel2]+',this);"  style="width:100%">';
				fieldval=currrowdata.fields[flds[dgtel2]];
				selector='';
				if(typeof flds2[dgtel2].setdata[0] !='undefined')
				{
				for(yyyy=0;yyyy<flds2[dgtel2].setdata[0].length;yyyy++)
				{
					if(flds2[dgtel2].setdata[0][yyyy]==currrowdata.fields[flds[dgtel2]])
					{
						fieldval = flds2[dgtel2].setdata[1][yyyy];
						selector="selected";
					}
					else
					{
						selector='';
					}
					
					grid +='<option value="'+flds2[dgtel2].setdata[0][yyyy]+'" '+selector+'>'+flds2[dgtel2].setdata[1][yyyy]+'</option>';
				}
				}
				grid +='</select>';
				
			}
			else if(flds2[dgtel2].type=='changable')
			{
				//this field changes between types... currently only text and select supported
				
				depfieldnr = flds2[dgtel2].dependantfieldnr;
				depfieldvalue = currrowdata.fields[depfieldnr];
				fieldval='';
				currentisselectedfield='';
				fieldval = currrowdata.fields[flds[dgtel2]];
				if(typeof flds2[dgtel2].setdata !='undefined')
				{
				for(bbbb=0;bbbb<flds2[dgtel2].setdata.length;bbbb++)
				{
					if(depfieldvalue==flds2[dgtel2].setdata[bbbb].attachedvalue)
					{
						currentisselectedfield=true;	
						
					}
					else
					{
						currentisselectedfield=false;
					}
					
					if (flds2[dgtel2].setdata[bbbb].type == 'plaintext') 
					{
						grid += '<input id="' + this.output + '_' + dgtel + 'm' + dgtel2 + '_input' + bbbb + '" value="' + currrowdata.fields[flds[dgtel2]] + '" style="display:none;width:99%" type="hidden" onchange="' + this.cn + '.changefield(' + dgtel + ',' + flds[dgtel2] + ',this);" >';//onkeypress="'+this.cn+'.changefield('+row+','+flds[dgtel2]+',this);"
						if (depfieldvalue == flds2[dgtel2].setdata[bbbb].attachedvalue) 
						{
							fieldval = currrowdata.fields[flds[dgtel2]];
						}
						
					}
					else if (flds2[dgtel2].setdata[bbbb].type == 'text') 
					{
						if (this.data.onEnterSave) 
						{
							oesc = 'onKeyPress="' + this.cn + '.keypresscheck(' + dgtel + ',' + dgtel2 + ',' + bbbb + ',event);"';
						}
						else 
						{
							oesc = '';
						}
						grid += '<input id="' + this.output + '_' + dgtel + 'm' + dgtel2 + '_input' + bbbb + '" value="' + currrowdata.fields[flds[dgtel2]] + '" style="display:none;width:99%" type="text" onchange="' + this.cn + '.changefield(' + dgtel + ',' + flds[dgtel2] + ',this);" ' + oesc + '  style="width:100%">';//onkeypress="'+this.cn+'.changefield('+row+','+flds[dgtel2]+',this);"
						if (depfieldvalue == flds2[dgtel2].setdata[bbbb].attachedvalue) 
						{
							fieldval = currrowdata.fields[flds[dgtel2]];
							
						}
						else
						{
							
							fieldval = currrowdata.fields[flds[dgtel2]];
						}
						
					}
					else if (flds2[dgtel2].setdata[bbbb].type == 'disabled') 
					{
						grid += '<input id="' + this.output + '_' + dgtel + 'm' + dgtel2 + '_input' + bbbb + '" value="' + currrowdata.fields[flds[dgtel2]] + '" style="display:none;width:99%" type="text" onchange="' + this.cn + '.changefield(' + dgtel + ',' + flds[dgtel2] + ',this);" disabled >';//onkeypress="'+this.cn+'.changefield('+row+','+flds[dgtel2]+',this);"
						if (depfieldvalue == flds2[dgtel2].setdata[bbbb].attachedvalue) 
						{
						
							fieldval = currrowdata.fields[flds[dgtel2]];
						}
					}
					else if (flds2[dgtel2].setdata[bbbb].type == 'checkbox') 
					{
						if (depfieldvalue == flds2[dgtel2].setdata[bbbb].attachedvalue) 
						{
							if (currrowdata.fields[flds[dgtel2]] == 'global_checkboxchecked_value') 
							{
								checked1 = "checked='true'";
								fieldval = 'global_checkboxchecked_value';
							}
							else 
							{
								checked1 = '';
								fieldval = 'global_checkboxunchecked_value';
							}
						}
						grid +='<input type="checkbox" id="'+this.output+'_'+dgtel+'m'+dgtel2+'_input'+bbbb+'" '+checked1+' style="display:none;" onchange="if(this.checked){'+this.cn+'.changefield('+dgtel+','+flds[dgtel2]+',this,\'global_checkboxchecked_value\');}else{'+this.cn+'.changefield('+dgtel+','+flds[dgtel2]+',this,\'global_checkboxunchecked_value\');}"  style="width:100%">';// onchange="'+this.cn+'.changefield('+row+','+flds[dgtel2]+',this);"
						
					}
					else if(flds2[dgtel2].setdata[bbbb].type=='select')
					{
						grid +='<select id="'+this.output+'_'+dgtel+'m'+dgtel2+'_input'+bbbb+'" value="'+currrowdata.fields[flds[dgtel2]]+'" style="display:none;width:99%" onchange="'+this.cn+'.changefield('+dgtel+','+flds[dgtel2]+',this);"  style="width:100%">';// onchange="'+this.cn+'.changefield('+row+','+flds[dgtel2]+',this);"
						
						selector='';
						hasselector=false;
						for(yyyy=0;yyyy<flds2[dgtel2].setdata[bbbb].setdata[0].length;yyyy++)
						{
							if(flds2[dgtel2].setdata[bbbb].setdata[0][yyyy]==currrowdata.fields[flds[dgtel2]])
							{
								hasselector=true;
							}
						}
						for(yyyy=0;yyyy<flds2[dgtel2].setdata[bbbb].setdata[0].length;yyyy++)
						{
							
							
							
							if(flds2[dgtel2].setdata[bbbb].setdata[0][yyyy]==currrowdata.fields[flds[dgtel2]])
							{
								

								selector="selected";
								if(currentisselectedfield)
								{
									fieldval=flds2[dgtel2].setdata[bbbb].setdata[1][yyyy];
								}
							}						
							else if((currentisselectedfield)&&(!hasselector))
							{
								if(yyyy==0)
								{
									flds2[dgtel2].setdata[bbbb].setdata[1][yyyy];
									fieldval=flds2[dgtel2].setdata[bbbb].setdata[1][yyyy];
									currrowdata.fields[flds[dgtel2]]=flds2[dgtel2].setdata[bbbb].setdata[0][yyyy];
								}
							}							
							else
							{
								selector='';
							}
							
							grid +='<option value="'+flds2[dgtel2].setdata[bbbb].setdata[0][yyyy]+'" '+selector+'>'+flds2[dgtel2].setdata[bbbb].setdata[1][yyyy]+'</option>';
						}
						grid +='</select>';
					}
					else if(flds2[dgtel2].setdata[bbbb].type=='hidden')
					{
						grid +='<input id="'+this.output+'_'+dgtel+'m'+dgtel2+'_input'+bbbb+'" value="'+currrowdata.fields[flds[dgtel2]]+'" style="display:none" type="hidden">';
						if(depfieldvalue==flds2[dgtel2].setdata[bbbb].attachedvalue)
						{
							fieldval = currrowdata.fields[flds[dgtel2]];
						}
					}
				}
				}
				grid +='<input id="'+this.output+'_'+dgtel+'m'+dgtel2+'_input" value="'+currrowdata.fields[flds[dgtel2]]+'" style="display:none" type="hidden">';
			}
			if(this.data.canEdit)
			{
				oc1='onclick="'+this.cn+'.editrow('+dgtel+','+dgtel2+')" style="cursor:pointer"';
			}
			else
			{
				oc1='';
			}
			grid +='<div id="'+this.output+'_'+dgtel+'m'+dgtel2+'_view" '+oc1+'>'+fieldval+'</div>';
			grid +='</td>';
		}
		if(totalspacing>=1)
		{
			//used for filling spaces.
			grid +='<td></td>';
		}
		if(this.data.canEdit)
		{
			grid +='<td width="15">';		
			grid +='<div class="ICON3_undo" onmouseout="_toolTip.hide();" onmouseover="'+tt1+'Cancel edit'+tt2+'" onclick="'+this.cn+'.cancelrow('+dgtel+')" id="'+this.output+'_'+dgtel+'_rowcancelbutton" style="display:none" style="cursor:pointer">&nbsp;</div>';		
			grid +='</td>';
			grid +='<td width="15">';		
			grid +='<div class="ICON3_edit" onmouseout="_toolTip.hide();" onmouseover="'+tt1+'Edit'+tt2+'" onclick="'+this.cn+'.editrow('+dgtel+')" id="'+this.output+'_'+dgtel+'_roweditbutton" style="cursor:pointer;display:table;">&nbsp;</div>';		
			grid +='<div class="ICON3_diskette" onmouseout="_toolTip.hide();" onmouseover="'+tt1+'Save changes'+tt2+'" onclick="'+this.cn+'.saverow('+dgtel+')" id="'+this.output+'_'+dgtel+'_rowsavebutton" style="display:none" style="cursor:pointer;">&nbsp;</div>';		
			grid +='</td>';
		}	
		
		
		if(this.data.canReorder)
		{
			grid +='<td width="15">';		
			grid +='<div class="ICON3_up" onmouseout="_toolTip.hide();" onmouseover="'+tt1+'Move up'+tt2+'" onclick="'+this.cn+'.moverowup('+dgtel+')" style="cursor:pointer">&nbsp;</div>';		
			grid +='</td>';
			grid +='<td width="15">';
			grid +='<div class="ICON3_down" onmouseout="_toolTip.hide();" onmouseover="'+tt1+'Move down'+tt2+'" onclick="'+this.cn+'.moverowdown('+dgtel+')" style="cursor:pointer">&nbsp;</div>';		
			grid +='</td>';
		}		
		if(this.data.canRemove)
		{
			grid +='<td width="15">';		
			grid +='<div class="ICON3_trash" onmouseout="_toolTip.hide();" onmouseover="'+tt1+'Remove'+tt2+'" onclick="'+this.cn+'.removerow('+dgtel+')" style="cursor:pointer">&nbsp;</div>';		
			grid +='</td>';
		}
		// this check is used for 'advanced search' on service page to make the first row editable immediately
 		if(this.data.alwaysOpen)
		{
		    	this.data.rows[dgtel].editmode=true;
		}
		//<td></td>		
		grid+='</tr>';
		if(ab=='a')
		{
			ab='b';
		}
		else
		{
			ab='a';
		}
	}
	
	bottomrowinsides='';
	if(this.data.canAdd)
	{
		bottomrowinsides='<div class="ICON3_add" onmouseout="_toolTip.hide();" onmouseover="'+tt1+'Add'+tt2+'" onclick="'+this.cn+'.addrow()" style="cursor:pointer">&nbsp;</div>';		
	}
	grid += '</td></tr></table>';
	grid += '<tr><td style="background-color:#'+this.bottomcolor+';font-size:1px;" align="right">'+bottomrowinsides+'</td></tr>';
	grid += '<tr><td><div class="roundcorner5bottom lightgraycontainer"></div></td></tr>';
	

	
	grid +='</table>';
	puntapi._(this.config.output).innerHTML=grid;
	//now check each field for the editmode
	for(dgtel=0;dgtel <this.data.rows.length;dgtel++)
	{
		if(this.data.rows[dgtel].editmode)
		{
			this.switchtoeditmode(dgtel);
		}
	}
}
datagrid.prototype.nlescaped2br=  function (myString) 
{
var regX = /\\n/gi ;

s = new String(myString);
s = s.replace(regX, "<br /> \n");
return s;
}




//[PACKSEP]



function punt_forms(cn)
{
		this.cn = cn;
		this.forms = [];
		this.debugon=false;
		this.debugtxt='';
		
		if (navigator.appVersion.indexOf("MSIE")!=-1)
		{
			this.isIE=true;
		}
		else
		{
			this.isIE=false;
		}
		this.ratingredrawtimeouts={};
		
}
punt_forms.prototype.setSubmitMessages = function(formid, data)
{
	if (data != '')
	{		
		realFormId = this.lookupid(formid);
		if (realFormId >= 0)
		{
			this.forms[realFormId].onSubmitMessages = [];
			var parsed = JSON2.parse(data);
			this.forms[realFormId].onSubmitMessages = parsed;
		}
	}		
}
punt_forms.prototype.doOnSubmitMessages = function(formid)
{
	realFormId = this.lookupid(formid);
	if (realFormId >= 0)
	{
		if (typeof this.forms[realFormId].onSubmitMessages != 'undefined')
		{
			for(i = 0;i<this.forms[realFormId].onSubmitMessages.length;i++)
			{
				formelementValue = this.getElementValue(formid, this.forms[realFormId].onSubmitMessages[i]['formelement']);
				if (typeof formelementValue != 'undefined')
				{


					if (this.forms[realFormId].onSubmitMessages[i]['value'] == formelementValue)
					{
						if (this.forms[realFormId].onSubmitMessages[i]['type'] == 'confirm')
						{
							value = confirm(this.forms[realFormId].onSubmitMessages[i]['message']);
							if (value == false)
							{
								return false;
							}
						}
						else if (this.forms[realFormId].onSubmitMessages[i]['type'] == 'alert')
						{
							alert(this.forms[realFormId].onSubmitMessages[i]['message']);
						}

					}
				}
				else
				{
					return true;
				}
			}
			return true;
		}
		else
		{
			return true;
		}
	}
}
punt_forms.prototype.getElementValue = function(formid, elementname)
{
	realFormId = this.lookupid(formid);
	elementId = this.lookupelementid(formid, elementname);	
	if (realFormId >= 0 && elementId >= 0)
	{
		element = puntapi._(formid+'_'+elementname);		
		if (element)
		{

			if (this.forms[realFormId].elements[elementId].itemtype == 'checkbox')
			{

				if (element.checked)
				{
					value  = element.value
				}
				else
				{
					value = '';
				}
			}
			else
			{
				value = element.value;
			}
		}
		return value;
	}
}
punt_forms.prototype.rescalestart = function()
{
	//rescale tinymce

	//first check if the forms are available
	var fou = 0;
	var foulen=0;
	var currmceid='';
	try
	{
		//tinyMCE.triggerSave();
	}
	catch(e)
	{
		
	}

	for(fou=0;fou<this.forms.length;fou++)
	{
		if(this.forms[fou].removed)
		{
			//forget it :)
		}
		else
		{
			//
			if(this.checkexistance(fou))
			{
				//form exists.. now check the elements for wysiwyg editors..... turn them off and renable them later 
				for(foulen=0;foulen<this.forms[fou].elements.length;foulen++)
				{
					if (this.forms[fou].elements[foulen].itemtype.indexOf('wysiwyg') > -1) 
					{
						currmceid = this.forms[fou].formid + '_' + this.forms[fou].elements[foulen].itemname;
						
						if (tinyMCE.getInstanceById(currmceid) != null) 
						{
							try 
							{
								puntapi._(this.forms[fou].formid + '_' + this.forms[fou].elements[foulen].itemname + '_tbl').style.width = '98%';
							} 
							catch (e) 
							{
							
							}
						// tinyMCE.execCommand('mceRemoveControl', false, this.forms[fou].formid+'_'+this.forms[fou].elements[foulen].itemname);
						}
						
					}
					else if (this.forms[fou].elements[foulen].itemtype == 'code') 
					{
						this.rescaleCodeField(this.forms[fou].formid, this.forms[fou].elements[foulen].itemname);
					}
					else if (this.forms[fou].elements[foulen].itemtype == 'image') 
					{
						setTimeout("puntforms.rescaleImageField('"+this.forms[fou].formid+"','"+this.forms[fou].elements[foulen].itemname+"');",100);
					}
				}
			}
		}
	}
}
punt_forms.prototype.rescaledone = function()
{
	//rescale tinymce

	//first check if the forms are available
	var fou = 0;
	var foulen=0;
	var currmceid='';
	try
	{
		//tinyMCE.triggerSave();
	}
	catch(e)
	{
		
	}

	for(fou=0;fou<this.forms.length;fou++)
	{
		if(this.forms[fou].removed)
		{
			//forget it :)
		}
		else
		{
			//
			if(this.checkexistance(fou))
			{
				//form exists.. now check the elements for wysiwyg editors..... turn them off and renable them later 
				for(foulen=0;foulen<this.forms[fou].elements.length;foulen++)
				{
					if(this.forms[fou].elements[foulen].itemtype.indexOf('wysiwyg')>-1)
					{
						currmceid=this.forms[fou].formid+'_'+this.forms[fou].elements[foulen].itemname;
						
	                    //tinyMCE.execCommand('mceAddControl', false, this.forms[fou].formid+'_'+this.forms[fou].elements[foulen].itemname);
                		
						
					}
				}
			}
		}
	}
	timg.rescale();
}
punt_forms.prototype.checkexistance = function(formid)
{
	//if the form exists... the form's id field should be available... lets get it 
	fo_elem = puntapi._(this.forms[formid].formid+'_formcheckelement');
	
	if(fo_elem)
	{
		//it exists
		
		return true;
	}
	else
	{
		
		this.clearform(formid);	
		return false
	}
	
	
	//
}
punt_forms.prototype.debugalert = function(teks)
{
	if(typeof env !='undefined')
	{
		if(env=='dev')
		{
			alert(teks);
		}
	}
}
punt_forms.prototype.debug = function(teks)
{
	if(this.debugon)
	{
		alert(teks);
	}
}

punt_forms.prototype.echoout = function(text)
{
	try
	{
		this.debugtxt+=text+'\n';
		
	}
	catch(e)
	{
		
	}
}
punt_forms.prototype.lookupBySubName = function(subname)
{
		var tto =0;
		var max = this.forms.length;
		
		for(tto=0;tto<max;tto++)
		{
			
			if(this.forms[tto].formid_sub==subname)
			{
		
				return tto;
			}
			else
			{
		
			}
			
		}
		return -1;
}
punt_forms.prototype.lookupid = function(formid)
{
		var tto =0;
		var max = this.forms.length;
		
		for(tto=0;tto<max;tto++)
		{
			
			if(this.forms[tto].formid==formid)
			{
		
				return tto;
			}
			else
			{
		
			}
			
		}
		return -1;
}
punt_forms.prototype.lookupelementid = function(formname,elementname)
{
	formidnr = this.lookupid(formname);
	
	
	max = this.forms[formidnr].elements.length;
		for(o=0;o<max;o++)
		{
			
			if(this.forms[formidnr].elements[o].itemname==elementname)
			{
				
				return o;
			}
			else
			{
				
			}
			
		}
		return -1;	
}
punt_forms.prototype.submitFormBySubid = function(subid)
{
	var formidnr =this.lookupBySubName(subid);
	
	if (formidnr > -1) 
	{
		var formid = this.forms[formidnr].formid;
		eval(formid+'_dosubmit()');
		
	}
}

punt_forms.prototype.submitForm = function(formid)
{
	eval(formid+'_dosubmit()');
}
punt_forms.prototype.toggleformsubmit = function(formid,status)
{
	cmdev = formid+'_togglesubmit(status)';
	eval(cmdev);
	
	
	
	
}
punt_forms.prototype.wysiwyginsertlink = function()
{
	 
	 ppos = arguments.length;
	 for(o=0;o<arguments.length;o++)
	 {
	  
	 }
	 
     itemid 		= arguments[ppos-2];
	 itemd 			= arguments[ppos-1];	 
	 
	 if(itemd=='wysiwygtinymce')
	 {
	 	
	 	origtext=itemid[2];
	 	
	 	
	 	
	 }
	 else
	 {
		 	var browserName = navigator.appName;
			origtext='';
			if (browserName == "Microsoft Internet Explorer") 	  
			{
				if(typeof currentrange.htmlText !='undefined')
				{
					try
					{
						origtext = ''+currentrange.htmlText;
					}
					catch(e)
					{
						origtext='';
					}
					
				}
			
			}
			else
			{
			 var range = currentrange.getRangeAt(0);
			 origtext = ''+range;
				
			}	 	 
	
	 	
	 }

	 //get the text from the current range
	
	 target ='';
	 hyperlink='';
	 
	 if(arguments[0]!='')
	 {
	 	target='target="'+arguments[0]+'"';
	 
	 }
	 if(arguments[2]=='page')
	 {
	 	hyperlink = arguments[3];
	 }
	 if(arguments[2]=='mediaalbums')
	 {
	 	hyperlink='/mediaalbum/albums';
	 }
	 if(arguments[2]=='mediaalbum')
	 {
	 	list = arguments[8].split('$^');
	 	articleid = list[0];
	 	if(typeof list[1] !='undefined')
	 	{
	 		hyperlink ='/mediaalbum/viewalbumitems/'+articleid+'/'+encodeURIComponent(list[1].replace(' ','_'));
	 	}
	 	else
	 	{
	 		hyperlink ='/mediaalbum/viewalbumitems/'+articleid;
	 	}
	 }	 
	 if(arguments[2]=='article')
	 {
	 	list = arguments[4].split('$^');
	 	articleid = list[0];
	 	if(typeof list[1] !='undefined')
	 	{
	 		hyperlink ='/content/view/'+articleid+'/'+encodeURIComponent(list[1].replace(' ','_'));
	 	}
	 	else
	 	{
	 		hyperlink ='/content/view/'+articleid;
	 	}
	 }	 
	 if(arguments[2]=='category')
	 {
	 	list = arguments[5].split('$^');
	 	articleid = list[0];
	 	if(typeof list[1] !='undefined')
	 	{
	 		hyperlink ='/content/getcategories/'+articleid+'/'+encodeURIComponent(list[1].replace(' ','_'));	 	
	 	}
	 	else
	 	{
	 		hyperlink ='/content/getcategories/'+articleid;
	 	}
	 }
	 
	 if(arguments[2]=='form')
	 {
	 	list = arguments[6].split('$^');
	 	articleid = list[0];
	 	if(typeof list[1] !='undefined')
	 	{	 	
	 		hyperlink ='/form/view/'+articleid+'/'+encodeURIComponent(list[1].replace(' ','_'));	 	
	 	}
	 	else
	 	{
	 		hyperlink ='/form/view/'+articleid;	
	 	}
	 	
	 }	 
	 if(arguments[2]=='rss')
	 {
	 	hyperlink = '/content/rss';
	 }
	 if(arguments[2]=='admin')
	 {
	 	hyperlink = '/Admin';
	 }	 
	 if(arguments[2]=='url')
	 {
	 	hyperlink = arguments[7];
	 }		 
	 if(arguments[1]!='')
	 {
	 	text = arguments[1];
	 }
	 else
	 {
	 	text = origtext;
	 }
	 
	 
	 if(text!='')
	 {
	 	html = '<a href="'+hyperlink+'" '+target+'>'+text+'</a>';
	 	
		if(itemd=='wysiwygtinymce')
	 	{
	 		puntapi.insertHTML(html,itemid[0],itemid[1],itemid[4]);
	 	}
	 	else
	 	{
	 		insertHTML(html,itemid,currentrange);
	 	}
	 }
	 else
	 {
	 	alert('Error: no text was selected for this link');
	 }
	 
}
punt_forms.prototype.clearform = function(id)
{
	
	this.forms[id].removed= true;
	this.forms[id].formid= '';
	this.forms[id].callbacks = [];
	this.forms[id].formelements = [];
}
punt_forms.prototype.doneInitForm = function(formid)
{
	var id = this.lookupid(formid);
	this.forms[id].initializing=false;
}
punt_forms.prototype.registerform = function(formid,formid_sub)
{

	
	
	var id = this.lookupid(formid);
	currentform = {};
	currentform.initializing=true;
	currentform.formid = formid;
	currentform.formid_sub = formid_sub;
	currentform.callbacks = [];
	currentform.dependencies = [];
	currentform.illustrations = [];
	currentform.writetootherfields = [];
	currentform.groups = [];
	currentform.elements = [];
	currentform.groupelements = [];
	currentform.uploadedstatus = 1;
	currentform.ruleset = {};
	
	if(id>-1)
	{
		this.clearform(id);	
		this.forms[id]=currentform;		
	}
	else
	{
		//id=this.forms.length;
		this.forms[this.forms.length]=currentform;		
	}
	
	

	
}

punt_forms.prototype.setRuleset =function(formid,ruleset)
{
	
	var id = this.lookupid(formid);
	this.forms[id].ruleset=ruleset;
	
}


punt_forms.prototype.applyRules =function(formid)
{
	var id = this.lookupid(formid);
	var match=-1;
	
	try
	{
		if(typeof this.forms[id].ruleset !='undefined')
		{
			if(typeof this.forms[id].ruleset.rules !='undefined')
			{
				//there is a ruleset...
				for(var rulenr=0;rulenr<this.forms[id].ruleset.rules.length;rulenr++)
				{
					if(match==-1)
					{
						if(this.checkRule(formid,this.forms[id].ruleset.rules[rulenr]))
						{
							match=rulenr;
						}
						
					}
				}
				if(match==-1)
				{
					//use the otherwise
					this.applyRule(formid,this.forms[id].ruleset.otherwise);
				}
				else
				{
					//apply the rule
					this.applyRule(formid,this.forms[id].ruleset.rules[match]);
				}
				
				
				
			}
			else
			{
				
			}
		}
	}
	catch(e)
	{
		this.debugalert('----->'+JSON.stringify(e));
	}
	this.redraw(formid);
}
punt_forms.prototype.checkRule =function(formid,rule)
{
	//run through the conditions of the rule...
	var id = this.lookupid(formid);
	
	var score =0;
	var subscore=0;
	for(var rulecond=0;rulecond<rule.conditions.length;rulecond++)
	{
		
		
		
		targetid= formid+'_'+rule.conditions[rulecond].field
	
	
		type = puntapi._(targetid).type
		
		var formelem = eval('document.'+this.forms[id].formid_sub+'.'+targetid);
		
		var elemvalue='';
		if((type!='checkbox')&&(type!='radio'))
		{
			//normal field just use the normal field value
			checked =true
			elemvalue = formelem.value;
		}
		else if(type=='radio')
		{
			
			
			for (var counter = 0; counter < formelem.length;counter++)
			{
				if(formelem[counter].checked)
				{
					elemvalue = formelem[counter].value;
				}
			}
			
	
		}
		else
		{
			
			//checked=true;
			if(formelem.checked)
			{
				elemvalue=formelem.value;
			}
			else
			{
				elemvalue='';
			}
		}
		
		
		
		
		
		
		
		
		
		
		
		
		if(rule.conditions[rulecond].type=='value')
		{
			
			if(typeof rule.conditions[rulecond].values!='undefined')
			{
				//multi value check
				subscore=0;
				for(rulecond2=0;rulecond2<rule.conditions[rulecond].values.length;rulecond2++)
				{
					if(elemvalue==rule.conditions[rulecond].values[rulecond2])
					{
						subscore++;
					}
				}
				if(subscore>0)
				{
					score++;
				}
				
			}
			else
			{
				if(elemvalue==rule.conditions[rulecond].value)
				{
					score++;
				}
				else
				{
					
				}
			}
			
		}
		else if(rule.conditions[rulecond].type=='valuenot')
		{
			if(typeof rule.conditions[rulecond].values!='undefined')
			{
				//multi value check
				
				subscore=0;
				for(rulecond2=0;rulecond2<rule.conditions[rulecond].values.length;rulecond2++)
				{
					if(elemvalue==rule.conditions[rulecond].values[rulecond2])
					{
						subscore++;
					}
				}
				if(subscore==0)
				{
					score++;
				}
				
			}
			else
			{			
				if(elemvalue!=rule.conditions[rulecond].value)
				{
					score++;
				}
				else
				{
					
				}
			}
		}
	}
	if(score==rule.conditions.length)
	{
		return true;
	}
	else
	{
		return false;
	}
}
punt_forms.prototype.applyRule =function(formid,rule)
{
	var id = this.lookupid(formid);
	
	var isfield=false;
	
	for(var ruletar=0;ruletar<this.forms[id].elements.length;ruletar++)
	{
		
		isfield=false;
		for(var ruletar2=0;ruletar2<rule.fields.length;ruletar2++)
		{
			//see if its one of the chosen one....
			if(rule.fields[ruletar2]==this.forms[id].elements[ruletar].itemname)
			{
				isfield=true;
			}
		
		}
		
		if(isfield)
		{
			try
			{
				this.showrow(formid,this.forms[id].elements[ruletar].itemname);
			}
			catch(e)
			{
			}
		}
		else
		{
			try
			{
				this.hiderow(formid,this.forms[id].elements[ruletar].itemname);
			}
			catch(e)
			{
			}			
		}
		
		
		
		
		
	}
	
	
}


punt_forms.prototype.returnvaluefromdialog =function()
{
	
	
	formid 		= arguments[arguments.length-2];
	itemd 	= arguments[arguments.length-1];
	valt 	= arguments;	

	retval = valt[0];
	if(valt[5]=='thumbnail')
	{
		retval = valt[0];
	}
	else if (valt[5]=='fullsize')
	{
		retval = valt[2];
	}
	else if (valt[5]=='normal')
	{
		retval = valt[1];
	}
	puntapi._(formid+'_'+itemd).value = retval;
	this.checkfield(formid,itemd,retval,true);
}



punt_forms.prototype.newFileUpload = function(formid,formidsub,item,sessionid,targeturl,filetypes,filetypedescriptions,filesize,uploadlimit)
{

	try {	
	//alert('formelem:'+formid+'->'+item+'\nTargeturl:\n'+targeturl);
	
	if(typeof filesize=='undefined')
	{
		var filesize = '100 MB'; 
	}
	if(typeof filetypes=='undefined')
	{
		var filetypes = '*.*'; 
	}	
	if(typeof filetypedescriptions=='undefined')
	{
		var filetypedescriptions = 'global_all_files'; 
	}	
	if(uploadlimit=='')
	{
		uploadlimit='0';
	}
	else
	{

	}

	this.currentUploadLimit=uploadlimit;
	var formidval = this.lookupid(formid);
	var elemidval = this.lookupelementid(formid,item);
	var buttonid = formid+'_'+item+'_addfilebutton';
	//disable the submit button until you are ready with upload
	this.toggleformsubmit(formid,0);
	
	
	var confobj= {
			// Backend Settings
			upload_url: targeturl,
			post_params: {
				"SLSid": sessionid
			},
			
			// File Upload Settings
			file_size_limit: filesize,
			file_types: filetypes,
			file_types_description: filetypedescriptions,
			
			
			// Event Handler Settings - these functions as defined in Handlers.js
			//  The handlers are not part of SWFUpload but are part of my website and control how
			//  my website reacts to the SWFUpload events.
			file_queue_error_handler: fileQueueError,
			file_queued_handler : fileQueue,
			file_dialog_complete_handler: fileDialogComplete,
			upload_progress_handler: uploadProgress,
			upload_error_handler: uploadError,
			upload_success_handler: uploadSuccess,
			upload_complete_handler: uploadComplete,
			
			// Button Settings
			button_image_url: "/Layout/Mijndomein/images/uploadbutton2.png",
			button_placeholder_id: buttonid,
			button_width: 181,
			button_height: 29,

			button_text: '<span class="buttonText">Select files</span>',
			button_text_style: '.buttonText {color:#FFFFFF;font-size: 14pt;font-weight:bold;font-family:Trebuchet MS;}',
			button_text_top_padding: 5,
			button_text_left_padding: 5,
			button_text_right_padding: 25,
			button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
			button_cursor: SWFUpload.CURSOR.HAND,
			
			// Flash Settings
			flash_url: "/extjavascript/swfupload/swfupload.swf",
			
			custom_settings: {
				browse_button_id:'swfuploadbutton_'+buttonid,
				uploadlimit:uploadlimit,
				formid: formid,
				formidsub:formidsub,
				formelementid: item,
				upload_target:'divFileProgressContainer'
			},
			
			// Debug Settings
			debug:false
			//debug: true
		};

		if(uploadlimit=='0')
		{
			confobj.file_upload_limit='0';	
		}
		else
		{
			confobj.file_upload_limit=uploadlimit;
		}
		
		
	
		this.forms[formidval].elements[elemidval].swfu = new SWFUpload(confobj);
		
	}
	catch(e)
	{
		//alert('exception!'+e)
	}
}
punt_forms.prototype.regenerateFilelist =function(url,formname,formid,item,handle)
{
	nr++;
	TA[nr] = new TAjax();
	TA[nr].cn = 'TA['+nr+']';
	var responsecommand = this.cn+'.regenerateFilelistRecieve(\''+formid+'\',\''+item+'\',\''+handle+'\',\''+url+'\',\''+formname+'\',getresponsexml('+nr+'),getresponse('+nr+'))';
	var urlparts=url.split('?');
		TA[nr].Sourcefile=urlparts[0]+'?formdo=getfilelist&_formid='+formname+'&formelement='+item+'&fileuploaderid='+handle+'&'+urlparts[1];
	TA[nr].onReadyresponsecommand = responsecommand;
	TA[nr].doPost();
}

punt_forms.prototype.regenerateFilelistRecieve =function(formid,item,handle,url,formname,message,message2)
{

	try
	{
 	var root = message.getElementsByTagName('files').item(0);
 	totaalfiles=0;
 	filelist = [];
 	if(root)
	{
		files = root.getElementsByTagName('file');
		
		for(o=0;o<files.length;o++)
		{
			tfid = files[o].getElementsByTagName('id').item(0).firstChild.nodeValue;
			tfname = files[o].getElementsByTagName('name').item(0).firstChild.nodeValue;
			filelist[totaalfiles]= {};
			filelist[totaalfiles].fileid=tfid;
			filelist[totaalfiles].filename=tfname;
			totaalfiles++;
		}
		
		html ='';
		if(totaalfiles>0)
		{
			html += '<table class="list" cellspacing="0" cellpadding="0">';	
			alternator = 'a';
			for(u=0;u<totaalfiles;u++)
			{
				html += '<tr class="row_'+alternator+'" onmouseover="this.className=\'row_'+alternator+'_active\'" onmouseout="this.className=\'row_'+alternator+'\'">';
				html += '<td>'+filelist[u].filename+'</td>';
				html += '<td><img src="/Layout/Puntbasic/blank.gif" class="ICON3_delete"  onclick="'+this.cn+'.deletefilefromfilelist(\''+url+'\',\''+formname+'\',\''+formid+'\',\''+item+'\',\''+handle+'\',\''+filelist[u].fileid+'\')" style="cursor:pointer;"></td></tr>';
				if(alternator=='a')
				{
					alternator ='b';
				}
				else
				{
					alternator='a';
				}
			}
			html += '</table>';
			this.toggleformsubmit(formid,1);
			
			this.writecheck(formid,item,'doneupload');
			//this.doformsubmit(formid);
		}
		else
		{
			this.toggleformsubmit(formid,0);
			
		}
		
		//alert(html);
		puntapi._(formid+'_'+item+'_filelist').innerHTML=html;
		
		
		
		
	}
	else
	{
		this.toggleformsubmit(formid,0);
	}
	}
	catch(e)
	{
		//alert(e);
		//this.regenerateFilelist(url,formname,formid,item,handle);
	}
	
 	
}

punt_forms.prototype.doformsubmit =function(formid)
{
	eval(formid+'_dosubmit()');
}
punt_forms.prototype.deletefilefromfilelist =function(url,formname,formid,item,handle,fid)
{
	
	var answer = confirm("global_areyousure_deletefilefromlist");
	if (answer){
		nr++;
		TA[nr] = new TAjax();
		TA[nr].cn = 'TA['+nr+']';
		var urlparts=url.split('?');
		//responsecommand = this.cn+'.deletefilelistdone(\''+formid+'\',\''+item+'\',\''+handle+'\',\''+url+'\',\''+formname+'\')';
		var responsecommand = this.cn+'.regenerateFilelistRecieve(\''+formid+'\',\''+item+'\',\''+handle+'\',\''+url+'\',\''+formname+'\',getresponsexml('+nr+'),getresponse('+nr+'))';
		TA[nr].Sourcefile=urlparts[0]+'?formdo=deletefile&_formid='+formname+'&formelement='+item+'&fileuploaderid='+handle+'&fid='+fid+'&'+urlparts[1];
		puntapi._(formid+'_'+item+'_filelist').innerHTML='Retrieving new file list';
		
		TA[nr].onReadyresponsecommand = responsecommand;
		TA[nr].doPost();
		
	}
	else
	{
		
	}
}
punt_forms.prototype.deletefilelistdone =function(formid,item,handle,url,formname)
{
	this.regenerateFilelist(url,formnameformid,item,handle);
}
punt_forms.prototype.addWriteToOtherField =function(formid,item,target)
{
	id = this.lookupid(formid);
	len = this.forms[id].writetootherfields.length;
	this.forms[id].writetootherfields[len]={};
	this.forms[id].writetootherfields[len].formid =formid;
	this.forms[id].writetootherfields[len].item =item;
	this.forms[id].writetootherfields[len].target =target;	
}
punt_forms.prototype.addIllustrationToValue =function(formid,item,value,valimgid)
{
	id = this.lookupid(formid);
	len = this.forms[id].illustrations.length;
	this.forms[id].illustrations[len]={};
	this.forms[id].illustrations[len].formid =formid;
	this.forms[id].illustrations[len].item =item;
	this.forms[id].illustrations[len].itemval =value;
	this.forms[id].illustrations[len].valimgid =valimgid;
}
punt_forms.prototype.adddependency = function(formid,item,target,type,value,targetval)
{
	
	try
	{
		
		var id = this.lookupid(formid);
		var tid =-1;
		var possiblematch =-1;
		var possiblematch2 =-1;
		
		for(var did=0;did<this.forms[id].dependencies.length;did++)
		{
			//try to find a similar one....
			if(possiblematch==-1)
			{
				if((this.forms[id].dependencies[did].item==item)&&(this.forms[id].dependencies[did].value==value)&&(this.forms[id].dependencies[did].type==type))
				{
					possiblematch=did;
					
				}
			}
		}
		if(possiblematch>-1)
		{
			tid=possiblematch;
		}
		else
		{
			//create a new one
			tid = this.forms[id].dependencies.length;
			this.forms[id].dependencies[tid]={};
			this.forms[id].dependencies[tid].item=item;
			this.forms[id].dependencies[tid].value=value;
			this.forms[id].dependencies[tid].type=type;
			this.forms[id].dependencies[tid].targets=[];
		}
		
		//now go through the targets and try to find a target.... otherwise throw an exception if in dev mode or ignore in other mode
		for(var targetid=0;targetid<this.forms[id].dependencies[tid].targets.length;targetid++)
		{
			
			if(possiblematch2==-1)
			{
				if(this.forms[id].dependencies[tid].targets[targetid].name==target)
				{
					possiblematch2=targetid;	
				
				}
				
			}
		}
		//if it isn't there create it 
		if(possiblematch2>-1)
		{
			targetid=possiblematch2;
			//this shouldn't happen
			this.debugalert('There is double form dependency on the field: '+item+' Please resolve it before committing');
			return false;
		}
		else
		{
			
			targetid= this.forms[id].dependencies[tid].targets.length;
			this.forms[id].dependencies[tid].targets[targetid]={};
			this.forms[id].dependencies[tid].targets[targetid].name=target;
			this.forms[id].dependencies[tid].targets[targetid].targetvalue=targetval;
			
		}
		
	}
	catch(e)
	{
		
	}
}
punt_forms.prototype.adddependency_old = function(formid,item,target,type,value,targetval)
{
	
	id = this.lookupid(formid);
	
	newdepid = this.forms[id].dependencies.length;
	
	this.forms[id].dependencies[newdepid]={};
	
	this.forms[id].dependencies[newdepid].item=item;
	
	this.forms[id].dependencies[newdepid].target=target;
	this.forms[id].dependencies[newdepid].type=type;
	this.forms[id].dependencies[newdepid].val=value;
	this.forms[id].dependencies[newdepid].targetval=targetval;
}
punt_forms.prototype.illustrationslookup = function(formid,item)
{
	var illustrations = [];
	var id = this.lookupid(formid);
	for(u=0;u<this.forms[id].illustrations.length;u++)
	{
		if(this.forms[id].illustrations[u].item==item)
		{
			illustrations[illustrations.length]=this.forms[id].illustrations[u];
	
		}
	}
	
	return illustrations;
}
punt_forms.prototype.dependencylookup = function(formid,item)
{
	dependencies = [];
	for(u=0;u<this.forms[formid].dependencies.length;u++)
	{
		if(this.forms[formid].dependencies[u].item==item)
		{
			dependencies[dependencies.length]=this.forms[formid].dependencies[u];
	
		}
	}
	return dependencies;
}
punt_forms.prototype.writetootherfieldlookup = function(formid,item)
{
	
	var dependencies = [];
	var lformid = this.lookupid(formid);
	
	for(u=0;u<this.forms[lformid].writetootherfields.length;u++)
	{
		
		if(this.forms[lformid].writetootherfields[u].item==item)
		{
			dependencies[dependencies.length]=this.forms[lformid].writetootherfields[u];
	
		}
	}
	
	return dependencies;
}


punt_forms.prototype.dependencycheck= function(formid,item)
{
	
	try
	{
	var id = this.lookupid(formid);
	var deps = this.dependencylookup(id,item);
	if(deps.length==0)
	{
		return false;
	}
	
	var tgnr=0;
	var hasmatch=-1;
		
	//collect data
		
	targetid= formid+'_'+item
	
	
	type = puntapi._(targetid).type
	
	var formelem = eval('document.'+this.forms[id].formid_sub+'.'+targetid);
	
	var elemvalue='';
	if((type!='checkbox')&&(type!='radio'))
	{
		//normal field just use the normal field value
		checked =true
		elemvalue = formelem.value;
	}
	else if(type=='radio')
	{
		for (var counter = 0; counter < formelem.length;counter++)
		{
			if(formelem[counter].checked)
			{
				elemvalue = formelem[counter].value;
			}
		}
		

	}
	else
	{
		
		//checked=true;
		if(formelem.checked)
		{
			elemvalue=formelem.value;
		}
		else
		{
			elemvalue='';
		}
	}
	

	
	
	
	
	
	if(deps.length>0)
	{
		for(var dnr=0;dnr<deps.length;dnr++)
		{
			if(hasmatch==-1)
			{
				if(deps[dnr].type=='value')
				{
					if(deps[dnr].value==elemvalue)
					{
						hasmatch=dnr;
					}
					else
					{
						
					}
				}
				else if(deps[dnr].type=='valuenot')
				{
					if(deps[dnr].value!=elemvalue)
					{
						hasmatch=dnr;
					}
					else
					{
						
					} 
				}
			}
		}
		
	}
//first do the no matches
	var formelem2  =null;
	for(var dnr=0;dnr<deps.length;dnr++)
	{
		if(dnr!=hasmatch)
		{
			for(var tgnr=0;tgnr<deps[dnr].targets.length;tgnr++)
			{
				this.hiderow(formid,deps[dnr].targets[tgnr].name);
			}
		}
		else
		{

		}
	}	
	if(hasmatch>-1)
	{
		
		
		
		for(var tgnr=0;tgnr<deps[hasmatch].targets.length;tgnr++)
		{
			this.showrow(formid,deps[hasmatch].targets[tgnr].name);
							
			if(deps[hasmatch].targets[tgnr].targetvalue!='-isnull-')	
			{
				targetid2= formid+'_'+deps[hasmatch].targets[tgnr].name;
			
				formelem2 = eval('document.'+this.forms[id].formid_sub+'.'+targetid2);				
				
				if(formelem2.type=='radio')
				{
					for (var counter = 0; counter < formelem2.length;counter++)
					{
						if(formelem2[counter].value==deps[hasmatch].targets[tgnr].targetvalue)
						{
							formelem2[counter].checked=true;
							
						}
						else
						{
							formelem2[counter].checked =false;
						}
					}
				}
				else if(formelem2.type=='checkbox')
				{
					if(formelem2.value==deps[hasmatch].targets[tgnr].targetvalue)
					{
						formelem2.checked=true;
					}
					else
					{
						formelem2.checked=false;
					}
				}
				else
				{
					formelem2.value=deps[hasmatch].targets[tgnr].targetvalue;
				}
				
			}
		}
		for(var tgnr=0;tgnr<deps[hasmatch].targets.length;tgnr++)
		{
			this.dependencycheck(formid,deps[hasmatch].targets[tgnr].name);
		}
		
	}
	else
	{
		//check it anyway
		for(var dnr=0;dnr<deps.length;dnr++)
		{
			for(var tgnr=0;tgnr<deps[dnr].targets.length;tgnr++)
			{
				this.dependencycheck(formid,deps[dnr].targets[tgnr].name);
			}		
		}
	}
	}
	catch(e)
	{
		
	}
			

	//otherwise skip it...
	
	
}
punt_forms.prototype.dependencycheck_newerbutstillold = function(formid,item)
{
	var depcheckresult=0;
	var triggereddep=-1;
	var targets= [];
	var tcheckid= [];
	var docheck = -1;
	
	var dependencies = this.dependencylookup(id,item);
	for(var fo=0;fo<dependencies.length;fo++)
	{
		docheck = -1;
		for(ttid=0;ttid<targets.length;ttid++)
		{
			if(dependencies[fo].target==targets[ttid])
			{
				docheck=0;
			}
		}
		if(docheck==-1)
		{
			depcheckresult = this.executedependency(formid,dependencies[fo]);
			if(depcheckresult)
			{
				
				//triggereddep=fo;
				tcheckid=-1;
				for(ttid=0;ttid<targets.length;ttid++)
				{
					if(targets[ttid]==dependencies[fo].target)
					{
						tcheckid=ttid;
					}
				}
				if(tcheckid==-1)
				{
					targets[targets.length]=dependencies[fo].target;
				}
			}
		}
		
	}
	for(ttid=0;ttid<targets.length;ttid++)
	{
		
		this.dependencycheck(formid,targets[ttid]);
		
	}	
	//now see if any of the targets changed....
	
	
}
punt_forms.prototype.dependencycheck_old = function(formid,item)
{
		
	var returnor = [];
	var id = this.lookupid(formid);
	
	var dependencies = this.dependencylookup(id,item);
	for(o=0;o<dependencies.length;o++)
	{
		
		if(this.lookupreturnor(returnor,dependencies[o].item,dependencies[o].target)<0)
		{
			depcheckresult = this.executedependency(formid,dependencies[o]);
			dependencies[o].depcheckresult=depcheckresult;
			if(depcheckresult==1)
			{
				newreturnor = returnor.length;
				returnor[newreturnor]=[];
				returnor[newreturnor].item=dependencies[o].item;
				returnor[newreturnor].target=dependencies[o].target;
				
				
			}
			
			
		}
		
		
		
	}
	/*for(o=0;o<dependencies.length;o++)
	{
		if(dependencies[o].depcheckresult==1)
		{
			this.dependencycheck(formid,dependencies[o].target);
		}
	}*/
}





punt_forms.prototype.iconselect_register = function(formid,item)
{
	formidval = this.lookupid(formid);
	elemidval = this.lookupelementid(formid,item);
	
	this.forms[formidval].elements[elemidval].isiconselect=true;
	
	
}
punt_forms.prototype.iconselect_readvalues = function(formid,item)
{
	formelemid= formid+'_'+item;
	tobesplit = puntapi._(formelemid).value;
	
	splitted = tobesplit.split(',');
	for(k=0;k<splitted.length;k++)
	{
		
		this.iconselect_togglevalue(formid,item,splitted[k],'on');
	}
	
}
punt_forms.prototype.iconselect_registervalue = function(formname,item,value)
{
	formidval = this.lookupid(formname);
	elemidval = this.lookupelementid(formname,item);
	
	max = this.forms[formidval].elements[elemidval].vals.length;
	this.forms[formidval].elements[elemidval].vals[max]= [];
	this.forms[formidval].elements[elemidval].vals[max].value=value;
	this.forms[formidval].elements[elemidval].vals[max].selected=false;
	
}
punt_forms.prototype.multiple_choice_initialise =function(formname,item,val)
{
	var elemname =formname+'_'+item;
	var selectelem = puntapi._(elemname);
	selectelem.value=val;
	val = '';
	
	try 
	{
		var prts = val.split(",");
		for (var o = 0; o < prts.length; o++) 
		{
			
			this.choice_select(formname, item, prts[o], '', 'multiplechoice', 'on')
		}
	}catch(e){
	}
}
punt_forms.prototype.choice_select = function(formname,item,val,styling,type,seton)
{
	var elemname =formname+'_'+item;
	
	var selectelem = puntapi._(elemname);
	
	var partname;
	
	if (type == 'multiplechoice') 
	{
		var selectelem2 = puntapi._(elemname+'_select');
		var prts = selectelem.value.split(",");
		var nwprts = [];
		var oo=0;
		var intherepos=-1;
		if (val != '') 
		{
			for (oo = 0; oo < prts.length; oo++) 
			{
				if (prts[oo] == val) 
				{
					intherepos = oo;
				}
			}
			
			
			if (intherepos == -1) 
			{
				//need to put it in there....
				prts[prts.length] = val;
				for (oo = 0; oo < prts.length; oo++) 
				{
					nwprts[oo] = prts[oo];
				}
			}
			else 
			{
				for (oo = 0; oo < prts.length; oo++) 
				{
					if (intherepos != oo) 
					{
						nwprts[nwprts.length] = prts[oo];
					}
				}
			}
		}
		else
		{
			for (oo = 0; oo < prts.length; oo++) 
			{
				nwprts[oo] = prts[oo];
			}			
		}
		selectelem.value=nwprts.join(',');
		prts = nwprts;
		
		
		for (var o = 0; o < selectelem2.options.length; o++) 
		{
			partname = elemname + '_item_' + (o + 1);
			puntapi._(partname + '_selectedicon').style.display = 'none';	
			for(oo=0;oo<prts.length;oo++)
			{
				if(prts[oo]==selectelem2.options[o].value)
				{
					puntapi._(partname + '_selectedicon').style.display = 'block';	
					
				}
				
			}
		}
	}
	else 
	{
		for (var o = 0; o < selectelem.options.length; o++) 
		{
			partname = elemname + '_item_' + (o + 1);
			
			if (selectelem.options[o].value == val) 
			{
			
				puntapi._(partname + '_selectedicon').style.display = 'block';
				selectelem.value = val;
				if (styling != '') 
				{
					if (this.isIE) 
					{
						puntapi._(elemname + '_styleOut').style.cssText = styling;
					}
					else 
					{
						puntapi._(elemname + '_styleOut').setAttribute('style', styling);
					}
				}
			}
			else 
			{
				puntapi._(partname + '_selectedicon').style.display = 'none';
			}
			
		}
		
	}
	this.checkfield(formname,item,val,true);
}
punt_forms.prototype.iconselect_togglevalue = function(formname,item,val,on)
{
	//okay the values
	
	if(typeof on == 'undefined')
	{
		//just toggle
	
	}
	else
	{
		
		if(on=='on')
		{
			toggleto=true;
		}
		else
		{
			toggleto=false;
		}
		
	}
	
	
	formidval = this.lookupid(formname);
	elemidval = this.lookupelementid(formname,item);	
	max = this.forms[formidval].elements[elemidval].vals.length;
	for(uu=0;uu<max;uu++)
	{
		if(this.forms[formidval].elements[elemidval].vals[uu].value==val)
		{
			if(typeof toggleon!='undefined')
			{
				this.forms[formidval].elements[elemidval].vals[uu].selected = toggleto	
			}
			else
			{
			
				if(this.forms[formidval].elements[elemidval].vals[uu].selected)
				{
					this.forms[formidval].elements[elemidval].vals[uu].selected=false;
				}
				else
				{
					this.forms[formidval].elements[elemidval].vals[uu].selected=true;
				}
			}
			
		}
	}
	if(typeof on=='undefined')
	{
		
		this.iconselect_repaint(formname,item);
	}
}

punt_forms.prototype.iconselect_repaint = function(formname,item)
{
	formelemid= formname+'_'+item;
	/*tobesplit = puntapi._(formelemid).value;
	splitted = tobesplit.split(',');*/
	
	formidval = this.lookupid(formname);
	elemidval = this.lookupelementid(formname,item);	
	max = this.forms[formidval].elements[elemidval].vals.length;
	outvals=[];
	selalpha=100;
	unselalpha=50;
	for(uu=0;uu<max;uu++)
	{
		fepath = formelemid+'_icon_'+this.forms[formidval].elements[elemidval].vals[uu].value;
		
		if(this.forms[formidval].elements[elemidval].vals[uu].selected)
		{
			outvals[outvals.length]=this.forms[formidval].elements[elemidval].vals[uu].value;
			puntapi._(fepath).style.opacity = selalpha/100;
			puntapi._(fepath).style.filter = 'alpha(opacity=' +selalpha + ')';
			puntapi._(fepath).style.border = '2px solid #587cb3';
			
			

		}
		else
		{
			
			
			puntapi._(fepath).style.opacity = unselalpha/100;
			puntapi._(fepath).style.filter = 'alpha(opacity=' +unselalpha + ')';	
			puntapi._(fepath).style.border = '2px solid white';

		

			
		}
		
	}
	puntapi._(formelemid).value =outvals.join(',');
	this.debugon=false;

}
punt_forms.prototype.lookupreturnor = function(returnor,field,target)
{
	
	
	lnth=returnor.length;
	
	for(p=0;p<lnth;p++)
	{
		if((returnor[p].item==field)&&(returnor[p].target==target))
		{
			return p;
		}
	}
	return -1;
}
punt_forms.prototype.executeIllustrations = function(formid)
{
	id = this.lookupid(formid);
	var dta='';
	for(u=0;u<this.forms[id].illustrations.length;u++)
	{
		targetid= formid+'_'+this.forms[id].illustrations[u].item;
		value = puntapi._(targetid).value;
		
		if(this.forms[id].illustrations[u].itemval==value)
		{
			puntapi._(this.forms[id].illustrations[u].valimgid).style.display='inline';
		}
		else
		{
			puntapi._(this.forms[id].illustrations[u].valimgid).style.display='none';
		}
		
	}	

	
}
punt_forms.prototype.executedependencies = function(formid)
{
	id = this.lookupid(formid);
	lnth = this.forms[id].dependencies.length;
	for(o=0;o<lnth;o++)
	{
		
		this.dependencycheck(formid,this.forms[id].dependencies[o].item);
	}
}
punt_forms.prototype.executedependency = function(formid,dependency)
{
	targetid= formid+'_'+dependency.item;
	targetid2= formid+'_'+dependency.target;
	
	type = puntapi._(targetid).type
	formidnr = this.lookupid(formid);
	var formelem = eval('document.'+this.forms[formidnr].formid_sub+'.'+targetid);
	var formelemtarget = eval('document.'+this.forms[formidnr].formid_sub+'.'+targetid2);
	var elemvalue='';
	if((type!='checkbox')&&(type!='radio'))
	{
		//normal field just use the normal field value
		checked =true
		elemvalue = formelem.value;
	}
	else if(type=='radio')
	{
		//('type'+type);
		
		
		for (var counter = 0; counter < formelem.length;counter++)
		{
			if(formelem[counter].checked)
			{
				elemvalue = formelem[counter].value;
			}
		}
		

	}
	else
	{
		
		//checked=true;
		if(formelem.checked)
		{
			elemvalue=formelem.value;
		}
		else
		{
			elemvalue='';
		}
	}
	if(dependency.type=='valuenot')
	{
		if(elemvalue!=dependency.val)
		{
			this.showrow(formid,dependency.target);
			if(dependency.targetval!='-null-')
			{
				formelemtarget.value=dependency.targetval;
			}
			return 1;
		}
		else
		{
			//this.hiderow(formid,dependency.target);
			return 0;
		}
	}
	else if(dependency.type=='value')
	{
		if(elemvalue==dependency.val)
		{
			this.showrow(formid,dependency.target);
			if(dependency.targetval!='-null-')
			{
				formelemtarget.value=dependency.targetval;
			}
			return 1;
		}
		else
		{
			this.hiderow(formid,dependency.target);
			return 0;
		}
	}
	else
	{
		return 0;
	}
	

	
}
punt_forms.prototype.toggleOnCodeField = function(formid, elementid)
{
	
	var formidval = this.lookupid(formid);
	var elemidval = this.lookupelementid(formid,elementid);
	if(this.forms[formidval].elements[elemidval].loadedCoder)
	{
		this.forms[formidval].elements[elemidval].editor.toggle_on();
	}
	else
	{
		this.forms[formidval].elements[elemidval].loadAnyway=true;
	}
}
punt_forms.prototype.toggleOffCodeField = function(formid, elementid)
{
	var formidval = this.lookupid(formid);
	var elemidval = this.lookupelementid(formid,elementid);
	if (typeof this.forms[formidval].elements[elemidval].editor != 'undefined') 
	{
		this.forms[formidval].elements[elemidval].editor.toggle_off();
	}	
}

punt_forms.prototype.rescaleCodeField = function(formid, elementid)
{
	var formidval = this.lookupid(formid);
	var elemidval = this.lookupelementid(formid,elementid);
	if (typeof this.forms[formidval].elements[elemidval].editor != 'undefined') 
	{
		this.forms[formidval].elements[elemidval].editor.rescale();
	}
}
punt_forms.prototype.insertIntoCodeField = function(formid,elementid,tag)
{
	var formidval = this.lookupid(formid);
	var elemidval = this.lookupelementid(formid,elementid);			
	this.forms[formidval].elements[elemidval].editor.insertCode(tag);
}
punt_forms.prototype.initialiseCodeFieldData = function(formid,elementid,mode)
{

	var formidval = this.lookupid(formid);
	var elemidval = this.lookupelementid(formid,elementid);
	if(typeof this.forms[formidval].elements[elemidval]=='undefined')
	{
		return false;
	}
	var mp = mode.split("/");	
	if(mode=='resume')
	{

		mp = this.forms[formidval].elements[elemidval].resumedCoder;
		if(mp[1]=='delayed')
		{
			mp[1]='direct';
		}	
		this.forms[formidval].elements[elemidval].resumedCoder=false;
	}
	
	var status='';
	if(mp.length>1)
	{
		//there is a mode.....
		mode=mp[0];
		status=mp[1];
	}
	if(status=='delayed')
	{
		this.forms[formidval].elements[elemidval].resumedCoder=mp;
		
		return false;
	}
	puntapi._(formid+'_'+elementid).style.display='none';
	this.forms[formidval].elements[elemidval].frm 	= puntapi._(formid+'_'+elementid+'_editor');
	this.forms[formidval].elements[elemidval].value 	= puntapi._(formid+'_'+elementid).value;
	eval("var func = function(){ puntforms.initialiseCodeFieldDataLoaded('"+formid+"','"+elementid+"');}");
	if(this.forms[formidval].elements[elemidval].frm.attachEvent) this.forms[formidval].elements[elemidval].frm.attachEvent('onload',func);
	else this.forms[formidval].elements[elemidval].frm.addEventListener('load',func,false);	
	var ts = (new Date).getTime(); 
	
	//this.forms[formidval].elements[elemidval].frm.src="/extjavascript/codepress/codepress.html?language="+mode+'&ts='+ts;
	this.forms[formidval].elements[elemidval].frm.src="/extjavascript/edit_area/codeloader.html?language="+mode+'&ts='+ts+'&initstatus='+status;
	
}
punt_forms.prototype.initialiseCodeFieldDataLoaded = function(formid, elementid)
{
	
	var formidval = this.lookupid(formid);
	var elemidval = this.lookupelementid(formid,elementid);	
	this.forms[formidval].elements[elemidval].editor = this.forms[formidval].elements[elemidval].frm.contentWindow.editor;
	this.forms[formidval].elements[elemidval].editor.setCode(puntapi._(formid+'_'+elementid).value);

	this.forms[formidval].elements[elemidval].editor.initialise_coder();
	/*
	 * 
	 * codepress
	 
	this.forms[formidval].elements[elemidval].editor = this.forms[formidval].elements[elemidval].frm.contentWindow.CodePress;
	this.forms[formidval].elements[elemidval].editor.setCode(puntapi._(formid+'_'+elementid).value);
	this.forms[formidval].elements[elemidval].editor.syntaxHighlight('init');
	*/
}
punt_forms.prototype.insertCodeIntoCodeField = function(formid, elementid,code)
{
	
	var formidval = this.lookupid(formid);
	var elemidval = this.lookupelementid(formid,elementid);		
	this.forms[formidval].elements[elemidval].editor.insertCode(code);
}
punt_forms.prototype.hasChangedCodeField = function(formid, elementid)
{
	
	var formidval = this.lookupid(formid);
	var elemidval = this.lookupelementid(formid,elementid);		
	if (typeof this.forms[formidval].elements[elemidval].editor == 'undefined') 
	{
		return false;
	}
	if(!this.forms[formidval].elements[elemidval].editor.initialised)
	{
		return false;
	}
	if(this.forms[formidval].elements[elemidval].editor.getCode()!=this.forms[formidval].elements[elemidval].value)
	{
		return true;
	}
	else
	{
		return false;
	}
}
punt_forms.prototype.getCodeFieldData = function(formid, elementid, mode)
{
	
	var formidval = this.lookupid(formid);
	var elemidval = this.lookupelementid(formid,elementid);	
	if (typeof this.forms[formidval].elements[elemidval].editor != 'undefined') 
	{
		if(this.forms[formidval].elements[elemidval].editor.initialised)
		{
			puntapi._(formid + '_' + elementid).value = this.forms[formidval].elements[elemidval].editor.getCode();	
		}		
		
	}
}


/*
 CodePress = function(obj) {
	var self = document.createElement('iframe');
	self.textarea = obj;
	self.textarea.disabled = true;
	self.style.height = self.textarea.clientHeight +'px';
	self.style.width = self.textarea.clientWidth +'px';
	
	self.initialize = function() {
		self.editor = self.contentWindow.CodePress;
		self.editor.body = self.contentWindow.document.getElementsByTagName('body')[0];
		self.editor.setCode(self.textarea.value);
		self.editor.syntaxHighlight('init');
	}
	
	self.edit = function(id,language) {
		self.language = (language) ? language : self.textarea.className.replace(/ ?codepress ?/,'');
		self.src = cpPath+'modules/codepress.html?engine='+self.getEngine()+'&language='+self.language;
		if(self.attachEvent) self.attachEvent('onload',self.initialize);
		else self.addEventListener('load',self.initialize,false);
	}
}
 */
punt_forms.prototype.lookupgroupelementStatus = function(formid,elementid)
{
	//this.
	fid = this.lookupid(formid);
	
	
	for(var gnr=0;gnr<this.forms[fid].groups.length;gnr++)
	{
		for(var felem=0;felem<this.forms[fid].groups[gnr].elements.length;felem++)
		{
			
			if(this.forms[fid].groups[gnr].elements[felem].itemname==elementid)
			{
				return gnr;
			}
		}
	}
	return -1;
		//len =this.forms[fid].groups.length;
		/*this.forms[fid].groups[gnr].elements[len]=[];
		this.forms[fid].groups[gnr].elements[len].formid=formid;
		this.forms[fid].groups[gnr].elements[len].itemname=item;*/
	

}

punt_forms.prototype.redraw = function(formid)
{
	//redraw the rows to show....
	var fid = this.lookupid(formid);
	var target ='';
	var groupid=-1;
	var doshow=false;
	var hasshown=false;
	var grouptarget='';
	//felementid = this.lookupelementid(formid,item);
	for(var felementid=0;felementid<this.forms[fid].elements.length;felementid++)
	{
		target = this.forms[fid].elements[felementid].itemname;
		
		//look it up in a group.
		doshow=false;
		try
		{
			groupid = this.lookupgroupelementStatus(formid,this.forms[fid].elements[felementid].itemname);
			
			
			if(groupid!=-1)
			{
				//its in a group.....
				
				if(this.forms[fid].groups[groupid].opened)
				{
				
					if(this.forms[fid].elements[felementid].shown)
					{
				
						doshow=true;
					}
				}
				
				
			}
			else
			{
				
				if(this.forms[fid].elements[felementid].shown)
				{
				
					doshow=true;
				}
			}
			
			/*
			if(((groupid!=-1)&&(!this.forms[fid].groups[gnr].opened)&&(this.forms[fid].elements[felementid].shown))||((groupid==-1)&&(this.forms[fid].groups[gnr].opened)&&(this.forms[fid].elements[felementid].shown)))
			{
				
				
			}
			else
			{

			}
			*/
			if(!doshow)
			{

				targetid1= "formrowa_"+formid+'_'+target;
				targetid2= "formrowb_"+formid+'_'+target;
				targetid3= "formrowc_"+formid+'_'+target;
				targetid4= ""+formid+'_'+target+'_error';
				
				if((this.forms[fid].elements[felementid].itemtype!='hidden')&&(this.forms[fid].elements[felementid].itemtype!='submit')&&(this.forms[fid].elements[felementid].itemtype!='submitandcancel')&&(this.forms[fid].elements[felementid].itemtype!='signin')&&(this.forms[fid].elements[felementid].itemtype!='submitfreeform'))
				{
					puntapi._(targetid1).style.display='none';
					puntapi._(targetid2).style.display='none';	
					puntapi._(targetid3).style.display='none';	
					
					if(puntapi._(targetid4).innerText!='')
					{
						puntapi._(targetid4).style.display='none';	
					}
				}
			}
			else
			{
				targetid1= "formrowa_"+formid+'_'+target;
				targetid2= "formrowb_"+formid+'_'+target;
				targetid3= "formrowc_"+formid+'_'+target;
				targetid4= ""+formid+'_'+target+'_error';
				if((this.forms[fid].elements[felementid].itemtype!='hidden')&&(this.forms[fid].elements[felementid].itemtype!='submit')&&(this.forms[fid].elements[felementid].itemtype!='submitandcancel')&&(this.forms[fid].elements[felementid].itemtype!='signin')&&(this.forms[fid].elements[felementid].itemtype!='submitfreeform'))
				{
					puntapi._(targetid1).style.display='';
					puntapi._(targetid2).style.display='';	
					puntapi._(targetid3).style.display='';
					
					if(puntapi._(targetid4).innerText!='')
					{
						puntapi._(targetid4).style.display='';	
					}
				}
			}
			//check if groups should be shown or not...
		}
		catch(e)
		{
			this.debugalert('->'+this.forms[fid].elements[felementid].itemtype+'->'+target+'->'+JSON.stringify(e));
		}
	}
	for(var gnr=0;gnr<this.forms[fid].groups.length;gnr++)
	{
		hasshown=false;
		for(var felem=0;felem<this.forms[fid].groups[gnr].elements.length;felem++)
		{
			//look up the elementid
			felementid = this.lookupelementid(formid,this.forms[fid].groups[gnr].elements[felem].itemname);
			///this.//this.forms[fid].groups[gnr].elements[felem].itemname;
			if(felementid>-1)
			{
				if((this.forms[fid].elements[felementid].shown)&&(!hasshown))
				{
					hasshown=true;

					if(this.forms[fid].elements[felementid].itemtype=='image')
					{
						setTimeout("puntforms.rescaleImageField('"+formid+"','"+this.forms[fid].groups[gnr].elements[felem].itemname+"');",100);
					}
				}
			}
		}
		grouptarget ='grouprow_'+formid+'_'+this.forms[fid].groups[gnr].groupname;
		if(!hasshown)
		{
			//hide it 
			puntapi._(grouptarget).style.display='none';
		}
		else
		{
			//show it ..
			if(this.isIE)
			{
				puntapi._(grouptarget).style.display='block';
			}
			else
			{
				puntapi._(grouptarget).style.display='table-row';
			}
		}
	}			
}
punt_forms.prototype.hiderow = function(formid,target)
{
	var id = this.lookupid(formid);
	//var target ='';
	felementid = this.lookupelementid(formid,target);	
	if(felementid>-1)
	{
		this.forms[id].elements[felementid].shown=false;
	}
	
}
punt_forms.prototype.showrow = function(formid,target)
{
	var id = this.lookupid(formid);
	
	var felementid = this.lookupelementid(formid,target);	
	
	if(felementid>-1)
	{
		this.forms[id].elements[felementid].shown=true;	
	}
}

punt_forms.prototype.addcallback = function(formid,item,type,application,command,id,customquery,recievingfield,needsapi,recievingfieldvalue)
{
	id = this.lookupid(formid);
	
	if(id>-1)
	{
		
		lnth = this.forms[id].callbacks.length;
		this.forms[id].callbacks[lnth]={};
		this.forms[id].callbacks[lnth].item=item;
		this.forms[id].callbacks[lnth].tid=lnth;
		this.forms[id].callbacks[lnth].callbacknr=lnth;
		this.forms[id].callbacks[lnth].type=type;
		this.forms[id].callbacks[lnth].application=application;
		this.forms[id].callbacks[lnth].command=command;
		this.forms[id].callbacks[lnth].commandid=id;
		this.forms[id].callbacks[lnth].needsapi=needsapi;
		this.forms[id].callbacks[lnth].totalrequests=0;
		this.forms[id].callbacks[lnth].customquery=customquery;
		this.forms[id].callbacks[lnth].recievingfield=recievingfield;
		if(typeof recievingfieldvalue != 'undefined')
		{
			this.forms[id].callbacks[lnth].recievingfieldvalue=recievingfieldvalue;
		}
		
	}
}
punt_forms.prototype.callbacklookup = function(id,item)
{
	callbacks = [];
	
	for(u=0;u<this.forms[id].callbacks.length;u++)
	{
		if(this.forms[id].callbacks[u].item==item)
		{
			
			callbacks[callbacks.length]=this.forms[id].callbacks[u];
	
		}
	}
	return callbacks;
}



punt_forms.prototype.getcallback = function(formid,id)
{
	return this.forms[formid].callbacks[id];
}

punt_forms.prototype.initfield = function(formid,item,value,checked)
{
	mdunloadUnloadable=false;
	this.checkforcallback(formid,item,value,'true');
	this.dependencycheck(formid,item,value,checked);
	
	this.valuecheck(formid,item,value,checked);
	
	this.writecheck(formid,item,value,checked);
	
}
punt_forms.prototype.attachEvent = function(element,ev,func)
{
	if(window.addEventListener){ // Mozilla, Netscape, Firefox
		element.addEventListener(ev, func, false);
	} else { // IE
		element.attachEvent('on'+ev, func);
	}

}

punt_forms.prototype.colorpicker_save = function()
{
	
	var targetid=this.currentcolorpicker.formid+'_'+this.currentcolorpicker.item;
	var color = puntapi._('form_colorpicker_input').value;

	eval(targetid+'_colorchange(color)');
	puntdialog.close();
}
punt_forms.prototype.isValidColor= function(value)
{
	if(value.length==0)
	{
		return false;
	}
	
 	var regColorcode = /^(#)?([0-9a-fA-F]{3})([0-9a-fA-F]{3})?$/;

    return regColorcode.test(value);
}
punt_forms.prototype.colorpicker_handchange = function()
{
	try {
		
		var value=puntapi._('form_colorpicker_input_text').value;
		if (puntforms.isValidColor(value)) 
		{
		
			jQuery.farbtastic("#form_colorpicker_farb").setColor(value);
		}
	}
	catch(e)
	{
		
	}
}
punt_forms.prototype.colorpicker_change = function(color)
{
	try {
		//puntforms.currentcolorpicker.formid;
		puntapi._('form_colorpicker_input').value = color;
		
		puntapi._('form_colorpicker_input_text').value = color;
		try {
			puntapi._('form_colorpicker').style.backgroundColor = color;
		} 
		catch (e) {
		
		}
	}
	catch (e) {
	
	}
	
}
punt_forms.prototype.colorpicker =function(formid,item,value)
{
	var button1 ="";
	var button2 ="";
	button1+=_tT.parse("button",{onclick:'puntforms.colorpicker_save()',icon:'ok',title:'select'});
	button2+=_tT.parse("button",{onclick:'puntdialog.close()',icon:'cancel',title:'Cancel'});
	
	var html = _tT.parse("colorpicker",{button1:button1,button2:button2});
	var obj = {};

	obj.formid=formid;
	obj.item=item;
	this.currentcolorpicker=obj;
	puntdialog.startSemiDialog(html,'',function(){});
	jQuery.farbtastic("#form_colorpicker_farb").linkTo(puntforms.colorpicker_change)
	jQuery.farbtastic("#form_colorpicker_farb").setColor(value);
	
	this.attachEvent(puntapi._('form_colorpicker_input_text'),'change',function(){setTimeout("puntforms.colorpicker_handchange()",200);});
	this.attachEvent(puntapi._('form_colorpicker_input_text'),'keypress',function(){setTimeout("puntforms.colorpicker_handchange()",200);});
}
punt_forms.prototype.changeDateSourceField  = function(formid,item,value)
{
	var parts = value.split(' ');
	var dateparts = parts[0].split('-');
	var day = dateparts[2];
	var month = dateparts[1];
	var year = parseInt(dateparts[0]);
	puntapi._(formid+'_'+item+'_year').value = year;
	puntapi._(formid+'_'+item+'_month').value = month;
	puntapi._(formid+'_'+item+'_day').value = day;
	
}
punt_forms.prototype.changeDateSelect = function(formid,item,type,valuechanged)
{
	
	var year = puntapi._(formid+'_'+item+'_year').value;
	var month = puntapi._(formid+'_'+item+'_month').value;
	var day = puntapi._(formid+'_'+item+'_day').value;
	puntapi._(formid+'_'+item).value=year+'-'+month+'-'+day; 
	
}
punt_forms.prototype.fillDateSelect = function(formid,item,kind,startyear,endyear)
{
	var month_name = new Array ("January","February","March","April","May","June","July","August","September","October","November","December");
	var includedash=false;
	if((puntapi._(formid+'_'+item).value=='----------')||(puntapi._(formid+'_'+item).value==''))
	{
		includedash=true;
	}
	var dayElem = puntapi._(formid+'_'+item+'_day');
	dayElem.options.length=0;
	var ot='01';

	for(var o=1;o<32;o++)
	{
		if(o<10)
		{
			ot = '0'+o;
		}
		else
		{
			ot = o;
		} 
		dayElem.options[dayElem.options.length]=new Option(o,ot);
	}
	if(includedash)
	{
		dayElem.options[dayElem.options.length]=new Option('--','--');
	}		
	var monthElem = puntapi._(formid+'_'+item+'_month');
	
	monthElem.options.length=0;

	for(var m=0;m<month_name.length;m++)
	{
		if((m+1)<10)
		{
			ot = '0'+(m+1);
		}
		else
		{
			ot = (m+1);
		} 

		monthElem.options[monthElem.options.length]=new Option(month_name[m],ot);
	}
	if(includedash)
	{
		monthElem.options[monthElem.options.length]=new Option('--','--');
	}	
	var yearElem = puntapi._(formid+'_'+item+'_year');
	yearElem.options.length=0;
	var start =parseInt(startyear);
	endyear = parseInt(endyear);

	for(var y=start;y<=endyear;y++)
	{
		yearElem.options[yearElem.options.length]=new Option(y,y);
	}
	if(includedash)
	{
		yearElem.options[yearElem.options.length]=new Option('----','----');
	}	
	if(includedash)
	{
		
		yearElem.value='----';
		monthElem.value='--';
		dayElem.value='--';
		
	}
}
punt_forms.prototype.checkfield = function(formid,item,value,checked,options)
{
	//puntap.preventclose('on');
	
	
	mdunloadUnloadable=false;
	this.updateField(formid,item,value,checked,options);
	this.applyRules(formid);
	
	this.checkforcallback(formid,item,value);
	this.dependencycheck(formid,item,value,checked);
	this.valuecheck(formid,item,value,checked);
	
	this.writecheck(formid,item,value,checked);
	
	this.redraw(formid);
	this.checkForWidgets(formid,item,value,checked);
	this.checkForHooks(formid,item,value,checked);
	
	
}
punt_forms.prototype.updateField = function(formid, item, value, checked,options)
{
	if(typeof options =='undefined')
	{
		var options = {};
	}
	var targetid = formid+'_'+item;
	var fid = this.lookupid(formid);
	var sourceelementid = this.lookupelementid(formid,item);
	var elemtype = this.forms[fid].elements[sourceelementid].itemtype;
	
	
	
	if((elemtype=='image')||(elemtype=='imagewithtext'))
	{
		var nobase=false;
		if(typeof options.nobase!='undefined')
		{
			nobase = options.nobase;
		}
		
		
		if(!nobase)
		{
			var base = puntapi._(targetid+'_ext').value;
			timg.i(targetid).i.updateImage(base+value+'?try='+(new Date()).getTime());

			if(elemtype=='imagewithtext')
			{
				puntapi._(targetid+'_manual').value=base+value;
			}
		}
		else
		{
			timg.i(targetid).i.updateImage(value+'?try='+(new Date()).getTime());
			if(elemtype=='imagewithtext')
			{
				puntapi._(targetid+'_manual').value=value;
			}			
		}
	}
	else if (elemtype=='select')
	{
		var elem = puntapi._(targetid);
		var vals = [];
		for(var o=0;o<elem.options.length;o++)
		{
			if(!elem.options[o].selected)
			{
				continue;
			}
			vals[vals.length] =  elem.options[o].value;
		}		
		this.forms[fid].elements[sourceelementid].currentSelectValue=vals.join(',');
	}
}
punt_forms.prototype.rescaleImageField = function(formid,item,newsrc)
{
	
	var targetid = formid+'_'+item;
	var src= puntapi._(targetid).value;
	
	var srcpart= puntapi._(targetid+'_ext').value;
	var fid = this.lookupid(formid);
	var sourceelementid = this.lookupelementid(formid,item);	
	
	
	
	var fullsrc = srcpart+src;
	var add =false;
	if(fullsrc==srcpart)
	{
		fullsrc = '/Layout/Mijndomein/blank.gif';
	}
	
	if(fullsrc.indexOf('?')==-1)
	{
		fullsrc= fullsrc+'?try='+(new Date()).getTime();
	}
	else
	{
		fullsrc= fullsrc+'&sccd='+(new Date()).getTime();
	}
	if(!this.forms[fid].elements[sourceelementid].initialisedImage)
	{
		add=true;
		//console.log("needs reload because it hasn't been initialised yet...",fullsrc);
	}
	else if(typeof timg.i(targetid)!='undefined')
	{
		
		if(!timg.i(targetid).i.isActive())
		{
			
			add=true;
		}
		else
		{
			
		}
	}
	else
	{
		add=true;
		
	}
	
	
	
	if(add)
	{
		
		var backgroundimg = '/Layout/Mijndomein/images/canvasbg.png';
		var loadingimage = '/Layout/Mijndomein/images/loader_small.gif';
		timg.addImage(targetid+"_image_container",targetid,{type	:'normal',
													 image	:fullsrc,
													 clean:true,
													 backgroundimage:backgroundimg,
													 loadingimage:loadingimage
													 });
													 
		this.forms[fid].elements[sourceelementid].initialisedImage=true;
													 
		
	}
	else
	{
		
		//timg.i(targetid).i.updateImage(fullsrc);
	}
		
												 
													 
}
punt_forms.prototype.rescaleImageFieldOld = function(formid,item)
{
	try
	{
		
	
	var targetid = formid+'_'+item;
	puntapi._(targetid+'_image_container').style.overflow="";
	puntapi._(targetid+'_image_container').style.width="200px";
	var dim = new dimensions();
	var dims = dim.dimensions(puntapi._(targetid+'_image'));
	var dims3 = dim.dimensions(puntapi._('formrowbCellA_'+targetid));
	if (navigator.appVersion.indexOf("MSIE") != -1) 
	{
		 if(dims.w>400)
		 {
		 	 dims.w=400;
			 puntapi._(targetid+'_image_container').style.overflow="auto";
		 }
	}
	else if(navigator.appVersion.indexOf("Chrome"))
	{

		 if(dims.w>400)
		 {
		 	 dims.w=400;
			 puntapi._(targetid+'_image_container').style.overflow="auto";
		 }
	}
	else
	{
		
		if(dims.w>(dims3.w-10))
		{
			dims.w=dims3.w-10;
			puntapi._(targetid+'_image_container').style.overflow="auto";
			
		}

	}
	if(dims.h>200)
	{
		dims.h=200;
		puntapi._(targetid+'_image_container').style.overflow="auto";
	}	
	
	
	puntapi._(targetid+'_image_container').style.height = dims.h+'px';
	puntapi._(targetid+'_image_container').style.width = dims.w+'px';	
	}
	catch(e)
	{
		
	}
}
punt_forms.prototype.attachHookdata = function(formid,hookdata)
{
	
	if(hookdata!='')
	{
		hookdata =JSON2.parse(hookdata);
	}
	var fid = this.lookupid(formid);
	this.forms[fid].hookdata=hookdata;
}

punt_forms.prototype.checkForHooks = function(formid,item,value,checked)
{
	var data = {};
	data.formid= formid;
	data.item = item;
	data.value = value;
	data.checked= checked;
	var fid = this.lookupid(formid);
	var sourceelementid = this.lookupelementid(formid,item);
	var hooks = this.forms[fid].elements[sourceelementid].hooks;

	var hookdata= this.forms[fid].hookdata;
	
	if(this.forms[fid].initializing)
	{
		//eek skip it
		return false;
	}
	if(hooks)
	{
		eval('var formvals = '+formid+'_formvals();');
		for(var ar =0;ar<hooks.length;ar++)
		{
			try
			{
				eval(hooks[ar]+'(data,hookdata,formvals);');
			}
			catch(e)
			{
				
			}	
		}
		
	}
	
		
}
punt_forms.prototype.checkForWidgets = function(formid,item,value,checked)
{
	
	var data = {};
	data.formid= formid;
	data.item = item;
	data.value = value;
	data.checked= checked;
	var fid = this.lookupid(formid);
	var sourceelementid = this.lookupelementid(formid,item);
	var widgets = this.forms[fid].elements[sourceelementid].widgets;
	data.initialValue=this.forms[fid].elements[sourceelementid].initialValue;
	if((typeof widgets =='array')||(typeof widgets =='object'))
	{
		
		
		_tW.notifyWidgets(widgets,data);
	}
	
}
punt_forms.prototype.writecheck = function(formid,item,value)
{
	try
	{
	var writetootherfields = this.writetootherfieldlookup(formid,item);
	
	fid = this.lookupid(formid);
	sourceelementid = this.lookupelementid(formid,item);

	for(u=0;u<writetootherfields.length;u++)
	{
		initialval = this.forms[fid].elements[sourceelementid].initialValue;
	
		target = formid+'_'+writetootherfields[u].target;
		
		

			if(writetootherfields[u].target=='submit')
			{
				//submit it ...
				
				if(initialval!=value)
				{
					this.doformsubmit(formid);
				}
				else
				{
					
				}
				
			}
			else
			{
				puntapi._(target).value=value;
			}
		
	}
	}
	catch(e)
	{
		//do nothing with this for now
		
	}
}
punt_forms.prototype.valuecheck = function(formid,item,value)
{
	var illustrations = this.illustrationslookup(formid,item);

	for(u=0;u<illustrations.length;u++)
	{
		
		
		if(illustrations[u].itemval==value)
		{
			puntapi._(illustrations[u].valimgid).style.display='inline';
		}
		else
		{
			puntapi._(illustrations[u].valimgid).style.display='none';
		}
		
	}
}
punt_forms.prototype.checkforcallback = function(formid,item,value,initial)
{
	
	var targetid=formid+'_'+item;
	
	value = puntapi._(targetid).value;
	if(puntapi._(targetid).type=='checkbox')
	{
		if(!puntapi._(targetid).checked)
		{
			value='';
		}
	}
	
	var id = this.lookupid(formid);
	var sourceelementid = this.lookupelementid(formid,item);
	var elemtype = this.forms[id].elements[sourceelementid].itemtype;
	if(elemtype=='select')
	{
		value = this.forms[id].elements[sourceelementid].currentSelectValue
	}
	
	callbacks = this.callbacklookup(id,item);
	
	for(t=0;t<callbacks.length;t++)
	{
		
		try
		{

		//if((callbacks[t].recievingfield == item)&&(callbacks[t].totalrequests <1))
		/*if(callbacks[t].totalrequests <1)
		{*/
			if(callbacks[t].recievingfield==callbacks[t].item)
			{
				if(typeof initial =='undefined')
				{
					//its not the initial request so don't retrieve it .
					continue;
				}
			}
			tid = callbacks[t].tid;
			this.executecallback(id,callbacks[t],value);
			
			this.forms[id].callbacks[tid].totalrequests=this.forms[id].callbacks[tid].totalrequests+1;
			/*
			
		}*/
		}
		catch(e)
		{
			
		}
		
	}
}
punt_forms.prototype.executecallback = function(formid,callback,value)
{
	
	
	nr++;
	tnr= nr;
	TA[tnr] = new TAjax();
	TA[tnr].cn = 'TA['+nr+']';
	
	
	var needsapi = '/API/';
	if(callback.needsapi=='no')
	{
		needsapi='/';
		if(basepath=='/')
		{
			needsapi='';
		}
	}

	if((callback.application!='')&&(callback.command!='')&&(value!=''))
	{
		TA[tnr].Sourcefile=basepath+needsapi+callback.application+'/'+callback.command+'/'+value;
	}
	else if((callback.application!='')&&(callback.command!=''))
	{
		TA[tnr].Sourcefile=basepath+needsapi+callback.application+'/'+callback.command;
	}
	else
	{
		TA[tnr].Sourcefile=basepath+needsapi+callback.application+'/'+value;
	}
	TA[tnr].Sourcefile +='?'+callback.customquery;
	TA[tnr].onReadyresponsecommand = this.cn+'.recievecallback('+formid+','+callback.callbacknr+',getresponsexml('+tnr+'),getresponse('+tnr+'))';
	
	TA[tnr].doPost();
	
	

}

punt_forms.prototype.recievecallback = function(formid,callbackid,data,data2)
{
	
	var o=0;
	
		
	callback = this.getcallback(formid,callbackid);
	try
	{
		if((callback.type=='options')||(callback.type=='optionsreplace'))
		{
			
			var root = data.getElementsByTagName('options').item(0);
			
	
			
			if(root)
			{
	
				var options = root.getElementsByTagName('option');
				
				
				var targetuy = this.forms[formid].formid+'_'+callback.recievingfield;
				
				
	
				
				
				var fid = this.lookupid(this.forms[formid].formid);
				var felementid = this.lookupelementid(this.forms[formid].formid,callback.recievingfield);
				var initialval = this.forms[fid].elements[felementid].initialValue;

				var targetfirstval =null;
				var value='';
				var description='';
				var newopt=null;
				var targetvalue = null;
				var isMultiSelect=false;
				puntapi._(targetuy).options.length = 0;
				for(o=0;o<options.length;o++)
				{
					value = options[o].getElementsByTagName('value').item(0).firstChild.nodeValue;
					description = options[o].getElementsByTagName('description').item(0).firstChild.nodeValue;
					
					newopt = new Option(description,value);
					
					
					if(targetfirstval==null)
					{
						targetfirstval = value;
					}
					if(options[o].getAttribute('selected')=='yes')
					{
						if(targetvalue!=null)
						{
							//hmmm multiple selections!
							isMultiSelect=true;
						}
						targetvalue = value;
						newopt.selected=true;
						
						
					}
					puntapi._(targetuy).options[o]=newopt;
					if(typeof callback.recievingfieldvalue != "undefined")
					{
						
						valsplit = value.split('$^');
						if(valsplit[0]==callback.recievingfieldvalue)
						{
							targetvalue = value;
						}
						
					}
				}
				//puntapi._(targetuy).value = 
				selectboxval =null;
				
				if((targetvalue !=null)&&(selectboxval==null))
				{
					selectboxval = targetvalue;
				}
				if((typeof initialval !='undefined')&&(selectboxval==null))
				{
					selectboxval = initialval;
				}
						
				
				if((targetfirstval !=null)&&(selectboxval==null))
				{
					selectboxval=targetfirstval;
				}
				
						
				if(selectboxval==null)
				{
					selectboxval='';
				}
				if(!isMultiSelect)
				{
					puntapi._(targetuy).value = selectboxval;
				}	
				
	
			}
		}
		else if(callback.type=='valuereplace')
		{
			var root = data.getElementsByTagName('values').item(0);
			
			var vals = root.getElementsByTagName('value');
			var targetuy = this.forms[formid].formid+'_'+callback.recievingfield;
			
			if(vals.length==1)
			{
				puntapi._(targetuy).value = vals.item(0).firstChild.nodeValue;
			}
			else
			{
				//there is more... so more fields to target...
				var targetfield=callback.recievingfield;
				var val;
				for(var tt=0;tt<vals.length;tt++)
				{
					val = vals.item(tt);
					
					targetfield = val.getAttribute('targetfield');
					
					if(targetfield==null)
					{
						
						targetfield=callback.recievingfield;
					}
					
					
					targetuy=  this.forms[formid].formid+'_'+targetfield;
					
					puntapi._(targetuy).value = val.firstChild.nodeValue;
				}
				
				
			}
			
		}
	
	}
	catch(e)
	{
		//no data!
		
	}
}
punt_forms.prototype._ = function(id)
{
	return puntapi._(id);
}
punt_forms.prototype.ratingSelect = function(formid,item,value,description,maxvalue,type)
{
	var targetid=formid+'_'+item;
	var targetidDesc=formid+'_'+item+'_desc';
	this._(targetid).value=value;
	this._(targetidDesc).value=description;
	this.checkfield(formid,item,value,true);
	
}
punt_forms.prototype.ratingHover = function(formid,item,value,description,maxvalue,type)
{
	
	var targetid=formid+'_'+item;
	clearTimeout(this.ratingredrawtimeouts[targetid]);
	var targetidDesc=formid+'_'+item+'_desc';
	var redrawvalue=1;
	var redrawdescvalue='';
	if(type=='out')
	{
		//recover...
		redrawvalue= parseInt(this._(targetid).value);
		redrawdescvalue= this._(targetidDesc).value;
		var tmpcall = this.cn+".ratingRedraw('"+targetid+"','"+targetidDesc+"',"+redrawvalue+",'"+redrawdescvalue+"',"+maxvalue+")";
		this.ratingredrawtimeouts[targetid] = setTimeout(tmpcall,200);
	}
	else
	{
		redrawvalue=value;
		redrawdescvalue=description
		this.ratingRedraw(targetid,targetidDesc,redrawvalue,redrawdescvalue,maxvalue);
	}
	
	
}
punt_forms.prototype.ratingRedraw = function(targetid,targetidDesc,value,description,maxvalue)
{
	
	this._(targetid+'_description').innerHTML=description;
	var cl='star_empty';
	for(var tel=1;tel<=maxvalue;tel++)
	{
		if(tel<=value)
		{
			cl='star_full';
		}
		else
		{
			cl='star_empty';
		}
		this._(targetid+'_rate_'+tel).className=cl;
		
	}
}
punt_forms.prototype.writeOptionsToId = function(id,data)
{
		target = id;
		puntapi._(target).options.length = 0;
		if(data)
		{
			var root = data.getElementsByTagName('options').item(0);
			
			
			
			if(root)
			{
			options = root.getElementsByTagName('option');
			
			
			
			
			
			for(o=0;o<options.length;o++)
			{
				value = options[o].getElementsByTagName('value').item(0).firstChild.nodeValue;
				description = options[o].getElementsByTagName('description').item(0).firstChild.nodeValue;
				
				puntapi._(target).options[o]=new Option(description,value);
			}
			}
		}

	
}

punt_forms.prototype.gettoken = function(formid)
{
	//gets token and places it so it can be sent with the submit...
}
punt_forms.prototype.registerelement = function(formid,item,type,widgets,hooks)
{
	
	fid = this.lookupid(formid);
	len =this.forms[fid].elements.length;
	this.forms[fid].elements[len] = {};
	this.forms[fid].elements[len].initialisedImage=false;
	this.forms[fid].elements[len].vals = [];
	this.forms[fid].elements[len].itemname = item;
	this.forms[fid].elements[len].itemtype = type;
	if(widgets!='')
	{
		
		widgets = widgets.split(',');
	}
	else
	{
		widgets=false;
	}
	if(hooks!='')
	{
		
		hooks = hooks.split(',');
	}
	else
	{
		hooks=false;
	}	
	
	this.forms[fid].elements[len].widgets = widgets;
	this.forms[fid].elements[len].hooks = hooks;
	this.forms[fid].elements[len].shown = true;

}
punt_forms.prototype.startdatagrid = function(formid,item)
{
			fid = this.lookupid(formid);
			felementid = this.lookupelementid(formid,item);
			datagridconfig = {};
			datagridconfig.output = formid+'_'+item+'_grid';
			datagridconfig.sourcefield = formid+'_'+item;
			this.forms[fid].elements[felementid].datagrid= new datagrid(this.cn+'.forms['+fid+'].elements['+felementid+'].datagrid');
			this.forms[fid].elements[felementid].datagrid.init(datagridconfig);
}
punt_forms.prototype.setdatagriddata = function(formid,item,data)
{
	fid = this.lookupid(formid);
	felementid = this.lookupelementid(formid,item);
	this.forms[fid].elements[felementid].datagrid.setdata(data);
}
punt_forms.prototype.returndatagrid = function(formid,item)
{
	fid = this.lookupid(formid);
	felementid = this.lookupelementid(formid,item);
	this.forms[fid].elements[felementid].datagrid.returndata();
}
/*
punt_forms.prototype.fillElementData = function(formid,item,config)
{
	fid = this.lookupid(formid);
	felementid = this.lookupelementid(formid,item);
	var len=0;
	if(felementid>-1)
	{
		
		this.forms[fid].elements[len].datasource=[];
		for(fuu=3;fuu<arguments.length;fuu++)
		{
			//each argument should be an object
			if(typeof arguments[fuu]=='object')
			{
				//is an object
				len = this.forms[fid].elements[len].datasources.length;
				this.forms[fid].elements[len].datasource[len]=arguments[fuu];
				
			}
		}
	}
	else
	{
		return false;
	}
	
}*/
punt_forms.prototype.setInitialValue = function(formid,item,tval)
{
	try
	{
	fid = this.lookupid(formid);
	felementid = this.lookupelementid(formid,item);
	
	if(this.forms[fid].elements[felementid].itemtype=='select')
	{
		
		this.forms[fid].elements[felementid].initialValue = tval;
		this.forms[fid].elements[felementid].currentSelectValue=tval;
	}
	else
	{
		this.forms[fid].elements[felementid].initialValue = puntapi._(formid+'_'+item).value;
	}
	
	}
	catch(e)
	{
		
	}
}
punt_forms.prototype.registergroupelements = function(formid,group,item)
{
	fid = this.lookupid(formid);
	gnr = this.lookupgroup(fid,group);
	if(gnr!=-1)
	{
		len =this.forms[fid].groups[gnr].elements.length;
		this.forms[fid].groups[gnr].elements[len]=[];
		this.forms[fid].groups[gnr].elements[len].formid=formid;
		this.forms[fid].groups[gnr].elements[len].itemname=item;
	}
	else
	{
		
	}
	
}
punt_forms.prototype.togglegroup = function(formid,group,openclose)
{
	
	togglerid = 'grouprowtoggler_'+formid+'_'+group;
	
	fid = this.lookupid(formid);
	gnr = this.lookupgroup(fid,group);
	if(typeof openclose !='undefined')
	{
		if(openclose=='open')
		{
			this.forms[fid].groups[gnr].opened=false;
		}
		else
		{
			this.forms[fid].groups[gnr].opened=true;
		}
		
	}
	if(!this.forms[fid].groups[gnr].opened)
	{
		this.forms[fid].groups[gnr].opened=true;
		puntapi._(togglerid).className='folderout';
	}
	else
	{
		this.forms[fid].groups[gnr].opened=false;
		puntapi._(togglerid).className='folderin';
	}

		this.redraw(formid);	
	

}


punt_forms.prototype.lookupgroup = function(fid,group)
{
	len = this.forms[fid].groups.length;
	for(u=0;u<len;u++)
	{
		if(this.forms[fid].groups[u].groupname==group)
		{
			return u;
		}
	}
	return -1;
}

punt_forms.prototype.registergroup = function(formid,group,opened)
{
	var fid = this.lookupid(formid);
	var len = this.forms[fid].groups.length;
	this.forms[fid].groups[len]= {};
	this.forms[fid].groups[len].groupname=group;
	this.forms[fid].groups[len].elements= [];
	var togglerid = 'grouprowtoggler_'+formid+'_'+group;
	if(opened=='yes')
	{
		this.forms[fid].groups[len].opened=true;
		puntapi._(togglerid).className='folderout';
	}
	else
	{
		this.forms[fid].groups[len].opened=false;
		puntapi._(togglerid).className='folderin';
	}
	
}


punt_forms.prototype.keypress = function(e,formid,item,type,extrainfo)
{
	var fieldid = formid+'_'+item;
	keynum=0;
	if(window.event) // IE
	{
		keynum = e.keyCode;
  	}
	else //firefox and rest
  	{
  		keynum = e.charCode;
  	}
	if(type=='price')
	{
		//allow if 
		if(((keynum>47)&&(keynum<58))||(keynum==8)||(keynum==0))
		{
			if(extrainfo=='a')
			{
				//allow it
				return true;
			}
			else
			{
				//the other half can only be 2 long after its longer than 2 only allow backspace or an "undefined field"
				if(puntapi._(fieldid+'_b').value.length>1)
				{
					if((keynum==8)||(keynum==0))
					{
						return true;
					}
					else
					{
						return false;
					}
					
				}
				else
				{
					return true;
				}
				
			}
			
		}
		else
		{
			return false;
		}
		
		
	}
	return true;
}
punt_forms.prototype.ajaxcallback = function(formid,item,value)
{
	
}









punt_forms.prototype.bankcheck_kp = function(formid,item)
{
	
	var fid = this.lookupid(formid);
	var felementid = this.lookupid(formid,item);
	var js = this.cn+'.bankcheck("'+formid+'","'+item+'")';
	
	clearTimeout(this.forms[fid].elements[felementid].timeout);
	this.forms[fid].elements[felementid].timeout = setTimeout(js,500);
	
	//this.forms.elements.setTimeout
}

punt_forms.prototype.bankcheck = function(formid,item)
{
	try
	{
		
		msg = this.elfproef(puntapi._(formid+'_'+item).value);
		//if its okay it has one of the following
		var target =formid+'_'+item+'_banktype';
		if((msg=='This bank account number is concidered a Postbank/ING account number.')||(msg=='This is a valid bank account number'))
		{
			//alleen dan doorlaten.
			puntapi._(target).innerHTML=msg;
			puntapi._(target).style.color='green';
		}
		else
		{
			puntapi._(target).innerHTML=msg;
			puntapi._(target).style.color='red';
		}
	}
	catch(error)
	{
		
	}
	
}

punt_forms.prototype.elfproef = function(nr)
{
	var getal = ""

	for (i = 0; i < nr.length; i++) 
	{
		var t = nr.substr(i, 1)
		
		if ((t < "0" || t > "9")&&(t!='.'))
		{
			break;
		}
		else
		{
			getal += t;
		}
	}
	if(nr=='')
	{
		return 'You have not filled in a bank account number';
	}
	if ((getal.length == 0)||(getal!=nr)){
		//alert("rekeningnummer bevat ongeldige tekens");
		return 'This bank account number contains invalid characters';
	}
	getal='';
	for (i = 0; i < nr.length; i++) 
	{
		var t = nr.substr(i, 1)
		if (t != ".")
		{
			if (t < "0" || t > "9")
			{
				break;
			}
			else
			{
				getal += t;
			}
		}
	}
	
	if (getal == 0)
	{
		return 'This bank account number is invalid'
	
	}
	else
	{
		if (getal.length < 3)
		{
			return 'The bankaccount number is too short to be valid';
		}
		if (getal.length == 8)
		{
			return 'The bankaccount number is both too long and too short to be valid';
		}
		if (getal.length <= 7)
		{
			return 'This bank account number is concidered a Postbank/ING account number.';
		}
		if (getal.length > 10){ 
			return 'The bankaccount number contains too many digits'
		}
		var s = 0;
		for (i = 0; i < getal.length; i++){
			s += (getal.length - i) * parseInt(getal.substr(i, 1))
		}
		if(s % 11){
		  return 'This is not a valid bank account number';
		}
		else
		{
		  return 'This is a valid bank account number';
		}
	}
	
}


/* ************************************************************



passwordstrength function Modified by : John Bakker for usage with 
Punt2 interface and improvements upon function. This piece of 
text only applies to the following function!

ORGINAL COPYRIGHT NOTICE/licence for this function:
Created: 20060120
Author:  Steve Moitozo <god at zilla dot us> -- geekwisdom.com
Description: This is a quick and dirty password quality meter 
		 written in JavaScript so that the password does 
		 not pass over the network.
License: MIT License 
*/
punt_forms.prototype.passwordstrength = function(formid,item,vallie)
{
	setTimeout(this.cn+'.passwordstrength_timer(\''+formid+'\',\''+item+'\',\''+vallie+'\')',200);
}
punt_forms.prototype.passwordstrength_timer = function(formid,item,vallie)
{
	
	target =formid+'_'+item;
	target2 =formid+'_'+item+'_pwdstrength';
	vallie = puntapi._(target).value;
	vallie = ''+vallie;
	/*value= puntapi._(target).value;*/

	len = vallie.length;
	score =0;
	var missesnumber=true;
	var missescapital=true;	
	if(len<=0)
	{

	}
	else
	{
	

	
	if(len>6){score =10;}
	if(len>8){score =12;}
	if(len>10){score =14;}
	if(len>16){score =20;}
	
	
	if (vallie.match(/[a-z]/))
	{score = (score+1)}
	
	if (vallie.match(/[A-Z]/))
	{
		score = (score+6);
		missescapital=false;
	}
	/*if (vallie.match(/\d+/))
	{
		score = (score+6)
		missesnumber=false;
	}*/
	if (vallie.match(/([0-9])/))
	{
		score = (score+6);
		missesnumber=false;
	}
	
	if (vallie.match(/(.*[0-9].*[0-9].*[0-9])/))
	{score = (score+6);}
	
	
	
	if (vallie.match(/.[!,@,#,$,%,^,&,*,?,_,~]/))
	{score = (score+6);}
	
	if (vallie.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/))
	{score = (score+6)}

	
	if (vallie.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/))
	{score = (score+6)}
	if (vallie.match(/([a-zA-Z])/) && vallie.match(/([0-9])/))
	{score = (score+6)}
	if (vallie.match(/([a-zA-Z0-9].*[!,@,#,$,%,^,&,*,?,_,~])|([!,@,#,$,%,^,&,*,?,_,~].*[a-zA-Z0-9])/))
	{score = (score+6)}
	
	
	}
	
	var color ='#ed2024';
	if(score < 16)
	{
	   retclass = "veryweak";
	   stars=1;
	   text = 'Very weak';
	   color = '#f1cecf';
	   
	}
	else if (score > 15 && score < 25)
	{
	   retclass = "weak";
	   stars=2;
	   text = 'Weak';
	   color = '#f9e8d0';
	}
	else if (score > 24 && score < 35)
	{
	   retclass = "mediocre";
	   stars=3;
	   text = 'Mediocre';
	   color = '#e8f2d0';
	}
	else if (score > 34 && score < 45)
	{
	   retclass = "strong";
	   stars=4;
	   text = 'Strong';
	   color = '#97ba3d';
	}
	else if (score > 45 && score < 55)
	{
	   retclass = "verystrong";
	   stars=5;
	   text = 'Very strong';
	   color = '#aaec00';
	}	
	else
	{
	   retclass = "overkill";
	   stars=6;
	   text = 'Overkill';
	   color = '#0499cc';
	}
	text ='';
	if(len<8)
	{
		text +=' is too short';
	}
	if(missescapital)
	{
		if(text!='')
		{
			if(!missesnumber)
			{
				text +=' and ';
			}
			else
			{
				text +=', '
			}
		}
		text +='missing a captial letter';
	}
	if(missesnumber)
	{
		if(text!='')
		{
			text +=' and ';
		}
		text +='missing a number';
	}
	if(text=='')
	{
		text +='Your password meets our requirements.';
	}
	else
	{
		text ='Your password: '+text;
	}
		
	
	puntapi._(target2).className="strength strength"+retclass;
	var html='<table cellspacing="0" cellpadding="0"><tr>';
	/*for(var st=0;st<stars;st++)
	{
		html +='<td><div class="ICON3_star" style="width:20px;">&nbsp;</div></td>'
	}*/
	html+='<td>'+text+'</td>';
	html+='</tr></table>';
	//puntapi._(target).style.backgroundColor=color;
	puntapi._(target2).innerHTML=html;
}
 
/*End of modified function*/





/**
 * For file uploads 
 */


function fileQueueError(file, errorCode, message) {
	try {
		var imageName = "error.gif";
		var errorName = "";
		var progress = new FileProgress(file,  this.customSettings.upload_target,this);
		if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
			
			
			alert("global_fileupload_queue_limit_exceeded "+puntforms.currentUploadLimit);
			
		}
		

		var progress = new FileProgress(file,  this.customSettings.upload_target,this);
		switch (errorCode) {
		case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
			progress.setStatus("You can't upload empty files.");
			break;
		case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
			progress.setStatus("The file is too big");
			break;
		case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
			progress.setStatus("global_fileupload_error_unsupported_filetype");
			break;
		
		default:
			break;
		}

		progress.toggleCancel(false, this);

	} catch (ex) {
		
		this.debug(ex);
	}

}

function fileDialogComplete(numFilesSelected, numFilesQueued,numFilesInQueue) {
	try {
		if (numFilesQueued > 0) {
			
			this.startUpload();
			if(this.customSettings.uploadlimit!='0')
			{
				if(numFilesInQueue>=this.customSettings.uploadlimit)
				{
					this.setButtonDisabled(true);
				}
			}
		}
	} catch (ex) {
		alert(ex);
		this.debug(ex);
	}
}
function fileQueue(file) {
	var bytesLoaded=0;
	try {
		var percent = Math.ceil((bytesLoaded / file.size) * 100);

		var progress = new FileProgress(file,  this.customSettings.upload_target,this);
		progress.setProgress(percent);
		if (percent === 100) {
			progress.setStatus("Busy checking");
			progress.toggleCancel(false, this);
		} else {
			progress.setStatus("Waiting for upload.");
			progress.toggleCancel(true, this);
		}
	} catch (ex) {
		this.debug(ex);
	}
}
function uploadProgress(file, bytesLoaded) {

	try {
		var percent = Math.ceil((bytesLoaded / file.size) * 100);

		var progress = new FileProgress(file,  this.customSettings.upload_target,this);
		progress.setProgress(percent);
		if (percent === 100) {
			progress.setStatus("Busy checking");
			progress.toggleCancel(false, this);
		} else {
			progress.setStatus("Uploading");
			progress.toggleCancel(true, this);
		}
	} catch (ex) {
		this.debug(ex);
	}
}

function uploadSuccess(file, serverData) {
	try {
		var progress = new FileProgress(file,  this.customSettings.upload_target,this);

		if (serverData.substring(0, 7) === "FILEID:") {
			

			progress.setStatus("Completed");
			progress.toggleCancel(false);
			progress.hide();
			eval('fr_'+this.customSettings.formidsub+'_'+this.customSettings.formelementid+'_doRecheck();');
		} else {
			
			progress.setStatus("Processing failed");
			progress.toggleCancel(false);
			//alert(serverData);

		}


	} catch (ex) {
		//alert(ex);
		this.debug(ex);
	}
}

function uploadComplete(file) {
	try {
		/*  I want the next upload to continue automatically so I'll call startUpload here */
		if (this.getStats().files_queued > 0) {
			this.startUpload();
		} else {
			var progress = new FileProgress(file,  this.customSettings.upload_target,this);
			progress.setComplete();
			progress.setStatus("All files recieved.");
			progress.toggleCancel(false);
			progress.hide();
			eval('fr_'+this.customSettings.formidsub+'_'+this.customSettings.formelementid+'_doRecheck();');
		}
	} catch (ex) {
		this.debug(ex);
	}
}

function uploadError(file, errorCode, message) {
	var imageName =  "error.gif";
	var progress;
	try {
		switch (errorCode) {
		case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
			try {
				progress = new FileProgress(file,  this.customSettings.upload_target,this);
				progress.setCancelled();
				progress.setStatus("global_fileupload_canceled");
				progress.toggleCancel(false);
				progress.hide();
			}
			catch (ex1) {
				this.debug(ex1);
			}
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
			try {
				progress = new FileProgress(file,  this.customSettings.upload_target,this);
				progress.setCancelled();
				progress.setStatus("global_fileupload_stopped");
				progress.toggleCancel(true,this);
			}
			catch (ex2) {
				this.debug(ex2);
			}
		case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
			progress.setStatus("global_fileupload_limit_reached");
			break;
		default:
			//alert(message);
			break;
		}

		addImage("images/" + imageName);

	} catch (ex3) {
		this.debug(ex3);
	}

}


function setOpacity(element,opacity)
{
		if (element.filters) {
		try {
			element.filters.item("DXImageTransform.Microsoft.Alpha").opacity = opacity;
		} catch (e) {
			// If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
			element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + opacity + ')';
		}
		} else {
			element.style.opacity = opacity / 100;
		}
}
function fadeIn(element, opacity,oncomplete) {
	try 
	{
		var reduceOpacityBy = 5;
		var rate = 30; // 15 fps
		if (typeof oncomplete == 'undefined') 
		{
			oncomplete = '';
		}
		
		if (opacity < 100) 
		{
			opacity += reduceOpacityBy;
			if (opacity > 100) 
			{
				opacity = 100;
			}
			
			if (element.filters) 
			{
				try 
				{
					element.filters.item("DXImageTransform.Microsoft.Alpha").opacity = opacity;
				} 
				catch (e) 
				{
					// If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
					element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + opacity + ')';
				}
			}
			else 
			{
				element.style.opacity = opacity / 100;
			}
		}
		
		if (opacity < 100) 
		{
			eval("setTimeout(function () {fadeIn(element, opacity,'" + oncomplete + "');},rate)");
		}
		else 
		{
			if (oncomplete != '') 
			{
				eval(oncomplete);
			}
		}
	}
	catch(e)
	{
		
	}
}


function fadeOut(element, opacity,oncomplete) {
	try 
	{
		var reduceOpacityBy = 5;
		var rate = 30; // 15 fps
		if (typeof oncomplete == 'undefined') 
		{
			oncomplete = '';
		}
		
		if (opacity > 0) 
		{
			opacity -= reduceOpacityBy;
			if (opacity < 0) 
			{
				opacity = 0;
			}
			
			if (element.filters) 
			{
				try 
				{
					element.filters.item("DXImageTransform.Microsoft.Alpha").opacity = opacity;
				} 
				catch (e) 
				{
					// If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
					element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + opacity + ')';
				}
			}
			else 
			{
				element.style.opacity = opacity / 100;
			}
		}
		
		if (opacity > 0) 
		{
			eval("setTimeout(function () {fadeOut(element, opacity,'" + oncomplete + "');},rate)");
		}
		else 
		{
			if (oncomplete != '') 
			{
				eval(oncomplete);
			}
			
			element.style.display = 'none';
		}
	}
	catch(e)
	{
		//error,forget it 	
	}
}


/* ******************************************
 *	FileProgress Object
 *	Control object for displaying file info
 * ****************************************** */
function FileProgress(file,targetID,swfinstance)
{
	try {
		this.targetID = targetID;
		this.container = this._(this.targetID);
		this.wrapper = this._(this.targetID + '_wrapper');
		this.file=file;
		if (!this.wrapper) {
			//make the wrapper
			this._c(this.container, 'div', this.targetID + '_wrapper');
			this.wrapper = this._(this.targetID + '_wrapper');
		}
		else 
		{
			//all is fine..
		}

		if(!file)
		{
			//ignore it ...
			
		}
		else
		{
			this.fileid = this.targetID+'_'+file.id;
			this.fileuplid =file.id;
			
			this.filecontainer = this._(this.fileid);
			this.cancelelement  = this._(this.fileid+'_cancel');
			if (!this.filecontainer) {
				this._c(this.wrapper,'div',this.fileid);
				this.filecontainer = this._(this.fileid);
				this.filecontainer.innerHTML='<div id="'+this.fileid+'_progressfile"><table width="100%"><tr><td>'+file.name+'<span id="'+this.fileid+'_status"></span></td><td width="82" align="left"><span id="'+this.fileid+'_cancel" class="clickable"><img class="ICON3_cancel" src="/Layout/Puntbasic/blank.gif"/></span></td></tr></table></div><div id="'+this.fileid+'_progressbar"  class="progressBarInProgress"></div>';
				this.cancelelement  = this._(this.fileid+'_cancel');
				this.toggleCancel(false,swfinstance)
			}
			else 
			{
				//all is fine
			}
			
		}
		
		
		
		
	}
	catch(e)
	{
		//alert(e);
	}
	
}
FileProgress.prototype._ = function(elemid)
{
	return document.getElementById(elemid);
}
FileProgress.prototype._c = function(parent,type,elemid)
{
	var tmpelem = document.createElement(type);
	tmpelem.setAttribute('id',elemid);
	parent.appendChild(tmpelem);
}
FileProgress.prototype.hide = function()
{
	
	try {
		fadeOut(this.filecontainer, 100);
	}
	catch(e)
	{
	//	alert(e);
	}
}
FileProgress.prototype.calculateColor = function(percentage)
{
	var color = 'ff0000';
	if(percentage==0)
	{
		color = 'ff0000';
	}
	else if(percentage==100)
	{
		color = '00ff00';
	}
	else
	{
		//d.toString(16);
		color ='';
		var red = 255-Math.floor((255/100)*percentage);
		var redstring =red.toString(16);
		var green = Math.floor((255/100)*percentage);
		var greenstring =green.toString(16);
		if(redstring.length==1)
		{
			redstring = '0'+redstring;
		} 
		if(greenstring.length==1)
		{
			greenstring = '0'+greenstring;
		}
		color += redstring+greenstring+'00';
	}
	return color;
}
FileProgress.prototype.setProgress = function(percentage)
{
	var color = this.calculateColor(percentage);
	document.getElementById(this.fileid+'_progressbar').style.backgroundColor='#'+color
	document.getElementById(this.fileid+'_progressbar').style.width=percentage+'%';
}
FileProgress.prototype.setComplete = function()
{
}
FileProgress.prototype.setError = function()
{
}
FileProgress.prototype.setCancelled = function()
{
}
FileProgress.prototype.setStatus = function(status)
{
	
	document.getElementById(this.fileid+'_status').innerHTML='&nbsp;-&nbsp;'+status;
}
FileProgress.prototype.toggleCancel = function (show, swfuploadInstance) {
	this.cancelelement.style.visibility = show ? "visible" : "hidden";
	if (swfuploadInstance) {
		
		eval("this.cancelelement.onclick = function () {swfuploadInstance.cancelUpload('"+this.fileuplid+"'); return false;};");
	}
};


/**
 * end of file upload function
 */



var puntforms = new punt_forms('puntforms');


//[PACKSEP]

//date-time picker uit EPL v2
//(c)2003-2007 JWB
//graag vervangen door een stabielere datam tijd picker
function getWeekNr(Y,M,D)
{
	var today = new Date(Y,M,D);
	Year = takeYear(today);
	Month = today.getMonth();
	Day = today.getDate();
	now = Date.UTC(Year,Month,Day+1,0,0,0);
	var Firstday = new Date();
	Firstday.setYear(Year);
	Firstday.setMonth(0);
	Firstday.setDate(1);
	then = Date.UTC(Year,0,1,0,0,0);
	var Compensation = Firstday.getDay();
	if (Compensation > 3) Compensation -= 4;
	else Compensation += 3;
	NumberOfWeek =  Math.round((((now-then)/86400000)+Compensation)/7);
	return NumberOfWeek;
}
function takeYear(theDate)
{
	x = theDate.getYear();
	var y = x % 100;
	y += (y < 38) ? 2000 : 1900;
	return y;
}

function getDaysInMonth(month,year)
{
var days =0;
if (month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12)  days=31;
else if (month==4 || month==6 || month==9 || month==11) days=30;
else if (month==2)  {
if (isLeapYear(year)) { days=29; }
else { days=28; }
}
return days;
}
function isLeapYear (Year) {
if (((Year % 4)==0) && ((Year % 100)!=0) || ((Year % 400)==0)) {
return true;
} else { return false; }
}


function Dayofw(Y,M,D)
{
var c = new Date(Y,M,D);
return c.getDay();
}
function Agenda(cn,Target,Div)
{
	try {
		this.cn = cn;
		var Datevalue = '';
		
		Datevalue = document.getElementById(Target).value;
		this.target = Target;
		this.agendadiv = Div
		var datevalsplit = Datevalue.split(' ');
		var dateval = datevalsplit[0];
		var timeval = datevalsplit[1];
		var dateval2 = dateval.split('-');
		this.year = dateval2[0];
		
		if(dateval2[1].charAt(0)=='0')
		{
			this.month = parseInt(dateval2[1].charAt(1));
		}
		else
		{
			this.month = parseInt(dateval2[1]);
		}
		if (dateval2[2].charAt(0) == '0') {
			this.day = parseInt(dateval2[2].charAt(1));
		}
		else 
		{
			this.day = parseInt(dateval2[2]);
		}
		
		var timeval2 = timeval.split(':');
		if(timeval2[0].charAt(0)=='0')
		{
			this.hour = parseInt(timeval2[0].charAt(1));
		}
		else
		{
			this.hour = parseInt(timeval2[0]);
		}

		if(timeval2[1].charAt(0)=='0')
		{
			this.minute = parseInt(timeval2[1].charAt(1));
		}
		else
		{
			this.minute = parseInt(timeval2[1]);
		}
		
	}
	catch(e)
	{
		alert(e);
	}
	
	
}

Agenda.prototype.show = function()
{
	
	this.Createagenda(this.agendadiv,this.year,this.month,this.day,this.hour,this.minute);
}
Agenda.prototype.setTarget = function(Year,Month,Selectedday,Hour,Minute)
{
	Year = parseInt(Year);
	Month = parseInt(Month);
	Selectedday = parseInt(Selectedday);
	Hour = parseInt(Hour);
	Minute = parseInt(Minute);
	if(Month<10)
	{
		Month='0'+Month;
	}
	if(Selectedday<10)
	{
		Selectedday='0'+Selectedday;
	}
	if(Hour<10)
	{
		Hour='0'+Hour;
	}
	if(Minute<10)
	{
		Minute='0'+Minute;
	}
	document.getElementById(this.target).value=Year+"-"+Month+'-'+Selectedday+' '+Hour+':'+Minute;
	if(typeof document.getElementById(this.target).onchange!='indefined')
	{
		try
		{
			document.getElementById(this.target).onchange();
		}
		catch(e)
		{
			alert(JSON.stringify(e));
		}
	}
	
}
Agenda.prototype.Createagenda = function(Agenda,Year,Month,Selectedday,Hour,Minute)
{

this.setTarget(Year,Month,Selectedday,Hour,Minute);
Year = parseInt(Year);
Agendaspan= document.getElementById(this.agendadiv);

try
{
var month_name = new Array ("January","February","March","April","May","June","July","August","September","October","November","December");


var NextYear = parseInt(Year) +1;
var NextMonth = parseInt(Month) +1;
var PrevYear = parseInt(Year) -1;
var PrevMonth = parseInt(Month) -1;


if(Month ==12)
{
var Nextmonthscript= this.cn+'.Createagenda(\''+Agenda+'\','+(Year+1)+','+1+','+Selectedday+',document.getElementById(\''+Agenda+'_hour\').value,document.getElementById(\''+Agenda+'_minute\').value)';
}
else
{
var Nextmonthscript= this.cn+'.Createagenda(\''+Agenda+'\','+Year+','+NextMonth+','+Selectedday+',document.getElementById(\''+Agenda+'_hour\').value,document.getElementById(\''+Agenda+'_minute\').value)';
}

if(Month ==1)
{
var Prevmonthscript= this.cn+'.Createagenda(\''+Agenda+'\','+(Year-1)+','+12+','+Selectedday+',document.getElementById(\''+Agenda+'_hour\').value,document.getElementById(\''+Agenda+'_minute\').value)';
}
else
{
var Prevmonthscript= this.cn+'.Createagenda(\''+Agenda+'\','+Year+','+PrevMonth+','+Selectedday+',document.getElementById(\''+Agenda+'_hour\').value,document.getElementById(\''+Agenda+'_minute\').value)';
}

var Nextyearscript= this.cn+'.Createagenda(\''+Agenda+'\','+NextYear+','+Month+','+Selectedday+',document.getElementById(\''+Agenda+'_hour\').value,document.getElementById(\''+Agenda+'_minute\').value)';
var Prevyearscript= this.cn+'.Createagenda(\''+Agenda+'\','+PrevYear+','+Month+','+Selectedday+',document.getElementById(\''+Agenda+'_hour\').value,document.getElementById(\''+Agenda+'_minute\').value)';


innerHTML ='';
innerHTML +='<table class="Agenda_Table" cellspacing=0 cellpadding=0>';
innerHTML +='<tr><Td Class="Agenda_Tablecel_MONTHNAME" colspan=8><a onclick="'+Prevyearscript+'" class="Agenda_Prevyear">&lt;&lt;&lt;</a>&nbsp;&nbsp;<a onclick="'+Prevmonthscript+'" class="Agenda_Prevmonth">&lt;&lt;</a>&nbsp;&nbsp;'+month_name[Month-1]+' '+Year+'&nbsp;&nbsp;<a onclick="'+Nextmonthscript+'" class="Agenda_Nextmonth">&gt;&gt;</a>&nbsp;&nbsp;<a onclick="'+Nextyearscript+'" class="Agenda_Nextyear">&gt;&gt;&gt;</a></td></tr>';

innerHTML +='<Tr><td class="Agenda_Tablecel_Topwk">Week</td><Td class="Agenda_Tablecel_Top">Su</td><Td class="Agenda_Tablecel_Top">Mo</td><Td class="Agenda_Tablecel_Top">Tue</td><Td class="Agenda_Tablecel_Top">We</td><Td class="Agenda_Tablecel_Top">Thu</td><Td class="Agenda_Tablecel_Top">Fri</td><Td class="Agenda_Tablecel_TopS">Sa</td></tr>';
Week=0;
Sweek=getWeekNr(Year,Month-1,1);
Firstday=Dayofw(Year,Month-1,1);
D=1;
var Daysinmonth = getDaysInMonth(Month,Year);

while(Week < 5 )
{

     innerHTML +='<Tr><td class="Agenda_TablecelWeek">'+(Week+Sweek)+'</td>';
     if(Week==0)
     {
     fd=0;
     while(fd<Firstday)
     {
          innerHTML +='<td class="Agenda_TablecelEmpty'+fd+'">&nbsp;</td>';
          fd++;
     }
     while(fd<7 && D<32 )
     {
if(!(Selectedday==D))
{
          innerHTML +='<td class="Agenda_TablecelDay'+fd+'" onmouseover="this.className=\'Agenda_TablecelDayselected'+fd+'\'" onmouseout="this.className=\'Agenda_TablecelDay'+fd+'\'"  onclick="'+this.cn+'.Createagenda(\''+Agenda+'\','+Year+','+Month+','+D+',document.getElementById(\''+Agenda+'_hour\').value,document.getElementById(\''+Agenda+'_minute\').value)"><a onclick="'+this.cn+'.Createagenda(\''+Agenda+'\','+Year+','+Month+','+D+',document.getElementById(\''+Agenda+'_hour\').value,document.getElementById(\''+Agenda+'_minute\').value)" class="Agenda_Daylink">'+D+'</a></td>';
}
else
{
          innerHTML +='<td class="Agenda_TablecelDayselected'+fd+'">'+D+'</td>';
}


          D++;
          fd++;

     }
     }
     else
     {
     fd=0;
     while(fd<7 && D<Daysinmonth+1 )
     {
if(!(Selectedday==D))
{
          innerHTML +='<td class="Agenda_TablecelDay'+fd+'" onmouseover="this.className=\'Agenda_TablecelDayselected'+fd+'\'" onmouseout="this.className=\'Agenda_TablecelDay'+fd+'\'"  onclick="'+this.cn+'.Createagenda(\''+Agenda+'\','+Year+','+Month+','+D+',document.getElementById(\''+Agenda+'_hour\').value,document.getElementById(\''+Agenda+'_minute\').value)"><a onclick="'+this.cn+'.Createagenda(\''+Agenda+'\','+Year+','+Month+','+D+',document.getElementById(\''+Agenda+'_hour\').value,document.getElementById(\''+Agenda+'_minute\').value)" class="Agenda_Daylink">'+D+'</a></td>';
}
else
{
          innerHTML +='<td class="Agenda_TablecelDayselected'+fd+'" >'+D+'</td>';
}
          D++;
          fd++;

     }
     while(fd<7)
     {
          innerHTML +='<td class="Agenda_TablecelEmpty'+fd+'">&nbsp;</td>';
          fd++;

     }

     }
     innerHTML +='</tr>';
     Week++
}

var Hour2 =0;
var Hours ='';
while(Hour2 <24)
{
  Hour2descr=Hour2;
	if(Hour2descr<10)
	{
		//Hour2descr='0'+Hour2descr;
	}  
  if(Hour2 == Hour)
  {
  Hours +='<option value="'+Hour2+'" class="Agenda_Timeoption" selected>'+Hour2descr+'</option>';
  }
  else
  {
  Hours +='<option value="'+Hour2+'" class="Agenda_Timeoption">'+Hour2descr+'</option>';
  }

  Hour2++;
}
var Minute2 =0;
var Minutes ='';
while(Minute2 <60)
{

  	Minute2descr = Minute2;
	if(Minute2descr<10)
	{
		Minute2descr='0'+Minute2descr;
	}
  
  if(Minute2 == Minute)
  {
  Minutes +='<option value="'+Minute2+'" class="Agenda_Timeoption" selected>'+Minute2descr+'</option>';
  }
  else
  {
  Minutes +='<option value="'+Minute2+'" class="Agenda_Timeoption">'+Minute2descr+'</option>';
  }
  Minute2++;
}
//document.getElementById(\''+this.target+'\').value = \''+Year+'-'+Month+'-'+Selectedday+' \'+document.getElementById(\''+Agenda+'_hour\').value+\':\'+document.getElementById(\''+Agenda+'_minute\').value
var settargetscript =this.cn+'.setTarget('+Year+','+Month+','+Selectedday+',document.getElementById(\''+Agenda+'_hour\').value,document.getElementById(\''+Agenda+'_minute\').value)';
innerHTML +='<tr><td colspan=8 class="Agenda_Timebar"><select id="'+Agenda+'_hour"  class="Agenda_Timeselect" onchange="'+settargetscript+'">'+Hours+'</select>:<select id="'+Agenda+'_minute"  class="Agenda_Timeselect"  onchange="'+settargetscript+'">'+Minutes+'</select></td></tr>';

innerHTML +='</table>';
Agendaspan.innerHTML = innerHTML;
}
catch(e)
{
	alert('EXCEPTION!'+JSON.stringify(e));
}
}




//[PACKSEP]



/**
 * @author: John Bakker
 * @contact: me@johnbakker.name
 */

function tSelectBoxDefaultConfig()
{
	this.height=100;
	this.heightlimit=6;
	this.scrollerwidth=15;
	this.spacingY=1;
	this.spacingX=0;
	this.baseClass='selectbox';
	this.debug=false;
	this.blankimagestring='<img width="1" height="1" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw%3D%3D/>';
}

function tSelectBox(id,config)
{
	
	ua = navigator.userAgent,
	this.isOpera = window.opera && opera.buildNumber;
	this.isWebKit = /WebKit/.test(ua);
	this.isOldWebKit = this.isWebKit && !window.getSelection().getRangeAt;
	this.isIE = !this.isWebKit && !this.isOpera && (/MSIE/gi).test(ua) && (/Explorer/gi).test(navigator.appName);
	this.isIE6 = this.isIE && /MSIE [56]/.test(ua);
	this.isGecko = !this.isWebKit && /Gecko/.test(ua);
	this.isMac = ua.indexOf('Mac') != -1;
	this.isSaf = ua.indexOf('Safari') != -1;
	this.id=id;
	this.originalElement=this._(id);
	this.newContainerId= id+'_newcontainer';
	this.overlayContainerId= id+'_overlay';
	this.parentElement = this.__(this.id);
	this.opened	= false;
	var defaultconfig = new tSelectBoxDefaultConfig;
	this.values=[];

	if(typeof config == 'undefined')
	{
		this.config = {};
	}
	else
	{
		this.config = config;		
	}
	for(var i in defaultconfig)
	{
		if (typeof this.config[i] == 'undefined') 
		{
			this.config[i] = defaultconfig[i];
		}
	}
	this.init();

}
tSelectBox.prototype.cleanUp = function ()
{
	try
	{
		this.body.removeChild(this.overlay);
		this.parentElement.removeChild(this.container);
		this.originalElement.style.display='block';
		//this.log('cleaned up');
	}
	catch(e)
	{
		
	}
}
tSelectBox.prototype.versionIE = function ()
{
	var data = -1
	if(navigator.appName=='Microsoft Internet Explorer')
	{
		data = parseFloat((new RegExp("MSIE ([0-9]{1,}[.0-9]{0,})")).exec(navigator.userAgent)[1]);
	}
	return data;
}
tSelectBox.prototype.init = function ()
{
	try {
		
		
		var isIE = false;
		if (navigator.appName == "Microsoft Internet Explorer") {
			isIE = true;
		}		
		var verie = this.versionIE();
		
		if ((verie >= 6) && (verie < 7)) {
			return false;
		}
		if (puntapi._(this.id + '_valuecontainer')) {
			//eek it already exists!
			return false;
		}
		//return false;
		var o = {};
		var option = {};
		//read out the values...
		for (var u = 0; u < this.originalElement.options.length; u++) {
			o = this.originalElement.options[u];
			option = {};
			option.value = o.value;
			option.text = o.text;
			if (o.value == this.originalElement.value) {
				option.selected = true;
				this.currentValue = o.value;
				this.currentText = o.text;
				this.currentValueId = u;
				this.cursorPos = u;
			}
			this.values[this.values.length] = option;
		}
		
		
		
		var dimensions = this.getDimensions(this.originalElement);
		//this.log(dimensions.w);
		//this.log(dimensions.h);
		this.originalDimensions = dimensions;
		
		this.container = document.createElement('div');
		//this.valueContainer = document.createElement('div');
		//this.valueContainer.innerHTML=this.currentText;
		
		
		this.valueContainerWrapper = document.createElement('div');
		this.valueContainerDummy = document.createElement('div');
		this.valueContainer = document.createElement('input');
		this.valueContainer.setAttribute('type', 'text');
		this.valueContainer.setAttribute('style', 'color:white;width:1px;height:10px;border:0px');
		
		this.valueContainer.setAttribute('id', this.id + '_valuecontainer');
		this.valueContainerDummy.setAttribute('id', this.id + '_valuecontainerDummy');
		this.valueContainerWrapper.innerHTML = "<table cellspacing='0' cellpadding='0'><tr><td id='" + this.id + "_inputcontainer'></td><td id='" + this.id + "_selectorcontainer'></td></tr></table>";
		//alert("<table cellspacing='0' cellpadding='0'><tr><td id='" + this.id + "_inputcontainer'></td><td id='" + this.id + "_selectorcontainer'></td></tr></table>");
		this.container.appendChild(this.valueContainerWrapper);
		
		
		
		//this.valueContainer.style.display='block';
		
		/*this.valueContainer.style.cursor='pointer';
	 this.valueContainer.style.border='0px';*/
		this.container.id = this.newContainerId;
		//this.container.style.width=(this.originalDimensions.w+20)+'px';
		this.parentElement.insertBefore(this.container, this.originalElement);


		puntapi._(this.id + "_inputcontainer").appendChild(this.valueContainer);
		puntapi._(this.id + "_selectorcontainer").appendChild(this.valueContainerDummy);
		
		/*this.valueContainerWrapper.appendChild(this.valueContainer);
	 this.valueContainerWrapper.appendChild(this.valueContainerDummy);*/
		this.valueContainerDummy.innerHTML = this.currentText;
		
		
		
		this.valueContainer.value = this.currentText;
		if (navigator.appName != "Microsoft Internet Explorer") {
			this.valueContainer.readOnly = true;
		}
		//this.valueContainer.className = this.config.baseClass + '_valuecontainer';
		this.valueContainer.style.color="#ffffff";
		this.valueContainer.style.width="1px";
		this.valueContainer.style.height="10px";
		
		//this.valueContainer.style.height="1px";
		this.valueContainer.style.border="0px";
		this.valueContainerDummy.className = this.config.baseClass + '_valuecontainer';
		this.valueContainerWrapper.className = this.config.baseClass + '_valuecontainer_wrapper';





		
		var dimensions2 = this.getDimensions(this.container);
		/*
	 this.valueContainer.style.width=(dimensions2.w-4)+'px';
	 this.valueContainerWrapper.style.width=(dimensions2.w-6)+'px';
	 this.valueContainer.style.height=(dimensions2.h-6)+'px';
	 this.valueContainerWrapper.style.height=(dimensions2.h-4)+'px';	*/
		this.container.style.display = 'none';
		this.container.className = this.config.baseClass;
		
		//	this.container.style.overflow='hidden';
		
		//	this.container.style.overflowX='hidden';
		
		
		this.container.style.display = 'none';
		//this.originalElement.style.display='none';	
		//this.log('Replaced selectbox with the new container');
		this.body = document.getElementsByTagName('body').item(0);
		
		this.overlay = document.createElement('div');
		this.overlay.id = this.id + '_overlay_container';
		
		this.body.appendChild(this.overlay);
		this.overlay.style.display = 'none';
		this.overlay.className = this.config.baseClass + '_overlay';
		//this.log('Created overlay');
		var tmpelem = '';
		var tmpfunc = '';
		var islimited = false;
		if (this.values.length > this.config.heightlimit) {
			islimited = true;
			this.overlay.style.height = this.config.height + 'px';
			this.overlay.style.overflow = 'auto';
		}
		var append = ' first';

	
		var tmpout='';
		var clname="";
		var outwidth="";
		if (!isIE) {
			outwidth = 'width:100%';
		}
		else {
			if (islimited) {
			//	outwidth = 'width:'+((dimensions2.w-1) - this.config.scrollerwidth) + 'px'
			}
			else {
				outwidth = 'width:49%';
			}
			
		}		
		for (var u = 0; u < this.values.length; u++) {
			
			
			tmpout +="<div id='"+this.id + '_item_' + u+"'";

			if (u > 0) {
				append = '';
			}
			if (this.values[u].selected) {
				clname = this.config.baseClass + '_item_selected' + append;
			}
			else {
				clname = this.config.baseClass + '_item' + append;
			}

			tmpout +="class='"+clname+"' style='"+outwidth+"'";
			tmpout+=">"+this.values[u].text+"</div>";
		}
		this.overlay.innerHTML=tmpout;
		eval('tmpfunc = function(event){_tselect.passThroughEvent(\'' + this.id + '\',event);}');
		for (u = 0; u < this.values.length; u++) 
		{
			tmpelem = puntapi._(this.id + '_item_' + u);
			
			this._a(tmpelem, 'onclick', tmpfunc);
			this._a(tmpelem, 'onmouseover', tmpfunc);
			this._a(tmpelem, 'onmouseout', tmpfunc);
		}

		this.attachEvents();
		//	return false;
		//all is well now hide everything
		this.originalElement.style.display = 'none';
		this.container.style.display = 'block';

	}
	catch(e)
	{
		//alert(e);
	}
}
tSelectBox.prototype.log = function(text)
{

	if (this.config.debug) 
	{
		if (navigator.appName != "Microsoft Internet Explorer") 
		{
			if (typeof console != 'undefined') {
				if (typeof console.log == 'function') {
					console.log(text);
					return true;
				}
				
			}
		}
		if(!this._(this.id+'debugout'))
		{
			var body = document.getElementsByTagName('body').item(0);
			var debugout = document.createElement('textarea');
			debugout.id=this.id+'debugout';
			debugout.style.width='400px';
			debugout.style.height='200px';
			debugout.style.zIndex=255;
			body.appendChild(debugout);
		}
		else
		{
			var debugout = this._(this.id+'debugout');
			
		}
		debugout.value +=text+'\n';
	
	}
}
tSelectBox.prototype.redraw = function()
{
	var tmpid='';
	for(var o =0 ; o< this.values.length;o++)
	{
		tmpid = this.id+'_item_'+o;

		if(this.values[o].selected)
		{
			if(this._(tmpid).className!=this.config.baseClass+'_item_selected')
			{
				this._(tmpid).className=this.config.baseClass+'_item_selected';
			}
		}
		else
		{
			if(this._(tmpid).className!=this.config.baseClass+'_item')
			{
				this._(tmpid).className=this.config.baseClass+'_item';
			}

		}
	}
	//this.valueContainer.innerHTML=this.currentText;
	//this.valueContainer.value=this.currentText;
	this.valueContainerDummy.innerHTML=this.currentText;
}
tSelectBox.prototype.scrolltop = function()
{
	var ScrollTop = document.body.scrollTop;
	if (ScrollTop == 0)
	{
	
	    if (window.pageYOffset)
	
	        ScrollTop = window.pageYOffset;
	
	    else
	
	        ScrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
	
	}

	return ScrollTop;
}
tSelectBox.prototype.reposition = function()
{
	this.overlay.style.display='block';
	this.overlay.style.position='absolute';
	var dim = this.getDimensions(this.container);
	var dim2 = this.getDimensions(this.overlay);
	
	var isChrome = function() {return Boolean(window.chrome);}


	var compensation = -2;
	
	if ((navigator.appName != "Microsoft Internet Explorer")&&(!isChrome())&&(!this.isWebKit))
	{
		//its not IE so borders are being counted.. remove the border sides
		compensation=-2;
		compensationy=-1;
		compensationy2=0;
	}
	else
	{
		compensation=0;
		compensationy=0;		
		compensationy2=0;		
	}

	
	
	var tmpsize = _vp.getPageSizeWithScroll();
	var vp = _vp.getviewportsize();
	
	
	var scrollheight = this.scrolltop();
	
	
	
	var openup=false;
	var endpos = dim.y+this.config.height+30;
	
	this.log("vp.viewportheight"+vp.height);
	this.log("scrollheight"+scrollheight);
	this.log("endpos"+endpos);
	
	if(scrollheight>0)
	{
		//its scrolled down....
		if(endpos>vp.height+scrollheight)
		{
			openup=true;
		}
	}
	else if(endpos>vp.height)
	{
		openup=true;
	}
	else if(endpos>vp.docheight)
	{
		openup=true;
		
	}

	
	//if((dim.y>(Math.floor(this.body.scrollHeight/2)))&&(dim.y+this.config.height<tmpsize[1]))
	
	if(openup)
	{
		//make it fold open up...
		//spacingy=;
		//this.log(this.container.style.border);
		var toppos = 0;
		if(this.overlay.scrollHeight>this.config.height)
		{
			toppos = (dim.y-(this.config.height+compensationy))+'px';
			////this.log('big'+toppos);
		}
		else
		{
			toppos = (dim.y-(dim2.h+this.config.spacingY))+'px';
			////this.log('small'+toppos);
		}
		//this.log('new toppos'+toppos+'->'+dim.y+'::'+dim2.h);
		this.overlay.style.position='absolute';
		this.overlay.style.top=toppos;
		this.overlay.style.left=dim.x+'px';
		this.overlay.style.width=(dim.w+compensation)+'px';
		this.overlay.className=this.config.baseClass+'_overlay foldup';
		dim2 = this.getDimensions(this.overlay);
		//this.log('?'+dim2.y);
	}
	else
	{
		//make it fold down
		this.overlay.style.top=(dim.y+(dim.h+compensationy))+'px';
		this.overlay.style.left=dim.x+'px';
		this.overlay.style.width=(dim.w+compensation)+'px';
		this.overlay.className=this.config.baseClass+'_overlay folddown';
	}

	//reposition the elements..
}
tSelectBox.prototype.moveTo=function(id)
{
	//this.log('repositioning the page from:'+this.overlay.scrollTop);
	if (this.values.length >= 1) 
	{
		var itemheight = this.overlay.scrollHeight / this.values.length;
		this.overlay.scrollTop = Math.floor(itemheight * id);
	}
	else
	{
		this.overlay.scrollTop = 0;
	}
	//this.log('repositioned the page to:'+this.overlay.scrollTop);
}
tSelectBox.prototype.open = function()
{
	this.reposition();
	//this.log(this.id+'::open');
	this.overlay.style.display='block';
	this.opened=true;
	this.moveTo(this.currentValueId);


}
tSelectBox.prototype.close = function()
{
	//this.reposition();
	//this.log(this.id+'::close');
	this.overlay.style.display='none';
	this.opened=false;

}

tSelectBox.prototype.toggleOpenClose = function()
{
	if(this.opened)
	{
		//close it
		
		this.close();
	}
	else
	{
		this.open();
		this.valueContainer.focus();
		//this.log('focus set');
	}
}
tSelectBox.prototype.handleClick = function(e,target)
{
	if((target.id == this.valueContainer.id)||(target.id == this.valueContainerDummy.id))
	{
		clearTimeout(this.closeTimer);
		this.toggleOpenClose();
			
		this.valueContainer.focus();	
		
	}
	else
	{
		//explode the items
		clearTimeout(this.closeTimer);
		if(target.id.indexOf('_item_'))
		{
			//this.log('item clicked::'+target.id);
			var splitted = target.id.split('_item_');
			if(splitted.length>1)
			{
				this.selectItem(parseInt(splitted[1]),e);
			}
		}
	}

}
tSelectBox.prototype.moveCursorPos = function(item,mouse)
{
	var oldcursorPos=this.cursorPos;
	var newcursorPos=0;
	if(item=='up')
	{
		newcursorPos=oldcursorPos-1;
	}
	else if (item=='down')
	{
		newcursorPos=oldcursorPos+1;
	}
	else
	{
		//it must be an int..
		newcursorPos=item;
		
	}
	var noupdate=false;
	if(newcursorPos>this.values.length-1)
	{
		//uh oh
		this.newcursorPos=this.values.length;
		noupdate=true;
	}
	if(newcursorPos<0)
	{
		this.newcursorPos=0;
		noupdate=true;
	}
	var tmpid=this.id+'_item_'+oldcursorPos;
	if(!noupdate)
	{
		if(this.values[oldcursorPos].selected)
		{
			if(this._(tmpid).className!=this.config.baseClass+'_item_selected')
			{
				this._(tmpid).className=this.config.baseClass+'_item_selected';
			}
		}
		else
		{
			if(this._(tmpid).className!=this.config.baseClass+'_item')
			{
				this._(tmpid).className=this.config.baseClass+'_item';
			}
	
		}
		
		this._(this.id+'_item_'+newcursorPos).className=this.config.baseClass+'_item_over';
		
		this.cursorPos=newcursorPos;
	}
	var itemheight = this.overlay.scrollHeight / this.values.length;
	if(!mouse)
	{
		this.overlay.scrollTop = Math.floor(itemheight * newcursorPos);	
	}
	
}
tSelectBox.prototype.changeToValue = function(value)
{
	for(var o =0;o<this.values.length;o++)
	{
		if(this.values[o].value==value)
		{
			return this.selectItem(o);
		}
	}
}
tSelectBox.prototype.selectItem = function(itemnr,e)
{
	for(var o =0;o<this.values.length;o++)
	{
		if(itemnr==o)
		{
			this.values[o].selected=true;
			this.currentText=this.values[o].text;
			this.currentValue=this.values[o].value;
			this.currentValueId=o;
			this.originalElement.value=this.values[o].value;
			if(typeof e !='undefined')
			{
				if (typeof this.originalElement.onchange == 'function') 
				{
					this.originalElement.onchange(e);
				}
			}
		}
		else
		{
			if(this.values[o].selected)
			{
				this.values[o].selected=false;
			}
		}
	}
	this.close();
	this.redraw();
	
}
tSelectBox.prototype.handleMouse = function(type,e,target)
{
	if(type=='over')
	{
		if (target.id.indexOf('_item_')) 
		{
			var splitted = target.id.split('_item_');
			if(splitted.length>1)
			{
				//this.log('change cursor pos to'+splitted[1]);
				this.moveCursorPos(parseInt(splitted[1]),true);
			}

		}
	}
	
}
tSelectBox.prototype.endIgnore = function()
{
	clearTimeout(this.ignoreTimeOut);
	this.ignoreothers=true;
}
tSelectBox.prototype.triggerEvent = function(e)
{
	try {
		if (e.type == 'ignoreStop') {
			this.ignoreothers = false;
			return false;
		}
	}
	catch(e)
	{
		//this.log(e);
	}
	var targ;
	if (!e) var e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;
	//okay so the event came in...figure out where to send em
	//this.log(e.type+'::'+targ.id+'::'+this.id);
	if(e.type=='click')
	{
		this.handleClick(e,targ);
	}
	else if(e.type=='mouseover')
	{
		this.handleMouse('over',e,targ);
	}
	else if(e.type=='mouseout')
	{
		this.handleMouse('out',e,targ);
	}
	else if((e.type=='focus')||(e.type=='blur'))
	{
		this.handleFocus(e,targ);
	}
	else if((e.type=='keypress')||(e.type=='keyup'))
	{
		//handle keypresses
		this.endIgnore();
		return this.handleKeypress(e,targ);
	}
	else if(e.type=='selectstart')
	{
		this.endIgnore();
		return false;
	}
	else if(e.type=='scroll')
	{
		this.handleScroll(e,targ);
	}
	else
	{
		//this.log('event:'+e.type);
	}
	
}

tSelectBox.prototype.triggerTimer = function(type)
{
	if(type=='close')
	{
		this.close();
	}
}
tSelectBox.prototype.handleFocus = function(e,target)
{
	if(target.id==this.valueContainer.id)
	{
		//yay its the one we want
		if(e.type=='focus')
		{
			clearTimeout(this.closeTimer);
			this.open();
		}
		else
		{
			this.closeTimer=setTimeout('_tselect.passThroughTimer(\''+this.id+'\',\'close\')',500);
		}
		
	}
}
tSelectBox.prototype.handleScroll = function(e,target)
{
	if(target.id == this.overlay.id)
	{
		clearTimeout(this.closeTimer);
		this.valueContainer.focus();
	}
}
tSelectBox.prototype.handleKeypress = function(e,target)
{
	//this.log('keypressed');
	var Esc = (window.event) ?   
                27 : e.DOM_VK_ESCAPE // MSIE : Firefox
	var keynum= (window.event) ?    // MSIE or Firefox?
                 event.keyCode : e.keyCode;
                 
		if((keynum>=37)&&(keynum<=40))
	{
		
		if(keynum==38)
		{
			//move up
			if(this.opened)
			{
				this.moveCursorPos('up');
			}
			else
			{
				this.open();
			}
			return false;
		}
		else if(keynum==40)
		{
			//move down
			if(this.opened)
			{
				this.moveCursorPos('down');
			}
			else
			{
				this.open();
			}
			return false;
		}
	}
	if(keynum==Esc)
	{
		
		this.close();
		return false;
	}
	if(keynum==13)
	{
		if(this.opened)
		{
			this.selectItem(this.cursorPos,e);
		}
		else
		{
			this.open();
		}
		
		return false;
	}
	var keychar = String.fromCharCode(keynum)		
	//this.log('keypress:'+keychar+'keynum:'+keynum);
	return false;
}
tSelectBox.prototype.attachEvents = function()
{
	eval('var func = function(event){return _tselect.passThroughEvent(\''+this.id+'\',event);}');
	var func2 = function(){return false};
	//this._a(this.valueContainer,'onclick',func);
	this._a(this.valueContainerDummy,'onclick',func);	
	//this._a(this.valueContainer,'onfocus',func);	
	this._a(this.overlay,'onscroll',func);	
	this._a(this.valueContainer,'onblur',func);	
	this._a(this.valueContainer,'onkeyup',func);	
	this._a(this.valueContainer,'onselectstart',func2);	
	this._a(this.originalElement,'onkeyup',func);	
}
/**
 * returns an dom element with an id.
 * @param {String} id
 */
tSelectBox.prototype._ = function (id)
{
	return document.getElementById(id);
}
/**
 * Retrieves the parent of an element
 * @param {String} id
 */
tSelectBox.prototype.__ = function (id)
{
	var elem = this._(id);
	return elem.parentNode;
}

tSelectBox.prototype._a = function(element,on,func)
{
	if(element.addEventListener)
	{
		var doon = on.substring(2);
		element.addEventListener(doon,func,false);
	}
	else if(element.attachEvent)
	{
		element.attachEvent(on,func);
	}
	else
	{
		element[on]=func;
	}
}

tSelectBox.prototype._getElementHeight = function(elem)
{
	var h;
	h = elem.scrollHeight;
	return h;
	if (this.isOpera) { 
		h = elem.style.pixelHeight;
	} else {
		h = elem.offsetHeight;
	}
	return h;
}
tSelectBox.prototype._getElementWidth = function(elem)
{
	var w;
	w = elem.scrollWidth;
	return w;
	if (this.isOpera) {
		w = elem.style.pixelWidth;
	} else {
		w = elem.offsetWidth;
	}
	return w;


}
tSelectBox.prototype.getPageOffsetLeft = function(el){
var x;x=el.offsetLeft;
if(el.offsetParent!=null)x+=this.getPageOffsetLeft(el.offsetParent);
return x;
}
tSelectBox.prototype.getPageOffsetTop = function(el){
	var y;y=el.offsetTop;
if(el.offsetParent!=null)y+=this.getPageOffsetTop(el.offsetParent);
return y;
}

tSelectBox.prototype.getDimensions = function(el)
{

var dim = [];
dim.x = this.getPageOffsetLeft(el);
dim.y = this.getPageOffsetTop(el);
dim.w = this._getElementWidth(el);
dim.h = this._getElementHeight(el);
return dim;


}


function tSelectContainer()
{
	/**
	 * Contains all selectboxes.
	 */
	this.selectboxes=[];
}

tSelectContainer.prototype.register =function(id)
{
	if(typeof this.selectboxes[id] != 'undefined')
	{
		//it already exists, clean up if possible
		this.selectboxes[id].cleanUp();
		this.selectboxes[id] = new tSelectBox(id);
		
	}  
	else
	{
		this.selectboxes[id] = new tSelectBox(id);
	}
}
tSelectContainer.prototype.passThroughTimer = function(id,type)
{
	if (typeof this.selectboxes[id] != 'undefined') 
	{
		return this.selectboxes[id].triggerTimer(type);
	}
}
tSelectContainer.prototype.changeValue = function(id,value)
{
	if (typeof this.selectboxes[id] != 'undefined') 
	{
		return this.selectboxes[id].changeToValue(value);
	}
}
tSelectContainer.prototype.passThroughEvent = function(id,event)
{
	
	if (typeof this.selectboxes[id] != 'undefined') 
	{
		return this.selectboxes[id].triggerEvent(event);
	}
}

var _tselect = new tSelectContainer();





//[PACKSEP]



function md3lists_bc(cn)
{
	this.cn = cn;
	this.lists = [];
	
}

md3lists_bc.prototype.debug = function(text)
{
	alert(text);
}
md3lists_bc.prototype.findList = function(name)
{
	//returns the listnr if it can find it or -1 if it can't
	for(var lnr=0;lnr<this.lists.length;lnr++)
	{
		//this.debug('testing '+this.lists[lnr].name+ '  against:'+name);
		if(this.lists[lnr].name==name)
		{
			return lnr;
		}
	}
	return -1;
}

md3lists_bc.prototype.sortToggle = function(name,column,defaultdirection)
{
	var listnr = this.findList(name);
	
	if(typeof this.lists[listnr].sort=='undefined')
	{
		//default is down...... 
		this.sortColumn(name,column,defaultdirection);
		
	}
	else
	{
		if(this.lists[listnr].sort.direction=='up')
		{
			this.sortColumn(name,column,'down');
		}
		else
		{
			this.sortColumn(name,column,'up');
		}
	}
}
md3lists_bc.prototype.sortColumn = function(name,column,direction)
{
	var listnr = this.findList(name);
	
	//set the sort area
	this.lists[listnr].sort={column:column,direction:direction};
	//clear the pages....
	this.lists[listnr].pages= [];
	//alert(JSON.stringify(this.lists[listnr].sort));
	this.openpage(name,1);
	
}
md3lists_bc.prototype.reset = function(name,page)
{
	var listnr = this.findList(name);
	this.lists[listnr]
}
md3lists_bc.prototype.init = function(config,page)
{
	listnr = this.findList(config.listid);
	if(listnr>-1)
	{
		llen = listnr;	
	}
	else
	{
		//create it....
		llen = this.lists.length;
		this.lists[llen] = {};
		this.lists[llen].name = config.listid;
	}
		this.lists[llen].config = config;
		
		if((this.lists[llen].config.totalrows>0)&&(this.lists[llen].config.pagelength>0))
		{
			this.lists[llen].config.totalpages =Math.ceil(this.lists[llen].config.totalrows/this.lists[llen].config.pagelength);
			
		}
		else	
		{
			this.lists[llen].config.totalpages=0;
		}
		if(this.lists[llen].config.type=='alldata')
		{
			//no need to worry just switch between the pages as they are all there...
			this.openpage(config.listid,page);
		}
		if(this.lists[llen].config.type=='querybased')
		{
			this.lists[llen].pages = [];
			this.lists[llen].pages[page]={};
			this.lists[llen].pages[page].content =puntapi._('list_page'+this.lists[llen].config.listid+'_'+page).innerHTML;
			this.openpage(config.listid,page);
		}		
		if(this.lists[llen].config.initialorder!='')
		{
			
			this.lists[listnr].sort = {};
			this.lists[listnr].sort.column=this.lists[llen].config.initialorder;
			this.lists[listnr].sort.direction=this.lists[llen].config.initialorderdirection;
		}
		

	
}
md3lists_bc.prototype.DoCommand = function(application,command,id,query,confirmation,target)
{
	if(basepath=='')
	{
		//not the interface use plain old redirections....
		if(confirmation!='')
		{
			if(!confirm(confirmation))
			{
				return false;
			}
			else
			{
				window.location.href=basepath+'/'+application+'/'+command+'/'+id+'/?'+query;
			}
			
		}
		else
		{
			window.location.href=basepath+'/'+application+'/'+command+'/'+id+'/?'+query;
		}
		
	}
	else
	{
		//use a puntapi.docommand
		if(puntapi.defaulttarget=='dialogoutput')
		{
			puntdialog.changecommand(application,command,id,query);
		}
		else
		{
			puntapi.DoCommand(application,command,id,query,confirmation,'',target);
		}
	}
}
md3lists_bc.prototype.pageSelectedRows = function(listid)
{
	listnr = this.findList(listid);
	ids = [];
	if(listnr>-1)
	{
		var rowids = puntapi._('list_'+listid+'_'+this.lists[listnr].config.currentpage+'_rowids').value.split(',');
		for(var yar=0;yar<rowids.length;yar++)
		{
			if(rowids[yar]!='')
			{
				tmpelem = puntapi._('listcheckbox_'+listid+'_'+this.lists[listnr].config.currentpage+'_'+rowids[yar]);
				if(tmpelem.checked)
				{
					
					ids[ids.length]=tmpelem.value;
				}
			}
			
		}
		return ids.join(',');
	}
	else
	{
		return '';
	}
	
}
md3lists_bc.prototype.selectcurrentpage = function(listid,checked)
{
	listnr = this.findList(listid);
	
	
	if(listnr>-1)
	{
		var rowids = puntapi._('list_'+listid+'_'+this.lists[listnr].config.currentpage+'_rowids').value.split(',');
		puntapi._('listcheckbox_'+listid+'_'+this.lists[listnr].config.currentpage+'_top').checked=checked;
		puntapi._('listcheckbox_'+listid+'_'+this.lists[listnr].config.currentpage+'_bottom').checked=checked;
		for(var yar=0;yar<rowids.length;yar++)
		{
			
			if(rowids[yar]!='')
			{
				puntapi._('listcheckbox_'+listid+'_'+this.lists[listnr].config.currentpage+'_'+rowids[yar]).checked=checked;
			}
		}
	}
}
md3lists_bc.prototype.pageback = function(listid)
{
	listnr = this.findList(listid);
	
	
	try
	{
		if(listnr>-1)
		{	
			
			var pb = this.lists[listnr].config.currentpage-1;
			
			if(pb>0)
			{
				this.openpage(listid,pb)
			}
		}
	}
	catch(e)
	{
		this.debug(JSON.stringify(e));
	}
}
md3lists_bc.prototype.pageforward = function(listid)
{
	
	listnr = this.findList(listid);
	
	try
	{
		if(listnr>-1)
		{	
			var pb = this.lists[listnr].config.currentpage+1;
			
			if(pb<=this.lists[listnr].config.totalpages)
			{
				this.openpage(listid,pb)
			}
		}
	}
	catch(e)
	{
		this.debug(JSON.stringify(e));
	}
}
md3lists_bc.prototype.pageloaded = function(listid,page)
{
	
	listnr = this.findList(listid);
	
	if(listnr>-1)
	{
		this.lists[listnr].pages[page]= {};
		this.lists[listnr].pages[page].content='';		
		this.lists[listnr].pages[page].content=puntapi._('list_page'+listid+'_'+page).innerHTML;
		this.switchpage(listid,page);
		
	}
}
md3lists_bc.prototype.openpage = function(listid,page)
{
	
	
	listnr = this.findList(listid);
	try
	{
		if(listnr>-1)
		{
			if(this.lists[listnr].config.type=='querybased')
			{
				if(typeof this.lists[listnr].pages[page]=='undefined')
				{
					
					var doctosend = "activelist="+listid+'&pagenr='+page+'&listcall=yes';
					if(typeof this.lists[listnr].sort!='undefined')
					{
						doctosend +='&sort=yes&column='+encodeURIComponent(this.lists[listnr].sort.column)+'&direction='+encodeURIComponent(this.lists[listnr].sort.direction);
					}
					
					var tmpurl = basepath+'/'+this.lists[listnr].config.appname
					if(this.lists[listnr].config.appcommand!='')
					{
					tmpurl += "/"+this.lists[listnr].config.appcommand;
					}
					if(this.lists[listnr].config.appid!='')
					{
					tmpurl += "/"+this.lists[listnr].config.appid;
					}	
					if(this.lists[listnr].config.appquery!='')
					{
					tmpurl += "?"+this.lists[listnr].config.appquery+'&'+doctosend;
					}	
					
					var apppost =this.lists[listnr].config.apppost;
					puntapi.DoCommand(this.lists[listnr].config.appname,this.lists[listnr].config.appcommand,this.lists[listnr].config.appid,this.lists[listnr].config.appquery+'&'+doctosend,'',apppost,'list_page'+listid+'_'+(page),this.cn+'.pageloaded(\''+listid+'\','+page+')');
				}
				else
				{
					
					this.switchpage(listid,page);
				}
				
			}
			else
			{
				//simply toggle the page to on and redraw
				
				
				this.switchpage(listid,page);
				
			}
				
		}
	}
	catch(e)
	{
		this.debug(JSON.stringify(e));
	}
}
md3lists_bc.prototype.switchpage = function(listid,page)
{
	//return this.switchpage_old(listid,page);
	try
	{
		listnr = this.findList(listid);
		this.lists[listnr].config.currentpage=parseInt(page);
		var needspagenrs=false;
		if(puntapi._('list_pageselect'+listid))
		{
			if(puntapi._('list_pageselect'+listid).value!=page)
			{
				puntapi._('list_pageselect'+listid).value=page;
				try
				{
					_tselect.changeValue('list_pageselect'+listid,page);
				}
				catch(e)
				{
					
				}
			}
		}
		else
		{
			needspagenrs=true;
		}
		
		for(var pnr = 0;pnr<this.lists[listnr].config.totalpages;pnr++)
		{
			
			pagenode = puntapi._('list_page'+listid+'_'+(pnr+1));
			if(needspagenrs)
			{
				pagenr = puntapi._('list_pagenr'+listid+'_'+(pnr+1));
			}
			if((pnr+1)==page)
			{
				pagenode.style.display='block';
				if(needspagenrs)
				{
					pagenr.className='listPagenrSelected';
				}
			}
			else
			{
				pagenode.style.display='none';
				if(needspagenrs)
				{
					pagenr.className='listPagenr';
				}				
			}
		}	
	}
	catch(e)
	{
		
	}
}
md3lists_bc.prototype.switchpage_old = function(listid,page)
{
	listnr = this.findList(listid);
	var range=2;
				var pagenode=null;
				this.lists[listnr].config.currentpage=page;
				for(var pnr = 0;pnr<this.lists[listnr].config.totalpages;pnr++)
				{
					
					pagenode = puntapi._('list_page'+listid+'_'+(pnr+1));
					pagenr = puntapi._('list_pagenr'+listid+'_'+(pnr+1));
					
					if((pnr+1)==page)
					{
						pagenode.style.display='block';
						pagenr.className='listPagenrSelected';
						pagenr.style.display='inline-block';
						
					}
					else
					{
						pagenode.style.display='none';
						pagenr.className='listPagenr';
						if(((pnr+1)>= page-(range-1))&&((pnr+1)<= page+(range-1)))
						{
							pagenr.style.display='inline-block';
						}
						else if(((pnr+1)==1)||((pnr+1)==this.lists[listnr].config.totalpages))
						{
							pagenr.style.display='inline-block';
						}
						else					
						{
							pagenr.style.display='none';	
						}
						
						
					}
				}
				//now go hide the ones we don't need.....
				//first see if we need to show the spacers.....
				
				if(this.lists[listnr].config.totalpages>2)
				{
				var pagenrspacer = puntapi._('list_pagenrspacer'+listid+'_1');
				
				var pagenrspacer2 = puntapi._('list_pagenrspacer'+listid+'_'+this.lists[listnr].config.totalpages);
				if(page-range>1)
				{
					pagenrspacer.style.display="inline-block";
				}
				else
				{
					pagenrspacer.style.display="none";
				}
				
				//the last one
				if(page+range<this.lists[listnr].config.totalpages)
				{
					pagenrspacer2.style.display="inline-block";
				}
				else
				{
					pagenrspacer2.style.display="none";
				}
							
				}
			
}
/**
 * Export a list
 * @param {String} listid
 */
md3lists_bc.prototype.exportList = function(listid)
{

	this.currentExportId=listid;
	var listnr = this.findList(listid);	
	this.lists[listnr].exports=[];
	this.lists[listnr].exportsDone=0;
	
	

	
	
	var doctosend = "outputtype=xml&activelist="+listid+'&listcall=yes';
	if(typeof this.lists[listnr].sort!='undefined')
	{
		doctosend +='&sort=yes&column='+encodeURIComponent(this.lists[listnr].sort.column)+'&direction='+encodeURIComponent(this.lists[listnr].sort.direction);
	}
	
	var tmpurl = basepath+'/'+this.lists[listnr].config.appname
	if(this.lists[listnr].config.appcommand!='')
	{
		tmpurl += "/"+this.lists[listnr].config.appcommand;
	}
	if(this.lists[listnr].config.appid!='')
	{
		tmpurl += "/"+this.lists[listnr].config.appid;
	}	
	if(this.lists[listnr].config.appquery!='')
	{
		tmpurl += "?"+this.lists[listnr].config.appquery+'&'+doctosend;
	}
	else
	{
		tmpurl += "?"+doctosend;		
	}	
	var func1=null;
	var html = _tT.parse("lists_export",{totalpages:this.lists[listnr].config.totalpages});
	eval("func1 = function(){md3lists.cleanUpExport('"+listid+"');}");
	puntdialog.startSemiDialog(html,'',function(){});
	puntdialog.onCloseMethod=func1;		
	this.exportpages =this.lists[listnr].config.totalpages; 
	
	if (this.lists[llen].config.type == 'alldata') 
	{
		this.exportpages=1;
	}

	//add the requests to the queue.
	for (var pnr = 0; pnr < this.exportpages; pnr++) {
		eval("func1 = function(response){md3lists.recieveExportPage('"+listid+"',"+ pnr +",response)}");
		_tajax.makeCall(tmpurl+'&pagenr='+(pnr+1), {
			method: 'POST',
			onFinish: func1,
			weight:pnr,
			doc:this.lists[listnr].config.apppost
		});
	}

	
}
/**
 * Clean up exports for this list
 * @param {String} listid
 */
md3lists_bc.prototype.cleanUpExport= function(listid)
{
	var listnr = this.findList(listid);
	this.lists[listnr].exports=[];
	this.lists[listnr].exportrows=[];
	this.lists[listnr].exportcolumns=[];
}
/**
 * Recieve the export page , save it and trigger the switch to viewing mode after everything is in
 * @param {String} listid
 * @param {Integer} pagenr
 * @param {Object} response
 */
md3lists_bc.prototype.recieveExportPage= function(listid,pagenr,response)
{
	
	var listnr = this.findList(listid);
	this.lists[listnr].exports[pagenr]=response;
	this.lists[listnr].exportsDone++;
	puntapi._('list_export_pagesdone').innerHTML = this.lists[listnr].exportsDone;
	if(this.lists[listnr].exportsDone>=this.exportpages)
	{
		//done exporting.
		//set a timeout so this doesn't interrupt the ajax request queueing
		if (this.lists[llen].config.type == 'alldata') {
			puntapi._('list_export_pagesdone').innerHTML = this.lists[listnr].config.totalpages;
		}
		
		setTimeout("md3lists.displayExportResults('"+listid+"');",200);
	}
}
/**
 * Displays the export
 * @param {Object} listid
 */
md3lists_bc.prototype.displayExportResults = function(listid)
{
	var listnr = this.findList(listid);

	puntapi._('list_export_loading').style.display='none';
	
	
	puntapi._('list_export_results').innerHTML =_tT.parse("lists_export_inside",{totalpages:this.lists[listnr].config.totalpages});
	this.joinExportResults(listid);
	var pref ='simpletable';
	
	pref = md3.settings.getValue('list_export_preference',pref);
	
	this.renderExport(listid,pref);
	this.renderExportTypes(listid);
}
/**
 * Show the types of exports available
 * @param {String} listid
 */
md3lists_bc.prototype.renderExportTypes = function(listid)
{
	var html ='';
	
	html +='<table><tr>';
	html+="<td>"+_tT.parse('actionbutton_small_onclick',{icon:'list',onclick:"md3lists.renderExport('"+listid+"','simpletable');",title:'global_lists_exporto_simpletable'})+"</td>";
	html+="<td>"+_tT.parse('actionbutton_small_onclick',{icon:'notecode',onclick:"md3lists.renderExport('"+listid+"','csv');",title:'global_lists_exporto_csv'})+"</td>";
	html +='</tr></table>';
	
	
	puntapi._('list_exporttypes').innerHTML=html
}
/**
 * Join the columns for the export
 * @param {String} listid
 */
md3lists_bc.prototype.joinExportResults = function(listid)
{
	var listnr = this.findList(listid);
	var page =null;
	var rows= null;
	var u=0;
	this.lists[listnr].exportrows=[];
	this.lists[listnr].exportcolumns=[];
	
	var columns=null;
	var column=null;
	
	var percentage=0;
	var lastpercentage=0;	
	var totalrows =this.lists[listnr].exports.length;
	for(var o=0;o<this.lists[listnr].exports.length;o++)
	{
		
		page = this.lists[listnr].exports[o];
		if(o==0)
		{
			//export the columns
			columns = page.xml.getElementsByTagName("column");
			for(u=0;u<columns.length;u++)
			{
				column = columns.item(u);
				
				tmpobj = {name:column.getAttribute('name'),
						description:column.getElementsByTagName('description').item(0).firstChild.nodeValue};

				this.lists[listnr].exportcolumns[this.lists[listnr].exportcolumns.length]=tmpobj;
			}
			
		}
		if(o>0)
		{
			percentage = Math.floor(o/totalrows);
			if(percentage>lastpercentage)
			{
				puntapi._('list_export_result_output').innerHTML=_tT.parse("list_export_percentage",{what:'global_lists_export_rendering',percentage:percentage});
				lastpercentage=percentage;					
			}
			
		}		
		
		rows = page.xml.getElementsByTagName("row");
		for (u = 0; u < rows.length; u++) 
		{
			tmpobj = new md3lists_exportRow(rows.item(u));
			
			if(tmpobj.dummy)
			{
				continue;
			}
			this.lists[listnr].exportrows[this.lists[listnr].exportrows.length] = tmpobj; 		
		}
	}
}
/**
 * Renders an export with a type
 * @param {String} listid
 * @param {String} type
 * @param {integer} startpos
 */
md3lists_bc.prototype.renderExport = function(listid,type,startpos)
{
	var listnr = this.findList(listid);
	var basetpl = 'lists_export_'+type;
	var exportcontent='';
	var rowhtml='';
	var breakpoint = 50;
	var columns = this.lists[listnr].exportcolumns;
	
	var u =0;
	var row =null;
	var sep='';
	var sepval = _tT.parse(basetpl + '_sep',{});

	if(typeof startpos=='undefined')
	{
		startpos=0;
		this.exportcontent='';
		var headercontent='';
		md3.settings.setValue('list_export_preference',type);
		for (u = 0; u < columns.length; u++) 
		{
			headercontent += sep+_tT.parse(basetpl + '_headeritem',columns[u]);
			
			sep =sepval; 
			
		}
		this.exportcontent +=_tT.parse(basetpl + '_header',{contents:headercontent});
		this.abswitch='b';
	}	
	

	var percentage=0;
	var lastpercentage=0;
	
	var totalrows = this.lists[listnr].exportrows.length;
	for (o = startpos; o < totalrows; o++) {
		rowhtml='';
		row =this.lists[listnr].exportrows[o];
		
		
		var sep='';
		for (u = 0; u < columns.length; u++) 
		{
			for (f = 0; f < row.items.length; f++) 
			{
				if (row.items[f].column == columns[u].name) 
				{
					rowhtml += sep+_tT.parse(basetpl + '_rowitem', row.items[u]);
					sep=sepval;
				}
			} 
		}		
		if(this.abswitch=='a')
		{
			this.abswitch='b';
		}
		else
		{
			this.abswitch='a';
		}
		this.exportcontent +=_tT.parse(basetpl + '_row', {contents:rowhtml,abswitch:this.abswitch});
		if(o-startpos>=breakpoint)
		{
			//let the interface update
			//continue after 200ms;
			percentage = Math.floor((o/totalrows)*100);
			
			puntapi._('list_export_result_output').innerHTML=_tT.parse("list_export_percentage",{what:'global_lists_export_rendering',percentage:percentage});
			setTimeout("md3lists.renderExport('"+listid+"','"+type+"',"+o+")",200);
			puntapi.rescale();
			return true;
		}
	}
	
	
	var html = _tT.parse(basetpl + '_container', {
			contents: this.exportcontent
		});

	puntapi._('list_export_result_output').innerHTML=html;
	puntapi.rescale();
}
/**
 * transforms an xml object to its js counterpart
 * @param {DomNode} domObj
 */
function md3lists_exportRow(domObj)
{
	this.xml = domObj;
	this.dummy=false;
	this.parseObj();
	
}
/**
 * Parses the node and transforms it to the data it should contain.
 */
md3lists_exportRow.prototype.parseObj = function()
{
	this.items = [];
	
	if(this.xml.getAttribute('dummyrow')=='yes')
	{
		this.dummy=true
	}
	var items = this.xml.getElementsByTagName('item');
	var o =0;
	var val ='';
	var htmlval='';
	var lines=null;
	var line='';
	for(var u=0;u<items.length;u++)
	{
		val ='';
		htmlval='';		
		lines = items[u].getElementsByTagName('line');
		
		if(lines.length>0)
		{
			for(o=0;o<lines.length;o++)
			{
				line = lines.item(o).firstChild.nodeValue;
				
				if(o>0)
				{
					val		+='\n';
					htmlval	+='<br/>';
				}
				val 		+=line
				htmlval		+=line;
			}
		}
		else
		{
			val = items.item(u).firstChild.nodeValue;
			htmlval= val;	
		}
		
		this.items[u]= {
							column:items.item(u).getAttribute('column'),
							value:val,
							htmlvalue:htmlval
						};
	}	
}

md3lists = new md3lists_bc('md3lists');


//[PACKSEP]



/**
Written By John Bakker
me [ at ] johnbakker.name

Feel free to change,fry and/or eat .. just be sure to drop me a line :)

Usage:

  _tT.define('template1','Hello {name}');
  alert(_tT.parse('template1',{name:'john'}));



**/


/**
Creates the container.. you can have multiple templates easily and can reference them by name.
**/

if(typeof _tT == 'undefined')
{
function tTemplatesContainer()
{
	this.templates = [];
}
/**
	you define a template here
**/
tTemplatesContainer.prototype.define = function(name,template)
{
	newtemplate = this.templates.length;
	this.templates[newtemplate]= new tTemplate(name,template);
}
tTemplatesContainer.prototype.parse = function(name,vals)
{
	empty ='';
	if(typeof vals!='object')
	{
		returndata ='';
	}
	else
	{
		lu = this.lookup(name);
		if(lu>-1)
		{
			
			returndata = this.templates[lu].parse(vals);
	
		}
		else
		{
			returndata = '';
		}
	}
	
	return returndata;
	
	
}
tTemplatesContainer.prototype.lookup = function(name)
{
	for(tT=0;tT<this.templates.length;tT++)
	{
		//now it reads throught the templates 
		try
		{
			//just in case
			if(this.templates[tT].name==name)
			{
				return tT;
			}
		}
		catch(e)
		{
			//whoops :)
		}
	}
	
	return -1;
}

function tTemplate(name,content)
{
	this.name    = name;
	this.content = content;
}

tTemplate.prototype.parse = function(vals)
{
	output = this.content;
	for (var i in vals)
	{
		cl = "/{"+i+"}/g";
		eval("output = output.replace("+cl+",vals[i])");
		
		
	}
	return output;
}
 
  _tT = new tTemplatesContainer('_tT');
}

//[PACKSEP]



function progressbar_bc()
{
	this.bars = {};
	this.defaultBarConfig = {
		percentage:50,
		tippingPoint:0,
		type:'normal',
		startColor:'ff00ff00',
		endColor:'ff00ff00'
	}
	this.fillTemplates();
	
}
progressbar_bc.prototype.addToContainer = function(container,name,config)
{
	container.innerHTML = _tT.parse('progressbarcontainer',{name:name,type:config.type});
	this.add(name,config);
}
progressbar_bc.prototype.add = function(name,config)
{
	for(var i in this.defaultBarConfig)
	{
		if(typeof config[i]=='undefined')
		{
			config[i]=this.defaultBarConfig[i];
		}
		
	}
	var sCS = {};
	
	sCS.a = parseInt(config.startColor.substring(0,2),16);
	sCS.r = parseInt(config.startColor.substring(2,4),16);
	sCS.g = parseInt(config.startColor.substring(4,6),16);
	sCS.b = parseInt(config.startColor.substring(6,8),16);
	var eCS = {};
	eCS.a = parseInt(config.endColor.substring(0,2),16);
	eCS.r = parseInt(config.endColor.substring(2,4),16);
	eCS.g = parseInt(config.endColor.substring(4,6),16);
	eCS.b = parseInt(config.endColor.substring(6,8),16);
	
	config.sCS=sCS;
	config.eCS=eCS;
	
	
	
	this.bars[name]={'name':name,config:config,percentage:0};
	this.initialise(name);
	
}
progressbar_bc.prototype.initialise = function(name)
{
	var config =this.bars[name].config;
	clearTimeout(this.bars[name].slideTimer);
	this.bars[name].slideTimer = setTimeout('progressbar.slideTo("'+name+'",'+config.percentage+');',60);
	
}
progressbar_bc.prototype.setPercentage = function(name,to)
{
	var config =this.bars[name].config;
	clearTimeout(this.bars[name].slideTimer);
	this.bars[name].slideTimer = setTimeout('progressbar.slideTo("'+name+'",'+to+');',60);
	
}
progressbar_bc.prototype.calcColor= function(name)
{
	var config =this.bars[name].config;
	var color = {};
	var perc=this.bars[name].percentage;
	var coldiff = 0;
	var prstep=0.1;
	var colvr2='hr';
	var hxval =0;
	var overtip=false;
	if(perc<=config.tippingPoint)
	{
		perc=0;
		
	}
	else
	{
		//larger or equal...
		var remainder = 100-config.tippingPoint;
		var perct = perc-config.tippingPoint;
		perc = Math.floor((perct/remainder)*100);
		overtip=false;
		
	}
	for(var col in config.sCS)
	{
		if(config.sCS[col]>config.eCS[col])
		{
			coldiff= config.sCS[col]-config.eCS[col];
			prstep = coldiff/100;
			color[col]=config.sCS[col]-Math.floor(prstep*perc);
		}
		else if(config.sCS[col]<config.eCS[col])
		{
			coldiff= config.eCS[col]-config.sCS[col];
			prstep = coldiff/100;
			color[col]=config.sCS[col]+Math.floor(prstep*perc);
		}
		else
		{
			//don't do anything
			color[col]=config.sCS[col];
		}
		colvr2='h'+col;
		hxval = md3.base_convert(color[col],10,16)
		if(hxval.length<2)
		{
			hxval = '0'+hxval;
		}
		color[colvr2]=hxval;
	}
	
	color.hex = color.hr+color.hg+color.hb;
	if(color.a>0)
	{
		
		color.alpha =Math.floor(color.a/2.55);
	}
	else
	{
		color.alpha=0;
	}
	
	

	return color;
}
progressbar_bc.prototype.calcspeed= function(diff)
{
	var returnval =  Math.floor(diff*0.3);
	if(returnval<1)
	{
		returnval=1;
	}
	return returnval;
}
progressbar_bc.prototype.slideTo = function(name,to)
{
	var config =this.bars[name].config;
	var step=1;
	clearTimeout(this.bars[name].slideTimer);
	if(to>this.bars[name].percentage)
	{
		step = this.calcspeed(to-this.bars[name].percentage);

		this.bars[name].percentage=this.bars[name].percentage+step;
		if(to!=this.bars[name].percentage)
		{
			this.bars[name].slideTimer = setTimeout('progressbar.slideTo("'+name+'",'+to+');',60);
		}		
	}
	else if(to<this.bars[name].percentage)
	{
		step = this.calcspeed(this.bars[name].percentage-to);
		this.bars[name].percentage=this.bars[name].percentage-step;
		if(to!=this.bars[name].percentage)
		{
			this.bars[name].slideTimer = setTimeout('progressbar.slideTo("'+name+'",'+to+');',60);
		}
	}
	else
	{
		//and we're done
	}
	this.render(name);
}
progressbar_bc.prototype.render = function(name)
{
	var config =this.bars[name].config;
	var slider =md3._('progressbar_progressBarSlider_'+name);	
	md3._('progressbar_percentagespan_'+name).innerHTML=this.bars[name].percentage;
	slider.style.width=this.bars[name].percentage+'%';
	var color = this.calcColor(name);
	slider.style.backgroundColor='#'+color.hex;
	slider.style.borderColor='#'+color.hex;

	if (slider.filters) 
	{
		//IE :|
		try 
		{
			slider.filters.item("DXImageTransform.Microsoft.Alpha").opacity = color.alpha;
		} 
		catch (e) 
		{
			
			slider.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + color.alpha + ')';
		}
	}
	else
	{
	
		slider.style.opacity=(color.alpha*0.01);
	
	}
	
	if(this.bars[name].percentage==0)
	{
		slider.style.display='none';
	}
	else
	{
		slider.style.display='block';
	}
	
}
progressbar_bc.prototype.fillTemplates = function()
{
	_tT.define("progressbarcontainer",'<div class="progressBar progressBar{type}" id="progressbar_{name}"><div class="progressBarPercentage" id="progressbar_percentage_{name}"><span id="progressbar_percentagespan_{name}" >0</span>%</div><div class="progressBarContainer"><div class="progressBarSliderContainer" id="progressbar_progressBarSliderContainer_{name}"><div class="progressBarSlider" id="progressbar_progressBarSlider_{name}"><img src="/Layout/Mijndomein/blank.gif"/></div></div></div></div>');
		
}
progressbar_bc.prototype.remove = function(name)
{
	
}


var progressbar = new progressbar_bc();





//[PACKSEP]

_tT.define('simpletext','<div class="simpletext"><div class="title">{title}</div><div class="text">{text}</div></div>');

_tT.define('actionbutton','<div class="actionbutton" onclick ="{onclick}"><table cellspacing="0" cellpadding="0"><tr><td align="center"><div class="ICONnav_{icon}" style="height:35px;">&nbsp;</div></td></tr><tr><td class="icontitle"  align="center" nobreak>{title}</td></tr></table></div>');
_tT.define('actionbutton_small','<div class="clickable actionbutton" id="{id}" title="{dotitle}"><table cellspacing="0" cellpadding="0"><tr><td align="center"><div class="ICON3_{icon}" >&nbsp;</div></td><td class="icontitle"  align="center" nobreak>{title}</td></tr></table></div>');
_tT.define('actionbutton_small_onclick','<div class="clickable actionbutton" onclick="{onclick}"><table cellspacing="0" cellpadding="0"><tr><td align="center"><div class="ICON3_{icon}" >&nbsp;</div></td><td class="icontitle"  align="center" nobreak>{title}</td></tr></table></div>');

_tT.define('quickstartbutton','<div class="actionbutton" id="qsab{name}"><div class="nonclickable handle"><table cellspacing="0" cellpadding="0"><tr><td align="center"><div class="ICON2_{icon}">&nbsp;</div></td></tr><tr><td class="icontitle"  align="center" nobreak>{title}</td></tr></table></div><div class="isclickable" onclick ="{onclick}"><table cellspacing="0" cellpadding="0"><tr><td align="center"><div class="ICON2_{icon}">&nbsp;</div></td></tr><tr><td class="icontitle"  align="center" nobreak>{title}</td></tr></table></div></div>');
_tT.define('helpbox','<div class="roundcorner5" style="{style};border:3px solid #{color};padding:2px;"  id="helptextinside"><div style=""><div class="ICON3_exit clickable" onclick="puntapi.closehelp();">&#160;</div></div><div id="pagehelpinner" style="overflow:auto;height:{height}px;text-align:left;">{text}</div><br/><div><center><img src="/Layout/Mijndomein/images/foldup.gif" onclick="puntapi.resizehelp(\'smaller\');"  class="clickable"/><img src="/Layout/Mijndomein/images/folddown.gif"  onclick="puntapi.resizehelp(\'bigger\');" class="clickable"/></center></div></div><br/>');
_tT.define('corner_top','<div class="roundcorner{size}top" style="background-color:#{color}"></div>');
_tT.define('corner_bottom','<div class="roundcorner{size}bottom" style="background-color:#{color}"></div>');

_tT.define('breadcrumb','<span class="breadcrumb clickable" onclick="puntapi.DoCommand(\'{application}\',\'{command}\',\'{id}\',\'{query}\',\'{confirm}\',\'{target}\')">{description}</span>');

	_tT.define('colorpicker',
				'<input id="form_colorpicker_input" type="hidden"/><table><tr><td><div id="form_colorpicker_farb" style="height:200px;width:200px;"></div></td><td><div id="form_colorpicker" style="width:200px;height:200px;border:2px solid gray;margin-bottom:5px;">&nbsp;</div><input id="form_colorpicker_input_text" type="text" style="width:100%" /></td></tr></table><br/><table><tr><td>{button1}</td><td>{button2}</td></tr></table>');
	_tT.define('step_front_delimeter_active',
				'<div class="step_delimitor_active_left"></div>');
	_tT.define('step_front_delimeter_inactive',
				'');
				
	_tT.define('step_first_front_delimeter_active',
				'<div class="steps_left_active"></div>');
	_tT.define('step_first_front_delimeter_inactive',
				'<div class="steps_left"></div>');
								
	_tT.define('step_end_delimeter_active',
				'<div class="step_delimitor_active_right"></div>');
	_tT.define('step_end_delimeter_inactive',
				'<div class="step_delimitor_right"></div>');



	_tT.define('step_past',
				'<div class="step" onclick="{onclick}">{content}</div>');
	_tT.define('step_active',
				'<div class="step_active">{content}</div>');
	_tT.define('step_future',
				'<div class="step">{content}</div>');
	_tT.define('step_inside',
				'<div class="content"><div class="title">Step {position}</div><div class="text">{title}</div></div>');
	
	_tT.define('step_wrapper','<div class="steps">{step_contents}<div class="steps_right"></div></div>');

	_tT.define('loading','<center><b>Loading...</b><br/><br/>{text}<br/><br/><img src="/Layout/Mijndomein/images/loading.gif"></center>');
	
	_tT.define('button','<span onclick="{onclick}" class="actionbuttonbttn clickable"><table cellspacing="0" cellpadding="0" class="button" ><tbody><tr><td class="buttonleft"> </td><td class="buttontitle">{title}</td><td class="buttonicon"><div class="ICONW3_{icon}"/></td><td class="buttonright"> </td></tr></tbody></table></span>');
	_tT.define('lists_export','<div id="list_export_loading" style="width:400px;height:200px;"><center><b>Loading...</b><br/><br/>global_lists_exporting:<span id="list_export_pagesdone">0</span>/{totalpages}<br/><br/><img src="/Layout/Mijndomein/images/loading.gif"></center></div><div id="list_exporttypes"></div><div id="list_export_results"></div>');
	
	_tT.define('lists_export_inside','<div id="list_export_results_header"><div class="simpletext"><div class="title">global_lists_export_title</div><div class="text">global_lists_export_text</div></div><div id="list_export_result_output" class="list_export_result_output"></div>');

	_tT.define("lists_export_simpletable_sep","<td style='font-size:5px;display:none;'>,</td>");
	_tT.define("lists_export_simpletable_container","<table class='simpletable'>{contents}</table>");
	_tT.define("lists_export_simpletable_header","<tr class='simpletable_header'>{contents}</tr>");	
	_tT.define("lists_export_simpletable_headeritem","<td class='simpletable_headercell'>{description}</td>");	
	_tT.define("lists_export_simpletable_row","<tr class='simpletable_row_{abswitch}'>{contents}</tr>");	
	_tT.define("lists_export_simpletable_rowitem","<td class='simpletable_rowcell' valign='top'>{htmlvalue}</td>");	
	
	_tT.define("lists_export_csv_sep",",");
	_tT.define("lists_export_csv_container","<center><textarea style='width:690px;height:590px;'>{contents}</textarea></center>");
	_tT.define("lists_export_csv_header","{contents}\n");	
	_tT.define("lists_export_csv_headeritem","\"{description}\"");	
	_tT.define("lists_export_csv_row","{contents}\n");	
	_tT.define("lists_export_csv_rowitem","\"{value}\"");
	
	_tT.define("list_export_percentage",'{what}:{percentage}/100%');
			

//[PACKSEP]

/**
USES tTemplates;
**/

function tTooltipDefaultConf()
{
	this.zIndex = 251;
	this.fontsize = 12;
	this.top = 20;
	//this.left = -40;
	this.left = 10;
	this.color = '#ffff00';
	this.bordercolor="black";
	this.pointsize = 15;
	this.blankimage = '/Layout/Mijndomein/blank.gif';
	this.timeout=2000;
	//this.debug=true;
}



function tTooltip()
{
	//define the templates!
	_tT.define('tooltipinside','<table cellspacing=\'0\' cellpadding=\'0\' id="tooltipballoon" width="{width}"><tr><td width="100%"><div class="roundcorner5 genericcontainer" style="{style};padding:2px;background-color:{color};"><span id="toolTipInside">{text}</span></td></tr></table>');	
	this.lastcolor='';
	this.disabled=false;
	this.orientation="left";
	this.mouseposx=0;
	this.mouseposy=0;
	this.updatetimeoutcounter=0;
}


tTooltip.prototype.debug = function(msg)
{
	var tmpelem = document.getElementById('tooltip_debug');
	if(this.config.debug)
	{
		tmpelem.innerHTML=msg+'->'+this.mouseposx+this.mouseposy;
	
	}
}
tTooltip.prototype.init = function(config)
{
	
	this.defaultconfig = new tTooltipDefaultConf();
	
	this.tooltips= [];
	
	this.config = config;
	if(typeof this.config =='object')
	{
		//its an object at least...
	}
	else
	{
		//whoops well make it then
		this.config = [];
	}
	
	//check each setting or set it to defaults
	for (var i in this.defaultconfig)
	{
		if(typeof this.config[i]=='undefined')
		{
			this.config[i] = this.defaultconfig[i];
		}
		
	}
	this.checkdiv();
	
}

tTooltip.prototype.checkdiv = function()
{
	
	if(!this.tdiv)
	{
		
		var bdy = document.getElementsByTagName('body').item(0);
		if (bdy) {
		
		
			//make a new element to contain the tooltip
			tdiv = document.createElement('div');
			tdiv.setAttribute('id', 'ttooltip');
			tdiv.style.display = 'none';
			tdiv.style.position = 'absolute';
			tdiv.style.top = '0px';
			tdiv.style.left = '0px';
			
			tdiv.style.zIndex = this.config.zIndex;
			tdiv.innerHTML = 'empty';
			bdy.appendChild(tdiv);
			tdiv = document.getElementById('ttooltip');
			document.onmousemove = function(e){
				_toolTip.updatepos(e)
			};
			this.tdiv = document.getElementById('ttooltip');
			
			tdiv2 = document.createElement('div');
			tdiv2.setAttribute('id', 'ttooltip2');
			tdiv2.style.display = 'none';
			tdiv2.style.position = 'absolute';
			tdiv2.style.top = '0px';
			tdiv2.style.left = '0px';
			tdiv2.style.zIndex = this.config.zIndex;
			tdiv2.innerHTML = 'empty';
			bdy.appendChild(tdiv2);
			tdiv2 = document.getElementById('ttooltip');
			document.onmousemove = function(e){
				_toolTip.updatepos(e)
			};
			this.tdiv2 = document.getElementById('ttooltip2');
		}
	}
	
}





tTooltip.prototype.updatepos = function(e)
{
	var noclear=false;
	this.updatetimeoutcounter++;
	if(this.updatetimeoutcounter>10)
	{
		noclear=true;
	}
	else
	{
		clearTimeout(this.updateto);
	}
	
	
	var mouseposx=0, x=0;
	var mouseposy=0, y=0;
	if (document.all) {
		//Interne exploder
		mouseposx = ((document.documentElement && document.documentElement.scrollLeft) ? document.documentElement.scrollLeft : document.body.scrollLeft)+window.event.clientX;
		mouseposy = ((document.documentElement && document.documentElement.scrollTop) ? document.documentElement.scrollTop : document.body.scrollTop)+window.event.clientY;
	} 
	else 
	{
		mouseposx = e.pageX;
		mouseposy = e.pageY;
	}	
	this.mouseposx=mouseposx;
	this.mouseposy=mouseposy;
	this.debug('updatepos');
	if(!noclear)
	{
		this.updateto = setTimeout('_toolTip.doupdatepos()',100);
	}
}	
tTooltip.prototype.doupdatepos = function()
{
	this.updatetimeoutcounter=0;
	clearTimeout(this.updateto);
	if(this.isactive)
	{

		var tmpwidth=Math.ceil(this.windowsize.docwidth/4);
		if(this.mouseposx<((tmpwidth*2)-20))
		{
			tmpwidth = this.calcwidth();
			this.debug('rescale 1 to :'+tmpwidth);
			this.tdiv.style.left = (this.mouseposx + this.config.left) + "px";
			this.tdiv.style.top = (this.mouseposy + this.config.top) + "px";
			
			
			if(this.orientation!='left')
			{
				this.orientation='left';
				this.redraw(this.orientation,tmpwidth);
			}
		}
		else
		{
			tmpwidth = this.calcwidth();
			this.debug('rescale 2 to :'+tmpwidth);
			this.tdiv.style.left = (((this.mouseposx -tmpwidth)+20)- this.config.left) + "px";
			this.tdiv.style.top = (this.mouseposy + this.config.top) + "px";
			
			
			if(this.orientation!='right')
			{
				this.orientation='right';
				this.redraw(this.orientation,tmpwidth);
			}			
		}
	}

}


tTooltip.prototype.calcwidth = function()
{
	//calculate the width and resize
	var tmpwidth=Math.ceil(this.windowsize.docwidth/4);
	var dims = this.dimensions(document.getElementById('toolTipInside'));
	
	
	if((dims.w+10)>tmpwidth)
	{
		//it needs a resize
		document.getElementById('toolTipInside').style.width=(tmpwidth-10)+'px';
		document.getElementById('tooltipballoon').style.width=(tmpwidth)+'px';
		this.tdiv.style.width=(tmpwidth)+'px';
		return tmpwidth;
	}
	else
	{
		this.tdiv.style.width=(dims.w+10)+'px';
		document.getElementById('tooltipballoon').style.width=(dims.w+10)+'px';
		return dims.w+10;
	}
}
tTooltip.prototype.redraw = function(direction,width,height)
{
	document.getElementById('tooltippointythingie').innerHTML=this.drawpointything(direction,width);
	document.getElementById('tooltippointythingie').style.textAlign='right';
}
tTooltip.prototype.drawpointything = function(direction,width,height)
{
	ht ='';
	
	var sdirection = 'left';
	style = 'padding-left:10px;padding-right:10px;width:100%;';
	if(typeof direction !='undefined')
	{
		
		ht +='<div style="text-align:'+direction+'">';
		if(direction=='right')
		{
			
			sdirection = 'right';
			if(width!='undefined')
			{
				style = 'padding-left:'+(width-30)+'px;padding-right:20px;width:100%;';
				
			}			
			else
			{
				
			}
		}
		else
		{
			sdirection = 'left';
			
		}
		
	}
	
	//alert(direction+'->'+sdirection);
	ht+='<table cellspacing=\'0\' cellpadding=\'0\' style="'+style+'">';
	if(typeof height !='undefined')
	{
		maxval = height;
	}
	else
	{
		maxval = this.config.pointsize;
	}
	for(gg=0;gg<maxval;gg++)
	{
		sp1='<img src="'+this.currentdata.blankimage+'" style="background-color:#'+this.currentdata.color+';" width="'+gg+'" height="1"/>';
		sp2='<img src="'+this.currentdata.blankimage+'"  width="'+(maxval-gg)+'" height="1"/>';
		if(sdirection=='left')
		{
			ht+='<tr><td height="1" align="'+sdirection+'">'+sp1+sp2+'</td></tr>';
		}
		else
		{
			ht+='<tr><td height="1" align="'+sdirection+'">'+sp2+sp1+'</td></tr>';
		}
	}
	ht +='</table>';
	if(typeof direction !='undefined')
	{
		ht +='</div>';
	}
	
	return ht;
	
}
tTooltip.prototype.showsticky = function(element,data)
{
	clearTimeout(this.to);
	
	this.checkdiv();
	
	if((typeof element =='object')&&(typeof data =='object'))
	{
		
		
		this.currentelement = element
		for (var i in this.defaultconfig)
		{
			if(typeof data[i]=='undefined')
			{
				data[i] = this.defaultconfig[i];
			}
		}
		this.currentdata= data;
		this.isactive2=true;
		
		dim = this.dimensions(element);
		
		this.tdiv2.style.position = 'absolute';
		this.tdiv2.style.top  = (dim.y+40)+'px';
		this.tdiv2.style.left = (dim.x-375)+'px';
		this.tdiv2.style.width = 400+'px';
		
		istyle = 'color:#'+data.fontcolor+';background-color:#'+data.color+';font-size:'+this.config.fontsize+'px;padding-left:2px;padding-right:2px;';
		text = data.text;
		innerhtml = this.drawpointything(data.orientation,400,20);
		
		innerhtml += _tT.parse('tooltipinside',{style:istyle,color:data.color,text:text});
		
		this.tdiv2.innerHTML=innerhtml;
		this.tdiv2.style.display='block';
		this.calcwidth();
		
	}
}
tTooltip.prototype.show = function(element,data)
{
	if(!this.disabled)
	{
		clearTimeout(this.to);
		this.currentdata=data;
		this.checkdiv();
		this.windowsize =this.getviewportsize();
		if((typeof element =='object')&&(typeof data =='object'))
		{
			if(this.lastcolor==data.color)
			{
				document.getElementById('toolTipInside').innerHTML = data.text;
			}
			else
			{
				this.currentelement = element
				for (var i in this.defaultconfig)
				{
					if(typeof data[i]=='undefined')
					{
						data[i] = this.defaultconfig[i];
					}
				}
				this.currentdata= data;
				this.tdiv.style.display="none";
				
				this.isactive=true;
				dim = this.dimensions(element);
				
				istyle = 'color:#'+data.fontcolor+';background-color:#'+data.color+';font-size:'+this.config.fontsize+'px;padding-left:2px;padding-right:2px;';
				text = data.text;
				
				this.orientation='left';
				var tmpwidth =Math.ceil(this.windowsize.docwidth/4);
				/*if(text.length<40)
				{
					tmpwidth=text.length*10;
				}*/
				if(this.mouseposx<((tmpwidth*2)-20))
				{				
					this.orientation="left";
				}
				else
				{
					this.orientation="right";
				}
				
				innerhtml = "<div id=\"tooltippointythingie\">"+this.drawpointything(this.orientation)+"</div>";
				innerhtml += _tT.parse('tooltipinside',{width:tmpwidth,style:istyle,color:data.color,text:text});
				var tmpwidth=Math.ceil(this.windowsize.docwidth/4);
				
				
				this.tdiv.innerHTML=innerhtml;
				
				//this.calcwidth();
			}
			this.tdiv.style.display='block';
			this.doupdatepos();
			
		}
	}
}
tTooltip.prototype.hide= function()
{

	try
	{
		this.tdiv.innerHTML='';
		this.tdiv.style.display='none';
		this.isactive=false;
	}
	catch(e)
	{
		this.isactive=false;
	}
}
tTooltip.prototype.hidesticky= function()
{
	this.tdiv2.innerHTML='';
	this.tdiv2.style.display='none';
	this.isactive2=true;
}
tTooltip.prototype._getElementHeight = function(elem)
{
	var h;
	h = elem.scrollHeight;
	return h;
	if (this.isOpera) { 
		h = elem.style.pixelHeight;
	} else {
		h = elem.offsetHeight;
	}
	return h;


}
tTooltip.prototype._getElementWidth = function(elem)
{
	var w;
	w = elem.scrollWidth;
	return w;
	if (this.isOpera) {
		w = elem.style.pixelWidth;
	} else {
		w = elem.offsetWidth;
	}
	return w;


}
tTooltip.prototype.dimensions = function(el)
{

var dim = [];
dim.x = this.getPageOffsetLeft(el);
dim.y = this.getPageOffsetTop(el);
dim.w = this._getElementWidth(el);
dim.h = this._getElementHeight(el);
return dim;


}
tTooltip.prototype.getPageOffsetLeft = function(el){
var x;x=el.offsetLeft;
if(el.offsetParent!=null)x+=this.getPageOffsetLeft(el.offsetParent);
return x;
}
tTooltip.prototype.getPageOffsetTop = function(el){
	var y;y=el.offsetTop;
if(el.offsetParent!=null)y+=this.getPageOffsetTop(el.offsetParent);
return y;
}
tTooltip.prototype.pageHeight = function()
{
	var docHeight;
	if (typeof document.height != 'undefined') {
	docHeight = document.height;

	
	}
	else if (document.compatMode && document.compatMode != 'BackCompat') {
	docHeight = document.documentElement.scrollHeight;
       
         	
	}
	else if (document.body && typeof document.body.scrollHeight !=
	'undefined') {
	docHeight = document.body.scrollHeight;
	}
	return docHeight;
}
tTooltip.prototype.pageWidth = function()
{
	var docWidth;
	if (typeof document.Width != 'undefined') {
	docWidth = document.Width;

	
	}
	else if (document.compatMode && document.compatMode != 'BackCompat') {
	docWidth = document.documentElement.scrollWidth;
       
         	
	}
	else if (document.body && typeof document.body.scrollWidth !='undefined') {
	docWidth = document.body.scrollWidth;
	}
	return docWidth;
}
tTooltip.prototype.getviewportsize = function()
{
 var viewportwidth;
 var viewportheight;
 
 
 docheight = this.pageHeight();
 docwidth = this.pageWidth();
 if (typeof window.innerWidth != 'undefined')
 {
      viewportwidth = window.innerWidth;
      viewportheight = window.innerHeight;

 }
 else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0)
 {
       viewportwidth = document.documentElement.clientWidth;
       viewportheight = document.documentElement.clientHeight;

 }
 else
 {
       viewportwidth = document.getElementsByTagName('body')[0].clientWidth;
       viewportheight = document.getElementsByTagName('body')[0].clientHeight;
 }
 viewprt = [];
 viewprt.width=viewportwidth;
 viewprt.height=viewportheight;
 if(docheight<viewportheight)
 {
 	//docheight = viewportheight;
 }
 viewprt.docheight=docheight;
 if(docwidth<viewportwidth)
 {
 	//docwidth = viewportwidth;
 }
 viewprt.docwidth=docwidth;
  
 return viewprt;
}

_toolTip = new tTooltip({})
_toolTip.init();

//[PACKSEP]



function md3frontend(cn)
{
	this.cn = cn;
	this.onDoCommands=[];	
}
md3frontend.prototype.docommand = function(app,command,id,query,confirmation,doc,resulttarget)
{
	key=app+'_'+command+'_'+id+'_'+query;
	
	
	
	
	
	
	confirmed = true;
    if ((typeof confirmation != 'undefined') && (confirmation!=''))
    {
    	confirmed = confirm(confirmation);
    }
	if (confirmed)
	{
		nr++
		TA[nr] = new TAjax();
		TA[nr].cn = 'TA['+nr+']';
	
		targetdiv='';
		if(typeof resulttarget!= 'undefined')
		{
			if(resulttarget!='')
			{
			targetdiv='formtargetdiv='+resulttarget+'&';
			//alert(targetdiv);
			}
		}
		
		if(command=='')
		{
			TA[nr].Sourcefile=basepath+'/'+app+'?AJAX_REQ=yes&'+targetdiv+query;
		}
		else
		{
	
	
			if(id!='')
			{
				TA[nr].Sourcefile=basepath+'/'+app+'/'+command+'/'+id+'?AJAX_REQ=yes&'+targetdiv+query;
	
			}
			else
			{
				TA[nr].Sourcefile=basepath+'/'+app+'/'+command+'?AJAX_REQ=yes&'+targetdiv+query;
	
	
			}
		}
	    if ((typeof doc != 'undefined') && (doc!=''))
	    {
	    	TA[nr].doctosend=doc;
	
	    }
	    TA[nr].onReadyresponsecommand = 'md3frontend.writeresponse(getresponse('+nr+'),\''+key+'\')';
	    if(typeof resulttarget!= 'undefined')
	    {
			if(resulttarget!='')
			{
	        	TA[nr].onReadyresponsecommand = 'md3frontend.writeresponse(getresponse('+nr+'),\''+key+'\',\''+resulttarget+'\')';
			}
	    }
		
		TA[nr].doPost();

	}
}
md3frontend.prototype.writeresponse = function(content,key,resulttarget)
{
	//very simplified;
	if (typeof resulttarget == 'undefined') {
		application_elem = document.getElementById('block_main');
	}
	else
	{
		application_elem = document.getElementById(resulttarget);
	}
   	var div_new = document.createElement('div');
   	div_new.innerHTML = content
   	application_elem.innerHTML = '';
   	application_elem.appendChild(div_new);
   	try 
	
	{
	
		var bSaf = (navigator.userAgent.indexOf('Safari') != -1);
		var bOpera = (navigator.userAgent.indexOf('Opera') != -1);
		var bMoz = (navigator.appName == 'Netscape');
		if (bSaf) 
		{
			execJS(application_elem);
		}
		else if (bOpera) 
		{
			execJS(application_elem);
		}
		else if (bMoz) 
		{
			execJS(application_elem);
		}
		else 
		{
			execJS(application_elem);
		}
	}
	catch(e)
	{
		alert(e);
	}
		   this.runOnDoCommands();
		   
}

md3frontend.prototype.runOnDoCommands = function(id)
{

	for(var o=0;o<this.onDoCommands.length;o++)
	{
		if(typeof this.onDoCommands[o] =='function')
		{
			 this.onDoCommands[o]();
		}
	}
}
md3frontend = new md3frontend('md3frontend');




//[PACKSEP]

function wsm_bc()
{
	
}
wsm_bc.prototype.init = function()
{
	var tmpObj = puntapi._('wsm_sessionContainerfloater');
	if (tmpObj) 
	{
		tmpObj.style.display = 'block';
	}
	//this.sessionbarTapped();
}
wsm_bc.prototype.sessionbarTapped = function()
{
	var tmpObj = puntapi._('wsm_sessionContainerfloater');
	if (tmpObj) 
	{
		tmpObj.style.display='none';
	}
	var tmpObj = puntapi._('wsm_sessionContainer');
	if (tmpObj) 
	{
		tmpObj.style.display='block';
	}
}
wsm_bc.prototype.sessionbarClose = function()
{
	var tmpObj = puntapi._('wsm_sessionContainer');
	if (tmpObj) 
	{
		tmpObj.style.display='none';
	}
	var tmpObj = puntapi._('wsm_sessionContainerfloater');
	if (tmpObj) 
	{
		tmpObj.style.display='block';
	}
	
}
wsm_bc.prototype.translationBarStart = function(lang)
{
	puntapi.currentlang= lang;
	puntapi.currentlangtags=puntapi._('allLanguageTags').value;

	var parts1 = puntapi.currentlangtags.split("/");
	var parts2 = parts1[0].split(",");

	if((parts2.length>0) && (parts2[0]!=''))
	{
		var tmpObj = puntapi._('wsm_translationbar');
	
		if (tmpObj) 
		{
			tmpObj.style.display='block';
		}
		
		puntapi._('wsm_translationbar_counter').innerHTML=parts2.length;
		try
		{
			puntapi.printLanguageWidget();	
		}
		catch(e)
		{
			alert(e);
		}
	}
	
		
}
wsm_bc.prototype.translationBarOpen = function()
{
	var tmpObj = puntapi._('wsm_translationbar');
	
	if (tmpObj) 
	{
		tmpObj.style.display='none';
	}
	var tmpObj = puntapi._('wsm_translationbarFull');
	
	if (tmpObj) 
	{
		tmpObj.style.display='block';
	}	
		
}
wsm_bc.prototype.translationBarClose = function()
{
	var tmpObj = puntapi._('wsm_translationbarFull');
	
	if (tmpObj) 
	{
		tmpObj.style.display='none';
	}
	var tmpObj = puntapi._('wsm_translationbar');
	
	if (tmpObj) 
	{
		tmpObj.style.display='block';
	}	
		
}
var wsm = new wsm_bc();
wsm.init();

//[PACKSEP]



/**
 * SWFUpload: http://www.swfupload.org, http://swfupload.googlecode.com
 *
 * mmSWFUpload 1.0: Flash upload dialog - http://profandesign.se/swfupload/,  http://www.vinterwebb.se/
 *
 * SWFUpload is (c) 2006-2007 Lars Huring, Olov Nilzén and Mammon Media and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * SWFUpload 2 is (c) 2007-2008 Jake Roberts and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */


/* ******************* */
/* Constructor & Init  */
/* ******************* */
var SWFUpload;

if (SWFUpload == undefined) {
	SWFUpload = function (settings) {
		this.initSWFUpload(settings);
	};
}

SWFUpload.prototype.initSWFUpload = function (settings) {
	try {
		this.customSettings = {};	// A container where developers can place their own settings associated with this instance.
		this.settings = settings;
		this.eventQueue = [];
		this.movieName = "SWFUpload_" + SWFUpload.movieCount++;
		this.movieElement = null;


		// Setup global control tracking
		SWFUpload.instances[this.movieName] = this;

		// Load the settings.  Load the Flash movie.
		this.initSettings();
		this.loadFlash();
		this.displayDebugInfo();
	} catch (ex) {
		delete SWFUpload.instances[this.movieName];
		throw ex;
	}
};

/* *************** */
/* Static Members  */
/* *************** */
SWFUpload.instances = {};
SWFUpload.movieCount = 0;
SWFUpload.version = "2.2.0 2009-03-25";
SWFUpload.QUEUE_ERROR = {
	QUEUE_LIMIT_EXCEEDED	  		: -100,
	FILE_EXCEEDS_SIZE_LIMIT  		: -110,
	ZERO_BYTE_FILE			  		: -120,
	INVALID_FILETYPE		  		: -130
};
SWFUpload.UPLOAD_ERROR = {
	HTTP_ERROR				  		: -200,
	MISSING_UPLOAD_URL	      		: -210,
	IO_ERROR				  		: -220,
	SECURITY_ERROR			  		: -230,
	UPLOAD_LIMIT_EXCEEDED	  		: -240,
	UPLOAD_FAILED			  		: -250,
	SPECIFIED_FILE_ID_NOT_FOUND		: -260,
	FILE_VALIDATION_FAILED	  		: -270,
	FILE_CANCELLED			  		: -280,
	UPLOAD_STOPPED					: -290
};
SWFUpload.FILE_STATUS = {
	QUEUED		 : -1,
	IN_PROGRESS	 : -2,
	ERROR		 : -3,
	COMPLETE	 : -4,
	CANCELLED	 : -5
};
SWFUpload.BUTTON_ACTION = {
	SELECT_FILE  : -100,
	SELECT_FILES : -110,
	START_UPLOAD : -120
};
SWFUpload.CURSOR = {
	ARROW : -1,
	HAND : -2
};
SWFUpload.WINDOW_MODE = {
	WINDOW : "window",
	TRANSPARENT : "transparent",
	OPAQUE : "opaque"
};

// Private: takes a URL, determines if it is relative and converts to an absolute URL
// using the current site. Only processes the URL if it can, otherwise returns the URL untouched
SWFUpload.completeURL = function(url) {
	if (typeof(url) !== "string" || url.match(/^https?:\/\//i) || url.match(/^\//)) {
		return url;
	}
	
	var currentURL = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ":" + window.location.port : "");
	
	var indexSlash = window.location.pathname.lastIndexOf("/");
	if (indexSlash <= 0) {
		path = "/";
	} else {
		path = window.location.pathname.substr(0, indexSlash) + "/";
	}
	
	return /*currentURL +*/ path + url;
	
};


/* ******************** */
/* Instance Members  */
/* ******************** */

// Private: initSettings ensures that all the
// settings are set, getting a default value if one was not assigned.
SWFUpload.prototype.initSettings = function () {
	this.ensureDefault = function (settingName, defaultValue) {
		this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName];
	};
	
	// Upload backend settings
	this.ensureDefault("upload_url", "");
	this.ensureDefault("preserve_relative_urls", false);
	this.ensureDefault("file_post_name", "Filedata");
	this.ensureDefault("post_params", {});
	this.ensureDefault("use_query_string", false);
	this.ensureDefault("requeue_on_error", false);
	this.ensureDefault("http_success", []);
	this.ensureDefault("assume_success_timeout", 0);
	
	// File Settings
	this.ensureDefault("file_types", "*.*");
	this.ensureDefault("file_types_description", "All Files");
	this.ensureDefault("file_size_limit", 0);	// Default zero means "unlimited"
	this.ensureDefault("file_upload_limit", 0);
	this.ensureDefault("file_queue_limit", 0);

	// Flash Settings
	this.ensureDefault("flash_url", "swfupload.swf");
	this.ensureDefault("prevent_swf_caching", true);
	
	// Button Settings
	this.ensureDefault("button_image_url", "");
	this.ensureDefault("button_width", 1);
	this.ensureDefault("button_height", 1);
	this.ensureDefault("button_text", "");
	this.ensureDefault("button_text_style", "color: #000000; font-size: 16pt;");
	this.ensureDefault("button_text_top_padding", 0);
	this.ensureDefault("button_text_left_padding", 0);
	this.ensureDefault("button_action", SWFUpload.BUTTON_ACTION.SELECT_FILES);
	this.ensureDefault("button_disabled", false);
	this.ensureDefault("button_placeholder_id", "");
	this.ensureDefault("button_placeholder", null);
	this.ensureDefault("button_cursor", SWFUpload.CURSOR.ARROW);
	this.ensureDefault("button_window_mode", SWFUpload.WINDOW_MODE.WINDOW);
	
	// Debug Settings
	this.ensureDefault("debug", false);
	this.settings.debug_enabled = this.settings.debug;	// Here to maintain v2 API
	
	// Event Handlers
	this.settings.return_upload_start_handler = this.returnUploadStart;
	this.ensureDefault("swfupload_loaded_handler", null);
	this.ensureDefault("file_dialog_start_handler", null);
	this.ensureDefault("file_queued_handler", null);
	this.ensureDefault("file_queue_error_handler", null);
	this.ensureDefault("file_dialog_complete_handler", null);
	
	this.ensureDefault("upload_start_handler", null);
	this.ensureDefault("upload_progress_handler", null);
	this.ensureDefault("upload_error_handler", null);
	this.ensureDefault("upload_success_handler", null);
	this.ensureDefault("upload_complete_handler", null);
	
	this.ensureDefault("debug_handler", this.debugMessage);

	this.ensureDefault("custom_settings", {});

	// Other settings
	this.customSettings = this.settings.custom_settings;
	
	// Update the flash url if needed
	if (!!this.settings.prevent_swf_caching) {
		this.settings.flash_url = this.settings.flash_url + (this.settings.flash_url.indexOf("?") < 0 ? "?" : "&") + "preventswfcaching=" + new Date().getTime();
	}
	
	if (!this.settings.preserve_relative_urls) {
		//this.settings.flash_url = SWFUpload.completeURL(this.settings.flash_url);	// Don't need to do this one since flash doesn't look at it
		this.settings.upload_url = SWFUpload.completeURL(this.settings.upload_url);
		this.settings.button_image_url = SWFUpload.completeURL(this.settings.button_image_url);
	}
	
	delete this.ensureDefault;
};

// Private: loadFlash replaces the button_placeholder element with the flash movie.
SWFUpload.prototype.loadFlash = function () {
	var targetElement, tempParent;

	// Make sure an element with the ID we are going to use doesn't already exist
	if (document.getElementById(this.movieName) !== null) {
		throw "ID " + this.movieName + " is already in use. The Flash Object could not be added";
	}

	// Get the element where we will be placing the flash movie
	targetElement = document.getElementById(this.settings.button_placeholder_id) || this.settings.button_placeholder;

	if (targetElement == undefined) {
		throw "Could not find the placeholder element: " + this.settings.button_placeholder_id;
	}

	// Append the container and load the flash
	tempParent = document.createElement("div");
	tempParent.innerHTML = this.getFlashHTML();	// Using innerHTML is non-standard but the only sensible way to dynamically add Flash in IE (and maybe other browsers)
	targetElement.parentNode.replaceChild(tempParent.firstChild, targetElement);

	// Fix IE Flash/Form bug
	if (window[this.movieName] == undefined) {
		window[this.movieName] = this.getMovieElement();
	}
	
};

// Private: getFlashHTML generates the object tag needed to embed the flash in to the document
SWFUpload.prototype.getFlashHTML = function () {
	// Flash Satay object syntax: http://www.alistapart.com/articles/flashsatay
	return ['<object id="', this.movieName, '" type="application/x-shockwave-flash" data="', this.settings.flash_url, '" width="', this.settings.button_width, '" height="', this.settings.button_height, '" class="swfupload">',
				'<param name="wmode" value="', this.settings.button_window_mode, '" />',
				'<param name="movie" value="', this.settings.flash_url, '" />',
				'<param name="quality" value="high" />',
				'<param name="menu" value="false" />',
				'<param name="allowScriptAccess" value="always" />',
				'<param name="flashvars" value="' + this.getFlashVars() + '" />',
				'</object>'].join("");
};

// Private: getFlashVars builds the parameter string that will be passed
// to flash in the flashvars param.
SWFUpload.prototype.getFlashVars = function () {
	// Build a string from the post param object
	var paramString = this.buildParamString();
	var httpSuccessString = this.settings.http_success.join(",");
	
	// Build the parameter string
	return ["movieName=", encodeURIComponent(this.movieName),
			"&amp;uploadURL=", encodeURIComponent(this.settings.upload_url),
			"&amp;useQueryString=", encodeURIComponent(this.settings.use_query_string),
			"&amp;requeueOnError=", encodeURIComponent(this.settings.requeue_on_error),
			"&amp;httpSuccess=", encodeURIComponent(httpSuccessString),
			"&amp;assumeSuccessTimeout=", encodeURIComponent(this.settings.assume_success_timeout),
			"&amp;params=", encodeURIComponent(paramString),
			"&amp;filePostName=", encodeURIComponent(this.settings.file_post_name),
			"&amp;fileTypes=", encodeURIComponent(this.settings.file_types),
			"&amp;fileTypesDescription=", encodeURIComponent(this.settings.file_types_description),
			"&amp;fileSizeLimit=", encodeURIComponent(this.settings.file_size_limit),
			"&amp;fileUploadLimit=", encodeURIComponent(this.settings.file_upload_limit),
			"&amp;fileQueueLimit=", encodeURIComponent(this.settings.file_queue_limit),
			"&amp;debugEnabled=", encodeURIComponent(this.settings.debug_enabled),
			"&amp;buttonImageURL=", encodeURIComponent(this.settings.button_image_url),
			"&amp;buttonWidth=", encodeURIComponent(this.settings.button_width),
			"&amp;buttonHeight=", encodeURIComponent(this.settings.button_height),
			"&amp;buttonText=", encodeURIComponent(this.settings.button_text),
			"&amp;buttonTextTopPadding=", encodeURIComponent(this.settings.button_text_top_padding),
			"&amp;buttonTextLeftPadding=", encodeURIComponent(this.settings.button_text_left_padding),
			"&amp;buttonTextStyle=", encodeURIComponent(this.settings.button_text_style),
			"&amp;buttonAction=", encodeURIComponent(this.settings.button_action),
			"&amp;buttonDisabled=", encodeURIComponent(this.settings.button_disabled),
			"&amp;buttonCursor=", encodeURIComponent(this.settings.button_cursor)
		].join("");
};

// Public: getMovieElement retrieves the DOM reference to the Flash element added by SWFUpload
// The element is cached after the first lookup
SWFUpload.prototype.getMovieElement = function () {
	if (this.movieElement == undefined) {
		this.movieElement = document.getElementById(this.movieName);
	}

	if (this.movieElement === null) {
		throw "Could not find Flash element";
	}
	
	return this.movieElement;
};

// Private: buildParamString takes the name/value pairs in the post_params setting object
// and joins them up in to a string formatted "name=value&amp;name=value"
SWFUpload.prototype.buildParamString = function () {
	var postParams = this.settings.post_params; 
	var paramStringPairs = [];

	if (typeof(postParams) === "object") {
		for (var name in postParams) {
			if (postParams.hasOwnProperty(name)) {
				paramStringPairs.push(encodeURIComponent(name.toString()) + "=" + encodeURIComponent(postParams[name].toString()));
			}
		}
	}

	return paramStringPairs.join("&amp;");
};

// Public: Used to remove a SWFUpload instance from the page. This method strives to remove
// all references to the SWF, and other objects so memory is properly freed.
// Returns true if everything was destroyed. Returns a false if a failure occurs leaving SWFUpload in an inconsistant state.
// Credits: Major improvements provided by steffen
SWFUpload.prototype.destroy = function () {
	try {
		// Make sure Flash is done before we try to remove it
		this.cancelUpload(null, false);
		

		// Remove the SWFUpload DOM nodes
		var movieElement = null;
		movieElement = this.getMovieElement();
		
		if (movieElement && typeof(movieElement.CallFunction) === "unknown") { // We only want to do this in IE
			// Loop through all the movie's properties and remove all function references (DOM/JS IE 6/7 memory leak workaround)
			for (var i in movieElement) {
				try {
					if (typeof(movieElement[i]) === "function") {
						movieElement[i] = null;
					}
				} catch (ex1) {}
			}

			// Remove the Movie Element from the page
			try {
				movieElement.parentNode.removeChild(movieElement);
			} catch (ex) {}
		}
		
		// Remove IE form fix reference
		window[this.movieName] = null;

		// Destroy other references
		SWFUpload.instances[this.movieName] = null;
		delete SWFUpload.instances[this.movieName];

		this.movieElement = null;
		this.settings = null;
		this.customSettings = null;
		this.eventQueue = null;
		this.movieName = null;
		
		
		return true;
	} catch (ex2) {
		return false;
	}
};


// Public: displayDebugInfo prints out settings and configuration
// information about this SWFUpload instance.
// This function (and any references to it) can be deleted when placing
// SWFUpload in production.
SWFUpload.prototype.displayDebugInfo = function () {
	this.debug(
		[
			"---SWFUpload Instance Info---\n",
			"Version: ", SWFUpload.version, "\n",
			"Movie Name: ", this.movieName, "\n",
			"Settings:\n",
			"\t", "upload_url:               ", this.settings.upload_url, "\n",
			"\t", "flash_url:                ", this.settings.flash_url, "\n",
			"\t", "use_query_string:         ", this.settings.use_query_string.toString(), "\n",
			"\t", "requeue_on_error:         ", this.settings.requeue_on_error.toString(), "\n",
			"\t", "http_success:             ", this.settings.http_success.join(", "), "\n",
			"\t", "assume_success_timeout:   ", this.settings.assume_success_timeout, "\n",
			"\t", "file_post_name:           ", this.settings.file_post_name, "\n",
			"\t", "post_params:              ", this.settings.post_params.toString(), "\n",
			"\t", "file_types:               ", this.settings.file_types, "\n",
			"\t", "file_types_description:   ", this.settings.file_types_description, "\n",
			"\t", "file_size_limit:          ", this.settings.file_size_limit, "\n",
			"\t", "file_upload_limit:        ", this.settings.file_upload_limit, "\n",
			"\t", "file_queue_limit:         ", this.settings.file_queue_limit, "\n",
			"\t", "debug:                    ", this.settings.debug.toString(), "\n",

			"\t", "prevent_swf_caching:      ", this.settings.prevent_swf_caching.toString(), "\n",

			"\t", "button_placeholder_id:    ", this.settings.button_placeholder_id.toString(), "\n",
			"\t", "button_placeholder:       ", (this.settings.button_placeholder ? "Set" : "Not Set"), "\n",
			"\t", "button_image_url:         ", this.settings.button_image_url.toString(), "\n",
			"\t", "button_width:             ", this.settings.button_width.toString(), "\n",
			"\t", "button_height:            ", this.settings.button_height.toString(), "\n",
			"\t", "button_text:              ", this.settings.button_text.toString(), "\n",
			"\t", "button_text_style:        ", this.settings.button_text_style.toString(), "\n",
			"\t", "button_text_top_padding:  ", this.settings.button_text_top_padding.toString(), "\n",
			"\t", "button_text_left_padding: ", this.settings.button_text_left_padding.toString(), "\n",
			"\t", "button_action:            ", this.settings.button_action.toString(), "\n",
			"\t", "button_disabled:          ", this.settings.button_disabled.toString(), "\n",

			"\t", "custom_settings:          ", this.settings.custom_settings.toString(), "\n",
			"Event Handlers:\n",
			"\t", "swfupload_loaded_handler assigned:  ", (typeof this.settings.swfupload_loaded_handler === "function").toString(), "\n",
			"\t", "file_dialog_start_handler assigned: ", (typeof this.settings.file_dialog_start_handler === "function").toString(), "\n",
			"\t", "file_queued_handler assigned:       ", (typeof this.settings.file_queued_handler === "function").toString(), "\n",
			"\t", "file_queue_error_handler assigned:  ", (typeof this.settings.file_queue_error_handler === "function").toString(), "\n",
			"\t", "upload_start_handler assigned:      ", (typeof this.settings.upload_start_handler === "function").toString(), "\n",
			"\t", "upload_progress_handler assigned:   ", (typeof this.settings.upload_progress_handler === "function").toString(), "\n",
			"\t", "upload_error_handler assigned:      ", (typeof this.settings.upload_error_handler === "function").toString(), "\n",
			"\t", "upload_success_handler assigned:    ", (typeof this.settings.upload_success_handler === "function").toString(), "\n",
			"\t", "upload_complete_handler assigned:   ", (typeof this.settings.upload_complete_handler === "function").toString(), "\n",
			"\t", "debug_handler assigned:             ", (typeof this.settings.debug_handler === "function").toString(), "\n"
		].join("")
	);
};

/* Note: addSetting and getSetting are no longer used by SWFUpload but are included
	the maintain v2 API compatibility
*/
// Public: (Deprecated) addSetting adds a setting value. If the value given is undefined or null then the default_value is used.
SWFUpload.prototype.addSetting = function (name, value, default_value) {
    if (value == undefined) {
        return (this.settings[name] = default_value);
    } else {
        return (this.settings[name] = value);
	}
};

// Public: (Deprecated) getSetting gets a setting. Returns an empty string if the setting was not found.
SWFUpload.prototype.getSetting = function (name) {
    if (this.settings[name] != undefined) {
        return this.settings[name];
	}

    return "";
};



// Private: callFlash handles function calls made to the Flash element.
// Calls are made with a setTimeout for some functions to work around
// bugs in the ExternalInterface library.
SWFUpload.prototype.callFlash = function (functionName, argumentArray) {
	argumentArray = argumentArray || [];
	
	var movieElement = this.getMovieElement();
	var returnValue, returnString;

	// Flash's method if calling ExternalInterface methods (code adapted from MooTools).
	try {
		returnString = movieElement.CallFunction('<invoke name="' + functionName + '" returntype="javascript">' + __flash__argumentsToXML(argumentArray, 0) + '</invoke>');
		returnValue = eval(returnString);
	} catch (ex) {
		throw "Call to " + functionName + " failed";
	}
	
	// Unescape file post param values
	if (returnValue != undefined && typeof returnValue.post === "object") {
		returnValue = this.unescapeFilePostParams(returnValue);
	}

	return returnValue;
};

/* *****************************
	-- Flash control methods --
	Your UI should use these
	to operate SWFUpload
   ***************************** */

// WARNING: this function does not work in Flash Player 10
// Public: selectFile causes a File Selection Dialog window to appear.  This
// dialog only allows 1 file to be selected.
SWFUpload.prototype.selectFile = function () {
	this.callFlash("SelectFile");
};

// WARNING: this function does not work in Flash Player 10
// Public: selectFiles causes a File Selection Dialog window to appear/ This
// dialog allows the user to select any number of files
// Flash Bug Warning: Flash limits the number of selectable files based on the combined length of the file names.
// If the selection name length is too long the dialog will fail in an unpredictable manner.  There is no work-around
// for this bug.
SWFUpload.prototype.selectFiles = function () {
	this.callFlash("SelectFiles");
};


// Public: startUpload starts uploading the first file in the queue unless
// the optional parameter 'fileID' specifies the ID 
SWFUpload.prototype.startUpload = function (fileID) {
	this.callFlash("StartUpload", [fileID]);
};

// Public: cancelUpload cancels any queued file.  The fileID parameter may be the file ID or index.
// If you do not specify a fileID the current uploading file or first file in the queue is cancelled.
// If you do not want the uploadError event to trigger you can specify false for the triggerErrorEvent parameter.
SWFUpload.prototype.cancelUpload = function (fileID, triggerErrorEvent) {
	if (triggerErrorEvent !== false) {
		triggerErrorEvent = true;
	}
	this.callFlash("CancelUpload", [fileID, triggerErrorEvent]);
};

// Public: stopUpload stops the current upload and requeues the file at the beginning of the queue.
// If nothing is currently uploading then nothing happens.
SWFUpload.prototype.stopUpload = function () {
	this.callFlash("StopUpload");
};

/* ************************
 * Settings methods
 *   These methods change the SWFUpload settings.
 *   SWFUpload settings should not be changed directly on the settings object
 *   since many of the settings need to be passed to Flash in order to take
 *   effect.
 * *********************** */

// Public: getStats gets the file statistics object.
SWFUpload.prototype.getStats = function () {
	return this.callFlash("GetStats");
};

// Public: setStats changes the SWFUpload statistics.  You shouldn't need to 
// change the statistics but you can.  Changing the statistics does not
// affect SWFUpload accept for the successful_uploads count which is used
// by the upload_limit setting to determine how many files the user may upload.
SWFUpload.prototype.setStats = function (statsObject) {
	this.callFlash("SetStats", [statsObject]);
};

// Public: getFile retrieves a File object by ID or Index.  If the file is
// not found then 'null' is returned.
SWFUpload.prototype.getFile = function (fileID) {
	if (typeof(fileID) === "number") {
		return this.callFlash("GetFileByIndex", [fileID]);
	} else {
		return this.callFlash("GetFile", [fileID]);
	}
};

// Public: addFileParam sets a name/value pair that will be posted with the
// file specified by the Files ID.  If the name already exists then the
// exiting value will be overwritten.
SWFUpload.prototype.addFileParam = function (fileID, name, value) {
	return this.callFlash("AddFileParam", [fileID, name, value]);
};

// Public: removeFileParam removes a previously set (by addFileParam) name/value
// pair from the specified file.
SWFUpload.prototype.removeFileParam = function (fileID, name) {
	this.callFlash("RemoveFileParam", [fileID, name]);
};

// Public: setUploadUrl changes the upload_url setting.
SWFUpload.prototype.setUploadURL = function (url) {
	this.settings.upload_url = url.toString();
	this.callFlash("SetUploadURL", [url]);
};

// Public: setPostParams changes the post_params setting
SWFUpload.prototype.setPostParams = function (paramsObject) {
	this.settings.post_params = paramsObject;
	this.callFlash("SetPostParams", [paramsObject]);
};

// Public: addPostParam adds post name/value pair.  Each name can have only one value.
SWFUpload.prototype.addPostParam = function (name, value) {
	this.settings.post_params[name] = value;
	this.callFlash("SetPostParams", [this.settings.post_params]);
};

// Public: removePostParam deletes post name/value pair.
SWFUpload.prototype.removePostParam = function (name) {
	delete this.settings.post_params[name];
	this.callFlash("SetPostParams", [this.settings.post_params]);
};

// Public: setFileTypes changes the file_types setting and the file_types_description setting
SWFUpload.prototype.setFileTypes = function (types, description) {
	this.settings.file_types = types;
	this.settings.file_types_description = description;
	this.callFlash("SetFileTypes", [types, description]);
};

// Public: setFileSizeLimit changes the file_size_limit setting
SWFUpload.prototype.setFileSizeLimit = function (fileSizeLimit) {
	this.settings.file_size_limit = fileSizeLimit;
	this.callFlash("SetFileSizeLimit", [fileSizeLimit]);
};

// Public: setFileUploadLimit changes the file_upload_limit setting
SWFUpload.prototype.setFileUploadLimit = function (fileUploadLimit) {
	this.settings.file_upload_limit = fileUploadLimit;
	this.callFlash("SetFileUploadLimit", [fileUploadLimit]);
};

// Public: setFileQueueLimit changes the file_queue_limit setting
SWFUpload.prototype.setFileQueueLimit = function (fileQueueLimit) {
	this.settings.file_queue_limit = fileQueueLimit;
	this.callFlash("SetFileQueueLimit", [fileQueueLimit]);
};

// Public: setFilePostName changes the file_post_name setting
SWFUpload.prototype.setFilePostName = function (filePostName) {
	this.settings.file_post_name = filePostName;
	this.callFlash("SetFilePostName", [filePostName]);
};

// Public: setUseQueryString changes the use_query_string setting
SWFUpload.prototype.setUseQueryString = function (useQueryString) {
	this.settings.use_query_string = useQueryString;
	this.callFlash("SetUseQueryString", [useQueryString]);
};

// Public: setRequeueOnError changes the requeue_on_error setting
SWFUpload.prototype.setRequeueOnError = function (requeueOnError) {
	this.settings.requeue_on_error = requeueOnError;
	this.callFlash("SetRequeueOnError", [requeueOnError]);
};

// Public: setHTTPSuccess changes the http_success setting
SWFUpload.prototype.setHTTPSuccess = function (http_status_codes) {
	if (typeof http_status_codes === "string") {
		http_status_codes = http_status_codes.replace(" ", "").split(",");
	}
	
	this.settings.http_success = http_status_codes;
	this.callFlash("SetHTTPSuccess", [http_status_codes]);
};

// Public: setHTTPSuccess changes the http_success setting
SWFUpload.prototype.setAssumeSuccessTimeout = function (timeout_seconds) {
	this.settings.assume_success_timeout = timeout_seconds;
	this.callFlash("SetAssumeSuccessTimeout", [timeout_seconds]);
};

// Public: setDebugEnabled changes the debug_enabled setting
SWFUpload.prototype.setDebugEnabled = function (debugEnabled) {
	this.settings.debug_enabled = debugEnabled;
	this.callFlash("SetDebugEnabled", [debugEnabled]);
};

// Public: setButtonImageURL loads a button image sprite
SWFUpload.prototype.setButtonImageURL = function (buttonImageURL) {
	if (buttonImageURL == undefined) {
		buttonImageURL = "";
	}
	
	this.settings.button_image_url = buttonImageURL;
	this.callFlash("SetButtonImageURL", [buttonImageURL]);
};

// Public: setButtonDimensions resizes the Flash Movie and button
SWFUpload.prototype.setButtonDimensions = function (width, height) {
	this.settings.button_width = width;
	this.settings.button_height = height;
	
	var movie = this.getMovieElement();
	if (movie != undefined) {
		movie.style.width = width + "px";
		movie.style.height = height + "px";
	}
	
	this.callFlash("SetButtonDimensions", [width, height]);
};
// Public: setButtonText Changes the text overlaid on the button
SWFUpload.prototype.setButtonText = function (html) {
	this.settings.button_text = html;
	this.callFlash("SetButtonText", [html]);
};
// Public: setButtonTextPadding changes the top and left padding of the text overlay
SWFUpload.prototype.setButtonTextPadding = function (left, top) {
	this.settings.button_text_top_padding = top;
	this.settings.button_text_left_padding = left;
	this.callFlash("SetButtonTextPadding", [left, top]);
};

// Public: setButtonTextStyle changes the CSS used to style the HTML/Text overlaid on the button
SWFUpload.prototype.setButtonTextStyle = function (css) {
	this.settings.button_text_style = css;
	this.callFlash("SetButtonTextStyle", [css]);
};
// Public: setButtonDisabled disables/enables the button
SWFUpload.prototype.setButtonDisabled = function (isDisabled) {
	this.settings.button_disabled = isDisabled;
	this.callFlash("SetButtonDisabled", [isDisabled]);
};
// Public: setButtonAction sets the action that occurs when the button is clicked
SWFUpload.prototype.setButtonAction = function (buttonAction) {
	this.settings.button_action = buttonAction;
	this.callFlash("SetButtonAction", [buttonAction]);
};

// Public: setButtonCursor changes the mouse cursor displayed when hovering over the button
SWFUpload.prototype.setButtonCursor = function (cursor) {
	this.settings.button_cursor = cursor;
	this.callFlash("SetButtonCursor", [cursor]);
};

/* *******************************
	Flash Event Interfaces
	These functions are used by Flash to trigger the various
	events.
	
	All these functions a Private.
	
	Because the ExternalInterface library is buggy the event calls
	are added to a queue and the queue then executed by a setTimeout.
	This ensures that events are executed in a determinate order and that
	the ExternalInterface bugs are avoided.
******************************* */

SWFUpload.prototype.queueEvent = function (handlerName, argumentArray) {
	// Warning: Don't call this.debug inside here or you'll create an infinite loop
	
	if (argumentArray == undefined) {
		argumentArray = [];
	} else if (!(argumentArray instanceof Array)) {
		argumentArray = [argumentArray];
	}
	
	var self = this;
	if (typeof this.settings[handlerName] === "function") {
		// Queue the event
		this.eventQueue.push(function () {
			this.settings[handlerName].apply(this, argumentArray);
		});
		
		// Execute the next queued event
		setTimeout(function () {
			self.executeNextEvent();
		}, 0);
		
	} else if (this.settings[handlerName] !== null) {
		throw "Event handler " + handlerName + " is unknown or is not a function";
	}
};

// Private: Causes the next event in the queue to be executed.  Since events are queued using a setTimeout
// we must queue them in order to garentee that they are executed in order.
SWFUpload.prototype.executeNextEvent = function () {
	// Warning: Don't call this.debug inside here or you'll create an infinite loop

	var  f = this.eventQueue ? this.eventQueue.shift() : null;
	if (typeof(f) === "function") {
		f.apply(this);
	}
};

// Private: unescapeFileParams is part of a workaround for a flash bug where objects passed through ExternalInterface cannot have
// properties that contain characters that are not valid for JavaScript identifiers. To work around this
// the Flash Component escapes the parameter names and we must unescape again before passing them along.
SWFUpload.prototype.unescapeFilePostParams = function (file) {
	var reg = /[$]([0-9a-f]{4})/i;
	var unescapedPost = {};
	var uk;

	if (file != undefined) {
		for (var k in file.post) {
			if (file.post.hasOwnProperty(k)) {
				uk = k;
				var match;
				while ((match = reg.exec(uk)) !== null) {
					uk = uk.replace(match[0], String.fromCharCode(parseInt("0x" + match[1], 16)));
				}
				unescapedPost[uk] = file.post[k];
			}
		}

		file.post = unescapedPost;
	}

	return file;
};

// Private: Called by Flash to see if JS can call in to Flash (test if External Interface is working)
SWFUpload.prototype.testExternalInterface = function () {
	try {
		return this.callFlash("TestExternalInterface");
	} catch (ex) {
		return false;
	}
};

// Private: This event is called by Flash when it has finished loading. Don't modify this.
// Use the swfupload_loaded_handler event setting to execute custom code when SWFUpload has loaded.
SWFUpload.prototype.flashReady = function () {
	// Check that the movie element is loaded correctly with its ExternalInterface methods defined
	var movieElement = this.getMovieElement();

	if (!movieElement) {
		this.debug("Flash called back ready but the flash movie can't be found.");
		return;
	}

	this.cleanUp(movieElement);
	
	this.queueEvent("swfupload_loaded_handler");
};

// Private: removes Flash added fuctions to the DOM node to prevent memory leaks in IE.
// This function is called by Flash each time the ExternalInterface functions are created.
SWFUpload.prototype.cleanUp = function (movieElement) {
	// Pro-actively unhook all the Flash functions
	try {
		if (this.movieElement && typeof(movieElement.CallFunction) === "unknown") { // We only want to do this in IE
			this.debug("Removing Flash functions hooks (this should only run in IE and should prevent memory leaks)");
			for (var key in movieElement) {
				try {
					if (typeof(movieElement[key]) === "function") {
						movieElement[key] = null;
					}
				} catch (ex) {
				}
			}
		}
	} catch (ex1) {
	
	}

	// Fix Flashes own cleanup code so if the SWFMovie was removed from the page
	// it doesn't display errors.
	window["__flash__removeCallback"] = function (instance, name) {
		try {
			if (instance) {
				instance[name] = null;
			}
		} catch (flashEx) {
		
		}
	};

};


/* This is a chance to do something before the browse window opens */
SWFUpload.prototype.fileDialogStart = function () {
	this.queueEvent("file_dialog_start_handler");
};


/* Called when a file is successfully added to the queue. */
SWFUpload.prototype.fileQueued = function (file) {
	file = this.unescapeFilePostParams(file);
	this.queueEvent("file_queued_handler", file);
};


/* Handle errors that occur when an attempt to queue a file fails. */
SWFUpload.prototype.fileQueueError = function (file, errorCode, message) {
	file = this.unescapeFilePostParams(file);
	this.queueEvent("file_queue_error_handler", [file, errorCode, message]);
};

/* Called after the file dialog has closed and the selected files have been queued.
	You could call startUpload here if you want the queued files to begin uploading immediately. */
SWFUpload.prototype.fileDialogComplete = function (numFilesSelected, numFilesQueued, numFilesInQueue) {
	this.queueEvent("file_dialog_complete_handler", [numFilesSelected, numFilesQueued, numFilesInQueue]);
};

SWFUpload.prototype.uploadStart = function (file) {
	file = this.unescapeFilePostParams(file);
	this.queueEvent("return_upload_start_handler", file);
};

SWFUpload.prototype.returnUploadStart = function (file) {
	var returnValue;
	if (typeof this.settings.upload_start_handler === "function") {
		file = this.unescapeFilePostParams(file);
		returnValue = this.settings.upload_start_handler.call(this, file);
	} else if (this.settings.upload_start_handler != undefined) {
		throw "upload_start_handler must be a function";
	}

	// Convert undefined to true so if nothing is returned from the upload_start_handler it is
	// interpretted as 'true'.
	if (returnValue === undefined) {
		returnValue = true;
	}
	
	returnValue = !!returnValue;
	
	this.callFlash("ReturnUploadStart", [returnValue]);
};



SWFUpload.prototype.uploadProgress = function (file, bytesComplete, bytesTotal) {
	file = this.unescapeFilePostParams(file);
	this.queueEvent("upload_progress_handler", [file, bytesComplete, bytesTotal]);
};

SWFUpload.prototype.uploadError = function (file, errorCode, message) {
	file = this.unescapeFilePostParams(file);
	this.queueEvent("upload_error_handler", [file, errorCode, message]);
};

SWFUpload.prototype.uploadSuccess = function (file, serverData, responseReceived) {
	file = this.unescapeFilePostParams(file);
	this.queueEvent("upload_success_handler", [file, serverData, responseReceived]);
};

SWFUpload.prototype.uploadComplete = function (file) {
	file = this.unescapeFilePostParams(file);
	this.queueEvent("upload_complete_handler", file);
};

/* Called by SWFUpload JavaScript and Flash functions when debug is enabled. By default it writes messages to the
   internal debug console.  You can override this event and have messages written where you want. */
SWFUpload.prototype.debug = function (message) {
	this.queueEvent("debug_handler", message);
};


/* **********************************
	Debug Console
	The debug console is a self contained, in page location
	for debug message to be sent.  The Debug Console adds
	itself to the body if necessary.

	The console is automatically scrolled as messages appear.
	
	If you are using your own debug handler or when you deploy to production and
	have debug disabled you can remove these functions to reduce the file size
	and complexity.
********************************** */
   
// Private: debugMessage is the default debug_handler.  If you want to print debug messages
// call the debug() function.  When overriding the function your own function should
// check to see if the debug setting is true before outputting debug information.
SWFUpload.prototype.debugMessage = function (message) {
	if (this.settings.debug) {
		var exceptionMessage, exceptionValues = [];

		// Check for an exception object and print it nicely
		if (typeof message === "object" && typeof message.name === "string" && typeof message.message === "string") {
			for (var key in message) {
				if (message.hasOwnProperty(key)) {
					exceptionValues.push(key + ": " + message[key]);
				}
			}
			exceptionMessage = exceptionValues.join("\n") || "";
			exceptionValues = exceptionMessage.split("\n");
			exceptionMessage = "EXCEPTION: " + exceptionValues.join("\nEXCEPTION: ");
			SWFUpload.Console.writeLine(exceptionMessage);
		} else {
			SWFUpload.Console.writeLine(message);
		}
	}
};

SWFUpload.Console = {};
SWFUpload.Console.writeLine = function (message) {
	var console, documentForm;

	try {
		console = document.getElementById("SWFUpload_Console");

		if (!console) {
			documentForm = document.createElement("form");
			document.getElementsByTagName("body")[0].appendChild(documentForm);

			console = document.createElement("textarea");
			console.id = "SWFUpload_Console";
			console.style.fontFamily = "monospace";
			console.setAttribute("wrap", "off");
			console.wrap = "off";
			console.style.overflow = "auto";
			console.style.width = "700px";
			console.style.height = "350px";
			console.style.margin = "5px";
			documentForm.appendChild(console);
		}

		console.value += message + "\n";

		console.scrollTop = console.scrollHeight - console.clientHeight;
	} catch (ex) {
		alert("Exception: " + ex.name + " Message: " + ex.message);
	}
};



//[PACKSEP]



/*
	Queue Plug-in
	
	Features:
		*Adds a cancelQueue() method for cancelling the entire queue.
		*All queued files are uploaded when startUpload() is called.
		*If false is returned from uploadComplete then the queue upload is stopped.
		 If false is not returned (strict comparison) then the queue upload is continued.
		*Adds a QueueComplete event that is fired when all the queued files have finished uploading.
		 Set the event handler with the queue_complete_handler setting.
		
	*/

var SWFUpload;
if (typeof(SWFUpload) === "function") {
	SWFUpload.queue = {};
	
	SWFUpload.prototype.initSettings = (function (oldInitSettings) {
		return function () {
			if (typeof(oldInitSettings) === "function") {
				oldInitSettings.call(this);
			}
			
			this.queueSettings = {};
			
			this.queueSettings.queue_cancelled_flag = false;
			this.queueSettings.queue_upload_count = 0;
			
			this.queueSettings.user_upload_complete_handler = this.settings.upload_complete_handler;
			this.queueSettings.user_upload_start_handler = this.settings.upload_start_handler;
			this.settings.upload_complete_handler = SWFUpload.queue.uploadCompleteHandler;
			this.settings.upload_start_handler = SWFUpload.queue.uploadStartHandler;
			
			this.settings.queue_complete_handler = this.settings.queue_complete_handler || null;
		};
	})(SWFUpload.prototype.initSettings);

	SWFUpload.prototype.startUpload = function (fileID) {
		this.queueSettings.queue_cancelled_flag = false;
		this.callFlash("StartUpload", [fileID]);
	};

	SWFUpload.prototype.cancelQueue = function () {
		this.queueSettings.queue_cancelled_flag = true;
		this.stopUpload();
		
		var stats = this.getStats();
		while (stats.files_queued > 0) {
			this.cancelUpload();
			stats = this.getStats();
		}
	};
	
	SWFUpload.queue.uploadStartHandler = function (file) {
		var returnValue;
		if (typeof(this.queueSettings.user_upload_start_handler) === "function") {
			returnValue = this.queueSettings.user_upload_start_handler.call(this, file);
		}
		
		// To prevent upload a real "FALSE" value must be returned, otherwise default to a real "TRUE" value.
		returnValue = (returnValue === false) ? false : true;
		
		this.queueSettings.queue_cancelled_flag = !returnValue;

		return returnValue;
	};
	
	SWFUpload.queue.uploadCompleteHandler = function (file) {
		var user_upload_complete_handler = this.queueSettings.user_upload_complete_handler;
		var continueUpload;
		
		if (file.filestatus === SWFUpload.FILE_STATUS.COMPLETE) {
			this.queueSettings.queue_upload_count++;
		}

		if (typeof(user_upload_complete_handler) === "function") {
			continueUpload = (user_upload_complete_handler.call(this, file) === false) ? false : true;
		} else if (file.filestatus === SWFUpload.FILE_STATUS.QUEUED) {
			// If the file was stopped and re-queued don't restart the upload
			continueUpload = false;
		} else {
			continueUpload = true;
		}
		
		if (continueUpload) {
			var stats = this.getStats();
			if (stats.files_queued > 0 && this.queueSettings.queue_cancelled_flag === false) {
				this.startUpload();
			} else if (this.queueSettings.queue_cancelled_flag === false) {
				this.queueEvent("queue_complete_handler", [this.queueSettings.queue_upload_count]);
				this.queueSettings.queue_upload_count = 0;
			} else {
				this.queueSettings.queue_cancelled_flag = false;
				this.queueSettings.queue_upload_count = 0;
			}
		}
	};
}



//[PACKSEP]




if(typeof loaderbar=='object'){loaderbar.loadedfile('wsmpack.js')};
