/******************************************************************************
@owner: SVSi
@author: Arthur Johnson
@functions: PanelBuilder Program Initialization
@setupPB
*******************************************************************************/
function setupPB(){
	
	pb.updating = true;
	pb.snap_to_panel = true;
	pb.mouse = new MouseControls({responsive: true});
	
	pb.default_theme = 'ace/theme/vibrant_ink';
	
	var code_editors = ['maineditor', 'scripteditor', 
		'ntouchleditor', 'ntouchmeditor', 'ntouchreditor'];
	for (var i=0; i<code_editors.length; i++){
		window[code_editors[i]] = ace.edit(code_editors[i]+'_code');
		window[code_editors[i]].setTheme(pb.default_theme);
		window[code_editors[i]].getSession().setMode('ace/mode/javascript');
		window[code_editors[i]].setDisplayIndentGuides(true);
		window[code_editors[i]].getSession().setUseWrapMode(true);
		window[code_editors[i]].setOptions({enableBasicAutocompletion: true});
		window[code_editors[i]].setOptions({enableLiveAutocompletion: true});
		window[code_editors[i]].setOptions({enableSnippets: true});
		window[code_editors[i]].setShowPrintMargin(false);
	}
	
	setEditorScripts('maineditor', $('#maineditor')[0], maineditor);
	setEditorScripts('scripteditor', $('#scripteditor')[0], scripteditor);
	setEditorScripts('ntouchleditor', $('#ntouchleditor')[0], ntouchleditor);
	setEditorScripts('ntouchmeditor', $('#ntouchmeditor')[0], ntouchmeditor);
	setEditorScripts('ntouchreditor', $('#ntouchreditor')[0], ntouchreditor);

	setTimeout(function(){
		if (wizard){
			$('#wizard-choice').show();
			$('#wizard-choice').cssAnim('fadeInLeft', function(){
				$('.wizard-choice').show(); $('.wizard-choice').cssAnim('fadeInDown', function(){
					$('#wizard-choice-editor, #wizard-choice-wizard').data('clickable', true);
				}, 0.5);
			}, 0.5);
		}
		else {
			$('#project-options').show();
			$('#project-options').cssAnim('fadeInRight', function(){
				$('.project-options').show(); $('.project-options').cssAnim('fadeInDown', function(){
					
				}, 0.5);
			}, 0.5);
		}
	}, 1000);
	$('#wizard-choice-editor')[0].onclick = function(){
		if (!$(this).data('clickable')) return;
		$('#wizard-choice').cssAnim('fadeOutRight', function(){
			$('#wizard-choice').hide();
		}, 0.5);
		setTimeout(function(){
			$('#hideall').hide();
			$('#project-options').show();
			$('#project-options').cssAnim('fadeInRight', function(){
				setTimeout(function(){$('.project-options').show(); $('.project-options').cssAnim('fadeInDown', noop, 0.5);}, 200);
			}, 0.5);
		}, 800);
	};
	$('#wizard-choice-wizard')[0].onclick = function(){
		if (!$(this).data('clickable')) return;
		$('#wizard-choice').cssAnim('fadeOutRight', function(){
			$('#wizard-choice').hide();
		}, 0.5);
		setTimeout(function(){
			$('#wizard, #wizard_step2').show();
			$('#hideall').fadeOut();
			wizardStart();
		}, 800);
	};
	$('#project-options-recent-select')[0].onchange = function(){
		
		$('#project-options').cssAnim('fadeOutLeft', function(){
			$('#project-options').hide();
			pb.loadRecent();
			$('#project-options-recent-select').val('-1');
			$('#dialog-mousecatch').fadeOut();
		}, 0.5);
		
	};
	$('#project-options-new')[0].onclick = function(){
		$('#project-options').cssAnim('fadeOutLeft', function(){
			$('#project-options').hide();
			pb.loadProject({new: true});
		}, 0.5);
	};
	$('#resourcesidebar').click(function(){
		if (resourceopener){
			resourceopener = false;
			$('#resourcesidebar img').removeClass('fliph');
		}
		else {
			resourceopener = true;
			$('#resourcesidebar img').addClass('fliph');
		}
	});
	$('#toolsidebar').click(function(){
		if (toolopener){
			toolopener = false;
			$('#toolsidebar img').addClass('fliph');
		}
		else {
			toolopener = true;
			$('#toolsidebar img').removeClass('fliph');
		}
	});
	/*$('#button-library-delete')[0].onclick = function(){
		for (var k=0; k<$('.buttonlibraryselected').length; k++){
			removeFromArray(pb.user.buttons, pb.getItemById($('.buttonlibraryselected')[k].id));
		}
		$('.buttonlibraryselected').remove();
	};*/
	
	$('#button-library-import')[0].onclick = function(){
		document.getElementById('file-open').accept = '.zip';
		pb.openFileBrowser(function(){
			sendFile($("#file-open")[0].files[0], {command: 'import_buttons', puid: ''+pb.project.core.puid}, noop);
		});
	};
	$('#button-library-export')[0].onclick = function(){
		if (!pb.project.core.puid){
			pb.openDialog({content: 'You must save your project before exporting.', title: 'Notice', confirm: false, cancel: 'ok'});
			return;
		}
		var userbuttons = [];
		var checkButtons = function(){
			for (var i=0; i<pb.user.buttons.length; i++){
				for (var j=0; j<pb.user.buttons.length; j++){
					if (i==j) continue;
					if (pb.user.buttons[i].core.id === pb.user.buttons[j].core.id){
						removeFromArray(pb.user.buttons, pb.user.buttons[j]);
						checkButtons();
						return;
					}
				}
			}
		}
		checkButtons();
		for (var k=0; k<pb.user.buttons.length; k++){
			if (!pb.user.buttons[k].panel && pb.user.buttons[k].element.parentNode &&
				pb.user.buttons[k].element.parentNode.id === 'User Buttons')
				userbuttons.push(pb.buttonToJSON(pb.user.buttons[k]));
		}
		var obj = {puid: pb.project.core.puid, buttons: userbuttons};
		websocket.emit('message', {command: 'export_buttons', data: obj, id: pb.project.core.puid}, 
			function(data){console.log(data);});
	};
	$('#templatesGrid').click(function(){
		for (var i=0; i<$('#templatesGrid')[0].children.length; i++){
			$($('#templatesGrid')[0].children[i]).removeClass('libraryselected');
		}
	});
	$('#import-template-panel').click(function(){
		document.getElementById('file-open').accept = '.zip';
		pb.openFileBrowser(function(){
			console.log('sending sending...', pb.project.core.puid);
			sendFile($("#file-open")[0].files[0], {command: 'import_templates', puid: ''+pb.project.core.puid}, noop);
		});
	});
	$('#export-template-panel').click(function(){
		if (!pb.project.core.puid){
			pb.openDialog({content: 'You must save your project before exporting.', title: 'Notice', confirm: false, cancel: 'ok'});
			return;
		}
		var usertemplates = [];
		for (var k=0; k<pb.user.templates.length; k++){
			usertemplates.push(pb.panelToJSON(pb.user.templates[k]));
		}
		var obj = {puid: pb.project.core.puid, templates: usertemplates};
		websocket.emit('message', {command: 'export_templates', data: obj, id: pb.project.core.puid}, 
			function(data){console.log(data);});
	});
	$('#delete-template').click(function(){
		pb.openDialog({
			content: '<div style="margin: 0px !important;">Delete this template?</div>',
			style: {height: '120px'},
			onConfirm: function(){
				for (var i=0; i<$('.templatelibraryselected').length; i++){
					pb.getItemById($('.templatelibraryselected')[i].id).destroy();
				}
				pb.closeDialog();
			}
		});
	});
	$('#add-template-panel').click(function(){
		pb.addTemplateFromPanel(pb.currentpanel);
	});
	$('#apply-template-panel').click(function(){
		if (!$('.templatelibraryselected').exists()) return;
		if ($('.templatelibraryselected').length == 1){
			var self = pb.getItemById($('.templatelibraryselected')[0].id);
					
			self.drop(pb.currentpanel); console.log('about to return...', self); return;
			
			pb.openDialog({
				content: '<div style="margin: 0px !important;">Replace current panel with this template?</div>',
				style: {height: '120px'},
				onConfirm: function(){
					var panel_onto = pb.currentpanel;
					//working here....
					//console.log('testing?');
					if (1){
						
						//console.log('applytemplate');
						
						pb.openDialog({
							content: '<div style="margin: 0px !important;">Replace current panel with this template?</div>',
							style: {height: '120px'},
							onConfirm: function(){
										
								//var self = this;
								
								var npanel = self.clone({autoinsert: false, id: pb.currentpanel.id});
					///console.log('cloning template...', npanel);
								$(npanel.element).addClass('selectables');
								var cparent = pb.currentpanel.element.parentNode;
								var twidth = parseInt(pb.currentpanel.element.style.width);
								var theight = parseInt(pb.currentpanel.element.style.height);
								$(pb.currentpanel.element).append(npanel.element);
								npanel.element.style.left = '0px';
								npanel.element.style.top = '0px';
								$(pb.currentpanel.element).remove();
								$(cparent).append(npanel.element);
								npanel.resize(twidth, theight);
								npanel.scaleTo(pb.currentpanel.core.scale);
								npanel.element.style.margin = 'none';
								npanel.element.style.marginTop = pb.currentpanel.element.style.marginTop;
								npanel.element.style.marginLeft = pb.currentpanel.element.style.marginLeft;
								
								var oldid = pb.currentpanel.element.id;
								var ind = pb.user.panels.indexOf(pb.currentpanel);
								pb.currentpanel.element.id = '';
								pb.currentpanel.core.id = '';
								pb.user.panels.splice(ind, 1, npanel);
								pb.currentpanel = npanel;
								npanel.core.type = 'panel';
								npanel.core.id = oldid;
								npanel.element.id = oldid;
								
								$('#'+oldid+'_label')[0].onclick = function(){
									pb.switchToPanel(this);
								}.bind(npanel);
								$('#'+oldid+'_label')[0].innerHTML = npanel.core.name;
								$('#panel-name-input').val(npanel.core.name);
								
								//npanel.element.className = 'clonable draggable';
								
								//console.log('dropping...subpanels?', this.subpanels);
								if (npanel.subpanels){
									//npanel.subpanels = [];
									for (var k=0; k<npanel.subpanels.length; k++){
										//var oldsubpanel = this.subpanels[k]; var subpanel = new SubPanel();
										var subpanel = npanel.subpanels[k];
										/*for (var l=0; l<oldsubpanel.children.length; l++){
											subpanel.children.push(oldsubpanel.children[l]);
										}
										var tid = subpanel.core.id;
										subpanel.core = deepCopy(oldsubpanel.core);
										subpanel.core.id = tid;*/
										//npanel.subpanels.push(subpanel);
										
										//$(subpanel.element).height($(oldsubpanel.element).height());
										
										//subpanel.makeDraggable(); 
										
										subpanel.element.className += ' draggable ';
										
										subpanel.panel = npanel;
										//subpanel.panel.addChild(subpanel);
										if (subpanel.element) npanel.element.appendChild(subpanel.element);
										
										subpanel.core.responsive = true;
										
										console.log('subpanel-', subpanel);
										
										subpanel.makeResizable();
										
										subpanel.element.style.width = subpanel.core.actualwidth + 'px';
										subpanel.element.style.height = subpanel.core.actualheight + 'px';
										subpanel.element.style.top = subpanel.core.top + 'px';
										subpanel.element.style.left = subpanel.core.left + 'px';
										
										//for (
										
										
										//subpanel.core.left = parseFloat(subpanel.element.style.left);
										//subpanel.core.top = parseFloat(subpanel.element.style.top);
											
										//tweencss({ object: subpanel.element, time: 0, props: {scale: 1.0}, to: {scale: 1.0} });
										
										//subpanel.core.previouslocation = {top: subpanel.element.style.top, left: subpanel.element.style.left};
										
										//npanel.addChild(subpanel);
									}
								}
								//console.log('npanel subpanels', npanel);
								for (var k=0;k<npanel.buttons.length;k++){
									npanel.buttons[k].element.style.width = self.buttons[k].basewidth + 'px';
									npanel.buttons[k].element.style.height = self.buttons[k].baseheight + 'px';
									npanel.buttons[k].element.style.top = self.buttons[k].basetop + 'px';
									npanel.buttons[k].element.style.left = self.buttons[k].baseleft + 'px';
									$(npanel.buttons[k].element).removeClass('item_child');
									npanel.buttons[k].textnode.style.display = 'block';
									npanel.buttons[k].makeResizable();
									npanel.buttons[k].panel = npanel;					
									npanel.buttons[k].container = npanel.element;	
									npanel.buttons[k].element.className = npanel.buttons[k].element.className.replaceAll('clonable', '');
									npanel.buttons[k].element.className = npanel.buttons[k].element.className.replaceAll('cloneable', '');
								}
								for (var k=0;k<npanel.widgets.length;k++){
									npanel.widgets[k].element.style.width = self.widgets[k].basewidth + 'px';
									npanel.widgets[k].element.style.height = self.widgets[k].baseheight + 'px';
									npanel.widgets[k].element.style.top = self.widgets[k].basetop + 'px';
									npanel.widgets[k].element.style.left = self.widgets[k].baseleft + 'px';
									$(npanel.widgets[k].element).removeClass('item_child');
									npanel.widgets[k].makeResizable();
									npanel.widgets[k].panel = npanel;					
									npanel.widgets[k].container = npanel.element;
									npanel.widgets[k].element.className = npanel.widgets[k].element.className.replaceAll('clonable', '');
									npanel.widgets[k].element.className = npanel.widgets[k].element.className.replaceAll('cloneable', '');
									npanel.widgets[k].element.style.display = 'block';
									if (npanel.widgets[k].parts && npanel.widgets[k].parts[0]) npanel.widgets[k].parts[0].element.style.backgroundSize = '100% 100%';
								}
								
								//pb.setCurrentProjectTree();
								//if (!panel_onto) self.destroy();
								pb.closeDialog();
								$('#fit-button').click();
								
							},
							onCancel: function(){
								//if (!panel_onto) this.destroy();
								pb.closeDialog();
							}.bind(this)
						});
						
					}
					else this.destroy();
					
					/*var oldbuttonids = []; var oldwidgetids = [];
					var newbuttonids = []; var newwidgetids = [];
					
					for (var pk=0; pk<self.buttons.length; pk++){
						oldbuttonids.push(self.buttons[pk].element.id);
					}
					for (var pk=0; pk<self.widgets.length; pk++){
						oldwidgetids.push(self.widgets[pk].element.id);
					}
					
					var npanel = self.clone({autoinsert: false, id: pb.currentpanel.id});
					
					for (var pk=0; pk<npanel.buttons.length; pk++){
						newbuttonids.push(npanel.buttons[pk].element.id);
					}
					for (var pk=0; pk<npanel.widgets.length; pk++){
						newwidgetids.push(npanel.widgets[pk].element.id);
					}
					
					for (var pk=0; pk<npanel.buttons.length; pk++){
						if (npanel.buttons[pk].scripts){
							for (var jk=0; jk<npanel.buttons[pk].scripts.length; jk++){
								for (var pj=0; pj<oldbuttonids.length; pj++){
									npanel.buttons[pk].scripts[jk] = 
										npanel.buttons[pk].scripts[jk].replaceAll(oldbuttonids[pj], newbuttonids[pj]);
								}
							}
						}
					}
					for (var pk=0; pk<npanel.widgets.length; pk++){
						if (npanel.widgets[pk].scripts){
							for (var jk=0; jk<npanel.widgets[pk].scripts.length; jk++){
								for (var pj=0; pj<oldwidgetids.length; pj++){
									npanel.widgets[pk].scripts[jk] = 
										npanel.widgets[pk].scripts[jk].replaceAll(oldwidgetids[pj], newwidgetids[pj]);
								}
							}
						}
					}
					
					$(npanel.element).addClass('selectables');
					var cparent = pb.currentpanel.element.parentNode;
					var twidth = parseInt(pb.currentpanel.element.style.width);
					var theight = parseInt(pb.currentpanel.element.style.height);
					$(pb.currentpanel.element).append(npanel.element);
					npanel.element.style.left = '0px';
					npanel.element.style.top = '0px';
					$(pb.currentpanel.element).remove();
					$(cparent).append(npanel.element);
					npanel.resize(twidth, theight);
					npanel.scaleTo(pb.currentpanel.core.scale);
					npanel.element.style.margin = 'none';
					npanel.element.style.marginTop = pb.currentpanel.element.style.marginTop;
					npanel.element.style.marginLeft = pb.currentpanel.element.style.marginLeft;
					
					var oldid = pb.currentpanel.element.id;
					var ind = pb.user.panels.indexOf(pb.currentpanel);
					pb.currentpanel.element.id = '';
					pb.currentpanel.core.id = '';
					pb.user.panels.splice(ind, 1, npanel);
					pb.currentpanel = npanel;
					npanel.core.type = 'panel';
					npanel.core.id = oldid;
					npanel.element.id = oldid;
					
					$('#'+oldid+'_label')[0].onclick = function(){
						pb.switchToPanel(this);
					}.bind(npanel);
					$('#'+oldid+'_label')[0].innerHTML = npanel.core.name;
					$('#panel-name-input').val(npanel.core.name);
					
					console.log('self?', self, self.subpanels);
					if (self.subpanels){
						npanel.subpanels = [];
						for (var k=0; k<self.subpanels.length; k++){
							var oldsubpanel = self.subpanels[k]; var subpanel = new SubPanel();
							for (var l=0; l<oldsubpanel.children.length; l++){
								subpanel.children.push(oldsubpanel.children[l]);
							}
							var tid = subpanel.core.id;
							subpanel.core = deepCopy(oldsubpanel.core);
							subpanel.core.id = tid;
							//npanel.subpanels.push(subpanel);
							$(subpanel.element).height($(oldsubpanel.element).height());
							
							//subpanel.makeDraggable(); 
							
							subpanel.element.className += ' draggable ';
							
							subpanel.panel = npanel;
							subpanel.panel.addChild(subpanel);
							
							subpanel.core.responsive = true;
							
							console.log('subpanel-', subpanel);
							
							subpanel.makeResizable();
							
							subpanel.element.style.width = subpanel.core.actualwidth + 'px';
							subpanel.element.style.height = subpanel.core.actualheight + 'px';
							subpanel.element.style.top = subpanel.core.top + 'px';
							subpanel.element.style.left = subpanel.core.left + 'px';
							
							//for (
							
							
							//subpanel.core.left = parseFloat(subpanel.element.style.left);
							//subpanel.core.top = parseFloat(subpanel.element.style.top);
								
							//tweencss({ object: subpanel.element, time: 0, props: {scale: 1.0}, to: {scale: 1.0} });
							
							//subpanel.core.previouslocation = {top: subpanel.element.style.top, left: subpanel.element.style.left};
							
							//npanel.addChild(subpanel);
						}
					}
					
					for (var k=0; k<npanel.buttons.length; k++){
						npanel.buttons[k].element.style.width = self.buttons[k].basewidth + 'px';
						npanel.buttons[k].element.style.height = self.buttons[k].baseheight + 'px';
						npanel.buttons[k].element.style.top = self.buttons[k].basetop + 'px';
						npanel.buttons[k].element.style.left = self.buttons[k].baseleft + 'px';
						$(npanel.buttons[k].element).removeClass('item_child');
						npanel.buttons[k].textnode.style.display = 'block';
						npanel.buttons[k].makeResizable();
						npanel.buttons[k].panel = npanel;					
						npanel.buttons[k].container = npanel.element;	
						npanel.buttons[k].element.className = npanel.buttons[k].element.className.replaceAll('clonable', '');
						npanel.buttons[k].element.className = npanel.buttons[k].element.className.replaceAll('cloneable', '');
					}
					for (var k=0; k<npanel.widgets.length; k++){
						npanel.widgets[k].element.style.width = self.widgets[k].basewidth + 'px';
						npanel.widgets[k].element.style.height = self.widgets[k].baseheight + 'px';
						npanel.widgets[k].element.style.top = self.widgets[k].basetop + 'px';
						npanel.widgets[k].element.style.left = self.widgets[k].baseleft + 'px';
						$(npanel.widgets[k].element).removeClass('item_child');
						npanel.widgets[k].makeResizable();
						npanel.widgets[k].panel = npanel;					
						npanel.widgets[k].container = npanel.element;
						npanel.widgets[k].element.className = npanel.widgets[k].element.className.replaceAll('clonable', '');
						npanel.widgets[k].element.className = npanel.widgets[k].element.className.replaceAll('cloneable', '');
						npanel.widgets[k].element.style.display = 'block';
					}
					*/
					
					//pb.setCurrentProjectTree();
					pb.closeDialog();
					$('#fit-button').click();
				}
			});
		}
	});
	
	if (wallcon) ngmodel.wallcon = true;
	else ngmodel.wallcon = false;

	$('#panel-name-input-button').click(function(){
		if (pb.currentpanel === null) return;
		var name = document.getElementById('panel-name-input').value;

		var panel_label = document.getElementById(pb.currentpanel.core.id+'_label');
		panel_label.innerHTML = name;
		$(panel_label).attr('title', name);
		
		pb.currentpanel.core.name = name;
	});
	
	$('#panel-width-input-button').click(function(){
		pb.currentpanel.resize(
			parseFloat($('#panel-width-input').val()), 
			parseFloat(pb.currentpanel.element.style.height)
		);
	});
	
	$('#panel-height-input-button').click(function(){
		pb.currentpanel.resize(
			parseFloat(pb.currentpanel.element.style.width),
			parseFloat($('#panel-height-input').val())
		);
	});
	
	window.__show8301 = false;
	window.___show8301 = false;
	$('#panel-props-show8301').click(function(){
		if (!__show8301){
			$(document.body).append('<img id="ntouch-bg-image" src="images/ntouch/ntouch.png" style="width: 480px; pointer-events: none;" />');
			$('#ntouch-bg-image').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+')',
			});
			__show8301 = true;
			___show8301 = true;
		}
		else {
			if (___show8301){
				$('#ntouch-bg-image').hide();
				___show8301 = false;
			}
			else {
				$('#ntouch-bg-image').show();
				___show8301 = true;
			}
		}
	});

	$('#panel-autoresize-input').click(function(){
		if ($(this).is(':checked'))
			pb.currentpanel.core.autoresize = true; 
		else
			pb.currentpanel.core.autoresize = false;
	});
	
	$('#panel-default-input').click(function(){
		for (var i=0; i<pb.user.panels.length; i++){
			pb.user.panels[i].core.defaultpanel = false;
		}
		pb.currentpanel.core.defaultpanel = true;
		$(this).prop('checked', true);
	});

	$('panel-remove-bg').click(function(){
		pb.currentpanel.element.style.backgroundImage = 'none';
		var fileInput = document.getElementById('panelbg_fileinput');
		fileInput.value = '';
	});

	$('panelbg_fileinput').click(function(){
		this.value = null;
	});

	$('#panelbg_fileinput').change(function(e){
		
		var file = fileInput.files[0];
		
		if (standalone){
			console.log('sio-fio image file upload');
			if (pb.project.core.puid) var puid = pb.project.core.puid;
			else var puid = false;
			siofio.uploadFile(fileInput.files[0], {command: 'image', puid: puid}, function(data){
				// data.file, data.response, data.success
				if (!pb.project.core.puid) pb.project.core.puid = data.response.puid;
				console.log('sio-fio client image return testing', data);
				//console.log('why are you being so difficult webkit, just set the value', data.response.filepath);
				console.log('url(\'file:///' + data.response.filepath.replaceAll('\\','/') + '\')');
				pb.currentpanel.element.style.background = 'url("file:///' + data.response.filepath.replaceAll('\\','/') + '")';
				pb.currentpanel.element.style.backgroundSize = '100% 100%';
				setTimeout(function(){
					pb.currentpanel.element.style.background = pb.currentpanel.element.style.background;
					pb.currentpanel.element.style.backgroundSize = '100% 100%';
				}, 1200);
			});
			return;
		}

		var fd = new FormData();
		fd.append("image", file);
		
		var opts = {
			command: 'write_image',
			width: parseInt(pb.currentpanel.element.style.width),
			height: parseInt(pb.currentpanel.element.style.height)
		};
		
		if (pb.project.puid) opts.puid = pb.project.puid;
		if (pb.project.core.puid) opts.puid = pb.project.core.puid;
		
		fd.append("opts", JSON.stringify(opts));
	
		server({formdata: fd, callback: function(data){
			//console.log(data);
			try {
				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.user.assets.length; i++){
					if (pb.user.assets[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();
			}
			catch (e){
				dumpError(e);
			}
			
			if (!standalone) pb.checkDiskSize();
			
		}});
		
	});
	
	$('#project-props-name').on("input", null, null, function(){
		pb.project.core.name = $('#project-props-name').val();
		$('#project-name-display').css('display', 'block');
		$('#project-name-display')[0].innerHTML = 'Project: ' + pb.project.core.name;
	});
	$('#project-props-setupscript').click(function(){
		if (!pb.project.core){
			pb.project.core = {};
			pb.project.core.scripts = ['',''];
			pb.project.core.conditional = '';
		}
		if (!pb.project.core.scripts) pb.project.core.scripts = ['',''];
		if (!pb.project.core.conditional) pb.project.core.conditional = '';
		textEditor.open({isProject: true});
	});
	$('#project-props-n8301').click(function(){
		
		if (pb.project.puid) var puid = pb.project.puid;
		else var puid = pb.project.core.puid;
		
		var fd = new FormData();
		
		fd.append('command', 'setSettings');
		fd.append('homepage', 'http://127.0.0.1/panels/?project='+puid+
						'&wallcon=1');
		
		server2({formdata: fd, callback: function(data){
				try {
					pb.openDialog({
						content: '<div style="margin: 15px;">This project is now the Wall Controller\'s panel.  Please wait a moment for the panel to refresh.',
						confirm: 'ok',
						cancel: false,
						style: {
							height: '120px',
							'border-radius': '15px'
						},
						onConfirm: function(){pb.closeDialog();}
					});
				}
				catch (e){
					dumpError(e);
				}					
			}
		}, '../index.php');
	});
	
	$('#button-library-label').click(function(){	
		$(".tools-item-pane").hide();
		
		$('.library-label').data('active', '0');
		$('.library-label').css({background: 'black', color: '#ccc'});
		
		$(this).data('active', '1');
		$(this).css({background: '#eee', color: 'black'});
		
		$('#button_library').show();
	});
	$('#widget-library-label').click(function(){
		$(".tools-item-pane").hide();
		
		$('.library-label').data('active', '0');
		$('.library-label').css({background: 'black', color: '#ccc'});
		
		$(this).data('active', '1');
		$(this).css({background: '#eee', color: 'black'});
		
		if (!window.subpaneladded){
			var subpanel = new SubPanel({
				type: 'default', actualwidth: 80, actualheight: 80,
				style: 'position: relative; border: none; background-color: rgba(255,255,255,0.5); float: left; margin: 4px; padding: 0px; width: 80px; height: 80px;'
			});
			subpanel.element.className += ' draggable cloneable';
			//$('#subpanelsGrid')[0].appendChild(subpanel.element);
			$(subpanel.element).append('<div style="font-family: Time; font-size: 20px; position: absolute; left: 10px; top: 28px; pointer-events: none;">SubPanel</div>');
			document.getElementById('Default Widgets').appendChild(subpanel.element);
			
		}
		window.subpaneladded = true;
		
		$('#widget_library').show();
	});
	$('#template-library-label').click(function(){
		$(".tools-item-pane").hide();
		
		$('.library-label').data('active', '0');
		$('.library-label').css({background: 'black', color: '#ccc'});
		
		$(this).data('active', '1');
		$(this).css({background: '#eee', color: 'black'});
		
		$('#template_library').show();
	});
	$('#subpanel-library-label').click(function(){ return;
		$(".tools-item-pane").hide();
		
		$('.library-label').data('active', '0');
		$('.library-label').css({background: 'black', color: '#ccc'});
		
		$(this).data('active', '1');
		$(this).css({background: '#eee', color: 'black'});
		
		if (!window.subpaneladded){
			var subpanel = new SubPanel({
				type: 'default', actualwidth: 80, actualheight: 80,
				style: 'position: relative; border: none; background-color: rgba(255,255,255,0.5); float: left; margin: 4px; padding: 0px; width: 80px; height: 80px;'
			});
			subpanel.element.className += ' draggable cloneable';
			//$('#subpanelsGrid')[0].appendChild(subpanel.element);
			document.getElementById('Default Widgets').appendChild(subpanel.element);
		}
		window.subpaneladded = true;
		
		
		$('#subpanel_library').show();
		
	});
	$('.library-label').hover(function(){
		if ($(this).data('active') != '1')
			$(this).css({background: '#222', color: 'white'});
	},function(){
		if ($(this).data('active') != '1')
			$(this).css({background: 'black', color: '#ccc'});
	});
	/*$('#toolsidebar').click(function(){
		if (toolopener){
			toolopener = false;
			$('#toolsidebar img').addClass('fliph');
		}
		else {
			toolopener = true;
			$('#toolsidebar img').removeClass('fliph');
		}
	});*/
	$('#toolsidebar').append('<img class="" src="images/ui/warrow.png"\
		style="width: 12px; position: absolute; left: 0px; top: calc(50% - 6px);" />');
	$('#button-library-label').css({background: '#eee', color: 'black'});
	$('#button-library-label').data('active', '1');
	
	
	$('#scriptname').html('Script Name: <input id="assets-script-addname" type="textbox"\
		style="position: relative; bottom: 2px; border-radius: 0px; height: 20px; font-size: 19px;"\
		value="myScript" />');

	$('#assets-images-add').click(function(){
		pb.openDialog({
			content: '<div style="margin: 0px !important;">Select an image:</div><br><input type="file" style="width: 245px;" id="select_image_upload" />',
			style: {height: '120px'},
			onConfirm: function(){
				//$('#select_image_upload').change(function(){
					var file = $('#select_image_upload')[0].files[0];
					/*var fd = new FormData();
					fd.append('image', file);
					fd.append('opts', JSON.stringify({command: 'write_image', puid: pb.project.core.puid}));
					
					server({formdata: fd, callback: function(data){
							console.log('imdata', data);
							$('#assets-props-images').click();
						}
					});*/
					
					if (pb.project.core.puid) var puid = pb.project.core.puid;
					else var puid = false;
					
					sendFile(file, {command: 'image', puid: puid}, function(opts){
						//$('.outlined').each(function(){
						//	pb.getItem(this.id).getState(index+1).bgimage = opts.filename;
						//	pb.getItem(this.id).setState();
						//});
						if (!pb.project.core.puid) pb.project.core.puid = opts.puid;
						$('#assets-props-images').click();
					});
					pb.closeDialog();
				//})
			}
		});
	});
	
	$('#assets-images-delete').click(function(){
		if (!$('.script-selected').exists()){
			pb.openDialog({
				content: 'No image selected to remove.',
				cancel: false,
				onConfirm: function(){pb.closeDialog()},
				style: {height: '120px'}
			});
			return;
		}
		else pb.openDialog({
			content: '<div style="margin: 0px !important;">Are you sure you want to delete this asset?</div>',
			style: {height: '120px'},
			onConfirm: function(){
				for (var i=0; i<$('.imagelibraryselected').length; i++){
					var imgasset = pb.getItemById($('.imagelibraryselected')[i].id);
					removeFromArray(pb.user.assets, pb.getItemById($('.imagelibraryselected')[i].id));
					server({opts: {command: 'delete_image', puid: pb.project.core.puid, filename: imgasset.core.data}, 
						callback: function(data){
							if (!standalone) pb.checkDiskSize();
						}
					});
				} 
				$('.imagelibraryselected').remove();
				pb.closeDialog();
			}
		});
	});
	
	$('#assets-modules-add').click(function(){
		pb.dialogs.module();
	});
	
	$('#assets-modules-import').click(function(){
		if (standalone) gui.Window.open('modules.php', {
				title: 'SVSi Control Modules', show: true, toolbar : false, frame: true,
				icon: 'icons/icon.png', width: 1330, 
				height: 770, position: 'center'
			});
		else window.open('modules.php', '_blank');
	});
	
	$('#assets-images-import').click(function(){
		if ($('.imagelibraryselected').exists())
			window.open(pb.getItemById($('.imagelibraryselected')[0].id).core.data, '_blank');
		else {
			pb.openDialog({
				content: 'No image selected to view.',
				cancel: false,
				onConfirm: function(){pb.closeDialog()},
				style: {height: '120px'}
			});
			return;
		}
	});
		
	$('#props-props-label').click(function(){
		$(".resources-item-pane").hide();
		
		$('.props-label').data('active', '0');
		$('.props-label').css({background: 'black', color: '#ccc'});
		
		$(this).data('active', '1');
		$(this).css({background: '#eee', color: 'black'});
		
		$('#props_props').show();
		/*tweencss({object: $('#item-basics-container')[0], time: 0.6,
			props: {height: parseInt($('#item-basics-container')[0].style.height)},
				to: {height: $('#item-basics-container')[0].scrollHeight}});*/
	});
	$('#panel-props-label').click(function(){		
		$(".resources-item-pane").hide();
		
		$('.props-label').data('active', '0');
		$('.props-label').css({background: 'black', color: '#ccc'});
		
		$(this).data('active', '1');
		$(this).css({background: '#eee', color: 'black'});
		
		$('#panel_props').show();
		$('#panel-basic').click();
		
	});
	$('#project-props-label').click(function(){		
		$(".resources-item-pane").hide();
		
		$('.props-label').data('active', '0');
		$('.props-label').css({background: 'black', color: '#ccc'});
		
		$(this).data('active', '1');
		$(this).css({background: '#eee', color: 'black'});
		
		$('#project_props').show();
	});
	$('#assets-props-label').click(function(){			
		$(".resources-item-pane").hide();
		
		$('.props-label').data('active', '0');
		$('.props-label').css({background: 'black', color: '#ccc'});
		
		$(this).data('active', '1');
		$(this).css({background: '#eee', color: 'black'});
		
		$('#asset_props').show();
		$('#assets-props-images').click();
	});
	$('#assets-props-images').click(function(){
		//console.log('clicked the assets button');
		$(".assets-pane").hide();
		
		$('.assets-props-label').data('active', '0');
		$('.assets-props-label').css({background: 'black', color: '#ccc'});
		
		$(this).data('active', '1');
		$(this).css({background: '#eee', color: 'black'});
		
		$('#assets-images-pane').show();
		
		if (pb.project.core) var puid = pb.project.core.puid;
		else var puid = false;
		
		if (true) server({opts: {command: 'read_image_filenames', puid: puid}, callback: function(data){
			//console.log('filenamas', data);
			try {
				var images = json_decode(data);
				for (var i=0; i<images.length; i++){
					var found = false;
					for (var j=0; j<pb.user.assets.images.length; j++){
						//console.log('compare', "projects/"+pb.project.core.puid+"/images/"+images[i], pb.user.assets.images[j].core.data);
						if ("projects/"+pb.project.core.puid+"/images/"+images[i] == pb.user.assets.images[j].core.data) found = true;
					}
					if (found) continue;
					var newasset = new Asset({data: "projects/"+pb.project.core.puid+"/images/"+images[i], type: 'image'});
					newasset.element.style.backgroundImage = 'url(' + "projects/"+pb.project.core.puid+"/images/"+images[i] + ')';
					newasset.element.style.backgroundSize = '100% 100%';
					newasset.element.className += ' cloneable draggable';
					$('#assets-images-pane-list').append(newasset.element);
				}
				/*var dimages = [];
				for (var i=1; i<40; i++){
					dimages.push('Buttons-'+i+'.png');
				}
				for (var i=0; i<dimages.length; i++){
					var found = false;
					for (var j=0; j<pb.user.assets.length; j++){
						//console.log(images[i], pb.user.assets[j].core.data);
						if ("images/buttons/"+dimages[i] == pb.user.assets[j].core.data) found = true;
					}
					if (found) continue;
					var newasset = new Asset({data: "images/buttons/"+dimages[i], type: 'image'});
					newasset.element.style.backgroundImage = 'url(' + "images/buttons/"+dimages[i] + ')';
					newasset.element.style.backgroundSize = '100% 100%';
					newasset.element.className += ' cloneable draggable';
					$('#assets-images-pane-list').append(newasset.element);
				}*/
			}
			catch (e){
				dumpError(e);
			}
		}});
		
		pb.checkDiskSize();
		
	});
	$('#assets-props-scripts')[0].onclick = function(){		
		$(".assets-pane").hide();
		
		$('.assets-props-label').data('active', '0');
		$('.assets-props-label').css({background: 'black', color: '#ccc'});
		
		$(this).data('active', '1');
		$(this).css({background: '#eee', color: 'black'});
		
		$('#assets-scripts-pane').show();
		
		$('#assets-scripts-import')[0].onclick = function(){
			
			if (!$('.script-selected').exists()){
				pb.openDialog({
					content: 'No script selected to edit.',
					cancel: false,
					onConfirm: function(){pb.closeDialog()},
					style: {height: '120px'}
				});
				return;
			}
			
			var script = false;
			for (var i=0; i<scriptlist.length; i++){
				console.log('names', scriptlist[i].name, $($('.script-selected')[0]).data('name'));
				if (scriptlist[i].name == $($('.script-selected')[0]).data('name')){
					script = scriptlist[i];
				}
			}
			console.log('script', script);
			if (!script){
				pb.openDialog({
					content: 'Error loading saved script.',
					cancel: false,
					onConfirm: function(){pb.closeDialog()},
					style: {height: '120px'}
				});
				return;
			}
			
			$('#scripteditor').fadeIn();
			
			$('#scriptname').html(script.name);
			
			scripteditor.setValue(script.script);
			
			$('#assets-script-addsave')[0].onclick = function(){
				console.log('get',scripteditor.getValue());
				script.script = scripteditor.getValue();
				scripteditor.setValue('');
				$('#scripteditor').fadeOut();
				$('#assets-props-scripts').click();
			}
			
			if (0) $('#assets-script-addcancel')[0].onclick = function(){
				scripteditor.setValue('');
				$('#scripteditor').fadeOut();
			}
				
			if (0) $('#assets-script-addcommand')[0].onclick = function(){
				var theval = $('#assets-script-command').val();
				switch (theval){
					case 'require':
						var thetext = '//require a module: require(filename);\nrequire("js/modules/SVSi/N_Series.js");\n';
						$('#assets-script-textarea').val($('#assets-script-textarea').val() + thetext);
						break;
					case 'gotopanel':
						var thetext = '//go to another panel: gotopanel(index);\ngotopanel(1);\n';
						$('#assets-script-textarea').val($('#assets-script-textarea').val() + thetext);
						break;
					case 'asciiToHex':
						var thetext = '//convert ascii to hex: asciiToHex(string);\nasciiToHex("convert this");\n';
						$('#assets-script-textarea').val($('#assets-script-textarea').val() + thetext);
						break;
					case 'hexToAscii':
						var thetext = '//convert hex to ascii: hexToAscii(string);\nhexToAscii("0a bb 8e ff");\n';
						$('#assets-script-textarea').val($('#assets-script-textarea').val() + thetext);
						break;
					case 'tcpclient':
						var thetext = '//opens tcp port, sends message, closes port, does not wait for response: tcpclient(ip, port, message, useWebsocket);\ntcpclient("192.168.1.12", 50002, asciiToHex("set:123"), true);\n';
						$('#assets-script-textarea').val($('#assets-script-textarea').val() + thetext);
						break;
					case 'tcpopen':
						var thetext = '//opens tcp port through websocket: tcpopen(ip, port);\ntcpopen("192.168.1.12", 50002);\n';
						$('#assets-script-textarea').val($('#assets-script-textarea').val() + thetext);
						break;
					case 'tcpsend':
						var thetext = '//sends tcp message and waits for response: tcpsend(ip, port, message, onResponse);\ntcpsend("192.168.1.12", 50002, asciiToHex("getStatus"), function(response){\n     var myresponse = response;\n});\n';
						$('#assets-script-textarea').val($('#assets-script-textarea').val() + thetext);
						break;
					case 'tcpclose':
						var thetext = '//closes tcp port: tcpsend(ip, port);\ntcpclose("192.168.1.12", 50002);\n';
						$('#assets-script-textarea').val($('#assets-script-textarea').val() + thetext);
						break;
					case 'nCmd':
						var thetext = '//sends command to scripting engine, synchronously waits for response: nCmd(script, useWebsocket);\nresponse = nCmd("tcpclient 127.0.0.1 5000 aa bb cc dd", false);\n';
						$('#assets-script-textarea').val($('#assets-script-textarea').val() + thetext);
						break;
					case 'nCmdAsync':
						var thetext = '//sends command to scripting engine, asynchronously waits for response: nCmdAsync(script, responseName, onResponse, onError);\nnCmdAysnc("tcpclient 127.0.0.1 5000 aa bb cc dd", "mydata", function(response){\n     var myresponse = response;\n     var storedresponse = responses["mydata"];\n});\n';
						$('#assets-script-textarea').val($('#assets-script-textarea').val() + thetext);
						break;
					case 'getButton':
						var thetext = '//gets a button by its ID: getButton(buttonid);\nbutton = getButton("Button-1");\n';
						$('#assets-script-textarea').val($('#assets-script-textarea').val() + thetext);
						break;
					default:
						break;
				}
			}
			
		}
		
		$('#assets-scripts-add')[0].onclick = function(){
		
			$('#scriptname').html('Script Name: <input id="assets-script-addname" type="textbox"\
				style="position: relative; bottom: 2px; border-radius: 0px; height: 20px; font-size: 19px;"\
				value="myScript" />');
			
			$('#scripteditor').fadeIn();
			
			scripteditor.setValue('');
			$('#scripteditor').find('.ace_text-input').focus();
			scripteditor.navigateFileEnd();
			
			$('#assets-script-addsave')[0].onclick = function(){
				
				for (var i=0; i<scriptlist.length; i++){
					if (scriptlist[i].name == $('#assets-script-addname').val()){
						pb.openDialog({
							content: 'A script with that name exists, please choose another name.',
							cancel: false,
							onConfirm: function(){pb.closeDialog()},
							style: {height: '120px'}
						});
						return;
					}
				}
				
				var script = scripteditor.getValue();
				var tlist = [];
				for (var i=0; i<scriptlist.length; i++){
					tlist.push(scriptlist[i].id);
				}
				var largest = Math.max.apply(Math, tlist);
				scriptlist.push({id: largest+1, script: script, name: $('#assets-script-addname').val()});
				$('#assets-script-textarea').val('');
				$('#scripteditor').fadeOut();
				$('#assets-props-scripts').click();
			}
			
			$('#assets-script-addcancel')[0].onclick = function(){
				$('#assets-script-textarea').val('');
				$('#scripteditor').fadeOut();
			}
				
			if (0) $('#assets-script-addcommand')[0].onclick = function(){
				var theval = $('#assets-script-command').val();
				var thetext = false;
				switch (theval){
					case 'require':
						thetext = '//require a module: require(filename);\nrequire("js/modules/SVSi/N_Series.js");\n';
						break;
					case 'gotopanel':
						thetext = '//go to another panel: gotopanel(index);\ngotopanel(1);\n';
						break;
					case 'asciiToHex':
						thetext = '//convert ascii to hex: asciiToHex(string);\nasciiToHex("convert this");\n';
						break;
					case 'hexToAscii':
						thetext = '//convert hex to ascii: hexToAscii(string);\nhexToAscii("0a bb 8e ff");\n';
						break;
					case 'tcpclient':
						thetext = '//opens tcp port, sends message, closes port, does not wait for response: tcpclient(ip, port, message, useWebsocket);\ntcpclient("192.168.1.12", 50002, asciiToHex("set:123"), true);\n';
						break;
					case 'tcpopen':
						thetext = '//opens tcp port through websocket: tcpopen(ip, port);\ntcpopen("192.168.1.12", 50002);\n';
						break;
					case 'tcpsend':
						thetext = '//sends tcp message and waits for response: tcpsend(ip, port, message, onResponse);\ntcpsend("192.168.1.12", 50002, asciiToHex("getStatus"), function(response){\n     var myresponse = response;\n});\n';
						break;
					case 'tcpclose':
						thetext = '//closes tcp port: tcpsend(ip, port);\ntcpclose("192.168.1.12", 50002);\n';
						break;
					case 'nCmd':
						thetext = '//sends command to scripting engine, synchronously waits for response: nCmd(script, useWebsocket);\nresponse = nCmd("tcpclient 127.0.0.1 5000 aa bb cc dd", false);\n';
						break;
					case 'nCmdAsync':
						thetext = '//sends command to scripting engine, asynchronously waits for response: nCmdAsync(script, responseName, onResponse, onError);\nnCmdAysnc("tcpclient 127.0.0.1 5000 aa bb cc dd", "mydata", function(response){\n     var myresponse = response;\n     var storedresponse = responses["mydata"];\n});\n';
						break;
					case 'getButton':
						thetext = '//gets a button by its ID: getButton(buttonid);\nbutton = getButton("Button-1");\n';
						break;
					default:
						break;
				}
				if (thetext) scripteditor.replaceSelection(thetext);
			}
			
		}
		
		$('#assets-scripts-delete')[0].onclick = function(){
			if (!$('.script-selected').exists()){
				pb.openDialog({
					content: 'No script selected to remove.',
					cancel: false,
					onConfirm: function(){pb.closeDialog()},
					style: {height: '120px'}
				});
				return;
			}
			else pb.openDialog({
				content: '<div style="margin: 0px !important;">Are you sure you want to delete this asset?</div>',
				style: {height: '120px'},
				onConfirm: function(){
					for (var i=0; i<$('.script-selected').length; i++){
						for (var j=0; j<scriptlist.length; j++){
							if (scriptlist[j].name == $($('.script-selected')[i]).data('name'))
								removeFromArray(scriptlist, scriptlist[j]);
						} 
					} 
					$('.script-selected').remove();
					pb.closeDialog();
				}
			});
		}
		
		var tstr = '';
		for (var i=0; i<scriptlist.length; i++){
			tstr +=
				'<div class="s-label" data-selected="false" data-id="'+scriptlist[i].id+'" data-name="'+scriptlist[i].name+'"\
					style="color: white; background: black; width: 100%;\
						position: relative; line-height: 30px; text-decoration: bold; text-align: center;\
						font-size: 19px; cursor: pointer;"\
				onmouseover="\
					if (!$(this).data(\'selected\')){\
						this.style.color = \'black\';\
						this.style.background = \'white\';\
					}\
				" onmouseout="\
					if (!$(this).data(\'selected\')){\
						this.style.color = \'white\';\
						this.style.background = \'black\';\
					}\
				" ondragstart="return false;">'+scriptlist[i].name+'</div>';
		}
		$('#assets-scripts-pane-list').html(tstr);
		$('.s-label').each(function(){
		
			var localtimer = false;
		
			this.onmousedown = function(){
			
				$('.s-label').css({color: 'white', background: 'black'});
				
				if ($(this).data('selected') == 'true'){
					this.style.color = 'white';
					this.style.background = 'black';
					$(this).data('selected', 'false');
					$(this).removeClass('script-selected');
				}
				else {
					$('.s-label').data('selected', 'false');
					$('.s-label').removeClass('script-selected');
					this.style.color = 'black';
					this.style.background = 'white';
					$(this).data('selected', 'true');
					$(this).addClass('script-selected');
				}
			
				localtimer = setTimeout(function(){
					if (!pb.mouse.down) return;
					$(document.body).append('<div id="floatingscript-'+$(this).data('name')+'" style="position: absolute; left: '+
						(pb.mouse.pagex-40)+'px; color: white; line-height: 80px; text-align: center; border: 2px solid #333; top: '+(pb.mouse.pagey-40)+
						'px; width: 80px; height: 80px; background: rgba(68,68,68, 0.5); z-index: 9000000000; cursor: default;"><span>'+$(this).data('name')+'</span></div>');
					
					var obj = {element: $('#floatingscript-'+$(this).data('name'))[0], dragging: function(e){
						$(this).css({
							left: (pb.mouse.pagex-40)+'px',
							top: (pb.mouse.pagey-40)+'px'
						});
					}.bind($('#floatingscript-'+$(this).data('name'))[0])};
					
					addEventHandler($('#floatingscript-'+$(this).data('name'))[0], 'dragstart', cancelEvent);
					
					$(obj.element).textfill2({ maxFontPixels: 36, padding: 7 });
					
					pb.mouse.dragged.push(obj);
					pb.mouse.clickup = function(){
						pb.mouse.clickup = noop;
						$(this).remove();
						if (!pb.mouse.itemsOver('.draggable')) return;
						if (!pb.mouse.itemsOver('.draggable').length) return;
						console.log(pb.mouse.itemsOver('.draggable'));
						var item = pb.getItemById(pb.mouse.itemsOver('.draggable')[0].id);
						if (item instanceof Button){
							console.log(this);
							var scriptid = this.id.replace('floatingscript-','');
							var script = false;
							
							for (var i=0; i<scriptlist.length; i++){
								if (scriptid == scriptlist[i].name) script = scriptlist[i];
							}
						
							if (script){
								if (item.element.className.indexOf('outlined') !== -1 && $('.outlined').length > 1){
									pb.openDialog({
										content: '<div style="margin: 15px;">Apply script to all selected items?<br><br>\
											<select id="script-state-select">\
												<option value="state1">State 1</option>\
												<option value="state2">State 2</option>\
												<option value="cond">Condtional</option>\
											</select></div>',
										style: {
											height: '120px',
											'border-radius': '15px'
										},
										confirm: 'yes',
										cancel: 'no',
										onConfirm: function(){
											//console.log
											if (!undef(script.labelcolorhtml)){
												for (var i=0; i<$('.outlined').length; i++){
													if ($('#script-state-select').val() == 'state1')
														pb.getItemById($('.outlined')[i].id).core.scripts[0] = '<nCmd>\n'+script.script+'\n<nCmd>';
													else if ($('#script-state-select').val() == 'state2')
														pb.getItemById($('.outlined')[i].id).core.scripts[1] = '<nCmd>\n'+script.script+'\n<nCmd>';
													else if ($('#script-state-select').val() == 'cond')
														pb.getItemById($('.outlined')[i].id).core.conditional = '<nCmd>\n'+script.script+'\n<nCmd>';
												}
											}
											else {
												for (var i=0; i<$('.outlined').length; i++){
													if ($('#script-state-select').val() == 'state1')
														pb.getItemById($('.outlined')[i].id).core.scripts[0] = script.script;
													else if ($('#script-state-select').val() == 'state2')
														pb.getItemById($('.outlined')[i].id).core.scripts[1] = script.script;
													else if ($('#script-state-select').val() == 'cond')
														pb.getItemById($('.outlined')[i].id).core.conditional = script.script;
												}
											}
											pb.closeDialog();
										}
									});
								}
								else {
									
									pb.openDialog({
										content: '<div style="margin: 15px;">Apply script to item?<br><br>\
											<select id="script-state-select2">\
												<option value="state1">State 1</option>\
												<option value="state2">State 2</option>\
												<option value="cond">Condtional</option>\
											</select></div>',
										style: {
											height: '120px',
											'border-radius': '15px'
										},
										confirm: 'yes',
										cancel: 'no',
										onConfirm: function(){
											if (!undef(script.labelcolorhtml)){
												if ($('#script-state-select2').val() == 'state1')
													item.core.scripts[0] = '<nCmd>\n'+script.script+'\n<nCmd>';
												else if ($('#script-state-select2').val() == 'state2')
													item.core.scripts[1] = '<nCmd>\n'+script.script+'\n<nCmd>';
												else if ($('#script-state-select2').val() == 'cond')
													item.core.conditional = '<nCmd>\n'+script.script+'\n<nCmd>';
											}
											else {
												if ($('#script-state-select2').val() == 'state1')
													item.core.scripts[0] = script.script;
												else if ($('#script-state-select2').val() == 'state2')
													item.core.scripts[1] = script.script;
												else if ($('#script-state-select2').val() == 'cond')
													item.core.conditional = script.script;
											}
											pb.closeDialog();
										}
									});
									
								}
							}
							
						}
						//pb.mouse.clickup = noop;
					}.bind($('#floatingscript-'+$(this).data('name'))[0]);
					
				}.bind(this), 300);
				
			}
			
			this.onmouseup = function(){
				clearTimeout(localtimer);
			}
			
		});
		
	};
	$('#assets-props-modules')[0].onclick = function(){

		htmlmodel.modulelist = modulelist;
		
		$(".assets-pane").hide();
		
		$('.assets-props-label').data('active', '0');
		$('.assets-props-label').css({background: 'black', color: '#ccc'});
		
		$(this).data('active', '1');
		$(this).css({background: '#eee', color: 'black'});
		
		$('#assets-modules-pane').show();
		
		var mlist = [];
		for (var i=0; i<modulelist.length; i++){
			if (!arrayContains(mlist, modulelist[i].manufacturer)) mlist.push(modulelist[i].manufacturer);
		}
		for (var i=0; i<mlist.length; i++){
			if (mlist[i] == 'SVSi'){
				var t = mlist[0];
				mlist[0] = mlist[i];
				mlist[i] = t;
			}
		}
		
		var tstr = '';
		for (var i=0; i<mlist.length; i++){
			tstr +=
				'<div id="manufacturerlabel-'+mlist[i]+'" class="mc-label m-label" data-selected="false"\
				style="color: white; background: black; width: 100%;\
					position: relative; line-height: 30px; text-decoration: bold; text-align: center;\
					font-size: 19px; cursor: pointer;"\
				onmouseover="\
					if (!$(this).data(\'selected\')){\
						this.style.color = \'black\';\
						this.style.background = \'white\';\
					}\
				" onmouseout="\
					if (!$(this).data(\'selected\')){\
						this.style.color = \'white\';\
						this.style.background = \'black\';\
					}\
				" onclick="\
					$(\'.mc-label\').data(\'selected\', false);\
					$(\'.m-label\').css({color: \'white\', background: \'black\'});\
					$(\'.c-label\').css({color: \'white\', background: \'#333\'});\
					if ($(this).data(\'selected\')){\
						this.style.color = \'white\';\
						this.style.background = \'black\';\
						$(this).data(\'selected\', false);\
					}\
					else {\
						this.style.color = \'black\';\
						this.style.background = \'white\';\
						$(this).data(\'selected\', true);\
					}\
				"><input style="display: none;" id="checkbox-'+mlist[i]+
				'" class="manufacturer-checkbox" type="checkbox" /> '+mlist[i]+'</div>';
			for (var j=0; j<modulelist.length; j++){
				if (mlist[i] == modulelist[j].manufacturer){
					if (modulelist[j].required) var checked = 'checked="checked"';
					else var checked = '';
					tstr +=
						'<div id="modulelabel-'+modulelist[j].make+'" class="mc-label c-label" data-selected="false"\
							data-make="'+modulelist[j].make+'" data-manufacturer="'+mlist[i]+'"\
							style="color: white; background: #333; width: 100%;\
							position: relative; line-height: 30px; text-decoration: none; text-align: center;\
							cursor: pointer;"\
						onmouseover="\
							if (!$(this).data(\'selected\')){\
								this.style.color = \'black\';\
								this.style.background = \'white\';\
							}\
						" onmouseout="\
							if (!$(this).data(\'selected\')){\
								this.style.color = \'white\';\
								this.style.background = \'#333\';\
							}\
						" onclick="\
							$(\'.mc-label\').data(\'selected\', false);\
							$(\'.m-label\').css({color: \'white\', background: \'black\'});\
							$(\'.c-label\').css({color: \'white\', background: \'#333\'});\
							if ($(this).data(\'selected\')){\
								this.style.color = \'white\';\
								this.style.background = \'#333\';\
								$(this).data(\'selected\', false);\
								$(this).removeClass(\'module-selected\');\
							}\
							else {\
								this.style.color = \'black\';\
								this.style.background = \'white\';\
								$(this).data(\'selected\', true);\
								$(this).addClass(\'module-selected\');\
							}\
						"><input id="checkbox-'+modulelist[j].make+
						'" class="module-checkbox" type="checkbox" '+checked+' /> '+modulelist[j].make+'</div>';
					
				}
			}
		}
		$('#assets-modules-pane-list').html(tstr);
		
		for (var j=0; j<modulelist.length; j++){
			$('#checkbox-'+modulelist[j].make)[0].onclick = function(moduleitem){
				if ($(this).prop('checked')){
					moduleitem.required = true;
				}
				else moduleitem.required = false;
			}.bind($('#checkbox-'+modulelist[j].make)[0], modulelist[j])
		}
		
		$('#assets-modules-delete')[0].onclick = function(){
			pb.openDialog({
				content: '<div style="margin: 0px !important;">Are you sure you want to delete this asset?</div>',
				style: {height: '120px'},
				onConfirm: function(){
					for (var i=0; i<$('.module-selected').length; i++){
						for (var j=0; j<modulelist.length; j++){
							if (modulelist[j].make == $($('.module-selected')[i]).data('make') &&
								modulelist[j].manufacturer == $($('.module-selected')[i]).data('manufacturer')){
								server({opts: {command: 'delete_module', filename: modulelist[j].file}, 
									callback: function(data){
										//pb.checkDiskSize();
									}
								});
								removeFromArray(modulelist, modulelist[j]);
								$('.module-selected').remove();
								return;
							}
						} 
					}
					pb.closeDialog();
				}
			});
		}
		
	}
	$('#assets-props-images').click();
	
	$('.props-label').hover(function(){
		if ($(this).data('active') != '1')
			$(this).css({background: '#222', color: 'white'});
	},function(){
		if ($(this).data('active') != '1')
			$(this).css({background: 'black', color: '#ccc'});
	});
	
	$('#resourcesidebar').append('<img class="fliph" src="images/ui/warrow.png"\
		style="width: 12px; position: absolute; left: 0px; top: calc(50% - 6px);" />');
	$('#panel-props-label').css({background: '#eee', color: 'black'});
	$('#panel-props-label').data('active', '1');
	
	document.getElementById('zoom-in-image').addEventListener('mousedown', function(e){
		if (pb.currentpanel){
			pb.zoomingin = true;
		}
	}, false);
	
	document.getElementById('zoom-in-image').addEventListener('mouseup', function(e){
		if (pb.currentpanel){
			pb.zoomingin = false;
		}
	}, false);
	
	document.getElementById('zoom-in-image').addEventListener('mouseout', function(e){
		if (pb.currentpanel){
			pb.zoomingin = false;
		}
	}, false);
	
	document.getElementById('zoom-out-image').addEventListener('mousedown', function(e){
		if (pb.currentpanel){
			pb.zoomingout = true;
		}
	}, false);
	
	document.getElementById('zoom-out-image').addEventListener('mouseup', function(e){
		if (pb.currentpanel){
			pb.zoomingout = false;
		}
	}, false);
	
	document.getElementById('zoom-out-image').addEventListener('mouseout', function(e){
		if (pb.currentpanel){
			pb.zoomingout = false;
		}
	}, false);
	
	var defaultWidgets = document.createElement('div');
	defaultWidgets.id = "Default Widgets";
	defaultWidgets.style.cssText += 'position: absolute; top: 0px; width: 100%; overflow-x: hidden; overflow-y: scroll;\
		z-index: 201; height: 100%; border-top: 1px solid darkgrey; border-bottom: 1px solid darkgrey;';

	defaultWidgets.appendChild(vslider().element);			
	defaultWidgets.appendChild(hslider().element);
	defaultWidgets.appendChild(vslider2().element);
	defaultWidgets.appendChild(hslider2().element);
	defaultWidgets.appendChild(textwidget().element);
	defaultWidgets.appendChild(imagewidget().element);		
	defaultWidgets.appendChild(numpad().element);
	///defaultWidgets.appendChild(numpad2().element);
	///defaultWidgets.appendChild(dial().element);		
	///defaultWidgets.appendChild(dial2().element);	
	///defaultWidgets.appendChild(dpad().element);	
	if (0) defaultWidgets.appendChild(dvr().element);			
	if (!wallcon && !modero) defaultWidgets.appendChild(nvr_play().element);			
	///defaultWidgets.appendChild(vlist().element);
	///defaultWidgets.appendChild(hlist().element);
	if (!wallcon && !modero) defaultWidgets.appendChild(encoderselect().element);	
	if (!wallcon && !modero) defaultWidgets.appendChild(decoderselect().element);				
	///defaultWidgets.appendChild(timeweather().element);
	
	document.getElementById('widget-library-pane').appendChild(defaultWidgets);
	
	addEventHandler($('#selectorbox')[0], 'dragstart', cancelEvent);

	$("#thebody").keyup(function(event){
	
		var keycode = (event.keyCode ? event.keyCode : event.which);
		var key = String.fromCharCode(keycode);
		
		pb.keys[keycode] = false;
		
		if (keycode == 46 && !textEditor.is_open && !(document.activeElement.nodeName == 'TEXTAREA' || document.activeElement.nodeName == 'INPUT')){
			var outlined = $('.outlined').toArray();
			var naction = new Action({type: 'delete'});
			naction.items = [];
			for (var i=0;i<outlined.length;i++){
				naction.items.push(pb.getItemById(outlined[i].id));
				pb.getItemById(outlined[i].id).remove();
			}
			$('.outlined').removeClass('outlined first');
			pb.saveaction(naction);
		}
		
	});
		
	$("#thebody").keydown(function(event){
		
		if (!(document.activeElement.nodeName == 'TEXTAREA' || document.activeElement.nodeName == 'INPUT')){
			var keycode = (event.keyCode ? event.keyCode : event.which);
			var key = String.fromCharCode(keycode);
			
			pb.keys[keycode] = true;
			
			if (textEditor.is_open || !$('.outlined').exists()) return;
			
			if (pb.keys['37']) {	
				$('.outlined').css({left: '-=1px', right: '+=1px'});
			}
			if (pb.keys['38']) {
				$('.outlined').css({top: '-=1px', bottom: '+=1px'});
			}
			if (pb.keys['39']) {
				$('.outlined').css({right: '-=1px', left: '+=1px'});
			}
			if (pb.keys['40']) {
				$('.outlined').css({bottom: '-=1px', top: '+=1px'});
			}
			$('.outlined').each(function(index, value){ 
				var button = pb.getItemById(this.id);
				if (button && button.constrain) button.constrain();
			});
		}
		
	});
	
	if (!standalone) window.onbeforeunload = function (e) {
		e = e || window.event;

		// For IE and Firefox prior to version 4
		if (e) {
			e.returnValue = 'Exit without saving?';
		}

		// For Safari
		return 'Exit without saving?';
	};
	
	document.ondragover = function() {
		pb.mouse.mousemove(window.event);
	}

	$("#filemenuitem1").click(function(e){
		pb.closeMenu('file');
		pb.closeMenu('recent'); 
		pb.openDialog({
			title: 'Are you sure?', 
			content: '<div style="margin: 15px">Your current progress won\'t be saved.</div>',
			style: {
				height: '130px',
				'border-radius': '15px'
			},
			onConfirm: function(){
				pb.user.templates = []; pb.user.buttons = []; pb.user.assets.images = [];
				$('#templatesGrid').html(''); $(document.getElementById('User Buttons')).html('');
				$('#assets-images-pane-list').html('');
				pb.closeDialog();
				pb.newprojecttimer = setInterval(function(){
					if (pb.dialogopen !== true){
						pb.loadProject();
						clearInterval(pb.newprojecttimer);
					}
				}, 100);
			}
		});
		$('#project-name-display').css('display', 'none');
	});
	$("#filemenuitem2").click(function(e){ console.log('i am working?');
		pb.closeMenu('file');
		pb.closeMenu('recent');
		document.getElementById('file-open').accept = '.zip';
		pb.openFileBrowser(function(){
			if (1){
				console.log('binsocket file upload');
				pb.user.templates = []; pb.user.buttons = [];
				$('#templatesGrid').html(''); $(document.getElementById('User Buttons')).html('');
				sendFile($("#file-open")[0].files[0], {command: 'import_project', filename: $("#file-open")[0].files[0].filename}, 
					function(opts){
						//$('.outlined').each(function(){
						//	pb.getItem(this.id).getState(index+1).bgimage = opts.filename;
						//	pb.getItem(this.id).setState();
						//});
						console.log('binsocket return', opts);
					});
				//siofio.uploadFile($("#file-open")[0].files[0], {command: 'zip'}, function(data){
					// data.file, data.response, data.success
				//	console.log('sio-fio client return', data);
				//});
			}
			else {
				var file = $("#file-open")[0].files[0];
				var fd = new FormData();
				fd.append("zip", file);
				fd.append("opts", JSON.stringify({command: 'import_project', name: file.name.replace('.zip', '')}));
			
				server({formdata: fd, callback: function(data){
						pb.loadProject(data);
					}
				});
			}
		});
	});
	$("#filemenuitem3").click(function(e){
		pb.unselectAll();
		pb.closeMenu('file');
		pb.closeMenu('recent'); 	
		if (!pb.project.core.name || pb.project.core.name == 'New Project'){
			pb.openDialog({
				content: 'Enter a name for your project:<br><br>'+
					'<input id="project_name" size="3" style="width: 145px;" value="" type="text"/>',
				onConfirm: function(){
					pb.project.core.name = $('#project_name').val();
					$('#project-name-display').css('display', 'block');
					$('#project-name-display')[0].innerHTML = 'Project: ' + pb.project.core.name;
					pb.saveProject();
					pb.closeDialog();
				}
			});
		}
		else{
			pb.saveProject();
		}	
	});
	$("#filemenuitem4").click(function(e){
		pb.closeMenu('file');
		pb.closeMenu('recent'); 
		pb.saveProject({silent: true}, function(){
			if (1||standalone) window.websocket.emit('message', {command: 'export_project', id: pb.project.core.puid});
			else $('#fileopener').attr('src', 'server.php?export='+pb.project.core.puid+'&name='+pb.project.core.name);
		});
	});
	$("#filemenuitem5").mouseover(function(e){
		pb.openMenu('recent');	
		pb.updateRecent();
	});
	$("#filemenuitem6").click(function(e){
		pb.closeMenu('file');
		pb.closeMenu('recent');
		pb.openSelectProjectList();
	});
	$("#filemenuitem7").click(function(e){
		pb.closeMenu('file');
		pb.closeMenu('recent');
		pb.openDialog({
			content: '<div style="margin: 15px;">Enter a new name for your project:<br><br>'+
			'<input id="project_name" size="3" style="width: 145px;" value="" type="text"/></div>',
			style: {
				height: '170px',
				'border-radius': '15px'
			},
			onConfirm: function(){
				if (0 && useDB_read)
					queryDB({opts: {query: 'rowcount'}, callback: function(id){
						pb.project.id = parseInt(id)+1;
						pb.project.core.name = $('#project_name').val();
						$('#project-name-display').css('display', 'block');
						$('#project-name-display')[0].innerHTML = 'Project: ' + pb.project.core.name;
						pb.saveProject();
						pb.closeDialog();
					}});
				else {
					//console.log('...?');
					pb.project.core.name = $('#project_name').val();
					$('#project-name-display').css('display', 'block');
					$('#project-name-display')[0].innerHTML = 'Project: ' + pb.project.core.name;
					//pb.project.core.puid = false;
					pb.saveProject({duplicate: true, silent: false, name: $('#project_name').val()});
					pb.closeDialog();
				}
				$('#project-props-name').val($('#project_name').val());
			}
		});
	});
	$("#filemenuitem1").hover(function(){
		pb.closeMenu('recent');
	});
	$("#filemenuitem2").hover(function(){
		pb.closeMenu('recent');
	});
	$("#filemenuitem3").hover(function(){
		pb.closeMenu('recent');
	});
	$("#filemenuitem4").hover(function(){
		pb.closeMenu('recent');
	});
	$("#filemenuitem6").hover(function(){
		pb.closeMenu('recent');
	});
	$("#filemenuitem7").hover(function(){
		pb.closeMenu('recent');
	});
	$("#filemenuitem9").hover(function(){
		pb.closeMenu('recent');
	});
	$("#filemenuitem9").click(function(e){
		pb.closeMenu('file');
		pb.closeMenu('recent');
		//pb.openAddModule();
	});
	$("#filemenuitem8").click(function(e){
		pb.closeMenu('file');
		pb.closeMenu('recent');
		pb.openDeleteProjectList();
	});
	$("#recentmenuitem1").click(function(e){
		pb.closeMenu('recent');	
		if (1||useDB) pb.loadProject(pb.projectlist[0]);
		else pb.loadProject(pb.projectlist[0].puid);
	});
	$("#recentmenuitem2").click(function(e){
		pb.closeMenu('recent');	
		if (1||useDB) pb.loadProject(pb.projectlist[1]);
		else pb.loadProject(pb.projectlist[1].puid);
	});
	$("#recentmenuitem3").click(function(e){
		pb.closeMenu('recent');	
		if (1||useDB) pb.loadProject(pb.projectlist[2]);
		else pb.loadProject(pb.projectlist[2].puid);
	});
	$("#recentmenuitem4").click(function(e){
		pb.closeMenu('recent');	
		if (1||useDB) pb.loadProject(pb.projectlist[3]);
		else pb.loadProject(pb.projectlist[3].puid);
	});
	$("#recentmenuitem5").click(function(e){
		pb.closeMenu('recent');	
		if (1||useDB) pb.loadProject(pb.projectlist[4]);
		else pb.loadProject(pb.projectlist[4].puid);
	});
	$("#recentmenuitem6").click(function(e){
		pb.closeMenu('recent');	
		if (1||useDB) pb.loadProject(pb.projectlist[5]);
		else pb.loadProject(pb.projectlist[5].puid);
	});
	$("#recentmenuitem7").click(function(e){
		pb.closeMenu('recent');	
		if (1||useDB) pb.loadProject(pb.projectlist[6]);
		else pb.loadProject(pb.projectlist[6].puid);
	});
	$("#recentmenuitem8").click(function(e){
		pb.closeMenu('recent');	
		if (1||useDB) pb.loadProject(pb.projectlist[7]);
		else pb.loadProject(pb.projectlist[7].puid);
	});
	
	$("#editmenuitem2").click(function(e){
		pb.closeMenu('edit');
		if ($('.outlined').exists()){
			if (pb.getItemById($('.outlined')[0].id) instanceof Button ||
				pb.getItemById($('.outlined')[0].id) instanceof Panel) 
				openItemEditor(pb.getItemById($('.outlined')[0].id), true, true);
			if (pb.getItemById($('.outlined')[0].id) instanceof Widget) 
				openWidgetEditor(pb.getItemById($('.outlined')[0].id), true, true);
		}
	});
	
	$("#addmenuitem1").click(function(e){
		pb.closeMenu('add');
		pb.addPanel(e);
	});
	$("#addmenuitem2").click(function(e){
		pb.closeMenu('add');
		var nbutton = new Button({});
		nbutton.element.style.width = '200px';
		nbutton.element.style.height = '200px';
		openItemEditor(nbutton, false, true);
		pb.openToolsPane();
		pb.openResourcesPane();
		$('#button-library-select').val('User Buttons');
		pb.setButtonLibrary();
		var thisid = "button_library_label";
		$(".tools_item").removeClass('layerD').addClass('layerC');
		$(".tools_item_label").css({'background-color': '#caccca'});
		$('#'+thisid.substring(0,thisid.length-6)).removeClass('layerC').addClass('layerD');
		$('#'+thisid).css({'background-color': '#eeeeee'});
	});
	$("#addmenuitem3").click(function(e){
		pb.closeMenu('add'); 
		var thisid = "widget_library_label";
		$(".tools_item").removeClass('layerD').addClass('layerC');
		$(".tools_item_label").css({'background-color': '#caccca'});
		$('#'+thisid.substring(0,thisid.length-6)).removeClass('layerC').addClass('layerD');
		$('#'+thisid).css({'background-color': '#eeeeee'});
		return false;
	});
	
	$("#viewmenuitem2").click(function(e){
		pb.closeMenu('view');
		setLocalDBObject('projectpreview', pb.projectToJSON(pb.project));
		if (standalone) gui.Window.open('../panels/index.php?panel='+(pb.user.panels.indexOf(pb.currentpanel)+1)+'&preview=true', {
			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 window.open('../panels/?panel='+(pb.user.panels.indexOf(pb.currentpanel)+1)+'&preview=true','_blank');
	}); 
	
	$("#viewmenuitem3").click(function(e){
		pb.closeMenu('view');
		if (!pb.project.core){
			pb.project.core = {};
			pb.project.core.scripts = ['',''];
			pb.project.core.conditional = '';
		}
		if (!pb.project.core.scripts) pb.project.core.scripts = ['',''];
		if (!pb.project.core.conditional) pb.project.core.conditional = '';
		textEditor.open({isProject: true});
	}); 
	
	$("#windowmenuitem2").click(function(e){
		pb.closeMenu('window'); 
		$('#toolsidebar img').addClass('fliph');
		$('.tools-panel').stop().animate({left: '-290px'}, 240).animate({left: '0px'}, 240);
		toolpaneopen = true;
		toolopener = false;
	});
	$("#windowmenuitem7").click(function(e){
		pb.closeMenu('window'); 
		$('#resourcesidebar img').removeClass('fliph');
		$('.resources-panel').stop().animate({right: '-290px'}, 240).animate({right: '0px'}, 240);
		resourcepaneopen = true;
		resourceopener = false;

	});
	
	$("#windowmenuitem1").click(function(e){
		pb.closeMenu('window'); 
		
		pb.openDialog({
			content: 'Choose your window skin colors:<br><br>'+
			'<div>Interface Color 1:  \
			<div id="uiColorSelector1" class="uiColorSelector colorSelector" title="Interface Color 1" style="margin-left: 10px; float: none; display: inline-block;"><div style="background-color: #caccca"></div></div>\
			&nbsp;&nbsp;Interface Color 2:  \
			<div id="uiColorSelector2" class="uiColorSelector colorSelector" title="Interface Color 1" style="margin-left: 10px; float: none; display: inline-block;"><div style="background-color: #caccca"></div></div>\</div>\
			<div>Font Color 1:  \
			<div id="uiColorSelector3" class="uiColorSelector colorSelector" title="Interface Color 1" style="margin-left: 10px; float: none; display: inline-block;"><div style="background-color: #caccca"></div></div>\
			&nbsp;&nbsp;Font Color 2:  \
			<div id="uiColorSelector4" class="uiColorSelector colorSelector" title="Interface Color 1" style="margin-left: 10px; float: none; display: inline-block;"><div style="background-color: #caccca"></div></div>\
			<br /><div>Dark Icons: <input id="isDarkIcons" type="checkbox" \></div></div>',
			onConfirm: function(){
				pb.ui.color1 = rgb2hex($('#uiColorSelector1 div').css('backgroundColor'));
				pb.ui.color1a = addHexColor(pb.ui.color1, '#222222');
				pb.ui.color1b = subHexColor(pb.ui.color1, '#111111'); 
				pb.ui.color2 = rgb2hex($('#uiColorSelector2 div').css('backgroundColor'));
				pb.ui.color2a = addHexColor(pb.ui.color1, '#020202');
				pb.ui.fontcolor1 = rgb2hex($('#uiColorSelector3 div').css('backgroundColor'));
				pb.ui.fontcolor2 = rgb2hex($('#uiColorSelector4 div').css('backgroundColor'));
				if ($('#isDarkIcons').prop('checked')) pb.ui.darkicons = '100%';
				else pb.ui.darkicons = '0%';
				pb.closeConfirmDialog();
				addStyleSheet('\
					.backgroundgradient{\
						background: '+pb.ui.color1+';\
						background: -moz-linear-gradient(top,  '+pb.ui.color1a+' 0%, '+pb.ui.color1b+' 50%, '+pb.ui.color2+' 51%, '+pb.ui.color2a+' 100%);\
						background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,'+pb.ui.color1a+'), color-stop(50%,'+pb.ui.color1b+'), color-stop(51%,'+pb.ui.color2+'), color-stop(100%,'+pb.ui.color2a+'));\
						background: -webkit-linear-gradient(top,  '+pb.ui.color1a+' 0%,'+pb.ui.color1b+' 50%,'+pb.ui.color2+' 51%,'+pb.ui.color2a+' 100%);\
						background: -o-linear-gradient(top,  '+pb.ui.color1a+' 0%,'+pb.ui.color1b+' 50%,'+pb.ui.color2+' 51%,'+pb.ui.color2a+' 100%);\
						background: -ms-linear-gradient(top,  '+pb.ui.color1a+' 0%,'+pb.ui.color1b+' 50%,'+pb.ui.color2+' 51%,'+pb.ui.color2a+' 100%);\
						background: linear-gradient(to bottom,  '+pb.ui.color1a+' 0%,'+pb.ui.color1b+' 50%,'+pb.ui.color2+' 51%,'+pb.ui.color2a+' 100%);\
						filter: progid:DXImageTransform.Microsoft.gradient( startColorstr=\''+pb.ui.color1+'\', endColorstr=\''+pb.ui.color2+'\',GradientType=0 );\
					}\
					.menu-button{\
						background: '+pb.ui.color1+';\
						background: -moz-linear-gradient(top,  '+pb.ui.color1a+' 0%, '+pb.ui.color1b+' 50%, '+pb.ui.color2+' 51%, '+pb.ui.color2a+' 100%);\
						background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,'+pb.ui.color1a+'), color-stop(50%,'+pb.ui.color1b+'), color-stop(51%,'+pb.ui.color2+'), color-stop(100%,'+pb.ui.color2a+'));\
						background: -webkit-linear-gradient(top,  '+pb.ui.color1a+' 0%,'+pb.ui.color1b+' 50%,'+pb.ui.color2+' 51%,'+pb.ui.color2a+' 100%);\
						background: -o-linear-gradient(top,  '+pb.ui.color1a+' 0%,'+pb.ui.color1b+' 50%,'+pb.ui.color2+' 51%,'+pb.ui.color2a+' 100%);\
						background: -ms-linear-gradient(top,  '+pb.ui.color1a+' 0%,'+pb.ui.color1b+' 50%,'+pb.ui.color2+' 51%,'+pb.ui.color2a+' 100%);\
						background: linear-gradient(to bottom,  '+pb.ui.color1a+' 0%,'+pb.ui.color1b+' 50%,'+pb.ui.color2+' 51%,'+pb.ui.color2a+' 100%);\
						filter: progid:DXImageTransform.Microsoft.gradient( startColorstr=\''+pb.ui.color1+'\', endColorstr=\''+pb.ui.color2+'\',GradientType=0 );\
						color: '+pb.ui.fontcolor1+';\
					}\
					.title_bar{\
						height: 15px;\
						background: #aebcbf; \
						background: -moz-linear-gradient(top,  '+pb.ui.color1a+' 0%, '+pb.ui.color1b+' 50%, '+pb.ui.color2+' 51%, '+pb.ui.color2a+' 100%);\
						background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,'+pb.ui.color1a+'), color-stop(50%,'+pb.ui.color1b+'), color-stop(51%,'+pb.ui.color2+'), color-stop(100%,'+pb.ui.color2a+'));\
						background: -webkit-linear-gradient(top,  '+pb.ui.color1a+' 0%,'+pb.ui.color1b+' 50%,'+pb.ui.color2+' 51%,'+pb.ui.color2a+' 100%);\
						background: -o-linear-gradient(top,  '+pb.ui.color1a+' 0%,'+pb.ui.color1b+' 50%,'+pb.ui.color2+' 51%,'+pb.ui.color2a+' 100%);\
						background: -ms-linear-gradient(top,  '+pb.ui.color1a+' 0%,'+pb.ui.color1b+' 50%,'+pb.ui.color2+' 51%,'+pb.ui.color2a+' 100%);\
						background: linear-gradient(to bottom,  '+pb.ui.color1a+' 0%,'+pb.ui.color1b+' 50%,'+pb.ui.color2+' 51%,'+pb.ui.color2a+' 100%);\
						filter: progid:DXImageTransform.Microsoft.gradient( startColorstr=\''+pb.ui.color1+'\', endColorstr=\''+pb.ui.color2+'\',GradientType=0 );\
						border-top-left-radius: 4px;\
						border-bottom: 1px solid #464745;\
						border-top-right-radius: 4px;\
						text-align: center;\
						font-family: Lucida Grande;\
						font-size: 14px;\
						color: '+pb.ui.fontcolor1+';\
						font-weight: bold;\
						text-shadow: 0 1px 1px #466278;\
						padding: 5px;\
					}\
					.menu-button:hover {\
						background: '+pb.ui.color2+';\
						background: -moz-linear-gradient(top, '+pb.ui.color2a+' 0%, '+pb.ui.color2+' 50%, '+pb.ui.color1+' 79%, '+pb.ui.color1+' 100%);\
						background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,'+pb.ui.color2+'), color-stop(50%,'+pb.ui.color2+'), color-stop(79%,'+pb.ui.color1+'), color-stop(100%,'+pb.ui.color1+'));\
						background: -webkit-linear-gradient(top, '+pb.ui.color2a+' 0%,'+pb.ui.color2+' 50%,'+pb.ui.color1+' 79%,'+pb.ui.color1+' 100%);\
						background: -o-linear-gradient(top, '+pb.ui.color2a+' 0%,'+pb.ui.color2+' 50%,'+pb.ui.color1+' 79%,'+pb.ui.color1+' 100%);\
						background: -ms-linear-gradient(top, '+pb.ui.color2a+' 0%,'+pb.ui.color2+' 50%,'+pb.ui.color1+' 79%,'+pb.ui.color1+' 100%);\
						background: linear-gradient(to bottom, '+pb.ui.color2a+' 0%,'+pb.ui.color2+' 50%,'+pb.ui.color1+' 79%,'+pb.ui.color1+' 100%);\
						filter: progid:DXImageTransform.Microsoft.gradient( startColorstr=\''+pb.ui.color2+'\', endColorstr=\''+pb.ui.color1+'\',GradientType=0 );\
						\
						color: white;\
					}\
					.main_bg_color{\
						background-color: #000000;\
					}\
					.second_bg_color{\
						background-color: #caccca;\
					}\
					.main_border_color{\
						border-color: '+pb.ui.color1+';\
					}\
					.second_border_color{\
						border-color: lightgrey;\
					}\
					.main_font_color{\
						border-color: #eeeeee;\
					}\
					.second_font_color{\
						border-color: lightgrey;\
					}\
					.icon img{\
						-webkit-filter: invert('+pb.ui.darkicons+');\
						filter: invert('+pb.ui.darkicons+');\
					}\
				');
				pb.closeDialog();
			},
			init: function(){
				$('#uiColorSelector1').ColorPicker({
					color: '#ffffff',
					onShow: function (colpkr) {
						$(colpkr).fadeIn(300);
						return false;
					},
					onHide: function (colpkr) {
						$(colpkr).fadeOut(300);
						return false;
					},
					onChange: function (hsb, hex, rgb) {
						$('#uiColorSelector1 div').css('backgroundColor', '#' + hex);
					}
				});
				$('#uiColorSelector2').ColorPicker({
					color: '#ffffff',
					onShow: function (colpkr) {
						$(colpkr).fadeIn(300);
						return false;
					},
					onHide: function (colpkr) {
						$(colpkr).fadeOut(300);
						return false;
					},
					onChange: function (hsb, hex, rgb) {
						$('#uiColorSelector2 div').css('backgroundColor', '#' + hex);
					}
				});
				$('#uiColorSelector3').ColorPicker({
					color: '#ffffff',
					onShow: function (colpkr) {
						$(colpkr).fadeIn(300);
						return false;
					},
					onHide: function (colpkr) {
						$(colpkr).fadeOut(300);
						return false;
					},
					onChange: function (hsb, hex, rgb) {
						$('#uiColorSelector3 div').css('backgroundColor', '#' + hex);
					}
				});
				$('#uiColorSelector4').ColorPicker({
					color: '#ffffff',
					onShow: function (colpkr) {
						$(colpkr).fadeIn(300);
						return false;
					},
					onHide: function (colpkr) {
						$(colpkr).fadeOut(300);
						return false;
					},
					onChange: function (hsb, hex, rgb) {
						$('#uiColorSelector4 div').css('backgroundColor', '#' + hex);
					}
				});
			}
		});
	});
	
	$("#windowmenuitem3").click(function(e){
		pb.closeMenu('window'); 
		var thisid = "button_library_label";
		$(".tools_item").removeClass('layerD').addClass('layerC');
		$(".tools_item_label").css({'background-color': '#caccca'});
		$('#'+thisid.substring(0,thisid.length-6)).removeClass('layerC').addClass('layerD');
		$('#'+thisid).css({'background-color': '#eeeeee'});
		$('.libraryselected').removeClass('libraryselected');
		return false;
	});
	$("#windowmenuitem4").click(function(e){
		pb.closeMenu('window'); 
		var thisid = "widget_library_label";
		$(".tools_item").removeClass('layerD').addClass('layerC');
		$(".tools_item_label").css({'background-color': '#caccca'});
		$('#'+thisid.substring(0,thisid.length-6)).removeClass('layerC').addClass('layerD');
		$('#'+thisid).css({'background-color': '#eeeeee'});
		$('.libraryselected').removeClass('libraryselected');
		return false;
	});
	$("#windowmenuitem5").click(function(e){
		pb.closeMenu('window'); 
		var thisid = "template_library_label";
		$(".tools_item").removeClass('layerD').addClass('layerC');
		$(".tools_item_label").css({'background-color': '#caccca'});
		$('#'+thisid.substring(0,thisid.length-6)).removeClass('layerC').addClass('layerD');
		$('#'+thisid).css({'background-color': '#eeeeee'});
		$('.libraryselected').removeClass('libraryselected');
		return false;
	});
	$("#windowmenuitem6").click(function(e){
		pb.closeMenu('window'); 
		var thisid = "panel_props_label";
		$(".tools_item").removeClass('layerD').addClass('layerC');
		$(".tools_item_label").css({'background-color': '#caccca'});
		$('#'+thisid.substring(0,thisid.length-6)).removeClass('layerC').addClass('layerD');
		$('#'+thisid).css({'background-color': '#eeeeee'});
		$('.libraryselected').removeClass('libraryselected');
		return false;
	});
	$("#helpmenuitem1, #helpmenuitem2, #helpmenuitem4").click(function(e){
		pb.closeMenu('help');
	});
	$("#helpmenuitem3").click(function(e){
		pb.closeMenu('help');
	});
	$("#helpmenuitem5").click(function(e){
		var type = ' N-Command';
		if (standalone) type = ' Standalone';
		if (wallcon) type = ' Wall Controller';
		if (modero) type = ' Wall Controller';
		pb.openDialog({
			content: '<div style="margin: 15px; text-align: center;"><span style="font-size: 18px;">Panel Builder'+type+'</span><br><br>&copy;SVSi 2015<br><br>version '+version+'</div>',
			confirm: 'ok',
			cancel: false,
			style: {
				height: '150px',
				'border-radius': '15px'
			},
			onConfirm: function(){pb.closeDialog();}
		});
		pb.closeMenu('help');
	});
	
	$("#left-arrow" ).click(pb.rotatePanelsLeft);
	$("#right-arrow" ).click(pb.rotatePanelsRight);
	
	$("#windowmenuitem2").click();
	$("#windowmenuitem7").click();
	setTimeout(function(){
		$('#resourcesidebar img').removeClass('fliph');
		$('#toolsidebar img').addClass('fliph');
	}, 1000);
	
	//*************************** BATCH EDIT ICONS ***************************//
	$('#border-button').click(function(){
		if (!$('.outlined').exists()){
			pb.openDialog({
				content: '<center>No item selected to edit.</center>',
				style: {height: '100px'},
				cancel: false,
				confirm: 'ok',
				onConfirm: function(){pb.closeDialog();}
			});
			return;
		}
		pb.openDialog({
			content: '<span style="font-size: 20px;">Enter border details for these items:</span><br><br>'+
			'Size: <input id="group_border" size="3" style="width: 45px;" value="0" type="text"/> px<br clear="all"><br>'+
			'Color: <div id="border-bgColorSelector" class="color {pickerFaceColor:\'#111\'}" title="Background Color" style=""><div style="background-color: #caccca"></div></div>',
			style: {height: '250px'},
			onConfirm: function(){
			
				var tempoutlined = $('.outlined' ).toArray();
				var outlined = [];
				var outlineditems = [];
				var outlinedwhs = [];
				var outlinedwhsb = [];
				for (var i=0; i<tempoutlined.length; i++) {
					if (pb.getItemById(tempoutlined[i].id).panel){
						outlined.push(tempoutlined[i]);
						outlineditems.push(pb.getItemById(tempoutlined[i].id));
						outlinedwhs.push({style: tempoutlined[i].style.cssText});
					}
				}
				
				var taction = new Action({
					type: 'style',
					items: outlineditems,
					oldvalues: outlinedwhs
				});
				
				var tcolor = $('#border-bgColorSelector div').css('backgroundColor');
				if (tcolor == 'rgba(0, 0, 0, 0)') tcolor = 'rgba(0, 0, 0, 1)';
				$('.outlined').css({'border-width': $('#group_border').val() + 'px', 'border-color': tcolor, 'border-style': 'solid'});
			
				for (var i=0;i<outlined.length;i++){
					outlinedwhsb.push({style: outlined[i].style.cssText});		
				}
				
				taction.newvalues = outlinedwhsb;
				pb.saveaction(taction);
				
				pb.closeDialog();
			
			},
			init: function(){
				var tn = parseInt($('.outlined')[0].style.borderWidth);
				if (isNaN(tn)) tn = 0;
				$('#group_border').val(tn);
			}
		});
	});
	$('#bteditor-button').click(function(){
		if (!$('.outlined').exists()){
			pb.openDialog({
				content: '<center>No item selected to edit.</center>',
				style: {height: '100px'},
				cancel: false,
				confirm: 'ok',
				onConfirm: function(){pb.closeDialog();}
			});
			return;
		}
		pb.openDialog({
			content: '<span style="font-size: 20px;">Enter item font options:</span><br><br>'+
				'font:&nbsp;&nbsp;<select id="group_font" name="font" >\
				  <option value="Arial">Arial</option>\
				  <option value="Impact">Impact</option>\
				  <option value="Georgia">Georgia</option>\
				  <option value="Times New Roman">Times New Roman</option>\
				</select><br><br>\
				color:&nbsp;&nbsp;<select id="group_fontcolor" name="fontcolor" >\
				  <option value="Black">Black</option>\
				  <option value="Red">Red</option>\
				  <option value="Green">Green</option>\
				  <option value="Blue">Blue</option>\
				  <option value="White">White</option>\
				</select><br><br>\
				size:&nbsp;&nbsp;<select id="group_fontsize" name="fontsize" >\
				  <option value="8">8</option>\
				  <option value="12">12</option>\
				  <option value="18">18</option>\
				  <option value="24">24</option>\
				  <option value="36">36</option>\
				  <option value="48">48</option>\
				  <option value="72">72</option>\
				</select>',
			onConfirm: function(){
				/*$('.outlined').css({'font-family': $('#group_font').val(),
					'color': $('#group_fontcolor').val(),
					'font-size': $('#group_fontsize').val() + 'px'});*/
				$('.outlined').each(function(index){
					var self = pb.getItemById($(this)[0].id);
					
					$(self.textnode).css({'font-family': $('#group_font').val(),
						'color': $('#group_fontcolor').val(),
						'font-size': $('#group_fontsize').val() + 'px'});
					$(self.textnode).find('*').css({'font-family': $('#group_font').val(),
						'color': $('#group_fontcolor').val(),
						'font-size': $('#group_fontsize').val() + 'px'});
						
					var theight = ($(self.element).outerHeight()/2)
						- ($(self.textnode).outerHeight()/2);
					$(self.textnode).css('top', theight + 'px');
				});
				pb.closeDialog();
			},
			init: function(){
				switch ($('.outlined')[0].style.fontFamily) {
					case 'Arial':
						$('#group_font')[0].selectedIndex = 0;
						break;
					case 'Impact':
						$('#group_font')[0].selectedIndex = 1;
						break;
					case 'Georgia':
						$('#group_font')[0].selectedIndex = 2;
						break;
					case '\'Times New Roman\'':
						$('#group_font')[0].selectedIndex = 3;
						break;
					default:
						break;
				}
				switch ($('.outlined')[0].style.fontSize) {
					case '8px':
						$('#group_fontsize')[0].selectedIndex = 0;
						break;
					case '12px':
						$('#group_fontsize')[0].selectedIndex = 1;
						break;
					case '18px':
						$('#group_fontsize')[0].selectedIndex = 2;
						break;
					case '24px':
						$('#group_fontsize')[0].selectedIndex = 3;
						break;
					case '36px':
						$('#group_fontsize')[0].selectedIndex = 4;
						break;
					case '48px':
						$('#group_fontsize')[0].selectedIndex = 5;
						break;
					case '72px':
						$('#group_fontsize')[0].selectedIndex = 6;
						break;
					default:
						break;
				}
				switch ($('.outlined')[0].style.color) {
					case 'rgb(0, 0, 0)':
						$('#group_fontcolor')[0].selectedIndex = 0;
						break;
					case 'rgb(255, 0, 0)':
						$('#group_fontcolor')[0].selectedIndex = 1;
						break;
					case 'rgb(0, 128, 0)':
						$('#group_fontcolor')[0].selectedIndex = 2;
						break;
					case 'rgb(0, 0, 128)':
						$('#group_fontcolor')[0].selectedIndex = 3;
						break;
					case 'rgb(255, 255, 255)':
						$('#group_fontcolor')[0].selectedIndex = 4;
						break;
					default:
						break;
				}
			}
		});
	});
	$('#shape-button').click(function(){
	
		if (!$('.outlined').exists()){
			pb.openDialog({
				content: '<center>No item selected to edit.</center>',
				style: {height: '100px'},
				cancel: false,
				confirm: 'ok',
				onConfirm: function(){pb.closeDialog();}
			});
			return;
		}
		
		pb.openDialog({
			content: '<span style="font-size: 20px;">Enter border radii for items:</span><br><br>'+
				'<div style="width: 55%; position: relative; left: 80px;">Top-left: <span style="float: right;"> px &nbsp;&nbsp;</span>&nbsp;<input id="group_tl" size="3" style="width: 45px; float: right;" value="0" type="text"/><br clear="all"><br>\
				Top-right: <span style="float: right;"> px &nbsp;&nbsp;</span>&nbsp;<input id="group_tr" size="3" style="width: 45px; float: right;" value="0" type="text"/><br clear="all"><br>\
				Bottom-left: <span style="float: right;"> px &nbsp;&nbsp;</span>&nbsp;<input id="group_bl" size="3" style="width: 45px; float: right;" value="0" type="text"/><br clear="all"><br>\
				Bottom-right: <span style="float: right;"> px &nbsp;&nbsp;</span>&nbsp;<input id="group_br" size="3" style="width: 45px; float: right;" value="0" type="text"/></div>',
			style: {height: '270px'},
			onConfirm: function(){
				$('.outlined').css({'border-radius': 
					parseInt($('#group_tl').val()) + 'px '
					+ parseInt($('#group_tr').val()) + 'px '
					+ parseInt($('#group_br').val()) + 'px '
					+ parseInt($('#group_bl').val()) + 'px '});
					
				pb.closeDialog();
			},
			init: function(){
				var ttl = parseInt($('.outlined')[0].style.borderTopLeftRadius);
				if (isNaN(ttl)) ttl = 0;
				var ttr = parseInt($('.outlined')[0].style.borderTopRightRadius);
				if (isNaN(ttr)) ttr = 0;
				var tbl = parseInt($('.outlined')[0].style.borderBottomLeftRadius);
				if (isNaN(tbl)) tbl = 0;
				var tbr = parseInt($('.outlined')[0].style.borderBottomRightRadius);
				if (isNaN(tbr)) tbr = 0;
				
				$('#group_tl').val(ttl);
				$('#group_tr').val(ttr);
				$('#group_bl').val(tbl);
				$('#group_br').val(tbr);
			}
		});
	});
	$('#alignleft-button').click(function(){
	
		if (!$('.outlined').exists()){
			pb.openDialog({
				content: '<center>No item selected to edit.</center>',
				style: {height: '100px'},
				cancel: false,
				confirm: 'ok',
				onConfirm: function(){pb.closeDialog();}
			});
			return;
		}
		
		var tempoutlined = $('.outlined' ).toArray();
		var outlined = [];
		var outlineditems = [];
		var outlinedwhs = [];
		var outlinedwhsb = [];
		for (var i=0; i<tempoutlined.length; i++) {
			if (pb.getItemById(tempoutlined[i].id).panel){
				outlined.push(tempoutlined[i]);
				outlineditems.push(pb.getItemById(tempoutlined[i].id));
				outlinedwhs.push({top: tempoutlined[i].style.top, left: tempoutlined[i].style.left});
			}
		}
		
		var lmost = parseInt($('.first')[0].style.left);

		var taction = new Action({
			type: 'move',
			items: outlineditems,
			oldvalues: outlinedwhs
		});
		
		$(".outlined" ).css({left: lmost + 'px'});
		
		for (var i=0;i<outlined.length;i++){
			outlinedwhsb.push({top: outlined[i].style.top, left: outlined[i].style.left});		
		}
		
		taction.newvalues = outlinedwhsb;
		pb.saveaction(taction);
		
	});
	$('#alignright-button').click(function(){
	
		if (!$('.outlined').exists()){
			pb.openDialog({
				content: '<center>No item selected to edit.</center>',
				style: {height: '100px'},
				cancel: false,
				confirm: 'ok',
				onConfirm: function(){pb.closeDialog();}
			});
			return;
		}
		
		var tempoutlined = $('.outlined' ).toArray();
		var outlined = [];
		var outlineditems = [];
		var outlinedwhs = [];
		var outlinedwhsb = [];
		for (var i=0; i<tempoutlined.length; i++) {
			if (pb.getItemById(tempoutlined[i].id).panel){
				outlined.push(tempoutlined[i]);
				outlineditems.push(pb.getItemById(tempoutlined[i].id));
				outlinedwhs.push({top: tempoutlined[i].style.top, left: tempoutlined[i].style.left});
			}
		}
		
		var rmost = parseInt($('.first')[0].style.left) + parseInt($('.first')[0].style.width);
		
		var taction = new Action({
			type: 'move',
			items: outlineditems,
			oldvalues: outlinedwhs
		});
		for (var i=0; i<outlined.length; i++){
			outlined[i].style.left = (rmost - parseInt(outlined[i].style.width)) + 'px';
		}
		for (var i=0;i<outlined.length;i++){
			outlinedwhsb.push({top: outlined[i].style.top, left: outlined[i].style.left});		
		}
		
		taction.newvalues = outlinedwhsb;
		pb.saveaction(taction);
		
	});
	$('#aligntop-button').click(function(){
	
		if (!$('.outlined').exists()){
			pb.openDialog({
				content: '<center>No item selected to edit.</center>',
				style: {height: '100px'},
				cancel: false,
				confirm: 'ok',
				onConfirm: function(){pb.closeDialog();}
			});
			return;
		}
		
		var tempoutlined = $('.outlined' ).toArray();
		var outlined = [];
		var outlineditems = [];
		var outlinedwhs = [];
		var outlinedwhsb = [];
		for (var i=0; i<tempoutlined.length; i++) {
			if (pb.getItemById(tempoutlined[i].id).panel){
				outlined.push(tempoutlined[i]);
				outlineditems.push(pb.getItemById(tempoutlined[i].id));
				outlinedwhs.push({top: tempoutlined[i].style.top, left: tempoutlined[i].style.left});
			}
		}
		
		var tmost = parseInt($('.first')[0].style.top);
		
		var taction = new Action({
			type: 'move',
			items: outlineditems,
			oldvalues: outlinedwhs
		});
		$(".outlined" ).css({top: tmost + 'px'});
		for (var i=0;i<outlined.length;i++){
			outlinedwhsb.push({top: outlined[i].style.top, left: outlined[i].style.left});		
		}
		
		taction.newvalues = outlinedwhsb;
		pb.saveaction(taction);
		
	});
	$('#alignbottom-button').click(function(){
	
		if (!$('.outlined').exists()){
			pb.openDialog({
				content: '<center>No item selected to edit.</center>',
				style: {height: '100px'},
				cancel: false,
				confirm: 'ok',
				onConfirm: function(){pb.closeDialog();}
			});
			return;
		}
		
		var tempoutlined = $('.outlined' ).toArray();
		var outlined = [];
		var outlineditems = [];
		var outlinedwhs = [];
		var outlinedwhsb = [];
		for (var i=0; i<tempoutlined.length; i++) {
			if (pb.getItemById(tempoutlined[i].id).panel){
				outlined.push(tempoutlined[i]);
				outlineditems.push(pb.getItemById(tempoutlined[i].id));
				outlinedwhs.push({top: tempoutlined[i].style.top, left: tempoutlined[i].style.left})
			}
		}
		
		var bmost = parseInt($('.first')[0].style.top) + parseInt($('.first')[0].style.height);
		
		var taction = new Action({
			type: 'move',
			items: outlineditems,
			oldvalues: outlinedwhs
		});
		for (var i=0; i<outlined.length; i++){
			outlined[i].style.top = (bmost - parseInt(outlined[i].style.height)) + 'px';
		}
		for (var i=0;i<outlined.length;i++){
			outlinedwhsb.push({top: outlined[i].style.top, left: outlined[i].style.left});		
		}
		
		taction.newvalues = outlinedwhsb;
		pb.saveaction(taction);
		
	});
	$('#alignh-button').click(function(){
	
		if (!$('.outlined').exists()){
			pb.openDialog({
				content: '<center>No item selected to edit.</center>',
				style: {height: '100px'},
				cancel: false,
				confirm: 'ok',
				onConfirm: function(){pb.closeDialog();}
			});
			return;
		}
		
		var tempoutlined = $('.outlined' ).toArray();
		var outlined = [];
		var outlineditems = [];
		var outlinedwhs = [];
		var outlinedwhsb = [];
		for (var i=0; i<tempoutlined.length; i++) {
			if (pb.getItemById(tempoutlined[i].id).panel){
				outlined.push(tempoutlined[i]);
				outlineditems.push(pb.getItemById(tempoutlined[i].id));
				outlinedwhs.push({top: tempoutlined[i].style.top, left: tempoutlined[i].style.left});
			}
		}
		
		var taction = new Action({
			type: 'move',
			items: outlineditems,
			oldvalues: outlinedwhs
		});
		var average = 0;
		for (var i=0; i<outlined.length; i++){
			average += parseInt(outlined[i].style.top) + (parseInt(outlined[i].style.height)/2);
		}
		average /= outlined.length;
		for (var i=0; i<outlined.length; i++){
			outlined[i].style.top = average - (parseInt(outlined[i].style.height)/2) + 'px';
		}
		
		for (var i=0;i<outlined.length;i++){
			outlinedwhsb.push({top: outlined[i].style.top, left: outlined[i].style.left});		
		}
		
		var taction = new Action({
			type: 'move',
			items: outlineditems,
			oldvalues: outlinedwhs
		});
		
		var panelwidth = parseInt(pb.currentpanel.element.style.width);
		var spacing = parseInt(panelwidth/(outlined.length+1));
		
		var swapped;
		do{
			swapped = false;
			for (var i=0;i<outlined.length-1;i++){
				if (parseInt(outlined[i].style.left) > parseInt(outlined[i+1].style.left)) {
					var tempsort = outlined[i];
					outlined[i] = outlined[i+1];
					outlined[i+1] = tempsort;
					swapped = true;
				}
			}
		}while(swapped);
		
		for (var i=0;i<outlined.length;i++){
			$(outlined[i]).css({left: (((i+1)*spacing) - ($(outlined[i]).outerWidth()/2)) + 'px'});
			outlinedwhsb.push({top: outlined[i].style.top, left: outlined[i].style.left});		
		}
		
		taction.newvalues = outlinedwhsb;
		pb.saveaction(taction);
		
	});
	$('#alignv-button').click(function(){
	
		if (!$('.outlined').exists()){
			pb.openDialog({
				content: '<center>No item selected to edit.</center>',
				style: {height: '100px'},
				cancel: false,
				confirm: 'ok',
				onConfirm: function(){pb.closeDialog();}
			});
			return;
		}
		
		var tempoutlined = $('.outlined' ).toArray();
		var outlined = [];
		var outlineditems = [];
		var outlinedwhs = [];
		var outlinedwhsb = [];
		for (var i=0; i<tempoutlined.length; i++) {
			if (pb.getItemById(tempoutlined[i].id).panel){
				outlined.push(tempoutlined[i]);
				outlineditems.push(pb.getItemById(tempoutlined[i].id));
				outlinedwhs.push({top: tempoutlined[i].style.top, left: tempoutlined[i].style.left});
			}
		}
		
		var taction = new Action({
			type: 'move',
			items: outlineditems,
			oldvalues: outlinedwhs
		});
		
		var panelheight = parseInt(pb.currentpanel.element.style.height);
		var spacing = parseInt(panelheight/(outlined.length+1));
		
		var outlined2 = [];

		var swapped;
		do{
			swapped = false;
			for (var i=0;i<outlined.length-1;i++){
				if (parseInt(outlined[i].style.top) > parseInt(outlined[i+1].style.top)) {
					var tempsort = outlined[i];
					outlined[i] = outlined[i+1];
					outlined[i+1] = tempsort;
					swapped = true;
				}
			}
		}while(swapped);
			
		for (var i=0;i<outlined.length;i++){
			$(outlined[i]).css({top: (((i+1)*spacing) - ($(outlined[i]).outerHeight()/2)) + 'px'});
			outlinedwhsb.push({top: outlined[i].style.top, left: outlined[i].style.left});		
		}
		
		var taction = new Action({
			type: 'move',
			items: outlineditems,
			oldvalues: outlinedwhs
		});
		var average = 0;
		for (var i=0; i<outlined.length; i++){
			average += parseInt(outlined[i].style.left) + (parseInt(outlined[i].style.width)/2);
		}
		average /= outlined.length;
		for (var i=0; i<outlined.length; i++){
			outlined[i].style.left = average - (parseInt(outlined[i].style.width)/2) + 'px';
		}
		
		for (var i=0;i<outlined.length;i++){
			outlinedwhsb.push({top: outlined[i].style.top, left: outlined[i].style.left});		
		}
		
		taction.newvalues = outlinedwhsb;
		pb.saveaction(taction);
		
	});
	$('#aligng-button').click(function(){
	
		if (!$('.outlined').exists()){
			pb.openDialog({
				content: '<center>No item selected to edit.</center>',
				style: {height: '100px'},
				cancel: false,
				confirm: 'ok',
				onConfirm: function(){pb.closeDialog();}
			});
			return;
		}
	
		pb.openDialog({
			content: '<span style="font-size: 20px;">Enter the number of rows/columns for the grid:</span><br><br>'+
				'<div style="width: 280px; position: relative; left: 76px; top: 15px;">\
					rows: <input id="group_rows" size="3" style="width: 45px; float: right;" value="0" type="text"/><br clear="all"><br>\
					columns: <input id="group_columns" size="3" style="width: 45px; float: right;" value="0" type="text"/>\
				</div>',
			style: {height: '210px', width: '480px'},
			onConfirm: function(){
				var tempoutlined = $('.outlined' ).toArray();
				var outlined = [];
				var outlineditems = [];
				var outlinedwhs = [];
				var outlinedwhsb = [];
				for (var i=0; i<tempoutlined.length; i++) {
					if (pb.getItemById(tempoutlined[i].id).panel){
						outlined.push(tempoutlined[i]);
						outlineditems.push(pb.getItemById(tempoutlined[i].id));
						outlinedwhs.push({top: tempoutlined[i].style.top, left: tempoutlined[i].style.left});
					}
				}
				
				var taction = new Action({
					type: 'move',
					items: outlineditems,
					oldvalues: outlinedwhs
				});
						
				var rows = parseInt($('#group_columns').val());
				var cols = parseInt($('#group_rows').val());
				
				var rowoffset = parseInt(pb.currentpanel.element.style.width)/(rows+1);
				var coloffset = parseInt(pb.currentpanel.element.style.height)/(cols+1);
				
				
				
				var k = 0;
				for (var i=0; i<cols; i++){
					if (undef(outlined[k])) break;
					for (var j=0; j<rows; j++){
						if (undef(outlined[k])) break;
						outlined[k].style.top = (coloffset*(i+1))-(parseInt(outlined[k].style.height)/2)+'px';
						outlined[k].style.left = (rowoffset*(j+1))-(parseInt(outlined[k].style.width)/2)+'px';
						
						k++;
					}
				
				}
				
				for (var i=0;i<outlined.length;i++){
					outlinedwhsb.push({top: outlined[i].style.top, left: outlined[i].style.left});		
				}
				
				taction.newvalues = outlinedwhsb;
				pb.saveaction(taction);
				
				pb.closeDialog();
				
			}
		});

	});
	$('#spacex-button').click(function(){
		if (!$('.outlined').exists()){
			pb.openDialog({
				content: '<center>No item selected to edit.</center>',
				style: {height: '100px'},
				cancel: false,
				confirm: 'ok',
				onConfirm: function(){pb.closeDialog();}
			});
			return;
		}
		var tempoutlined = $('.outlined' ).toArray();
		var outlined = [];
		var outlineditems = [];
		var outlinedwhs = [];
		var outlinedwhsb = [];
		for (var i=0; i<tempoutlined.length; i++) {
			if (pb.getItemById(tempoutlined[i].id).panel){
				outlined.push(tempoutlined[i]);
				outlineditems.push(pb.getItemById(tempoutlined[i].id));
				outlinedwhs.push({top: tempoutlined[i].style.top, left: tempoutlined[i].style.left});
			}
		}
		
		var taction = new Action({
			type: 'move',
			items: outlineditems,
			oldvalues: outlinedwhs
		});
		
		var panelwidth = parseInt(pb.currentpanel.element.style.width);
		var spacing = parseInt(panelwidth/(outlined.length+1));
		
		var swapped;
		do{
			swapped = false;
			for (var i=0;i<outlined.length-1;i++){
				if (parseInt(outlined[i].style.left) > parseInt(outlined[i+1].style.left)) {
					var tempsort = outlined[i];
					outlined[i] = outlined[i+1];
					outlined[i+1] = tempsort;
					swapped = true;
				}
			}
		}while(swapped);
		
		for (var i=0;i<outlined.length;i++){
			$(outlined[i]).css({left: (((i+1)*spacing) - ($(outlined[i]).outerWidth()/2)) + 'px'});
			outlinedwhsb.push({top: outlined[i].style.top, left: outlined[i].style.left});		
		}
		
		taction.newvalues = outlinedwhsb;
		pb.saveaction(taction);
		
	});
	$('#spacey-button').click(function(){
		if (!$('.outlined').exists()){
			pb.openDialog({
				content: '<center>No item selected to edit.</center>',
				style: {height: '100px'},
				cancel: false,
				confirm: 'ok',
				onConfirm: function(){pb.closeDialog();}
			});
			return;
		}
		var tempoutlined = $('.outlined' ).toArray();
		var outlined = [];
		var outlineditems = [];
		var outlinedwhs = [];
		var outlinedwhsb = [];
		for (var i=0; i<tempoutlined.length; i++) {
			if (pb.getItemById(tempoutlined[i].id).panel){
				outlined.push(tempoutlined[i]);
				outlineditems.push(pb.getItemById(tempoutlined[i].id));
				outlinedwhs.push({top: tempoutlined[i].style.top, left: tempoutlined[i].style.left});
			}
		}
		
		var taction = new Action({
			type: 'move',
			items: outlineditems,
			oldvalues: outlinedwhs
		});
		
		var panelheight = parseInt(pb.currentpanel.element.style.height);
		var spacing = parseInt(panelheight/(outlined.length+1));
		
		var outlined2 = [];

		var swapped;
		do{
			swapped = false;
			for (var i=0;i<outlined.length-1;i++){
				if (parseInt(outlined[i].style.top) > parseInt(outlined[i+1].style.top)) {
					var tempsort = outlined[i];
					outlined[i] = outlined[i+1];
					outlined[i+1] = tempsort;
					swapped = true;
				}
			}
		}while(swapped);
			
		for (var i=0;i<outlined.length;i++){
			$(outlined[i]).css({top: (((i+1)*spacing) - ($(outlined[i]).outerHeight()/2)) + 'px'});
			outlinedwhsb.push({top: outlined[i].style.top, left: outlined[i].style.left});		
		}
		
		taction.newvalues = outlinedwhsb;
		pb.saveaction(taction);
	});
	
	$('#aligntext-button').click(function(){
		if (!$('.outlined').exists()){
			pb.openDialog({
				content: '<center>No item selected to edit.</center>',
				style: {height: '100px'},
				cancel: false,
				confirm: 'ok',
				onConfirm: function(){pb.closeDialog();}
			});
			return;
		}
		pb.openDialog({
			content: '<span style="font-size: 20px;">Enter the text offset for these items:</span><br><br>'+
			'<div style="width: 280px; position: relative; left: 36px; top: 15px;">\
				x: <input id="group_textoffsetx" size="3" style="width: 45px; float: right;" value="0" type="text"/> px<br clear="all"><br>\
				y: <input id="group_textoffsety" size="3" style="width: 45px; float: right;" value="0" type="text"/> px\
			</div>',
			style: {height: '200px'},
			onConfirm: function(){
				var tempoutlined = $('.outlined' ).toArray();
				var outlined = [];
				for (var i=0; i<tempoutlined.length; i++) {
					if (pb.getItemById(tempoutlined[i].id).panel) outlined.push(tempoutlined[i]);
				}
				for (var i=0; i<outlined.length; i++){
					pb.getItemById(outlined[i].id).textnode.style.marginLeft = $('#group_textoffsetx').val() + 'px';
					pb.getItemById(outlined[i].id).textoffsetx = $('#group_textoffsetx').val();
					pb.getItemById(outlined[i].id).textnode.style.marginTop = -$('#group_textoffsety').val() + 'px';
					pb.getItemById(outlined[i].id).textoffsety = $('#group_textoffsety').val();
				}
				pb.closeDialog();
			},
			init: function(){
				if (!isNaN(parseInt(pb.getItemById($('.outlined')[0].id).textnode.style.marginLeft)))
					$("#group_textoffsetx" ).val(parseInt(pb.getItemById($('.outlined')[0].id).textnode.style.marginLeft));
						else $("#group_textoffsetx" ).val('0');
				if (!isNaN(parseInt(pb.getItemById($('.outlined')[0].id).textnode.style.marginTop)))
					$("#group_textoffsety" ).val(-parseInt(pb.getItemById($('.outlined')[0].id).textnode.style.marginTop));
						else $("#group_textoffsety" ).val('0');
			}
		});
	});
	$('#setwidth-button').click(function(){
		if (!$('.outlined').exists()){
			pb.openDialog({
				content: '<center>No item selected to edit.</center>',
				style: {height: '100px'},
				cancel: false,
				confirm: 'ok',
				onConfirm: function(){pb.closeDialog();}
			});
			return;
		}
		pb.openDialog({
			content: '<span style="font-size: 20px;">Enter new width for these items:</span><br><br>'+
			'<div style="position: relative; width: 100%; text-align: center;">\
				<input id="group_width" size="3" style="width: 45px;" value="0" type="text"/> px\
			</div>',
			style: {height: '150px'},
			onConfirm: function(){
				
				var tempoutlined = $('.outlined' ).toArray();
				var outlined = [];
				var outlineditems = [];
				var outlinedwhs = [];
				var outlinedwhsb = [];
				for (var i=0; i<tempoutlined.length; i++) {
					if (pb.getItemById(tempoutlined[i].id).panel){
						outlined.push(tempoutlined[i]);
						outlineditems.push(pb.getItemById(tempoutlined[i].id));
						outlinedwhs.push({width: tempoutlined[i].style.width,
							height: tempoutlined[i].style.height});
					}
				}
				
				$(".outlined" ).css({width: $('#group_width').val() + 'px'});
				
				var taction = new Action({
					type: 'size',
					items: outlineditems,
					oldvalues: outlinedwhs
				});
				
				for (var i=0; i<outlined.length; i++){
					var panelbb = pb.currentpanel.element.getBoundingClientRect();
					var buttonbb = outlined[i].getBoundingClientRect();
					if (parseInt(outlined[i].style.width) > parseInt(pb.currentpanel.element.style.width)){
						outlined[i].style.width = pb.currentpanel.element.style.width;
					}
					if (parseInt(outlined[i].style.height) > parseInt(pb.currentpanel.element.style.height)){
						outlined[i].style.height = pb.currentpanel.element.style.height;
					}
					
					if (buttonbb.right > panelbb.right){
						outlined[i].style.left = parseInt(pb.currentpanel.element.style.width) - parseInt(outlined[i].style.width) + 'px';
					}
					if (buttonbb.bottom > panelbb.bottom){
						outlined[i].style.top = parseInt(pb.currentpanel.element.style.height) - parseInt(outlined[i].style.height) + 'px';
					}
					
					outlinedwhsb.push({width: outlined[i].style.width, height: outlined[i].style.height});
					
				}
				
				
				taction.newvalues = outlinedwhsb;
				pb.saveaction(taction);
				
				pb.closeDialog();
				
			},
			init: function(){
				$("#group_width" ).val(parseInt($('.outlined')[0].style.width));
			}
		});
	});
	$('#setheight-button').click(function(){
		if (!$('.outlined').exists()){
			pb.openDialog({
				content: '<center>No item selected to edit.</center>',
				style: {height: '100px'},
				cancel: false,
				confirm: 'ok',
				onConfirm: function(){pb.closeDialog();}
			});
			return;
		}
		pb.openDialog({
			content: '<span style="font-size: 20px;">Enter new height for these items:</span><br><br>'+
			'<div style="position: relative; width: 100%; text-align: center;">\
				<input id="group_height" size="3" style="width: 45px;" value="0" type="text"/> px\
			</div>',
			style: {height: '150px'},
			onConfirm: function(){
				
				var tempoutlined = $('.outlined' ).toArray();
				
				var outlined = [];
				var outlineditems = [];
				var outlinedwhs = [];
				var outlinedwhsb = [];
				
				for (var i=0; i<tempoutlined.length; i++) {
					if (pb.getItemById(tempoutlined[i].id).panel){
						outlined.push(tempoutlined[i]);
						outlineditems.push(pb.getItemById(tempoutlined[i].id));
						outlinedwhs.push({width: tempoutlined[i].style.width, height: tempoutlined[i].style.height});
						//console.log(outlinedwhs[i]);
					}
				}
				
				$(".outlined" ).css({height: $('#group_height').val() + 'px'});
				
				var taction = new Action({
					type: 'size',
					items: outlineditems,
					oldvalues: outlinedwhs
				});
				
				for (var i=0; i<outlined.length; i++){
					var panelbb = pb.currentpanel.element.getBoundingClientRect();
					var buttonbb = outlined[i].getBoundingClientRect();
					if (parseInt(outlined[i].style.width) > parseInt(pb.currentpanel.element.style.width)){
						outlined[i].style.width = pb.currentpanel.element.style.width;
					}
					if (parseInt(outlined[i].style.height) > parseInt(pb.currentpanel.element.style.height)){
						outlined[i].style.height = pb.currentpanel.element.style.height;
					}
					if (buttonbb.right > panelbb.right){
						outlined[i].style.left = parseInt(pb.currentpanel.element.style.width) - parseInt(outlined[i].style.width) + 'px';
					}
					if (buttonbb.bottom > panelbb.bottom){
						outlined[i].style.top = parseInt(pb.currentpanel.element.style.height) - parseInt(outlined[i].style.height) + 'px';
					}
					outlinedwhsb.push({width: outlined[i].style.width, height: outlined[i].style.height});
					
				}
				
				
				taction.newvalues = outlinedwhsb;
				pb.saveaction(taction);
				
				pb.closeDialog();
				
			}
		});
	});
	$('#centerh-button').click(function(){
	
		if (!$('.outlined').exists()){
			pb.openDialog({
				content: '<center>No item selected to edit.</center>',
				style: {height: '100px'},
				cancel: false,
				confirm: 'ok',
				onConfirm: function(){pb.closeDialog();}
			});
			return;
		}
		
		var tempoutlined = $('.outlined').toArray();
		var outlined = [];
		var outlineditems = [];
		var outlinedwhs = [];
		var outlinedwhsb = [];
		
		for (var i=0; i<tempoutlined.length; i++) {
			if (pb.getItemById(tempoutlined[i].id).panel){
				outlined.push(tempoutlined[i]);
				outlineditems.push(pb.getItemById(tempoutlined[i].id));
				outlinedwhs.push({top: tempoutlined[i].style.top,
					left: tempoutlined[i].style.left});
			}
		}
		
		var taction = new Action({
			type: 'move',
			items: outlineditems,
			oldvalues: outlinedwhs
		});

		for (var i=0;i<outlined.length;i++){
			$(outlined[i]).css({left: ((parseInt(pb.currentpanel.element.style.width)/2) - parseInt(outlined[i].style.width)/2) + 'px'});
			
			outlinedwhsb.push({top: outlined[i].style.top, left: outlined[i].style.left});
					
		}
		
		taction.newvalues = outlinedwhsb;
		pb.saveaction(taction);
		
	});
	$('#centerv-button').click(function(){
	
		if (!$('.outlined').exists()){
			pb.openDialog({
				content: '<center>No item selected to edit.</center>',
				style: {height: '100px'},
				cancel: false,
				confirm: 'ok',
				onConfirm: function(){pb.closeDialog();}
			});
			return;
		}
		
		var tempoutlined = $('.outlined' ).toArray();
		var outlined = [];
		var outlineditems = [];
		var outlinedwhs = [];
		var outlinedwhsb = [];
		for (var i=0; i<tempoutlined.length; i++) {
			if (pb.getItemById(tempoutlined[i].id).panel){
				outlined.push(tempoutlined[i]);
				outlineditems.push(pb.getItemById(tempoutlined[i].id));
				outlinedwhs.push({top: tempoutlined[i].style.top, left: tempoutlined[i].style.left});
			}
		}
		
		var taction = new Action({
			type: 'move',
			items: outlineditems,
			oldvalues: outlinedwhs
		});
		for (var i=0;i<outlined.length;i++){
			$(outlined[i]).css({top: ((parseInt(pb.currentpanel.element.style.height)/2) - parseInt(outlined[i].style.height)/2) + 'px'});
			outlinedwhsb.push({top: outlined[i].style.top, left: outlined[i].style.left});
					
		}
		
		taction.newvalues = outlinedwhsb;
		pb.saveaction(taction);
		
	});
	$('#centerb-button').click(function(){
	
		if (!$('.outlined').exists()){
			pb.openDialog({
				content: '<center>No item selected to edit.</center>',
				style: {height: '100px'},
				cancel: false,
				confirm: 'ok',
				onConfirm: function(){pb.closeDialog();}
			});
			return;
		}
		
		var tempoutlined = $('.outlined' ).toArray();
		var outlined = [];
		var outlineditems = [];
		var outlinedwhs = [];
		var outlinedwhsb = [];
		
		for (var i=0; i<tempoutlined.length; i++) {
			if (pb.getItemById(tempoutlined[i].id).panel){
				outlined.push(tempoutlined[i]);
				outlineditems.push(pb.getItemById(tempoutlined[i].id));
				outlinedwhs.push({top: tempoutlined[i].style.top, left: tempoutlined[i].style.left});
			}
		}
		
		var taction = new Action({
			type: 'move',
			items: outlineditems,
			oldvalues: outlinedwhs
		});
		
		$(".outlined" ).css({left: (((parseInt(pb.currentpanel.element.style.width)/2) - parseInt(outlined[0].style.width)/2 - 0) + 0) + 'px'});
		$(".outlined" ).css({top: (((parseInt(pb.currentpanel.element.style.height)/2) - parseInt(outlined[0].style.height)/2 - 0) + 0) + 'px'});
		
		for (var i=0;i<outlined.length;i++){
		
			outlinedwhsb.push({top: outlined[i].style.top, left: outlined[i].style.left});
					
		}
		
		taction.newvalues = outlinedwhsb;
		pb.saveaction(taction);
	
	});
	$('#text-button').click(function(){
	
		if (!$('.outlined').exists()){
			pb.openDialog({
				content: '<center>No item selected to edit.</center>',
				style: {height: '100px'},
				cancel: false,
				confirm: 'ok',
				onConfirm: function(){pb.closeDialog();}
			});
			return;
		}
		
		pb.openDialog({
			content: 'Enter the new text for these items:<br><br>'+
				'<input id="group_text" size="3" style="width: 135px;" value="" type="text"/>',
			onConfirm: function(){
				var outlined = $('.outlined' ).toArray();
				for (var i=0; i<outlined.length; i++){
					pb.getItemById(outlined[i].id).textnode.lastChild.innerHTML = $('#group_text').val();
				}
				pb.closeDialog();
			},
			init: function(){
				var outlined = $('.outlined' ).toArray();
				$('#group_text').val(pb.getItemById(outlined[0].id).textnode.lastChild.innerHTML);
			}
		});
			
	});
	$('#copysize-button').click(function(){
	
		if (!$('.outlined').exists()){
			pb.openDialog({
				content: '<center>No item selected to edit.</center>',
				style: {height: '100px'},
				cancel: false,
				confirm: 'ok',
				onConfirm: function(){pb.closeDialog();}
			});
			return;
		}
		
		var tempoutlined = $('.outlined' ).toArray();
		var outlined = [];
		
		for (var i=0; i<tempoutlined.length; i++) {
			if (pb.getItemById(tempoutlined[i].id).panel) outlined.push(tempoutlined[i]);
		}
		for (var i=0; i<outlined.length; i++){
			outlined[i].style.width = $('.first')[0].style.width;
			outlined[i].style.height = $('.first')[0].style.height;
			pb.getItem(outlined[i].id).core.actualwidth = parseFloat(outlined[i].style.width);
			pb.getItem(outlined[i].id).core.actualheight = parseFloat(outlined[i].style.height);
		}
		
		var outlined = $('.outlined' ).toArray();
		
		for (var i=0; i<outlined.length; i++){
			var panelbb = pb.currentpanel.element.getBoundingClientRect();
			var buttonbb = outlined[i].getBoundingClientRect();
			if (parseInt(outlined[i].style.width) > parseInt(pb.currentpanel.element.style.width)){
				outlined[i].style.width = pb.currentpanel.element.style.width;
			}
			if (parseInt(outlined[i].style.height) > parseInt(pb.currentpanel.element.style.height)){
				outlined[i].style.height = pb.currentpanel.element.style.height;
			}
			if (buttonbb.right > panelbb.right){
				outlined[i].style.left = parseInt(pb.currentpanel.element.style.width) - parseInt(outlined[i].style.width) + 'px';
			}
			if (buttonbb.bottom > panelbb.bottom){
				outlined[i].style.top = parseInt(pb.currentpanel.element.style.height) - parseInt(outlined[i].style.height) + 'px';
			}
			var item = pb.getItem(outlined[i].id);
			if (item instanceof Button){
				item.centerText();
			}
		}
		
		pb.currentpanel.resize();
		
	});
	$('#master-button').click(function(){
		if (!pb.project.core.hasMaster) pb.openDialog({
				content: '<div>width:<input id="master-template-width" /><br>height:<input id="master-template-height" /></div>',
				style: {height: '100px'},
				cancel: 'cancel', confirm: 'ok',
				onConfirm: function(){
					var name = 'Master Template',
						width = $('#master-template-width').val() || 1024,
						height = $('#master-template-height').val() || 600;
					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'
					});
					newpanel.core.id = newpanel.element.id = "Master_Template";
					$('#labels').prepend('<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);
					var i = pb.user.panels.indexOf(newpanel);
					var t = pb.user.panels[0];
					pb.user.panels[0] = newpanel;
					pb.user.panels[1] = t;
					pb.project.core.hasMaster = true;
					pb.closeDialog();
				},
				onCancel: function(){
					pb.closeDialog();
				}
			});
		else {
			var found = false;
			for (var i=0; i<pb.user.panels.length; i++){
				if (pb.user.panels[i].core.id === 'Master_Template') found = pb.user.panels[i];
			}
			if (found) pb.switchToPanel(found);
		}
		
		/*pb.closeMenu(null, ['file','edit','add','view']);
		$('#add-panel-name').val('Panel-'+pb.panelindex);
		if (wallcon){
			$('#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);
		}*/
		
	});
	$('#clone-button').click(function(){
	
		if (!$('.outlined').exists()){
			pb.openDialog({
				content: '<center>No item selected to edit.</center>',
				style: {height: '100px'},
				cancel: false,
				confirm: 'ok',
				onConfirm: function(){pb.closeDialog();}
			});
			return;
		}
		
		var tempoutlined = $('.outlined' ).toArray();
		var outlined = [];
		var noutlined = [];
		
		for (var i=0; i<tempoutlined.length; i++) {
			if (pb.getItemById(tempoutlined[i].id).panel) outlined.push(tempoutlined[i]);
		}
		
		for (var i=0; i<outlined.length; i++){
		
			var clone = pb.getItemById(outlined[i].id).clone({
				extrastyle: 'left: '+(parseFloat(pb.getItemById(outlined[i].id).element.style.left)+20)
				+'px; top: '+(parseFloat(pb.getItemById(outlined[i].id).element.style.top)+20)+'px;'});
			pb.currentpanel.addChild(clone);
			var o = 0;
			var bbox = pb.currentpanel.element.getBoundingClientRect();
			
			clone.element.style.zIndex = 2000;
			clone.element.className = clone.element.className.replace('cloneable','');
			clone.container = pb.currentpanel.element;
			clone.texteditable = true;
			clone.element.className += ' draggable ';
			
			var elebox = clone.element.getBoundingClientRect();
			if (elebox.left < bbox.left) clone.element.style.left = '0px';
			if (elebox.top < bbox.top) clone.element.style.top = pb.currentpanel.element.style.top;
			if (elebox.right > bbox.right) clone.element.style.left =
				$(pb.currentpanel.element).outerWidth() - $(clone.element).outerWidth() + o + 'px';
			if (elebox.bottom > bbox.bottom) clone.element.style.top =
				$(pb.currentpanel.element).outerHeight() - $(clone.element).outerHeight() + o + 'px';
			clone.responsive = true;
			noutlined.push(clone);
			
		}
		
		$('.outlined').removeClass('outlined').removeClass('first');
		for (var i=0; i<noutlined.length; i++){
		
			$(noutlined[i].element).addClass('outlined');
			
		}
		
		var taction = new Action({
			type: 'clone',
			items: noutlined,
		});

		pb.saveaction(taction);
		if (pb.updateTree) pb.updateTree();
		
	});
	$('#fit-button').click(function(){
		if (pb.currentpanel){
			var tpanelwidth = parseInt(pb.currentpanel.element.style.width);
			var tpanelheight = parseInt(pb.currentpanel.element.style.height);
			var twindowwidth = window.innerWidth;
			var twindowheight = window.innerHeight-150;
			
			var s = (twindowwidth/tpanelwidth);
			var ts = (twindowheight/tpanelheight);
			
			s = ts;
			
			pb.currentpanel.core.scale = s;
			$(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+')',
			});
				
			var tml = (twindowwidth/2) - (tpanelwidth/2);
			pb.currentpanel.element.style.marginTop = (-tpanelheight*(1-s)/2) + 25 + 'px';		
			pb.currentpanel.element.style.marginLeft = tml + 'px';
			$('.panel-space-center').css({left: '0px'});
			
		}
	});
//*************************** END OF BATCH EDIT ICONS ***************************//
	
	$(".icon").not("#beditor-button").not("#peditor-button").hover(function(){
		$(this).css("opacity","1.0");
	},function(){
		$(this).css("opacity","0.9");
	});
	
	$(".arrowicon").hover(function(){
		$(this).css("opacity","1.0");
	},function(){
		$(this).css("opacity","0.9");
	});
	
	$("#beditor-button").hover(function(){
		if ($(".outlined").length == 1 && pb.getItemById($('.outlined')[0].id) instanceof Button)
			$(this).css("opacity","1.0");
	},function(){
		$(this).css("opacity","0.9");
	});
	
	$("#beditor-button").click(function(){
		if ($(".outlined").length == 1 && pb.getItemById($('.outlined')[0].id) instanceof Button)
			openItemEditor({item: pb.getItemById($('.outlined')[0].id)});
		else if ($(".outlined").length == 0){
			pb.openDialog({
				content: '<center>No item selected to edit.</center>',
				style: {height: '100px'},
				cancel: false,
				confirm: 'ok',
				onConfirm: function(){pb.closeDialog();}
			});
			return;
		}
		else if ($(".outlined").length > 1){
			pb.openDialog({
				content: '<center>Too many items selected to edit.</center>',
				style: {height: '100px'},
				cancel: false,
				confirm: 'ok',
				onConfirm: function(){pb.closeDialog();}
			});
			return;
		}
	});
	
	$("#weditor-button").hover(function(){
		if ($(".outlined").length == 1 && pb.getItemById($('.outlined')[0].id) instanceof Widget)
			$(this).css("opacity","1.0");
	},function(){
		$(this).css("opacity","0.9");
	});
	
	$("#weditor-button").click(function(){
		if ($(".outlined").length == 1 && pb.getItemById($('.outlined')[0].id) instanceof Widget)
			openWidgetEditor(pb.getItemById($('.outlined')[0].id));
	});
	
	$("#peditor-button").hover(function(){
		if (pb.currentpanel)
			$(this).css("opacity","1.0");
	},function(){
		$(this).css("opacity","0.9");
	});
	
	$("#peditor-button").click(function(){
		if (pb.currentpanel)
			openItemEditor(pb.currentpanel, true, true);
	});
	
	$("#seditor-button").hover(function(){
		if (pb.currentpanel)
			$(this).css("opacity","1.0");
	},function(){
		$(this).css("opacity","0.9");
	});
	
	$("#seditor-button").click(function(){
		if (!$('.outlined').exists()){
			pb.openDialog({
				content: '<center>No item selected to edit.</center>',
				style: {height: '100px'},
				cancel: false,
				confirm: 'ok',
				onConfirm: function(){pb.closeDialog();}
			});
			return;
		}
		if (0&&$(".outlined").length > 1){
			pb.openDialog({
				content: '<center>Too many items selected to edit.</center>',
				style: {height: '100px'},
				cancel: false,
				confirm: 'ok',
				onConfirm: function(){pb.closeDialog();}
			});
			return;
		}
		var found = false;
		$('.outlined').each(function(){
			var item = pb.getItem(this.id);
			if (item instanceof Button || item instanceof Widget || item instanceof SubPanel) found = true;
		});
		if (found) textEditor.open();
		else pb.openDialog({
			content: '<center>No button items selected to edit.</center>',
			style: {height: '100px'},
			cancel: false,
			confirm: 'ok',
			onConfirm: function(){pb.closeDialog();}
		});
	});
	
	$(document).delegate('#maineditor', 'keydown', function(e) {
		var keyCode = e.keyCode || e.which;

		if (keyCode == 9){ //tab support
			e.preventDefault();
			var start = $(this).get(0).selectionStart;
			var end = $(this).get(0).selectionEnd;

			$(this).val($(this).val().substring(0, start) + "\t"
				+ $(this).val().substring(end));

			$(this).get(0).selectionStart =
			$(this).get(0).selectionEnd = start + 1;
		}
	});
	
	$("#delete-button").click(function(){
		if (!$('.outlined').exists()){
			pb.openDialog({
				content: '<center>No item selected to edit.</center>',
				style: {height: '100px'},
				cancel: false,
				confirm: 'ok',
				onConfirm: function(){pb.closeDialog();}
			});
			return;
		}
		var outlined = $('.outlined').toArray();
		var naction = new Action({type: 'delete'});
		naction.items = [];
		$('.outlined').each(function(){
			console.log('wt');
			var item = pb.getItem(this.id);
			naction.items.push(item);
			item.remove();
		});
		//$('.outlined').removeClass('outlined first');
		pb.saveaction(naction);
	});
	
	$("#undo-button").click(function(){
		pb.undo();
	});
	
	$("#redo-button").click(function(){
		pb.redo();
	});

	$('body').keydown(function(e){
        if(e.keyCode == 16){
            pb.shiftdown = true;
        }
    });
	
    $('body').keyup(function(e){
        if(e.keyCode == 16){
            pb.shiftdown = false;
        }
    });
	
	$("#filemenu-button").click(function(){
		if (document.getElementById('filemenu-menu').style.display == 'none') pb.openMenu('file');
		else pb.closeMenu('file');
	});
	$("#editmenu-button").click(function(){
		if (document.getElementById('editmenu-menu').style.display == 'none') pb.openMenu('edit');
		else pb.closeMenu('edit');
	});
	$("#addmenu-button").click(function(){
		if (document.getElementById('addmenu-menu').style.display == 'none') pb.openMenu('add');
		else pb.closeMenu('add');
	});
	$("#viewmenu-button").click(function(){
		if (document.getElementById('viewmenu-menu').style.display == 'none') pb.openMenu('view');
		else pb.closeMenu('view');
	});
	$("#windowmenu-button").click(function(){
		if (document.getElementById('windowmenu-menu').style.display == 'none') pb.openMenu('window');
		else pb.closeMenu('window');
	});
	$("#helpmenu-button").click(function(){
		if (document.getElementById('helpmenu-menu').style.display == 'none') pb.openMenu('help');
		else pb.closeMenu('help');
	});
	
	$(".menu-item").hover(
		function(){
			$(this).addClass( "menuitemhover" );
		}, 
		function(){
			$(this).removeClass( "menuitemhover" );
		}
	);
	
	$('.item-options-labels').click(function(e){
		var self = this;
		$('.item-options').each(function(){
			if ($(this).css('display') != 'none') $(this).slideUp();
		});
		setTimeout(function(){
			$('#'+self.id+'-container').slideDown(400);
		}, 200);
	});
	
	$('#text-shadow').change(function(){
		if ($('#text-shadow').is(':checked')){
			pb.tempbutton.textnode.style.textShadow = 
				$('#text-shadow-hp-input').val()+"px "+
				$('#text-shadow-vp-input').val()+"px "+
				$('#text-shadow-br-input').val()+"px #ff0000";
		}
		else pb.tempbutton.textnode.style.textShadow="none";
	});
	$('#text-shadow-vp-input').keyup(function(){
		if ($('#text-shadow').is(':checked')){
			pb.tempbutton.textnode.style.textShadow = 
				$('#text-shadow-hp-input').val()+"px "+
				$('#text-shadow-vp-input').val()+"px "+
				$('#text-shadow-br-input').val()+"px #ff0000";
		}
	});
	$('#text-shadow-hp-input').keyup(function(){
		if ($('#text-shadow').is(':checked')){
			pb.tempbutton.textnode.style.textShadow = 
				$('#text-shadow-hp-input').val()+"px "+
				$('#text-shadow-vp-input').val()+"px "+
				$('#text-shadow-br-input').val()+"px #ff0000";
		}
	});
	$('#text-shadow-br-input').keyup(function(){
		if ($('#text-shadow').is(':checked')){
			pb.tempbutton.textnode.style.textShadow = 
				$('#text-shadow-hp-input').val()+"px "+
				$('#text-shadow-vp-input').val()+"px "+
				$('#text-shadow-br-input').val()+"px #ff0000";
		}
	});
	
	$('#box-shadow').change(function(){
		if ($('#box-shadow-inset').is(':checked')) var inset = 'inset ';
		else var inset = '';
		var hex = '#'+$('#ie-boxshadowColorSelector').val();
		if ($('#box-shadow').is(':checked')){
			$('.outlined').css({boxShadow: inset+
			$('#box-shadow-hp-input').val()+"px "+
			$('#box-shadow-vp-input').val()+"px "+
			$('#box-shadow-br-input').val()+"px "+
			$('#box-shadow-sr-input').val()+"px "+hex});
		}
		else preview.style.boxShadow="none";
	});
	$('#box-shadow-inset').change(function(){
		if ($('#box-shadow-inset').is(':checked')) var inset = 'inset ';
		else var inset = '';
		var hex = '#'+$('#ie-boxshadowColorSelector').val();
		if ($('#box-shadow').is(':checked')){
			$('.outlined').css({boxShadow: inset+
			$('#box-shadow-hp-input').val()+"px "+
			$('#box-shadow-vp-input').val()+"px "+
			$('#box-shadow-br-input').val()+"px "+
			$('#box-shadow-sr-input').val()+"px "+hex});
		}
		//else preview.style.boxShadow="none";
	});
	$('#box-shadow-vp-input').keyup(function(){
		if ($('#box-shadow-inset').is(':checked')) var inset = 'inset ';
		else var inset = '';
		var hex = '#'+$('#ie-boxshadowColorSelector').val();
		if ($('#box-shadow').is(':checked')){
			$('.outlined').css({boxShadow: inset+
			$('#box-shadow-hp-input').val()+"px "+
			$('#box-shadow-vp-input').val()+"px "+
			$('#box-shadow-br-input').val()+"px "+
			$('#box-shadow-sr-input').val()+"px "+hex});
		}
	});
	$('#box-shadow-hp-input').keyup(function(){
		if ($('#box-shadow-inset').is(':checked')) var inset = 'inset ';
		else var inset = '';
		var hex = '#'+$('#ie-boxshadowColorSelector').val();
		if ($('#box-shadow').is(':checked')){
			$('.outlined').css({boxShadow: inset+
			$('#box-shadow-hp-input').val()+"px "+
			$('#box-shadow-vp-input').val()+"px "+
			$('#box-shadow-br-input').val()+"px "+
			$('#box-shadow-sr-input').val()+"px "+hex});
		}
	});
	$('#box-shadow-br-input').keyup(function(){
		if ($('#box-shadow-inset').is(':checked')) var inset = 'inset ';
		else var inset = '';
		var hex = '#'+$('#ie-boxshadowColorSelector').val();
		if ($('#box-shadow').is(':checked')){
			$('.outlined').css({boxShadow: inset+
			$('#box-shadow-hp-input').val()+"px "+
			$('#box-shadow-vp-input').val()+"px "+
			$('#box-shadow-br-input').val()+"px "+
			$('#box-shadow-sr-input').val()+"px "+hex});
		}
	});
	$('#box-shadow-sr-input').keyup(function(){
		if ($('#box-shadow-inset').is(':checked')) var inset = 'inset ';
		else var inset = '';
		var hex = '#'+$('#ie-boxshadowColorSelector').val();
		if ($('#box-shadow').is(':checked')){
			$('.outlined').css({boxShadow: inset+
			$('#box-shadow-hp-input').val()+"px "+
			$('#box-shadow-vp-input').val()+"px "+
			$('#box-shadow-br-input').val()+"px "+
			$('#box-shadow-sr-input').val()+"px "+hex});
		}
	});
	$('#ie-boxshadowColorSelector').change(function(){
		if ($('#box-shadow-inset').is(':checked')) var inset = 'inset ';
		else var inset = '';
		var hex = '#'+$('#ie-boxshadowColorSelector').val();
		if ($('#box-shadow').is(':checked')){
			$('.outlined').css({boxShadow: inset+
			$('#box-shadow-hp-input').val()+"px "+
			$('#box-shadow-vp-input').val()+"px "+
			$('#box-shadow-br-input').val()+"px "+
			$('#box-shadow-sr-input').val()+"px "+hex});
		}
	});
	
	$('#drop-shadow').change(function(){
		if ($('#drop-shadow-inset').is(':checked')) var inset = 'inset ';
		else var inset = '';
		var hex = '#'+$('#ie-dropshadowColorSelector').val();
		if ($('#drop-shadow').is(':checked')){
			$('.outlined').find('bgimage').css({dropShadow: inset+
			$('#drop-shadow-hp-input').val()+"px "+
			$('#drop-shadow-vp-input').val()+"px "+
			$('#drop-shadow-br-input').val()+"px "+
			$('#drop-shadow-sr-input').val()+"px "+hex});
		}
		else preview.style.boxShadow="none";
	});
	$('#drop-shadow-inset').change(function(){
		if ($('#drop-shadow-inset').is(':checked')) var inset = 'inset ';
		else var inset = '';
		var hex = '#'+$('#ie-dropshadowColorSelector').val();
		if ($('#drop-shadow').is(':checked')){
			$('.outlined').find('bgimage').css({dropShadow: inset+
			$('#drop-shadow-hp-input').val()+"px "+
			$('#drop-shadow-vp-input').val()+"px "+
			$('#drop-shadow-br-input').val()+"px "+
			$('#drop-shadow-sr-input').val()+"px "+hex});
		}
		else preview.style.boxShadow="none";
	});
	$('#drop-shadow-vp-input').keyup(function(){
		if ($('#drop-shadow-inset').is(':checked')) var inset = 'inset ';
		else var inset = '';
		var hex = '#'+$('#ie-dropshadowColorSelector').val();
		if ($('#drop-shadow').is(':checked')){
			$('.outlined').find('bgimage').css({dropShadow: inset+
			$('#drop-shadow-hp-input').val()+"px "+
			$('#drop-shadow-vp-input').val()+"px "+
			$('#drop-shadow-br-input').val()+"px "+
			$('#drop-shadow-sr-input').val()+"px "+hex});
		}
	});
	$('#drop-shadow-hp-input').keyup(function(){
		if ($('#drop-shadow-inset').is(':checked')) var inset = 'inset ';
		else var inset = '';
		var hex = '#'+$('#ie-dropshadowColorSelector').val();
		if ($('#drop-shadow').is(':checked')){
			$('.outlined').find('bgimage').css({dropShadow: inset+
			$('#drop-shadow-hp-input').val()+"px "+
			$('#drop-shadow-vp-input').val()+"px "+
			$('#drop-shadow-br-input').val()+"px "+
			$('#drop-shadow-sr-input').val()+"px "+hex});
		}
	});
	$('#drop-shadow-br-input').keyup(function(){
		if ($('#drop-shadow-inset').is(':checked')) var inset = 'inset ';
		else var inset = '';
		var hex = '#'+$('#ie-dropshadowColorSelector').val();
		if ($('#drop-shadow').is(':checked')){
			$('.outlined').find('bgimage').css({dropShadow: inset+
			$('#drop-shadow-hp-input').val()+"px "+
			$('#drop-shadow-vp-input').val()+"px "+
			$('#drop-shadow-br-input').val()+"px "+
			$('#drop-shadow-sr-input').val()+"px "+hex});
		}
	});
	$('#drop-shadow-sr-input').keyup(function(){
		if ($('#drop-shadow-inset').is(':checked')) var inset = 'inset ';
		else var inset = '';
		var hex = '#'+$('#ie-dropshadowColorSelector').val();
		if ($('#drop-shadow').is(':checked')){
			$('.outlined').find('bgimage').css({dropShadow: inset+
			$('#drop-shadow-hp-input').val()+"px "+
			$('#drop-shadow-vp-input').val()+"px "+
			$('#drop-shadow-br-input').val()+"px "+
			$('#drop-shadow-sr-input').val()+"px "+hex});
		}
	});
	$('#ie-dropshadowColorSelector').change(function(){
		if ($('#drop-shadow-inset').is(':checked')) var inset = 'inset ';
		else var inset = '';
		var hex = '#'+$('#ie-dropshadowColorSelector').val();
		if ($('#drop-shadow').is(':checked')){
			$('.outlined').find('bgimage').css({'-webkit-filter': 'drop-shadow('+
			$('#drop-shadow-hp-input').val()+"px "+
			$('#drop-shadow-vp-input').val()+"px "+
			$('#drop-shadow-br-input').val()+"px "+hex+')'});
		}
	});
	
	if (!modero){
		$('#touchpanelkey-radio1')[0].onmousedown = function(e){
			e.preventDefault();
			$('.outlined').each(function(){
				pb.getItem(this.id).core.touchpanelkey = 1;
			});
			$('#touchpanelkey-radio2').prop('checked', false);
			$('#touchpanelkey-radio3').prop('checked', false);
			$('#touchpanelkey-radio4').prop('checked', false);
			$('#touchpanelkey-radio5').prop('checked', false);
			$('#touchpanelkey-radio6').prop('checked', false);
			$('#touchpanelkey-radio7').prop('checked', false);
			$('#touchpanelkey-radio8').prop('checked', false);
		};
		$('#touchpanelkey-radio1')[0].onmouseup = function(e){
			if ($('#touchpanelkey-radio1').prop('checked')){
				setTimeout(function(){$('#touchpanelkey-radio1').prop('checked', false);}, 100);
				$('.outlined').each(function(){
					pb.getItem(this.id).core.touchpanelkey = false;
				});
			}
		}
		$('#touchpanelkey-radio2')[0].onmousedown = function(e){
			e.preventDefault();
			$('.outlined').each(function(){
				pb.getItem(this.id).core.touchpanelkey = 2;
			});
			$('#touchpanelkey-radio1').prop('checked', false);
			$('#touchpanelkey-radio3').prop('checked', false);
			$('#touchpanelkey-radio4').prop('checked', false);
			$('#touchpanelkey-radio5').prop('checked', false);
			$('#touchpanelkey-radio6').prop('checked', false);
			$('#touchpanelkey-radio7').prop('checked', false);
			$('#touchpanelkey-radio8').prop('checked', false);
		};
		$('#touchpanelkey-radio2')[0].onmouseup = function(e){
			if ($('#touchpanelkey-radio2').prop('checked')){
				setTimeout(function(){$('#touchpanelkey-radio2').prop('checked', false);}, 100);
				$('.outlined').each(function(){
					pb.getItem(this.id).core.touchpanelkey = false;
				});
			}
		}
		$('#touchpanelkey-radio3')[0].onmousedown = function(e){
			e.preventDefault();
			$('.outlined').each(function(){
				pb.getItem(this.id).core.touchpanelkey = 3;
			});
			$('#touchpanelkey-radio1').prop('checked', false);
			$('#touchpanelkey-radio2').prop('checked', false);
			$('#touchpanelkey-radio4').prop('checked', false);
			$('#touchpanelkey-radio5').prop('checked', false);
			$('#touchpanelkey-radio6').prop('checked', false);
			$('#touchpanelkey-radio7').prop('checked', false);
			$('#touchpanelkey-radio8').prop('checked', false);
		};
		$('#touchpanelkey-radio3')[0].onmouseup = function(e){
			if ($('#touchpanelkey-radio3').prop('checked')){
				setTimeout(function(){$('#touchpanelkey-radio3').prop('checked', false);}, 100);
				$('.outlined').each(function(){
					pb.getItem(this.id).core.touchpanelkey = false;
				});
			}
		}
		$('#touchpanelkey-radio4')[0].onmousedown = function(e){
			e.preventDefault();
			$('.outlined').each(function(){
				pb.getItem(this.id).core.touchpanelkey = 4;
			});
			$('#touchpanelkey-radio1').prop('checked', false);
			$('#touchpanelkey-radio2').prop('checked', false);
			$('#touchpanelkey-radio3').prop('checked', false);
			$('#touchpanelkey-radio5').prop('checked', false);
			$('#touchpanelkey-radio6').prop('checked', false);
			$('#touchpanelkey-radio7').prop('checked', false);
			$('#touchpanelkey-radio8').prop('checked', false);
		};
		$('#touchpanelkey-radio4')[0].onmouseup = function(e){
			if ($('#touchpanelkey-radio4').prop('checked')){
				setTimeout(function(){$('#touchpanelkey-radio4').prop('checked', false);}, 100);
				$('.outlined').each(function(){
					pb.getItem(this.id).core.touchpanelkey = false;
				});
			}
		}
		$('#touchpanelkey-radio5')[0].onmousedown = function(e){
			e.preventDefault();
			$('.outlined').each(function(){
				pb.getItem(this.id).core.touchpanelkey = 5;
			});
			$('#touchpanelkey-radio1').prop('checked', false);
			$('#touchpanelkey-radio2').prop('checked', false);
			$('#touchpanelkey-radio3').prop('checked', false);
			$('#touchpanelkey-radio4').prop('checked', false);
			$('#touchpanelkey-radio6').prop('checked', false);
			$('#touchpanelkey-radio7').prop('checked', false);
			$('#touchpanelkey-radio8').prop('checked', false);
		};
		$('#touchpanelkey-radio5')[0].onmouseup = function(e){
			if ($('#touchpanelkey-radio5').prop('checked')){
				setTimeout(function(){$('#touchpanelkey-radio5').prop('checked', false);}, 100);
				$('.outlined').each(function(){
					pb.getItem(this.id).core.touchpanelkey = false;
				});
			}
		}
		$('#touchpanelkey-radio6')[0].onmousedown = function(e){
			e.preventDefault();
			$('.outlined').each(function(){
				pb.getItem(this.id).core.touchpanelkey = 6;
			});
			$('#touchpanelkey-radio1').prop('checked', false);
			$('#touchpanelkey-radio2').prop('checked', false);
			$('#touchpanelkey-radio3').prop('checked', false);
			$('#touchpanelkey-radio4').prop('checked', false);
			$('#touchpanelkey-radio5').prop('checked', false);
			$('#touchpanelkey-radio7').prop('checked', false);
			$('#touchpanelkey-radio8').prop('checked', false);
		};
		$('#touchpanelkey-radio6')[0].onmouseup = function(e){
			if ($('#touchpanelkey-radio6').prop('checked')){
				setTimeout(function(){$('#touchpanelkey-radio6').prop('checked', false);}, 100);
				$('.outlined').each(function(){
					pb.getItem(this.id).core.touchpanelkey = false;
				});
			}
		}
		$('#touchpanelkey-radio7')[0].onmousedown = function(e){
			e.preventDefault();
			$('.outlined').each(function(){
				pb.getItem(this.id).core.touchpanelkey = 7;
			});
			$('#touchpanelkey-radio1').prop('checked', false);
			$('#touchpanelkey-radio2').prop('checked', false);
			$('#touchpanelkey-radio3').prop('checked', false);
			$('#touchpanelkey-radio4').prop('checked', false);
			$('#touchpanelkey-radio5').prop('checked', false);
			$('#touchpanelkey-radio6').prop('checked', false);
			$('#touchpanelkey-radio8').prop('checked', false);
		};
		$('#touchpanelkey-radio7')[0].onmouseup = function(e){
			if ($('#touchpanelkey-radio7').prop('checked')){
				setTimeout(function(){$('#touchpanelkey-radio7').prop('checked', false);}, 100);
				$('.outlined').each(function(){
					pb.getItem(this.id).core.touchpanelkey = false;
				});
			}
		}
		$('#touchpanelkey-radio8')[0].onmousedown = function(e){
			e.preventDefault();
			$('.outlined').each(function(){
				pb.getItem(this.id).core.touchpanelkey = 8;
			});
			$('#touchpanelkey-radio1').prop('checked', false);
			$('#touchpanelkey-radio2').prop('checked', false);
			$('#touchpanelkey-radio3').prop('checked', false);
			$('#touchpanelkey-radio4').prop('checked', false);
			$('#touchpanelkey-radio5').prop('checked', false);
			$('#touchpanelkey-radio6').prop('checked', false);
			$('#touchpanelkey-radio7').prop('checked', false);
		};
		$('#touchpanelkey-radio8')[0].onmouseup = function(e){
			if ($('#touchpanelkey-radio8').prop('checked')){
				setTimeout(function(){$('#touchpanelkey-radio8').prop('checked', false);}, 100);
				$('.outlined').each(function(){
					pb.getItem(this.id).core.touchpanelkey = false;
				});
			}
		}
		$('#touchpanelkey-radio9')[0].onmousedown = function(e){
			e.preventDefault();
			$('.outlined').each(function(){
				pb.getItem(this.id).core.touchpanelkey = false;
			});
			$('#touchpanelkey-radio1').prop('checked', false);
			$('#touchpanelkey-radio2').prop('checked', false);
			$('#touchpanelkey-radio3').prop('checked', false);
			$('#touchpanelkey-radio4').prop('checked', false);
			$('#touchpanelkey-radio5').prop('checked', false);
			$('#touchpanelkey-radio6').prop('checked', false);
			$('#touchpanelkey-radio7').prop('checked', false);
		};
	}
	
	$("input[name='border-tl']").change(function(e){
		if (this.value == 'px'){
			$('#item-border-radius-tl').show();
			$('#tl-slider').hide();
			$('.outlined').each(function(i){
				//var item = pb.getItem(this.id); if (i === 0) $('#item-border-radius-tl').val(item. || 0);
				tweencss({object: this, time: 1, units: 'px',
					props: {borderTopLeftRadius: parseInt(this.style.borderTopLeftRadius)},
					to: {borderTopLeftRadius: $('#tl-slider').slider("option", "value")}});
				if ($(this).find('.bgimage')[0]) tweencss({object: $(this).find('.bgimage')[0], time: 1, units: 'px',
					props: {borderTopLeftRadius: parseInt($(this).find('.bgimage')[0].style.borderTopLeftRadius)},
					to: {borderTopLeftRadius: $('#tl-slider').slider("option", "value")}});
			});
		}
		else {
			$('#item-border-radius-tl').hide();
			$('#tl-slider').show();
			$('#tl-slider').css({display: 'inline-block'});
			$('.outlined').each(function(){
				tweencss({object: this, time: 1, units: '%',
					props: {borderTopLeftRadius: parseInt(this.style.borderTopLeftRadius)},
					to: {borderTopLeftRadius: $('#tl-slider').slider("option", "value")}});
				if ($(this).find('.bgimage')[0]) tweencss({object: $(this).find('.bgimage')[0], time: 1, units: 'px',
					props: {borderTopLeftRadius: parseInt($(this).find('.bgimage')[0].style.borderTopLeftRadius)},
					to: {borderTopLeftRadius: $('#tl-slider').slider("option", "value")}});
			});
		}
	});
	
	$("input[name='border-tr']").change(function(e){
		if (this.value == 'px') {
			$('#item-border-radius-tr').show(); $('#item-border-radius-tr').val(parseInt(this.style.borderTopRightRadius));
			$('#tr-slider').hide();
			$('.outlined').each(function(){
				tweencss({object: this, time: 1, units: 'px',
					props: {borderTopRightRadius: parseInt(this.style.borderTopRightRadius)},
					to: {borderTopRightRadius: $('#tr-slider').slider("option", "value")}});
				if ($(this).find('.bgimage')[0]) tweencss({object: $(this).find('.bgimage')[0], time: 1, units: 'px',
					props: {borderTopRightRadius: parseInt($(this).find('.bgimage')[0].style.borderTopRightRadius)},
					to: {borderTopRightRadius: $('#tr-slider').slider("option", "value")}});
			});
		}
		else {
			$('#item-border-radius-tr').hide();
			$('#tr-slider').show();
			$('#tr-slider').css({display: 'inline-block'});
			$('.outlined').each(function(){
				tweencss({object: this, time: 1, units: '%',
					props: {borderTopRightRadius: parseInt(this.style.borderTopRightRadius)},
					to: {borderTopRightRadius: $('#tr-slider').slider("option", "value")}});
				if ($(this).find('.bgimage')[0]) tweencss({object: $(this).find('.bgimage')[0], time: 1, units: 'px',
					props: {borderTopRightRadius: parseInt($(this).find('.bgimage')[0].style.borderTopRightRadius)},
					to: {borderTopRightRadius: $('#tr-slider').slider("option", "value")}});
			});
		}
	});
	
	$("input[name='border-bl']").change(function(e){
		if (this.value == 'px'){
			$('#item-border-radius-bl').show(); $('#item-border-radius-bl').val(parseInt(this.style.borderBottomLeftRadius));
			$('#bl-slider').hide();
			$('.outlined').each(function(){
				tweencss({object: this, time: 1, units: 'px',
					props: {borderBottomLeftRadius: parseInt(this.style.borderBottomLeftRadius)},
					to: {borderBottomLeftRadius: $('#bl-slider').slider("option", "value")}});
				if ($(this).find('.bgimage')[0]) tweencss({object: $(this).find('.bgimage')[0], time: 1, units: 'px',
					props: {borderBottomLeftRadius: parseInt($(this).find('.bgimage')[0].style.borderBottomLeftRadius)},
					to: {borderBottomLeftRadius: $('#bl-slider').slider("option", "value")}});
			});
		}
		else {
			$('#item-border-radius-bl').hide();
			$('#bl-slider').show();
			$('#bl-slider').css({display: 'inline-block'});
			$('.outlined').each(function(){
				tweencss({object: this, time: 1, units: '%',
					props: {borderBottomLeftRadius: parseInt(this.style.borderBottomLeftRadius)},
					to: {borderBottomLeftRadius: $('#bl-slider').slider("option", "value")}});
				if ($(this).find('.bgimage')[0]) tweencss({object: $(this).find('.bgimage')[0], time: 1, units: 'px',
					props: {borderBottomLeftRadius: parseInt($(this).find('.bgimage')[0].style.borderBottomLeftRadius)},
					to: {borderBottomLeftRadius: $('#bl-slider').slider("option", "value")}});
			});
		}
	});
	
	$("input[name='border-br']").change(function(e){
		if (this.value == 'px'){
			$('#item-border-radius-br').show(); $('#item-border-radius-br').val(parseInt(this.style.borderBottomRightRadius));
			$('#br-slider').hide();
			$('.outlined').each(function(){
				tweencss({object: this, time: 1, units: 'px',
					props: {borderBottomRightRadius: parseInt(this.style.borderBottomRightRadius)},
					to: {borderBottomRightRadius: $('#br-slider').slider("option", "value")}});
				if ($(this).find('.bgimage')[0]) tweencss({object: $(this).find('.bgimage')[0], time: 1, units: 'px',
					props: {borderBottomRightRadius: parseInt($(this).find('.bgimage')[0].style.borderBottomRightRadius)},
					to: {borderBottomRightRadius: $('#br-slider').slider("option", "value")}});
			});
		}
		else {
			$('#item-border-radius-br').hide();
			$('#br-slider').show();
			$('#br-slider').css({display: 'inline-block'});
			$('.outlined').each(function(){
				tweencss({object: this, time: 1, units: '%',
					props: {borderBottomRightRadius: parseInt(this.style.borderBottomRightRadius)},
					to: {borderBottomRightRadius: $('#br-slider').slider("option", "value")}});
				if ($(this).find('.bgimage')[0]) tweencss({object: $(this).find('.bgimage')[0], time: 1, units: '%',
					props: {borderBottomRightRadius: parseInt($(this).find('.bgimage')[0].style.borderBottomRightRadius)},
					to: {borderBottomRightRadius: $('#br-slider').slider("option", "value")}});
			});
		}
	});
	
	$("#tl-slider").slider({
		value:0, min: 0, max: 100, step: 1,
		slide: function(event, ui){
			pb.tlradius = $('#tl-slider').slider("option", "value");
			$('.outlined').each(function(){
				tweencss({object: this, time: 1, units: '%',
					props: {borderTopLeftRadius: parseInt(this.style.borderTopLeftRadius)},
					to: {borderTopLeftRadius: pb.tlradius}});
				if ($(this).find('.bgimage')[0]) tweencss({object: $(this).find('.bgimage')[0], time: 1, units: '%',
					props: {borderTopLeftRadius: parseInt($(this).find('.bgimage')[0].style.borderTopLeftRadius)},
					to: {borderTopLeftRadius: pb.tlradius}});
				var item = pb.getItem(this.id); if (!item.core.states[item.core.currentstate].borders) item.core.states[item.core.currentstate].borders = {};
					item.core.states[item.core.currentstate].borders.tl = pb.tlradius + '%';
			});
		}
	});
	
	$("#tr-slider").slider({
		value:0, min: 0, max: 100, step: 1,
		slide: function(event, ui){
			pb.trradius = $('#tr-slider').slider("option", "value");	
			$('.outlined').each(function(){
				tweencss({object: this, time: 1, units: '%',
					props: {borderTopRightRadius: parseInt(this.style.borderTopRightRadius)},
					to: {borderTopRightRadius: pb.trradius}});
				if ($(this).find('.bgimage')[0]) tweencss({object: $(this).find('.bgimage')[0], time: 1, units: '%',
					props: {borderTopRightRadius: parseInt($(this).find('.bgimage')[0].style.borderTopRightRadius)},
					to: {borderTopRightRadius: pb.trradius}});
				var item = pb.getItem(this.id); if (!item.core.states[item.core.currentstate].borders) item.core.states[item.core.currentstate].borders = {};
					item.core.states[item.core.currentstate].borders.tr = pb.trradius + '%';
			});
		}
	});
	
	$("#bl-slider").slider({
		value:0, min: 0, max: 100, step: 1,
		slide: function(event, ui){
			pb.blradius = $('#bl-slider').slider("option", "value");
			$('.outlined').each(function(){
				tweencss({object: this, time: 1, units: '%',
					props: {borderBottomLeftRadius: parseInt(this.style.borderBottomLeftRadius)},
					to: {borderBottomLeftRadius: pb.blradius}});
				if ($(this).find('.bgimage')[0]) tweencss({object: $(this).find('.bgimage')[0], time: 1, units: '%',
					props: {borderBottomLeftRadius: parseInt($(this).find('.bgimage')[0].style.borderBottomLeftRadius)},
					to: {borderBottomLeftRadius: pb.blradius}});
				var item = pb.getItem(this.id); if (!item.core.states[item.core.currentstate].borders) item.core.states[item.core.currentstate].borders = {};
					item.core.states[item.core.currentstate].borders.bl = pb.blradius + '%';
			});
		}
	});
	
	$("#br-slider").slider({
		value:0, min: 0, max: 100, step: 1,
		slide: function(event, ui){
			pb.brradius = $('#br-slider').slider("option", "value");
			$('.outlined').each(function(){
				tweencss({object: this, time: 1, units: '%',
					props: {borderBottomRightRadius: parseInt(this.style.borderBottomRightRadius)},
					to: {borderBottomRightRadius: pb.brradius}});
				if ($(this).find('.bgimage')[0]) tweencss({object: $(this).find('.bgimage')[0], time: 1, units: '%',
					props: {borderBottomRightRadius: parseInt($(this).find('.bgimage')[0].style.borderBottomRightRadius)},
					to: {borderBottomRightRadius: pb.brradius}});
				var item = pb.getItem(this.id); if (!item.core.states[item.core.currentstate].borders) item.core.states[item.core.currentstate].borders = {};
					item.core.states[item.core.currentstate].borders.br = pb.brradius + '%';
			});
		}
	});
	
	$("#hue-slider").slider({
		value:0, min: 0, max: 100, step: 1,
		slide: function(event, ui){
			$('.outlined').each(function(){
				var item = pb.getItem(this.id); if (!item) return;
				var tval = parseInt(parseInt($('#hue-slider').slider('option', 'value'))*3.6)+'deg';

				if (item instanceof Button){
					if (undef(item.core.states[item.core.currentstate].cssfilter) || 
						item.core.states[item.core.currentstate].cssfilter === 'none' || !item.core.states[item.core.currentstate].cssfilter)
						item.core.states[item.core.currentstate].cssfilter = 'hue-rotate(0deg) saturate(1)';

					var s1 = item.core.states[item.core.currentstate].cssfilter.substring(0, item.core.states[item.core.currentstate].cssfilter.indexOf('(')+1);
					var s2 = item.core.states[item.core.currentstate].cssfilter.substring(item.core.states[item.core.currentstate].cssfilter.indexOf(')'));
					item.core.states[item.core.currentstate].cssfilter = s1+tval+s2;
				}
				
				$(this).find('.bgimage').css({'-webkit-filter': s1+tval+s2});
			});
		}
	});
	
	$("#sat-slider").slider({
		value:0, min: 0, max: 100, step: 1,
		slide: function(event, ui){
			$('.outlined').each(function(){
				var item = pb.getItem(this.id); if (!item) return;
				var tval = (parseInt($('#sat-slider').slider('option', 'value'))*2)+'%';
				
				if (item instanceof Button){
					if (undef(item.core.states[item.core.currentstate].cssfilter) ||
						item.core.states[item.core.currentstate].cssfilter === 'none' || !item.core.states[item.core.currentstate].cssfilter)
						item.core.states[item.core.currentstate].cssfilter = 'hue-rotate(0deg) saturate(1)';
					
					var s1 = item.core.states[item.core.currentstate].cssfilter.substring(0, nindexOf(item.core.states[item.core.currentstate].cssfilter, '(', 2)+1);
					var s2 = item.core.states[item.core.currentstate].cssfilter.substring(nindexOf(item.core.states[item.core.currentstate].cssfilter, ')', 2));
					item.core.states[item.core.currentstate].cssfilter = s1+tval+s2;
				}
				
				$(this).find('.bgimage').css({'-webkit-filter': s1+tval+s2});
			});
		}
	});
	
	$('#item-border-radius-tl').keyup(function(){
		var tlradius = $('#item-border-radius-tl').val(); console.log(tlradius);
		$('.outlined').each(function(){
			$(this).css({borderTopLeftRadius: tlradius+'px'});
			$(this).find('.bgimage').css({borderTopLeftRadius: tlradius+'px'});
			var item = pb.getItem(this.id);
			if (!item.core.states[item.core.currentstate].borders) item.core.states[item.core.currentstate].borders = {};
				item.core.states[item.core.currentstate].borders.tl = tlradius + 'px';
		});
	});
	$('#item-border-radius-tr').keyup(function(){
		var trradius = $('#item-border-radius-tr').val();
		$('.outlined').each(function(){
			$(this).css({borderTopRightRadius: trradius+'px'});
			$(this).find('.bgimage').css({borderTopRightRadius: trradius+'px'});
			var item = pb.getItem(this.id);
			if (!item.core.states[item.core.currentstate].borders) item.core.states[item.core.currentstate].borders = {};
				item.core.states[item.core.currentstate].borders.tr = trradius + 'px';
		});
	});
	$('#item-border-radius-bl').keyup(function(){
		var blradius = $('#item-border-radius-bl').val();
		$('.outlined').each(function(){
			$(this).css({borderBottomLeftRadius: blradius+'px'});
			$(this).find('.bgimage').css({borderBottomLeftRadius: blradius+'px'});
			var item = pb.getItem(this.id);
			if (!item.core.states[item.core.currentstate].borders) item.core.states[item.core.currentstate].borders = {};
				item.core.states[item.core.currentstate].borders.bl = blradius + 'px';
		});
	});
	$('#item-border-radius-br').keyup(function(){
		var brradius = $('#item-border-radius-br').val();
		$('.outlined').each(function(){
			$(this).css({borderBottomRightRadius: brradius+'px'});
			$(this).find('.bgimage').css({borderBottomRightRadius: brradius+'px'});
			var item = pb.getItem(this.id);
			if (!item.core.states[item.core.currentstate].borders) item.core.states[item.core.currentstate].borders = {};
				item.core.states[item.core.currentstate].borders.br = brradius + 'px';
		});
	});
	
	$('#text-shadow-button').click(function(){
		$('.outlined').each(function(){
			$(pb.getItemById(this.id).textnode).css({'text-shadow': $('#text-shadow-vp-input').val()+'px '+
				$('#text-shadow-hp-input').val()+'px '+$('#text-shadow-br-input').val()+'px #'+
				$('#ie-textShadowColorSelector')[0].color
			});
		});
	});
	
	$('#text-shadow-remove-button').click(function(){
		$('.outlined').each(function(){
			$(pb.getItemById(this.id).textnode).css({'text-shadow': 'none'});
		});
	});
	
	$('#box-shadow-button').click(function(){
		$('.outlined').each(function(){
			$(this).css({'box-shadow': $('#box-shadow-vp-input').val()+'px '+
				$('#box-shadow-hp-input').val()+'px '+$('#box-shadow-br-input').val()+'px #'+
				$('#ie-boxShadowColorSelector')[0].color
			});
		});
	});
	
	$('#box-shadow-remove-button').click(function(){
		$('.outlined').each(function(){
			$(this).css({'box-shadow': 'none'});
		});
	});
	
	$('#drop-shadow-button').click(function(){
		$('.outlined').each(function(){
			$(this).css({'filter': 'drop-shadow('+$('#drop-shadow-vp-input').val()+'px '+
				$('#drop-shadow-hp-input').val()+'px '+$('#drop-shadow-br-input').val()+'px #'+
				$('#ie-dropShadowColorSelector')[0].color+')'
			});
			$(this).css({'-webkit-filter': 'drop-shadow('+$('#drop-shadow-vp-input').val()+'px '+
				$('#drop-shadow-hp-input').val()+'px '+$('#drop-shadow-br-input').val()+'px #'+
				$('#ie-dropShadowColorSelector')[0].color+')'
			});
		});
	});
	
	$('#drop-shadow-remove-button').click(function(){
		$('.outlined').each(function(){
			//$(this).find('.bgimage').css({'-webkit-filter': 'none'});
			$(this).css({'-webkit-filter': 'none'});
		});
	});
	
	$('#item-height-input-button').click(function(){
		$('.outlined').each(function(){
			$(this).height($('#item-height-input').val());
			var item = pb.getItem(this.id);
			if (item instanceof Button) item.setSizeSmart(null, $('#item-height-input').val());
			if (item instanceof Widget) for (var k=0;k<item.parts.length;k++){
				if (item.parts[k].resize) item.parts[k].resize();
			}
		});
	});
	
	$('#item-width-input-button').click(function(){
		$('.outlined').each(function(){
			$(this).width($('#item-width-input').val());
			var item = pb.getItem(this.id);
			if (item instanceof Button) item.setSizeSmart($('#item-width-input').val(), null);
			if (item instanceof Widget) for (var k=0;k<item.parts.length;k++){
				if (item.parts[k].resize) item.parts[k].resize();
			}
		});
	});
	
	$('#item-top-input-button').click(function(){
		$('.outlined').each(function(){
			pb.getItem(this.id).element.style.top = $('#item-top-input').val() + 'px';
		});
	});
	
	$('#item-left-input-button').click(function(){
		$('.outlined').each(function(){
			pb.getItem(this.id).element.style.left = $('#item-left-input').val() + 'px';
		});
	});
	
	$("#item-border-size-button").click(function(e){
		var val = $('#item-border-size').val();
		var col = $('#ie-borderColorSelector')[0].color;
		console.log(val, col);
		$('.outlined').each(function(){
			this.style.borderWidth = val+'px';
			this.style.borderStyle = 'solid';
			this.style.borderColor = '#'+col;
		});
	});
	
	$('#item-to-up-button').click(function(){
		$('.outlined').each(function(){
			pb.getItem(this.id).setZ(pb.getItem(this.id).core.zvalue+1);
		});
	});
	
	$('#item-to-down-button').click(function(){
		$('.outlined').each(function(){
			pb.getItem(this.id).setZ(pb.getItem(this.id).core.zvalue-1);
		});
	});
	
	$('#item-to-top-button').click(function(){
		var max = 1;
		for (var i=0; i<pb.currentpanel.buttons.length; i++){
			if (pb.currentpanel.buttons[i].core.zvalue > max) 
				max = pb.currentpanel.buttons[i].core.zvalue;
		}
		for (var i=0; i<pb.currentpanel.widgets.length; i++){
			if (pb.currentpanel.widgets[i].core.zvalue > max) 
				max = pb.currentpanel.widgets[i].core.zvalue;
		}
		$('.outlined').each(function(){
			pb.getItem(this.id).setZ(max+1);
		});
	});
	
	$('#item-to-bottom-button').click(function(){
		var min = 1;
		for (var i=0; i<pb.currentpanel.buttons.length; i++){
			if (pb.currentpanel.buttons[i].core.zvalue < min) 
				min = pb.currentpanel.buttons[i].core.zvalue;
		}
		for (var i=0; i<pb.currentpanel.widgets.length; i++){
			if (pb.currentpanel.widgets[i].core.zvalue < min) 
				min = pb.currentpanel.widgets[i].core.zvalue;
		}
		$('.outlined').each(function(){
			pb.getItem(this.id).setZ(min-1);
		});
	});
	
	$('#text-to-item').attr('contenteditable', 'true');
	var ck = CKEDITOR.inline($('#text-to-item')[0]);
	$('#text-to-item').focus();
	ck.on('instanceReady', function(ev){
		var editor = ev.editor;
		editor.setReadOnly(false);
	});
	
	$('#text-to-item').click(function(){
		try {
			var ck = CKEDITOR.inline($('#text-to-item')[0]);
		}
		catch (e){}
	});
	
	/*$('#text-to-item').blur(function(){
		for (k in CKEDITOR.instances){
			var instance = CKEDITOR.instances[k];
			instance.destroy();
		}
	});*/
	
	$('#text-to-item-button').click(function(){
		$('.outlined').each(function(){
			var item = pb.getItem(this.id);
			if (item.textnode){
				//item.textnode.style = clone($('#text-to-item')[0].style);
				item.textnode.innerHTML = $('#text-to-item').html();
				var theight = ($(item.element).outerHeight()/2) - ($(item.textnode).outerHeight()/2);
				$(item.textnode).css('top', theight + 'px');
				//$(item.textnode)[0].style.cssText = document.defaultView.getComputedStyle($('#text-to-item')[0], "").cssText;
				$(item.textnode)[0].style.cssText += 'color: black;';
				//console.log(document.defaultView.getComputedStyle($('#text-to-item')[0], "").cssText);
			}
		});
	});
	
	$('#props-props-label').click();
	
	$('#add-state-button').click(function(){
		var name = $('#new-state-name-input').val();
		var replace = 0; var total = 0;
		$('.outlined').each(function(){
			total++;
			var item = pb.getItem(this.id);
			if (item instanceof Button) for (var i=0; i<item.core.states.length; i++){
				if (item.core.states[i].name == name) replace++;
			}
		});
		$('.outlined').each(function(){
			pb.getItem(this.id).addState({bgimage: blankimg, name: name});
		});
		if (replace == total)  pb.openDialog({
			content: '<center>All of the selected buttons already contain the state you are trying to add.</center>',
			style: {height: '100px'},
			cancel: false,
			confirm: 'ok',
			onConfirm: function(){
				pb.closeDialog();
			}
		});
		else pb.openDialog({
			content: '<center>A new state has been added to selected buttons that didn\'t have a state with that name.</center>',
			style: {height: '100px'},
			cancel: false,
			confirm: 'ok',
			onConfirm: function(){
				$('#new-state-name-input').val('');
				pb.closeDialog();
			}
		});
		var array = [];
		$('.outlined').each(function(){
			var item = pb.getItem(this.id);
			if (item instanceof Button) for (var i=0; i<item.core.states.length; i++){
				var found = false;
				for (var j=0; j<array.length; j++){
					if (item.core.states[i].name == array[j].name) found = true;
				}
				if (!found) array.push(item.core.states[i]);
			}
		});
		ng.buttonstates = array;
		$('#item-states-container').slideDown(1000);
	});
	
	$('#item-remove-bg').click(function(){
		$('.outlined').each(function(){
			var item = pb.getItem(this.id);
			if (item.setBackground) item.setBackground(blankimg);
		});
	});

	$('#buttonbgFileInput').change(function(e){
		
		var file = this.files[0];
		this.value = null;
		
		if (standalone){
			sendFile({
				file: file,
				callback: function(opts){
					$('.outlined').each(function(){
						var item = pb.getItem(this.id);
						if (item.setBackground) item.setBackground('file:///'+opts.filepath);
					});
				}
			});
			return;
		}

		var fd = new FormData();
		fd.append("image", file);
		
		var opts = {
			command: 'write_image',
			width: parseInt(pb.currentpanel.element.style.width),
			height: parseInt(pb.currentpanel.element.style.height)
		};
		
		if (pb.project.puid) opts.puid = pb.project.puid;
		
		fd.append("opts", JSON.stringify(opts));
	
		server({formdata: fd, callback: function(data){
			try {
				var tstr = data;
				var fstr = tstr.substring(tstr.indexOf('projects/')+9, tstr.indexOf('/images/'));
				pb.project.core.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.user.assets.length; i++){
					if (pb.user.assets[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();
			}
			catch (e){
				dumpError(e);
			}
			
			if (!standalone) pb.checkDiskSize();
			
		}});
		
	});
	
}