<!--

/*****************************************************/
/*																	 */
/*					Purpose: Repository of JavaScript				 */
/*									 					    		 */
/*					Written by: Adam Nelson 10/16/01				 */
/*													 				 */
/*****************************************************/

/*      Browser sniffing variable
        isIE is true when you're using IE (duh) */
var agt = navigator.userAgent.toLowerCase();
var ver = navigator.appVersion.toLowerCase();
var isIE = (agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1);
var isIE500 = (isIE) && (ver.indexOf("5.00") != -1);
var isIE501 = (isIE) && (ver.indexOf("5.01") != -1);
var isAol   = (agt.indexOf('aol') != -1);

function selectPopup(select, win_width, win_height) {
			 //var page = select.options[select.selectedIndex].value
			 //var win_width = win_width;
			 //var win_height = win_height;
			 //var parameters = "left=0,top=0,toolbar=yes,menubar=yes,scrollbars=yes,resizable=yes,width=" + win_width + ",height=" + win_height;
			 //if (page == 15) { // the number here accords to the selection foreclosure
  		 		//var newWindow = window.open('/fore.html','name',parameters);
				//newWindow.creator = self;
				//newWindow.focus();
			//}


return true;

}

/* Useless now, but keep the function for any calls I didn't notice */

function validateCounty (theForm) {
  if (isBlank(theForm.szPostalCode)) {
	  theForm.szPostalCode.focus();
		alert ("Please enter a zip code.");
		return false;
  }	
}


function isNumeric(theObject) {
  var refString = "0123456789";
  var checkStr = theObject.value;
  var allValid = true;
  for (i = 0; i < checkStr.length; i++) {
    ch = checkStr.charAt(i);
    if (refString.indexOf(ch, 0) == -1) { return (false); }
  }
  return (true);
}

function isBlank (theObject) {
  if (theObject == null)     { return true; }
  if (theObject.value == "") { return true; }
  return false;
}

