//Add custom startsWith function to String
String.prototype.startsWith = function(str){
	return (this.match("^"+str)==str)
}

//Add custom endsWith function to String
String.prototype.endsWith = function(str){
	return (this.match(str+"$")==str)
}

String.prototype.isNumeric = function(){
	var ValidChars = "0123456789.";
	var IsNumber=true;
	var Char;
 
	for (i = 0; i < this.length && IsNumber == true; i++){
		Char = this.charAt(i);
		if (ValidChars.indexOf(Char) == -1){
			IsNumber = false;
		}
	}
	return IsNumber;
}



var glob = new Array();
glob['counter_form'] = '';
glob['counter_elm'] = '';
glob['counter_cnt'] = 0;


function setRemindMeOptionsForCalendarEvent(checkbox){
	var cmbWaitPeriod = YAHOO.util.Dom.get("pm_reminder_wait_period");
	var cmbReminderMethod = YAHOO.util.Dom.get("pm_reminder_method");
	if (checkbox.checked){
		cmbWaitPeriod.selectedIndex = 1;
		cmbReminderMethod.selectedIndex = 1;
	}else{
		cmbWaitPeriod.selectedIndex = 0;
		cmbReminderMethod.selectedIndex = 0;
	}
}

var tempX = 0;
var tempY = 0;
function getMouseXY(e) {
	if (IE) { // grab the x-y pos.s if browser is IE
		tempX = event.clientX + document.body.scrollLeft;
		tempY = event.clientY + document.body.scrollTop;
	} else {  // grab the x-y pos.s if browser is NS
		tempX = e.pageX;
		tempY = e.pageY;
	}
	// catch possible negative values in NS4
	if (tempX < 0){
		tempX = 0;
	}
	if (tempY < 0){
		tempY = 0;
	}

	return true;
}

// Pattern matching routine
function checkIt(string)
{
	place = detect.indexOf(string) + 1;
	thestring = string;
	return place;
}

// Detect Web Browser routine
var detect = navigator.userAgent.toLowerCase();
var OS,browser,version,total,thestring;

if (checkIt('konqueror'))
{
	browser = "Konqueror";
	OS = "Linux";
}
else if (checkIt('safari')) browser = "Safari"
else if (checkIt('omniweb')) browser = "OmniWeb"
else if (checkIt('opera')) browser = "Opera"
else if (checkIt('webtv')) browser = "WebTV";
else if (checkIt('icab')) browser = "iCab"
else if (checkIt('msie')) browser = "Internet Explorer"
else if (!checkIt('compatible'))
{
	browser = "Netscape Navigator"
	version = detect.charAt(8);
}
else browser = "An unknown browser";

if (!version) version = detect.charAt(place + thestring.length);

if (!OS)
{
	if (checkIt('linux')) OS = "Linux";
	else if (checkIt('x11')) OS = "Unix";
	else if (checkIt('mac')) OS = "Mac"
	else if (checkIt('win')) OS = "Windows"
	else OS = "an unknown operating system";
}



// Clears the input on field focus
function clearInput(obj, defaultvalue)
{
	if(obj.value == defaultvalue)
		obj.value = "";
}

// Check event keypress for enter button
function checkEnter(obj, evt, act)
{
	// Backward compatibility for netscape
	var netscape = 0;
	if(browser == "Netscape" && version >= 3)
		netscape = 1;
		
	// Grab client input event
	if (netscape)
		code = evt.which;
	else
		code = evt.keyCode;
		
	// If client inputs enter key
	if (code == 13)
	{
		switch(act)
		{
			case 'next':
				var next = obj.tabIndex;
				next++;
				if (next < obj.form.length)
					obj.form.elements[next].focus();
				break;
			case 'submit':
				obj.form.submit();
				break;
			default:
				// do nothing
				break;
		}
	}
}

// Check which package client can purchase
function package_buy(packagetype){
		
	if (packagetype == 'basic')
		document.location.href = '/subscribe/register/1001';
	else if (packagetype == 'advisor')
		document.location.href = '/subscribe/register/1002';
}

// Drop down payment details based on payment type
function showDiv(what, prefix, showobj)
{
	// what		=> form element
	// prefix 	=> id prefix to hide/show
	// showobj	=> object to auto show when any pattern is matched
	 
	var divs = document.getElementsByTagName('div');
	var show = document.getElementById(showobj);
	
	// Iterate through div elements
	for(var i = 0; i < divs.length; i++)
	{
		var elm = divs[i];
		if(elm.id.match(eval("/^" +prefix+ "_/"))) // Match object prefix
			if(elm.id == prefix +"_" + what.value)
				elm.style.display = "";
			else
				elm.style.display = "none";
	}
	if(what.value != "")
		show.style.display = "";
	else
		show.style.display = "none";
}

