/*
 *	AEMCorp.com Javascript 
 */


function toggleDirections(path, id, parentid)
{	

	
	if (! $('directions_' + parentid).visible())
	{
		if ( $('map_' + parentid).visible())
		{	
			$('map_' + parentid).fade({ delay: 0.0, duration: 0.3, from: 1.0, to: 0.0, queue: 'front' });
		}
		
		new Ajax.Updater('directions_' + parentid,'/content/view/path:' + path + '/id:' + id, {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'directions_' + parentid], queue: 'front'});

		$('directions_' + parentid).appear({ delay: 0.0, duration: 0.3, from: 0.0, to: 1.0, queue: 'end' });

	}
	else
	{
		$('directions_' + parentid).fade({ delay: 0.0, duration: 0.3, from: 1.0, to: 0.0 });
		
	}

}

function toggleMap(path, id, parentid)
{	

	if (! $('map_' + parentid).visible())
	{
		if ( $('directions_' + parentid).visible())
		{	
			$('directions_' + parentid).fade({ delay: 0.0, duration: 0.3, from: 1.0, to: 0.0, queue: 'front' });
		}
		
		new Ajax.Updater('map_' + parentid,'/content/view/path:' + path + '/id:' + id, {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'map_' + parentid], queue: 'front'});

		$('map_' + parentid).appear({ delay: 0.0, duration: 0.3, from: 0.0, to: 1.0, queue: 'end'});

	}
	else
	{
		$('map_' + parentid).fade({ delay: 0.0, duration: 0.3, from: 1.0, to: 0.0 });
		
	}
}


function Open_Article(path, id)
{
	//Check for any existing article div
	var articleContent;
	if (!$('articleContent'))
	{
		//Article container div
		var articleContainer = new Element('div', {id : 'articleContainer'});
		$('article_' + id).insert({after : articleContainer});

		//Set style of container div
		var cw = f_clientWidth();
		var ch = f_clientHeight();
		var st = f_scrollTop();
		var sl = f_scrollLeft();
		var width, height, xCord, yCord;
		width = 600;
		height = 400;
		xCord = sl+(cw/2)-(width/2);
		yCord = st+(ch/2)-(height/2);
		//Adjust top and left position if browser will not currently fit them
		var conWidth = $('container').offsetWidth;
		var conHeight = $('container').offsetHeight;
		if (xCord < 0)
			xCord = 0;
		else if ((cw < conWidth) && ((xCord+width) > conWidth))
			xCord = conWidth - width - 2;
		if (yCord < 0)
			yCord = 0;
		else if ((ch < conHeight) && ((yCord+height) > conHeight))
			yCord = conHeight - height - 2;
		articleContainer.setStyle({
		display: 'none',
		width: width + 'px',
		height: height + 'px',
		top: yCord + 'px',
		left: xCord + 'px'
		});

		//Article bar and close div
		var articleBar = new Element('div', {id : 'articleBar'});
		var articleClose = new Element('div', {id : 'articleClose'});
		$('articleContainer').insert(articleBar);
	    $('articleContainer').insert(articleClose);
	    var closeStr = '<a href="javascript:Close_Article();">' +
	    '	<img alt="Close" src="/themed/default/img/close_icon.gif" border="0" />' +
	    '</a>';
	    articleClose.update(closeStr);

	    //Set style of bar and close div
	    articleBar.setStyle({
			width: (width-19) + 'px',
			height: '19px'
		});
	    articleClose.setStyle({
			width: '19px',
			height: '19px'
		});

		//Article content div
		articleContent = new Element('div', {id : 'articleContent'});
	    $('articleContainer').insert(articleContent);

	    //Set style of content div
	    articleContent.setStyle({
			width: width + 'px',
			height: (height-19) + 'px'
		});

		//Body overlay
	    Body_Overlay();
	}
	else
		articleContent = $('articleContent');

	//Display loading message to user
	articleContent.update(loadingHTML(false));
	
	//Make the div appear on page
	new Effect.Appear('divOverlay', {duration: 0.5, to: 0.25});
	new Effect.Appear('articleContainer', {duration: 0.5, afterFinish: function(){new Ajax.Updater('articleContent','/content/view/path:' + path + '/id:' + id + '/showTitle:true', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'articleContent']});}});
	new Draggable('articleContainer', {handle: 'articleBar', scroll: window, starteffect: function(){return false;}, endeffect: function(){return false;}});
}

