/***********************************************
 ***** GENERAL CONTROL PANEL FUNCTIONALITY ***** 
 **********************************************/

/*
* Set links with rel="external" to pop to a new window (mainly used for the documentation)
*/
function focusOnMainForm() {
    if ($$('input.autofocus')[0] !== undefined) {
		$$('input.autofocus')[0].focus();
	}
}

document.observe('dom:loaded', focusOnMainForm);

/*
 * Set links with rel="external" to pop to a new window (mainly used for the documentation)
*/
function setExternalLink() {
	$$('a[rel="external"]').each(function(elm) {
		elm.setAttribute('target', '_blank');
	});
	$$('a[title="external"]').each(function(elm) {
		elm.setAttribute('target', '_blank');
	});
}

document.observe('dom:loaded', setExternalLink);

/*
 * Set control panel menus hide/disclose state (also sets cookie)
 */
function setMenuToggles() {
	$$('.cp-group').each(function(elm) {
		elm.firstDescendant().observe('click', function(event) {
			event.stop();
			toggleMenu(elm.firstDescendant());
		});
		if(elm.firstDescendant().hasClassName('cp-head-hide')) {
			elm.firstDescendant().next().hide();
		}
	});
}

function toggleMenu(elm) {
	elm.next().toggle();
	if(elm.hasClassName('cp-head-show')) {
		new Ajax.Request(elm.href, {parameters: 'section=' + elm.up().id + '&status=hide'});
		elm.removeClassName('cp-head-show');
		elm.addClassName('cp-head-hide');
	} else {
		new Ajax.Request(elm.href, {parameters: 'section=' + elm.up().id + '&status=show'});
		elm.removeClassName('cp-head-hide');
		elm.addClassName('cp-head-show');
	}
}

document.observe('dom:loaded', setMenuToggles);

/*
 * Functions for building setting and removing form hints
 */
function setFormHints() {
	// loop through all form input elements where class="form-hint"
	$$('input.form-hint').each(function(elm) {
		// watch for any focus events on the form input
		elm.observe('focus', function() {
			removeFormHint(elm);
		});
		// watch for any blur events on the form input
		elm.observe('blur', function() {
			displayFormHint(elm);
		});
		// watch for any blur events on the form input
		elm.up('form').observe('submit', function() {
			if(elm.value == elm.title) {
				elm.value = '';
			}
		});
		displayFormHint(elm);
	});
}
function removeFormHint(elm) {
	// quick check to see if we are setting the form from a datepicker object (if so, our elm value is an object).
	if(typeof elm == 'object') {
		elm = $(elm.id);
	}
	// if the value of the field is equal to the title, then we need to clear it and set the styling.
	if(elm.value == elm.title) {
		elm.value = "";
		elm.style.color = "#000";
		elm.style.fontStyle = "normal";
	}
}
function displayFormHint(elm) {
	// if the value of the filed is empty then set it to the form hint (the title).
	if(elm.value == "") {
		elm.value = elm.title;
		elm.style.color = "#999";
		elm.style.fontStyle = "italic";
	} else if (elm.value == elm.title) {
		elm.style.color = "#999";
		elm.style.fontStyle = "italic";
	}
}

// when the dom has loaded, apply all form hint observers
document.observe('dom:loaded', setFormHints);

/*
 * Set functionality to auto close/manually close flash messages
 * Good flash messages should auto close after a few seconds, bad flash messages should remain until dismissed
 */

// check for any flash message, if good, then setTimeout to auto-dismiss. If bad, then disregard.
function watchFlashMessage() {
	if($('flash_msg')) {
		if(!($('flash_msg').hasClassName('bad'))) {
			setTimeout('dismissFlashMessage()', 3000);
		}
	}
}

// dismisses the actual flash message
function dismissFlashMessage() {
	new Effect.SlideUp('flash_msg', {duration: 0.3});
}

document.observe('dom:loaded', watchFlashMessage);


/*
 * Handles the front-end admin bars Jump to Page menu functionality
 */
function jumpToPage() {
	if($('PageSelect')) {
		$('PageSelect').observe('change', function(event) {
			$('PageViewForm').action = $F('PageSelect');
			$('PageViewForm').submit();
		});	
	}
}

document.observe('dom:loaded', jumpToPage);

/*
 * Handles the front-end admin bars Jump to Site menu functionality
 */
function jumpToSite() {
	if($('SiteSelect')) {
		$('SiteSelect').observe('change', function(event) {
			if($('SiteViewForm')) {
				$('SiteViewForm').action = $F('SiteSelect');
				$('SiteViewForm').submit();
			}
		});
	}
	if($('SwitchSite')) {
		$('SwitchSite').observe('change', function(event) {
			if($('SwitchSite')) {
				$('SwitchSite').action = $('SwitchSite').action+'/site:'+$F('SwitchSiteSite');
				$('SwitchSite').submit();
			}
		});
	}
}

document.observe('dom:loaded', jumpToSite);

/*
 * Handles the grow/shrinking markdown editor functionality
 */
function setMarkdownHeight() {
	$$('.wmd-height-toggle').each(function(elm) {
		elm.observe('click', function(e) {
			e.stop();
			var parent = elm.up();
			if(parent.hasClassName('wmd-short')) {
				parent.removeClassName('wmd-short');
				parent.addClassName('wmd-tall');
			} else {
				parent.removeClassName('wmd-tall');
				parent.addClassName('wmd-short');
			}
		});
	});
}

document.observe('dom:loaded', setMarkdownHeight);


/***********************************************
 ****** CONTROL PANEL PAGES & NAVIGATION ******* 
 **********************************************/

/*
 * Used on the List Pages & Navigation index page to set alternating row colors after
 * sorting rows into different orders.
 */ 
function setRowColor() {
	var i=0;
	// match any divs with some part of the class name as rp-level-wrap l-1
	// this also gets all divs with rp-level-wrap l-1 white
	$$('div.l-1').each(function(elm) {
		if(i++ % 2 == 0) {
			// if we are mod 0 then this should be white, check and change if necessary.
			if(!elm.hasClassName('white')) {
				elm.addClassName('white')
			}
		} else {
			// if we are NOT mod 0 then this should NOT be white, check and change if necessary.
			if(elm.hasClassName('white')) {
				elm.removeClassName('white');
			}
		}
	});
}

/*
 * Set control panel Manage Pages & Nav index page collapse/disclose state for all page levels
 */
function setPageToggles() {
	$$('.rp-level').each(function(elm) {
		if(elm.firstDescendant().firstDescendant()) {
			elm.firstDescendant().firstDescendant().observe('click', function(event) {
				event.stop();
				toggleListSection(elm.firstDescendant(), elm.firstDescendant().firstDescendant().href);
			});
			if(elm.firstDescendant().hasClassName('r')) {
				elm.next('div').hide();
			}
		}
	});
}

