var status_list = new Array("Current", "Expired", "Pending", "Sold", "Withdrawn");
var cstatus_list = new Array("NewListing", "BackOnMarket", "Pending", "Sold", "OffMarket", "PriceChange");

var counties = new Array();

counties["ME"] = new Array();
counties["ME"]["Aroostook"] = new Object();
counties["ME"]["Aroostook"].selected = false;
counties["ME"]["Aroostook"].towns = new Array("Allagash","Amity","Ashland","Bancroft","Blaine","Bridgewater","Caribou","Cary","Castle Hill","Caswell","Chapman","Crystal","Cyr","Dyer Brook","Eagle Lake","Easton","Fort Fairfield","Fort Kent","Frenchville","Garfield","Glenwood","Grand Isle","Hamlin","Hammond","Haynesville","Hersey","Hodgdon","Houlton","Island Falls","Limestone","Linneus","Littleton","Ludlow","Macwahoc","Madawaska","Mapleton","Mars Hill","Masardis","Merrill","Monticello","Moro","Nashville","New Canada","New Limerick","New Sweden","Oakfield","Orient","Oxbow","Perham","Portage Lake","Presque Isle","Reed","Saint Agatha","Saint Francis","Saint John","Sherman","Smyrna","Stockholm","Unorganized Aro","Van Buren","Wade","Wallagrass","Washburn","Westfield","Westmanland","Weston","Winterville","Woodland");

counties["ME"]["Cumberland"] = new Object();
counties["ME"]["Cumberland"].selected = false;
counties["ME"]["Cumberland"].towns = new Array("Baldwin","Bridgton","Brunswick","Cape Elizabeth","Casco","Cumberland","Falmouth","Freeport","Frye Island","Gorham","Gray","Harpswell","Harrison","Long Island","Naples","New Gloucester","North Yarmouth","Portland","Pownal","Raymond","Scarborough","Sebago","South Portland","Standish","Westbrook","Windham","Yarmouth");

counties["ME"]["York"] = new Object();
counties["ME"]["York"].selected = false;
counties["ME"]["York"].towns = new Array("Acton","Alfred","Arundel","Berwick","Biddeford","Buxton","Cornish","Dayton","Eliot","Hollis","Kennebunk","Kennebunkport","Kittery","Lebanon","Limerick","Limington","Lyman","Newfield","North Berwick","Ogunquit","Old Orchard Beach","Parsonsfield","Saco","Sanford","Shapleigh","South Berwick","Waterboro","Wells","York");

counties["ME"]["Knox"] = new Object();
counties["ME"]["Knox"].selected = false;
counties["ME"]["Knox"].towns = new Array("Appleton","Camden","Cushing","Friendship","Hope","Isle Au Haut","Matinicus Isle","North Haven","Owls Head","Rockland","Rockport","Saint George","South Thomaston","Thomaston","Union","Unorganized Kno","Vinalhaven","Warren","Washington");

counties["ME"]["Lincoln"] = new Object();
counties["ME"]["Lincoln"].selected = false;
counties["ME"]["Lincoln"].towns = new Array("Alna","Boothbay","Boothbay Harbor","Bremen","Bristol","Damariscotta","Dresden","Edgecomb","Jefferson","Monhegan Island","Newcastle","Nobleboro","Somerville","South Bristol","Southport","Unorganized Lin","Waldoboro","Westport","Whitefield","Wiscasset");

counties["ME"]["Sagadahoc"] = new Object();
counties["ME"]["Sagadahoc"].selected = false;
counties["ME"]["Sagadahoc"].towns = new Array("Arrowsic","Bath","Bowdoin","Bowdoinham","Georgetown","Phippsburg","Richmond","Topsham","Unorganized Sag","West Bath","Woolwich");

counties["ME"]["Waldo"] = new Object();
counties["ME"]["Waldo"].selected = false;
counties["ME"]["Waldo"].towns = new Array("Belfast","Belmont","Brooks","Burnham","Frankfort","Freedom","Islesboro","Jackson","Knox","Liberty","Lincolnville","Monroe","Montville","Morrill","Northport","Palermo","Prospect","Searsmont","Searsport","Stockton Springs","Swanville","Thorndike","Troy","Unity","Unorganized Wal","Waldo","Winterport");

counties["ME"]["Piscataquis"] = new Object();
counties["ME"]["Piscataquis"].selected = false;
counties["ME"]["Piscataquis"].towns = new Array("Abbot","Atkinson","Beaver Cove","Bowerbank","Brownville","Dover Foxcroft","Greenville","Guilford","Kingsbury","Lake View","Medford","Milo","Monson","Parkman","Sangerville","Sebec","Shirley","Unorganized Pis","Wellington","Willimantic");

counties["ME"]["Hancock"] = new Object();
counties["ME"]["Hancock"].selected = false;
counties["ME"]["Hancock"].towns = new Array("Amherst","Aurora","Bar Harbor","Blue Hill","Brooklin","Brooksville","Bucksport","Castine","Cranberry Isles","Dedham","Deer Isle","Eastbrook","Ellsworth","Franklin","Frenchboro","Gouldsboro","Great Pond Plt","Hancock","Lamoine","Mariaville","Mount Desert","Orland","Osborn","Otis","Penobscot","Sedgwick","Sorrento","Southwest Harbor","Stonington","Sullivan","Surry","Swans Island","Tremont","Trenton","Unorganized Han","Verona","Waltham","Winter Harbor");

