/*<!--- do not compress --->
File:  		JsUtilities.js
Description: All the JavaScript Utilities that are used by Homes.com.
Author:		Kiran Adapa
Date:		Feb 2, 2000

10/24/2003, M. Marrotte -- added optionsAndMap, setPropType, toggleObject, toggleObjects for F5 project. 
10/24/2003, M. Marrotte -- added rollover and link_color_on, change_link_color -- source from Lime Interactive design firm. 
11/03/2003, M. Marrotte -- added path, updateAdRightClick, updateOnClick, and updateImgSrc for F5.
03/11/2004, D. Hamilton -- added CheckStateValue for rentals search enhancement for MoveOnIn partnership
05/31/2005,	D. Hamilton -- changed any refs to imgsrv to www
10/12/2005, D. Hamilton -- added resizeimage function
12/13/2005, G.Winter    -- removed line that swapped the homeform_ad_right image on the home page in function link_color_on
*/


function changeImages(img) {
	// document.write(img);
	document.find_img.src = img;
}


function switchDiv(div_id)
{
  var style_sheet = getStyleObject(div_id);
  if (style_sheet)
  {
    
    changeObjectVisibility(div_id, "visible");
  }
  else 
  {
    alert("sorry, this only works in browsers that do Dynamic HTML");
  }
}

function switchDivOff(div_id)
{
  var style_sheet = getStyleObject(div_id);
  if (style_sheet)
  {
    
    changeObjectVisibility(div_id, "hidden");
  }
  else 
  {
    alert("sorry, this only works in browsers that do Dynamic HTML");
  }
}

function getStyleObject(objectId) {
  // checkW3C DOM, then MSIE 4, then NN 4.
  //
  if(document.getElementById && document.getElementById(objectId)) {
	return document.getElementById(objectId).style;
   }
   else if (document.all && document.all(objectId)) {  
	return document.all(objectId).style;
   } 
   else if (document.layers && document.layers[objectId]) { 
	return document.layers[objectId];
   } else {
	return false;
   }
}

function changeObjectVisibility(objectId, newVisibility) {
    // first get the object's stylesheet
    var styleObject = getStyleObject(objectId);

    // then if we find a stylesheet, set its visibility
    // as requested
    //
    if (styleObject) {
	styleObject.visibility = newVisibility;
	return true;
    } else {
	return false;
    }
}

// Global used by updateAdRightOnClick and updateOnClick
var path ="";
var sClickitem="boa_homeright";

// updateImgSrc -- Changes img's src to src
function updateImgSrc(img, src){
if(document.images[img]) //Netscape
	document.images[img].src=src
else if(document.images(img)) //IE
	document.images(img).src=src
}

// updateAdRightonClick -- Changes the object onclick event to newPath.
// TODO:  This really is a a general function...  
//        Should probably change name and update callers.
function updateAdRightOnClick(object, newPath, sItem)
{
path=newPath;
sClickitem=sItem;
//if(document.anchors[object]) //Netscape
//    document.anchors[object].onclick = updateOnClick
//else if(document.anchors(object)) //IE
//	document.anchors(object).onclick = updateOnClick
}

function updateOnClick(){
//  window.open(path)
	return path;
}


function change_link_color(number)
	{
		if (document.getElementById) {
			menu_item = document.getElementById('homeform'+number);

			i = 1;
			while ( document.getElementById('homeform'+i) ) {
				document.getElementById('homeform'+i).className='home_form';
				i++;
			}
			menu_item.className='home_form-on';
		}
	}

function change_link_color_header(number)
	{
		if (document.getElementById) {
			menu_item = document.getElementById('homeform'+number);

			i = 1;
			while ( document.getElementById('homeform'+i) ) {
				document.getElementById('homeform'+i).className='home_form';
				i++;
			}
			menu_item.className='home_form_sm-on';
		}
	}

