var hexColorArray = [
					'AFD8F8',
					'F6BD0F',
					'8BBA00',
					'A66EDD',
					'F984A1',
					'CCCC00',
					'999999',
					'0099CC',
					'FF0000',
					'006F00',
					'0099FF',
					'FF66CC',
					'669966',
					'7C7CB4',
					'FF9933',
					'9900FF',
					'99FFCC',
					'CCCCFF',
					'669900',
					'1941A5' 
					];

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

function URLEncode (clearString) {
	clearString = clearString.replace('\n','\\n');
	var output = '';
	var x = 0;
	clearString = clearString.toString();
	var regex = /(^[a-zA-Z0-9_.]*)/;
	while (x < clearString.length) {
		var match = regex.exec(clearString.substr(x));
		if (match != null && match.length > 1 && match[1] != '') {
			output += match[1];
			x += match[1].length;
		} else {
			if (clearString[x] == ' ') {
				output += '+';
			} else if (clearString[x] == '"') {
				output += '\"';
			} else if (clearString[x] == "'") {
				output += "`";
			} else {			
				var charCode = clearString.charCodeAt(x);
				var hexVal = charCode.toString(16);
				output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
			}
			x++;
		}
	}  	
	return output;	
}

function cleanJSON(string) {
	var newString = string;
	
	charToRemove = /#/g;	
		newString = newString.replace(charToRemove,'%23');
	charToRemove = /%/g;	
		newString = newString.replace(charToRemove,'%25');	
	charToRemove = /&/g;	
		newString = newString.replace(charToRemove,'%26');
	charToRemove = /\\/g;	
		newString = newString.replace(charToRemove,'/');
	//charToRemove = '';	
		//newString = newString.replace(charToRemove,'&#63;');	
			
	return newString;
}


// ***** Remove bad characters from input strings ************************** //
function removeChar(str) {
	var newString = str;
	charToRemove = /"/g;	
		newString = newString.replace(charToRemove,'&#34;');
	charToRemove = /'/g;	
	newString = newString.replace(charToRemove,'&#39;');
	return newString;
}

function replaceHTMLEntities(string) {
    string = string.replace('&amp;','&');
    string = string.replace('&#039;',"'");
    string = string.replace('&#034;','"');
    string = string.replace('&quot;','"');
    return string;
}

// ***** getSelected selects the correct drop-down menu items in an edit screen
// ***** passed the javascript variable and the select id
function getSelect(variable,selectID) {
	var selectMenu    = document.getElementById(selectID);
	var selectOptions = selectMenu.length-1;
	var a=0;
	for(a=0;a<=selectOptions;a++) {
		if (selectMenu.options[a].value == variable) {
			document.getElementById(selectID).selectedIndex = a;
		}
	}
}

// ***** Verify that an email addres is valid ******************************* //
// ***** Written by Paolo Wales (paolo@taize.fr) **************************** //

function isValidEmail(emailad) {

   var exclude=/[^@\-\.\w]|^[_@\.\-]|[\._\-]{2}|[@\.]{2}|(@)[^@]*\1/;
   var check=/@[\w\-]+\./;
   var checkend=/\.[a-zA-Z]{2,4}$/;
   if(((emailad.search(exclude) != -1) ||
       (emailad.search(check)) == -1) ||
       (emailad.search(checkend) == -1)){
      return false;
   } else {
      return true;
   }
}

// ***** Little pause function just for kicks ******************************************** //
function pausecomp(millis) {
	date = new Date();
	var curDate = null;

	do { var curDate = new Date(); }
	while(curDate-date < millis);
} 

function hideControls(spanID) {
	var control = document.getElementById(spanID);
	control.style.visibility = "hidden";
}	

function gotoURL(urlID) {
	var url = document.getElementById(urlID).value;
	window.open(url);
}

function checkUserid() {
	var userid = document.getElementById('addUserid').value;
	x_checkUserid(userid,returnCheckUserid);
}

function clearUserid() {
	document.getElementById('addUserid').style.background = '#ffffff';
	document.getElementById('addUseridError').innerHTML = '';
	
}

