
/*
 * Copyright (C) 2010/2011 Im-At-Home BV
 * All Rights Reserved
 * No copying, duplication or replication of code permitted without
 * express permission of Im-At-Home BV
 * 
 */

WorldLayer = function(id, color, regions) { return this.init(id, color, regions); };

$.extend(WorldLayer.prototype, {
	id: null,
	id_parent: null,
	regions : null,
	color : null,
	width : null,
	height : null,
	url : function() {
		var parent = $('#'+this.id_parent);
		if ((parent==null) || (parent=='undefined') || (this.regions == null)) return null;
		var width = $(parent).width();
		this.width = width;
		var height = $(parent).height();
		this.height = height;
		var urlOut = '/statistics/world/'+width+'/'+height+'?color='+this.color+'&country=';
		var countries = '';		
		for (var counter=0; counter< this.regions.length; counter++) {
			countries += (countries != '' ? ',':'') + this.regions[counter].toString();
		}
		return (urlOut+countries);
	},
	init : function(id, color, regions) {
		this.id_parent = id;
		this.id = new String().guid();
		this.regions = regions;
		this.color = color;		
		return this;
	},
	html : function() {
		var oHtml = '<li class="layer" id="'+ this.id + '" style="background-image: url('+this.url()+');" ></li>';
		return oHtml;
	}
});

GoogleMapContainer = function(id, mapobject, options) { return this.init(id, mapobject, options); };

$.extend(GoogleMapContainer.prototype, {
		 id: null,
		 gmap: null,
		 options: null,
		 locate: function(long, lat) {
			var location = new google.maps.LatLng(lat, long);
			this.gmap.setCenter(location);
		 },
		 home: function() {
			if(navigator.geolocation) {
				browserSupportFlag = true;
				navigator.geolocation.getCurrentPosition(
														 function(position) { 
															this.__showMap(position);
														 },
														 function() { 
															console.info('nogeo support');
														 });
			} else {
				console.info('No geo-support');
			}
		 },
		 zoom: function(level) {
			this.gmap.setZoom(level);
		 },
		 __showMap : function(position) {		 
			this.locate(position.coords.longitude, position.coords.latitude);
		 },
		 init : function(id, mapobject, options) {
			this.id = id;
			this.gmap = mapobject;
			this.options = options;
		 }
});

SlideshowContainer = function(id) { return this.init(id); };

$.extend(SlideshowContainer.prototype, {
		 id : null,
		 slides : null,
		 current : 0,
		 init : function(id) {
			this.id = id;
			this.current = 0;			
			this.slides = new Hashtable();
			this.__setup();
		 },
		 next : function() {
			this.gotoslide((this.current+1) % this.slides.count());
		 },
		 prev : function() {
			if (this.current > 0) {
				this.gotoslide(this.current-1);
			}
		 },
		 __setup : function() {
			var target = '#' + this.id;
			$(target).attr('data-current', this.current);
			if (this.slides.count() == 0) {
				var lis = $("footer ul.pips li", target);
				if (lis.length > 0) {
					for (var counter=0; counter < lis.length; counter++) {
						var url = $(lis[counter]).attr('data-url');
						if ((url != null) && (url != 'undefined')) {
							this.slides.add(counter.toString(), url);
						}
					}
					if (this.slides.count() > this.current) {
						$(target).css({"background-image": "url('"+this.slides.get(this.current)+"')"});
					}
				}
			} else {
				if (this.slides.count() > this.current) {
					$(target).css({"background-image": "url('"+this.slides.get(this.current)+"')"});
				}		 
			}
		 },		 
		 gotoslide : function(index) {		 
			if (this.current == index) return;		 
			var target = '#' + this.id;		 
			if (index < this.slides.count()) {		 		 
				$(target).css({"background-image": "url('"+this.slides.get(index.toString())+"')"});
		 
				$('.pips li.pip.selected', target).removeClass('selected');

				var pips = $('.pips li.pip', target);
				$(pips[index]).addClass('selected');
		 
				$(target).attr('data-current', index);				
				this.current = index;
			}
		 }
});


DataComponent = function(id) { return this.init(id); };

$.extend(DataComponent.prototype, {
	id: null,
	templates : null,
	datastore : null, // for later !!
	type : function() { return $('#'+this.id).attr('data-component'); },
	init : function(id) {
		this.id = id;
		this.__setup(); // get templates etc...
	},
	
	verify : function() {
		var htmlTemplates = $('.template', '#'+this.id);
		if (htmlTemplates.length > 0) {
			// we have templates - something seems different - reload them asap !!
			this.__loadTemplates(htmlTemplates, true);			
		}
	},
	
	__setup : function() {		
		var targetId = this.id;
		if ((targetId==null) || (targetId=='undefined') || (targetId=='')) return;				
		var htmlTemplates = $('.template', '#'+targetId);
		this.__loadTemplates(htmlTemplates, false);
	},
	
	__loadTemplates : function(htmlTemplates, reset) {
		
		if ((this.templates==null) || reset) {
			this.templates = new Hashtable();
		} else {
			if (htmlTemplates.length > 0) {
				for (var counter=0; counter< htmlTemplates.length; counter++) {
					$(htmlTemplates[counter]).remove();
				}
			}
			return;
		}
		if (htmlTemplates.length > 0) {
			for (var counter=0; counter< htmlTemplates.length; counter++) {
				
				if ($(htmlTemplates[counter]).parents('.template').length == 0) {
				
					var classid = $(htmlTemplates[counter]).attr('class');
					var classes = classid.split(' ');
					var out = '';				
					
					for (var xcount=0; xcount<classes.length; xcount++) {
						if (classes[xcount]!='template') out += '.'+classes[xcount];					
					}				
					
					if (this.templates.indexof(out)==-1) {					
						var content = $(htmlTemplates[counter]).html();
						var attributesraw = $(htmlTemplates[counter])[0].attributes;
						var attrs = {};
						for (var acount=0; acount<attributesraw.length; acount++) {
							attrs[attributesraw[acount].name] = attributesraw[acount].value;
						}
												
						this.templates.add(out, {'html':content, 'attr':attrs});
						$(htmlTemplates[counter]).remove();
					}
					
				} else {
					// template is nested.... 
				}
			}
		}
	}
});

