var ns4 = (document.layers) ? true : false;
var ns6 = (document.getElementById) ? true : false;
var ie4 = (document.all) ? true : false;
var ie5 = false;
if (ie4) {
	if ((navigator.userAgent.indexOf("MSIE 5") > 0)
			|| (navigator.userAgent.indexOf("MSIE 6") > 0)) {
		ie5 = true;
	}
	if (ns6) {
		ns6 = false;
	}
}
var chatId;

function isUndefined(value) {   
    var undef;   
    return value == undef; 
}
function saveUsername(theForm,path) {
	var expires = new Date();
	//expires.setTime(expires.getTime() + 24 * 30 * 60 * 60 * 1000); // sets it for approx 30 days.
	//setCookie("username", theForm.j_username.value, expires,path,path);
	createCookie("username", theForm.j_username.value,30);	
	createCookie("password",theForm.j_password.value,30);
	createCookie("rememberMe",theForm.rememberMe.checked,30);	
}
/* This function is used to set cookies */
function setCookie(name, value, expires, path, domain, secure) {
	document.cookie = name + "=" + escape(value)
			+ ((expires) ? "; expires=" + expires.toGMTString() : "")
			+ ((path) ? "; path=" + path : "")
			+ ((domain) ? "; domain=" + domain : "")
			+ ((secure) ? "; secure" : "");
}
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();		
	}
	else var expires = "";	
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}


/* This function is used to get cookies */
function getCookie(name) {
	var prefix = name + "="
	var start = document.cookie.indexOf(prefix)
	if (start == -1) {
		return null;
	}
	var end = document.cookie.indexOf(";", start + prefix.length)
	if (end == -1) {
		end = document.cookie.length;
	}

	var value = document.cookie.substring(start + prefix.length, end)
	return unescape(value);
}

/* This function is used to delete cookies */
function deleteCookie(name, path, domain) {
	if (getCookie(name)) {
		document.cookie = name + "=" + ((path) ? "; path=" + path : "")
				+ ((domain) ? "; domain=" + domain : "")
				+ "; expires=Thu, 01-Jan-70 00:00:01 GMT";
	}
}

function removeHTMLTags(strInputCode) {	
	if (strInputCode) {
		/*
		 * This line is optional, it replaces escaped brackets with real ones,
		 * i.e. < is replaced with < and > is replaced with >
		 */
		strInputCode = strInputCode.replace(/&(lt|gt);/g,
		function(strMatch, p1) {
			return (p1 == "lt") ? "<" : ">";
		});
		strInputCode = strInputCode.replace(/&amp;nbsp;/g,' ');
		var strTagStrippedText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
		//var temp = strTagStrippedText.replace(/[\s(&amp;)]+$/g,'');
		//temp = temp.replace(/[\s(nbsp;)]+$/g,'');		
		return strTagStrippedText;
	}
}
function changeTime(begin) {
	startIndex = document.getElementById(begin).selectedIndex;
	document.getElementById('eventEndTime').selectedIndex = startIndex
}

function verifyTime(end) {
	startIndex = document.getElementById('eventStartTime').selectedIndex;
	endIndex = document.getElementById(end).selectedIndex;
	if (endIndex < startIndex) {
		alert("Your end time is before your start time.");
	}
}
function updateDiv(_objName, text) {
	var _obj = null;
	if (isIE || isNS6)
		_obj = document.getElementById(_objName);
	if (_obj) {
		_obj.innerHTML = text;
	}
}

function disableAlphas(e) {
	var keynum;
	var keychar;
	var numcheck;

	if (window.event) // IE
	{

		keynum = e.keyCode;
	} else if (e.which) // Netscape/Firefox/Opera
	{
		keynum = e.which;
	}
	if (keynum == 8) {
		return true;
	} else if (keynum < 47 || keynum > 57) {
		return false;
	}
	// keychar = String.fromCharCode(keynum);
	// numcheck = /\d/;
	// return numcheck.test(keychar);
}
function getWebCalDomain(str) {
	var webCalUrl = "webcal://";
	if (str == null || str.length == 0)
		return "";

	var i = str.indexOf("//");
	if (i > -1) {
		return webCalUrl + str.substring(i + 2, str.length);
	} else {
		return webCalUrl + str;
	}
}
imgout = new Image(9, 9);
imgin = new Image(9, 9);
imgout.src = "images/icons/down.gif";
imgin.src = "images/icons/right.gif";
function addInnerHtml(targetDivName) {
	var obj = $(targetDivName);
	if (obj) {
		var div = document.createElement('div');
		div.innerHTML = obj.innerHTML;
		obj.parentNode.insertBefore(div, obj);
		obj.remove();
	}
}

