function boolToInt(boolValue) {
	return (boolValue ? 1 : 0);
}

function defaultParameter(inCallerArgumentsArray, inPosition, inDefault) {
	return (inCallerArgumentsArray.length >= inPosition) ? inCallerArgumentsArray[inPosition - 1] : inDefault;
}

// Note default parameters
function dumpObject(obj) {
//	var debugOutput = document.getElementById('debugOutput');

	var asHTML = defaultParameter(arguments, 2, true);
	var maxDumpDepth = defaultParameter(arguments, 3, 10);
	var depth = defaultParameter(arguments, 4, 0);
	var indentString = defaultParameter(arguments, 5, '');
	var dumpTitle = defaultParameter(arguments, 6, 'The Object');
	
	var indentChar = (asHTML ? '+' : '\t');
	var newline = (asHTML ? '<br/>' : '\n');
	var lt = (asHTML ? '&lt;' : '<');
	var gt = (asHTML ? '&gt;' : '>');

	if(depth >= maxDumpDepth) {
		return indentString + dumpTitle + ': ' + lt + 'Maximum Depth Reached' + gt + newline;
	}
	
	if(typeof obj == "object") {
		var child = null;
		var output = indentString + dumpTitle + ':' + newline;
		
//		debugOutput.innerHTML += output;
		
		indentString += indentChar;
		
		var hasItems = false;
		for(var item in obj)
		{
			hasItems = true;
			try {
				child = obj[item];
			} catch (e) {
				child = lt + 'Unable to Evaluate' + gt;
			}
			
			var re = new RegExp("(parent)|(sibling)|(owner)", "i");
			var isParentOrSibling = re.test(item);

			if ((typeof child == "object") && !isParentOrSibling) {
//				debugOutput.innerHTML += '; child is object--dumping<br/>';
				output += dumpObject(child, asHTML, maxDumpDepth, (depth + 1), indentString, item);
			} else {
//				debugOutput.innerHTML += '; child is not an object; child is ' + item + ' value is ' + child;
				if(isParentOrSibling)
					output += indentString + item + ": " + lt + 'Parent/Sibling not shown' + gt + newline;
				else
					output += indentString + item + ": " + child + newline;
			}
		}
		
//		if(!hasItems)
//			output = indentString + dumpTitle + ': (empty object)' + newline;
		
//		debugOutput.innerHTML += 'returning ' + output;
		return output;
	} else {
		return obj;
	}
}

// Default parameter 2: enable
function enableButton(buttonIDString) {
	var enable = defaultParameter(arguments, 2, true);
	var button = document.getElementById(buttonIDString);
	if(button == null)
		alert('Button "' + buttonIDString + '" does not exist.');
	else
		button.disabled = !enable;
}

function error_log(message) {
	if(typeof document == 'undefined') {
		alert('Cannot write to JS error log--document not defined yet; attempted to log this message:\n' + message);
	} else {
		var errorLog = document.getElementById('debugOutput');
		if(errorLog == null) {
			alert('Cannot write to JS error log--page does not have a debug output element; attempted to log this message\n' + message);
		} else {
			errorLog.innerHTML += message + '<br/>';
		}
	}
}

function fuzzilyEqual(lLatLng, rLatLng) {
	// If I'm doing the math right, this epsilon amounts to 18 feet at the very worst.
	// 25000 miles / 360 degrees * .00005
	var epsilon = defaultParameter(arguments, 3, 0.00005);
		
	return (Math.abs(lLatLng.lat() - rLatLng.lat()) < epsilon) &&
			(Math.abs(lLatLng.lng() - rLatLng.lng()) < epsilon);
}

// this fixes an issue with the old method, ambiguous values 
// with this test document.cookie.indexOf( name + "=" );
function getCookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
				
				// Rob added this because somehow cookies are urlencoded from javascript's perspective,
				// although I didn't urlencode them when I stored them.
				cookie_value = cookie_value.replace(/\+/g, ' ');
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}				

