/******************************************************************************
@owner: SVSi
@author: Arthur Johnson
@functions: PanelBuilder Program Initialization and Utilities
@pb class object
*******************************************************************************/

var PanelBuilder = {};
var pb = PanelBuilder;

pb.mouse = false; pb.updating = false; pb.view = 'single';

pb.menustate = {fileopen: false, editopen: false, addopen: false, viewopen: false, hovertimer: false};

pb.project = {};
pb.currentpanel = false;

pb.recyclebin = []; pb.undoactions = []; pb.redoactions = [];

pb.default = {};
pb.default.buttons = []; pb.default.widgets = [];
pb.default.widgetparts = []; pb.default.assets = [];
pb.default.panels = []; pb.default.templates = [];
pb.default.subpanels = []

pb.user = {};
pb.user.buttons = []; pb.user.widgets = [];
pb.user.widgetparts = []; pb.user.assets = {scripts: [], modules: [], images: []};
pb.user.panels = []; pb.user.templates = [];
pb.user.subpanels = [];

pb.buttonindex = 1; pb.userbuttonindex = 1;
pb.widgetindex = 1; pb.widgetpartindex = 1;
pb.panelindex = 1; pb.templateindex = 1;
pb.scriptindex = 1; pb.imageindex = 1;
pb.subpanelindex = 1;

pb.keys = {};

pb.dialogs = {
	save: function(){
		
	},
	saveas: function(){
		
	},
	delete: function(){
		pb.openDialog({
			content: '<div style="margin: 15px;"><span style="font-size: 19px;">Are you sure you want to delete this panel?</span></div>',
			style: {height: '120px', width: '430px', 'border-radius': '15px'},
			confirm: 'yes', cancel: 'no',
			onConfirm: function(){
				//if (pb.currentpanel.core.id === 'Master_Template') pb.project.core.hasMaster = false;
				$(pb.currentpanel.element).remove();
				$('#'+pb.currentpanel.core.id+'_label').remove();
				removeFromArray(pb.user.panels, pb.currentpanel);
				if (pb.user.panels.length > 0) pb.switchToPanel(pb.user.panels[0]);
				if (!pb.user.panels.length) $('#labels').html('<div id="_no_panels_added"\
					style="width: 100%; height: 100%; text-align: center; color: red; line-height: 28px; font-size: 13px;">No Panels Added!</div>');
				pb.closeDialog();
			},
			onCancel: function(){pb.closeDialog();}
		});
	},
	module: function(){
		pb.openDialog({
			content: '<div style="margin: 15px;">Manufacturer:<br>'+
				'<input id="manufacturer_name" size="3" style="width: 145px;" value="Generic" type="text"/><br><br>'+
				'Module File:<br><input id="module_file" size="3" style="width: 245px;" value="" type="file" accept=".js"/></div>',
			style: {height: '170px', 'border-radius': '15px'},
			onConfirm: function(){
				var fileInput = document.getElementById('module_file'); var file = fileInput.files[0];
				sendFile(file, {command: 'module', manufacturer: $('#manufacturer_name').val()}, 
					function(opts){
						pb.updateModules(function(){$('#assets-props-modules').click();});
					});
				pb.closeDialog();
			}
		});
	}
};

pb.uniqueId = function(id){
	if (get(id)){
		var idnum = parseInt(id.substring(id.indexOf('-') + 1));
		var newid = id.substring(0, id.indexOf('-')+1) + (idnum + 1);
		return pb.uniqueId(newid);
	}
	else return id;
}

pb.unselectAll = function(){$('.outlined').removeClass('outlined first');}

pb.searchArrayById = function(array, id){
	for (var i=0; i<array.length; i++) 
		if (array[i].core.id == id) return i;
	return -1;
}

pb.saveaction = function(action){
	pb.undoactions.push(action); pb.redoactions = [];
}

pb.undo = function(){
	if (pb.undoactions.length > 0){
		var action = pb.undoactions.pop(); action.reverse();
		pb.redoactions.push(action);
	}
}

pb.redo = function(){
	if (pb.redoactions.length > 0){
		var action = pb.redoactions.pop(); action.commit();
		pb.undoactions.push(action);
	}
}

pb.openMenu = function(name){
	$("#"+name+"menu-menu").css({display:'block', height:'auto', padding:'5px 0px 0px 0px', margin:'0 auto', border:'0'});
}

pb.closeMenu = function(name){
	$("#"+name+"menu-menu").css({display:'none', height:'auto', padding:'5px 0px 0px 0px', margin:'0 auto', border:'0'});
}

pb.openToolsPane = function(){
	var tp = document.getElementById('tools-panel');
	if (tp.style.opacity < 1.0 || tp.style.display != 'block'){
		tp.style.display = 'block'; tp.style.opacity = 0;
		tweencss({
			object: tp, time: 0.8, ease: TWEEN.Easing.Sine.Out,
			props: {left: parseInt(tp.style.left), opacity: parseInt(tp.style.opacity)}, to: {left: 0, opacity: 1}
		});	
	}
}

pb.openResourcesPane = function(){
	var rp = document.getElementById('resources-panel');
	if (rp.style.opacity < 1.0 || rp.style.display != 'block'){
		rp.style.display = 'block'; rp.style.opacity = 0;
		tweencss({
			object: rp, time: 0.8, ease: TWEEN.Easing.Sine.Out,
			props: {right: parseInt(rp.style.right), opacity: parseInt(rp.style.opacity)}, to: {right: 0, opacity: 1}
		});
	}
}

pb.openFileBrowser = function(command){
	$("#file-open")[0].value = null;
	$("#file-open").click();
	document.getElementById('file-open').onchange = function(){
		command($("#file-open")[0].files);
	};
}

pb.getItem = function(identifier){
	var result = pb.getItemById(identifier);
	if (!result) result = pb.getItemByName(identifier);
	return result;
}

pb.getItemByName = function(name){
	for (var key in pb.user){
		if (pb.user.hasOwnProperty(key) && Array.isArray(pb.user[key])){
			for (var i=0; i<pb.user[key].length; i++){
				if (pb.user[key][i].core && pb.user[key][i].core.name === name)
					return pb.user[key][i];
			}
		}
	}
	for (var key in pb.default){
		if (pb.default.hasOwnProperty(key) && Array.isArray(pb.default[key])){
			for (var i=0; i<pb.default[key].length; i++){
				if (pb.default[key][i].core && pb.default[key][i].core.name === name)
					return pb.default[key][i];
			}
		}
	}
	return false;
}

pb.getItemById = function(id){
	for (var key in pb.user){
		if (pb.user.hasOwnProperty(key) && Array.isArray(pb.user[key])){
			for (var i=0; i<pb.user[key].length; i++){
				if (pb.user[key][i].core && pb.user[key][i].core.id === id)
					return pb.user[key][i];
			}
		}
	}
	for (var i=0; i<pb.user.assets.images.length; i++){
		if (pb.user.assets.images[i].core && pb.user.assets.images[i].core.id === id)
			return pb.user.assets.images[i];
	}
	for (var key in pb.default){
		if (pb.default.hasOwnProperty(key) && Array.isArray(pb.default[key])){
			for (var i=0; i<pb.default[key].length; i++){
				if (pb.default[key][i].core && pb.default[key][i].core.id === id)
					return pb.default[key][i];
			}
		}
	}
	return false;
}

pb.updateFromMasterTemplate = function(){
	var mt = false;
	for (var i=0; i<pb.user.panels.length; i++){
		if (pb.user.panels[i].core.id === 'Master_Template') mt = pb.user.panels[i];
	}
	if (!mt) return;
	for (var i=0; i<mt.buttons.length; i++){
		var button = mt.buttons[i];
		
	}
};

pb.updateTree = function(project){
	var str = '';
	for (var i=0; i<pb.user.panels.length; i++){
		str += '<div style="background: none; width: 100%; height: 30px;\
			font-size: 22px; text-align: center; line-height: 30px;\
			cursor: pointer;" id="'+pb.user.panels[i].core.id+'"\
			onmouseover="$(this).css({background: \'white\', color: \'black\'});"\
			onmouseout="$(this).css({background: \'none\', color: \'white\'});"\
			onclick="pb.switchToPanel(pb.getItemById(this.id));">' +
			pb.user.panels[i].core.name +
		'</div>';
		for (var j=0; j<pb.user.panels[i].buttons.length; j++){
			str += '<div style="background: none; width: 100%; height: 20px;\
				font-size: 15px; text-align: center; line-height: 20px;\
				cursor: pointer;"\
				onmouseover="$(this).css({background: \'white\', color: \'black\'});"\
				onmouseout="$(this).css({background: \'none\', color: \'white\'});"\
				>' + 
					(pb.user.panels[i].buttons[j].core.__hidden ? '<img src="icons/hidden.png" style="width: 15px; height: 15px;" \
					onclick="\
						if (/visible/.test(this.src)){this.src = \'icons/hidden.png\'; get(\''+pb.user.panels[i].buttons[j].core.id+'\')._hide();}\
						else {this.src = \'icons/visible.png\'; get(\''+pb.user.panels[i].buttons[j].core.id+'\')._show();}\
					" />' :
					'<img src="icons/visible.png" style="width: 15px; height: 15px;"\
					onclick="\
						if (/visible/.test(this.src)){this.src = \'icons/hidden.png\'; get(\''+pb.user.panels[i].buttons[j].core.id+'\')._hide();}\
						else {this.src = \'icons/visible.png\'; get(\''+pb.user.panels[i].buttons[j].core.id+'\')._show();}\
					" />') + ' <span onclick="pb.switchToPanel(pb.getItemById(\'' + pb.user.panels[i].buttons[j].core.id + '\').panel);\
					pb.getItemById(\'' + pb.user.panels[i].buttons[j].core.id + '\').click();"\
				ondblclick="pb.switchToPanel(pb.getItemById(\'' + pb.user.panels[i].buttons[j].core.id + '\').panel);\
					pb.getItemById(\'' + pb.user.panels[i].buttons[j].core.id + '\').doubleclick();">' +
				pb.user.panels[i].buttons[j].core.id + '</span></div>';
		}
		for (var j=0; j<pb.user.panels[i].widgets.length; j++){
			str += '<div style="background: none; width: 100%; height: 20px;\
				font-size: 15px; text-align: center; line-height: 20px;\
				cursor: pointer;"\
				onmouseover="$(this).css({background: \'white\', color: \'black\'});"\
				onmouseout="$(this).css({background: \'none\', color: \'white\'});"\
				>' + 
					(pb.user.panels[i].widgets[j].core.__hidden ? '<img src="icons/hidden.png" style="width: 15px; height: 15px;" \
					onclick="\
						if (/visible/.test(this.src)){this.src = \'icons/hidden.png\'; get(\''+pb.user.panels[i].widgets[j].core.id+'\')._hide();}\
						else {this.src = \'icons/visible.png\'; get(\''+pb.user.panels[i].widgets[j].core.id+'\')._show();}\
					" />' :
					'<img src="icons/visible.png" style="width: 15px; height: 15px;"\
					onclick="\
						if (/visible/.test(this.src)){this.src = \'icons/hidden.png\'; get(\''+pb.user.panels[i].widgets[j].core.id+'\')._hide();}\
						else {this.src = \'icons/visible.png\'; get(\''+pb.user.panels[i].widgets[j].core.id+'\')._show();}\
					" />') + ' <span onclick="pb.switchToPanel(pb.getItemById(\'' + pb.user.panels[i].widgets[j].core.id + '\').panel);\
					pb.getItemById(\'' + pb.user.panels[i].widgets[j].core.id + '\').click();"\
				ondblclick="pb.switchToPanel(pb.getItemById(\'' + pb.user.panels[i].widgets[j].core.id + '\').panel);\
					pb.getItemById(\'' + pb.user.panels[i].widgets[j].core.id + '\').doubleclick();">' +
				pb.user.panels[i].widgets[j].core.id + '</span></div>';
		}
		for (var j=0; j<pb.user.panels[i].subpanels.length; j++){
			str += '<div style="background: none; width: 100%; height: 20px;\
				font-size: 15px; text-align: center; line-height: 20px;\
				cursor: pointer;"\
				onmouseover="$(this).css({background: \'white\', color: \'black\'});"\
				onmouseout="$(this).css({background: \'none\', color: \'white\'});"\
				>' + 
					(pb.user.panels[i].subpanels[j].core.__hidden ? '<img src="icons/hidden.png" style="width: 15px; height: 15px;" \
					onclick="\
						if (/visible/.test(this.src)){this.src = \'icons/hidden.png\'; get(\''+pb.user.panels[i].subpanels[j].core.id+'\')._hide();}\
						else {this.src = \'icons/visible.png\'; get(\''+pb.user.panels[i].subpanels[j].core.id+'\')._show();}\
					" />' :
					'<img src="icons/visible.png" style="width: 15px; height: 15px;"\
					onclick="\
						if (/visible/.test(this.src)){this.src = \'icons/hidden.png\'; get(\''+pb.user.panels[i].subpanels[j].core.id+'\')._hide();}\
						else {this.src = \'icons/visible.png\'; get(\''+pb.user.panels[i].subpanels[j].core.id+'\')._show();}\
					" />') + ' ' +
				pb.user.panels[i].subpanels[j].core.id + '</div>';
		}
	}
	$('#project-props-tree').html(str);
}