function turnOn(imgName) {
	if (document.images) {
		imgOn = eval(imgName + "On.src");
		document[imgName].src = imgOn;
	}
}

function turnOff(imgName) {
	if (document.images) {
		imgOff = eval(imgName + "Off.src");
		document[imgName].src = imgOff;
	}
}
function changeImageToActive(imgName) {
	if (document.images) {
		imgOn = eval(imgName + "On.src");
		document[imgName].src = imgOn;
		document[imgName].onmouseover = "";
		document[imgName].onmouseout = "";
	}
}
function replaceImageToggleIt(onOff, imgName) {

	if (document.getElementById) { // DOM3 = IE5, NS6
		if (onOff == "on") {
			filter(("img" + id), 'imgin');
		} else {
			filter(("img" + id), 'imgout');
		}
		Effect.toggle(id, 'slide');
	} else {
		if (document.layers) {
			if (document.id.display == "none") {
				filter(("img" + id), 'imgin');
			} else {
				filter(("img" + id), 'imgout');
			}
			Effect.toggle(id, 'slide');
		} else {
			if (document.all.id.style.visibility == "none") {
			} else {
				filter(("img" + id), 'imgout');
			}
			Effect.toggle(id, 'slide');
		}
	}
}
function filter(imagename, objectsrc) {
	if (document.images) {
		document.images[imagename].src = eval(objectsrc + ".src");
	}
}
// show OR hide funtion depends on if element is shown or hidden
function toggleIt(id) {
	if (document.getElementById) { // DOM3 = IE5, NS6
		if (document.getElementById(id).style.display == "none") {
			filter(("img" + id), 'imgin');
		} else {
			filter(("img" + id), 'imgout');
		}
		Effect.toggle(id, 'slide');
	} else {
		if (document.layers) {
			if (document.id.display == "none") {
				filter(("img" + id), 'imgin');
			} else {
				filter(("img" + id), 'imgout');
			}
			Effect.toggle(id, 'slide');
		} else {
			if (document.all.id.style.visibility == "none") {
			} else {
				filter(("img" + id), 'imgout');
			}
			Effect.toggle(id, 'slide');
		}
	}
}
function hrefOnClickAddClass(currentSelectedHref) {
	$$("#mycustomscrollleftsmall a").each( function(a) {
		var temp = a.innerHTML;
		temp=temp.replace(/&amp;/, "");		
		if (a.hasClassName('selected') && !temp.match(currentSelectedHref)) {
			a.className = "";
		}
		if (temp.match(currentSelectedHref)) {
			a.className = "selected";
		}
	});
}
function searchPopupSerialScroll(currentSelectedHref) {
	var previousSelectedHref = "";
	var currPos = 0;
	var nextPos = 0;
	var indexPos = 0;
	var isSelf = false;
	$$("#searchnav a").each(
			function(a) {
				var temp = a.innerHTML;
				if (a.hasClassName('selected')
						&& temp.match(currentSelectedHref)) {
					isSelf = true;
				} else {
					if (a.hasClassName('selected')
							&& !temp.match(currentSelectedHref)) {
						currPos = indexPos;
						a.className = "";
						previousSelectedHref = a.innerHTML;
					}
					if (temp.match(currentSelectedHref)) {
						a.className = "selected";
						nextPos = indexPos;
					}
				}
				indexPos = indexPos + 1;
			});
	var factor = (currPos - nextPos) * 800;
	if (isSelf || factor == 0)
		return;
	if (factor >= 5600) {
		factor = 4800;
	} else if (factor < -5600) {
		factor = -4800;
	}
	new Effect.MoveBy('scrollContainer', 0, factor, {
		duration :0.4,
		transition :Effect.Transitions.sinoidal
	});
}

/*
 * protoload 0.1 beta by Andreas Kalsch last change: 09.07.2007
 * 
 * This simple piece of code automates the creating of Ajax loading symbols. The
 * loading symbol covers an HTML element with correct position and size -
 * example: $('myElement').startWaiting() and $('myElement').stopWaiting()
 */