function modexample(frm, obj, act, example)
{
	var frm = eval('document.' + frm);
	var obj = eval('frm' + '.' + obj)
	obj.value = example;
	frm.action = act;
	frm.submit();
}

function skipInterviewQuestion(qid)
{
	var elm = document.forms[0];
	qid = parseInt(qid) + 1;
	elm.action = '/interview/nextquestion/' + qid;
	elm.submit();
}

function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

// FUNC: Lightbox Creator
function addLightbox(title,strHref,boxWidth, boxHeight,close){
	//Make sure we have screenoverlay and topbox
	var overlay = document.getElementById('screenoverlay');
	if (overlay == null) {
		overlay = document.createElement('div');
		overlay.setAttribute('id', 'screenoverlay');
		document.body.appendChild(overlay);
	}
	overlay.style.visibility = "hidden";
	//overlay.style.width = "100%";
	//overlay.style.height = "100%";

	var topbox = document.getElementById('topbox');
	if (topbox == null) {
		topbox = document.createElement('div');
		topbox.setAttribute('id', 'topbox');
		document.body.appendChild(topbox);
	}
	topbox.style.visibility = "hidden";
	overlay.style.width = boxWidth;
	overlay.style.height = boxHeight;
	topbox.style.left= "50%";
	topbox.style.top = "50%";
	topbox.style.marginLeft = 0;
	topbox.style.marginTop = 0;

	var myForm = document.createElement("form");
	myForm.method="POST";
	myForm.action = "/tests/lightbox/showVariableIframe" ;
	myForm.setAttribute('id', 'jsLightboxForm');
	var myInput = document.createElement("input") ;
	myInput.setAttribute("name", "lightboxtitle");
	myInput.setAttribute("type", "hidden");
	myInput.setAttribute("value", title);
	myForm.appendChild(myInput);
	myInput = document.createElement("input") ;
	myInput.setAttribute("name", "iframehref");
	myInput.setAttribute("type", "hidden");
	myInput.setAttribute("value", strHref);
	myForm.appendChild(myInput);
	myInput = document.createElement("input") ;
	myInput.setAttribute("name", "iframewidth");
	myInput.setAttribute("type", "hidden");
	myInput.setAttribute("value", boxWidth-10);
	myForm.appendChild(myInput);
	myInput = document.createElement("input") ;
	myInput.setAttribute("name", "iframeheight");
	myInput.setAttribute("type", "hidden");
	myInput.setAttribute("value", boxHeight-50);
	myForm.appendChild(myInput);
	myInput = document.createElement("input") ;
	myInput.setAttribute("name", "lightboxclosable");
	myInput.setAttribute("type", "hidden");
	myInput.setAttribute("value", close);
	myForm.appendChild(myInput);
	document.body.appendChild(myForm);

	xmlhttpSubmit("jsLightboxForm", "topbox", myForm.action, myForm.method);
	showTop(boxWidth, boxHeight, false);
	return false;
}

// FUNC: AJAX Page Changer
function xmlhttpHref(res, strHref, clearhtml, PostGet) {
	/****************************************
 res            = Destination ID
 strHref        = Target File
****************************************/

	// *VI* Variable Initialization
	var self        = new Object;
	self = this;

	// Blank out object
	if(clearhtml)
		document.getElementById(res).innerHTML = '';

	//Determine if POST or GET to be utilized
	fType = "GET";
	if(PostGet) fType = "POST";

	self = openAJAX(self);

	// Establish connection to static destination
	self.xmlHttpReq.open(fType, strHref, true);

	// Move along to next page, if successful,
	// otherwise fall back to an error
	self.xmlHttpReq.onreadystatechange = function() {
		if (self.xmlHttpReq.readyState == 4) {
			if (self.xmlHttpReq.status == 200) {
				if (isSessionValid(self.xmlHttpReq.responseText)){
					updatepage('', res, self.xmlHttpReq.responseText, clearhtml);
				}else{
					self.location.href="/wclogin";
				}
			} else {
				alert('There was a problem with the request.');
			}
		}
	}

	self.xmlHttpReq.send(null); // GET submission
}