counties["ME"]["Oxford"] = new Object();
counties["ME"]["Oxford"].selected = false;
counties["ME"]["Oxford"].towns = new Array("Andover","Bethel","Brownfield","Buckfield","Byron","Canton","Denmark","Dixfield","Embden","Fryeburg","Gilead","Greenwood","Hanover","Hartford","Hebron","Hiram","Lovell","Magalloway","Mexico","Newry","Norway","Otisfield","Oxford","Paris","Peru","Porter","Roxbury","Rumford","Stoneham","Stow","Sumner","Sweden","Unorganized Oxf","Upton","Waterford","West Paris","Woodstock");

counties["ME"]["Somerset"] = new Object();
counties["ME"]["Somerset"].selected = false;
counties["ME"]["Somerset"].towns = new Array("Anson","Athens","Bingham","Brighton","Cambridge","Canaan","Caratunk","Cornville","Dennistown","Detroit","Fairfield","Harmony","Hartland","Jackman","Madison","Mercer","Moose River","Moscow","New Portland","Norridgewock","Palmyra","Pittsfield","Pleasant Ridge","Ripley","Saint Albans","Skowhegan","Smithfield","Solon","Starks","The Forks","Unorganized Som","West Forks");

counties["ME"]["Androscoggin"] = new Object();
counties["ME"]["Androscoggin"].selected = false;
counties["ME"]["Androscoggin"].towns = new Array("Auburn","Durham","Greene","Leeds","Lewiston","Lisbon","Livermore","Livermore Falls","Mechanic Falls","Minot","Poland","Sabattus","Turner","Wales");

counties["ME"]["Washington"] = new Object();
counties["ME"]["Washington"].selected = false;
counties["ME"]["Washington"].towns = new Array("Addison","Alexander","Baileyville","Baring","Beals","Beddington","Calais","Centerville","Charlotte","Cherryfield","Codyville","Columbia","Columbia Falls","Cooper","Crawford","Cutler","Danforth","Deblois","Dennysville","East Machias","Eastport","Grand Lake Stream","Harrington","Jonesboro","Jonesport","Lubec","Machias","Machiasport","Marshfield","Meddybemps","Milbridge","Northfield","Passamaquoddy Indian Township","Passamaquoddy Pleasant Point","Pembroke","Perry","Princeton","Robbinston","Roque Bluffs","Steuben","Talmadge","Topsfield","Unorganized Was","Vanceboro","Waite","Wesley","Whiting","Whitneyville");

counties["ME"]["Franklin"] = new Object();
counties["ME"]["Franklin"].selected = false;
counties["ME"]["Franklin"].towns = new Array("Avon","Carrabassett Valley","Carthage","Chesterville","Coplin","Dallas","Eustis","Farmington","Industry","Jay","Kingfield","Madrid","New Sharon","New Vineyard","Phillips","Rangeley","Sandy River","Strong","Temple","Unorganized Fra","Weld","Wilton");

counties["ME"]["Penobscot"] = new Object();
counties["ME"]["Penobscot"].selected = false;
counties["ME"]["Penobscot"].towns =new Array("Alton","Bangor","Bradford","Bradley","Brewer","Burlington","Carmel","Carroll","Charleston","Chester","Clifton","Corinna","Corinth","Dexter","Dixmont","Drew","East Millinocket","Eddington","Edinburg","Enfield","Etna","Exeter","Garland","Glenburn","Greenbush","Hampden","Hermon","Holden","Howland","Hudson","Kenduskeag","Lagrange","Lakeville","Lee","Levant","Lincoln","Lowell","Mattawamkeag","Maxfield","Medway","Milford","Millinocket","Mount Chase","Newburgh","Newport","Old Town","Orono","Orrington","Passadumkeag","Patten","Penobscot Indian Island","Plymouth","Seboeis","Springfield","Stacyville","Stetson","Unorganized Pen","Veazie","Webster","Winn","Woodville");

counties["ME"]["Kennebec"] = new Object();
counties["ME"]["Kennebec"].selected = false;
counties["ME"]["Kennebec"].towns = new Array("Albion","Augusta","Belgrade","Benton","Chelsea","China","Clinton","Farmingdale","Fayette","Gardiner","Hallowell","Litchfield","Manchester","Monmouth","Mount Vernon","Oakland","Pittston","Randolph","Readfield","Rome","Sidney","Vassalboro","Vienna","Waterville","Wayne","West Gardiner","Windsor","Winslow","Winthrop");

counties["NH"] = new Array();
counties["NH"]["Belknap"] = new Object();
counties["NH"]["Belknap"].selected = false;
counties["NH"]["Belknap"].towns = new Array("Alton","Barnstead","Belmont","Center Harbor","Gilford","Gilmanton","Laconia","Meredith","New Hampton","Sanbornton","Tilton");

counties["NH"]["Carroll"] = new Object();
counties["NH"]["Carroll"].selected = false;
counties["NH"]["Carroll"].towns = new Array("Albany","Bartlett","Brookfield","Chatham","Conway","Eaton","Effingham","Freedom","Harts Location","Jackson","Madison","Moultonboro","Ossipee","Sandwich","Tamworth","Tuftonboro","Wakefield","Wolfeboro");

counties["NH"]["Cheshire"] = new Object();
counties["NH"]["Cheshire"].selected = false;
counties["NH"]["Cheshire"].towns = new Array("Alstead","Chesterfield","Dublin","Fitzwilliam","Gilsum","Harrisville","Hinsdale","Jaffrey","Keene","Marlborough","Marlow","Nelson","Richmond","Rindge","Roxbury","Stoddard","Sullivan","Surry","Swanzey","Troy","Walpole","Westmoreland","Winchester");

counties["NH"]["Coos"] = new Object();
counties["NH"]["Coos"].selected = false;
counties["NH"]["Coos"].towns = new Array("Berlin","Carroll","Clarksville","Colebrook","Columbia","Dalton","Dummer","Errol","Gorham","Jefferson","Lancaster","Milan","Northumberland","Pittsburg","Randolph","Shelburne","Stark","Stewartstown","Stratford","Whitefield");

