

var isFileQueued;
var progressBar;

	function swfUploadComplete () {
		
	}
	
	function swfDialogStart () {
		
	}
	
	function swfDialogComplete () {
		
	}
	
	
	
	
	function swfUploadError () {
		
	}
	
function swfUploadStart () 
{
	

	
	try {
		var browseButton = dojo.byId ('btnBrowse');
		var isDisabled = false;
	
		if (isDisabled || !isFileQueued) {
			
		
			// redir to /files
			flvUploadOnComplete();
			return;
		}
	
		
		// STILL BUGGY IN 2.2 B3
		/*var swfuploadContainer = dojo.byId ('swfupload_container');
		if (swfuploadContainer) {
			swfuploadContainer.style.display="none";
		}*/
		
		var popupUploadProgressNode = dojo.byId ('popupUploadProgress');
		if (popupUploadProgressNode) {
			popupUploadProgressNode.style.display="block";
			progressBar=dijit.byId('progressBar');
			if (!progressBar) {
				progressBar=dijit.byId('popupProgressBar');
			}
		}
		// NOWd");
		swfu.startUpload();
		
	} catch (e) {
		handleCatchedErrror(e);
	}
}



function swfUploadOnProgress (file, bytesLoaded, bytesTotal) 
{
	
	if (!progressBar) return;
	
	try {
		progressBar.update({ 
			progress: Math.ceil((bytesLoaded / bytesTotal) * 100)
		});
	} catch (e) {
		handleCatchedErrror(e);
	}
}

function swfUploadOnStart()  {
	
	return true;
}

function swfUploadDone()  {
	
}

function swfuploadActivate () 
{
	
	
	try {
		swfu.setButtonDisabled();
		dojo.byId("txtFileName").value = "Bitte Datei auswÃ¤hlen";
		dojo.byId('fileuploadDeleteButton').style.display="none";
	} catch (e) {
		handleCatchedErrror(e);
	}
}

function swfUploadLoaded()  {
	
}

function fileBrowse() 
{	
	
	
	try {
		var txtFileName = dojo.byId("txtFileName");
		txtFileName.value = "";

		this.cancelUpload();
		this.selectFile();
	} catch (e) {
		handleCatchedErrror(e);
	}
}


function swfUploadOnQueued(file) 
{
	
	try {
		var txtFileName = dojo.byId("txtFileName");
		txtFileName.value = file.name;
		isFileQueued=true;
	} catch (e) {
		isFileQueued=false;
	}
}

function swfUploadOnQueuedDoAutoUpload(file) 
{
	
	
	try {
		var txtFileName = dojo.byId("txtFileName");
		if (txtFileName) {
			txtFileName.value = file.name;
		}
		isFileQueued=true;
		
	} catch (e) {
		isFileQueued=false;
	}
	
	// WHY THIS???? AH WAS FOR PROFILE AUTO PIC
	//helper_triggerFlvUpload('upload_form_node');
	
	swfUploadStart();
}

