function advanced_features_toggle(el)
{
	if($(el).visible())
	{
		Cookie.set('advanced_features', 0);
		new Effect.BlindUp($(el),{duration: 0.8});
	}
	else
	{
		Cookie.set('advanced_features', 1);
		new Effect.BlindDown($(el),{duration: 0.8});
	}
}

function advanced_schools_toggle(el)
{
	if($(el).visible())
	{
		Cookie.set(el, 0);
		new Effect.BlindUp($(el),{duration: 0.8});
	}
	else
	{
		Cookie.set(el, 1);
		new Effect.BlindDown($(el),{duration: 0.8});
	}
}

var aPropertyList = [];

function list_removeitem(oFrom,oTo){
	moveSelectedOptions(oFrom,oTo);
}

function list_moveitem(oFrom,oTo)
{
	var iItem = oTo.options.length;
	if (oFrom && oTo && iItem < 15)
	{
		moveSelectedOptions(oFrom,oTo);
	}
	else
	{
		gInfoBoxes.MB_Open('msgbox_shortime','Please do not add more than 15 subdivisions.');
	}
	selectAllOptions(oTo);
}

function UnselectTabsFromList(szTabs){
	var aItems = szTabs.split(',');
	for (var i = 0;i < aItems.length; i++)
	{
		var oEl = $('index-'+aItems[i]);
		if (oEl)
		{
			oEl.className = '';
		}
	}
}

function selectLetter(elmID,szChar,oNotIn){
	var oList = $(elmID);
	szChar = szChar.toLowerCase();
	
	UnselectTabsFromList('a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,oth');
	
	$('index-'+szChar).className = 'active';
	
	//Firefox handles this in a much better way.
	if (document.all == 'dd')
	{
		for(var i=0; i < oList.options.length; i++)
		{
			var oEl = oList[i];
			if (oEl)
			{
				var szChr1 = oEl.text.charAt(0).toLowerCase();
				var szgroup = oEl.text.substr(1,3).toLowerCase();

				if (szChr1 == szChar || szChar =='oth')
					oEl.show();
				else
					oEl.hide();
				
			}
		}
	} //End firefox
	else //Ie handles it
	{
		//See if we need to make a copy
		if (aPropertyList.length == 0)
		{
			//Sort
			//sortSelect(oList);
			
			for(var i=0; i < oList.options.length; i++)
			{
				var oEl = oList[i];
				var oItem = new Object();
				oItem.id = oEl.id;
				oItem.value = oEl.value;
				oItem.text = oEl.text;
				oItem.selected = oEl.selected;
				aPropertyList.push(oItem);
			}
		} //End Copy
		
		//Remove all items from list
		oList.options.length = 0; //let java clean up the memory

		//Add the items.
		for(var i=0; i < aPropertyList.length; i++)
		{
			var oEl = aPropertyList[i];
			var bflag = doesValueExistInOptions(oNotIn,oEl.value);
			if (oEl && bflag === false)
			{
				var szChr1 = oEl.text.charAt(0).toLowerCase();
				
					if (szChr1 == szChar)
					{
						var optn = document.createElement("OPTION");
						addOption(oList,oEl.text,oEl.value,oEl.selected);
					}
					else if (szChr1 != 'a' &&
							szChr1 != 'b' && szChr1 != 'c' && szChr1 != 'd' &&
							szChr1 != 'e' && szChr1 != 'f' && szChr1 != 'g' &&
							szChr1 != 'h' && szChr1 != 'i' && szChr1 != 'j' &&
							szChr1 != 'k' && szChr1 != 'l' && szChr1 != 'm' &&
							szChr1 != 'n' && szChr1 != 'o' && szChr1 != 'p' &&
							szChr1 != 'q' && szChr1 != 'r' && szChr1 != 's' &&
							szChr1 != 't' && szChr1 != 'u' && szChr1 != 'v' &&
							szChr1 != 'w' && szChr1 != 'x' && szChr1 != 'y' &&
							szChr1 != 'z' && szChar == 'oth')
					{
					var optn = document.createElement("OPTION");
					addOption(oList,oEl.text,oEl.value,oEl.selected);
					}
			}
		}

		sortSelect(oList);
	}
	
	return true;	
}

function dialogBox(type, el, message, delay) {
	//if(!delay) { var delay = 5; }
	if(type != null)
	{
		var dialog = new Control.Window(el,{ className: 'simple_window', closeOnClick: true});
	}
	else
	{
		var dialog = new Control.Modal(el,{ className: 'simple_window', closeOnClick: 'overlay'});
	}
	dialog.observe('afterOpen',function(){ 
		dialog.remoteContentLoaded=false;
		if(delay) {
			mytimer = setTimeout(function(){$(el).hide();}, (delay * 1000));
		}
	});
	dialog.observe('afterClose', function() { 
		dialog.container.update("");
		if(delay) {
			clearInterval(mytimer);
		}
	});
	
	switch(type) {
		case "success":
			dialog.container.insert("<p class=\"success\">"+message+"</p>");
			dialog.open();
		break;
		
		case "error":
			dialog.container.insert("<p class=\"error\">"+message+"</p>");
			dialog.open();
		break;
		
		case "notice":
			dialog.container.insert("<p class=\"notice\">"+message+"</p>");
			dialog.open();
		break;
		
		default:
			dialog.container.insert(message);
			dialog.open();
		break;
	}
}

