var pagingRequest = false;

/*
 *	Once the window has completed loading install any required event observers for the page
 */
Event.observe(window, 'load', function() {
 // Neighborhood selector on package search, add and edit pages
 if ($('neighborhood_selector')) {
	Event.observe($('StateState'),'change',setState);
	Event.observe($('removeButton').down('em'),'click',removelocation);
	$('PackageLocation').activate();
	}
 // Site administrator page controls	
 if ($('admin')) {
 	$('DisplayPageNumber').value = 1;
	Event.observe($('StateState'),'change',setState);
	Event.observe($('StatisticsResultsBy'),'change',showAdminStatsParms);
	showAdminStatsParms();
	}
 // Control fee specification on Package add and edit pages	
  if ($('feestructure')) {
	  $('feestructure').select('input[type="checkbox"]').each( function(checkbox){
  		if (checkbox.checked) {setInputStatus(checkbox)};
  		Event.observe(checkbox,'click',clearPrecedingInputs);
  });
  }
 //Control behavior of tabbed panels 
  if ($('TabbedPanels1')) {
	  $('TabbedPanels1').select('textarea').each( function(textarea){
  		Event.observe(textarea,'keyup',limitTextAreaChars.bindAsEventListener(this, 200));});
  	  $('TabbedPanels1').select('li').each( function(textarea){
  		Event.observe(textarea,'focus', function() {$('charsleft').innerHTML ='';});
  });
  }
  //Control submission of multi-select neighborhood boxes
  if ($('package_form')) {
  	Event.observe('package_form','submit',selectAllNeighborhoods);
  }
  //Manage captcha processing on Package search pages
  if ($('captcha_image')) {
  	$('CaptchaUserMessage').hide();
    Event.observe('captcha_image','click',captchaRefresh);
  }
  //Handle requests to view Glossary entries
  $$('a.glossary').each(function (link) {
    Event.observe(link,'click',showGlossary);
    });
  //Resize the Glossary page when displayed  
  if ($('agentglossary')) {
  	 Event.observe(window,'focus',resizeGlossary);
  	 resizeGlossary();
  }
  // Respond to sorting of Package lists  
  if ($('DisplaySearchSort')) {
  	Event.observe('DisplaySearchSort','change',resort);
  	Event.observe('DisplaySearchValue','change',resort);
  	$('DisplayPageNumber').value = 1;
  }	
  // Hide or display the 'Other' field for agent brokerage
  if ($('AgentBrokerage') && $('AgentBrokerageOther')) {
  	Event.observe('AgentBrokerage','change',checkBrokerageChoice);
  	$check = checkBrokerageChoice();
  }	
  //Manage the display of the email contact form on a Profile page
  if ($('profile')) {
  	Event.observe('contactlink','click',showContactForm);
  }
  //Limit the number of characters that can be entered into the welcome message text area on the Profile page
  if ($('ProfileWelcomeMessage')) {
    	Event.observe('ProfileWelcomeMessage','keyup',limitTextAreaChars.bindAsEventListener(this, 500));
  }
  // If the enter key is pressed in the captcha dialog click the button
	 if ($('CaptchaCaptcha')) {
		Event.observe('CaptchaCaptcha','keyup', function (){
			if ($('CaptchaCaptcha').value.length == 4)
			{$('captcha_button').activate();}
		});	
	}	
});
//  When the users changes their preferred State (IL, NY etc.) make an Ajax request to update their session data
function setState(event) {
	if ($('area_selector')) {$('area_selector').remove();}
	new Ajax.Request('/states/setState/' + $F('StateState'));
}
// Take a location entered into the autocomplete field and add it into the location multiple select box if it doesnt already exist
function addlocation(event) {
	$id = $F('PackageLocationid');
	if (!$('Option' +$id)) {
		$option = '<option id="Option' + $id + '" value="' + $id + '">' + $F('PackageLocation') + '</option>'
		selectbox = $('NeighborhoodNeighborhood');
		selectbox.insert({top: $option});
		sortselectbox(selectbox);
		if ($('CaptchaRequireCaptcha')) {$('CaptchaRequireCaptcha').value = 'true';};
	}	
	$('addButton').stopObserving('click',addlocation);
	$('PackageLocation').value = '';
}
// Remove the selected location from the location multiple select box
function removelocation(event) {
	$selectedPosition = $('NeighborhoodNeighborhood').selectedIndex;
	$option = $('NeighborhoodNeighborhood').down($selectedPosition);
	$id = $option.value;
	$option.remove();
	$checkbox = 'Neighborhood' + $id;
	if ($($checkbox)) {$($checkbox).checked = false;};
	if ($('CaptchaRequireCaptcha')) {$('CaptchaRequireCaptcha').value = 'true';};
}