// optionsAndMap --  Only changes the HREF for the 'moreOptions' anchor according to 'button'
// TODO:  Will need to change HREF for the 'mapSearch' anchor, eventually.
function optionsAndMap(button){
  if(button=='lots'){
    if(document.anchors['moreOptions'])  //Netscape
      document.anchors['moreOptions'].href = "/Content/ListingUSMap.cfm?PropType=L";
    else //IE
	   document.anchors('moreOptions').href="/Content/ListingUSMap.cfm?PropType=L";
  } else if(button=='homes'){
     if(document.anchors['moreOptions'])  //Netscape
       document.anchors['moreOptions'].href = "/Content/ListingUSMap.cfm";
     else //IE
      document.anchors('moreOptions').href = "/Content/ListingUSMap.cfm";
  } else if(button=='agents'){
     if(document.anchors['moreOptions'])  { //Netscape
      document.anchors['moreOptions'].href = "/Content/AgentOfficeUSMap.cfm";
	  document.anchors['mapSearch'].href = "/Content/AgentOfficeUSMap.cfm";
	  }
     else {//IE
	   document.anchors('moreOptions').href="/Content/AgentOfficeUSMap.cfm"; 	
	   document.anchors('mapSearch').href = "/Content/AgentOfficeUSMap.cfm";
	  }
  }

}

// setPropType -- Set the "form" element PropType's value to "value". 
function setPropType(form, value){
  document.homesAndLots.PropType.value = value;
}

// toggleObject -- objectID visibility based on state (1 yes, 0 no) 
function toggleObjectOld(objectID, state)
{

    if(document.layers)	   //NN4+
       document.layers[objectID].visibility = state ? "show" : "hide";

    else if(document.getElementById)	  //gecko(NN6) + IE 5+
       document.getElementById(objectID).style.visibility = state ? "visible" : "hidden";
     
    else if(document.all)	// IE 4
        document.all[objectID].style.visibility = state ? "visible" : "hidden";
}

// toggleObject -- objectID visibility based on state (1 yes, 0 no) 
function toggleObject(objectID, state)
{

    if(document.layers)	   //NN4+
       document.layers[objectID].visibility = state ? "show" : "hide";

    else if(document.getElementById)	  //gecko(NN6) + IE 5+
       //document.getElementById(objectID).style.visibility = state ? "visible" : "hidden";
		document.getElementById(objectID).style.display = state ? "block" : "none";
     
    else if(document.all)	// IE 4
        document.all[objectID].style.visibility = state ? "visible" : "hidden";
}


// toggleObjects -- Array wrapping ('controlList') for toggleObject.
function toggleObjects(controlList)
{      
       for(i=0; i<controlList.length; i++)
         toggleObject(controlList[i][0], controlList[i][1]);
    
}

function rollover(img_name, img_src){
	document[img_name].src = img_src;
}

function link_color_on(number,adrtsrc)
{
	if (document.getElementById) {
		menu_item = document.getElementById('homeform'+number);

		i = 1;
		while ( document.getElementById('homeform'+i) ) {
			document.getElementById('homeform'+i).className='home_form';
			i++;
		}
		menu_item.className='home_form-on';
//		document.homeform_ad_top.src = "http://www.homes.com/HomesCom/Images/F5_misc/homeform_ad_top" + number + ".gif";		
//		document.homeform_text_top.src = "http://www.homes.com/HomesCom/Images/F5_misc/homeform_text_top" + number + ".gif";		

	}
}

// A function to validate the E-mail
 function validEmail(email) {
    invalidChars = " /:,;"

  if (email == "") {      // cannot be empty
   return false
  }
  for (i=0; i<invalidChars.length; i++) { // does it contain any invalid characters?
   badChar = invalidChars.charAt(i)
   if (email.indexOf(badChar,0) > -1) {
    return false
   }
  }
  atPos = email.indexOf("@",1)   // there must be one "@" symbol
  if (atPos == -1) {
   return false
  }
  if (email.indexOf("@",atPos+1) != -1) { // and only one "@" symbol
   return false
  }
  periodPos = email.indexOf(".",atPos)
  if (periodPos == -1) {     // and at least one "." after the "@"
   return false
  }
  if (periodPos+3 > email.length) {  // must be at least 2 characters after the "."
   return false
  }
  return true
}

// Check form field content.
function checkField (thisform, fieldvalue) {
	if (thisform.BookmarkName.value == "") {
	   alert ('Please enter ' +  fieldvalue);
	   return false;
	}
	return true;
}