function addFavorite(mlsid) {
	new Ajax.Request('/favorites/add/'+mlsid, {
		onComplete: function(transport) {
			var msg = $('favorite_'+mlsid);
			var response = transport.responseText;
			
			if (response == 'success') 
			{
				//msgbox_shortime //errmsg1
				gInfoBoxes.MB_Open('msgbox_shortime','Listing added to your <a href="/favorites.html">Favorites List</a>');
				//dialogBox('success', msg, 'Listing added to your <a href="/favorites">Favorites List</a>', 3); 
				$('favoriteType').update('<a class="dv-favorite-remove" href="javascript:void(0);" onclick="delFavorite(\''+mlsid+'\');" rel="nofollow">Remove Favorite</a>');
			}
			else if (response == 'invalid')
			{
				//dialogBox('error', msg, 'This listing is already in your favorites list.', 3);
				gInfoBoxes.MB_Open('msgbox_shortime','This listing is already in your favorites list.');
				$('favoriteType').update('<a class="dv-favorite-remove" href="javascript:void(0);" onclick="delFavorite(\''+mlsid+'\');" rel="nofollow">Remove Favorite</a></div>');
			}
			else if (response == 'limit_reached')
			{
				gInfoBoxes.MB_Open('msgbox_shortime','You have reached your limit of <strong>(20)</strong> Favorites. Please delete some before adding new favorites.');
				//dialogBox('notice', msg, 'You have reached your limit of <strong>(20)</strong> Favorites. Please delete some before adding new favorites.', 3);
			}
			else if (response == 'error')
			{
				//dialogBox('error', msg, 'There was an error adding this listing to your favorites list.', 3);
				gInfoBoxes.MB_Open('msgbox_shortime','There was an error adding this listing to your favorites list.');
			}
			else
			{
				gInfoBoxes.MB_Open('msgbox_shortime',response);
				//dialogBox(null, msg, response);
			}
			
			$('spinner').hide();
		},
		onLoading: function(request) {
			$('spinner').show();
		}
	});
}
function delFavorite(mlsid) {
	new Ajax.Request('/favorites/delete/'+mlsid, {
		onComplete: function(transport) {
			var msg = $('favorite_'+mlsid);
			var response = transport.responseText;
			
			if (response == 'success') 
			{
				//dialogBox('success', msg, 'Favorite Removed', 3);
				gInfoBoxes.MB_Open('msgbox_shortime','Favorite Removed');
				$('favoriteType').update('<a class="dv-favorite-add" href="javascript:void(0);" onclick="addFavorite(\''+mlsid+'\');" rel="nofollow">Add to Favorites</a>');
			}
			else if(response == 'not_in')
			{
				gInfoBoxes.MB_Open('msgbox_shortime','This listing is not in your <a href="/favorites.html">favorites list.</a>');
				//dialogBox('error', msg, 'This listing is not in your <a href="/favorites">favorites list.</a>', 3);
			}
			else if (response == 'error')
			{
				gInfoBoxes.MB_Open('msgbox_shortime','Unable to Delete Favorite');
				//dialogBox('error', msg, 'Unable to Delete Favorite', 3);
			}
			else
			{
				gInfoBoxes.MB_Open('msgbox_shortime',response);
				//dialogBox(null, msg, response);
			}

			$('spinner').hide();
		},
		onLoading: function(request) {
			$('spinner').show();
		}
	});
}

//livepipe window factory
var window_factory = function(container,options){
	var window_header = new Element('div',{  
		className: 'window_header'
	});
	var window_title = new Element('div',{
		className: 'window_title'
	});
	var window_close = new Element('div',{
		className: 'window_close'
	});
	var window_contents = new Element('div',{
		className: 'window_contents'
	});
	var w = new Control.Window(container,Object.extend({
        className: 'window',  
        closeOnClick: window_close,  
        draggable: window_header, 
		constrainToViewport: true,
		insertRemoteContentAt: window_contents,
		afterOpen: function(){
			window_title.update(container.readAttribute('title'))
		}
	},options || {})); 
		w.container.insert(window_header);
		window_header.insert(window_title);
		window_header.insert(window_close);
		w.container.insert(window_contents);
		return w;
};

/*
** Property Search
*/
function propertyCount() {
	new Ajax.Request('/listings/property_count', {
	 method:'post',
	 parameters: Form.serialize($('ListingSearchForm')),
	 onLoading: function(request) {
	 	Element.show("spinner");
		$('propcount').setStyle({background: 'none', border: 'none', float: 'left'});
		$('propcount').innerHTML = '';
	 	$('countBtn').value = 'Disabled For 4 Seconds';
	 	$('countBtn').disabled = true;
	}, 
	 onSuccess: function(){
		setTimeout(function(){$('countBtn').disabled=false; $('countBtn').value = 'Count Listings';},4000);
	   },
	 onComplete: function(resp) {
	 	Element.hide("spinner");
		$('propcount').setStyle({background: '#cc0000', border: '1px solid #ddd', float: 'left'});
		$('propcount').innerHTML = resp.responseText;
	 },
	 onFailure: function(){ alert('Could not find listing count. Please try again.') }
	});
}

/* 
** resets search fields
*/
function resetSearch() {
	if (typeof(ListingLp) != 'undefined' && ListingLp != null)
		$('ListingLp').value = 0;
	if (typeof(ListingHp) != 'undefined' && ListingHp != null)
		$('ListingHp').value = 999999999999;
	if (typeof(ListingBr) != 'undefined' && ListingBr != null)
		$('ListingBr').value = 0;
	if (typeof(ListingFba) != 'undefined' && ListingFba != null)
		$('ListingFba').value = 0;
	if (typeof(ListingHba) != 'undefined' && ListingHba != null)
		$('ListingHba').value = 0;
	if (typeof(ListingProperty) != 'undefined' && ListingProperty != null)
		$('ListingProperty').value = "";

	gElemCounter = [];
}

function unselectAll(element) {
	element = $(element) || document;
	if( element && element.getElementsByTagName ){
		var inputs = element.getElementsByTagName("input");
		for(var i = 0; inputs && i < inputs.length; i++){
			if(inputs[i].type == "checkbox") {
				inputs[i].checked = false;
			}
		}
	}
}

function save_search() {
	
	var alphaExp = /^[-_a-zA-Z\s\d]+$/;
	var result = $('result').value;
	
	if (result != null)
	{
		if(result.match(alphaExp) && result != "") 
		{
			$('result').value = result;
			gSSModal.close();
			return true;
		} 
		else 
		{
			alert('Please only use letters, numbers, spaces, dashes, and underscores');
			return false;
		}
	}
	else
	{
		return false;
	}
}