/**
 * Custom function to handle the processing of a location autocomplete field.  This special processing
 * takes the id from the selected option in the dropdown and stores it as the value of a hidden field with named
 * the same as the autocomplete field with 'id' appended to it.
 */
function updateAutoComplete($listitem){
	$strippedText = $listitem.innerHTML.replace(/(<([^>]+)>)/ig,"");
	$cols = $strippedText.split("|");
	$inputField = $listitem.up('div',1).down('input').identify();
	$idField = $inputField + 'id';
	$($inputField).value = $cols[0];
	$($idField).value = $cols[1];
	if ($('addButton')) {Event.observe($('addButton'),'click',addlocation)};
	addlocation();
}
/**
 * This function handles the display of the selected area in the Neighborhoods - Show All dialog.
 */
function showdiv(menuitem, $areadiv) {
$$('#area_selector div.area_neighborhoods').each( function(div){div.hide();});
$$('#area_selector ul li').each( function(li){li.removeClassName('selected');});
$($areadiv).show();
menuitem.addClassName('selected');
}
/**
 * This function displays the Neighborhoods - Show All dialog, displays the first area and checks any checkbox
 * that corresponds to an entry that existed in the multiple select list box.
 */
function show_neighborhoods () {
$$('#area_selector ul li').each( function(li, i){
	if (i==0) {
		li.addClassName('selected');
		}
	else {
		li.removeClassName('selected');
		}
	});	
$('all_neighborhoods').show();
$$('#area_selector div.area_neighborhoods').each( function(div, i){
	if (i==0) {div.show();} else {div.hide();} 
});
$$('#NeighborhoodNeighborhood option').each( function(option) {
	$checkbox = $('Neighborhood' + option.value);
	if ($checkbox) {$checkbox.checked = true;};
});
	$$('a.selectall').each(function(selectalllink) {
	Event.observe(selectalllink,'click',toggleAllNeighborhoods);
	});
}
/*
 * This function toggles all the checkboxes in the currently displayed Area
 */
function toggleAllNeighborhoods (){
	neighborhood = $(this).up('div.area_neighborhoods');
	action = $(this).innerHTML;
	neighborhood.select('input').each(function(checkbox){
		if (action == 'Select All') {
			checkbox.checked = true;
		} else {
			checkbox.checked = false;
		}
	});
	if (action == 'Select All') {
		$(this).innerHTML = 'Deselect All'
	} else {
		$(this).innerHTML  = 'Select All'
	}
} 
/**  This function executes when the Neighborhoods - Show All dialog is closed.  It inserts into the Neighborhoods multiple select
 *   box each of the locations for which a location was selected.
 */
function returnSelections() {
if ($('CaptchaRequireCaptcha')) {$('CaptchaRequireCaptcha').value = 'true';} //Require Captch as we have a change in locations
$('NeighborhoodNeighborhood').childElements().invoke('remove'); //Remove all the previous entries from the select box
$$('#area_selector input[type="checkbox"]').each( function(box){
if (box.checked) {
	$id = box.identify().replace(/Neighborhood/ig,"");
	if (!$('Option' +$id)) {
		$name = box.next('label').innerHTML;
 		$option = '<option id="Option' + $id + '" value="' + $id + '">' + $name + '</option>'
		$('NeighborhoodNeighborhood').insert({top: $option});
		}
	}}
);
		selectbox = $('NeighborhoodNeighborhood');
		sortselectbox(selectbox);
window.scrollTo(0,0); // Reposition to the top of the window
$('all_neighborhoods').hide(); //Hide the Show All dialog
}
/**
 *  This function is used to determine whether the list of neighborhoods for the current states has already been requested from the server.
 *  If it already has been retrieved the dialog is shown, if not we return true so that the Ajax request will execute.  
 */
