/*
ModalBox - The pop-up window thingie with AJAX, based on prototype and script.aculo.us.
 
Copyright Andrey Okonetchnikov (andrej.okonetschnikow@gmail.com), 2006-2007
All rights reserved.
VERSION 1.6.1
Last Modified: 04/13/2008
*/
 
if (!window.Modalbox)
var Modalbox = new Object();
 
Modalbox.Methods = {
overrideAlert: false, // Override standard browser alert message with ModalBox
focusableElements: new Array,
currFocused: 0,
initialized: false,
active: true,
options: {
title: "ModalBox Window", // Title of the ModalBox window
overlayClose: true, // Close modal box by clicking on overlay
width: 500, // Default width in px
height: 90, // Default height in px
overlayOpacity: .65, // Default overlay opacity
overlayDuration: .25, // Default overlay fade in/out duration in seconds
slideDownDuration: .5, // Default Modalbox appear slide down effect in seconds
slideUpDuration: .5, // Default Modalbox hiding slide up effect in seconds
resizeDuration: .25, // Default resize duration seconds
inactiveFade: true, // Fades MB window on inactive state
transitions: true, // Toggles transition effects. Transitions are enabled by default
loadingString: "Please wait. Loading...", // Default loading string message
closeString: "Close window", // Default title attribute for close window link
closeValue: "&times;", // Default string for close link in the header
params: {},
method: 'get', // Default Ajax request method
autoFocusing: true, // Toggles auto-focusing for form elements. Disable for long text pages.
aspnet: false // Should be use then using with ASP.NET costrols. Then true Modalbox window will be injected into the first form element.
},
_options: new Object,
 
setOptions: function(options) {
Object.extend(this.options, options || {});
},
 
_init: function(options) {
// Setting up original options with default options
Object.extend(this._options, this.options);
this.setOptions(options);
 
//Creating the overlay
this.MBoverlay = new Element("div", { id: "MB_overlay", style: "opacity: 0" });
 
//Creating the modal window
this.MBwindow = new Element("div", {id: "MB_window", style: "display: none"}).update(
this.MBframe = new Element("div", {id: "MB_frame"}).update(
this.MBheader = new Element("div", {id: "MB_header"}).update(
this.MBcaption = new Element("div", {id: "MB_caption"})
)
)
);
this.MBclose = new Element("a", {id: "MB_close", title: this.options.closeString, href: "#"}).update("<span>" + this.options.closeValue + "</span>");
this.MBheader.insert({'bottom':this.MBclose});
 
this.MBcontent = new Element("div", {id: "MB_content"}).update(
this.MBloading = new Element("div", {id: "MB_loading"}).update(this.options.loadingString)
);
this.MBframe.insert({'bottom':this.MBcontent});
 
// Inserting into DOM. If parameter set and form element have been found will inject into it. Otherwise will inject into body as topmost element.
// Be sure to set padding and marging to null via CSS for both body and (in case of asp.net) form elements.
var injectToEl = this.options.aspnet ? $(document.body).down('form') : $(document.body);
injectToEl.insert({'top':this.MBwindow});
injectToEl.insert({'top':this.MBoverlay});
 
// Initial scrolling position of the window. To be used for remove scrolling effect during ModalBox appearing
this.initScrollX = window.pageXOffset || document.body.scrollLeft || document.documentElement.scrollLeft;
this.initScrollY = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
 
//Adding event observers
this.hideObserver = this._hide.bindAsEventListener(this);
this.kbdObserver = this._kbdHandler.bindAsEventListener(this);
this._initObservers();
 
this.initialized = true; // Mark as initialized
},
 
show: function(content, options) {
if(!this.initialized) this._init(options); // Check for is already initialized
 
this.content = content;
this.setOptions(options);
 
if(this.options.title) // Updating title of the MB
$(this.MBcaption).update(this.options.title);
else { // If title isn't given, the header will not displayed
$(this.MBheader).hide();
$(this.MBcaption).hide();
}
 
if(this.MBwindow.style.display == "none") { // First modal box appearing
this._appear();
this.event("onShow"); // Passing onShow callback
}
else { // If MB already on the screen, update it
this._update();
this.event("onUpdate"); // Passing onUpdate callback
}
},
 
hide: function(options) { // External hide method to use from external HTML and JS
if(this.initialized) {
// Reading for options/callbacks except if event given as a pararmeter
if(options && typeof options.element != 'function') Object.extend(this.options, options);
// Passing beforeHide callback
this.event("beforeHide");
if(this.options.transitions)
Effect.SlideUp(this.MBwindow, { duration: this.options.slideUpDuration, transition: Effect.Transitions.sinoidal, afterFinish: this._deinit.bind(this) } );
else {
$(this.MBwindow).hide();
this._deinit();
}
} else throw("Modalbox is not initialized.");
},
 
_hide: function(event) { // Internal hide method to use with overlay and close link
event.stop(); // Stop event propaganation for link elements
/* Then clicked on overlay we'll check the option and in case of overlayClose == false we'll break hiding execution [Fix for #139] */
if(event.element().id == 'MB_overlay' && !this.options.overlayClose) return false;
this.hide();
},
 
alert: function(message){
var html = '<div class="MB_alert"><p>' + message + '</p><input type="button" onclick="Modalbox.hide()" value="OK" /></div>';
Modalbox.show(html, {title: 'Alert: ' + document.title, width: 300});
},
 
_appear: function() { // First appearing of MB
if(Prototype.Browser.IE && !navigator.appVersion.match(/\b7.0\b/)) { // Preparing IE 6 for showing modalbox
window.scrollTo(0,0);
this._prepareIE("100%", "hidden");
}
this._setWidth();
this._setPosition();
if(this.options.transitions) {
$(this.MBoverlay).setStyle({opacity: 0});
new Effect.Fade(this.MBoverlay, {
from: 0,
to: this.options.overlayOpacity,
duration: this.options.overlayDuration,
afterFinish: function() {
new Effect.SlideDown(this.MBwindow, {
duration: this.options.slideDownDuration,
transition: Effect.Transitions.sinoidal,
afterFinish: function(){
this._setPosition();
this.loadContent();
}.bind(this)
});
}.bind(this)
});
} else {
$(this.MBoverlay).setStyle({opacity: this.options.overlayOpacity});
$(this.MBwindow).show();
this._setPosition();
this.loadContent();
}
this._setWidthAndPosition = this._setWidthAndPosition.bindAsEventListener(this);
Event.observe(window, "resize", this._setWidthAndPosition);
},
 
resize: function(byWidth, byHeight, options) { // Change size of MB without loading content
var oWidth = $(this.MBoverlay).getWidth();
var wHeight = $(this.MBwindow).getHeight();
var wWidth = $(this.MBwindow).getWidth();
var hHeight = $(this.MBheader).getHeight();
var cHeight = $(this.MBcontent).getHeight();
var newHeight = ((wHeight - hHeight + byHeight) < cHeight) ? (cHeight + hHeight) : (wHeight + byHeight);
var newWidth = wWidth + byWidth;
        this.options.width = newWidth;
if(options) this.setOptions(options); // Passing callbacks
if(this.options.transitions) {
new Effect.Morph(this.MBwindow, {
style: "width:" + newWidth + "px; height:" + newHeight + "px; left:" + ((oWidth - newWidth)/2) + "px",
duration: this.options.resizeDuration,
beforeStart: function(fx){
fx.element.setStyle({overflow:"hidden"}); // Fix for MSIE 6 to resize correctly
},
afterFinish: function(fx) {
fx.element.setStyle({overflow:"visible"});
this.event("_afterResize"); // Passing internal callback
this.event("afterResize"); // Passing callback
}.bind(this)
});
} else {
this.MBwindow.setStyle({width: newWidth + "px", height: newHeight + "px"});
setTimeout(function() {
this.event("_afterResize"); // Passing internal callback
this.event("afterResize"); // Passing callback
}.bind(this), 1);
}
 
},
 
resizeToContent: function(options){
 
// Resizes the modalbox window to the actual content height.
// This might be useful to resize modalbox after some content modifications which were changed ccontent height.
 
var byHeight = this.options.height - $(this.MBwindow).getHeight();
if(byHeight != 0) {
if(options) this.setOptions(options); // Passing callbacks
Modalbox.resize(0, byHeight);
}
},
 
resizeToInclude: function(element, options){
 
// Resizes the modalbox window to the camulative height of element. Calculations are using CSS properties for margins and border.
// This method might be useful to resize modalbox before including or updating content.
 
var el = $(element);
var elHeight = el.getHeight() + parseInt(el.getStyle('margin-top'), 0) + parseInt(el.getStyle('margin-bottom'), 0) + parseInt(el.getStyle('border-top-width'), 0) + parseInt(el.getStyle('border-bottom-width'), 0);
if(elHeight > 0) {
if(options) this.setOptions(options); // Passing callbacks
Modalbox.resize(0, elHeight);
}
},
 
_update: function() { // Updating MB in case of wizards
$(this.MBcontent).update($(this.MBloading).update(this.options.loadingString));
this.loadContent();
},
 
loadContent: function () {
if(this.event("beforeLoad") != false) { // If callback passed false, skip loading of the content
if(typeof this.content == 'string') {
var htmlRegExp = new RegExp(/<\/?[^>]+>/gi);
if(htmlRegExp.test(this.content)) { // Plain HTML given as a parameter
this._insertContent(this.content.stripScripts(), function(){
this.content.extractScripts().map(function(script) {
return eval(script.replace("<!--", "").replace("// -->", ""));
}.bind(window));
}.bind(this));
} else // URL given as a parameter. We'll request it via Ajax
new Ajax.Request( this.content, { method: this.options.method.toLowerCase(), parameters: this.options.params,
onSuccess: function(transport) {
var response = new String(transport.responseText);
this._insertContent(transport.responseText.stripScripts(), function(){
response.extractScripts().map(function(script) {
return eval(script.replace("<!--", "").replace("// -->", ""));
}.bind(window));
});
}.bind(this),
onException: function(instance, exception){
Modalbox.hide();
throw('Modalbox Loading Error: ' + exception);
}
});
 
} else if (typeof this.content == 'object') {// HTML Object is given
this._insertContent(this.content);
} else {
Modalbox.hide();
throw('Modalbox Parameters Error: Please specify correct URL or HTML element (plain HTML or object)');
}
}
},
 
_insertContent: function(content, callback){
$(this.MBcontent).hide().update("");
if(typeof content == 'string') { // Plain HTML is given
this.MBcontent.update(new Element("div", { style: "display: none" }).update(content)).down().show();
} else if (typeof content == 'object') { // HTML Object is given
var _htmlObj = content.cloneNode(true); // If node already a part of DOM we'll clone it
// If clonable element has ID attribute defined, modifying it to prevent duplicates
if(content.id) content.id = "MB_" + content.id;
/* Add prefix for IDs on all elements inside the DOM node */
$(content).select('*[id]').each(function(el){ el.id = "MB_" + el.id; });
this.MBcontent.update(_htmlObj).down('div').show();
if(Prototype.Browser.IE) // Toggling back visibility for hidden selects in IE
$$("#MB_content select").invoke('setStyle', {'visibility': ''});
}
 
// Prepare and resize modal box for content
if(this.options.height == this._options.height) {
Modalbox.resize((this.options.width - $(this.MBwindow).getWidth()), $(this.MBcontent).getHeight() - $(this.MBwindow).getHeight() + $(this.MBheader).getHeight(), {
afterResize: function(){
setTimeout(function(){ // MSIE fix
this._putContent(callback);
}.bind(this),1);
}.bind(this)
});
} else { // Height is defined. Creating a scrollable window
this._setWidth();
this.MBcontent.setStyle({overflow: 'auto', height: $(this.MBwindow).getHeight() - $(this.MBheader).getHeight() - 13 + 'px'});
setTimeout(function(){ // MSIE fix
this._putContent(callback);
}.bind(this),1);
}
},
 
_putContent: function(callback){
this.MBcontent.show();
this.focusableElements = this._findFocusableElements();
this._setFocus(); // Setting focus on first 'focusable' element in content (input, select, textarea, link or button)
if(callback != undefined)
callback(); // Executing internal JS from loaded content
this.event("afterLoad"); // Passing callback
},
 
activate: function(options){
this.setOptions(options);
this.active = true;
$(this.MBclose).observe("click", this.hideObserver);
if(this.options.overlayClose)
$(this.MBoverlay).observe("click", this.hideObserver);
$(this.MBclose).show();
if(this.options.transitions && this.options.inactiveFade)
new Effect.Appear(this.MBwindow, {duration: this.options.slideUpDuration});
},
 
deactivate: function(options) {
this.setOptions(options);
this.active = false;
$(this.MBclose).stopObserving("click", this.hideObserver);
if(this.options.overlayClose)
$(this.MBoverlay).stopObserving("click", this.hideObserver);
$(this.MBclose).hide();
if(this.options.transitions && this.options.inactiveFade)
new Effect.Fade(this.MBwindow, {duration: this.options.slideUpDuration, to: .75});
},
 
_initObservers: function(){
$(this.MBclose).observe("click", this.hideObserver);
if(this.options.overlayClose)
$(this.MBoverlay).observe("click", this.hideObserver);
if(Prototype.Browser.Gecko)
Event.observe(document, "keypress", this.kbdObserver); // Gecko is moving focus a way too fast
else
Event.observe(document, "keydown", this.kbdObserver); // All other browsers are okay with keydown
},
 
_removeObservers: function(){
$(this.MBclose).stopObserving("click", this.hideObserver);
if(this.options.overlayClose)
$(this.MBoverlay).stopObserving("click", this.hideObserver);
if(Prototype.Browser.Gecko)
Event.stopObserving(document, "keypress", this.kbdObserver);
else
Event.stopObserving(document, "keydown", this.kbdObserver);
},
 
_setFocus: function() {
/* Setting focus to the first 'focusable' element which is one with tabindex = 1 or the first in the form loaded. */
if(this.focusableElements.length > 0 && this.options.autoFocusing == true) {
var firstEl = this.focusableElements.find(function (el){
return el.tabIndex == 1;
}) || this.focusableElements.first();
this.currFocused = this.focusableElements.toArray().indexOf(firstEl);
firstEl.focus(); // Focus on first focusable element except close button
} else if($(this.MBclose).visible())
$(this.MBclose).focus(); // If no focusable elements exist focus on close button
},
 
_findFocusableElements: function(){ // Collect form elements or links from MB content
this.MBcontent.select('input:not([type~=hidden]), select, textarea, button, a[href]').invoke('addClassName', 'MB_focusable');
return this.MBcontent.select('.MB_focusable');
},
 
_kbdHandler: function(event) {
var node = event.element();
switch(event.keyCode) {
case Event.KEY_TAB:
event.stop();
 
/* Switching currFocused to the element which was focused by mouse instead of TAB-key. Fix for #134 */
if(node != this.focusableElements[this.currFocused])
this.currFocused = this.focusableElements.toArray().indexOf(node);
 
if(!event.shiftKey) { //Focusing in direct order
if(this.currFocused == this.focusableElements.length - 1) {
this.focusableElements.first().focus();
this.currFocused = 0;
} else {
this.currFocused++;
this.focusableElements[this.currFocused].focus();
}
} else { // Shift key is pressed. Focusing in reverse order
if(this.currFocused == 0) {
this.focusableElements.last().focus();
this.currFocused = this.focusableElements.length - 1;
} else {
this.currFocused--;
this.focusableElements[this.currFocused].focus();
}
}
break;
case Event.KEY_ESC:
if(this.active) this._hide(event);
break;
case 32:
this._preventScroll(event);
break;
case 0: // For Gecko browsers compatibility
if(event.which == 32) this._preventScroll(event);
break;
case Event.KEY_UP:
case Event.KEY_DOWN:
case Event.KEY_PAGEDOWN:
case Event.KEY_PAGEUP:
case Event.KEY_HOME:
case Event.KEY_END:
// Safari operates in slightly different way. This realization is still buggy in Safari.
if(Prototype.Browser.WebKit && !["textarea", "select"].include(node.tagName.toLowerCase()))
event.stop();
else if( (node.tagName.toLowerCase() == "input" && ["submit", "button"].include(node.type)) || (node.tagName.toLowerCase() == "a") )
event.stop();
break;
}
},
 
_preventScroll: function(event) { // Disabling scrolling by "space" key
if(!["input", "textarea", "select", "button"].include(event.element().tagName.toLowerCase()))
event.stop();
},
 
_deinit: function()
{
this._removeObservers();
Event.stopObserving(window, "resize", this._setWidthAndPosition );
if(this.options.transitions) {
Effect.toggle(this.MBoverlay, 'appear', {duration: this.options.overlayDuration, afterFinish: this._removeElements.bind(this) });
} else {
this.MBoverlay.hide();
this._removeElements();
}
$(this.MBcontent).setStyle({overflow: '', height: ''});
},
 
_removeElements: function () {
$(this.MBoverlay).remove();
$(this.MBwindow).remove();
if(Prototype.Browser.IE && !navigator.appVersion.match(/\b7.0\b/)) {
this._prepareIE("", ""); // If set to auto MSIE will show horizontal scrolling
window.scrollTo(this.initScrollX, this.initScrollY);
}
 
/* Replacing prefixes 'MB_' in IDs for the original content */
if(typeof this.content == 'object') {
if(this.content.id && this.content.id.match(/MB_/)) {
this.content.id = this.content.id.replace(/MB_/, "");
}
this.content.select('*[id]').each(function(el){ el.id = el.id.replace(/MB_/, ""); });
}
/* Initialized will be set to false */
this.initialized = false;
this.event("afterHide"); // Passing afterHide callback
this.setOptions(this._options); //Settings options object into intial state
},
 
_setWidth: function () { //Set size
$(this.MBwindow).setStyle({width: this.options.width + "px", height: this.options.height + "px"});
},
 
_setPosition: function () {
$(this.MBwindow).setStyle({left: (($(this.MBoverlay).getWidth() - $(this.MBwindow).getWidth()) / 2 ) + "px"});
},
 
_setWidthAndPosition: function () {
$(this.MBwindow).setStyle({width: this.options.width + "px"});
this._setPosition();
},
 
_getScrollTop: function () { //From: http://www.quirksmode.org/js/doctypes.html
var theTop;
if (document.documentElement && document.documentElement.scrollTop)
theTop = document.documentElement.scrollTop;
else if (document.body)
theTop = document.body.scrollTop;
return theTop;
},
_prepareIE: function(height, overflow){
$$('html, body').invoke('setStyle', {width: height, height: height, overflow: overflow}); // IE requires width and height set to 100% and overflow hidden
$$("select").invoke('setStyle', {'visibility': overflow}); // Toggle visibility for all selects in the common document
},
event: function(eventName) {
if(this.options[eventName]) {
var returnValue = this.options[eventName](); // Executing callback
this.options[eventName] = null; // Removing callback after execution
if(returnValue != undefined)
return returnValue;
else
return true;
}
return true;
}
};
 