counties["NH"]["Grafton"] = new Object();
counties["NH"]["Grafton"].selected = false;
counties["NH"]["Grafton"].towns = new Array("Alexandria","Ashland","Bath","Benton","Bethlehem","Bridgewater","Bristol","Campton","Canaan","Dorchester","Easton","Ellsworth","Enfield","Franconia","Grafton","Groton","Hanover","Haverhill","Hebron","Holderness","Landaff","Lebanon","Lincoln","Lisbon","Littleton","Lyman","Lyme","Monroe","Orange","Orford","Piermont","Plymouth","Rumney","Sugar Hill","Thornton","Warren","Waterville","Wentworth","Woodstock");

counties["NH"]["Hillsborough"] = new Object();
counties["NH"]["Hillsborough"].selected = false;
counties["NH"]["Hillsborough"].towns = new Array("Amherst","Antrim","Bedford","Bennington","Brookline","Deering","Francestown","Goffstown","Greenfield","Greenville","Hancock","Hillsborough","Hollis","Hudson","Litchfield","Lyndeborough","Manchester","Mason","Merrimack","Milford","Mont Vernon","Nashua","New Boston","New Ipswich","Pelham","Peterborough","Sharon","Temple","Weare","Wilton","Windsor");

counties["NH"]["Merrimack"] = new Object();
counties["NH"]["Merrimack"].selected = false;
counties["NH"]["Merrimack"].towns = new Array("Allenstown","Andover","Boscawen","Bow","Bradford","Canterbury","Chichester","Concord","Danbury","Dunbarton","Epsom","Franklin","Henniker","Hill","Hooksett","Hopkinton","Loudon","Newbury","New London","Northfield","Pembroke","Pittsfield","Salisbury","Sutton","Warner","Webster","Wilmot");

counties["NH"]["Rockingham"] = new Object();
counties["NH"]["Rockingham"].selected = false;
counties["NH"]["Rockingham"].towns = new Array("Atkinson","Auburn","Brentwood","Candia","Chester","Danville","Deerfield","Derry","East Kingston","Epping","Exeter","Fremont","Greenland","Hampstead","Hampton","Hampton Falls","Kensington","Kingston","Londonderry","New Castle","Newfields","Newington","Newmarket","Newton","North Hampton","Northwood","Nottingham","Plaistow","Portsmouth","Raymond","Rye","Salem","Sandown","Seabrook","South Hampton","Stratham","Windham");

counties["NH"]["Strafford"] = new Object();
counties["NH"]["Strafford"].selected = false;
counties["NH"]["Strafford"].towns = new Array("Barrington","Dover","Durham","Farmington","Lee","Madbury","Middleton","Milton","New Durham","Rochester","Rollinsford","Somersworth","Strafford");

counties["NH"]["Sullivan"] = new Object();
counties["NH"]["Sullivan"].selected = false;
counties["NH"]["Sullivan"].towns = new Array("Acworth","Charlestown","Claremont","Cornish","Croydon","Goshen","Grantham","Langdon","Lempster","Newport","Plainfield","Springfield","Sunapee","Unity","Washington");

var i, c, j; 
if( active_counties ) {
  for( state in active_counties ) {
	if (state == 'ME') { // temporary
   	  for( i = 0; i < active_counties[state].length; ++i ) {
	    cnty = active_counties[state][i];
        counties[state][cnty].img    = new Image();
        counties[state][cnty].img_on = new Image();
        counties[state][cnty].img.src    = "/images/" + cnty + ".gif";
        counties[state][cnty].img_on.src = "/images/" + cnty + "_on.gif";
	    counties[state][cnty].active = 1;
	  }
	}
  }
}

function clearTownSelect(state)
{
  var towns_sel = document.page_form.elements[state + "_towns_selected[]"];
  while (towns_sel.length) {
    towns_sel.options[towns_sel.length-1] = null;
  }
  var towns = document.page_form.elements[state + "_towns[]"];
  for(i=0; i<towns.length; i++){
    towns.options[i].selected = false;
  }
   var towns_selected_str = "";
  for (state in counties) {
    var towns_sel = document.page_form.elements[state + "_towns_selected[]"];
	for (var i = 0; i < towns_sel.length; ++i) {
	  towns_selected_str += ((towns_selected_str)?",":"") + towns_sel.options[i].value;
	}
  }
  
  document.page_form.towns_selected.value = towns_selected_str;
}

function initTowns()
{
  for (var state in counties) {
    var counties_sel = document.page_form.elements[state + "_counties[]"];
   if(counties_sel){	
	  var counties_sel_map = new Array();
	  for (var i = 0; i < counties_sel.length; ++i) {
	    counties_sel_map[counties_sel.options[i].value] = i;
	  }
      if(counties_selected[state]){
	    if( (state == "ME" && counties_selected[state].length != 16) || (state == "NH" && counties_selected[state].length != 10) ){
	      for (i = 0; i < counties_selected[state].length; ++i) {
	        if (counties_sel.options[counties_sel_map[state + "|" + counties_selected[state][i]]]) {
			  counties_sel.options[counties_sel_map[state + "|" + counties_selected[state][i]]].selected = true;
	        }
	      }
	    }
	  }
	  else{
	    if(wasRedefined != 1){
		//Clear Means Clear
		  //counties_sel.options[0].selected = true;         //Changed 9/30/2004  remmed
	    }
	  }
	  
	selectActiveCounties(counties_sel, state);
 }//end if counties_sel
    var towns_sel = document.page_form.elements[state + "_towns[]"];
	var towns_sel_map = new Array();
	//towns_sel.options[0].selected = false;
if(towns_sel){
	for (i = 0; i < towns_sel.length; ++i) {
	  towns_sel_map[towns_sel.options[i].value] = i;
	}

	
	if(towns_selected[state]){
	  towns_sel.options[0].selected = false;
	  for (i = 0; i < towns_selected[state].length; ++i) {
	    if (towns_sel.options[towns_sel_map[state + "|" + towns_selected[state][i]]]) {
	     //if(document.page_form.elements["thisDocument"].value == "prefs"){
		   towns_sel.options[towns_sel_map[state + "|" + towns_selected[state][i]]].selected = true;
          //}
	    }
	  }
	}
	else{
	  if(wasRedefined != 1){
	    //Clear Means Clear
		//towns_sel.options[0].selected = true;              //Changed 9/30/2004 remmed out
	  }
	}
	 
	selectActiveTowns(towns_sel, state);
}//end towns_sel
  }//end for state in counties
}