Protoload = {
	// the script to wait this amount of msecs until it shows the loading
	// element
	timeUntilShow :250,

	// opacity of loading element
	opacity :0.85,

	// Start waiting status - show loading element
	startWaiting : function(element, className, timeUntilShow) {
		if (typeof element == 'string')
			element = document.getElementById(element);
		if (className == undefined)
			className = 'waiting';
		if (timeUntilShow == undefined)
			timeUntilShow = Protoload.timeUntilShow;
		element._waiting = true;
		if (!element._loading) {
			var e = document.createElement('div');
			(element.offsetParent || document.body)
					.appendChild(element._loading = e);
			element.parentNode.appendChild(element._loading = e);
			e.style.position = 'absolute';
			try {
				e.style.opacity = Protoload.opacity;
			} catch (e) {
			}
			try {
				e.style.MozOpacity = Protoload.opacity;
			} catch (e) {
			}
			try {
				e.style.filter = 'alpha(opacity=' + Math
						.round(Protoload.opacity * 100) + ')';
			} catch (e) {
			}
			try {
				e.style.KhtmlOpacity = Protoload.opacity;
			} catch (e) {
			}

			/*******************************************************************
			 * var zIndex = 0; if (window.UI) if (UI.zIndex) zIndex =
			 * ++UI.zIndex; if (!zIndex) zIndex = ++Protoload._zIndex;
			 * e.style.zIndex = zIndex;
			 ******************************************************************/
		}
		element._loading.className = className;
		window
				.setTimeout(( function() {
					if (this._waiting) {
						if (Prototype.Browser.IE) {
							var delta = [ 0, 0 ];
							var parent = null;
							var p = this.viewportOffset();
							// delta [0,0] will do fine with position: fixed
							// elements,
						// position:absolute needs offsetParent deltas
						if (Element.getStyle(element, 'position') == 'absolute') {
							parent = this.getOffsetParent();
							delta = parent.viewportOffset();
						}

						// correct by body offsets (fixes Safari)
						if (parent == document.body) {
							delta[0] -= document.body.offsetLeft;
							delta[1] -= document.body.offsetTop;
						}
						var left = p[0] - delta[0], top = p[1] - delta[1], width = this.offsetWidth, height = this.offsetHeight, l = element._loading;
						l.style.left = left + 'px';
						l.style.top = top + 'px';
						l.style.width = width + 'px';
						l.style.height = height + 'px';
						l.style.display = 'inline';
					} else {
						var left = this.offsetLeft, top = this.offsetTop, width = this.offsetWidth, height = this.offsetHeight, l = this._loading;
						l.clonePosition(this);
						/*******************************************************
						 * l.style.left = left+'px'; l.style.top = top+'px';
						 * l.style.width = width+'px'; l.style.height =
						 * height+'px'; l.style.display = 'inline';
						 ******************************************************/
					}
				}
			}).bind(element), timeUntilShow);
	},

	// Stop waiting status - hide loading element
	stopWaiting : function(element) {
		if (element._waiting) {
			element._waiting = false;
			element._loading.parentNode.removeChild(element._loading);
			element._loading = null;
		}
	}/*
		 * ,
		 * 
		 * _zIndex: 1000000
		 */
};

/* */

function bigWaitingProcess(elementName) {
	$(elementName).startWaiting('bigWaiting');
}
function waitingProcess(elementName) {
	$(elementName).startWaiting('waiting');
}
function stopWaitingProcess(elementName) {
	$(elementName).stopWaiting();
}
function disableButton(idName) {
	waitingProcess(idName);
}
var defaultEmptyOK = false
// BOI, followed by one or more characters, followed by @,
// followed by one or more characters, followed by .,
// followed by one or more characters, followed by EOI.
var reEmail = /^.+\@.+\..+$/

// Check whether string s is empty.

function isEmpty(s) {
	return ((s == null) || (s.length == 0))
}
// Returns true if string s is empty or
// whitespace characters only.

function isWhitespace(s)

{ // Is s empty?
	return (isEmpty(s) || reWhitespace.test(s));
}
// isEmail (STRING s [, BOOLEAN emptyOK])
// 
// Email address must be of form a@b.c -- in other words:
// * there must be at least one character before the @
// * there must be at least one character before and after the .
// * the characters @ and . are both required
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isEmail(s) {
	if (isEmpty(s))
		if (isEmail.arguments.length == 1)
			return defaultEmptyOK;
		else
			return (isEmail.arguments[1] == true);
	else {
		return reEmail.test(s)
	}
}
// Notify user that contents of field theField are invalid.
// String s describes expected contents of theField.value.
// Put select theField, pu focus in it, and return false.

function warnInvalid(theField, s) {
	theField.focus();
	theField.select();
	alert(s);
	return false;
}
// checkEmail (TEXTFIELD theField [, BOOLEAN emptyOK==false])
//
// Check that string theField.value is a valid Email.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function checkEmail_unused(theField, emptyOK) {
	if (checkEmail.arguments.length == 1)
		emptyOK = defaultEmptyOK;
	if ((emptyOK == true) && (isEmpty(theField.value)))
		return true;
	else if (!isEmail(theField.value, false))
		return warnInvalid(theField, iEmail);
	else
		return true;
}

