// vc_id = "$Id: mainLibrary.js 12508 2009-04-14 00:19:46Z jgiven $"
// This is the NEW general library of functions
function rtListingHolder() {
	//alert('getting here');
	var brRes = window.parent.screen.width + "X" + window.parent.screen.height;
	var brResWidth = window.parent.screen.width;
	var brResHeight = window.parent.screen.height;
	if (brResWidth >= 1024) {
		parent.document.getElementById('rtListingHolder').style.display = 'block';
		parent.document.getElementById('rtListingHolder').style.height = brResHeight + 'px';
	} else {
		parent.document.getElementById('rtListingHolder').style.display = 'none';
	}
}

// method to get an id'd element
// @param id of the element
// @param frame that the element is in, optional
// @return element
function getElementById( id, frame ) {
        var el = null;

        if ( frame ) {
          el = window.parent[ frame ].document.getElementById( id );
        } else {
          el = document.getElementById( id );
        }
	
	return el;
}

// method to set the html of an id'd element
// @param id of the element
// @param new html
// @param frame that the element is in, optional
function setHtmlById( id, html, frame, isPparent ) {
		if (isPparent == 0)
        	var el = getElementById( id );
		else if (isPparent == 1)
			var el = parent.getElementById( id );
        if ( el ) {
	  el.innerHTML = html;
        }
}

// method to get the html of an id'd element
// @param id of the element
// @param frame that the element is in, optional
// @return html
function getHtmlById( id, frame ) {
        var el = getElementById( id, frame );
        var html = "";
        
 	if ( el ) {
	  html = el.innerHTML;
        }
	return html;
}

// method to extract the input field settings
// from a form
// @param form to extract from
// @return an associative array.  each key in the
//  array is a name of a form input.  the associated
//  value is an array of input form values.
function extractFormSettings( form ) {
    var settings = new Object( );
    var elements = form.elements;
    for ( var i = 0; i < elements.length; i++ ) {
      var type = elements[i].type;
      if ( type == "hidden" || 
           type == "text" ||
           type == "select-one" ||
		   type == "password" ||
           ( type == "checkbox" && elements[i].checked ) ||
           ( type == "radio" && elements[i].checked ) ) {
        captureFormSetting( settings, elements[i].name, elements[i].value );
      } else if ( type == "select-multiple" ) {
        for ( var j = 0; j < elements[i].options.length; j++ ) {
          if ( elements[i].options[j].selected ) {
            captureFormSetting( settings, elements[i].name, elements[i].options[j].value );
          } 
        }
      }
    }
    return settings;
}

// method to update a form element with a new value.
// centralizes the logic of handling different element types.
// currently, this impl. skips input types that one would likely
// not update. like button, submit, reset and image.  also, it will
// set multiple values for checkbox and select-multiple, if an array of 
// values is passed.  otherwise, the standard single value is accepted.
// @param form element object
// @param new value, null will do nothing
function updateFormElement( element, value ) {
    var type = element.type;
    var name = element.name;

    if ( value != null ) {

      if ( type == "hidden" ||
           type == "text" ||
           type == "textarea" ) {
        element.value = value;
      } else if ( type == "radio" ||
                  type == "checkbox" ) {
        if ( type == "checkbox" && 
             ( typeof value ) == "object" ) {
          element.checked = findValueInArray( element.value, value ) > -1 ? true : false;
       } else {
          element.checked = element.value == value ? true : false;
        }
      } else if ( type == "select-one" ||
                  type == "select-multiple" ) {
        for ( var i = 0; i < element.options.length; i++ ) {
          if ( type == "select-multiple" &&
               ( typeof value ) == "object" ) {
            element.options[i].selected = findValueInArray( element.options[i].value, value ) > -1 ? true : false;
          } else {
            element.options[i].selected = element.options[i].value == value ? true : false;
          }
        }
      }
    }
}

// find the first location of this value in the array
// @param value to find
// @param array to search
// @return array index or -1 if not found 
function findValueInArray( value, els ) {
  var rcode = -1;
  for ( var i = 0; i < els.length; i++ ) {
    if ( els[i] == value ) {
      rcode = i;
      break;
    }
  }
  return rcode;
}

// helper method to store a form setting
// @param settings object
// @param input name
// @param input value
function captureFormSetting( settings, name, value ) {
    var vals = settings[name];
    if ( vals == null ) {
      vals = new Array( );
      settings[name] = vals;
    }
    vals[vals.length] = value;
}

var AMPERSAND_DELIM = "&";
var PIPE_DELIM = "|";