//Remove article div from page
function Close_Article(){
	//Only do effect if previous effect not in progress
	var queue = Effect.Queues.get('close').effects;
	if (queue.length == 0){
		new Effect.Fade('articleContainer', {queue: {scope: 'close'}, duration: 0.5, afterFinish: function(){$('articleContainer').remove();}});
		new Effect.Fade('divOverlay', {duration: 0.5, afterFinish: function(){$('divOverlay').remove();}});
	}
}

//Add transparent div to overlay html body
function Body_Overlay(){
	//Create and insert div into body
	var divOverlay = new Element('div', {id : 'divOverlay'});
    $('body').insert(divOverlay);

    //Set style of overlay div
    var arrayPageSize = getPageSize();
    divOverlay.setStyle({
    	display: 'none',
    	width: arrayPageSize[0] + 'px',
    	height: arrayPageSize[1] + 'px'
	});
}
	
function f_clientWidth() {
	return f_filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}

function f_clientHeight() {
	return f_filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0//,
		//document.body ? document.body.clientHeight : 0
	);
}

function f_scrollLeft() {
	return f_filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}

function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0, 
		document.body ? document.body.scrollTop : 0
	);
}

function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

function getPageSize() {
    var pageWidth, pageHeight;

	//Get width of document
	var bodyWidth = $('body').offsetWidth;
	var containerWidth = $('container').offsetWidth;
	if (bodyWidth > containerWidth)
		pageWidth = bodyWidth;
	else
		pageWidth = containerWidth;

	//Get height of document
	var clientHeight = f_clientHeight();
	var documentHeight = $('page_header').offsetHeight + $('menu_top').offsetHeight;
	documentHeight += $('interior_header').offsetHeight + $('interior').offsetHeight;
	documentHeight += $('footer').offsetHeight;
	if (clientHeight > documentHeight)
		pageHeight = clientHeight;
	else
		pageHeight = documentHeight;

	return [pageWidth,pageHeight];
}

function loadingHTML(isInterior){
	var styleStr = '';
	if (isInterior)
		styleStr = ' style="top: 43px;"';
	return '<div class="divSpinner"' + styleStr + '>' +
    '	<img id="imgSpinner" alt="Loading..." class="imgSpinner" src="/themed/default/img/ajax_spinner.gif" />' +
    '</div>'+
	'<div class="divLoading"' + styleStr + '>' +
    '	<img id="imgLoading" alt="Loading..." class="imgLoading" src="/themed/default/img/loading.gif" />' +
    '</div>';
}

function toggleMenu(location, menuID, checkToggle)
{
	// Disable other menus (top only)
	
	if (location == 'top')
	{	

		if (menuID == 1)
			cntr = 2;
		else
			cntr = 1;
			
		other = location + '_menu_' + cntr + '_sub';


		while ($(other))
		{
			if ($(other) && cntr != menuID)
			{
				if ($(other).visible())
				{
					$(other).fade({ delay: 0.0, duration: 0.3, from: 1.0, to: 0.0 });
				}
			}

			cntr++;

			other = location + '_menu_' + cntr + '_sub';
			
		}

	}	

	// Toggle menu
	
	id = location + '_menu_' + menuID + '_sub';

	if (!checkToggle || (checkToggle && !$(id).visible()))
	{
		Effect.toggle(id, 'slide', { delay: 0.0, duration: 0.5 });
	}

	return false;
}


function hideMenus(location)
{
	cntr = 1;
	id = location + '_menu_' + cntr + '_sub';

	while ($(id))
	{
		if ($(id))
		{
			if ($(id).visible())
			{
				if (location == 'top')
					$(id).fade({ delay: 0.0, duration: 0.3, from: 1.0, to: 0.0 });
				else
					$(id).slide({ delay: 0.0, duration: 0.3, from: 1.0, to: 0.0 });
			}
		}

		cntr++;
		id = location + '_menu_' + cntr + '_sub';
		
	}
	
}

function showMenu(location, menuID)
{

	id = location + '_menu_' + menuID + '_sub';
	
	if (! $(id).visible())
	{
		Effect.toggle(id, 'slide', { delay: 0.0, duration: 0.5 });
	}

	// Disable other menus (top only)
	
	if (location == 'top')
	{	

		if (menuID == 1)
			cntr = 2;
		else
			cntr = 1;
			
		other = location + '_menu_' + cntr + '_sub';


		while ($(other))
		{
			if ($(other) && cntr != menuID)
			{
				if ($(other).visible())
				{
					$(other).fade({ delay: 0.0, duration: 0.3, from: 1.0, to: 0.0 });
				}
			}

			cntr++;

			other = location + '_menu_' + cntr + '_sub';
			
		}

	}		
	
}



function hideMenu(location, menuID)
{

	id = location + '_menu_' + menuID + '_sub';
	
	if ($(id).visible())
	{
		Effect.toggle(id, 'slide', { delay: 0.0, duration: 0.5 });
	}
	
}