function fadeRowBG(color,targetId,colorId,origCssClass) {
	var FadeInterval = 80;
	var FadeSteps = new Array();
	
	if (color == 'yellow') {
			FadeSteps[1] = "ffffff";
			FadeSteps[2] = "ffffee";
			FadeSteps[3] = "ffffdd";
			FadeSteps[4] = "ffffcc";
			FadeSteps[5] = "ffffbb";
			FadeSteps[6] = "ffffaa";
			FadeSteps[7] = "ffff99";
	} else if (color == 'green') {
			FadeSteps[1] = "ffffff";
			FadeSteps[2] = "F8FDF3";
			FadeSteps[3] = "F1FDE4";
			FadeSteps[4] = "E7FBD3";
			FadeSteps[5] = "DFFCC2";
			FadeSteps[6] = "D7FFB0";
			FadeSteps[7] = "ccff99";
	}	
	
    if (colorId >= 1) {
		$(targetId).style.backgroundColor = FadeSteps[colorId];
		colorId--;
		// Wait a little bit and fade another shade
		setTimeout("fadeRowBG('" + color + "','" + targetId + "','" + colorId + "','" + origCssClass + "')", FadeInterval);
	}
	else {
		$(targetId).className = origCssClass;
	}	        
} 

function divRollUpDown(element) {
	var displayStatus = $(element).style.display;
	if (displayStatus == 'none') {
		// Roll Down
		new Effect.SlideDown(element, {direction: 'top', duration: .2});
		$(element).title = 'Roll Up';
	} else {
		Effect.SlideUp(element, {direction: 'top', duration: .2});
		$(element).title = 'Roll Down';
	}	
}

function divClose(element) {
	var displayStatus = $(element).style.display;
	if (displayStatus != 'none') {
		Effect.SlideUp(element, {direction: 'top', duration: .2});
	}
}

function rowHoverControls(id,onOff,offClass) {
	var rowID     = 'row'+id;
	var controlID = 'control'+id;
	
	if (onOff == 'on') {
		$(rowID).className = 'hiLite';
		$(controlID).style.display = 'block';
	} else {
		$(rowID).className  = offClass;
		$(controlID).style.display = 'none';
	}	
}

function checkInputToClear(elementID,text) {
	if (elementID.value == text) {
		elementID.value = '';
	}
}

function confirmDelete(itemID,deleteWhat) {
	if (deleteWhat == 'member') {
		var OK = confirm("Are you sure you want to delete this member? This will PERMANENTLY DELETE this members' information! If you just want to remove this member from this contact, close the members' tab by clicking the X inside the tab.");
		if (OK == true) {
			contactSaveFamilyTeamObj.deleteTeamMember(itemID);
		}
	} else if (deleteWhat == 'user') {
		var OK = confirm("Are you sure you want to deactivate this User?");
		if (OK == true) {
			usersObj.deleteUser(itemID);
		}
	} else if (deleteWhat == 'contact') {
		var OK = confirm("Are you sure you want to delete this Contact?");
		if (OK == true) {
			deleteContacts.deleteContact(itemID);		
		}
	} else if (deleteWhat == 'event') {
		var OK = confirm("Are you sure you want to delete this Event?");
		if (OK == true) {
			calendarUpdateObj.deleteEvent(itemID);			
		}
	} else if (deleteWhat == 'libraryitem') {
		var OK = confirm("Are you sure you want to delete this Library Item?");
		if (OK == true) {
			x_deleteProduct(itemID,returnDeleteProduct);			
		}
	} else if (deleteWhat == 'job') {
		var OK = confirm("Are you sure you want to delete this Employment Listing?");
		if (OK == true) {
			x_deleteListing(itemID,returnDeleteListing);			
		}
	} else if (deleteWhat == 'savedSet') {
		var OK = confirm("Are you sure you want to delete this Saved Set?");
		if (OK == true) {
			x_deleteSavedSet(itemID,returnDeleteSavedSet);			
		}
	} else if (deleteWhat == 'resource') {
		// We need to get the itemID from hidden field
		var itemID = $('resourceEditID').value;
		var OK = confirm("Are you sure you want to delete this Resource?");
		if (OK == true) {
			x_deleteResource(itemID,returnDeleteResource);			
		}
	}		
}

function updateStatus(message,status,statusDiv,noFade) {
	if (status == 'error') {
		$(statusDiv).innerHTML = '<div id="statusDivInner" class="errorMessageBig">'+message+'</div>';
		if (noFade != 1) {
			Effect.Fade('statusDivInner', {delay: 1, duration: 3});
		}	
	} else if (status == 'success') {
		$(statusDiv).innerHTML = '<div id="statusDivInner" class="successMessageBig">'+message+'</div>';
		if (noFade != 1) {
			Effect.Fade('statusDivInner', {delay: 1, duration: 3});
		}	
	} else if (status == 'wait') {
		$(statusDiv).innerHTML = '<div id="statusDivInner" class="activityMessageBig">'+message+'</div>';
	} else if (status == 'clearStatus') {
		$(statusDiv).innerHTML = '';
	}	
}