// Borrowed from http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_htmlentities/
function get_html_translation_table(table, quote_style) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: noname
    // %          note: It has been decided that we're not going to add global
    // %          note: dependencies to php.js. Meaning the constants are not
    // %          note: real constants, but strings instead. integers are also supported if someone
    // %          note: chooses to create the constants themselves.
    // %          note: Table from http://www.the-art-of-web.com/html/character-codes/
    // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
    // *     returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}
    
    var entities = {}, histogram = {}, decimal = 0, symbol = '';
    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};
    
    useTable      = (table ? table.toUpperCase() : 'HTML_SPECIALCHARS');
    useQuoteStyle = (quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT');
    
    // Translate arguments
    constMappingTable[0]      = 'HTML_SPECIALCHARS';
    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';
    
    // Map numbers to strings for compatibilty with PHP constants
    if (!isNaN(useTable)) {
        useTable = constMappingTable[useTable];
    }
    if (!isNaN(useQuoteStyle)) {
        useQuoteStyle = constMappingQuoteStyle[useQuoteStyle];
    }
    if (useTable == 'HTML_SPECIALCHARS') {
        // ascii decimals for better compatibility
        entities['38'] = '&amp;';
        entities['60'] = '&lt;';
        entities['62'] = '&gt;';
    } else if (useTable == 'HTML_ENTITIES') {
        // ascii decimals for better compatibility
      entities['38'] = '&amp;';
      entities['60'] = '&lt;';
      entities['62'] = '&gt;';
      entities['160'] = '&nbsp;';
      entities['161'] = '&iexcl;';
      entities['162'] = '&cent;';
      entities['163'] = '&pound;';
      entities['164'] = '&curren;';
      entities['165'] = '&yen;';
      entities['166'] = '&brvbar;';
      entities['167'] = '&sect;';
      entities['168'] = '&uml;';
      entities['169'] = '&copy;';
      entities['170'] = '&ordf;';
      entities['171'] = '&laquo;';
      entities['172'] = '&not;';
      entities['173'] = '&shy;';
      entities['174'] = '&reg;';
      entities['175'] = '&macr;';
      entities['176'] = '&deg;';
      entities['177'] = '&plusmn;';
      entities['178'] = '&sup2;';
      entities['179'] = '&sup3;';
      entities['180'] = '&acute;';
      entities['181'] = '&micro;';
      entities['182'] = '&para;';
      entities['183'] = '&middot;';
      entities['184'] = '&cedil;';
      entities['185'] = '&sup1;';
      entities['186'] = '&ordm;';
      entities['187'] = '&raquo;';
      entities['188'] = '&frac14;';
      entities['189'] = '&frac12;';
      entities['190'] = '&frac34;';
      entities['191'] = '&iquest;';
      entities['192'] = '&Agrave;';
      entities['193'] = '&Aacute;';
      entities['194'] = '&Acirc;';
      entities['195'] = '&Atilde;';
      entities['196'] = '&Auml;';
      entities['197'] = '&Aring;';
      entities['198'] = '&AElig;';
      entities['199'] = '&Ccedil;';
      entities['200'] = '&Egrave;';
      entities['201'] = '&Eacute;';
      entities['202'] = '&Ecirc;';
      entities['203'] = '&Euml;';
      entities['204'] = '&Igrave;';
      entities['205'] = '&Iacute;';
      entities['206'] = '&Icirc;';
      entities['207'] = '&Iuml;';
      entities['208'] = '&ETH;';
      entities['209'] = '&Ntilde;';
      entities['210'] = '&Ograve;';
      entities['211'] = '&Oacute;';
      entities['212'] = '&Ocirc;';
      entities['213'] = '&Otilde;';
      entities['214'] = '&Ouml;';
      entities['215'] = '&times;';
      entities['216'] = '&Oslash;';
      entities['217'] = '&Ugrave;';
      entities['218'] = '&Uacute;';
      entities['219'] = '&Ucirc;';
      entities['220'] = '&Uuml;';
      entities['221'] = '&Yacute;';
      entities['222'] = '&THORN;';
      entities['223'] = '&szlig;';
      entities['224'] = '&agrave;';
      entities['225'] = '&aacute;';
      entities['226'] = '&acirc;';
      entities['227'] = '&atilde;';
      entities['228'] = '&auml;';
      entities['229'] = '&aring;';
      entities['230'] = '&aelig;';
      entities['231'] = '&ccedil;';
      entities['232'] = '&egrave;';
      entities['233'] = '&eacute;';
      entities['234'] = '&ecirc;';
      entities['235'] = '&euml;';
      entities['236'] = '&igrave;';
      entities['237'] = '&iacute;';
      entities['238'] = '&icirc;';
      entities['239'] = '&iuml;';
      entities['240'] = '&eth;';
      entities['241'] = '&ntilde;';
      entities['242'] = '&ograve;';
      entities['243'] = '&oacute;';
      entities['244'] = '&ocirc;';
      entities['245'] = '&otilde;';
      entities['246'] = '&ouml;';
      entities['247'] = '&divide;';
      entities['248'] = '&oslash;';
      entities['249'] = '&ugrave;';
      entities['250'] = '&uacute;';
      entities['251'] = '&ucirc;';
      entities['252'] = '&uuml;';
      entities['253'] = '&yacute;';
      entities['254'] = '&thorn;';
      entities['255'] = '&yuml;';
    } else {
        throw Error("Table: "+useTable+' not supported');
        return false;
    }
    
    if (useQuoteStyle != 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }
    
    if (useQuoteStyle == 'ENT_QUOTES') {
        entities['39'] = '&#039;';
    }
    
    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal)
        histogram[symbol] = entities[decimal];
    }
    
    return histogram;
}

