/***
 *	V-focus.js
 *
 *	V-focus framework core
 *	Use Vfocus because V-focus is not allowed as variable name in JavaScript
 *
 *	copyright (c) 2008 Infor
 */

var lastTimeStamp = 0;
var lastTimeStampText = '';

// height fix
function fixHeight() {
	if (dojo==undefined||dojo.coords==undefined||dojo.byId==undefined||dijit.getViewport==undefined) {
		setTimeout(fixHeight,1);
		return;
	}
	var cW = dojo.byId("columnwrapper");
	if (cW==null) {
		setTimeout(fixHeight,1);
		return;
	}
	//console.log(cW);
	var posCW = dojo.coords(cW);
	//console.log(posCW);
	//var posB = dojo.coords(dojo.doc.body); // => 'body' of document, not of window/viewport
	var posB = dijit.getViewport();
	//console.log(posB);
	var posF = dojo.coords(dojo.byId("footer"));
	//console.log(posF);
	//var h = posB.h-posCW.y+posF.h*2; // this makes no sense whatsoever :(
	var h = posB.h-posCW.y-posF.h;
	//console.log("h "+h);
	//console.log("expected h "+(posB.h-posCW.y-posF.h));
	//h = 600;
	//console.log("min-height: "+h);
	var i = 1;
	var d = dojo.byId("column"+i++);
	while (d!=undefined) {
		d.style.minHeight = h+"px";
		var d = dojo.byId("column"+i++);
	}
}
fixHeight();

if ((typeof Vfocus)=="undefined")
	this.Vfocus = {
		_scopeName: "Vfocus"
	};

// also create Data container
var Data = {};

/***
 *	copy from dojo - both properties and methods
 *	keep in mind that strings, numbers and booleans are copied by value
 *	everything else is copied by reference
 */
 
if ((typeof dojo)!="undefined") {
	var copyFromDojoArray = [["mixin"], ["setOpacity","_setOpacity"], ["global"], ["setObject"], ["getObject"], ["exists"], ["isBrowser"], ["isFF"], ["isIE"], ["isSafari"], ["isKhtml"], ["isMozilla"], ["isOpera"], ["isAIR"], ["toJson"], ["fromJson"], ["connect"], ["byId"], ["query"], ["forEach"], ["doc"], ["body"], ["trim"], ["_destroyElement"], ["clone"], ["place"], ["hitch"], ["",""]];
	var cFDALen = copyFromDojoArray.length;
	var cFDAI, cFDAI0;
	for (var i=0;i<cFDALen;++i) {
		cFDAI = copyFromDojoArray[i];
		cDFAI0 = cFDAI[0];
		if (cDFAI0!=undefined&&cDFAI0!="") {
			if (cFDAI.length==1) Vfocus[cDFAI0] = dojo[cDFAI0];
			else Vfocus[cDFAI0] = dojo[cFDAI[1]];
		}
	}
	delete copyFromDojoArray, cFDALen, cFDAI, cDFAI0;
}

/***
 *	Extend/build on Dojo
 */
Vfocus.getUniqueId = function () {
	return dojo.dnd.getUniqueId();
}

Vfocus.widgetById = function (id) {
	if (id!="") return dijit.byId(id);
	else return false;
}

Vfocus.removeById = function(id) {
	var elem = dojo.byId(id);
	if (elem) {
		dojo._destroyElement(elem);
		return true;
	} else return false;
}

/***
 *	Messaging
 */
Vfocus.Messaging = {
	publish: dojo.publish,
	subscribe: dojo.subscribe,
	unsubscribe: dojo.unsubscribe
};

/***
 *	Get text of identifier 'ident' of language 'lang' from textobject 'tObj'
 *
 *	@param tObj		Object holding texts
 *	@param ident	Identifier of text
 *	@param lang		Language, optional
 */
Vfocus.getText = function (tObj,ident) {
	if (tObj==null||tObj==undefined) return "";
	var argLen = arguments.length;
	if (argLen>2&&arguments[2]!="") var lang = arguments[2];
	else var lang = Vfocus.Settings.uiLanguage;
	//
	var identLC = ident.toLowerCase();
	//
	var ret = "";
	var t = "";
	var foundText = false;
	if (tObj[lang]!=undefined&&((typeof tObj[lang])=="object")) {
		var t = tObj[lang];
		// try to get text
		if (t[ident]!=undefined) {
			ret = t[ident];
			foundText = true;
		} else if (t[identLC]!=undefined) {
			ret = t[identLC];
			foundText = true;
		}
	}
	if(!foundText&&lang!=Vfocus.Settings.defaultUiLanguage) {
		lang = Vfocus.Settings.defaultUiLanguage;
		if (tObj[lang]!=undefined&&((typeof tObj[lang])=="object")) {
			var t = tObj[lang];
			// try to get text
			if (t[ident]!=undefined) {
				ret = t[ident];
			} else if (t[identLC]!=undefined) {
				ret = t[identLC];
			}
		}
	}
	// if ret is still empty, try backup texts
	if (ret==""&&tObj!=Data.texts) ret = Vfocus.getText(Data.texts,ident);
	// see if there are replacements to be inserted
	if (ret!=""&&argLen>3) {
		var repl;
		for (var i=3;i<=argLen;++i) {
			repl = arguments[i];
			ret = ret.split("${"+(i-2)+"}").join(repl);
		}
	}
	// return
	return ret;
}

/***
 *	Turn a supplied date-string (dd/mm//yyyy) into a JavaScript/Dojo acceptable date-string (yyyy-mm-dd)
 *	If nothing's supplied, use current date
 *  If length of date string is 8, then date is in YYYYMMDD format
 *
 *	@param dateString	date-string to convert
 *	@param delimiter	delimited used in dateString, optional, default is '/'
 */
Vfocus.getDate = function () {
	var dStr = "";
	if (arguments.length==0) {
		// use current date
		var d = new Date();
		var day = d.getDate();
		var month = d.getMonth()+1;
		var year = d.getFullYear();
	} else {
		var dateString = arguments[0].toString();
		if (dateString==undefined||dateString=="") return "";
		if (dateString.length==8 || dateString.length==14) {
			dStr=dateString.substr(0,4)+'-'+dateString.substr(4,2)+'-'+dateString.substr(6,2);
			if (dateString.length==14) dStr+='-'+dateString.substr(8,2)+'-'+dateString.substr(10,2)+'-'+dateString.substr(12,2);
			return dStr;
		}
		else {
			var delim = (arguments.length>1)?(arguments[1]):('-');
			var dateArr = dateString.split(delim);
			if (dateArr.length==1) dateArr = dateString.split('/');
			var day = (dateArr[0].length<3)?(dateArr[0]):(dateArr[2]);
			if (day.length>1&&day.charAt(0)=='0') day = day.charAt(1);
			day = parseInt(day);
			var month = dateArr[1];
			if (month.length>1&&month.charAt(0)=='0') month = month.charAt(1);
			month = parseInt(month);
			var year = parseInt((dateArr[0].length>3)?(dateArr[0]):(dateArr[2]));
		}
	}
	//console.log(day+":"+month+":"+year);
	// create string
	if (day<10) day = '0'+day;
	if (month<10) month = '0'+month;
	// return date
	return year+'-'+month+'-'+day;
}