function toggleListSection(elm, action) {
	// find the page ID from the element ID
	var underscore = elm.id.lastIndexOf('_');
	var id = elm.id.substring(underscore + 1);
	if(elm.hasClassName('d')) {
		new Ajax.Request(action, {parameters: 'section=' + id + '&status=hide'});
		elm.up().next('div').hide();
		elm.removeClassName('d');
		elm.addClassName('r');
	} else {
		// status of d == show
		new Ajax.Request(action, {parameters: 'section=' + id + '&status=show'});
		elm.up().next('div').show();
		elm.removeClassName('r');
		elm.addClassName('d');
	}
}

document.observe('dom:loaded', setPageToggles);

/*
 * Allows toggling of additional "meta" page information on the new/edit Page pages and the widget pages
 */
function disclosePageInfo() {
	$$('div.section a').each(function(elm) {
		elm.observe('click', function(event) {
			event.stop();
			if(elm.hasClassName('disclose')) {
				elm.removeClassName('disclose');
				$('page_info').blindUp({duration:0.3});
			} else {
				elm.addClassName('disclose');
				$('page_info').blindDown({duration:0.3});
				 // Had to add this to fix the markdown editor error when the textbox is hidden on page load.
				if($('wmd-input')) {
					$('wmd-input').show();
				}
			}
		});
		// set off by default when page loads
		elm.removeClassName('disclose');
		$('page_info').hide();
	});
}

document.observe('dom:loaded', disclosePageInfo);

/*
 * Allows toggling of "Parent Page" section on the edit Page page
 */
function discloseParentPath() {
	if($('path_picker_toggle')) {
		$('path_picker_toggle').observe('click', function(event) {
			event.stop();
			// hide the toggle button
			$('path_picker_toggle').hide();
			// now blind in the content
			new Effect.toggle('path_picker', 'appear', {duration:1.0});
			$('hierarchy').toggleClassName('active');
		});
		// set off by default when page loads
		$('path_picker_toggle').next().hide();
	}
}

document.observe('dom:loaded', discloseParentPath);

/*
 * Functionality for selecting a parent path
 */
path = new Array();
function parentPathFromHome() {
	if($('parent_path_home')) {
		$('parent_path_home').observe('click', function(event) {
			event.stop();
			// clear and hide all boxes past the current home selection
			$$('#path_picker .level-box').invoke('update');
			$$('#path_picker .level-box').invoke('hide');
			$$('#path_picker .level-arrow').invoke('hide');
			new Ajax.Updater($('parent_path_home').next(2), $('parent_path_home').href, {parameters: 'page=' + $F('PageId') + '&parent=', onComplete: function() {
				parentPathSub();
				$('parent_path_home').next(1).appear({duration:0.2});
				$('parent_path_home').next(2).appear({duration:0.2});
			}});
			$('parent_path_home').addClassName('parent_page_selected');
			path.clear();
			path.push("Home");
			
			// find the page ID from the element HREF
			var slash = $('parent_path_home').href.lastIndexOf('/');
			var parent = $('parent_path_home').href.substring(slash + 1);
			$('PageParentId').value = parent;
			
			// update the breadcrumb trail & hidden field
			$('hierarchy').update('Selected Page Hierarchy: &nbsp;' + 'Home');
		});
		
		// Set all level boxes to hidden...
		$$('#path_picker .arrow-down').invoke('hide');
		$$('#path_picker .level-box').invoke('hide');
		$$('#path_picker .level-arrow').invoke('hide');
	}
}

function parentPathSub() {
	$$('#path_picker .level-list li a').each(function(elm) {
		// stop observing since we call this function every time we add a level
		elm.stopObserving();
		// add new observer...
		elm.observe('click', function(event) {
			event.stop();
			// find current container & remove any previous content / styling
			var underscore = elm.up(2).id.lastIndexOf('_');
			var container = elm.up(2).id.substring(underscore + 1);
			var num_levels = $$('.level-box').length;
			// clear & hide boxes past the current box
			for(i=parseInt(container)+1;i<=num_levels;i++) {
				$('path_level_' + i).hide();
				$('path_level_' + i).previous().hide();
				$('path_level_' + i).update();
				path[parseInt(i)-1] = null;
			}
			path = path.compact();
			
			// remove styling if we clicked an item in a box we had previously selected
			$$('#path_picker #path_level_'+container+' a').invoke('removeClassName', 'parent_page_selected').invoke('removeClassName', 'parent_page_ancestor')
			
			// find the page ID from the element HREF
			var slash = elm.href.lastIndexOf('/');
			var parent = elm.href.substring(slash + 1);
			// get the next box's pages
			new Ajax.Updater(elm.up(2).next(1), elm.href, {parameters: 'page=' + $F('PageId') + '&parent=' + parent, onComplete: function() {
				parentPathSub();
				elm.up(2).next().appear({duration:0.2});
				elm.up(2).next(1).appear({duration:0.2});
			}});
			$$('#path_picker .parent_page_selected').each(function(item) {
				// set the previous class names accordingly
				item.removeClassName('parent_page_selected');
				item.addClassName('parent_page_ancestor');
			});
			// show the clicked page as selected & set the hidden field
			$('PageParentId').value = parent;
			elm.addClassName('parent_page_selected');
			path.push(elm.innerHTML);
			
			// update the breadcrumb trail & hidden field
			$('hierarchy').update('Selected Page Hierarchy: &nbsp;' + path.join(' &gt; '));
		});
	});
}

document.observe('dom:loaded', parentPathFromHome);

/*
 * Functionality for toggling the external or internal url for a page
 */
function toggleURL(elm) {
	if(elm.value == 1) {
		$('pretty_url').hide();
		$('pretty_url_options').hide();
		$('url').show();
		if($('pretty_error')) {
			$('pretty_error').hide();
		}
		if($('url_error')) {
			$('url_error').show();
		}
	} else {
		$('pretty_url').show();
		$('pretty_url_options').show();
		$('url').hide();
		if($('pretty_error')) {
			$('pretty_error').show();
		}
		if($('url_error')) {
			$('url_error').hide();
		}
	}
}

/*
 * Functionality for suggesting the pretty url based off page name
 */