// FUNC: AJAX Universal Submission
function xmlhttpSubmit(frm, res, strHref, PostGet, clearhtml, waitCursor) {
	/****************************************
 frm            = Source Form ID
 res            = Destination ID
 strHref        = Submission Target File
 PostGet        = GET  : 0 / undefined
                  POST : 1
****************************************/
	// *VI* Variable Initialization
	var self        = new Object;
	self = this;

	// Blank out object
	if(clearhtml)
		document.getElementById(res).innerHTML = '';

	// Determine if POST or GET to be utilized
	fType = "GET";
	if(PostGet) fType = "POST";
	else strHref += "?" + makeQuery(frm);                                 // Append url query to url for GET

	self = openAJAX(self);

	// Establish connection to submission destination
	self.xmlHttpReq.open(fType, strHref, true);

	// Send Headers
	self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

	// Move along to next page, if successful,
	// otherwise fall back to an error
	self.xmlHttpReq.onreadystatechange = function() {
		if (self.xmlHttpReq.readyState == 4) {
			if((document != null) && (document.body != null) && (document.body.style != null)){
				//Reset cursor to default
				document.body.style.cursor = "default";
			}
			if (self.xmlHttpReq.status == 200) {
				if (isSessionValid(self.xmlHttpReq.responseText)){
					updatepage(frm, res, self.xmlHttpReq.responseText, clearhtml);
				}else{
					self.location.href="/wclogin";
				}
			} else {
				alert('There was a problem with the request.');
			}
		}
	}

	if((waitCursor) && (document != null) && (document.body != null) && (document.body.style != null)){
		//Set cursor to hourglass
		document.body.style.cursor = "wait";
	}
  
	// Sends the request (if necessary)
	if(PostGet)
		self.xmlHttpReq.send(makeQuery(frm));                               // POST submission
	else
		self.xmlHttpReq.send(null);                                         // GET submission
}

/**
 * This function tests the responseText for 'You must be logged in to perform that action'
 * and returns false if it exits.  If this method returns false, redirect the user to the wclogin page.
 *
 * @param responseText
 * @return
 */
function isSessionValid(responseText){
	if (responseText!=null){
		if (responseText.indexOf('Login To Your Account') != -1){
			self.location.href="/wclogin"; //just take them directly to the login page so every caller of this function doesnt have to do it.
		//return false; //session is  not valid, the phrase above was found
		}
	}
	return true; //default to session being valid.
}

// FUNC: URL query generator
function makeQuery(frm) {
	/***************************************
 frm            = Source Form ID
****************************************/
	frm = document.getElementById(frm);
	var myQuery = "";
	for (i = 0; i < frm.elements.length; i++) {                           // Loop through form elements
		myElm = frm.elements[i];
		switch (myElm.type) {
			case "text":
			case "select-one":
			case "hidden":
			case "password":
			case "textarea":
				myQuery += myElm.name + "=" + escape(myElm.value) + "&";
				break;
			case "checkbox":
				if(myElm.checked)
					myQuery += myElm.name + "=" + escape(myElm.value) + "&";
				break;
			case "select-multiple":
				var csv = "";
				for(n = 0; n < myElm.length; n++) {
					if(myElm.options[n].selected) {
						if(csv) csv += "|";
						csv += myElm.options[n].value
					}
				}
				myQuery += myElm.name + "=" + escape(csv) + "&";
				break;
		}
	}
	return (myQuery);
}

// FUNC: Updates content within target object
function updatepage(frm, elm, str){
	/***************************************
 frm            = Source Form ID
 elm            = Element to update
 str            = Content
****************************************/

	// *VI* Variable Initialization
	var tname       = new String;
	var newtitle    = new String;

	// Login verification test
	if(str.substring(0, 11) == '<!--AUTH-->')
	{
		document.getElementById(elm).innerHTML = 'Invalid user detected, redirecting...';
		window.location.href = "/wclogin";
		return;
	}
	
	document.getElementById(elm).innerHTML = str;	// Update element content
}

// FUNC: Open AJAX Object
function openAJAX(obj) {
	/****************************************
 obj            = AJAX object
****************************************/
	if (window.XMLHttpRequest) {
		obj.xmlHttpReq = new XMLHttpRequest();                              // Mozilla/Safari/Opera?
		if(obj.xmlHttpReq.overrideMimeType)
			obj.xmlHttpReq.overrideMimeType("text/html");                     // Declare as text/html content only
	} else if (window.ActiveXObject) {                                    // Active X, IE.. what other browser could it be..
		try {
			obj.xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");           // MS XML v2
		} catch (e) {
			try {
				obj.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");      // MS XML v1 (backward compatable w/ IE 5.5)
			} catch (e) {}
		}
	}
	return obj;
}