function toggleForms(type) {

	if(type == 'register')
	{
		$('ajaxLoginReg').update("<a href=\"javascript:void(0);\" onclick=\"toggleForms('login');\" title=\"Already Have a Profile?\">Already have a Profile? Login.</a>");
		$('ajaxLoginForm').hide();
		$('ajaxRegisterForm').show();
	}
	else
	{
		$('ajaxLoginReg').update("<a href=\"javascript:void(0);\" onclick=\"toggleForms('register');\" title=\"Create a Profile\">New? Create a Profile!</a>");
		$('ajaxRegisterForm').hide();
		$('ajaxLoginForm').show();
	}
}

function expandCities() { 
	if($('cities').getStyle('height') == "330px") {
		$('cities').setStyle({height: 85+"px"});
		$('cityToggle').update("Show More Cities...");
		$('cities').scrollTop = 0;
	} else {
		$('cities').setStyle({height: 330+"px"});
		$('cityToggle').update("Show Less Cities...");
	}
}

//Lets Overide the String object and add the trim function 
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

//Lets Overide the String object and add the ltrim function 
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}

//Lets Overide the String object and add the rtrim function 
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}


//Open Modal. Note now if you are using validation you need to add to it as well.
function OpenControlModal(oobject,szActView,szAjaxLnk,id,preqphone){
	if (oobject){
		switch (szActView) 
		{
			case 'listings/inquiry':
				oobject.MM_Get('/listings/contact/'+id,{viewevent:'listings/inquiry',formid:'MoreInfoForm',ajaxlink:szAjaxLnk+id,reqPhone:preqphone});
			break;

			case 'listings/schedule_showing':
				oobject.MM_Get('/listings/schedule_showing/'+id,{viewevent:'listings/schedule_showing',formid:'ScheduleShowingForm',ajaxlink:szAjaxLnk+id,reqPhone:preqphone});
			break;

			case '/listings/contact/':
				oobject.MM_Get(szActView+id,{viewevent:szActView,formid:'MoreInfoForm',ajaxlink:szAjaxLnk+id,reqPhone:preqphone});
			break;

			case '/listings/tell_a_friend/':
				oobject.MM_Get(szActView+id,{viewevent:szActView,formid:'TellAFriendForm',ajaxlink:szAjaxLnk+id,reqPhone:preqphone});
			break;

			case 'custom_listings/inquiry':
				oobject.MM_Get('/custom_listings/contact/'+id,{viewevent:'custom_listings/inquiry',formid:'MoreInfoForm',ajaxlink:szAjaxLnk+id,reqPhone:preqphone});
			break;
			
			case '/custom_listings/contact/':
				oobject.MM_Get(szActView+id,{viewevent:szActView,formid:'MoreInfoForm',ajaxlink:szAjaxLnk+id,reqPhone:preqphone});
			break;

			case '/custom_listings/tell_a_friend/':
				oobject.MM_Get(szActView+id,{viewevent:szActView,formid:'TellAFriendForm',ajaxlink:szAjaxLnk+id,reqPhone:preqphone});
			break;

			case '/mortgage_calculator/listing/':
				oobject.MM_Get(szActView+id,{viewevent:szActView,formid:'MortgageCalculatorForm',ajaxlink:szAjaxLnk+id,reqPhone:preqphone});
			break;

			case '/mortgage_calculator/custom_listing/':
				oobject.MM_Get(szActView+id,{viewevent:szActView,formid:'MortgageCalculatorForm',ajaxlink:szAjaxLnk+id,reqPhone:preqphone});
			break;

			case '/users/login/':
				oobject.MM_Get(szActView+id,{viewevent:szActView,formid:'UserLoginForm',ajaxlink:szAjaxLnk+id,reqPhone:preqphone});
			break;

			case '/users/register/':
				oobject.MM_Get(szActView+id,{viewevent:szActView,formid:'UserRegisterForm',ajaxlink:szAjaxLnk+id,reqPhone:preqphone});
			break;
			
			default:
				alert('Function OpenControlModal:: ['+szActView+'] not set in file common_frontend.js');
			break;
		}
		
	}
}


	//Handle the Gray out of Select Objects
	function MC_GrayoutSelect(oMin,oMax,oChange){
		var iMin;
		var iMinIndex;
		var iMax;
		var iMaxIndex;
		var iChangeTo;

		if (oMin && oMin)
		{
			iMin = oMin[oMin.selectedIndex].value;
			iMinIndex = oMin.selectedIndex;
				
			iMax = oMax[oMax.selectedIndex].value;
			iMaxIndex = oMax.selectedIndex;
			
			if (oChange == oMax)
				iChangeTo = iMinIndex;
			else
				iChangeTo = iMaxIndex;
				
			if (iMinIndex != 0 && iMaxIndex != 0 && iMinIndex > iMaxIndex)
			{
				alert('Note: '+iMin+' should be less than or equal to '+iMax+'.');
				if (oChange){
					oChange.selectedIndex = iChangeTo;		
				}	
			}	
		}
		
		MC_AdjustMin(oMin,oMax);
		MC_AdjustMax(oMin,oMax);		

		return true;
	}
	
	
	function MC_AdjustMin(omin,omax){
		
		var iminindex = omin.selectedIndex;
		var imaxindex = omax.selectedIndex;
		
		for(var i=1; i < omin.options.length; i++){
			if (i <= imaxindex || imaxindex == 0 )
				omin.options[i].className = 'selnormal';
			else	
				omin.options[i].className = 'selgray';
		}
	}
	
	function MC_AdjustMax(omin,omax){
		var iminindex = omin.selectedIndex;
		var imaxindex = omax.selectedIndex;
		
		for(var i=1; i < omax.options.length; i++){
			if (i < iminindex )
				omax.options[i].className = 'selgray';
			else	
				omax.options[i].className = 'selnormal';
		}
	}
	
	function RemoveInvalidChars(szstring,validchars)
	{
		if (szstring == '') return "";
		var vchr="";
		var badchr="";
		for (var i=0; i < szstring.length; i++)
		{
			var temp = "" + szstring.substring(i, i+1);
			if (validchars.indexOf(temp) == "-1")
				badchr = badchr + szstring.substring(i, i+1);
			else
			vchr = vchr + szstring.substring(i, i+1);
		}
	
	return vchr;
	}

	function createSlug(szStrToMake,oDst,validchars){
		if (szStrToMake != ''){
			var szstring = szStrToMake;
			//Lets remove any double, tripple spaces
			for (i=0;i<4;i++){
				szstring = szstring.replace(/  /g," ");
			}
			
			//Replace all spaces with -
			szstring = szstring.replace(/-/g," ");
			szstring = szstring.trim();
			szstring = szstring.replace(/ /g,"-");
			//Remove any invalid characters.
			szstring = RemoveInvalidChars(szstring,validchars);
			szstring = szstring.toLowerCase();
			if (oDst)
				oDst.value = szstring;
			
			return szstring;			
		}
		else{
		alert('Fields can not be located.');
		}
	}
	

	//European Phone number format. will add more soon.
	function formatPhone_EURO(oObject){
		if (!oObject.value.length) return true;
		if (oObject.value.length > 0)
		{
			noplus = oObject.value.substring(1,oObject.value.length);
			noplus = noplus.replace(/[^0-9 \(\)x\.]+/g,'');
			oObject.value = '+'+noplus;
		}
		return true;
	}

	//Us phone number format
	function formatPhone_US(oObject){
		var CharEleven = "";
		var numstrwithspace = "";
		var numStr = "";
		var dstValue = oObject.value;
	
		numStr = dstValue.replace(/[^0-9]+/g,'');
	
		if (oObject.value.length > 13){
			numstrwithspace = oObject.value.replace(/[^0-9 ]+/g,'');
			CharEleven = numstrwithspace.substring(10,11);
		}
	
		if (numStr == ''){oObject.value = numStr;return;}
	
		var newLength = numStr.length;
		var fNumber = "";
	
		if (newLength > 3 && newLength <=7){
			fNumber = fNumber + numStr.substring(0, 3) + '.' + numStr.substring(3, newLength);
		}
		else if (newLength > 7){
			fNumber = fNumber + '(' + numStr.substring(0, 3) + ')' + numStr.substring(3, 6) + '.';
	
			if (newLength > 10){
				fNumber = fNumber + numStr.substring(6,10);
				}
			else
				fNumber = fNumber + numStr.substring(6,newLength);
	
			if (numstrwithspace.length >= 11 && CharEleven == ' '){
					//Did they add the space?
					fNumber = fNumber + ' ';
				}
	
			if (newLength > 10){
				if (CharEleven == ' ')
					fNumber = fNumber + 'x';
				else
					fNumber = fNumber + ' x';
	
				fNumber = fNumber + numStr.substring(10, newLength);
			}
		}
		else{
			fNumber = numStr;
		}
	
		oObject.value = fNumber;
	
		return true;	
	}
	
	//Phone Number :: ^[\+]{0,1}([0-9]){1,3}[- ]{0,1}[\\(\]]{0,1}([0-9]){3}[\\)\]]{0,1}[ -\.]?([^0-1]){1}([0-9]){2}[ ]?[-]?[ ]?([0-9]){4}[ ]*((x){0,1}([0-9]){1,5}){0,1}$
	//return Validation.get('IsEmpty').test(v) || /^[\+]{0,1}([0-9]){1,3}[- ]{0,1}[\\(\]]{0,1}([0-9]){3}[\\)\]]{0,1}[ -\.]?([^0-1]){1}([0-9]){2}[ ]?[-]?[ ]?([0-9]){4}[ ]*((x){0,1}([0-9]){1,5}){0,1}$/i.test(v);
	function formatPhone(oObject)
	{
		//If the number starts with + we are assuming international
		euro = oObject.value.substring(0,1);
	
		if (euro == '+')
			return formatPhone_EURO(oObject);
		else
			return formatPhone_US(oObject);
	
		return true;
	}	
	
	//This function will handle the detail property map tabs.
	function Myrsol_detailmaptabs(id,tabprefixtoshow,styleprefixtoshow)
	{
		//Hide them all
		if ($('view-googlemap_'+id)) { $('view-googlemap_'+id).hide(); }
		if ($('view-streetview_'+id)){ $('view-streetview_'+id).hide(); }
		if ($('view-birdseye_'+id)) { $('view-birdseye_'+id).hide(); }
		if ($('view-walkscore_'+id)) { $('view-walkscore_'+id).hide(); }
		if ($('view-trulia_'+id)) { $('view-trulia_'+id).hide(); }
		
		//Set all styles to default
		if ($('googlemapLI_'+id)){
			$('googlemapLI_'+id).setStyle({backgroundColor: '#eee'});
		}

		if ($('streetviewLI_'+id)){
			$('streetviewLI_'+id).setStyle({backgroundColor: '#eee'});
		}

		if ($('birdseyeLI_'+id)){
			$('birdseyeLI_'+id).setStyle({backgroundColor: '#eee'});
		}

		if ($('walkscoreLI_'+id)){
			$('walkscoreLI_'+id).setStyle({backgroundColor: '#eee'});
		}
		
		if ($('truliaLI_'+id)){
			$('truliaLI_'+id).setStyle({backgroundColor: '#eee'});		
		}
		
		
		//Select the one they want
		if ($(tabprefixtoshow+id)){
			$(tabprefixtoshow+id).show();

		}
		
		if ($(styleprefixtoshow+id)){
			$(styleprefixtoshow+id).setStyle({backgroundColor: '#DAEFF6'});
		}
		
		if (tabprefixtoshow == 'view-streetview_')
		{
			//$('svmap_'+id).show();
			//gStreetMap.hide();
			//gStreetView.show();
		}
		else if (tabprefixtoshow == 'view-googlemap_')
			{
			//gStreetMap.show();
			//gStreetView.hide();
			}

		return true;
	}
	
	