function selectCounty(p_county)
/*
 * (Un)selects the provided 'county', then (re)populates the towns multi-select box.
 used for map onclick event only
 */
{
  var arr = p_county.split('|');
  var state = arr[0];
  var county = arr[1];

  //_toggleCountySelect(state, county);	
  _toggleCountySelectMap(state, county);	
  buildTownList(state);
  
  _setCountiesSelected();
}

function selectAllCounties(state)
{

    var i=0;
    var counties_sel = document.page_form.elements[state + "_counties[]"];
    for (i=0; i<counties_sel.length; i++){
      if(i<2){}//counties_sel.options[i].selected = true;}
      else{counties_sel.options[i].selected=false;}
    }

  var county = "";
  if(active_counties[state]){
    for (county in active_counties[state]) {
      for(i=0; i < active_counties[state].length; i++){ 
        county = active_counties[state][i];
	    if (!counties[state][county].selected) {
          _toggleCountySelect(state, county);
	    }
      }
    }
  }  
  _setCountiesSelected();
  buildTownList(state);
 
}

function selectActiveCounties(county_sel, state)
{ 
  if(county_sel.options[1].selected == true){
    county_sel.options[1].selected = false;
	county_sel.options[0].selected = true;
  }
  counties_changed = new Array();
  num_counties_selected = 0;
  for( i = 2; i < county_sel.length; ++i) {                    //9/30/2004  Changed 2 to 0 and back again
    var arr = county_sel.options[i].value.split("|");
	var county = arr[1];
//alert(county_sel.options[i].selected + " : " + counties[state][county].selected);
    if (counties[state][county] && county_sel.options[i].selected != counties[state][county].selected) {
	  counties_changed[counties_changed.length] = county;
	}
	if (county_sel.options[i].selected) {
	  ++num_counties_selected;
	}
  }
if (county_sel[0].selected) { // if ALL is selected ...
    if (num_counties_selected >= 1) {
      for(i=1; i < county_sel.length; i++){
	    county_sel[i].selected = false;
	  }
	}
	else {
	  selectAllCounties(state);
	  return;
	}
  }
  else{
    if(num_counties_selected == 0 ){
      //county_sel[0].selected = true;
      //selectAllCounties(state);
     buildTownList(state);
	 return;
	}
  }
  for (var i = 0; i < counties_changed.length; i++) {
    _toggleCountySelect(state, counties_changed[i]);
  }
  _setCountiesSelected();
  buildTownList(state);
 
}

function buildTownList(state)
{
var towns_sel = document.page_form.elements[state + "_towns[]"];
  var base_town_list = new Array("ALL", "------------------------------------------------");
  var town_list = new Array();

  for (county in counties[state]) {
    if (counties[state][county].selected) {
     town_list = town_list.concat(counties[state][county].towns);
	}
  }

  town_list.sort();
  
  town_list = base_town_list.concat(town_list);
  
  while (town_list.length < towns_sel.length) {  
	towns_sel.options[(towns_sel.length - 1)] = null;
  }

  for (var i = 0; i < town_list.length; ++i) {
    towns_sel.options[i] = new Option(town_list[i], state + "|" + town_list[i]);
  }
  var goahead = "NO";
  var counties_sel = document.page_form.elements[state + "_counties[]"];
  if(counties_sel){
    for(i=0; i<counties_sel.length; i++){
	  if(counties_sel.options[i].selected == true){
	    goahead = "YES";
	  }
    }
  }
  if(goahead == "YES"){
    towns_sel.options[0].selected = true;
  }
//////////////////////  IF WE ARE IN SEARCH ////////////////////////////
/*  if(document.page_form.elements["thisDocument"].value == "search"){
    towns_sel.options[0].selected = true;
  }
  */
  selectActiveTowns(towns_sel, state);
  _setTownsSelected();
}

function selectActiveTowns(towns_sel, state)
{
  towns_sel.options[1].selected = false;

  var num_towns_selected = 0;
  for (var i = 2; i < towns_sel.length; ++i) {
    if (towns_sel.options[i].selected) {
	  ++num_towns_selected;
	}
  }
  
  if (towns_sel.options[0].selected && num_towns_selected > 0) {
    for(i=1; i<towns_sel.length; i++){
      towns_sel.options[i].selected = false;
    }
  }
  else if(num_towns_selected == 0){
    //towns_sel.options[0].selected = true;
  }
/* 
  if(towns_sel.options[0].selected == false && num_towns_selected == 0){
    towns_sel.options[0].selected = true;
  }
 */ 
  _setTownsSelected();
}

function _setCountiesSelected()
{
  var counties_selected_str = "";
  for (state in counties) {
    var counties_sel = document.page_form.elements[state + "_counties[]"];
	if(counties_sel){
	  for (var i = 0; i < counties_sel.length; ++i) {
	    if (counties_sel.options[i].selected) {
	      counties_selected_str += ((counties_selected_str)?",":"") + counties_sel.options[i].value;
	    }
	  }
    }
  
  document.page_form.counties_selected.value = counties_selected_str;
  }
}

