
// Production
var virtualDir = "/mls";
var localDir   = "/vhmls-pr";
var photoDir   = "/photos";

// Staging
// var virtualDir = "/mls-staging";
// var localDir   = "/vhmls-st";
// var photoDir   = "/photos";

// Development
// var virtualDir = "/staging";
// var localDir   = "/vhmls-st";
// var photoDir   = "/photos";

var MINPRICE_DEFAULT = "0";
var MAXPRICE_DEFAULT = "1000000"; // 1 million dollars

var popsearch  = new Array();

//    --  A    Adult Living – 55+      AdultLiving
//    --  B    Affordable Homes      Affordable 
//    --  C    Antique Homes          Antique 
//    --  D    Colonial Homes          Colonial 
//    --  E    Contemporary Homes  Contemporary 
//    --  F    Farms                         Farm 
//    --  G    FORECLOSURES      Foreclosure
//    --  H    Horse Property          Horse 
//    --  I    New Properties           New 
//    --  J    Single Level Living      SingleLevel 
//    --  K    Townhouse Condominiums  Townhouse 
//    --  L    View Properties        Waterview
//    --  M    Waterfront Homes   Waterfront 

popsearch[0]  = ['A', 'adultliving'];
popsearch[1]  = ['B', 'affordable'];
popsearch[2]  = ['C', 'antique'];
popsearch[3]  = ['D', 'colonial'];
popsearch[4]  = ['E', 'contemporary'];
popsearch[5]  = ['F', 'farm'];
popsearch[6]  = ['G', 'foreclosure'];
popsearch[7]  = ['H', 'horse'];
popsearch[8]  = ['I', 'new'];
popsearch[9]  = ['J', 'singlelevel'];
popsearch[10] = ['K', 'townhouse'];
popsearch[11] = ['L', 'waterview'];
popsearch[12] = ['M', 'waterfront'];

var areaBoston = new Array(
    'Allston/Brighton, MA',
    'Beacon Hill, MA',
    'Back Bay, MA',
    'Dorchester, MA',
    'Hyde Park, MA',
    'East Boston, MA',
    'Fenway, MA',
    'North End, MA',
    'West End, MA',
    'Downtown, MA',
    'Chinatown, MA',
    'South Boston, MA',
    'South End, MA',
    'Kenmore, MA',
    'Mission Hill, MA',
    'Mattapan, MA',
    'Roslindale, MA',
    'Roxbury, MA',
    'West Roxbury, MA',
    'Jamaica Plain, MA',
    'Charlestown, MA'
    );


String.prototype.contains = function(t) { return this.toLowerCase().indexOf(t.toLowerCase()) >= 0 ? true : false }
String.prototype.startswith = function(t) { return this.toLowerCase().substring(0,t.length) == (t.toLowerCase()) ? true : false }

  function formatPrice(rp) {
	var fp = rp;
	if (fp.length > 6) {
		fp = rp.substring(0,rp.length-6) + ',' + rp.substring(rp.length-6,rp.length-3) + ',' + rp.substring(rp.length-3,rp.length);
	}
	else if (rp.length > 3) {
		fp = rp.substring(0,rp.length-3) + ',' + rp.substring(rp.length-3,rp.length);
	}
	return '$' + fp;
  }
  
  function getBostonAreaIndex( cname ) {
      for ( var i=0; i<areaBoston.length; i++ )
          if ( areaBoston[i] == cname )
               return i;
      return -1;
  }