function showTop(boxWidth, boxHeight, usemousexy, disableOverlay)
{
	//Position the topBox. In this example I am just centering it on the screen
	if(!boxWidth)
	{
		boxWidth = 550;
		boxHeight = 200;
	}

	var topbox = document.getElementById('topbox');
	var coords = findPos(topbox);
	
	var leftEdge = coords[0];
	var topEdge = coords[1];
	
	document.getElementById('topbox').style.width = boxWidth + 'px';
	document.getElementById('topbox').style.height = boxHeight + 'px';
		
	if(usemousexy)
	{
		// Position container to the top left user input location
		xPos = tempX - (boxWidth/2) - 15;
		yPos = tempY - boxHeight - 25;
		
		// Ensure entire container is always visible regardless of mouse position
		if(xPos < 5) xPos = 5;
		if(yPos < 5) yPos = 5;
		
		// Perform positioning
		document.getElementById('topbox').style.left=xPos + 'px';
		document.getElementById('topbox').style.top=yPos + 'px';
	} else {
		
		//Move topbox left and up to center it in the viewport
		var leftAdjustment = boxWidth * -0.5;
		if((leftEdge + leftAdjustment) < 0){
			//Don't go off the screen
			document.getElementById('topbox').style.left= 0;
			document.getElementById('topbox').style.marginLeft = 0;
		}
		else{
			document.getElementById('topbox').style.left= "50%";
			document.getElementById('topbox').style.marginLeft = leftAdjustment + 'px';
		}

		var topAdjustment = boxHeight * -0.5;
		if((topEdge + topAdjustment) < 0){
			//Don't go off the screen
			document.getElementById('topbox').style.top = 0;
			document.getElementById('topbox').style.marginTop = 0;
		}
		else{
			document.getElementById('topbox').style.top = "50%";
			document.getElementById('topbox').style.marginTop = topAdjustment + 'px';
		}
	}
	
	var arrayPageSize = getPageSize();
	
	//Show the background overlay and topbox...
	if(!disableOverlay)
	{
		document.getElementById('screenoverlay').style.visibility = 'visible';
	//document.getElementById('screenoverlay').style.height = (arrayPageSize[1] + 'px');
	}
	document.getElementById('screenoverlay').style.height = "100%";
	document.getElementById('screenoverlay').style.width = "100%";
	document.getElementById('topbox').style.visibility = 'visible';
}

function findPos(obj){
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
		while (obj = obj.offsetParent);
	}
	return [curleft, curtop];
}

function delayedShowTop(seconds)
{
	setTimeout("showTop()", seconds*1000);
}

function closeTop()
{
	//Hide the overlay and tobox...
	document.getElementById('screenoverlay').style.visibility = 'hidden';
	document.getElementById('topbox').style.visibility = 'hidden';
	document.getElementById('calbox').style.visibility = 'hidden';
}

function closeMiniCal()
{
	//Hide the overlay and tobox...
	document.getElementById('calbox').style.visibility = 'hidden';
}


function getPageSize(){
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;

	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else {
		pageHeight = yScroll;
	}
	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
	return arrayPageSize;
}

// Show mini calendar for date input fields
function miniCal(datetime, elm, frmobj)
{
	var e = document.getElementById(elm);
	
	var calbox = document.getElementById('calbox');
	document.getElementById('calbox').style.left = getX(e) + 'px';
	document.getElementById('calbox').style.top = (getY(e) + e.offsetHeight + 1) + 'px';
	calbox.style.visibility = 'visible';
	
	if(datetime == 0)
	{
		var frm = eval("document.calevent." + frmobj)
		var myDate = new Date(frm.value); // Your timezone!
		var myEpoch = myDate.getTime()/1000.0;
		datetime = myEpoch;
	}
	xmlhttpHref('calbox', ('/tools/calendar/minical/' + datetime + '/' + elm + '/' + frmobj), 1);
	
}

function getY( oElement )
{
	var iReturnValue = 0;
	while( oElement != null ) {
		iReturnValue += oElement.offsetTop;
		oElement = oElement.offsetParent;
	}
	return iReturnValue;
}

function getX( oElement )
{
	var iReturnValue = 0;
	while( oElement != null ) {
		iReturnValue += oElement.offsetLeft;
		oElement = oElement.offsetParent;
	}
	return iReturnValue;
}

function rateVideo(vidId,rating){
	
	var upEl = YAHOO.util.Dom.get("thumbsUpElement");
	var downEl = YAHOO.util.Dom.get("thumbsDownElement");
	
	downEl.innerHTML = "";
	upEl.colspan=2;
	upEl.innerHTML = "<img src='/img/ajaxloadingsmall.gif'/> Saving..."
	
	// Define the callback object for Connection Manager
	var callback = {
		success : function(o) {
			upEl.innerHTML = "Thank you for voting.";
		},
		failure : function(o) {
			alert("Unable to rate the video.  Please try again later");
		}
	};
    
	// Connect to our data source and load the data
	var conn = YAHOO.util.Connect.asyncRequest("GET", "/learningcenter/main/rateVideo/"+vidId+"/"+rating, callback);
    
}

function gotoUrl(url){
	self.location.href=url;
}


/**
 * Called from edit profile, member registration pages.  When entering a community nickname,
 * this function is called using onkeyup() to use AJAX to respond if the name is unique or not.
 *   
 * @param textbox
 * @return
 */