// method to build a query string from a form.
// this method pulls out the current settings 
// from the form, and builds the resultant 
// query string.
// @param a form to extract from
// @param optional delimeter, defaults to ampersand.
// @param optional prune, if true, clear out empty values
// @return query string
function queryStringFromForm( form, delimeter, prune ) {
    var settings = extractFormSettings( form );
    var msg = "";
    var delim = "";
    delimeter = delimeter || AMPERSAND_DELIM;
    for ( key in settings ) {
      var vals = settings[key];
      var vals_escaped = new Array( );
      for ( var i = 0, j = 0; i < vals.length; i++ ) {
	  if ( !prune || vals[i] != "" ) {
	      vals_escaped[j++] = escape( vals[i] );
	  }
      }
      if ( !prune || vals_escaped.length ) {
	  msg = msg + delim + key + "=" + vals_escaped;
	  delim = delimeter;
      }
    }
    return msg;
}

function hideLoader( divID ) {
	document.getElementById(divID).style.display = 'none';
}

function showLoader( divID ) {
	document.getElementById(divID).style.display = 'block';
}

//Returns the height of a browser window
function getWindowHeight() {
	var windowHeight = 0;
	if (typeof(window.innerHeight) == 'number') {
		windowHeight = window.innerHeight;
	}
	else {
		if (document.documentElement && document.documentElement.clientHeight) {
			windowHeight = document.documentElement.clientHeight;
		}
		else {
			if (document.body && document.body.clientHeight) {
				windowHeight = document.body.clientHeight;
			}
		}
	}
	return windowHeight;
}

function showHideElement(el) {
	var thisDivElement = document.getElementById(el);
	
	if ((thisDivElement.style.display == '')||(thisDivElement.style.display == 'block')) {
		thisDivElement.style.display = 'none';
	} else {
		thisDivElement.style.display = 'block';
	}
	
}

function refreshParent() {
  window.opener.location.href = window.opener.location.href;
  if (window.opener.progressWindow) 
    window.opener.progressWindow.close();
  window.close();
}

function getClientWidth() {
	var thsClientWidth = document.body.clientWidth;
	return thsClientWidth;
}

function setIframeHeight(frameName,headerHeight) {
	var iframeElement = document.getElementById(frameName);
	var clientHeight = document.body.clientHeight - headerHeight;
	iframeElement.style.height =  clientHeight + 'px';
}

function setDivHeight(divID,headerHeight) {
	var divElement = document.getElementById(divID);
	var clientHeight = document.body.clientHeight - headerHeight;
	divElement.style.height =  clientHeight + 'px';
}

function setIframeWidth(frameName,offSetWidth) {
	var iframeElement = document.getElementById(frameName);
	var clientWidth = document.body.clientWidth - offSetWidth;
	iframeElement.style.width =  clientWidth + 'px';
}


// helper method return a number in a usd format
// @param input number to be formatted
// @param input showSign bool show '$' in return string if true

function dollarFormat (number, showSign) 
{
	var sStr = "";
	sStr += number;
	if(showSign == true)
	{
		var moneyval = "$";
	}
	else
	{
		var moneyval = "";
	}
	var i;
	for (i=0; i < sStr.length; i++) 
	{
		j=i+1;
		moneyval += sStr.substring(i,j);
		if (number == Math.round(number)) 
		{ 
			pos = sStr.length-j;
		}
		else 
		{
			pos = sStr.length-3-j;
		}
		tmp = Math.round(pos/3);
		if (pos == tmp*3 && pos != 0) 
			moneyval+=",";
	}
	return moneyval;
}

// get the key code, related to an event, in a 
// standard way.  typically, you would register this
// to an onKeyDown handler.
// @param event
// @return keycode number, or -1 if none found
function getKeyCode( e ) {
	return e ? ( e.which ? e.which : e.keyCode ) : -1;
}

// capture a key event
// @param event
// @param key to look for
// @param action to take ( function ptr ) if key found,
//  this function will be passed the event
// @return false if found key.  this may seem counter intuitive, but
//  makes it easy to cancel default behavior, ex:
//   onKeyDown="return captureKey( e, key,act );"
function captureKey( e, key, act ) {
  rcode = true;
  if ( getKeyCode( e ) == key ) {
    act( e );
    rcode = false;
  }
  return rcode;
}