function checkEmail(email) {
	emailValue = document.getElementById(email).value;
	if (emailValue.length > 0) {
		var filter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
		if (filter.test(emailValue)) {
			return true;
		} else {
			document.getElementById(email).select();
			alert("E-mail address format is invalid. Please reenter. Example: myname@aol.com");
			return false;
		}
	}
	return true;
}
function getChatText() {
	if (!isUndefined(chatId)) {
		if (receiveRequest.readyState == 4 || receiveRequest.readyState == 0) {
			receiveRequest.open("GET", 'ajaxGetChatMessage.do?chatId=' + chatId
					+ '&msgId=' + lastMsgId + '&un=' + username, true);
			receiveRequest.onreadystatechange = handleReceiveChat;
			receiveRequest.send(null);
		}
	} else {
		mTimer = setTimeout('getChatText();', 2000); // Refresh our chat in 2 seconds
	}
}

function handleReceiveChat() {
	if (receiveRequest.readyState == 4) {
		// Get a reference to our chat container div for easy access
		var chat_div = document.getElementById('chatMessagesDiv');
		// Get the AJAX response and run the JavaScript evaluation function
		// on it to turn it into a usable object. Notice since we are passing
		// in the JSON value as a string we need to wrap it in parentheses
		//alert(receiveRequest.responseText);
		if (receiveRequest.responseText!=0) {
		    var response = eval("(" + receiveRequest.responseText + ")");
			for (i = 0; i < response.messages.message.length; i++) {
				chat_div.innerHTML += '<span class="receiver">' + response.messages.message[i].user + '</span>';
				// chat_div.innerHTML += '&nbsp;&nbsp;<font class="chat_time">'
				// + response.messages.message[i].time + '</font><br />';
				chat_div.innerHTML += '<span class="receiverMessage">' + response.messages.message[i].text + '</span><br />';
				chat_div.scrollTop = chat_div.scrollHeight;
				lastMsgId = response.messages.message[i].id;
			}
		}
		mTimer = setTimeout('getChatText();', 2000); // Refresh our chat in 2
														// seconds
	}
}

function checkEnter(e) { // e is event object passed from function invocation
	var characterCode;// literal character code will be stored in this
						// variable

	if (e && e.which) { // if which property of event object is supported (NN4)
		e = e
		characterCode = e.which // character code is contained in NN4's which
								// property
	} else {
		e = event
		characterCode = e.keyCode // character code is contained in IE's
									// keyCode property
	}

	if (characterCode == 13) { // if generated character code is equal to ascii
								// 13 (if enter key)
		sendchatMessage()// submit the form
		return false
	} else {
		return true
	}

}
function sendchatMessage() {
	username = document.getElementById('usernameId').value;
	var message = document.getElementById('inputMessage').value;
	var currentMessageBlock = document.getElementById('chatMessagesDiv');
	var url = 'ajaxSendChatMessage.do';
	var pars = 'username=' + username + '&' + 'message=' + message + '&'
			+ 'id=' + chatId;
	var myAjax = new Ajax.Request(
			url,
			{
				method :'get',
				parameters :pars,
				onComplete : function(request) {
					document.getElementById('inputMessage').value = '';
					chatId = request.responseText;
					currentMessageBlock.innerHTML += '<span class="sender">me</span>:&nbsp;<span class="senderMessage">' + message + '</span><br/>';
				},
				evalScript :true
			});
}
function HideContent(d) {
	if (d.length < 1) {
		return;
	}
	document.getElementById(d).style.display = "none";
}
function ShowContent(d) {
	if (d.length < 1) {
		return;
	}
	var dd = document.getElementById(d);
	AssignPosition(dd);
	dd.style.display = "block";
}

function highlightFormElements() {
    // add input box highlighting
    addFocusHandlers(document.getElementsByTagName("input"));
    addFocusHandlers(document.getElementsByTagName("textarea"));
}

function addFocusHandlers(elements) {
    for (i=0; i < elements.length; i++) {
        if (elements[i].type != "button" && elements[i].type != "submit" &&
            elements[i].type != "reset" && elements[i].type != "checkbox" && elements[i].type != "radio") {
            if (!elements[i].getAttribute('readonly') && !elements[i].getAttribute('disabled')) {
                elements[i].onfocus=function() {this.style.backgroundColor='#ffd';this.select()};
                elements[i].onmouseover=function() {this.style.backgroundColor='#ffd'};
                elements[i].onblur=function() {this.style.backgroundColor='';}
                elements[i].onmouseout=function() {this.style.backgroundColor='';}
            }
        }
    }
}