Object.extend(Modalbox, Modalbox.Methods);
 
if(Modalbox.overrideAlert) window.alert = Modalbox.alert;/* Global JS for all Shuls sites */

Event.observe(window,'load',function(){
	try{
		$$("a.icon_popup").each(function(el){
			el.tabIndex = 9;
		});
	}
	catch(e){} // do nothing

	try{
		if( $("admin_frm_head") ){
			if( $("admin_frm_head").admin_section.length < 2){
				$("admin_frm_head").hide();
			} else {
				$("admin_frm_head").show();
			}
		}
	}catch(e){}

});

function _getElement(id)
{
	if (document.getElementById && document.getElementById(id)) {
		return document.getElementById(id);
	}
	else if (document.all && document.all[id]) {
		return document.all[id];
	}
	else {
		return false;
	}
}


function toggleBlock(id)
{
	if(_getElement(id) ){
			if (_getElement(id).style.display == 'none') {
				_getElement(id).style.display = 'block';
			}
			else {
				_getElement(id).style.display = 'none';
			}
	}

}

function showSubMenu(id)
{
//	Effect.BlindDown(id,{duration:1});
	if($('subnav'+id)){
		$('subnav'+id).show();
		$('navlabel'+id).addClassName('openheader');
	}

}
function hideSubMenu(id)
{
//	Effect.BlindUp(id);
	if($('subnav'+id)){
		$('subnav'+id).hide();
		$('navlabel'+id).removeClassName('openheader');
	}
}

