//******** Configuration variables ********//
var inactiveOpacity = .5
var minModuleHeight = 170
var toolboxHeight = 143

//******** Variables ********//
// When clicking "add a module" at the top of the page, we want to disable module editing.
// This variable tracks the edit state of the modules.
var disableModuleEdit = false
// In order to prevent double click trouble we increment this counter before starting
// an animation and decrement it after it is done. This way, we ignore mouse clicks
// until busyCount is once again 0.
var busyCount = 0

//******** Setup ********//
// Observe the window for the load event to do some set up
Event.observe(window,'load',function(){setup()})

// Do some setup stuff
function setup() {
	makeInactive()
	addBalloons()
}

//******** Functions ********//
// This function will change the opacity to inactiveOpacity for an element passed to it
// or it will look for all elements classed with inactive
function makeInactive(id) {
	if (id) {
		Element.setOpacity(id,inactiveOpacity)
	} else {
		var inactive = document.getElementsByClassName('inactive')
		for (i=0;i<inactive.length;i++) {
			Element.setOpacity(inactive[i],inactiveOpacity)
		}
	}
}

// This will increase the opacity to 100% for any element passed to it
function makeActive(id) {
	Element.setOpacity(id,1)
}

// If a module is too short to display the toolbox, we need to add a balloon that can
// be "blown up" to increase the module height so the toolbox will fit.
function addBalloons() {
	var modules = document.getElementsByClassName('Module')
	for (i=0;i<modules.length;i++) {
		var moduleHeight = Element.getHeight(modules[i])
		// Insert the balloon that we'll blow up to make the module taller
		new Insertion.Bottom(modules[i],'<div class="Balloon" style="display:none;height:'+(minModuleHeight-moduleHeight)+'px"></div>')
	}
}

// When the mouse rolls over and out of a module, we highlight the module
// and show the toolbar
function toggleToolbar(edit,evt) {
	// Get the elements we'll need
	var module = Element.childrenWithClassName(edit,'Module',true)
	var toolbar = Element.childrenWithClassName(edit,'Toolbar',true)
	var toolbox = Element.childrenWithClassName(toolbar,'Toolbox',true)
	// Check to see if module editing is disabled
	if (!disableModuleEdit) {
		// Mouseover
		if (evt.type == 'mouseover') {
			// Each Edit wrapper gets stacked according to source order
			// In order for the toolbox to overlay other Edit blocks, we need
			// to pop it to the top
			Element.setStyle(edit,{zIndex:1000})
			// Give the module the class ModuleHover
			Element.addClassName(module,'ModuleHover')
			// Show the toolbar
			Element.show(toolbar)
			// Set up the toolbar widths
			setupToolbar(toolbar)
		// Mouseout
		} else {
			// If the toolbox is still visible, we need to hide it
			if (Element.visible(toolbox)) {
				toggleToolbox(toolbar,true)
			}
			// Hide the toolbar
			Element.hide(toolbar)
			// Ditch the ModuleHover class
			Element.removeClassName(module,'ModuleHover')
			// Put it back to the bottom
			Element.setStyle(edit,{zIndex:1})
		}
	}
}

/*
function setupToolbar(toolbar) move to startpage_edit_mode.js and sitemaster_edit_mode.js


// This will set the width of the toolbar and subelements based on the width
// of the module it contains
function setupToolbar(toolbar) {
	// Get the elements we'll need
	var column = toolbar.parentNode.parentNode
	var edit = Element.childrenWithClassName(toolbar.parentNode,'Module',true)
	var toolbarTitle = Element.childrenWithClassName(toolbar,'ToolbarTitle',true)
	var toolbarButton = Element.childrenWithClassName(toolbar,'ToolbarButton',true)
	// Get some widths for our calculations
	var toolbarWidth = (Element.getDimensions(edit).width > Element.getDimensions(column).width ? Element.getDimensions(column).width-20 : Element.getDimensions(edit).width)-10
	var toolbarButtonWidth = Element.getDimensions(toolbarButton).width
	// Set the widths
	
	//Element.setStyle(toolbar,{width:toolbarWidth+'px'})
	//Element.setStyle(toolbarTitle,{width:toolbarWidth-toolbarButtonWidth-5+'px'})
	
	// Add a title so a tooltip will pop up with the full name of the module if
	// it's too long and ends up partially hidden
	toolbarTitle.title = toolbarTitle.innerHTML
}
*/