// capture a key events
// @param event
// @param array of keys to look for.  indices are the key codes.  
//  values are the associated action to take ( function ptr ).
//  remember, js Arrays are sparse, and can contain only the indices you need.
// @return false if found key.  this may seem counter intuitive, but
//  makes it easy to cancel default behavior, ex:
//   onKeyDown="return captureKeys( e, map );"
function captureKeys( e, map ) {
  rcode = true;
  var code = getKeyCode( e );
  if ( map[code] ) {
    map[code]( e );
    rcode = false;
  }
  return rcode;
}


// below is where we could register useful/known key codes
var KEY_CODE_ENTER = 13;
var KEY_CODE_BACKSPACE = 8;

// Generic funtion for setting opacity on objects.
function setOpacity(id, opacStart, opacEnd, millisec) {
    var speed = Math.round(millisec / 100);
    var timer = 0;

    if(opacStart > opacEnd) {
        for(i = opacStart; i >= opacEnd; i--) {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    } else if(opacStart < opacEnd) {
        for(i = opacStart; i <= opacEnd; i++)
            {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    }
}

/* change the opacity for different browsers */
function changeOpac(opacity, id) {
    var object = document.getElementById(id).style;
    object.opacity = (opacity / 100);
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
    object.filter = "alpha(opacity=" + opacity + ")";
} 

function setFullOpac(id, setOpac) {
	var object = document.getElementById(id).style;
	if (setOpac) {
		object.opacity = setOpac;
		object.MozOpacity = setOpac;
		object.KhtmlOpacity = setOpac;
		object.filter = "alpha(opacity=" + setOpac + ")";
	} else {
		object.opacity = 100;
		object.MozOpacity = 100;
		object.KhtmlOpacity = 100;
		object.filter = "alpha(opacity=100)";
	}
}

function setZeroOpac(id) {
	var object = document.getElementById(id).style;
    object.opacity = 0;
    object.MozOpacity = 0;
    object.KhtmlOpacity = 0;
    object.filter = "alpha(opacity=0)";
}

// Functions to return any object screen XY
function findPosX(obj)
  {
    var curleft = 0;
    if(obj.offsetParent)
        while(1) 
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
  }

  function findPosY(obj)
  {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
  }
  
  // Function to set the proper shim regardless of ppV2 or ppV3

function setShim( mapWidth ) {
	var currentMapWidth = null;
	var mapImage = document.getElementById('mapImage');

		if (mapWidth) { // if ppV2
			if (mapWidth == 670) {
				currentMapWidth = 627;
			} else if (mapWidth == 535) {
				currentMapWidth = 492;
			} else {
				currentMapWidth = 385;
			}
		} else { // if ppV3
			currentMapWidth = mapImage.offsetWidth;
		}
		
		var ppResize1 = document.getElementById('ppResize1');
		var ppResize2 = document.getElementById('ppResize2');
		var ppResize3 = document.getElementById('ppResize3');

		ppResize1.className = 'ppShim1';
		ppResize2.className = 'ppShim2';
		ppResize3.className = 'ppShim3';

		if (currentMapWidth == 492) {
			ppResize2.className = 'ppShim2on';
		} else if (currentMapWidth == 627) {
			ppResize3.className = 'ppShim3on';
		} else {
			ppResize1.className = 'ppShim1on';
		}
}

function isDefined(variable) {
	return (!(!(document.getElementById(variable))))
}

/**
 * size window inner to width,height.  
 * good for dynamically sizing popups.  
 * missing width, height will default to contents size ( experimental )
 * this width default only is accurate if the original window width is smaller than
 * the content width.  until another solution is found, original window sizes should
 * be sized narrow, then dynamically made wider by this function if width is not passed.
 * @param width, defaults to content width
 * @param height, defaults to content height
 */
function resizeWindowInner( width, height ) {
      if ( window.innerWidth ) {
	  /** non ie */
	  if ( !width ) { width = window.innerWidth + window.scrollMaxX; }
	  if ( !height ) { height = window.innerHeight + window.scrollMaxY; }
	  window.innerWidth = width;
	  window.innerHeight = height;
      } else {
        /** ie */
	  if ( !width ) { width = document.body.scrollWidth; }
	  if ( !height ) { height = document.body.scrollHeight; } 
	  var dw = width - document.body.clientWidth;
	  var dh = height - document.body.clientHeight;
	  window.resizeBy(dw, dh);
      }
}

/**
 * attach a callback to an arbitrary dom object and event
 * @param dom object to register with
 * @param event to listen to; load,click,mousedown
 * @param callback function
 */
function registerEventHandler( reporter, activity, callback ) {
    activity = activity.toLowerCase( );
    if ( reporter.addEventListener ) {
	reporter.addEventListener( activity, callback, false );
    } else {
	activity = "on" + activity;
	if ( reporter.attachEvent ) {
	    reporter.attachEvent( activity, callback );
	} else {
	    reporter[ activity ] = reporter[ activity ] ? reporter[ activity ] + callback : callback;
	}
    }
}

/***********************************************************
// Memento - popup calendar
***********************************************************/
// all the js junk Memento needs to run
function checkDate(the_date) {
	if (document.TheDate.TextDate.value.indexOf("-") == true){
		var date_array = the_date.split("-");
	} else {
		var date_array = the_date.split("/");
	}
	if ((date_array.length == 3) &&
		(date_array[0] > 0) && (date_array[0] < 13) &&
		(date_array[1] > 0) && (date_array[1] < 32) &&
		(date_array[2] >= 0) && (date_array[1] < 100))
	{
		return true;
	} else {
		alert("Please click the calendar icon to select the date, or type a date in m/d/yyyy format. For example, type 1/20/2008.");
		return false;
	}
}

function ValidateForm(the_date){
	if (!checkDate(the_date)){
		return false;
	}
	return true;
 }
 
function isEven (num) {
	if (num % 2 == 0) {
		return true;
	} else {
		return false;
	}
} 

/**
 * Sets a Cookie with the given name and value.
 *
 * name       Name of the cookie
 * value      Value of the cookie
 * [expires]  Expiration date of the cookie (default: end of current session)
 * [path]     Path where the cookie is valid (default: path of calling document)
 * [domain]   Domain where the cookie is valid
 *              (default: domain of calling document)
 * [secure]   Boolean value indicating if the cookie transmission requires a
 *              secure transmission
 */
function setCookie(name, value, expires, path, domain, secure) {
    // set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );

	/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
	expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
	
}

/**
 * Gets the value of the specified cookie.
 *
 * name  Name of the desired cookie.
 *
 * Returns a string containing value of specified cookie,
 *   or null if cookie does not exist.
 */
function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

// Simple function to add days to a date object and return it's value.
// Right now it simply adds days, but this can be extended as needed.
function addDate (numToAdd) {
	var thsDate = new Date();
	thsDate.setDate(thsDate.getDate() + numToAdd);
	
	return thsDate;
}


// function to limit number of selection in multiple select box to a specified value
// if more than the specified number are selected, the user is notified and any selection(s) over the limit are deselected until
// only the specified selection maximum remains
function limitSelect(element, maxSelections)
{
	var numSelected = 0;
	for (var i=0; i<element.options.length; i++) 
	{
		if(element.options[i].selected == true)
		{
			numSelected++;
			if(numSelected > maxSelections)
			{
				alert('Sorry, only ' + maxSelections + ' are allowed');
				element.options[i].selected = false;
			}
		}
	}
	
}

function setFormLabels (form, label, value, expectedValue, onFocus) {
	var d = document.getElementById('messageDiv');
	if (onFocus) {
		//d.innerHTML = form[label].value;
		form[label].select();
	} else {
		if (value == '') {
			form[label].value = expectedValue;
		}
	}
}

function lightBoxLight (html,imgWidth,imgHeight,ovrflow,id) {
	if(getCookie(id) != 1){	
		var myDate = new Date(); 
		//myDate.setMinutes(myDate.getMinutes()+2) ;
		myDate.setDate(myDate.getDate()+3) ;
		//setCookie(id,1,myDate);
		document.cookie = id+"=1;expires="+myDate;
		var windowHeight = document.body.clientHeight;
		var windowWidth = document.body.clientWidth;
		
		//create an iFrame around the lightbox to prevent flash movies from overlapping it
		var newiframe= document.createElement('iframe');
		var iframeid = 'ltIframe';
		newiframe.setAttribute('id',iframeid);
		newiframe.setAttribute('name',iframeid);
		newiframe.setAttribute('allowtransparency','true');
		newiframe.setAttribute('frameborder','0');
		document.body.appendChild(newiframe);
		
		var thsIframe = document.getElementById('ltIframe');
		
		thsIframe.style.position = 'absolute';
		thsIframe.style.border = '0px';
		thsIframe.style.top = ((windowHeight-imgHeight) / 2) + 'px';
		thsIframe.style.left = ((windowWidth -imgWidth) / 2) + 'px';
		thsIframe.style.width = imgWidth + 'px';
		thsIframe.style.height = imgHeight + 'px';

		var oDiv = document.createElement('div');
		oDiv.setAttribute('id', 'oDiv');
		oDiv.style.position = 'absolute';
		oDiv.style.top = '0px';
		oDiv.style.left = '0px';
		oDiv.style.backgroundColor = '#333333';
		oDiv.style.zIndex = '2000';
		oDiv.style.width = windowWidth + 'px';
		oDiv.style.height = windowHeight + 'px';
		oDiv.style.opacity = .50;
		oDiv.style.filter = 'alpha(opacity=' + 50 + ')';
		
		var mDiv = document.createElement('div');
		mDiv.setAttribute('id', 'mDiv');
		mDiv.style.position = 'absolute';
		mDiv.style.zIndex = '2500';
		mDiv.style.backgroundColor = '#FFFFFF';
		if (ovrflow != ""){
			mDiv.style.overflow = ovrflow;
			
		}
		else{
			mDiv.style.overflow = 'auto';
		}
		//mDiv.style.top = ((windowHeight * .25) / 2) + 'px';
		//mDiv.style.left = ((windowWidth * .25) / 2) + 'px';
		//mDiv.style.width = ((windowWidth * .75)) + 'px';
		//mDiv.style.height = ((windowHeight * .75)) + 'px';

		mDiv.style.top = ((windowHeight-imgHeight) / 2) + 'px';
		mDiv.style.left = ((windowWidth -imgWidth) / 2) + 'px';
		mDiv.style.width = imgWidth + 'px';
		mDiv.style.height = imgHeight + 'px';
		
		
		mDiv.innerHTML = '<div style="background-color: #cccccc;"><div style="float: right;"><a href="#" onclick="removeLightBoxLight();">Close This Window</a></div><div style="clear: both;"></div></div>';
		mDiv.innerHTML += html;
		
		document.body.appendChild(oDiv);
		document.body.appendChild(mDiv);
	}

}
function removeLightBoxLight () {
	var oDiv  = document.getElementById('oDiv');
	var mDiv  = document.getElementById('mDiv');
	var ltIframe  = document.getElementById('ltIframe');

	oDiv.style.display = 'none';
	mDiv.style.display = 'none';
	ltIframe.style.display = 'none';
}

function showFeedbackForm () {

		var mDiv = document.getElementById('feedback_form'); 
		//mDiv.setAttribute('id', 'mDiv');
		mDiv.style.position = 'absolute';
		//mDiv.style.zIndex = '2500';
		mDiv.style.backgroundColor = '#FFFFFF';
		mDiv.style.top = (findPosY(document.getElementById('feed_back'))-230) + 'px'; 
		mDiv.style.left = (findPosX(document.getElementById('feed_back'))-250) + 'px';
		mDiv.style.width = 270 + 'px';
		mDiv.style.height = 155 + 'px';
		mDiv.style.padding = 10 +'px';
		mDiv.style.border ='1px solid black';
		
		document.getElementById('feedback_form').style.display='block';
		//document.body.appendChild(mDiv);
		

}
function sendEmailFeedback (val,emailId) { 
		var EMAIL_FEEDBACK = new XHR( "Email Feedback" );
		EMAIL_FEEDBACK.addListener( new XHRStateChangeListener( sendFeedback ) );
		if(emailId != ""){
			EMAIL_FEEDBACK.setAction( 'index.cfm?fuseaction=account.SendFeedback&comments='+val +'&emailId='+emailId);
		}
		else {
			EMAIL_FEEDBACK.setAction( 'index.cfm?fuseaction=account.SendFeedback&comments='+val);
		}

		EMAIL_FEEDBACK.run( null );
		
		return false;
	}
	
function sendFeedback ( xhr ) { 
		var ed = document.getElementById('feedback_form');
			if ( xhr.complete( ) ) {
				if ( xhr.success( ) ) { 
				ed.innerHTML = '<br><br>Your email has been sent.<br><br>  Thank you for your input!'; 
				setTimeout("setOpacity(\'feedback_form\', 100, 0, 2500)", 2500);
				setTimeout('document.getElementById("feedback_form").style.display = "none"', 5000);
				} else { 
				ed.innerHTML = xhr.responseText();
				//ed.style.backgroundColor = '#c62828';
				ed.style.color = 'red';
				ed.style.fontWeight = 'bold';
				setTimeout("setOpacity(\'feedback_form\', 100, 0, 2500)", 7000);
				setTimeout('document.getElementById("feedback_form").style.display = "none"', 9500);
				}
			}
}

function removefeedbackform (){ 
document.getElementById('feedback_form').style.display='none';
}