App.UI.Core = {

	hasInit : false,
	componentsRegisterd : new Hashtable(),
	inprogress : false,

	__preinit : function() {		
		if (this.hasInit) return;
		this.hasInit = true;
		$('*').bind('page-refresh', function(object, data) {
			if (App.UI.Core.inprogress) {
				console.info('refresh in progress - aborting');
			}
			App.UI.Core.inprogress = true;
			App.UI.Core.refresh(data);
			App.UI.Core.inprogress = false;
		});				
	},
	
	attr : function(id, template, attribute) {
		if (id==null) return null;
		var dataComp = App.UI.Core.componentsRegisterd.get(id);
		if (dataComp != null) {
			if (dataComp.templates.indexof(template) != -1 ) {
				if (dataComp.templates.get(template).attr[attribute] != null) {
					return dataComp.templates.get(template).attr[attribute];		
				}
			}
		}
		return null;		
	},
	
	get : function(id, template) {
		if (id==null) return null;
		var dataComp = App.UI.Core.componentsRegisterd.get(id);
		if (dataComp != null) {
			if (dataComp.templates.indexof(template) != -1 ) {
				return dataComp.templates.get(template).html;		
			}
		}
		return null;
	},
	
	refresh : function(target) {
		if ((target == null) || (typeof(target) == 'object')) {
			$('body').find('[data-component]').each(function() { 
				App.UI.Core.__processComponent(this); 
			});										
		} else {
			if (($(target).attr('data-component') != null) && ($(target).attr('data-component') != 'undefined')) {
				App.UI.Core.__processComponent($(target)); 			
			} else {
				$(target).find('[data-component]').each(function() { 
					App.UI.Core.__processComponent(this); 
				});			
			}
		}
	},			
	
	__processComponent : function(target) {
		
		if ((target==null) || (target=='undefined')) return;
		
		var objectid = $(target).attr('id');
		
		if (App.UI.Core.componentsRegisterd.indexof(objectid) == -1) {
			// not in cache - prob havent seen it before .....
			var datacomp = new DataComponent(objectid);
			App.UI.Core.componentsRegisterd.add(objectid, datacomp);
		} else {
			var datacomp = App.UI.Core.componentsRegisterd.get(objectid);
			datacomp.verify();
		}
		
	},
			
	checkConditions : function(line) {
		
		var r=/(<condition[^>]*>)([\u0000-\u0320]+)/i;
		var q = /eval\=\"[^"]+\"/;
		var s=/(<result[A-Za-z0-9\=\_\'\" ]+>)([\u0000-\u0320]+)/i;		
		var m = null;
		
		while((m=r.exec(line))!=null&&m.length>1&&m[1]!='') {				
						
			var sequence = m[0].substring(0, m[0].indexOf('</condition>')+12);
			
			var toreplace= sequence;
			var evalsequence = false;			
			var oHtml = '';			
			
			if ((n=q.exec(m[1]))!=null) {				
				var evaluate = n[0].substr(6, n[0].length-7);
				evaluate = evaluate.replace('&lt;', '<');
				evaluate = evaluate.replace('&gt;', '>');
				if ((evaluate!='') && (evaluate != null) && (evaluate != 'undefined')) {
					if ((evaluate.indexOf('=')!=-1) || (evaluate.indexOf('>')!=-1) || (evaluate.indexOf('<')!=-1)) {
						evalsequence = eval(evaluate);
					} else {					
						evalsequence = evaluate;
					}
				} else {
					evalsequence = 'null';
				}
			} else {
				evalsequence = 'null';				
			}
			
			var o = null;
			
			while((o=s.exec(sequence))!=null&&o.length>1&&o[1]!='') {				
				var resultentry = o[0].substring(0, o[0].indexOf('</result>')+9);
				var resulteval = o[1].substring(o[1].indexOf('is="')+4);
				resulteval = resulteval.substring(0, resulteval.indexOf('"'));
				var textout = jQuery.trim((o[0].substring(o[1].length, o[0].indexOf('</result>'))));				

				if ((resulteval == evalsequence.toString()) || (resulteval=='default')) {
					oHtml += textout;
					break;
				}				
				sequence = sequence.replace(resultentry, '');				
			}
			
			line = line.replace(toreplace, oHtml);
			
		}
		
		return line;
		
	},
	
	doReplaceDir : function(line, prefix) {
		
		if ((prefix==null)  || (prefix=='undefined')) prefix = '';
		var rep = new RegExp('(replace\=\"'+prefix+'[^"]+\")');
		//var rep=/(replace\=\"[^"]+\")/;		
		var sequence = '';
		var m;
		
		// check for replace directive....		
		while((m=rep.exec(line))!=null&&m.length>1&&m[1]!=''){
			sequence=m[1].substr(9, m[1].length-10);
			line = line.replace(m[1], sequence);
		}
		
		return line;
	},
	
	doVarSubstitution : function(data, line) {
		
		if ((line=='') || (line==null) || (line=='undefined') || (data==null)) return line;
		
		line = this.doReplaceDir(line);
		
		var r=/(%[^%]+%)/;
		var sequence = '';
		var m;
		var dataItem = null;
				
		while((m=r.exec(line))!=null&&m.length>1&&m[1]!=''){
			
			sequence=m[1].substr(1, m[1].length-2);
			
			var defaultvalue = '';
			var lookup = null;
			var keyword = '';
			var isarray = false;
			var done = false;
			var arraycontent = null;
			var formatting = null;
			var datatype = null;
			
			// check for default....
			
			var posrepl = sequence.indexOf('$');
			if ( posrepl != -1) { // sequence start..
				isarray = true;
				keyword = sequence.substring(0,posrepl);
				arraycontent = sequence.substring(posrepl+1);
				done = true;
			}
			
			var posdef = sequence.indexOf('|');
			if ((!done) && (posdef != -1)) {
				// is there is a default value to show.....
				defaultvalue = sequence.substring(posdef+1);
				keyword = sequence.substring(0,posdef);
				done = true;
			}
			
			var poscol = sequence.indexOf(':');
			if ((!done) && (poscol != -1)) {
				// is there is a default value to show.....				
				var rightbit = sequence.substring(poscol+1);
				var dtype = rightbit.indexOf(':');
				if (dtype != -1) {
					datatype = rightbit.substring(0, dtype);
					formatting = rightbit.substring(dtype+1);
				} else {
					datatype = 'date';
					formatting = rightbit;
				}		
				keyword = sequence.substring(0,poscol);
				done = true;				
			}			
			
			var possub = sequence.indexOf('#');
			if ((!done) && (possub != -1)) {
				var options =  sequence.substring(possub+1).split(',');
				if (options.length > 0) {
					lookup = new Array();
					for (var ocounter=0; ocounter<options.length; ocounter++) {
						var ioption = options[ocounter].split('=');
						lookup['o'+ioption[0].toString()] = ioption[1];
					}
				}
				keyword = sequence.substring(0, possub);
				done = true;				
			}
			
			if (keyword == '') keyword = sequence;			
			dataItem = null;
			
			try {
				
				if (keyword.indexOf('.') != -1) {
					
					var splitUp = keyword.split('.');
					var counter = 0;
					var dpointer = data;
					
					while ((counter < splitUp.length) && (dpointer != null)) {
						if (dpointer[splitUp[counter]] != null) {
							if (dpointer[splitUp[counter]] != null) {
								dpointer = dpointer[splitUp[counter]];
							} else {
								dpointer = null;
								break;
							}
						} else {
							dpointer = null;
							break;
						}
						counter++;
					}
										
					dataItem = (lookup != null) ? lookup['o'+dpointer.toString()] : dpointer; 
					
				} else {
					if ((keyword!=null) && (data != null)) {
						if (data[keyword] != null) {
							var dataItem = null;
							if (lookup != null) {
								if (lookup['o'+data[keyword].toString()] != null) {
									dataItem = lookup['o'+data[keyword].toString()];
								} else {
									dataItem = (lookup['odef'] != null) ? lookup['odef'] : data[keyword];  									
								}
							} else {
								dataItem = data[keyword];
							}
						} else {
							dataItem = null;
						}
					} else {
						dataItem = null;
					}
				}
				
			} catch (err) {
				//console.info(err);
				dataItem = null;
			}
			
			if (!isarray) {			
				
				if (formatting != null) {
					
					switch (datatype) {
						
						case 'eval': {
							try {
								formatting = formatting.replace(/&amp;37;/gi,'%');
								formatting = formatting.replace(/&amp;7c;/gi,'|');
								var question = this.doVarSubstitution(data, formatting);
								dataItem = eval(question);
							}
							catch (err) {
								//console.info('An error occurred in the eval');
								console.info('error in line = '+line);	
							}
							break;
						}
					
						case 'string': {
							if ((dataItem=='undefined') || (dataItem==null)) {
								dataItem = '';
							} else {
								if (dataItem.length > formatting) {
									dataItem = dataItem.substring(0, formatting) + '...';
								}
							}
							break;
						}
					
						case 'date': {
							try {
								if ((dataItem == null) || (dataItem=='undefined')) {
									dataItem = '';
								} else {									
									date = Date.frommysql(dataItem);
									dataItem = date.format(formatting);
								}
							}
							catch (err) {
								console.info('error in line = '+line);								
							}
							break;
						}
										
					}
										
				}
				
				line = ((dataItem != null) && (dataItem !='undefined') && (dataItem != '')) ?
						line.replace(m[1], dataItem) : line.replace(m[1], defaultvalue);
										
			} else {
				var oHtml = '<ul class="clear">';
				if ((dataItem != null) && (dataItem.length>0)) {

					arraycontent = arraycontent.replace(/&amp;37;/gi,'%');
					arraycontent = arraycontent.replace(/&amp;35;/gi,'#');
					arraycontent = arraycontent.replace(/&amp;39;/gi,'\'');
					arraycontent = arraycontent.replace(/&amp;61;/gi,'=');
					arraycontent = arraycontent.replace(/&amp;7c;/gi,'|');
					
					for (var counter = 0; counter< dataItem.length; counter++) {
						var subst = this.doVarSubstitution(dataItem[counter], arraycontent);
						if ((dataItem[counter] != null) && (dataItem[counter].id != 'undefined') && (dataItem[counter].id != null)) {
							oHtml += '<li data-id="' + dataItem[counter].id + '">' + subst + '</li>';							
						} else {
							oHtml += '<li>' + subst + '</li>';
						}
					}
				}
				
				oHtml += '</ul>';
				
				line = line.replace(m[1], oHtml);
			}
						
		}
		
		return this.checkConditions(line);
		
	},		

	sortOn : function(arr) {
		if (arr && arr.length > 0) {
			return function(a,b) {
				var asub, bsub, prop, direction;
				for (var i=0; i<arr.length; i++) {
					prop = arr[i];
					if (prop[0]=='!') {
						direction = -1;
						prop = prop.substring(1);
					} else {
						direction = 1;
					}
					
					asub = (a[prop] != null) ? a[prop] : '';					
					bsub = (b[prop] != null) ?  b[prop] : '';
					
					if ( asub < bsub ) return (direction*-1);
					if ( asub > bsub ) return (direction*1);
				}
				return 0;
			};
		} else {
			return function(a,b) { return a<=b; };
		}
	}
	
};

App.UI.DataServices = {

	dataStore : new Hashtable(),
	oldData : new Hashtable(),
	curPtrs : new Hashtable(),
	dataitems : new Hashtable(), //persistent datastorage
	
	hasInit : false,

	__preinit : function() {
	
		if (this.hasInit) return;
		this.hasInit = true;
	
		$('*').bind('page-refresh page-changed', function(object, data) {
			if (data == 'undefined') data = null;
			if (object.type == 'page-changed') {
				while (App.UI.DataServices.curPtrs.count() > 0) {
					var pointer = App.UI.DataServices.curPtrs.pop();		
					if (pointer != null) pointer.abort();				
				}
			}
			App.UI.DataServices.refresh();
		});
	},
	
	getDataItem : function(spacename, data) {
		if (data=='undefined') data = null;
		if ((spacename==null) || (spacename=='undefined')) return null;
		
		if (!App.UI.DataServices.dataitems.exists(spacename)) {
			if (data!=null) {
				App.UI.DataServices.dataitems.add(spacename, data);				
			} else {
				App.UI.DataServices.dataitems.add(spacename, new Array());
			}
			console.info('created dynamic memory space '+spacename);
		} else {
			if (data != null) {
				App.UI.DataServices.dataitems.add(spacename, data);
			}
		}
		return App.UI.DataServices.dataitems.get(spacename);
	},
	
	getData : function(url, target, callback) {
		
		if (callback==null) return;
		
		if (App.UI.DataServices.oldData.indexof(url) != -1) {
			callback(App.UI.DataServices.oldData.get(url), target);
			return;
		}
				
		var pointer = $.ajax({
			type: "get",
			dataType: "text",										// we get this as text as otherwise cant do comparison
			error: function(data) {
				App.UI.DataServices.__recoverFailed(data, target);
			},
			success: function(data) {
				App.UI.DataServices.oldData.add(url, data);
				App.UI.DataServices.curPtrs.remove(url);
				callback(data, target);
			},				
			url: url, 
			data:{}
		});		
		
		App.UI.DataServices.curPtrs.add(url, pointer);
		
	},
		
	__recoverFailed : function(data, target) {
		$(target).attr('data-callinpro', false);
	},
	
	clear : function() {
		// console.info('info / Dataservices clear of all data');
		App.UI.DataServices.oldData.clear();
		App.UI.DataServices.dataStore.clear();		
	},
	
	refresh : function() {
		// clear the data !!
		App.UI.DataServices.clear();
	}	
	
};

App.UI.HideAndSeek = {

	hasInit : false,
	delay : 10000,
	
	__preinit : function() {
		
		if (this.hasInit) return;
		this.hasInit = true;
		
		$('*').bind('data-refresh', function(object, data) {
			if (data != null) {
				var parent = $($(data.object).parent()).attr('data-component');
				if ((parent != null) && (parent != 'undefined') && (parent == 'peekaboo')) {
					App.UI.HideAndSeek.refresh($(data.object).parent()); 					
				}
			}
		});	
				
	},
		
	refresh : function(target) {

		if ((target=='undefined') || (target==null)) target = null;		
		
		if (target==null) {
			$('body').find('[data-component="peekaboo"]').each(function() { 
				App.UI.HideAndSeek.setup(this); 
			});			
		} else {
			App.UI.HideAndSeek.setup(target); 
		}
		
	},
	
	setup : function(target) {
	
		if ((target==null) || (target=='undefined')) return;		
		var lis_available = $('li', target);				
		var count = lis_available.length;
		var index = 0;
				
		$(target).attr({'data-count':count, 'data-index':index});
		
		if (count > 0) {
			$(lis_available).hide();
			App.UI.HideAndSeek.doFadeIn(target);
		}
		
	},
	
	doFadeOut : function(target) {
		
		if (target==null) return;
		$('li.in', target).fadeOut('fast', function() {
			$(this).removeClass('in');			
			App.UI.HideAndSeek.doFadeIn(target);
		});
		
	},
	
	doFadeIn : function(target) {
		
		if (target==null) return;
		
		var index = parseInt($(target).attr('data-index'));
		var count = parseInt($(target).attr('data-count'));		
		var lis = $('li', target);
		
		if (index < lis.length) {
			$(lis[index]).fadeIn('fast', function() {
				$(this).addClass('in');
				var nextindex = (index+1) % count;
				if (nextindex != index) {
					$(target).attr('data-index', nextindex);
				}
				$.doTimeout(App.UI.HideAndSeek.delay, function() { // 30 seconds
					App.UI.HideAndSeek.doFadeOut(target);
					return false;
				});								
			});
		}
				
	}
	
};

Person = function(parent, text, url) { return this.init(parent, text, url); };

$.extend(Person.prototype, {
	id : null,
	userid : null,
	title : 'No title',
	url : '',
	type : function() { return 'Person'; },
	x : function() { return $('#'+this.id).position().left; },
	y : function() { return $('#'+this.id).position().top; },
	width: function() { return $('#'+this.id).width(); },
	height: function() { return $('#'+this.id).height(); },
	parent: null,
	init : function(parent, text, url) {				
		this.id = new String().guid();
		this.parent = parent;
		this.title = text;
		this.url = url;
		
		var oHtml = '';
		var urlOut = this.url;

		if (this.url == '') urlOut = 'https://graph.facebook.com/1/picture';
				
		oHtml += '<span id="'+this.id+'" class="person" title="'+this.title+'" style="background-image: url(\''+ urlOut + '\');"></span>';		
		
		$(parent).append(oHtml);		
		
		return this;
	},	
	redraw : function() {		
		var urlOut = this.url;
		if (this.url == '') urlOut = 'https://graph.facebook.com/1/picture';
		if (this.parent != null) {
			if ($('#'+this.id, this.parent).length > 0) {
				$('#'+this.id).css({'background-image':'url(\''+urlOut+'\')'});
				$('#'+this.id).attr('title', this.title);						
			} else {
				var oHtml = '<span id="'+this.id+'" class="person" title="'+this.title+'" style="background-image: url(\''+ urlOut + '\');"></span>';						
				$(this.parent).append(oHtml);						
			}
		}
	},	
	close : function() {
		this.parent.remove('#'+this.id);
		$('*').triggerHandler('object-closed', {'id': this.id, 'type':'person'});
	}
});


App.UI.PeopleGallery = {

	hasInit : false,
	img : [51,51],
	objects : new Hashtable(),
	
	__preinit : function() {
		
		if (this.hasInit) return;
		this.hasInit = true;

		$('*').bind('page-refresh data-refresh', function(object, data) { App.UI.PeopleGallery.refresh(null); });	
		$('*').bind('object-closed', function(object, data) { App.UI.PeopleGallery.removeItem(null); });	
		
		$('[data-component="peoplegallery"]').live('click', function(oEvent) {
			return;
		});				
	
	},
	
	removeItem : function() {
		
	},
	
	refresh : function(target) {
		if ((target=='undefined') || (target==null)) target = null;				
		if (target==null) {
			$('body').find('[data-component="peoplegallery"]').each(function() { 
				App.UI.PeopleGallery.setup(this); 
			});			
		} else {
			App.UI.PeopleGallery.setup(target, 'full'); 
		}		
	},
	
	resize : function() {
		
	},
	
	setup : function(target, mode) {
		
		if (target==null) return;

		if ((mode=='undefined')||(mode==null)) mode='full';
		
		var width = $(target).width();
		var height = $(target).height();
		
		var numx = parseInt(width / this.img[0]);
		var numy = parseInt(height / this.img[1]);
		
		var total = (numx*numy);
		
		if (this.objects.count() < total) {
			while (this.objects.count() < total) {
				var newPerson = new Person(target, '', '');
				this.objects.add(newPerson.id, newPerson);
			}
		} else {
			if (this.objects.count() > total) {
				var personObject = this.objects.pop();
				personObject.close();
			} else {
				for (var counter=0; counter< total; counter++) {
					var personObject = this.objects.itemat(counter);
					personObject.parent = $(target);
					personObject.redraw();
				}
			}
		}

		var datasource = $(target).attr('data-datasource');
		if ((datasource=='undefined') || (datasource==null)) datasource = null; 

		var callinpro = $(target).attr('data-callinpro');
		if ((callinpro=='undefined') || (callinpro==null)) { 
			callinpro = false;		
		} else {
			callinpro = callinpro.toString().bool();
		}
				
		if ((datasource != null) && (datasource != '') && (!callinpro)) {
			$(target).attr('data-callinpro', true);					
			App.UI.DataServices.getData(datasource, target, App.UI.PeopleGallery.__processJsonData);			
		}				
		
	},

	__processJsonData : function(datain, target, dataonly) {

		$(target).attr('data-callinpro', false);

		if (datain==null) return;
		var data = jQuery.parseJSON(datain);

		var countresults = (data!=null) ? data.length : 0;
		var counter = 0;
		var count = $(target).children().length;
		
		while (counter<count) {
			var personObject = App.UI.PeopleGallery.objects.itemat(counter);
			if (counter < countresults) {
				personObject.url = data[counter].image;
				personObject.title = data[counter].displayname;
				personObject.userid = data[counter].id;
				personObject.redraw();
			} else {
				personObject.url = '';
				personObject.title = '';
				personObject.userid = null;
				personObject.redraw();				
			}			
			counter++;
		}
		
	}

},

App.UI.Select = {
				
	hasInit : false,
	
	__preinit : function() {
		
		if (this.hasInit) return;
		this.hasInit = true;
		
		$('*').bind('data-refresh', function(object, data) { App.UI.Select.__refreshReceived(data); });	
				
	},

	__refreshReceived : function(data) {
		$('body').find('select[data-value]').each(function() {						
			App.UI.Select.__updateSelector(this); 			
		});				
	},

	refresh : function() {
		this.__refreshReceived(null);
	},
	
	__updateSelector : function(target) {
		if (target==null) return;
		if ($(target).parents('.template').length != 0) return;
		var optionValue = $(target).attr('data-value');
		$('option[value='+ optionValue +']', $(target)).attr('selected', 'selected');
	}
		
};

App.UI.SmartInput = {
	
		hasInit : false,
		
	__preinit : function() {
		
		if (this.hasInit) return;
		this.hasInit = true;

		$('*').bind('page-refresh data-refresh', function(object, data) { App.UI.SmartInput.refresh(null); });	
		
		$('[data-component="smart"]').live('change keyup', function(oEvent) {
			App.UI.SmartInput.setup(oEvent.currentTarget); 
		});				
	
	},
	
	refresh : function(target) {
		if ((target=='undefined') || (target==null)) target = null;		
		
		if (target==null) {
			$('body').find('[data-component="smart"]').each(function() { 
				App.UI.SmartInput.setup(this); 
			});			
		} else {
			App.UI.SmartInput.setup(target); 
		}
		
	},
	
	setup : function(target) {
		
		if ((target=='undefined') || (target==null)) return;
		
		var datatarget = $(target).attr('data-target');
		if ((datatarget=='undefined') || (datatarget=='')) datatarget = null;
		
		var dataprefix = $(target).attr('data-prefix');
		if ((dataprefix=='undefined') || (dataprefix==null)) dataprefix = '';
				
		var datavar = $(target).attr('data-var');
		if ((datavar=='undefined') || (datavar=='')) datavar = null;
		
		if ((datavar==null) || (datatarget==null)) return;		
		
		var currentvalue = null;
				
		switch (target.tagName)
		{
			case 'SELECT': {
				currentvalue = dataprefix + $(':selected', target).attr('data-value');	
				break;
			}
			case 'INPUT': {
				currentvalue = dataprefix + $.URLEncode($(target).val());				
				break;
			}
			default: {
				console.info('object is unsupport at the moment / type ' + target.tagName);				
			}
		}
		
		var targetvalue = $('#'+datatarget).attr(datavar);
		
		if ((currentvalue != null) && (targetvalue != currentvalue)) {
			$('#'+datatarget).attr(datavar, currentvalue);
			var oData = { 'object': target }; 		
			if ($('#'+datatarget).attr('data-callinpro') == 'true') {
				$('#'+datatarget).attr('data-callinpro', 'false');
			}
			$('*').triggerHandler('page-refresh', oData); // inform everyone that the grid dynamics just changed !!			
		}
		
	}
		
};


App.UI.DropDown = {
	
	hasInit : false,

	__preinit : function() {
		
		if (this.hasInit) return;
		this.hasInit = true;
		
		$('*').bind('data-refresh page-refresh', function(object, data) { App.UI.DropDown.refresh(null); });	
		
	},

	refresh : function(target) {

		if ((target=='undefined') || (target==null)) target = null;		
		
		if (target==null) {
			$('body').find('[data-component="dropdown"]').each(function() { 
				App.UI.DropDown.__getData(this); 
			});			
		} else {
			App.UI.DropDown.__getData(target); 
		}
		
	},

	__getData : function(target) {
		
		if (target==null) return;

		var datasource = $(this).attr('data-source');
		if ((datasource == 'undefined') || (datasource == null)) datasource = null;

		$.ajax({
			type: "get",
			dataType: "text",										// we get this as text as otherwise cant do comparison
			error: function(data) {
				// do nothing...
			},
			success: function(data) {

				var data = jQuery.parseJSON(datain);
				if (data == null) return;

				var propname = $(target).attr('data-propname');
				if ((propname == 'undefined') || (propname == null)) propname = 'display';
												
				var oHtml = '';
				if (data.length >0) {
					for (var counter=0; counter< data.length; counter++) {
						oHtml += '<option value="'+ data[counter].id +'">'+ data[counter][propname] +'</option>';												
					}
				}
				
				$('#'+ target).html(oHtml);
				$('#'+ target).change();
								
			},				
			url:datasource, 
			data:{}
		});
		
	}
	
};

App.UI.Pager = {
	
	hasInit : false,
	
	__preinit : function() {
		
		if (this.hasInit) return;
		this.hasInit = true;
		
		$('*').bind('data-refresh', function(object, data) { App.UI.Pager.__refreshReceived(data); });	
		
		$('[data-component="pager"] .pager_info li').live('click', function(oEvent) { 
			App.UI.Pager.mouseControl_page(oEvent);
		});
		
	},
	
	mouseControl_page : function(oEvent) {

		if (oEvent == null) return;
		
		// get the parent and then the data source as we are completely async..
		
		var parent = $(oEvent.currentTarget).parents('[data-component="pager"]');
		var datasource = $(parent).attr('data-source');
		
		if ((datasource == 'undefined') || (datasource == null)) datasource = null;		
		if (datasource==null) return;

		var source = $('#'+datasource);
		if (source==null) return;
		
		var sourcetype = $(source).attr('data-component');
		var pageInfo = null;

		switch (sourcetype) {
			case 'list': {
				pageInfo = App.UI.List.getPageInfo(source);				
				break;
			}
			case 'repeater': {
				pageInfo = App.UI.Repeater.getPageInfo(source);				
				break;
			}
			case 'pictureselector': {
				pageInfo = App.UI.PictureSelector.getPageInfo(source);				
				break;
			}						
			default: {
				break;
			}
		}
		
		switch (oEvent.type) {
		
			case 'click': {			
				var pageno = -1;
				if ($(oEvent.currentTarget).hasClass('pageno')) {
					if ($(oEvent.currentTarget).hasClass('selected')) return;
					pageno = parseInt($(oEvent.currentTarget).attr('data-pageno'));
				}
				if ($(oEvent.currentTarget).hasClass('last')) {
					pageno = (pageInfo.pagemax-1);
				}
				if ($(oEvent.currentTarget).hasClass('start')) {
					pageno = 0;
				}
				if ($(oEvent.currentTarget).hasClass('next')) {
					if (pageInfo.pageno < (pageInfo.pagemax-1)) {
						pageno = pageInfo.pageno+1;
					}
				}				
				if ($(oEvent.currentTarget).hasClass('prev')) {
					if (pageInfo.pageno > 0) {
						pageno = pageInfo.pageno-1;
					}
				}
				if (pageno != -1) {
					$('li.selected', $(oEvent.currentTarget).parent()).removeClass('selected');
					switch (sourcetype) {
						case 'list': {
							App.UI.List.changePage(source, pageno);											
							break;
						} 
						case 'repeater': {
							App.UI.Repeater.changePage(source, pageno);				
							break;
						}
						case 'pictureselector': {
							App.UI.PictureSelector.changePage(source, pageno);				
							break;
						}
					}
					//$('li.pageno[data-pageno|="'+ pageno +'"]', $(oEvent.currentTarget).parent()).addClass('selected');
					this.__createPager(parent, false);
				}
				break;
			}
		
		}
		
	},
	
	__refreshReceived : function(data) {
	
		if (data==null) return;
		
		$('body').find('[data-component="pager"]').each(function() {			
			
			var datasource = $(this).attr('data-source');
			if ((datasource == 'undefined') || (datasource == null)) datasource = null;
			
			var notificationsource = $(data.object).attr('id');
			if ((notificationsource == 'undefined') || (notificationsource == null)) notificationsource = null;
			
			if ((notificationsource != null) && (notificationsource == datasource)) {
				App.UI.Pager.__createPager(this, data.datachanged); 
			}
			
		});		
		
	},
	
	__createPager : function(target, datachanged) {
		
		if (target==null) return;	
		// when we get here we are inside the pager...
		
		var datasource = $(target).attr('data-source');
		if ((datasource == 'undefined') || (datasource == null)) datasource = null;		
		if (datasource==null) return;
		
		var source = $('#'+datasource);
		if (source==null) return;
		
		var sourcetype = $(source).attr('data-component');
		var pageInfo = null;

		switch (sourcetype) {
			case 'list': {
				pageInfo = App.UI.List.getPageInfo(source);				
				break;
			}
			case 'repeater': {
				pageInfo = App.UI.Repeater.getPageInfo(source);				
				break;
			}
			case 'pictureselector': {
				pageInfo = App.UI.PictureSelector.getPageInfo(source);				
				break;
			}			
			default: {
				break;
			}
		}
		
		if (pageInfo==null) return;

		var pagefrom = pageInfo.pageno - 1;
		var pageto = pageInfo.pageno + 3;
		
		if (pagefrom < 1) pagefrom = 1;
		if (pageto > pageInfo.pagemax) pageto = pageInfo.pagemax;

		if (datachanged) {
		
			oHtml = '<ul class="pager_info">';
			
			oHtml += '<li class="start"><span>|&lt;</span></li>';
			oHtml += '<li class="prev"><span>&lt;</span></li>';
				
			for (var pageno=1; pageno<=pageInfo.pagemax; pageno++) {		
				if ((pageno>=pagefrom) && (pageno<=pageto)) {
					oHtml += '<li class="pageno' + (((pageno-1)==pageInfo.pageno)?' selected':'') +'" data-pageno="'+ (pageno-1) + '"><span>'+ pageno + '</span></li>';				
				} else {
					oHtml += '<li class="pageno' + (((pageno-1)==pageInfo.pageno)?' selected':'') +'" style="display: none;" data-pageno="'+ (pageno-1) + '"><span>'+ pageno + '</span></li>';
				}
			}
			
			oHtml += '<li class="next"><span>&gt;</span></li>';
			oHtml += '<li class="last"><span>&gt;|</span></li>';
			
			oHtml += '</ul>';
			
			$(target).html(oHtml);
		
		} else {

			var lis = $('li.pageno', $(target));
			$(lis).removeClass('selected');
			for (var pageno=1; pageno<= lis.length; pageno++) {
				if ((pageno-1)==pageInfo.pageno) {
					$(lis[pageno-1]).addClass('selected');
				}
				$(lis[pageno-1]).css({'display':( ((pageno>=pagefrom) && (pageno<=pageto)) ? 'inline-block':'none' )});
			}
			
		}
		
	}
	
};

App.UI.Worldview = {
		
	hasInit : false,
	layers : new Hashtable(),

	__preinit : function(){
		
		if (this.hasInit) return;
		this.hasInit = true;
		
		$('*').bind('page-refresh', function(object, data) { App.UI.Worldview.refresh(data); });	
		
	},
	
	refresh : function(target) {
		
		if ((target == 'undefined') || (target==null)) target = null;

		if ((target==null) || (typeof(target) == 'object')) {
			$('body').find('[data-component="worldview"]').each(function() { 
				App.UI.Worldview.setup(this); 
			});			
		} else {
			$(target).find('[data-component="worldview"]').each(function() { 
				App.UI.Worldview.setup(this); 
			});			
		}
		
	},		
	
	setup : function(target)
	{
		
		if (target==null) return;
		
		var tid = $(target).attr('id');
		if ((tid==null) || (tid=='undefined')) return;
		
		if ($('ul.layers', $(target)).length == 0) {
			$(target).html('<ul class="layers"></ul>');
		}
		
		// get data....
		this.getData(null, target, true);
		
	},
	
	getLayers : function(target)
	{
		if (target == null) return null;
		
	},

	getData : function(datain, target, force)
	{
			
		if ((force==null) || (force=='undefined')) force=false;
		
		if (target==null) return;		
		var datasource = $(target).attr('data-datasource');
		if ((datasource==null) || (datasource=='undefined')) datasource = null;
		if (datasource==null) return;
		
		var tid = $(target).attr('id');
		
		if ((datain==null) && (!force)) return;
		
		if (force) {

			// go get the data...
			
			if (datasource.startsWith('arr:')) {			
				var space = datasource.substring(4);
				dataIn = App.UI.DataServices.getDataItem(space);				
			} else {
				App.UI.DataServices.getData(datasource, target, App.UI.Worldview.getData);				
			}			
			
			return;
		}

		App.UI.Worldview.layers.clear();
		var oHtml = '';
		var data = null;
		
		if (typeof datain == 'string') {
			data = jQuery.parseJSON(datain);
		} else {
			data = datain;			
		}
		
		jQuery.parseJSON(datain);

		if ((data != null) && (data.length>0)) {
			for (var counter=0; counter<data.length; counter++) {
				var layer = new WorldLayer(tid, data[counter].color, data[counter].regions);
				App.UI.Worldview.layers.add(layer.id, layer);
				oHtml += layer.html();
			}
		}
				
		$('ul.layers', $(target)).html(oHtml);
		
		return;
		
	}
		
};

App.UI.PictureSelector = {

	hasInit : false,
	
	__preinit : function(){
		
		if (this.hasInit) return;
		this.hasInit = true;
		
		$('*').bind('page-refresh', function(object, data) { App.UI.PictureSelector.refresh(data); });	

		$('[data-component="pictureselector"] .imagethumb_sm').live('click', function(oEvent) { 
			App.UI.PictureSelector.mouseControl(oEvent);
		});
		
	},
	
	mouseControl : function(oEvent) {
		
		if (oEvent == null) return;

		var parent = $(oEvent.currentTarget).parents('[data-component="pictureselector"]');	
		
		switch (oEvent.type) {
		
			case 'click': {
				var id = $(oEvent.currentTarget).attr('data-id');
				var oData = { 'object': parent, 'id': id }; 		
				$('*').triggerHandler('item-selected', oData); 	
				break;
			}
		
		}
		
	},
	
	refresh : function(target) {
		
		if ((target == 'undefined') || (target==null)) target = null;

		if ((target==null) || (typeof(target) == 'object')) {
			$('body').find('[data-component="pictureselector"]').each(function() { 
				App.UI.PictureSelector.setup(this); 
			});			
		} else {
			$(target).find('[data-component="pictureselector"]').each(function() { 
				App.UI.PictureSelector.setup(this); 
			});			
		}
		
	},
	
	getPageInfo : function(target) {
		
		var pageno = $(target).attr('data-page');
		pageno = ((pageno == 'undefined') || (pageno == null)) ? 0 : parseInt(pageno);

		var pagesize = $(target).attr('data-pagesize');
		pagesize = ((pagesize == 'undefined') || (pagesize == null)) ? 0 : parseInt(pagesize);

		var pagemax = $(target).attr('data-pagemax');
		pagemax = ((pagemax == 'undefined') || (pagemax == null)) ? 0 : parseInt(pagemax);
		
		var offset = pageno*pagesize; // calculate the offset of the data

		return {'pageno': pageno, 'pagesize': pagesize, 'pagemax': pagemax, 'offset': offset};
		
	},

	changePage : function(target, pageNo) {

		if (target==null) return;		
		pageNo = ((pageNo == 'undefined') || (pageNo == null)) ? 0 : parseInt(pageNo);
		
		var pageInfo = this.getPageInfo(target);
		if ((pageNo >= 0) && (pageInfo.pageno != pageNo) && (pageNo < pageInfo.pagemax)) {			
			// change the page number...
			$(target).attr('data-page', pageNo);			
			//refresh the page
			this.setup(target);	
		}
		
	},
	
	setup : function(target) {
		
		if ((target == 'undefined') || (target == null)) return;
		
		var datasource = $(target).attr('data-url');
		if ((datasource == 'undefined') || (datasource=='')) datasource = null;		
		
		if (datasource == null) return;
		
		var pageno = $(target).attr('data-page');
		if ((pageno == 'undefined') || (pageno == null)) pageno = 0;
		pageno = parseInt(pageno);
		if (pageno < 0) pageno = 0;
				
		$(target).attr('data-page', pageno);
		
		var url = datasource + '/' + pageno;

		$.ajax({
			type: "get",
			dataType: "text",										// we get this as text as otherwise cant do comparison
			error: function(data) {
				App.UI.PictureSelector.__recoverFailed(data, target);
			},
			success: function(data) {
				App.UI.PictureSelector.__processJsonData(data, target);
			},				
			url: url, 
			data:{}
		});	
				
	},
		
	__processJsonData : function(datain, target) {
		
		if ((datain == null) || (target == null)) return;
		
		var data = jQuery.parseJSON(datain); 

		$(target).attr({'data-page':data.info.page, 'data-pagemax':data.info.pagemax, 'data-total':data.info.total});
		
		var oHtml = '';
		if ((data != null) && (data.photos != null) && (data.photos.length > 0)) {
			for (var counter=0; counter < data.photos.length; counter++) {
				var photo = data.photos[counter];
				var actualurl = photo.url_actual;
				if ((actualurl == 'undefined') || (actualurl == null)) actualurl = '';
				oHtml += '<div class="imagethumb_sm" data-id="' + photo.id + '" data-url="' + actualurl + '" style="background-image: url('+ photo.url + ')"></div>';				
			}
		}

		$(target).html(oHtml);

		var oData = { 'object': target, 'pageno': parseInt(data.info.page), datachanged: true }; 		
		$('*').triggerHandler('data-refresh', oData); // inform everyone that the grid dynamics just changed !!

	},
	
	__recoverFailed : function(datain, target) {

	}
	
};

App.UI.List = {
	
	hasInit : false,
	
	__preinit : function() {
		
		if (this.hasInit) return;
		this.hasInit = true;
		
		$('*').bind('page-refresh', function(object, data) {
			var target = (data!=null) ? data.target : null;
			App.UI.List.refresh(target);			
		});
		
		$('[data-component="list"] dt.row').live('click', function(oEvent) { 
			App.UI.List.mouseControl_row(oEvent);
		});
		
		$('[data-component="list"] dt.titlebar .sortable').live('click', function(oEvent) { 
			App.UI.List.mouseControl_sort(oEvent);
		});
		
	},
	
	refresh : function(target) {

		if ((target=='undefined') || (target==null)) target = null;		
			
		if ((target==null) || (typeof(target) == 'object')) {
			$('body').find('[data-component="list"]').each(function() { 
				App.UI.List.__createList(this); 
			});			
		} else {
			if ($(target).attr('data-component') != null) {
				App.UI.List.__createList($(target));				
			} else {
				$(target).find('[data-component="list"]').each(function() { 
					App.UI.List.__createList(this);
				});
			}
		}
		
	},

	mouseControl_sort : function(oEvent) {
		
		switch (oEvent.type) {
			
			case 'click': {
				
				var sortField = $(oEvent.currentTarget).attr('data-sort');
				if ((sortField=='undefined') || (sortField==null)) sortField = '';
				
				var parent = $(oEvent.currentTarget).parents('[data-component="list"]');	
				if (!$(oEvent.currentTarget).hasClass('sort')) {
					$('dt.titlebar .sortable.sort', parent).removeClass('sort');
				}
				$('dt.titlebar .sortable.desc', parent).removeClass('desc');
				
				var currentSearch = $(parent).attr('data-sorton');
				if ((currentSearch == 'undefined') || (currentSearch == null)) currentSearch = '';
				
				if (currentSearch != '') {
					if (currentSearch[0]!='!') {
						if (currentSearch==sortField) {
							// invert the search...
							sortField = '!' + sortField;
							$(oEvent.currentTarget).addClass('desc');
						}
					} 
				}				
				
				$(parent).attr('data-sorton', sortField);
				
				if (!$(oEvent.currentTarget).hasClass('sort')) {
					$(oEvent.currentTarget).addClass('sort');
				}
				
				if (sortField[0] == '!') {
					$(oEvent.currentTarget).addClass('desc');
				}

				// refreshes the data
				this.__processJsonData(null, parent, true);	
				
				break;
			}
			
		}
		
	},
	
	mouseControl_row : function(oEvent) {

		if (($(oEvent.target).hasClass('pagenav')==true) || ($(oEvent.target).attr('data-event')!=null) || ($(oEvent.target).attr('data-url')!=null)) {
			oEvent.preventDefault();
			return;
		}
		
		switch (oEvent.type) {
					
			case 'click': {

				var parent = $(oEvent.currentTarget).parents('[data-component="list"]');
				
				var mode = $(parent).attr('data-mode');				
				if ((mode == 'undefined') || (mode == null)) mode = null;					
																				
				if (mode != null) {
					
					switch (mode) {
					
						case 'true': 
						case 'multi': {
							if ($(oEvent.currentTarget).hasClass('selected')) {
								$(oEvent.currentTarget).removeClass('selected');				
							} else {
								$(oEvent.currentTarget).addClass('selected');											
							}							
							break;
						}
						
						case '2state': {
							if ($(oEvent.currentTarget).hasClass('selected')) {
								$(oEvent.currentTarget).removeClass('selected');				
							} else {
								$('dt.selected', $(oEvent.currentTarget).parents('dl')).removeClass('selected'); // clear anything already selected...
								$(oEvent.currentTarget).addClass('selected');											
							}								
							break;
						}
					
					}
					
				} else {
					
					if ($(oEvent.currentTarget).hasClass('selected')) return; // dont do anything as its already selected									
					$('dt.selected', $(oEvent.currentTarget).parents('dl')).removeClass('selected'); // clear anything already selected...
					$(oEvent.currentTarget).addClass('selected');
					
				}
				
				var selection = this.getSelected(parent);				
				
				/* if there are no items selected, we still raise an event */
				var oData = {'object': parent, 'selected':selection};				
				$('*').triggerHandler('row-selected', oData);

				break;
				
			}
		
		}		
		
	},

	/* allow direct access just in case */
	getSelected : function(target) {

		var selection = new Array();
		if (target==null) return selection;

		var items = $('dl', target).find('dt.row.selected');
		
		if (items.length > 0) {
			selection = new Array();
			for (var counter=0; counter<items.length; counter++) {
				selection.push($(items[counter]).attr('data-id'));
			}
		}
		
		return selection;
		
	},

	reload : function(target) {
		
		this.__createList(target);
		
	},
	
	changePage : function(target, pageNo) {

		if (target==null) return;		
		pageNo = ((pageNo == 'undefined') || (pageNo == null)) ? 0 : parseInt(pageNo);
		
		var pageInfo = this.getPageInfo(target);
		if ((pageNo >= 0) && (pageInfo.pageno != pageNo) && (pageNo < pageInfo.pagemax)) {
			// change the page number...
			$(target).attr('data-page', pageNo);			
			//refresh the page
			this.__processJsonData(null, target, true);	
		}
		
	},
	
	__createList : function(target) {

		if (target==null) return;
		
		var datasource = $(target).attr('data-datasource');
		if ((datasource=='undefined') || (datasource==null)) datasource = null; 
		
		var isnew = $(target).attr('data-ready');
		if ((isnew=='undefined') || (isnew==null)) {
			isnew = true; 
		} else {
			isnew = isnew.toString().bool();
		}
		$(target).attr('data-ready', isnew);
		
		if (isnew) {
			$(target).parents('.i_panel.hidden').css({'display':'none'});
		}
		
		var callinpro = $(target).attr('data-callinpro');
		if ((callinpro=='undefined') || (callinpro==null)) { 
			callinpro = false;		
		} else {
			callinpro = callinpro.toString().bool();
		}
				
		if ($('dl.row_column', target).length>0) {
			// already has a ul specification
		} else {
			$(target).append('<dl class="row_column"></dl>');
		}
		
		if ((datasource != null) && (datasource != '')) {

			if (callinpro) return;
			$(target).attr('data-callinpro', true);
			
			if (datasource.startsWith('arr:')) {			
				var space = datasource.substring(4);
				var memData = App.UI.DataServices.getDataItem(space);
				this.__processJsonData(memData, target, false);
			} else {
				App.UI.DataServices.getData(datasource, target, App.UI.List.__processJsonData);				
			}
			
		}
				
	},
	
	getPageInfo : function(target) {
		
		var pageno = $(target).attr('data-page');
		pageno = ((pageno == 'undefined') || (pageno == null)) ? 0 : parseInt(pageno);

		var pagesize = $(target).attr('data-pagesize');
		pagesize = ((pagesize == 'undefined') || (pagesize == null)) ? 0 : parseInt(pagesize);

		var pagemax = $(target).attr('data-pagemax');
		pagemax = ((pagemax == 'undefined') || (pagemax == null)) ? 0 : parseInt(pagemax);
		
		var offset = pageno*pagesize; // calculate the offset of the data

		return {'pageno': pageno, 'pagesize': pagesize, 'pagemax': pagemax, 'offset': offset};
		
	},

	filter : function(target, filter) {
		if (target==null) return;
		if ((filter=='undefined') || (filter==null)) filter = '';
		$(target).attr('data-filter', filter);
		this.__processJsonData(null, target, true);
	},
	
	__processJsonData : function(datain, target, dataonly) {
		
		if (datain != null) {
			$(target).attr('data-callinpro', false);
		}

		var isnew = $(target).attr('data-ready');
		isnew = isnew.toString().bool();
		
		var callinpro = $(target).attr('data-callinpro');
		if ((callinpro=='undefined') || (callinpro==null)) { 
			callinpro = false;		
		} else {
			callinpro = callinpro.toString().bool();
		}
		
		// the data is being refreshed - avoid this process....
		if (callinpro && dataonly) return;
				
		if ((dataonly=='undefined') || (dataonly==null)) dataonly = false;
		if (target==null) return;

		var oHtml = '';								
		var datachanged = (datain!=null);
		var max = 0;
		var maxpages = 0;
		
		var storeId = $(target).attr('id');
		if ((storeId == 'undefined') || (storeId==null)) storeId = null;

		if (storeId != null) {
			if (datain==null) {
				datain = App.UI.DataServices.dataStore.get(storeId);
			} else { 
				App.UI.DataServices.dataStore.add(storeId, datain); // will overwrite if necessary !!				
			}
		}

		var data = null;
		if (typeof datain == 'string') {
			data = jQuery.parseJSON(datain);
		} else {
			data = datain;			
		}
		
		// set up the templates - all should be display:none to be sure no ui glitch...
		var template_header = App.UI.Core.get(storeId, '.row');
		var template_data = App.UI.Core.get(storeId, '.data'); 
		var template_title = App.UI.Core.get(storeId, '.title'); 
		var template_footer = App.UI.Core.get(storeId, '.footer'); 

		// reset the template if it doesnt exist...
		if ((template_header == 'undefined') || (template_header == null)) template_header = '';		
		if ((template_data == 'undefined') || (template_data == null)) template_data = '';

		if ((!dataonly) && (template_title != 'undefined') && (template_title != null)) {
			oHtml += '<dt class="titlebar">' + template_title + '</dt>';
		}
		
		var pageInfo = App.UI.List.getPageInfo(target);
		var _rowClass = '';
		var _rowdataClass = '';
		var eventClass = null;
		var id = null;
		var filter = null;
		
		if ((data != null) && (data.length>0)) {
		
			// do sorting !!
			var sorton = $(target).attr('data-sorton');
			sorton = ((sorton == 'undefined') || (sorton == null)) ? null : sorton.split(',');		
			
			if ((sorton != null) && (sorton != '')) data.sort(App.UI.Core.sortOn(sorton));

			var filteron = $(target).attr('data-filteron');
			filteron = ((filteron == 'undefined') || (filteron == '')) ? null : filteron;		
	
			filter = $(target).attr('data-filter');
			filter = ((filter == 'undefined') || (filter == '')) ? null : filter;		
					
			if ((filteron != null) && (filter != null)) {
				var filteredData = new Array();
				$.each(data, function(i, item) { 
					if ((item != null) && (item[filteron] != null)) {
						if (item[filteron].toLowerCase().indexOf(filter) != -1) filteredData.push(item);						
					}
				});
				data = filteredData;
			}

			eventClass = App.UI.Core.attr(storeId, '.row', 'data-event'); 
			if ((eventClass == 'undefined') || (eventClass == null)) eventClass = null;

			_rowClass = App.UI.Core.attr(storeId, '.row', 'data-rowclass'); 
			if ((_rowClass == 'undefined') || (_rowClass == null)) _rowClass = '';

			_rowdataClass = App.UI.Core.attr(storeId, '.data', 'data-rowclass'); 
			if ((_rowdataClass == 'undefined') || (_rowdataClass == null)) _rowdataClass = '';

			id = $(target).attr('data-id');
			if ((id == 'undefined') || (id == null)) id = '';
			
			// get paging information		
			
			if ((data != null) && (data.length > 0) && (pageInfo.pagesize > 0)) {
				max = ((pageInfo.offset+pageInfo.pagesize)>data.length) ? data.length : (pageInfo.offset+pageInfo.pagesize);
				maxpages = parseInt(data.length / pageInfo.pagesize) + (((data.length % pageInfo.pagesize) != 0) ? 1 : 0 ); 			
			} else {
				if ((data == null) || (data.length == 0)) {
					max = 0;
				} else {
					if (pageInfo.pagesize==0) {
						max = data.length;
					}
				}
			}		
			
			$(target).attr('data-pagemax', maxpages);
			if ((pageInfo.pageno< 0) || (pageInfo.pageno>maxpages)) pageInfo.pageno = 0; // move to the front again as the data isnt there...
			$(target).attr('data-page', pageInfo.pageno); // write the page number back to the service as required
			
		} else {
			
			$(target).attr('data-pagemax', 0);
			$(target).attr('data-page', 0);
		
		}
				
		// present data
		
		if ((data != null) && (data.length > 0)) {
			
			if ($('.noresults.static', target)) $('.noresults.static', target).hide();						
			if ($('.results.static', target)) $('.results.static', target).show();
						
			$('dl', target).show();
			
			var row_counter=0;
			
			oHtml += '<dt class="spacer"></dt>';
				
			for (var counter=pageInfo.offset; counter < max; counter++) {
								
				var rowClass = ((counter-pageInfo.offset) % 2)==0?'even':'odd';
				var rowdataClass = '';
				
				if (_rowClass != '') rowClass += (' ' + App.UI.Core.doVarSubstitution(data[counter], _rowClass));
				if (_rowdataClass != '') rowdataClass += (' ' + App.UI.Core.doVarSubstitution(data[counter], _rowdataClass));
				
				// make variable substitution here....
				var output_header = App.UI.Core.doVarSubstitution(data[counter], template_header);
				var output_data = App.UI.Core.doVarSubstitution(data[counter], template_data);
				
				oHtml += '<dt class="row '+rowClass+'" data-rowindex="'+ row_counter+'" data-id="';				
				oHtml += ((data[counter] != null) && (id != '') && (data[counter][id] != null)) ? data[counter][id] : counter;  
				oHtml += '"';
				
				if (eventClass !=null) {
					oHtml += ' data-event="'+ App.UI.Core.doVarSubstitution(data[counter], eventClass) + '"';
				}
				
				oHtml += '>'+ output_header + '</dt>';

				if (output_data != '') oHtml += '<dd class="data '+rowdataClass+'">'+ output_data +'</dd>';				
				
				row_counter++;
				
			}
			
			var currentdata = {'rows_total':data.length, 'rows_shown': row_counter};
			
			var output_footer = App.UI.Core.doVarSubstitution(currentdata, template_footer);			
			if ((template_footer != 'undefined') && (template_footer != null) && (template_footer != '')) oHtml += '<dt class="footer">'+ output_footer +'</dt>';
			
		} else {

			if ($('.noresults.static', target)) $('.noresults.static', target).show();			
			if ($('.results.static', target)) $('.results.static', target).hide();								
			
			$('dl', target).hide();
			
		}
		
		if (!dataonly) {
			$('dl.row_column', target).html(oHtml);
		} else {
			$('dl.row_column dt.row, dl.row_column dt.spacer, dl.row_column dd, dl.row_column dt.footer', target).remove();
			$('dl.row_column', target).append(oHtml);
		}
		
		if (isnew) {
			$(target).parents('.i_panel.hidden').fadeIn();
			$(target).attr('data-ready', 'false');
		}
		
		var oData = { 'object': target, 'pageno': pageInfo.pageno, 'datachanged': (datachanged || (filter != null)) }; 		
		$('*').triggerHandler('data-refresh', oData); // inform everyone that the grid dynamics just changed !!
		
	},
		
	__recoverFailed : function(datain, target) {
		/* data not received */
		$(target).attr('data-callinpro', false);
	}
		
};

App.UI.Filter = {
	
	hasInit : false,

	__preinit : function() {

		if (this.hasInit) return;
		this.hasInit = true;

		$('*').bind('page-refresh', function(object, data) { App.UI.Filter.refresh(); });
		$('[data-component="filter"] input[type=text]').live('keyup', function(oEvent){ App.UI.Filter.content_Changed(oEvent); });

	},

	content_Changed : function(oEvent) {

		var currentText = '';
		
		if (oEvent == null) return;

		switch (oEvent.type)
		{
			case 'keyup':{
				currentText = $(oEvent.currentTarget).attr('value');
				break;
			}
		}
		
		// get the parent and then the data source as we are completely async..
		
		var parent = $(oEvent.currentTarget).parents('[data-component="filter"]');
		var datasource = $(parent).attr('data-source');
		
		if ((datasource == 'undefined') || (datasource == null)) datasource = null;		
		if (datasource==null) return;

		var source = $('#'+datasource);
		if (source==null) return;
		
		var sourcetype = $(source).attr('data-component');

		switch (sourcetype) {
			case 'list': {
				App.UI.List.filter(source, currentText);
				break;
			}
			case 'repeater': {
				App.UI.Repeater.filter(source, currentText);
				break;
			}
			default: {
				break;
			}
		}
		
	},	
	
	refresh : function() {
		$('body').find('[data-component="filter"]').each(function() {
			App.UI.Filter.__setupFilter(this); 
		});		
	},
	
	__setupFilter : function(target) {
		
	}
			
};

App.UI.Repeater = {
		
	hasInit : false,
	dataStore : null,
	
	__preinit : function() {

		if (this.hasInit) return;
		this.hasInit = true;

		$('*').bind('page-refresh', function(object, data) {
			App.UI.Repeater.refresh(data); 
		});

		App.UI.Repeater.dataStore = new Hashtable();

	},

	refresh : function(target) {
				
		if ((target=='undefined') || (target==null)) target = null;		
				
		if ((target==null) || (typeof(target) == 'object')) {
			$('body').find('[data-component="repeater"]').each(function() { 				
				var listento = $(this).attr('data-listento');
				if ((listento == 'undefined')||(listento == null)) {
					App.UI.Repeater.__createList(this); 					
				} else {
					var listenarray = listento.split(',');
					if ((target != null) && (target.listen != null) && (listenarray.indexOf(target.listen)!=-1)) {
						App.UI.Repeater.__createList(this); 				
					}					
				}				
			});			
		} else {
			if ($(target).attr('data-component') != null) {
				App.UI.Repeater.__createList($(target));				
			} else {
				$(target).find('[data-component="repeater"]').each(function() { 
					App.UI.Repeater.__createList(this);
				});
			}
			
			//$(target).find('[data-component="repeater"]').each(function() { 
			//	App.UI.Repeater.__createList(this); 
			//});			
		}
				
	},	
	
	__createList : function(target) {
		
		if (target==null) return;
		
		var datasource = $(target).attr('data-datasource');
		if ((datasource=='undefined') || (datasource==null)) datasource = null; 
		
		var callinpro = $(target).attr('data-callinpro');
		if ((callinpro=='undefined') || (callinpro==null)) { 
			callinpro = false;		
		} else {
			callinpro = callinpro.toString().bool();
		}
				
		if ($('ul.list', target).length>0) {
			// already has a ul specification
		} else {
			$(target).append('<ul class="list clear"></ul>');
		}
		
		if ((datasource != null) && (datasource != '')) {

			if (callinpro) return;
			$(target).attr('data-callinpro', true);

			if (datasource.startsWith('arr:')) {			
				var space = datasource.substring(4);
				var memData = App.UI.DataServices.getDataItem(space);
				this.__processJsonData(memData, target, false);
			} else {
				App.UI.DataServices.getData(datasource, target, App.UI.Repeater.__processJsonData);
			}

//			App.UI.DataServices.getData(datasource, target, App.UI.Repeater.__processJsonData);
			
		}
		
	},

	getPageInfo : function(target) {
		
		var pageno = $(target).attr('data-page');
		pageno = ((pageno == 'undefined') || (pageno == null)) ? 0 : parseInt(pageno);

		var pagesize = $(target).attr('data-pagesize');
		pagesize = ((pagesize == 'undefined') || (pagesize == null)) ? 0 : parseInt(pagesize);

		var pagemax = $(target).attr('data-pagemax');
		pagemax = ((pagemax == 'undefined') || (pagemax == null)) ? 0 : parseInt(pagemax);
		
		var offset = pageno*pagesize; // calculate the offset of the data

		return {'pageno': pageno, 'pagesize': pagesize, 'pagemax': pagemax, 'offset': offset};
		
	},

	changePage : function(target, pageNo) {

		if (target==null) return;		
		pageNo = ((pageNo == 'undefined') || (pageNo == null)) ? 0 : parseInt(pageNo);
		
		var pageInfo = this.getPageInfo(target);
		if ((pageNo >= 0) && (pageInfo.pageno != pageNo) && (pageNo < pageInfo.pagemax)) {
			// change the page number...
			$(target).attr('data-page', pageNo);			
			//refresh the page
			this.__processJsonData(null, target, true);	
		}
		
	},
	
	filter : function(target, filter) {
		if (target==null) return;
		if ((filter=='undefined') || (filter==null)) filter = '';
		$(target).attr('data-filter', filter);
		this.__processJsonData(null, target, true);
	},
	
	__processJsonData : function(datain, target, dataonly) {

		if (datain != null) {
			$(target).attr('data-callinpro', false);
		}

		var callinpro = $(target).attr('data-callinpro');
		if ((callinpro=='undefined') || (callinpro==null)) { 
			callinpro = false;		
		} else {
			callinpro = callinpro.toString().bool();
		}
		
		// the data is being refreshed - avoid this process....
		if (callinpro && dataonly) return;
				
		if ((dataonly=='undefined') || (dataonly==null)) dataonly = false;
		if (target==null) return;

		var oHtml = '';								
		var datachanged = (datain!=null);
		
		var storeId = $(target).attr('id');
		if ((storeId == 'undefined') || (storeId==null)) storeId = null;

		if (storeId != null) {
			if (datain==null) {
				datain = App.UI.DataServices.dataStore.get(storeId);
			} else { 
				App.UI.DataServices.dataStore.add(storeId, datain); // will overwrite if necessary !!				
			}
		}
		
		var data = null;
		if (typeof datain == 'string') {
			data = jQuery.parseJSON(datain);
		} else {
			data = datain;			
		}
		
		// set up the templates - all should be display:none to be sure no ui glitch...
		
		var template_item = App.UI.Core.get(storeId, '.item'); 
		
		// do sorting !!
		var sorton = $(target).attr('data-sorton');
		sorton = ((sorton == 'undefined') || (sorton == null)) ? null : sorton.split(',');		
		
		if ((sorton != null) && (sorton != '') && (data!=null) && (data.length>0)) {
			data.sort(App.UI.Core.sortOn(sorton));
		}
		
		var filteron = $(target).attr('data-filteron');
		filteron = ((filteron == 'undefined') || (filteron == '')) ? null : filteron;		

		var filter = $(target).attr('data-filter');
		filter = ((filter == 'undefined') || (filter == '')) ? null : filter;		
				
		if ((filter != null) && (filteron != null) && (data!=null) && (data.length>0)) {
			var filteredData = new Array();
			$.each(data, function(i, item) { 
				if ((item != null) && (item[filteron] != null)) {
					if (item[filteron].toLowerCase().indexOf(filter) != -1) {
						filteredData.push(item);
					}
				}
			});
			data = filteredData;
		} else {
			
		}
		
		// reset the template if it doesnt exist...
		if ((template_item == 'undefined') || (template_item == null)) { 
			template_item = '';		
		}
		
		var _rowClass = App.UI.Core.attr(storeId, '.item', 'data-itemclass');
		if ((_rowClass == 'undefined') || (_rowClass == null)) _rowClass = '';
				
		var id = $(target).attr('data-id');
		if ((id == 'undefined') || (id == null)) id = '';
		
		// get paging information		
		var pageInfo = App.UI.Repeater.getPageInfo(target);
		var max = 0;
		var maxpages = 0;
		
		if ((data != null) && (data.length > 0) && (pageInfo.pagesize > 0)) {
			max = ((pageInfo.offset+pageInfo.pagesize)>data.length) ? data.length : (pageInfo.offset+pageInfo.pagesize);
			maxpages = parseInt(data.length / pageInfo.pagesize) + (((data.length % pageInfo.pagesize) != 0) ? 1 : 0 ); 			
		} else {
			if ((data == null) || (data.length == 0)) {
				max = 0;
			} else {
				if (pageInfo.pagesize==0) {
					max = data.length;
				}
			}
		}
					
		if ((pageInfo.pageno< 0) || (pageInfo.pageno>maxpages)) pageInfo.pageno = 0; // move to the front again as the data isnt there...
		$(target).attr({'data-pagemax':maxpages, 'data-page':pageInfo.pageno}); // write the page number back to the service as required		
		
		// present data
		
		if ((data != null) && (data.length > 0)) {

			if ($('.noresults.static', target)) $('.noresults.static', target).hide();
			if ($('.results.static', target)) $('.results.static', target).show();			
			
			for (var counter=pageInfo.offset; counter < max; counter++) {
								
				var rowClass = (_rowClass != '') ? ' ' + _rowClass : '';
				
				// make variable substitution here....
				var output_item = App.UI.Core.doVarSubstitution(data[counter], template_item);
				
				oHtml += '<li class="item'+rowClass+'" data-id="'; 				
				oHtml += ((data[counter] != null) && (id != '') && (data[counter][id] != null)) ? data[counter][id] : counter;				
				oHtml += '">'+ output_item + '</li>';
				
			}
		} else {
			
			if ($('.noresults.static', target)) $('.noresults.static', target).show();			
			if ($('.results.static', target)) $('.results.static', target).hide();			
			
		}
		
		if (!dataonly) {
			$('ul.list', target).html(oHtml);
		} else {
			$('ul.list li.item', target).remove();
			$('ul.list', target).append(oHtml);
		}
		
		var oData = { 'object': target, 'pageno': pageInfo.pageno, 'datachanged': (datachanged || (filter != null)) }; 		
		$('*').triggerHandler('data-refresh', oData); // inform everyone that the grid dynamics just changed !!
		
	},

	
	__recoverFailed : function(datain, target) {
		/* data not received */
		$(target).attr('data-callinpro', false);
	}	
				
};

App.UI.MiniView = {
		
		hasInit : false,
		count : 0,
		target : null,
		show : false,
		max : 1,		
		
		__preinit : function() {

			if (this.hasInit) return;
			this.hasInit = true;

			$('*').bind('page-refresh page-changed', function(object, data) { App.UI.MiniView.hideWindow(data); });	

			$('.miniview').live('mouseover mouseout', function(oEvent) { App.UI.MiniView.triggerCountdown(oEvent); });
			$('.miniview').live('click', function(oEvent) { App.UI.MiniView.triggerClear(oEvent); });
			
			var oHtml = '<section id="mytooltip" class="tooltipper"><div class="inner"><div class="content"></div></div></section>';						
			$('body').append(oHtml);

		},
				
		showWindow : function() {

			if ((App.UI.MiniView.show) || (App.UI.MiniView.target == null)) return;			
			
			var params = $(App.UI.MiniView.target).attr('data-miniview');
			if ((params=='undefined') || (params==null)) return;
			params = eval('('+ params +')');
			if (params == null) return;
			
			App.UI.MiniView.show = true;
			
			var xpos = $(App.UI.MiniView.target).offset().left;
			var ypos = $(App.UI.MiniView.target).offset().top;
			
			var wwidth = $(App.UI.MiniView.target).width();			
			var wheight = $(App.UI.MiniView.target).height();
			
			var width = (params.width != null) ? params.width : 300;
			var height = (params.height != null) ? params.height : 100;
			
			var offset = parseInt((height - wheight) / 2);
			
			$('#mytooltip .inner .content').html('').load(params.url);			
			$('#mytooltip').css({'left':(xpos+wwidth+10)+'px', 'top':(ypos-offset)+'px', 'display':'block', 'width':width});			
			
		},
		
		hideWindow : function() {			
			if (!App.UI.MiniView.show) return;			
			App.UI.MiniView.count = 0;
			App.UI.MiniView.target = null;
			App.UI.MiniView.show = false;
			$('#mytooltip').css({'display':'none'});			
		},
		
		triggerClear : function(oEvent) {
			if (oEvent==null) return;						
			App.UI.MiniView.target = null;
			App.UI.MiniView.hideWindow();
		},
		
		triggerCountdown : function(oEvent) {
			
			if (oEvent==null) return;						
			var target = $(oEvent.currentTarget);
			
			if (target==null) return;
			
			switch (oEvent.type) {
			
				case 'mouseover': {
					if (App.UI.MiniView.target == null) {
						App.UI.MiniView.target = target;
						$.doTimeout(500, function() {
							if (App.UI.MiniView.target==null) return false;
							if (App.UI.MiniView.count < App.UI.MiniView.max) {				
								App.UI.MiniView.count += 1;
								return true;
							} else {
								App.UI.MiniView.showWindow();
							}
							return false;																					
						});
					} else {
						
					}
					break;
				}

				case 'mouseout': {
					if (App.UI.MiniView.target != null) {
						if (App.UI.MiniView.show) {
							App.UI.MiniView.hideWindow();
						} else {
							App.UI.MiniView.count = 0;
							App.UI.MiniView.target = null;							
						}
					}
					break;
				}

			}
			
			
		}
				
};
		
App.UI.GMaps = {
	
	hasInit : false,
	dataStore : null,
	
	__preinit : function() {
		
		if (this.hasInit) return;
		this.hasInit = true;
				
		$('*').bind('page-refresh', function(object, data) {
					App.UI.GMaps.refresh(data); 
					});
		
		App.UI.GMaps.dataStore = new Hashtable();			
		
	},
	
	refresh : function(target) {
		
		if ((target=='undefined') || (target==null)) target = null;		
		
		App.UI.GMaps.dataStore.clear();
		
		if ((target==null) || (typeof(target) == 'object')) {
			$('body').find('[data-component="gmaps"]').each(function() { 
															   App.UI.GMaps.__createMap(this); 
															   });			
		} else {
			$(target).find('[data-component="gmaps"]').each(function() { 
															   App.UI.GMaps.__createMap(this); 
															   });			
		}
		
	},	
	
	__getData : function(target) {
	
		if (target==null) return;
		var targetid = $(target).attr('data-id');
		
		// push the object into the datastore if available..
		if ((targetid != null) && (targetid != 'undefined')) {	
			
			var map = App.UI.GMaps.datastore.get(targetid);			
			var bounds = map.gmap.getBounds();
			var sw = bounds.sw;
			var ne = bounds.ne;
			
			console.info(sw);
			console.info(ne);
						
		}
		
		
	},
	
	__createMap : function(target) {
		
		if (target==null) return;
				
		var doneinit = $(target).attr('data-initialized');
		
		if ((doneinit == null) || (doneinit=='undefined')) {	
			
			$(target).attr('data-initialized', true);
			
			var latlng = new google.maps.LatLng(-34.397, 150.644);
			
			var myOptions = {
				zoom: 8,
				center: latlng,
				mapTypeId: google.maps.MapTypeId.ROADMAP
			};

			var map = new google.maps.Map(target, myOptions);
			
			var targetid = $(target).attr('data-id');
			
			// push the object into the datastore if available..
			if ((targetid != null) && (targetid != 'undefined')) {				

				var container = new GoogleMapContainer(targetid, map, null);
				App.UI.GMaps.dataStore.add(targetid, container);		

				google.maps.event.addListener(map, 'bounds_changed', function() {
							console.info('bounds changed - '+targetid);			
						});				
				
			}
			
			console.info("target map initialized");

		}			
		
		this.__validateMaps(null);
		
	},
	
	__validateMaps : function(target) {
		
		if (App.UI.GMaps.dataStore.count() == 0) return;
		
		var map = App.UI.GMaps.dataStore.itemat(0);
		map.locate(4.9166665, 52.3499980);
		map.zoom(17);
		
		console.info("maps appears stored!!");
		
	}
	
};
		
App.UI.Slideshow = {

	hasInit : false,
	shows: new Hashtable(),
	
	__preinit : function() {

		if (this.hasInit) return;
		this.hasInit = true;
		
		$('ul.pips li.pip').live('click', function(oEvent) {
						App.UI.Slideshow.pipClicked(oEvent);	  
					});
		
		$('*').bind('page-refresh', function(object, data) {
						App.UI.Slideshow.refresh(data); 
					});
		
	},

	refresh : function(target) {
		
		if ((target=='undefined') || (target==null)) target = null;		
		
		if ((target==null) || (typeof(target) == 'object')) {
			$('body').find('[data-component="slideshow"]').each(function() { 
					   App.UI.Slideshow.setup(this); 
				   });			
		} else {
			$(target).find('[data-component="slideshow"]').each(function() { 
					   App.UI.Slideshow.setup(this); 
				   });			
		}
		
	},
	
	pipClicked : function(oEvent) {
		
		if (oEvent==null) return;		
		
		var target = $(oEvent.currentTarget);
		var parent = $(target).parents('[data-component="slideshow"]');
		
		if ((parent == null) || (parent == 'undefined')) return;
				
		var targetid = $(parent).attr('id');
				
		if ((targetid == null) || (targetid == 'undefined')) return;

		var slideindex = $(target).index();
		var container = App.UI.Slideshow.shows.get(targetid);

		container.gotoslide(slideindex);
		
	},
	
	setup : function(target) {
		
		if (target == null) return;
		var targetid = $(target).attr('id');
		if ((targetid == null) || (targetid == 'undefined')) return;
		
		var container = App.UI.Slideshow.shows.get(targetid);
		
		if (container == null) {
			// setup a new container ...
			container = new SlideshowContainer(targetid);
			App.UI.Slideshow.shows.add(targetid, container);
		} else {
			container.__setup();
		}
		
	}
	
};

App.UI.Stepshow = {
		
	hasInit : false,
	
	__preinit : function() {
		
		if (this.hasInit) return;
		this.hasInit = true;
		
		$('ul.pips li.pip').live('click', function(oEvent) {
								 App.UI.Stepshow.pipClicked(oEvent);	  
								 });
		
		$('*').bind('page-refresh', function(object, data) {
						App.UI.Stepshow.refresh(data); 
					});
		
	},
	
	refresh : function(target) {
		
		if ((target=='undefined') || (target==null)) target = null;		
		
		if ((target==null) || (typeof(target) == 'object')) {
			$('body').find('[data-component="stepshow"]').each(function() { 
																App.UI.Stepshow.setup(this); 
																});			
		} else {
			$(target).find('[data-component="stepshow"]').each(function() { 
																App.UI.Stepshow.setup(this); 
																});			
		}
		
	},
	
	pipClicked : function(oEvent) {
		
		if (oEvent==null) return;		
		
		var target = $(oEvent.currentTarget);
		var parent = $(target).parents('[data-component="stepshow"]');
		
		if ((parent == null) || (parent == 'undefined')) return;
				
		var slideindex = $(target).index();		
		var slides = $('.steps > li', parent);
		
		$('.steps > li', parent).removeClass('selected');
		$(slides[slideindex]).addClass('selected');

		$('.pips li.pip.selected', parent).removeClass('selected');
		
		var pips = $('.pips li.pip', parent);
		$(pips[slideindex]).addClass('selected');

	},
	
	setup : function(target) {
		
		if (target == null) return;
					
	}
	
};
		
		
		
App.UI.TreeView = {

	hasInit : false,
	dataStore : null,
	
	__preinit : function() {

		if (this.hasInit) return;
		this.hasInit = true;

		$('.treenav').live('click', function(oEvent) { App.UI.TreeView.nav(oEvent); });
		
		$('*').bind('page-refresh', function(object, data) {
			App.UI.TreeView.refresh(data); 
		});

		App.UI.TreeView.dataStore = new Hashtable();

	},

	nav : function(oEvent) {
		
		if (oEvent==null) return;
		var target = $(oEvent.currentTarget).parents('[data-component="treeview"]');
		if (target == null) return;

		var current = $(oEvent.currentTarget).parents('[data-component|=""]');
		if (current.length == 0) return;
		
		var args = $(oEvent.currentTarget).attr('data-treeargs');
		if ((args == 'undefined') || (args==null)) { 
			return;
		} else {
			args = eval('('+ args +')');
		}

		var ids = $(target).attr('data-ids');
		if ((ids==null) || (ids=='undefined')) ids=null;		
		if (ids != null) ids = ids.split(',');
						
		switch (args.action) {
		
			case 'select': {
				var startindex = args.pindex+1;
				while (ids.length > startindex) {
					ids.pop();
				}
				ids.push(args.id);
				var out = '';
				for (var counter=0; counter< ids.length; counter++) {
					out += (out != '' ? ',' : '') + ids[counter];
				}
				$(target).attr('data-ids', out);
				this.__createPanels(target);				
				break;
			}
		
			default: {
				// eh ?
				break;
			}
		}
				
	},
	
	refresh : function(target) {
				
		if ((target=='undefined') || (target==null)) target = null;		
				
		if ((target==null) || (typeof(target) == 'object')) {
			$('body').find('[data-component="treeview"]').each(function() { 
				App.UI.TreeView.__createPanels(this); 
			});			
		} else {
			$(target).find('[data-component="treeview"]').each(function() { 
				App.UI.TreeView.__createPanels(this); 
			});			
		}
				
	},	
	
	__createPanels : function(target) {
	
		
		var callinpro = $(target).attr('data-callinpro');
		if ((callinpro=='undefined') || (callinpro==null)) { 
			callinpro = false;		
		} else {
			callinpro = callinpro.toString().bool();
		}
		
		if (callinpro) return;
		if (target==null) return;

		this.__setup(target);

		var storeId = $(target).attr('id');
		if ((storeId == 'undefined') || (storeId==null)) return;
		
		$(target).attr('data-callinpro', true);
		
		var ids = $(target).attr('data-ids');
		if ((ids==null) || (ids=='undefined')) ids=null;
		
		if (ids != null) ids = ids.split(',');
		
		var holder = $('ul.panels', target);
		var panels = $('ul.panels li.panel', target);
		var required = (ids != null) ? ids.length : 0;
				
		var template = App.UI.Core.get(storeId, '.tempanel'); 
		var inccounter = panels.length;
				
		while (inccounter > required) {
			var panel = panels[inccounter-1];
			$(panel).remove();
			inccounter+=-1;
		}
				
		var baseurl = $(target).attr('data-baseurl');
		if ((baseurl=='null') || (baseurl=='undefined')) baseurl = null;

		var panelcounter = 0;
		
		while (panelcounter < required) {
							
			var data = new Array(
					{'key':'panel_id', 'value': storeId+'_p'+panelcounter }, 
					{'key':'panel_url', 'value': baseurl+ids[panelcounter] },
					{'key':'panel_index', 'value': panelcounter },
					{'key':'panel_dataid', 'value': ids[panelcounter] },
					{'key':'panel_nextid', 'value': (panelcounter< (ids.length-1)) ? ids[panelcounter+1] : 0 }						
				);
						
			var newtemplate = template;			
			
			for (var counter=0; counter< data.length; counter++) {
				var lookfor = '%'+data[counter].key+'%';
				while (newtemplate.search(lookfor) != -1) {
					newtemplate = newtemplate.replace(lookfor, data[counter].value);
				}
			}
			
			newtemplate = App.UI.Core.doReplaceDir(newtemplate, 'id=');
			var refresh = true;
			
			if (panelcounter >= inccounter) {
				var oHtml = '<li class="panel" data-panelid="'+ids[panelcounter]+'" id="panel_'+panelcounter+'">';			
				oHtml += newtemplate;
				oHtml += '</li>';
				$(holder).append(oHtml);							
			} else {
				if ($(panels[panelcounter]).attr('data-panelid') != ids[panelcounter]) {
					$(panels[panelcounter]).attr('data-panelid', ids[panelcounter]);
					$(panels[panelcounter]).html(newtemplate);							
				} else {
					refresh = false;
				}
			}

			if (refresh) {
				$('*').triggerHandler('page-refresh', '#panel_'+panelcounter);				
			}
			
			panelcounter++;
			
		}

		$(target).attr('data-callinpro', false);

	},
	
	__setup : function(target) {

		if ($('ul.panels', $(target)).length > 0) return;

		$(target).html('<ul id="trepeater" class="panels clear"></ul>');

	}
	
};

$(document).ready(function() {
	
	App.UI.DataServices.__preinit();
	App.UI.Core.__preinit();

	App.UI.TreeView.__preinit();
	App.UI.List.__preinit();
	App.UI.Repeater.__preinit();	
	App.UI.Worldview.__preinit();
	App.UI.Pager.__preinit();
	App.UI.Filter.__preinit();	
	App.UI.Select.__preinit();
	App.UI.HideAndSeek.__preinit();
	App.UI.SmartInput.__preinit();
	App.UI.PeopleGallery.__preinit();
	App.UI.MiniView.__preinit();
	App.UI.GMaps.__preinit();
	App.UI.Slideshow.__preinit();
	App.UI.Stepshow.__preinit();
				  
	/* Now check if i need to see something... */

	App.UI.Core.refresh();

	App.UI.TreeView.refresh();
	//App.UI.List.refresh();
	//App.UI.Repeater.refresh();
	App.UI.Worldview.refresh();
	App.UI.Filter.refresh();	
	App.UI.Select.refresh();	
	App.UI.HideAndSeek.refresh();
	App.UI.SmartInput.refresh();
	App.UI.PeopleGallery.refresh();
	//App.UI.GMaps.refresh();
	App.UI.Slideshow.refresh();
	App.UI.Stepshow.refresh();
				  
});