function firstTimeThisState(){
	if ($('area_selector')) {
	show_neighborhoods();
	return(false);
	} else {
	return(true);
	}
}

/**
 *	This function formats currency fields with appropriate commas and periods
 */
function formatCurrency(field) {
num = $(field).value;
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num%100;
num = Math.floor(num/100).toString();
if(cents<10)
cents = "0" + cents;
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+
num.substring(num.length-(4*i+3));
$(field).value = (((sign)?'':'-') + num + '.' + cents);
}
/**
 *	This function formats percentage fields
 */
function formatPercent(field, decimals) {
num = $(field).value;
num = num.toString().replace(/\%|\,/g,'');
if(isNaN(num))
num = "0";
out = new Number(num);
$(field).value = out.toFixed(decimals);
}
/**
 *	This function responds to a checkbox beng checked/unchecked and calls setInputStatus to set the enable/disable states of the
 *  preceding input fields. It is used in the add and edit Package pages.
 */
function clearPrecedingInputs(event) {
    checkbox = Event.element(event);
    setInputStatus(checkbox);
}   

function setInputStatus(checkbox) {    
	priorElement = checkbox.previous();
	while (priorElement.innerHTML != '$') 
	{
		if (priorElement.match('input') 
	//	&& priorElement.readAttribute('type') == 'text'
		) 
		{
		if (checkbox.checked) 
			{
			if (priorElement.readAttribute('type') == 'text') {
				priorElement.value = ''; }
			else {
				priorElement.checked = false;
			};	
			priorElement.disabled = true;
			priorElement.style.backgroundColor = 'silver';
			} else {
			priorElement.disabled = false;
			priorElement.style.backgroundColor = 'white';
			}
		}
		priorElement = priorElement.previous();
	}
}
function limitTextAreaChars(event, count) {
	    textarea = Event.element(event);
	    if (textarea.value.length >count) {
	    	textarea.value = textarea.value.substr(0,count);
	    	} else {
	    	$('charsleft').innerHTML =  'Characters remaining: ' + (count - textarea.value.length);
	    	return(true)
	    	};
}	 
function resultsLoaded() {
	if ($('CaptchaMismatch')) {
		$('CaptchaUserMessage').show();
		captchaRefresh();
	} else {
	$('CaptchaRequireCaptcha').value = 'false';
	$('CaptchaUserMessage').hide();
	$('captcha').hide();
	captchaRefresh();
	$('NeighborhoodNeighborhood').select('option').each( function(option) {
		option.selected = false;
	});
	if ($('package_results')) {
		showColumn($('DisplayColumnindex').value);
		$('sort_options').show();
		} else { $('sort_options').hide();}
	}	
}	
function captchaRefresh() {
	$('captcha_image').src = '/packages/captcha/' + Math.random()*1000 ;
	$('CaptchaCaptcha').value = '';   
}
function selectAllNeighborhoods (event){
	neighborhoodCount = 0;
	$('NeighborhoodNeighborhood').select('option').each( function(option) {
		option.selected = true;
		neighborhoodCount++;
		});
	if (neighborhoodCount == 0) {
		alert('Please add at least one location to the list');
		Event.stop(event);
	}
	if (!$('service_level_10').checked && !$('service_level_20').checked) {
	   alert('Please select either Basic or Full Service');
	   Event.stop(event);
	}
	return(neighborhoodCount);
}	
function checkCapture(event) {
	if (!selectAllNeighborhoods(event)) {return (false)};

/*	if ($('CaptchaRequireCaptcha').value == 'true') { */
	if (false) { /* Commented out prior line and added this one to disable capture */
		$('captcha').show();
		$('CaptchaCaptcha').activate();
		return(false); }
	else {
		return(true);
		}
}		

/* Synthetic click of the find button uses different approaches for IE and Firefox */