function updatePageContent(path, id)
{
	//Display loading message to user
	$('interior').update(loadingHTML(true));

	//Update class of menu items
	updateTopMenu(id);
	updateLeftMenu(id);

	// Body Content
	new Ajax.Updater('interior','/aem/interiorAjax/path:' + path + '/method:view', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'interior']});

	return false;
}

function updateTopMenu(id)
{
	//Set li with active class to inactive
	var lis = $('menu_top').select('li[class="itemli_active"]');
	lis.each(function(li)
	{
			li.className = 'itemli';
	});

	//Item related to id should be set to active class
	var items = id.split('_');
	if ($('topitem_' + items[0]))
		$('topitem_' + items[0]).className = 'itemli_active';
}

function updateLeftMenu(id)
{
	//Set all divs with active class to inactive
	var arr1 = $('menu_left').select('div[class="itemdiv_active"]');
	var arr2 = arr1.concat($('menu_left').select('div[class="itemdiv_active_hover"]'));
	arr2.each(function(div)
	{
		div.className = div.className.replace('_active', '');
	});

	//Items related to id should be set to active class
	var items = id.split('_');
	var idStr = 'leftitem';
	for (var i = 0; i < items.length; i++)
	{
		idStr += '_' + items[i];
		if ($(idStr).className.endsWith('hover'))
			$(idStr).className = 'itemdiv_active_hover';
		else
			$(idStr).className = 'itemdiv_active';
		if ($(idStr).firstDescendant().title.startsWith('Toggle'))
			toggleMenu('left', items[i], true);	
	}
}

function highlightTopMenu(parent, isActive, topItem)
{
	//Set the class of the parent container
	var classStr = parent.className.replace('_hover', '');
	if (!isActive)
		parent.className = classStr;
	else
		parent.className = classStr + '_hover';

	//If there is another parent container its class should be set
	if (topItem)
		highlightTopMenu(topItem, isActive);
	else
		return;
}

function highlightLeftMenu(div, isActive)
{
	//Set the class of the div
	var classStr = div.className.replace('_hover', '');
	if (!isActive)
		div.className = classStr;
	else
		div.className = classStr + '_hover';

	//If there is a parent div its class should be set
	var items = div.id.split('_');
	if ($('leftitem_' + items[items.length-2]))
		highlightLeftMenu($('leftitem_' + items[items.length-2]), isActive);
	else
		return;
}

function getPreviousSibling(node)
{
	var tempNode = node.previousSibling;
	while(tempNode.nodeType != 1)
	{
		tempNode = tempNode.previousSibling;
	}
	return tempNode;
}

function showDropShadow()
{
	//Try to show shadow since element may have been overridden if new ajax request was made
	try {
		if (!$('shadow1').visible())
			$('shadow1').show();
	}
	catch(e){}
}

/**
 *	Basic Slideshow App
 *	
 *	Plagerised from Tom Doyle by Isotope Communications Ltd, Dec 2008
 *	http://www.tomdoyletalk.com/2008/10/28/simple-image-gallery-slideshow-with-scriptaculous-and-prototype/
 *	
 *	Published [16/12/08]:
 *	http://www.icommunicate.co.uk/articles/all/simple_slide_show_for_prototype_scriptaculous_38/	
 *
 *	Changes: Basically made it an object so that you can run multiple instances and so that
 *			 it doesn't get interfered with by other scripts on the page.
 */

var iSlideShow = new Class.create();

