var agt = navigator.userAgent.toLowerCase();
var is_major = parseInt(navigator.appVersion);
var is_nav = ((agt.indexOf('mozilla') != -1) && (agt.indexOf('spoofer') == -1) && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera') == -1) && (agt.indexOf('webtv') == -1));
var is_nav4up = (is_nav && (is_major >= 4));
var is_ie = (agt.indexOf("msie") != -1);
var is_ie3  = (is_ie && (is_major < 4));
var is_ie4  = (is_ie && (is_major == 4) && (agt.indexOf("msie 5") == -1) && (agt.indexOf("msie 6") == -1) && (agt.indexOf("msie 7") == -1) && (agt.indexOf("msie 8") == -1));
var is_ie4up = (is_ie && (is_major >= 4));
var is_ie5up  = (is_ie  && !is_ie3 && !is_ie4);
var is_mac = (agt.indexOf("mac") != -1);
var is_gecko = (agt.indexOf("gecko") != -1);

function getObject(id)
{
	if (is_ie4) 
		var el = eval(id);
	if (is_ie5up || is_gecko)
		var el = document.getElementById(id);
	return el;
}

function addGetVariable(string, variable, val)
{
	// process for each variable in the array
	if(isArray(variable))
  {
  	for(i=0; i<variable.length; i++)
    	string = addGetVariable(string, variable[i], (isArray(val) ? val[i] : val));
    return string;
  }
  
  // if the val is an object, extract its value
	if(typeof(val) == 'object')
  	if(val.selectedIndex != "undefined")
    	val = val.options[val.selectedIndex].value;
    else
    	val = val.value;
  
  // do the adding
	regexp = new RegExp(variable+"=[^&]*");

	// variable is already there
	if(string.match(regexp))
  	return string.replace(regexp, variable+"="+val);

  // variable is not there, add it to the end
 	if(string.match(/\?/))
 		return string+"&"+variable+"="+val;

 	//otherwise put it as only
 	return string+"?"+variable+"="+val;
}

function addslashes(str) 
{
  str=str.replace(/\'/g,'\\\'');
  str=str.replace(/\"/g,'\\"');
  str=str.replace(/\\/g,'\\\\');
  str=str.replace(/\0/g,'\\0');
  return str;
}
function stripslashes(str)
{
  str=str.replace(/\\'/g,'\'');
  str=str.replace(/\\"/g,'"');
  str=str.replace(/\\\\/g,'\\');
  str=str.replace(/\\0/g,'\0');
  return str;
}

function getWindow(t, s)
{
	if(t == "top")
  {
  	if(s > screen.availHeight)
    	return 0;
    return (screen.availHeight-s)/2
  }
  else
  {
  	if(s > screen.availWidth)
    	return 0;
    return (screen.availWidth-s)/2
  }
}

function centerWindow(id)
{
	t = getWindow("top", getElementHeight(id));
  l = getWindow("left", getElementWidth(id));
  setElementLeft(id, l);
  setElementTop(id, t);
}

function popWindow(loc, title, w, h, r, m)
{
	t = getWindow("top", h);
  l = getWindow("left", w);
  if(w == 'full' || w > screen.availWidth)
  	w = screen.availWidth;
  if(h == 'full' || h > screen.availHeight)
  	h = screen.availHeight;  	
    
	win = window.open(loc, title, 'top='+t+',left='+l+',width='+w+',height='+h+',status=no,resizable='+r+',scrollbars='+(h > screen.availHeight || w > screen.availWidth ? "yes" : r)+',toolbar='+(m == 'yes' ? "yes" : "no")+',location='+(m == 'yes' ? "yes" : "no")+',directories='+(m == 'yes' ? "yes" : "no")+',menubar='+(m == 'yes' ? "yes" : "no"));
	win.focus();
}

function showHelp(id)
{
	popWindow("help.php?id="+id, "help", 300, 300, "no");
}

function showCustomFormsHelp(id)
{
	popWindow("/view_custom_form_help.php?id="+id, "help", 300, 300, "no");
}

function setHTML(o, html)
{
	getObject(o).innerHTML = html;
}

function round(num)
{ 
  num = num.toString();
  if(num.indexOf(".") == -1)
  	return num;
  var split = num.split("."); 
  var dec = split[1].substr(0,3); 
  var dec1 = dec.match(/\d{2,2}/); 
  var dec2 = dec.match(/(\d$)/); 
  var rounded = (dec1 + "." + dec2[0]); 
  return split[0] + "." + Math.round(rounded); 
}

function is_numeric(s, int_only)
{
	if(isNaN(s))
  	return false;
  if(!int_only || s.indexOf(".") == -1)
  	return true;
  return false;
}

function doSaveAs()
{
	if(document.execCommand)
    document.execCommand("SaveAs");
  else
		alert('Feature available only in Internet Explorer 4.0 and later.');
}

function upgradeAccount(msg)
{
	alert("The ability to "+msg+" is not enabled for your account.\n\nPlease email deisenberg@mls2u.com for details about enabling it.");
  return false;
}

function URLEncode(plaintext)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
}

function URLDecode(encoded)
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
  return plaintext;
}

function getRequestURI(path)
{
	url = path.split("/");
  url = url[url.length-1];
  return url;
}

function changeDisplay(obj, display)
{
	obj = obj.style ? obj : getObject(obj);
  if(obj)
		obj.style.display = display;
}

function setDisplay(id, display)
{
	changeDisplay(id, display);
}

function show(id, display)
{
	changeDisplay(id, display ? display : 'block');
}

function hide(id)
{
	changeDisplay(id, 'none');
}

function showHide(id)
{
	if(is_ie4up || is_gecko)
	{
  	var show = getObject('show_'+id);
		var hide = getObject('hide_'+id);
		var c = getObject('counties_'+id);
		
    if(c.style.display == '')
		{
    	c.style.display = 'none';
			show.style.display = '';
			hide.style.display = 'none';
		}
    else
		{
			c.style.display = '';
			show.style.display = 'none';
			hide.style.display = '';
		}
	}
}

function showHideCond(id, i)
{
	if(i)
  	getObject(id).style.display = 'block';
  else
  	getObject(id).style.display = 'none';
}

function showState(name, m, id)
{
	if(is_ie4up || is_gecko) {
  	var s = getObject(name+m+'_'+id);
    if(s.style.display == '')
    	s.style.display = 'none';
    else 
    	s.style.display = '';
	}
}

function delay(gap)
{
	/* gap is in millisecs */
	var then,now;
  then=new Date().getTime();
	now=then;
	while((now-then)<gap)
  	now=new Date().getTime();
}

function stripString(string, strip_pennies)
{
	if(strip_pennies !== false)
  	string = string.replace(/\.(.{2})$/, "");
    
	string = string.replace(/[^\d]/g, "");
  return string;
}

function checkCorrespondingBox(m, c)
{
	if(m.value)
  	getObject(c).checked = "checked";
  else
  	getObject(c).checked = false;
}

function check(id)
{
	if(isArray(id))
  	for(i in id)
    {
    	getObject(id[i]).checked = 'checked';
      getObject(id[i]).onclick();
    }
  else
  {
		getObject(id).checked = 'checked';
    getObject(id).onclick();
  }
}

function uncheck(id)
{
	if(isArray(id))
  	for(i in id)
    {
    	getObject(id[i]).checked = false;
      getObject(id[i]).onclick();
    }
  else
  {
		getObject(id).checked = false;
    getObject(id).onclick();
  }
}

function swapCheck(id)
{
	if(getObject(id).checked)
  	getObject(id).checked = false;
  else
		getObject(id).checked = 'checked';
}

function isArray(obj)
{
	if(!window.obj || obj.constructor.toString().indexOf("Array") == -1)
		return false;
	return true;
}

function changeTo(highlightcolor)
{
	source=event.srcElement;
	if (source.tagName=="TABLE")
		return;
	while(source.tagName!="TR")
		source=source.parentElement;
	if (source.style.backgroundColor!=highlightcolor&&source.id!="ignore")
		source.style.backgroundColor=highlightcolor;
}

function changeBack(originalcolor)
{
	if (event.fromElement.contains(event.toElement)||source.contains(event.toElement)||source.id=="ignore")
		return;
	if (event.toElement!=source)
		source.style.backgroundColor=originalcolor;
}

function addLoadEvent(func)
{
	if(typeof func == 'string')
  	eval('func = function() {'+func+';}');
    
	var oldonload = window.onload;
  if (typeof window.onload != 'function')
  	window.onload = func;
  else
  	window.onload = function() { oldonload(); func(); }
}

function messageFocus()
{
	getObject("message").focus()
}

function isArray(obj)
{
	//returns true is it is an array
	if (obj.constructor.toString().indexOf('Array') == -1)
		return false;
	return true;
} 

function execThis(obj, action)
{
	source=event.srcElement;
  fTag = obj.tagName;
	if(fTag == "TABLE" || fTag == "TR")
  	fTag = "TD";
	if(source.tagName != fTag)
		return;

	eval(action);
}

function eventIsThis(obj)
{
	source=event.srcElement;
  if(source.tagName == "A" || source.tagName == "INPUT" || source.tagName == "LABEL")
  	return false;
	return true;
}

/**
 * DHTML textbox character counter (IE4+) script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */

function charLimit(id, maxLength, a) {
	var charObj = id.value || id.id || id.name ? id : getObject(id);
	if (charObj.value.length >= maxLength) 
  {
  	if(a)
    	alert("You have reached your limit of "+maxLength+" characters.");
  	return false;
  }
}

function charCount(id, maxLength, a, visCnt) { 
	var charObj = id.value || id.id || id.name ? id : getObject(id);
	if (charObj.value.length > maxLength)
  {
  	charObj.value = charObj.value.substring(0,maxLength);
    if(a)
    	alert("The text that you pasted has been cut down to the allowed length of "+maxLength+" characters.");
  }
	if (visCnt)
  {
    visCnt = document.getElementById(visCnt);
  	content = maxLength-charObj.value.length;
  	if (document.getElementById && !document.all)
    {
      rng = document.createRange();
      rng.setStartBefore(visCnt);
      htmlFrag = rng.createContextualFragment(content);
      while (visCnt.hasChildNodes())
	      visCnt.removeChild(visCnt.lastChild);
      visCnt.appendChild(htmlFrag);
    }
    else
	  	visCnt.innerText=content;
  }
}

function copyText(from, to)
{
	if(getObject(from))
  	from = getObject(from).value;
    
	getObject(to).value = from;
}

function copyToClipboard(text)
{
	window.clipboardData.setData('Text',text); 
}

function getObjNN4(obj,name)
{
	var x = obj.layers;
	var foundLayer;
	for (var i=0;i<x.length;i++)
	{
		if (x[i].id == name)
		 	foundLayer = x[i];
		else if (x[i].layers.length)
			var tmp = getObjNN4(x[i],name);
		if (tmp) foundLayer = tmp;
	}
	return foundLayer;
}

function getElementHeight(Elem) {
	if (is_nav && !is_nav4up) {
		var elem = getObjNN4(document, Elem);
		return elem.clip.height;
	} else {
		if(document.getElementById) {
			var elem = document.getElementById(Elem);
		} else if (document.all){
			var elem = document.all[Elem];
		}
		if (!is_gecko) { 
			xPos = elem.style.pixelHeight;
		} else {
			xPos = elem.offsetHeight;
		}
		return xPos;
	} 
}

function getElementWidth(Elem) {
	if (is_nav && !is_nav4up) {
		var elem = getObjNN4(document, Elem);
		return elem.clip.width;
	} else {
		if(document.getElementById) {
			var elem = document.getElementById(Elem);
		} else if (document.all){
			var elem = document.all[Elem];
		}
		if (!is_gecko) {
			xPos = elem.style.pixelWidth;
		} else {
			xPos = elem.offsetWidth;
		}
		return xPos;
	}
}

function setElementLeft(objectID, left)
{
	var obj = getObject(objectID);
  var objs = getObject(objectID).style;
 	objs.left = left;
} 

function setElementTop(objectID, top)
{
	var obj = getObject(objectID);
  var objs = getObject(objectID).style;
 	objs.top = top;
}

function getDateFromMySQLDate(date, part)
{
	mo = date.substr(5, 2);
  d = date.substr(8, 2);
  y = date.substr(0, 4);
  h24 = date.substr(11, 2);
  h = h24 > 12 ? h24-12 : h24;
  mi = date.substr(14, 2);
  s = date.substr(17, 2);
  ap = h24 >= 12 ? "pm" : "am";
  
	if(date)
  {
  	if(part == 'm')
    	return mo;
    else if(part == 'd')
    	return d;
    else if(part == 'y')
    	return y;
    else if(part == 't')
    	return h+":"+mi+":"+s+ap;
    else if(part == 'all')
    	return getDateFromMySQLDate(date)+" "+getDateFromMySQLDate(date, 't');
    else
			return mo+"/"+d+"/"+y;
  }
  return false;
}

function disable(id)
{  
	getObject(id).disabled='disabled';
}

function setFocus(id)
{  
	getObject(id).focus();
}

function include(src)
{
	var html_doc = document.getElementsByTagName('head').item(0);
	var js = document.createElement('script');
	js.setAttribute('language', 'javascript');
	js.setAttribute('type', 'text/javascript');
	js.setAttribute('src', src);
	html_doc.appendChild(js);
}

function checkTarget(form)
{
	var ctrlPressed=0;
  if(is_ie4up)
    ctrlPressed = event.ctrlKey;

  if(ctrlPressed) 
  	form.target = "_blank";
  return true;
}

function swapDiv(div, show)
{
	if(show)
  	getObject(div).style.display = 'block';
  else
  	getObject(div).style.display = 'none';
}

function formatURL(url)
{
	// don't mess with https URLs because of the cert sensitivity
  if(url.match(/^https:\/\//))
  	return url;
    
	// strip out http to start	
	url = url.replace(/^http:\/\//, "");
  
  // not more than one ., force www
  if(!url.match(/(.*)\.(.*)\.(.*)/))
  	url = forceWWW(url);
  
  url = "http://"+url;
	
  return url;
}

function forceWWW(string)
{
	if(string && !string.match(/^www\.(.*)/))
  	string = "www."+string;
  return string;
}

function number_format(a, b, c, d) {
	if(!b)
  	b = 0;
	if(!c)
  	c = ".";
  if(!d)
  	d = ",";
	// number_format(number, decimals, comma, formatSeparator)
	a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
	e = a + '';
	f = e.split('.');
	if(!f[0]) f[0] = '0';
	if(!f[1]) f[1] = '';
	if(f[1].length < b){
		g = f[1];
		for(i = f[1].length + 1; i <= b; i++) {
			g += '0';
		}
		f[1] = g;
	}
	if(d != '' && f[0].length > 3) {
		h = f[0];
		f[0] = '';
		for(j = 3; j < h.length; j += 3) {
			i = h.slice(h.length - j, h.length - j + 3);
			f[0] = d + i +  f[0] + '';
		}
		j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
		f[0] = j + f[0];
	}
	c = (b <= 0) ? '': c;
	return f[0] + c + f[1];
}

function checkCustomForm()
{
	var error = "";
  var error2 = "";
	for(var id in objects)
  {
  	if(objects[id]['required'] == '1')
    {
    	if((objects[id]['object_type'] == 'text' || objects[id]['object_type'] == 'textarea' || objects[id]['object_type'] == 'select') && getObject("response["+id+"]").value == "")
      {
      	error += objects[id]['name']+"\n";
      }
      else if(objects[id]['object_type'] == 'multiselect')
      {
      	selected = false;
      	m = getObject("response["+id+"][]");
      	for(var i=0; i<m.length; i++)
        	if(m[i].selected)
          	selected = true;
            
        if(!selected)
        	error += objects[id]['name']+"\n";
      }
      else if(objects[id]['object_type'] == 'checkbox' || objects[id]['object_type'] == 'radio')
      {
      	selected = false;
      	m = document.getElementsByName("response["+id+"][]");
      	for(var i=0; i<m.length; i++)
        	if(m[i].checked)
          	selected = true;
            
        if(!selected)
        	error += objects[id]['name']+"\n";
      }
    }
    
    if((objects[id]['object_type'] == 'text' || objects[id]['object_type'] == 'textarea') && objects[id]['max_char'] != '')
    {
      if(getObject("response["+id+"]").value.length > objects[id]['max_char'])
      	error2 += "Only "+objects[id]['max_char']+" characters are allowed for "+objects[id]['name']+".  You entered "+getObject("response["+id+"]").value.length+" characters.\n";
  	}
  }
  
  if(error != "" || error2 != "")
  {
  	alert((error ? "The following questions must be answered:\n"+error : "")+(error2 ? "\nThe following errors occured:\n"+error2 : ""));
    return false;
  }
  return true;
}


function checkCustomFormObject(o, id)
{
	var error = "";
  num_selected = 0;
  if(objects[id]['max_selected'] != '')
  {
  	if(objects[id]['object_type'] == 'multiselect')
    {
    	m = getObject("response["+id+"][]");
    	for(var i=0; i<m.length; i++)
      	if(m[i].selected)
        	num_selected++;
    }
    else if((objects[id]['object_type'] == 'checkbox' || objects[id]['object_type'] == 'radio') && o.checked)
    {
    	m = document.getElementsByName("response["+id+"][]");
    	for(var i=0; i<m.length; i++)
      	if(m[i].checked)
        	num_selected++; 
    }
    
    if(num_selected > objects[id]['max_selected'])
    {
    	alert("You may only select "+objects[id]['max_selected']+" item(s) for this question.");
    	return false;
    }
  }
  return true;
}