if (!window.desma) { window.desma = {}; }

desma._globalId = 0;
desma.generateId = function() 
{
	desma._globalId++;
	return desma._globalId;
};

desma.site = {};
desma.site.quick_form = function(arg) 
{
	desma.ajax.get.xhtml(
		desma.request.createUrl('site','action-handler'),
		"function=login&"+params,
		function(res) {
			
		}
	);
};



desma.xml = {};

desma.xml.adapter = function()
{
	var adapter = '';
	if('undefined' != typeof ActiveXObject) {
		adapter = 'MS';
	} 
	else if('undefined' != typeof document 
		&& document.implementation
		&& document.implementation.createDocument
		&& 'undefined' != typeof DOMParser) {
		adapter = 'default';
	}
	switch (adapter) {
		case 'MS':
			return new (function () {
				this.createDocument = function () {
					var names = ["Msxml2.DOMDocument.6.0",
						"Msxml2.DOMDocument.3.0", "MSXML2.DOMDocument",
						"MSXML.DOMDocument", "Microsoft.XMLDOM"];
					for (var key in names) {
						if(true) {
							try {
								return new ActiveXObject(names[key]);
							} catch (e) {}
						}
					}
					throw new Error('Unable to create DOMDocument');
				};
				this.serialize = function (doc) {
					return doc.xml;
				};
				this.parseXml = function (xml) {
					var doc = this.createDocument();
					if (!doc.loadXML(xml)) {
						throw new Error('Parse error');
					}
					return doc;
				};
			})();
		case 'default':
			return new (function () {
				this.createDocument = function () {
					return document.implementation.createDocument("", "", null);
				};
				this.serialize = function (doc) {
					return new XMLSerializer().serializeToString(doc);
				};
				this.parseXml = function (xml) {
					var doc = new DOMParser().parseFromString(xml, "text/xml");
					if ("parsererror" == doc.documentElement.nodeName) {
						throw new Error('Parse error');
					}
					return doc;
				};
			})();
		default:
			throw new Error('Unable to select the DOM adapter');
	}
};

/** 
 * <p>Serialize any <strong>non</strong> DOM object to an XML string. All properties are serialized using the property name
 * as the XML element name. Array elements are rendered as <code>array-item</code> elements, 
 * using their index/key as the value of the <code>key</code> attribute.</p>
 * @memberOf desma.xml
 * @param {Object} anyObject the object to serialize
 * @param {String} objectName a name for that object, to be used as the root element name
 * @return {String} the XML serialization of the given object as a string
 */ 
desma.xml.xmlize = function(anyObject, objectName, indentSpace) 
{
    indentSpace = indentSpace?indentSpace:'';
    var s = indentSpace  + '<' + objectName + '>';
    var isLeaf = false;
    if(!(anyObject instanceof Object) 
       || anyObject instanceof Number 
       || anyObject instanceof String 
       || anyObject instanceof Boolean 
       || anyObject instanceof Date) {
        s += desma.xml.escape(""+anyObject);
        isLeaf = true;
    } 
    else {
			s += "\n";
			var isArrayItem = anyObject instanceof Array;
			for(var name in anyObject) {
				if(true) {
					s += desma.xml.xmlize(anyObject[name], (isArrayItem?"array-item key=\""+name+"\"":name), indentSpace + "   ");
				}
			}
			s += indentSpace;
    }
    return (s += (objectName.indexOf(' ')!=-1?"</array-item>\n":"</" + objectName + ">\n"));
};

/** 
 * Escape the given string chacters that correspond to the five predefined XML entities
 * @memberOf desma.xml
 * @param {String} sXml the string to escape
 */
desma.xml.escape = function(sXml)
{
	if(sXml && sXml.replace) {
		return sXml.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
	}
	return "";
};

/** 
 * Unescape the given string. This turns the occurences of the predefined XML 
 * entities to become the characters they represent correspond to the five predefined XML entities
 * @memberOf desma.xml
 * @param  {String}sXml the string to unescape
 */
desma.xml.unescape = function(sXml)
{
	if(sXml && sXml.replace) {
		return sXml.replace(/&apos;/g,"'").replace(/&quot;/g,"\"").replace(/&gt;/g,">").replace(/&lt;/g,"<").replace(/&amp;/g,"&");
	}
	return "";
};


desma.ajax = {};
desma.ajax.get = {};
desma.ajax.post = {};
desma.ajax.get.json = function(url, params, callback) 
{
	if(typeof params =='object') {
		params.format = 'json';
	}
	else if(typeof params =='string') {
		params += '&format=json';
	}
	return desma.dom.post(url, params, callback, 'json');
};
desma.ajax.get.xhtml = function(url, params, callback) 
{
	return desma.dom.get(url, params, callback, 'html');
};
desma.ajax.post.json = function(url, params, callback) 
{
	if(typeof params =='object') {
		params.format = 'json';
	}
	else if(typeof params =='string') {
		params += '&format=json';
	}
	return desma.dom.post(url, params, callback, 'json');
};
desma.ajax.post.xhtml = function(url, params, callback) 
{
	return desma.dom.post(url, params, callback, 'html');
};


desma.request = {};
desma.request.raw = {};
desma.request.get = function(name, type) 
{
	return desma.request.raw[name];
};
desma.request.set = function(name, value) 
{
	desma.request.raw[name] = value;
};


desma.request.setBaseUrl = function(base_url)
{
	desma.request.base_url = base_url;
};

desma.request.getBaseUrl = function()
{
	return desma.request.base_url;
};
desma.request.getSiteId = function()
{
	var site_id;
	site_id = desma.request.get('site_id','int');
	if(site_id) {
		return site_id;
	}
	return null;
};

desma.request.getSiteBaseUrl = function()
{
	var site_id;
	site_id = desma.request.get('site_id','int');
	if(site_id) {
		return desma.request.getBaseUrl()+site_id+'/';
	}
	return null;
};

desma.request.createUrl = function(type, link)
{
	var base_url = '';
	if(link.substring(0,1)!='/') {
		base_url = desma.request.getBaseUrl();
		base_site_url = desma.request.getSiteBaseUrl();
	}
	switch(type) {
		case 'base':
			return base_url+link;
		case 'site':
			return base_site_url+link;
		default:
			return base_url+link;
	}
};

desma.navigate = function(url)
{
	document.location.href = url;
};

// AUTH
desma.auth = {};
desma.auth.login = function(form_handler)
{
	var r = desma.qform.validate({
			handler: form_handler,
			rules: {
				account: {not_empty:'Account is required'},
				login: {not_empty:'Login is required'},
				password: {not_empty:'Password is required'}
			}
		}
	);
	if(r.valid){
		var params = desma.dom(r.frm).serialize();
		desma.ajax.post.json(
			desma.request.createUrl('base','auth/login'),
			params,
			function(res) {
				r = desma.dom.extend(r, res.data);
				if(r.valid) {
					desma.qform.errorCleanup(r.frm);
					desma.qform.reset(r.frm);
				}
				else {
					desma.qform.errors(r.frm, r);
				}
			}
		);
	}//if valid
	else {
		desma.qform.errors(r.frm, r);
	}
	return false;
};