iSlideShow.prototype = {
	
	initialize : function(oArgs){
		this.wait 			= oArgs.wait ? oArgs.wait : 4000;
		this.start 			= oArgs.start ? oArgs.start : 0;
		this.duration		= oArgs.duration ? oArgs.duration : 0.3;
		this.autostart		= (typeof(oArgs.autostart)=='undefined') ? true : oArgs.autostart;
		this.slides 		= oArgs.slides;
		this.iImageId		= this.start;
		this.interval       = null;
		if (this.slides) {
			this.numOfImages	= this.slides.length;
			if (!this.numOfImages)
				alert('No slides?');
		}
		if (this.autostart)
			this.startSlideShow();
	},
	
	//Swap images and update buttons
	swapImage: function(x, y){
		//Cancel any previous effects on elements that have not finished
		var slideX = this.slides[x];
		var slideY = this.slides[y];
		var queue = Effect.Queues.get('banner').effects;
		queue.each(function(effect) {
			if (effect.element.id == slideX)
				effect.cancel();
			else if (effect.element.id == slideY)
				effect.cancel();
			else if (effect.element.id == 'imgBannerBtn' + (x+1) + 'a')
				effect.cancel();
			else if (effect.element.id == 'imgBannerBtn' + (y+1))
				effect.cancel();
			else if (effect.element.id == 'imgBannerBtn' + (x+1))
				effect.cancel();
			else if (effect.element.id == 'imgBannerBtn' + (y+1) + 'a')
				effect.cancel();
		});

		new Effect.Appear(this.slides[x], {queue: {scope: 'banner'}, duration: this.duration, from: 0.0, to: 1.0});
		new Effect.Fade(this.slides[y], {queue: {scope: 'banner'}, duration: this.duration, from: 1.0, to: 0.0});
		new Effect.Appear('imgBannerBtn' + (x+1) + 'a', {queue: {scope: 'banner'}, duration: this.duration, from: 0.0, to: 1.0}); 
		new Effect.Appear('imgBannerBtn' + (y+1), {queue: {scope: 'banner'}, duration: this.duration, from: 0.0, to: 1.0});
		new Effect.Fade('imgBannerBtn' + (x+1), {queue: {scope: 'banner'}, duration: this.duration, from: 1.0, to: 0.0});
		new Effect.Fade('imgBannerBtn' + (y+1) + 'a', {queue: {scope: 'banner'}, duration: this.duration, from: 1.0, to: 0.0});

		/*new Effect.Parallel([
 			new Effect.Appear(this.slides[x], {sync: true, duration: this.duration}),
 			new Effect.Fade(this.slides[y], {sync: true, duration: this.duration}),
 			new Effect.Appear('imgBannerBtn' + (x+1) + 'a', {sync: true, duration: this.duration}), 
 			new Effect.Appear('imgBannerBtn' + (y+1), {sync: true, duration: this.duration}),
 			new Effect.Fade('imgBannerBtn' + (x+1), {sync: true, duration: this.duration}),
 			new Effect.Fade('imgBannerBtn' + (y+1) + 'a', {sync: true, duration: this.duration})
 			], {duration: this.duration, queue: {scope: 'banner', position: 'end'}});*/
	},

	//Start slideshow
	startSlideShow: function(){
		if (!this.interval)
			this.interval = setInterval(this.play.bind(this),this.wait);						
	},

	play: function(){
		var imageShow, imageHide;

		imageShow = this.iImageId+1;
		imageHide = this.iImageId;

		if (imageShow == this.numOfImages) {
			this.swapImage(0,imageHide);	
			this.iImageId = 0;
		} else {
			this.swapImage(imageShow,imageHide);			
			this.iImageId++;
		}
	},

	update: function(imageId){
		clearInterval(this.interval);
		this.interval = setInterval(this.play.bind(this),this.wait);

		var imageHide;
		imageHide = this.iImageId;
		
		if ((imageId-1) != imageHide){
			this.swapImage((imageId-1),imageHide);			
			this.iImageId = (imageId-1);
		}
	}
};





var DDSPEED = 5;
var DDTIMER = 15;	


// main function to handle the mouse events //
function ddMenu(headerDiv,d){
	var h = headerDiv;
	var id = headerDiv.id.split('-')[0];
	var c = $(id + '-ddcontent');
  clearInterval(c.timer);
  if(d == 1){
    clearTimeout(h.timer);
    if(c.maxh && c.maxh <= c.offsetHeight){return;}
    else if(!c.maxh){
      c.style.display = 'block';
      c.style.height = 'auto';
      c.maxh = c.offsetHeight;
      c.style.height = '0px';
    }
    c.timer = setInterval(function(){ddSlide(c,1);},DDTIMER);
  }else{
    h.timer = setTimeout(function(){ddCollapse(c);},50);
  }
}

// collapse the menu //
function ddCollapse(c){
  c.timer = setInterval(function(){ddSlide(c,-1)},DDTIMER);
}

// cancel the collapse if a user rolls over the dropdown //
function cancelHide(contentDiv){
	var c = contentDiv;
	var id = contentDiv.id.split('-')[0];
	var h = $(id + '-ddheader');
  clearTimeout(h.timer);
  clearInterval(c.timer);
  if(c.offsetHeight < c.maxh){
    c.timer = setInterval(function(){ddSlide(c,1)},DDTIMER);
  }
}