function autovalidateCommunityNickname(textbox){

	//show ajax name checking
	var communityNameMessage = YAHOO.util.Dom.get("communityNameMessage");
	communityNameMessage.innerHTML = "<img src='/img/ajaxloadingsmall.gif'/> Validating...";
	
	var callback = {
		success : function(o) {
			if (isSessionValid(o.responseText)){
				if (o.responseText.indexOf("SUCCESS") > -1)
					communityNameMessage.innerHTML = "<img src='/img/Symbol_Check.png'/> The name you selected, '"+textbox.value+"', is valid.";
				else
					communityNameMessage.innerHTML = "<img src='/img/Symbol_Error.png'/> Name is not allowed or already in use.  Please try another.";
			}else{
				self.location.href="/wclogin";
			}
        	
		},
		failure : function(o) {
		//do nothing
		}
	};
	var conn = YAHOO.util.Connect.asyncRequest("GET", "/phorum/main/namecheck/" + textbox.value, callback);
}


function urlencode( str ) {
	// http://kevin.vanzonneveld.net
	// +   original by: Philip Peterson
	// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +      input by: AJ
	// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +   improved by: Brett Zamir (http://brettz9.blogspot.com)
	// +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +      input by: travc
	// +      input by: Brett Zamir (http://brettz9.blogspot.com)
	// +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +   improved by: Lars Fischer
	// %          note 1: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
	// *     example 1: urlencode('Kevin van Zonneveld!');
	// *     returns 1: 'Kevin+van+Zonneveld%21'
	// *     example 2: urlencode('http://kevin.vanzonneveld.net/');
	// *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
	// *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
	// *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
                             
	var histogram = {}, tmp_arr = [];
	var ret = (str+'').toString();
    
	var replacer = function(search, replace, str) {
		var tmp_arr = [];
		tmp_arr = str.split(search);
		return tmp_arr.join(replace);
	};
    
	// The histogram is identical to the one in urldecode.
	histogram["'"]   = '%27';
	histogram['(']   = '%28';
	histogram[')']   = '%29';
	histogram['*']   = '%2A';
	histogram['~']   = '%7E';
	histogram['!']   = '%21';
	histogram['%20'] = ' ';
	histogram['\u00DC'] = '%DC';
	histogram['\u00FC'] = '%FC';
	histogram['\u00C4'] = '%D4';
	histogram['\u00E4'] = '%E4';
	histogram['\u00D6'] = '%D6';
	histogram['\u00F6'] = '%F6';
	histogram['\u00DF'] = '%DF';
	histogram['\u20AC'] = '%80';
	histogram['\u0081'] = '%81';
	histogram['\u201A'] = '%82';
	histogram['\u0192'] = '%83';
	histogram['\u201E'] = '%84';
	histogram['\u2026'] = '%85';
	histogram['\u2020'] = '%86';
	histogram['\u2021'] = '%87';
	histogram['\u02C6'] = '%88';
	histogram['\u2030'] = '%89';
	histogram['\u0160'] = '%8A';
	histogram['\u2039'] = '%8B';
	histogram['\u0152'] = '%8C';
	histogram['\u008D'] = '%8D';
	histogram['\u017D'] = '%8E';
	histogram['\u008F'] = '%8F';
	histogram['\u0090'] = '%90';
	histogram['\u2018'] = '%91';
	histogram['\u2019'] = '%92';
	histogram['\u201C'] = '%93';
	histogram['\u201D'] = '%94';
	histogram['\u2022'] = '%95';
	histogram['\u2013'] = '%96';
	histogram['\u2014'] = '%97';
	histogram['\u02DC'] = '%98';
	histogram['\u2122'] = '%99';
	histogram['\u0161'] = '%9A';
	histogram['\u203A'] = '%9B';
	histogram['\u0153'] = '%9C';
	histogram['\u009D'] = '%9D';
	histogram['\u017E'] = '%9E';
	histogram['\u0178'] = '%9F';
    
	// Begin with encodeURIComponent, which most resembles PHP's encoding functions
	ret = encodeURIComponent(ret);
    
	for (search in histogram) {
		replace = histogram[search];
		ret = replacer(search, replace, ret); // Custom replace. No regexing
	}
    
	// Uppercase for full PHP compatibility
	return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
		return "%"+m2.toUpperCase();
	});
    
	return ret;
}

/**
 * Update the dofOfMonth combo to show proper number of days
 * based on the month combo
 * @param sMonth -HTMLElement input select
 * @param dayOfMonthElementId -string id
 * @return
 */