Vfocus.getDateString = function (date,format) {
	if (typeof date=="string") {
		// create date object
		var dateArr = date.split("-");
		date = new Date();
		date.setDate(dateArr[2]);
		// month -> 0-index
		var month = dateArr[1];
		if (month.charAt(0)=="0") month = month.charAt(1);
		month = parseInt(month)-1;
		date.setMonth(month);
		date.setFullYear(dateArr[0]);
		if (dateArr.length>5) {
			date.setHours(dateArr[3],dateArr[4],dateArr[5]);
		}
	}
	return dojo.date.locale.format(date,format);
}

Vfocus.getDateObject = function(string) {
	// Return a javascript Date object from a string in YYYYMMDD format
	var d = new Date();
	d.setFullYear(string.substr(0,4));
	d.setMonth(string.substr(4,2)-1);
	d.setDate(string.substr(6,2));

	return d;
}

Vfocus.parseDateStringIntoObject = function (date) {
	var dateArr = "";
	var dateObj = false;
	if (date.indexOf("-")>-1) dateArr = date.split("-");
	else if (date.indexOf("/")>-1) dateArr = date.split("-");
	if (dateArr!="") {
		var dateObj = {
			year: parseInt(dateArr[0]),
			month: dateArr[1],
			day: dateArr[2]
		};
	} else if (date.length==8) {
		var dateObj = {
			year: parseInt(date.substring(0,4)),
			month: date.substring(4,6),
			day: date.substring(6,8)
		};
	}
	if (dateObj.month.length==2&&dateObj.month.charAt(0)=="0") dateObj.month = dateObj.month.charAt(1);
	dateObj.month = parseInt(dateObj.month);
	if (dateObj.day.length==2&&dateObj.day.charAt(0)=="0") dateObj.day = dateObj.day.charAt(1);
	dateObj.day = parseInt(dateObj.day);
	return dateObj;
}

Vfocus.parseObjectIntoDate = function (obj) {
	var d = new Date();
	if (obj.year!=undefined) d.setFullYear(obj.year);
	if (obj.month!=undefined) d.setMonth(obj.month-1); // 0-index
	if (obj.day!=undefined) d.setDate(obj.day);
	return d;
}

/***
 *	Returns weeknumber for specific date
 *	from: http://www.meanfreepath.com/support/getting_iso_week.html
 *
 *	@param dObj		date to determine weeknumber of
 *	@param startDay	starting day of week (default 0)
 */
Vfocus.getWeekNumber = function (dObj,startDay) {
	if (arguments.length<2) var startDay = 0;
	var newYear = new Date(dObj.getFullYear(),0,1);
	var day = newYear.getDay() - startDay; //the day of week the year begins on
	day = (day >= 0 ? day : day + 7);
	var daynum = Math.floor((dObj.getTime() - newYear.getTime() - (dObj.getTimezoneOffset()-newYear.getTimezoneOffset())*60000)/86400000) + 1;
	var weeknum;
	//if the year starts before the middle of a week
	if(day < 4) {
		weeknum = Math.floor((daynum+day-1)/7) + 1;
		if(weeknum > 52) {
			nYear = new Date(dObj.getFullYear() + 1,0,1);
			nday = nYear.getDay() - startDay;
			nday = nday >= 0 ? nday : nday + 7;
			weeknum = nday < 4 ? 1 : 53;
		}
	} else {
		weeknum = Math.floor((daynum+day-1)/7);
	}
	return weeknum;
}

/***
 *	Convert date from date textbox into yyyymmdd format
 *	@param date
 */
Vfocus.convertDateForServer = function (date) {
	// 
	var temp=dojo.date.stamp.toISOString(date);
	return temp.substr(0,4)+temp.substr(5,2)+temp.substr(8,2);
}

/***
 *	Validate date
 *	@param day
 *  @param month
 *  @param year
 */
Vfocus.isDate = function(day, month, year) {
	if (day < 1 || day > 31) return false;
	if (month < 1 || month > 12) return false;
	if ((month==4 || month==6 || month==9 || month==11) && day==31) return false;
	if (month == 2) {
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); 
		if (day > 29 || (day==29 && !isleap)) return false;
	}
	return true; 
}

/***
 *	Validate e-mail address
 *	@param email
 */
Vfocus.isEmail = function(email) {
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	return reg.test(email);
}

/***
 *	Get texts for specified module
 *
 *	@param moduleObj		Object of module
 *	@param moduleIdent		Identifier used serverside to collect texts
 *	@param moduleCllback	Method to execute after texts are received
 */