// incrementally expand/contract the dropdown and change the opacity //
function ddSlide(c,d){
		
  var currh = c.offsetHeight;
  var dist;
  if(d == 1){
    dist = (Math.round((c.maxh - currh) / DDSPEED));
  }else{
    dist = (Math.round(currh / DDSPEED));
  }
  if(dist <= 1 && d == 1){
    dist = 1;
  }
  c.style.height = currh + (dist * d) + 'px';
  c.style.opacity = currh / c.maxh;
  c.style.filter = 'alpha(opacity=' + (currh * 100 / c.maxh) + ')';
  if((currh < 2 && d != 1) || (currh > (c.maxh - 2) && d == 1)){
    clearInterval(c.timer);
  }
}


function updateCalendar(path, date)
{

	//Display loading message to user
	$('interior').update(loadingHTML(true));

	// Body Content
	new Ajax.Updater('interior','/aem/interiorAjax/path:' + path + '/sort:' + date, {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'interior']});

}

function populateStats(id, type, period, date, path1, path2, path3, path4, path5, host, browserplatform, browsername, browserversion)
{

	$(id).update(loadingHTML(true));
	
	if (! period)
		period = '';
	
	if (! date)
		date = '';
	
	if (! path1)
		path1 = '';

	if (! path2)
		path2 = '';
	
	if (! path3)
		path3 = '';
	
	if (! path4)
		path4 = '';
	
	if (! path5)
		path5 = '';
	
	if (! host)
		host = '';
	
	if (! browserplatform)
		browserplatform = '';
	
	if (! browsername)
		browsername = '';

	if (! browserversion)
		browserversion = '';

	params = '/type:' + type;
	params += '/date:' + date + '/period:' + period;
	params += '/path1:' + path1 + '/path2:' + path2 + '/path3:' + path3 + '/path4:' + path4 + '/path5:' + path5;
	params += '/host:' + host;
	params += '/browserplatform:' + browserplatform + '/browsername:' + browsername + '/browserversion:' + browserversion;

	new Ajax.Updater(id, '/stats/view' + params, {asynchronous:true, evalScripts:true});	
	

	var divs = $('stats_button_container').select('div[class="stats_button_active"]');
	
	divs.each(function(d)
	{
		d.className = 'stats_button';
	});
	

	
	if (type == 'date')
		$('stats_date_link').className = 'stats_button_active';
	else if (type == 'host')
		$('stats_visitor_link').className = 'stats_button_active';
	else if (type == 'browser')
		$('stats_browser_link').className = 'stats_button_active';
	else if (type == 'section')
		$('stats_page_link').className = 'stats_button_active';

		
		
}



function togglePersonnel(id)
{
	var divs = $('personnel_container').select('div[class="person_link_active"]');
	divs.each(function(d)
	{
		d.className = 'person_link';
	});	
	
	divs = $('personnel_container').select('div[class="person_details"]');
	divs.each(function(d)
	{
		if (d.visible() && d.id != id)
			Effect.toggle(d, 'slide', { delay: 0.0, duration: 0.2 });
		
		
	});
	
	

	Effect.toggle(id, 'slide', { delay: 0.0, duration: 0.2 });

	$(id + '_link').className = 'person_link_active';

	return false;
}

function GetIEVersion() {
    var rv = -1; // Return value assumes failure.
    if (navigator.appName == 'Microsoft Internet Explorer') {
        var ua = navigator.userAgent;
        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null)
            rv = parseFloat(RegExp.$1);
    }
    return rv;
}

/* * * * * * * * * * * * 
 * Manage New Employees
 * * * * * * * * * * * */

function togglePassword(sel, type)
{
	if (type == 1)
		type = '';
	else
		type = 'Edit';
	switch(sel.options[sel.selectedIndex].value)
	{
		case "1": case "2":
			if (type == 'Edit')
			{
				$('divEditPassword').hide();
				$('divEditPassword2').hide();
			}
			$('UserPassword' + type).disable();
			$('UserPassword' + type + '2').disable();
			$('UserPassword' + type).className = 'disabled';
			$('UserPassword' + type + '2').className = 'disabled';
			break;
		default:
			$('UserPassword' + type).enable();
			$('UserPassword' + type + '2').enable();
			$('UserPassword' + type).className = 'addUser';
			$('UserPassword' + type + '2').className = 'addUser';
			if (type == 'Edit')
			{
				$('divEditPassword').show();
				$('divEditPassword2').show();
			}
	}	
}

function addUser()
{
	var login = $('UserLogin').value;
	var sel = $('UserAccesslevel');
	var level = sel.options[sel.selectedIndex].value;
	if (level == 1 || level == 2)
	{
		$('UserPassword').value = '';
		$('UserPassword2').value = '';
	}
	$('formAdd').request(
	{
		onCreate:function() {toggleWait('Add', false);toggleForm('Add', false);},
		onSuccess:function(transport) {checkAdd(login, transport.responseText);},
		onFailure:function() {checkAdd(login, 1);}
    });
	return false;
}