// Check form for E-mail addresses
 function checkForm (emailform) {
 	  if (emailform.email_target_email.value == "") {
	      alert ('Please enter "Send to" address.');
		  return false
	  }
	  else {  
		   if (!validEmail(emailform.email_target_email.value)) {
		    alert('Invalid "Send to" email address')
		    emailform.email_target_email.focus()
		    emailform.email_target_email.select()
		    return false
		   }
	  }
	  
	   if (emailform.email_from.value == "") {
	      alert ('Please enter "Your email" address.');
		  return false
	   }
	   else {
	   	   if (!validEmail(emailform.email_from.value)) {
		    alert('Invalid email address')
		    emailform.email_from.focus()
		    emailform.email_from.select()
		    return false
		   }
	   }

	  return true
 }

// Check thisform's multiple select list and give an error if selected 
// items count is more than maxcount.
function checkSelectionCount (thisform, selname, maxcount) {
   var j = 0;


   for (var i=0; i<thisform.elements[selname].options.length; i++) {

   	   if(thisform.elements[selname].options[i].selected) {
		   	if ((thisform.elements[selname].options[i].value == 'PUBLIC') ||
				(thisform.elements[selname].options[i].value == 'PRIVATE')) {
				alert('Do not select the school type identifiers - "PUBLIC" or "PRIVATE"');
				return false;
			}
	   }
	   
   }

   
   for (var i=0; i<thisform.elements[selname].options.length; i++) {
   	   if(thisform.elements[selname].options[i].selected) j++;		   
   }

   if (j > maxcount) {
	   alert("Please select " + maxcount + " or fewer items.\nCurrently selected items: " + j);
       return false;
   }
   else {
       return true;
   }

}

// Pops up a child window with the given window name and dimensions
/*
function popupWindow(winname,w,h) {
	if (winname == null) winname = "newWindow";
	if (w == null) w = 600;
	if (h == null) h = 600;
	cwin=window.open("", winname,
	"nomenubar,status,scrollbars,noresizable,width=" + w + ",height=" + h);
return true;
}
*/

// Pops up a child window with the given window name and dimensions.
// Takes the optional arguments to set the menubar, resize, and scrollbars attributes of Window.
function popupWindow(winname,  w, h, menu, resize, scroll) {
	popupWindowURL("", winname,  w, h, menu, resize, scroll);
return true;
}

function popupWindowURL(url, winname,  w, h, menu, resize, scroll, x, y) {
	if (winname == null) winname = "newWindow";
	if (w == null) w = 600;
	if (h == null) h = 600;
	if (resize == null) resize = 1;
	
	menutype   = "nomenubar";
	resizetype = "noresizable";
	scrolltype = "noscrollbars";
	if (menu) menutype = "menubar";
	if (resize) resizetype = "resizable";
	if (scroll) scrolltype = "scrollbars";
	
	if (x == null || y == null) {
		cwin=window.open(url,winname,"status," + menutype + "," + scrolltype + "," + resizetype + ",width=" + w + ",height=" + h);
	}
	else {
		cwin=window.open(url,winname,"top=" + y + ",left=" + x + ",screenX=" + x + ",screenY=" + y + "," + "status," + menutype + "," + scrolltype + "," + resizetype + ",width=" + w + ",height=" + h);
	}
	if (!cwin.opener) cwin.opener=self;
	cwin.focus();
return true;
}

// Submits the form associated with "thiswin" window and displays the results in 
// "popupname" window of dimensions 'w' and 'h'.  Uses popupWindow function. 
function submitClose(thiswin, popupname, w, h, menu, resize, scroll) {
	if (popupname == null) popupname = "resultswindow";
	if (w == null) w = 600;
	if (h == null) h = 600;
	popupWindow(popupname, w, h, menu, resize, scroll);
	
	thiswin.document.forms[0].submit();
	
	thiswin.close();
}

// Checks(status true) or unchecks(status false) all the checkboxes associated with the form.
function CheckUncheck(status) {
   for (i = 0; i < document.forms[0].length; i++) {
      document.forms[0].elements[i].checked = status
   }
}

// Reads user cookie
function ReadCookie (CookieName) {
  var CookieString = document.cookie;
//  var CookieSet = CookieString.split (';');
  var CookieSet = splitArray(CookieString, ';');
  var SetSize = CookieSet.length;
  var CookiePieces
  var ReturnValue = "";
  var x = 0;

  for (x = 0; ((x < SetSize) && (ReturnValue == "")); x++) {

//    CookiePieces = CookieSet[x].split ('=');
    CookiePieces = splitArray(CookieSet[x], '=');

    if (CookiePieces[0].substring (0,1) == ' ') {
      CookiePieces[0] = CookiePieces[0].substring (1, CookiePieces[0].length);
    }

    if (CookiePieces[0] == CookieName) {
      ReturnValue = CookiePieces[1];
    }

  }

  return ReturnValue;
}