function M_Loadimagetosrc(elemid,imgsrc){
	var oimg = $(elemid);
	if (!oimg) return false;
	oimg.onload=null;	
	oimg.src = imgsrc;
	
/*	if (imgerrsrc && imgerrsrc != '')
		oimg.onerror = function(){M_Loadimagetosrc(elemid,imgerrsrc,'')};
	else
		oimg.onerror = '';
*/		
	//alert(elemid+' '+imgsrc+ ' '+imgerrsrc);
	//return true;
}

function M_LoadimagetosrcByObject(oimg,imgsrc){
	if (!oimg) return false;
	oimg.onload=null;	
	oimg.src = imgsrc;
	//alert(elemid+' '+imgsrc+ ' '+imgerrsrc);
	//return false;
}

function M_nrSelectCheckBox(szname,bvalue)
{
	var olist = $$('input');
	var icount = 0;
	for (var i = 0; i <olist.length; i++)
	{
		 if (olist[i].type == 'checkbox' && olist[i].name == szname)
		 {
			el = olist[i];
			if (el.checked == bvalue)
			{
				icount++;
			}
		 }
	}
	
	return icount;
}

function M_GetListSelectCheckBox(szname,bvalue)
{	var alist = Array();
	var olist = $$('input');
	var icount = 0;
	for (var i = 0; i <olist.length; i++)
	{
		 if (olist[i].type == 'checkbox' && olist[i].name == szname)
		 {
			el = olist[i];
			if (el.checked == bvalue)
			{
				alist.push(el.value);
			}
		 }
	}
	
	return alist;
}