function _setTownsSelected()
{ 
  var towns_selected_str = "";
  for (state in counties) {
    var towns_sel = document.page_form.elements[state + "_towns[]"];
    if(towns_sel){
	  for (var i = 0; i < towns_sel.length; ++i) {
	    if (towns_sel.options[i].selected) {
	      towns_selected_str += ((towns_selected_str)?",":"") + towns_sel.options[i].value;
		  //towns_sel.options[i].selected = false;
	    }
	  }
    }
  }
  document.page_form.towns_selected.value = towns_selected_str;
}

function _toggleCountySelect(state, county)
{
var frm = document.page_form;
   counties[state][county].selected = !counties[state][county].selected;
  if(counties[state][county].active == 1){	
	if( state == 'ME' && frm.elements[county]) {	
	  frm.elements[county].src = ((counties[state][county].selected)?counties[state][county].img_on.src:counties[state][county].img.src);
	}
  }
	_setCountiesSelected();
}
function _toggleCountySelectMap(state, county){
var frm = document.page_form;
  counties[state][county].selected = !counties[state][county].selected;
	if( state == 'ME' ) {
	  //frm.elements[county].src = ((counties[state][county].selected)?counties[state][county].img_on.src:counties[state][county].img.src);
	  for(var i=2; i < frm.elements["ME_counties[]"].length; i++){
		if( frm.elements["ME_counties[]"].options[i].value == (state + "|" + county)){ 
   	      frm.elements[county].src = ((counties[state][county].selected)?counties[state][county].img_on.src:counties[state][county].img.src);
		  //frm.elements[county].src = ((frm.elements["ME_counties[]"].options[i].selected)?counties[state][county].img_on.src:counties[state][county].img.src);
	      frm.elements["ME_counties[]"].options[i].selected = ((counties[state][county].selected)?true:false);
	    
		}
	  }

	  frm.elements["ME_counties[]"].options[0].selected = false;
	  frm.elements["ME_counties[]"].options[1].selected = false;

	}
	_setCountiesSelected();
}

function selectState(state)
{
}

function validateIDXForm()
{
  var frm = document.page_form;

  if( frm.MLSNbr.value ) { return true; }

  var basicCrit = false;
  if( frm.MLSNbr.value ) { basicCrit = true; }
  else if( frm.town && frm.town.value ) { basicCrit = true; }
  else if( frm.zip && frm.zip.value  ) { basicCrit = true; }
  else if( frm.elements["ME_towns[]"] && frm.elements["ME_towns[]"].selectedIndex != -1 ) { basicCrit = true; }
  else if( frm.elements["NH_towns[]"] && frm.elements["NH_towns[]"].selectedIndex != -1 ) { basicCrit = true; }
  if( !basicCrit ) {
    alert("You must type an MLS Number, Town, Zip Code, or select a town in the town list box.");
    return false;
  }

  var propType = false;
  var flds = new Array("Single_Family", "Multi_Family", "Condominium", "All_Categories", "Mobile_Home", "Land", "Commercial");
  for( idx in flds ) {
    if( eval("frm." + flds[idx]) && eval("frm." + flds[idx] + ".checked") ) { propType = true; }
  }

  if( !propType ) {
    alert("You must select one or more options under the Property Type section.");
    return false;
  }

  return true;
}

function validateMNForm()
{
  var frm = document.page_form;

  if( frm.MLSNbr.value ) { return true; }
  if(frm.OfficeListingsButton.value == 'goahead'){
    frm.OfficeListingsButton.value = "";
	return true;
  }
  if(frm.MyListingsButton.value == 'goahead'){
    frm.MyListingsButton.value = "";
	return true;
  }
  var basicCrit = false;
  if( frm.MLSNbr.value ) { basicCrit = true; }
  else if( frm.town && frm.town.value ) { basicCrit = true; }
  else if( frm.zip && frm.zip.value  ) { basicCrit = true; }
 else if( frm.elements["ME_towns[]"] && frm.elements["ME_towns[]"].selectedIndex != -1 ) { basicCrit = true; }
  else if( frm.elements["NH_towns[]"] && frm.elements["NH_towns[]"].selectedIndex != -1 ) { basicCrit = true; }
  if( !basicCrit ) {
    alert("You must type an MLS Number, Town, Zip Code, or select a town in the town list box.");
    return false;
  }

  var propType = false;
  var flds = new Array("Single_Family", "Multi_Family", "Condominium", "All_Categories", "Mobile_Home", "Land", "Commercial");
  for( idx in flds ) {
    if( eval("frm." + flds[idx]) && eval("frm." + flds[idx] + ".checked") ) { propType = true; }
  }

  if( !propType ) {
    alert("You must select one or more options under the Property Type section.");
    return false;
  }

  var cstatus = false;
  var cflds = new Array("CStatus_NewListing", "CStatus_BackOnMarket", "CStatus_Pending", "CStatus_Sold", "CStatus_OffMarket", "CStatus_PriceChange");
  for( var idx in cflds ) {
    if( eval("frm." + cflds[idx]) && eval("frm." + cflds[idx] + ".checked") ) { cstatus = true; }
  }
  if( !cstatus ) {
    var status = false;
    var flds = new Array("Current", "Expired", "Pending", "Sold", "Withdrawn");
    for( var idx in flds ) {
      if( eval("frm.Status_" + flds[idx]) && eval("frm.Status_" + flds[idx] + ".checked") ) { status = true; }
    }
    if( !status ) {
      alert("You must select one or more options under the Status or Status Changed To section.");
      return false;
    }
  }
  
  //Hotsheet or Activity
  if (frm.status_drop.options[2].selected || frm.status_drop.options[3].selected) {
    if (frm.cdays_back.options[0].selected) {
		if (!isDate(frm.cfrom_date.value, "MM/dd/yyyy")) {
			alert("From date is blank or invalid.");
			return false;
		}
		if (!isDate(frm.cto_date.value, "MM/dd/yyyy")) {
			alert("To date is blank or invalid.");
			return false;
		}
	}
  }

  return true;
}