path = new Array();
function suggestPrettyURL() {
	// does $('PageName') element exist && does it have a class of suggest (add page)
	if($('PageName') && $('PagePrettyUrl') && $('PageName').hasClassName('suggest')) {
		$('PageName').observe('keyup', function() {
			var text = $F('PageName');
			text = text.replace(/\s/g, '-');
			text = text.replace(/[^a-zA-Z0-9\_\-]/g, '');
			$('PagePrettyUrl').value = text.toLowerCase();
		});
	}
}

document.observe('dom:loaded', suggestPrettyURL);

/*
 * Hides or reveals widgets extra option from pages list if exists
 */
function showOption(elm) {
	if(elm.value == '-1') {
		$('read_more_external').show();
	} else if(elm.value != '-1') {
		$('read_more_external').hide();
		$('read_more_link').value = '';
	}
}

/*
 * Functionality for remapping widgets to new content areas when the page template changes
 */
function changeTemplate() {
	if($('PageTemplateId')) {
		$('PageTemplateId').observe('change', function(event) {
			// determine if the user just re-selected the current template (we don't need to make them select the content areas if so)
			if($('PageTemplateId').hasClassName('current_template_'+$F('PageTemplateId'))) {
				// empty the select lists
				$$('#map_content_areas select').each(function(elm) {
					elm.update();
					// apply empty option
					var opt = new Element ('option', {'value':''}).update('Choose Content Area...');
					elm.update(opt);
				});
				if($('map_content_areas').visible()) {
					$('map_content_areas').fade({duration:0.2});
				}
			} else {
				// this is a different template, let's find the applicable content areas
				new Ajax.Request('../../pages/content_areas', {parameters: 'template=' + $F('PageTemplateId'), onSuccess: function(transport) {
			     	var json = transport.responseText.evalJSON();
					$$('#map_content_areas select').each(function(elm) {
						// empty the select lists
						elm.update();
						// apply empty option
						var opt = new Element ('option', {'value':''}).update('Choose Content Area...');
						elm.update(opt);
						// apply options to all select boxes
						for(var i=0;i<json.length;i++) {
							opt = new Element ('option', {'value':json[i].ContentArea.id}).update(json[i].ContentArea.name);
							elm.insert(opt);
						}
					});
					var i = $('PageTemplateId').selectedIndex;
					$('target_template').down().innerHTML = $('PageTemplateId').options[i].text;
					$('map_content_areas').appear({duration:0.2});
				}});
			}
		});
	}
}

document.observe('dom:loaded', changeTemplate);


/***********************************************
 *******  FUNCTIONALITY FOR USERS MODULE ****** 
 **********************************************/
function displaySites() {
	if($('rp_sites') && $('UserLevel')) {
		$('UserLevel').observe('click', function() {
			setSiteDisplayState();
		});
		setSiteDisplayState();
	}
}

function setSiteDisplayState() {
	if($F('UserLevel') == 'super') {
		$('rp_sites').hide();
	} else if($F('UserSiteCount') > 1) {
		$('rp_sites').show();
	}
}

document.observe('dom:loaded', displaySites);

/***********************************************
 **  FUNCTIONALITY FOR IMAGES & FILE MANAGER  ** 
 **********************************************/

function setFileCategoryToggles() {
	$$('.file_category').each(function(elm) {
		elm.firstDescendant().stopObserving();
		elm.firstDescendant().firstDescendant().observe('click', function(event) {
			event.stop();
			// calls toggleListSelection function listed above (near line 110)
			toggleListSection(elm.firstDescendant(), elm.firstDescendant().firstDescendant().href);
		});
		if(elm.firstDescendant().hasClassName('r')) {
			if(elm.next('div').visible()) {
				elm.next('div').hide();
			}
		}
	});
}

document.observe('dom:loaded', setFileCategoryToggles);


// function for closing the generated litebox
function closeLitebox() {
	// close the modal box
	$$('.modal-close').each(function(elm) {
		elm.observe('click', function(event) {
			event.stop();
			$('rp_litebox_bg').fade({duration:0.2});
		});
	});
}

