$(document).ready(function() {
	$.webix.application.root = $('meta[name=application-root]').attr('content'); 
	$.webix.application.link = $('meta[name=application-link]').attr('content'); 
	$.webix.profiles.load(userArray);
});

(function($) {
	
	$.webix = {
			application: {},
			abstrct: {},
			cache: {}
	};
	
	$.webix.profiles = {
		load: function(profiles) {
			$(profiles).each(function(index,data){
				var profile = jQuery.extend({}, new $.webix.profile(data), $.webix.abstrct.profile);
				$(profile.toHTML()).insertAfter('#profile-template');
			});
			$('#profile-template').remove();
		}
	}
	
	$.webix.profile = function(data){
		this.data = data;
	}
	
	$.webix.abstrct.profile = {
		
		_mapper: {
			nickname: /{user\.nickname}/g,
			city: /{visitor\.city}/g,
			link: /{application\.link}/g,
			thumb: /{user\.thumb}/g,
			description: /{user\.description}/g,
			root: /{application\.root}/g,
			id: /{user\.id}/g
		},
		
		toHTML: function() {
			if(typeof this.data != "object"){
				throw "Invalid user profile data!";
				return false;
			}
			var tpl = this._getTemplate();
			tpl = tpl.replace(this._mapper.id, this.data.id);
			tpl = tpl.replace(this._mapper.nickname, this.data.nickname);
			tpl = tpl.replace(this._mapper.description, this.data.description);
			tpl = tpl.replace(this._mapper.thumb, this.data.thumb);
			tpl = tpl.replace(this._mapper.root, $.webix.application.root);
			tpl = tpl.replace(this._mapper.link, $.webix.application.link);
			tpl = tpl.replace(this._mapper.city, visitorCity);
			return $(tpl);
		},
		
		_getTemplate: function() {
			if(typeof $.webix.cache.template == 'undefined') {
				var tpl = $('#profile-template').html();
				$.webix.cache.template = tpl.replace(/(:?\<\!\[CDATA\[|\]\]>)/g, '');
			}
			return $.webix.cache.template;
		}
	}
})(jQuery);