if (!window.desma) { window.desma = {}; }
if (!window.desma.dom) {

desma.dom = jQuery;

desma.ready = function(f) 
{
	desma.dom(document).ready(f);
};

}if (!window.desma) { window.desma = {}; }
if (!window.desma.string) {

desma.string = {};
desma.string._underscoreCache = {};
desma.string._camelizeCache = {};

desma.string.underscore = function(v) {
	if(typeof desma.string._underscoreCache[v] != 'undefined') {
		return desma.string._underscoreCache[v];
	}
	var re = /(.)([A-Z])/g;
	var result;
	result = v.replace(re, "$1_$2");
	result = result.toLowerCase();
	desma.string._underscoreCache[v] = result;
	return result;
};

desma.string.camelize = function(v) {
	if(typeof desma.string._camelizeCache[v] != 'undefined') {
		return desma.string._camelizeCache[v];
	}
	var re = /[^A-Za-z]+/g;
	var parts = v.split(re), len = parts.length;
  if (len == 1) {
  	return parts[0];
  }

  var camelized = v.charAt(0).match(re)
		? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
		: parts[0];

	for (var i = 1; i < len; i++) {
		camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);
	}

	desma.string._camelizeCache[v] = camelized;
	return camelized;
};

desma.string.trim = function(str, chars)
{
	var re;
	if(!chars) {
		re = /^\s+|\s+$/g;
	}
	else if(chars.substring(0,1)=="~") {
		re = new RegExp("/^+"+chars.substring(0,1)+"|"+chars.substring(0,1)+"$/");
	}
	else {
		re = "";
		for(var i=0;i<chars.length;i++) {
			re += "\\\\"+chars[i];
		}
		re = new RegExp("^["+re+"]+|["+re+"]+$","g");
	}
	return str.replace(re,"");
};

}if (!window.desma) { window.desma = {}; }
if (!window.desma.util) {

desma.util = {};

desma.util.each = desma.dom.each;

desma.util.isEmpty = function(obj) {
	for(var i in obj){ if(obj.hasOwnProperty(i)){return false;}}
	return true;
};
desma.util.extend = function(destination, source) {
	for (var property in source) {
		if(property) {
			destination[property] = source[property];
		}
	}
  return destination;
};



desma.util.isCallable = function(str) {
	if(!str) {
		return false;
	}
	if(desma.type.isFunction(str)) {
		return true;
	}
	++window.test;
	if(desma.cache.has(str)) {
		return desma.cache.get(str);
	}
	var is_callable = true;
	var a = str.split('.');
	var obj=window;
	for(var i=0;i<a.length;i++) {
		if(!obj[a[i]]) {
			desma.cache.set(str, false);
			return false;
		}
		else {
			obj = obj[a[i]];
		}
		if(!obj) {
			desma.cache.set(str, false);
			return false;
		}
		if(i==(a.length-1) && typeof obj!='function') {
			desma.cache.set(str, false);
			return false;
		}
	}
	desma.cache.set(str, is_callable);
	return is_callable;
	
	/*if(typeof desma.object[node_item.ct_name] == 'object' && 
		 typeof desma.object[node_item.ct_name][ab_name_safe] == 'function') {
		handler_s = "desma.object.action['"+node_item.ct_name+"']['"+ab_name_safe+"']";
	}*/
};

desma.util.callable = function(constructor) 
{
	return function () {
		var callable_instance = function () {
			return callable_instance.callOverload.apply(callable_instance, arguments);
		};
		constructor.apply(callable_instance, arguments);
		return callable_instance;
	};
};

desma.util.unselect = function() 
{
	try {
		if(document.selection) {
			document.selection.empty();
		}
		else if (window.getSelection) {
			window.getSelection().removeAllRanges();
		}
	}
	catch(e) {
		alert('Document selection unselect error');
	}
};





desma.validator = {
	empty: function(v)
	{
		var regex = /^[\s\r\n\t]*$/g;
		return regex.test(v);
	},
	email: function(v)
	{
		var regex =  /^((\"[^\"\f\n\r\t\v\b]+\")|([\w\!\#$\%\&'\*\+\-\~\/\^\`\|\{\}]+(\.[\w\!\#$\%\&'\*\+\-\~\/\^\`\|\{\}]+)*))@((\[(((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9])))\])|(((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9])))|((([A-Za-z0-9\-])+\.)+[A-Za-z\-]+))$/;
		return regex.test(v);
	},
	phone: function(v)
	{
		var regex = /^\+{0,1}[0-9]{7,12}$/;
		return regex.test(v);
	}
};

desma.uiform = {};
desma.uiform.toggleCollapsibleBlock = function(elm) {
	var p = desma.dom(elm).parents('fieldset')[0];
	desma.dom(p).toggleClass('collapsed');
	return false;
};

desma.qform = {};
desma.qform.reset = function(frm)
{
	var form = null;
	if(desma.dom(frm).size() && desma.dom(frm)[0].tagName.toLowerCase() == 'form') {
		form = desma.dom(frm)[0];
	}
	else {
		if(desma.dom('form',frm).size()) {
			form = desma.dom('form',frm)[0];
		}
	}
	if(form) {
		form.reset();
	}
};

desma.qform.getForm = function(arg)
{
	return desma.dom(arg.handler).parents('form')[0];
};

desma.qform.validate = function(arg)
{
	arg = desma.dom.extend({
		rules: {}
	}, arg);
	arg.frm = desma.dom(arg.handler).parents('form')[0];
	
	var valid = true;
	var form_errors = [];
	var field_errors = {};
	
	desma.dom.each(arg.rules, function(element, element_validator_param) {
		var field;
		var element_params = {};
		var element_rules = {}; 
		if(typeof element_validator_param[0] == 'object' && typeof element_validator_param[1] == 'object') {
			element_params = element_validator_param[0];
			element_rules = element_validator_param[1];
		}
		else {
			element_rules = element_validator_param;
		}
		if(element_params.selector) {
			field = desma.dom(element_params.selector.replace('%name%', element), arg.frm);
		}
		else {
			field = desma.dom('[name='+element+']', arg.frm);
		}
		if(field.size()>=1) {
			// single input
			desma.dom.each(element_rules, function(rule, rule_prm) {
				var param = {msg:''};
				if(typeof rule_prm == 'string') {
					param.msg = rule_prm;
				}
				else {
					param = rule_prm;
				}
				if(rule.substr(0,4)=='not_') {
					param.negation = true;
					rule = rule.substr(4);
				}
				var rule_function;
				if(rule=='callback' && typeof param.callback=='function') {
					rule_function = param.callback;
				}
				else if(typeof desma.validator[rule] == 'function') {
					rule_function = desma.validator[rule];
				}
				if(typeof rule_function != 'function') {
					alert('Unknown rule: '+rule);
					return;
				}
				else {
					var rule_function_m;
					if(param.negation) {
						rule_function_m = function(_tv, _param) { return !rule_function(_tv, _param); };
					}
					else {
						rule_function_m = function(_tv, _param) { return rule_function(_tv, _param); };
					}
				}
				if(!field_errors[element] && !rule_function_m(field.val(), param)) {
					valid = false;
					field_errors[element] = {text:param.msg};
				}
			});
		}
	});
	return {
		
		frm: arg.frm,
		handler: arg.handler, 
		rules: arg.rules,
		valid:valid,
		form_errors:form_errors,
		field_errors:field_errors
	};
		
};


desma.qform.errorCleanup = function(container)
{
	if(typeof container == 'string') {
		if(container.substring(0,1)=='#') {
			desma.dom('.err-text', container).empty();
			desma.dom('.err-mark', container).removeClass('error');
		}
		else {
			desma.dom('.err-text', '#'+container).empty();
			desma.dom('.err-mark', '#'+container).removeClass('error');
		}
	}
	else if(typeof container == 'object') {
		desma.dom('.err-text', container).empty();
		desma.dom('.err-mark', container).removeClass('error');
	}

};

desma.qform.errors = function(container, arg)
{
	desma.qform.errorCleanup(container);
	if(arg.field_errors) {
		desma.dom.each( arg.field_errors, function(i,v) {
			desma.dom('.for-'+i, container).each(function(i,el){
				if(desma.dom(el).is('.err-text')) {
					desma.dom(el).show().html(v.text);
				}
				if(desma.dom(el).is('.err-mark')) {
					desma.dom(el).addClass('error');
				} 
			});
			//desma.dom('.for-'+i).html(v["text"]).show();
			//desma.dom('.for-'+i).addClass('error');
			//desma.dom('#err_text_'+i).html(v["text"]);
		});
	}
};


desma.page_configurator = {
	init_page: function() {
		desma.dom(document).ready(function() {
			desma.page_configurator.initForms();
		});
	},
	initForms: function (block) {
		block = block || document;
		var form_submit = function(e) {
			desma.dom(e.target).parents('form').bind('submit', function(event) {event.stopPropagation(); event.preventDefault();return false;});
			if (!e) {
				e = window.event;
			}
			if (!e.target) {
				e.target = e.srcElement; // ie
			}
			if (e.keyCode == 13 || e.type=='click') {
				desma.dom('.xbtn_submit', desma.dom(e.target).parents('form')).trigger('click');
				return true;
			}
		};
		// prevent double submission;
		desma.dom('input', desma.dom(block)).not('.prevent_submit').unbind('keydown');
		desma.dom('input', desma.dom(block)).not('.prevent_submit').keydown(form_submit);
		
		desma.dom('button[type=submit]', desma.dom(block)).not('.prevent_submit').unbind('click');
		desma.dom('button[type=submit]', desma.dom(block)).not('.prevent_submit').click(form_submit);
		desma.dom('input[type=submit]', desma.dom(block)).not('.prevent_submit').unbind('click');
		desma.dom('input[type=submit]', desma.dom(block)).not('.prevent_submit').click(form_submit);
	}
};







}if (!window.desma) window.desma = {};
if (!window.desma.log) {

desma.log = {
	log: function(v) {
		desma.log._log("log", v);
	},
	info: function(v) {
		desma.log._log("info", v);
	},
	debug: function(v) {
		desma.log._log("debug", v);
	},
	warn: function(v) {
		desma.log._log("warn", v);
	},
	error: function(v) {
		desma.log._log("error", v);
	},
	profile: function(v) {
		desma.log._log("profile", v);
	},
	_log: function(level, v) {
		if((typeof console !='undefined') && (typeof console[level] != 'undefined')) {
			console[level](v);
		}
		else {
			if(level=='log') {
				level = 'info';
			}
			if((typeof log !='undefined') && (typeof log[level] != 'undefined')) {
				//log[level](v);
			}
		}
	}
};

}if (!window.desma) { window.desma = {}; }
if (!window.desma.type) {

desma.type = {
	isObject: function(object) {
		return object != null && typeof object == "object";
  },
	isArray: function(object) {
		return object != null && typeof object == "object" &&
			'splice' in object && 'join' in object;
  },
	isFunction: function(object) {
		return typeof object == "function";
	},
	isUndefined: function(object) {
    return typeof object == "undefined";
  },
  isDefined: function(object) {
    return typeof object != "undefined";
  },
  isString: function(object) {
    return typeof object == "string";
  },
  isNumber: function(object) {
    return typeof object == "number";
  },
  isCallable: function(object) {
    return typeof object == "function";
  }
  
};

}if (!window.desma) { window.desma = {}; }
if (!window.desma.cmenu) {

desma.cmenu = {};
desma.cmenu.create = function(jm, arg) 
{
	arg = arg||{};
	if(!jm.type) {
		desma.util.each(jm, function(n, v) {
			desma.cmenu.create(v);
		});
		return;
	}
	
	if(!jm.dom) {
		// create jm.dom = ;
	}
	//jm.dom
	//desma.log.log(jm);
	var span = desma.dom('>a>span',jm.dom);
	var span_v = span.hasClass('qmbv');
	var span_h = span.hasClass('qmbh');
	if((span_h||span_v) && 
	   !desma.dom('>a .qm-ibcss-static',jm.dom).size()) {
		alert(1);
		// add bullet;
		var bcn = span_h?"xhbc":"xvbc";
		/*
		span.after(''
			+'<i class="qm-ibcss-static '+bcn+'">'
				+'<i class="'+bcn+'0"></i>'
				+'<i class="'+bcn+'1"></i>'
				+'<i class="'+bcn+'2"></i>'
				+'<i class="'+bcn+'3"></i>'
				+'<i class="'+bcn+'4"></i>'
				+'<i class="'+bcn+'5"></i>'
			+'</i>');
		*/
	}
	if(jm.opts.click) {
		desma.dom('>a',jm.dom).click(function(e) {
			var target = e.target || e.srcElement;
			var ul = desma.dom('>ul',jm.dom);
			
			if(target.tagName.toLowerCase()!='span') {
				if(ul.css('left')=='auto') {
					ul.css('left','-10000px');
					ul.hide();
				}
				else {
					ul.parent().css('z-index',9);
					ul.css('left','auto');
					ul.show();
					
					var t = true;
					var remove = function(e_1) {
						var e_t = e_1.target || e_1.srcElement;
						//desma.log.log( e_t );
						//desma.log.log( ul );
						if(t && ( desma.dom(e_t).parents().index(ul)<0 ) && ul.index(e_t)<0) {
							ul.css('left','-10000px');
							ul.hide();
							t = false;
							desma.dom(document).unbind('click',remove);
						}
						t = true;
					};
					desma.dom(document).click(remove);
				}
			}
			else {

			}
			return false;
		});
	}
	//desma.dom(jm.dom).bind('click', function() { alert(1); });
	if(jm.items) {
		desma.util.each(jm.items, function(n, v) {
		
			//desma.cmenu.create(v);
		});
	}
};

desma.cmenu._parseMenu = function(menu) 
{
	var menuItems = [];
	desma.dom('>li',menu).not('.qmclear').each(function(i, item) {
		var p_item = desma.cmenu._parseItem(item);
		menuItems.push(p_item);
	});
	return menuItems;
};

desma.cmenu._parseItem = function(item)
{
	var di = desma.dom(item);
	var item = {opts:{}};
	var t, t_html;
	t = desma.dom('>a',di);
	item.dom = di;
	if(di.hasClass('qclick')) {
		item.opts.click = true;
	}
	if(t.size()) {
		item.type = "item";
		if(t.hasClass('qmparent')) {
			item.parent = true;
		}
		if(t.hasClass('qmactive')) {
			item.active = true;
		}
		if(desma.dom('.qm-ibcss-static', t).size()) {
			item.bullet = true;
			item.bullet_direction = 'vertical';
			if(desma.dom('.xhbc', t).size()) {
				item.bullet_direction = 'horizontal';
			}
		}
		t_html = t.html();
		
		if(desma.dom(">span",t).size()) {
			item.label = desma.dom(">span",t).html();
		}
		else {
			item.label = desma.string.trim(t.html().replace(/<.*?>/g,""));
		}
		if(desma.dom(">ul",di).size()) {
			item.items = desma.cmenu._parseMenu(desma.dom(">ul",di));
		}
	}
	else {
		item.type = "header";
		t = desma.dom('>span',di);
		//desma.log.log(t);
		if(t.size()) {
			item.label = t.html();
		}
	}
	return item;
};

desma.cmenu.createFromMarkup = function(el) 
{
	var elm = desma.dom(el);
	var mjson = desma.cmenu._parseMenu(elm);
	desma.cmenu.create(mjson);
};
	
}if (!window.desma) { window.desma = {}; }
if (!window.desma.jmenu) {

desma.jmenu = function(data) {
	this._openMode = "click";
	this._class = 'ui.menu';
	this.handlers = {};
	this.data = data || {items:[]};
	this.data = desma.util.extend({id:desma.generateId(),parent:null,items:[]},this.data.items);
	this.panel = data.panel;
	this._activePanels = [];
	this._activeItem = null;
};

desma.jmenu.prototype.findItem = function(id, data)
{
	id = this._getItemId(id);
	data = data||this.data;
	if(data.id==id) {
		return data;
	}
	for(var i = 0;i<data.items.length;i++) {
		if(data.items[i].id==id) {
			return data.items[i];
		}
		else if(data.items[i].items) {
			var found_id = this.findItem(id, data.items[i]);
			if(found_id) {
				return found_id;
			}
		}
	}
	return null;
};

desma.jmenu.prototype.getItemPosition = function(parent, item)
{
	for(var i = 0;i<parent.items.length;i++) {
		if(parent.items[i]==item) {
			return i;
		}
	}
	return null;
};

desma.jmenu.prototype.isChildOf = function(item, parent)
{
	if(!item) return false;
	if(!parent) return false;
	var _parent = item;
	while(_parent = _parent.parent) {
		if(_parent==parent) {
			return true;
			break;
		}
	}
	return false;
};

desma.jmenu.prototype.addItem = function(item, to, mode) {
	mode = mode||'child';
	item = desma.util.extend({id:desma.generateId(),parent:null,items:[]},item);
	var to_id = null;
	if(to && desma.type.isObject(to) && desma.type.isDefined(to.id)) {
		to_id = to.id;
	}
	to_id = to_id?to_id:this.data.id;
	var to_item = this.findItem(to_id);
	if(!to_item) {
		desma.log.warn("Menu item with id \""+to_id+"\" not found");
		return;
	}
	switch(mode) {
		case 'sibling':
			var parent = to_item.parent?to_item.parent:this.data;
			var pos = this.getItemPosition(parent, to_item);
			if(pos===null) {
				pos = -1;
			}
			var items = [];
			parent.items = items.concat(parent.items.slice(0,pos+1), item, parent.items.slice(pos+1));
			item.parent = parent;
		break;
		default:
		case 'child':
			item.parent = to_item;
			to_item.items.push(item);
		break;
	}
//	if(item.handler) {
//		this.handlers[item.id] = item.handler;
//	}
	return item;
};

desma.jmenu.prototype.getIcon = function(item)
{
	if(item.icon) return "<img class='menuItemIcon' src='/img/print.gif'/>";
	return "";
};

desma.jmenu.prototype.getBullet = function(item)
{
	if(item.bullet) return "<div class=\"menuItemBullet\"></div>";
	return "";
};

desma.jmenu.prototype.getSpace = function(item)
{
	if(item.space) {
		return "<span class='menuSpaceArea'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>";
	}
	return "";
};


desma.jmenu.prototype.getPanel = function(scope, item, level) {
	level = level||0;
	var panel = desma.dom("#dmpanel"+item.id);
	if(!panel.length) {
		var s = "";
		for(var i=0;i<item.items.length;i++) {
			s += "<div id='dm"+item.items[i].id+"' class='menuItem"+
				(item.items[i].icon?' menuItemWithIcon':'')+
				(item.items[i].bullet?' menuItemWithBullet':'')+
				(item.items[i].shortcut?' menuItemWithShortcut':'')+
				(item.items[i].items.length>0?' menuItemWithChilds':'')+
				(item.items[i].disabled?' menuItemDisabled':'')+
				"'>"+
					this.getIcon(item.items[i])+
					item.items[i].label+
					this.getBullet(item.items[i])+
					(item.items[i].shortcut?' <div class="menuItemShortcut">Ctrl+X</div>':'')+
					this.getSpace(item.items[i]) + 
			"</div>";
		}
		desma.dom(document.body).append('' +
			'<div id="dmpanel'+item.id+'" class="menuPanel menuId'+scope.data.id+' menuLevel'+level+'" style="z-index:1000;position:absolute;background-color:#FA5;">' +
			s +
			'</div>'
		);
//		for(var i=0;i<item.items.length;i++) {
//			var item = item.items[i];
//			if(scope.handlers[item.id]) {
//				//desma.dom('#dm'+item.id).bind('click', scope.handlers[item.id]);
//			}
//		}
		
		panel = desma.dom("#dmpanel"+item.id);
		for(var i=0;i<item.items.length;i++) {
			var subitem_dom = desma.dom("#dm"+item.items[i].id, panel);
			subitem_dom
				.bind('click', function(scope, subitem) { 
					return function(ex) {
						if(subitem.handler) {
							desma.log.log(subitem.handler);
							subitem.handler();
							scope._activeItem = null;
							scope.updatePanels();
						}
					};
				}(scope, item.items[i]));
			subitem_dom
				.bind('mouseover', function(scope, subitem) { 
					return function(ex) {
						scope._activeItem = subitem;
						scope.updatePanels();
					};
				}(scope, item.items[i]));
			if(scope._openMode=="web") {
				subitem_dom
					.bind('mouseout', function(scope, subitem) {
						return function(ex) {
							if(scope.isMouseOut2(scope, ex)) {
								scope._activeItem = null;
								scope.updatePanels();
							}
							/*
							var out = false;
							var r_target = desma.dom(ex.relatedTarget);
							if(!r_target.parents(".menuId"+scope.data.id).length && 
							   !r_target.hasClass("menuId"+scope.data.id)) {
								out = true;
							}
							if(out) {
								scope._activeItem = null;
								scope.updatePanels();
							}
							*/
						};
					}(scope, item.items[i]))
				;
			}//
		}//for
		panel.hide();
	}
	this._activePanels.push(panel);
	var ofs = desma.dom('#dm'+item.id).offset();
	var coords = {top:parseInt(ofs.top)+25,left:parseInt(ofs.left)};
	if(item.parent && item.parent.parent) {
		coords = {top:parseInt(ofs.top),left:parseInt(ofs.left)+parseInt(desma.dom('#dmpanel'+item.parent.id).width())-5};
	}
	panel.css({"top":coords.top, "left":coords.left});
	return panel;
};

desma.jmenu.prototype.updatePanels = function() {
	// hide all panels
	// show panels for activeItem
	
	var cur_item = this._activeItem;
	var panels = [];
	var _panels = [];
	
	if(!cur_item) {
		this.hideAllPanels();
		desma.dom(".menuItemTopLevel","#dm"+this.data.id).removeClass("menuItemOver");
		return;
	}
	else {
		//this.hideAllPanels();
		// show panel for cur_item;
		panels.push(cur_item);
		_panels.push(cur_item.label);
		while(cur_item = cur_item.parent) {
			// show panel for cur_item;
			panels.push(cur_item);
			_panels.push(cur_item.label + " " + cur_item.id);
		}
	}
	panels.pop();
	_panels.pop();
	panels.reverse();
	_panels.reverse();
	//desma.log.log(_panels.join(" :: "));
	for(var i=0;i<panels.length;i++) {
		if(!desma.dom("#dm"+panels[i].id).hasClass('menuItemDisabled')) {
			desma.dom("#dm"+panels[i].id).addClass("menuItemOver")
		}
		if(panels[i].items.length) {
			var p = this.getPanel(this, panels[i]);
			desma.dom(".menuItem",p).removeClass("menuItemOver");
			if(!p.is(":visible")) {
				//desma.log.log(p.attr("id"));
				p.show();
			}
		}
		//desma.dom("#dmpanel"+panels[i].id).show();
		//this.getPanel(this, panels[i]).show();
	}
	
	var new_panels = [];
	for(var i=0;i<this._activePanels.length;i++) {
		var found = false;
		for(var j=0;j<panels.length;j++) {
			//desma.log.log("dmpanel"+panels[j].id+" == "+this._activePanels[i].attr("id"));
			if("dmpanel"+panels[j].id==this._activePanels[i].attr("id")) {
				found = true;
			}
		}
		if(!found) {
			desma.dom(".menuItem",this._activePanels[i]).removeClass("menuItemOver");
			this._activePanels[i].hide();
		}
		else {
			new_panels.push(this._activePanels[i]); 
		}
	}
	this._activePanels = new_panels;
	
};

desma.jmenu.prototype.isMouseOut2 = function(scope, e)
{
	var out = false;
	var r_target = desma.dom(e.relatedTarget);
	if(!r_target.parents(".menuId"+scope.data.id).length && 
	   !r_target.hasClass("menuId"+scope.data.id)) {
		out = true;
	}
	return out;
};

desma.jmenu.prototype._getItemId = function(item)
{
	var id = item;
	if(desma.type.isObject(item)) {
		id = item.id;
	}
	return id;
};

desma.jmenu.prototype._getItemDom = function(item)
{
	return desma.dom("#dm"+this._getItemId(item));
};

desma.jmenu.prototype.enableItem = function(item)
{
	var dom = this._getItemDom(item);
	dom.removeClass("menuItemDisabled");
	var _item = this.findItem(item);
	if(_item) {
		_item.disabled = false;
	}
	
};

desma.jmenu.prototype.disableItem = function(item)
{
	var dom = this._getItemDom(item);
	dom.addClass("menuItemDisabled");
	var _item = this.findItem(item);
	if(_item) {
		_item.disabled = true;
	}
};

desma.jmenu.prototype.hideAllPanels = function() 
{
	var _p;
	while(_p = this._activePanels.pop()) {
		desma.dom(".menuItem",_p).removeClass("menuItemOver");
		_p.hide();
	}
};

desma.jmenu.prototype.show = function() 
{
	this._getItemDom(this.data.id).remove();
	var s = "";
	for(var i=0;i<this.data.items.length;i++) {
		var item = this.data.items[i]; 
		s += "" +
			"<div id='dm"+item.id+"' class='menuItemTopLevel " +
			(item.icon?' menuItemWithIcon':'')+
			(item.bullet?' menuItemWithBullet':'')+
			(item.items.length>0?' menuItemWithChilds':'')+
			(item.disabled?' menuItemDisabled':'')+
			"'>" +
				this.getIcon(item)+
				"<span class='menuLabel'>"+item.label+"</span>"+
				this.getBullet(item)+
				(item.shortcut?"<div class='menuItemShortcut'></div>":"")+
				""
			;
			if(item.items.length && item.handler) {
				s += "<a class='menuItemSwitch' href='#'></a>";
			}
			s += this.getSpace(item);
			s += "</div>";
	}
	this.panel.append("<div id='dm"+this.data.id+"' class='desmaMenu menuPanel menuId"+this.data.id+"'>"+s+"</div>");
	
//	for(var i=0;i<this.data.items.length;i++) {
//		var item = this.data.items[i];
//		if(this.handlers[item.id]) {
//			//desma.dom('#dm'+item.id).bind('click', this.handlers[item.id]);
//		}
//	}
	
	
	if(this._openMode=="click") {
		var scope = this;
		for(var i=0;i<this.data.items.length;i++) {
			scope._getItemDom(scope.data.items[i])
				.bind("mouseover", function(scope, item) {
					return function(e) {
						if(scope._activeItem && item!=scope._activeItem) {
							desma.dom(".menuItemTopLevel","#dm"+scope.data.id).removeClass("menuItemOver")
							scope._activeItem = item;
							scope.updatePanels();
						}
					};
				}(scope, scope.data.items[i]))
				.bind("click", function(scope, item) {
					return function(e) {
						desma.dom(".menuItemTopLevel","#dm"+scope.data.id).removeClass("menuItemOver")
						//e.stopPropagation();
						desma.log.log(desma.dom(e.target));
						if(item.handler && !desma.dom(e.target).hasClass("menuItemSwitch")) {
							desma.log.log(item.handler);
							item.handler();
							scope._activeItem = null;
							scope.updatePanels();
						}
						else {
							if(scope._activeItem==item || scope.isChildOf(scope._activeItem, item)) {
								scope._activeItem = null;
							}
							else {
								scope._activeItem = item;
							}
							scope.updatePanels();
							if(scope._activeItem) {
								desma.dom(document)
									.bind("click.dmenu"+scope.data.id, function(ex) {
										//e.stopPropagation();
										var r_target = desma.dom(ex.target);
										//desma.log.log(r_target.parents(".menuId"+scope.data.id).length);
										
										if(!r_target.parents(".menuId"+scope.data.id).length) {
											scope._activeItem = null;
											scope.updatePanels();
											desma.dom(document).unbind("click.dmenu"+scope.data.id);
										}
									});
								//scope.updatePanels();
							}
							else {
								desma.dom(document).unbind("click.dmenu"+scope.data.id);
							}
						}
						return false;
						
					};
				}(scope, scope.data.items[i])
			);
		}
		
	}
	else if(this._openMode=="rclick") {
		var scope = this;
		for(var i=0;i<this.data.items.length;i++) {
			scope._getItemDom(scope.data.items[i])
				.bind("mouseover", function(scope, item) {
					return function(e) {
						if(scope._activeItem && item!=scope._activeItem) {
							desma.dom(".menuItemTopLevel","#dm"+scope.data.id).removeClass("menuItemOver")
							scope._activeItem = item;
							scope.updatePanels();
						}
					};
				}(scope, scope.data.items[i]))
				.bind("click", function(scope, item) {
					return function(e) {
						desma.dom(".menuItemTopLevel","#dm"+scope.data.id).removeClass("menuItemOver")
						//e.stopPropagation();
						desma.log.log(desma.dom(e.target));
						if(0 && item.handler && !desma.dom(e.target).hasClass("menuItemSwitch")) {
							desma.log.log(item.handler);
							item.handler();
							scope._activeItem = null;
							scope.updatePanels();
						}
						else if(1){
							if(scope._activeItem==item || scope.isChildOf(scope._activeItem, item)) {
								scope._activeItem = null;
							}
							else {
								scope._activeItem = item;
							}
							scope.updatePanels();
							if(scope._activeItem) {
								desma.dom(document)
									.bind("click.dmenu"+scope.data.id, function(ex) {
										//e.stopPropagation();
										var r_target = desma.dom(ex.target);
										//desma.log.log(r_target.parents(".menuId"+scope.data.id).length);
										
										if(!r_target.parents(".menuId"+scope.data.id).length) {
											scope._activeItem = null;
											scope.updatePanels();
											desma.dom(document).unbind("click.dmenu"+scope.data.id);
										}
									});
								//scope.updatePanels();
							}
							else {
								desma.dom(document).unbind("click.dmenu"+scope.data.id);
							}
						}
						return false;
						
					};
				}(scope, scope.data.items[i])
			);
		}
		
	}
	else {		
		// event mouseover mouseout
		for(var i=0;i<this.data.items.length;i++) {
			var scope = this; 
			scope._getItemDom(scope.data.items[i])
				.bind("mouseover", function(scope, item) {
					return function(e) {
						//e.stopPropagation();
						desma.dom(".menuItemTopLevel","#dm"+scope.data.id).removeClass("menuItemOver")
						scope._activeItem = item;
						scope.updatePanels();
					};
				}(scope, scope.data.items[i]))
				.bind("mouseout", function(scope, item) {
					return function(e) {
						if(scope.isMouseOut2(scope, e)) {
//							if(scope.isMouseOut(e, item)) {
							scope._activeItem = null;
							scope.updatePanels();
						}
					};
				}(scope, scope.data.items[i]))
			;
		}
	}// else if openMode == over
};
	

}if (!window.desma) { window.desma = {}; }
if (!window.desma.json) {


/*
    http://www.JSON.org/json2.js
    2009-09-29

    Public Domain.

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

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

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

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

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

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

            This method produces a JSON text from a JavaScript value.

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

            For example, this would serialize Dates as ISO strings.

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

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

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

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

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

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

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

            Example:

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


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

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


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

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

            Example:

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

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

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


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

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

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

/*jslint evil: true, strict: false */

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


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

if (!this.JSON) {
    this.JSON = {};
}

(function () {

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

    if (typeof Date.prototype.toJSON !== 'function') {

        Date.prototype.toJSON = function (key) {

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

        String.prototype.toJSON =
        Number.prototype.toJSON =
        Boolean.prototype.toJSON = function (key) {
            return this.valueOf();
        };
    }

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


    function quote(string) {

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

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


    function str(key, holder) {

// Produce a string from holder[key].

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

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

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

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

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

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

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

        case 'number':

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

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

        case 'boolean':
        case 'null':

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

            return String(value);

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

        case 'object':

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

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

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

            gap += indent;
            partial = [];

// Is the value an array?

            if (Object.prototype.toString.apply(value) === '[object Array]') {

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

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

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

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

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

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

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

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

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

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

// If the JSON object does not yet have a stringify method, give it one.
    if (typeof JSON.stringify !== 'function') {
        JSON.stringify = function (value, replacer, space) {

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

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

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

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

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

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

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

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

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

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


// If the JSON object does not yet have a parse method, give it one.

    if (typeof JSON.parse !== 'function') {
        JSON.parse = function (text, reviver) {

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

            var j;

            function walk(holder, key) {

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

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


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

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

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

// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

            if (/^[\],:{}\s]*$/.
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

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

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

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

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

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

            throw new SyntaxError('JSON.parse');
        };
    }
}());

//window.desma.json = this.JSON;
// Prototype temp replacement. Prototype break native json support because Array and String extending
window.desma.json = {};
window.desma.json.stringify = function(obj) { return Object.toJSON(obj); };
window.desma.json.parse = function(str) { return str.evalJSON(); };

}if (!window.desma) { window.desma = {}; }
if (!window.desma.browser) {

desma.browser = jQuery;

desma.browser.enableSelection = function() 
{
	document.onselectstart = null; // ie
	document.onmousedown = null; // mozilla
};

desma.browser.disableSelection = function() 
{
	document.onselectstart = function() {return false;}; // ie
	document.onmousedown = function() {return false;}; // mozilla
};

}
				if (!window.desma) window.desma = {};
if (!window.desma.registry) {

desma.registry = function() { this._data = {}; };
desma.registry.prototype.setValue = function(k, v) { this._data[k] = v; };
desma.registry.prototype.getValue = function(k) { if(typeof this._data[k] != 'undefined') return this._data[k]; };
desma.registry.prototype.hasValue = function(k) { if(typeof this._data[k] == 'undefined') {return false;} return true; };
desma.registry.prototype.toString = function() {
	var s = [];
	var l = this._data.length;
	var i=0;
	for(k in this._data) {
		s.push(k+": "+this._data[k]);
	}
	return s.join(", ");
};
desma.registry.set = function(k, v) { desma.registry.instance().setValue(k, v); };
desma.registry.get = function(k) { return desma.registry.instance().getValue(k); };


desma.registry._instances = {};
desma.registry.defaultName = "_global_";
desma.registry.getName = function(registry_name) {
	return registry_name||desma.registry.defaultName;
};
desma.registry.instance = function(name) { 
	if(!name) {
		name = desma.registry.defaultName;
	}
	if(typeof desma.registry._instances[name] != 'object') {
		desma.registry._instances[name] = new desma.registry();
	}
	return desma.registry._instances[name];
};

}

if (!window.desma) { window.desma = {}; }
if (!window.desma.object) {

desma.object = {};


desma.object.object = function(data) {
	data = data||{};
	this._data = data;
	this._origData = {};
	this._idField = null;
	this._isDeleted = null;
	this._init(data);
};
desma.object.object.prototype._init = function() {
	
};
desma.object.object.prototype.isDeleted = function() {
	return this._isDeleted;
};
desma.object.object.prototype.setIdField = function(v) {
	this._idField = v;
	return this;
};
desma.object.object.prototype.getId = function() {
	if (this._idField) {
		return this.getData(this._idField);
	}
	return this.getData('id');
};
desma.object.object.prototype.setId = function(v) {
	if (this._idField) {
		this.setData(this._idField, v);
	}
	else {
		this.setData('id', v);
	}
	return this;
};
desma.object.object.prototype.addData = function(data) {
	var scope = this;
//	desma.util.each(data, function(k, v) {
//		scope._data[k] = v;
//	});
	//scope._data = desma.util.extend(scope._data, data);
	scope._data["test"] = data; 
	return this;
};
desma.object.object.prototype.setData = function(key, value) {
	if(typeof key=='object') {
		this._data = key;
	} else {
		this._data[key] = value;
	}
	return this;
};
desma.object.object.prototype.unsetData = function(key) {
	if(!key) {
		this._data = {};
	} else {
		delete this._data[key];
	}
	return this;
};

desma.object.object.prototype.getData = function(key, index) {
	index = index||null;
	if(!key) {
		return this._data;
	}
	var _default = null;
	/*
	// accept a/b/c as ['a']['b']['c']
	if (strpos($key,'/')) {
		$keyArr = explode('/', $key);
		$data = $this->_data;
		foreach ($keyArr as $i=>$k) {
			if ($k==='') {
				return $default;
			}
			if (is_array($data)) {
				if (!isset($data[$k])) {
					return $default;
				}
				$data = $data[$k];
			} elseif ($data instanceof Desma_Object) {
				$data = $data->getData($k);
			} else {
				return $default;
			}
		}
		return $data;
	}
	*/
	if(typeof this._data[key] != 'undefined') {
		if(index===null) {
			return this._data[key];
		}
		var value = this._data[key];
		if(typeof value == 'object') {
			if(typeof value.getData == 'function') {
				return value.getData(index);
			}
			if(typeof value[index] != 'undefined') {
				return value[index];
			}
			return null;
		}
		else if(typeof value == 'string') {
			var arr = value.split("\n");
			if(arr.length>index && arr[index] && arr[index].length>0) {
				return arr[index];
			} 
			return null;
		}
		return _default;
	}
	return _default;
};
desma.object.object.prototype._get = function(key) {
	if(typeof this._data[key] !='undefined') {
		return this._data[key];
	}
	return null;
};

desma.object.object.prototype.getUsingMethod = function(key, args) {
	args = args||null;
	var method = "get"+desma.string.camelize(key);
	if(typeof this[key] == "function") {
		return this[key](args);
	}
	return null;
};

desma.object.object.prototype.setUsingMethod = function(key, args) {
	args = args||[];
	var method = "get"+desma.string.camelize(key);
	if(typeof this[key] == "function") {
		this[key](args);
	}
	return this;
};

desma.object.object.prototype.getSetDefault = function(key, _default) {
	if (typeof this._data[key] == "undefined") {
		this._data[key] = _default;
	}
	return this._data[key];
};
desma.object.object.prototype.has = function(key) {
	key = key||"";
	if(key==="" || (typeof key != "string")) {
		return this.isEmpty();
	}
	if (typeof this._data[key] != "undefined") {
		return this._data[key];
	}
	return false;
};

desma.object.object.prototype.isEmpty = function() {
	return desma.util.isEmpty(this._data);
};

desma.object.object.prototype.getOrigData = function(key) {
	key = key||null;
	if(!key) {
		return this._origData;
	}
	if(typeof this._origData[key] != 'undefined') {
		return this._origData[key];
	}
	return null;
};

desma.object.object.prototype.setOrigData = function(key, data) {
	key = key||null;
	data = data||null;
	if(key===null) {
		this._origData = this._data;
	}
	else {
		this._origData[key] = this._data[key];
	}
	return this;
};

desma.object.object.prototype.dataHasChangedFor = function(field) {
	var newData = this.getData(field);
	var origData = this.getOrigData(field);
	return newData!=origData;
};

desma.object.object.prototype.isDirty = function(field) {
	field = field||null;
	if(desma.util.isEmpty(this._dirty)) {
		return false;
	}
	if(field===null) {
		return true;
	}
	if(typeof this._dirty[field] != 'undefined') {
		return true;
	}
	return false;
};

desma.object.object.prototype.flagDirty = function(field, flag) {
	field = field||null;
	flag = flag||true;
	if(field===null) {
		var scope = this;
		desma.util.each(this.getData(), function(field, value) {
			scope.flagDirty(field, flag);
		});
		
	}
	else {
		if (flag) {
			this._dirty[field] = true;
		} 
		else {
			if(typeof this._dirty[field] != 'undefined') {
				delete this._dirty[field];
			}
		}
	}
	return this;
};


}



/*
desma.oop = {};
desma.oop.create = function() {
	var parent = null, properties = arguments;
	if (desma.type.isFunction(properties[0]))
	  parent = properties.shift();
	
	function klass() {
	  this.initialize.apply(this, arguments);
	}
	
	desma.util.extend(klass, desma.oop.methods);
	klass.superclass = parent;
	klass.subclasses = [];
	
	if (parent) {
	  var subclass = function() { };
	  subclass.prototype = parent.prototype;
	  klass.prototype = new subclass;
	  parent.subclasses.push(klass);
	}
	
	for (var i = 0; i < properties.length; i++)
	  klass.addMethods(properties[i]);
	
	if (!klass.prototype.initialize)
	  klass.prototype.initialize = desma.type.emptyFunction;
	
	klass.prototype.constructor = klass;
	
	return klass;
};

desma.util.extend(Function.prototype, {
  argumentNames: function() {
    var names = this.toString().match(/^[\s\(]*function[^(]*\(([^\)]*)\)/)[1]
      .replace(/\s+/g, '').split(',');
    return names.length == 1 && !names[0] ? [] : names;
  },

  bind: function() {
    if (arguments.length < 2 && desma.type.isUndefined(arguments[0])) return this;
    var __method = this, args = arguments, object = args.shift();
    return function() {
      return __method.apply(object, args.concat(arguments));
    }
  },

  bindAsEventListener: function() {
    var __method = this, args = arguments, object = args.shift();
    return function(event) {
      return __method.apply(object, [event || window.event].concat(args));
    }
  },

  curry: function() {
    if (!arguments.length) return this;
    var __method = this, args = arguments;
    return function() {
      return __method.apply(this, args.concat(arguments));
    }
  },

  delay: function() {
    var __method = this, args = arguments, timeout = args.shift() * 1000;
    return window.setTimeout(function() {
      return __method.apply(__method, args);
    }, timeout);
  },

  defer: function() {
    var args = [0.01].concat(arguments);
    return this.delay.apply(this, args);
  },

  wrap: function(wrapper) {
    var __method = this;
    return function() {
      return wrapper.apply(this, [__method.bind(this)].concat(arguments));
    }
  },

  methodize: function() {
    if (this._methodized) return this._methodized;
    var __method = this;
    return this._methodized = function() {
      return __method.apply(null, [this].concat(arguments));
    };
  }
});

desma.oop.keys = function(object) {
	var keys = [];
	for (var property in object)
		keys.push(property);
	return keys;
};
desma.oop.methods = {
  addMethods: function(source) {
    var ancestor   = this.superclass && this.superclass.prototype;
    var properties = desma.oop.keys(source);

    if (!desma.oop.keys({ toString: true }).length)
      properties.push("toString", "valueOf");

    for (var i = 0, length = properties.length; i < length; i++) {
      var property = properties[i], value = source[property];
      if (ancestor && desma.type.isFunction(value) &&
          value.argumentNames()[0] == "$super") {
        var method = value;
        value = (function(m) {
          return function() { return ancestor[m].apply(this, arguments) };
        })(property).wrap(method);

        value.valueOf = method.valueOf.bind(method);
        value.toString = method.toString.bind(method);
      }
      this.prototype[property] = value;
    }

    return this;
  }
};

*/// @TODO desma.util.each
if (!window.desma) { window.desma = {}; }
if (!window.desma.event) {
	
desma.event = {};



desma.event.manager = {
	_status: {},
	init: function(registry_name) {
		registry_name = desma.registry.getName(registry_name);
		desma.registry.instance(registry_name).setValue('desma.events', new desma.event.eventCollection());
		desma.event.manager._status[registry_name] = 'initialized';
		return desma.registry.instance(registry_name).getValue('desma.events'); 
	},
	addObserver: function(eventName, callback, data, observerName, observerClass) {
		var registry_name = desma.registry.getName(registry_name);
		if(!desma.event.manager._status[registry_name] || desma.event.manager._status[registry_name]!='initialized') {
			desma.event.manager.init();
		}
		data = data||{};
		observerName = observerName||"";
		var observer = new desma.event.observer();
		
		observer
			.setName(observerName)
			//.addData(data)
			.setData(data)
			.setEventName(eventName)
			.setCallback(callback);
		return desma.registry.instance().getValue('desma.events').addObserver(observer);
	},
	dispatchEvent: function(name, data) {
		var registry_name = desma.registry.getName(registry_name);
		if(!desma.event.manager._status[registry_name] || desma.event.manager._status[registry_name]!='initialized') {
			desma.event.manager.init();
		}
		data = data||[];
		return desma.registry.instance().getValue('desma.events').dispatch(name, data);
	}
	
};

//desma.event.observe = desma.event.manager.addObserver;
//desma.event.dispatch = desma.event.manager.dispatchEvent;
desma.event.observe = function(eventName, elements, callback)
{
	if(elements && callback) {
		desma.dom(elements).bind(eventName, callback);
	}
	if(elements && !callback) {
		desma.dom(document).bind(eventName, elements);
	}
};
desma.event.trigger = function(eventName, elements, data)
{
	
	var event = {type:eventName};
	if(elements && data) {
		event.edata = data;
		desma.dom(elements).trigger(event);
	}
	else if(elements && !data) {
		event.edata = elements;
		desma.dom(document).trigger(event);
	}
	else if(!elements && !data) {
		desma.dom(document).trigger(eventName);
	}
};





desma.event.event = function(eventName, data) {
	// @TODO subclassing of desma.oop.object
	this._class = 'event';
	this._observers = {};
	data = data||{};
	this.setName(eventName);
	desma.object.object.call(this, data);
};

desma.event.event.prototype = new desma.object.object();

/*
desma.event.event.prototype.addData = function(data) {
	var scope = this;
	desma.util.each(data, function(k, v) {
		scope._data[k] = v;
	});
	return this;
};
desma.event.event.prototype.get = function(k)
{
	return this._data[k];
};
desma.event.event.prototype.set = function(k, v)
{
	this._data[k] = v;
	return this;
};
*/

desma.event.event.prototype.getObservers = function() {
	return this._observers;
};
desma.event.event.prototype.getObserverByName = function(name) {
	return this._observers[name];
};
desma.event.event.prototype.addObserver = function(observer) {
	this._observers[observer.getName()] = observer;
	return this;
};
desma.event.event.prototype.removeObserverByName = function(name) {
	delete this._observers[name];
	return this;
};
desma.event.event.prototype.dispatch = function() {
	var event = this;
	desma.util.each(this._observers, function(i, observer){
		observer.dispatch(event);
	});
};
desma.event.event.prototype.getName = function() {
	return this._eventName;
//	if(typeof this._data['name']!='undefined') {
//		return this._data['name'];
//	}
//	return null;
};
desma.event.event.prototype.setName = function(name) {
	this._eventName = name;
	return this;
	//this._data['name'] = name;
	//return this;
};

desma.event.eventCollection = function() {
	this._class = 'eventCollection';
	this._events = {};
	this._globalObservers = new desma.event.observerCollection();
};
desma.event.eventCollection.prototype.getAllEvents = function() {
	return this._events;
};
desma.event.eventCollection.prototype.getGlobalObservers = function() {
	return this._globalObservers;
};
desma.event.eventCollection.prototype.getEventByName = function(eventName) {
	if(typeof this._events[eventName]=='undefined') {
		//this.addEvent(new desma.event.event({name:eventName}));
		this.addEvent(new desma.event.event(eventName));
	}
	return this._events[eventName];
};
desma.event.eventCollection.prototype.addEvent = function(event) {
	this._events[event.getName()] = event;
	return this;
};
desma.event.eventCollection.prototype.addObserver = function(observer) {
	var eventName = observer.getEventName();
	if(eventName) {
		this.getEventByName(eventName).addObserver(observer);
	} 
	else {
		this.getGlobalObservers().addObserver(observer);
	}
	return this;
};
desma.event.eventCollection.prototype.dispatch = function(eventName, data) {
	data = data||[];
	var event = this.getEventByName(eventName);
	event
		//.addData(data)
		.setData(data)
		.dispatch();
	this.getGlobalObservers().dispatch(event);
	return this;
};


desma.event.observer = function(data) {
	// @TODO subclassing from desma.oop.object
	this._class = 'observer';
	data = data||{};
	desma.object.object.call(this, data);
};

desma.event.observer.prototype = new desma.object.object();
/*
desma.event.observer.prototype.addData = function(data) {
	var scope = this;
	desma.util.each(data, function(k, v) {
		scope._data[k] = v;
	});
	return this;
};
desma.event.observer.prototype.get = function(k) {
	return this._data[k];
};
desma.event.observer.prototype.set = function(k, v) {
	this._data[k] = v;
	return this;
};
*/
desma.event.observer.prototype.isValidFor = function(event) {
	
	return ((this.getEventName()==event.getName()) || (this.getEventName()==null));
};
desma.event.observer.prototype.dispatch = function(event) {
	if(!this.isValidFor(event)) {
		return this;
	}
	var callback = this.getCallback();
	this.setEvent(event);
	callback(this);
	return this;
};
desma.event.observer.prototype.getName = function() {
	//return this.getData('name');
	return this.observerName;
};
desma.event.observer.prototype.setName = function(v) {
	//return this.setData('name', v);
	this.observerName = v;
	return this;
};
desma.event.observer.prototype.getEventName = function() {
	//return this.getData('event_name');
	return this.eventName;
};
desma.event.observer.prototype.setEventName = function(v) {
	//return this.setData('event_name', v);
	this.eventName = v;
	return this;
};
desma.event.observer.prototype.getCallback = function() {
	//return this.getData('callback');
	return this.callback;
};
desma.event.observer.prototype.setCallback = function(v) {
	//this.setData('callback', v);
	this.callback = v;
	return this;
};
desma.event.observer.prototype.getEvent = function() {
	//return this.getData('event');
	return this.event;
};
desma.event.observer.prototype.setEvent = function(v) {
	//this.setData('event', v);
	this.event = v;
	return this;
};



desma.event.observerCollection = function() {
	this._class = 'observerCollection';
	this._observers = {};
};

desma.event.observerCollection.prototype.getAllObservers = function() {
	return this._observers;
};
desma.event.observerCollection.prototype.getObserverByName = function(name) {
	return this._observers[name];
};
desma.event.observerCollection.prototype.addObserver = function(observer) {
	this._observers[observer.getName()] = observer;
	return this;
};
desma.event.observerCollection.prototype.removeObserverByName = function(name) {
	delete this._observers[name];
	return this;
};
desma.event.observerCollection.prototype.dispatch = function(event) {
	desma.util.each(this._observers, function(i, observer){
		observer.dispatch(event);
	});
	return this;
};


}


if (!window.desma) { window.desma = {}; }
if (!window.desma.cookie) {


jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

}