// opens litebox allowing user to select an image to attach to a specific widget.
// includes all the event handlers for the components within the litebox.
function selectFile(elm, id, type) {
	var request_url = elm.href;
	var allowed = null;
	var params = '';
	if(type == 'file') {
		allowed = $F('FilesPagesWidget'+id+'Allowed');
		params = 'allowed=' + $F('FilesPagesWidget'+id+'Allowed');
	}
	new Ajax.Request(request_url, {parameters: params, onSuccess: function(transport) {
		$('rp_modal_functions').update(transport.responseText);
		closeLitebox();
		// if this is an image type
		if(type == 'img') {
			// display the originally selected file if it exists
			if($('selected_file_'+id).up().visible()) {
				$('selected_file').src = $('selected_file_'+id).src;
				$('selected_file').up().show();
				$('selected_file_title').update($('selected_file_title_'+id).innerHTML);
			}
			if($F('FilesPagesWidget'+id+'UseOriginalSize') == 1) {
				$('FilesPagesWidgetUseOriginalSize').checked = true;
			}
			if($('FilesPagesWidget'+id+'Caption')) {
				$('FilesPagesWidgetCaption').value = $F('FilesPagesWidget'+id+'Caption');
			} else {
				$('FilesPagesWidgetCaption').up().hide();
			}
			if($('FilesPagesWidget'+id+'Link')) {
				$('FilesPagesWidgetLink').value = $F('FilesPagesWidget'+id+'Link');
			} else {
				$('FilesPagesWidgetLink').up().hide();
			}
		// if this is a file type
		} else {
			$('selected_file_title').update($('selected_file_title_'+id).innerHTML);
		}
		$('FilesPagesWidgetFileId').value = $F('FilesPagesWidget'+id+'FileId');
		
		// click on the tab to upload a new file
		$('upload_tab_r').observe('click', function(event) {
			Event.stop(event);
			$('upload_tab_l').removeClassName('selected');
			$('upload_tab_r').addClassName('selected');
			$('rp_uploader_scroll').hide();
			// if the preview area exists (won't on files) then hide it. 
			if($('img_preview_area')) {
				$('img_preview_area').hide();
			}
			$('rp_uploader').show();
		});
		// click on the tab to view the list of files
		$('upload_tab_l').observe('click', function(event) {
			Event.stop(event);
			$('upload_tab_r').removeClassName('selected');
			$('upload_tab_l').addClassName('selected');
			$('rp_uploader').hide();
			// if the preview area exists (won't on files) then show it. 
			if($('img_preview_area')) {
				$('img_preview_area').show();
			}
			$('rp_uploader_scroll').show();
		});
		$$('#upload_list a').each(function(elm) {
			observeFileChooserList(elm, type);
		});
		// when we change the category we are viewing in the litebox file list
		$('category_id').observe('change', function(event) {
			if($F('category_id') == '') {
				$$('#upload_list li').invoke('show');
			} else {
				$$('#upload_list li').each(function(elm) {	
					if(!elm.hasClassName('category_'+$F('category_id'))) {
						elm.hide();
					} else {
						elm.show();
					}
				});
			}
		});
		// when the litebox is submitted and selection confirmed
		$('rp_uploader_form').observe('submit', function(event) {
			Event.stop(event);
			// if the type we are submitting is an image
			if(type == 'img') {
				if($('selected_file').up().visible()) {
					// check validations as necessary
					new Ajax.Request($('rp_uploader_form').action, {parameters: $('rp_uploader_form').serialize(), onSuccess: function(transport) {
						var data = transport.responseText.evalJSON(true);
						if(data.response == 'Success') {
							// set the main preview image & show it (if this is new)
							$('selected_file_'+id).src = $('selected_file').src;
							$('selected_file_'+id).up().show();
							// update the title on the main page
							$('selected_file_title_'+id).update($('selected_file_title').innerHTML);
							// modify the title-bar if necessary
							$$('#'+type+'_'+id+' .'+type+'-delete').invoke('show');
							$$('#'+type+'_'+id+' .'+type+'-select').invoke('addClassName', ''+type+'-edit').invoke('removeClassName', ''+type+'-select');

							// populate the form fields for the specific file chooser (with the info being saved)
							// first get the file name from the src (we must remove the path first and thumb_).
							var slash = $('selected_file_'+id).src.lastIndexOf('/');
							var filename = $('selected_file_'+id).src.substring(slash + 7);

							// check the value and manually set it instead of passing the checkbox value; fixes IE checkbox inconsistencies
							if($F('FilesPagesWidgetUseOriginalSize') != '1') {
								$('FilesPagesWidget'+id+'UseOriginalSize').value = 0;
							} else {	
								$('FilesPagesWidget'+id+'UseOriginalSize').value = 1;
							}
							if($('FilesPagesWidget'+id+'Link')) {
								$('FilesPagesWidget'+id+'Link').value = $F('FilesPagesWidgetLink');
							}
							if($('FilesPagesWidget'+id+'Caption')) {
								$('FilesPagesWidget'+id+'Caption').value = $F('FilesPagesWidgetCaption');
							}
							$('FilesPagesWidget'+id+'FileId').value = $F('FilesPagesWidgetFileId');
							
							$('rp_litebox_bg').fade({duration:0.2});
							
						} else {
							var error_div = new Element('div', {'class':'error-message'});
							for(var i in data.reason) {
								error_div.update(data.reason[i]);
								if(i == 'link') {
									$('FilesPagesWidgetLink').insert({'after':error_div});
								} else if(i == 'caption') {
									$('FilesPagesWidgetCaption').insert({'after':error_div});
								} else {
									$('FilesPagesWidgetLink').up.insert({'before':error_div});
								}
							}
						}
					}
					});
				} else {
					$('rp_litebox_bg').fade({duration:0.2});
				}
			// it is a file
			} else {
				// update the title on the main page
				if($('selected_file_title').innerHTML != $('selected_file_title_'+id).innerHTML) {
					$('selected_file_title_'+id).removeClassName('none').update($('selected_file_title').innerHTML);
					// modify the title-bar if necessary
					$$('#'+type+'_'+id+' .'+type+'-delete').invoke('show');
					$$('#'+type+'_'+id+' .'+type+'-select').invoke('addClassName', ''+type+'-edit').invoke('removeClassName', ''+type+'-select');
					
					// populate the form fields for the specific file chooser (with the info being saved)
					$('FilesPagesWidget'+id+'FileId').value = $F('FilesPagesWidgetFileId');
				}
				$('rp_litebox_bg').fade({duration:0.2});
			}
		});
		var swfUploader;
		swfUploader = createSingleUploader(type, allowed);
	}});
}

function validateUpload(elm) {
	new Ajax.Request(rp_base_url+'library/validate_upload', {parameters: $('rp_uploader').serialize(), onSuccess: function(transport) {
		var data = transport.responseText.evalJSON(true);
		if(data.response == "Success") {
			// the alt text and category were valid, upload the file.
			swfUploader.startUpload();
		} else {
			var error_div = new Element('div', {'class':'error-message'});
			for(var i in data.reason) {
				error_div.insert(data.reason[i]);
			}
			$('LibraryAltText').insert({'after':error_div});
			return false;
		}
	}});
}

// removes the selected file from a given widget
function removeSelectedFile(id, type) {
	if(type == 'img') {
		// hide the main preview image
		$('selected_file_'+id).up().hide();
		// update the title on the main page
		$('selected_file_title_'+id).update();
		
		// empty out all the hidden form fields for the specific file chooser
		$('FilesPagesWidget'+id+'UseOriginalSize').value = 0;
		if($('FilesPagesWidget'+id+'Link')) {
			$('FilesPagesWidget'+id+'Link').value = "";
		}
		if($('FilesPagesWidget'+id+'Caption')) {
			$('FilesPagesWidget'+id+'Caption').value = "";
		}
	} else {
		$('selected_file_title_'+id).addClassName('none').update('No File Selected');
	}
	
	// modify the title-bar to show the correct buttons
	$$('#'+type+'_'+id+' .'+type+'-delete').invoke('hide');
	$$('#'+type+'_'+id+' .'+type+'-edit').invoke('addClassName', ''+type+'-select').invoke('removeClassName', ''+type+'-edit');
	
	// empty out all the hidden form fields for file_id
	$('FilesPagesWidget'+id+'FileId').value = "";
}

// event handlers used on the list of files in the file chooser (also called after uploading a new item in the file chooser)
function observeFileChooserList(elm, type) {
	elm.stopObserving();
	if(type == 'img') {
		// show preview when mousing over an item in the file list
		elm.observe('mouseover', function(event) {
			$('preview_img').src = elm.rel;
			$('preview_img').up().show();
		});
		// remove preview when mousing off an item in the file list
		elm.observe('mouseout', function(event) {
			$('preview_img').up().hide();
		});
	}
	
	// when an item in the list is clicked, add it to the "selected file" section w/ preview
	elm.observe('click', function(event) {
		Event.stop(event);
		if(type == 'img') {
			$('selected_file').src = elm.rel;
			$('selected_file').up().show();
			var file_name = createPrettyFileName(elm.title, 20);
		} else {
			var file_name = createPrettyFileName(elm.title, 53);
		}
		
		$('selected_file_title').update(file_name);
		// get the file id (minus the "file_" which is 5 characters)
		$('FilesPagesWidgetFileId').value = elm.id.substring(5);
	});
}