Vfocus.getModuleTextsOld = function (moduleObj,moduleIdent,moduleCallback) {
	// set function to store texts
	var callbackOld = function (response,ioArgs) {
		// store texts
		var result = parseInt(response.result);
		if (result&&response.texts) {
			if ((typeof moduleObj)=="string") var module = eval(moduleObj);
			else var module = moduleObj;
			if (module==undefined&&response.module!=undefined) var module = eval(response.module);
			//else if ((typeof moduleCallback)=="string") var module = eval(moduleCallback);
			//else var module = moduleCallback;
			//console.log("response.module "+response.module);
			if (module!=undefined) module.texts = response.texts;
		}
		// callback
		if (moduleCallback!=undefined) {
			if ((typeof moduleCallback)=="string") eval(moduleCallback)(response);
			else moduleCallback(response);
		}
	}
	var callback = function (xObj,ioArgs) {
		var response = (new XMLJS()).parseXML(ioArgs.xhr.responseXML);//.getmoduletexts;
		if (response["#document"]!=undefined) response = response["#document"];
		response = response.getmoduletexts;
		if (response.result!=undefined&&(response.result=="1"||response.result==1)) {
			if ((typeof moduleObj)=="string") var module = eval(moduleObj);
			else var module = moduleObj;
			if (module==undefined&&response.module!=undefined) var module = eval(response.module);
			if (module!=undefined) module.texts = response.moduletexts;
		}
		// callback
		if (moduleCallback!=undefined) {
			if ((typeof moduleCallback)=="string") eval(moduleCallback)(response);
			else moduleCallback(response);
		}
	};
	var url = Vfocus.Settings.url+"Service.Text.cls";
	var content = {};
	content.action = "getModuleTexts";
	content.module = moduleIdent;
	content.type = "xml";
	var handleAs = "xml";
	Vfocus.get(url,content,handleAs,callback);
}
Vfocus.getModuleTexts = function (moduleObj,moduleIdent,moduleCallback) {
	// check if module 'moduleIdent's not already loaded in
	if (Data.ModuleTexts[moduleIdent]!=undefined) {
		if ((typeof moduleObj)=="string") var module = eval(moduleObj);
		else var module = moduleObj;
		if (module==undefined&&response.module!=undefined) var module = eval(response.module);
		if (module!=undefined) module.texts = Data.ModuleTexts[moduleIdent].moduletexts;
		// callback
		if (moduleCallback!=undefined) {
			if ((typeof moduleCallback)=="string") eval(moduleCallback)(Data.ModuleTexts[moduleIdent]);
			else moduleCallback(Data.ModuleTexts[moduleIdent]);
		}
		return;
	}
	// check if module 'moduleIdent's not being requested already
	if (Data.ModuleTextsLoadObj[moduleIdent]!=undefined) {
		// there's already a request issued, add to stack
		var t = {
			obj: moduleObj,
			cb: moduleCallback
		}
		Data.ModuleTextsLoadObj[moduleIdent].push(t);
		return;
	}
	// module 'moduleIdent's not been requested yet
	Data.ModuleTextsLoadObj[moduleIdent] = [];
	var t = {
		obj: moduleObj,
		cb: moduleCallback
	}
	Data.ModuleTextsLoadObj[moduleIdent].push(t);
	// set function to store texts
	var callback = function (xObj,ioArgs) {
		var response = (new XMLJS()).parseXML(ioArgs.xhr.responseXML);
		if (response["#document"]!=undefined) response = response["#document"];
		response = Data.ModuleTexts[moduleIdent] = response.getmoduletexts;
		if (response.result!=undefined&&(response.result=="1"||response.result==1)) {
			// loop over all requests made for 'moduleIdent' and set text
			var mTLO = Data.ModuleTextsLoadObj[moduleIdent];
			var mTLOLen = mTLO.length;
			var m,mObj,mCb,module;
			for (var i=0;i<mTLOLen;++i) {
				m = mTLO[i];
				mObj = m.obj;
				mCb = m.cb;
				module = null;
				if ((typeof mObj)=="string") module = eval(mObj);
				else module = mObj;
				if (module==null&&response.module!=undefined) module = eval(response.module);
				if (module!=null) module.texts = response.moduletexts;
				// callback
				if (mCb!=undefined) {
					if ((typeof mCb)=="string") eval(mCb)(response);
					else mCb(response);
				}
			}
			delete Data.ModuleTextsLoadObj[moduleIdent];
		}
	};
	var url = Vfocus.Settings.url+"Service.Text.cls";
	var content = {};
	content.action = "getModuleTexts";
	content.module = moduleIdent;
	content.type = "xml";
	var handleAs = "xml";
	Vfocus.get(url,content,handleAs,callback);
	//Vfocus.loadJS(Vfocus.Settings.url+"Service.Text.cls?action=getModuleTexts&module="+moduleIdent+"&type=json");
}
// keep reference of objects requesting moduletext
Data.ModuleTextsLoadObj = {};
// keep reference of loaded in moduletexts
Data.ModuleTexts = {};
// get default texts
Data.texts = null;

Vfocus.getModuleTemplatesOld = function (moduleObj,moduleIdent,moduleCallback) {
	console.log("Vfocus.getModuleTemplates");
	// set function to store templates
	var callback = function (response,ioArgs) {
		console.log("Vfocus.getModuleTemplates callback");
		console.log(response);
		// store templates
		var result = parseInt(response.result);
		if (result&&response.templates) {
			if ((typeof moduleObj)=="string") var module = eval(moduleObj);
			else var module = moduleObj;
			if (module==undefined&&response.module!=undefined) var module = eval(response.module);
			console.log("templates module");
			console.log(module);
			if (module!=undefined) module.templates = response.templates;
			console.log(module.templates);
		}
		// callback
		if (moduleCallback!=undefined) {
			if ((typeof moduleCallback)=="string") eval(moduleCallback)(response);
			else moduleCallback(response);
		}
	}
	var url = Vfocus.Settings.url+"Service.Template.cls";
	var content = {};
	content.action = "getModuleTemplates";
	content.module = moduleIdent;
	var handleAs = "json";
	Vfocus.post(url,content,handleAs,callback);
}
Vfocus.getModuleTemplates = function (moduleObj,moduleIdent,moduleCallback) {
	// check if module 'moduleIdent's not already loaded in
	if (Data.ModuleTemplates[moduleIdent]!=undefined) {
		if ((typeof moduleObj)=="string") var module = eval(moduleObj);
		else var module = moduleObj;
		if (module==undefined&&response.module!=undefined) var module = eval(response.module);
		if (module!=undefined) module.templates = Data.ModuleTemplates[moduleIdent].templates;
		// callback
		if (moduleCallback!=undefined) {
			if ((typeof moduleCallback)=="string") eval(moduleCallback)(Data.ModuleTemplates[moduleIdent]);
			else moduleCallback(Data.ModuleTexts[moduleIdent]);
		}
		return;
	}
	// check if module 'moduleIdent's not being requested already
	if (Data.ModuleTemplatesLoadObj[moduleIdent]!=undefined) {
		// there's already a request issued, add to stack
		var t = {
			obj: moduleObj,
			cb: moduleCallback
		}
		Data.ModuleTemplatesLoadObj[moduleIdent].push(t);
		return;
	}
	// module 'moduleIdent's not been requested yet
	Data.ModuleTemplatesLoadObj[moduleIdent] = [];
	var t = {
		obj: moduleObj,
		cb: moduleCallback
	}
	Data.ModuleTemplatesLoadObj[moduleIdent].push(t);
	// set function to store texts
	var callback = function (response,ioArgs) {
		// store templates
		var result = parseInt(response.result);
		if (result&&response.templates) {
			Data.ModuleTemplates[moduleIdent] = response;
			// loop over all requests made for 'moduleIdent' and set text
			var mTLO = Data.ModuleTemplatesLoadObj[moduleIdent];
			var mTLOLen = mTLO.length;
			var m,mObj,mCb,module;
			for (var i=0;i<mTLOLen;++i) {
				m = mTLO[i];
				mObj = m.obj;
				mCb = m.cb;
				module = null;
				if ((typeof mObj)=="string") module = eval(mObj);
				else module = mObj;
				if (module==null&&response.module!=undefined) module = eval(response.module);
				if (module!=null) module.templates = response.templates;
				// callback
				if (mCb!=undefined) {
					if ((typeof mCb)=="string") eval(mCb)(response);
					else mCb(response);
				}
			}
			//delete Data.ModuleTemplatesLoadObj[moduleIdent];
		}
	};
	var url = Vfocus.Settings.url+"Service.Template.cls";
	var content = {};
	content.action = "getModuleTemplates";
	content.module = moduleIdent;
	var handleAs = "json";
	Vfocus.post(url,content,handleAs,callback);
}
// keep reference of objects requesting moduletemplates
Data.ModuleTemplatesLoadObj = {};
// keep reference of loaded in moduletemplates
Data.ModuleTemplates = {};

/***
 *	Parse supplied template & replace-object
 */