//Multi Box functions here
///////////////////////////////////////////////
function M_togglemultiboxes(how,whatgroup,whatid)
{
	var icount = 0;
	$('class_type_fieldset').hide();
	for (var i=0; i < gMultiBoxes.length; i++)
	{
		var oMulti = gMultiBoxes[i];
		var oselect = $(oMulti.selectid);
		var oitem = $(oMulti.containerid);
		var oparent = $(oMulti.parentid);
		var parentname = oMulti.parentname;
		icount = M_nrSelectCheckBox(parentname,true);
		
		if (oMulti.group == whatgroup || whatgroup == '')
		{
			switch (how)
			{
				case "hide":
					if (oMulti.containerid == whatid || whatid == '')
					{
						if (oitem)
						{
							oitem.hide();
						}
					}
				break;
				case "show":
					if (oMulti.containerid == whatid || whatid == '')
					{
						if (oitem)
						{
							oitem.show();
						}
					}
				break;
				case "showhide": //show whatid and hide the rest
				case "hideshow": //hide whatid and show the rest
					if (oparent && oitem)
					{
						if (oparent.checked && icount <=1)
						{
							if (how == 'showhide')
							{
								$('class_type_fieldset').show();
								oitem.show();
								Element.insert($('class_types'),{before:oitem});
								if (oselect) oselect.enable();
							}
							else	
							{
								oitem.hide();
								if (oselect) oselect.disable();
							}
						}
						else
						{
							if (how == 'hideshow')
							{
								$('class_type_fieldset').show();
								oitem.show();
								if (oselect) oselect.enable();
							}
							else
							{
								oitem.hide();
								if (oselect) oselect.disable();
							}
						}
							
					}
				break;
			}
		}

		//Kick out if we have done our job
		if (oMulti.containerid == whatid && whatid != '' && how != 'showhide' && how != 'hideshow')
			return true;
		
	}
	
	return true;
}	
	
//
//This is loaded for every page on the backend.
//

//Predefine Array of invalid browsers
var gAssetsRoot = 'http://assets.myrsol.com/';
var szloadimg = 'http://assets.myrsol.com/ajax-loader.gif';
var gBrowserType = 'CCBot 1.0';
var gwalkscoreapi = '';
var gMyrsolObserver = null;


//////////////////////////////////////
//Cooke for ToolTips Enabled
//////////////////////////////////////
var gToolTipsActive = false;
if (Cookie.get('tooltips_enabled') == null || Cookie.get('tooltips_enabled') == '1')
{
	gToolTipsActive = true;
}

var gInfoBoxes = null;
var gBrowserDetected = null;
var gBrowserList = new Array();
//gBrowserList['MSIE 6.0'] = "Microsoft Internet Explorer 6";
//gBrowserList['Firefox 3.0.1'] = "Firefox Ver 3.0.1";
//gBrowserList['Firefox 3.0.2'] = "Firefox Ver 3.0.2";
//gBrowserList['Firefox 3.0.3'] = "Firefox Ver 3.0.3";
//gBrowserList['notusedyet'] = "Microsoft Internet Explorer 6";


var gBrowserDetected = null;