function setPointer(theRow,classn)
{
	if (typeof(theRow.style) == 'undefined') {
        return false;
    }
    theRow.className = classn;
    return true;
}

function sure()
{
	return confirm('Are you sure you would like to remove this?');
}



/*
Javascript popup window
By Michael Butler 07/01/09

Usage:
to auto generate the popup window, simply include this script and add this click handler:
onclick="return Popup.display('Hello World',this)"
to use an existing div as the popup (the div must have 3 divs beneath it)
onclick="return Popup.display('Hello World',this,'Div_Id')"
*/

var Popup = {};

Popup.display = function(theText,clickedEl,divId,iWidth){
	var inserted = null;

	if(!divId){
		divId = "myPopup";
	}
	var oDiv = $(divId);
	if(!oDiv){
		oDiv = this.insertDiv();
		inserted = true;
	}
	if(!oDiv){
		alert("Div not found.");
		return false;
	}

	if(!oDiv.hasClassName("styled")){
		this.styleDiv(oDiv);
		oDiv.addClassName("styled");
	}

	if(iWidth){
		oDiv.style.width = "" + iWidth + "px";
	}

	oDiv.show();
	this.moveDiv(oDiv,clickedEl);

	var children = oDiv.childElements();

	children[1].update(theText);

	Event.observe(children[0].down(),'click',function(e){
		var el = Event.element(e);
		el.up().up().fade({duration:0.5});
	});

	if(!this.dragg){
		new Draggable(divId,{handle:"hd"});
		this.dragg = true;
	}

	if(inserted){
		this.moveDiv(oDiv,clickedEl);
	}

	return false;
};