// creates filenames that are truncated around 2/3 of the name with elipses. 
// used for displaying filenames in small/constrained places.
function createPrettyFileName(file_name, len) {
	if((file_name).length > len) {
		var length_no_separator = len - 3;
		var length_left = Math.floor(length_no_separator * .66);
		var length_right = Math.ceil(length_no_separator * .34);
		var str_l = file_name.substring(0, length_left);
		var str_r = file_name.substring((file_name).length-length_right);
		return str_l + '...' + str_r;
	} else {
		return file_name;
	}
}

// displays the addFile litebox used to upload multiple images to the library
function addFiles(elm, type, allowed) {
	var request_url = elm.href;
	new Ajax.Request(request_url, {onSuccess: function(transport) {
		$('rp_modal_functions').update(transport.responseText);
		closeLitebox();
		var swfUploader;
		swfUploader = createUploader(type, allowed);
	}});
}

// function for creating litebox and allowing user to edit category
function editCategory() {
	$$('.rp-edit-cat').each(function(elm) {
		elm.observe('click', function(event) {
			event.stop();
			
			// now create the lightbox, display it and set its handlers
			new Ajax.Request(elm.href, {onSuccess: function(transport) {
				$('rp_modal_functions').update(transport.responseText);
				closeLitebox();
				// perform the update when the user clicks save
				$('rp_category_form').observe('submit', function(event) {
					event.stop();
					new Ajax.Request($('rp_category_form').action, {parameters: $('rp_category_form').serialize(), onSuccess: function(transport) {
						var data = transport.responseText.evalJSON(true);
						if(data.response == "Success") {
							$('rp_litebox_bg').fade({duration:0.3});
							elm.up().previous().down().update($F('category_name'));
							elm.up().next().down().title = $F('category_name');
							elm.title = $F('category_name');
						} else {
							var error_div = new Element('div', {'class':'error-message'});
							for(var i in data.reason) {
								error_div.insert(data.reason[i]);
							}
							$('category_name').insert({'after':error_div});
						}
					}});
				});
			}});
		});
	});
}

// function for creating litebox and allowing user to create new category
function addCategory(elm, type) {
	// now create the lightbox, display it and set its handlers
	new Ajax.Request(elm.href, {parameters: 'type='+type, onSuccess: function(transport) {
		$('rp_modal_functions').update(transport.responseText);
		closeLitebox();
		// perform the update when the user clicks save
		$('rp_category_form').observe('submit', function(event) {
			event.stop();
			new Ajax.Request($('rp_category_form').action, {parameters: $('rp_category_form').serialize(), onSuccess: function(transport) {
				var data = transport.responseText.evalJSON(true);
				if(data.response == "Success") {
					$('rp_litebox_bg').fade({duration:0.3});
					// new we build the dom element to insert with the new category.
					var ul = new Element('ul', {'class':'category file_category'});
					var li_disclose = new Element('li', {'class':'rp-disclosure r', 'id':'file_cat_'+data.id}).update(new Element('a', {'href':'set_list_state'}));
					var li_name = new Element('li', {'class':'cat-name'}).update(new Element('span', {'class':'file-name'}).update($F('category_name'))).insert('(0 files)');
					var li_edit = new Element('li', {'class':'rp-layout'}).update(new Element('a', {'href':'edit_category/'+data.id, 'class':'rp-edit-cat', 'title':$F('category_name')}));
					var li_delete = new Element('li', {'class':'rp-delete'}).update(new Element('a', {'href':'delete_category/'+data.id, 'class':'rp-cat-delete rp-no-files', 'title':$F('category_name')}));
					var img_div = new Element('div');
					if(type == 'images') {
						img_div = new Element('div', {'class':'images', 'style':'display:none;'}).update(new Element('div', {'class':'clear'}));
					}
					
					// stick the new category at the top of the list (right after the search form)
					$('rp_file_srch').insert({'after':ul.update(li_disclose).insert(li_name).insert(li_edit).insert(li_delete)});
					$('rp_file_srch').next('ul').insert({'after':img_div});

					// finally, re-do the coloring of rows and setup the listeners again.
					$$('.file_category').each(function(elm) {
						if(elm.hasClassName('category')) {
							elm.removeClassName('category');
							elm.addClassName('category-white');
							if(type == 'images') {
								elm.next('div').removeClassName('images');
								elm.next('div').addClassName('images-white');
							}
						} else {
							elm.removeClassName('category-white');
							elm.addClassName('category');
							if(type == 'images') {
								elm.next('div').removeClassName('images-white');
								elm.next('div').addClassName('images');
							}
						}
					});

					// setup listeners again
					editCategory();
					confirmDelete();
					setFileCategoryToggles();
				} else {
					var error_div = new Element('div', {'class':'error-message'});
					for(var i in data.reason) {
						error_div.insert(data.reason[i]);
					}
					$('category_name').insert({'after':error_div});
				}
			}});
		});
	}});
}

document.observe('dom:loaded', editCategory);

/***********************************************
 ** MODAL BOX DELETES PAGES & NAV & FRONT-END ** 
 **********************************************/

/*
 * Used to display and modify the delete modal box for both pages and widgets
 * used on the Pages index page in the CP and all front-end admin pages
 */