function validate (theForm) {
  	// set var radio_choice to false
	var iAccountNumberExists = false;

	if (theForm.iAccountNumber) {
		// Loop from zero to the one minus the number of radio button selections
		for (counter = 0; counter < theForm.iAccountNumber.length; counter++)
		{
		// If a radio button has been selected it will return true
		// (If not it will return false)
		if (theForm.iAccountNumber[counter].checked)
		 	 iAccountNumberExists = true;
		}
		if (theForm.iAccountNumber2) {
			for (counter = 0; counter < theForm.iAccountNumber2.length; counter++)
			{
			// If a radio button has been selected it will return true
			// (If not it will return false)
			if (theForm.iAccountNumber2[counter].checked)
			 	 iAccountNumberExists = true;
			}	
		}

		if (iAccountNumberExists == false) {
		 	 theForm.iAccountNumber[0].focus();
		 	 theForm.iAccountNumber[0].click();
	  	 	 alert ("Please select a package type.  I have selected the first option for you.");
		 	 return false;
		}	
	}

	if (isBlank(theForm.szFirstName)) {
    theForm.szFirstName.focus();
    alert ("Please enter the homeowner's first name.");
    return false;
  }

  if (isBlank(theForm.szPhone1)) {
    theForm.szPhone1.focus();
    alert ("Please enter a contact phone number.");
    return false;
  }

  if (!isBlank(theForm.szEmailAddress) && !isEmail(theForm.szEmailAddress.value)) {
	 theForm.szEmailAddress.focus();
   	 theForm.szEmailAddress.select();
	 alert ("I'm sorry, it appears that the email address you entered is not valid.  Please try again.")
     return false;
  }

  if (isBlank(theForm.szAddress)) {
    theForm.szAddress.focus();
    alert ("Please enter the property address.");
    return false;
  }
  if (isBlank(theForm.szCity)) {
    theForm.szCity.focus();
    alert ("Please enter the city that this property is in.");
    return false;
  }
  if (theForm.szStateCode.selectedIndex == 0) {
    theForm.szStateCode.focus();
    alert ("Please select the state/province for this property.");
    return false;
  }
	  if (isBlank(theForm.szPassword) && (theForm.iAdmin.value == "")) {
    	theForm.szPassword.focus();
    	alert ("Please select a password for this ad.");
    	return false;
  	}
  if (theForm.iPropTypeCode.selectedIndex == 0) {
    theForm.iPropTypeCode.focus();
    alert ("Please select the type of property for sale.");
    return false;
  }
  	if (theForm.szPassword.value != theForm.szConfPassword.value) {
    	theForm.szConfPassword.focus();
    	theForm.szConfPassword.select();
    	alert ("Those passwords don't match.");
    	return false;
  	}
	
	//check that open house info is complete
	var missingFields = "";
	var count = 0;
	if (theForm.iMonth.value == "00") {
		 missingFields = missingFields + "month ";
		 count++;		
	}
	if (theForm.iDay.value == "00") {
		 missingFields = missingFields + "day ";
		 count++;		
	}
	if (theForm.iYear.value == "0000") {
		 missingFields = missingFields + "year ";
		 count++;		
	}
	/* Ha, the same thing that is true for minutes is true for hours
       here -- 12 needs to have a value of 0 (midnight is stored in the db as
       00:00 -- otherwise we need much more complex logic

	if (theForm.iHour.value == "00") {
		 missingFields = missingFields + "hour ";
		 count++;		
	}
*/
	/* left this out because of preexisting bug--the
	   select list has two options with value = 00, the "MM"
		 option and the "00" option. if user selected "00"
		 then he/she wouldn't have been able to proceed. 
		 need to find a better solution. -melissa
 
	if (theForm.iMinute15.value == "00") {
		 missingFields = missingFields + "minute ";
		 count++;		
	}
	*/
	if (theForm.szAMPM.value == "00") {
		 missingFields = missingFields + "AM/PM ";
		 count++;		
	}	
	if (count>0 && count <5) {
		 alert ("Open house information is incomplete.\nPlease specify the following:\n" + missingFields);	
		 return false;
  }
	
  if (isBlank(theForm.iAskingPrice)) {
    theForm.iAskingPrice.focus();
    alert ("Please enter the asking price for this property.");
    return false;
  } 
  if (!isNumeric(theForm.iNumBedrooms)) {
    theForm.iNumBedrooms.focus();
    theForm.iNumBedrooms.select();
    alert ("Please use only the digits 0-9 to enter the number of bedrooms.");
    return false;
  }
  if (!isNumeric(theForm.iNumFloors)) {
    theForm.iNumFloors.focus();
    theForm.iNumFloors.select();
    alert ("Please use only the digits 0-9 to enter the number of floors.");
    return false;
  }
  
  var filter = /^[\d\,\.]*$/;
  if (! filter.test(theForm.iSqFootage.value)) {
    theForm.iSqFootage.focus();
    theForm.iSqFootage.select();
    alert ("Please use only digits and commas to enter the square footage.");
    return false;
  }
  if (theForm.dEndRun) {
  	if (!formatDate(theForm.dEndRun.value))  {
		theForm.dEndRun.focus();
		theForm.dEndRun.select();
		alert('Date must be in format YYYY-MM-DD');
		return false;
	}
  }
  return true;
}

function verifyInfo(theForm){
  // Check that name is given, that email is valid if specified
  // and that at least the email or a phone number is provided
	if (isBlank(theForm.szName)){
		 alert ("Please enter your name so that we may contact you.");
		 return false;
	} else if (!isBlank(theForm.szEmail) && !isEmail(theForm.szEmail.value)) {
     alert ("Please enter a valid email address where you can be reached, then try again.");
		 return false;
  } else if (isBlank(theForm.szEmail)&&(isBlank(theForm.szPhone))&&(isBlank(theForm.szPhone2))&&(isBlank(theForm.szPhoneEve))){
     alert ("Please enter either a phone numnber or email address where you can be reached, then try again.");
		 return false;
	}
	return true;
}


function isEmail(email) {
    invalidChars = " ~\'^\`\"*+=\\|][(){}$!#%/:,;";

    // Remove leading and trailing whitespace
    email = email.replace(/^\s+/,"");
    email = email.replace(/\s+$/,""); 
    
    // Check for null
    if (email == "") {
  		return false;
    }

    // Check for invalid characters as defined above
    for (i=0; i<invalidChars.length; i++) {
        badChar = invalidChars.charAt(i);
        if (email.indexOf(badChar,0) > -1) {
            return false;
        }
    }
    lengthOfEmail = email.length;
    if ((email.charAt(lengthOfEmail - 1) == ".") || (email.charAt(lengthOfEmail - 2) == ".")) {
        return false;
    }
    Pos = email.indexOf("@",1);
    if (email.charAt(Pos + 1) == ".") {
        return false;
    }
    while ((Pos < lengthOfEmail) && ( Pos != -1)) {
        Pos = email.indexOf(".",Pos);
        if (email.charAt(Pos + 1) == ".") {
            return false;
        }
        if (Pos != -1) {
            Pos++;
        }
    }

    // There must be at least one @ symbol
    atPos = email.indexOf("@",1);
    if (atPos == -1) {
        return false;
    }

    // But only ONE @ symbol
    if (email.indexOf("@",atPos+1) != -1) {
        return false;
    }

    // Also check for at least one period after the @ symbol
    periodPos = email.indexOf(".",atPos);
    if (periodPos == -1) {
        return false;
    }
    if (periodPos+3 > email.length) {
        return false;
    }
    return true;
}