document.observe('dom:loaded', function() {
	//Not this must be used if you wish to use the triggers.
	if (typeof(gInfoBoxes) == 'undefined' || gInfoBoxes == null){
		//Info Boxes
		gInfoBoxes = new MyrsolBox({id:'HelpModals'});
			
	}	

	//Create Default Dialogs that are used through the product.									
	gInfoBoxes.MB_Add({fid:'loading_mask',targetId:'center',openOnCreate:false/*,autoCloseAfter:4000*/,content:'<p class="loader"><img src="'+szloadimg+'" alt="Loading..."/><br/>Please wait...</p>'},{closeOnClick:false,width:250});
	gInfoBoxes.MB_Add({fid:'errmsg1',targetId:'center',openOnCreate:false,content:''},{closeOnClick:true,width:250});
	gInfoBoxes.MB_Add({fid:'reg_errors',targetId:'center',openOnCreate:false,content:''},{closeOnClick:true,width:450});
	gInfoBoxes.MB_Add({fid:'msgbox_shortime',targetId:'center',openOnCreate:false/*,autoCloseAfter:2000*/,content:''},{closeOnClick:true,width:250});

	//////////////////////////////////////
	//Browser Detected Cookie and Message
	//////////////////////////////////////
	//gBrowserDetected = Cookie.get('browser_status');
	//var checkbrowser = gBrowserList[gBrowserType];
	//if (typeof(checkbrowser) == 'undefined')
		//checkbrowser = 'na';
		
	//alert('list '+gBrowserType+' chk '+checkbrowser);

	//if ('MSIE 6.0' == gBrowserType && gBrowserDetected == null)
	//{
//		if (typeof(gBrowserType) != 'undefined' && typeof(checkbrowser) != 'undefined' && gBrowserDetected == null && typeof(gBrowserList[gBrowserType]) != 'undefined' && gBrowserList[gBrowserType] != '' && checkbrowser != 'na')
		//{
			//gInfoBoxes.MB_Open('errmsg1','If you are currently using '+checkbrowser+' which is an outdated browser. We recommend a newer browser that supports newer web standards such as Mozilla Firefox 3.0, or Internet Explorer 7.0/8.0.<br /><br />Please upgrade as soon as you can to take full advantage of all the great features in this product.');
	//	}
	//}
	
	//Cookie.set('browser_status', '1',99999999);
	
});	

/* protofish-min.js - http://techblog.procurios.nl/k/618/news/view/34556/14863/ProtoFish-advanced-hover-menu-based-on-Prototype.html */
var ProtoFish=Class.create({initialize:function(d,b,a,c){this.id=d;this.timeout=(b==undefined)?"400":b;this.cssClass=(a==undefined)?"hover":a;this.remActive=(c==undefined)?false:c;this.queue=[];this.activeTimeout="";if($(d)&&$(d).down()){this.listItems=$(d).select("li");this.activeItems=$(d).select("li.active");this.initObservers()}},initObservers:function(){this.listItems.each(function(a){a.observe("mouseover",function(c,b){this.enterMenu(b);b.addClassName(this.cssClass)}.bindAsEventListener(this,a));a.observe("mouseleave",function(c,b){this.queue.push([this.leaveMenu.delay(this.timeout/1000,this),b])}.bindAsEventListener(this,a));a.down().observe("focus",function(c,b){b.addClassName(this.cssClass)}.bindAsEventListener(this,a));a.down().observe("blur",function(c,b){if(!b.down("li")){b.removeClassName(this.cssClass);while(b.up("li")&&!b.next("li")){b.up("li").removeClassName(this.cssClass);b=b.up("li")}}}.bindAsEventListener(this,a))}.bind(this))},enterMenu:function(){while(this.queue.length){clearTimeout(this.queue[0][0]);this.leaveMenu(this)}if(this.remActive==true){if(typeof this.activeTimeout=="number"){clearTimeout(this.activeTimeout);delete this.activeTimeout}this.activeItems.invoke("removeClassName","active")}},leaveMenu:function(b){if(b.queue.length){var a=b.queue.shift()[1];a.removeClassName(b.cssClass)}if(b.remActive==true){b.activeItems.invoke("addClassName","active")}}});

/* fader-min.js - http://www.eternal.co.za/scripts/fader/ */
if(typeof Widget=="undefined"){Widget={}}Widget.Fader=Class.create({initialize:function(A,C,B){this.img=$(A);this.list=C;this.options=Object.extend({id:this.img.id,fadeInDuration:2.5,fadeOutDuration:1.5,displayDuration:2.5,autoSize:false,autoStart:true,attributes:{},dir:"",beforeFade:null,startIndex:0,builder:Widget.Fader.imageBuilder},B||{});this.options.attributes.id=this.options.id;this.index=this.options.startIndex;this.container=$(this.img.parentNode);this.loadedObserver=this.loaded.bind(this);this.fadeInObserver=this.fadeIn.bind(this);this.nextObserver=this.next.bind(this);if(this.options.autoStart){setTimeout(this.start.bind(this),this.options.displayDuration*1000)}},start:function(){this.stopped=false;this.next()},stop:function(){this.stopped=true;try{clearTimeout(this.timeout)}catch(A){}try{Effect.Queues.get(this.options.id).each(function(B){B.cancel()})}catch(A){}if(this.oldImg){this.img=this.oldImg;--this.index}Element.setOpacity(this.img,1)},next:function(){this.oldImg=this.img;if(this.stopped||this.list.length==0){return }++this.index;if(this.index>=this.list.length){this.index=0}this.img=this.options.builder(this,this.list[this.index],this.loadedObserver)},loaded:function(){Event.stopObserving(this.img,"load",this.loadedObserver);if(typeof this.options.beforeFade=="function"){this.options.beforeFade(this.oldImg,false)}new Effect.Opacity(this.oldImg,{duration:this.options.fadeOutDuration,from:1,to:0,queue:{scope:this.options.id}});this.timeout=setTimeout(this.fadeInObserver,this.options.fadeOutDuration*1000)},fadeIn:function(){if(typeof this.options.beforeFade=="function"){this.options.beforeFade(this.img,true)}this.img.id=this.id;Element.setOpacity(this.img,0);if(this.options.autoSize){this.resize(this.img)}this.container.replaceChild(this.img,this.oldImg);this.oldImg=null;new Effect.Opacity(this.img,{duration:this.options.fadeInDuration,from:0,to:1,queue:{scope:this.options.id}});this.timeout=setTimeout(this.nextObserver,(this.options.fadeInDuration+this.options.displayDuration)*1000)},resize:function(B){var F=this.container.getDimensions();F.width-=parseInt(this.container.getStyle("padding-left"))+parseInt(this.container.getStyle("padding-right"))+parseInt(this.container.getStyle("border-left-width"))+parseInt(this.container.getStyle("border-right-width"));F.height-=parseInt(this.container.getStyle("padding-top"))+parseInt(this.container.getStyle("padding-bottom"))+parseInt(this.container.getStyle("border-top-width"))+parseInt(this.container.getStyle("border-bottom-width"));var C=F.width/B.width;var E=F.height/B.height;var A=B.width*E;var D=B.height*C;if(C>E){B.width=A;B.height=F.height}else{B.width=F.width;B.height=D}}});Widget.Fader.imageBuilder=function(D,C,B){var A=new Element("img",D.options.attributes);A.observe("load",B);A.src=D.options.dir+C;return A};Widget.Fader.textBuilder=function(C,B,A){var D=new Element("div",C.options.attributes).update(B);A.defer();return D};var Fader=Widget.Fader;