Popup.moveDiv = function(oDiv,clickedEl){
	var loc = this.findPos(clickedEl);

	oDiv.style.position = "absolute";

	var dimen = oDiv.getDimensions();
	var wdimen = document.viewport.getDimensions();
	var offset = document.viewport.getScrollOffsets();
	var offsety = offset.top;
	var w,h;

	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		w = window.innerWidth;
		h = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		w = document.documentElement.clientWidth;
		h = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		w = document.body.clientWidth;
		h = document.body.clientHeight;
	}

//	console.log("loc[1] " + loc[1]);
//	console.log("offsety " + offsety);
//	console.log("h " + h);
//	console.log("dimen.height " + dimen.height);
//
	if(loc[0] > w/2){
		oDiv.style.left = "" + (loc[0] - dimen.width) + "px";
	} else {
		oDiv.style.left = "" + (loc[0]+16) + "px";
	}
	if( (loc[1]-offsety) > (h/2) ){
		oDiv.style.top  = "" + (loc[1] - dimen.height) + "px";
	} else {
		oDiv.style.top  = "" + (loc[1]+10) + "px";
	}
};

Popup.styleDiv = function(oDiv,clickedEl){

	oDiv.style.position = "absolute";
	oDiv.style.margin = 0;
};

Popup.insertDiv = function(){
	var html = '<div id="myPopup" style="display:none;"><div class="hd"><div class="close">&times;</div></div><div class="bd"></div><div class="ft"></div></div>';
	var n = $(window.document.body);
	var newN = n.insert(html);
	return $('myPopup');
};