function checkEmail(val) {

    // Remove all whitespace
    val = val.replace(/^\s+/,"");
    val = val.replace(/\s+$/,"");
    
	if (isEmail(val)==false) {
		var notValid =  "I'm sorry, " + val + " is not a valid email address";
		alert(notValid);
		return false;
	}
	return true;
}

function formatDate(date) {

//	with (date.form) { 
		var spot = date.indexOf('-',0)
		//alert(spot);
		if ((spot != 4) || (date.length != 10)) {
		//alert ("I dont think spot is 4");
	//		alert('Date must be in format YYYY-MM-DD'); 
	//		date.form.focus(); 
			return false;
		}				
		var spot = date.indexOf('-',5)
		if (spot != 7) {
		//	alert('Date must be in format YYYY-MM-DD'); 
		//	date.form.focus(); 
			return false;
		}
//	} 
	return true;
}

//functions for slideshow
//written by: scott bice 6/15/02
var timer = null;

function playpauseShow(option) {
	if (option == "play") {
		if (currentImage == imageList.length-1) {
			currentImage=0;
		} else {
			currentImage++;
		}
		document.slideimage.src = imageList[currentImage];
		timer = setTimeout("playpauseShow('play')", 3000);
	} else {
		clearTimeout(timer);
	}
}

function nextImage() {
		if (currentImage == imageList.length-1) {
			currentImage = 0;
		} else {
			currentImage++;
		}
		document.slideimage.src = imageList[currentImage];
}

function prevImage() {
		if (currentImage == 0) {
			currentImage = imageList.length-1;
		} else {
			currentImage--;
		}
		document.slideimage.src = imageList[currentImage];
}
//end of functions for slideshow


var browser = navigator.appName;
var version = navigator.appVersion.substring(0,1);

function redirectTopNav(dest) {
  window.location=dest;
}

function changeFontColor(loc, color) {
  if (browser == "Microsoft Internet Explorer") {
	  window[loc].style.color=color;
	} 
}

function changeBGColor(loc, color) {
  if (browser == "Microsoft Internet Explorer") {
    window[loc].style.backgroundColor=color;
	} 
}

function changeImage(loc, image) {
  if (browser == "Microsoft Internet Explorer") {
	  window[loc].src = image;
	} else if (browser == "Netscape" && version>=5) {
    document.getElementById(loc).src = image;
  }
}


function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num)) num = "0";
	cents = Math.floor((num * 100 + 0.5) % 100);
	num = Math.floor((num * 100 + 0.5) / 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));
	return ("$" + num + "." + cents);
}


// Savings Calculation: Used in What Will I Save sections
// Need more input as to when this is used with prior calculations
function checkChoice(whichbox) {
  with (whichbox.form) {
  	var p = price.value;
  	var prior = priorval.value;
    var savings = "$0.00";
    
    // Make sure value is a number and no decimal is entered, or reset to prior	
    if (isNaN(whichbox.value)) { 
      whichbox.value = prior;
      whichbox.focus();
    }
    whichbox.value = Math.abs(whichbox.value);
    var dec = whichbox.value.indexOf('.', 1)
    if (dec > 0) { 
      alert('No decimal places allowed for \"' +whichbox.name +'\" !');
      whichbox.value = prior;
      whichbox.focus();
    }
    // ? eval(p*prior) is always zero since priorval.value is never set
    hiddentotal.value = eval(hiddentotal.value) - eval(p * prior);
    prior = whichbox.value;
  //  priorval.value = prior;  // This should be added if using the following:
  //  hiddentotal.value = eval(hiddentotal.value) + eval(p * whichbox.value);
    hiddentotal.value = eval(p * whichbox.value);
    savings = formatCurrency(hiddentotal.value);
    return(savings.substring(0,(savings.length)-3));
  }
}

function popupform(myform, windowname, h, w) {
	if (! window.focus) { return true; }
		window.open('', windowname, 'height='+h+',width='+w+',scrollbars=no');
		myform.target=windowname;
		return true;
}

function popupform_withtb(myform, windowname, h, w) {
	if (! window.focus) { return true; }
		window.open('', windowname, 'height='+h+',width='+w+',scrollbars=no,toolbar=yes');
		myform.target=windowname;
		return true;
}