Vfocus.parseTemplate = function (tpl,repl) {
	var delims = [["${","}"],["[[","]]"]];
	for (var i=0;i<delims.length;++i) {
		var delim = delims[i];
		var idx = tpl.indexOf(delim[0]);
		var idx2;
		var len2 = delim[1].length;
		var before,key,after;
		while (idx>-1) {
			before = tpl.substring(0,idx);
			idx2 = tpl.indexOf(delim[1],idx);
			key = tpl.substring(idx+2,idx2);
			after = tpl.substring(idx2+len2);
			tpl = before+((repl[key]!=undefined)?(repl[key]):(""))+after;
			var idx = tpl.indexOf(delim[0],idx+1);
		}
		// one final check
		for (var r in repl) tpl = tpl.split(delim[0]+r+delim[1]).join(repl[r]);
	}
	return tpl;
}

/***
 *	XMLHTTPRequest
 *	
 *	The following construct is not used so custom defaults can be used
 *	Vfocus.get = dojo.xhrGet;
 *	Vfocus.post = dojo.xhrPost;
 *	Instead use the following
 */
Vfocus.XMLHTTPRequest = {
	defaultHandleAs: "json",
	
	/***
	 *	Default method called to receive result from XHR call
	 *
	 *	@param response			response object from server
	 *	@param ioArgs			arguments used to make the original xhr call
	 */
	defaultLoadFunction: function (response,ioArgs) {
		// Now you can just use the object
		console.log("defaultLoadFunction called");
		console.log(response);  // Dump it to the console
		return response;
	},
	
	create: function (callingType) {
		// 'callingType' is either 'xhrGet' or 'xhrPost'
		var func = function () {
			var url = "";
			var content = {};
			var handleAs = Vfocus.XMLHTTPRequest.defaultHandleAs;
			var loadFunction = Vfocus.XMLHTTPRequest.defaultLoadFunction;
			var errorFunction = Vfocus.XMLHTTPRequest.defaultErrorFunction;
			var argLen = arguments.length;
			if (argLen==1&&(typeof arguments[0]=="object")) {
				var obj = arguments[0];
				if (obj.url) url = obj.url;
				if (obj.content) content = obj.content;
				if (obj.handleAs) handleAs = obj.handleAs;
				if (obj.loadFunction) loadFunction = obj.loadFunction;
				if (obj.errorFunction) errorFunction = obj.errorFunction;
			} else if (argLen>1) {
				url = arguments[0];
				content = arguments[1];
				if (argLen>2) handleAs = arguments[2];
				if (argLen>3) loadFunction = arguments[3];
				if (argLen>4) errorFunction = arguments[4];
			}
			if (url=="") return false;
			// add randomization to request
			// only if IE?
			//if (content.random==undefined) content.random = (new Date()).getTime();
			//
			// default call
			dojo[callingType]({
				url: url,
				handleAs: handleAs,
				content: content,
				load: loadFunction
			});
		}
		return func;
	}
};

/***
 *	create an xhrGet object
 *	can be called as follows:
 *	Vfocus.get(obj)
 *	where obj = {url:.., content:.. etc}
 *	or
 *	Vfocus.get(url,content[,handleAs[,loadFunction]])
 */
Vfocus.get = Vfocus.XMLHTTPRequest.create("xhrGet");

/***
 *	create an xhrPost object
 *	can be called as follows:
 *	Vfocus.post(obj)
 *	where obj = {url:.., content:.. etc}
 *	or
 *	Vfocus.post(url,content[,handleAs[,loadFunction]])
 */
Vfocus.post = Vfocus.XMLHTTPRequest.create("xhrPost");

/***
 *	Alert popups
 */
Vfocus.alert = function (msg,title,func) {
	console.log("Vfocus.alert");
	console.log(arguments);
	var texts = Data.texts;
	if (texts==null) {
		var f = function () {
			Vfocus.alert(msg,title,func);
		}
		Vfocus.getModuleTexts(Data,"defaultTexts",f);
	}
	if (title==undefined) var title = Vfocus.getText(texts,"alertTitle");
	var dlg = new dijit.Dialog({
		title:title
	});
	// set message
	var msgDiv = document.createElement("div");
	msgDiv.innerHTML = msg;
	dlg.containerNode.appendChild(msgDiv);
	// set OK
	var btnDiv = document.createElement("div");
	btnDiv.className = "dialogButtons";
	var okTxt = Vfocus.getText(texts,"okBtn");
	var btn = new dijit.form.Button({
		label: okTxt,
		iconClass: "okIcon"
	});
	if (func!=undefined) {
		dojo.connect(btn, "onClick", function(){
			// first hide
			dlg.hide();
			// then destroy
			setTimeout(function() { dlg.destroy(); func(); },dlg.duration);
		});
	} else {
		dojo.connect(btn, "onClick", function(){
			// first hide
			dlg.hide();
			// then destroy
			setTimeout(function() { dlg.destroy(); },dlg.duration);
		});
	}
	btnDiv.appendChild(btn.domNode);
	dlg.containerNode.appendChild(btnDiv);
	dlg.show();
}

Vfocus.confirm = function (msg,title,execFunc,execCancel) {
	var texts = Data.texts;
	if (texts==null||dijit==undefined||dijit.form==undefined||dijit.form.Button==undefined) {
		var f = function () {
			Vfocus.confirm(msg,title,execFunc,execCancel);
		}
		if (texts==null) Vfocus.getModuleTexts(Data,"defaultTexts",f);
		else setTimeout(f,100);
		return false;
	}
	if (title==undefined||title=="") var title = Vfocus.getText(texts,"confirmTitle");
	var dlg = new dijit.Dialog({
		title:title
	});
	// set message
	var msgDiv = document.createElement("div");
	msgDiv.innerHTML = msg;
	dlg.containerNode.appendChild(msgDiv);
	// set OK & cancel
	var btnDiv = document.createElement("div");
	btnDiv.className = "dialogButtons";
	var okTxt = Vfocus.getText(texts,"okBtn");//(buttons[Vfocus.Settings.uiLanguage].ok!=undefined)?(buttons[Vfocus.Settings.uiLanguage].ok):(buttons[Vfocus.Settings.defaultUiLanguage].ok);
	var btnOk = new dijit.form.Button({
		label: okTxt,
		iconClass: "okIcon"
	});
	dojo.connect(btnOk, "onClick", function () {
		// first hide
		dlg.hide();
		// then destroy
		setTimeout(function() { dlg.destroy(); execFunc(); },dlg.duration);
	});
	btnDiv.appendChild(btnOk.domNode);
	// create distance between buttons
	var cancelTxt = Vfocus.getText(texts,"cancelBtn");//(buttons[Vfocus.Settings.uiLanguage].cancel!=undefined)?(buttons[Vfocus.Settings.uiLanguage].cancel):(buttons[Vfocus.Settings.defaultUiLanguage].cancel);
	var btnCancel = new dijit.form.Button({
		label: cancelTxt,
		iconClass: "cancelIcon",
		style:"margin:0 5px;"
	});
	dojo.connect(btnCancel, "onClick", function(){
		// first hide
		dlg.hide();
		// then destroy
		if (execCancel != undefined) {
			setTimeout(function() { dlg.destroy(); execCancel(); },dlg.duration);
		}
		else {
			setTimeout(function() { dlg.destroy(); },dlg.duration);
		}
	});
	btnDiv.appendChild(btnCancel.domNode);
	dlg.containerNode.appendChild(btnDiv);
	dlg.show();
}