function confirmDelete() {
	// for pages with children
	$$('.rp-has-children').each(function(elm) {
		elm.observe('click', function(event) {
			event.stop();
			// find the last slash in the URL. (ie. /cp/pages/delete/12)
			// get the id portion (12)
			var slash = elm.href.lastIndexOf('/');
			var delete_all_href = elm.href.substring(0, slash) + '_all' + elm.href.substring(slash);

			var content = new Element('div');
			var option1 = new Element('a', {'href':elm.href, 'id':'rp_remove_option_1', 'class':'modal-choice'});
			var option1_text = new Element('span').update('Delete Page Only');
			var option2 = new Element('a', {'href':delete_all_href, 'id':'rp_remove_option_2', 'class':'modal-choice'});
			var option2_text = new Element('span').update('Delete Page & Subpages');
			option1 = option1.update(option1_text).insert('This will delete only 1 page. All associated subpages will move up one level in nav hierarchy.');
			content.update(option1).insert(option2.update(option2_text).insert('This will delete the page and all associated subpages.'));
			
			var modal_box = createModalBox('Are you sure you want to delete this page?', elm.title, content)
			$('rp_modal_functions').update(modal_box);
			$('rp_modal_confirm').appear({duration:0.1});
			
			closeModal();
		});
	});
	
	// for pages without children
	$$('.rp-no-children').each(function(elm) {
		elm.observe('click', function(event) {
			event.stop();
			var content = new Element('a', {'href':elm.href, 'id':'rp_remove_option_1', 'class':'modal-choice'}).update(new Element('span').update('Delete Page'));
			var modal_box = createModalBox('Are you sure you want to delete this page?', elm.up().previous('.rp-page-name').innerHTML, content);
			
			$('rp_modal_functions').update(modal_box);
			$('rp_modal_confirm').appear({duration:0.1});
			
			closeModal();
		});
	});
	
	// for deleting widgets off the front-end
	$$('.widget-delete').each(function(elm) {
		elm.observe('click', function(event) {
			event.stop();
			// if this is a master or clone
			if(elm.up().previous().down().next() && elm.up().previous().down().next().innerHTML != "Inactive") {
				var type = elm.up().previous().down().next().innerHTML;
				var content = new Element('div');
				if(type == 'master') {
					var option1 = new Element('a', {'href':elm.href, 'id':'rp_widget_option', 'class':'modal-choice'});
					var option1_text = new Element('span').update('Delete Widget & Clones');
					var option2 = new Element('a', {'href':elm.href, 'id':'rp_widget_option_2', 'class':'modal-choice'});
					var option2_text = new Element('span').update('Delete Widget & Convert Clones');
					
					option1 = option1.update(option1_text).insert('This widget and all associated clones will be removed from the site.');
					content.update(option1).insert(option2.update(option2_text).insert('This widget will be deleted and all associated clones will be converted to editable copies.'));
					var modal_box = createModalBox('Are you sure you want to delete this widget?', 'This is a Master Widget - ' + elm.up().previous().down().innerHTML, content);
					
				} else if(type == 'clone') {					
					var content = new Element('a', {'href':elm.href, 'id':'rp_widget_option', 'class':'modal-choice'}).update(new Element('span').update('Delete Widget'));
					var modal_box = createModalBox('Are you sure you want to delete this widget?', 'This is a Cloned Widget - ' + elm.up().previous().down().innerHTML, content);
				}
								
			} else {
				var content = new Element('a', {'href':elm.href, 'id':'rp_widget_option', 'class':'modal-choice'}).update(new Element('span').update('Delete Widget'));
				var modal_box = createModalBox('Are you sure you want to delete this widget?', elm.up().previous().down().innerHTML, content);
			}
			$('rp_modal_functions').update(modal_box);
			$('rp_modal_confirm').appear({duration:0.1});
			
			closeModal();
			
			$('rp_modal_confirm').appear({duration:0.1});
			
			$('rp_widget_option').observe('click', function(ev) {
				ev.stop();
				// selected to delete widget and all clones (if any)
				deleteWidget(elm, 'delete_all');
			});
			if($('rp_widget_option_2') != null) {
				$('rp_widget_option_2').observe('click', function(ev) {
					ev.stop();
					// selected to delete and convert clones
					deleteWidget(elm, 'delete_convert');
				});
			}
		});
	});
	
	// deleting files from the library
	$$('.rp-file-delete').each(function(elm) {
		// stop observing since we call this function every time we add a new file
		elm.stopObserving();
		elm.observe('click', function(event) {
			event.stop();
			var content = new Element('a', {'href':elm.href, 'id':'rp_remove_option_1', 'class':'modal-choice'}).update(new Element('span').update('Delete File'));
			var modal_box = createModalBox('Are you sure you want to delete this file?', elm.title, content);
			
			$('rp_modal_functions').update(modal_box);
			$('rp_modal_confirm').appear({duration:0.1});
			
			closeModal();
		});
	});
	
	// deleting categories from the library
	$$('.rp-cat-delete').each(function(elm) {
		elm.observe('click', function(event) {
			event.stop();
			var slash = elm.href.lastIndexOf('/');
			var delete_all_href = elm.href.substring(0, slash) + '_all' + elm.href.substring(slash);
			
			var content = new Element('div');
			if(elm.hasClassName('rp-has-files')) {
				var option1 = new Element('a', {'href':delete_all_href, 'id':'rp_remove_option_1', 'class':'modal-choice'});
				var option1_text = new Element('span').update('Delete Category & Files');
				var option2 = new Element('a', {'href':elm.href, 'id':'rp_remove_option_2', 'class':'modal-choice'});
				var option2_text = new Element('span').update('Delete Category & Keep Files');
				option1 = option1.update(option1_text).insert('This category and all associated files will be removed from the site.');
				content.update(option1).insert(option2.update(option2_text).insert('This category will be deleted and all associated files will become "Uncategorized".'));
			} else {
				var option1 = new Element('a', {'href':delete_all_href, 'id':'rp_remove_option_1', 'class':'modal-choice'});
				var option1_text = new Element('span').update('Delete Category');
				content = option1.update(option1_text).insert('This category will be removed from the site.');
			}
			var modal_box = createModalBox('Are you sure you want to delete this category?', elm.title, content);
			
			$('rp_modal_functions').update(modal_box);
			$('rp_modal_confirm').appear({duration:0.1});
			
			closeModal();
		});
	});
	
	// deleting user from the users module
	$$('.rp-user-delete').each(function(elm) {
		elm.observe('click', function(event) {
			event.stop();
			var content = new Element('a', {'href':elm.href, 'id':'rp_remove_option_1', 'class':'modal-choice'}).update(new Element('span').update('Delete User'));
			var modal_box = createModalBox('Are you sure you want to delete this user?', elm.title, content);
			
			$('rp_modal_functions').update(modal_box);
			$('rp_modal_confirm').appear({duration:0.1});
			
			closeModal();
		});
	});
	
	// deleteing any additional models
	$$('.delete-module').each(function(elm) {
		elm.observe('click', function(event) {
			event.stop();
			var content = new Element('a', {'href':elm.href, 'id':'rp_remove_option_1', 'class':'modal-choice'}).update(new Element('span').update('Delete'));
			var modal_box = createModalBox('Are you sure you want to delete this record?', elm.title, content);

			$('rp_modal_functions').update(modal_box);
			$('rp_modal_confirm').appear({duration:0.1});

			closeModal();
		});
	});
	
	// adding export from the exports module
	$$('.rp-export-add').each(function(elm) {
		elm.observe('click', function(event) {
			if (elm.hasClassName('export-limit-reached')) {
				event.stop();		
				var text = new Element('p', {'class':'modal-paragraph'}).update('If you continue, the oldest export will be overwritten. Otherwise, please delete an existing export before adding a new one.');
				var link = new Element('a', {'href':elm.href, 'id':'rp_remove_option_1', 'class':'modal-choice'}).update(new Element('span').update('Overwrite oldest Export'));
				var content = new Element('div').insert(text).insert(link);
				var modal_box = createModalBox('Max number of exports has been reached.', elm.title, content);

				$('rp_modal_functions').update(modal_box);
				$('rp_modal_confirm').appear({duration:0.1});

				closeModal();
			}
		})
	});
	
}

