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 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 popWindow(loc, title, w, h, r)
{
	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=no,location=no,directories=no,menubar=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 calculate(price, dest) {
	var price = getObject(price).value;
	var plan = document.getElementsByName("plan");
	for(i=0; i<plan.length; i++)
		if(plan[i].checked == true)
			var val = plan[i].value;
      
	var packagePrice = document.getElementById("p"+val+"_price").value;
	var plus = document.getElementById("p"+val+"_plus").value;
	var type = document.getElementById("p"+val+"_plus_type").value;
  var commission = .06-(getObject('selling_broker_1').checked ? (getObject('selling_broker_commission').value/100) : 0);

	if(type == 'p')
		var a = eval(price*commission-packagePrice-price*plus*.01);
	else if(type == 'd')
		var a = eval(price*commission-packagePrice-plus);
	else
		var a = eval(price*commission-packagePrice);

	getObject(dest).innerHTML = "$"+(Math.round(a) > 0 ? Math.round(a) : 0);
}

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 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 forceChooseState(a, type)
{
	var url = getRequestURI(window.location.pathname);
  var notice = true;
  if(url == "index.php" || url == "" || url == "go.php")
  {
  	msg = type == "contact" ? "Please make your request via the contact form and we will respond shortly." : "Please first choose the area your property is located in so we may direct you to our local affiliate.";
  	alert(msg);
    return false;
  }
  
  base_url = "/";
  if(current_pl_url)
	  base_url = "http://"+current_pl_url;
  else if(current_pl)
  	base_url = "/"+current_pl;
  
 	alert("You are being forwarded to the home page.\n\nPlease click OK and choose the state\nyour property is in to continue.");
  a.href = base_url+"?next="+URLEncode(getRequestURI(URLDecode(a.href)));
  return true;
}

function forceChooseCounty(a, loc, base_url)
{
	if(!base_url)
	{
		base_url = "";
		if(current_pl_url)
			base_url = "http://"+current_pl_url;
		else if(current_pl)
			base_url = "/"+current_pl;
	}
  
	if(loc)
  {
  	url = loc;
    window.location.href=base_url+"/"+current_state+"/go.php?force=true&next="+URLEncode(url);
  }
  else
  {
		url = getRequestURI(a.href);
    a.href=base_url+"/"+current_state+"/go.php?force=true&next="+URLEncode(url);
  }
  return true;
}

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

function changeDisplay(obj, display)
{
	getObject(obj).style.display = 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();
}

/*
	Developed by Robert Nyman, http://www.robertnyman.com
	Code/licensing: http://code.google.com/p/getelementsbyclassname/
*/	
var getElementsByClassName = function (className, tag, elm){
	if (document.getElementsByClassName) {
		getElementsByClassName = function (className, tag, elm) {
			elm = elm || document;
			var elements = elm.getElementsByClassName(className),
				nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
				returnElements = [],
				current;
			for(var i=0, il=elements.length; i<il; i+=1){
				current = elements[i];
				if(!nodeName || nodeName.test(current.nodeName)) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	else if (document.evaluate) {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = "",
				xhtmlNamespace = "http://www.w3.org/1999/xhtml",
				namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
				returnElements = [],
				elements,
				node;
			for(var j=0, jl=classes.length; j<jl; j+=1){
				classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
			}
			try	{
				elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
			}
			catch (e) {
				elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
			}
			while ((node = elements.iterateNext())) {
				returnElements.push(node);
			}
			return returnElements;
		};
	}
	else {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = [],
				elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
				current,
				returnElements = [],
				match;
			for(var k=0, kl=classes.length; k<kl; k+=1){
				classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
			}
			for(var l=0, ll=elements.length; l<ll; l+=1){
				current = elements[l];
				match = false;
				for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
					match = classesToCheck[m].test(current.className);
					if (!match) {
						break;
					}
				}
				if (match) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	return getElementsByClassName(className, tag, elm);
};
