API Docs for:
Show:

File: generic-dialog.js

/*******************************************************************************
 * Copyright (c) 2017 Genialist Software Ltd.
 * All rights reserved.
 ******************************************************************************/

const pPictures = new (function() {
	var that = this, canvas = pElement.create('canvas');
	
	this.ATTR_URL = 'attr-url';
	this.ATTR_THUMB = 'attr-thumb';

	this.dragStart = function(e, a) {
		pDrag.setURL(e, pURL.addQueryParameter(e.currentTarget.getAttribute(a || pPictures.ATTR_URL), 'ref', window.location.pathname));
	};
	
	this.supports = function(m) {
		//console.log('mime ' + m + ' ' + canvas.toDataURL(m));
		if (pString.v(m)) {
			var u = canvas.toDataURL(m);
			return u.substring(5, 5+m.length) == m || ((m=='image/bmp' || m=='image/gif') && u.substring(5, 5+'image/png'.length) == 'image/png');
		}
	};
	
	this.turnToRight = function(p_img) {
		var c = pElement.create("canvas");
        c.width = p_img.height;
        c.height = p_img.width;

        var context = c.getContext("2d");
        context.save();
        context.translate(p_img.height / 2, p_img.width / 2);
        context.rotate(Math.PI / 2);//3 * Math.PI / 2);
        context.drawImage(p_img, -p_img.width / 2, -0.5 * p_img.height);
        context.restore();
        
        return c.toDataURL("image/jpeg");
	};
	
	this.flipHorizontally = function(p_img) {
		var c = pElement.create("canvas");
        c.width = p_img.width;
        c.height = p_img.height;

        var context = c.getContext("2d");
        context.save();
        context.translate(c.width / 2, c.height / 2);
        context.rotate(Math.PI);
        context.translate(-c.width / 2, -c.height / 2);
        context.drawImage(p_img, 0, 0);
        context.restore();
        
        return c.toDataURL("image/jpeg");
	};
	
	this.turnToLeft = function(p_img) {
		var c = pElement.create("canvas");
        c.width = p_img.height;
        c.height = p_img.width;

        var context = c.getContext("2d");
        context.save();
        context.translate(p_img.height / 2, p_img.width / 2);
        context.rotate(3 * Math.PI / 2);
        context.drawImage(p_img, - p_img.width / 2 , -0.5 * p_img.height);
        context.restore();
        
        return c.toDataURL("image/jpeg");
	};
	
	this.width = function(x) {
		if (x = pElement.x(x))
			return (pElement.hasClassName(x, 'rotate-left') || pElement.hasClassName(x, 'rotate-right'))? x.height : x.width;
	};

	this.height = function(x) {
		if (x = pElement.x(x))
			return (pElement.hasClassName(x, 'rotate-left') || pElement.hasClassName(x, 'rotate-right'))? x.width : x.height;
	};
	
	this.rsort = function(a,b) {
		if (a.ww > b.ww)
			return -1;
		if (a.ww < b.ww)
			return 1;
		return 0;
	};
	
	this.resizeLine = function(ds, aw) {
		if (aw>0) {
			ds = ds.sort(pPictures.rsort);
			var wt = 0;
			ds.forEach(function(d) { wt += d.ww; });
			ds.forEach(function(d) { d.p = Math.floor(d.ww * aw / wt) });
			
			ds.forEach(function(d) { if (aw>0) { /*console.log('d.w: ' + d.w + ' d.p: ' + d.p + ' aw: ' + aw);*/ d.w -= d.p; aw -= d.p; } });
			if (aw>0)
				ds.forEach(function(d) { if (aw>0) { d.w--; aw--; } });
			if (aw>0)
				ds.forEach(function(d) { if (aw>0) { d.w--; aw--; } });
		}
	};
	
	this.thumbWidth = function(nw, nh, h) {
		if (nh<=0 || nw<=0)
			return h;
		else if (nh == nw)
			return h;
		//else if (nh > nw)
		//	return Math.trunc(h * nh / nw);
		else
			return Math.trunc(h * nw / nh); 
	};
	
	this.thumbHeight = function(nw, nh, h) {
		if (nh<=0 || nw<=0)
			return h;
		else if (nh == nw)
			return h;
		//else if (nh > nw)
		//	return Math.trunc(h * nh / nw);
		else
			return Math.trunc(h * nh / nw); 
	};
	
	this.resizeImages = function(i_x, divs, h, r) {
		
		var i_prect_right = r || pDocument.innerWidth(i_x);
		if (pApplicationUI.OPTION_PICTURES_RESIZE_GALLERY && i_prect_right>0) {
			var i_line_first = 0, i_first_of_line = true, i_right = 0, i_divs = [];
			
			[].forEach.call(divs, function(d, i) {
	
				var x = d.getElementsByTagName('img')[0], nw = x.getAttribute('org-width'), nh = x.getAttribute('org-height'), 
					ww = pPictures.thumbWidth(parseInt(pString.v(nw)? nw : x.naturalWidth), parseInt(pString.v(nh)? nh : x.naturalHeight), h), 
					ps = new pStyle(d), w = ww + ps.surroundWidth(); 
				
				i_divs.push({ x: d, img: x, ww: ww, pstyle: ps, w: w });
				
				if (i_first_of_line) {
					i_first_of_line = false;
					i_line_first = i;
					i_right = w;
				}
				else if (i_right + w == i_prect_right) { // line break
					i_first_of_line = true;
				}
				else if (i_right + w > i_prect_right) { // line break;
					i_first_of_line = true;
	
					var aw = w - (i_prect_right - i_right) + 1;
					//console.log(i+' aw: ' + aw + ' w: ' + w + ' rect: ' + i_prect_right + ' r: ' + i_right);
					
					if (aw > 0) {
						var s = i_divs.slice(i_line_first)
						pPictures.resizeLine(s, aw);
						
						s.forEach(function(d) {
							var w = d.w - d.pstyle.surroundWidth();
							
							d.x.style.width = w + 'px';
							if (w < d.ww) {
								//console.log(i_i.id + ' marginLeft: ' + i_i.img_w + ' - ' + w + ' ' + (i_i.img_w - w)/2 + ' ' + Math.trunc((i_i.img_w - w)/2));
								d.img.style.marginLeft = '-'+Math.trunc((d.ww - w)/2) + 'px';
							}
							else
								d.img.style.marginLeft = '0px';
						});
					}
				}
				else
					i_right += w;
			});
		}
		return i_prect_right;
	};
	
	this.title = function(i) {
		var t = i.name;
		if (t)
			return pString.basename(t);
		return pURL.fixedDecodeURIComponent(pString.basename(i.uri));
	};
	
	this.tooltip = function(op, sep) {
		var t = [ pPictures.title(op) ];
		if (!pString.v(t[0])) t = [];
		
		if (op.owidth && op.owidth>0 && op.oheight && op.oheight>0)
			t[t.length] = parseInt(op.owidth) + ' x ' + parseInt(op.oheight);
		else if (op.width && op.width>0)
			t[t.length] = parseInt(op.width) + ' x ' + parseInt(op.height);

		if (op.domain) t[t.length] = op.domain;
		
		if (op.date!=null && op.date!='' && op.date!='-1') 
			t[t.length] = 'Date Taken: ' + pDate.toLocaleDateString(pDate.create(op.date)) + ' ' + pDate.toLocaleTimeString(pDate.create(op.date));
		
		return t.join(sep || '\n');
	};
	
	this.hasdim = function(op) {
		if (op.owidth && op.owidth>0 && op.oheight && op.oheight>0)
			return true;
		else if (op.width && op.width>0)
			return true;
	};
});

/*[ 'image/jpeg', 'image/png', 'image/webp', 'image/bmp', 'image/tiff' ].forEach(function(f) {
	try {
		console.log(pElement.create('canvas').toDataURL(f).substring(0, 20) + ' ' + pPictures.supports(f));
	}
	catch (ex) {
		console.log(f + ' exception...');
	}
});*/

/******************************************************************************/
/******************************************************************************/
/******************************************************************************/