/**
	//modified line 53 (addControls function) for pastawithgustoandmore.com
	Copyright (c) 2009 Filippo Buratti; info [at] cssrevolt.com [dot] com; http://www.filippoburatti.net/

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/

var Protofade = Class.create({

	initialize: function(element, options) {		
		this.options = {
      		Duration: 1,
			Delay: 4.0,
			Random: false,
			Slideshow:true,
			Controls:false
    	}
		Object.extend(this.options, options || {});

    	this.element        = $(element);
		this.slides			= this.element.childElements();
		this.num_slides		= this.slides.length;		
		this.current_slide 	= (this.options.Random) ? (Math.floor(Math.random()*this.num_slides)) : 0;
		this.end_slide		= this.num_slides - 1;
		
		this.slides.invoke('hide');
		this.slides[this.current_slide].show();
				
		if (this.options.Slideshow) { 
			this.startSlideshow();
		}				
		if (this.options.Controls) {
			this.addControls();
		}		
	},
	
	addControls: function() {
		this.wrapper 		= this.element.up();
		this.controls		= new Element('div', { 'class': 'controls' });
		this.wrapper.insert(this.controls);
		
		this.btn_next 		= new Element('a', { 'class': 'next', 'title': 'Next', href: '#' }).update('Next');
		this.btn_previous	= new Element('a', { 'class': 'previous', 'title': 'Previous', href: '#' }).update('Previous');
		this.btn_start		= new Element('a', { 'class': 'start', 'title': 'Start', href: '#' }).update('Start');
		this.btn_stop		= new Element('a', { 'class': 'stop', 'title': 'Stop', href: '#' }).update('Stop');
		
		this.btns = [this.btn_next, this.btn_previous, this.btn_start, this.btn_stop];
		this.btns.each(function(el){
			this.controls.insert(el);
		}.bind(this));
		
		this.btn_previous.observe('click', this.moveToPrevious.bindAsEventListener(this));
		this.btn_next.observe('click', this.moveToNext.bindAsEventListener(this));
		this.btn_start.observe('click', this.startSlideshow.bindAsEventListener(this));
		this.btn_stop.observe('click', this.stopSlideshow.bindAsEventListener(this));
	},

	startSlideshow: function(event) {
		if (event) { Event.stop(event); }
		if (!this.running)	{
			this.executer = new PeriodicalExecuter(function(){
	  			this.updateSlide(this.current_slide+1);
	 		}.bind(this),this.options.Delay);
			this.running=true;
		}
	},
	
	stopSlideshow: function(event) {	
		if (event) { Event.stop(event); } 
		if (this.executer) { 
			this.executer.stop();
			this.running=false;
		}	 
	},

	moveToPrevious: function (event) {
		if (event) { Event.stop(event); }
		this.stopSlideshow();
  		this.updateSlide(this.current_slide-1);
	},

	moveToNext: function (event) {
		if (event) { Event.stop(event); }
		this.stopSlideshow();
  		this.updateSlide(this.current_slide+1);
	},
	
	updateSlide: function(next_slide) {
		
		if (next_slide > this.end_slide) { 
				next_slide = 0; 
		} 
		else if ( next_slide == -1 ) {
				next_slide = this.end_slide;
		}
		
		this.fadeInOut(next_slide, this.current_slide);		
	},

 	fadeInOut: function (next, current) {		
		new Effect.Parallel([
			new Effect.Fade(this.slides[current], { sync: true }),
			new Effect.Appear(this.slides[next], { sync: true }) 
  		], { duration: this.options.Duration });
		
		this.current_slide = next;		
	}

});

//---------------------------------------------------------------------------
//----------------------LOGIN Javascript-------------------------------------
//---------------------------------------------------------------------------

function ajax_registerUser(){
	var id = 0;
	
	// hide submit button when pressed... because this could take awhile.
	$('registrationSubmit').hide();	
	
	//Call Server
	new Ajax.Request('/users/ajaxhandler/register/'+id, {
	  parameters: Form.serialize($('UserRegisterForm')), 				 
	  method: 'POST',
	  onSuccess: registerUser_CB,
	  loading: gInfoBoxes.MB_Open('loading_mask')
	});

	return false;
}

function registerUser_CB(oReq, oJSN){
	// hide submit button when pressed... because this could take awhile.
	$('registrationSubmit').show();	
	gInfoBoxes.MB_Close('loading_mask');
	
	if (oReq)
	{
		var oData = oReq.responseText.evalJSON(true);

		//Errors
		if (oData.status != 0 ){
			gInfoBoxes.MB_Open('reg_errors',oData.msg);
			return;
		}
		else if (oData.status == 0){
			window.location = oData.redirect_url;
		}
		
		//New message here.

	}
	return true;		
}


//Login ajax call
function ajax_loginUser(){
	var id = 0;
	
	// hide submit button when pressed... because this could take awhile.
	$('loginSubmit').hide();	
	
	//Call Server
	new Ajax.Request('/users/ajaxhandler/login/'+id, {
	  method: 'POST',
	  parameters: Form.serialize($('UserLoginForm')), 
	  onSuccess: loginUser_CB,
	  loading: gInfoBoxes.MB_Open('loading_mask')
	});			

	return false;
}

//login ajax call back
function loginUser_CB(oReq, oJSN){
	// hide submit button when pressed... because this could take awhile.
	$('loginSubmit').show();
	gInfoBoxes.MB_Close('loading_mask');
	
	if (oReq)
	{
		var oData = oReq.responseText.evalJSON(true);

		//Errors
		if (oData.status != 0 ){
			gInfoBoxes.MB_Open('errmsg1',oData.msg);	
			return;
		}
		else if (oData.status == 0){
			window.location = oData.redirect_url;
		}
		
		//New message here.
		
	}
	return true;		
}

//---------------------------------------------------------------------------


/*

CUSTOM FORM ELEMENTS

Created by Ryan Fait
www.ryanfait.com

The only things you may need to change in this file are the following
variables: checkboxHeight, radioHeight and selectWidth (lines 24, 25, 26)

The numbers you set for checkboxHeight and radioHeight should be one quarter
of the total height of the image want to use for checkboxes and radio
buttons. Both images should contain the four stages of both inputs stacked
on top of each other in this order: unchecked, unchecked-clicked, checked,
checked-clicked.

You may need to adjust your images a bit if there is a slight vertical
movement during the different stages of the button activation.

The value of selectWidth should be the width of your select list image.

Visit http://ryanfait.com/ for more information.

*/