function toggleWait(type, undo)
{
	var divId = 'div' + type + 'Wait';
	if (!undo)
	{
		$('btn' + type).insert({before: new Element('div', {id: divId, style: 'line-height: 20px;'})});
		$(divId).update('<img alt="Wait" src="/themed/default/img/wait.gif" style="vertical-align: middle;"/><span style="font-size: 8pt;"> &nbsp;' + (type == 'Add' ? type : 'Sav') + 'ing&#8230;</span>');
		$('btn' + type).hide();
		if (type == 'Edit')
			$('btnCancel').hide();
	}
	else
	{
		$(divId).remove();
		$('btn' + type).show();
		if (type == 'Edit')
			$('btnCancel').show();
	}
}

function toggleForm(type, enable)
{
	$('div' + type + 'User').select('input', 'select').each(function(inp)
	{
		if (!inp.hasAttribute('disabled') && inp.getAttribute('type') != 'submit' && inp.getAttribute('type') != 'button')
		{
			if (!enable)
			{
				inp.readOnly = true;
				inp.className = 'disabled';
			}
			else
			{
				inp.readOnly = false;
				inp.className = 'addUser';
			}
		}
	});	
}

function checkAdd(login, result)
{
	var code = result.substr(0,1);
	switch(code)
	{
		case "1":
			toggleWait('Add', true);
			toggleForm('Add', true);
			alert('Error: User "' + login + '"could not be added. Please try again.');
			break;
		case "2": case "3":
			toggleWait('Add', true);
			toggleForm('Add', true);
			if (code == "3")
				clearPasswords('');
			$('divResults').update(result);
			break;
		default:
			var tbody = $('bodyUserList');
			var className = '';
			var eColor = '#FFFFFF';
			if (!tbody.firstDescendant().hasClassName('roweven'))
			{
				className = 'roweven';
				eColor = '#F2F2F2';
			}
			else
				className = 'rowodd';

			var tr = new Element('tr', {id: 'trAdded'});
			$('bodyUserList').insert({top: tr});
			tr.className = className;
			tr.update(result);
			removeSortClass();
			//Effect.Appear does not work on tr in IE
			//Effect.Appear(tr, {duration: 0.5, afterFinish: function(){resetForm(); toggleWait('Add', true); /*alert('Successful: User "' + login + '" added.');*/ new Effect.Highlight(tr, {duration: 0.5, startcolor: '#6AFB92', endcolor: eColor, restorecolor: eColor})}});
			var tdArr = tr.childElements();
			for (var i = 0; i < tdArr.length; i++)
			{
				if (i == tdArr.length - 1)
					Effect.Appear(tdArr[i], {duration: 0.5, afterFinish: function(){checkTableHeight(); resetForm(); toggleWait('Add', true); clearTdColor(tdArr, eColor); /*alert('Successful: User "' + login + '" added.');*/}});
				else
					Effect.Appear(tdArr[i], {duration: 0.5});
			}
	}
}

function removeSortClass()
{
	$('sortable-table-0-head').select('th').each(function(th)
		{
			th.removeClassName('sortdesc');
			th.removeClassName('sortasc');
		});
}

function checkTableHeight()
{
	var div = $('sortable-table-0-body');
	var divWidth = div.getDimensions().width;
	var divHeight = 400;
	if($('sortable-table-0').offsetHeight - divHeight > 0)
		div.setStyle({overflowY: 'auto', overflowX: 'hidden', height: divHeight + 'px'});
	else
		div.setStyle({overflowY: 'hidden', overflowX: 'hidden', height: ''});
}

function clearTdColor(tds, eColor)
{
	tds.each(function(td){new Effect.Highlight(td, {duration: 0.5, startcolor: '#6AFB92', endcolor: eColor, restorecolor: eColor, afterFinish: function(){td.style.backgroundColor = '';}});});
}

function clearPasswords(type)
{
	$('UserPassword' + type).value = '';
	$('UserPassword' + type + '2').value = '';
}

function resetForm()
{
	$('divAddUser').select('input', 'select').each(function(inp)
	{
		var type = inp.type.toLowerCase();
		if (type != 'submit')
		{
			inp.readOnly = false;
			inp.className = 'addUser';
			switch(type)
			{
				case "text": case "password":
					inp.value = '';
					inp.enable();
					break;
				default:
					inp.selectedIndex = 0;
			}
		}
	});
}