// deleting export from the exports module
$$('.rp-export-delete').each(function(elm) {
	// stop observing since we call this function every time we add a new file
	elm.stopObserving();
	elm.observe('click', function(event) {
		event.stop();
		var content = new Element('a', {'href':elm.href, 'id':'rp_remove_option_1', 'class':'modal-choice'}).update(new Element('span').update('Delete Export'));
		var modal_box = createModalBox('Are you sure you want to delete this export?', elm.title, content);
		
		$('rp_modal_functions').update(modal_box);
		$('rp_modal_confirm').appear({duration:0.1});
		
		closeModal();
	});
});

function closeModal() {
	// setup method handle close click on modalbox
	$$('.rp-close-modal').each(function(elm) {
		elm.stopObserving();
		elm.observe('click', function(event) {
			event.stop();
			$('rp_modal_confirm').fade({duration:0.3});
		});
	});
}

/*
 * Create general modal box wrapper for deletes/warnings
 */
function createModalBox(title, subtitle, content) {
	var modal_div = new Element('div', {'id':'rp_modal_confirm', 'style':'display:none;'});
	var modal_wrap = new Element('div', {'id':'rp_modal_wrapper'});
	var modal_head = new Element('div', {'id':'rp_modal_head'});
	var modal_head_title = new Element('span').update(title);
	var modal_x = new Element('a', {'class':'rp-close-modal'});
	modal_head = modal_head.update(modal_head_title).insert(modal_x);
	var modal_content = new Element('div', {'id':'rp_modal_text'});
	var modal_text_title = new Element('h2', {'id':'rp_modal_text_title'}).update(subtitle);
	var modal_close = new Element('a', {'class':'modal-choice rp-close-modal'}).update(new Element('span', {'class':'red'}).update('Cancel'));
	modal_content = modal_content.update(modal_text_title).insert(content).insert(modal_close);
	var modal_foot = new Element('div', {'id':'rp_modal_foot'});

	var modal_box = modal_div.update(modal_wrap.update(modal_head).insert(modal_content).insert(modal_foot));

	return modal_box;
}

/*
 * Perform the AJAX delete and animate the widget away.
 */
function deleteWidget(elm, type) {
	new Ajax.Request(elm.href, {parameters: 'del_type=' + type, onSuccess: function(response) {
		// if widget clones were deleted, those ids are passed so the widget elements can be removed
		if(response.responseText) {
			var action = response.responseText.split(":");
			var ids = action['1'].split("'");
			if(action['0'] == "convert") {
				ids.each(function(name) {
					$("rp_widget_"+name).down('div',1).next('div',1).down('span').next().remove();
					$("id_"+name).removeClassName("clone_edit").writeAttribute("href","/cp/pages_widgets/edit/"+name).stopObserving('click');
				});
			} else if(action['0'] == "delete") {
			    ids.each(function(name) {
			    	new Effect.BlindUp($("rp_widget_"+name)), {duration: 0.5, afterFinish:function() {
			    		$("rp_widget_"+name).remove();
			    	}}
			    });
			}
		}
		new Effect.BlindUp(elm.up(2), {duration: 0.5, afterFinish:function() {
			elm.up(2).remove();
		}});
		new Effect.Opacity(elm.up(), {duration:0.5, from:1.0, to:0.0});
		$('rp_modal_confirm').fade({duration:0.3});
	}});
}

document.observe('dom:loaded', confirmDelete);

/*
 * Throw modal box when trying to edit a clone
 */
function editClone() {
	$$('.clone_edit').each(function(elm) {
		elm.observe('click', function(event) {
			event.stop();
			// find the last slash in the URL. (ie. /cp/pages/delete/12)
			// get the id portion (12)
			var underscore = elm.id.lastIndexOf('_');
			var id = elm.id.substring(underscore + 1);
			// create convert clone address (we do it this way so it is more portable... grab the generated base URL and change it from edit to convert clone)
			var slash = elm.href.lastIndexOf('/');
			var convert_href = elm.href.substring(0, slash - 4) + 'convert_clone/' + id;

			var content = new Element('div');
			var option1 = new Element('a', {'href':elm.href, 'id':'rp_widget_option', 'class':'modal-choice'});
			var option1_text = new Element('span').update('Edit This Clone\'s Master Widget');
			var option2 = new Element('a', {'href':convert_href, 'id':'rp_widget_option_2', 'class':'modal-choice'});
			var option2_text = new Element('span').update('Convert This Clone to an Editable Copy');
			option1 = option1.update(option1_text).insert('Changes to the master will be reflected in this and its other clones.');
			content.update(option1).insert(option2.update(option2_text).insert('This widget wil no longer be associated with a master and will become individually editable.'));
			
			var modal_box = createModalBox('Edit Cloned Widget', elm.up().previous().down().innerHTML, content)
			$('rp_modal_functions').update(modal_box);
			$('rp_modal_confirm').appear({duration:0.1});
			
			closeModal();
		});
	});
}

document.observe('dom:loaded', editClone);

/*
 * Functions for copy/clone widgets
 */

// stetup for opening the Copy Modal Box
function openCopyModal() {
	if($('create_copies')) {
		copyWidget('copy');
		// variable to hold initial confirmed value
		copy_confirm = new Array();
		$$('#rp_litebox_bg_cc #copy input[type=checkbox]').each(function(el, i) {
			copy_confirm[i] = el.checked;
		});
		$('create_copies').observe('click', function(event) {
			event.stop();
			$('rp_litebox_head_cc').down().innerHTML = "Select pages on which you want to place copies of this widget:";
			$('copy').show();
			$('clone_select_all').hide();
			$('copy_select_all').show();
			$('rp_litebox_bg_cc').appear({duration:0.1});
		});
	}
}

// setup for opening the Clone Modal Box (same as copy, but minor variations)
function openCloneModal() {
	copyWidget('clone');
	// variable to hold initial confirmed value
	clone_confirm = new Array();
	$$('#rp_litebox_bg_cc #clone input[type=checkbox]').each(function(el, i) {
		clone_confirm[i] = el.checked;
	});
	$$('.create_clones').each(function(elm) {
		elm.observe('click', function(event) {
			event.stop();
			$('rp_litebox_head_cc').down().innerHTML = "Select pages on which you want to place clones of this widget:";
			$('clone').show();
			$('copy_select_all').hide();
			$('clone_select_all').show();
			$('rp_litebox_bg_cc').appear({duration:0.1});
		});
	});
}