function popupform_withtbmb(myform, windowname, h, w) {
	if (! window.focus) { return true; }
		window.open('', windowname, 'height='+h+',width='+w+',scrollbars=yes,toolbar=no,menubar=yes');
		myform.target=windowname;
		return true;
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
//add event function from http://www.dynarch.com/projects/calendar/
function addAnEvent(el, evname, func) {
    if (el.attachEvent) { // IE
        el.attachEvent("on" + evname, func);
    } else if (el.addEventListener) { // Gecko / W3C
        el.addEventListener(evname, func, true);
    } else {
        el["on" + evname] = func;
    }
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
	Javascript to handle AJAX / XMLHTTPRequest
	author/contact - Alan Nouri - July 2005
**************************************************************************/

// test the browsers XMLHTTPRequest support so we can return errors properly later
var AJAX_SUPPORT = test_ajax();

function test_ajax() {
	// ie 5.01 doesn't support xmlhttprequest but thinks it does...
	// it also thinks it supports the DOM
	// so, death to ie 5.01
	if (!createXmlObj(null) || !document.getElementById || isIE501 || isIE500 || isAol) {
		return false;
	}
	return true;
}

/* Performs a HTTP GET request on 'url' and sends responseText to 'callback'
    callback and fallback are optional
    fallback is called and HTTPGet returns false when the browser does not support XMLHTTPRequest
    callback should take two parameters: the responseText and the entire XMLHTTPRequest object
    fallback is called when the request times out
    
    when the response to the request is not recieved after the timeout, then the request is made again   >>> not implemented yet
    if the retry limit is reached, fallback is called and HTTPGet returns false                                     >>> not implemented yet
    
    i.e. HTTPGet('messageHandler.php?foo=1', function(response, obj) {alert(response);}, function() {alert('Request Failed');})
    or  HTTPGet('messageHandler.php?foo=1', function(response, obj) { alert(response); })
    or  HTTPGet('messageHandler.php?foo=1');
													*/
var timeout = 5; // seconds
var retryAmount = 5; // # of times to retry
var HTTPRequests = new Array; // keep track of requests by storing the timeout in here
function HTTPGet(url, callback, fallback) {
	// no ajax support
	if (!AJAX_SUPPORT) {
		if (fallback) {
			fallback();
		}
		return false;
	}
	
	// XMLHttpRequest obj not re-usable?
	var xmlhttp = createXmlObj(callback);

	try {
		xmlhttp.open("GET", url, "true");
		xmlhttp.setRequestHeader('If-Modified-Since', 'Wed, 15 Nov 1995 00:00:00 GMT');	// safari fix
		xmlhttp.send(null);
	}
	catch(e) {
		return false;
	}
}

// Creates the XMLHttpRequest object and resets any variables
//		 needed to restart the application
function createXmlObj(callback) {
	var XMLObj;

	/*@cc_on @*/
	/*@if (@_jscript_version >= 5)
	// JScript gives us Conditional compilation, we can cope with old IE versions.
	// and security blocked creation of the objects.
		try {
			XMLObj = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e) {
			try {
				XMLObj = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (E) {
				XMLObj = false;
			}
		}
	@end @*/

	if (!XMLObj && typeof XMLHttpRequest != 'undefined') {
		XMLObj = new XMLHttpRequest();
		XMLObj.overrideMimeType('text/xml');
	}
	
	// browser not supported
	if (!XMLObj) {
		return false;
	}

	if (callback) {
		XMLObj.onreadystatechange = function() {
				try {
					if (XMLObj.readyState == 4) {
						// send response to the callback function
						callback(XMLObj.responseText, XMLObj);
					}
				}
				catch(e) { }
			}
	}

	return XMLObj;
}

// Uses XMLHTTPRequest to attempt to cache a page
//	optional delay on request in seconds
function HTTPCache(url, delay) {
	// no ajax support
	if (!AJAX_SUPPORT) {
		return false;
	}
	
	//alert('delay: '+delay+' url: '+url);
	
	if (delay) {
		setTimeout("HTTPCache('"+url+"', null)", delay*1000);
	}
	else {
		// XMLHttpRequest obj not re-usable?
		var xmlhttp = createXmlObj(null);
	
		try {
			xmlhttp.open("GET", url, "true");
			xmlhttp.send(null);
		}
		catch(e) {
			return false;
		}
	}
}

/***********  END AJAX / XMLHTTPREQUEST FUNCTIONS  *************
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