function updateDayOfMonthDropdown(sMonth,dayOfMonthElementId){
	
	//remove existing items
	var sDay = YAHOO.util.Dom.get(dayOfMonthElementId);
	while (sDay.length > 0){
		sDay.remove(0);
	}
	//add new items
	var month = sMonth.selectedIndex;
	if (month == 1){
		addDays(sDay, 31);
	}else if (month == 2){
		addDays(sDay, 28);
	}else if (month == 3){
		addDays(sDay, 31);
	}else if (month == 4){
		addDays(sDay, 30);
	}else if (month == 5){
		addDays(sDay, 31);
	}else if (month == 6){
		addDays(sDay, 30);
	}else if (month == 7){
		addDays(sDay, 31);
	}else if (month == 8){
		addDays(sDay, 31);
	}else if (month == 9){
		addDays(sDay, 30);
	}else if (month == 10){
		addDays(sDay, 31);
	}else if (month == 11){
		addDays(sDay, 30);
	}else if (month == 12){
		addDays(sDay, 31);
	}
}
function addDays(sDay, numberOfDays){
	sDay.options[0]=new Option("--Select--","",false,false);
	for (var i=1;i<=numberOfDays;i++){
		sDay.options[i]=new Option(i,i,false,false);
	}
}

//create onDomReady Event
window.onDomReady = DomReady;

//Setup the event
function DomReady(fn)
{
	//W3C
	if(document.addEventListener)
	{
		document.addEventListener("DOMContentLoaded", fn, false);
	}
	//IE
	else
	{
		document.onreadystatechange = function(){
			readyState(fn)
		}
	}
}

//IE execute function
function readyState(fn)
{
	//dom is ready for interaction
	if(document.readyState == "interactive")
	{
		fn();
	}
}



function uploadProfilePicture (){
	//show ajax loading
	var imageContainer = document.getElementById('imageContainer');
	var originalHTML = imageContainer.innerHTML;
	imageContainer.innerHTML = "<center><img src='/img/ajaxloading.gif'/><br/>Uploading...</center>";
	
	// set form
	YAHOO.util.Connect.setForm('multi', true);
	// upload image
	YAHOO.util.Connect.asyncRequest('POST', '/documents/uploadPhotoAJAX', {
		upload: function(o){
			if (o.responseText.indexOf('Allowed memory size of') > -1){
				alert('The image you selected for upload is too large.  Please reduce the image size and upload again.')
				imageContainer.innerHTML = originalHTML;
			}
			else if (o.responseText.indexOf('File type uploaded is not allowed') > -1){
				alert('The file you selected is not allowed.  Please make sure to upload a GIF, JPG, or PNG file.')
				imageContainer.innerHTML = originalHTML;
			}
			else{
				// put image in our image container
				var timestamp = new Date();
				var imgurl = '<img id="yuiImg" src="/image/profile/' + timestamp +  '" alt="Your profile picture" />';
				imageContainer.innerHTML = imgurl;
				
				//clear out the name of the file
				var fileNameDiv = YAHOO.util.Dom.get("file-name");
				fileNameDiv.innerHTML = "";
			}
		},
		failure : function(o) {
			alert('error: ' + o.responseText);
		}
	});
}

function deleteProfilePicture(){
	//show ajax loading
	var imageContainer = document.getElementById('imageContainer');
	imageContainer.innerHTML = "<center><img src='/img/ajaxloading.gif'/><br/>Deleting...</center>";

	var deletecallback = {
		success : function(o) {
			if (isSessionValid(o.responseText)){
				var timestamp = new Date();
				var imgurl = '<img id="yuiImg" src="/image/profile/' + timestamp +  '" alt="Your profile picture" />';
				imageContainer.innerHTML = imgurl;
			}else{
				self.location.href="/wclogin";
			}
        	
		},
		failure : function(o) {
			alert('unable to determine profile pic name');
		}
	};
	var conn = YAHOO.util.Connect.asyncRequest("GET", "/image/deleteprofile", deletecallback);
}


function validateCommunityNickname(input){
	if(input.value != '') {
		input.style.background = "url('../img/ajaxloadingsmall.gif') no-repeat right";
	
		var callback = {
			success : function(o) {
				if (isSessionValid(o.responseText)){
					if (o.responseText.indexOf("SUCCESS") > -1)
						input.style.background = "url('../img/Symbol_Check.png') no-repeat right";
					else
						input.style.background = "url('../img/Symbol_Error.png') no-repeat right";
				}else{
					self.location.href="/wclogin";
				}
        	
			},
			failure : function(o) {
			//do nothing
			}
		};
		var conn = YAHOO.util.Connect.asyncRequest("GET", "/phorum/main/namecheck/" + input.value, callback);
	} else {
		input.style.background = "";
	}
}


function validateEmail(input) {
	if(input.value != '') {
		input.style.background = "#fff url('../img/ajaxloadingsmall.gif') no-repeat right";
	
		var callback = {
			success : function(o) {
				if (isSessionValid(o.responseText)){
					if (o.responseText.indexOf("FALSE") > -1) {
						input.style.background = "#fff url('../img/Symbol_Check.png') no-repeat right";
						return true;
					} else {
						input.style.background = "#fff url('../img/Symbol_Error.png') no-repeat right";
						return false;
					}
				}else{
					self.location.href="/wclogin";
				}
        	
			},
			failure : function(o) {
			//do nothing
			}
		};
		var conn = YAHOO.util.Connect.asyncRequest("GET", "/register/email_in_use/" + input.value, callback);
	} else {
		input.style.background = "#fff";
		return false;
	}
}