// sets up all modal box functionality for copying and cloning
function copyWidget(type) {
	// set click observer on individual checkboxes
	$$('#rp_litebox_bg_cc input[type=checkbox]').each(function(elm) {
		elm.observe('click', function(event) {
			checkTemplates(type);
		});
	});
	
	// de/select all checkboxes based on link
	if($(type+'_select_all')) {
		$(type+'_select_all').observe('click', function(event) {
			event.stop();
			// determine if we need to select or deselect the checkboxes
			var check_value;
			var select_value;
			if($(type+'_select_all').innerHTML == 'select all pages') {
				check_value = true;
				select_value = 'deselect';
			} else {
				check_value = false;
				select_value = 'select';
			}

			// check or uncheck all the checkboxes as necessary.
			$$('#'+type+' input[type=checkbox]').each(function(elm) {
				elm.checked = check_value;
			});

			// change the "select all pages" link to it's appropriate value (deselect, or select)
			$(type+'_select_all').innerHTML = select_value + " all pages";
			// change the text of all the other select links (deselect, or select)
			$$('#'+type+' .select-link').each(function(links) {
				links.innerHTML = select_value + " all subpages";
			});

			// display warning box if necessary
			checkTemplates(type);
		});
	}
    
	// de/select children checkboxes
	$$('#'+type+' .select-link').each(function(elm) {
		elm.observe('click', function(event) {
			event.stop();
			// determine if we need to select or deselect the checkboxes
			var check_value;
			var select_value;
			if(elm.innerHTML == 'select all subpages') {
				check_value = true;
				select_value = 'deselect';
			} else {
				check_value = false;
				select_value = 'select';
			}
			
			// select the current checkbox (the parent line)
			elm.previous(2).down().next().checked = check_value;
			// find the last underscore in the ID. (ie. Copy_12)
			// get the id portion (12)
			var underscore = elm.up().id.lastIndexOf('_');
			var id = elm.up().id.substring(underscore + 1);
			
			// select all decendants
			$$('#'+type+' .child_'+id+' input[type=checkbox]').each(function(item) {
				item.checked = check_value;
				// modify the link text on any children that also have children
				if(item.up().next(2)) {
					item.up().next(2).innerHTML = select_value + " all subpages";
				}
			});
			elm.innerHTML = select_value + " all subpages";
			
			// display warning box if necessary
			checkTemplates(type);
		});
	});
    
	// close the modal box
	$$('#rp_litebox_bg_cc .modal-close').each(function(elm) {
		elm.observe('click', function(event) {
			event.stop();
			$(type).fade({duration:0.3});
			$('rp_litebox_bg_cc').fade({duration:0.3});
			// we are canceling so we need to reset the previously selected checkboxes.
			$$('#rp_litebox_bg_cc #'+type+' input[type=checkbox]').each(function(el, i) {
				if(type == 'clone') {
					el.checked = clone_confirm[i];
				} else {
					el.checked = copy_confirm[i];
				}
				
			});
			checkTemplates(type);
		});
	});
	
	// confirm & close the modal box
	$$('#rp_litebox_bg_cc .modal-confirm').each(function(elm) {
		elm.observe('click', function(event) {
			event.stop();
			// we are confirming, so we need to store in our array the selected checkboxes.
			$$('#rp_litebox_bg_cc #'+type+' input[type=checkbox]').each(function(el, i) {
				if(type == 'clone') {
					clone_confirm[i] = el.checked;
				} else {
					copy_confirm[i] = el.checked;
				}
			});
			$(type).fade({duration:0.3});
			$('rp_litebox_bg_cc').fade({duration:0.3});
		});
	});
}

// Determine which pages have been selected and show/hide the appropriate content area drop-downs
function checkTemplates(type) {
	var different;
	// hide all previously shown drop-downs
	$$('#rp_litebox_bg_cc #'+type+' #map_content_'+type+'>div').invoke('hide');
	
	$$('#rp_litebox_bg_cc #'+type+' input[title=template]').each(function(elm) {
		// determine what template each page is using and update the drop-downs accordingly.
		if(elm.previous().down().next().checked) {
			if(elm.value != $('template_id').value) {
				$(type+'_template_'+elm.value).show();
				different = true;
			}
		}
	});
	if(different) {
		$('map_content_'+type).appear({duration:0.2});
	} else {
		$('map_content_'+type).fade({duration:0.2});
	}
}

// display the unlinking options if the "Unlink Clones" link is checked
function unlinkClones() {
	if($('unlink_clones')) {
		$('unlink_clones').observe('click', function(event) {
			if($('unlink_clones').checked) {
				$('unlink_options').appear({duration:0.2});
			} else {
				$('unlink_options').fade({duration:0.1});
			}
			
		});
	}
	if($('unlink_options')) {
		$('unlink_options').hide();
	}
}

document.observe('dom:loaded', openCopyModal);
document.observe('dom:loaded', openCloneModal);
document.observe('dom:loaded', unlinkClones);

// Animated Grow Button
var growy_last_id = '';
function scaleGrowy(elem){
	bigheight = 250;
	bigwidth = 250;
	bigfont = 18;
	smallheight = 150;
	smallwidth  = 150;
	smallfont = (bigfont*(smallheight/bigheight));
	
	document.observe('dom:loaded', function() {
		// Set parent height and width
		$(elem).up().up().setStyle('width:'+bigwidth+'px;height:'+bigheight+'px;');
		
		// Morph images
		new Effect.Morph(elem, {
		  style: 'height:'+smallheight+'px;width:'+smallwidth+'px;font-size:'+smallfont+'px;top:'+((bigheight-smallheight)/2)+'px;left:'+((bigwidth-smallwidth)/2)+'px;', 
		  duration: 0.01
		});
	});
	
	$(elem).observe('mouseover', function(event) {
		if(growy_last_id == elem) return false;
		new Effect.Morph(elem, {
		  style: 'height:'+bigheight+'px;width:'+bigwidth+'px;font-size:'+bigfont+'px;top:0px;left:0px;', 
		  duration: 0.2,
		  queue: {limit: 2, scope: elem, position:'end'},
		  beforeStart: function(elem1){
			
				if(growy_last_id != ''){
					new Effect.Morph(growy_last_id, {
					   style: 'height:'+smallheight+'px;width:'+smallwidth+'px;font-size:'+smallfont+'px;top:'+((bigheight-smallheight)/2)+'px;left:'+((bigwidth-smallwidth)/2)+'px;', 
					  duration: 0.2
					});
				}
				growy_last_id = elem;				
			}
		});
	});
}