var checkboxHeight = "10";
var radioHeight = "25";
var selectWidth = "190";


/* No need to change anything after this */


document.write('<style type="text/css">input.styled { display: none; } select.styled { position: relative; width: ' + selectWidth + 'px; opacity: 0; filter: alpha(opacity=0); z-index: 5; } .disabled { opacity: 0.5; filter: alpha(opacity=50); }</style>');

var Custom = {
	init: function() {
		var inputs = document.getElementsByTagName("input"), span = Array(), textnode, option, active;
		for(a = 0; a < inputs.length; a++) {
			if((inputs[a].type == "checkbox" || inputs[a].type == "radio") && inputs[a].className == "styled") {
				span[a] = document.createElement("span");
				span[a].className = inputs[a].type;

				if(inputs[a].checked == true) {
					if(inputs[a].type == "checkbox") {
						position = "0 -" + (checkboxHeight*2) + "px";
						span[a].style.backgroundPosition = position;
					} else {
						position = "0 -" + (radioHeight*2) + "px";
						span[a].style.backgroundPosition = position;
					}
				}
				inputs[a].parentNode.insertBefore(span[a], inputs[a]);
				inputs[a].onchange = Custom.clear;
				if(!inputs[a].getAttribute("disabled")) {
					span[a].onmousedown = Custom.pushed;
					span[a].onmouseup = Custom.check;
				} else {
					span[a].className = span[a].className += " disabled";
				}
			}
		}
		inputs = document.getElementsByTagName("select");
		for(a = 0; a < inputs.length; a++) {
			if(inputs[a].className == "styled") {
				option = inputs[a].getElementsByTagName("option");
				active = option[0].childNodes[0].nodeValue;
				textnode = document.createTextNode(active);
				for(b = 0; b < option.length; b++) {
					if(option[b].selected == true) {
						textnode = document.createTextNode(option[b].childNodes[0].nodeValue);
					}
				}
				span[a] = document.createElement("span");
				span[a].className = "select";
				span[a].id = "select" + inputs[a].name;
				span[a].appendChild(textnode);
				inputs[a].parentNode.insertBefore(span[a], inputs[a]);
				if(!inputs[a].getAttribute("disabled")) {
					inputs[a].onchange = Custom.choose;
				} else {
					inputs[a].previousSibling.className = inputs[a].previousSibling.className += " disabled";
				}
			}
		}
		document.onmouseup = Custom.clear;
	},
	pushed: function() {
		element = this.nextSibling;
		if(element.checked == true && element.type == "checkbox") {
			this.style.backgroundPosition = "0 -" + checkboxHeight*3 + "px";
		} else if(element.checked == true && element.type == "radio") {
			this.style.backgroundPosition = "0 -" + radioHeight*3 + "px";
		} else if(element.checked != true && element.type == "checkbox") {
			this.style.backgroundPosition = "0 -" + checkboxHeight + "px";
		} else {
			this.style.backgroundPosition = "0 -" + radioHeight + "px";
		}
	},
	check: function() {
		element = this.nextSibling;
		if(element.checked == true && element.type == "checkbox") {
			this.style.backgroundPosition = "0 0";
			element.checked = false;
		} else {
			if(element.type == "checkbox") {
				this.style.backgroundPosition = "0 -" + checkboxHeight*2 + "px";
			} else {
				this.style.backgroundPosition = "0 -" + radioHeight*2 + "px";
				group = this.nextSibling.name;
				inputs = document.getElementsByTagName("input");
				for(a = 0; a < inputs.length; a++) {
					if(inputs[a].name == group && inputs[a] != this.nextSibling) {
						inputs[a].previousSibling.style.backgroundPosition = "0 0";
					}
				}
			}
			element.checked = true;
		}
	},
	clear: function() {
		inputs = document.getElementsByTagName("input");
		for(var b = 0; b < inputs.length; b++) {
			if(inputs[b].type == "checkbox" && inputs[b].checked == true && inputs[b].className == "styled") {
				inputs[b].previousSibling.style.backgroundPosition = "0 -" + checkboxHeight*2 + "px";
			} else if(inputs[b].type == "checkbox" && inputs[b].className == "styled") {
				inputs[b].previousSibling.style.backgroundPosition = "0 0";
			} else if(inputs[b].type == "radio" && inputs[b].checked == true && inputs[b].className == "styled") {
				inputs[b].previousSibling.style.backgroundPosition = "0 -" + radioHeight*2 + "px";
			} else if(inputs[b].type == "radio" && inputs[b].className == "styled") {
				inputs[b].previousSibling.style.backgroundPosition = "0 0";
			}
		}
	},
	choose: function() {
		option = this.getElementsByTagName("option");
		for(d = 0; d < option.length; d++) {
			if(option[d].selected == true) {
				document.getElementById("select" + this.name).childNodes[0].nodeValue = option[d].childNodes[0].nodeValue;
			}
		}
	}
}
window.onload = Custom.init;