function selectAllStatus()
{
  var frm = document.page_form;
  for( idx in status_list ) {
    if( eval("frm.Status_" +status_list[idx]) ) { eval("frm.Status_" + status_list[idx] + ".checked = true"); }
  }
}
function selectNoneStatus()
{
  var frm = document.page_form;
  for( idx in status_list ) {
    if( eval("frm.Status_" +status_list[idx]) ) { eval("frm.Status_" + status_list[idx] + ".checked = false"); }
  }
  
}

function selectAllCStatus()
{
  var frm = document.page_form;
  for( idx in cstatus_list ) {
    if( eval("frm.CStatus_" +cstatus_list[idx]) ) { eval("frm.CStatus_" + cstatus_list[idx] + ".checked = true"); }
  }
}
function selectNoneCStatus()
{
  var frm = document.page_form;
  for( idx in cstatus_list ) {
    if( eval("frm.CStatus_" +cstatus_list[idx]) ) { eval("frm.CStatus_" + cstatus_list[idx] + ".checked = false"); }
  }
}

function changedDaysBack()
{
  if( document.page_form.cdays_back.selectedIndex ) {
    document.page_form.cfrom_mo.selectedIndex = 0;
    document.page_form.cfrom_dy.selectedIndex = 0;
    document.page_form.cto_mo.selectedIndex   = 0;
    document.page_form.cto_dy.selectedIndex   = 0;
    document.page_form.cfrom_yr.selectedIndex = 0;
    document.page_form.cto_yr.selectedIndex   = 0;
  }
  else {
    // these work because the numeric day or month happens to be the same
    // value as the corresponding selectedIndex value for that day/month
    document.page_form.cfrom_mo.selectedIndex = default_cfrom_mo;
    document.page_form.cfrom_dy.selectedIndex = default_cfrom_dy;
    document.page_form.cto_mo.selectedIndex   = default_cto_mo;
    document.page_form.cto_dy.selectedIndex   = default_cto_dy;

    // year is only slighly trickier
    document.page_form.cfrom_yr.selectedIndex = default_cfrom_yr - base_year;
    document.page_form.cto_yr.selectedIndex   = default_cto_yr   - base_year;
  }
}

function changedDateRange()
{
  validateHotsheetFromDate();
  document.page_form.cdays_back.selectedIndex = 0;
}

function getSelectedSavedSearch()
{
  var el = document.page_form.saved_search;

  if( el ) {
    // if el is an array
    if( el.length ) {
      for(var i = 0; i < el.length; ++i) {
        if(el[i].checked) {
          return el[i].value;
        }
      }
    }
    // el is a simple element
    else {
      if(el.checked) {
        return el.value;
      }
    }
  }

  return -1;
}

function validateHotsheetFromDate()
{
  var frm = document.page_form;

  var yr = frm.cfrom_yr.options[frm.cfrom_yr.selectedIndex].value;
  var mo = frm.cfrom_mo.options[frm.cfrom_mo.selectedIndex].value;
  var dy = frm.cfrom_dy.options[frm.cfrom_dy.selectedIndex].value;

  // the default month, day, and year (from date cannot be earlier than this date)
  var def_yr = "1997";
  var def_mo = "1";
  var def_dy = "1";


  // check the selected from date
  var change = 0;
  if( yr < def_yr ) {
    yr = def_yr;
    mo = def_mo;
    dy = def_dy;
    change = 1;
  }
  else if( yr == def_yr && mo < def_mo ) {
    mo = def_mo;
    dy = def_dy;
    change = 1;
  }
  else if( yr == def_yr && mo == def_mo && dy < def_dy ) {
    dy = def_dy;
    change = 1;
  }

  // set the new date if there was a change
  if( change ) {
    for( var i = 0; i < frm.cfrom_yr.length; ++i ) {
      if( frm.cfrom_yr.options[i].value == yr ) {
        frm.cfrom_yr.options.selectedIndex = i;
      }
    }
    for( var i = 0; i < frm.cfrom_mo.length; ++i ) {
      if( frm.cfrom_mo.options[i].value == mo ) {
        frm.cfrom_mo.options.selectedIndex = i;
      }
    }
    for( var i = 0; i < frm.cfrom_dy.length; ++i ) {
      if( frm.cfrom_dy.options[i].value == dy ) {
        frm.cfrom_dy.options.selectedIndex = i;
      }
    }
  }

}


//*****************************************************************************
//********************     Preferences Form Functions     *********************
//*****************************************************************************

function validatePrefsForm(frm)
{
  var def_prop_type = frm.def_prop_type[frm.def_prop_type.selectedIndex].value;

  if( eval("frm." + def_prop_type + ".checked") == true )
  {
    alert("You must select a default property type that has not been deselected.  Change the default property type and try again.");
    frm.def_prop_type.focus();
    return false;
  }

  // select all towns in the towns_selected box
  
  var ME_towns_sel_op = document.page_form.elements["ME_towns_selected[]"].options;
  for( var i = 0; i < ME_towns_sel_op.length; ++i ) {
    ME_towns_sel_op[i].selected = true;
  }
  var NH_towns_sel_op = document.page_form.elements["NH_towns_selected[]"].options;
  for( var i = 0; i < NH_towns_sel_op.length; ++i ) {
    NH_towns_sel_op[i].selected = true;
  }

  return true;
}