function makeTinyURL(urlField) {
	var url = $(urlField).value;
	x_makeTinyURL(url,urlField,returnMakeTinyURL);
}

function returnMakeTinyURL(string) {
	stringArray = string.split("|");
	var tinyURL  = stringArray[0];
	var urlField = stringArray[1];
	$(urlField).value = tinyURL; 
}

function enterPressed(e) {
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return false;	
	return (keycode == 13);
}

function clearField(fieldID) {
	$(fieldID).value = '';
}

function mysqlToExtDate(date) {
	var eArray = date.split('-');
	extDate = eArray[1]+'/'+eArray[2]+'/'+eArray[0];
	return extDate;
}

function extToMySQLDate(date) {
	var eArray = date.split('-');
	extDate = eArray[1]+'/'+eArray[2]+'/'+eArray[0];
	return extDate;
}

function dateToMySQL(date) {
	if (date == 'today') {
		var d = new Date();
		var day   = d.getDate();
		var month = d.getMonth();
		month++;
		var year  = d.getFullYear();
		
		if (day.length<2) {
			day = '0'+day;
		}
		if (month.length<2) {
			month = '0'+month;
		}
	}
	var mySQLDate = year+'-'+month+'-'+day;
	return mySQLDate;
}

function showGoogleMap(address, mapDiv, pointerText){
	var map = new GMap2($(mapDiv));
	var geocoder = new GClientGeocoder();
	geocoder.getLatLng(address, function(point){
		if (!point) {
			//alert(address + " not found");
		}
		else {
			map.setCenter(point, 13);
			map.addControl(new GSmallMapControl());
			var marker = new GMarker(point);
			map.addOverlay(marker);
			marker.openInfoWindowHtml(pointerText);
		}
	});
}

function togglePanel(panelID) {
	if ($(panelID).style.display == 'none') {
		new Effect.SlideDown(panelID, {direction: 'top', duration: .3});
	} else {
		new Effect.SlideUp(panelID, {direction: 'top', duration: .3});
	}
}

function randomString(string_length) {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var randomstring = '';
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	return randomstring;
}

function logErrorAJAX(response) {
	var status = response.status;
	var statusText = response.statusText;
	var responseText = response.responseText;
	var response = status+'|'+statusText+'|'+responseText;
	
	var params = 'handler=logAJAXError&responseString='+response;
	var ajaxResults = new Ajax.Request('ajaxDirector.php', {
		method: 'POST',
		parameters: params
	});	
}

function openPopUpWindow(url) {
	var params = 'status=0,toolbar=1,location=0,menubar=0,height=600,width=800,resizable=1,scrollbars=1';
	window.open(url,'newWindow',params);
}

/*
 * Scriptaculous autocomplete hover bug fix
 */
Autocompleter.Base.prototype.render = function() {
	if(this.entryCount > 0) {
		if (this.selected_item)
			Element.removeClassName(this.getEntry(this.selected_item-1),"selected");
			Element.addClassName(this.getEntry(this.index),"selected");
			this.selected_item = this.index+1;
			if(this.hasFocus) {
				this.show();
			this.active = true;
		}
	} else {
		this.active = false;
		this.hide();
	}
};

Autocompleter.Base.prototype.onHover = function(event) {
	var element = Event.findElement(event, 'LI');
	if(element && element.autocompleteIndex && this.index != element.autocompleteIndex) {
		this.index = element.autocompleteIndex;
		this.render();
	}
	Event.stop(event);
};

Autocompleter.Base.prototype.addObservers = Prototype.emptyFunction;

if (Prototype.Browser.IE) {
Autocompleter.Base.prototype.onBlur = function(event) {
	setTimeout((function(e) {
		if (this.dontBlur) {
			this.dontBlur = false;
			return;
		}
		this.hasFocus = false;
		this.active = false;
		this.hide();
		}).bind(this), 100);
	};
}

function checkSearchAge(year) {
    if (year >= 3) {
        $('ageMonth').style.display = 'none';
    } else {
        $('ageMonth').style.display = '';
    }
    return false;
}