var Builder = {

	shown: false,
		
	hide: function()
	{	
		/* Save current position (to be restored in next "show") */
		$(document.body).initial_background_position = $(document.body).getStyle('background-position')
		$(document.body).initial_padding_top = $(document.body).getStyle('padding-top')
		window.previous_scroll = window.getScroll().y
		
		/* Set revert action */
		$(document.body).addEvent('mousedown', Builder.show)

		/* Hide admin elements */
		$('phi_builder').setStyle('display', 'none')
		$$('.no_preview').setStyle('display', 'none')
		$$('.phi_instance_menu').setStyle('display', 'none')
		$$('.phi_instance.disabled').setStyle('display', 'none')
		$$('.phi_widget_options_extra_div').setStyle('display', 'none')

		/* Reposition body */
		$(document.body).setStyle('background-position', '')
		$(document.body).setStyle('padding-top', '')
		
		Builder.shown = false
	},

	show: function()
	{		
		/* Show admin elements */
		$('phi_builder').setStyle('display', '')
		$$('.no_preview').setStyle('display', '')
		$$('.phi_instance_menu').setStyle('display', '')
		$$('.phi_instance.disabled').setStyle('display', '')
		$$('.phi_widget_options_extra_div').setStyle('display', '')

		/* Restore body */
		$(document.body).setStyle('background-position', $(document.body).initial_background_position||'0 75px')
		$(document.body).setStyle('padding-top', $(document.body).initial_padding_top||'75px')
		window.scrollTo(0,window.previous_scroll)
		
		/* Return body to normal behavior */
		$(document.body).removeEvent('mousedown', Builder.show)
		
		Builder.shown = true
	},
	
	toggle: function()
	{
		if ( Builder.shown ) {
			Builder.hide()
		} else {
			Builder.show()
		}
	}
}

/* Drag and Drop behavior */
Builder.Drag = {

	sortables: null,
	containers: null,
	blocks: null,
	resorted: false,
	
	refresh: function()
	{
		Builder.Drag.containers = $$('.phi_container')
		Builder.Drag.blocks = $$('.phi_block')
	
		Builder.Drag.sortables = new Sortables(Builder.Drag.blocks, {
			opacity: 0.3,
			clone: true,
			constrain: false,
			handle: '.phi_instance_bar'
		})

		Builder.Drag.sortables.addEvent('start',	Builder.Drag.showContainers)
		Builder.Drag.sortables.addEvent('complete',	Builder.Drag.hideContainers)
		Builder.Drag.sortables.addEvent('sort',		Builder.Drag.adjustContainers)
	},

	adjustContainers: function(element) 
	{
		if ( element.hasClass('inserter') ) {
			return;
		}

		Builder.Drag.resorted	= true

		Builder.Drag.blocks.each( function(item, index)
		{
			var children_count = item.getChildren().length
		
			if( !children_count || ( children_count == 1 && item.getFirst().get('style').test('absolute') ) ) {
				item.addClass('empty')
			} else {
				item.removeClass('empty')
			}
		})
		Builder.Drag.adjustBar(element)
	},

	showContainers: function(element, clone)
	{
		element._initial_parent = element.getParent()

		Builder.Drag.containers.each( function(item, index)
		{
			item.addClass('dragging')
		})
		
		Builder.Drag.blocks.each( function(item, index)
		{
			if( item.getChildren().length == 0 ) {
				item.addClass('empty')
			}
		})
	},
	
	hideContainers: function(element)
	{
		Builder.Drag.containers.each(function(item, index){
			item.removeClass('dragging')
			item.removeClass('empty')
		})

		Builder.Drag.blocks.each(function(item, index){
			item.removeClass('empty')
		})

		/* New module dragged */
		if ( element.hasClass('phi_inserter') ) {

			var element_parent = element.getParent('.phi_container_body')
			if ( !element_parent ) {
				return;
			}

			/* Determine the module */
			var module	= element.get('class').match(/phi_module_([^ ]+)/)[1]

			/* Look for block and container */
			var container_id	= element_parent.id.replace('container_','')
			var block_id		= element.getParent('.phi_block').id.replace('phi_block_'+container_id+'_','')

			/* Determine the iorder */
			var iorder			= 0
			var previous		= element.getPrevious('.phi_instance')
			while ( previous ) {
				iorder++
				previous = previous.getPrevious('.phi_instance')
			}

			Builder.Instance.create(module, container_id, block_id, iorder)
			element.inject(element._initial_parent, 'bottom')
			
			return;
		}

		/* Save layout */
		if ( Builder.Drag.resorted ) {

			var params	= Builder.Drag.sortables.serialize(null, function(element) {
				
				if ( element.hasClass('phi_inserter') ) {
					return;
				}
				
				var matches = element.getParent().id.match(/phi_block_([0-9]+)_([0-9]+)/)
				return 'containers['+matches[1]+']['+matches[2]+'][]='+element.id.replace('phi_instance_','')
			}).flatten().join('&')

			new Request({
				'url': Phi.linkbase+'phi/section/layout&section='+Phi.section,
				'data': params
			}).send()

			Builder.Drag.resorted = false
		}
		
		/*(document.body).behave(Builder.topRules)
		console.log('!!!!')*/
	},

	adjustBar: function(element){
	     var parent = element.getElement('.phi_instance_bar')
	     var extras = element.getElement('.phi_widget_options_extra_div')
	     var tools = element.getElement('.phi_instance_tools')
	     var marker = element.getElement('.phi_instance_marker')
	     var xpander = element.getElement('.phi_widget_options_expander')

	     if($defined(tools)){
		 if(parent.getCoordinates().width > tools.getCoordinates().width){
			marker.setStyle('width', marker.get('delta'))
		    }else{
			marker.set('delta', marker.getStyle('width'))
			marker.setStyle('width', parent.getCoordinates().width - (xpander.getCoordinates().width+10)) //borders and padding added
		    }

		 if(parent.getSize().x > tools.getSize().x+63){
			    extras.removeClass('outside')
			    extras.addClass('inside')
			    extras.setStyles({
				'position' : '',
				'top' : '',
				'left' :''
			    })
			    extras.inject(parent, 'bottom')
		 }else{
			    extras.removeClass('inside')
			    extras.addClass('outside')
			    extras.setStyles({
				'position' : 'absolute',
				'top' : -17,
				'left' : parent.getParent().getCoordinates().width - 59
			    })

			    extras.inject(parent.getParent().getParent().getParent(), 'top')
		}
	    }
	}

}

