/******************************************************************************
@owner: SVSi
@author: Arthur Johnson
@function: SubPanel Class
@SubPanel
*******************************************************************************/

//*************  SUBPANEL CLASS  ***************//

	function SubPanel(opts){
		
		if (undef(opts)) opts = {};
		
		if (undef(pb.subpanelindex)) pb.subpanelindex = 0;
		
	//**************************** CORE ******************************//
		if (opts.hasOwnProperty('core')){
		
			this.core = opts.core;
			
			if (undef(opts.copyid)) this.core.id = pb.uniqueId('SubPanel-'+(pb.subpanelindex++));
			//else this.core.id = pb.uniqueId(this.core.id);
			
			if (!undef(opts.type)) this.core.type = opts.type;
			
			if (undef(this.core.actualwidth)) this.core.actualwidth = this.core.basewidth;
			if (undef(this.core.actualheight)) this.core.actualheight = this.core.baseheight;
			if (undef(this.core.id)) this.core.id = 'SubPanel-'+(pb.subpanelindex++);	
			if (undef(this.core.type)) this.core.type = 'user';			
			if (undef(this.core.scale)) this.core.scale = 1;
			if (undef(this.core.elementHTML)) this.core.elementHTML = '';
			if (undef(this.core.className)) this.core.className = '';
			if (undef(this.core.style)) this.core.style = '';
			if (undef(this.core.basewidth)) this.core.basewidth = 80;
			if (undef(this.core.baseheight)) this.core.baseheight = 80;
			if (undef(this.core.basetop)) this.core.basetop = 0;
			if (undef(this.core.baseleft)) this.core.baseleft = 0;			
			if (undef(this.core.draggedoffsetx)) this.core.draggedoffsetx = 0;
			if (undef(this.core.draggedoffsety)) this.core.draggedoffsety = 0;
			if (undef(this.core.updating)) this.core.updating = false;
			if (undef(this.core.update)) this.core.update = noop;
			if (undef(this.core.responsive)) this.core.responsive = false;
			if (undef(this.core.keepaspect)) this.core.keepaspect = false;
			if (undef(this.core.draggable)) this.core.draggable = false;
			if (undef(this.core.zvalue)) this.core.zvalue = 2000;
			
		}
		else {
		
			this.core = {};
			
			this.core.id = opts.hasOwnProperty('id') ? opts.id : pb.uniqueId('SubPanel-'+(pb.subpanelindex++));	
			this.core.type = opts.hasOwnProperty('type') ? opts.type : 'user';			
			this.core.scale = opts.hasOwnProperty('scale') ? opts.scale : 1;
			this.core.elementHTML = opts.hasOwnProperty('elementHTML') ? opts.elementHTML : '';
			this.core.className = opts.hasOwnProperty('className') ? opts.className : '';
			this.core.style = opts.hasOwnProperty('style') ? opts.style : '';
			this.core.basewidth = opts.hasOwnProperty('basewidth') ? opts.basewidth : 80;
			this.core.baseheight = opts.hasOwnProperty('baseheight') ? opts.baseheight : 80;
			this.core.basetop = opts.hasOwnProperty('basetop') ? opts.basetop : 0;
			this.core.baseleft = opts.hasOwnProperty('baseleft') ? opts.baseleft : 0;
			this.core.actualwidth = opts.hasOwnProperty('actualwidth') ? opts.actualwidth : 80;
			this.core.actualheight = opts.hasOwnProperty('actualheight') ? opts.actualheight : 80;
			this.core.actualtop = opts.hasOwnProperty('actualtop') ? opts.actualtop : 0;
			this.core.actualleft = opts.hasOwnProperty('actualleft') ? opts.actualleft : 0;
			this.core.draggedoffsetx = opts.hasOwnProperty('draggedoffsetx') ? opts.draggedoffsetx : 0;
			this.core.draggedoffsety = opts.hasOwnProperty('draggedoffsety') ? opts.draggedoffsety : 0;
			this.core.updating = opts.hasOwnProperty('updating') ? opts.updating : false;
			this.core.update = opts.hasOwnProperty('update') ? opts.update : noop;
			this.core.responsive = opts.hasOwnProperty('responsive') ? opts.responsive : false;
			this.core.keepaspect = opts.hasOwnProperty('keepaspect') ? opts.keepaspect : false;
			this.core.draggable = opts.hasOwnProperty('draggable') ? opts.draggable : false;
			this.core.clonable = opts.hasOwnProperty('clonable') ? opts.clonable : false;
			this.core.resizable = opts.hasOwnProperty('resizable') ? opts.resizable : false;
			this.core.zvalue = opts.hasOwnProperty('zvalue') ? opts.zvalue : 1;
			
		}
			
	//**************************** PANEL *****************************//
		this.panel = opts.hasOwnProperty('panel') ? opts.panel : false;
	
	//*************************** ELEMENT ****************************//
		this.element = document.createElement("div");	
		this.element.style.cssText += this.core.style;
		this.element.id = this.core.id;
		this.element.className = this.core.className;

	//**************************** INIT ******************************//
		if (undef(this.core.actualwidth) && undef(this.core.actualheight)){
			this.core.states[0].style = this.core.style;
			this.core.states[1].style = this.core.style;
			this.core.actualwidth = parseFloat(this.element.style.width);
			this.core.actualheight = parseFloat(this.element.style.height);
		}
	
		this.core.type = 'user';
	
		try {
			pb[this.core.type].subpanels.push(this);
		}
		catch (e){
			pb.user.subpanels.push(this);
		}
		
		this.core.previouslocation = {top: this.element.style.top, left: this.element.style.left};
		
		if (!activepanel){
			this.element.title = this.element.id;
			this.element.style.backgroundColor = 'rgba(128,128,128,0.5)';
		}
		else {
			this.element.title = '';
			this.element.style.backgroundColor = 'transparent';
		}
		
		this._dragwait = true;
		this._dragfired = false;
		
		if (opts.children) this.children = opts.children; else this.children = [];
		
	}
	//************************** PROTOTYPE **************************//
	SubPanel.prototype = {
		_show: function(){
			$(this.element).show();
			if (this.children) for (var i=0; i<this.children.length; i++){
				var child = get(this.children[i]); child._show();
			}
			this.core.__hidden = false;
		},
		_hide: function(){
			$(this.element).hide();
			if (this.children) for (var i=0; i<this.children.length; i++){
				var child = get(this.children[i]); child._hide();
			}
			this.core.__hidden = true;
		},
		show: function(){
			//$(this.element).show();
			if (this.children) for (var i=0; i<this.children.length; i++){
				var child = get(this.children[i]);
				$(child.element).show();
			}
		},
		hide: function(){
			//$(this.element).hide();
			if (this.children) for (var i=0; i<this.children.length; i++){
				var child = get(this.children[i]);
				$(child.element).hide();
			}
		},
		fadein: function(time){
			//$(this.element).stop().fadeIn(time*1000);
			time = time || 0;
			if (this.children) for (var i=0; i<this.children.length; i++){
				var child = get(this.children[i]);
				$(child.element).stop().fadeIn(time*1000);
			}
		},
		fadeIn: function(time){
			//$(this.element).stop().fadeIn(time*1000);
			time = time || 0;
			if (this.children) for (var i=0; i<this.children.length; i++){
				var child = get(this.children[i]);
				$(child.element).stop().fadeIn(time*1000);
			}
		},
		fadeout: function(time){
			//$(this.element).stop().fadeOut();
			time = time || 0;
			if (this.children) for (var i=0; i<this.children.length; i++){
				var child = get(this.children[i]);
				$(child.element).stop().fadeOut(time*1000);
			}
		},
		fadeOut: function(time){
			//$(this.element).stop().fadeOut(time*1000);
			time = time || 0;
			if (this.children) for (var i=0; i<this.children.length; i++){
				var child = get(this.children[i]);
				$(child.element).stop().fadeOut(time*1000);
			}
		},
		animate: function(opts, time, ease, onComplete){
			$(this.element).stop().animate(opts, time*1000, ease, onComplete);
		},
		animate3d: function(opts){
		
			var from = opts.from;
			var to = opts.to;
			var ease = opts.ease;
			
			if (!from || !to) return;
			
			var newopts = {};
			newopts.object = this.element;
			newopts.time = (opts.time || 1.0);
			if (ease) newopts.ease = ease;
			newopts.props = from;
			newopts.to = to;
		
			tweencss(newopts);
			
		},
		setStyle: function(s){
			if (typeof s == 'string'){
				if (this.element) this.element.style.cssText = s;
				this.states[this.currentstate].style = s;
			}
			if (typeof s == 'object'){
				$(this.element).css(s);
			}
			window.onresize();
		},
		setOpacity: function(t){
			if (this.element) this.element.style.opacity = t;
		},
		setBackground: function(filepath){
			this.core.states[this.core.currentstate].bgimage = filepath;
			this.setState(this.core.currentstate+1);
		},
		setBackgroundImage: function(t){
			var puid = false;
			if (pb.project && pb.project.puid) var puid = pb.project.puid;
			if (project && project.puid) var puid = project.puid;
			if (!puid) return;
			if (this.element){
				this.element.style.backgroundImage = 'url(projects/'+puid+'/images/'+t+')';
				this.element.style.backgroundSize = '100% 100%';
			}
		},
		setBackgroundColor: function(c){
			if (this.element) this.element.style.backgroundColor = c;
		},
		setLeft: function(l){
			if (this.element) this.element.style.left = l + 'px';
			this.left = l;
		},
		setTop: function(t){
			if (this.element) this.element.style.top = t + 'px';
			this.left = t;
		},
		setPosition: function(l,t){
			if (this.element) this.element.style.left = l + 'px';
			if (this.element) this.element.style.top = t + 'px';
			this.left = l;
			this.top = t;
		},
		setZ: function(z){
			if (this.element) this.element.style.zIndex = z;
			this.core.zvalue = z;
		},
		setWidth: function(w){
			if (this.element) this.element.style.width = w + 'px';
			this.core.actualwidth = w;
		},
		setHeight: function(h){
			if (this.element) this.element.style.height = h + 'px';
			this.core.actualheight = h;
		},
		setSize: function(w, h){
			if (w !== null){
				if (this.element) this.element.style.width = w + 'px';
				this.core.actualwidth = w;
			}
			if (!undef(h) && h !== null){
				if (this.element) this.element.style.height = h + 'px';
				this.core.actualheight = h;
			}
			window.onresize();
		},
		setSizeSmart: function(w, h){
			if (w !== null){
				if (this.element){
					var oldleft = parseFloat(this.element.style.left);
					var oldw = parseFloat(this.element.style.width);
					this.element.style.width = w + 'px';
					this.element.style.left = oldleft - (w-oldw);
				}
				this.core.actualwidth = w;
			}
			if (!undef(h) && h !== null){
				if (this.element){
					var oldtop = parseFloat(this.element.style.top);
					var oldh = parseFloat(this.element.style.height);
					this.element.style.height = h + 'px';
					this.element.style.top = oldtop - (h-oldh);
				}
				this.core.actualheight = h;
			}
			var theight = ($(this.element).outerHeight()/2)
					- ($(this.textnode).outerHeight()/2);
				$(this.textnode).css('top', theight + 'px');
			window.onresize();
		},
		setPositionCenter: function(x, y){
			if (x !== null){
				if (this.element) this.element.style.left = (x - $(this.element).outerWidth()/2) + 'px';
				this.left = parseFloat(this.element.style.left);
			}
			if (!undef(y) && y !== null){
				if (this.element) this.element.style.top = (y - $(this.element).outerHeight()/2) + 'px';
				this.top = parseFloat(this.element.style.top);
			}
		},
		getPositionCenter: function(){
			var result = {};
			result.x = parseFloat(this.element.style.left) + ($(this.element).outerWidth()/2);
			result.y = parseFloat(this.element.style.top) + ($(this.element).outerHeight()/2);
			return result;
		},
		getWidthToHeight: function(){
			return this.width/this.height;
		},
		getHeightToWidth: function(){
			return this.height/this.width;
		},
		getActualWidth: function(){
			return parseFloat(this.element.style.width);
		},
		getActualHeight: function(){
			return parseFloat(this.element.style.width);
		},
		scaleTo: function(s){
			this.core.scale = s; 
			$(this.element).css({
				'transform': 'scale('+s+','+s+')',
				'-ms-transform': 'scale('+s+','+s+')',
				'-moz-transform': 'scale('+s+','+s+')',
				'-webkit-transform': 'scale('+s+','+s+')'
			});
		},
		remove: function(opts){
			this.panel.removeChild(this); //console.log('rmove');
			for (var i=0; i<this.children.length; i++){
				get(this.children[i]).remove();
			}
		},
		destroy: function(){
			$(this.element).remove();
			removeFromArray(pb[this.core.type].subpanels, this);
			if (this.panel) removeFromArray(this.panel.subpanels, this);
		},
		restore: function(){
			this.panel.addChild(this);
			pb[this.core.type].subpanels.push(this);
		},
		clone: function(opts){
		
			if (undef(opts)) opts = {};
			
			var type = opts.hasOwnProperty('type') ? opts.type : this.core.type;
			var extrastyle = opts.hasOwnProperty('extrastyle') ? opts.extrastyle : '';
			
			this.core.style = this.element.style.cssText + extrastyle;
		
			var newsubpanel = new SubPanel({	
				core: window.clone(this.core),
				panel: this.panel,
				type: type
			});
			
			newsubpanel.element.style.cssText += this.element.style.cssText
				+ ' ' + extrastyle + ' background-size: 100% 100%; margin: 0px;';
			
			if (!undef(opts.library)) newsubpanel.library = opts.library;
			
			var clonedchildren = [];
			for (var i=0; i<this.children.length; i++){
				var child = get(this.children[i]);
				var clone = child.clone({extrastyle: 'left: '+(parseFloat(child.element.style.left)+20)
				+'px; top: '+(parseFloat(child.element.style.top)+20)+'px;'});
				clonedchildren.push(clone.core.id);
				pb.currentpanel.addChild(clone);
			}
			
			newsubpanel.children = clonedchildren;
			
			//for (var i=0; i<clonedchildren.length; i++){
				
			//}
			
			
			return newsubpanel;
		},
		copy: function(opts){
		
			if (undef(opts)) return;
			if (undef(opts.subpanel)) return;
			
			var extrastyle = opts.hasOwnProperty('extrastyle') ? opts.extrastyle : '';
			var copyid = opts.hasOwnProperty('copyid') ? opts.copyid : false;
			
			this.core = clone(btn.core);
			this.element.className = btn.element.className;
			this.element.style.cssText = btn.element.style.cssText + extrastyle;
			
			if (copyid){
				this.element.id = btn.element.id;
				this.core.id = btn.element.id;
			}
			
		},
		whileDown: false,
		click: function(){
			
			$('#tooltip2').finish().fadeOut();
			
			if (this.children){
				var bbox = this.element.getBoundingClientRect();
				for (var i=0; i<this.children.length; i++){
					var child = get(this.children[i]);
					//var cbox = child.element.getBoundingClientRect();
					//child._x = bbox.left - cbox.left;
					//child._y = bbox.top - cbox.top;
					var _bbox = this.element.getBoundingClientRect();
					var _cbox = child.element.getBoundingClientRect();
					var _pbox = this.panel.element.getBoundingClientRect();
					child._x = _cbox.left - _bbox.left - _pbox.left;
					child._y = _cbox.top - _bbox.top - _pbox.top;
				}
			}
			

			if (pb.currentpanel){
				if (this.panel){
					if (pb.shiftdown){
						if (this.element.className.indexOf('outlined') != -1){
							$('.outlined').removeClass('first');
							$(this.element).addClass('outlined'); $(this.element).addClass('first');
						}
						else {
							if ($('.outlined').length == 0) $(this.element).addClass('first');
							$(this.element).addClass('outlined');
						}
					}
					else {
						if (this.element.className.indexOf('outlined') != -1){
							$('.outlined').removeClass('first'); $(this.element).addClass('outlined'); $(this.element).addClass('first');
						}
						else {
							$('.outlined').removeClass('outlined').removeClass('first'); $(this.element).addClass('outlined');
							$($('.outlined')[0]).addClass('first'); var item = pb.getItem($('.outlined')[0].id);
						}
					}
					
					$('.outlinedjson').removeClass('outlinedjson');
					
					if ($('.outlined').exists()){
						
						var array = [];
						$('.outlined').each(function(){
							var type = false, set = false;
							var item = pb.getItem(this.id);
							if (item instanceof SubPanel) type = 'subpanel';
							if (item instanceof Widget){
								type = 'widget'; set = item.core.set;
							}
							array.push({id: this.id, type: type, set: set, width: item.core.actualwidth});
						});
						ng.selected = array;
						
						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;
						
						if (this.core.touchpanelkey) $('#touchpanelkey-radio'+this.core.touchpanelkey).click();
						else $('#touchpanelkey-radio9').click();
						
						$('#item-width-input').val(pb.getItem($('.first')[0].id).core.actualwidth);
						$('#item-height-input').val(pb.getItem($('.first')[0].id).core.actualheight);
						
						this.core.actualtop = parseFloat(this.element.style.top);
						this.core.actualleft = parseFloat(this.element.style.left);
						
						$('#item-top-input').val(pb.getItem($('.first')[0].id).core.actualtop);
						$('#item-left-input').val(pb.getItem($('.first')[0].id).core.actualleft);
						
						$('#props-props-label').click();
						
						if ($('#props_props').css('display') == 'none'){
							$('.item-options').each(function(){
								$(this).css({display: 'none'});
							});
							setTimeout(function(){
								$('#item-basics-container').slideDown(400);
							}, 200);
						}
						
					}
					else {
						ng.selected = false, ng.buttonstates = [];
						$('.item-options').each(function(){
							if ($(this).css('display') != 'none') $(this).slideUp();
						});
					}
				
				}
				else {				
					$('.buttonlibraryselected').removeClass('buttonlibraryselected');
					$(this.element).addClass('buttonlibraryselected');
				}
			
			}
		
			if (pb.project.textEditing){
			
				if (pb.project.textEditing.core.text)
					pb.project.textEditing.core.text = 
					$(pb.project.textEditing.textnode)[0].innerHTML;
				
				for (k in CKEDITOR.instances){
					var instance = CKEDITOR.instances[k];
					instance.destroy();
				}
				
				if (pb.project.textEditing.textnode){
					$(pb.project.textEditing.textnode).attr('contenteditable', 'false');
					$(pb.project.textEditing.textnode).blur();
					$(pb.project.textEditing.textnode).addClass('item_child');
					allDescendantsAddClass(pb.project.textEditing.textnode, 'ck_edit');
					$(pb.project.textEditing.textnode).children().addClass( 'ck_edit' );
				}
				else {
					$(pb.project.textEditing.element).attr('contenteditable', 'false');
					$(pb.project.textEditing.element).blur();
					$(pb.project.textEditing.element).addClass('item_child');
					if (pb.project.textEditing.element) 
						allDescendantsAddClass(pb.project.textEditing.element, 'ck_edit');
					$(pb.project.textEditing.element).children().addClass( 'ck_edit' );
				}
				pb.project.textEditing = false;
				$(this.textnode).removeClass('selectable');
				
			}
			
		},
		doubleclick: function(){
		
			$('#tooltip2').finish().fadeOut();

			if (pb.project.textEditing){
			
				if (pb.project.textEditing.text) pb.project.textEditing.text = $(pb.project.textEditing.textnode)[0].innerHTML;
				
				for (k in CKEDITOR.instances){
					var instance = CKEDITOR.instances[k];
					instance.destroy();
				}
				
				if (pb.project.textEditing.textnode){
					$(pb.project.textEditing.textnode).attr('contenteditable', 'false');
					$(pb.project.textEditing.textnode).blur();
					$(pb.project.textEditing.textnode).addClass('item_child');
					allDescendantsAddClass(pb.project.textEditing.textnode, 'ck_edit');
					$(pb.project.textEditing.textnode).children().addClass( 'ck_edit' );
				}
				else {
					$(pb.project.textEditing.element).attr('contenteditable', 'false');
					$(pb.project.textEditing.element).blur();
					$(pb.project.textEditing.element).addClass('item_child');
					if (pb.project.textEditing.element) 
						allDescendantsAddClass(pb.project.textEditing.element, 'ck_edit');
					$(pb.project.textEditing.element).children().addClass( 'ck_edit' );
				}
				
				pb.project.textEditing = false;
				$(this.textnode).removeClass('selectable');
				
			}
			
		},
		dragging: function(offx, offy){
		
			if (this._dragwait){
				if (pb.mouse.distancefromdown < 4) return;
				else {
					this._dragwait = false;
					
					if (!this._dragfired){

						this.element.style.transform =
							'scale('+pb.currentpanel.core.scale+','+
									pb.currentpanel.core.scale+')';
						$(this.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+')'
						});

						document.body.appendChild(this.element);
					
					}
					
					this._dragfired = true;
				}
			}
		
			this.element.style.zIndex = 24000;
			this.element.style.position = 'absolute';

			var elebounds = this.element.getBoundingClientRect();
			var bbox = pb.currentpanel.element.getBoundingClientRect();
			var s = pb.currentpanel.core.scale;
			var doffsetx = -this.core.draggedoffsetx;
			var doffsety = -this.core.draggedoffsety;
			var oy = 0;
			var ox = 0;
			
			if (!this.panel){
				doffsetx = doffsetx*s;
				doffsety = doffsety*s;
			}
			
			var bbox1 = this.element.getBoundingClientRect();
			
			this.element.style.top = oy + (doffsety + pb.mouse.y) - ($(this.element).outerHeight()*(1-s)/2) + 'px';
			this.element.style.left = ox + (doffsetx + pb.mouse.x) - ($(this.element).outerWidth()*(1-s)/2) + 'px';	
	
			var bbox2 = this.element.getBoundingClientRect();
			
			if (this.panel && this.children){ //console.log('dragchildren', this.children);
				var pbox = this.panel.element.getBoundingClientRect();
				for (var i=0; i<this.children.length; i++){
					var child = get(this.children[i]); if (!child) continue;
					
					var cbox = child.element.getBoundingClientRect();
					var left = bbox1.left - cbox.left;
					var top = bbox1.top - cbox.top;
					/*child.element.style.left = (bbox2.left + left)*s + 'px';
					child.element.style.top = (bbox2.top + top)*s + 'px';*/
					//console.log(bbox1.left, bbox2.left, cbox.left, pbox.left, pb.mouse.x);
					//console.log('eachchild', child._x, child._y);
					child.element.style.left = ((bbox2.left + child._x)/s) + 'px';
					child.element.style.top = ((bbox2.top + child._y)/s) + 'px';
					//child.core.draggedoffsetx = bbox2.left - cbox.left + pb.mouse.x;
					//child.core.draggedoffsety = 10;
					//child.dragging(offx + left, offy + top);
					
					
				}
			}

			$(this.element).css({
				'transform': 'scale('+pb.currentpanel.core.scale+','+pb.currentpanel.core.scale+')',
				'-ms-transform': 'scale('+pb.currentpanel.core.scale+','+pb.currentpanel.core.scale+')',
				'-moz-transform': 'scale('+pb.currentpanel.core.scale+','+pb.currentpanel.core.scale+')',
				'-webkit-transform': 'scale('+pb.currentpanel.core.scale+','+pb.currentpanel.core.scale+')'
			});
			
			this.core.actualtop = (doffsety + pb.mouse.y)/s - bbox.top/s + -1;
			this.core.actualleft = (doffsetx + pb.mouse.x)/s - bbox.left/s + -1;
			
			if ($('.first').exists()){
				$('#item-top-input').val(pb.getItem($('.first')[0].id).core.actualtop);
				$('#item-left-input').val(pb.getItem($('.first')[0].id).core.actualleft);
			}

		},
		drop: function(){
		
			if (undef(pb.project)) return;
			if (undef(pb.currentpanel)) return;
			if (undef(pb.currentpanel.element)) return;
			
			if (this._dragwait) return;
			
			this._dragwait = true;
			this._dragfired = false;
		
			var oy = -1; var ox = -1;
			var s = pb.currentpanel.core.scale;
			var doffsetx = -this.core.draggedoffsetx;
			var doffsety = -this.core.draggedoffsety;
			var elebox = this.element.getBoundingClientRect();
			var bbox = pb.currentpanel.element.getBoundingClientRect();
			
			if (this.panel){
			
				if (pb.mouse.isOverElement(document.getElementById('subpanel-library-pane'))){	
					//pb.addUserButton(this);
				}
				
				$(this.element).css({ 
					'transform': 'scale('+1+','+1+')',
					'-webkit-transform': 'scale('+1+','+1+')',
					'-moz-transform': 'scale('+1+','+1+')',
					'-ms-transform': 'scale('+1+','+1+')'
				});
				
				$(this.element).remove();
				pb.currentpanel.element.appendChild(this.element);
				this.element.style.zIndex = this.core.zvalue;
				
				//todo: move to constrain?
				if (pb.snap_to_panel && doffsetx + pb.mouse.pagex < bbox.left) 
					this.element.style.left = 0 + 'px';
				else if (pb.snap_to_panel && doffsetx + pb.mouse.pagex > bbox.right - $(this.element).outerWidth()*s) 
					this.element.style.left = $(pb.currentpanel.element).outerWidth() 
						- $(this.element).outerWidth() - 2 + 'px';
				else this.element.style.left = (doffsetx + pb.mouse.x)/s - bbox.left/s + ox + 'px';
					
				if (pb.snap_to_panel && doffsety + pb.mouse.pagey < bbox.top)
					this.element.style.top = 0 + 'px';
				else if (pb.snap_to_panel && doffsety + pb.mouse.pagey > bbox.bottom - $(this.element).outerHeight() * s)
					this.element.style.top = $(pb.currentpanel.element).outerHeight() 
						- $(this.element).outerHeight() - 2 + 'px';
				else this.element.style.top = (doffsety + pb.mouse.y)/s - bbox.top/s + oy + 'px';
				
				this.makeResizable();
				
				if (pb.mouse.isOverElement(document.getElementById('subpanel-library-pane'))){	
					this.element.style.top = this.core.previouslocation.top;
					this.element.style.left = this.core.previouslocation.left;
				}
				
				this.core.previouslocation = {top: this.element.style.top, left: this.element.style.left};

			}
			else {
			
				if (pb.currentpanel && !pb.mouse.isOverElement($('#tools-panel')[0]) &&
					pb.mouse.isOverElement(pb.currentpanel.element)){
					
					//this.core.type = 'user';
					
					console.log('test');
					
					var taction = new Action({ type: 'drop', items: [this] });
					pb.saveaction(taction);
						
					$(this.element).remove();
			
					this.element.style.zIndex = this.core.zvalue;
					this.library = 'panel';
					
					this.setPosition(
						doffsetx + pb.mouse.x/s - bbox.left/s + ox,
						doffsety + pb.mouse.y/s - bbox.top/s + oy
					);
					
					this.element.className = this.element.className.replace('cloneable','');
					this.core.texteditable = true;	
					this.element.className += ' draggable ';
					
					this.makeResizable();
					
					this.element.style.width = this.basewidth + 'px';
					this.element.style.height = this.baseheight + 'px';
					
					this.panel = pb.currentpanel;
					this.panel.addChild(this);
					
					this.constrain();
					
					this.core.responsive = true;
					this.core.left = parseFloat(this.element.style.left);
					this.core.top = parseFloat(this.element.style.top);
						
					tweencss({ object: this.element, time: 0, props: {scale: 1.0}, to: {scale: 1.0} });
					
					this.core.previouslocation = {top: this.element.style.top, left: this.element.style.left};
					
					pb.updateTree();
					
				}
				else this.destroy();
			}
			
			this.core.actualtop = parseFloat(this.element.style.top);
			this.core.actualleft = parseFloat(this.element.style.left);
			
			if ($('.first').exists()){
				$('#item-top-input').val(pb.getItem($('.first')[0].id).core.actualtop);
				$('#item-left-input').val(pb.getItem($('.first')[0].id).core.actualleft);
			}
			
		},
		clickup: noop,
		hoverin: function(){
			if (activepanel) return;
			$('#tooltip2').hide();
		},
		hoverout: function(){
			if (activepanel) return;
			$('#tooltip2').finish().fadeOut();		
		},
		constrain: function(){
		
			var bbox = pb.currentpanel.element.getBoundingClientRect();
			var elebox = this.element.getBoundingClientRect();
			var ox = 0; var oy = 0;
		
			if (elebox.left < bbox.left) this.element.style.left = '0px';
			if (elebox.top < bbox.top) this.element.style.top = '0px';
			if (elebox.right > bbox.right) this.element.style.left =
				$(pb.currentpanel.element).outerWidth()
				- $(this.element).outerWidth() + ox + 'px';
			if (elebox.bottom > bbox.bottom) this.element.style.top =
				$(pb.currentpanel.element).outerHeight()
				- $(this.element).outerHeight() + oy + 'px';
				
		},
		makeDraggable: function(opts){
		
			if (undef(opts)) opts = {};
		
			var appendTo = opts.hasOwnProperty('appendTo') ? opts.appendTo : 'body';
			var helper = opts.hasOwnProperty('helper') ? opts.helper : 'clone';
			var start = opts.hasOwnProperty('start') ? opts.start : noop;
			var drag = opts.hasOwnProperty('drag') ? opts.drag : noop;
			var stop = opts.hasOwnProperty('stop') ? opts.stop : noop;
			var grid = opts.hasOwnProperty('grid') ? opts.grid : [1, 1];
			var containment = opts.hasOwnProperty('containment') ? opts.containment : 'document';
		
			$(this.element).draggable({
				appendTo: appendTo,
				helper: helper,
				start: start,
				drag: drag,
				stop: stop,
				grid: grid,
				containment: containment
			});
			
		},
		makeResizable: function(){
			
			$(this.element).resizable({
				autoHide: true,
				containment: 'parent', 
				handles: 'n, e, s, w, se, sw, nw, ne',
				resize: function (e, ui) {	
				
					var s = pb.currentpanel.core.scale;
					var bbox = pb.currentpanel.element.getBoundingClientRect();
					var elebox = this.element.getBoundingClientRect();
					
					var changeWidth = ui.size.width - ui.originalSize.width;
					
					var newWidth = ui.originalSize.width + changeWidth/s;
				 
					var changeHeight = ui.size.height - ui.originalSize.height;
					var newHeight = ui.originalSize.height + changeHeight/s; 
					
					this.element.style.width = newWidth+'px';
					this.element.style.height = newHeight+'px';
					
					var oldtop = this.element.style.top;
	
					if (ui.handle == 'w' || ui.handle == 'nw' || ui.handle == 'sw'){
						//console.log('nw');
						this.element.style.left = ((pb.mouse.x - bbox.left)/s) + 'px';
					}
					if (ui.handle == 'n' || ui.handle == 'nw' || ui.handle == 'ne'){
						//console.log('ne');
						this.element.style.top = ((pb.mouse.y - bbox.top)/s) + 'px';
					}
					
					var elebox = this.element.getBoundingClientRect();
					if (pb.snap_to_panel && elebox.right >= bbox.right)
						this.element.style.width = newWidth - ((elebox.right - bbox.right)/s) + 'px';
					if (pb.snap_to_panel && elebox.bottom >= bbox.bottom)
						this.element.style.height = newHeight - ((elebox.bottom - bbox.bottom)/s) + 'px';
					if (pb.snap_to_panel && elebox.top <= bbox.top){
						if (this._lastsizey) this.element.style.height = this._lastsizey;
						this.element.style.top = '0px';
					}
					if (pb.snap_to_panel && elebox.left <= bbox.left){
						if (this._lastsizex) this.element.style.width = this._lastsizex;
						this.element.style.left = '0px';
					}
				
					var theight = ($(this.element).outerHeight()/2)
						- ($(this.textnode).outerHeight()/2);
					$(this.textnode).css('top', theight + 'px');
					
					this._lastsizex = this.element.style.width;
					this._lastsizey = this.element.style.height;
					this._lastleft = this.element.style.left;
					this._lasttop = this.element.style.top;
					
					this.core.actualwidth = parseInt(this.element.style.width);
					this.core.actualheight = parseInt(this.element.style.height);
					
					if ($('.first').exists()){
						$('#item-width-input').val(pb.getItem($('.first')[0].id).core.actualwidth);
						$('#item-height-input').val(pb.getItem($('.first')[0].id).core.actualheight);
					}
					
				}.bind(this),
				start: function(e, ui) {
					this.action = new Action({
						type: 'size',
						items: [this],
						oldvalues: [{width: this.element.style.width, height: this.element.style.height}]
					});
				}.bind(this),
				stop: function(e, ui) {
					this.action.newvalues = [{width: this.element.style.width, height: this.element.style.height}];
					pb.saveaction(this.action);
					if (this.children) for (var i=0; i<this.children.length; i++){
						var child = get(this.children[i]);
						var _bbox = this.element.getBoundingClientRect();
						var _cbox = child.element.getBoundingClientRect();
						var _pbox = child.panel.element.getBoundingClientRect();
						child._x = _cbox.left - _bbox.left - _pbox.left;
						child._y = _cbox.top - _bbox.top - _pbox.top;
						//child.element.style.zIndex = parseInt(this.element.style.zIndex) + 1;
					}
				}.bind(this)
			}); 
			
		}
	}
//**************  END SUBPANEL  ****************//