function ptClick(el)
{
  if( el.name == 'All_Categories' ) {
    if(el.checked == true){
	  el.form.Single_Family.checked = true;  
	  el.form.Multi_Family.checked  = true;
	  el.form.Condominium.checked   = true; 
	  el.form.Mobile_Home.checked   = true; 
	  el.form.Land.checked          = true; 
	  el.form.Commercial.checked    = true;
	}
	else{
	  el.form.Single_Family.checked = false;  
	  el.form.Multi_Family.checked  = false;
	  el.form.Condominium.checked   = false; 
	  el.form.Mobile_Home.checked   = false; 
	  el.form.Land.checked          = false; 
	  el.form.Commercial.checked    = false;
    }
  }
  else {
    if( el.form.Single_Family.checked == true &&  
	                  el.form.Multi_Family.checked  == true &&
	  				  el.form.Condominium.checked   == true &&
					  el.form.Mobile_Home.checked   == true && 
					  el.form.Land.checked          == true &&
					  el.form.Commercial.checked    == true ) {
      el.form.All_Categories.checked = true;
    }
    else {
      if( el.form.Single_Family.checked == false || 
                            el.form.Multi_Family.checked  == false ||
                            el.form.Condominium.checked   == false ||
                            el.form.Mobile_Home.checked   == false ||
                            el.form.Land.checked          == false ||
                            el.form.Commercial.checked    == false    ) {
        el.form.All_Categories.checked = false;
      }
    }
  }
  return true;
}

function ptAllCatChange(el)
{
  if( el.name == 'All_Categories' )
  {
    if( el.form.Single_Family.checked == true || 
                    el.form.Multi_Family.checked  == true ||
                    el.form.Condominium.checked   == true ||
                    el.form.Mobile_Home.checked   == true ||
                    el.form.Land.checked          == true ||
                    el.form.Commercial.checked    == true    )
    {
      el.checked = true;
    }
  }
}

function initPreferences()
{
  // initialize user settings
  frm = document.page_form;

  if( prefs["head_color"] ) {
    _initSelect(frm.head_color, prefs["head_color"]);
  }

  if( prefs["show_map"] ) {
    _initRadio(frm.show_map, prefs["show_map"]);
  }
  if( prefs["show_address"] ) {
    _initRadio(frm.show_address, prefs["show_address"]);
  }
  if( prefs["show_office_info"] ) {
    _initRadio(frm.show_office_info, prefs["show_office_info"]);
  }
  if( prefs["show_agent_info"] ) {
    _initRadio(frm.show_agent_info, prefs["show_agent_info"]);
  }
  if( prefs["show_multiphoto"] ) {
    _initRadio(frm.show_multiphoto, prefs["show_multiphoto"]);
  }
  if( prefs["show_virtualtour"] ) {
    _initRadio(frm.show_virtualtour, prefs["show_virtualtour"]);
  }
  if( prefs["show_ME"] ) {
    _initCheck(frm.show_ME, prefs["show_ME"]);
  }
  if( prefs["show_NH"] ) {
    _initCheck(frm.show_NH, prefs["show_NH"]);
  }
  if( prefs["def_prop_type"] ) {
    _initSelect(frm.def_prop_type, prefs["def_prop_type"]);
  }
  if( prefs["def_groups"] ) {
    _initSelect(frm.def_groups, prefs["def_groups"]);
  }

  if( prefs["email_to"] ) {
    frm.email_to.value = prefs["email_to"];
  }
  if( prefs["email_subj"] ) {
    frm.email_subj.value = prefs["email_subj"];
  }
  if( prefs["email_text"] ) {
    frm.email_text.value = prefs["email_text"];
  }

  if( prefs["sort_order"] ) {
    var arr = prefs["sort_order"].split(",");
    for( i = 1; i <= arr.length; ++i ) {
      var val = arr[i-1].split(" ");
      _initSelect(eval("frm.sort_fld_"+i), val[0]);
    }
  }

  for( var fld in excluded_fields ) {
    if( eval("frm." + fld) ) {
      eval("frm." + fld + ".checked = true;");
    }
  }
/*
  state_count = 0;
  var state_sel_map = new Array();
  for(var i = 0; i < frm.elements['state[]'].options.length; ++i) {
      state_sel_map[frm.elements['state[]'].options[i].value] = i;
   }
  
  for( var state in limit_states ) {
  	frm.elements['state[]'].options[state_sel_map[state]].selected = true;
	state_count++;
  }
  if (state_count) {
  	selectState('ACTIVE');
  }
  else {
    frm.elements['state[]'].options[0].selected = true;
	selectState('ALL');
  }

 selectCounty('NONE');

  county_count = 0;
  for( var state in limit_counties ) {
  	for (var county in limit_counties[state]) {
	    selectCounty(state + "|" + county);
		county_count++;
	}
  }
  if (!county_count) {
    for(var state in limit_counties){
      frm.elements[state + 'counties[]'].options[0].selected = true;
	  selectCounty(state + '|ALL');
    }
  }

  var towns = frm.elements['towns[]'].options;
  var towns_selected = frm.elements['towns_selected[]'].options;
  var town_sel_map = new Array();

  for(var i = 0; i < towns.options.length; ++i) {
      town_sel_map[towns.options[i].value] = i;
   }

  for( var town in limit_towns ) {
    insertSortedSelect(towns_selected.options, towns.options[town_sel_map[town]]);
  }
*/
}