/* Generic top shelf.  Loads module inserters and section modules */
Builder.Shelf = {

	onHide: $empty,
	onBeforeHide: $empty,	

	setHeight: function(height, onResize)
	{
		if ( !onResize )
			onResize = $empty
		
		shelf = $('phi_builder_shelf')

		shelf.setStyle('overflow', 'hidden')
		Builder.Shelf.overflown = false
		if ( height > 500 ) {
			height = 500
			Builder.Shelf.overflown = true
		}

		initial_height = shelf.getSize().y-2
		
		if ( initial_height == height ) {
			shelf.setStyle('overflow', Builder.Shelf.overflown ? 'auto' : 'visible')
			return
		}

		previous_scroll = window.getScroll().y
			

		if ( (previous_scroll+5 < initial_height) && (height < initial_height) ) {
			
			$(document.body).morph({
				backgroundPosition: '0 '+(height+70)+'px',
				paddingTop: height+70
			})
			
			new Fx.Scroll(window).start(0,previous_scroll-(initial_height-height))
			
			new Fx.Morph(shelf).start({height: height}).chain(function() {
				shelf.setStyle('overflow', Builder.Shelf.overflown ? 'auto' : 'visible')	
				onResize.run()
			})			
			
			
		} else {

			new Fx.Morph(shelf).start({height: height}).chain(function() {
				$(document.body).setStyle('background-position', '0 '+(height+70)+'px')
				$(document.body).setStyle('padding-top', height+70)
				window.scrollTo(0,previous_scroll+height-initial_height)
				
				shelf.setStyle('overflow', Builder.Shelf.overflown ? 'auto' : 'visible')	
				onResize.run()
			})
		}
	},

	goto: function(url, onResize)
	{
		new Request.HTML({
			url: url,
			evalScripts: false,
			onComplete: function(tree,elements,html,javascript) {
				
				new_content	= new Element('div', {html:html}).inject(document.body)
				new_height	= new_content.getCoordinates().height
			
				shelf = $('phi_builder_shelf')
				
				shelf.set('html',new_content.get('html'))
				new_content.destroy()
				Builder.Shelf.setHeight(new_height+30, onResize)

				$exec(javascript)
				
				Phi.runRules()

				/* Apply new behaviors */
				shelf.getElements('form').each( function(form){
					
					/* Look for a target _id in this form */
					var matches 	= form.action.match(/(instance|_id)=([0-9]+)/)
					var instance_id	= false
					if ( matches != null && typeof matches[1] != 'undefined' ) {
						instance_id = matches[2]
					}

					/* wrap file upload forms in an IFRAME */
					if ( form.getAttribute('enctype') == 'multipart/form-data' ) {
						
						form.onsubmit = function() {
				
							var iframeId				= 'iframe_'+Math.floor(Math.random()*99999)
							var iframeElem				= document.createElement('IFRAME')
							iframeElem.style.display	= 'none'
							iframeElem.id				= iframeId
							iframeElem.name				= iframeId
							iframeElem.src				= 'about:blank'
				
							iframeElem.onload			= function()
							{
								if ( instance_id ) {
									Builder.Instance.reload(instance_id)
								}
								Builder.Shelf.hide()
							}
				
							document.body.appendChild(iframeElem)
							this.setAttribute('target',iframeId)							
							return true
						}
					
					/* Instance creation form */
					} else if ( form.action.match(/instance\/create/) ) {
						
						form.onsubmit = function()
						{
							/* Determine target container id */
							var matches			= form.action.match(/container=([0-9]+)/)
							var container_id	= 1
							if ( matches != null && matches.length == 2 ) {
								container_id	= matches[1]
							}
							
							/* Determine target block id */
							var matches			= form.action.match(/block=([0-9]+)/)
							var block_id		= 0
							if ( matches != null && matches.length == 2 ) {
								block_id	= matches[1]
							}
							
							/* Determine target iorder */
							var matches		= form.action.match(/iorder=([0-9]+)/)
							var iorder		= 0
							if ( matches != null && matches.length == 2 ) {
								iorder = matches[1]
							}
						
							/* Send the form via AJAX */
							form.set('send',{
								url: form.action+'&output=1',
								method: 'post',
								onComplete: function(response) {

									/* Create object via DOM */
									tmpdiv = new Element('div', {
										html: response
									})

									nmodule = tmpdiv.getFirst()
									
									/* Look for the previous sibling */
									if ( iorder > 0 ) {
									
										var sibling = $('phi_block_'+container_id+'_'+block_id).getFirst('.phi_instance')
										while ( iorder > 1 ) {
											sibling	= sibling.getNext('.phi_instance')
											iorder--
										}
										nmodule.inject(sibling,'after')
									
									} else {
										nmodule.inject($('phi_block_'+container_id+'_'+block_id),'top')
									}

									Builder.Drag.refresh()
									$(document.body).behave(Builder.instanceRules)
									nmodule.highlight()
								}
							})

							form.send()
							Builder.Shelf.hide()
							return false
						}

					} else {

						form.onsubmit = function() {

							this.set('send',{
								url: this.action,
								method: 'post',
								onComplete: function(response) {
									Builder.Shelf.hide()
									if ( instance_id ) {
										Builder.Instance.reload(instance_id)
									}
								}
							})
							this.send()
							return false
						}

					}
				} )

				/* Load links within shelf */
				shelf.getElements('a').each( function(link) {
					if ( !link.get('target') && !link.get('href').match(/#$/) ) {
						link.onclick = function() {
							Builder.Shelf.goto(this.href)
							return false
						}
					}
				})
				
				/* Look for cancel buttons */
				shelf.getElements('input').each( function(button) {
					if ( button.type == 'button') {
						
						if ( button.name == 'cancel' ) {
							button.onclick = function() {
								Builder.Shelf.hide()
								return false
							}
						} else if ( button.name == 'reload' ) {
							button.onclick = function() {
								window.location.reload()
								return false
							}
						}
					}
				})
				
			}
		}).send()
	},

	hide: function()
	{	
		Builder.Shelf.onBeforeHide()
		Builder.Shelf.onBeforeHide = $empty
		Builder.Shelf.setHeight(5, function() {
			$('phi_builder_shelf').set('html','')
			Builder.Shelf.onHide()
			Builder.Shelf.onHide = $empty
		})
	}
}


/* Instance Tooltip.  Loads core instance options */
Builder.Tooltip = {
	
	open: function(instance, url, avoid_visualfocus)
	{
		if ( !(instance = $(instance)) )
			return

		instance_content = instance.getElement('.phi_instance_content')
		
		$$('#main_menu li').removeClass('active')

		Builder.Shelf.goto(url, function() {

			offset = (instance_content.getPosition().y-window.getScroll().y) - ($('phi_builder_shelf').getSize().y+75)

			if ( offset < 0 ) {
				new Fx.Scroll(window).start(0,window.getScroll().y+offset-15).chain( function() {
					instance_content.visualFocus({border: 5, opacity: 0.6, color: '#000'})
				} )
			} else if (!avoid_visualfocus) {
				instance_content.visualFocus({border: 5, opacity: 0.6, color: '#000'})
			}

			instance_content.addEvent('visualBlur', Builder.Shelf.hide)

			Builder.Shelf.onBeforeHide = function() {
				instance_content.removeEvents('visualBlur')
				instance_content.visualBlur()
			}
		})
	}		

}

/* Instance in-place actions */
Builder.Instance = {
	
	create: function(module, container_id, block_id, iorder)
	{	
		/* Send the form via AJAX */
		new Request({
			url: Phi.linkbase+'phi/instance/create&module='+module+'&section='+Phi.section+'&container='+container_id+'&block='+block_id+'&iorder='+iorder+'&output=1',
			method: 'post',
			data: 'foo=bar',
			onComplete: function(response) {
			
				/* Create object via DOM */
				tmpdiv = new Element('div', {
					html: response
				})
	
				nmodule = tmpdiv.getFirst()
				
				/* Look for the previous sibling */
				if ( iorder > 0 ) {
				
					var sibling = $('phi_block_'+container_id+'_'+block_id).getFirst('.phi_instance')
					while ( iorder > 1 ) {
						sibling	= sibling.getNext('.phi_instance')
						iorder--
					}
					nmodule.inject(sibling,'after')
				
				} else {
					nmodule.inject($('phi_block_'+container_id+'_'+block_id),'top')
				}
	
				Builder.Drag.refresh()
				$(document.body).behave(Builder.instanceRules)
				nmodule.highlight()
			}
		}).send()

	},
		
	reload: function(instance_id)
	{
		var instance = $('phi_instance_'+instance_id)

		new Request.HTML({
			'url': Phi.linkbase+'phi/instance/run&instance='+instance_id+'&section='+Phi.section,
			'evalScripts': false,
			onComplete: function(tree,elements,response,javascript) {
				/* Create a new div */
				var newdiv	= document.createElement('DIV')
				newdiv.inject(instance,'before')
				
				/* Put the current instance inside the DIV, and overwrite it with the updated instance */
				newdiv.innerHTML = response
				instance.destroy()
				
				/* Break the new instance out of the div */
				var new_instance	= newdiv.getFirst('.phi_instance')
				new_instance.inject(newdiv, 'before')
				newdiv.destroy()

				/* Notify, and re-apply behavior */
				new_instance.highlight()
				$(document.body).behave(Builder.instanceRules)
				
				$exec(javascript)
				
				Builder.Drag.refresh()
			}
		}).send()
	},
	
	browseTo: function(instance_id, url)
	{
		var instance = $('phi_instance_'+instance_id)

		new Request.HTML({
			'url': url,
			'evalScripts': false,
			onComplete: function(tree,elements,html,javascript) {
				
				/* Create a new div */
				var newdiv	= document.createElement('DIV')
				newdiv.inject(instance,'before')

				/* Put the current instance inside the DIV, and overwrite it with the updated instance */
				newdiv.set('html',html)
				$exec(javascript)
				instance.destroy()
				
				newdiv.set('id', 'phi_instance_'+instance_id)

				/* Look for forms */
				newdiv.getElements('form').each( function(form){
					
					/* Look for a target _id in this form */
					var matches 	= form.action.match(/(instance|_id)=([0-9]+)/)
					var instance_id	= false
					if ( matches != null && typeof matches[1] != 'undefined' ) {
						instance_id = matches[2]
					}

					/* wrap file upload forms in an IFRAME */
					if ( form.getAttribute('enctype') == 'multipart/form-data' ) {
				
						form.onsubmit = function() {
				
							var iframeId				= 'iframe_'+Math.floor(Math.random()*99999)
							var iframeElem				= document.createElement('IFRAME')
							iframeElem.style.display	= 'none'
							iframeElem.id				= iframeId
							iframeElem.name				= iframeId
							iframeElem.src				= 'about:blank'
				
							iframeElem.onload			= function()
							{
								if ( instance_id ) {
									Builder.Instance.reload(instance_id)
								}
							}
				
							document.body.appendChild(iframeElem)
							this.setAttribute('target',iframeId)
							return true
						}

					} else {

						form.onsubmit = function() {

							this.set('send',{
								url: this.action,
								method: 'post',
								onComplete: function(response) {
									Builder.Instance.reload(instance_id)
								}
							})

							this.send()
							return false
						}

					}
				} )

				/* Look for cancel buttons */
				newdiv.getElements('input').each( function(button) {
					if ( button.type == 'button' && button.name == 'cancel' ) {
						button.onclick = function() {
							Builder.Instance.reload(instance_id)
							return false
						}
					}
				})
			}
		}).send()
	}
}





/* Top bar behavior */
Builder.topRules = {


	'#main_menu a.tab_label:click': function(event)
	{	
		this.blur()	
		$$('#main_menu li').removeClass('active')
		this.getParent('li').addClass('active')
		Builder.Shelf.hide()
		return false
	},

	'#phi_builder_tab_settings li a:click': function()
	{
		
		$$('#main_menu li ul li').removeClass('active')
		this.getParent('li').addClass('active')
		this.blur()
		Builder.Shelf.goto(this.href)
		return false
	},
	
	'#phi_builder_tab_appearance li a:click': function(event)
	{
		$$('#main_menu li ul li').removeClass('active')
		this.getParent('li').addClass('active')
		this.blur()

		if ( this.href.match(/section\/template\/style/) ) {
			Builder.Shelf.goto(this.href, function() {
				window.scrollTo(0,0)
			})
		} else if ( this.href.match(/section\/variable/) ) {
			Builder.Shelf.goto(this.href, function() {
				$('phi_builder_shelf').getElement('form').onsubmit = $lambda(true)
			})
		} else {
			Builder.Shelf.goto(this.href)
		}
		
		return false
	},
	
	/* Click on any module group (populate shelf) */
	'#phi_builder_tab_content ul li a:click': function()
	{	
		$$('#main_menu li ul li').removeClass('active')
		this.getParent('li').addClass('active')
		this.blur()
		
		group_id = this.id.replace(/[^0-9]/g,'')
		
		instance_group = new Element('div', {
			'class':	'phi_instance_group phi_block',
			html:		$('_module_group_'+group_id).get('html')
		})

		
		/* Shelf item behavior */
		instance_group.behave({
			'.phi_inserter:mouseenter': function(event) {
				if ( !$chk(this.bubble) ) {
					
					/* Cache window size  */
					winsize = $(window).getScrollSize()
					
					this.bubble = new PhiTooltip(this, {
						position: 'bottom',
						margin: 0,
						rollover: true,
						html: '<div class="body"><h1 class="loading">'+Language.get('loading')+'...</h1></div>',
						width: 350,
						height: 200,
						classname: 'inserter_tooltip',
						limit: {
							x: 0,
							y: 0,
							width: winsize.x-30,
							height: winsize.y
						}
					})
					this.bubble._show(event)
					
					modname = this.className.match(/phi_module_([^ ]+)/)[1]
					
					new Request({
						url: Phi.linkbase+'phi/help&item='+modname,
						onComplete: function(response) {
							this.bubble.setHTML('<div class="body"><p class="guideline">'+Language.get('drag this icon into your website to insert')+'</p>'+response+'</div>')
						}.bind(this)
					}).send()
				}
			},
			
			'.phi_inserter:mousedown': function(event) {
				if ( $chk(this.bubble) ) {
					this.bubble.hide()
				}
			}			
		})
		
		
		
		shelf = $('phi_builder_shelf')
		shelf.set('html', '')
		instance_group.inject(shelf)
		Builder.Shelf.setHeight(80)
		
		Builder.Drag.refresh()
		
		return false
	},
	
	/* Preview button */
	'#phi_builder_preview a:click': function(event)
	{
		event.stop()
		Builder.hide()
	},
	
	/* Editable variables */
	'.phi_editable_variable:mouseover':	function()
	{
		this.addClass('hover')
	},
	
	'.phi_editable_variable:mouseout':	function()
	{
		this.removeClass('hover')
	},	

	'.phi_editable_variable':	function()
	{
		
		if ( !this.get('name') ) {
			return;
		}
		
		var element		= this
		
		var form		= new Element('div')		

		var input = new Element('input', {
			
			type: this.get('type')||'text',
			value: this.get('html'),
			
			styles: {
				fontWeight: this.getStyle('fontWeight'),
				fontFamily: this.getStyle('fontFamily')
			},

			events: {
				
				keyup: function(event) {
					if ( event.key == 'enter' ) {
						element.save(input.value,false)
					} else if ( event.key == 'esc' ) {
						element.hide()
					} else {
						element.set('html', this.value)
					}
				}
			}

		}).inject(form)

		
		deleter_row = new Element('div', {
			'class': 'deleter'
		}).inject(form)
		
		new Element('label', {
			html: Language.get('use default value'),
			'for': 'chbox_default_'+this.get('name'),
			styles: {
				fontSize: 10,
				marginLeft: 20
			}
		}).inject(deleter_row)
		
		this.deleter = new Element('input', {
			id: 'chbox_default_'+this.get('name'),
			type: 'checkbox',
			name: 'delete_var_'+this.get('name'),
			value: 1
		}).inject(deleter_row)		
		
		
		new Element('button', {
			html: Language.get('apply'),
			events: {
				click: function() {
					element.save(input.value,false)
					return false
				}
			}
		}).inject(form)
		
		new Element('a', {
			href: '#', 
			html: Language.get('apply to all sections'),
			events: {
				click: function() {
					element.save(input.value,true)
					return false
				}
			}
		}).inject(form)
		
		this.set('initial_html', this.get('html'))
		
		if ( !this.get('html') ) {
			this.set('html', Language.get('click here to add')+' '+this.get('name'))
		}
		
		this.tooltip = new PhiTooltip(this, {
			position: 'top',
			margin: 0,
			rollover: false,
			html: form,
			width: 400,
			height: 100,
			classname: 'variable_tooltip'
		})

		this.tooltip.input		= input

		/* Hide tooltip when clicked outside */
		this.hide = function(event) {

			if ( $chk(event) )
				event.target = $(event.target)
			
			if ( !$chk(event) || (event.target.get('class') != 'variable_tooltip' && !event.target.getParent('.variable_tooltip')) ) {
				this.tooltip.hide()
				this.tooltip.input.set('value', this.get('initial_html'))
				this.set('html', this.get('initial_html')||Language.get('click here to add')+' '+this.get('name'))
			}
		}.bind(this)

		$(document.body).addEvent('mousedown', this.hide)
		
		this.save = function(value, toAll) {

			new Request({
				url: Phi.linkbase+'phi/section/variable&section='+Phi.section,
				data: 'var_'+this.get('name')+'='+input.value+(toAll?'&all_var_'+this.get('name')+'=1':'')+(this.deleter.checked?'&'+this.deleter.name+'=1':''),
				onComplete: function(response) {
					
					object = JSON.decode(response)
				
					value = object[this.get('name')]||Language.get('click here to add')+' '+this.get('name')
					
					this.tooltip.hide()
					this.set('initial_html',value)
					this.set('html', value)
					
					this.deleter.checked = false
					
					element.highlight()
				}.bind(this)
			}).send()
		}.bind(this)
		
	},

	'.phi_editable_variable:mouseup': function()
	{
		if ( this.get('name') ) {
			this.tooltip._show()
			this.tooltip.input.focus()
			this.tooltip.input.select()
		}
	},


	/* Editable images */
	'.phi_editable_image:mouseover':	function()	{
		this.addClass('hover')
	},
	
	'.phi_editable_image:mouseout':	function()	{
		this.removeClass('hover')
	},	
	
	'.phi_editable_image':	function()	{
		
		if ( !this.get('name') ) {
			return;
		}
		
		var max_width	= this.get('max_width')||''
		var max_height	= this.get('max_height')||''
		
		var form		= new Element('form', {
			action: Phi.linkbase+'phi/section/variable&section='+Phi.section+'&variable=var_'+this.get('name')+'&max_width='+max_width+'&max_height='+max_height,
			method: 'post',
			enctype: 'multipart/form-data',
			styles: {
				padding:	'5px',
				textAlign:	'center'
			}
		})
		
		new Element('input', {
			type: 'file',
			name: 'var_'+this.get('name'),
			size: 15,
			styles: {
				background:	'#fff',
				color:		'#000',
				padding:	0,
				margin:		'7px 0',
				border:		'1px solid black'
			}
		}).inject(form)
		
		new Element('label', {
			html: Language.get('delete image'),
			'for': 'chbox_delete_image',
			styles: {
				fontSize: 10,
				marginLeft: 20
			}
		}).inject(form)
		
		new Element('input', {
			id: 'chbox_delete_image',
			type: 'checkbox',
			name: 'delete_var_'+this.get('name'),
			value: 1
		}).inject(form)
		
		new Element('button', {
			html: Language.get('apply'),
			events: {
				click: function() {	
					form.submit()
					return false
				}
			}
		}).inject(form)
		
		new Element('a', {
			href: '#',
			html: Language.get('apply to all sections'),
			events: {
				click: function() {
					new Element('input', {type:'hidden', name:'all_var_'+this.get('name'), value:1}).inject(form)	
					form.submit()
					return false
				}.bind(this)
			}
		}).inject(form)
		
		this.tooltip = new PhiTooltip(this, {
			position: 'top',
			margin: 0,
			rollover: false,
			html: form,
			width: 400,
			height: 80,
			classname: 'file_tooltip'
		})
		
		/* Hide tooltip when clicked outside */
		this.hide = function(event) {
			
			if ( $chk(event) ) 
				event.target = $(event.target)
			
			if ( event.target.get('class') != 'file_tooltip' && !event.target.getParent('.file_tooltip') ) {
				this.tooltip.hide()
			}
		}.bind(this)
		$(document.body).addEvent('mousedown', this.hide)
	},

	'.phi_editable_image:mouseup': function()
	{
		if ( this.get('name') ) {
			this.tooltip._show()
		}
	},
	
	
	/* in-place section layout */
	'.phi_container_header a:click': function(event) {
		
		event.stop()
		this.setStyle('display','none')
		
		this.container						= this.getParent('.phi_container')
		this.container_body					= this.container.getElement('.phi_container_body')
		
		new Request.HTML({
			url: this.href,
			evalScripts: false,
			onComplete: function(tree,elements,html,javascript) {
				
				this.container_body.setStyle('display', 'none')

				this.layout_editor = new Element('div', {
					html: html
				}).inject(this.container_body, 'after')
				
				$exec(javascript)
				
				/* Set restore behavior for cancel button */
				if ( cancel_button = this.layout_editor.getElement('input[name=cancel]') ) {

					cancel_button.onclick = function() {
						this.container_body.setStyle('display', '')
						this.layout_editor.destroy()
						this.setStyle('display','')
						return false
					}.bind(this)
				}
			}.bind(this)
		}).send()
	}
}



/* Each instance behavior */
Builder.instanceRules = {

	/* Hover class */
	'.phi_instance:mouseover': function() {
		this.addClass('hover')
	},

	'.phi_instance:mouseout': function() {
		this.removeClass('hover')
	},		

	/* All core links */
	'.phi_instance_bar li.phi_core a:click': function(event)
	{
		event.stop()
		
		if ( $('phi_builder_shelf') ) {
			Builder.Tooltip.open(this.getParent('.phi_instance'), this.href, this.href.match('instance/style'))
		} else {
			if ( !$chk(this.tooltip) ) {
				new Request({
					url: this.href,
					onComplete: function(response) {
						coords = this.getParent('.phi_instance').getCoordinates()
						this.tooltip = new PhiTooltip(this, {
							classname: 'lightboxed',
							html: response,
							rollover: false,
							width: 500,
							height: 150,
							y: coords.top,
							x: coords.left+coords.width/2
						})

						this.tooltip.show()
						this.addEvent('blur', this.tooltip.hide.bind(this.tooltip))

					}.bind(this)
				}).send()
				
			} else {
				this.tooltip.show()
			}
			
			this.getParent('.phi_instance').getElement('.phi_instance_content').visualFocus()
		}
	},
	
	/* Enable button */
	'.phi_instance_bar ul .enable a': function() {
		this.removeEvents('click')
	},

	'.phi_instance_bar ul .enable a:click': function(event)
	{
		event.stop()

		var instance = this.getParent('.phi_instance')
		var link	 = this
		
		new Request({
			url: this.href,
			
			onComplete: function(response) {
				
				if ( instance.hasClass('enabled') ) {

					instance.addClass('disabled')
					instance.removeClass('enabled')
					
					link.set('html', Language.get('enable'))
					link.set('title', Language.get('enable'))
					link.href = link.href.replace('set=0','set=1')
				
				} else {

					instance.addClass('enabled')
					instance.removeClass('disabled')
					
					link.set('html', Language.get('disable'))
					link.set('title', Language.get('disable'))
					link.href = link.href.replace('set=1','set=0')
				
				}
				
			}
			
		}).send()
		
		if ( whats_this_link = instance.getElement('.disabled_warning a') ) {
			whats_this_link.blur()
		}	
	},
	
	/* Delete button */
	'.phi_instance_bar ul .delete a': function() {
		this.removeEvents('click')
	},

	'.phi_instance_bar ul .delete a:click': function(event)
	{
		event.stop()
		
		if ( !confirm(Language.get('delete this instance')+' ?') ) {
			return
		}
		
		var instance = this.getParent('.phi_instance')

		new Request({
			url: this.href,
			onComplete: function(response)
			{
				var fade	= new Fx.Tween(instance, {
					duration: 400,
					property: 'opacity'
				})
				
				var scale	= new Fx.Tween(instance, {
					duration: 500,
					transition: Fx.Transitions.Bounce.easeOut,
					property: 'height',
					onComplete: function() {
						instance.destroy()
					}
				})

				fade.start(0).chain( scale.start.pass([16], scale) )
			}
		}).send()	
	},
	
	/* Turn instance menu into drop-down widget thingy  */

	'.phi_instance_bar_menu': function()
	{
		if ( $chk(this.options_widget) ) {
			return
		}
		var parent = this.getParent('.phi_instance_bar')
	        var tools = new Element('div', {'class' : 'phi_instance_tools'})
	        var marker = new Element('div', {'class' : 'phi_instance_marker'})
	        var xpander = new Element('div', {'class' : 'phi_widget_options_expander closed'})


		this.marker = marker
		this.options_widget = tools

		xpander.addEvent('mousedown', function(){
		    if(this.hasClass('closed')){
			this.getPrevious('ul.phi_instance_bar_menu').setStyle('display', 'block');
			this.removeClass('closed')
			this.addClass('open')
		    }else{
			this.getPrevious('ul.phi_instance_bar_menu').setStyle('display', 'none');
			this.removeClass('open')
			this.addClass('closed')
		    }
		})

		marker.addEvent('mousedown', function(){
		    if(xpander.hasClass('closed')){
			marker.getPrevious('ul.phi_instance_bar_menu').setStyle('display', 'block');
			xpander.removeClass('closed')
			xpander.addClass('open')
		    }else{
			marker.getPrevious('ul.phi_instance_bar_menu').setStyle('display', 'none');
			xpander.removeClass('open')
			xpander.addClass('closed')
		    }
		}.bind(this))



		    var title = new Element('span', {'class': 'phi_instance_title', 'html': parent.getFirst('h3').get('html'),  'styles' : {'text-align': 'center'}})
		    title.set('tween',{duration: 'short'})
		    title.inject(marker)


		    var options = new Element('span', {'class' : 'phi_instance_options_title', 'html' : Language.get('options').capitalize(), 'styles' : {'opacity' : 0, 'text-align': 'center'}})
		    options.set('tween',{duration: 'short'})
		    options.inject(marker)


		    parent.getFirst('h3').destroy();

		    this.setStyles({'display':'none', 'position' : 'absolute', 'z-index' : 1000}).inject(tools)
		    this.addClass('phi_widget_options_menu')

		   marker.inject(tools)
		   xpander.inject(tools)
		   tools.inject(parent)
		   
		   
		   /*make the width adjust to the space available*/
		   if(parent.getCoordinates().width > tools.getCoordinates().width){
		       marker.setStyle('width', title.getCoordinates().width)
		   }
		   else{
		       marker.set('delta', title.getStyle('width'))
		       marker.setStyle('width', parent.getCoordinates().width - (xpander.getCoordinates().width+10)) //borders and padding added
		   }


		   title.setStyle('margin-bottom', -1*(title.getStyle('height').toInt()+title.getStyle('padding').toInt()*2))

		    var dimensions = tools.getCoordinates();
		   // console.log(dimensions)
		    tools.getFirst('.phi_instance_bar_menu').setPosition({x : 12 , y : 22})


		    tools.addEvent('mouseover', function(element){
			this.getElement('.phi_instance_marker .phi_instance_title').tween('opacity', 0)
			this.getElement('.phi_instance_marker .phi_instance_options_title').tween('opacity', 1)
		    })

		    tools.addEvent('mouseout', function(element){
			this.getElement('.phi_instance_marker .phi_instance_title').tween('opacity', 1)
			this.getElement('.phi_instance_marker .phi_instance_options_title').tween('opacity', 0)
		    })


		    var extras = new Element('div', {'class': 'phi_widget_options_extra_div'})
		    

		   if(parent.getSize().x > tools.getSize().x+63){
			extras.addClass('inside')
			extras.inject(parent, 'bottom')
		    }else{
			extras.addClass('outside')
			extras.setStyles({
			    'position' : 'absolute',
			    'top' : -17,
			    'left' : parent.getParent().getCoordinates().width - 59
			    //'margin-left' : parent.getParent().getCoordinates().width - 59
			})

			extras.inject(parent.getParent().getParent().getParent(), 'top')
			//extras.inject(parent, 'bottom')
		    }

		    var ul = new Element('ul', {
			'class': 'phi_widget_options_extra'
		    }).inject(extras)
		    extras.list = ul
		    this.extras = extras

	    },

	'.phi_instance_tools a.prim:click': function(event)
	{
		var menu = this.getParent('.phi_instance_bar')
		var xpander = menu.getElement('.phi_widget_options_expander')
		var marker = menu.getElement('.phi_instance_marker')

	        if(xpander.hasClass('closed')){
		    marker.getPrevious('ul.phi_instance_bar_menu').setStyle('display', 'block');
		    xpander.removeClass('closed')
		    xpander.addClass('open')
		 }else{
		    marker.getPrevious('ul.phi_instance_bar_menu').setStyle('display', 'none');
		    xpander.removeClass('open')
		    xpander.addClass('closed')
		 }
		
		/*var menu = this.getParent('.phi_instance_bar_menu')
		
		if ( !$chk(menu) )
			return;
		
		menu.setStyle('display','none')
		
		var holder 	= menu.getPrevious('.phi_widget_options')
		if ( first = holder.face.getFirst('a'))
			first.destroy()
		
		var parent = this.getParent('.phi_instance_bar')
		if (parent && parent.getSize().x >= 150 )
			this.clone().cloneEvents(this).inject(holder.face,'top')
        
		var instance_id = this.getParent('.phi_instance').id
		Cookie.write('widget_'+instance_id, this.id)
	    */
	},

	'.phi_instance_bar_menu li.delete': function() {
		var parent = this.getParent('ul')
		if ( $chk(parent.extras) ) {
			this.inject(parent.extras.list,'top')
		}
	},
	
	'.phi_instance_bar_menu li.enable': function() {
		var parent = this.getParent('ul')
		if ( $chk(parent.extras) ) {
			this.inject(parent.extras.list,'top')
		}
	},
	
	/* In-place instance actions */
	'.phi_instance_bar a.inplace:click': function(event)
	{
		event.stop();
		var instance_id = this.getParent('.phi_instance').id.replace('phi_instance_','');
		Builder.Instance.browseTo(instance_id, this.href);
	},
	
	/* Lightboxed elements */
	'a.lightboxed:click': function(event)
	{
		event.stop()
		
		instance = this.getParent('.phi_instance')
		instance.visualFocus()
		
		if ( !$chk(this.tooltip) ) {
			new Request({
				url: this.href,
				onComplete: function(response) {
					coords = instance.getCoordinates()
					this.tooltip = new PhiTooltip(this, {
						classname: 'inserter_tooltip',
						html: '<div class="body">'+response+'</div>',
						rollover: false,
						width: 500,
						height: 150,
						y: coords.top,
						x: coords.left+coords.width/2
					})

					this.tooltip.show()
					this.addEvent('blur', function() {
						this.tooltip.hide()
						instance.visualBlur()
					})

				}.bind(this)
			}).send()
			
		} else {
			this.tooltip.show()
		}
	},
	
	'.disabled_warning a:click': function(event)
	{
		event.stop()
		instance = this.getParent('.phi_instance')
		instance.visualFocus()
		
		tooltip_target = instance.getElement('li.enable')
		show_check = true
		
		if ( !tooltip_target ) {
			tooltip_target = instance
			show_check = false
		}
		
		if ( !$chk(this.tooltip) ) {
			new Request({
				url: this.href+(show_check?'&showcheck=1':''),
				onComplete: function(response) {
					coords = tooltip_target.getCoordinates()
					this.tooltip = new PhiTooltip(tooltip_target, {
						classname: 'inserter_tooltip',
						html: '<div class="body">'+response+'</div>',
						rollover: false,
						width: 300,
						height: 150,
						y: coords.top,
						x: coords.left+coords.width/2
					})

					this.tooltip.show()
					this.addEvent('blur', function() {
						this.tooltip.hide()
						instance.visualBlur()
					}.bind(this))

				}.bind(this)
			}).send()
			
		} else {
			this.tooltip.show()
		}		
	}
}

window.addEvent('domready', function() {
	
	if ( $('phi_builder') ) {
		Builder.show()
		Builder.Drag.refresh()
		
		window.addEvent('keydown', function(event) {
			if ( event.key == 'esc' ) {
				Builder.toggle()
			}
		})
	}
	
	$(document.body).behave(Builder.topRules)
	$(document.body).behave(Builder.instanceRules)
})