// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

// site navigation methods

var xmlhttp=false;
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
	xmlhttp = new XMLHttpRequest();
}

function modal_dialog(title, url, width, height)
{
	Modalbox.show(title, url, {overlayClose:true, width:width, height:height});
}


function gcLoc(targetId){
	document.getElementById("pl[" + targetId + "]").innerHTML = "Please wait&hellip;";
}

function autotab(original){
	if (original.getAttribute&&original.value.length==original.getAttribute("maxlength")){
		var els = original.form.elements;
		var nextEl;
		for (var i=0, len=els.length; i<len; i++){
			if (original == els[i] && (nextEl = els[i+1])){
				if (nextEl.focus) nextEl.focus();
			}
		}
	}
}

function checkAll(id) {
	var el = document.getElementById(id);
	for (var i = 0; i < el.elements.length; i++) {
		if (el.elements[i].type == "checkbox" && !el.elements[i].checked) {
			targetId = el.elements[i].name.split("[")[1].split("]")[0];
			gcLoc(targetId);
			el.elements[i].checked = true;
		}
	}
}

function uncheckAll(id) {
	var el = document.getElementById(id);
	for (var i = 0; i < el.elements.length; i++) {
		if (el.elements[i].type == "checkbox" && el.elements[i].checked) {
			targetId = el.elements[i].name.split("[")[1].split("]")[0];
			gcLoc(targetId);
			el.elements[i].checked = false;
		}
	}
}


function recActive(targetId) {	
	getUrl = "/library/toggle_record/" + targetId;
	xmlhttp.open("GET", getUrl, true);
	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4) {
			if (document.getElementById("recrow[" + targetId + "]").className == "inactive") {
				document.getElementById("recrow[" + targetId + "]").className = "active"
			}
			else {
				document.getElementById("recrow[" + targetId + "]").className = "inactive"
			}
		}
	}

	xmlhttp.send(null);

}

function showLibDesc(targetId) {
	targetLink = "link[" + targetId + "]";
	targetDiv = "desc[" + targetId + "]";
	Effect.Fade(targetLink);
	Effect.Appear(targetDiv);
}

function hideLibDesc(targetId) {
	targetLink = "link[" + targetId + "]";
	targetDiv = "desc[" + targetId + "]";
	Effect.Fade(targetDiv);
	Effect.Appear(targetLink);

}