Popup.findPos = function(obj){
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	} else {
		curleft = 20;
		curtop = 20;
	}

	return [curleft,curtop];
};



var toggleStyles = function(){
	var linkTag = $("id_template_css");
	var adminLinkTag = $("id_admin_css");
	if(linkTag.href == "#"){
		linkTag.href = linkTag.readAttribute("altval");
	} else {
		linkTag.writeAttribute("altval",linkTag.href);
		linkTag.href = "#";
	}

	if(adminLinkTag){
		adminLinkTag.href = "";
	}
}

function showPhotoGallerySearch()
{
	$('gallery_sort').style.display="none";
	//$('gallery_search').style.display="";
	Effect.SlideDown('gallery_search_a');
}

function showPhotoGallerySort( test )
{
	//$('gallery_sort').style.display="";
	if(test)
	{
		$('gallery_search_a').style.display="none";
		Effect.SlideDown('gallery_search_a');
	}
	else
	{
		$('gallery_search_a').style.display="none";
		Effect.SlideDown('gallery_sort');
	}

}


function closeSortTab()
{
	//$('gallery_sort').style.display="none";
	Effect.SlideUp('gallery_sort');
}

function closeSearchTab()
{
	//$('gallery_search').style.display="none";
	Effect.SlideUp('gallery_search_a');
}

// Return True on Good Email
function validateEmail(str){
	return str.match(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i);
}
var swfu = new Array();
var site;

/******* preload images ***************/
pic1= new Image(94,26);
pic1.src="/pics/btn_add.gif";
pic2= new Image(94,26);
pic2.src="/pics/btn_cancel.gif";


function checkList(){
//	Modalbox.resizeToContent();

	$$('.hazard').each(function(red){ red.removeClassName('hazard')})
	var lis = $$('#tree ul ul li');
	if(lis.length > 0 ){
		$('save_button').disabled = true;
		$('error_div').style.visibility  = "visible";
		lis.each(function(li){	li.addClassName('hazard');	}	)
	}else{
		$('save_button').disabled = false;
		$('error_div').style.visibility  = "hidden";
	}
}

function openAddPageDialog(){
	Modalbox.show('ajax/ajax.content.php?action=add_page_form',{title:"Add New Page",width:350});
}
function openEditPageDialog(id){
	Modalbox.show('ajax/ajax.content.php?action=edit_page_form&id='+id,{title:"Edit Page",width:350});
}

function openAddContentDialog(id){
	Modalbox.show('ajax/ajax.content.php?action=add_content_form&id='+id,{title:"Add New Content",width:550});
}

function openSponsorEdit(){
	Modalbox.show('ajax/ajax.content.php?action=sponsor_form',{title:"Edit Sponsor Info",width:350});
}

function uploadNewLogo(){
	Modalbox.show('ajax/ajax.content.php?action=logo_form',{title:"Upload New Logo",width:450});

	//Relative Window / Content from Ajax
//	var ajax = new Control.Window('editlogo',{
//			className: 'simple_window',
//			closeOnClick: 'container',
//			offsetLeft: 75,
//			position: 'relative',
//			fade: true,
//		});
//	ajax.open();

}

function openSortMenuDialog(){
	var height	= 'auto';
	if (screen.height<=768){
		height = (typeof window.innerHeight != 'undefined' ? window.innerHeight : document.body.offsetHeight);
	}
	 Modalbox.show('ajax/ajax.menu_sort.php',{title:"Sort Main Menu",width:550,height: height});
	// Modalbox.show($('treeparent'),{title:"Sort Main Menu",width:550,height:800});
	// Modalbox.show('tree_sandbox.php',{title:"Sort Main Menu",width:550});
}


function cancelAddPageDialog(){
	// $('newPageForm').reset();
	Modalbox.hide();
}

function cancelContentDialog(){
	// $('newPageForm').reset();
	Modalbox.hide();
}

function addPage(){
	if($('newPageForm').name.value ==''){
		$('addPageFormError').innerHTML = "Please provide a page name."
		Modalbox.resizeToContent();
		return false;
	}


	$('newPageForm').request({
		onSuccess: function(transport){
		   	// alert('The new page has been added!');
		    $('newPageForm').reset();
		    var json = transport.responseText.evalJSON();
		    insertNavItem(json.cid,json.url,json.name);
		   //  Sortable.create('mainnav',{onUpdate: updateNavOrder, tag:'div'});
			// toggleBlock('addPageFormDiv');
			Modalbox.hide();
			window.location = json.url
		}
	});
}