// Swaps one Character for Another
function SwapStr (str, fnd, rpl) {
  if (rpl.indexOf(fnd) != -1) return str;

  while ((pos = str.indexOf(fnd)) != -1) {
    str = str.substring(0,pos) + rpl + str.substring(pos+fnd.length,str.length);
  }

  return str;
}

// A JavaScript 1.0 version of split
function splitArray(joinedString, splitString) {
	var tempArray = new Array(0);
	var arrayCounter = 0;
	var elementBoolean	= true;
	for (var i = 0; i < joinedString.length; i++) {
		if(elementBoolean) {
			tempArray[arrayCounter] = "";
			elementBoolean 		  = false;
			}
		if(joinedString.charAt(i) == splitString) { 
			arrayCounter++;
			elementBoolean = true;
			continue;
			}
		tempArray[arrayCounter] += joinedString.charAt(i);
		}
	return tempArray;
	}


//If a checkbox is selected in a form, this will give a 
//confirmation as to whether they really want to check 
//the box or not. Clicking "Ok" will leave the checkbox alone. 
//Clicking "Cancel" will make the checkbox become unchecked.
//
//Inputs:	thisform (the form object identifier)
//		checkname (the name of the form variable for the checkbox)
function VerifyCheckBox(thisform, checkname) {
   if (thisform.elements[checkname].checked) {
	   if (confirm("Are you sure?")) {
		        thisform.elements[checkname].checked=true;
			return true;
		} else {
	   		thisform.elements[checkname].checked=false;
			return false;
		}
	}
}

//	If the page has been called in a frame, this will reload the location 
//	in the top of the browser window.
function VerifyLoadedOnTop() {
	if (top.frames.length!=0)
	top.location=self.document.location;
	return true;
}

function CheckStateValue (thisform, testvalue, partnerwebsite, passcity) {
	//alert('State: '+thisform.State.value+', State abbrev len: '+thisform.State.length);
	var myString = thisform.State.value;
	if (myString.indexOf(testvalue) == 2) {
		if (passcity == 1){
			 var myCity	 = thisform.City.value;
	  		 partnerwebsite = partnerwebsite + '&st=' + myString + '&cty=' + myCity;
		}
	   window.open(partnerwebsite,'MoveOnIn');
	   thisform.submit();
	   return false;
	}
	else{
		thisform.submit();
		return true;
	}
}

// this function preserves aspect ratio.... 
function resizeImage(prevImgId, fixedWidth) { 
    // create an image object 
    actImg = new Image(); 
	img=document.getElementById(prevImgId);
    // associate the Image object to the image 
    actImg.src = img.src; 
    // get the file size , width and height of the image 
    imgWidth = actImg.width; 
    imgHeight = actImg.height; 
    // to find the aspect ratio 
    if (imgWidth > fixedWidth) { 
        // if the width is greater than height then fix width = fixedWidthHeight 
            imgHeight = (imgHeight*fixedWidth)/imgWidth; 
            imgWidth = fixedWidth; 
    } 
    // assign the calculated width and height to the preview image field. 
    if ((imgWidth > 0)&&(imgHeight > 0)) {
    img.width = imgWidth; 
    img.height = imgHeight; 
    }
} // end of resizeImage function 

function testme(someval) {
	alert(someval);
}
function SetChecked(val,chkName,formname) {
	var form=formname;
	dml=document.forms[form];
	len = dml.elements.length;
	var i=0;
	for( i=0 ; i<len ; i++) {
		if (dml.elements[i].name==chkName) {
			dml.elements[i].checked=val;
		}
	}
}

function charcount(field, countfield, maxlimit){
if (field.value.length > maxlimit){ 
// if too long...trim it!
field.value = field.value.substring(0, maxlimit); 
alert('You have run out of space.');
document.all[countfield].innerHTML = maxlimit - field.value.length;
}
else // otherwise, update ''characters left'' counter
document.all[countfield].innerHTML = maxlimit - field.value.length;
}

function checkForEnter(evt, action) 
  {
	 evt = (evt) ? evt : event
	 var charCode = (evt.which) ? evt.which : evt.keyCode;
	 if (charCode == 13) 
	{
		formSubmit(action);
		//return false;
	}
}