/***
 *	
 */

/***
 *	Create a new file reference (HTML tag)
 *
 *	@param filename			filename to create reference (HTML tag) for
 *	@param filetype			filetype, allowed values: 'js', 'css'
 *	@param arguments[2]		media to use, optional
 */
Vfocus.createJsCSSFile = function (filename,filetype) {
	if (filetype=="js"){
		var fileref=document.createElement('script');
		fileref.setAttribute("type","text/javascript");
		fileref.setAttribute("src", filename);
	}
	else if (filetype=="css"){
		var fileref=document.createElement("link");
		fileref.setAttribute("rel", "stylesheet");
		fileref.setAttribute("type", "text/css");
		fileref.setAttribute("href", filename);
		if (arguments.length>2) fileref.setAttribute("media", arguments[2]);
		
	}
	return fileref;
}

/***
 *	Check if a specified file has already been loaded in
 *
 *	@param filename			file to load in
 *	@param filetype			filetype, allowed values: 'js', 'css'
 *	@param arguments[2]		add (1 or not present) or remove (0)
 *
 *	@return true			if file needs to be added and wasn't present yet, or file needs to be removed and removal was successful
 *	@return false			if file needs to be added but was already present, or file needs to be removed but wasn't present
 */
Vfocus.checkJsCSSFile = function (filename,filetype) {
	if (filename==undefined||filename=="") return false;
	var action = (arguments.length>2)?(arguments[2]):(1);
	// check if  file hasn't been loaded in yet
	if (filename.indexOf("?")>0) {
		filename = filename.split("?")[0];
	}
	var ret = true;
	var isFound = false;
	var files = Data.Files[filetype];
	var fLen = files.length;
	for (var i=0;i<fLen;++i) {
		if (files[i]==filename) {
			if (action) {
				// add, but already present
				ret = false;
			} else {
				// remove
				Data.Files[filetype].splice(i,1);
			}
			isFound = true;
			i = fLen;
		}
	}
	if (!isFound) {
		// not found
		if (action) {
			// add
			Data.Files[filetype].push(filename);
		} else {
			// remove, but not present
			ret = false;
		}
	}
	return ret;
}

Vfocus.initializeJsCSS = function () {
	// have to parse files into Data.Files
	if (Data.Files==undefined) {
		Data.Files = {
			css: [],
			js: []
		};
	}
	// parse files from HTML
	var f = function (file) {
		// remove leading part of 'file' if necessary
		var parts = [Vfocus.Settings.url,"../","./","/"];
		// check domain
		var pLen = parts.length;
		var part,partLen;
		for (var i=0;i<pLen;++i) {
			part = parts[i];
			partLen = part.length;
			while (file.indexOf(part)==0) {
				file = file.substring(partLen);
			}
		}
		return file;
	}
	var css = Vfocus.query("link");
	for (i in css) if (css[i].href!=undefined) Vfocus.checkJsCSSFile(f(css[i].href),"css");
	var js = Vfocus.query("script");
	for (i in js) if (js[i].src!=undefined) Vfocus.checkJsCSSFile(f(js[i].src),"js");
}

/***
 *	Load in an external JS or CSS file
 *
 *	@param filename			file to load in
 *	@param filetype			filetype, allowed values: 'js', 'css'
 *	@param arguments[2]		media to use (in case of CSS), optional
 */
Vfocus.loadJsCSSFile = function (filename,filetype) {
	// check if  file hasn't been loaded in yet
	//console.log("Vfocus.loadJsCSSFile "+filename+" : "+Vfocus.checkJsCSSFile(filename,filetype,1));
	if (Vfocus.checkJsCSSFile(filename,filetype,1)==false) return;
	if (arguments.length>2) var fileref = Vfocus.createJsCSSFile(filename,filetype,arguments[2]);
	else var fileref = Vfocus.createJsCSSFile(filename,filetype);
	if (typeof fileref!="undefined") {
		document.getElementsByTagName("head")[0].appendChild(fileref);
	}
	//
	if (dojo.byId("loaderSplash")) {
		var lI = dojo.byId("loaderIndicator");
		lI.innerHTML = "bezig met laden van "+filename;
	}
}

/***
 *	Unload or replace an external JS or CSS file
 *	In the case of JS this does not automagically remove/reset variables/content set by the unloaded JS
 *
 *	@param filename			file to unload
 *	@param filetype			filetype, allowed values: 'js', 'css'
 *	@param arguments[2]		file to replace 'filename', optional
 *	@param arguments[3]		media to use for CSS, optional
 */
Vfocus.unloadReplaceJsCSSFile = function (filename,filetype) {
	var argLen = arguments.length;
	// check if  file has been loaded in already
	if (Vfocus.checkJsCSSFile(filename,filetype,0)==false) return;
	// check if  file hasn't been loaded in yet
	if (argLen>2) {
		if (Vfocus.checkJsCSSFile(arguments[2],filetype,1)==false) return;
	}
	var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none";
	var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none";
	var allsuspects=document.getElementsByTagName(targetelement);
	for (var i=allsuspects.length; i>=0; i--) {
		if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(filename)!=-1) {
			if (argLen>2) {
				// replace
				if (argLen>3) var newelement = Vfocus.createJsCSSFile(arguments[2],filetype,arguments[3]);
				else newelement = Vfocus.createJsCSSFile(arguments[2],filetype);
				allsuspects[i].parentNode.replaceChild(newelement,allsuspects[i]);
			} else {
				// remove
				allsuspects[i].parentNode.removeChild(allsuspects[i]);
			}
		}
	}
}

/***
 *	Load in CSS file
 *
 *	@param filename			CSS file to load in
 *	@param arguments[1]		Type of media to use CSS for, optional
 */
Vfocus.loadCSS = function (filename) {
	// add versioning if necessary
	if (Vfocus.Settings.cssVersion!=undefined) {
		var idx = filename.indexOf("version=");
		if (idx<0) {
			filename = filename+((filename.indexOf("?")<0)?("?"):("&"))+"version="+Vfocus.Settings.cssVersion;
		} else {
			var fBefore = filename.substring(0,idx);
			var fAfter = filename.substring(idx+8);
			if (fAfter.indexOf("&")<0) {
				filename = fBefore+"version="+Vfocus.Settings.cssVersion;
			} else {
				filename = fBefore+"version="+Vfocus.Settings.cssVersion+fAfter.substring(fAfter.indexOf("&"));
			}
		}
	}
	if (arguments.length>1) Vfocus.loadJsCSSFile(filename,"css",arguments[1]);
	else Vfocus.loadJsCSSFile(filename,"css");
}

/***
 *	Load in JavaScript file
 *
 *	@param filename			JavaScript file to load in
 */