function editSponsor(){

	$('sponsorForm').request(
		{
		onSuccess: function(transport){
		    var json = transport.responseText.evalJSON();
			if(json.link){
				$('sponsHeader').innerHTML = '';
				var link =	new Element('a',{href: json.link })
				link.innerHTML = "Sponsored by: " + json.sponsor;
				$('sponsHeader').appendChild(link);
			}else{
				$('sponsHeader').innerHTML = "Sponsored by: " + json.sponsor;
			}
		    Modalbox.hide();

		}
	});

}

function insertNavItem(id,url,txt){

	var link = document.createElement('a');
	link.setAttribute('href',url);
	link.innerHTML = txt;

	var label = document.createElement('label');
	label.appendChild(link);

	var div = document.createElement('div');
	div.className = "menuheader moveable";
	div.setAttribute('id','nav_'+id);
	div.setAttribute('href','#');
	div.appendChild(label);

	$('mainnav').appendChild(div);
}

function updateLeftNav(){
	new Ajax.Updater("mainnav","/ajax/ajax.update_nav.php");
}

function updateNavOrder(next){
	// Sortable.create('tree',{ tag:'li',tree:true });
	var params = Sortable.serialize('tree')+'&hold=true';
	var url = '/ajax/ajax.update_nav_order.php';
	var ajax = new Ajax.Request(
			url,
			{method: 'post', parameters: params,
			onSuccess: function(){ window.location = next }
			}
	);
  	//	Modalbox.hide();
	// updateLeftNav();

}

function createSwfUpload(id){

	var settings = {
					flash_url : "/shared_files/SWFUpload.swf",
					upload_url: site+'/ajax/ajax.content.php',	// Relative to the SWF file
					post_params: {"action": "upload_image", "content_id": id },
					file_post_name: 'image',
					file_size_limit : "20 MB",
					file_types : "*.jpg; *.gif; *.jpeg; *.png",
					file_types_description : "Image Files",
					file_upload_limit : 100,
					file_queue_limit : 1,
					debug: false,
					custom_settings : {
						content_id : id,
						upload_successful : false
					},

					// Button settings
					button_image_url: "/shared_files/uploadfile.jpg",	// Relative to the Flash file
					button_placeholder_id : "spanButtonPlaceHolder"+id,
					button_width: 90,
					button_height: 22,

					// Event handler settings
					swfupload_loaded_handler : swfUploadLoaded,
					file_dialog_start_handler: fileDialogStart,
					file_queued_handler : fileQueued,
					file_queue_error_handler : fileQueueError,
					file_dialog_complete_handler : fileDialogComplete,
	//				// upload_start_handler : uploadStart,	// I could do some client/JavaScript validation here, but I don't need to.
	//				upload_progress_handler : uploadProgress,
					upload_error_handler : uploadError,
					upload_success_handler : uploadSuccess,
					upload_complete_handler : uploadComplete
			};

	swfu[id] = new SWFUpload(settings);
}


function showForm(id){
	$('viewDiv'+id).hide();
	$('editDiv'+id).show();
}

function hideForm(id){
	$('viewDiv'+id).show();
	$('editDiv'+id).hide();
}

function updateContent(id){

	if(!swfu[id].startUpload())
		startTextUpdate(id);
}

function startTextUpdate(id){
	var fckText = FCKeditorAPI.GetInstance('fck_'+id).GetXHTML();

	$('title_'+id).innerHTML = $('cntName'+id).value;
	$('body_'+id).innerHTML = fckText;

	var params = 'action=update&id='+id+'&info[name]='+escape($('cntName'+id).value)+'&info[body]='+escape(fckText);
	var url = '/ajax/ajax.content.php';
	var ajax = new Ajax.Request(
			url,
			{method: 'post', parameters: params }

	);

	Modalbox.hide();

	/*
	$('editForm'+id).request({
		parameters: { 'info[body]' : fckText },
		onSuccess: function(transport){
			var json = transport.responseText.evalJSON();
			$('title_'+json.id).innerHTML = json.name;
			$('body_'+json.id).innerHTML = json.body;
			Modalbox.hide();
			// alert("In request onSuccess.");
		},
		onException: function(requester, exc){
			alert("an exception occured! " + exc);
		},
		onFailure: function(){
			alert("There was a problem with the update.");
		}
	});*/
}


function updateDivOrder(id){
	var params = Sortable.serialize('div_order')+'&action=div_order';
	var url = '/ajax/ajax.content.php';
	var ajax = new Ajax.Request(
			url,
			{method: 'post', parameters: params }
	);
}


function addContent(sid, pid){

	var params = 'site_id='+ sid +'&pid=' + pid;
	 var myAjax = new Ajax.Request(
	 		'/ajax/ajax.content.php',
	 		{	method: 'get',
	 			parameters: params,
	 			onSuccess: function(transport){
//	 				alert("here");
	 				var json = transport.responseText.evalJSON();
					insertDiv(json.id,json.name,json.body);
					Sortable.create('div_order',{onUpdate: updateDivOrder, tag:'div'});
					createSwfUpload(json.id);
				}
	 		}
	 );
}


function deleteContent(id){

	var conf = confirm("You are about to delete content from your site. \n Once deleted, this content including any images, will no longer be available. \n Would you like to continue?");
	if(conf){
		Modalbox.hide();
		var params = 'action=delete&id='+id;
		var myAjax = new Ajax.Request(
		 		'/ajax/ajax.content.php',
		 		{	method: 'get',
		 			parameters: params,
		 			onSuccess: function(){
		 				$('div_order').removeChild($('content_'+id));
					}
		 		}
		 );
	}

}