function GetPolpularSearchByName(psname) {
    var psnamei = psname.toLowerCase();
    for (var i=0; i<popsearch.length; i++) {
        if (popsearch[i][0] == psname || popsearch[i][1] == psnamei)
            return popsearch[i][0];
    }
    return 'I'; // new, by default
}

  function getMLSString(list_no) {
    var fl = list_no + "";
    while (fl.length < 8)
        fl = '0' + fl;
    return fl;
  }

    function VHMLSSearch() {
        if ( cityArray == undefined || cityArray.length == 0 ) {
          VHMLSSearchHome();
          return;
        }
        var elm = document.getElementById("SearchVal");
        var str = elm.value;

        /*
         * Process Boston Areas
         */
        var ba_idx = getBostonAreaIndex( str );
        if ( ba_idx != -1 ) {
            var tokens = areaBoston[ba_idx].split(",", 1);
            window.location = virtualDir + "/MA/Boston/Area/" + tokens[0].replace(" ", "_").replace("/", "_");
            return;
        }
        
        /*
         * Look for (optional) state name after comma
         */
        var last_comma = str.lastIndexOf(",");
        if ( last_comma > 0 ) {
          VHMLSSearchHome();
          return;
        }
        /* */
        for (var i=0; i<cityArray.length; i++) {
          if (cityArray[i].startswith(elm.value)) {
            elm.value = cityArray[i];
            var tokens = cityArray[i].split(",", 1);
            window.location = virtualDir + "/" + tokens[1] + "/" + tokens[0];
            return;
          }
        }
        /* */
        alert("Match not found for [" + elm.value + "], try again.");
    }

    function VHMLSSearchHome() {
        var elm = document.getElementById("SearchVal");
        var str = elm.value;
        /*
         * Look for (required) state name after comma
         */
        var last_comma = str.lastIndexOf(",");
        if ( last_comma > 0 ) {
          var state_name = str.substr( last_comma+1 ).replace( " ", "" ).toUpperCase();
          if ( state_name == "MA" || state_name == "NH" ) {
            var city_name = str.substr( 0, last_comma );
            city_name = city_name.substr( 0, 1 ).toUpperCase() + city_name.substr( 1 ).toLowerCase();
            window.location = virtualDir + "/" + state_name + "/" + city_name;
            return;
          }
          alert("Only states MA and NH are currently supported, please try again.");
          return;
        }
        alert("Please type a city name, then a comma, then either MA or NH.");
    }

    var last_checked = -1;
    
    function autoloadImages()
    {
        while (++last_checked < document.images.length)
        {
            var img = document.images[last_checked];
            if (img.name.startswith("MLS")) {
                var mls_no = img.name.substring(3);
                var src = photoDir + '/' +
                    mls_no.substring(0, 2) + '/' + mls_no.substring(2, 5) + '/' + mls_no.substring(5, 8) + '_0.jpg';
                var newImg = new Image();
                newImg.src = src;
                document.images[last_checked].src = newImg.src
                setTimeout("autoloadImages()", 500);
                return;
            }
        }
    }
    
    function submitenter(myfield,e)
    {
        var keycode;
        if (window.event) keycode = window.event.keyCode;
        else if (e) keycode = e.which;
        else return true;

        if (keycode == 13)
           {
           VHMLSSearch();
           return false;
           }
        else
           return true;
    }


  function viewProperty(propertyid) {
    if ( parseInt( propertyid, 10 ) < 70000000 )
        state_code = 'NH';
    else
        state_code = 'MA';
    var fl = getMLSString(propertyid);
    var winfeatures='left=250,top=50,width=946,height=768,scrollbars=1,resizable=1,toolbar=0,location=0,menubar=0,status=0,directories=0';
    var prop_win = window.open(virtualDir+"/"+state_code+"_MLS/"+fl, "property_"+fl, winfeatures);
	if (window.focus) {prop_win.focus()}
  }

  function mapProperty(propertyid) {
    var fl = getMLSString(propertyid);
    var winfeatures='left=250,top=50,width=946,height=768,scrollbars=1,resizable=1,toolbar=0,location=0,menubar=0,status=0,directories=0';
    var prop_win = window.open("http://www.virtualhomes.com"+virtualDir+"/MapIt/"+fl, "property_"+fl, winfeatures);
	if (window.focus) {prop_win.focus()}
  }

  function infoPage(pageURL, winName) {
    var winfeatures='left=250,top=50,width=830,height=768,scrollbars=1,resizable=1,toolbar=0,location=0,menubar=0,status=0,directories=0';
    var info_win = window.open(pageURL, winName, winfeatures);
	if (window.focus) {info_win.focus()}
  }

  function commWindow(pageURL, winName) {
    var winfeatures='left=250,top=10,width=850,height=768,scrollbars=1,resizable=1,toolbar=0,location=1,menubar=0,status=0,directories=0';
    var comm_win = window.open(pageURL, winName, winfeatures);
	if (window.focus) {comm_win.focus()}
  }

function changeLocation(menuObj) {
  var i = menuObj.selectedIndex;
  if(i > 0) {
    window.location = menuObj.options[i].value;
  }
}

//
// This is the city list for current state context ...
//
var cityArray  = new Array();


// Browser Window Size and Position
// copyright Stephen Chapman, 3rd Jan 2005, 8th Dec 2005
// you may copy these functions but please keep the copyright notice as well
function pageWidth() {return window.innerWidth != null? window.innerWidth : document.documentElement && document.documentElement.clientWidth ?       document.documentElement.clientWidth : document.body != null ? document.body.clientWidth : null;} function pageHeight() {return  window.innerHeight != null? window.innerHeight : document.documentElement && document.documentElement.clientHeight ?  document.documentElement.clientHeight : document.body != null? document.body.clientHeight : null;} function posLeft() {return typeof window.pageXOffset != 'undefined' ? window.pageXOffset :document.documentElement && document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft ? document.body.scrollLeft : 0;} function posTop() {return typeof window.pageYOffset != 'undefined' ?  window.pageYOffset : document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop ? document.body.scrollTop : 0;} function posRight() {return posLeft()+pageWidth();} function posBottom() {return posTop()+pageHeight();}