Vfocus.loadJS = function (filename) {
	// add versioning if necessary
	if (Vfocus.Settings.jsVersion!=undefined) {
		var idx = filename.indexOf("version=");
		if (idx<0) {
			filename = filename+((filename.indexOf("?")<0)?("?"):("&"))+"version="+Vfocus.Settings.jsVersion;
		} else {
			var fBefore = filename.substring(0,idx);
			var fAfter = filename.substring(idx+8);
			if (fAfter.indexOf("&")<0) {
				filename = fBefore+"version="+Vfocus.Settings.jsVersion;
			} else {
				filename = fBefore+"version="+Vfocus.Settings.jsVersion+fAfter.substring(fAfter.indexOf("&"));
			}
		}
	}
	Vfocus.loadJsCSSFile(filename,"js");
}

/***
 *	Unload CSS file
 *
 *	@param filename			CSS file to unload
 */
Vfocus.unloadCSS = function (filename) {
	Vfocus.unloadReplaceJsCSSFile(filename,"css");
}

/***
 *	Unload JavaScript file
 *
 *	@param filename			JavaScript file to unload
 */
Vfocus.unloadJS = function (filename) {
	Vfocus.unloadReplaceJsCSSFile(filename,"js");
}

/***
 *	Replace CSS file
 *
 *	@param oldfilename		CSS file to be replaced
 *	@param newfilename		CSS file to replace with
 *	@param arguments[2]		Type of media to use CSS for, optional
 */
Vfocus.replaceCSS = function (oldfilename,newfilename) {
	if (arguments.length>2) Vfocus.unloadReplaceJsCSSFile(oldfilename,"css",newfilename,arguments[2]);
	else Vfocus.unloadReplaceJsCSSFile(oldfilename,"css",newfilename);
}

/***
 *	Replace JavaScript file
 *
 *	@param oldfilename		JavaScript file to be replaced
 *	@param newfilename		JavaScript file to replace with
 */
Vfocus.replaceJS = function (oldfilename,newfilename) {
	Vfocus.unloadReplaceJsCSSFile(oldfilename,"js",newfilename);
}

/***
 *	Sanitize a string to remove any possible tags (eg script tags)
 *	Use to sanitize strings entered into a public form field
 */
Vfocus.sanitizeString = function (str) {
	str = str.replace(/(<([^>]+)>)/ig,"");
	return str;
}

/***
 *	Initialization scripts
 */
Vfocus.initialize = function () {
	// initialize the framework
	//
	console.log("Vfocus.initialize");
	Vfocus.initializeJsCSS();
	// requires
	var compList = ["dojo.back","dijit.dijit","dijit.TitlePane","dojo.dnd.Source","dijit.form.TextBox","dijit.form.SimpleTextarea","dijit.form.DateTextBox","dijit.form.Button","dijit.form.CheckBox","dijit.form.FilteringSelect","dijit.layout.TabContainer","dijit.Dialog","dijit.Tooltip"];
	Vfocus.loadRequiredComponents(compList);
	// load in necessary files
	Vfocus.loadJS("Service.Session.cls?a="+Vfocus.Settings.applicationID+"&p="+Vfocus.Settings.profileID+"&v="+Vfocus.Settings.viewID+"&"+Math.random());
	// load in static content
	var url = Vfocus.Settings.url+"www.staticContent.cls";//?a="+Vfocus.Settings.applicationID+"&p="+Vfocus.Settings.profileID+"&v="+Vfocus.Settings.viewID;
	var content = {};
	content.a = Vfocus.Settings.applicationID;
	content.p = Vfocus.Settings.profileID;
	content.v = Vfocus.Settings.viewID;
	var handleAs = "xml";
	var callback = Vfocus.receiveStaticContent;
	Vfocus.get(url,content,handleAs,callback);
	//
	Vfocus.loadJS(Vfocus.Settings.jsDir+"V-focus.QueryString.js");
	Vfocus.loadJS(Vfocus.Settings.jsDir+"XMLJS.js");
	Vfocus.loadJS(Vfocus.Settings.jsDir+"WebService.js");
	Vfocus.loadJS(Vfocus.Settings.jsDir+"V-focus.Header.js");
	Vfocus.loadJS(Vfocus.Settings.jsDir+"V-focus.Banner.js");
	Vfocus.loadJS(Vfocus.Settings.jsDir+"V-focus.Cookie.js");
	Vfocus.loadJS(Vfocus.Settings.jsDir+"V-focus.CMS.js");
	Vfocus.loadJS(Vfocus.Settings.jsDir+"V-focus.Widget.js");
	//Vfocus.loadJS(Vfocus.Settings.jsDir+"V-focus.Iconify.js");
	Vfocus.loadJS(Vfocus.Settings.jsDir+"fckeditor/fckeditor.js");
	// last in line
	Vfocus.loadJS(Vfocus.Settings.jsDir+"V-focus.Navigation.js");
	Vfocus.loadJS(Vfocus.Settings.jsDir+"V-focus.Content.js");
	// mandatory applications
	Vfocus.loadJS(Vfocus.Settings.jsDir+"FormHandler.js");
	//Vfocus.loadJS(Vfocus.Settings.jsDir+"applications/UserActivities.js");
	Vfocus.loadJS(Vfocus.Settings.jsDir+"applications/Login.js");
	Vfocus.loadJS(Vfocus.Settings.jsDir+"applications/Common.js");
	Vfocus.loadJS(Vfocus.Settings.jsDir+"applications/Search.js");
	//Vfocus.loadJS(Vfocus.Settings.jsDir+"applications/Search.Reserve.js");
	var f = function () {
		if (window["Search"]!=undefined) {
			clearInterval(Vfocus.searchSI);
			delete Vfocus.searchSI;
			Vfocus.loadJS(Vfocus.Settings.jsDir+"applications/Search.Reserve.js");
		}
	}
	Vfocus.searchSI = setInterval(f,100);
	Vfocus.loadJS(Vfocus.Settings.url+"www.jsSettings.cls");
	//Vfocus.loadJS("www.jsSettings.cls");
	//
	// start listening
	Vfocus.subscriptions = {};
	Vfocus.subscriptions.onOpenCMSRequest = Vfocus.Messaging.subscribe("onOpenCMSRequest",Vfocus,"doOpenCMS");
	
}

Vfocus.initializePreview = function () {
	// initialize the framework preview (of a single module)
	//
	console.log("Vfocus.initializePreview");
	Vfocus.initializeJsCSS();
	// requires
	var compList = ["dijit.dijit","dijit.TitlePane","dojo.dnd.Source"];
	Vfocus.loadRequiredComponents(compList);
	// load in necessary files
	Vfocus.loadJS(Vfocus.Settings.jsDir+"V-focus.QueryString.js");
	Vfocus.loadJS(Vfocus.Settings.jsDir+"XMLJS.js");
	Vfocus.loadJS(Vfocus.Settings.jsDir+"V-focus.Cookie.js");
	Vfocus.loadJS(Vfocus.Settings.jsDir+"V-focus.Widget.js");
	Vfocus.loadJS(Vfocus.Settings.jsDir+"Formhandler.js");
	// last in line
	Vfocus.loadJS(Vfocus.Settings.jsDir+"V-focus.Content.js");
}