function insertDiv(id,name,body){

	/***** Create the VIEW DIV ******/

//		var editLink = document.createElement('a');
//		editLink.className = "edit_link";
//		editLink.setAttribute('id','editTitle'+id);
//		editLink.setAttribute('href','#');
//		editLink.innerHTML = "Edit";
//		editLink.onclick = function() { openAddContentDialog(id); return false; }
//
//		var delLink = document.createElement('a');
//		delLink.className = "delete_content";
//		delLink.setAttribute("id","deleteContent"+id);
//		delLink.setAttribute('href','#');
//		delLink.innerHTML = "Delete";
//		delLink.onclick= function() { deleteContent(id); return false; };

		var newH2 = document.createElement('h2');
		newH2.setAttribute('id','title_'+id);
		newH2.setAttribute('class','moveable');
		newH2.innerHTML = name;

		var imgDiv = document.createElement('div');
		imgDiv.setAttribute('id','img_'+id);
		imgDiv.style.float = 'left';

		var bodyDiv = document.createElement('div');
		bodyDiv.setAttribute('id','body_'+id);
		bodyDiv.innerHTML = body;

		var editLink = document.createElement('a');
		editLink.className = "contpop hidden_elem";
		editLink.setAttribute('id','editcontent'+id);
		editLink.setAttribute('href','#');
		editLink.innerHTML = "Edit Content";
		editLink.onclick = function() { openAddContentDialog(id); return false; }
		var bgSpan = document.createElement('span');
		editLink.appendChild(bgSpan);

		var viewDiv = document.createElement('div');
		viewDiv.setAttribute('id','viewDiv'+id);
		// viewDiv.appendChild(delLink);
		viewDiv.appendChild(newH2);
		viewDiv.appendChild(imgDiv);
		viewDiv.appendChild(bodyDiv);
		viewDiv.appendChild(editLink);

	/******** Create the EDIT DIV *********/

//		var frmNode = document.createElement('form');
//		frmNode.setAttribute('id','editForm'+id);
//		frmNode.action ='/ajax/ajax.content.php';
//		frmNode.setAttribute('method', 'post');
//
//		var idHid = document.createElement('input');
//		idHid.setAttribute('type','hidden');
//		idHid.setAttribute('name','id');
//		idHid.setAttribute('value',id);
//		frmNode.appendChild(idHid);
//
//		var actionHid = document.createElement('input');
//		actionHid.setAttribute('type','hidden');
//		actionHid.setAttribute('name','action');
//		actionHid.setAttribute('value','update');
//		frmNode.appendChild(actionHid);
//
//		var nameInp = document.createElement('input');
//		nameInp.setAttribute('type','text');
//		nameInp.setAttribute('id','cntName'+id);
//		nameInp.setAttribute('name','info[name]');
//		nameInp.setAttribute('size','55');
//		nameInp.setAttribute('value',name);
//		frmNode.appendChild(nameInp);
//
//		var swfInp = document.createElement('input');
//		swfInp.setAttribute('type','text');
//		swfInp.setAttribute('id','txtFileName'+id);
//		swfInp.setAttribute('disabled','true');
//		swfInp.style.backgroundColor = '#ffffff';
//
//		var swfSpan = document.createElement('span');
//		swfSpan.setAttribute('id','spanButtonPlaceHolder'+id);
//
//		var swfDiv = document.createElement('div');
//		swfDiv.setAttribute('class','swfdiv');
//		swfDiv.appendChild(swfInp);
//		swfDiv.appendChild(swfSpan);
//		frmNode.appendChild(swfDiv);
//
//		var fckDiv 		= document.createElement('div');
//		var fck 		= new FCKeditor("fck_"+id);
//		fck.BasePath 	= "/shared_files/FCKeditor/" ;
//		fck.ToolbarSet 	= 'Basic';
//		fck.Value		= body;
//		fck.Width		= 500;
//		fck.Height		= 200;
//		fckDiv.innerHTML = fck.CreateHtml();
//		frmNode.appendChild(fckDiv);
//
//		var submitBtn = document.createElement('input');
//		submitBtn.setAttribute('type','button');
//		submitBtn.setAttribute('id','btnSubmit'+id);
//		submitBtn.setAttribute('value','OK');
//		submitBtn.onclick = function(){ updateContent(id); };
//		frmNode.appendChild(submitBtn);
//
//		var cancelBtn = document.createElement('input');
//		cancelBtn.setAttribute('type','button');
//		cancelBtn.setAttribute('id','btnCancel'+id);
//		cancelBtn.setAttribute('value','Cancel');
//		cancelBtn.onclick = function(){ executeCancel(id); };
//		frmNode.appendChild(cancelBtn);
//
//
//		var editDiv = document.createElement('div');
//		editDiv.setAttribute('id','editDiv'+id);
//		editDiv.style.display = 'none';
//		editDiv.appendChild(frmNode);

	// Append view & edit Divs to the container Div.
	var containerDiv = document.createElement('div');
	containerDiv.className = "featured_article";
	containerDiv.setAttribute('id','content_'+id);
	containerDiv.onmouseover = function() { $('editcontent'+id).removeClassName('hidden_elem') }
	containerDiv.onmouseout = function() { $('editcontent'+id).addClassName('hidden_elem') }
	containerDiv.appendChild(viewDiv);
	// containerDiv.appendChild(editDiv);


	var parentDiv = $('div_order');
	parentDiv.insertBefore(containerDiv,parentDiv.firstChild);
}