// version: beta
// created: 2005-08-30
// updated: 2005-08-31
// mredkj.com
function extractPrice(obj, decimalPlaces, allowNegative)
{
	var temp = obj.value;
	
	// avoid changing things if already formatted correctly
	var reg0Str = '[0-9]*';
	if (decimalPlaces > 0) {
		reg0Str += '\\.?[0-9]{0,' + decimalPlaces + '}';
	} else if (decimalPlaces < 0) {
		reg0Str += '\\.?[0-9]*';
	}
	reg0Str = allowNegative ? '^-?' + reg0Str : '^' + reg0Str;
	reg0Str = reg0Str + '$';
	var reg0 = new RegExp(reg0Str);
	if (reg0.test(temp)) {
	    obj.value = formatPrice(temp);
	    return true;
	}

	// first replace all non numbers
	var reg1Str = '[^0-9' + (decimalPlaces != 0 ? '.' : '') + (allowNegative ? '-' : '') + ']';
	var reg1 = new RegExp(reg1Str, 'g');
	temp = temp.replace(reg1, '');

	if (allowNegative) {
		// replace extra negative
		var hasNegative = temp.length > 0 && temp.charAt(0) == '-';
		var reg2 = /-/g;
		temp = temp.replace(reg2, '');
		if (hasNegative) temp = '-' + temp;
	}
	
	if (decimalPlaces != 0) {
		var reg3 = /\./g;
		var reg3Array = reg3.exec(temp);
		if (reg3Array != null) {
			// keep only first occurrence of .
			//  and the number of places specified by decimalPlaces or the entire string if decimalPlaces < 0
			var reg3Right = temp.substring(reg3Array.index + reg3Array[0].length);
			reg3Right = reg3Right.replace(reg3, '');
			reg3Right = decimalPlaces > 0 ? reg3Right.substring(0, decimalPlaces) : reg3Right;
			temp = temp.substring(0,reg3Array.index) + '.' + reg3Right;
		}
	}
	
	obj.value = formatPrice(temp);
}

// version: beta
// created: 2005-08-30
// updated: 2005-08-31
// mredkj.com
function extractNumber(obj, decimalPlaces, allowNegative)
{
	var temp = obj.value;
	
	// avoid changing things if already formatted correctly
	var reg0Str = '[0-9]*';
	if (decimalPlaces > 0) {
		reg0Str += '\\.?[0-9]{0,' + decimalPlaces + '}';
	} else if (decimalPlaces < 0) {
		reg0Str += '\\.?[0-9]*';
	}
	reg0Str = allowNegative ? '^-?' + reg0Str : '^' + reg0Str;
	reg0Str = reg0Str + '$';
	var reg0 = new RegExp(reg0Str);
	if (reg0.test(temp)) return true;

	// first replace all non numbers
	var reg1Str = '[^0-9' + (decimalPlaces != 0 ? '.' : '') + (allowNegative ? '-' : '') + ']';
	var reg1 = new RegExp(reg1Str, 'g');
	temp = temp.replace(reg1, '');

	if (allowNegative) {
		// replace extra negative
		var hasNegative = temp.length > 0 && temp.charAt(0) == '-';
		var reg2 = /-/g;
		temp = temp.replace(reg2, '');
		if (hasNegative) temp = '-' + temp;
	}
	
	if (decimalPlaces != 0) {
		var reg3 = /\./g;
		var reg3Array = reg3.exec(temp);
		if (reg3Array != null) {
			// keep only first occurrence of .
			//  and the number of places specified by decimalPlaces or the entire string if decimalPlaces < 0
			var reg3Right = temp.substring(reg3Array.index + reg3Array[0].length);
			reg3Right = reg3Right.replace(reg3, '');
			reg3Right = decimalPlaces > 0 ? reg3Right.substring(0, decimalPlaces) : reg3Right;
			temp = temp.substring(0,reg3Array.index) + '.' + reg3Right;
		}
	}
	
	obj.value = temp;
}

function blockNonNumbers(obj, e, allowDecimal, allowNegative)
{
	var key;
	var isCtrl = false;
	var keychar;
	var reg;
		
	if(window.event) {
		key = e.keyCode;
		isCtrl = window.event.ctrlKey
	}
	else if(e.which) {
		key = e.which;
		isCtrl = e.ctrlKey;
	}
	
	if (isNaN(key)) return true;
	
	keychar = String.fromCharCode(key);
	
	// check for backspace or delete, or if Ctrl was pressed
	if (key == 8 || isCtrl)
	{
		return true;
	}

	reg = /\d/;
	var isFirstN = allowNegative ? keychar == '-' && obj.value.indexOf('-') == -1 : false;
	var isFirstD = allowDecimal ? keychar == '.' && obj.value.indexOf('.') == -1 : false;
	
	return isFirstN || isFirstD || reg.test(keychar);
}
                    