Vfocus.initializeExternalCMS = function () {
	// initialize the framework external CMS
	//
	console.log("Vfocus.initializeExternalCMS");
	Vfocus.initializeJsCSS();
	// requires
	var compList = ["dijit.dijit","dijit.TitlePane","dojo.dnd.Source","dijit.form.TextBox","dijit.form.SimpleTextarea","dijit.form.DateTextBox","dijit.form.Button","dijit.form.CheckBox","dijit.form.FilteringSelect","dijit.layout.TabContainer","dijit.Dialog","dijit.Tooltip","dijit.form.Textarea"];
	Vfocus.loadRequiredComponents(compList);
	// load in necessary files
	//console.log("loading in querystring");
	Vfocus.loadJS(Vfocus.Settings.jsDir+"V-focus.QueryString.js");
	Vfocus.loadJS(Vfocus.Settings.jsDir+"XMLJS.js");
	Vfocus.loadJS(Vfocus.Settings.jsDir+"WebService.js");
	console.log("loading in extcms");
	Vfocus.loadJS(Vfocus.Settings.jsDir+"V-focus.ExtCMS.js");
	Vfocus.loadJS(Vfocus.Settings.jsDir+"V-focus.ExtCMSHeader.js");
	Vfocus.loadJS(Vfocus.Settings.jsDir+"V-focus.ExtCMSNavigation.js");
	Vfocus.loadJS(Vfocus.Settings.jsDir+"V-focus.CMS.js");
	Vfocus.loadJS(Vfocus.Settings.jsDir+"V-focus.Widget.js");
	Vfocus.loadJS(Vfocus.Settings.jsDir+"fckeditor/fckeditor.js");
	Vfocus.loadJS(Vfocus.Settings.jsDir+"V-focus.Cookie.js");
}

Vfocus.receiveApplications = function (response,ioArgs) {
	console.log(response);
}

Vfocus.loadRequiredComponents = function (compList) {
	var cLen = compList.length;
	for (var i=0;i<cLen;++i) {
		dojo.require(compList[i]);
	}
}

/***
 *	Methods that acts as subscriptions
 */
Vfocus.doOpenCMS = function () {
	// open the external CMS
	//
	Vfocus.Settings.externalCmsHandle = Vfocus.openNewWindow(Vfocus.Settings.url+"www.ExternalCMS.cls","ExternalCMS");
}

/***
 *	Open a new window
 *	url: mandatory, url to open in new window
 *	name: optional, name of window, if not set or "", unique id will be used
 *	options: optional, options of new window
 */
Vfocus.openNewWindow = function (url,name,options) {
	console.log("Vfocus.openNewWindow called");
	console.log(arguments);
	var argLen = arguments.length;
	if (argLen==0) return false;
	if (argLen==1||name=="") var name = Vfocus.getUniqueId();
	if (argLen<3) var options = "";
	// open window
	var handle = window.open(url,name,options);
	// return handle
	return handle;
}

/***
 *	Clear a div of all contents
 *	This method is recommended over plain 'div.innerHTML = "";'
 *	cuz of possible Dojo widgets (dijit) which creates errors when reinstating these widgets using innerHTML=""
 */
Vfocus.clearDiv = function (div) {
	console.log("clearDiv");
	console.log(div);
	if ((typeof div)=="string") div = Vfocus.byId(div);
	if (div) {
		Vfocus.query('[widgetId]',div).forEach(function(node){
			var widget = dijit.byNode(node);
			if (widget) {
				console.log(widget);
				if (widget.destroyRecursive) widget.destroyRecursive();
				else widget.destroy();
			}
		});
		// now it's safe to use innerHTML
		div.innerHTML = "";
	}
}

/***
 *	Cover specified element using unique name with html
 */
Vfocus.coverElement = function (elem,name,html) {
	var coverDiv = document.createElement("div");
	coverDiv.id = "cover_"+name;
	coverDiv.className = "loadingCoverDiv";
	coverDiv.style.width = "100%";
	coverDiv.style.height = "100%";
	coverDiv.style.display = "block";
	// set background
	var bgDiv = document.createElement("div");
	bgDiv.style.position = "absolute";
	bgDiv.style.width = "100%";
	bgDiv.style.height = "100%";
	bgDiv.style.backgroundColor = "#FFFFFF";
	Vfocus.setOpacity(bgDiv,".5");
	coverDiv.appendChild(bgDiv);
	// set html
	var hDiv = document.createElement("div");
	hDiv.style.position = "absolute";
	hDiv.style.width = "100%";
	hDiv.style.height = "100%";
	hDiv.style.textAlign = "center";
	hDiv.style.align = "middle";
	hDiv.style.marginTop = "auto";
	hDiv.style.marginBottom = "auto";
	hDiv.innerHTML = '<table width="100%" height="100%" border="0"><tr><td width="100%" height="100%" align="center" vAlign="middle">'+html+'</td></tr></table>';
	coverDiv.appendChild(hDiv);
	//
	console.log("adding coverElement to "+elem);
	console.log(coverDiv);
	Vfocus.place(coverDiv,elem,"first");
}

Vfocus.displayLoading = function (name,elem) {
	console.log("Vfocus.displayLoading");
	console.log(arguments);
	if (arguments.length<2) var elem = dojo.body();
	var html = "Loading<br/><img src=\"img/loading.gif\" alt=\"loading\"/>";
	Vfocus.coverElement(elem,name,html);
}

Vfocus.hideLoading = function (name) {
	var elem = Vfocus.byId("cover_"+name);
	if (elem) elem.parentNode.removeChild(elem);
}

Vfocus.subscriptions = {};
Vfocus.subscriptions.onDisplayLoading = Vfocus.Messaging.subscribe("onDisplayLoading",Vfocus,"displayLoading");
Vfocus.subscriptions.onHideLoading = Vfocus.Messaging.subscribe("onHideLoading",Vfocus,"hideLoading");

/***
 *	Global functions
 */
 
/***
 *	Open widget
 *
 *	@param uuid		UUID of widget, mandatory
 *	@param appId	appId of widget, mandatory
 *	@param column	Column to place it in, mandatory
 *	@param position	Position in column, optional, add to bottom if not set
 *	@param additional	Additional properties which will be copied over to the instance
 */