function executeCancel(id){

	$("editForm"+id).reset();

    // Get the initial value of the FCDEditor
    var sInitialValue = document.getElementById("fck_"+id).value;

    // Overwrite the editor's current value with the initial value
    FCKeditorAPI.GetInstance('fck_'+id).SetHTML(sInitialValue);

	hideForm(id);
}


function deleteImage(id){
	var params = 'action=delete_image&id='+id;
	var myAjax = new Ajax.Request(
		 		'/ajax/ajax.content.php',
		 		{
		 			parameters: params,
		 			onSuccess: function(){
		 				$('img_'+id).innerHTML = '';
					}
		 		}
		 );
}



function openAddAnnouncementDialog(timestamp,wholemonth){
	if(!wholemonth) {
		var wholemonth = "Y";
	}

	Modalbox.show('ajax/ajax.calendar.php?action=add_announcement_form&wholemonth='+wholemonth+'&timestamp='+timestamp,{title:"Add Announcement"+(wholemonth!="Y"?" or Special Event":""),width:550});
}

function openEditAnnouncementDialog(id){
	Modalbox.show('ajax/ajax.calendar.php?action=edit_announcement_form&id='+id,{title:"Edit Announcement",width:400});
}

function openAddOverrideDialog(id,date,time){
	Modalbox.show('ajax/ajax.calendar.php?action=add_override&id='+id+'&date='+date+'&time='+time,{title:"Edit Calendar Event",width:400,evalScripts:true});
}

function openEditOverrideDialog(id){
	Modalbox.show('ajax/ajax.calendar.php?action=edit_override&id='+id,{title:"Edit Calendar Event",width:400,evalScripts:true});
}

function editSpecialEventDialog(event_id) {
	Modalbox.show('ajax/ajax.calendar.php?action=edit_special_event&event_id='+event_id,{title:"Edit Special Event",width:400,evalScripts:true});
}

function processAnnouncement(){
	if($('announcementForm').elements["info[body]"].value == ''){
		$('announcement_error').innerHTML = "Please provide the announcement body."
		Modalbox.resizeToContent();
		return false;
	}
	$('announcementForm').request({
		onSuccess: function(transport){
			refreshAnnouncementTable($('announcementForm').elements["info[date]"].value);
			Modalbox.hide();
		}
	});
}

function deleteAnnouncement(id){
	var conf = confirm("Are you sure you want to delete this announcement?");
	if(conf){
		var params = 'action=delete_announcement&id='+id;
		var myAjax = new Ajax.Request(
		 		'/ajax/ajax.calendar.php',
		 		{	method: 'get',
		 			parameters: params,
		 			onSuccess: function(){
		 				// $('annTableRow'+id).hide();
		 				Modalbox.hide();
		 				location.reload(true);
					}
		 		}
		 );
	}

}

function refreshAnnouncementTable(date){
	var params = 'action=refresh_table&date='+date;
	var myAjax = new Ajax.Updater(	'announcement_table',	'/ajax/ajax.calendar.php',	{	parameters: params	} );

}


function processOverride(){
        var hour;

        if ($('overrideForm').elements["info[is_hidden]"][1].checked) {

        	var ret = confirm('Deleting this event will only remove it from this day.  Are you sure you want to do this?  You can always add the event back manually.');

        	if (!ret)
        		return false;
        }
        else {
			if ($('overrideForm').hour_select.selectedIndex + 1 == 12) {
					if ($('overrideForm').ampm_select.value == 12)
							hour = 0;
					else
							hour = -12;
			} else
					hour = parseInt($('overrideForm').ampm_select.value);

			$('hidden_time').value = (parseInt($('overrideForm').hour_select.selectedIndex+1) + parseInt(hour)) + ":" + ($('overrideForm').minute_select.value) + ":00";
			//alert($('hidden_time').value);
		}

	$('overrideForm').request({
		onSuccess: function(transport){
			// refreshAnnouncementTable($('announcementForm').elements["info[date]"].value);
			Modalbox.hide();
                        location.reload(true);
		}
	});
}

function deleteOverride(id){
	var conf = confirm("Are you sure you want to delete this override?");
	if(conf){
		var params = 'action=delete_override&id='+id;
		var myAjax = new Ajax.Request(
		 		'/ajax/ajax.calendar.php',
		 		{	method: 'get',
		 			parameters: params,
		 			onSuccess: function(){
		 				// $('annTableRow'+id).hide();
		 				Modalbox.hide();
		 				location.reload(true);
					}
		 		}
		 );
	}

}


function processSpecialEvent() {
	if($('specialEventForm').elements["info[name]"].value == ''){
		$('special_event_error').innerHTML = "Please provide the event name.";
		Modalbox.resizeToContent();
		return false;
	}
	if ($('date_start').value == '' || $('date_end').value == '') {
		$('special_event_error').innerHTML = "Please select both a start and end date.";
		Modalbox.resizeToContent();
		return false;
	}
	if ($('date_start').value > $('date_end').value) {
		$('special_event_error').innerHTML = "Start date is after end date.  Please correct.";
		Modalbox.resizeToContent();
		return false;
	}

	$('specialEventForm').request({
		onSuccess: function(transport){
			Modalbox.hide();
                        location.reload(true);
		}
	});
}

function deleteSpecialEvent(id){
	var conf = confirm("Are you sure you want to delete this special event?");
	if(conf){
		var params = 'action=delete_special_event&id='+id;
		var myAjax = new Ajax.Request(
		 		'/ajax/ajax.calendar.php',
		 		{	method: 'get',
		 			parameters: params,
		 			onSuccess: function(){
		 				// $('annTableRow'+id).hide();
		 				Modalbox.hide();
		 				location.reload(true);
					}
		 		}
		 );
	}

}