function syntheticClick(button){
pagingRequest = true;
if(window.navigator.userAgent.indexOf("MSIE")> 0) {
button.click()
} else {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);
button.dispatchEvent(evt);
}
}
/* If the request about to be processes is a new find then set the page number back to one, else
process as a paging request with the current page number*/
function setPage() {
if (!pagingRequest) {
$('DisplayPageNumber').value = 1;
}
pagingRequest = false;
}
/*Increment the page counter and simulate a user click of the button*/

function nextpage(){
$('DisplayPageNumber').value = Number($('DisplayPageNumber').value) + 1;
syntheticClick($('search_button'));
}

/*Decrement the page counter and simulate a user click of the button*/

function previouspage(){
if (+$('DisplayPageNumber').value >1) {
$('DisplayPageNumber').value = Number($('DisplayPageNumber').value) - 1;};
syntheticClick($('search_button'));
}
function resort(){
chosenIndex = $('DisplaySearchSort').selectedIndex;
	 chosenText = $('DisplaySearchSort').options[chosenIndex].text;
	 if (chosenText == 'Agent Name' || chosenText == 'Shortest Term' ||
	     chosenText == 'Upfront Fees' || chosenText == 'Agreement Length'
	 ) {
	 $('priceoptions').hide()
	 } else
	 {
	 $('priceoptions').show()
	 };

syntheticClick($('search_button'));
}
function showGlossary(event){
 link =	Event.element(event);
 glossarywindow = document.open('/pages/glossary.shtml#' +  link.name,'Glossary','toolbar=no,status=no,location=no,height=1,width=1');
 glossarywindow.focus();
}
function resizeGlossary() { 
  	hash = location.hash;
  	glossaryEntry = hash.substring(1);
  	window.resizeTo($(glossaryEntry).getWidth(),$(glossaryEntry).getHeight()+200);
}
function showDetail(event) {
	leader = Event.element(event);
	$$('#home2 div.detail').each( function(div){div.hide();});
	detail = leader.up('div.leader').next('div.detail');
	detail.show();
}
function checkBrokerageChoice () {
	 chosenIndex = $('AgentBrokerage').selectedIndex;
	 chosenText = $('AgentBrokerage').options[chosenIndex].text;
	 if (chosenText == 'Other') {
	 $('AgentBrokerageOther').up('div').show()
	 } else
	 {
	 $('AgentBrokerageOther').up('div').hide()
	 };
}

/**
 *  This function controls showing and hiding the appropriate input fields on the management statistics page based upon the type of
 *  statistics that are being requested.
 */
function showAdminStatsParms() {
	chosenIndex = $('StatisticsResultsBy').selectedIndex;
	chosenText = $('StatisticsResultsBy').options[chosenIndex].text;
	switch (chosenText){
	case "By Neighborhood":
		$('brokerage').hide();
	    $('state').show();
	    $('location').show();
	    break;
	case "By Brokerage":
	    $('state').hide();
	    $('location').hide();
	    $('brokerage').show();
	    break;
	case "Totals":
		$('state').hide();
	    $('location').hide();
	    $('brokerage').hide();
	    break;
	};    
}
/**
 *	This function shows the agent contact form.
 */
function showContactForm () {
	$('contactform').show();
}
/** 
  *  This function hides the containing div.  It is used on the Profile view, Package Listing and Agent Listing to close detail dialogs
  */
function closeDiv() {
	$('close_icon').up('div',1).hide();
}	
/**
 *	This function is used on the Management/Admin page and ensures that if a request is made to show statistics by Nieghborhood
 *  that a neighborhood has in fact been entered.
 */

function locationSet() {
 chosenIndex = $('StatisticsResultsBy').selectedIndex;
 chosenText = $('StatisticsResultsBy').options[chosenIndex].text;
 if ($F('PackageLocationid') != ''  || chosenText != 'By Neighborhood') {
 	return(true); 
 } else {
 alert('Please enter a neighborhood'); 
 return(false);}	
}
function sortselectbox(selectbox) {
		std_array = $A(selectbox.options).slice(0);
		selectbox.length = 0;	 				
		std_array.sort(function(a,b){ return (a.text.toLowerCase() < b.text.toLowerCase() ) ?
			-1 : 1; });
		for (i=0;i<std_array.length; i++){
			selectbox.options[i] = std_array[i];
		};
}