pb.toJSON = function(obj){
	if (obj instanceof Panel) return pb.panelToJSON(obj);
	if (obj instanceof Button) return pb.buttonToJSON(obj);
	if (obj instanceof Widget) return pb.widgetToJSON(obj);
	if (obj instanceof WidgetPart) return pb.widgetPartToJSON(obj);
	if (obj.core) return pb.projectToJSON(obj);
	return false;
}

pb.buttonToJSON = function(button){	
	var thisobj = {};
	thisobj.core = button.core;	
	thisobj.core.style = button.element.style.cssText;
	thisobj.core.textstyle = button.textnode.style.cssText;
	thisobj.core.textnodeHTML = button.textnode.innerHTML;
	return thisobj;
}

pb.widgetToJSON = function(widget){
	var thisobj = {};
	thisobj.core = widget.core;
	thisobj.core.style = widget.element.style.cssText;
	var blacklist = ['panel','core','element','parts','container','library','action'];
	for (var property in widget)
		if (widget.hasOwnProperty(property) && !arrayContains(blacklist, property)) 
			thisobj[property] = widget[property];
	thisobj.parts = [];
	for (var i=0; i<widget.parts.length; i++) 
		thisobj.parts.push(pb.widgetPartToJSON(widget.parts[i]));	
	return thisobj;
}

pb.widgetPartToJSON = function(widgetpart){
	var thisobj = {};
	thisobj.core = widgetpart.core;
	thisobj.core.elementHTML = widgetpart.element.innerHTML;
	thisobj.core.style = widgetpart.element.style.cssText;
	var blacklist = ['panel','core','element','parts','container','library','action','widget'];
	for (var property in widgetpart){
		if (widgetpart.hasOwnProperty(property) && !arrayContains(blacklist, property)){
			thisobj[property] = widgetpart[property];
		}
	}
	
	return thisobj;
}

pb.subPanelToJSON = function(subpanel){
	var thisobj = {};
	thisobj.core = subpanel.core;
	thisobj.core.style = subpanel.element.style.cssText;
	thisobj.children = [];
	for (var i=0; i<subpanel.children.length; i++) thisobj.children.push(subpanel.children[i]);
	return thisobj;
}

pb.panelToJSON = function(panel){
	var thisobj = {};
	thisobj.core = panel.core;	
	thisobj.core.style = panel.element.style.cssText;
	thisobj.buttons = []; thisobj.widgets = []; thisobj.subpanels = [];
	for (var i=0; i<panel.buttons.length; i++)
		thisobj.buttons.push(pb.buttonToJSON(panel.buttons[i]));
	for (var i=0; i<panel.widgets.length; i++)
		thisobj.widgets.push(pb.widgetToJSON(panel.widgets[i]));
	for (var i=0; i<panel.subpanels.length; i++)
		thisobj.subpanels.push(pb.subPanelToJSON(panel.subpanels[i]));
	return thisobj;
}

pb.projectToJSON = function(project){
	var thisobj = {};
	if (!pb.project.core) pb.project.core = {};
	thisobj.core = clone(pb.project.core);
	thisobj.core.buttonindex = pb.buttonindex;
	thisobj.core.widgetindex = pb.widgetindex;
	thisobj.core.widgetpartindex = pb.widgetpartindex;
	thisobj.core.panelindex = pb.panelindex;
	thisobj.core.templateindex = pb.templateindex;
	thisobj.core.subpanelindex = pb.subpanelindex;
	thisobj.core.modulelist = pb.user.modulelist;
	thisobj.core.scriptlist = pb.user.scriptlist;
	thisobj.panels = [];
	for (var i=0; i<pb.user.panels.length; i++)
		thisobj.panels.push(pb.panelToJSON(pb.user.panels[i]));
	return thisobj;
}

pb.getDefaultButton = function(name){
	var tempstates = [
		{name: 'state1', style: '', bgimage: 'images/buttons/'+name+'.png', images: []},
		{name: 'state2', style: '', bgimage: 'images/buttons/Inactive-Button.png', images: []}
	];		
	var button = new Button({
		id: 'Default-'+name, type: 'default',
		actualwidth: 80, actualheight: 80,
		style: 'position: relative; border: none; background-color: transparent; float: left; margin: 4px; padding: 0px;',
		states: tempstates
	});
	switch (name){
		case 'Buttons-1': case 'Buttons-5': case 'Buttons-9': case 'Buttons-13': case 'Buttons-17':
		case 'Buttons-21':case 'Buttons-25': case 'Buttons-29': case 'Buttons-33': case 'Buttons-37':
			button.core.states[1].bgimage = 'url(\'images/buttons/Inactive-Button-2.png\')';
		default:
	}
	switch (name){
		case 'Buttons-3': case 'Buttons-7': case 'Buttons-11': case 'Buttons-15': case 'Buttons-19':
		case 'Buttons-23':case 'Buttons-27': case 'Buttons-31': case 'Buttons-35': case 'Buttons-39':
			button.core.states[1].bgimage = 'url(\'images/buttons/Inactive-Button-3.png\')';
		default:
	}	
	switch (name){
		case 'Buttons-4': case 'Buttons-8': case 'Buttons-12': case 'Buttons-16': case 'Buttons-20':
		case 'Buttons-24':case 'Buttons-28': case 'Buttons-32': case 'Buttons-36': case 'Buttons-40':
			button.core.states[1].bgimage = 'url(\'images/buttons/Inactive-Button-4.png\')';
		default:
	}
	switch (name){
		case 'Buttons-1': case 'Buttons-4': case 'Buttons-5': case 'Buttons-8': case 'Buttons-9': 
		case 'Buttons-12': case 'Buttons-13': case 'Buttons-16': case 'Buttons-17': case 'Buttons-20': 
		case 'Buttons-21': case 'Buttons-24': case 'Buttons-25': case 'Buttons-28': case 'Buttons-29': 
		case 'Buttons-32': case 'Buttons-33': case 'Buttons-36': case 'Buttons-37': case 'Buttons-40':
		case 'Buttons-41': case 'Buttons-42': case 'Buttons-43': case 'Buttons-44':
		case 'Buttons-49': case 'Buttons-50': case 'Buttons-51': case 'Buttons-52':
		case 'Buttons-61': case 'Buttons-62': case 'Buttons-63': case 'Buttons-64':
		case 'Buttons-65': case 'Buttons-66': case 'Buttons-67': case 'Buttons-68': case 'Buttons-69': case 'Buttons-70':
			button.element.style.height = '26px';
			button.core.actualheight = 26;
			button.element.style.marginTop = '32px';
			button.element.style.marginBottom = '30px';
			break;
		default:
	}
	switch (name){
		case 'Buttons-13': case 'Buttons-14': case 'Buttons-15': case 'Buttons-16': case 'Buttons-17': 
		case 'Buttons-18': case 'Buttons-19': case 'Buttons-20': case 'Buttons-21': case 'Buttons-22': 
		case 'Buttons-23': case 'Buttons-24': case 'Buttons-25': case 'Buttons-26': case 'Buttons-27': 
		case 'Buttons-28': case 'Buttons-29': case 'Buttons-30': case 'Buttons-31': case 'Buttons-32': 
		case 'Buttons-44': case 'Buttons-46': case 'Buttons-53': case 'Buttons-54': case 'Buttons-77': 
		case 'Buttons-78': case 'Buttons-79': case 'Buttons-80': case 'Buttons-81': case 'Buttons-82': 
		case 'Buttons-86': 
			button.textnode.style.color = 'white';
			break;
		default:
	}
	button.element.className = "draggable cloneable";
	return button;
}

pb.loadButtonLibrary = function(library){
	$(library).addClass('button_library');
	$('#button-library-pane').append(library);	
	$('#button-library-select').append('<option value="'+library.id+'">'+library.id+'</option>');	
	library.style.height = 'calc(100% - 71px)';	
	$(library).click(function(){
		for (var i=0; i<$(library)[0].children.length; i++) 
			$($(library)[0].children[i]).removeClass('libraryselected');
	});	
	pb.setButtonLibrary();
}

pb.setButtonLibrary = function(){
	$('.button_library').css({display: 'none'});
	$(document.getElementById($('#button-library-select option:selected').text())).css({display: 'block'});
}

pb.setWidgetLibrary = function(){
	if ($('#widget-library-select option:selected').text() == 'User Library'){
		$('#widget_library_user_widgets').css({display: 'block'});
		$('#widget_library_default_widgets').css({display: 'none'});
		$('.widgets-button').css({opacity: 1.0}).attr('disabled', false);	
	}
	else {
		$('#widget_library_user_widgets').css({display: 'none'});
		$('#widget_library_default_widgets').css({display: 'block'});
		$('.widgets-button').css({opacity: 0.5}).attr('disabled', true);
	}
}

pb.deleteProject = function(project){
	if (project.fromDB) queryDB({opts: {query: 'delete', id: project.puid}, callback: function(data){
			pb.openDialog({
				title: 'Project deleted.',
				content: '<br><center>The project "'+project.name+'" has been deleted.</center>',
				confirm: 'ok', cancel: false,
				style: {height: '120px'},
				onConfirm: function(){
					pb.closeDialog(); if (project.puid == pb.project.core.puid) pb.loadProject();
				}
			});
		}});
	else server({opts: {command: 'delete_project', puid: project.puid}, callback: function(data){
			pb.openDialog({
				title: 'Project deleted.',
				content: '<br><center>The project "'+project.name+'" has been deleted.</center>',
				confirm: 'ok', cancel: false,
				style: {height: '120px'},
				onConfirm: function(){
					pb.closeDialog(); if (project.puid == pb.project.core.puid) pb.loadProject();
				}
			});
		}});	
}

pb.saveProject = function(opts, callback){
	if (!opts) opts = {};
	var tproject = pb.projectToJSON(pb.project);
	
	var tuserbuttons = [];
	for (var k=0; k<pb.user.buttons.length; k++)
		tuserbuttons.push(pb.buttonToJSON(pb.user.buttons[k]));
	var tusertemplates = [];
	for (var k=0; k<pb.user.templates.length; k++)
		tusertemplates.push(pb.panelToJSON(pb.user.templates[k]));
	var name = opts.name ? opts.name : pb.project.core.name;
	if (opts.duplicate && !pb.project.core.puid) opts.duplicate = false;
	var command = opts.duplicate ? 'duplicate_project' : 'write_project';
	var _opts = {command: command, name: name, time: millitime()};
	if (pb.project.core.puid) _opts.puid = pb.project.core.puid;
	if (pb.project.core.hasMaster) _opts.hasMaster = pb.project.core.hasMaster;
	//console.log('saving...', command, opts, tproject, json_encode(tproject), typeof json_encode(tproject), typeof tproject);
	$('#spinner').fadeIn(200);
	
	tproject.core._userbuttons = tuserbuttons;
	tproject.core._usertemplates = tusertemplates;
	
	console.log('duplicate?', opts.duplicate);
	
	server({
		opts: _opts,
		data: tproject, 
		callback: function(data){
			try {

				$('#spinner').fadeOut(200);
				if (!opts.duplicate && pb.project.core.puid && parseInt(pb.project.core.puid) !== parseInt(data.puid)){
					var tproject = pb.projectToJSON(pb.project);
					tproject = json_encode(tproject);
					tproject = tproject.replaceAll(pb.project.core.puid, data.puid);
					var __opts = {command: 'write_project', puid: data.puid, time: millitime()};
					server({opts: __opts, data: tproject, callback: noop});
					console.log('rewriting in callback');
				}
				pb.project.core.puid = data.puid;
				
				console.log('rewrite?', data);
				
				var str = '';
				if (wallcon || modero){
					str = '<center><br>Project Saved to Server <br><br><span id="project-link"\
						style="cursor: pointer; text-decoration: underline;">Here\'s a link to your project.</span>\
						<br><br><span id="settowallcon" style="cursor: pointer;">Set to Wall Controller</span></center>';
				}
				if (standalone || ncommand){
					str = '<center><br>Project Saved to Server <br><br>'+
						'<span id="project-link" style="cursor: pointer; text-decoration: underline;"'+
						'>Here\'s a link to your project.</span></center>';
				}
				if (!opts.skipdialog && !opts.silent){
					pb.openDialog({
						content: str, cancel: false,
						onConfirm: function(){pb.closeDialog();},
						init: function(){
							if (wallcon || modero) $('#settowallcon')[0].onclick = function(){
								$('#project-props-n8301').click(); pb.closeDialog();
							};
							if (standalone) $('#project-link')[0].onclick = function(){
								var panelwin = gui.Window.open('../panels/index.php?project='+pb.project.core.puid, {
									title: 'SVSi Control Panels', show: true, toolbar: false, frame: true,
									icon: 'icons/icon.png', width: parseInt(pb.currentpanel.element.style.width)+0, 
									height: parseInt(pb.currentpanel.element.style.height)+0, position: 'center'
								});
							}
							else $('#project-link')[0].onclick = function(){
								window.open('../panels/index.php?project='+pb.project.core.puid, '_blank');
							}
						}
					});
				}
				if (callback) callback();
			}
			catch (e){dumpError(e);}
		}
	});
}