// Hide and show the toolbox, based on a click or mouseout
function toggleToolbox(toolbar,quickHide) {
	if (busyCount > 0) { return }
	// Get the elements we'll need
	var edit = toolbar.parentNode
	var module = Element.childrenWithClassName(toolbar.parentNode,'Module',true)
	var balloon = Element.childrenWithClassName(module,'Balloon',true)
	var moduleHeight = Element.getHeight(module)
	var toolbox = Element.childrenWithClassName(toolbar,'Toolbox',true)
	var link = Element.childrenWithClassName(toolbar,'ToolboxLink',true)
	
	// If the module is too short or the balloon is currently visible, show or hide it
	if (moduleHeight < minModuleHeight || Element.visible(balloon)) {
		var useBalloon = true
	}
	
	// On mouseout, you want to quickly hide the toolbox instead of animate it
	if (quickHide) {
		Element.hide(toolbox)
		// If there's a balloon, hide it
 		if (useBalloon) {
 			Element.hide(balloon)
 		}
		// The link swaps back and forth between "edit" and "close"
		Element.update(link,'EDIT')
		// If there is a selectBlocker, kill it
		toggleSelectBlocker(toolbox)
	// If the toolbox is visible, that means we need to hide it
	} else if (Element.visible(toolbox)) {
		// Roll up the toolbox
		busyCount++
		Effect.BlindUp(toolbox,{duration:.5,queue:'end',afterFinish:function(){toggleSelectBlocker(toolbox);busyCount--}})
		// If there is a balloon, roll it up next
 		if (useBalloon) {
 			busyCount++
 			Effect.BlindUp(balloon,{duration:.5,queue:'end',afterFinish:function(){busyCount--}})
 		}
		// Change the link back to "edit"
		Element.update(link,'EDIT')
		// We need to set up the toolbar again because the the changing width of the link
		setupToolbar(toolbar)
	// The toolbox is not visible, so let's show it
	} else {
		// Create the stupid IE select blocker. It's there for all browsers, but other browsers hide it
		toggleSelectBlocker(toolbox)
		// Swap the button back to "close"
		Element.update(link,'CLOSE')
		// We need to set up the tool bar widths
		setupToolbar(toolbar)
		// If the module is too short to display the contents of the toolbox
 		if (useBalloon) {
 			// Blow up the balloon and show the toolbox
  			busyCount++
  			Effect.BlindDown(balloon,{duration:.5,queue:'end',afterFinish:function(){showToolbox(toolbox);busyCount--}})
 		} else {
			// Show the toolbox
			showToolbox(toolbox)
		}
	}
}

// Workaround for IE's handling of the animation of the balloon. We need to show the toolbox only after the
// balloon has expanded, IE is stupid.
function showToolbox(toolbox) {
	// Roll down the toolbox
	busyCount++
	Effect.BlindDown(toolbox,{duration:.5,queue:'end',afterFinish:function(){busyCount--}})
	scrollToFitToolbox(toolbox)
}

// If the toolbox is partially off the screen, we need to scroll down to show it. What is the offset
// all about? Script.aculo.us provides a ScrollTo method to scroll to the position of an element passed
// to it. We don't want to scroll that far. We want the window to scroll down only as much as the toolbox
// is being hidden off the bottom of the viewport. The offset is the vertical offset from the position
// of the element being passed to the ScrollTo method. It takes a bit of calculation to determine the offset.
function scrollToFitToolbox(toolbox) {
	// Get the elements we'll need
	var toolbar = toolbox.parentNode.parentNode
	var viewportHeight = (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight)
	var scrollTop = (document.documentElement.scrollTop || document.body.scrollTop)
	var topOfModule = Position.cumulativeOffset(toolbar)[1]
	// Caculations
	var bottomOfViewport = scrollTop+viewportHeight
	var bottomOfToolbox = topOfModule+toolboxHeight
	var amountBelowViewport = bottomOfToolbox-bottomOfViewport
	// Set the offset
	var offset = ((amountBelowViewport > 0) ? -(topOfModule-scrollTop-amountBelowViewport-10) : false)
	if (offset) {
		busyCount++
		new Effect.ScrollTo(toolbox,{offset:offset,duration:1,queue:'end',afterFinish:function(){busyCount--}})
	}
}

