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;
}

document.getElementsByClassName = function(clsName){
	var retVal = new Array();
  var elements = document.getElementsByTagName("*");
  for(var i = 0;i < elements.length;i++){
  	if(elements[i].className.indexOf(" ") >= 0){
    	var classes = elements[i].className.split(" ");
      for(var j = 0;j < classes.length;j++){
      	if(classes[j] == clsName)
        	retVal.push(elements[i]);
      }
    }
    else if(elements[i].className == clsName)
    	retVal.push(elements[i]);
  }
  return retVal;
}

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 (self.innerHeight)
  {
  	h = self.innerHeight;
    w = self.innerWidth;
  }
	else if (document.documentElement && document.documentElement.clientHeight)
  {
  	h = document.documentElement.clientHeight;
    w = document.documentElement.clientWidth;
  }
	else if (document.body)
  {
  	h = document.body.clientHeight;
    w = document.body.clientWidth;
  }

	if(t == "top")
  {
  	if(s > h)
    	return 0;
    return (h-s)/2
  }
  else
  {
  	if(s > w)
    	return 0;
    return (w-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, d)
{
	if(i)
  	getObject(id).style.display = d ? d : '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';
      if(getObject(id).onclick)
	      getObject(id[i]).onclick();
    }
  else
  {
		getObject(id).checked = 'checked';
    if(getObject(id).onclick)
	    getObject(id).onclick();
  }
}

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

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

function isChecked(id)
{
	return getObject(id).checked ? true : false;
}

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, no_cut) { 
	var charObj = id.value || id.id || id.name ? id : getObject(id);
	if (charObj.value.length > maxLength && !no_cut)
  {
  	var e = window.event;
    	//alert(e.keyCode);

  	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 fixTarget(form)
{
	form.target = "_self";
  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 serialize (txt) {
	switch(typeof(txt)){
	case 'string':
		return 's:'+txt.length+':"'+txt+'";';
	case 'number':
		if(txt>=0 && String(txt).indexOf('.') == -1 && txt < 65536) return 'i:'+txt+';';
		return 'd:'+txt+';';
	case 'boolean':
		return 'b:'+( (txt)?'1':'0' )+';';
	case 'object':
		var i=0,k,ret='';
		for(k in txt){
			//alert(isNaN(k));
			if(!isNaN(k)) k = Number(k);
			ret += serialize(k)+serialize(txt[k]);
			i++;
		}
		return 'a:'+i+':{'+ret+'}';
	default:
		return 'N;';
		alert('var undefined: '+typeof(txt));return undefined;
	}
}

function unserialize(txt){
	var level=0,arrlen=new Array(),del=0,final=new Array(),key=new Array(),save=txt;
	while(1){
		switch(txt.substr(0,1)){
		case 'N':
			del = 2;
			ret = null;
		break;
		case 'b':
			del = txt.indexOf(';')+1;
			ret = (txt.substring(2,del-1) == '1')?true:false;
		break;
		case 'i':
			del = txt.indexOf(';')+1;
			ret = Number(txt.substring(2,del-1));
		break;
		case 'd':
			del = txt.indexOf(';')+1;
			ret = Number(txt.substring(2,del-1));
		break;
		case 's':
			del = txt.substr(2,txt.substr(2).indexOf(':'));
			ret = txt.substr( 1+txt.indexOf('"'),del);
			del = txt.indexOf('"')+ 1 + ret.length + 2;
		break;
		case 'a':
			del = txt.indexOf(':{')+2;
			ret = new Array();
			arrlen[level+1] = Number(txt.substring(txt.indexOf(':')+1, del-2))*2;
		break;
		case 'O':
			txt = txt.substr(2);
			var tmp = txt.indexOf(':"')+2;
			var nlen = Number(txt.substring(0, txt.indexOf(':')));
			name = txt.substring(tmp, tmp+nlen );
			//alert(name);
			txt = txt.substring(tmp+nlen+2);
			del = txt.indexOf(':{')+2;
			ret = new Object();
			arrlen[level+1] = Number(txt.substring(0, del-2))*2;
		break;
		case '}':
			txt = txt.substr(1);
			if(arrlen[level] != 0){alert('var missed : '+save); return undefined;};
			//alert(arrlen[level]);
			level--;
		continue;
		default:
			if(level==0) return final;
			alert('syntax invalid(1) : '+save+"\nat\n"+txt+"level is at "+level);
			return undefined;
		}
		if(arrlen[level]%2 == 0){
			if(typeof(ret) == 'object'){alert('array index object no accepted : '+save);return undefined;}
			if(ret == undefined){alert('syntax invalid(2) : '+save);return undefined;}
			key[level] = ret;
		} else {
			var ev = '';
			for(var i=1;i<=level;i++){
				if(typeof(key[i]) == 'number'){
					ev += '['+key[i]+']';
				}else{
					ev += '["'+key[i]+'"]';
				}
			}
			eval('final'+ev+'= ret;');
		}
		arrlen[level]--;//alert(arrlen[level]-1);
		if(typeof(ret) == 'object') level++;
		txt = txt.substr(del);
		continue;
	}
}

function array_search(array, val)
{
	for (var i = 0; i < array.length; i++)
		if (array[i] == val)
			return i;
	return false;
}

function ucwords (str) {
    // Uppercase the first character of every word in a string  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/ucwords    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Waldo Malqui Silva
    // +   bugfixed by: Onno Marsman
    // *     example 1: ucwords('kevin van zonneveld');
    // *     returns 1: 'Kevin Van Zonneveld'    // *     example 2: ucwords('HELLO WORLD');
    // *     returns 2: 'HELLO WORLD'
    return (str+'').replace(/^(.)|\s(.)/g, function ( $1 ) { return $1.toUpperCase( ); } );
}