pb._loadProject = function(opts){
	if (opts.project) var project = opts.project;
	else var project = opts;
	//console.log('_loading: opts', opts);
	pb.user.templates = []; pb.user.buttons = []; pb.user.assets.images = [];
	$('#templatesGrid').html(''); $(document.getElementById('User Buttons')).html('');
	$('#assets-images-pane-list').html('');
	$('#spinner').fadeIn(200);
	if (project.fromDB){
		queryDB({opts: {query: 'select_byname', name: project.puid}, callback: function(data){
			//var tcode = json_decode(data); var oldid = tcode.puid;
			//data = data.replaceAll(oldid, project.puid);
			opts.__project = json_decode(data); opts.puid = project.puid; pb.loadProject(opts);
			for (var i=0; i<pb.user.panels.length; i++){
				for (var j=0; j<pb.user.panels[i].buttons.length; j++)
					for (var k=0; k<pb.user.panels[i].buttons[j].core.scripts.length; k++)
						pb.user.panels[i].buttons[j].core.scripts[k] = '<nCmd>\n' +
							pb.user.panels[i].buttons[j].core.scripts[k] + '\n</nCmd>';
				for (var j=0; j<pb.user.panels[i].widgets.length; j++)
					for (var k=0; k<pb.user.panels[i].widgets[j].core.scripts.length; k++)
						pb.user.panels[i].widgets[j].core.scripts[k] = '<nCmd>\n' +
							pb.user.panels[i].widgets[j].core.scripts[k] + '\n</nCmd>';
				
			}
			pb.project.core.puid = false; pb.saveProject(true);
			queryDB({opts: {query: 'delete_byname', name: project.puid}, callback: noop});
		}});
	}
	else {
		server({opts: {command: 'read_project', name: project.name, puid: project.puid, time: millitime()}, callback: function(data){
			try {
				var tstr = '';
				if (0&&data.indexOf){
					while (data.indexOf('http://') !== -1 && data.indexOf('/panels/') !== -1){
						tstr = data.substring(data.indexOf('http://'), (data.indexOf('/panels/')+8)); data = data.replace(tstr, '');
					}
					while (data.indexOf('file:///') !== -1 && data.indexOf('/index/') !== -1){
						tstr = data.substring(data.indexOf('file:///'), (data.indexOf('/index/')+7)); data = data.replace(tstr, '');
					}
				}
				
				var tcode = json_decode(data);  
				if (tcode && tcode.core) var oldid = tcode.puid || tcode.core.puid; else var oldid = tcode.puid;
				//data = data.replaceAll(oldid, project.puid);
				if (oldid) data = data.replace(/projects\/[0-9]*\//g, 'projects/'+project.puid+'/');
				opts.__project = json_decode(data); opts.puid = project.puid; pb.loadProject(opts);
				setTimeout(function(){
					if (pb.currentpanel){
						pb.currentpanel.element.style.background = pb.currentpanel.element.style.background;
						pb.currentpanel.element.style.backgroundSize = '100% 100%';
					}
				}, 2000);
			}
			catch (e){
				dumpError(e);
			}
		}});
	}
}
pb.loadProject = function(opts){
	$('#spinner').fadeOut(200);
	console.log('loadproject', opts);
	if (!opts) opts = {new: true};
	
	//if no actual project && not new project, load from server
	if (!opts.new && !opts.__project){
		pb._loadProject(opts); return;
	}

	for (var i=0; i<pb.user.panels.length; i++){
		$(pb.user.panels[i].element).remove();
		for (var j=0; j<pb.user.panels[i].buttons.length; j++){
			$(pb.user.panels[i].buttons[j].element).remove();
			for (var k=0; k<pb.default.buttons.length; k++)
				if (pb.default.buttons[k].element.id === pb.user.panels[i].buttons[j].element.id) 
					removeFromArray(pb.default.buttons, pb.default.buttons[k]);
		}
		for (var j=0; j<pb.user.panels[i].widgets.length; j++){
			$(pb.user.panels[i].widgets[j].element).remove();
			for (var k=0; k<pb.user.panels[i].widgets[j].parts.length; k++)
				$(pb.user.panels[i].widgets[j].parts[k].element).remove();
			for (var k=0; k<pb.default.widgets.length; k++)
				if (pb.default.widgets[k].element.id === pb.user.panels[i].widgets[j].element.id) 
					removeFromArray(pb.default.widgets, pb.default.widgets[k]);
		}
	}
	
	pb.unselectAll();
	
	pb.undoactions = []; pb.redoactions = [];
	pb.project = {core: {name: 'New Project', puid: false, buttonindex: 0, widgetindex: 0, widgetpartindex: 0, panelindex: 0}};
	pb.user.buttons = []; pb.user.widgets = []; pb.user.widgetparts = [];
	pb.user.assets = {scripts: [], modules: [], images: []};
	pb.user.panels = []; pb.user.templates = [];
	
	if (opts.__project){
		if (!opts.__project.core) pb.project.core = {
			name: opts.__project.name, puid: opts.puid, scripts: opts.__project.core.scripts,
			buttonindex: opts.__project.buttonindex||1, widgetindex: opts.__project.widgetindex||1,
			widgetpartindex: opts.__project.widgetpartindex||1, panelindex: opts.__project.panelindex||1, hasMaster: opts.__project.hasMaster
		};
		else pb.project.core = {
			name: opts.__project.core.name, puid: opts.puid, scripts: opts.__project.core.scripts,
			buttonindex: opts.__project.core.buttonindex||1, widgetindex: opts.__project.core.widgetindex||1,
			widgetpartindex: opts.__project.core.widgetpartindex||1, panelindex: opts.__project.core.panelindex||1, hasMaster: opts.__project.core.hasMaster
		};
	}
	else if (opts.puid) pb.project.core.puid = opts.puid;
	
	pb.currentpanel = false;
	
	$('#panel-space-1').html(''); $('#panel-space-2').html(''); $('#panel-space-3').html(''); $('#labels').html('');
	
	if (pb.project.core.passkey) $('#project-props-passkey').val(pb.project.core.passkey);

	//console.log('hm1?', opts.__project);
	if (opts.__project && opts.__project.panels && opts.__project.panels.length){
		//console.log('hm2?');
		for (var i=0; i<opts.__project.panels.length; i++) pb.loadPanel(opts.__project.panels[i]);
		
	}
	if (opts.new || opts.addPanel) pb.addPanel();
	
	if (!pb.defaultButtonsLoaded) pb.setupDefaultButtons();
	if (!pb.userButtonsLoaded) pb.setupUserButtons();

	pb.openToolsPane(); pb.openResourcesPane(); pb.closeDialog();
	
	if ($('#project-options')[0].style.display !== 'none') 
		$('#project-options').cssAnim('fadeOutLeft', function(){$(this).hide();});
	if (!$('#selectorbox').exists()) $('#thebody').append('<div id="selectorbox"\
		style="opacity: 0.65; display: none; z-index: 10000000;"></div>');
	if (!undef(pb.project.core.name)){
		$('#project-name-display').css('display', 'block');
		$('#project-name-display')[0].innerHTML = 'Project: ' + pb.project.core.name;
		$('#project-props-name').val(pb.project.core.name);
	}
			
	pb.ready = true;
	
	if (!pb.user.panels.length){
		//pb.project.panels = pb.user.panels;
		$('#labels').html('<div id="_no_panels_added"\
			style="width: 100%; height: 100%; text-align: center; color: red; line-height: 28px; font-size: 13px;">No Panels Added!</div>');
	}
	
	
	if (1) if (opts.__project && opts.__project.core && opts.__project.core._userbuttons){
		for (var i=0; i<opts.__project.core._userbuttons.length; i++){
			if (opts.__project.core._userbuttons[i].core) opts.__project.core._userbuttons[i].core.type = 'default';
			setTimeout(function(i){pb.addUserButton(new Button(opts.__project.core._userbuttons[i]));}.bind({}, i), 1000);
		}
	}
	if (1) if (opts.__project && opts.__project.core && opts.__project.core._usertemplates){
		for (var i=0; i<opts.__project.core._usertemplates.length; i++){
			//if (opts.__project.core._usertemplates[i].core) opts.__project.core._usertemplates[i].core.type = 'panels';
			if (opts.__project.core._usertemplates[i].core) delete opts.__project.core._usertemplates[i].core.id;
			//setTimeout(function(i){pb.addTemplateFromPanel(new Panel(opts.__project.core._usertemplates[i]));}.bind({}, i), 1000);
			if (opts.__project.core._usertemplates[i].buttons) for (var j=0; j<opts.__project.core._usertemplates[i].buttons.length; j++){
				//console.log(opts.__project.core._usertemplates[i].buttons[j]);
				if (opts.__project.core._usertemplates[i].buttons[j].core){
					opts.__project.core._usertemplates[i].buttons[j].core.id = undefined;
					
				}
				var keys = Object.keys(opts.__project.core._usertemplates[i].buttons[j].core); var obj = {};
				for (var k=0; k<keys.length; k++){
					//console.log('fFFFFFFFFFFFFFFFFFFF', keys[k], keys[k] != 'id');
					if (keys[k] != 'id') obj[keys[k]] = opts.__project.core._usertemplates[i].buttons[j].core[keys[k]];
				}
				//console.log('here', obj);
				//console.log('here', opts.__project.core._usertemplates[i].buttons[j]);
				opts.__project.core._usertemplates[i].buttons[j] = new Button({core: obj});
			}
			if (opts.__project.core._usertemplates[i].widgets) for (var j=0; j<opts.__project.core._usertemplates[i].widgets.length; j++){
				for (var k=0; k<opts.__project.core._usertemplates[i].widgets[j].parts.length; k++){
					opts.__project.core._usertemplates[i].widgets[j].parts[k] = new WidgetPart(opts.__project.core._usertemplates[i].widgets[j].parts[k]);
				}
				opts.__project.core._usertemplates[i].widgets[j] = new Widget(opts.__project.core._usertemplates[i].widgets[j]);
				
			}
			opts.__project.core._usertemplates[i].core.autoinsert = false;
			var panel = new Panel(opts.__project.core._usertemplates[i]);
			for (var j=0; j<panel.buttons.length; j++){
				panel.buttons[j].panel = panel;
			}
			//console.log('setting panel', $(panel.element).width());
			/*for (var j=0; j<panel.widgets.length; j++){
				panel.widgets[j].panel = panel;
				panel.widgets[j].width = (opts.__project.core._usertemplates[i].widgets[j].basewidth*($(panel.element).width()/80)) + 'px';
				panel.widgets[j].height = (opts.__project.core._usertemplates[i].widgets[j].baseheight*($(panel.element).width()/80)) + 'px';
				panel.widgets[j].top = (opts.__project.core._usertemplates[i].widgets[j].basetop*($(panel.element).width()/80)) + 'px';
				panel.widgets[j].left = (opts.__project.core._usertemplates[i].widgets[j].baseleft*($(panel.element).width()/80)) + 'px';
			}*/
			
			//console.log('p', panel);
			/*if (opts.__project.core._usertemplates[i].buttons) for (var j=0; j<opts.__project.core._usertemplates[i].buttons.length; j++){
				panel.addChild(new Button(opts.__project.core._usertemplates[i].buttons[j]));
			}
			if (opts.__project.core._usertemplates[i].widgets) for (var j=0; j<opts.__project.core._usertemplates[i].widgets.length; j++){
				panel.addChild(new Widget(opts.__project.core._usertemplates[i].widgets[j]));
			}*/
			//pb.addTemplateFromPanel(panel);
			$('#button-library-select').val('Default Buttons'); $('#button-library-select').change();
			setTimeout(function(panel){
				pb.addTemplateFromPanel(panel); 
				$('#button-library-select').val('Default Buttons'); $('#button-library-select').change();
			}.bind({}, panel), 300*i);
		}
	}
	
}

pb.loadRecent = function(callback){
	for (var i=0;i<projectlist.length;i++){
		if ($('#project-options-recent-select').val() == projectlist[i].puid){
			pb.user.templates = []; pb.user.buttons = [];
			$('#templatesGrid').html(''); $(document.getElementById('User Buttons')).html('');
			pb.loadProject({project: projectlist[i], callback: callback});
		}
	}
}

pb.addPanel = function(){
	pb.closeMenu(null, ['file','edit','add','view']);
	$('#add-panel-name').val('Panel-'+pb.panelindex);	
	if (wallcon){
		$('#add-panel-width').val('240');
		$('#add-panel-height').val('320');
	}
	else if (modero){
		$('#add-panel-width').val('1024');
		$('#add-panel-height').val('600');
	}
	else {
		$('#add-panel-width').val('1024');
		$('#add-panel-height').val('768');
	}
	if ($('#dialog-mousecatch').css('display') != 'block') $('#dialog-mousecatch').fadeIn();
	$('#add-panel').show(); 
	$('#add-panel').cssAnim('fadeInLeft', function(){
		setTimeout(function(){$('.add-panel').show(); $('.add-panel').cssAnim('fadeInDown', noop, 0.5);}, 200);
	}, 0.5);
	$('#add-panel-add')[0].onclick = function(){
		$('#dialog-mousecatch, #hideall').fadeOut();
		$('#add-panel').cssAnim('fadeOutRight', function(){
			$('#add-panel, .add-panel').hide();
			pb.ready = true;
		}, 0.5);
		var name = $('#add-panel-name').val(),
			width = $('#add-panel-width').val(),
			height = $('#add-panel-height').val();
		var newpanel = new Panel({
			name: name, 
			style: 'float: left; width: '+width+'px; height: '+height+'px;\
			position: absolute; left: 0px; border: 1px solid black; background: white;',
			className: 'panel selectables'
		});
		$('#labels').append('<div style="overflow: hidden; float: left; width: 70px; height: 27px;\
			background: #f5f5f5; text-align: center; margin-top: 1px; -moz-box-shadow: inset 1px 1px 1px 1px #aaa;\
			-webkit-box-shadow: inset 1px 1px 1px 1px #aaa; box-shadow: inset 1px 1px 1px 1px #aaa;\
			border-radius: 4px; margin-left: 4px; margin-right: 4px; line-height: 26px;" id="'+newpanel.core.id
											+'_label" class="panel_label" title="'+name+'">'+name+'</div>');								
		$('#'+newpanel.core.id+'_label').css('cursor', 'pointer');
		$('#'+newpanel.core.id+'_label')[0].onclick = function(){
			pb.switchToPanel(newpanel);
		};
		pb.switchToPanel(newpanel);
		$('#_no_panels_added').hide();
		//console.log('setting timeout?');
		setTimeout(function(){$('#dialog-mousecatch, #hideall').fadeOut();}, 1000);
	}
	$('#add-panel-cancel')[0].onclick = function(){
		$('#dialog-mousecatch, #hideall').fadeOut();
		setTimeout(function(){$('#dialog-mousecatch, #hideall').fadeOut();}, 1000);
		$('#add-panel').cssAnim('fadeOutRight', function(){
			$('#add-panel, .add-panel').hide();
		}, 0.5);
	}
}

pb.loadPanel = function(panel){

	if (!panel) return;
	
	$('#_no_panels_added').hide();

	$('.outlined').removeClass('outlined'); $('.first').removeClass('first');

	if (panel.core){
		panel.core.autoinsert = true;
		var thispanel = new Panel({
			core: panel.core,
			copyid: true
		});
	}
	else
		var thispanel = new Panel({
			name: panel.name,
			id: panel.id,
			scale: panel.scale,
			width: panel.width,
			height: panel.height,
			style: panel.style,
			className: panel.className,
			states: panel.states,
			svgstring: panel.svgstring,
			autoresize: panel.autoresize
		});
	//console.log('appending?');
	$('#labels').append('<div style="overflow: hidden; float: left; width: 70px; height: 27px;\
		background: #f5f5f5; text-align: center; margin-top: 1px; -moz-box-shadow: inset 1px 1px 1px 1px #aaa;\
		-webkit-box-shadow: inset 1px 1px 1px 1px #aaa; box-shadow: inset 1px 1px 1px 1px #aaa;\
		border-radius: 4px; margin-left: 4px; margin-right: 4px; line-height: 26px;" id="'+thispanel.core.id
										+'_label" class="panel_label" title="'+thispanel.core.name+'">'+thispanel.core.name+'</div>');
										
	$('#'+thispanel.core.id+'_label').css('cursor', 'pointer');

	$('#'+thispanel.core.id+'_label')[0].onclick = function(){
		pb.switchToPanel(thispanel);
	};
	
	thispanel.element.style.backgroundSize = "100% 100%";
	thispanel.buttons = [];
	for (var j=0;j<panel.buttons.length;j++){
		if (panel.buttons[j].core){
			var thisbutton = new Button({
				core: panel.buttons[j].core,
				copyid : true
			});
		}
		else {
			if (!panel.buttons[j].states[0].images) panel.buttons[j].states[0].images = [];
			if (!panel.buttons[j].states[1].images) panel.buttons[j].states[1].images = [];
			var thisbutton = new Button({
				id: panel.buttons[j].id,
				name: panel.buttons[j].name,
				textnodeHTML: panel.buttons[j].text,
				textoffsetx: panel.buttons[j].textoffsetx,
				textoffsety: panel.buttons[j].textoffsety,
				textstyle: panel.buttons[j].textstyle,
				scale: panel.buttons[j].scale,
				style: panel.buttons[j].style,
				className: panel.buttons[j].className,
				states: panel.buttons[j].states,
				scripts: panel.buttons[j].scripts,
				conditional: panel.buttons[j].conditional,
				touchpanelkey: panel.buttons[j].touchpanelkey
			});
		}
		thisbutton.element.className = 'draggable';
		thisbutton.element.style.backgroundSize = "100% 100%";

		thispanel.addChild(thisbutton);
		thisbutton.container = thispanel.element;
		thisbutton.makeResizable();
	}
	thispanel.widgets = [];
	for (var j=0;j<panel.widgets.length;j++){
	
		var newparts = [];
		for (var k=0;k<panel.widgets[j].parts.length;k++){
			if (panel.widgets[j].parts[k].core)
				var newpart = new WidgetPart({
					copyid: true,
					core: panel.widgets[j].parts[k].core,
					init: panel.widgets[j].parts[k].init || noop,
					update: panel.widgets[j].parts[k].update || noop,
					moving: panel.widgets[j].parts[k].moving || noop,
					drop: panel.widgets[j].parts[k].drop || noop,
					click: panel.widgets[j].parts[k].click || noop,
					clickup: panel.widgets[j].parts[k].clickup || noop,
					hoverin: panel.widgets[j].parts[k].hoverin || noop,
					hoverout: panel.widgets[j].parts[k].hoverout || noop,
					ontopanel: panel.widgets[j].parts[k].ontopanel || noop,
					resize: panel.widgets[j].parts[k].resize || noop
				});
			else
				var newpart = new WidgetPart({
					name: panel.widgets[j].parts[k].name,
					width: panel.widgets[j].parts[k].width,
					height: panel.widgets[j].parts[k].height,
					scale: panel.widgets[j].parts[k].scale,
					style: panel.widgets[j].parts[k].style,
					drop: panel.widgets[j].parts[k].drop,
					script: panel.widgets[j].parts[k].script,
					conditional: panel.widgets[j].parts[k].conditional,
					click: panel.widgets[j].parts[k].click || noop,
					clickup: panel.widgets[j].parts[k].clickup || noop,
					hoverin: panel.widgets[j].parts[k].hoverin || noop,
					hoverout: panel.widgets[j].parts[k].hoverout || noop,
					init: panel.widgets[j].parts[k].init || noop,
					update: panel.widgets[j].parts[k].update || noop,
					moving: panel.widgets[j].parts[k].moving || noop,
					update: panel.widgets[j].parts[k].update || noop,
					className: panel.widgets[j].parts[k].className,
					id: panel.widgets[j].parts[k].id,
					ontopanel: panel.widgets[j].parts[k].ontopanel || noop,
					fn: panel.widgets[j].parts[k].fn,
					innerhtml: panel.widgets[j].parts[k].innerhtml
				});
			newparts.push(newpart);
		}
	
		if (panel.widgets[j].core)
			var thiswidget = new Widget({
				copyid: true,
				core: panel.widgets[j].core,
				init: panel.widgets[j].init || noop,
				update: panel.widgets[j].update || noop,
				hoverin: panel.widgets[j].hoverin || noop,
				hoverout: panel.widgets[j].hoverout || noop,
				ontopanel: panel.widgets[j].ontopanel || noop,
				resize: panel.widgets[j].resize || noop,
				parts: newparts
			});
		else {
			var thiswidget = new Widget({
				name: panel.widgets[j].name,
				id: panel.widgets[j].id,
				type: panel.widgets[j].type,
				width: panel.widgets[j].width,
				height: panel.widgets[j].height,
				scale: panel.widgets[j].scale,
				style: panel.widgets[j].style,
				basewidth: panel.widgets[j].basewidth,
				baseheight: panel.widgets[j].baseheight,
				basetop: panel.widgets[j].basetop,
				baseleft: panel.widgets[j].baseleft,
				init: panel.widgets[j].init || noop,
				update: panel.widgets[j].update || noop,
				className: panel.widgets[j].className,
				states: panel.widgets[j].states,
				innerhtml: panel.widgets[j].innerhtml,
				svgstring: panel.widgets[j].svgstring,
				parts: newparts,
				script: panel.widgets[j].script,
				conditional: panel.widgets[j].conditional,
				resize: panel.widgets[j].resize || noop,
				vars: panel.widgets[j].vars,
				aspectratio: panel.widgets[j].aspectratio
			});
		}
		thiswidget.dropped = true;
		thiswidget.element.className = 'draggable';
		thiswidget.makeResizable();
		thiswidget.container = thispanel.element;
		thispanel.addChild(thiswidget);
		thiswidget.ontopanel();
	}
	thispanel.subpanels = [];
	if (panel.subpanels) for (var j=0;j<panel.subpanels.length;j++){
		if (panel.subpanels[j].core){
			var thissubpanel = new SubPanel({
				core: panel.subpanels[j].core,
				children: panel.subpanels[j].children,
				copyid : true
			});
		}
		else {
			var thissubpanel = new SubPanel({
				id: panel.subpanels[j].id,
				name: panel.subpanels[j].name,
				scale: panel.subpanels[j].scale,
				style: panel.subpanels[j].style,
				className: panel.subpanels[j].className,
				conditional: panel.subpanels[j].conditional,
				touchpanelkey: panel.subpanels[j].touchpanelkey,
				children: panel.subpanels[j].children
			});
		}
		
		//thispanel.addChild(thissubpanel);
		if (!thispanel.subpanels) thispanel.subpanels = [];
		if (!arrayContains(thispanel.subpanels, thissubpanel)) thispanel.subpanels.push(thissubpanel);
		$(thispanel.element).append(thissubpanel.element);
		
		//thissubpanel.element.className = 'draggable';
		
		thissubpanel.makeResizable();
		
		$(thissubpanel.element).addClass('draggable');
		
		thissubpanel.panel = thispanel;
		
		var _bbox = thissubpanel.element.getBoundingClientRect();
		var _pbox = thispanel.element.getBoundingClientRect();
		for (var k=0; k<thissubpanel.children.length; k++){
			var child = get(thissubpanel.children[k]); if (!child) continue;
			child.subpanel = thissubpanel.core.id;
			
			var _cbox = child.element.getBoundingClientRect();
			//console.log('setting', child.core.id);
			child._x = _cbox.left - _bbox.left - _pbox.left;
			child._y = _cbox.top - _bbox.top - _pbox.top;
		}

		
	}
	
	pb.switchToPanel(thispanel);
	pb.updateTree();
	
}

pb.setupUserButtons = function(){
	var userButtons = document.createElement('div');
	userButtons.id = "User Buttons";
	userButtons.style.cssText += "position: absolute; top: 0px; width: 100%;\
		height: calc(100% - 1px); overflow:auto; z-index: 201; min-height: 200px;\
		";
	
	pb.loadButtonLibrary(userButtons);
	pb.userButtonsLoaded = true;
}

pb.setupDefaultButtons = function(){
	var defaultButtons = document.createElement('div');
	defaultButtons.id = "Default Buttons";
	defaultButtons.style.cssText += "position: absolute; top: 0px; width:100%;\
		height: calc(100% - 1px); overflow:auto; z-index: 201; \
		border-top: 1px solid darkgrey; border-bottom: 0px solid darkgrey;";
	
	var tempbuttons = [];
	for (var i=1; i<87; i++){
		if (i<21 || i>24) tempbuttons.push(pb.getDefaultButton('Buttons-'+i));
	}
	for (var i=0; i<tempbuttons.length; i++){
		defaultButtons.appendChild(tempbuttons[i].element);
	}
	
	pb.loadButtonLibrary(defaultButtons);
	pb.defaultButtonsLoaded = true;
}

pb.openProjectListDialog = function(){
	var selectstring = '';
	selectstring += '<select id="project_list_all" name="projectlistall" >'
	for (var i=0; i<projectlist.length; i++)
		selectstring += '<option value="'+projectlist[i]+'">'+projectlist[i]+'</option>';
	selectstring += '</select>';
	pb.closeDialog();
	pb.openDialog({
		content: 'Choose the project to open:'+selectstring,
		onConfirm: function(){
			for (var i=0; i<projectlist.length; i++)
				if ($('#project_list_all').val() == projectlist[i]) pb.loadProject(projectlist[i]);
		}
	});

}

pb.updateProjectList = function(){
	queryDB({opts: {query: 'select_allnames'}, callback: function(data){
		projectnames = []; projectlist = json_decode(data.trim())||[];
		//projectlist.sort(function(a, b){if(a.name < b.name) return -1; if(a.name > b.name) return 1; return 0;});
		for (var i=0; i<projectlist.length; i++) 
			for (var key in projectlist[i])
				if (key == 'name') projectnames.push(projectlist[i][key]);
	}});
	server({
		opts: {command: 'read_projectnames'}, 
		callback: function(data){
			projectnames = []; projectlist = json_decode(data)||[];
			//projectlist.sort(function(a, b){if(a.name < b.name) return -1; if(a.name > b.name) return 1; return 0;});
			for (var i=0; i<projectlist.length; i++)
				for (var key in projectlist[i])
					if (key == 'name') projectnames.push(projectlist[i][key]);
		}
	});
}

pb.openSelectProjectList = function(){
	projectlist = [];
	var list_capsule = new capsule(2, function(){
		var selectstring = '';
		selectstring += '<select id="project_list_all" name="projectlistall" >';
		//projectlist.sort(function(a, b){if(a.name < b.name) return -1; if(a.name > b.name) return 1; return 0;});
		for (var i=0; i<projectlist.length; i++){
			selectstring += '<option value="'+projectlist[i].puid+'">'+projectlist[i].name+'</option>';
		}
		selectstring += '</select>';
		pb.openDialog({
			title: '<br><br><span style="font-size: 25px;">Choose the project to open:</span>',
			content: '<br><center>'+selectstring+'</center>',
			style: {height: '240px', width: '560px', 'border-radius': '17px'},
			buttonstyle: {
				'float': 'right', 'margin-left': '2px', 'border-radius': '5px',
				'padding-top': '6px', 'padding-bottom': '6px', 'padding-left': '12px', 'padding-right': '12px',
				'background': 'white', 'font-weight': 'bold', 'color': 'black'
			},
			onConfirm: function(){
				//$(document.getElementById('User Buttons')).html(''); pb.user.buttons = [];
				pb.user.templates = []; pb.user.buttons = [];
				$('#templatesGrid').html(''); $(document.getElementById('User Buttons')).html('');
				for (var i=0;i<projectlist.length;i++){
					if ($('#project_list_all').val() == projectlist[i].puid)
						pb.loadProject(projectlist[i]);
				}
				pb.closeDialog();
			},
			onCancel: function(){
				pb.closeDialog();
			}
		});
	
	});

	if (useDB_read)
		queryDB({opts: {query: 'select_allnames'}, callback: function(data){
			
			var tlist = json_decode(data);
			
			for (var i=0; i<tlist.length; i++){
				projectlist.push(tlist[i]);
			}
			
			list_capsule.push(1);
			
		}});
	else list_capsule.push(1);
	
	server({opts: {command: 'read_projectnames'}, callback: function(data){
	
		try {
			var tlist = json_decode(data);
				
			for (var i=0; i<tlist.length; i++){
				projectlist.push(tlist[i]);
			}
			
			list_capsule.push(1);
		}
		catch (e){
			dumpError(e);
			list_capsule.push(1);
		}
		
	}});
	
}

pb.openDeleteProjectList = function(){
	
	projectlist = [];
	
	var list_capsule = new capsule(2, function(){
		var selectstring = '';
		selectstring += '<select id="project_list_all" name="projectlistall" >'
		
		for (var i=0;i<projectlist.length;i++){
			selectstring += '<option value="'+projectlist[i].puid+'">'+
				projectlist[i].name+'</option>';
		}
		selectstring += '</select>';
		
		pb.openDialog({
			title: '<br><br>Choose the project to delete:',
			content: '<br><center>'+selectstring+'</center>',
			style: {
				height: '240px',
				width: '560px',
				'border-radius': '17px'
			},
			buttonstyle: {
				'float': 'right',
				'margin-left': '2px',
				'border-radius': '5px',
				'padding-top': '6px',
				'padding-bottom': '6px',
				'padding-left': '12px',
				'padding-right': '12px',
				'background': 'white',
				'font-weight': 'bold',
				'color': 'black'
			},
			onConfirm: function(){
				for (var i=0;i<projectlist.length;i++) {
					if ($('#project_list_all').val() == projectlist[i].puid) 
						pb.deleteProject(projectlist[i]);
				}
				pb.closeDialog();
			}
		});
	});
	if (useDB_read)
		queryDB({opts: {query: 'select_allnames'}, callback: function(data){
			var tlist = json_decode(data);
			for (var i=0; i<tlist.length; i++) projectlist.push(tlist[i]);
			list_capsule.push(1);
		}});
	else list_capsule.push(1);
	server({opts: {command: 'read_projectnames'}, callback: function(data){
		try {
			var tlist = json_decode(data);
			for (var i=0; i<tlist.length; i++) projectlist.push(tlist[i]);
			list_capsule.push(1);
		}
		catch (e){dumpError(e); list_capsule.push(1);}
	}});
}

pb.updateRecent = function(){
	
	projectlist = [];
	pb.projectlist = [];
	
	var list_capsule = new capsule(2, function(){
		if (projectlist.length == 0){
			$('#recentmenuitem1').html('empty');
			$('#recentmenuitem1').css({display: 'block'});
			$('#recentmenuitem2').css({display: 'none'});
			$('#recentmenuitem3').css({display: 'none'});
			$('#recentmenuitem4').css({display: 'none'});
			$('#recentmenuitem5').css({display: 'none'});
			$('#recentmenuitem6').css({display: 'none'});
			$('#recentmenuitem7').css({display: 'none'});
			$('#recentmenuitem8').css({display: 'none'});
		}
		
		if (projectlist.length >= 1){
			$('#recentmenuitem1').html(projectlist[0].name);
			$('#recentmenuitem1').css({display: 'block'});
		}
		if (projectlist.length >= 2){
			$('#recentmenuitem2').html(projectlist[1].name);
			$('#recentmenuitem2').css({display: 'block'});
		}
		else $('#recentmenuitem2').css({display: 'none'});
		if (projectlist.length >= 3){
			$('#recentmenuitem3').html(projectlist[2].name);
			$('#recentmenuitem3').css({display: 'block'});
		}
		else $('#recentmenuitem3').css({display: 'none'});
		if (projectlist.length >= 4){
			$('#recentmenuitem4').html(projectlist[3].name);
			$('#recentmenuitem4').css({display: 'block'});
		}
		else $('#recentmenuitem4').css({display: 'none'});
		if (projectlist.length >= 5){
			$('#recentmenuitem5').html(projectlist[4].name);
			$('#recentmenuitem5').css({display: 'block'});
		}
		else $('#recentmenuitem5').css({display: 'none'});
		if (projectlist.length >= 6){
			$('#recentmenuitem6').html(projectlist[5].name);
			$('#recentmenuitem6').css({display: 'block'});
		}
		else $('#recentmenuitem6').css({display: 'none'});
		if (projectlist.length >= 7){
			$('#recentmenuitem7').html(projectlist[6].name);
			$('#recentmenuitem7').css({display: 'block'});
		}
		else $('#recentmenuitem7').css({display: 'none'});
		if (projectlist.length >= 8){
			$('#recentmenuitem8').html(projectlist[7].name);
			$('#recentmenuitem8').css({display: 'block'});
		}
		else $('#recentmenuitem8').css({display: 'none'});
	});
	
	/*server({opts: {command: 'read_projectnames'}, callback: function(data){

		projectlist = json_decode(data);

	}});*/
	
	if (useDB_read)
		queryDB({opts: {query: 'select_allnames'}, callback: function(data){
			
			var tlist = json_decode(data);
			
			for (var i=0; i<tlist.length; i++){
				projectlist.push(tlist[i]);
				pb.projectlist.push(tlist[i]);
			}
			
			list_capsule.push(1);
			
		}});
	else list_capsule.push(1);
	
	server({opts: {command: 'read_projectnames'}, callback: function(data){
	
		if (1||!standalone) try {
			var tlist = json_decode(data);
				
			for (var i=0; i<tlist.length; i++){
				projectlist.push(tlist[i]);
				pb.projectlist.push(tlist[i]);
			}
			
			list_capsule.push(1);
		}
		catch (e){
			dumpError(e);
			list_capsule.push(1);
		}
		
	}});
	
}

pb.openDialog = function(opts){
	if (pb.dialogopen){
		waitfor(
			function(){if (!pb.dialogopen) return true; else return false;}, 
			function(){pb.openDialog(opts)}
		);
		return;
	}
	pb.dialogopen = true;
	
	if (undef(opts)) var opts = {};
	var type = opts.hasOwnProperty('type') ? opts.type : 'warning';
	var title = opts.hasOwnProperty('title') ? opts.title : false;
	var content = opts.hasOwnProperty('content') ? opts.content : false;
	var confirm = opts.hasOwnProperty('confirm') ? opts.confirm : "ok";
	var cancel = opts.hasOwnProperty('cancel') ? opts.cancel : "cancel";
	var extra = opts.hasOwnProperty('extra') ? opts.extra : false;
	var onConfirm = opts.hasOwnProperty('onConfirm') ? opts.onConfirm : function(){pb.closeDialog();};
	var onCancel = opts.hasOwnProperty('onCancel') ? opts.onCancel : function(){pb.closeDialog();};
	var onExtra = opts.hasOwnProperty('onExtra') ? opts.onExtra : false;
	var init = opts.hasOwnProperty('init') ? opts.init : noop;
	var width = opts.hasOwnProperty('width') ? opts.width : 400;
	var height = opts.hasOwnProperty('height') ? opts.height : 300;
	var style = opts.hasOwnProperty('style') ? opts.style : {};
	var buttonstyle = opts.hasOwnProperty('buttonstyle') ? opts.buttonstyle : false;
	
	$('#dialog_title').hide();
	$('#dialog_content').hide();
	$('#dialog_confirm').hide();
	$('#dialog_cancel').hide();
	$('#dialog_extra').hide();
	
	if (title){
		$('#dialog_title').show();
		$('#dialog_title').html(title);
	}
	if (content){
		$('#dialog_content').show();
		$('#dialog_content').html(content);
		if ($('#dialog_content')[0].children[0] && $('#dialog_content')[0].children[0].style) 
			$('#dialog_content')[0].children[0].style.margin = '15px';
		$('#dialog_content')[0].style.margin = '15px';
	}
	if (confirm){
		$('#dialog_confirm').show();
		$('#dialog_confirm').val(confirm);
	}
	if (cancel){
		$('#dialog_cancel').show();
		$('#dialog_cancel').val(cancel);
	}
	if (extra){
		$('#dialog_extra').show();
		$('#dialog_extra').val(extra);
	}
	if (onConfirm){
		$('#dialog_confirm')[0].onclick = onConfirm;
	}
	if (onCancel){
		$('#dialog_cancel')[0].onclick = onCancel;
	}
	if (onExtra){
		$('#dialog_extra')[0].onclick = onExtra;
	}
	
	$('#dialog-pane').css({display: 'block'});
	
	$('#dialog-minipane').css({
		width: width+'px',
		height: height+'px',
		background: 'black',
		color: 'white',
		'border-radius': '15px',
		border: '1px solid #ccc'
	});
	
	$('#dialog-minipane').css(style);
	
	$('#dialog-minipane').css({
		left: 'calc(50% - '+($('#dialog-minipane').width()/2)+'px)',
		top: 'calc(46% - '+($('#dialog-minipane').height()/2)+'px)'
	});
	
	if (buttonstyle){
		$('#dialog_confirm').css(buttonstyle);
		$('#dialog_cancel').css(buttonstyle);
		$('#dialog_extra').css(buttonstyle);
	}
	
	$('#dialog-pane').css({display: 'block', opacity: 0, transform: 'scale3d(1.0,1.0,1.0)', webkitTransform: 'scale3d(1.0,1.0,1.0)'}).animate({opacity: 1});

	init();
	
	switch (type) {
		case 'warning': default:
			$('#dialog-mousecatch').click(function(){pb.closeDialog()});
			break;
		case 'error':
			break;
		case 'confirm':
			break;
	}
}

pb.closeDialog = function(onComplete){
	$('#dialog-pane').fadeOut(function(){
		pb.dialogopen = false;
		$('#dialog-pane').css({display: 'none'});
		if (onComplete) onComplete();
	});
}

pb.updateModules = function(callback){
	server({opts: {command: 'read_allmodules'}, callback: function(data){
		modulelist = json_decode(data);
		server({opts: {command: 'read_allmanufacturers'}, callback: function(data){
			manufacturerlist = json_decode(data);
			if (callback) callback();
		}});
	}});
}

pb.checkDiskSize = function(callback){
	if (undef(callback)) callback = noop;
	if (!standalone) server({opts: {command: 'get_disk_filesize'}, callback: function(data){
		try {
			var percent = (data/100000000).toPrecision(3);
			var total = (data/1000000).toPrecision(3)+'MB';
			if (wallcon) var max = 100+'MB';
			else if (modero) var max = 1000+'MB';
			else var max = false;
			htmlmodel.disk = {percent: percent, total: total, max: max};
		}
		catch (e){
			dumpError(e);
		}
		callback(htmlmodel.disk);
	}});
}

pb.updateProjectList = function(callback){
	if (undef(callback)) callback = noop;
	var list_capsule = new capsule(2, callback);
	if (useDB_read)
		queryDB({opts: {query: 'select_allnames'}, callback: function(data){
			var tlist = json_decode(data);
			for (var i=0; i<tlist.length; i++) projectlist.push(tlist[i]);
			list_capsule.push(1);
		}});
	else list_capsule.push(1);
	server({opts: {command: 'read_projectnames'}, callback: function(data){
		var tlist = json_decode(data);
		for (var i=0; i<tlist.length; i++) projectlist.push(tlist[i]);
		list_capsule.push(1);
	}});
}

pb.switchToPanel = function(panel, fit){

	setTimeout(function(){$('#dialog-mousecatch, #hideall').fadeOut();}, 10);

	$('.outlined').removeClass('outlined');
	$('.first').removeClass('first');

	if (pb.currentpanel == panel) return;
	var oind = 0; var nind = 1;
	if (pb.currentpanel){
		oind = pb.searchArrayById(pb.user.panels, pb.currentpanel.element.id);
		nind =  pb.searchArrayById(pb.user.panels, panel.element.id);
	}
	
	pb.currentpanel = panel; pb.currentpanel.element.style.marginLeft = '0px';
	
	if (pb.currentpanel){
		if (pb.user.panels[pb.user.panels.indexOf(pb.currentpanel)]){
			var amount = (pb.user.panels.indexOf(pb.currentpanel)) * (-78);
			tweencss({object: $( '#labels' )[0], time: 0.5,
				props: {left: parseInt($( '#labels' )[0].style.left)}, to: {left: (234+amount)}});
		}
	} 
	
	$('#panel-name-input').val(pb.currentpanel.core.name);
	$('#panel-width-input').val(parseInt(pb.currentpanel.element.style.width));
	$('#panel-height-input').val(parseInt(pb.currentpanel.element.style.height));

	if (nind - oind > 0){
	
		var panelspaceR = $('.panel-space-right')[0];
		while (panelspaceR.lastChild){
			panelspaceR.removeChild(panelspaceR.lastChild);
		}
		$('.panel-space-right').append(panel.element);

		$(".panel_label").css({opacity: 0.3});
		$('#'+pb.currentpanel.core.id +'_label').css({opacity: 1.0});

		$('.panel-space-right, .panel-space-center, .panel-space-left' ).css({display: 'block'});
	
		tweencss({object: $('.panel-space-right')[0], time: 1,
				props: {opacity: $('.panel-space-right')[0].style.opacity, left: (window.innerWidth/2)+(window.innerWidth/3.0), rotationY: Math.PI/2}, 
				to: {opacity: 1, left: (-$($( '.panel-space-right' )[0].lastChild).outerWidth()/2 + window.innerWidth/2), rotationY: 0},
				transformPerspective: 16500, transformOrigin:"center center -1500", transformStyle: 'preserve-3d'});
		tweencss({object: $('.panel-space-center')[0], time: 1,
				props: {opacity: $('.panel-space-center')[0].style.opacity, left: parseInt($('.panel-space-center')[0].style.left), rotationY: 0}, 
				to: {opacity: 0, left: (window.innerWidth/2)-(window.innerWidth/2.7), rotationY: -Math.PI/2},
				transformPerspective: 16500, transformOrigin:"center center -1500", transformStyle: 'preserve-3d'});
		tweencss({object: $('.panel-space-left')[0], time: 1,
				props: {opacity: $('.panel-space-left')[0].style.opacity, left: (window.innerWidth/2)-(window.innerWidth/3.0), rotationY: -Math.PI/2}, 
				to: {opacity: 0, left: (window.innerWidth/2)+(window.innerWidth/2.7), rotationY: Math.PI/2},
				transformPerspective: 16500, transformOrigin:"center center -1500", transformStyle: 'preserve-3d',
				onComplete: function(){$( '.panel-space-right, .panel-space-left' ).css({display: 'none'});}});
		
		setTimeout(function(){
			$('.panel-space-right, .panel-space-left').css({left: '-90000px', display: 'none'});
		}, 1000);
		
		var right = $('.panel-space-right');
		var center = $('.panel-space-center');
		var left = $('.panel-space-left' );
		right.addClass('panel-space-center').removeClass('panel-space-right');
		center.addClass('panel-space-left').removeClass('panel-space-center');
		left.addClass('panel-space-right').removeClass('panel-space-left');
				
	}
	else {
	
		var panelspaceR = $('.panel-space-left')[0];
		while (panelspaceR.lastChild){panelspaceR.removeChild(panelspaceR.lastChild);}
		$('.panel-space-left').append(panel.element);

		$(".panel_label").css({opacity: 0.3});
		$("#"+pb.currentpanel.core.id +"_label").css({opacity: 1.0});

		$('.panel-space-right, .panel-space-center, .panel-space-left' ).css({display: 'block'});
	
		tweencss({object: $('.panel-space-right')[0], time: 1,
				props: {opacity: $('.panel-space-right')[0].style.opacity, left: (window.innerWidth/2)+(window.innerWidth/3.0), rotationY: Math.PI/2}, 
				to: {opacity: 0, left: (window.innerWidth/2)-(window.innerWidth/2.7), rotationY: -Math.PI/2},
				transformPerspective: 16500, transformOrigin:"center center -1500", transformStyle: 'preserve-3d'});
		tweencss({object: $('.panel-space-center')[0], time: 1,
				props: {opacity: $('.panel-space-center')[0].style.opacity, left: parseInt($('.panel-space-center')[0].style.left), rotationY: 0}, 
				to: {opacity: 0, left: (window.innerWidth/2)+(window.innerWidth/2.7), rotationY: Math.PI/2},
				transformPerspective: 16500, transformOrigin:"center center -1500", transformStyle: 'preserve-3d'});
		tweencss({object: $('.panel-space-left')[0], time: 1,
				props: {opacity: $('.panel-space-left')[0].style.opacity, left: (window.innerWidth/2)-(window.innerWidth/3.0), rotationY: -Math.PI/2}, 
				to: {opacity: 1, left: (-$($( '.panel-space-left' )[0].lastChild).outerWidth()/2 + window.innerWidth/2), rotationY: 0},
				transformPerspective: 16500, transformOrigin:"center center -1500", transformStyle: 'preserve-3d',
				onComplete: function(){$( '.panel-space-right, .panel-space-left' ).css({display: 'none'});}});
				
		setTimeout(function(){$('.panel-space-right, .panel-space-left').css({left: '-90000px', display: 'none'});}, 1000);	
		
		var right = $('.panel-space-right');
		var center = $('.panel-space-center');
		var left = $('.panel-space-left');
		right.addClass('panel-space-left').removeClass('panel-space-right');
		center.addClass('panel-space-right').removeClass('panel-space-center');
		left.addClass('panel-space-center').removeClass('panel-space-left');
	}
	 
	if (oldIE) $('.panel-space-right, .panel-space-left').css({display: 'none'});
	
	var drop = pb.currentpanel.element;  
	addEventHandler(drop, 'dragstart', cancelEvent);
	addEventHandler(drop, 'dragover', cancelEvent);
	addEventHandler(drop, 'dragenter', cancelEvent);
	addEventHandler(drop, 'drop', function(e){
		e = e || window.event;   
		if (e.preventDefault) e.preventDefault();
		if (pb.mouse.elementover != pb.currentpanel.element) return;
		var dt = e.dataTransfer; var files = dt.files; var file = files[0]; var fd = new FormData();
		fd.append("image", file);
		var opts = {command: 'write_image'};
		if (pb.project.puid) opts.puid = pb.project.puid;
		fd.append("opts", JSON.stringify(opts));
		server({formdata: fd, callback: function(data){
			var tstr = data;
			var fstr = tstr.substring(tstr.indexOf('projects/')+9, tstr.indexOf('/images/'));
			pb.project.puid = fstr;
			pb.currentpanel.element.style.backgroundImage = 'url(' + data + ')';
			pb.currentpanel.element.style.backgroundSize = '100% 100%';
			var found = false;
			for (var i=0; i<pb.assets['user'].length; i++)
				if (pb.assets['user'][i].core.data == data) found = true;
			if (!found){
				var newasset = new Asset({data: data});
				newasset.element.style.backgroundImage = 'url(' + data + ')';
				newasset.element.style.backgroundSize = '100% 100%';
				newasset.element.className += ' cloneable draggable';
				$('#assets-images-pane-list').append(newasset.element);
			}
			pb.checkDiskSize();
		}});
		return false;
	});
	
	if (pb.currentpanel.core.autoresize) $('#panel-autoresize-input').prop('checked', true);
	else $('#panel-autoresize-input').prop('checked', false);
	
	if (pb.currentpanel.core.defaultpanel) $('#panel-default-input').prop('checked', true);
	else $('#panel-default-input').prop('checked', false);
	
	$('#panel-bgColorSelector div').css({backgroundColor: pb.currentpanel.element.style.backgroundColor});
	
	$(pb.currentpanel.element).css({ 
		'transform': 'scale('+pb.currentpanel.core.scale+','+
			pb.currentpanel.core.scale+')',
		'-webkit-transform': 'scale('+pb.currentpanel.core.scale+','+
			pb.currentpanel.core.scale+')',
		'-moz-transform': 'scale('+pb.currentpanel.core.scale+','+
			pb.currentpanel.core.scale+')',
		'-ms-transform': 'scale('+pb.currentpanel.core.scale+','+
			pb.currentpanel.core.scale+')'
	});
	
	if (fit) $('#fit-button').click();
	
	if (pb.currentpanel.element.style.backgroundColor == 'white') var rgb = [255,255,255];
	else var rgb = pb.currentpanel.element.style.backgroundColor.match(/\d+/g);
	if (!rgb) rgb = [255,255,255]; $('#panelBGcolor')[0].color.fromRGB(rgb[0]/255, rgb[1]/255, rgb[2]/255);
	
	$('#_no_panels_added').hide();
	pb.updateTree();

}

pb.rotatePanelsLeft = function(){

	if (pb.currentpanel){
		if (pb.user.panels[pb.user.panels.indexOf(pb.currentpanel)-1]) {
			pb.currentpanel = pb.user.panels[pb.user.panels.indexOf(pb.currentpanel)-1];
			pb.currentpanel.element.style.marginLeft = '0px';
			var amount = (pb.user.panels.indexOf(pb.currentpanel)) * (-78);
			TWEEN.removeAll();
			tweencss({object: $( '#labels' )[0], time: 0.5, props: {left: parseInt($( '#labels' )[0].style.left)}, to: {left: (234+amount)}});
		} else return;
	} else return;
	
	$(".panel_label").css({opacity: 0.3});
	$("#"+pb.currentpanel.core.id+"_label").css({opacity: 1.0});
	
	document.getElementById('panel-name-input').value = pb.currentpanel.core.name;
	document.getElementById('panel-width-input').value = parseInt(pb.currentpanel.element.style.width);
	document.getElementById('panel-height-input').value = parseInt(pb.currentpanel.element.style.height);
	
	var panelspaceL = $('.panel-space-left')[0];
	while (panelspaceL.lastChild) {
		panelspaceL.removeChild(panelspaceL.lastChild);
	}
	$('.panel-space-left').append(pb.currentpanel.element);

	$( '.panel-space-right, .panel-space-center, .panel-space-left' ).css({display: 'block'});
	$('.panel-space-right').css({opacity: 0});
	$('.panel-space-left').css({opacity: 0});
	
	tweencss({object: $('.panel-space-right')[0], time: 1,
				props: {opacity: $('.panel-space-right')[0].style.opacity, left: (window.innerWidth/2)+(window.innerWidth/3.0), rotationY: Math.PI/2}, 
				to: {opacity: 0, left: (window.innerWidth/2)-(window.innerWidth/2.7), rotationY: -Math.PI/2},
				transformPerspective: 16500, transformOrigin:"center center -1500", transformStyle: 'preserve-3d'});
	tweencss({object: $('.panel-space-center')[0], time: 1,
				props: {opacity: $('.panel-space-center')[0].style.opacity, left: parseInt($('.panel-space-center')[0].style.left), rotationY: 0}, 
				to: {opacity: 0, left: (window.innerWidth/2)+(window.innerWidth/2.7), rotationY: Math.PI/2},
				transformPerspective: 16500, transformOrigin:"center center -1500", transformStyle: 'preserve-3d'});
	tweencss({object: $('.panel-space-left')[0], time: 1,
				props: {opacity: $('.panel-space-left')[0].style.opacity, left: (window.innerWidth/2)-(window.innerWidth/3.0), rotationY: -Math.PI/2}, 
				to: {opacity: 1, left: (-$($( '.panel-space-left' )[0].lastChild).outerWidth()/2 + window.innerWidth/2), rotationY: 0},
				transformPerspective: 16500, transformOrigin:"center center -1500", transformStyle: 'preserve-3d',
				onComplete: function(){$( '.panel-space-right, .panel-space-left' ).css({display: 'none'});}});
	
	setTimeout(function(){
		$( '.panel-space-right, .panel-space-left' ).css({left: '-90000px', display: 'none'});
	}, 1000);
	
	var right = $( '.panel-space-right' );
	var center = $( '.panel-space-center' );
	var left = $( '.panel-space-left' );
	right.addClass('panel-space-left').removeClass('panel-space-right');
	center.addClass('panel-space-right').removeClass('panel-space-center');
	left.addClass('panel-space-center').removeClass('panel-space-left');
	
	if (oldIE) $( '.panel-space-right, .panel-space-left' ).css({display: 'none'});

	$('.outlined').removeClass('outlined');
	$('.first').removeClass('first');
	
	if (pb.currentpanel.core.autoresize) $('#panel-autoresize-input').prop('checked', true);
	else $('#panel-autoresize-input').prop('checked', false);
	
	if (pb.currentpanel.core.defaultpanel) $('#panel-default-input').prop('checked', true);
	else $('#panel-default-input').prop('checked', false);
	
	$('#panel-bgColorSelector div').css({backgroundColor: pb.currentpanel.element.style.backgroundColor});
	
	if (pb.currentpanel.element.style.backgroundColor == 'white') var rgb = [255,255,255];
	else var rgb = pb.currentpanel.element.style.backgroundColor.match(/\d+/g);
	$('#panelBGcolor')[0].color.fromRGB(rgb[0]/255, rgb[1]/255, rgb[2]/255);
}

pb.rotatePanelsRight = function(){
	
	if (pb.currentpanel){
		if (pb.user.panels[pb.user.panels.indexOf(pb.currentpanel)+1]){
			pb.currentpanel = pb.user.panels[pb.user.panels.indexOf(pb.currentpanel)+1];
			pb.currentpanel.element.style.marginLeft = '0px';
			var amount = (pb.user.panels.indexOf(pb.currentpanel)) * (-78);
			TWEEN.removeAll();
			tweencss({object: $( '#labels' )[0], time: 0.5, props: {left: parseInt($( '#labels' )[0].style.left)}, to: {left: (234+amount)}});
		} else return;
	} else return;
	
	$(".panel_label").css({opacity: 0.3});
	$("#"+pb.currentpanel.core.id+"_label").css({opacity: 1.0});
	
	document.getElementById('panel-name-input').value = pb.currentpanel.core.name;
	document.getElementById('panel-width-input').value = parseInt(pb.currentpanel.element.style.width);
	document.getElementById('panel-height-input').value = parseInt(pb.currentpanel.element.style.height);
	
	var panelspaceR = $('.panel-space-right')[0];
	while (panelspaceR.lastChild) {
		panelspaceR.removeChild(panelspaceR.lastChild);
	}
	$('.panel-space-right').append(pb.currentpanel.element);

	$( '.panel-space-right, .panel-space-center, .panel-space-left' ).css({display: 'block'});
	$('.panel-space-right').css({opacity: 0});
	$('.panel-space-left').css({opacity: 0});

	tweencss({object: $('.panel-space-right')[0], time: 1,
				props: {opacity: $('.panel-space-right')[0].style.opacity, left: (window.innerWidth/2)+(window.innerWidth/3.0),
				rotationY: Math.PI/2}, to: {opacity: 1, left: (-$($( '.panel-space-right' )[0].lastChild).outerWidth()/2 + window.innerWidth/2), 
				rotationY: 0}, transformPerspective: 16500, transformOrigin:"center center -1500", transformStyle: 'preserve-3d'});
	tweencss({object: $('.panel-space-center')[0], time: 1,
				props: {opacity: $('.panel-space-center')[0].style.opacity, left: parseInt($('.panel-space-center')[0].style.left), rotationY: 0}, 
				to: {opacity: 0, left: (window.innerWidth/2)-(window.innerWidth/2.7), rotationY: -Math.PI/2},
				transformPerspective: 16500, transformOrigin:"center center -1500", transformStyle: 'preserve-3d'});
	tweencss({object: $('.panel-space-left')[0], time: 1,
				props: {opacity: $('.panel-space-left')[0].style.opacity, left: (window.innerWidth/2)-(window.innerWidth/3.0),
				rotationY: -Math.PI/2}, to: {opacity: 0, left: (window.innerWidth/2)+(window.innerWidth/2.7), rotationY: Math.PI/2},
				transformPerspective: 16500, transformOrigin:"center center -1500", transformStyle: 'preserve-3d',
				onComplete: function(){$( '.panel-space-right, .panel-space-left' ).css({display: 'none'});}});
				
	setTimeout(function(){
		$( '.panel-space-right, .panel-space-left' ).css({left: '-90000px', display: 'none'});
	}, 1000);
	
	var right = $( '.panel-space-right' );
	var center = $( '.panel-space-center' );
	var left = $( '.panel-space-left' );
		right.addClass('panel-space-center').removeClass('panel-space-right');
		center.addClass('panel-space-left').removeClass('panel-space-center');
		left.addClass('panel-space-right').removeClass('panel-space-left');
	
	if (oldIE) $( '.panel-space-right, .panel-space-left' ).css({display: 'none'});
	
	$('.outlined').removeClass('outlined');
	$('.first').removeClass('first');
	
	if (pb.currentpanel.core.autoresize) $('#panel-autoresize-input').prop('checked', true);
	else $('#panel-autoresize-input').prop('checked', false);
	
	if (pb.currentpanel.core.defaultpanel) $('#panel-default-input').prop('checked', true);
	else $('#panel-default-input').prop('checked', false);
	
	$('#panel-bgColorSelector div').css({backgroundColor: pb.currentpanel.element.style.backgroundColor});
	
	if (pb.currentpanel.element.style.backgroundColor == 'white') var rgb = [255,255,255];
	else var rgb = pb.currentpanel.element.style.backgroundColor.match(/\d+/g);
	$('#panelBGcolor')[0].color.fromRGB(rgb[0]/255, rgb[1]/255, rgb[2]/255);
}

pb.importButtonLibrary = function(data){
	data = json_decode(data); if (!data) return;
	//pb.user.buttons = []; $(document.getElementById('User Buttons')).html('');
	for (var j=0;j<data.buttons.length;j++){
		var button = new Button({core: data.buttons[j].core, isuserbutton: true});
		pb.user.buttons.push(button);
		$('#User\\ Buttons').append(button.element);
		button.draggable = true; button.panel = false;
		button.element.style.cssText += 'background-size: 100% 100%; position: relative; margin: 5px;';
		button.element.className += ' draggable cloneable';
		button.setState();
	}
	$('#button-library-select').val('User Buttons');
	$('#button-library-select')[0].onchange();
}

pb.importTemplateLibrary = function(data){

	data = json_decode(data); if (!data) return; console.log('importing data', data);
	
	for (var i=0; i<data.templates.length; i++){

		var loadpanel = data.templates[i]; loadpanel.core.autoinsert = true;
		
		var thispanel = new Panel({core: loadpanel.core, copyid: true});
		
		//console.log('---', loadpanel, thispanel);
		
		$('#templatesGrid').append(thispanel.element);
		thispanel.draggable = true;
		thispanel.element.style.cssText += ' background-size: 100% 100%; position: relative; margin: 5px; display: inline-block;';
		thispanel.element.className += 'draggable cloneable';
		thispanel.element.style.backgroundSize = "100% 100%";
		thispanel.scale = 1;
		$(thispanel.element).css('transform', 'scale('+thispanel.scale+','+thispanel.scale+')');
		
		thispanel.buttons = [];
		
		var switchers = [];
		
		for (var j=0;j<loadpanel.buttons.length;j++){

			var old = loadpanel.buttons[j].core.id;
		
			var nbutton = new Button({core: loadpanel.buttons[j].core, copyid: true})
		
			thispanel.buttons.push(nbutton);
			
			switchers.push({old: old, current: nbutton.core.id});
			
			try {
				var thisbutton = thispanel.buttons[j];
				thisbutton.element.style.backgroundSize = "100% 100%";
				
				thisbutton.setState(1);
				$(thisbutton.element).removeClass('draggable'); $(thisbutton.element).removeClass('cloneable');
				$(thispanel.element).append(thisbutton.element);
				$('#'+thisbutton.id+'_text').attr('contenteditable', false);
				if (thisbutton.textnode && thisbutton.textnode.lastChild) 
					thisbutton.textnode.lastChild.onselectstart = function(e){e.preventDefault(); return false;};
				
				thisbutton.element.title = '';
				$(thisbutton.element).addClass('item_child');
				thisbutton.panel = thispanel;
			}
			catch (e){}
			
		}
		thispanel.widgets = [];
		for (var j=0;j<loadpanel.widgets.length;j++){
			//console.log('template widget', j);
			try {
				var newparts = [];
				for (var k=0;k<loadpanel.widgets[j].parts.length;k++){
					var twidgetpart = new WidgetPart({
						core: loadpanel.widgets[j].parts[k].core,
						copyid: true,
						//name: panel.widgets[j].name,
						//id: panel.widgets[j].id,
						//type: loadpanel.widgets[j].type,
						width: loadpanel.widgets[j].parts[k].width,
						height: loadpanel.widgets[j].parts[k].height,
						scale: loadpanel.widgets[j].parts[k].scale,
						style: loadpanel.widgets[j].parts[k].style,
						basewidth: loadpanel.widgets[j].parts[k].basewidth,
						baseheight: loadpanel.widgets[j].parts[k].baseheight,
						basetop: loadpanel.widgets[j].parts[k].basetop,
						baseleft: loadpanel.widgets[j].parts[k].baseleft,
						init: loadpanel.widgets[j].parts[k].init || noop,
						update: loadpanel.widgets[j].parts[k].update || noop,
						className: loadpanel.widgets[j].parts[k].className,
						states: loadpanel.widgets[j].parts[k].states,
						innerhtml: loadpanel.widgets[j].parts[k].innerhtml,
						script: loadpanel.widgets[j].parts[k].script,
						conditional: loadpanel.widgets[j].parts[k].conditional,
						resize: loadpanel.widgets[j].parts[k].resize || noop,
						moving: loadpanel.widgets[j].parts[k].moving || noop,
						click: loadpanel.widgets[j].parts[k].click || noop,
						clickup: loadpanel.widgets[j].parts[k].clickup || noop,
						drop: loadpanel.widgets[j].parts[k].drop || noop,
						hoverin: loadpanel.widgets[j].parts[k].hoverin || noop,
						hoverout: loadpanel.widgets[j].parts[k].hoverout || noop,
						ontopanel: loadpanel.widgets[j].parts[k].ontopanel || noop,
						doubleclick: loadpanel.widgets[j].parts[k].doubleclick || noop,
					});
					twidgetpart.element.style.backgroundSize = '100% 100%';
					newparts.push(twidgetpart);
					
					try {
						if (!undef(loadpanel.widgets[j].parts[k].innerhtml)) newparts[k].element.innerHTML = loadpanel.widgets[j].parts[k].innerhtml;
						else newparts[newparts.length-1].element.innerHTML = '';
						//console.log(loadpanel.widgets[j].parts[k].core); console.log(loadpanel.widgets[j].parts[k].core.elementHTML);
						if (loadpanel.widgets[j].parts[k].core && loadpanel.widgets[j].parts[k].core.elementHTML) newparts[k].element.innerHTML = loadpanel.widgets[j].parts[k].core.elementHTML;
					} catch(e){console.log('gote',e);}
				}
			
				var old = loadpanel.widgets[j].core.id;
				
				var nwidget = new Widget({
					core: loadpanel.widgets[j].core,
					parts: newparts,
					init: loadpanel.widgets[j].init || noop,
					update: loadpanel.widgets[j].update || noop,
					hoverin: loadpanel.widgets[j].hoverin || noop,
					hoverout: loadpanel.widgets[j].hoverout || noop,
					ontopanel: loadpanel.widgets[j].ontopanel || noop,
					doubleclick: loadpanel.widgets[j].doubleclick || noop,
					resize: loadpanel.widgets[j].resize || noop,
					copyid: true
				});
				
				//console.log("CREATING WIDGET", nwidget);
			
				thispanel.widgets.push(nwidget);
				//var thiswidget = thispanel.widgets[thispanel.widgets.length-1];
				
				switchers.push({old: old, current: nwidget.core.id});
				
				$(nwidget.element).click(function(event){});
				$(nwidget.element).removeClass('draggable');
				$(thispanel.element).append(nwidget.element);

				nwidget.element.title = '';
				$(nwidget.element).addClass('item_child');
			} catch(e){console.log('gote',e);}
		}

		for (var j=0;j<thispanel.widgets.length; j++){
			thispanel.widgets[j].panel = thispanel;
			for (var k=0;k<thispanel.widgets[j].parts.length; k++){
				thispanel.widgets[j].parts[k].init();
			}
		}
		
		thispanel.subpanels = [];
		
		if (loadpanel.subpanels) for (var j=0;j<loadpanel.subpanels.length;j++){
			
			if (loadpanel.subpanels[j].core){
				var thissubpanel = new SubPanel({
					core: loadpanel.subpanels[j].core,
					children: loadpanel.subpanels[j].children,
					copyid : true
				});
			}
			else {
				var thissubpanel = new SubPanel({
					id: loadpanel.subpanels[j].id,
					name: loadpanel.subpanels[j].name,
					scale: loadpanel.subpanels[j].scale,
					style: loadpanel.subpanels[j].style,
					className: loadpanel.subpanels[j].className,
					conditional: loadpanel.subpanels[j].conditional,
					touchpanelkey: loadpanel.subpanels[j].touchpanelkey,
					children: loadpanel.subpanels[j].children
				});
			}
			thispanel.subpanels.push(thissubpanel);
			
			//console.log('switchers', switchers);
			
			if (0) for (var k=0; k<loadpanel.subpanels[j].children.length; k++){
				//console.log('looping k?', loadpanel.subpanels[j].children, switchers.length);
				/*for (var qq=0; qq<switchers.length; qq++){
					console.log("comparing", switchers[qq].old, loadpanel.subpanels[j].children[k].core.id);
					if (switchers[qq].old === loadpanel.subpanels[j].children[k].core.id) thissubpanel.children.push(switchers[qq].current);
				}*/
				for (var s=0; s<switchers.length; s++){
					//console.log('hello?');
					//console.log("comparing", switchers[s], loadpanel.subpanels[j].children[k]);
					try {
						if (switchers[s].old === loadpanel.subpanels[j].children[k]) thissubpanel.children.push(switchers[s].current);
					} catch (e){console.log(e);}
				}
			}
			for (var k=0; k<thissubpanel.children.length; k++){
				
				
				
				
				var child = get(thissubpanel.children[k]); if (!child) continue;
				child.subpanel = thissubpanel.core.id;
				
				//var _cbox = child.element.getBoundingClientRect();
				//console.log('setting', child.core.id);
				//child._x = _cbox.left - _bbox.left - _pbox.left;
				//child._y = _cbox.top - _bbox.top - _pbox.top;
			}
			/*thissubpanel.element.className = 'draggable';
			thispanel.addChild(thissubpanel);
			thissubpanel.makeResizable();
			var _bbox = thissubpanel.element.getBoundingClientRect();
			var _pbox = thispanel.element.getBoundingClientRect();
			for (var k=0; k<thissubpanel.children.length; k++){
				var child = get(thissubpanel.children[k]); if (!child) continue;
				child.subpanel = thissubpanel.core.id;
				
				var _cbox = child.element.getBoundingClientRect();
				//console.log('setting', child.core.id);
				child._x = _cbox.left - _bbox.left - _pbox.left;
				child._y = _cbox.top - _bbox.top - _pbox.top;
			}*/

			
		}
		
		thispanel.resize(80,80);
	}
	
}

pb.addUserButton = function(button){
	if (undef(button)){
		var newstates = clone(itemEditor.tempitem.states);
		if (itemEditor.item){
			var ttext = itemEditor.item.textnode.innerHTML;
			var ttextoffsetx = itemEditor.item.textoffsetx ? itemEditor.item.textoffsetx : 0;
			var ttextoffsety = itemEditor.item.textoffsety ? itemEditor.item.textoffsety : 0;
		}
		else {
			var ttext = 'text';
			var ttextoffsetx = 0;
			var ttextoffsety = 0;
		}
		var newbutton = new Button({
			states: newstates,
			draggable: true,
			text: ttext,
			textoffsetx: ttextoffsetx,
			textoffsety: ttextoffsety,
			textstyle: itemEditor.item.textnode.style.cssText,
			basewidth: parseInt(document.getElementById('item-preview').style.width),
			baseheight: parseInt(document.getElementById('item-preview').style.height),
			scripts: itemEditor.tempitem.scripts,
			conditional: itemEditor.tempitem.conditional,
			extrastyle: document.getElementById('item-preview').style.cssText,
			isuserbutton: true
		});
		$('#User\\ Buttons').append(newbutton.element);
		newbutton.draggable = true;
		newbutton.element.style.cssText += 'background-size: 100% 100%; position: relative; margin: 4px; display: inline-block;';
		newbutton.element.className = 'draggable cloneable';
		newbutton.textnode.style.zIndex = '10000000';
		
		var previewarea = document.getElementById('item-preview-panel');
		var preview = document.getElementById('item-preview');
		
		newbutton.setState();
		
		newbutton.element.style.width = newbutton.element.style.height = '80px';
		newbutton.element.style.margin = '4px';
		document.getElementById('item-preview').style.outline = 'invert none medium';
		newbutton.element.style.cssText += document.getElementById('item-preview').style.cssText;
		newbutton.element.style.cssText += 'position: relative; float: left; background-size: 100% 100%;\
			left: 0; top: 0; outline: invert none medium; margin: 4px; border-size: 0px;';
		
		if (!undef(itemEditor.tempitem.touchpanelkey)) newbutton.touchpanelkey = itemEditor.tempitem.touchpanelkey;
		itemEditor.tempitem.touchpanelkey = false;
		
		newbutton.element.style.boxShadow = preview.style.boxShadow;
		
		delete itemEditor.tempitem;
		closeItemEditor(false);
		
	}
	else {
		var newbutton = button.clone({type: 'user'});
	
		$('#User\\ Buttons').append(newbutton.element);
		newbutton.draggable = true;
		newbutton.element.style.cssText += 'left: 0; top: 0; background-size: 100% 100%; position: relative; margin: 5px; display: inline-block;';
		newbutton.element.className = 'draggable cloneable';
		
		tweencss({object: $( newbutton.element )[0], time: 0, props: {scale: 1}, to: {scale: 1}});
	}

	newbutton.panel = false;
	
	$('#button-library-select').val('User Buttons');
	pb.setButtonLibrary();
}

pb.addTemplateFromPanel = function(panel){

	var oldbuttonids = []; var oldwidgetids = [];
	var newbuttonids = []; var newwidgetids = [];
	
	for (var pk=0; pk<panel.buttons.length; pk++){
		oldbuttonids.push(panel.buttons[pk].element.id);
	}
	for (var pk=0; pk<panel.widgets.length; pk++){
		oldwidgetids.push(panel.widgets[pk].element.id);
	}
	
	var newpanel = panel.clone({type: 'template', autoinsert: true});
	
	for (var pk=0; pk<newpanel.buttons.length; pk++){
		newbuttonids.push(newpanel.buttons[pk].element.id);
	}
	for (var pk=0; pk<newpanel.widgets.length; pk++){
		newwidgetids.push(newpanel.widgets[pk].element.id);
	}
	
	for (var pk=0; pk<newpanel.buttons.length; pk++){
		if (newpanel.buttons[pk].scripts){
			for (var jk=0; jk<newpanel.buttons[pk].scripts.length; jk++){
				for (var pj=0; pj<oldbuttonids.length; pj++){
					newpanel.buttons[pk].scripts[jk] = 
						newpanel.buttons[pk].scripts[jk].replaceAll(oldbuttonids[pj], newbuttonids[pj]);
				}
			}
		}
	}
	for (var pk=0; pk<newpanel.widgets.length; pk++){
		if (newpanel.widgets[pk].scripts){
			for (var jk=0; jk<newpanel.widgets[pk].scripts.length; jk++){
				for (var pj=0; pj<oldwidgetids.length; pj++){
					newpanel.widgets[pk].scripts[jk] = 
						newpanel.widgets[pk].scripts[jk].replaceAll(oldwidgetids[pj], newwidgetids[pj]);
				}
			}
		}
	}
	
	for (var i=0; i<newpanel.buttons.length; i++){
		var tbutton = newpanel.buttons[i];
		$(tbutton.element).removeClass('outlined').removeClass('first');
		$(tbutton.element).addClass('item_child');
		//tbutton.basewidth = parseInt(newpanel.buttons[i].element.style.width);
		//tbutton.baseheight = parseInt(newpanel.buttons[i].element.style.height);
		//tbutton.basetop = parseInt(newpanel.buttons[i].element.style.top);
		//tbutton.baseleft = parseInt(newpanel.buttons[i].element.style.left);
	}
	for (var i=0; i<newpanel.widgets.length; i++){
		var twidget = newpanel.widgets[i];
		$(twidget.element).removeClass('outlined').removeClass('first');
		$(twidget.element).addClass('item_child');
		//twidget.basewidth = parseInt(newpanel.widgets[i].element.style.width);
		//twidget.baseheight = parseInt(newpanel.widgets[i].element.style.height);
		//twidget.basetop = parseInt(newpanel.widgets[i].element.style.top);
		//twidget.baseleft = parseInt(newpanel.widgets[i].element.style.left);
		twidget.element.style.display = 'none';
	}
	
	newpanel.element.style.transform = "scale(1,1)";
	newpanel.element.style.webkitTransform = "scale(1,1)";
	newpanel.element.style.mozTransform = "scale(1,1)";
	newpanel.element.style.msTransform = "scale(1,1)";

	newpanel.resize(80,80);
	
	$('#templatesGrid').append(newpanel.element);
	newpanel.element.style.cssText += ' background-size: 100% 100%; position: relative; margin: 5px; display: inline-block;';
	newpanel.element.className += ' draggable cloneable';
	
	newpanel.element.style.width = newpanel.element.style.height = '80px';
	newpanel.element.style.margin = '4px';
	newpanel.element.style.cssText += 'position: relative; float: left; background-size: 100% 100%; width: 80px;\
		height: 80px; left: 0; top: 0; outline: invert none medium; margin: 4px; border-size: 0px;';
	
	newpanel.core.style = newpanel.element.style.cssText;
	newpanel.basewidth = parseFloat(panel.element.style.width);
	newpanel.baseheight = parseFloat(panel.element.style.height);
	
	var rgb = pb.currentpanel.element.style.backgroundColor.match(/\d+/g);
	if (!rgb) rgb = [255,255,255];
	$('#panelBGcolor')[0].color.fromRGB(rgb[0]/255, rgb[1]/255, rgb[2]/255);
	
}