// In IE, <select> elements will overlay on top of all other elements except an <iframe>
// So we dynamically create and destroy an iframe to work around this
function toggleSelectBlocker(toolbox) {
	if ($('selectBlocker')) {
		Element.remove('selectBlocker')
	} else {
		// Get the parent module
		var edit = toolbox.parentNode.parentNode.parentNode
		// Get all the <select>s within the module
		var selects = edit.getElementsByTagName('select')
		// If there are selects, we should use the select blocker
		if (selects.length != 0) {
			new Insertion.Before(toolbox,'<iframe id="selectBlocker" frameborder="0" scrolling="no" marginwidth="0" marginheight="0" src="/jonyxx/shared/images/edit_mode/selectBlocker.html"></iframe>')
		}
	}
}

// When clicking the 'add a module' button in the main toolbar, we need to
// disable editing of individual modules and show the add module buttons.
// Or we need to hide the buttons and re-enable module editing
function toggleAddModuleButtons() {
	// Loop through all the columns on the page
	var columns = document.getElementsByClassName('column')
	for (i=0;i<columns.length;i++) {
		// If you can add a module to this column, get the button
		var addButton = Element.childrenWithClassName(columns[i],'addModule',true)
		if (addButton != "") {
			// If the button is visible, we need to hide it
			if (Element.visible(addButton)) {
				// Hide the button
				busyCount++
				Effect.BlindUp(addButton,{duration:.3,queue:'end',afterFinish:function(){busyCount--}})
				// Change the main toolbar button text back
				$('addModuleText').value = 'ADD A MODULE'
				// Allow module editing again
				disableModuleEdit = false
			} else {
				// Get the width of the column
				var colWidth = Element.getDimensions(columns[i]).width
				// Make the button the width of the column and center it
				Element.setStyle(addButton,{width:colWidth+"px"})
				Element.setStyle(addButton,{marginLeft:(0-(colWidth/2))+"px"})
				// Disallow module editing while adding a module to a column
				disableModuleEdit = true
				// Change the main toolbar button text
				$('addModuleText').value = 'CANCEL (DON\'T ADD A MODULE)'
				// Show the button
				busyCount++
				Effect.BlindDown(addButton,{duration:.3,queue:'end',afterFinish:function(){busyCount--}})
			}
		}
	}
	// For IE, we need to loop through all the inactive items and reset the opacity
	// Stupid IE
	makeInactive()
}

// Drop down the list of available modules to add
function toggleAddModuleList(id) {
	var list = Element.childrenWithClassName(id,'addModuleList',true)
	busyCount++
	Effect.toggle(list,'blind',{duration:.7,queue:'end',afterFinish:function(){busyCount--}})
}



//******** Mouse Events ********//
// Mouse over and out wizardry
function checkMouseEnter(element,evt) {
	if (element.contains && evt.fromElement) {
		return !element.contains(evt.fromElement)
	} else if (evt.relatedTarget) {
		return !containsDOM(element,evt.relatedTarget)
	}
}

function checkMouseLeave(element,evt) {
	if (element.contains && evt.toElement) {
		return !element.contains(evt.toElement)
	} else if (evt.relatedTarget) {
		return !containsDOM(element,evt.relatedTarget)
	}
}

function containsDOM(container,containee) {
	var isParent = false;
	do {
		if ((isParent = container == containee)) { break }
		containee = containee.parentNode
	} while (containee != null)
	return isParent
}