function validateInputsMatch(input1, input2) {
	var parent = input1.parentNode;
	if(input1.value != '') {
		parent.style.background = "url('../img/ajaxloadingsmall.gif') no-repeat right";
		
		if(input1.value == input2.value) {
			parent.style.background = "url('../img/Symbol_Check.png') no-repeat right";
			return true;
		} else {
			parent.style.background = "url('../img/Symbol_Error.png') no-repeat right";
			return false;
		}
	} else {
		parent.style.background = "";
		return false
	}
}

function validatePassword(input) {
	var parent = input.parentNode;
	if(input.value != '') {
		parent.style.background = "url('../img/ajaxloadingsmall.gif') no-repeat right";
		
		re = /[0-9]/;
		if(!re.test(input.value)) {
			parent.style.background = "url('../img/Symbol_Error.png') no-repeat right";
			return false;
		}
		
		re = /[a-z]/;
		if(!re.test(input.value)) {
			parent.style.background = "url('../img/Symbol_Error.png') no-repeat right";
			return false;
		}
		
		if(input.value.length < 8) {
			parent.style.background = "url('../img/Symbol_Error.png') no-repeat right";
			return false;
		}

		//re = /[A-Z]/;
		//if(!re.test(input.value)) {
		//	input.style.background = "url('../img/Symbol_Error.png') no-repeat right";
		//	return false;
		//}
		
		parent.style.background = "url('../img/Symbol_Check.png') no-repeat right";
		return true;
	} else {
		parent.style.background = "";
		return false;
	}
}

function validateRequired(input) {
	var parent = input.parentNode;
	if(input.value != '') {
		parent.style.background = "url('../img/Symbol_Check.png') no-repeat right";
		return true;
	} else {
		parent.style.background = "";
		return false;
	}
}



function submitPayment() {
	if(submitted == true) {
		return;
	}

	//because some browsers do not like disabling submit buttons
	//and then altering an overlying image, we have to make sure
	//the image is deleted for all browsers
	//
	button = document.getElementById('submit-image');
	parentbutton = button.parentNode;
	parentbutton.removeChild(button);


	// now we will add the disabled image back
	formImg = document.getElementById('form_img');
	formImg.src = Image1.src;

	//add a message
	formtext = document.getElementById('form_text');
	formtext.innerHTML="Processing... <br />Please do not reload/refresh the page or press the back button.";
	document.forms[0].submit();
	submitted = true;
}

function updateFileName() {
	document.getElementById('file-name').innerHTML=document.getElementById('uploadImage').value
}
var globaldivid =null;
function onPseudoSave(divid) {
	dataSavedSuccessfully(divid);
	scroll(0,0);
}

function dataSavedSuccessfully(divid) {
	if ((undefined==divid)||(divid.length==0) || (divid==null)) {
		divid="indicator"
	}
	
	var indicator = document.getElementById(divid);
	
	if(indicator){
		indicator.style.background = '#a3d869';
		indicator.style.padding = '10px';
		indicator.style.margin = '10px auto';
		indicator.style.textAlign = 'center';
		indicator.style.width = '300px';
		indicator.style.color = '#fff';
		indicator.style.fontWeight = 'bold';
		indicator.innerHTML = "You've successfully saved this form";
		globaldivid=divid;
		var t = setTimeout("dataSavedSuccessfullyEmty()",5000);
	}
	
	return;
}

function dataSavedSuccessfullyEmty() {
	if ((undefined==globaldivid)||(globaldivid.length==0) || (globaldivid==null)) {
		globaldivid="indicator"
	}
	var indicator = document.getElementById(globaldivid);

	if(indicator){
		indicator.style.background = '#ffffff';
		indicator.style.padding = '0';
		indicator.style.margin = '0';
		indicator.innerHTML = "";
	}
	
	return;
}


/**
 * Used to load pages via AJAX. This is a trick needed to execute the scripts returned via AJAX
 * @param element
 * @param rawJS
 * @return
 */