window.pDialog = new (function() {
	var that = this, m_dialogs = new pMap();
	
	function f_getDialog(did) {
		return m_dialogs.getValue((typeof did=="string")? did : did.id, null);
	};
	
	function f_removeDialog(did) {
		m_dialogs.remove((typeof p_id=="string")? did : did.id);
	}
	
	function f_putDialog(d) {
		m_dialogs.put(''+d.id, d);
	}
	
	function f_ui_getDialogElement(p_dialog) {
		return pElement.x('dialog-question'+p_dialog.m_id_suffix);
	}
	
	function f_ui_getDialogInputElement(op) {
		return op.input? pElement.x('dialog-input-'+op.id) : null;
	}
	
	function f_ui_getDialogFromInputElement(i_input) {
		return pDialog.getValue(i_input.getAttribute('attr_dialog_id'));
	}
	
	function f_getInputValue(op) {
		if (op.input)
			return pObject.trim(pElement.getValue(f_ui_getDialogInputElement(op)));
	}
	
	function f_setInputValue(op, v) {
		if (op.input)
			pElement.setValue(f_ui_getDialogInputElement(op), v);
	}
	
	//*** INIT OPTIONS
	pROSE.initOptions(this);
	
	this.resources = {
		icon_copy: { className: 'dq-bt-copy', title: 'Copy', onclick: function(op_id){ pElement.copy('dialog-input-'+op_id); }, ondisable: true },
		icon_delete: { className: 'dq-bt-delete', title: 'Delete', onclick: function(op_id){
			var x = pElement.x('dialog-input-'+op_id);
			if (!x || x.readOnly)
				return;
			pElement.updateValue(x, ''); pElement.focus(x);
		}, ondisable: true },
		icon_paste: { className: 'dialog-question-button-paste', title: 'Paste', onclick: function(op_id){ pElement.paste('dialog-input-'+op_id); } },
		
		ae_f: [ 
			{ id: 'trim', f: function(v) { return v.trim() }, text: 'Trim: ', after: '<hr>'},
			{ id:' lowercase', f: function(v) { return v.toLowerCase() }, text: 'Lowercase: ' },
			{ id: 'uppercase', f: function(v) { return v.toUpperCase() }, text: 'Uppercase: ' },
			{ id: 'capitalize', f: function(v) { return pTag.format(v) }, text: 'Capitalize: ' },
		],
		
		icon_advanced_editting: {
			className: 'dq-bt-advanced-edit',
			title: 'Click here to change the text with advanced formatting...',
			onclick: function(op_id){
				var v = pElement.x('dialog-input-' + op_id).value, l = [];
				if (pString.v(v)) {
					pDialog.resources.ae_f.forEach(function(f) {
						var nv = f.f(v);
						if (v != nv) {
							l.push({ id: f.id, text: f.text + nv.replace(/ /g, '&nbsp;'), fcall: function() { 
								pElement.updateValue('dialog-input-' + op_id, nv);
								//pElement.focus('dialog-input-' + op_id);
								
							}});
							if (f.after)
								l.push(f.after);
						}
					});
					
					pApplicationMenu.menu('advanced-edit', l);
				}
			},
			ondisable: true
		},
		
		validators_foldername: /^[^/\\<>:\"|?*]{1,100}$/,
		pattern_foldername: '[^/\\\\<>:"\|\?\*]{1,100}',
		input_foldername: function() {
			return { validators: pDialog.resources.validators_foldername, pattern: pDialog.resources.pattern_foldername,
				required: true, spellcheck: false, autocomplete: false, autocorrect: false, autocapitalize: false, placeholder: 'Folder name...' };
		},
		f_enableIfEnabled: function(did, id, ids) {
			var b = pDialog.getInputValue(did, id);
			ids.forEach(function(i) { 
				var x = f_ui_getDialogInputElement({ id: i, input: {}})
				if (x)
					x.disabled = b==false;
			});			
		},
		f_disableIfEnabled: function(did, id, ids) {
			var b = pDialog.getInputValue(did, id);
			ids.forEach(function(i) { 
				var x = f_ui_getDialogInputElement({ id: i, input: {}});
				if (x)
					x.disabled = b;
			});			
		}
	};
	
	var eh = new pEventHandler();
	this.addEventListener = function(eid, f) {
		return eh.addEventListener(eid, f);
	};
	this.removeEventListener = function(eid, f) {
		return eh.removeEventListener(eid, f);
	};

	this.isDialogOn = function() {
		return m_dialogs.length>0;
	};

	this.getValue = function(did) {
		return f_getDialog(did);
	};

	this.addDialogOption = function(did, p_part, op) {
		if (did = pDialog.getValue(did)) {
			var i_x_id = 'dialog-question-'+p_part+did.m_id_suffix, tabid = null;
			if (p_part!='header' && p_part!='content' && p_part!='footer') {
				i_x_id = p_part;
				tabid = p_part;
			}
	
			var x = pElement.x(i_x_id);
			if (x) {
				var i_child = pDialog.genDialogOption(did, op, true, tabid);
				if (i_child) {
					var xc = pElement.x(x.id + '-clear');
					if (xc)
						x.insertBefore(i_child, xc);
					else
						x.appendChild(i_child);
					
					if (window.pPictures)
						pPictures.resizeImages(x, x.getElementsByClassName('dialog-question-option-image'), 120);
				}
				//TODO: select...
			}
		}
	};
	this.insertDialogOption = function(did, p_part, op, before_op_id) {
		if (did = pDialog.getValue(did)) {
			var i_x_id = 'dialog-question-'+p_part+did.m_id_suffix;
			if (p_part!='header' && p_part!='content' && p_part!='footer')
				i_x_id = p_part;
	
			var x = pElement.x(i_x_id);
			if (x) {
				var ch = pDialog.genDialogOption(did, op, true);
				if (ch) {
					var xb = pElement.x(before_op_id);
					if (xb)
						x.insertBefore(ch, xb);
					else
						x.appendChild(ch);
					
					if (window.pPictures)
						pPictures.resizeImages(x, x.getElementsByClassName('dialog-question-option-image'), 120);
				}
				//TODO: select...
			}
		}
	};
	this.clearDialogOptions = function(did, pt) {
		if (did = pDialog.getValue(did))
			pElement.setInnerHTML('dialog-question-'+pt+did.m_id_suffix, '');
		/*
		if (did = pDialog.getValue(did)) {
			var x = pElement.x('dialog-question-'+p_part+did.m_id_suffix);
			if (!x)
				return;
	
			pElement.setInnerHTML(i_x, '');
		}*/
	};
	this.removeDialogOption = function(did, oid) {
		if (did = pDialog.getValue(did)) {
			if (did.request.options)
				did.request.options = did.request.options.filter(function(op) { return null!=op && op.id != oid; });
			pElement.remove(oid);
		}
	};

	this.getInputValue = function(did, oid) {
		if (did = pDialog.getValue(did)) {
			if (did.request.options) {
				var op = did.request.options.find(function(op) { return op && op.id == oid; });
				if (op)
					return f_getInputValue(op);
			}/*
				for(var i=0 ; i<i_dialog.request.options.length ; i++) {
					var op = i_dialog.request.options[i];
					if (null == op) continue;
					if (op.id != p_op_id) continue;
	
					if (op.input)
						return f_getInputValue(op);
				}*/
		}
		return null;
	};
	this.setInputValue = function(did, oid, v) {
		if (did = pDialog.getValue(did)) {
			if (did.request.options) {
				var op = did.request.options.find(function(op) { return op && op.id == oid; });
				if (op)
					f_setInputValue(op, v);
			}/*
				for(var i=0 ; i<i_dialog.request.options.length ; i++) {
					var op = i_dialog.request.options[i];
					if (null == op) continue;
					if (op.id != p_op_id) continue;
	
					if (op.input) {
						f_setInputValue(op, p_value);
						return;
					}
				}
	
			return null;*/
		}
	};
	this.getInputValues = function(did) {
		if (did = pDialog.getValue(did)) {
			var r = new pMap();
			if (did.request.options)
				did.request.options.forEach(function(op) {
					if (op)
						if (op.id != 'ok' && op.id != 'cancel')
							if (op.input) {
								var n = (op.input.type=='radio' && op.input.name)? op.input.name : op.id;
								if (!r.getValue(n))
									r.put(n, f_getInputValue(op));
							}
				});
	
			return r;
		}
	};
	this.isValid = function(did) {
		if (did = pDialog.getValue(did)) {
			if (did.request.options)
				for(var j=0 ; j<did.request.options.length ; j++) {
					var op = did.request.options[j];
					if (null == op) continue;
					if (op.id && op.id == 'ok') continue;
					if (op.id && op.id == 'cancel') continue;
	
					if (op.validators) {
						var vls = (Array.isArray(op.validators) === false)? [ op.validators ] : op.validators;
						for(var i=0 ; i<vls.length ; i++)
							if (vls[i] && vls[i].call(did, op) === false)
								return false;
					}
	
					if (op.input) {
						var v = pDialog.getInputValue(did, op.id);
	
						if (op.input.validators) {
							var vls = (Array.isArray(op.input.validators) === false)? [ op.input.validators ] : op.input.validators;
							for(var i=0 ; i<vls.length ; i++)
								if (vls[i]) {
									if (vls[i].isCallback || (typeof vls[i] == 'function')) {
										if (vls[i].call(did, op) === false)
											return false;
									}
									else if (!vls[i].test(v))
										return false;
								}
						}
	
						if (op.input.required && op.input.required === true)
							if (v == '')
								return false;
	
						/*if (op.input.pattern)
							if ((new RegExp(op.input.pattern)).test(i_value) === false) {
								//console.log('value : ' + i_value + ' invalid');
								return false;
							}*/
					}
	
			}
			return true;
		}
	};
	this.validate = function(did) {
		var x = pElement.x(did+'-ok');
		if (x)
			x.style.display = pDialog.isValid(did)? 'inline-block' : 'none';
	};

	function resizeTabs(i_dialog) {

		var i_min_w = 0;
		var i_min_h = 0;
		i_dialog.tags.forEach(function(t) {
			i_min_w = Math.max(i_min_w, pDocument.width(t.element));
			i_min_h = Math.max(i_min_h, pDocument.height(t.element));
		});/*
		for(var i=0 ; i<i_dialog.tabs.length ; i++) {
			var i_tab = i_dialog.tabs.valueAt(i);
			i_min_w = Math.max(i_min_w, pDocument.width(i_tab.element));
			i_min_h = Math.max(i_min_h, pDocument.height(i_tab.element));
		}*/

		i_dialog.tabs.forEach(function(t) {
			var i_style = new pStyle(t.element);

			//if (pDocument.width(i_tab.element)<i_min_w)
			t.element.style.minWidth = (i_min_w - i_style.surroundWidth()) + 'px';
			t.element.style.minHeight = (i_min_h - i_style.surroundHeight()) + 'px';
		});/*
		for(var i=0 ; i<i_dialog.tabs.length ; i++) {
			var i_tab = i_dialog.tabs.valueAt(i);
			var i_style = new pStyle(i_tab.element);

			//if (pDocument.width(i_tab.element)<i_min_w)
			i_tab.element.style.minWidth = (i_min_w - i_style.surroundWidth()) + 'px';
			i_tab.element.style.minHeight = (i_min_h - i_style.surroundHeight()) + 'px';
		}*/
	};

	this.selectNextTab = function(did) {
		if (did = pDialog.getValue(did)) {
			if (did.tabs) {
				if (did.selectedTabID) {
					var i_next_key = did.tabs.nextKey(did.selectedTabID);
					if (i_next_key)
						pDialog.selectTab(did, did.tabs.getValue(i_next_key).id);
					return;
				}
	
				var i_next_key = did.tabs.nextKey(did.tabs.keyAt(0));
				if (i_next_key)
					pDialog.selectTab(did, did.tabs.getValue(i_next_key).id);
				return;
			}
		}
	};

	this.selectPreviousTab = function(did) {
		if (did = pDialog.getValue(did)) {
			if (did.tabs) {
				if (did.selectedTabID) {
					var i_next_key = did.tabs.previousKey(did.selectedTabID);
					if (i_next_key)
						pDialog.selectTab(p_dialog_id, did.tabs.getValue(i_next_key).id);
					return;
				}
	
				var i_next_key = did.tabs.previousKey(did.tabs.keyAt(did.tabs.length-1));
				if (i_next_key)
					pDialog.selectTab(p_dialog_id, did.tabs.getValue(i_next_key).id);
				return;
			}
		}
	};

	this.selectTab = function(did, p_tab_id) {
		if (did = pDialog.getValue(did)) {
			var i_min_w = 0, i_min_h = 0;
			did.tabs.values().forEach(function(t) {
				i_min_w = Math.max(i_min_w, pDocument.width(t.element));
				i_min_h = Math.max(i_min_h, pDocument.height(t.element));
			});
			/*for(var i=0 ; i<did.tabs.length ; i++) {
				var i_tab = did.tabs.valueAt(i);
				i_min_w = Math.max(i_min_w, pDocument.width(i_tab.element));
				i_min_h = Math.max(i_min_h, pDocument.height(i_tab.element));
			}*/
	
			did.tabs.values().forEach(function(i_tab) {
				var i_style = new pStyle(i_tab.element);
			//for(var i=0 ; i<did.tabs.length ; i++) {
			//	var i_tab = did.tabs.valueAt(i), i_style = new pStyle(i_tab.element);
	
				//if (pDocument.width(i_tab.element)<i_min_w)
				i_tab.element.style.minWidth = (i_min_w - i_style.surroundWidth())+'px';
				i_tab.element.style.minHeight = (i_min_h - i_style.surroundHeight())+'px';
	
				if (i_tab.id == p_tab_id) {
					//*** LOAD TAB IMAGES
					(i_tab.imgs || []).forEach(function(i) {
						i.src = i.getAttribute(pPictures.ATTR_THUMB);
					});
	
					i_tab.element.scrollTop = 0;
					i_tab.element.scrollLeft = 0;
	
					pElement.addClassName(i_tab.element, 'dialog-tab-selected');
					pElement.addClassName('dialog-tab-title-'+i_tab.id, 'selected');
				}
				else {
					pElement.removeClassName(i_tab.element, 'dialog-tab-selected');
					pElement.removeClassName('dialog-tab-title-'+i_tab.id, 'selected');
					
					//*** UNLOAD TAB IMAGES
					(i_tab.imgs || []).forEach(function(i) {
						i.src = null;
					});
				}
				i_tab.title.style.display = 'inline-block';
			});
			did.selectedTabID = p_tab_id;
			
			//*** UPDATE SELECTORS
			did.fs_resize.f_resizeTabMore();
						
			//console.log(pDocument.top('dialog-question-tab-titles'+did.m_id_suffix) + ' ' + pDocument.top(p_tab_id));
			/*if (pDocument.top(p_tab_id) - pDocument.top('dialog-question-tab-titles'+did.m_id_suffix) > 20) {
				var show = false;
				did.tabs.values().forEach(function(t) {
					if (show || 'dialog-tab-title-'+t.id == p_tab_id) {
						t.title.style.display = 'inline-block';
						show = true;
					}
					else
						t.title.style.display = 'none';
				});
			}*/
		}
	};

	this.getSelectedTabID = function(did) {
		if (did = pDialog.getValue(did))
			if (did.tabs) {
				if (did.selectedTabID)
					return did.tabs.getValue(did.selectedTabID).id;
	
				return did.tabs.valueAt(0, null);
			}
	};

	this.lastTabID = function(did) {
		if (did = pDialog.getValue(did))
			if (did.tabs)
				return did.tabs.valueAt(did.tabs.length-1, null);
	};
	
	this.genDialogOption = function(i_dialog, op, p_show_img, p_tabid) {

		//*** HIDDEN
		if (op.hidden)
			return null;
		
		//*** SEPARATOR
		if (op.sep === true)
			return pElement.create('div', op.id, 'dialog-question-sep ' + (op.className || ''), op.text, op.style, [ 'attr_dialog_id', i_dialog.request.id ]);
		
		var i_value_done = false;

		//*** INPUT
		if (op.input) {
			var i_aedit = false;
			var i_div = pElement.create('div', op.id, 'dialog-question-input ' + (op.className || ''), null, op.style, [ 'attr_dialog_id', i_dialog.request.id ]);
			/*if (op.input.onchange)
				i_div.onchange = op.input.onchange;
			else
				i_div.onchange = function() { pDialog.validate(this.getAttribute('attr_dialog_id')); };
			if (op.input.oninput)
				i_div.oninput = op.input.oninput;
			else
				i_div.oninput = function() { pDialog.validate(this.getAttribute('attr_dialog_id')); };*/
				
			//*** SELECTOR
			var i_selector = i_dialog.select_input===true || (i_dialog.request && i_dialog.request.select_input===true);
			if (i_selector) {
				var x = pElement.create('input', 'select-'+op.id, 'dialog-select-input');
				x.type = "checkbox";
				x.onchange = function() { 
					var b = pElement.getValue('select-'+this.id); 
					pElement.x('dialog-input-'+this.id).disabled = b==false;
					pElement.setFor('dialog-input-label-'+this.id, b? 'dialog-input-'+this.id : 'select-'+this.id);
					if (b) pElement.focus('dialog-input-'+this.id);
				}.bind({ id: op.id });
				if (op.selected === true)
					x.checked = true; 
				else
					op.input.disabled = true;

				i_div.appendChild(x);
			}

			//*** LABEL 
			if (op.text) {
				var x = pElement.create(
					'label', 
					'dialog-input-label-' + op.id, 
					'dialog-input-label ' + ((i_dialog.select_input===true || (i_dialog.request && i_dialog.request.select_input===true))? 'dialog-select-input': '') + (op.text_class || ''), 
					op.text,
					op.label? op.label.style : null
				);
				x.htmlFor = (i_selector && op.input.disabled === true)? 'select-'+op.id : 'dialog-input-' + op.id;
				i_div.appendChild(x);
			}

			var i_input,  i_icons = [];

			if (op.input.type == 'select') {

				//*** IMPLEMENT DIALOG BOX INSTEAD OF SELECT FOR iOS
				if (pROSE.getProp('ui-dialog-for-select')) {
					i_input = pElement.create('input');
					i_input.type = 'search';

					var i_links = [];
					(op.input.options || []).forEach(function(o) {
						i_links.push({
							text: (typeof o=="string")? o : o.text,
							value: (typeof o=="string")? o : (o.value || o.text),
							title: (typeof o=="string")? null : o.title,
							fcall: function(p_dialog, p_value) { pElement.updateValue(i_input, p_value); }
						});
					});
					if (op.value && !i_links.some(function(p_link) { return p_link.value == op.value; }))
						i_links.push({ 
							text: op.value, 
							value: op.value, 
							fcall: function(p_dialog, p_value) { pElement.updateValue(i_input, p_value); }
						});

					i_icons.push({
						className: 'dialog-question-button-select',
						title: 'Click here to select the value...',
						onclick: function(op_id){ pApplicationMenu.menu(op_id, i_links); }
					});
				}
				else {
					i_input = pElement.create('select');
					(op.input.options || []).forEach(function(o) {
						var x = pElement.create('option');
						x.text = (typeof o=="string")? o : o.text;
						x.value = (typeof o=="string")? o : (o.value || o.text);
						pElement.setTitle(x, o.title);
						if (op.selected || op.input.selected || (op.value && x.value == op.value) || o.selected) x.selected = true;
						i_input.add(x);
					});
				}

				if (op.value)
					pElement.setValue(i_input, op.value);
			}
			else if (op.input.type == 'textarea') {
				i_input = pElement.create('textarea');
				if (op.input.rows) i_input.rows = op.input.rows;
				if (op.input.cols) i_input.cols = op.input.cols;
			}
			else if (op.input.type == 'checkbox') {
				i_input = pElement.create('input');
				i_input.type = op.input.type;
				if (op.value === true || op.value == "true") i_input.checked = true;
			}
			else if (op.input.type == 'radio') {
				i_input = pElement.create('input');
				i_input.type = op.input.type;
				if (op.input.selected) i_input.checked = true;
			}
			else if (op.input.type == 'server-file') {
				i_input = pElement.create('input');
				i_input.type = 'search';

				i_icons.push(pDialog.genOptionInputIcon(op.id, { className: 'dialog-question-button-fileserver',
					onclick: function(oid, iid) {
						pOpenFileDialog.selectFile({ 
							readonly: i_input.readOnly, 
							callback: (i_input.readOnly)? null : function(p_path) { pElement.updateValue(iid, p_path); }, 
							title: (op.browse)? op.browse.title : (i_input.readOnly)? null : 'Select File...', 
							current_path: i_input.value 
						});
					},
					title: "Click here to select a file from the server..."
				}));
			}
			else if (op.input.type == 'server-folder') {
				i_input = pElement.create('input');
				i_input.type = 'search';

				i_icons.push(pDialog.genOptionInputIcon(op.id, { className: 'dialog-question-button-fileserver',
					onclick: function(oid, iid) {
						pOpenFileDialog.selectFolder({ 
							readonly: i_input.readOnly, 
							callback: (i_input.readOnly)? null : function(p_path) { pElement.updateValue(iid, p_path); }, 
							title: (op.browse)? op.browse.title : (i_input.readOnly)? null : 'Select Folder...', 
							current_path: i_input.current_path || i_input.value 
						});
					},
					title: "Click here to select a folder from the server..."
				}));
			}
			else if (op.input.type == 'link') {
				i_input = pElement.create('input', null, 'dialog-input-link');
				i_input.type = 'search';
				i_input.pattern = /.+/g;
				i_input.onclick = function() { if (this.value && this.value.trim()!='') window.open(this.value.trim(), '_blank'); };
			}
			else {
				i_input = pElement.create('input');
				i_input.type = op.input.type || 'search';
				i_input.setAttribute('xtype', op.input.type);

				if (op.value) pElement.setValue(i_input, op.value);
				if (op.input.data_value) pElement.setAttribute(i_input, 'data_value', op.input.data_value);
				i_value_done = true;

				if (op.input.selection && op.value) {
					var i_pos = op.value.indexOf(op.input.selection);
					if (i_pos>=0)
						i_input.setSelectionRange(i_pos, i_pos+op.input.selection.length);
				}
				
				i_aedit = true; //remove if disabled or readonly
			}
			
			i_input.id = 'dialog-input-' + op.id;
			if (op.input.name) i_input.name = op.input.name;
			if (op.input.value) i_input.value = op.input.value; //0.9.20
			i_input.className += ' dialog-input';
			i_input.setAttribute('attr_dialog_id', i_dialog.request.id);
			
			if (!i_value_done)
				if (op.value) pElement.setValue(i_input, op.value, false);
			
			//*** TITLE
			if (op.title) 
				i_input.title = op.title; 
			else if (op.input.readonly && op.input.type!='checkbox' && op.input.type!='radio') 
				i_input.title = op.value;
						
			//i_input.onsubmit = function() { alert('submit'); };
			if (op.input.disabled) i_input.disabled = true;
			if (i_dialog.request.readonly === true || op.input.readonly === true || op.input.readonly_value === true) {
				i_input.readOnly = true;
				if (op.input.type == 'select')
					i_input.disabled = true;
				if (op.input.type == 'checkbox')
					i_input.disabled = true;
			}
			if (op.input.autocomplete === false || op.input.raw === true) i_input.autocomplete = "off"; else i_input.autocomplete = "on";
			if (op.input.autocorrect === false || op.input.raw === true) i_input.autocorrect="off"; else i_input.autocorrect = "on";
			if (op.input.autocapitalize === false || op.input.raw === true) i_input.autocapitalize="off"; //else i_input.autocapitalize = "words";
			if (op.input.spellcheck === false) i_input.spellcheck="false"; else i_input.spellcheck = "true";
			if (op.input.placeholder) i_input.placeholder = op.input.placeholder;
			if (op.input.min) i_input.min = op.input.min;
			if (op.input.max) i_input.max = op.input.max;
			i_input.style = op.input.style;
			if (op.input.pattern) i_input.pattern = op.input.pattern; //TODO: transform RegEx objects into strings
			//op.input.re = new RegExp(op.input.pattern);
			if (op.input.required) i_input.required = op.input.required;
			
			if (op.input.onchange)
				i_input.onchange = op.input.onchange;
			else
				i_input.onchange = function() { pDialog.validate(this.getAttribute('attr_dialog_id')); };
			if (op.input.oninput)
				i_input.oninput = op.input.oninput;
			else
				i_input.oninput = function() { pDialog.validate(this.getAttribute('attr_dialog_id')); };

			i_input.addEventListener("keydown", function(e) {
				pConsole.info('Document', 'keyCode down: ' + e.keyCode);// + ', dialog: ' + i_dialog_id);

				if (e.keyCode == pKeys.escape && i_dialog.has_cancel===true) { //ESC
					//console.log(pDocumenti.activeElement());
					pElement.blur(pDocumenti.activeElement());
				}
				
				if (e.keyCode == 13 && i_dialog.has_ok) {
					this.setAttribute("attr_value", this.value);
					//console.log("store value: " + this.value);
				}
			});
			
			i_input.addEventListener("keyup", function(e) {
				var i_dialog_id = this.getAttribute('attr_dialog_id');

				pConsole.info('Document', 'keyCode up: ' + e.keyCode + ', dialog: ' + i_dialog_id);

				//var x = pDocumenti.activeElement();
				//var y = x.localName;
				
				//var i_dialog_id
				var i_dialog = m_dialogs.getValue(i_dialog_id, null);
				if (null==i_dialog) {
					//console.log('here');
					return;
				}

				//i_dialog = i_dialog.request;
				//var i_dialog_id

				if (e.keyCode == pKeys.escape && i_dialog.has_cancel===true) { //ESC
					
					//console.log(pDocumenti.activeElement());
					pElement.blur(pDocumenti.activeElement());
					
					e.stopPropagation();

					pDialog.dialogQuestionClose(i_dialog.id, 'cancel');
					return false;
				}
				if (e.keyCode == pKeys.enter && i_dialog.has_ok && pDialog.isValid(i_dialog_id)) { //RETURN
				
					//console.log("stored  value: " + this.getAttribute('attr_value'));
					//console.log("current value: " + this.value);
					if (this.value != this.getAttribute('attr_value'))
						return;
					
					e.stopPropagation();

					pDialog.dialogQuestionClose(i_dialog.id, 'ok');
					return false;
				}
				/*if (e.keyCode >= 97 && e.keyCode <= 105) { //1 to 9if (e.keyCode <=
					var i = e.keyCode -96;
					if (i_dialog.options && i_dialog.options.length>0 && i_dialog.options.length>=i) {
						var op = i_dialog.options[i-1];
						pDialog.dialogQuestionClose(i_dialog.id, ((op.id)? op.id : ''), + op.value);
					}
					return false;
				}*/
			}, false);
			i_input.setAttribute("list", 'dlist-'+i_input.id);

			var i_field = pElement.create('div', null, 'form-field', null, null, [ 'input-type', op.input.type ]);
			i_field.appendChild(i_input);
			
			//*** CREATE AND FILL DATALIST
			if (op.input.type != 'checkbox' && op.input.type != 'radio')
				pElement.fillDatalist(i_field.appendChild(pElement.create('datalist', 'dlist-'+i_input.id)), op.input.datalist);
			//var i_datalist = document.createElement('datalist');
			//i_datalist.id = 'dlist-'+i_input.id;
			//i_field.appendChild(i_datalist);

			//*** CREATE ICONS
			var x_icons = pElement.create('div', null, 'dialog-question-input-buttons'), i_op_icons_length = 0;
			if (i_aedit && !i_input.disabled  && !i_input.readOnly && i_input.type!='password')
				i_icons = [ pDialog.resources.icon_advanced_editting ].concat(i_icons);
			i_icons.forEach(function(i) {
				if (i) {
					x_icons.appendChild(pDialog.genOptionInputIcon(op.id, i, i_input));
					i_op_icons_length++;
				}
			});
			(op.input.icons || []).forEach(function(i) {
				if (i) {
					x_icons.appendChild(pDialog.genOptionInputIcon(op.id, i, i_input));
					i_op_icons_length++;
				}
			});
			if (i_op_icons_length>0) {
				i_input.className = i_input.className + ' dialog-question-input-'+i_op_icons_length+'-buttons';

				x_icons.appendChild(pElement.createClearDiv());
			}
			i_field.appendChild(x_icons);

			//*** ADD INPUT FIELD
			i_div.appendChild(i_field);

			//*** ADD TEXT AFTER
			if (op.text_after) {
				var x = pElement.create('label', 'dialog-input-label-' + op.id, 'dialog-input-label ' + (op.text_after_class || ''), op.text_after);
				x.htmlFor = 'dialog-input-' + op.id;
				i_div.appendChild(x);
			}

			if (op.trailer)
				i_div.appendChild(pElement.create('span', null, null, op.trailer));

			//*** SET FOR FOCUS
			if (!i_dialog.focus && !op.input.disabled)
				i_dialog.focus = i_input;

			return i_div;
		}

		//*** IMAGE
		if (op.image && (op.image.uri || op.image.name)) {
			//if (op.image.uri && op.image.uri.indexOf('file:/')!=0) {

			if (op.id) i_dialog.options.put(op.id, op);

			var i_div = pElement.create(
				'div', op.id, 
				((op.enabled === false || op.disabled === true)? 'dialog-question-disabled dialog-question-option-image ' : 'dialog-question-option dialog-question-option-image ') + (op.className || ''),
				null, //text
				op.style,
				[ 'attr_dialog_id', i_dialog.request.id ]
			);
			//i_div.setAttribute('attr_dialog_id', i_dialog.request.id);
			//i_div.style = op.style;
			if (op.value && op.disabled != true)
				i_div.onclick = function() { pDialog.dialogQuestionClose(this.getAttribute('attr_dialog_id'), this.id); };

				var cl = '';
				if (!op.image.thumbs && pApplicationUI.OPTION_PICTURES_ROTATE) {
					switch (parseInt(op.image.orientation)) {
						case 8: //turn to right
							cl = 'rotate-right'; break;
						case 3: //flip horizontally
							cl = 'rotate-half'; break;
						case 6:
							cl = 'rotate-left'; break;
					}
				}
				
			var i_img = pElement.create(
				'img', null, 
				'dialog-question-image ' + (op.image.className || '') + ' ' + cl,
				null, //text
				null, //style
				[ 
					pPictures.ATTR_THUMB, (op.image.thumbs)? pURL.addParam(op.image.thumbs[0].uri, 'v', op.image.thumbs[0].lastModified) : (op.image.uri)? pURL.addParam(op.image.uri, 'v', op.image.lastModifed) : op.image.name,
					pPictures.ATTR_URL, op.image.uri,
					'org-or', op.image.orientation,
					'ondragstart', 'pPictures.dragStart(event)'
				]);
			
			//i_img.setAttribute('attr_opid', op.id);
			if (op.image.owidth && op.image.owidth>0) {
				i_img.setAttribute('org-width', op.image.owidth);
				i_img.setAttribute('org-height', op.image.oheight);
			}
			if (op.image.width && op.image.width>0) {
				i_img.setAttribute('org-width', op.image.width);
				i_img.setAttribute('org-height', op.image.height);
			}
			//i_img.setAttribute('org-or', op.image.orientation);
			if (p_show_img===true || i_dialog.tabs.length<2)  // || pDialog.getSelectedTabID(i_dialog.id) == pDialog.lastTabID(i_dialog.id))
				i_img.src = i_img.getAttribute(pPictures.ATTR_THUMB);

			if (!op.image.thumbs && pApplicationUI.OPTION_PICTURES_ROTATE) {
				var o = parseInt(op.image.orientation);
				if (o == 8 || o == 6) {
					var h = 120, ww = op.image.ww || pPictures.thumbWidth(op.image.width, op.image.height, h);
					i_img.style.width = Math.max(h, pPictures.thumbHeight(op.image.width, op.image.height, h)) + 'px';
					i_img.style.height = Math.max(h, ww) + 'px';
				}
			}
			else {
				if (op.image.owidth && op.image.owidth>0) {
					i_img.height = 120;
					i_img.width = 120 * parseInt(op.image.owidth) / parseInt(op.image.oheight);
				}
				if (op.image.width && op.image.width>0) {
					i_img.height = 120;
					i_img.width = 120 * parseInt(op.image.width) / parseInt(op.image.height);
				}
			}
			
			/*
			var i_srcset = i_img.getAttribute(pPictures.ATTR_URL);
			if (op.image.width) i_srcset += ' '+op.image.width + 'w';
			if (op.image.s1024x768 && op.image.s1024x768.width)
				i_srcset += ','+op.image.s1024x768.uri + ' ' + op.image.s1024x768.width + 'w';
			if (op.image.s1920x1080 && op.image.s1920x1080.width)
				i_srcset += ','+op.image.s1920x1080.uri + ' ' + op.image.s1920x1080.width + 'w';
			i_img.srcset = i_srcset;
			*/
			
			i_img.title = pString.validOrNull(op.title) || pPictures.tooltip(op.image);
			
			//i_img.title = (op.title)? op.title :
			//	((op.image.owidth && op.image.owidth>0 && op.image.oheight && op.image.oheight>0)? ''+op.image.owidth + ' x ' + op.image.oheight +
			//			((op.image.domain)? ' - ' + op.image.domain : ''):'');
			
			if (!pString.v(i_img.title) || !pPictures.hasdim(op.image))
				i_img.onload = function() {
					var n = (pString.validOrNull(op.image.name) || pString.basename(pLocation.path(i_img.src))) + '\n';
					i_img.title = (pString.validOrNull(n) || '') + i_img.naturalWidth + ' x ' + i_img.naturalHeight;
					/*
					if (op.image.name)
						i_img.title = op.image.name+'\n'+i_img.naturalWidth + ' x ' + i_img.naturalHeight;
					else {
						var n  = pString.basename(pLocation.path(i_img.src));
						i_img.title = ((pString.v(n))? n+'\n' : '') + i_img.naturalWidth + ' x ' + i_img.naturalHeight;
					}*/
				};
			
			if (op.image.onerror) {
				var i_cb = op.image.onerror;
				i_img.onerror = function() {
					i_cb.call(this, this);
				};
			}
			//if (op.image.height) i_img.height = op.image.height;
			//if (op.image.width) i_img.width = op.image.width;
			i_img.referrerPolicy = op.image.referrerPolicy;
			i_img.crossOrigin = op.image.crossOrigin;
			if (op.image.srcset) i_img.srcset = op.image.srcset;
			i_img.sizes = op.image.sizes;

			//*** SELECTOR
			/*var i_selector = document.createElement('input');
			i_selector.type = 'checkbox';
			i_selector.id = op.id + '-selector';
			i_selector.className = 'dialog-question-image-selector';
			i_div.appendChild(i_selector);*/

			i_div.appendChild(i_img);
			if (op.dcall && !i_dialog.readonly && op.readonly!=true) {
				var x = pElement.create('div', null, 'link dialog-question-image-remove', '&times');
				x.onclick = function() { op.dcall.call(this); };
				i_div.appendChild(x);
			}

			if (op.text_after) {
				var x = pElement.create('div', 'dialog-after-' + op.id, 'dialog-after dialog-after-img ' + (op.text_after_class || ''), op.text_after);
				x.htmlFor = 'dialog-input-' + op.id;
				i_div.appendChild(x);
			}

			//*** ADD INTO TAB IMAGE ARRAY...
			if (i_dialog.tabs.length>0) {
				var t = i_dialog.tabs.getValue(p_tabid || i_dialog.selectedTabID);//valueAt(i_dialog.tabs.length-1, null);
				(t.imgs = t.imgs || []).push(i_img);
			}

			//*** DELETE
			/*var i_delete = document.createElement('div');
			i_delete.id = op.id + '-delete';
			i_delete.className = 'dialog-question-image-delete';
			i_div.appendChild(i_delete);*/

			//if (!op.value)
			//	op.value = {image: op.image};

			return i_div;
		}

		//*** DISABLED
		if (op.enabled === false || op.disabled === true) {
			var x = pElement.create('div', op.id, 'dialog-question-disabled ' + (op.className || ''), op.text, op.style, [ 'attr_dialog_id', i_dialog.request.id ]);

			if (op.icon == 'null')
				x.innerHTML = '<div style="padding-left: 26px;">' + op.text + '</div>';
			else if (op.icon)
				x.innerHTML = '<img class="image"  style="vertical-align: middle; padding-right: 10px;" src="'+op.icon+'"/>' + op.text;
			return x;
		}

		//*** DEFAULT
		var i_id = op.id;
		if (i_id == 'ok') i_id = i_dialog.request.id+'-ok';
		if (i_id == 'cancel') i_id = i_dialog.request.id+'-cancel';

		if (op.id) {
			i_dialog.options.put(i_id, op);
			if (op.id != i_id)
				i_dialog.options.put(op.id, op);
		}

		var i_div = pElement.create(
			'div', i_id, 'dialog-question-option ' + (op.className || '') + ((op.vdefault===true && i_dialog.has_ok===false)? ' dialog-default':''), 
			op.text, 
			op.style,
			[ 'attr_dialog_id', i_dialog.request.id, 'attr_op_id', op.id, 'name', i_id, 'title', op.title ]
		);
		//i_div.setAttribute('attr_dialog_id', i_dialog.request.id);
		//i_div.setAttribute('attr_op_id', op.id);
		//i_div.setAttribute('name', i_id);
		//pElement.setTitle(i_div, op.title);

		if (op.icon == 'null')
			i_div.innerHTML = '<div style="padding-left: 26px;">' + op.text + '</div>';
		else if (op.icon && op.icon != 'none')
			i_div.innerHTML = '<img class="image" style="vertical-align: middle; padding-right: 10px; max-height: 16px; max-width: 16px;" width="16" height="16" src="'+op.icon+'"/>' + op.text;

		if (op.accessKey)
			i_div.accessKey = op.accessKey;
		i_div.onclick = function() {
			pDialog.dialogQuestionClose(this.getAttribute('attr_dialog_id'), this.getAttribute('attr_op_id'));
			return false;
		};
		return i_div;
	};

	this.genOptionInputIcon = function(p_op_id, p_icon, p_input) {
		var x = pElement.create('div', null, 'dq-input-bt ' + (p_icon.className || ''), null, null, [ 'dialog-option-id', p_op_id ]);
		x.onclick = function() { p_icon.onclick.call(this, this.getAttribute('dialog-option-id'), 'dialog-input-' + this.getAttribute('dialog-option-id')); };
		pElement.setTitle(x, p_icon.title);
		
		if (p_icon.ondisable === true) {
			var f = function() {
				var v = this.value;
				if (pString.v(v))
					pElement.removeClassName(x, 'disabled');
				else
					pElement.addClassName(x, 'disabled');
			}.bind(p_input);
			p_input.addEventListener('input', f);
			f.call(p_input);
		}
		return x;
	};

	this.dialogDestroy = function(did, p_noremove) {
		if (did = pDialog.getDialog(did)) {
			var i_id_suffix = did.m_id_suffix, xf = pElement.x('dialog-question-frame' + i_id_suffix), xq = pElement.x('dialog-question'+i_id_suffix), xb = pElement.x(xq.id+'-bg');

			eh.fireEvent('close-before', did, { });
			
			//*** REMOVE ON RESIZE FUNCTIONS
			for(var n in did.fs_resize)
				pDocument.removeOnResize(did.fs_resize[n]);
			
			pDocument.hide(xb);
			pDocument.hideComponent(f_ui_getDialogElement(did));
			pElement.removeClassName(xf, 'dialog-show ' + (did.request.className || ''));
			if (did.request.className) pElement.removeClassName('dialog-question-content'+i_id_suffix, 'content-'+did.request.className);
			/*pDialog.clearDialogOptions(id, 'content');
			pDialog.clearDialogOptions(id, 'header');
			pDialog.clearDialogOptions(id, 'footer');
			if (i_id_suffix!='')
				pElement.x('dialog-question').removeChild(pElement.x('dialog-question' + i_id_suffix));*/

			pElement.x(xf).style.width = null;
			pElement.x(xf).style.maxWidth = null;
			
			//*** DISABLE KEY ESC BINDING
			if (did.onkeydown_old)
				document.onkeydown = did.onkeydown_old;
	
			f_removeDialog(did);
			
			if (!pDialog.isDialogOn())
				pElement.removeClassName(document.body, 'noscroll-dialog');
				
			//*** ENABLE TAB NAVIGATION
			pDocument.enableNav();
			
			eh.fireEvent('close', did, { first: !pDialog.isDialogOn() });
			
			if (pString.v(did.m_id_suffix)) {
				pDocument.uncoverWholePage(xb);
				pElement.remove(xb);
				
				pDocument.uncoverWholePage(xq);
				pElement.remove(xq);
			}
		}
	};

	this.dialogSelect = function(p_dialog, opid) {
		
		var i_option = p_dialog.options.getValue(opid, null);
		if (i_option) {
			var v = i_option.value || opid;
			
			if (!p_dialog.selected.includes(v)) {
			//var pos = p_dialog.selected.indexOf(opid);
			//if (pos < 0) {
				p_dialog.selected.push(v);
	
				var x = p_dialog.elements.getValue(opid, null);
				if (!x)
					p_dialog.elements.put(opid, x = pElement.x(opid));
	
				pElement.addClassName(x, 'dialog-selected');
				pElement.addClassName(pElement.n(opid), 'dialog-selected');
			}
		}
	};
	this.dialogUnSelect = function(p_dialog, opid) {

		var i_option = p_dialog.options.getValue(opid, null);
		if (i_option) {
			var v = i_option.value || opid;
		
			//if (p_dialog.selected.includes(opid)) {
			var pos = p_dialog.selected.indexOf(v);
			if (pos >= 0) {
				p_dialog.selected.splice(pos, 1);
	
				var x = p_dialog.elements.getValue(opid, null);
				if (!x)
					p_dialog.elements.put(opid, x = pElement.x(opid));
	
				pElement.removeClassName(x, 'dialog-selected');
				pElement.removeClassName(pElement.n(opid), 'dialog-selected');
			}
		}
	};
	this.getDialog = function(did) {
		return f_getDialog(did);
	};

	this.dialogSaveInputValues = function(i_dialog) {
		if (i_dialog.request.options) {

			var i_select = i_dialog.select_input===true || (i_dialog.request && i_dialog.request.select_input===true);

			(i_dialog.request.inputs = i_dialog.request.inputs || new pMap()).clear();
			//i_dialog.request.inputs.clear();

			i_dialog.request.options.forEach(function(op) {
				if (null == op) return;
				if (op.id == 'ok') return;
				if (op.id == 'cancel') return;

				if (op.input) {
					var i_input = f_ui_getDialogInputElement(op);
					if (i_input.disabled === true) return;
					if (i_select === true && pElement.x('select-'+op.id).checked != true) return;

					var i_value = f_getInputValue(op);

					var n = (op.input.type == 'radio' && op.input.name)? op.input.name : op.id;
					if (!i_dialog.request.inputs.getValue(n)) {
						if (op.input.type!='radio' && i_dialog.request.submitChangedInputsOnly === true) {
							if (i_value != op.value)
								i_dialog.request.inputs.put(n, i_value);
						}
						else
							i_dialog.request.inputs.put(n, i_value);
					}
				}
			});
		}
	};

	this.dialogQuestionClose = function(id, opid) {
		var i_dialog = pDialog.getDialog(id);
		if (null==i_dialog)
			return;
		
		var i_option = i_dialog.options.getValue(opid, null);
		if (i_option)
			if (i_option.scall) {
				i_option.scall.call(this, i_dialog.request, i_option.value, i_option);
				return;
			}

		var i_id_suffix = i_dialog.m_id_suffix;
		var i_multiple = i_dialog.request.multiple === true;
		var i_radio = i_dialog.request.radio === true;

		if (opid != 'ok' && opid != 'cancel') {

			if (i_multiple === true) {
				var v = i_option.value || i_option.id;
				
				if (i_dialog.selected.includes(v))
					pDialog.dialogUnSelect(i_dialog, opid);
				else
					pDialog.dialogSelect(i_dialog, opid);
				return;
			}

			if (i_radio === true) {
				var i_sep_prev_index = -1;
				for(var i=0 ; i<i_dialog.request.options.length ; i++) {
					var op = i_dialog.request.options[i];
					if (null == op) continue;

					if (op.sep === true)
						i_sep_prev_index = i;
					if (op.id === opid)
						break;
				}

				for(var i=(i_sep_prev_index>=0)? i_sep_prev_index+1 : 0 ; i<i_dialog.request.options.length ; i++) {
					var op = i_dialog.request.options[i];
					if (null == op) continue;

					if (op.sep === true)
						break;

					if (op.id === opid)
						pDialog.dialogSelect(i_dialog, op.id);
					else
						pDialog.dialogUnSelect(i_dialog, op.id);
				}
				return;
			}
		}

		//*** SAVE INPUT VALUES
		pDialog.dialogSaveInputValues(i_dialog);

		if (i_dialog.request.destroy==null || i_dialog.request.destroy===true)
			pDialog.dialogDestroy(id);

		if (opid === 'cancel' && !i_option.value) {
			pDialog.dialogDestroy(id);

			if (i_dialog.request.ccall)
				i_dialog.request.ccall.call(this, i_dialog.request, null, i_option);

			return;
		}

		if (opid != 'cancel' && (i_multiple === true || i_radio === true)) {
			if (i_dialog.request.fcall)
				i_dialog.request.fcall.call(this, i_dialog.request, i_dialog.selected);
			return;
		}

		//*** INVOKE CALLBACK
		if (i_option)
			if (i_option.fcall) {
					i_option.fcall.call(this, i_dialog.request, i_option.value, i_option);
					return;
				}
		
		if (i_dialog.request.fcall)
			i_dialog.request.fcall.call(this, i_dialog.request, i_option? i_option.value : null, i_option);
	};
	
	this.filterOptions = function(ops, did) {
		ops = (ops || []).filter(pObject.isNotNull).map(function(op) {
			if (op=='ok' || op=='cancel')
				return { id: op };
			if (op=='yes')
				return { id: 'ok', text: 'YES' };
			if (op=='no')
				return { id: 'cancel', text: 'NO' };
			if (typeof op == "string")
				return { id: 'sep', sep: true, text: op.charAt(0)=='!'? pDocument.getStyleValue('dialog-'+did.id+'-' + op.substring(1), 'content') : op, disabled: true };
			return op;
		});
		return ops.filter(function(op) { return op.id!=null });
	};
	
	this.getDefaultTitle = function(id) {
		return pDocument.getStyleValue('dq-'+id+'-title') || pDocument.getStyleValue('dialog-'+id+'-title');
	};
	
	this.tabMenu = function(did) {
		if (did = pDialog.getDialog(did)) {
			var l = did.tabs.values().map(function(t) {
				return { id: t.id, text: t.text, title: t.title.title, description: t.description, className: t.id == did.selectedTabID? 'tab-title-selected' : '', fcall: t.id == did.selectedTabID? null : t.f_select, selected: t.id == did.selectedTabID, disabled: t.id == did.selectedTabID };
			});
			
			pApplicationMenu.menu('dq-tab-titles'/*+i_id_suffix*/, l, true);
		}
	};
		
	this.dialogQuestion = function(p_dialog) {
		var x = pElement.x("dialog-question");
		if (null==x) {
			pConsole.error('Document', 'Cannot find dialog-question element...');
			return null;
		}

		if (!p_dialog.id) {
			pConsole.error(this, 'Missing dialog id');
			return;
		}
		
		//*** DEFAULT TITLE
		p_dialog.title = p_dialog.title || pDialog.getDefaultTitle(p_dialog.id);
		
		//*** DEFAULT ICON
		if (!p_dialog.icon) {
			var u = pDocument.getStyleValue('dq-'+p_dialog.id+'-icon') || pDocument.getStyleValue('dialog-'+p_dialog.id+'-icon');
			if (u)
				p_dialog.icon = { src: u };
		}

		//*** DISABLE TAB NAVIGATION
		pDocument.disableNav();
		
		var i_dialog = {
			id: p_dialog.id,
			request: p_dialog,
			focus: p_dialog.focus,
			selected: [],
			elements: new pMap(),
			options: new pMap(),
			onkeydown: function(e) {
				pConsole.debug('Dialog', 'keyCode: ' + e.keyCode + ', dialog: ' + p_dialog.id);

				var i_dialog = m_dialogs.valueAt(m_dialogs.length-1);//getValue(''+p_dialog.id, null);
				if (!i_dialog) {
					//console.log('no dialog...');
					return;
				}

				//i_dialog = i_dialog.request;

				if (e.keyCode == pKeys.escape && i_dialog.has_cancel) { //ESC
					e.stopPropagation();

					pDialog.dialogQuestionClose(i_dialog.id, 'cancel');
					return false;
				}
				if (e.keyCode == pKeys.enter && i_dialog.has_ok && pDialog.isValid(i_dialog.id)) { //RETURN
					
					var f = pDocumenti.activeElement();
					if (f)
						if ([ "input", "select", "a", "textarea" ].includes(f.localName.toLowerCase()))
							return true;
					
					e.stopPropagation();

					pDialog.dialogQuestionClose(i_dialog.id, 'ok');
					return false;
				}
				if (e.keyCode == 13 && i_dialog.default_id && pDialog.isValid(i_dialog.id)) { //RETURN
					e.stopPropagation();

					pDialog.dialogQuestionClose(i_dialog.id, i_dialog.default_id);
					return false;
				}
				if (e.keyCode >= 97 && e.keyCode <= 105) { //1 to 9if (e.keyCode <=
					var i = e.keyCode -96;
					if (i_dialog.request.options && i_dialog.request.options.length>0 && i_dialog.request.options.length>=i) {
						e.stopPropagation();

						var op = i_dialog.request.options[i-1];
						pDialog.dialogQuestionClose(i_dialog.id, ((op.id)? op.id : ''), + op.value);
						return false;
					}
				}

				if (i_dialog.request.options)
					for(var i=0 ; i<i_dialog.request.options.length ; i++) {
						var op = i_dialog.request.options[i];
						if (!op) continue;
						if (!op.accessKey) continue;
						if (e.key == op.accessKey) {
							var i_x = pElement.x(op.id);//.focus();
							if (i_x && i_x.sctrollIntoView)
								pDocument.scrollTo(i_x);
							break;
						}
					}
				
				//console.log('here...');
			},
			has_cancel: false,
			has_ok: false,
			fs_resize: {}
		};

		f_putDialog(i_dialog);

		var i_id_suffix = i_dialog.m_id_suffix = p_dialog.m_id_suffix = '';

		//*** DIALOG ALREADY IN PLACE...
		var fs = pDocument.isFullScreen(), dl = m_dialogs.length;
		if (dl>1 || fs) {
			i_id_suffix = i_dialog.m_id_suffix = p_dialog.m_id_suffix = '-' + p_dialog.id;

			var y = pElement.x('dialog-question'+i_id_suffix), zi = parseInt(pDocument.getStyleValue('.dialog-question', 'z-index'));
			if (!y) {
				(fs? pDocument.fullScreenElement() : x).appendChild(pElement.create('div', 'dialog-question'+i_id_suffix+'-bg', 'dialog-question-bg', null, 'z-index: ' + (zi+dl)));
				
				var i_div = pElement.create('div', 'dialog-question'+i_id_suffix, 'dialog-question', null, 'z-index: ' + (zi+dl));

				var i_html = '';//'<div id="dialog-question'+i_id_suffix+'" class="dialog-question">';// style="z-index: '+(99 + m_dialogs.length)+'; ">';
				i_html += '<div class="dialog-question-filler"><!----></div>';
				i_html += '<div id="dialog-question-frame'+i_id_suffix+'" class="dialog-question-frame">';
				i_html += '<div id="dialog-question-titlebar'+i_id_suffix+'">';
				i_html += '<div id="dialog-question-icon'+i_id_suffix+'" class="dialog-question-icon">';
				i_html += '<img id="img_dialog-question-icon'+i_id_suffix+'" src="/resources/html/images/32x32/question.png"/>';
				i_html += '	</div>';
				i_html += '<div id="dialog-question-title'+i_id_suffix+'" class="dialog-question-title">';
				i_html += '		<!---->';
				i_html += '	</div>';
				i_html += '</div>';
				i_html += '<div id="dialog-question-header'+i_id_suffix+'" class="dialog-question-header">';
				i_html += '	<!---->';
				i_html += '</div>';
				i_html += '<div id="dialog-question-tab-titles'+i_id_suffix+'" class="dialog-question-tab-titles">';
				i_html += '					<!---->';
				i_html += '</div>';
				i_html += '<div id="dialog-question-content'+i_id_suffix+'" class="dialog-question-content">';
				i_html += '	<!---->';
				i_html += '</div>';
				i_html += '<div id="dialog-question-footer'+i_id_suffix+'" class="dialog-question-footer">';
				i_html += '	<!---->';
				i_html += '</div>';
				i_html += '<!---->';
				i_html += '</div>';
				i_html += '<div class="dialog-question-filler"><!----></div>';
				i_html += '<!---->';
				//i_html += '</div>';

				i_div.innerHTML = i_html;

				(fs? pDocument.fullScreenElement() : x).appendChild(i_div);
				x = i_div;
			}
			else
				x = y;
			
			eh.fireEvent('open', p_dialog, { first: false });
		}
		else {
			eh.fireEvent('open', p_dialog, { first: true });			
			
			pElement.setClassName('dialog-question-frame' + i_id_suffix, 'dialog-question-frame');
			pElement.setClassName('dialog-question-content'+i_id_suffix, 'dialog-question-content');
		}

		//*** ICON
		//pDocument.show('dialog-question-icon'+i_id_suffix);
		pElement.setSrc('img_dialog-question-icon'+i_id_suffix, '/resources/html/images/32x32/question.png');
		if (p_dialog.icon) {
			if (p_dialog.icon.src)
				pElement.setSrc('img_dialog-question-icon'+i_id_suffix, p_dialog.icon.src);
			else
				pDocument.hide('dialog-question-icon'+i_id_suffix);
		}
		
		//*** TITLE
		if (p_dialog.title) {
			pDocument.show("dialog-question-titlebar"+i_id_suffix);
			pElement.setInnerHTML('dialog-question-title' + i_id_suffix, p_dialog.title);
		}
		else
			pDocument.hide("dialog-question-titlebar"+i_id_suffix);

		//var i_html = '';
		//var i_focus = null;

		//*** FILTER
		p_dialog.header = pDialog.filterOptions(p_dialog.header, p_dialog);
		p_dialog.options = pDialog.filterOptions(p_dialog.options, p_dialog);
		p_dialog.footer = pDialog.filterOptions(p_dialog.footer, p_dialog);
		
		//*** CREATE FOOTER
		var i_x = pElement.x('dialog-question-footer' + i_id_suffix);
		pElement.removeAllChildren(i_x);
		p_dialog.footer.forEach(function(op) {
			if (op.id == 'ok') {
				i_dialog.has_ok = true;
				op.text = op.text || pDocument.getStyleValue('dq-' + i_dialog.id + '-ok-title') || 'OK';
			}
			if (op.id == 'cancel') {
				i_dialog.has_cancel = true;
				op.text = op.text || pDocument.getStyleValue('dq-' + i_dialog.id + '-cancel-title') || 'Cancel';
			}
			
			var i_child = pDialog.genDialogOption(i_dialog, op);
			if (i_child) {
				if (op.id == 'ok' || op.id == 'cancel') {
					pElement.addClassName(i_child, 'dialog-footer-button');
					if (op.id == 'ok') i_child.style.display = 'none';
				}
				i_x.appendChild(i_child);
			}
		});

		p_dialog.options.forEach(function(op) {
			if (op.id == 'ok' || op.id == 'cancel') {
				if (op.id == 'ok') {
					i_dialog.has_ok = true;
					op.text = op.text || pDocument.getStyleValue('dq-' + i_dialog.id + '-ok-title') || 'OK';
				}
				if (op.id == 'cancel') {
					i_dialog.has_cancel = true;
					op.text = op.text || pDocument.getStyleValue('dq-' + i_dialog.id + '-cancel-title') || 'Cancel';
				}

				var i_child = pDialog.genDialogOption(i_dialog, op);
				if (i_child) {
					pElement.addClassName(i_child, 'dialog-footer-button');
					if (op.id == 'ok') i_child.style.display = 'none';
					i_x.appendChild(i_child);
				}
			}
		});
		
		i_x.appendChild(pElement.createClearDiv());

		if (i_dialog.has_ok===true || i_dialog.has_cancel===true) {
			i_dialog.onkeydown_old = document.onkeydown;
			document.onkeydown = i_dialog.onkeydown;
		}

		//*** CREATE CONTENT
		i_x = pElement.x('dialog-question-content'+i_id_suffix);
		var i_content = i_x;

		var i_titles = pElement.x('dialog-question-tab-titles'+i_id_suffix);
		pElement.removeAllChildren(i_titles);

		pElement.removeAllChildren(i_x);
		if (p_dialog.options) {
			
			//*** CREATE TAB DATA
			i_dialog.tabs = new pMap();
			p_dialog.options.forEach(function(op) {
				if (op.id != 'ok')
					if (op.id != 'cancel')
						if (op.tab) {
							if (op.selected === true) i_dialog.selectedTabID = op.id;
					
							var t = { id: op.id, text: op.text, did: i_dialog.request.id, description: op.description };
							t.f_select = function() { pDialog.selectTab(this.did, this.id); }.bind(t);
					
							i_dialog.tabs.put(op.id, t);
						}
			});

			if (i_dialog.tabs.length>0) {

				//*** SELECT DEFAULT TAB
				i_dialog.selectedTabID = i_dialog.selectedTabID || i_dialog.tabs.firstKey; 
				
				//*** TAB TITLES MORE BUTTON
				var m = pElement.create('div', 'dbtn-tab-title-more', 'dialog-tab-title', null, null, [ 'dialog_id', i_dialog.request.id ]);
				var a = pElement.create('a', null, 'link', null, null, [ 'href', 'javascript:void(pDialog.tabMenu(\''+i_dialog.request.id+'\'))', 'dialog_id', i_dialog.request.id]);
				pElement.decorate(a, 'dbtn-tab-title-more');
				/*m.onclick = function() {
					var did = pDialog.getDialog(i_dialog.id), l = did.tabs.values().map(function(t) {
						return { id: t.id, text: t.text, title: t.title.title, description: t.description, className: t.id == did.selectedTabID? 'tab-title-selected' : '', fcall: t.id == did.selectedTabID? null : t.f_select, selected: t.id == did.selectedTabID, disabled: t.id == did.selectedTabID };
					});
					
					pApplicationMenu.menu('dq-tab-titles'/*+i_id_suffix, l, true);
				};*/
				m.appendChild(a);
				i_titles.appendChild(m);
				
				/*i_titles.ondragenter = function() { 
					if (pApplicationUI.OPTION_DRAG_AND_DROP)
						pDialog.tabMenu(i_dialog.request.id);//pElement.getAttribute(this, 'dialog_id')) 
				};*/
			}
				
			var p_tabid = null;
			p_dialog.options.forEach(function(op) {
				if (op.id != 'ok')
					if (op.id != 'cancel') {
						if (op.tab) {

							var i_t = pElement.create(
								'div', 
								'dialog-tab-title-'+op.id, 
								"dialog-tab-title " + ((op.id == i_dialog.selectedTabID)? 'selected ':' ') + (op.className || ''),// + ' di-tab-title',
								null, //op.text
								null,
								[ 'title', op.title, 'dialog_id', i_dialog.request.id, 'opid', op.id ]
							);
							i_t.appendChild(pElement.create('span', 'dialog-tab-title-'+op.id+'-span', 'selected', op.text));
							i_t.appendChild(pElement.create('a', 'dialog-tab-title-'+op.id+'-a', 'link', op.text, null, [ 'href', 'javascript:void(pDialog.selectTab(\''+i_dialog.request.id+'\', \''+op.id+'\'))']));
							/*i_t.onclick = function(event) {
								//console.log(this.id);
								pDialog.selectTab(this.getAttribute('attr_dialog_id'), this.id);
							};*/
							i_t.setAttribute('attr_dialog_id', i_dialog.request.id);
							i_t.ondragenter = function() { 
								if (pApplicationUI.OPTION_DRAG_AND_DROP)
									pDialog.selectTab(pElement.getAttribute(this, 'dialog_id'), pElement.getAttribute(this, 'opid')) 
							};
		
							i_titles/*i_content*/.appendChild(i_t);
							
							i_x = pElement.create('div', op.id, "dialog-tab " + ((op.id == i_dialog.selectedTabID)? 'dialog-tab-selected':'') + ((op.content && op.content.className)? ' ' + op.content.className:''));
							i_x.setAttribute('attr_tab_title', op.text);
		
							//*** STORE TAB INFO
							i_dialog.tabs.getValue(op.id).element = i_x;
							i_dialog.tabs.getValue(op.id).title = i_t;
							
							p_tabid = op.id;
						}
						else {
							var c = pDialog.genDialogOption(i_dialog, op, p_tabid == i_dialog.selectedTabID, p_tabid);
							if (c)
								i_x.appendChild(c);
			
							if (op.vdefault === true)
								i_dialog.default_id = op.id;
						}
					}
			});
		}

		//*** FINISH TAB LIST
		var i_tabs = pElement.create('div', null, 'dialog-tabs');
		i_content.appendChild(i_tabs);
		
		i_dialog.tabs.values().forEach(function(t) {
			//*** APPEND CLEARER IN TAB CONTENT
			t.element.appendChild(pElement.createClearDiv(t.id + '-clear'));

			i_tabs/*i_content*/.appendChild(t.element);
		});
		
		i_x.appendChild(pElement.createClearDiv());

		//*** CREATE HEADER
		i_x = pElement.x('dialog-question-header'+i_id_suffix);
		pElement.removeAllChildren(i_x);
		p_dialog.header.forEach(function(op) {
			if (op.id != 'ok' && op.id != 'cancel') {
				var ch = pDialog.genDialogOption(i_dialog, op);
				if (ch)
					i_x.appendChild(ch);
			}
		});
		i_x.appendChild(pElement.createClearDiv());

		//*** PRE-SELECTION
		p_dialog.options.forEach(function(op) {
			if (!op.sep && !op.tab)
				if (op.selected === true)
					pDialog.dialogSelect(i_dialog, op.id);
		});
		
		//*** PRE-CHANGE
		p_dialog.options.forEach(function(o) {
			if (o.input && o.input.onchange)
				o.input.onchange.call(this);
		});

		//*** VALIDATE
		pDialog.validate(p_dialog.id);

		//*** RESIZE TABS
		//resizeTabs(i_dialog);

		//*** SHOW
		//pElement.removeClassName('dialog-question-frame' + i_id_suffix, 'dialog-show');

		//pElement.addClassName('dialog-question-frame', 'dialog-show-before');
		pElement.addClassName('dialog-question-frame' + i_id_suffix, p_dialog.className || '');
		pElement.addClassName('dialog-question-content'+i_id_suffix, ((p_dialog.className)? 'content-' + p_dialog.className : ''));

		pDocument.show(x.id+'-bg');
		pDocument.showComponent(x, null, 'dialog-hide');
		pElement.addClassName(document.body, 'noscroll-dialog');

		//*** ANIMATE
		//pElement.addClassName('dialog-question-frame' + i_id_suffix, 'dialog-show');
		setTimeout(function() { pElement.addClassName('dialog-question-frame' + i_id_suffix, 'dialog-show'); }, 100);

		pElement.focus((i_dialog.focus)? i_dialog.focus : 'dialog-question-frame' + i_id_suffix);

		//*** ENABLE BACKGROUND RESIZING
		pDocument.coverWholePage('dialog-question'+i_id_suffix);
		pDocument.coverWholePage('dialog-question'+i_id_suffix+'-bg');
		
		//*** RESIZE IMAGES
		i_dialog.fs_resize.f_resizeImages = function() {
			if (window.pPictures) {
				var r = null;
				i_dialog.tabs.values().forEach(function(t) {
					r = pPictures.resizeImages(t.element, t.element.getElementsByClassName('dialog-question-option-image'), 120, r);
				});
			}
		};
		pDocument.addOnResize(i_dialog.fs_resize.f_resizeImages);
		i_dialog.fs_resize.f_resizeImages();

		//*** HIDE MORE BUTTON if not required
		i_dialog.fs_resize.f_resizeTabMore = function() {
			if (i_dialog.tabs.length>1) {

				//*** UPDATE SELECTORS
				this.tabs.values().forEach(function(t, i) {
					t.title.style.display = 'inline-block';
					pElement.x(t.title.id+'-a').tabIndex = i+1;
				});
				
				if (!pElement.isOverflow('dialog-question-tab-titles'+i_id_suffix)) //pDocument.top(i_t) - pDocument.top('dialog-question-tab-titles'+i_id_suffix) <= 20)
					pDocument.hide('dbtn-tab-title-more'+i_id_suffix);
				else {
					//0.9.18
					var s = new pStyle('dialog-question-tab-titles'+i_id_suffix);
					var w = s.paddingWidth() + s.marginWidth();
					//console.log('w: ' + w);
					this.tabs.values().forEach(function(t) { w += pDocument.width(t.title); });//console.log(t + ' ' + pDocument.width(t.title)) });
					console.log('w: ' + w + ' window: ' + window.innerWidth)
					if (w < window.innerWidth) {
						pElement.x('dialog-question-frame'+i_id_suffix).style.width = w + 'px';
						pElement.x('dialog-question-frame'+i_id_suffix).style.maxWidth = w + 'px';
					}
					else {
						pDocument.show('dbtn-tab-title-more'+i_id_suffix);
					
						//*** UPDATE SELECTORS
						if (pDocument.top('dialog-tab-title-'+this.selectedTabID) - pDocument.top('dialog-question-tab-titles'+this.m_id_suffix) > 20) {
							var show = false, sid = this.selectedTabID;
							this.tabs.values().forEach(function(t) {
								if (show || t.id == sid) {
									t.title.style.display = 'inline-block';
									show = true;
								}
								else
									t.title.style.display = 'none';
							});
						}
						
						var suffix = this.m_id_suffix;
						this.tabs.values().forEach(function(t) {
							if (pDocument.top(t.title) - pDocument.top('dialog-question-tab-titles'+suffix) > 20)
								pElement.x(t.title.id+'-a').tabIndex = -1;
						});
					}
				}
			}
		}.bind(i_dialog);
		
		pDocument.addOnResize(i_dialog.fs_resize.f_resizeTabMore);
		pDocument.setTimeout(i_dialog.id, i_dialog.fs_resize.f_resizeTabMore, 200);

		//*** BEEP
		//pDocument.beep();

		p_dialog._runtime = { visible: true };

		// "visible" property
		Object.defineProperty(p_dialog, "visible", { get: function() { return this._runtime.visible; }});

		return i_dialog;
	};
	
	//*** SHOW A question + yes/no DIALOG
	//*** when the promise is executed, the dialog inputs can be retrieved from p_request.inputs
	this.question = function(req) {
		return new Promise(function(resolve, reject) {

			var q = req.question || pDocument.getStyleValue('dq-'+req.id+'-question') || pDocument.getStyleValue('dialog-'+req.id+'-question');
			if (q && req.replace)
				for(var i in req.replace)
					if (!i.startsWith('f_'))
						q = pDocument.replace(q, i, req.replace[i], req.replace['f_'+i]);
			
			var d = {
				id: req.id,
				title: req.title,
				icon: req.icon,
				options: req.options || [ q, '<hr>' ],
				footer: [/*
					{ id: 'ok', text: 'YES' },
					{ id: 'cancel', text: 'NO' },*/
				],
				fcall: function(dg) { 
					this.inputs = dg.inputs; 
					resolve(dg.inputs);
				}.bind(req)
			};
			if (!d.options.find(function(o) { return o && (o == 'ok' || o.id == 'ok') })) d.footer.push({ id: 'ok', text: 'YES' });
			if (!d.options.find(function(o) { return o && (o == 'cancel' || o.id == 'cancel') })) d.footer.push({ id: 'cancel', text: 'NO' });
			
			pDialog.dialogQuestion(d);
		});
	};
	
	this.newCheckbox = function(i, t, oc, v) {
		return { id: i, input: { type: 'checkbox', onchange: oc }, text_after: t, text_after_class: 'library-properties-checkbox', value: v };
	};
});

/******************************************************************************/
/******************************************************************************/
/******************************************************************************/

const pOpenFileDialog = new (function() {
	var that = this, icons = { folder: '/resources/html/images/16x16/folder.png' };
		
	function f_initRequest(p_request) {
		if (!p_request.getIconSrc)
			p_request.getIconSrc = function(p_dialog, p_file) {
				if (p_file.path == "::{20D04FE0-3AEA-1069-A2D8-08002B30309D}")
					return "/resources/html/images/16x16/computer.png";
				if (p_file.name == "Desktop")
					return "/resources/html/images/16x16/desktop.png";

				//console.log('here');
				if (p_file.files)
					for(var i=0 ; i<p_file.files.length ; i++) {
						//if (p_file.files[i].name == "music-medias.mlb")
						//	return "/resources/html/images/16x16/folder_blue.png";
						if (p_file.files[i].name == "4178918784091587936")
							return "/resources/html/images/16x16/folder_blue.png";
					}
				return null;
			};
	}
	
	function f_createFolder(p_path, p_name, p_callback, p_error) {
		// /^[^/\\<>:\"|?*]{1,100}$/
		var i_data = { path: p_path, name: p_name, callback: p_callback };
		pDialog.dialogQuestion({
			id: 'create-folder',
			title: "New Folder...",
			icon: { src: '/resources/html/images/32x32/folder_add.png' },
			options: [
				(p_error)? { id: 'error', text: p_error, disabled: true, className: 'dialog-error' } : null,
				{ id: 'name', input: pDialog.resources.input_foldername(), text: 'Folder name:', value: p_name || '' },
				'ok', 'cancel'
			],
			fcall: function(p_dialog, p_value) {
				var i_data = this;

				var i_url = pURL.addQueryParameter("/server", [ 'action', 'create-folder', 'path', i_data.path + '/' + p_dialog.inputs.getValue('name', ''), 'v', Math.random(), 'wait', 1 ]);
				var i_cdata = { path: i_data.path, name: p_dialog.inputs.getValue('name', ''), callback: i_data.callback };

				pTransaction.transaction({
					trace: that, url: i_url, method_name: "CreateFolder", responseType: 'text',
					msg_start: 'Creating '+i_cdata.name+' Folder...',
					msg_409: function(i_request) {
						var i_cdata = this;
						f_createFolder(i_cdata.path, i_cdata.name, i_cdata.callback, 'A folder already exists with this name on the server, please try another name...');
					}.bind(i_cdata),
					msg_500: function(i_request) {
						pApplicationUI.errorDialog({ text: 'Failed to create folder, the server returned an error:<br/>'+i_request.statusText, icon: { src: '/resources/html/images/32x32/folder_error.png' } });
						//var i_cdata = this;
						//f_createFolder(i_cdata.path, i_cdata.name, i_cdata.callback, 'Failure: ' + i_request.statusText);
					}.bind(i_cdata),
					msg_error: function(i_request) {
						var i_cdata = this;
						f_createFolder(i_cdata.path, i_cdata.name, i_cdata.callback, i_request.statusText);
					}.bind(i_cdata),
					msg_end: i_data.callback
				});
			}.bind(i_data)
		});
	}

	function f_createOption(p_dialog, i, p_text) {
		var ic = null;
		if (p_dialog.fileSelector && p_dialog.fileSelector.getIconSrc)
			ic = p_dialog.fileSelector.getIconSrc.call(p_dialog, p_dialog, i);
		if (!ic && i.drive)
			ic = '/resources/html/images/16x16/drive.png';

		if (i.type === "file") {
			if (!ic)
				ic = '/resources/html/images/16x16/file_extension_'+i.ext+'.png';
			return {
				id: i.path,
				value: i.path,
				accessKey: (p_text || i.name).substring(0, 1),
				text: '<img class="image" style="vertical-align: middle; padding-right: 10px;" src="'+ic+'" onError="pImage.changeSrc(this, \'/resources/html/images/16x16/file_extension_txt.png\');"  width="16" height="16">' +
					(p_text || i.name),
				fcall: function(p_dialog, p_value) {
					pConsole.info(that, 'Selected File: ' + p_value);
					if (p_dialog.callback)
						p_dialog.callback.call(this, p_value);
				}
			};
		}
		else {
			if (!ic)
				ic = icons.folder;
			return {
				id: i.path,
				value: i.path,
				accessKey: (p_text || i.name).substring(0, 1),
				text: '<img class="image" style="vertical-align: middle; padding-right: 10px;" src="'+ic+'">' + (p_text || i.name),
				scall: that.openFolder
			};
		}
	}
	
	function f_createLocationOption(p_dialog, i_obj) {
		var i_text = icons.folder+'<span class="selected">'+i_obj.name+'</span>';//((i_obj.path.indexOf('::{')==0)? i_obj.name : i_obj.path);

		var ic = null;
		if (p_dialog.fileSelector && p_dialog.fileSelector.getIconSrc)
			ic = p_dialog.fileSelector.getIconSrc.call(p_dialog, p_dialog, i_obj);
		if (!ic && i_obj.drive === true)
			ic = '/resources/html/images/16x16/drive.png';
		if (!ic)
			ic = icons.folder;

		i_text = '<img class="image"  style="vertical-align: middle; padding-right: 10px;" src="'+ic+'" width="16" height="16">'+'<span class="selected">'+i_obj.name+'</span>';//((i_obj.path.indexOf('::{')==0)? i_obj.name : i_obj.path);

		if (i_obj.parent) {
			var i_parent = i_obj.parent;
			while(i_parent) {
				ic = null;
				if (p_dialog.fileSelector && p_dialog.fileSelector.getIconSrc)
					ic = p_dialog.fileSelector.getIconSrc.call(p_dialog, p_dialog, i_parent);
				if (!ic && i_parent.drive === true)
					ic = '/resources/html/images/16x16/drive.png';
				if (!ic)
					ic = icons.folder;

				var i_ptext = '<img class="image" style="vertical-align: middle; padding-right: 10px;" src="'+ic+'" width="16" height="16">';

				i_ptext += '<a class="link" href="javascript:pOpenFileDialog.openFolder(\''+p_dialog.id+'\', \''+i_parent.path.replace(/\\/g, '/')+'\')">'+i_parent.name + '</a><span> &gt; </span>';
				i_text = i_ptext + i_text;
				i_parent = i_parent.parent;
			}
		}
		return { id: 'path', text: i_text, disabled: true };
	}
	
	function f_start(p_dialog) {

		var i_url = '/files/'+((p_dialog.current_path)? pURL.fixedEncodeURIComponent(p_dialog.current_path) : '.')+'?format=json&v='+Math.random();
		pConsole.info(that, 'Getting files (start): ' + i_url);

		pHTTPRequest.get(i_url, function(i_request, p_dialog) {

			if (i_request.status == 404 || i_request.responseText.indexOf('{')!=0) {
				pConsole.info(that, 'Getting files (start): Response: 404');

				if (p_dialog.retry === false) {
					pDocument.stopwait();
					pDialog.dialogQuestion({ id: 'open-file-not-found', title: 'File not found...', options: [ 'ok', 'Cannot find folder: ' + p_dialog.temp ] });
					return;
				}
				//console.log(i_request.responseText);
				//pConsole.info(that, 'Getting files (start): Response: 404');
				p_dialog.current_path = null;
				p_dialog.retry = false;
				f_start(p_dialog);
				return;
			}

			var i_obj = pJSON.parse(i_request.responseText);
			//pConsole.info(that, 'Getting files... Response: ' + pJSON.pretty(i_request.responseText));

			var i_dialog = p_dialog;//{ id: 'open-file', title: 'Open file...', options: [{ id: 'cancel' } ] }; // dialog request...

			i_dialog.current_path = i_obj.path;
			i_dialog.current_files = i_obj.files;

			i_dialog.header.push(f_createLocationOption(i_dialog, i_obj));
			i_dialog.header.push('<hr>');
			if (i_obj.parent)
				i_dialog.options.push(f_createOption(i_dialog, i_obj.parent, '..'));

			if (i_obj.files) {
				i_obj.files.forEach(function(f) {
					if (f.type != "file")
						i_dialog.options.push(f_createOption(p_dialog, f));
				});
				if (p_dialog.folder === false)
					i_obj.files.forEach(function(f) {
						if (f.type == "file")
							i_dialog.options.push(f_createOption(p_dialog, f));
					});
			}

			if (i_dialog.options.length>0 && i_dialog.options[0]!=null && i_dialog.options[0].id == 'ok') {
				i_dialog.options[0].text = i_dialog.getOkText? i_dialog.getOkText.call(i_dialog, i_dialog, i_obj) : i_dialog.vdefault.ok_title;
				if (!i_dialog.options[0].text)
					i_dialog.options[0].text = i_dialog.vdefault.ok_title;
			}

			pDocument.stopwait();
			pDialog.dialogQuestion(i_dialog);
		}, false, p_dialog);
	}

	this.openFolder = function(p_dialog, p_value) {

		pDocument.wait();

		p_dialog = pDialog.getDialog(p_dialog);
		p_dialog = p_dialog.request;
		p_dialog.temp = p_value;

		//pConsole.debug(that, 'value: '+p_value);
		var i_url = '/files/'+pURL.fixedEncodeURIComponent(p_value)+'?format=json&v='+Math.random();
		pConsole.info(that, 'Getting files: ' + i_url);

		pHTTPRequest.get(i_url, function(i_request, p_dialog) {

			if (i_request.status == 404 || i_request.responseText.indexOf('{')!=0) {
				pDocument.stopwait();
				pDialog.dialogQuestion({ id: 'open-file-not-found', title: 'File not found...', options: [ 'ok', 'Cannot find folder: ' + p_dialog.temp ] });
				return;
			}

			//p_dialog = this;

			var i_obj = pJSON.parse(i_request.responseText);
			//pConsole.info(that, 'Getting files... Response: ' + pJSON.pretty(i_request.responseText));

			pDialog.clearDialogOptions('open-file', 'content');
			pDialog.clearDialogOptions('open-file', 'header');

			p_dialog.current_path = i_obj.path;
			p_dialog.current_files = i_obj.files;

			pDialog.addDialogOption('open-file', 'header', f_createLocationOption(p_dialog, i_obj));
			pDialog.addDialogOption('open-file', 'header', { id: 'sep', sep: true, text: "<hr>"  });
			if (i_obj.parent)
				pDialog.addDialogOption('open-file', 'content', f_createOption(p_dialog, i_obj.parent, '..'));

			if (i_obj.files) {
				i_obj.files.forEach(function(f) {
					if (f.type != "file")
						pDialog.addDialogOption('open-file', 'content', f_createOption(p_dialog, f));
				});
				if (p_dialog.folder === false || (p_dialog.request && p_dialog.request.folder === false))
					i_obj.files.forEach(function(f) {
						if (f.type == "file")
							pDialog.addDialogOption('open-file', 'content', f_createOption(p_dialog, f));
					});
			}

			pCookieManager.set(p_dialog.cookie || 'open-file-folder', i_obj.path);

			//*** SET OK BUTTON TEXT
			if (p_dialog.options.length>0 && p_dialog.options[0]!=null && p_dialog.options[0].id == 'ok') {
				var t = p_dialog.getOkText? p_dialog.getOkText.call(p_dialog, p_dialog, i_obj) : p_dialog.vdefault.ok_title;
				pElement.setInnerHTML(pElement.x('open-file-ok'), t || p_dialog.vdefault.ok_title); //TODO: ...
			}

			pDocument.stopwait();

		}, false, p_dialog);
	};

	this.selectFile = function(p_request) {//p_callback, p_title, p_current_path) {
		pDocument.wait();

		var d = {
			id: 'open-file',
			className: 'dialog-open-file',
			title: p_request.title || (p_request.readonly? 'View File Location' : 'Open File...'),
			icon: p_request.icon,
			header: [],
			options: [ 'cancel' ],
			folder: false,
			current_path: p_request.current_path || pCookieManager.getCookie(p_request.cookie || 'open-file-folder'),
			fcall: (p_request.readonly)? null : function(p_dialog, p_value) {
				pConsole.debug(that, 'Selected File: ' + p_dialog.current_path);
				if (p_dialog.callback)
					p_dialog.callback.call(this, p_dialog.current_path);
			},
			callback: p_request.callback,
			fileSelector: p_request
		};

		f_initRequest(p_request);
		f_start(d);
	};

	this.selectFolder = function(p_request) {//p_callback, p_title, p_current_path, p_ok_title) {

		pDocument.wait();

		var i_ok_title = p_request.ok_title || 'Open this Folder';
		var d = {
			id: 'open-file',
			className: 'dialog-open-folder',
			title: (p_request.title)? p_request.title : (p_request.readonly)? 'View Folder Location' : 'Open Folder...',
			icon: p_request.icon,
			header: [],
			footer: [ { id: 'new', text: (pDevice.isSmallScreen())? '+':'<div class="dialog-button-create-folder">New Folder...</div>', className: 'dialog-footer-button-new dialog-footer-button noselect', scall: function(p_dialog) {

				/*var i_name = "New Folder", i = 2;
				if (p_dialog.current_files)
					while(p_dialog.current_files.some(function(i_file) { return i_file.name == i_name; })) {
						i_name = "New Folder ("+i+")";
						i++;
					}*/

				f_createFolder(p_dialog.current_path, null/*i_name*/, function() {
					that.openFolder(this, this.current_path);
				}.bind(p_dialog));
			} } ],
			options: [
				(p_request.readonly)? null : { id: 'ok', text: i_ok_title },
				'cancel'
				/*(p_request.recents)? { id: 'recent', tab: true, text: 'Recent(s)' } : null,
				(p_request.recents)? p_request.recents.map(function(i_recent) { return {
					id: i_recent.file, text: i_recent.file }
				};}) : null,
				{ id: 'browse', tab: true, text: 'Browse' }*/
			],
			folder: true,
			current_path: p_request.current_path || pCookieManager.getCookie(p_request.cookie || 'open-file-folder'),
			cookie: p_request.cookie,
			
			fcall: function(p_dialog, p_value) {
				pConsole.info(that, 'Selected Folder: ' + p_dialog.current_path);
				if (p_dialog.callback)
					p_dialog.callback.call(this, p_dialog.current_path);
			},
			callback: p_request.callback,

			fileSelector: p_request,
			getOkText: p_request.getOkText
		};
		d.vdefault = { ok_title: i_ok_title };

		f_initRequest(p_request);
		f_start(d);
	};
});

/******************************************************************************/
/******************************************************************************/
/******************************************************************************/

const pOpenImageDialog = new (function() {
	var that = this;
	
	this.tracePrefix = 'OpenImageDialog';

	this.opSelectImage = { id: 'select-image-drop', disabled: true, className: 'image-drop', text:
			'Drop some images here or '+
			'<label id="label-select-image-drop-browse" for="select-image-drop-browse">browse<input id="select-image-drop-browse" type="file"/></label> for an image file...' };

	function addFile(f) {
		if (f && pApplicationUI.acceptImageFile(f) && pApplicationUI.acceptImageFileSize(f)) {
			pFile.readAsDataURL(f, function(p_file, p_bin) {
				if (p_bin.startsWith)
				addImage(that, p_bin, { image: { name: p_file.name, lastModified: p_file.lastModified, size: p_file.size, type: p_file.type }});
			});
			return true;
		}
	}
		
	function addFileSystemEntry(f) {
		if (f && pApplicationUI.acceptImageFile(f)) {
			f.file(addFile);
			return true;
		}
	}
			
	function addSelectedImage(p_files, p_url, e) {
			//this is the callback data...
			//var i_data = this;
			var fc = 0, mfc = 128;
			
			if (e && e.dataTransfer && e.dataTransfer.items) {
				var done = 0;
				for(var i=0 ; i<e.dataTransfer.items.length && fc<mfc ; i++)
					if (e.dataTransfer.items[i].webkitGetAsEntry) {
						var d = e.dataTransfer.items[i].webkitGetAsEntry();
						if (d) {
							done++;
							pFiles.toFiles(d, function(files) {
								files.forEach(function(f) {
									if (fc<mfc)
										if (addFile(f))
											fc++;
								});
							});
						}
					}
				
				if (fc>=mfc || done == e.dataTransfer.items.length)
					return;
			}
			
			if (p_files) {
				for(var i=0 ; i<p_files.length && fc<mfc ; i++) 
					if (addFile(p_files[i]))
						fc++;
			}
			else if (p_url) {
				addImage(that, p_url);
			}
	}
		
	function removeImage(op) {
		var i = op.p_data.dialog.artworks.indexOf(op.image);
		if (i>=0)
			op.p_data.dialog.artworks = op.p_data.dialog.artworks.filter(function(x, ii){ return i!=ii });//splice(i, 1);
		pDialog.removeDialogOption(op.p_data.dialog.id, op.id);
		pDialog.validate(op.p_data.dialog.id);
	}
		
	function addImageImpl(p_data, op) {
		p_data.dialog.artworks.push(op.image);//0.9.16: .uri);

		if (p_data.dialog.visible === true) {
			pDialog.addDialogOption(p_data.dialog.id, 'tab-more', op, 'select-image-1');
			pDialog.validate(p_data.dialog.id);
		}
		else
			p_data.dialog.options.push(op);
	}
		
	function addImage(p_data, p_url, p_option) {

		if (!p_url)
			return;

		if (!p_data.dialog.artworks)
			p_data.dialog.artworks = [];
		
		if (p_url.image) {
			var op = {
				id: 'added-'+p_data.dialog.artworks.length,//p_url.image.uri,
				//value: p_url,
				image: p_url.image,
				fcall: p_data.fcall,
				disabled: p_data.dialog.i_data.multiples,
				p_data: p_data
			};
			if (op.disabled)
				op.dcall = function() { removeImage(this); }.bind(op);
			
			addImageImpl(p_data, op);
			return;
		}

		//TODO: check if mime type is image
		var i_op = {
			id: 'added-'+p_data.dialog.artworks.length,//p_url,
			value: p_url,
			image: pImages.createImage(p_url, p_option),
			//title: ''+((i_item.width)? i_item.width + ' x ' + i_item.height : '') + ((i_item.lang)? '&lt;br&gt;'+i_item.lang:''),
			fcall: p_data.fcall,
			disabled: p_data.dialog.i_data.multiples,
			p_data: p_data
		};
		if (i_op.disabled)
			i_op.dcall = function() { removeImage(this); }.bind(i_op);
		//if (p_option && p_option.image && p_option.image.thumbs)
		//	i_op.image.thumbs = p_option.image.thumbs;

		//test with http://www.imagebam.com/image/0e892a74410806/
		i_op.image.onerror = function(p_img) {
			pConsole.error(pDialog, 'Failed to load image: ' + p_img.src);

			if (p_img.src.startsWith('data:')) {
				p_img.onerror = null;
				pHTTPRequest.post({
					url: pURL.addQueryParameter(this.doc_url, [ 'action', 'download-url', 'transcode', 'jpg', 'v', ''+Math.random(), 'name', i_op.image.name ]),
					headers: pHTTPRequest.headers_post,
					body: pURL.addBodyParameter('', 'url', p_img.src),
					responseType: 'arraybuffer'
				}).then(function(req) {
					var blob = new Blob([req.response], {type: "image/jpeg"});
			        p_img.src = URL.createObjectURL(blob);
				});
				return;
			}
			
			var i = this.dialog.artworks.indexOf(p_img.src);
			if (i>=0)
				this.dialog.artworks.splice(i, 1);

			pImages.download(this.doc_url, p_img.src).then(function(p_new_url) {

				this.op.value = p_new_url;
				this.dialog.artworks.push(p_new_url);
				this.img.onerror = null;
				this.img.src = p_new_url;
			}.bind({ dialog: this.dialog, img: p_img, op: this.op }));

		}.bind({ doc_url: p_data.doc_url, dialog: p_data.dialog, op: i_op });

		addImageImpl(p_data, i_op);
	}

	/*enableImageDrop: function(p_dialog_id, fcall) {
		pElement.setOnDrop('select-image-drop', function() { addImage(); }.bind({ dialog_id: p_dialog_id, fcall: fcall }));
		pElement.setOnFileChange('select-image-drop-browse', function() { addImage(); }.bind({ dialog_id: p_dialog_id, fcall: fcall }));
	}*/
	function enableImageDrop(p_dialog, fcall) {
		pElement.setOnDrop('select-image-drop',function() { addSelectedImage(); }.bind({ dialog: p_dialog, fcall: fcall }));
		pElement.setOnFileChange('select-image-drop-browse', function() { addSelectedImage(); }.bind({ dialog: p_dialog, fcall: fcall }));
	}
	
	var r_ui_googleSearchValue = [ /(.*)[ ]*[-#_]+[ ]*Images.*/i, /(.*)[ ]*[-#_]*[ ]*Images.*/i ];
	function f_ui_googleSearchValue(s) {
		if (s) {
			s = s.trim();
			for(var i=0 ; i<r_ui_googleSearchValue.length ; i++) {
				var i_strs = r_ui_googleSearchValue[i].exec(s);
				if (i_strs && i_strs.length>1) return i_strs[1];
			}
		}
		return s;
	}

	this.selectImage = function(p_doc_url, i_url, p_title, fcall, i_more) {

		var i_data = {
			doc_url: p_doc_url,
			fcall: fcall,
			title: p_title,
			more: i_more,
			images: i_url
		};
		this.select(i_data);
	};

	/**
	 * Image selector dialog
	 */
	this.select = function(i_data) {

		pDocument.wait();

		i_data.doc_url = i_data.doc_url || window.location.pathname;
		i_data.scall = function(p_dialog, p_value, p_option) {
			var i_data = this;
			if (i_data.fcall)
				i_data.fcall.call(this, p_dialog, p_value, p_option);
		}.bind(i_data);

		if (typeof i_data.images == "string") {
			//var i_url = p_doc_url+'?action=posters&format=json&v=' + Math.random();
			pConsole.info(this, "GetImages: " + i_data.images);

			pHTTPRequest.get(i_data.images, function(i_request, i_data) {

				var i_url = pLocation.param(i_request.responseURL, 'url');
				if (i_url && i_url.indexOf('https://www.google.com/')==0 ) {

					//console.log(i_request.responseText);

					var x = document.createElement('div');
					x.innerHTML = i_request.responseText;

					var i_imgs = x.getElementsByClassName('rg_meta');
					i_data.images = {images:[]};
					for(var i=0 ; i<i_imgs.length ; i++) {
						var i_obj = pJSON.parse(i_imgs[i].innerHTML);
						var i_uri = i_obj.ou.replace(/\[/g, '%91').replace(/\]/g, '%93');
						if (i_data.exclude_urls && i_data.exclude_urls.indexOf(i_uri)>-1) continue;

						i_data.images.images.push({ uri: i_uri, owidth: i_obj.ow, oheight: i_obj.oh, site: i_obj.ru, domain: i_obj.isu, thumbs:[ { uri: i_obj.tu }] });
					}

					x.innerHTML = '';

					pOpenImageDialog.dialogImage(i_data);
					return;
				}

				//handle errors
				if (pROSE.handleHTTPResponse(i_request) === false)
					return false;

				var i_obj = pJSON.parse(i_request.responseText);
				if (!i_obj)
					return;
				
				//TODO: SORT BY DATE TAKEN...
				if (pApplicationUI.OPTION_PICTURES_SORT_DATETAKEN)
				for(var i=0 ; i<i_obj.images.length ; i++)
					if (i_obj.images[i].date!=null && i_obj.images[i].date!='') {
						pConsole.info(this, "Sort pictures by date taken...");
						i_obj.images.sort(function(a, b) {
							if (a.date == b.date)
								return 0;
							if (a.date < b.date)
								return -1;
							return 1;
						});
						break;
					}
				
				//0.9.13
				i_obj.images.forEach(function(i) {
					if (i.orientation == "08" || i.orientation == "06")
					{ var w = i.width; i.width = i.height; i.height = w; } 
				});

				i_data.images = i_obj;
				pOpenImageDialog.dialogImage(i_data);
			}, false, i_data);
		}
		else {
			pOpenImageDialog.dialogImage(i_data);
		}
	};

	//TODO: multiples...
	this.dialogImage = function(i_data) {

		var i_obj = i_data.images;
		if (i_obj && i_obj.images) 
			i_obj.images = i_obj.images.filter(function(img) { return (img.uri.startsWith("file:"))? false: true; });
		var p_more = i_data.more;

		const m_max = pApplicationUI.OPTION_PAGE_MAXSIZE;
		var id = 'select-image-'+Math.random(), i_dialog = {
			id: id,
			title: i_data.title || "Select Image...",
			className: 'dialog-images',
			options: [ 
				i_data.multiples? { id: 'sep', hidden: true, did: id, validators: function(op){
					var did = pDialog.getValue(op.did);
					if (did)
						return (did.request.artworks || []).length>0;
				}} : null,
				i_data.multiples? { id: 'ok', text: i_data.ok_text } : null,
				{ id: 'cancel' }
			],
			i_data: i_data,

			addURL: function(p_url) {
				addImage({ dialog: this, fcall: this.i_data.fcall }, p_url);
				//p{ dialog: p_dialog, fcall: fcall };
			},
			
			fcall: i_data.fcall
		};
		i_dialog.addImageURL = function(p_dialog, p_url, p_option) {
			if (!p_url)
				return;

			var i_dialog = pDialog.getValue(this.id);
			if (i_dialog && i_dialog.request)
				i_dialog = i_dialog.request;

			addImage({ dialog: i_dialog, fcall: i_dialog.i_data.fcall }, p_url, p_option);
		}.bind(i_dialog);

		var i_more = false;
		if (i_obj && i_obj.images && i_obj.images.length>0) {
			i_more = true;
			if (i_obj.images.length<=m_max) {
				var i_last = i_obj.images.length;
				i_dialog.options.push({ id: 'tab-'+(i_last==0)? 0:1+'-'+i_last, tab: true, text: ''+((i_last==0)? 0:1)+'-'+i_last });
			}

			i_obj.images.forEach(function(i_item, i) {
				if (i_item) {
					if (i_obj.images.length>m_max)
						if ((i % m_max)==0) {
							var i_last = Math.min(i_obj.images.length, i+m_max);
							i_dialog.options.push({ id: 'tab-'+(i+1) + '-'+i_last, tab: true, text: ''+(i+1) + '-'+i_last });
						}

					i_dialog.options.push({
						id: 'select-image-'+i,
						value: i_item.uri || i_item.name,
						image: i_item,
						fcall: i_data.scall
					});
				}
			});
		}
		
		if (i_data.tab_more != false) {
			i_dialog.options.push({ id: 'tab-more', tab: true, text: (i_more===true)? 'More...':'Choose...' });
	
			//*** TYPE AN URL
			i_dialog.options.push({ id: 'img-url', input: { icons: [ /*pDialog.resources.icon_copy, pDialog.resources.icon_paste,*/ pDialog.resources.icon_delete,
				{
					className: 'dq-bt-download',
					title: 'Download image from this URL...',
					onclick: function(op_id){
						var i_input = pElement.x('dialog-input-'+op_id);
						var i_url = pElement.x('dialog-input-'+op_id).value;
						if (i_url!='') {
							var i_dialog = pDialog.getValue(i_input.getAttribute('attr_dialog_id'));
							i_dialog.request.addURL(i_url);
						}
					},
					ondisable: true
				}]
			}, text: 'Type an URL:' });
	
			//*** GOOGLE IMAGE SEARCH
			if (pApplicationUI.OPTION_GOOGLE_IMAGE_SEARCH)
				i_dialog.options.push({ id: 'img-google', input: { icons: [ /*pDialog.resources.icon_copy, pDialog.resources.icon_paste,*/ pDialog.resources.icon_delete,
					{
						className: 'dq-bt-download',
						title: 'Google Search...',
						onclick: function(op_id){
							var i_input = pElement.x('dialog-input-'+op_id);
							var i_q = pElement.x('dialog-input-'+op_id).value;
							i_q = (i_q)? i_q.trim() : '';
							if (i_q!='') {
								var i_url = pURL.addQueryParameter(i_data.p_doc_url, [ 'action', 'download-url', 'url', 'https://www.google.com/search?q='+pURL.fixedEncodeURIComponent(i_q)+'&client=firefox-b-ab&tbm=isch', 'v', Math.random() ]);
								var p_dialog = f_ui_getDialogFromInputElement(i_input);
								pOpenImageDialog.select({ images: i_url, title: 'Select Image from Google...', fcall: i_dialog.addImageURL, exclude_urls: p_dialog.request.artworks, selectall: true });
							}
						},
						ondisable: true
					}]
				}, text: 'Google Search:', value: (pPage.title)? f_ui_googleSearchValue(pPage.title) : '' });
	
			i_dialog.options.push(that.opSelectImage);
	
			if (i_data.doc_url && (i_data.doc_url.indexOf('/tvshows.medias/')>0 || i_data.doc_url.indexOf('/movies.medias/')>0))
				i_dialog.options.push({ 
					id: 'select-poster',
					scall: function() {
						var i_data = this;
						pMediaLibrary.selectPosterImage(i_data.doc_url, null, i_dialog.addImageURL, null, false);
					  }.bind(i_data), 
					text: 'Select image from posters...'
				});
			if (i_data.doc_url && (i_data.doc_url.indexOf('/pictures.')>0 || i_data.doc_url.indexOf('/books.')>0))
				i_dialog.options.push(
					{ id: 'select-image-folder', text: 'Select an image from folder content...',
					  scall: function() {
						var i_data = this;
		
						var i_url = pURL.addQueryParameter(i_data.p_doc_url, [ 'action', 'contents', 'v', Math.random() ]);
						pOpenImageDialog.select({
							images: i_url, 
							title: 'Select Image from Folder...', 
							fcall: i_dialog.addImageURL,
							tab_more: false
						});
					  }.bind(i_data)
					});
	
			if (p_more && p_more.images)
				p_more.images.forEach(function(img) {
					if (img)
						addImage({ dialog: i_dialog, fcall: i_dialog.i_data.fcall }, img.uri || img.name, { image: img });
				});
		}
		
		if (i_data.selectall === true)
			i_dialog.footer = [
				{ id: 'dialog-addall', text: 'Select All', className: 'dialog-footer-button', scall: function(p_dialog, value) {
					var i_data = this;
					p_dialog.options.forEach(function(op) {
						if (op.image) i_data.scall.call(this, p_dialog, op.value, op);
					});
					pDialog.dialogQuestionClose(p_dialog.id, 'cancel');
				}.bind(i_data)}
			];//footer: [		
		
		pNoteUI.createNoteDialogOption('help-select-image').then(function(op) {
			var i_dialog = this.dialog;
			if (op != 'success')
				i_dialog.header = [ op ];

			pDocument.stopwait();
			pDialog.dialogQuestion(i_dialog);

			//TODO
			enableImageDrop(i_dialog, this.data.scall);
		}.bind({ dialog: i_dialog, data: i_data }));
	};
});

//console.log("TEST: pOpenImageDialog.f_ui_googleSearchValue(\"XXX AAA - Images-2\"): " + pOpenImageDialog.f_ui_googleSearchValue("XXX AAA - Images-2"));
//console.log("TEST: pOpenImageDialog.f_ui_googleSearchValue(\"XXX AAA # Images-2\"): " + pOpenImageDialog.f_ui_googleSearchValue("XXX AAA # Images-2"));
//console.log("TEST: pOpenImageDialog.f_ui_googleSearchValue(\"XXX AAA Images-2\"): " + pOpenImageDialog.f_ui_googleSearchValue("XXX AAA Images-2"));

/******************************************************************************/
/***  END OF FILE  ************************************************************/
/******************************************************************************/