function swfUploadQueueOnError(file, errorCode, message)  {
	
	
	
	
	
	try {
		// Handle this error separately because we don't want to create a FileProgress element for it.
		switch (errorCode) {
		case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
			alert("You have attempted to queue too many files.\n" + (message === 0 ? "You have reached the upload limit." : "You may select " + (message > 1 ? "up to " + message + " files." : "one file.")));
			return;
		case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
			alert("The file you selected is too big.");
			this.debug("Error Code: File too big, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			return;
		case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
			alert("The file you selected is empty.  Please select another file.");
			this.debug("Error Code: Zero byte file, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			return;
		case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
			alert("The file you choose is not an allowed file type.");
			this.debug("Error Code: Invalid File Type, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			return;
		default:
			alert("An error occurred in the upload. Try again later.");
			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			return;
		}
	} catch (e) {
		handleCatchedErrror(e);
	}
}


function fileDialogComplete(numFilesSelected, numFilesQueued) {
	
}

function swfUploadOnSuccess(file, serverData) 
{
	//alert ("swfupload - uploadSuccess");
	
	
	try {
		if (progressBar) {
			progressBar.update({ 
				progress:100
			});
		}
	} catch (e) {
		handleCatchedErrror(e);
	}
}

function swfUploadOnError(file, errorCode, message) {
	
	
	
	
	try {
		var txtFileName = document.getElementById("txtFileName");
		txtFileName.value = "";
		
		// Handle this error separately because we don't want to create a FileProgress element for it.
		switch (errorCode) {
		case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL:
			alert("There was a configuration error.  You will not be able to upload a resume at this time.");
			this.debug("Error Code: No backend file, File name: " + file.name + ", Message: " + message);
			return;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
			alert("You may only upload 1 file.");
			this.debug("Error Code: Upload Limit Exceeded, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			return;
		case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
		case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
			break;
		default:
			alert("An error occurred in the upload. Try again later.");
			this.debug("Error Code: " + errorCode + ", File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			return;
		}

		switch (errorCode) {
		case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
			progress.setStatus("Upload Error");
			this.debug("Error Code: HTTP Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
			progress.setStatus("Upload Failed.");
			this.debug("Error Code: Upload Failed, File name: " + file.name + ", File size: " + file.size + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.IO_ERROR:
			progress.setStatus("Server (IO) Error");
			this.debug("Error Code: IO Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
			progress.setStatus("Security Error");
			this.debug("Error Code: Security Error, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
			progress.setStatus("Upload Cancelled");
			this.debug("Error Code: Upload Cancelled, File name: " + file.name + ", Message: " + message);
			break;
		case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
			progress.setStatus("Upload Stopped");
			this.debug("Error Code: Upload Stopped, File name: " + file.name + ", Message: " + message);
			break;
		}
	} catch (e) {
		handleCatchedErrror(e);
	}
}



var _gat=new Object({c:"length",lb:"4.3",m:"cookie",b:undefined,cb:function(d,a){this.zb=d;this.Nb=a},r:"__utma=",W:"__utmb=",ma:"__utmc=",Ta:"__utmk=",na:"__utmv=",oa:"__utmx=",Sa:"GASO=",X:"__utmz=",lc:"http://www.google-analytics.com/__utm.gif",mc:"https://ssl.google-analytics.com/__utm.gif",Wa:"utmcid=",Ya:"utmcsr=",$a:"utmgclid=",Ua:"utmccn=",Xa:"utmcmd=",Za:"utmctr=",Va:"utmcct=",Hb:false,_gasoDomain:undefined,_gasoCPath:undefined,e:window,a:document,k:navigator,t:function(d){var a=1,c=0,h,
o;if(!_gat.q(d)){a=0;for(h=d[_gat.c]-1;h>=0;h--){o=d.charCodeAt(h);a=(a<<6&268435455)+o+(o<<14);c=a&266338304;a=c!=0?a^c>>21:a}}return a},C:function(d,a,c){var h=_gat,o="-",k,l,s=h.q;if(!s(d)&&!s(a)&&!s(c)){k=h.w(d,a);if(k>-1){l=d.indexOf(c,k);if(l<0)l=d[h.c];o=h.F(d,k+h.w(a,"=")+1,l)}}return o},Ea:function(d){var a=false,c=0,h,o;if(!_gat.q(d)){a=true;for(h=0;h<d[_gat.c];h++){o=d.charAt(h);c+="."==o?1:0;a=a&&c<=1&&(0==h&&"-"==o||_gat.P(".0123456789",o))}}return a},d:function(d,a){var c=encodeURIComponent;
return c instanceof Function?(a?encodeURI(d):c(d)):escape(d)},J:function(d,a){var c=decodeURIComponent,h;d=d.split("+").join(" ");if(c instanceof Function)try{h=a?decodeURI(d):c(d)}catch(o){h=unescape(d)}else h=unescape(d);return h},Db:function(d){return d&&d.hash?_gat.F(d.href,_gat.w(d.href,"#")):""},q:function(d){return _gat.b==d||"-"==d||""==d},Lb:function(d){return d[_gat.c]>0&&_gat.P(" \n\r\t",d)},P:function(d,a){return _gat.w(d,a)>-1},h:function(d,a){d[d[_gat.c]]=a},T:function(d){return d.toLowerCase()},
z:function(d,a){return d.split(a)},w:function(d,a){return d.indexOf(a)},F:function(d,a,c){c=_gat.b==c?d[_gat.c]:c;return d.substring(a,c)},uc:function(){var d=_gat.b,a=window;if(a&&a.gaGlobal&&a.gaGlobal.hid)d=a.gaGlobal.hid;else{d=Math.round(Math.random()*2147483647);a.gaGlobal=a.gaGlobal?a.gaGlobal:{};a.gaGlobal.hid=d}return d},wa:function(){return Math.round(Math.random()*2147483647)},Gc:function(){return(_gat.wa()^_gat.vc())*2147483647},vc:function(){var d=_gat.k,a=_gat.a,c=_gat.e,h=a[_gat.m]?
a[_gat.m]:"",o=c.history[_gat.c],k,l,s=[d.appName,d.version,d.language?d.language:d.browserLanguage,d.platform,d.userAgent,d.javaEnabled()?1:0].join("");if(c.screen)s+=c.screen.width+"x"+c.screen.height+c.screen.colorDepth;else if(c.java){l=java.awt.Toolkit.getDefaultToolkit().getScreenSize();s+=l.screen.width+"x"+l.screen.height}s+=h;s+=a.referrer?a.referrer:"";k=s[_gat.c];while(o>0)s+=o--^k++;return _gat.t(s)}});_gat.hc=function(){var d=this,a=_gat.cb;function c(h,o){return new a(h,o)}d.db="utm_campaign";d.eb="utm_content";d.fb="utm_id";d.gb="utm_medium";d.hb="utm_nooverride";d.ib="utm_source";d.jb="utm_term";d.kb="gclid";d.pa=0;d.I=0;d.wb="15768000";d.Tb="1800";d.ea=[];d.ga=[];d.Ic="cse";d.Gb="q";d.ab="google";d.fa=[c(d.ab,d.Gb),c("yahoo","p"),c("msn","q"),c("aol","query"),c("aol","encquery"),c("lycos","query"),c("ask","q"),c("altavista","q"),c("netscape","query"),c("cnn","query"),c("looksmart","qt"),c("about",
"terms"),c("mamma","query"),c("alltheweb","q"),c("gigablast","q"),c("voila","rdata"),c("virgilio","qs"),c("live","q"),c("baidu","wd"),c("alice","qs"),c("yandex","text"),c("najdi","q"),c("aol","q"),c("club-internet","query"),c("mama","query"),c("seznam","q"),c("search","q"),c("wp","szukaj"),c("onet","qt"),c("netsprint","q"),c("google.interia","q"),c("szukacz","q"),c("yam","k"),c("pchome","q"),c("kvasir","searchExpr"),c("sesam","q"),c("ozu","q"),c("terra","query"),c("nostrum","query"),c("mynet","q"),
c("ekolay","q"),c("search.ilse","search_for")];d.B=undefined;d.Kb=false;d.p="/";d.ha=100;d.Da="/__utm.gif";d.ta=1;d.ua=1;d.G="|";d.sa=1;d.qa=1;d.pb=1;d.g="auto";d.D=1;d.Ga=1000;d.Yc=10;d.nc=10;d.Zc=0.2};_gat.Y=function(d,a){var c,h,o,k,l,s,q,f=this,n=_gat,w=n.q,x=n.c,g,z=a;f.a=d;function B(i){var b=i instanceof Array?i.join("."):"";return w(b)?"-":b}function A(i,b){var e=[],j;if(!w(i)){e=n.z(i,".");if(b)for(j=0;j<e[x];j++)if(!n.Ea(e[j]))e[j]="-"}return e}function p(){return u(63072000000)}function u(i){var b=new Date,e=new Date(b.getTime()+i);return"expires="+e.toGMTString()+"; "}function m(i,b){f.a[n.m]=i+"; path="+z.p+"; "+b+f.Cc()}function r(i,b,e){var j=f.V,t,v;for(t=0;t<j[x];t++){v=j[t][0];
v+=w(b)?b:b+j[t][4];j[t][2](n.C(i,v,e))}}f.Jb=function(){return n.b==g||g==f.t()};f.Ba=function(){return l?l:"-"};f.Wb=function(i){l=i};f.Ma=function(i){g=n.Ea(i)?i*1:"-"};f.Aa=function(){return B(s)};f.Na=function(i){s=A(i)};f.Hc=function(){return g?g:"-"};f.Cc=function(){return w(z.g)?"":"domain="+z.g+";"};f.ya=function(){return B(c)};f.Ub=function(i){c=A(i,1)};f.K=function(){return B(h)};f.La=function(i){h=A(i,1)};f.za=function(){return B(o)};f.Vb=function(i){o=A(i,1)};f.Ca=function(){return B(k)};
f.Xb=function(i){k=A(i);for(var b=0;b<k[x];b++)if(b<4&&!n.Ea(k[b]))k[b]="-"};f.Dc=function(){return q};f.Uc=function(i){q=i};f.pc=function(){c=[];h=[];o=[];k=[];l=n.b;s=[];g=n.b};f.t=function(){var i="",b;for(b=0;b<f.V[x];b++)i+=f.V[b][1]();return n.t(i)};f.Ha=function(i){var b=f.a[n.m],e=false;if(b){r(b,i,";");f.Ma(f.t());e=true}return e};f.Rc=function(i){r(i,"","&");f.Ma(n.C(i,n.Ta,"&"))};f.Wc=function(){var i=f.V,b=[],e;for(e=0;e<i[x];e++)n.h(b,i[e][0]+i[e][1]());n.h(b,n.Ta+f.t());return b.join("&")};
f.bd=function(i,b){var e=f.V,j=z.p,t;f.Ha(i);z.p=b;for(t=0;t<e[x];t++)if(!w(e[t][1]()))e[t][3]();z.p=j};f.dc=function(){m(n.r+f.ya(),p())};f.Pa=function(){m(n.W+f.K(),u(z.Tb*1000))};f.ec=function(){m(n.ma+f.za(),"")};f.Ra=function(){m(n.X+f.Ca(),u(z.wb*1000))};f.fc=function(){m(n.oa+f.Ba(),p())};f.Qa=function(){m(n.na+f.Aa(),p())};f.cd=function(){m(n.Sa+f.Dc(),"")};f.V=[[n.r,f.ya,f.Ub,f.dc,"."],[n.W,f.K,f.La,f.Pa,""],[n.ma,f.za,f.Vb,f.ec,""],[n.oa,f.Ba,f.Wb,f.fc,""],[n.X,f.Ca,f.Xb,f.Ra,"."],[n.na,
f.Aa,f.Na,f.Qa,"."]]};_gat.jc=function(d){var a=this,c=_gat,h=d,o,k=function(l){var s=(new Date).getTime(),q;q=(s-l[3])*(h.Zc/1000);if(q>=1){l[2]=Math.min(Math.floor(l[2]*1+q),h.nc);l[3]=s}return l};a.O=function(l,s,q,f,n,w,x){var g,z=h.D,B=q.location;if(!o)o=new c.Y(q,h);o.Ha(f);g=c.z(o.K(),".");if(g[1]<500||n){if(w)g=k(g);if(n||!w||g[2]>=1){if(!n&&w)g[2]=g[2]*1-1;g[1]=g[1]*1+1;l="?utmwv="+_gat.lb+"&utmn="+c.wa()+(c.q(B.hostname)?"":"&utmhn="+c.d(B.hostname))+(h.ha==100?"":"&utmsp="+c.d(h.ha))+l;if(0==z||2==z){var A=
new Image(1,1);A.src=h.Da+l;var p=2==z?function(){}:x||function(){};A.onload=p}if(1==z||2==z){var u=new Image(1,1);u.src=("https:"==B.protocol?c.mc:c.lc)+l+"&utmac="+s+"&utmcc="+a.wc(q,f);u.onload=x||function(){}}}}o.La(g.join("."));o.Pa()};a.wc=function(l,s){var q=[],f=[c.r,c.X,c.na,c.oa],n,w=l[c.m],x;for(n=0;n<f[c.c];n++){x=c.C(w,f[n]+s,";");if(!c.q(x))c.h(q,f[n]+x+";")}return c.d(q.join("+"))}};_gat.i=function(){this.la=[]};_gat.i.bb=function(d,a,c,h,o,k){var l=this;l.cc=d;l.Oa=a;l.L=c;l.sb=h;l.Pb=o;l.Qb=k};_gat.i.bb.prototype.S=function(){var d=this,a=_gat.d;return"&"+["utmt=item","utmtid="+a(d.cc),"utmipc="+a(d.Oa),"utmipn="+a(d.L),"utmiva="+a(d.sb),"utmipr="+a(d.Pb),"utmiqt="+a(d.Qb)].join("&")};_gat.i.$=function(d,a,c,h,o,k,l,s){var q=this;q.v=d;q.ob=a;q.bc=c;q.ac=h;q.Yb=o;q.ub=k;q.$b=l;q.xb=s;q.ca=[]};_gat.i.$.prototype.mb=function(d,a,c,h,o){var k=this,l=k.Eb(d),s=k.v,q=_gat;if(q.b==
l)q.h(k.ca,new q.i.bb(s,d,a,c,h,o));else{l.cc=s;l.Oa=d;l.L=a;l.sb=c;l.Pb=h;l.Qb=o}};_gat.i.$.prototype.Eb=function(d){var a,c=this.ca,h;for(h=0;h<c[_gat.c];h++)a=d==c[h].Oa?c[h]:a;return a};_gat.i.$.prototype.S=function(){var d=this,a=_gat.d;return"&"+["utmt=tran","utmtid="+a(d.v),"utmtst="+a(d.ob),"utmtto="+a(d.bc),"utmttx="+a(d.ac),"utmtsp="+a(d.Yb),"utmtci="+a(d.ub),"utmtrg="+a(d.$b),"utmtco="+a(d.xb)].join("&")};_gat.i.prototype.nb=function(d,a,c,h,o,k,l,s){var q=this,f=_gat,n=q.xa(d);if(f.b==
n){n=new f.i.$(d,a,c,h,o,k,l,s);f.h(q.la,n)}else{n.ob=a;n.bc=c;n.ac=h;n.Yb=o;n.ub=k;n.$b=l;n.xb=s}return n};_gat.i.prototype.xa=function(d){var a,c=this.la,h;for(h=0;h<c[_gat.c];h++)a=d==c[h].v?c[h]:a;return a};_gat.gc=function(d){var a=this,c="-",h=_gat,o=d;a.Ja=screen;a.qb=!self.screen&&self.java?java.awt.Toolkit.getDefaultToolkit():h.b;a.a=document;a.e=window;a.k=navigator;a.Ka=c;a.Sb=c;a.tb=c;a.Ob=c;a.Mb=1;a.Bb=c;function k(){var l,s,q,f,n="ShockwaveFlash",w="$version",x=a.k?a.k.plugins:h.b;if(x&&x[h.c]>0)for(l=0;l<x[h.c]&&!q;l++){s=x[l];if(h.P(s.name,"Shockwave Flash"))q=h.z(s.description,"Shockwave Flash ")[1]}else{n=n+"."+n;try{f=new ActiveXObject(n+".7");q=f.GetVariable(w)}catch(g){}if(!q)try{f=
new ActiveXObject(n+".6");q="WIN 6,0,21,0";f.AllowScriptAccess="always";q=f.GetVariable(w)}catch(z){}if(!q)try{f=new ActiveXObject(n);q=f.GetVariable(w)}catch(z){}if(q){q=h.z(h.z(q," ")[1],",");q=q[0]+"."+q[1]+" r"+q[2]}}return q?q:c}a.xc=function(){var l;if(self.screen){a.Ka=a.Ja.width+"x"+a.Ja.height;a.Sb=a.Ja.colorDepth+"-bit"}else if(a.qb)try{l=a.qb.getScreenSize();a.Ka=l.width+"x"+l.height}catch(s){}a.Ob=h.T(a.k&&a.k.language?a.k.language:(a.k&&a.k.browserLanguage?a.k.browserLanguage:c));a.Mb=
a.k&&a.k.javaEnabled()?1:0;a.Bb=o?k():c;a.tb=h.d(a.a.characterSet?a.a.characterSet:(a.a.charset?a.a.charset:c))};a.Xc=function(){return"&"+["utmcs="+h.d(a.tb),"utmsr="+a.Ka,"utmsc="+a.Sb,"utmul="+a.Ob,"utmje="+a.Mb,"utmfl="+h.d(a.Bb)].join("&")}};_gat.n=function(d,a,c,h,o){var k=this,l=_gat,s=l.q,q=l.b,f=l.P,n=l.C,w=l.T,x=l.z,g=l.c;k.a=a;k.f=d;k.Rb=c;k.ja=h;k.o=o;function z(p){return s(p)||"0"==p||!f(p,"://")}function B(p){var u="";p=w(x(p,"://")[1]);if(f(p,"/")){p=x(p,"/")[1];if(f(p,"?"))u=x(p,"?")[0]}return u}function A(p){var u="";u=w(x(p,"://")[1]);if(f(u,"/"))u=x(u,"/")[0];return u}k.Fc=function(p){var u=k.Fb(),m=k.o;return new l.n.s(n(p,m.fb+"=","&"),n(p,m.ib+"=","&"),n(p,m.kb+"=","&"),k.ba(p,m.db,"(not set)"),k.ba(p,m.gb,"(not set)"),
k.ba(p,m.jb,u&&!s(u.R)?l.J(u.R):q),k.ba(p,m.eb,q))};k.Ib=function(p){var u=A(p),m=B(p);if(f(u,k.o.ab)){p=x(p,"?").join("&");if(f(p,"&"+k.o.Gb+"="))if(m==k.o.Ic)return true}return false};k.Fb=function(){var p,u,m=k.Rb,r,i,b=k.o.fa;if(z(m)||k.Ib(m))return;p=A(m);for(r=0;r<b[g];r++){i=b[r];if(f(p,w(i.zb))){m=x(m,"?").join("&");if(f(m,"&"+i.Nb+"=")){u=x(m,"&"+i.Nb+"=")[1];if(f(u,"&"))u=x(u,"&")[0];return new l.n.s(q,i.zb,q,"(organic)","organic",u,q)}}}};k.ba=function(p,u,m){var r=n(p,u+"=","&"),i=!s(r)?
l.J(r):(!s(m)?m:"-");return i};k.Nc=function(p){var u=k.o.ea,m=false,r,i;if(p&&"organic"==p.da){r=w(l.J(p.R));for(i=0;i<u[g];i++)m=m||w(u[i])==r}return m};k.Ec=function(){var p="",u="",m=k.Rb;if(z(m)||k.Ib(m))return;p=w(x(m,"://")[1]);if(f(p,"/")){u=l.F(p,l.w(p,"/"));if(f(u,"?"))u=x(u,"?")[0];p=x(p,"/")[0]}if(0==l.w(p,"www."))p=l.F(p,4);return new l.n.s(q,p,q,"(referral)","referral",q,u)};k.sc=function(p){var u="";if(k.o.pa){u=l.Db(p);u=""!=u?u+"&":u}u+=p.search;return u};k.zc=function(){return new l.n.s(q,
"(direct)",q,"(direct)","(none)",q,q)};k.Oc=function(p){var u=false,m,r,i=k.o.ga;if(p&&"referral"==p.da){m=w(l.d(p.ia));for(r=0;r<i[g];r++)u=u||f(m,w(i[r]))}return u};k.U=function(p){return q!=p&&p.Fa()};k.yc=function(p,u){var m="",r="-",i,b,e=0,j,t,v=k.f;if(!p)return"";t=k.a[l.m]?k.a[l.m]:"";m=k.sc(k.a.location);if(k.o.I&&p.Jb()){r=p.Ca();if(!s(r)&&!f(r,";")){p.Ra();return""}}r=n(t,l.X+v+".",";");i=k.Fc(m);if(k.U(i)){b=n(m,k.o.hb+"=","&");if("1"==b&&!s(r))return""}if(!k.U(i)){i=k.Fb();if(!s(r)&&
k.Nc(i))return""}if(!k.U(i)&&u){i=k.Ec();if(!s(r)&&k.Oc(i))return""}if(!k.U(i))if(s(r)&&u)i=k.zc();if(!k.U(i))return"";if(!s(r)){var y=x(r,"."),E=new l.n.s;E.Cb(y.slice(4).join("."));j=w(E.ka())==w(i.ka());e=y[3]*1}if(!j||u){var F=n(t,l.r+v+".",";"),I=F.lastIndexOf("."),G=I>9?l.F(F,I+1)*1:0;e++;G=0==G?1:G;p.Xb([v,k.ja,G,e,i.ka()].join("."));p.Ra();return"&utmcn=1"}else return"&utmcr=1"}};_gat.n.s=function(d,a,c,h,o,k,l){var s=this;s.v=d;s.ia=a;s.ra=c;s.L=h;s.da=o;s.R=k;s.vb=l};_gat.n.s.prototype.ka=
function(){var d=this,a=_gat,c=[],h=[[a.Wa,d.v],[a.Ya,d.ia],[a.$a,d.ra],[a.Ua,d.L],[a.Xa,d.da],[a.Za,d.R],[a.Va,d.vb]],o,k;if(d.Fa())for(o=0;o<h[a.c];o++)if(!a.q(h[o][1])){k=h[o][1].split("+").join("%20");k=k.split(" ").join("%20");a.h(c,h[o][0]+k)}return c.join("|")};_gat.n.s.prototype.Fa=function(){var d=this,a=_gat.q;return!(a(d.v)&&a(d.ia)&&a(d.ra))};_gat.n.s.prototype.Cb=function(d){var a=this,c=_gat,h=function(o){return c.J(c.C(d,o,"|"))};a.v=h(c.Wa);a.ia=h(c.Ya);a.ra=h(c.$a);a.L=h(c.Ua);a.da=
h(c.Xa);a.R=h(c.Za);a.vb=h(c.Va)};_gat.Z=function(){var d=this,a=_gat,c={},h="k",o="v",k=[h,o],l="(",s=")",q="*",f="!",n="'",w={};w[n]="'0";w[s]="'1";w[q]="'2";w[f]="'3";var x=1;function g(m,r,i,b){if(a.b==c[m])c[m]={};if(a.b==c[m][r])c[m][r]=[];c[m][r][i]=b}function z(m,r,i){return a.b!=c[m]&&a.b!=c[m][r]?c[m][r][i]:a.b}function B(m,r){if(a.b!=c[m]&&a.b!=c[m][r]){c[m][r]=a.b;var i=true,b;for(b=0;b<k[a.c];b++)if(a.b!=c[m][k[b]]){i=false;break}if(i)c[m]=a.b}}function A(m){var r="",i=false,b,e;for(b=0;b<k[a.c];b++){e=m[k[b]];if(a.b!=
e){if(i)r+=k[b];r+=p(e);i=false}else i=true}return r}function p(m){var r=[],i,b;for(b=0;b<m[a.c];b++)if(a.b!=m[b]){i="";if(b!=x&&a.b==m[b-1]){i+=b.toString();i+=f}i+=u(m[b]);a.h(r,i)}return l+r.join(q)+s}function u(m){var r="",i,b,e;for(i=0;i<m[a.c];i++){b=m.charAt(i);e=w[b];r+=a.b!=e?e:b}return r}d.Kc=function(m){return a.b!=c[m]};d.N=function(){var m=[],r;for(r in c)if(a.b!=c[r])a.h(m,r.toString()+A(c[r]));return m.join("")};d.Sc=function(m){if(m==a.b)return d.N();var r=[m.N()],i;for(i in c)if(a.b!=
c[i]&&!m.Kc(i))a.h(r,i.toString()+A(c[i]));return r.join("")};d._setKey=function(m,r,i){if(typeof i!="string")return false;g(m,h,r,i);return true};d._setValue=function(m,r,i){if(typeof i!="number"&&(a.b==Number||!(i instanceof Number)))return false;if(Math.round(i)!=i||i==NaN||i==Infinity)return false;g(m,o,r,i.toString());return true};d._getKey=function(m,r){return z(m,h,r)};d._getValue=function(m,r){return z(m,o,r)};d._clearKey=function(m){B(m,h)};d._clearValue=function(m){B(m,o)}};_gat.ic=function(d,a){var c=this;c.jd=a;c.Pc=d;c._trackEvent=function(h,o,k){return a._trackEvent(c.Pc,h,o,k)}};_gat.kc=function(d){var a=this,c=_gat,h=c.b,o=c.q,k=c.w,l=c.F,s=c.C,q=c.P,f=c.z,n="location",w=c.c,x=h,g=new c.hc,z=false;a.a=document;a.e=window;a.ja=Math.round((new Date).getTime()/1000);a.H=d;a.yb=a.a.referrer;a.va=h;a.j=h;a.A=h;a.M=false;a.aa=h;a.rb="";a.l=h;a.Ab=h;a.f=h;a.u=h;function B(){if("auto"==g.g){var b=a.a.domain;if("www."==l(b,0,4))b=l(b,4);g.g=b}g.g=c.T(g.g)}function A(){var b=g.g,e=k(b,"www.google.")*k(b,".google.")*k(b,"google.");return e||"/"!=g.p||k(b,"google.org")>-1}function p(b,
e,j){if(o(b)||o(e)||o(j))return"-";var t=s(b,c.r+a.f+".",e),v;if(!o(t)){v=f(t,".");v[5]=v[5]?v[5]*1+1:1;v[3]=v[4];v[4]=j;t=v.join(".")}return t}function u(){return"file:"!=a.a[n].protocol&&A()}function m(b){if(!b||""==b)return"";while(c.Lb(b.charAt(0)))b=l(b,1);while(c.Lb(b.charAt(b[w]-1)))b=l(b,0,b[w]-1);return b}function r(b,e,j){if(!o(b())){e(c.J(b()));if(!q(b(),";"))j()}}function i(b){var e,j=""!=b&&a.a[n].host!=b;if(j)for(e=0;e<g.B[w];e++)j=j&&k(c.T(b),c.T(g.B[e]))==-1;return j}a.Bc=function(){if(!g.g||
""==g.g||"none"==g.g){g.g="";return 1}B();return g.pb?c.t(g.g):1};a.tc=function(b,e){if(o(b))b="-";else{e+=g.p&&"/"!=g.p?g.p:"";var j=k(b,e);b=j>=0&&j<=8?"0":("["==b.charAt(0)&&"]"==b.charAt(b[w]-1)?"-":b)}return b};a.Ia=function(b){var e="",j=a.a;e+=a.aa?a.aa.Xc():"";e+=g.qa?a.rb:"";e+=g.ta&&!o(j.title)?"&utmdt="+c.d(j.title):"";e+="&utmhid="+c.uc()+"&utmr="+a.va+"&utmp="+a.Tc(b);return e};a.Tc=function(b){var e=a.a[n];b=h!=b&&""!=b?c.d(b,true):c.d(e.pathname+unescape(e.search),true);return b};a.$c=
function(b){if(a.Q()){var e="";if(a.l!=h&&a.l.N().length>0)e+="&utme="+c.d(a.l.N());e+=a.Ia(b);x.O(e,a.H,a.a,a.f)}};a.qc=function(){var b=new c.Y(a.a,g);return b.Ha(a.f)?b.Wc():h};a._getLinkerUrl=function(b,e){var j=f(b,"#"),t=b,v=a.qc();if(v)if(e&&1>=j[w])t+="#"+v;else if(!e||1>=j[w])if(1>=j[w])t+=(q(b,"?")?"&":"?")+v;else t=j[0]+(q(b,"?")?"&":"?")+v+"#"+j[1];return t};a.Zb=function(){var b;if(a.A&&a.A[w]>=10&&!q(a.A,"=")){a.u.Uc(a.A);a.u.cd();c._gasoDomain=g.g;c._gasoCPath=g.p;b=a.a.createElement("script");
b.type="text/javascript";b.id="_gasojs";b.src="https://www.google.com/analytics/reporting/overlay_js?gaso="+a.A+"&"+c.wa();a.a.getElementsByTagName("head")[0].appendChild(b)}};a.Jc=function(){var b=a.a[c.m],e=a.ja,j=a.u,t=a.f+"",v=a.e,y=v?v.gaGlobal:h,E,F=q(b,c.r+t+"."),I=q(b,c.W+t),G=q(b,c.ma+t),C,D=[],H="",K=false,J;b=o(b)?"":b;if(g.I){E=c.Db(a.a[n]);if(g.pa&&!o(E))H=E+"&";H+=a.a[n].search;if(!o(H)&&q(H,c.r)){j.Rc(H);if(!j.Jb())j.pc();C=j.ya()}r(j.Ba,j.Wb,j.fc);r(j.Aa,j.Na,j.Qa)}if(!o(C))if(o(j.K())||
o(j.za())){C=p(H,"&",e);a.M=true}else{D=f(j.K(),".");t=D[0]}else if(F)if(!I||!G){C=p(b,";",e);a.M=true}else{C=s(b,c.r+t+".",";");D=f(s(b,c.W+t,";"),".")}else{C=[t,c.Gc(),e,e,e,1].join(".");a.M=true;K=true}C=f(C,".");if(v&&y&&y.dh==t){C[4]=y.sid?y.sid:C[4];if(K){C[3]=y.sid?y.sid:C[4];if(y.vid){J=f(y.vid,".");C[1]=J[0];C[2]=J[1]}}}j.Ub(C.join("."));D[0]=t;D[1]=D[1]?D[1]:0;D[2]=undefined!=D[2]?D[2]:g.Yc;D[3]=D[3]?D[3]:C[4];j.La(D.join("."));j.Vb(t);if(!o(j.Hc()))j.Ma(j.t());j.dc();j.Pa();j.ec()};a.Lc=
function(){x=new c.jc(g)};a._initData=function(){var b;if(!z){a.Lc();a.f=a.Bc();a.u=new c.Y(a.a,g)}if(u())a.Jc();if(!z){if(u()){a.va=a.tc(a.Ac(),a.a.domain);if(g.sa){a.aa=new c.gc(g.ua);a.aa.xc()}if(g.qa){b=new c.n(a.f,a.a,a.va,a.ja,g);a.rb=b.yc(a.u,a.M)}}a.l=new c.Z;a.Ab=new c.Z;z=true}if(!c.Hb)a.Mc()};a._visitCode=function(){a._initData();var b=s(a.a[c.m],c.r+a.f+".",";"),e=f(b,".");return e[w]<4?"":e[1]};a._cookiePathCopy=function(b){a._initData();if(a.u)a.u.bd(a.f,b)};a.Mc=function(){var b=a.a[n].hash,
e;e=b&&""!=b&&0==k(b,"#gaso=")?s(b,"gaso=","&"):s(a.a[c.m],c.Sa,";");if(e[w]>=10){a.A=e;if(a.e.addEventListener)a.e.addEventListener("load",a.Zb,false);else a.e.attachEvent("onload",a.Zb)}c.Hb=true};a.Q=function(){return a._visitCode()%10000<g.ha*100};a.Vc=function(){var b,e,j=a.a.links;if(!g.Kb){var t=a.a.domain;if("www."==l(t,0,4))t=l(t,4);g.B.push("."+t)}for(b=0;b<j[w]&&(g.Ga==-1||b<g.Ga);b++){e=j[b];if(i(e.host))if(!e.gatcOnclick){e.gatcOnclick=e.onclick?e.onclick:a.Qc;e.onclick=function(v){var y=
!this.target||this.target=="_self"||this.target=="_top"||this.target=="_parent";y=y&&!a.oc(v);a.ad(v,this,y);return y?false:(this.gatcOnclick?this.gatcOnclick(v):true)}}}};a.Qc=function(){};a._trackPageview=function(b){if(u()){a._initData();if(g.B)a.Vc();a.$c(b);a.M=false}};a._trackTrans=function(){var b=a.f,e=[],j,t,v,y;a._initData();if(a.j&&a.Q()){for(j=0;j<a.j.la[w];j++){t=a.j.la[j];c.h(e,t.S());for(v=0;v<t.ca[w];v++)c.h(e,t.ca[v].S())}for(y=0;y<e[w];y++)x.O(e[y],a.H,a.a,b,true)}};a._setTrans=
function(){var b=a.a,e,j,t,v,y=b.getElementById?b.getElementById("utmtrans"):(b.utmform&&b.utmform.utmtrans?b.utmform.utmtrans:h);a._initData();if(y&&y.value){a.j=new c.i;v=f(y.value,"UTM:");g.G=!g.G||""==g.G?"|":g.G;for(e=0;e<v[w];e++){v[e]=m(v[e]);j=f(v[e],g.G);for(t=0;t<j[w];t++)j[t]=m(j[t]);if("T"==j[0])a._addTrans(j[1],j[2],j[3],j[4],j[5],j[6],j[7],j[8]);else if("I"==j[0])a._addItem(j[1],j[2],j[3],j[4],j[5],j[6])}}};a._addTrans=function(b,e,j,t,v,y,E,F){a.j=a.j?a.j:new c.i;return a.j.nb(b,e,
j,t,v,y,E,F)};a._addItem=function(b,e,j,t,v,y){var E;a.j=a.j?a.j:new c.i;E=a.j.xa(b);if(!E)E=a._addTrans(b,"","","","","","","");E.mb(e,j,t,v,y)};a._setVar=function(b){if(b&&""!=b&&A()){a._initData();var e=new c.Y(a.a,g),j=a.f;e.Na(j+"."+c.d(b));e.Qa();if(a.Q())x.O("&utmt=var",a.H,a.a,a.f)}};a._link=function(b,e){if(g.I&&b){a._initData();a.a[n].href=a._getLinkerUrl(b,e)}};a._linkByPost=function(b,e){if(g.I&&b&&b.action){a._initData();b.action=a._getLinkerUrl(b.action,e)}};a._setXKey=function(b,e,
j){a.l._setKey(b,e,j)};a._setXValue=function(b,e,j){a.l._setValue(b,e,j)};a._getXKey=function(b,e){return a.l._getKey(b,e)};a._getXValue=function(b,e){return a.l.getValue(b,e)};a._clearXKey=function(b){a.l._clearKey(b)};a._clearXValue=function(b){a.l._clearValue(b)};a._createXObj=function(){a._initData();return new c.Z};a._sendXEvent=function(b){var e="";a._initData();if(a.Q()){e+="&utmt=event&utme="+c.d(a.l.Sc(b))+a.Ia();x.O(e,a.H,a.a,a.f,false,true)}};a._createEventTracker=function(b){a._initData();
return new c.ic(b,a)};a._trackEvent=function(b,e,j,t){var v=true,y=a.Ab;if(h!=b&&h!=e&&""!=b&&""!=e){y._clearKey(5);y._clearValue(5);v=y._setKey(5,1,b)?v:false;v=y._setKey(5,2,e)?v:false;v=h==j||y._setKey(5,3,j)?v:false;v=h==t||y._setValue(5,1,t)?v:false;if(v)a._sendXEvent(y)}else v=false;return v};a.ad=function(b,e,j){a._initData();if(a.Q()){var t=new c.Z;t._setKey(6,1,e.href);var v=j?function(){a.rc(b,e)}:undefined;x.O("&utmt=event&utme="+c.d(t.N())+a.Ia(),a.H,a.a,a.f,false,true,v)}};a.rc=function(b,
e){if(!b)b=a.e.event;var j=true;if(e.gatcOnclick)j=e.gatcOnclick(b);if(j||typeof j=="undefined")if(!e.target||e.target=="_self")a.e.location=e.href;else if(e.target=="_top")a.e.top.document.location=e.href;else if(e.target=="_parent")a.e.parent.document.location=e.href};a.oc=function(b){if(!b)b=a.e.event;var e=b.shiftKey||b.ctrlKey||b.altKey;if(!e)if(b.modifiers&&a.e.Event)e=b.modifiers&a.e.Event.CONTROL_MASK||b.modifiers&a.e.Event.SHIFT_MASK||b.modifiers&a.e.Event.ALT_MASK;return e};a._setDomainName=
function(b){g.g=b};a.dd=function(){return g.g};a._addOrganic=function(b,e){c.h(g.fa,new c.cb(b,e))};a._clearOrganic=function(){g.fa=[]};a.hd=function(){return g.fa};a._addIgnoredOrganic=function(b){c.h(g.ea,b)};a._clearIgnoredOrganic=function(){g.ea=[]};a.ed=function(){return g.ea};a._addIgnoredRef=function(b){c.h(g.ga,b)};a._clearIgnoredRef=function(){g.ga=[]};a.fd=function(){return g.ga};a._setAllowHash=function(b){g.pb=b?1:0};a._setCampaignTrack=function(b){g.qa=b?1:0};a._setClientInfo=function(b){g.sa=
b?1:0};a._getClientInfo=function(){return g.sa};a._setCookiePath=function(b){g.p=b};a._setTransactionDelim=function(b){g.G=b};a._setCookieTimeout=function(b){g.wb=b};a._setDetectFlash=function(b){g.ua=b?1:0};a._getDetectFlash=function(){return g.ua};a._setDetectTitle=function(b){g.ta=b?1:0};a._getDetectTitle=function(){return g.ta};a._setLocalGifPath=function(b){g.Da=b};a._getLocalGifPath=function(){return g.Da};a._setLocalServerMode=function(){g.D=0};a._setRemoteServerMode=function(){g.D=1};a._setLocalRemoteServerMode=
function(){g.D=2};a.gd=function(){return g.D};a._getServiceMode=function(){return g.D};a._setSampleRate=function(b){g.ha=b};a._setSessionTimeout=function(b){g.Tb=b};a._setAllowLinker=function(b){g.I=b?1:0};a._setAllowAnchor=function(b){g.pa=b?1:0};a._setCampNameKey=function(b){g.db=b};a._setCampContentKey=function(b){g.eb=b};a._setCampIdKey=function(b){g.fb=b};a._setCampMediumKey=function(b){g.gb=b};a._setCampNOKey=function(b){g.hb=b};a._setCampSourceKey=function(b){g.ib=b};a._setCampTermKey=function(b){g.jb=
b};a._setCampCIdKey=function(b){g.kb=b};a._getAccount=function(){return a.H};a._getVersion=function(){return _gat.lb};a.kd=function(b){g.B=[];if(b)g.B=b};a.md=function(b){g.Kb=b};a.ld=function(b){g.Ga=b};a._setReferrerOverride=function(b){a.yb=b};a.Ac=function(){return a.yb}};_gat._getTracker=function(d){var a=new _gat.kc(d);return a};
/**
 * 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 Beta 3";
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"
};

/* ******************** */
/* 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("file_post_name", "Filedata");
	this.ensureDefault("post_params", {});
	this.ensureDefault("use_query_string", false);
	this.ensureDefault("requeue_on_error", false);
	this.ensureDefault("http_success", []);
	
	// 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", 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 + "?swfuploadrnd=" + Math.floor(Math.random() * 999999999);
	}
	
	delete this.ensureDefault;
};

SWFUpload.prototype.loadFlash = function () {
	if (this.settings.button_placeholder_id !== "") {
		this.replaceWithFlash();
	} else {
		this.appendFlash();
	}
};

// Private: appendFlash gets the HTML tag for the Flash
// It then appends the flash to the body
SWFUpload.prototype.appendFlash = function () {
	var targetElement, container;

	// 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 body tag where we will be adding the flash movie
	targetElement = document.getElementsByTagName("body")[0];

	if (targetElement == undefined) {
		throw "Could not find the 'body' element.";
	}

	// Append the container and load the flash
	container = document.createElement("div");
	container.style.width = "1px";
	container.style.height = "1px";
	container.style.overflow = "hidden";

	targetElement.appendChild(container);
	container.innerHTML = this.getFlashHTML();	// Using innerHTML is non-standard but the only sensible way to dynamically add Flash in IE (and maybe other browsers)

	// Fix IE Flash/Form bug
	if (window[this.movieName] == undefined) {
		window[this.movieName] = this.getMovieElement();
	}
	
	
};

// Private: replaceWithFlash replaces the button_placeholder element with the flash movie.
SWFUpload.prototype.replaceWithFlash = 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);

	if (targetElement == undefined) {
		throw "Could not find the placeholder element.";
	}

	// 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;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) {
			// 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 (ex1) {
		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", "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_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: 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;
};

SWFUpload.prototype.flashReady = function () {
	// Check that the movie element is loaded correctly with its ExternalInterface methods defined
	var movieElement = this.getMovieElement();

	// Pro-actively unhook all the Flash functions
	if (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) {
			}
		}
	}
	
	this.queueEvent("swfupload_loaded_handler");
};


/* 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) {
	this.queueEvent("file_dialog_complete_handler", [numFilesSelected, numFilesQueued]);
};

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) {
	file = this.unescapeFilePostParams(file);
	this.queueEvent("upload_success_handler", [file, serverData]);
};

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);
	}
};
var lastAjaxFilledDivID = null;
var IS_BACK_BUTTON_ACTIVE = true;

/*
dojo.declare("newDateTextBox",[dijit.form.DateTextBox],
		{
		serialize: function(d, options) {
			return 44;//dojo.date.locale.format(d, {selector:'date', datePattern:'yyyy-dd-MM'}).toLowerCase();
		}

		});
*/
/*
//Date.prototype.json = function(){ return dojo.date.stamp.toISOString(this, {selector: 'date'});};
Date.prototype.json = function(){ return 22; //dojo.date.stamp.toISOString(this, {selector: 'date'});
};
*/

var PROCESS_AJAX_CLICKS_WHILE_XHR_ACTIVE=0;
var IS_PROCESS_AJAX_ACTIVE=false;
function processAjax (requestType, directUrl, controller, ajaxType, ajaxAction, divID, formID, dontRegister, loaderRef, loaderNewStyle) 
{
	try {
		
		var requestInfo="\n\nrequestType: "+requestType+"\ndirectUrl: "+directUrl+"\ncontroller: "+controller+"\najaxType "+ajaxType+"\najaxAction: "+ ajaxAction+"\ndivID: "+divID+"\nformID: "+ formID+"\nloaderRef:"+loaderRef;
		
		if (CURRENT_XHR_CONNECTION) {
			CURRENT_XHR_CONNECTION.cancel();
			CURRENT_XHR_CONNECTION=null;
		}
				
		/*if (CURRENT_XHR_CONNECTION) {
			//alert ("PROCESS_AJAX_CLICKS_WHILE_XHR_ACTIVE: "+PROCESS_AJAX_CLICKS_WHILE_XHR_ACTIVE);
			PROCESS_AJAX_CLICKS_WHILE_XHR_ACTIVE = PROCESS_AJAX_CLICKS_WHILE_XHR_ACTIVE +1;
			//alert ("no double clicks please");
			
			if (PROCESS_AJAX_CLICKS_WHILE_XHR_ACTIVE > 1) {
				handleError ('SILENT PRVENTING DOuBLECLicK, CURRENT_XHR_CONNECTION IS '+CURRENT_XHR_CONNECTION, requestInfo, true);
			} else {
				return;
			}
			
		} */
		/*else {
			IS_PROCESS_AJAX_ACTIVE=true;
			IS_PROCESS_AJAX_ACTIVE=true;
		}*/
		
		toaster.onSelect();
		
		
		
			
		
	 	// grab all form-data if exists
	 	if (formID) 
	 	{
	 		// try getting data by diji
	 		var formDijit=dijit.byId(formID);
	 		var formNode=dojo.byId(formID);
	 		//
	 		if(formDijit && 1==1) 
	 		{
	 			
	 			//formData=formDijit.getValues();
	 			formData=formDijit.attr('value');
	 			
	 			
	 			// thats pretty cool, take hidden fields directly
	 			// so besides performance leaks from to much dijits
	 			dojo.query('.hiddenFieldClass', formID).forEach(function(n){
				formData[n.name] = n.value;
				});
				
	 			// we need to read out date directly, otherwise its preformated via dijit directly
				
	 			//alert (dumpObj(formData, 1));
	 			
	 			//
	 			
	 			dojo.query('input[id^="date_"]', formID).forEach(function(n){
	 				//dojo.query('*[widgetId]"]', formID).forEach(function(n){
	 				
	 				
	 				var myDijit = dijit.byId (n.id);
	 				var val = myDijit.attr ("value");
	 				
	 				if (val) {
	 					var formatedDateString=dojo.date.locale.format(val, {
	 	 					selector:'date', 
	 	 					datePattern:'yyyy-dd-MM', 
	 	 					locale:'en'}).toLowerCase(); 
	 	 				
	 	 				formData[n.id] = formatedDateString;	
	 				}
	 				
	 				
	 				
	 				//
	 				
	 				
	 				//var testX = n.getValue();
	 				//alert ("testX");
	 				
	 				//
	 				//
	 				//var val = myDijit.attr('value');
	 				//
	 				//
	 				//alert ("Yeah! found date-field "+n.id+" with content:"+n.value);
	 				//formData[n.name] = n.value;
	 			});
	 			/*
	 			dojo.forEach(
	 					dojo.query('input[id^="date_"]', dojo.byId(divID)),
	 						function(node) {
	 						alert ("Yeah! found date_ field "+node.id+" with content:"+node.value);
	 						formData[node.id] = node.value;
	 					}
	 					);
	 			*/
	 			/*
	 			var f = dojo.byId(formID);
				for (var i = 0; i <= f.elements.length-1; i++) {
					var elem = f.elements[i];
					if (elem.name.substr(0, 5) != "date_") {
						continue;
					}
					else {
						formData[elem.name] = elem.value;
					}
				}
				*/
				//alert (dumpObj(formData, 1));
	 		}
	 		
	 		else if (formNode)
	 		{
	 			//
	 			var formNode = dojo.byId (formID);
	 			var elementNodesCollection =  formNode.getElementsByTagName("input");
	
	 			var dataToPost = new Array();
				for (var i = 0; i <= elementNodesCollection.length-1;  i++) 
				{
					var name =elementNodesCollection[i].getAttribute("name");
					var value=elementNodesCollection[i].getAttribute("value");
					dataToPost[name] = value;
				}
				formData=dataToPost;
				
	 		}
	 		//
	 		//
	 		//
	 	}
	 	
	 	
	 	var previewCat;
	 	var isPreview = false;
	 	
	 	
	 	// identify controller name if directUrl was set
	 	if (!controller && directUrl) {
	 		urlTokenItems = getSplicedUrlTokenItems(directUrl);
	 		//
			controller = urlTokenItems[0];
			if (urlTokenItems[1] == "preview") {
				previewCat = urlTokenItems[2];
				isPreview = true;
				//alert ("previewmode processAjax, controller: "+controller);
				
			}
		}
	 	
	 	
	 	
	 	
	 	
		// perhaps rei-nit popup widget?
		if (divID == 'popup' && divID == lastAjaxFilledDivID) {
			//
		}
		
		// REMOVED TO OTHER PLACE
		/*// goto navigation change proceedure if multi-ajax 
		if (divID=='ajax_multi_replace_node') {
			changeMainNavigation (controller, previewCat);
		}*/
	 	
	 	
	 	
	 	
	 	var ajaxRequestUrl = buildAjaxRequestUrl(directUrl, controller, ajaxType, ajaxAction);
	 	
	 	/*if (ajaxAction == "login") {
			alert ("make ssl");
			var ajaxRequestUrl = buildAjaxRequestUrl(directUrl, controller, ajaxType, ajaxAction, true);
		} else {
			var ajaxRequestUrl = buildAjaxRequestUrl(directUrl, controller, ajaxType, ajaxAction);
		}*/
	 	
	 	
	 	
	 	
	 	if (loaderRef) {
	 		initLoaders (loaderRef, loaderNewStyle);
		}
	 	
		switch (requestType)  {		
			case "json": 		
				var dijitID=divID;
				jsonRequest(ajaxRequestUrl, dijitID, formData);
				break;
			case "get": 
				// back-button: register state
			 	if (!dontRegister && IS_BACK_BUTTON_ACTIVE) {
			 		registerClick (requestType, directUrl, controller, ajaxType, ajaxAction, divID, formID);
			 	}
			 	ajaxGETRequest(ajaxRequestUrl, divID, controller, previewCat);
				break;
			case "post": 
				ajaxPOSTRequest(ajaxRequestUrl, divID, formData);
				break;
			case "cleanAll": 
				makeAllClean(true);
				IS_PROCESS_AJAX_ACTIVE=false;
				break;
			case "cleanPopup": 
				makePopupClean(true);
				IS_PROCESS_AJAX_ACTIVE=false;
				break;
			case "cleanDialog": 
				makeDialogClean(true);
				IS_PROCESS_AJAX_ACTIVE=false;
				break;
				
				
				/*	case "upload": 
				if (loaderRef) {
					initLoaders (loaderRef, loaderNewStyle);
				}
				var formDijit=dojo.byId(formID);
				ajaxFILEUpload (ajaxRequestUrl, divID, formDijit);
				break;
			case "articlePopup": 
				if (loaderRef) {
					initLoaders (loaderRef, loaderNewStyle);
				}
				var elementNodesCollection =  formNode.getElementsByTagName("input");
				ajaxPopupArticleRequest (ajaxRequestUrl, divID, formNode, elementNodesCollection);
				break; */	
			
		}		
	} catch (e) {
		handleCatchedErrror(e, 'processAjax');
	}
}


window.onerror = onWindowErrorHandler;

//dojo.connect(window, "onerror", this, "onWindowErrorHandler");

function initSmartReturnLogin (checkController, isPreview) {
	
	try {
		
		if (isPreview) {
			checkController = 'preview';
		}
		
		if (!checkController) {
			return;
		}
		
		
		
		
		if (checkController == 'agb' || checkController == 'impressum' || checkController == 'welcome' || checkController == 'register' || checkController == 'preview') {
			
			var login = dojo.byId ('login');
			var passwd = dojo.byId ('passwd');
			var loginForm = dijit.byId ('loginForm');
			
			if (!login || !passwd || !loginForm) {
				return;
			}
			
			// FIXME: BROKEN SIND RENDERING DIJOTS ONLOAD!
			/*login.setAttribute('autocomplete',"on");
			passwd.setAttribute('autocomplete',"on");*/
			
//			alert("done");
			
			//TrustLogo("/public/pics/redesign/propremiumssl3.gif", "SC4", "none");
			
			
			if (loginForm) {
				
			 	dojo.connect(loginForm.domNode, 'onkeypress', 
			        function(event) {
			 			
			            if (event.keyCode==dojo.keys.ENTER) {
			            	
			                //loginForm.execute(); 
			            	
			            	try {
			            		loginForm.submit();
			            	} catch (e) {
			            		var exceptionMessage= dumpObj(e,2);
			            		handleError('Return Button! ERROR', "exceptionMessage: "+exceptionMessage);
			            		//alert ("error catched"+exceptionMessage);	
			            	}
			            	 
			            }
			        }
			   	);
			}
		}
		
	} catch (e) {
		handleCatchedErrror(e, 'initSmartReturnLogin');
	}
	
}




function doOnSiteLoaded () 
{

	try {
		
		
		
		var isPreview=false;
		var url;
		if (urlTokenItems[1] == "preview") {
			url = '/preview/'+currentController;
			isPreview=true;
		}
	
		else if (urlTokenItems[0]) {
			url = '/'+currentController;
		}
		
		initSmartReturnLogin (currentController, isPreview);
		
		if (IS_BACK_BUTTON_ACTIVE) {
			var appState = new ApplicationState('get', url, null, null, null, 'ajax_multi_replace_node', 'formNode_init');
			dojo.back.setInitialState(appState);
		}
		
		initSlideShow();
		
		//eval (originalRequest.responseJSCalls);
		
		
		/*
		var dialogDijit_popup=dijit.byId('dialog_popup');
		
		dialogDijit_popup.show();
		
		var dialogDijit_dialog=dijit.byId('dialog_popup2');
		
		dialogDijit_dialog.show();
		
		
		var dialogDijit_dialog=dijit.byId('dialog_popup2');
		var test=dojo.byId('dialog_popup2');
		dojo.connect(dialogDijit_dialog, "onLoad", firetest);
		dialogDijit_dialog.show();
		dojo.connect(test, "onload", this, dialog_popup2_ONLOAD);
		//dojo.connect(null, "dialog_popup2_ONLOAD", function () {alert(221);});
		*/
		
		
		
		//dijit.byId('toast').setContent('VitaminP senkt die Preise! Jetzt Schlussverkauf!','fatal',5000);
	   //dijit.byId('toast').show();
		initSubnaviDescriptionSlider();
	} catch (e) {	
		handleCatchedErrror(e, 'doOnSiteLoaded');
	}
}



function insertSmilie (code) 
{
	try {
	 	var formName = "popupDescription";
	 	var formNameFound;
	 	// rich-text
	 	var myDijit = dijit.byId (formName);
	 	if (myDijit) {
	 		myDijit.setValue (myDijit.getValue()+code);
	 		return;
	 	}
	 	
	 	// standard-text
	 	dojo.query("textarea").forEach(
	    	function(inputElement)  {
	    		
	    		formNameFound=inputElement.getAttribute("name");
	    		
				if (formNameFound == formName) {
					
					formNode = inputElement;
					formNode.focus();
					formNode.value = formNode.value+code;
					formNode.focus();
				}	
			}	
	    );
	} catch (e) {
		handleCatchedErrror(e, 'insertSmilie');
	}
}

function fireForm (formName, ref) 
{
	
	
	try {
		//var x=e;
		var formDijit=dijit.byId(formName);
		if (formDijit) {
			formDijit.submit();
		} else {
			var formNode=dojo.byId(formName);
			if (formNode) {
				formNode.onsubmit();
			} else {
				
			}
		}
	} catch (e) {
		
		handleCatchedErrror(e, 'fireForm');
	}
} 


var IS_REDIR_IN_PROGRESS = false;
function helper_toastMessage (message, type, dontCleanOlds, duration) 
{
	try {
		
		functionsToCallOnLoad.push("helper_toastMessageREAL('"+message+"', '"+type+"', '"+dontCleanOlds+"', '"+duration+"')");
		
		/*if (!IS_REDIR_IN_PROGRESS) {
			helper_toastMessageREAL (message, type, dontCleanOlds, duration);
		} else {
			functionsToCallAfterRedirect.push("helper_toastMessageREAL('"+message+"', '"+type+"', '"+dontCleanOlds+"', '"+duration+"')");
		}*/
	} catch (e) {		
		handleCatchedErrror(e, 'helper_toastMessage');
		
	}
} 


function helper_toastMessageREAL (message, type, dontCleanOlds, duration) 
{
	//
	
	
	try {
		//if (toaster && !dontCleanOlds) {
		//	toaster.onSelect();
		//}
		if (!duration){
			duration="0";
		}
		if (!type) {
			type = "error";
		}
		dojo.publish("testMessageTopic", [{
			message: message, 
			type: type, 
			duration: duration }]
		);
	} catch (e) {
		handleCatchedErrror(e, 'helper_toastMessage');
	}
} 

function helper_clearContent (formElementNode) {
	try {
		if (formElementNode._resetValue==formElementNode.value) {
			formElementNode.attr('value', "");
		}
	} catch (e) {
		handleCatchedErrror(e, 'helper_clearContent');
	}
}

function helper_highlightLabels (divIDs, targetDivID, dontCleanOlds) 
{
	

	try {
		if (!dontCleanOlds) {
			dojo.forEach(
				dojo.query('span[id*="label_"]', dojo.byId(targetDivID)),
					function(node) {
								
					dojo.removeClass(node, "format_status_error");
				}
			);
		}
					
		
		divIDs = divIDs.split(',');
		for(var x = 0; x <= divIDs.length-1; x++){
			
	     	var node = dojo.byId (divIDs[x]);
	     	if (node) {
	     		//
	     		dojo.addClass(node, "format_status_error");
	     	}
		}
	} catch (e) {
		handleCatchedErrror(e, 'helper_highlightLabels');
	}
}

function helper_makeVisible (divIDs) 
{
	try {
		divIDs = divIDs.split(',');
		for(var x = 0; x <= divIDs.length-1; x++){
	     	dojo.byId (divIDs[x]).style.visibility="visible";
		}
	} catch (e) {
		handleCatchedErrror(e, 'helper_makeVisible');
	}
}

function helper_makeEnabled (divIDs) 
{
	try {
		divIDs = divIDs.split(',');
		var myDijit;	
		for(var x = 0; x <= divIDs.length-1; x++){
			myDijit= dijit.byId(divIDs[x]);
	     	if (myDijit.disabled) {
				myDijit.setAttribute('disabled',false);
			} else {
				myDijit.setAttribute('disabled',true);
			}
		}
	} catch (e) {
		handleCatchedErrror(e, 'helper_makeEnabled');
	}
}

function helper_fillDiv (content, divID) 
{
	try {
		content = decodeParam (content);
		fillDiv (content, divID);
	} catch (e) {
		handleCatchedErrror(e, 'helper_fillDiv');
	}
}

function helper_triggerFlvUpload (param) {
		
	
	try {
		swfUploadStart();
	} catch (e) {	
		handleCatchedErrror(e, 'helper_triggerFlvUpload');
	}
}

function flvUploadOnComplete () {
	
	try {
		
		helper_redirect('/files', true);
	} catch (e) {	
		handleCatchedErrror(e, 'flvUploadOnComplete');
	}
}


/*
function callFunctionsAfterRedirect () {
	
	//alert ("renderDijtsProgrammaticly");
	
	
	
	try {
		for (var i=0; i <= (functionsToCallAfterRedirect.length-1); i++) {
			
			eval (functionsToCallAfterRedirect[i]);
		}
		functionsToCallAfterRedirect = new Array();
	} catch (e) {
		handleCatchedErrror(e, 'callFunctionsAfterRedirect');
	}
}
*/



function callFunctionsAfterOnLoad () {
	
	//alert ("renderDijtsProgrammaticly");
	
	
	
	try {
		for (var i=0; i <= (functionsToCallOnLoad.length-1); i++) {
			
			eval (functionsToCallOnLoad[i]);
		}
		functionsToCallOnLoad = new Array();
	} catch (e) {
		handleCatchedErrror(e, 'callFunctionsAfterOnLoad');
	}
}

var functionsToCallOnLoad = new Array();
var functionsToCallAfterRedirect = new Array();
function helper_redirect (targetUrl, doItDirect) 
{	
	try {
		if (doItDirect || !IS_XHR_IN_PROGRESS) {
			window.location.href= targetUrl;
		} else {
			IS_REDIR_IN_PROGRESS=true;
			functionsToCallOnLoad.push("window.location.href ='"+targetUrl+"';");
		}
	} catch (e) {		
		handleCatchedErrror(e, 'helper_redirect');
	}
}

function helper_divInnerer (divID, directUrl) 
{
	try {
		functionsToCallOnLoad.push("processAjax ('get', '"+directUrl+"', null, null, null, '"+divID+"')");
	} catch (e) {
		handleCatchedErrror(e, 'helper_divInnerer');
	}
}
function helper_changeNaviAfterDispatchingFormwar (controller, previewCat) 
{
	try {
		functionsToCallOnLoad.push("changeMainNavigation ('"+controller+"', '"+previewCat+"');");
	} catch (e) {		
		handleCatchedErrror(e, 'helper_changeNaviAfterDispatchingFormwar');
	}
}
function helper_showPopup () 
{
	try {
		functionsToCallOnLoad.push("dijit.byId('dialog_popup2').show();");
	} catch (e) {
		handleCatchedErrror(e, 'helper_showPopup');
	}
}
function helper_showDialog (content) { //renderedJSON
	
	try {
		content = decodeParam (content);
		dojo.byId('dialog').innerHTML = content;
		functionsToCallOnLoad.push("dijit.byId('dialog_popup2').show();");
	} catch (e) {		
		handleCatchedErrror(e, 'helper_showDialog');
	}

	//functionsToCallOnLoad.push("dojo.byId('dialog').innerHTML('"+content+"')");
}

	


function uploadProgress(file, bytesLoaded, bytesTotal) 
{
	try {
		var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);
		alert(percent);
		file.id = "singlefile";	// This makes it so FileProgress only makes a single UI element, instead of one for each file
		var progress = new FileProgress(file, this.customSettings.progress_target);
		progress.setProgress(percent);
		progress.setStatus("Uploading...");
	} catch (e) {
		handleCatchedErrror(e, 'uploadProgress');
	}
}

function renderDijtsProgrammaticly () 
{
	
	
	
	var item;
	for (var i=0; i <= (dijitsToRenderOnLoad.length-1); i++) 
	{
		//alert ("loop"+i);
		item = dijitsToRenderOnLoad[i];

		
		
		// get css style, needed for dijit'ing
		var node = dojo.byId (item.nodeID);
		if (!node) {
			
		}		
		if (node && node.className) {
			item.props['class'] = node.className;
		}
		
		// function call via window[], because only string is available
		if (item.props.submit) {
			item.props.submit = new Function(item.props.submit);
		}
		
		var mydijit=null;
		
		// factory
		if (item.dijitClassName == 'dijit.form.TextBox') 
		{
			try {
				item.props.onClick = new Function(item.props.onClick);
				
				
				
				
				mydijit=new dijit.form.TextBox (item.props, item.nodeID);
				
				//item.props.autocomplete="on";
				//mydijit.setAttribute('autocomplete',"on");
				
				
				
				mydijit.startup();
			} catch (e) {
				handleCatchedErrror(e, 'renderDijtsProgrammaticly_TextBox');
			}
		} 
		else if (item.dijitClassName == 'dijit.form.CheckBox') {
			//
			//
			//
			//item.props.onClick = "alert(2);";
			
			try {
				item.props.onClick = new Function(item.props.onClick);
				mydijit=new dijit.form.CheckBox (item.props, item.nodeID);
				mydijit.startup();
			} catch (e) {
				handleCatchedErrror(e, 'renderDijtsProgrammaticly_CheckBox');
			}
			
		}
		else if (item.dijitClassName == 'dijit.form.NumberSpinner') {
			
			try {
				mydijit=new dijit.form.NumberSpinner (item.props, item.nodeID);
				mydijit.startup();
			} catch (e) {
				handleCatchedErrror(e, 'renderDijtsProgrammaticly_NumberSpinner');
			}
		}
		else if (item.dijitClassName == 'dijit.Editor') {
			
			try {
				mydijit=new dijit.Editor (item.props, item.nodeID);
				mydijit.startup();
				
			} catch (e) {
				handleCatchedErrror(e, 'renderDijtsProgrammaticly_Editor');
			}
			//dojo.query('#'+item.nodeID).orphan();
		}
		else if (item.dijitClassName == 'dijit.form.SimpleTextarea') {
			
			try {
				
				mydijit=new dijit.form.SimpleTextarea (item.props, item.nodeID);
				mydijit.startup();
				
				//setting value per props not working :(
				mydijit.setValue (item.props.value);
			} catch (e) {
				handleCatchedErrror(e, 'renderDijtsProgrammaticly_SimpleTextarea');
			}
			
		}
		else if (item.dijitClassName == 'dijit.TitlePane') {
			
			try {
				mydijit=new dijit.TitlePane (item.props, item.nodeID);
				mydijit.startup();
			
			} catch (e) {
				handleCatchedErrror(e, 'renderDijtsProgrammaticly_TitlePane');
			}
		}
		/*else if (item.dijitClassName == 'dojox.form.FileInputAuto') {
			
			item.props.onComplete = "alert(123);";
			item.props.onComplete = new Function(item.props.onChange);
			var mydijit=new dojox.form.FileInput (item.props, item.nodeID);
		}
		else if (item.dijitClassName == 'dojox.form.FileInput') {
			var mydijit=new dojox.form.FileInput (item.props, item.nodeID);
		}*/
		else if (item.dijitClassName == 'dijit.ProgressBar') {
			
			try {
				mydijit=new dijit.ProgressBar (item.props, item.nodeID);
				mydijit.startup();
			
			} catch (e) {
				handleCatchedErrror(e, 'renderDijtsProgrammaticly_ProgressBar');
			}
			
		}
		
		else if (item.dijitClassName == 'swfupload') 
		{
			
			
			try {
				item.props.swfupload_loaded_handler = new Function(item.props.swfupload_loaded_handler);
				item.props.file_queued_handler = window[item.props.file_queued_handler];
				item.props.file_queue_error_handler = window[item.props.file_queue_error_handler];
				item.props.file_dialog_complete_handler = window[item.props.file_dialog_complete_handler];
				
				item.props.upload_progress_handler = window[item.props.upload_progress_handler];
				item.props.upload_error_handler = window[item.props.upload_error_handler];
				item.props.upload_success_handler = window[item.props.upload_success_handler];
				item.props.upload_start_handler = window[item.props.upload_start_handler];
				
	//			item.props.upload_complete_handler =window[item.props.upload_complete_handler];
				item.props.upload_complete_handler =new Function(item.props.upload_complete_handler);
				
				item.props.button_window_mode = SWFUpload.WINDOW_MODE.TRANSPARENT;
				item.props.button_cursor = SWFUpload.CURSOR.HAND;
				
				/*item.propsbutton_placeholder_id = "swfuploadButtonPlaceHolder";
				item.propsbutton_image_url = "../images/swfupload/button.jpg";
				item.propsbutton_width = "216";
				item.propsbutton_height = "25";*/
				
				swfu = new SWFUpload(item.props);
				
			} catch (e) {
				handleCatchedErrror(e, 'renderDijtsProgrammaticly_swfupload');
			}
		}
		
		else if (item.dijitClassName == 'dojox.form.FileUploader') 
		{
			try {
		
				var buttonName= "btn0";
				var buttonProps = {
					name:buttonName,
					label:"Datei auswÃ¤hlen"
				};
				
				//var button = new dijit.form.Button (buttonProps, buttonName);
				//dojo.attr (dojo.byId("buttonName"), 'widgetId', buttonName);
				//item.props.button = button;
				
				item.props.uploadUrl = '/public/upload.php';
				
				mydijit=new dojox.form.FileUploader (item.props, item.nodeID);
				mydijit.startup();
			
			} catch (e) {
				handleCatchedErrror(e, 'renderDijtsProgrammaticly_FileUploader');
			}
		}
		else if (item.dijitClassName == 'dijit.form.Form') {
			//alert(item.dijitClassName+" _ "+item.nodeID);
			try {
				
				// item.nodeID
				
				item.props.onSubmit = new Function(item.props.onSubmit);				
				mydijit=new dijit.form.Form (item.props, item.nodeID);
				mydijit.startup();
				/*if (item.nodeID =="fileUploadForm") {
					var myNode = dojo.byId(item.nodeID);
					
					dojo.attr (myNode, 'enctype', 'multipart/form-data');
					dojo.attr (myNode, 'type', 'POST');
				}*/
			} catch (e) {
				
				handleCatchedErrror(e, 'renderDijtsProgrammaticly_Form');

			}
		} 
		else if (item.dijitClassName == 'dojox.layout.ContentPane') {
			
			try {
				mydijit=new dojox.layout.ContentPane (item.props, item.nodeID);
				mydijit.startup();
		
			} catch (e) {
				handleCatchedErrror(e, 'renderDijtsProgrammaticly_ContentPane');
			}
		} 

		else if (item.dijitClassName == 'dijit.layout.ContentPane_TabContainerChild') {
			
			try {
				mydijit=new dijit.layout.ContentPane (item.props, item.nodeID);
				var tabContainer = dijit.byId("tabContainer");
				tabContainer.addChild(mydijit);
				mydijit.startup();

			} catch (e) {
				handleCatchedErrror(e, 'renderDijtsProgrammaticly_ContentPane_TabContainerChild');
			}
            
		} 
		else if (item.dijitClassName == 'dijit.layout.TabContainer') {
			
			try {
				mydijit=new dijit.layout.TabContainer (item.props, item.nodeID);
				mydijit.startup();
			
			} catch (e) {
				handleCatchedErrror(e, 'renderDijtsProgrammaticly_TabContainer');
			}

		} 
		
		else if (item.dijitClassName == 'dijit.form.FilteringSelect') {
			
			try {
				
			
				//item.props.onChange ="alert(123)"; 
				//item.props.onChange ='fireForm("groupselect2", this)'; 
				item.props.onChange = new Function(item.props.onChange);
				item.props.width="200px";
				mydijit = new dijit.form.FilteringSelect (item.props, item.nodeID);
				mydijit.startup();
				//
				
				if (item.props.setValue) {
					mydijit.attr ('value', item.props.setValue);
				}
				
			} catch (e) {
				handleCatchedErrror(e, 'renderDijtsProgrammaticly_FilteringSelect');
			}
		}
		else if (item.dijitClassName == 'dojox.widget.Dialog') {
			
			item.props.dimensions= [638,317];
			item.props.sizeDuration = 800;
			item.props.sizeMethod = "combine";
			item.props.easing = dojo.fx.easing.backOut;			
			
			mydijit=new dojox.widget.Dialog (item.props, item.nodeID);
//			mydijit=new dijit.Dialog (item.props, item.nodeID);
			mydijit.startup();
			
		} 	
		
		else if (item.dijitClassName == 'dijit.Dialog') {
			
			try {
				if (item.nodeID == 'dialog_popup2' && dialog2Title) {
					item.props.title = dialog2Title;
					dialog2Title = null;
				}
				
			} catch (e) {
				handleCatchedErrror(e, 'renderDijtsProgrammaticly_Dialog');
			}
			
			mydijit=new dijit.Dialog (item.props, item.nodeID);
			mydijit.startup();
		} 	
		else if (item.dijitClassName == 'dijit.form.DateTextBox') {
			
			try {
				item.props.value= new Date(item.props.value);
				mydijit=new dijit.form.DateTextBox (item.props, item.nodeID);
			} catch (e) {
				handleCatchedErrror(e, 'renderDijtsProgrammaticly_DateTextBox');
			}
		} 	
		
		
		
		
		else if (item.dijitClassName == 'dojox.grid.DataGrid') {
			
			
			try 
			{
				var layoutCountries = [ 
	       			{ cells: [ new dojox.grid.cells.RowIndex({width: 5}) ], noscroll: true}, 
	       			[ 
	       				{ name: "field 0", field: 'name', width: 8 }, 
	       				{ name: "field 1", field: 'type', width: 8 } 
	       			]
	       		];
				
	       		
	       		var emptyData = { identifier: 'name', label: 'name', items: []}; 
	       		var jsonStore = new dojo.data.ItemFileWriteStore({data: emptyData, jsId: 'jsonStore'} ); 
	       		var numItems = 0;
				
				item.props.structure = layoutCountries;
				item.props.store = jsonStore;
				//
				mydijit=new dojox.grid.DataGrid (item.props, document.createElement('div'));	// , item.nodeID
				
				
		        
		                
		        var row_array = new Array();
	            var grp_id = "asdasdasdasdasdasdasd";
	            row_array[0] = "0";
	            row_array[1] = "Test";
	            row_array[2] = "test group";       
	            
	            dojo.byId("grid").appendChild(mydijit.domNode);
	            
	            mydijit.startup();
				
				mydijit.addRow(row_array,1);
				
				//mydijit.render();
	            
				numItems++; 
				jsonStore.newItem({
					name: numItems + "-person Land", 
					type: "city", 
					population: numItems
				}); 
				
		
			} catch (e) {
				handleCatchedErrror(e, 'renderDijtsProgrammaticly_DataGrid');
			}
		
		}
	}
	dijitsToRenderOnLoad = new Array();	
}


function triggerDialog (controller, ajaxAction, doItDirect) 
{
	try {
		if (doItDirect || !IS_XHR_IN_PROGRESS) {
			processAjax ('get', null, controller, 'dialog', ajaxAction, 'dialog');
		} else {
			functionsToCallOnLoad.push("processAjax ('get', null, '"+controller+"', 'dialog', '"+ajaxAction+"', 'dialog');");
		}
	} catch (e) {
		handleCatchedErrror(e, 'triggerDialog');
	}
}

var dijitsToRenderOnLoad = new Array();
function dijitControl_buildDijits (dijitClassName, opt, nodeID) 
{
	try {
		var dijit = {
			dijitClassName: dijitClassName,
			props: opt,
			nodeID: nodeID
		};
		dijitsToRenderOnLoad.push(dijit);
	} catch (e) {		
		handleCatchedErrror(e, 'dijitControl_buildDijits');
	}
}
function dijitControl_setChecked (state, dijitID, divID) 
{
	try {
		if (dijitID=='all') 
		{
			dojo.forEach(
			dojo.query('input[type=\"checkbox\"]', document.getElementById(divID)),		//type='checkbox'
			function(widget) {
		      	var widgetId=widget.id;
		      	if (dijit.byId(widgetId)) {
		      		dijit.byId(widgetId).setChecked(false); 
		      	} 
			} ); 
		}
	} catch (e) {
		handleCatchedErrror(e, 'dijitControl_setChecked');
	}
}   	


var dialog2Title ="";
function dijitControl_setTitle (title, dijitID) 
{
	
	
	
	try {
		var myDijit= dijit.byId (dijitID);
		if (myDijit) {
			
			myDijit.titleNode.innerHTML=title;
		}
		else {
			if (dijitID == 'dialog_popup2') {
				dialog2Title=title;
			}
			//var titleNode = dojo.byId(dijitID+"_title");
			//
		}
	} catch (e) {
		handleCatchedErrror(e, 'dijitControl_setTitle');
	}
}





function percentager_new_change_percentage(task_id, new_percentage) 
{
	try {
		processAjax ('get', '/tasks/percentage/'+task_id+'/'+new_percentage, null, null, null, 'ajax_multi_replace_node', null, true);
	} catch (e) {		
		handleCatchedErrror(e, 'percentager_new_change_percentage');
	}
} 

function percentager_new_over_percentage(linkNodeRef, value, taskIDVIR, isPopup) 
{
	try {
		
		var nodePercentager=linkNodeRef.parentNode;
		nodePercentager.className = 'button_percentage_'+value;
		
		var percentagePostfix="";
		if (isPopup) {
			percentagePostfix="popup_";
		}
		var textNode = dojo.byId ("percentage_current_percentage_"+percentagePostfix+taskIDVIR);
		textNode.innerHTML = value+"%";
		
	} catch (e) {		
		handleCatchedErrror(e, 'percentager_new_over_percentage');
	}	
}




 
 function changeMainNavigation (controller, previewCat) {
 
	 //
	 //
	 //
 	
	try {
		if (previewCat) {
	 		controller=  previewCat;
	 	}
		
			
	 	//
	 	// menu-mappings
		var navigationMappings = new Array();
		navigationMappings['controlproject'] = 'controlcenter'; 
		navigationMappings['statistics'] = 'overview'; 
		navigationMappings['support'] = 'overview'; 
		navigationMappings['register'] = 'welcome'; 
		navigationMappings['impressum'] = 'welcome'; 
		navigationMappings['agbs'] = 'welcome'; 
		
		//var navigationMappings = new Array('welcome', 'statistic', 'todos', 'writeboard', 'tasks', 'calendar', 'email', 'team', 'files', 'controlcenter');
			
		//
		//
			
		// change main navigation via js
		if ( (currentController != controller) && controller) {
			var currentControllerTMP;
			if (navigationMappings[currentController]) {
				//
				currentControllerTMP = navigationMappings[currentController];
			}
			else {
				currentControllerTMP = currentController;
				//
			}
				
			var controllerTMP;
			if (navigationMappings[controller]) {
				controllerTMP = navigationMappings[controller];
			}
			else {
				controllerTMP = controller;
			}
			
			
			
			if (currentControllerTMP != controllerTMP) { 
				
				/*var navNodeNew = dojo.byId ('nav_item_'+controllerTMP);
	 			if (!navNodeNew) {
	 				
	 				return;
	 			}*/
	 			
	 			//if (!navNodeOld || !navNodeNew) {
	 			//	
	 			//	return;
	 			//}
	 			
				// if its preview mode, we've to disbale _active_lo style instead of _active!
				var stylePostfix ="";
				if (currentPreviewSection) {
					stylePostfix ="_lo";	
					//
				} 
			
				// inactivate old one
				var currentNode = dojo.byId('nav_item_'+currentControllerTMP);
				
				if (currentControllerTMP != "welcome" && currentNode) {
//					
					if (currentControllerTMP=="controlcenter" || currentControllerTMP=='overview') {
						dojo.removeClass (currentNode, 'main_nav_item_'+currentControllerTMP+'_active'+stylePostfix);
						dojo.addClass (currentNode, 'main_nav_item_'+currentControllerTMP);
						
					}
					else {
						dojo.removeClass (currentNode, 'main_nav_item_active'+stylePostfix);
						dojo.addClass (currentNode, 'main_nav_item');	
					}
					
					
					//dojo.removeClass (currentNode, 'main_nav_item_'+currentControllerTMP+stylePostfix);
					
					//dojo.addClass (currentNode, 'main_nav_item_'+currentControllerTMP);	
				}
	 			
	 			// activate new one
	 			var comingNode = dojo.byId('nav_item_'+controllerTMP);
	 			if (comingNode) {
	 				
	 				if (controllerTMP=="controlcenter"  || controllerTMP=='overview') {
	 					dojo.removeClass (comingNode, 'main_nav_item_'+controllerTMP);
	 					dojo.addClass (comingNode, 'main_nav_item_'+controllerTMP+'_active'+stylePostfix);	
	 				}
	 				
	 				else {
	 					dojo.removeClass (comingNode, 'main_nav_item_'+stylePostfix);
	 					dojo.addClass (comingNode, 'main_nav_item_active'+stylePostfix);	
	 				}
	 				
//	 	 			
	 	 			
	 			}
	 			
	 			// set currentController
	 			//dojo.style ('nav_item_'+controller, 'cursor', 'crosshair');
	 			currentController = controller;
	 		}
	 	}
	} catch (e) {
		handleCatchedErrror(e, 'changeMainNavigation');
	}
}
 
 
function buildAjaxRequestUrl(directUrl, controller, ajaxType, ajaxAction) 
{

	try {
		var prefix="";
		
		var ajaxRequestUrl;
		if (!directUrl) {
			ajaxRequestUrl = prefix+"/"+controller+"/ajax/"+ajaxType+"/"+ajaxAction;	// single-ajax
		} else {
			ajaxRequestUrl = prefix+directUrl;											// multi-ajax
		}
	} catch (e) {		
		handleCatchedErrror(e, 'buildAjaxRequestUrl');
	}
	//alert ("ajaxRequestUrl: "+ajaxRequestUrl);
	return ajaxRequestUrl;
}


	
var isIn = true;

function initSubnaviDescriptionSlider () 
{
	try {
		var subnaviDescriptionID = dojo.byId("button_corner");
		if (subnaviDescriptionID) {
			dojo.connect(subnaviDescriptionID,"onmousedown","slideSubnaviDescription");
		}
		var subnaviDescriptionOnOff = dojo.byId("subnavi_description_on_off");
		if (subnaviDescriptionOnOff) {
			dojo.connect( subnaviDescriptionOnOff,"onmousedown","slideSubnaviDescription");
		}
	} catch (e) {
		handleCatchedErrror(e, 'initSubnaviDescriptionSlider');
	}
}

var slideSubnaviDescription = function() 
{
	try {
		var left=33;
		var top=-162;
	
		if (isIn) {
			top=0;
			isIn=false;
		} else {
			top=-162;
			isIn=true;
		}
		
		var movingTarget= dojo.byId("subnavi");
		dojo.fx.slideTo({
			node: movingTarget,
			duration: 500,
			left: left,
			top: top
		}).play();
	} catch (e) {
		handleCatchedErrror(e, 'slideSubnaviDescription');
	}	
};

function initSlideShow () {

	// NOt IN USE;
	return;
	
	
	//var myJsonStore = new dojo.data.ItemFileReadStore( {  id:'jsonStore', data: items } );
	/*
	
	var myWelcomeSlideshow = dijit.byId ('welcomeSlideshow');
	
	//myWelcomeSlideshow.setDataStore(myJsonStore);
	var myJsonStore = dijit.byId ('welcomeSlideshowItemStore');
	
	
	
	
	var myWelcomeSlideshow = dijit.byId('welcomeSlideshow');
	if (myWelcomeSlideshow) {
		myWelcomeSlideshow.setDataStore(welcomeSlideshowItemStore,
		{ query: {}, count:20 },
		{
			imageThumbAttr: "thumb",
			imageLargeAttr: "large"
		}
	);
	}
	*/
}


var GLOBAL_LOADER_INTERVAL;
var GLOBAL_LOADER_SITE_HAS_LOAD;
var GLOBAL_LOADER_LATENCY=700;
// div that is to follow the mouse
var divName = 'mouse_status'; 	
// X offset from mouse position
var offX = -10;          		
// Y offset from mouse position
var offY = -4;          		

function initLoaders (loaderRef, loaderNewStyle)  
{
	if (!loaderRef) {
		alert ("HEY; INIT LOADER WITHOUT LOADERREF? = "+loaderRef);
	}
	try {
		GLOBAL_LOADER_SITE_HAS_LOAD = false;
		GLOBAL_LOADER_INTERVAL = setInterval(startLoaders,GLOBAL_LOADER_LATENCY, { 
			loaderRef: loaderRef,
			loaderNewStyle:loaderNewStyle 
		});
	} catch (e) {
		handleCatchedErrror(e, 'initLoaders');
	}
}

function startLoaders (evtObj) 
{	
	try {
		clearInterval (GLOBAL_LOADER_INTERVAL);
		
		if (GLOBAL_LOADER_SITE_HAS_LOAD) {
			return;
		}
	
 		if (evtObj.loaderRef) {
 			var oldClassName=evtObj.loaderRef.className;
 			dojo.removeClass (evtObj.loaderRef, oldClassName);
 			dojo.addClass (evtObj.loaderRef, evtObj.loaderNewStyle);
 		}
 		else {
 			document.onmousemove = follow;
 		}
	} catch (e) {
		handleCatchedErrror(e, 'startLoaders');
	}
}

function mouseX(evt) 
{
	try {
		if (!evt) {
			evt = window.event;
		} 
		if (evt.pageX) {
			return evt.pageX;
		} else {
			if (evt.clientX) {
				return evt.clientX + (document.documentElement.scrollLeft ?  document.documentElement.scrollLeft : document.body.scrollLeft);
			} else {
				return 0;
			}
		}
	} catch (e) {		
		handleCatchedErrror(e, 'mouseX');
	}
	return null;
}

function mouseY(evt) 
{
	try {
		if (!evt) {
			evt = window.event;
		} 
		if (evt.pageY) {
			return evt.pageY;
		} else if (evt.clientY) {
			return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
		} else {
			return 0;
		}
	} catch (e) {
		handleCatchedErrror(e, 'mouseY'); 
	}
	return null;
}

function follow(evt) 
{
	try {
		if (document.getElementById) {
			var node = dojo.byId(divName);
			if (node) {
				var obj = node.style; 
				obj.visibility = 'visible';
				obj.left = (parseInt(mouseX(evt))+offX) + 'px';
				obj.top = (parseInt(mouseY(evt))+offY) + 'px';	
			}
		}
	} catch (e) {
		handleCatchedErrror(e, 'follow');
	}
}

function mouseLoaderStop() 
{
	try {
		GLOBAL_LOADER_SITE_HAS_LOAD=true;
		document.onmousemove = null;
		dojo.byId(divName).style.visibility = 'hidden';
	} catch (e) {	
		handleCatchedErrror(e, 'mouseLoaderStop');
	}
}


var MAX_DUMP_DEPTH = 2;

function dumpObj(obj, name, indent, depth) {
	if (depth > MAX_DUMP_DEPTH) {
		return indent + name + ": <Maximum Depth Reached>\n";
	}
	if (typeof obj == "object") {
		var child = null;
        var output = indent + name + "\n";
        indent += "\t";
        for (var item in obj)
        {
        	try {
        		child = obj[item];
        	} catch (e) {
                 child = "<Unable to Evaluate>";
               }
               if (typeof child == "object") {
                      output += dumpObj(child, item, indent, depth + 1);
               } else {
                      output += indent + item + ": " + child + "\n";
                       }
                 }
                 return output;
          } else {
                 return obj;
          }
   }
 

function handleError (title, text, throwSilent) 
{
	alert(title+text);	
	if (text.length > 6000) {
		text = text.substring(0, 6000);
	}
	
	text = "\nPROCESS_AJAX_CLICKS_WHILE_XHR_ACTIVE: "+PROCESS_AJAX_CLICKS_WHILE_XHR_ACTIVE+" \n"+text;
	
	if (!throwSilent)  {
		mouseLoaderStop();
		IS_XHR_IN_PROGRESS=false;
		IS_PROCESS_AJAX_ACTIVE=false;
	}
	
	
	if (isDebug) {
		
				
	}
	else {
		var msg = encodeURI (title+" -> "+text);
		
		if (throwSilent) {
			if (typeof(dojo) != "object") { 
				helper_redirect ('/exception/js?msg=HARDERROR_SILENT'+msg, true);
				alert ("Es ist ein schwerer Javascript-Fehler aufgetreten. Wahrscheinlich konnten wir den Fehler nicht Ã¼bermitteln. Bitte sei so gut und benachrichtige uns kurz per mail an support@vitap.de Ã¼ber den Fehler. Dankeeee.");
			}
			else {
				dojo.xhrGet( {
			       	url: '/exception/js?msg=ERROR_SILENT'+msg,
			       	timeout: 15000 
			  	} );	
			}
		}
		else {
			if (typeof(dojo) != "object") {
				helper_redirect ('/exception/js?msg=ERROR_HARD'+msg, true);
				alert ("Es ist ein schwerer Javascript-Fehler aufgetreten. Wahrscheinlich konnten wir den Fehler nicht Ã¼bermitteln. Bitte sei so gut und benachrichtige uns kurz per mail an support@vitap.de Ã¼ber den Fehler. Dankeeee.");
				
			} else {
				helper_redirect ('/exception/js?msg=ERROR'+msg, true);
				alert ("Achtung. \nEs ist leider ein Javascript-Fehler aufgetreten.\nIn diesem Moment schicken wir die Fehlermeldung an unseren Server.");	
			}
		}
		//alert ("Wichtig-Wichtig-Wichtig\nBitte diese Meldung erst wegklicken wenn die Fehlermeldug geladen wurde. Danke.");
		
	// does not work, must be ajax'ble 
	//helper_divInnerer ('ajax_multi_replace_node', '/error/js?msg='+msg);
	}
	
	if (throwSilent) {
		return true;
	}
	else {
		return false;
	}
}


function handleCatchedErrror(e, functionName) 
{
	//alert ("handleCatchedErrror in "+functionName);
	
	var errorObj = {
		msg:e.message, 
		name:e.name, 
		description:e.description, 
		number:e.number,
		stack:e.stack,
		fileName:e.fileName,
		lineNumber:e.lineNumber
	}
	
	errorObj = wrapErrorsMetaData (errorObj);
	var exceptionMessage= dumpObj(errorObj);
    handleError ('handleCatchedErrror IN '+functionName, exceptionMessage);
    return true;
}

function onWindowErrorHandler(msg, url, line) 
{
	//alert ("onWindowErrorHandler");
	var errorObj = {msg:msg, url:url, line:line}
	errorObj = wrapErrorsMetaData (errorObj);	
    var exceptionMessage= dumpObj(errorObj);
    handleError ('onWindowErrorHandler', exceptionMessage);
	return true;
}


function wrapErrorsMetaData (errorObj) {
    errorObj.JsErrorAppcode = navigator.appName;
    errorObj.Browser = navigator.appVersion;
    errorObj.BrowserVersion = navigator.appCodeName;
    errorObj.UserAgent = navigator.userAgent;
    errorObj.Referer = document.referer;
    return errorObj;
}



ApplicationState = function(requestType, directUrl, controller, ajaxType, ajaxAction, divID, formNode) {	
		
	try {
		var ajaxRequestUrl="";
		if (!directUrl) {
			ajaxRequestUrl = "/"+controller+"/ajax/"+ajaxType+"/"+ajaxAction;
		} else {
			ajaxRequestUrl = directUrl;
		}
		
		this.requestType = requestType;
		this.directUrl = directUrl;
		this.controller = controller;
		this.ajaxType = ajaxType;
		this.ajaxAction = ajaxAction;
		this.divID = divID;
		
		
		this.formNode = formNode;
		
		if (ajaxRequestUrl == 'directUrl_init') {
			this.changeUrl = null;
		} else {
			this.changeUrl = ajaxRequestUrl.replace (/\//g, '_')  || false;
		}
		
	
		this.back = function(){
			handleClickBackward (this.requestType, this.directUrl, this.controller, this.ajaxType, this.ajaxAction, this.divID, this.formNode );
		},
		this.forward= function(){
			handleClickBackward (this.requestType, this.directUrl, this.controller, this.ajaxType, this.ajaxAction, this.divID, this.formNode );
		}
		,
		this.showStateData= function(){
			//
		},
		this.showBackForwardMessage= function(message){
			//
		};
	} catch (e) {		
		handleCatchedErrror(e, 'ApplicationState');
	}
}
		
function registerClick (requestType, directUrl, controller, ajaxType, ajaxAction, divID, formNode) 
{
	
	
	try {
		if (controller == undefined) {
			controller="no";
			//return;
		}
		
		
		var appState = new ApplicationState(requestType, directUrl, controller, ajaxType, ajaxAction, divID, formNode);
		//
	
		//FIXME BUG	
		dojo.back.addToHistory(appState);
		
	} catch (e) {		
		handleCatchedErrror(e, 'registerClick');
	}
}

function handleClickBackward (requestType, directUrl, controller, ajaxType, ajaxAction, divID, formNode)   
{
	
	try {
		processAjax (requestType, directUrl, controller, ajaxType, ajaxAction, divID, formNode, true);
	} catch (e) {
		handleCatchedErrror(e, 'handleClickBackward');
	}
}


function dispatchHiddenFields (formNode) 
{
	try {
		var hiddenFields = new Array();
  
		var hiddenFieldCollection =  formNode.getElementsByTagName("input");

		for (var i = 0; i <= hiddenFieldCollection.length-1;  i++) {
			var currentHiddenField = new Object();
			currentHiddenField.name = hiddenFieldCollection[i].getAttribute("name");
			currentHiddenField.value = hiddenFieldCollection[i].getAttribute( "value");
			currentHiddenField.toString = function() { return "["+this.name + "="+this.value + "]";};
			hiddenFields.push(currentHiddenField);	
		}
	} catch (e) {
		handleCatchedErrror(e, 'dispatchHiddenFields');
	}
	return hiddenFields;
}


function decodeParam (encodedParam) 
{
	try {
		var decodedResponseJSCalls = decodeURIComponent (encodedParam);
	} catch (e) {	
		handleCatchedErrror(e, 'decodeParam');
	}
	return decodedResponseJSCalls;		
}
		
function fillDiv (originalRequest,divID)   
{

	try {
		mouseLoaderStop();
	
		//
		//
		if (originalRequest.responseJSCalls) {
			eval (originalRequest.responseJSCalls);
			if (originalRequest.responseJSHaltAfter) {
				//
				return;
			}	
		}
		
		// if divID ist switching by json, we've to watch out
		// for cleaning the original one if popup or dialog :D
		if (originalRequest.divID) {
			divID = originalRequest.divID;	// testing! was before 5 lines under
			
			if (divID == 'popup') {
				makePopupClean(true);
			}
			else if (divID == 'dialog')  {
				makeDialogClean(true);
			}
			
			
		}
		
		
		if (!divID)  {
			return;
		}
		if (originalRequest.html) {
			originalRequest=originalRequest.html;
		}
		
		lastAjaxFilledDivID = divID;
		
			
		//if (divID != 'mainDebugMessages_content' && divID != 'ajaxTemplateErrors_content' && divID != 'mainDebugMessages_content') 
		destroyAllWidgetsByNode(divID);
		
		
		
		var dijitNode = dijit.byId(divID);
		if (dijitNode) {
			//dijitNode.setContent (originalRequest); // depricated
			dijitNode.attr('content', originalRequest);
			//dijitNode.setHref ("/test.html");
		} 
		else {
			//	
			
			var node = dojo.byId(divID);
			if (!node) {
				
			}
			else {
				node.innerHTML = originalRequest;
			}
		}
		
		if (divID == 'ajax_multi_replace_node') {
			renderDijtsProgrammaticly();
		}
		else if (divID == 'popup') {
			renderDijtsProgrammaticly();
			
			dijit.byId('dialog_popup').show();
		} 
		else if (divID == 'popupPartial') {
			renderDijtsProgrammaticly();
		} 
		else if (divID == 'dialog') {
			renderDijtsProgrammaticly();
			dijit.byId('dialog_popup2').show();
		} else if (divID == 'contactdata') {
			renderDijtsProgrammaticly();
		} else if (divID == 'projectsections') {
			renderDijtsProgrammaticly();
		} else if (divID == 'subscribers') {
			renderDijtsProgrammaticly();
		} else if (divID == 'userpic_upload_node') {
			renderDijtsProgrammaticly();
		} else if (divID == 'invitation') {
			renderDijtsProgrammaticly();
		}

		//if (node) dojo.parser.parse(node);
		initSubnaviDescriptionSlider(true);
	
	} catch (e) {		
		handleCatchedErrror(e, 'fillDiv');
	}
	
}



/****** CLEANERS ******/
function destroyAllWidgetsByNode (divID) 
{
	try {
		
		//nsole.log ("destroy start");
		var test = dojo.byId(divID);
		//
		//
		dojo.forEach(
			dojo.query('*[widgetId]', dojo.byId(divID)),
			function(widget) {
		    	//var widgetId=widget.id.substring(7);	// widget.widgetid; trim the "widget_" prefix off of the id
		      	var widgetId=widget.id;
		      	
		      	//
		      	var currentDijit = dijit.byId(widgetId);
		      	if (currentDijit) {
		      		currentDijit.destroyRecursive();
		      			
		      	}
		    }
		);
		
	} catch (e) {
		handleCatchedErrror(e, 'destroyAllWidgetsByNode');
	}
		//
	
}



function makePopupClean ()  
{
	
	
	try {
		var dialogDijit = dijit.byId('dialog_popup');
		if (dialogDijit) {
			dialogDijit.hide();
			//destroyAllWidgetsByNode('popup');		// WE DONT NEED THIS ANYMORE! - SO while CLOSING FADING OUT CONTENT STILL EXISTS
		} 
		else {
			
		}
		
		
		var dialogDijitNew = dijit.byId('dialog_popup_new');
		if (dialogDijitNew) {
			dialogDijitNew.hide();
		} 
		
	} catch (e) {
		handleCatchedErrror(e, 'makePopupClean');
	}
}

function makeDialogClean () 
{
	try {
		var dialogDijit = dijit.byId('dialog_popup2');
		if (dialogDijit) {	
			dialogDijit.hide();
		}
		else {
			
		}
	} catch (e) {
		handleCatchedErrror(e, 'makeDialogClean');
	}
}

function makeAllClean ()  {
	try {
		makePopupClean ();
		makeDialogClean ();
	} catch (e) {		
		handleCatchedErrror(e, 'makeAllClean');
	}
}
	

var REDIRECT_TARGET_AFTER_XHR_COMPLETE=null;
var IS_XHR_IN_PROGRESS=false;
var CURRENT_XHR_CONNECTION=null;
function checkIfToRedirectAfterXhrComplete(divID, controller, previewCat) 
{
	try {
		if (REDIRECT_TARGET_AFTER_XHR_COMPLETE) {
				
			location.href = REDIRECT_TARGET_AFTER_XHR_COMPLETE;
			REDIRECT_TARGET_AFTER_XHR_COMPLETE=null;
		}
		IS_XHR_IN_PROGRESS=false;
		IS_PROCESS_AJAX_ACTIVE=false;
		CURRENT_XHR_CONNECTION=null;
		PROCESS_AJAX_CLICKS_WHILE_XHR_ACTIVE=0;
		callFunctionsAfterOnLoad();
		
		initSmartReturnLogin(controller, previewCat);
		
	} catch (e) {		
		handleCatchedErrror(e, 'checkIfToRedirectAfterXhrComplete');
	}
}
// currently used for highshool-choice
function jsonRequest (requestUrl, dijitID, formData)   
{	
	
	try {
		var myDijit= dijit.byId (dijitID);
		IS_XHR_IN_PROGRESS=true;
		CURRENT_XHR_CONNECTION = dojo.xhrPost( {
	        url: requestUrl,
	        headers: { "X_REQUESTED_WITH": "XMLHttpRequest" },
	        handleAs: "json",
	        timeout: 15000, 
			content: formData,
	        load: function(response, ioArgs)  {
	        	
	        	//
	        	//
	        	dijitID= dijitID+"_";
	        	//
	        	//
	        	
	        	
	       		fillDiv(response);
	       		
	       		
	       		
	       		if (myDijit) {
	       			
//	       			myDijit.attr('displayedValue', "test");
	       			
	       			var data = response.responseJSJsonData;
					var jsonstore = new dojo.data.ItemFileReadStore( {  id:'jsonStore', data: data } );
					myDijit.store = jsonstore;
					
	       			//
					//
	
					myDijit.attr('_onChangeActive', false);
					myDijit.attr('value', 0);
					myDijit.attr('_onChangeActive', true);
					
					//myDijit.attr('onChange', oldOnChange);
					
		        	//myDijit.setDisplayedValue('Bitte Auswahl treffen');
		        	
		        	//myDijit.attr('displayedValue', 'Bitte wÃ¤hlen');
					//myDijit.parse();
		        	//return;
	       		}
	        	checkIfToRedirectAfterXhrComplete();
	        	
	        	
	        	
	        	return response;
			},
	        error: function(response, ioArgs)  {
				if (response.message="xhr cancelled") {
	        		return null;
	        	}
				var exceptionResponeMessage= dumpObj(response, 2);
				var exceptionIOMessage= dumpObj(ioArgs,2);
	        	handleError('jsonRequest '+ioArgs.xhr.statusText+" // exceptionResponeMessage: "+exceptionResponeMessage+" // exceptionIOMessage: "+exceptionIOMessage, response.message);
	        	return response;
	        }
	  	} );		
	} catch (e) {		
		handleCatchedErrror(e, 'jsonRequest');
	}
}

function ajaxGETRequest (requestUrl, divID, controller, previewCat)  
{		
	try {
		if (requestUrl == "") {
			dojo.byId(divID).innerHTML = "no requestUrl found";
			return;
		}
		
		IS_XHR_IN_PROGRESS=true;
		CURRENT_XHR_CONNECTION = dojo.xhrGet( {
	       	url: requestUrl,
	       	headers: { "X_REQUESTED_WITH": "XMLHttpRequest" }, 
	       	handleAs: "json",
	       	timeout: 15000, 
	       	load: function(response, ioArgs) {
				
	       		
	       		// goto navigation change proceedure if multi-ajax 
	       		if (divID=='ajax_multi_replace_node' && (controller|| previewCat)) {
	       			changeMainNavigation (controller, previewCat);
	       		}
	       		
	       		fillDiv(response, divID);
				
				checkIfToRedirectAfterXhrComplete(divID, controller, previewCat);
				
				
	          	return response;
	        },
	        error: function(response, ioArgs) {
	        	
	        	if (response.message="xhr cancelled") {
	        		return null;
	        	}
	        	var exceptionResponeMessage= dumpObj(response, 2);
				var exceptionIOMessage= dumpObj(ioArgs,2);
	        	handleError('ajaxGETRequest '+ioArgs.xhr.statusText+" // exceptionResponeMessage: "+exceptionResponeMessage+" // exceptionIOMessage: "+exceptionIOMessage, response.message);
	        	//handleError('ajaxGETRequest '+ioArgs.xhr.statusText, response.message);
	        	return response;
	        }
	  	} );	
	} catch (e) {
		handleCatchedErrror(e, 'ajaxGETRequest');
	}
}

function ajaxPOSTRequest (ajaxRequestUrl, divID, formData) 
{		
	// check for textarea fields - as long as dojo 1.1 is beta :/
	//
	
	
	try {
			
//	 	var nodes = dojo.query("textarea", document.getElementById(divID));
	 	var nodes = dojo.query("textarea", dojo.byId (divID));
	 	var name;
	 	for(var x = 0; x <= nodes.length-1; x++){
	 		name=nodes[x].name;
		    formData[name] = nodes[x].value;
		}
		
		//
	 	IS_XHR_IN_PROGRESS=true;
	 	CURRENT_XHR_CONNECTION = dojo.xhrPost( {
	        url: ajaxRequestUrl,
	        headers: { "X_REQUESTED_WITH": "XMLHttpRequest" },
	        handleAs: "json",
	        timeout: 15000, 
			content: formData,
	        load: function(response, ioArgs)  {   	
				fillDiv(response, divID);
				
				checkIfToRedirectAfterXhrComplete();
				
				
				return response;
			},
	        error: function(response, ioArgs)  {
				if (response.message="xhr cancelled") {
	        		return null;
	        	}
				var exceptionResponeMessage= dumpObj(response, 2);
				var exceptionIOMessage= dumpObj(ioArgs, 2);
	        	handleError('ajaxPOSTRequest '+ioArgs.xhr.statusText+" // exceptionResponeMessage: "+exceptionResponeMessage+" // exceptionIOMessage: "+exceptionIOMessage, response.message);
	        	return response;
	        }
	  	} );	
	} catch (e) {		
		handleCatchedErrror(e, 'ajaxPOSTRequest');
	}
}