function get_directions(start, end)
{
	if (GBrowserIsCompatible()) {
		var map = new GMap2($("map_div_id"));	
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		var directionsPanel = document.getElementById("directions");
		var directions = new GDirections(map, directionsPanel);
		//GEvent.addListener(directions, "load", onGDirectionsLoad);
		//GEvent.addListener(directions, "error", handleErrors);
		directions.load(start + " to " + end);
		if ($('backtomap') != null) $('backtomap').style.display = "block"
	}
	// display a warning if the browser was not compatible
	else {
		alert("Sorry, the Google Maps API is not compatible with this browser");
	}


	return false;

}

	function gmap_update_position(){ 
		lat = $('location_lat'); 
		lng = $('location_lng'); 
		lat.value = ""+ marker.getPoint().lat(); 
		lng.value = ""+ marker.getPoint().lng(); 
		if ($('is_address')) {
			ajax_url = "/address/update_pin/" + $('address_id').value + "?lat=" + lat.value + "&lng=" + lng.value;	
		}
		else {
			ajax_url = "/map/update_pin/" + $('location_id').value + "?lat=" + lat.value + "&lng=" + lng.value;	
		}
		
		new Ajax.Request(ajax_url,{method: 'get'});
		Effect.Appear("success");

	} 



	function legendClick(i) {
		GEvent.trigger(gmarkers[i], "click");
	}

	function handleErrors(){
		if (directions.getStatus().code == G_GEO_UNKNOWN_ADDRESS) {
			alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + directions.getStatus().code);
			//window.location = window.location;
		}
		else if (directions.getStatus().code == G_GEO_SERVER_ERROR)
		alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + directions.getStatus().code);

		else if (directions.getStatus().code == G_GEO_MISSING_QUERY)
		alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + directions.getStatus().code);

		//   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
		//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);

		else if (directions.getStatus().code == G_GEO_BAD_KEY)
		alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + directions.getStatus().code);

		else if (directions.getStatus().code == G_GEO_BAD_REQUEST)
		alert("A directions request could not be successfully parsed.\n Error code: " + directions.getStatus().code);

		else alert("An unknown error occurred.");

	}

	function onGDirectionsLoad(){ 
		// Use this function to access information about the latest load()
		// results.


	}

	function sfHover(targetId) {
		if(document.getElementById(targetId))
		{
			var sfEls = document.getElementById(targetId).getElementsByTagName("LI");

			for (var i=0; i<sfEls.length; i++) {
				sfEls[i].onmouseover=function() {
					this.className+=" sfhover";
				}
				sfEls[i].onmouseout=function() {
					this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
				}
			}
		}
	}

	function show_progress() {
		$('progress').style.display = "block"
	}
	/**
	* Throughout, whitespace is defined as one of the characters
	*  "\t" TAB \u0009
	*  "\n" LF  \u000A
	*  "\r" CR  \u000D
	*  " "  SPC \u0020
	*
	* This does not use Javascript's "\s" because that includes non-breaking
	* spaces (and also some other characters).
	*/


	/**
	* Determine whether a node's text content is entirely whitespace.
	*
	* @param nod  A node implementing the |CharacterData| interface (i.e.,
		*             a |Text|, |Comment|, or |CDATASection| node
		* @return     True if all of the text content of |nod| is whitespace,
		*             otherwise false.
		*/
		function is_all_ws( nod )
		{
			// Use ECMA-262 Edition 3 String and RegExp features
			return !(/[^\t\n\r ]/.test(nod.data));
		}


		/**
		* Determine if a node should be ignored by the iterator functions.
		*
		* @param nod  An object implementing the DOM1 |Node| interface.
		* @return     true if the node is:
		*                1) A |Text| node that is all whitespace
		*                2) A |Comment| node
		*             and otherwise false.
		*/

		function is_ignorable( nod )
		{
			return ( nod.nodeType == 8) || // A comment node
			( (nod.nodeType == 3) && is_all_ws(nod) ); // a text node, all ws
		}

		/**
		* Version of |previousSibling| that skips nodes that are entirely
		* whitespace or comments.  (Normally |previousSibling| is a property
			* of all DOM nodes that gives the sibling node, the node that is
			* a child of the same parent, that occurs immediately before the
			* reference node.)
			*
			* @param sib  The reference node.
			* @return     Either:
			*               1) The closest previous sibling to |sib| that is not
			*                  ignorable according to |is_ignorable|, or
			*               2) null if no such node exists.
			*/
			function node_before( sib )
			{
				while ((sib = sib.previousSibling)) {
					if (!is_ignorable(sib)) return sib;
				}
				return null;
			}

			/**
			* Version of |nextSibling| that skips nodes that are entirely
			* whitespace or comments.
			*
			* @param sib  The reference node.
			* @return     Either:
			*               1) The closest next sibling to |sib| that is not
			*                  ignorable according to |is_ignorable|, or
			*               2) null if no such node exists.
			*/
			function node_after( sib )
			{
				while ((sib = sib.nextSibling)) {
					if (!is_ignorable(sib)) return sib;
				}
				return null;
			}

			/**
			* Version of |lastChild| that skips nodes that are entirely
			* whitespace or comments.  (Normally |lastChild| is a property
				* of all DOM nodes that gives the last of the nodes contained
				* directly in the reference node.)
				*
				* @param sib  The reference node.
				* @return     Either:
				*               1) The last child of |sib| that is not
				*                  ignorable according to |is_ignorable|, or
				*               2) null if no such node exists.
				*/
				function last_child( par )
				{
					var res=par.lastChild;
					while (res) {
						if (!is_ignorable(res)) return res;
						res = res.previousSibling;
					}
					return null;
				}

				/**
				* Version of |firstChild| that skips nodes that are entirely
				* whitespace and comments.
				*
				* @param sib  The reference node.
				* @return     Either:
				*               1) The first child of |sib| that is not
				*                  ignorable according to |is_ignorable|, or
				*               2) null if no such node exists.
				*/
				function first_child( par )
				{
					var res=par.firstChild;
					while (res) {
						if (!is_ignorable(res)) return res;
						res = res.nextSibling;
					}
					return null;
				}

				/**
				* Version of |data| that doesn't include whitespace at the beginning
				* and end and normalizes all whitespace to a single space.  (Normally
					* |data| is a property of text nodes that gives the text of the node.)
					*
					* @param txt  The text node whose data should be returned
					* @return     A string giving the contents of the text node with
					*             whitespace collapsed.
					*/
					function data_of( txt )
					{
						var data = txt.data;
						// Use ECMA-262 Edition 3 String and RegExp features
						data = data.replace(/[\t\n\r ]+/g, " ");
						if (data.charAt(0) == " ")
						data = data.substring(1, data.length);
						if (data.charAt(data.length - 1) == " ")
						data = data.substring(0, data.length - 1);
						return data;
					}

					function fakeChildren() 
					{
						if (document.getElementById('NavBar')) 
						{
							first_child($('NavBar')).id = "btn_calendar";
							last_child($('NavBar')).id = "btn_blog";
						}
					}
					if (window.attachEvent) window.attachEvent("onload", function() {sfHover("SiteNavBar")});
					if (window.attachEvent) window.attachEvent("onload", function() {sfHover("CommunityHeader")});
					if (window.attachEvent) window.attachEvent("onload", function() {sfHover("submit")});
					if (window.attachEvent) window.attachEvent("onload", function() {sfHover("SubNavBar")});

// Nested attribute method for PHONE NUMBER
function insert_fields(link, method, content) {
  var new_id = new Date().getTime();
  var regexp = new RegExp("new_" + method, "g")
  $(link).up().insert({
    after: content.replace(regexp, new_id)
  });
}

// Remove fields for PHONE NUMBER
function remove_fields(link) {
  var hidden_field = $(link).previous("input[type=hidden]");
  if (hidden_field) {
    hidden_field.value = '1';
  }
  $(link).up(".phone_number").hide();
}