function deleteUser(id)
{
	var divLogin = $('divLogin' + id);
	var login = divLogin.innerHTML;
	var tr = divLogin.parentNode.parentNode;
	toggleHighlight(tr, true, 2);
	if (confirm('Are you sure you want to delete user "' + login + '"?'))
	{
		new Ajax.Updater('divResults','/users/delete/' + id,
		{
			asynchronous:true,
			evalScripts:true,
			onCreate:function() {deleteWait(id, false);},
			onSuccess:function(transport) {checkDelete(id, login, transport.responseText);},
			onFailure:function() {checkDelete(id, login, 2);},
			requestHeaders:['X-Update', 'divResults']
		});
	}
	else
		toggleHighlight(tr, false, 2);
}

function checkDelete(id, login, result)
{
	switch(result.substr(0,1))
	{
		case "1":
			deleteWait(id, true);
			alert('Error: User "' + login + '" is invalid.');
			break;
		case "2":
			deleteWait(id, true);
			alert('Error: User "' + login + '"could not be deleted. Please try again.');
			break;
		default:
			var tr = $('divDeleteWait' + id).parentNode.parentNode;	
			//Effect.Fade(tr, {duration: 0.5, afterFinish: function(){updateRows(tr); /*alert('Successful: User "' + login + '" deleted.');*/}});
			var tdArr = tr.childElements();
			for (var i = 0; i < tdArr.length; i++)
			{
				if (i == tdArr.length - 1)
				{
					var color = '#FFFFFF';
					if (tr.hasClassName('roweven'))
						color = '#F2F2F2';
					new Effect.Parallel(
						[
							new Effect.Fade(tdArr[i], {duration: 0.5}),
							new Effect.Highlight(tr, {duration: 0.5, startcolor: '#E77471', endcolor: color, restorecolor: color})
						],
						{duration: 0.5, afterFinish: function(){updateRows(tr); /*tr.remove();*/ checkTableHeight();/*alert('Successful: User "' + login + '" deleted.');*/}});
				}
				else
					Effect.Fade(tdArr[i], {duration: 0.5});
			}
	}
}

function toggleHighlight(tr, highlight, type, id)
{
	if (highlight)
	{
		var sColor = (tr.hasClassName == 'roweven' ? '#F2F2F2' : '#FFFFFF');
		if (type == 0)
			tr.style.backgroundColor = '#6AFB92';
		else if (type == 1)
			tr.style.backgroundColor = '#FFFF99';
		else
			tr.style.backgroundColor = '#E77471';
	}
	else
		tr.style.backgroundColor = '';
}

function updateRows(tr)
{
	tr.nextSiblings().each(function(row)
	{
		if (row.hasClassName('roweven'))
			row.className = 'rowodd';
		else
			row.className = 'roweven';
	});
	tr.remove();
}

function deleteWait(id, undo)
{
	var divId = 'divDeleteWait' + id;
	var editId = $('UserIdEdit').value;
	if (!undo)
	{
		$('aDelete' + id).insert({before: new Element('div', {id: divId, style: 'height: 16px; line-height: 14px;'})});
		$(divId).update('<img alt="Wait" src="/themed/default/img/wait.gif" style="vertical-align: middle;"/><span style="font-size: 8pt;"> &nbsp;Deleting&#8230;</span>');
		$('aDelete' + id).hide();
		$('aEdit' + id).hide();
		try
		{
			$('aReset' + id).hide();
		}
		catch(e){}
		if (id == editId)
			$('divEditUser').hide();
	}
	else
	{
		$(divId).remove();
		$('aDelete' + id).show();
		$('aEdit' + id).show();
		try
		{
			$('aReset' + id).show();
		}
		catch(e){}
		if (id == editId)
			$('divEditUser').show();
	}
}

function editUser(id)
{
	var editId = $('UserIdEdit').value;
	var divLogin = $('divLogin' + editId);
	var tr;
	if (divLogin != null)
	{
		tr = divLogin.parentNode.parentNode;
		if (id != editId)
			try{toggleHighlight(tr, false, 1);}catch(e){}
	}

	//Check if user is already being edited
	var formVisible = $('divEditUser').visible();
	if (formVisible && $('divEditLogin').visible() && id == editId)
		return;

	//Setup form
	divLogin = $('divLogin' + id);
	tr = divLogin.parentNode.parentNode;
	toggleHighlight(tr, true, 1);
	var login = divLogin.innerHTML;
	var level = $('divLevel' + id).innerHTML;
	var html = 'Edit User: &nbsp;<span style="font-weight: normal;">' + login + '</span><br/>' +
	'<span style="font-size: 8pt; font-weight: normal;">Note: &nbsp;Password will be cleared if changing access level from "New employee."</span>';
	$('editTitle').innerHTML = html;
	$('UserIdEdit').value = id;
	$('divEditLevel').show();
	$('divEditLogin').show();
	$('divEditPassword').hide();
	$('divEditPassword2').hide();
	$('UserPasswordEdit').value = '';
	$('UserPasswordEdit2').value = '';
	$('UserPasswordEdit2').disable();
	$('UserPasswordEdit').disable();
	$('UserPasswordEdit2').disable();
	$('UserAccesslevelEdit').enable();
	$('UserLoginEdit').enable();
	$('UserLoginEdit').value = login;
	$(level.replace(' ', '')).selected = true;
	var sel = $('UserAccesslevelEdit');
	if (level == "New employee")
		sel.onchange = '';
	else
		sel.onchange = function(){togglePassword(this, 2);};

	//Display form
	if (!formVisible)
		$('divEditUser').show();
		//new Effect.Appear($('divEditUser'), {duration: 0.5});
}