function stripJS(element, rawJS) {
	var children = element.childNodes;
	if(children != null) {
		for (var i=0;i<children.length;i++){
			var child = children[i];
			if("SCRIPT" == child.tagName){
				rawJS += child.innerHTML;
			//alert(child.innerHTML);
			}
			if (child.childNodes.length>0){
				rawJS = stripJS(child,rawJS);
			}
		}
	}
	return rawJS;
}
function loadListItemsScholarship(){
	var elem= document.getElementById('selectSchoolList');
	if(undefined==elem){
		return;
	}
	//show swirly
	var swirly = YAHOO.util.Dom.get("swirlySchoolList");

	var oldHTML = swirly.innerHTML;
	swirly.innerHTML = "<img alt='' src='/img/ajaxloadingsmall.gif' />";

	var index =elem.selectedIndex;
	var value = elem.options[index].value;
	var schoollist = document.getElementById('selectSchool');
	var i;
	for(i=schoollist.options.length-1;i>=1;i--)
	{
		schoollist.remove(i);
	}
	var schoolcontainer = document.getElementById("schoolcontainer");

	// Define the callback object for Connection Manager that will set the body of our content area when the content has loaded
	var callback = {
		success : function(o) {
			if (isSessionValid(o.responseText)){

				if(o.responseText.length >1){
					var splits = o.responseText.split("|");
					for (i=0;i<splits.length;i++){
						var innersplit=splits[i].split("->");
						var optn = document.createElement("OPTION");
						optn.text = innersplit[1];
						optn.value = innersplit[0];
						schoollist.options.add(optn);
					}
				}
				swirly.innerHTML =oldHTML;
				schoolcontainer.style.display = "table-row";
			}else{
				self.location.href="/login";
			}

		},
		failure : function(o) {

		}
	};

	// Connect to our data source and load the data
	if(index != "undefined"&&index > 0){
		var conn = YAHOO.util.Connect.asyncRequest("GET", "/globalajax/ajaxschoolsearch/schoolList/"+value+"/false/true", callback);
	}else{
		swirly.innerHTML =oldHTML;
		schoolcontainer.style.display = "none";
	}
		
}
function loadListItems(){
	var elem= document.getElementById('cmbListList');
	if(undefined==elem){
		return;
	}
	//show swirly
	var swirly = YAHOO.util.Dom.get("searchToolbarSwirly");
		
	var oldHTML = swirly.innerHTML;
	swirly.innerHTML = "<img alt='' src='/img/ajaxloadingsmall.gif' />";
		
	var index =elem.selectedIndex;
	var value = elem.options[index].value;
	var schoollist = document.getElementById('cmbSchoolList');
	var i;
	for(i=schoollist.options.length-1;i>=1;i--)
	{
		schoollist.remove(i);
	}
	var schoolcontainer = document.getElementById("schoolcontainer");

	// Define the callback object for Connection Manager that will set the body of our content area when the content has loaded
	var callback = {
		success : function(o) {
			if (isSessionValid(o.responseText)){

				//alert(o.responseText);
				if(o.responseText.length >1){
					var splits = o.responseText.split("|");
					for (i=0;i<splits.length;i++){
						var optn = document.createElement("OPTION");
						optn.text = splits[i];
						optn.value = splits[i];
						schoollist.options.add(optn);
					}
				}
				swirly.innerHTML =oldHTML;
				schoolcontainer.style.display = "block";
			}else{
				self.location.href="/login";
			}

		},
		failure : function(o) {

		}
	};

	// Connect to our data source and load the data
	if(index != "undefined"&&index > 0){
		var conn = YAHOO.util.Connect.asyncRequest("GET", "/globalajax/ajaxschoolsearch/schoolList/"+value, callback);
	}else{
		swirly.innerHTML =oldHTML;
		schoolcontainer.style.display = "none";
	}
		
}
function loadListItemsUnitId(){
	//show swirly
	var swirly = YAHOO.util.Dom.get("searchSwirly");
	var oldHTML = swirly.innerHTML;
	swirly.innerHTML = "<img alt='' src='/img/ajaxloadingsmall.gif' />";
	var elem= document.getElementById('cmbListList');
	var index =elem.selectedIndex;
	var value = elem.options[index].value;
	var schoollist = document.getElementById('cmbSchoolList');
	var i;
	for(i=schoollist.options.length-1;i>=1;i--)
	{
		schoollist.remove(i);
	}
	var schoolcontainer = document.getElementById("schoolcontainer");

	// Define the callback object for Connection Manager that will set the body of our content area when the content has loaded
	var callback = {
		success : function(o) {
			if (isSessionValid(o.responseText)){

				//alert(o.responseText);
				if(o.responseText.length >1){
					var splits = o.responseText.split("|");
					for (i=0;i<splits.length;i++){
						var innersplit=splits[i].split("->");
						var optn = document.createElement("OPTION");
						optn.text = innersplit[1];
						optn.value = innersplit[0];
						schoollist.options.add(optn);
					}
				}
				swirly.innerHTML =oldHTML;
				schoolcontainer.style.display = "block";
			}else{
				self.location.href="/login";
			}

		},
		failure : function(o) {

		}
	};

	// Connect to our data source and load the data
	if(index != "undefined"&&index > 0){
		var conn = YAHOO.util.Connect.asyncRequest("GET", "/globalajax/ajaxschoolsearch/schoolList/"+value+"/true", callback);
	}else{
		swirly.innerHTML =oldHTML;
		schoolcontainer.style.display = "none";
	}
}