// Borrowed from http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_htmlentities/
function htmlentities (string, quote_style) {
	if((typeof string != 'string') || (string.length == 0)) {
		return '';
	}
	
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: nobbler
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: get_html_translation_table
    // *     example 1: htmlentities('Kevin & van Zonneveld');
    // *     returns 1: 'Kevin &amp; van Zonneveld'
 
    var histogram = {}, symbol = '', tmp_str = '', i = 0;
    tmp_str = string.toString();
    
    if (false === (histogram = get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }
    
    for (symbol in histogram) {
        entity = histogram[symbol];
        tmp_str = tmp_str.split(symbol).join(entity);
    }
    
    return tmp_str;
}

function initForm() {
	for(var i = 0; i < document.forms.length; ++i) {
		// When the browser calls onsubmit, the return value from 
		// onsubmit tells the browser what to do next. true means that
		// the for is ok and should be submitted to the server; false
		// means that something is wrong and the form should not be
		// submitted.
		document.forms[i].onsubmit = function() { return validForm(); };
	}

	// Set the focus to the first text input field
	for(var i = 0; i < document.forms[0].length; ++i) {
		if(document.forms[0][i].type == "text") {
			document.forms[0][i].focus();
			break;
		}
	}
}

function intToBool(intValue) {
	return ((intValue == 0) ? false : true);
}

function isIE() {
   return /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);
}

function removeStyle(element, styleElement) {
//	error_log('removeStyle(' + element.id + ', ' + styleElement + ')');
//	logElementInfo(element, styleElement);

	var cssText = element.style.cssText;
	
	// A painful lesson to remember here:
	// For string.search, you can use a quoted string that has \\s in it, like string.search('\\shello')
	// For string.replace, you can't do that. I don't know why. You have to do string.replace(/\shello/, 'replacement');
	// The only way to get consistent results is to create a RegExp object, as here.
	var pattern = new RegExp('(^|\\s)' + styleElement + ': (.*?);');
	var position = cssText.search(pattern);
	if(position >= 0) {
		cssText = cssText.replace(pattern, '');
	}
	
	element.style.cssText = cssText;
	
	
	if(isIE()) {
		if(styleElement == 'visiblity') {
			element.visibility = '';
		}
	}

//	logElementInfo(element, styleElement);
//	error_log('Done with removeStyle(' + element.id + ', ' + styleElement + ')');
}

function setStyle(element, styleElement, value) {
//	error_log('setStyle(' + element.id + ', ' + styleElement + ', ' + value + ')');
//	logElementInfo(element, styleElement);
	var cssText = element.style.cssText;
	
	// A painful lesson to remember here:
	// For string.search, you can use a quoted string that has \\s in it, like string.search('\\shello')
	// For string.replace, you can't do that. I don't know why. You have to do string.replace(/\shello/, 'replacement');
	// The only way to get consistent results is to create a RegExp object, as here.
	var pattern = new RegExp('(^|\\s)' + styleElement + ': (.*?);');
	var position = cssText.search(pattern);
	if(position >= 0) {
		cssText = cssText.replace(pattern, ('$1' + styleElement + ': ' + value + ';'));
	} else {
		cssText += ' ' + styleElement + ': ' + value + ';';
	}
	
	element.style.cssText = cssText;
	
	if(isIE()) {
		if(styleElement == 'visibility') {
			element.visibility = value;
		}
	}

//	logElementInfo(element, styleElement);
//	error_log('Finish setStyle(' + element.id + ', ' + styleElement + ', ' + value + ')');
}

function stripslashes( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +      fixed by: Mick@el
    // +   improved by: marrtins
    // +   bugfixed by: Onno Marsman
    // +   improved by: rezna
    // *     example 1: stripslashes('Kevin\'s code');
    // *     returns 1: "Kevin's code"
    // *     example 2: stripslashes('Kevin\\\'s code');
    // *     returns 2: "Kevin\'s code"
 
    return (str+'').replace(/\0/g, '0').replace(/\\([\\'"])/g, '$1');
}

// Borrowed this request stuff from http://www.boutell.com/newfaq/creating/ajaxfetch.html
// Get an XMLHttpRequest object in a portable way.
function makeHTTPRequest() {
	var httpRequest = false;
	
	// For Safari, Firefox, and other non-MS browsers
	if(window.XMLHttpRequest) {
		try {
			httpRequest = new XMLHttpRequest();
		} catch(e) {
			httpRequest = false;
		}
	} else if(window.ActiveXObject) {
		// For Internet Explorer on Windows
		try {
			httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try {
				httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {
				httpRequest = false;
			}
		}
	}
	
	return httpRequest;
}