Vfocus.openWidget = function (uuid,appId,column) {
	console.log("openWidget");
	console.log(arguments);
	var argLen = arguments.length;
	if (argLen.length==3) {
		// determine position
		var position = false;
	} else {
		var position = arguments[3];
	}
	var addProps = (argLen>4)?(arguments[4]):("");
	uuid = uuid.toLowerCase();
	try {
		// get details of application if not yet known
		if (uuid!=""&&appId!="") {
			// no need to add if already showing
			if (Data.applications[uuid]!=undefined) return;
			if (Data.applicationDetails!=undefined&&Data.applicationDetails[appId]!=undefined) {
				var application = Vfocus.clone(Data.applicationDetails[appId]);
				application.uuid = uuid;
				application.column = column;
				if (position) application.position = position;
				if (addProps!="") for (var i in addProps) application[i] = addProps[i];
				console.log("addApplication with cloned application");
				Vfocus.Content.addApplication(application);
			} else {
				// return function
				var f = function (response,ioArgs) {
					console.log("return from openWidget");
					console.log(response);
					var result = (response.result)?(parseInt(response.result)):(0);
					if (result) {
						// copy over details
						var application = (response.application)?(response.application):("");
						if (Data.applicationDetails==undefined) Data.applicationDetails = {};
						Data.applicationDetails[appId] = Vfocus.clone(application);
						delete Data.applicationDetails[appId].uuid;
						if (application!="") {
							// add to application
							application.column = column;
							console.log("application to add");
							console.log(application);
							if (addProps!="") for (var i in addProps) application[i] = addProps[i];
							if (position!==false) {
								application.position = position;
								Vfocus.Content.addApplication(application,position);
							} else {
								Vfocus.Content.addApplication(application);
							}
						}
					}
				}
				// create request
				var url = Vfocus.Settings.url+"Service.ApplicationManagement.cls";
				var content = {};
				content.action = "getApplicationDetails";
				content.uuid = uuid;
				content.appId = appId;
				var handleAs = "json";
				Vfocus.post(url,content,handleAs,f);
			}
		}
	}
	catch(err) {
		// error
		console.log("error within Vfocus.openWidget");
		console.log(err);
	}
}
//
/***
 *	Switch widths of columns
 *
 *	@params	widths (relative) of column widths that need to be assigned - NEEDS TO BE SET FOR ALL COLUMNS ON A PAGE
 *
 *	Note that the resulting widths will not be identical as 1% gaps are assigned inbetween columns
 */
Vfocus.setColumnWidths = function () {
	var argLen = arguments.length;
	// first determine total
	var total = 0;
	var mainTotal = 100;
	for (var i=0;i<argLen;++i) {
		total += arguments[i];
		if (arguments[i]==0) mainTotal += 1;
	}
	var c,w;
	var multiplier = mainTotal-argLen;
	for (var i=0;i<argLen;++i) {
		c = Vfocus.byId("column"+(i+1));
		if (c == null) continue;
		// determine new width
		w = multiplier*arguments[i]/total;
		c.style.width = w+"%";
	}
}
Vfocus.getColumnWidths = function() {
	var widths = '',w,c;
	for (var i = 0; i < 99; ++i) {
		c = Vfocus.byId("column"+(i+1));
		if (c == null) break;
		w = c.style.width;
		w = w.replace('%','');
		if (i > 0) widths += ',';
		widths += w;
	}
	console.log("Vfocus.getColumnWidths "+widths);
	return widths;
}
//
// get static content
Vfocus.receiveStaticContent = function(xObj,ioArgs) {
	//console.log("receiveStaticContent");
	//console.log(ioArgs);
	//console.log(sc.toString());
	//console.log("responseText "+ioArgs.xhr.responseText.length);
	//console.log(ioArgs.xhr.responseXML);
	//var sc = ioArgs.xhr.responseXML;
	var f = function (scx) {
		if (window["XMLJS"]!=undefined) {
			var sc = (new XMLJS()).parseXML(scx);
			//console.log("parsed staticContent");
			//console.log(sc);
			if (sc&&sc["#document"]!=undefined&&sc["#document"]!=null) sc = sc["#document"];
			if (sc.staticContent!=undefined&&sc.staticContent!=null) sc = sc.staticContent;
			// store
			if (sc.app) {
				Data.staticContent = {};
				if (sc.app.length!=undefined) {
					var scLen = sc.app.length;
					var app;
					for (var i=0;i<scLen;++i) {
						app = sc.app[i];
						if (app.content!=undefined) Data.staticContent[app.uuid] = app.content;
						else if (app.news!=undefined) Data.staticContent[app.uuid] = app.news;
					}
				} else {
					app = sc.app;
					if (app.content!=undefined) Data.staticContent[app.uuid] = app.content;
					else if (app.news!=undefined) Data.staticContent[app.uuid] = app.news;
				}
			}
		} else setTimeout(f,100,scx);
	}
	f(ioArgs.xhr.responseXML);
}
//
/***
 *	Hide/Show an application completely
 *
 *	@param application	Application that should be hidden
 */
Vfocus.hideApplication = function (application) {
	if (application==undefined||application.divId==undefined) return;
	var appDiv = Vfocus.query("#"+application.divId)[0];
	// store current display style
	if (appDiv!=undefined && appDiv.style.display!="none") {
		application.cssDisplay = (appDiv.style.display!=undefined)?(appDiv.style.display):("block");
		appDiv.style.display = "none";
	}
}
Vfocus.showApplication = function (application) {
     console.log(application);
	if (application==undefined||application.divId==undefined) return;
	var appDiv = Vfocus.query("#"+application.divId)[0];
	if (appDiv!=undefined) {
		appDiv.style.display = "block";
		delete application.cssDisplay;
	}
}
Vfocus.appIsVisible = function (application) {
	if (application==undefined||application.divId==undefined) return;
	var appDiv = Vfocus.query("#"+application.divId)[0];
	return (appDiv!=undefined && appDiv.style.display!="none");
}
Vfocus.logTimeStamp = function(text) {
	var d = new Date();
	var timeStamp = d.getTime();
	console.log('timestamp -----> ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds() + '.' + d.getMilliseconds() + ' [ ' + text + ' ]');
	if (lastTimeStamp != 0) {
		var elapsed = timeStamp - lastTimeStamp;
		console.log('elapsed   -----> ' + elapsed + ' [ ' + lastTimeStampText + ' ]');
	}
	lastTimeStamp = timeStamp;
	lastTimeStampText = text;
}
//
/***
 *	Popup possibilities
 */
Vfocus.openPopup = function (url,name,settings) {
	var argLen = arguments.length;
	if (argLen==0) return false;
	var wName = (argLen>1&&name!="")?(name):("win_"+Math.floor(Math.random()*999999));
	var wSettings = (argLen>2)?(settings):("width=400,height=300,resizable=yes"); // default
	console.log("Vfocus.openPopup");
	console.log(url+" - "+wName+" - "+wSettings);
	window.open(url,wName,wSettings);
}
//
var f = function () {
	console.log("checking for loading default texts");
	if (Vfocus.Settings!=undefined&&Vfocus.Settings.url!=undefined&&window["XMLJS"]!=undefined) {
		clearInterval(sI);
		Vfocus.getModuleTexts(Data,"defaultTexts");
	}
}
var sI = setInterval(f,250);
//
if (window["console"]==undefined) {
	console = {};
	console.log = function () {
		// do nothing
	}
}

//
// end of include