function addSelectedTown(state)
/*
 * Adds the selected town in towns[] to towns_selected[].
 */
{
document.page_form.towns_selected.value = "";
  var towns_selected = document.page_form.elements[state + '_towns_selected[]'];
  var towns = document.page_form.elements[state + '_towns[]'];

  if(towns.selectedIndex == -1 || towns.selectedIndex == 0 || towns.selectedIndex == 1 ) { return; }

  insertSortedSelect(towns_selected.options, towns.options[towns.selectedIndex]);
  towns.selectedIndex = -1;
////////////////// set string ///////////////////
  var towns_selected_str = "";
  for (state in counties) {
    var towns_sel = document.page_form.elements[state + "_towns_selected[]"];
	for (var i = 0; i < towns_sel.length; ++i) {
	  towns_selected_str += ((towns_selected_str)?",":"") + towns_sel.options[i].value;
	}
  }
  
  document.page_form.towns_selected.value = towns_selected_str;
}

function removeSelectedTown(state)
/*
 * Removes the selected town in towns_selected[].
 */
{
document.page_form.towns_selected.value = "";
  var towns_selected = document.page_form.elements[state + '_towns_selected[]'];

  if(towns_selected.selectedIndex == -1) { return; }

  towns_selected.options[towns_selected.selectedIndex] = null;
  ////////////////// set string ///////////////////
  var towns_selected_str = "";
  for (state in counties) {
    var towns_sel = document.page_form.elements[state + "_towns_selected[]"];
	for (var i = 0; i < towns_sel.length; ++i) {
	  towns_selected_str += ((towns_selected_str)?",":"") + towns_sel.options[i].value;
	}
  }
  
  document.page_form.towns_selected.value = towns_selected_str;
}

function setHSDate(status_drop)
{
  if(status_drop == "present") {
    document.page_form.hsdate.value = "";
  }
  else if(status_drop == "hotsheet") {
    document.page_form.hsdate.value = "ChangeDate";
  }
  else if(status_drop == "activity") {
    document.page_form.hsdate.value = "StatusDate";
  }
}

function insertSortedSelect(opts, op)
/*
 * Inserts 'op' into 'opts' in sorted order.  Assumes 'opts' is already sorted,
 * and that the sort is by 'op.value'.
 *
 * Note: this function intentionally ignores duplicates; all values are unique
 *
 * opts: array of Option objects.
 * op: the Option object to be inserted.
 *
 * Returns the index at which op was inserted.
 */

{
  var l = 0;
  var m = 0;
  var r = opts.length - 1;

  if( !op ) {
    return;
  }

  while( 1 ) {
    // if we've found where to insert (namely 'l')
    if( r < l ) {
      i = opts.length - 1;
      // shift all the elements after our insert point one to the right
      while( i >= l ) {
        opts[i+1] = new Option(opts[i].text, opts[i].value);
        --i;
      }

      // insert
      opts[l] = new Option(op.text, op.value);
      return l;
    }
    else {
      m = Math.floor((r-l)/2) + l; // get midpoint
      if( opts[m].value < op.value ) {
        l = m + 1;
      }
      else if( opts[m].value > op.value ) {
        r = m - 1;
      }
      // found an exact match
      else {
        return -1; // dump the dupe
      }
    }
  }
}

function _initRadio(fld, val)
{
  for( var idx = 0; idx < fld.length; ++idx ) {
    if(fld[idx].value == val) {
      fld[idx].checked = true;
    }
  }
}
function _initCheck(fld, val)
{
  var frm = document.page_form;
  if( val == 1 ){
    fld.checked = true;
  }
  else{
    fld.checked = false;
  }
}

function _initSelect(fld, val)
{
  for( var idx = 0; idx < fld.length; ++idx ) {
    if(fld.options[idx].value == val) {
      fld.options[idx].selected = true;
    }
  }
}

function clearSelects(state)
{
  var towns = document.page_form.elements[state + "_towns[]"];
  for(i=0; i<towns.length; i++){
    towns.options[i].selected = false;
  }
  document.page_form.towns_selected.value = "";
  var towns_selected_str = "";  
  for (st in active_counties) {
    var twns = document.page_form.elements[st + "_towns[]"];
    for (var i = 0; i < twns.length; ++i) {
	  if(twns.options[i].selected == true){
        towns_selected_str += ((towns_selected_str)?",":"") + twns.options[i].value;
	  }
	}
  }
  document.page_form.towns_selected.value = towns_selected_str;
  //alert(document.page_form.towns_selected.value);

  var cnty = document.page_form.elements[state + "_counties[]"];
  if(cnty){
    for(i=0; i < cnty.length; i++){
      cnty.options[i].selected = false;
      if(i > 1){
	    var arr = cnty.options[i].value.split('|');
	   counties[arr[0]][arr[1]].selected = true;
	    _toggleCountySelect(arr[0], arr[1]);
      }
	}
    var counties_selected_str = "";
    for (st in active_counties) {
      var counties_sel = document.page_form.elements[st + "_counties[]"];
      if(counties_sel && counties_sel.length){	
	    for (var i = 0; i < counties_sel.length; ++i) {
	      if(counties_sel.options[i].selected == true){
	        counties_selected_str += ((counties_selected_str)?",":"") + counties_sel.options[i].value;
	      }
	    }
      }
    }
  document.page_form.counties_selected.value = counties_selected_str;
  //alert(counties_selected_str);
  }
}
/*
var frm = document.page_form;
  for(var st in towns_selected){
    for(var i=0; i < towns_selected[st].length; i++){
	  for(var j=0; j < frm.elements[st + "_Towns[]"].length; j++){
	    if( frm.elements[st + "_Towns[]"].options[j].value == st + "|" towns_selected[st][i] ){
	      frm.elements[st + "_Towns[]"].options[j].select;
	    }
	  }
	}    
  }
 */