function cancelEdit()
{
	//new Effect.Fade($('divEditUser'), {duration: 0.5});
	$('divEditUser').hide();
	var editId = $('UserIdEdit').value;
	var divLogin = $('divLogin' + editId);
	var tr = divLogin.parentNode.parentNode;
	toggleHighlight(tr, false, 1);
}

function saveEdit()
{
	var id = $('UserIdEdit').value;
	var login = $('UserLoginEdit').value;
	var sel = $('UserAccesslevelEdit');
	var level = sel.options[sel.selectedIndex].text;
	var origLogin = $('divLogin' + id).innerHTML;
	var origLevel = $('divLevel' + id).innerHTML;
	//Check if any changes have been made
	if ($('divEditLogin').visible() && login == origLogin && level == origLevel)
	{
		alert('No changes have been made. Data will not be saved.');
		return false;
	}
	
	$('formEdit').request(
	{
		onCreate:function() {toggleWait('Edit', false);toggleForm('Edit', false);},
		onSuccess:function(transport) {checkSave(id, login, transport.responseText);},
		onFailure:function() {checkSave(id, login, 1);}
    });
	return false;
}

function checkSave(id, login, result)
{
	var code = result.substr(0,1);
	switch(code)
	{
		case "1":
			toggleWait('Edit', true);
			toggleForm('Edit', true);
			alert('Error: User "' + login + '"could not be saved. Please try again.');
			break;
		case "2": case "3":
			toggleWait('Edit', true);
			toggleForm('Edit', true);
			if (code == "3")
				clearPasswords('Edit');
			$('divResults').update(result);
			break;
		case "4": default:
			var tr = $('divLogin' + id).parentNode.parentNode;
			if (code != "4")
			{
				removeSortClass();
				tr.update(result);
			}
			var color = '#FFFFFF';
			if (tr.hasClassName('roweven'))
				color = '#F2F2F2';
			new Effect.Parallel(
				[
					new Effect.Fade($('divEditUser'), {duration: 1.0}),
					new Effect.Highlight(tr, {duration: 1.0, startcolor: '#FFFF99', endcolor: color, restorecolor: color})
				],
				{duration: 1.0, afterFinish: function(){toggleWait('Edit', true); toggleForm('Edit', true); tr.style.backgroundColor = ''; /*alert('Successful: User "' + login + '" saved.');*/}});
	}
}

function resetPassword(id)
{
	var editId = $('UserIdEdit').value;
	var divLogin = $('divLogin' + editId);
	var tr;
	if (divLogin != null)
	{
		tr = divLogin.parentNode.parentNode;
		if (id != editId)
			try{toggleHighlight(tr, false, 1);}catch(e){}
	}

	//Check if user is already being edited
	var formVisible = $('divEditUser').visible();
	if (formVisible && !$('divEditLogin').visible() && id == editId)
		return;

	//Setup form
	divLogin = $('divLogin' + id);
	tr = divLogin.parentNode.parentNode;
	toggleHighlight(tr, true, 1);
	var login = $('divLogin' + id).innerHTML;
	var html = 'Reset Password - User: &nbsp;<span style="font-weight: normal;">' + login + '</span>';
	$('editTitle').innerHTML = html;
	$('UserIdEdit').value = id;
	$('divEditLevel').hide();
	$('divEditLogin').hide();
	$('UserPasswordEdit').enable();
	$('UserPasswordEdit2').enable();
	$('UserPasswordEdit').value = '';
	$('UserPasswordEdit2').value = '';
	$('divEditPassword').show();
	$('divEditPassword2').show();
	$('UserAccesslevelEdit').disable();
	$('UserLoginEdit').disable();

	//Display form
	if (!formVisible)
		$('divEditUser').show();
		//new Effect.Appear($('divEditUser'), {duration: 0.5});
}