// <script type="text/javascript">
<!--  to hide script contents from old browsers

/******************************************************************************
This file contains both jquery format and functions and older functions
written without javascript.
******************************************************************************/

$(document).ready(function()
{
	display_urhere_db();
	setup_tinymce();

	setup_service_areas();
	setup_categories();
	setup_word_counters();
	setup_capture_agency_click();

	// Moved to setup_tinymce
	//setup_warn_form();

	//setup_scroll_to_agency_position();
});

/*******************************************************************************
* Set up code to warn user if they navigate away from a page with a form without
* saving the data. Note that usually the .change() function will work with
* textareas, but because tinymce is being used, it no longer works. Instead,
* the values of the textareas on the page are stored initially and then compared
* to their final value.
*******************************************************************************/
function setup_warn_form()
{
	// Need this in order to get html tags
	tinyMCE.triggerSave();

	// Store initial value of textareas in global variable
	textareas_initial = new Array();
	$('textarea').each(function(index)
	{
		var id = $(this).attr('id');
		var textarea_html = $('#' + id).val();

		// Remove new lines
		textarea_html = textarea_html.replace(/\\n/gm, '')
		textarea_html = textarea_html.replace("\n", '')

		textareas_initial[index] = textarea_html;
	});

	// Set initial value to alert user to false
	setConfirmUnload(false);

	// If user changes an input value, warn them if they go to another page
	$(':input').change(function()
	{
		setConfirmUnload(true);display_communities
	});


	$('form').submit(function()
	{
		window.onbeforeunload = null;
	});


}

function setConfirmUnload(on)
{
	//window.onbeforeunload = (on) ? unloadMessage : null;
	window.onbeforeunload = (on) ? unloadMessage : check_textareas;
}

function check_textareas()
{
	// This seems necessary to get the new value of the textarea
	tinyMCE.triggerSave();

	// This is how you get the textarea info from tinymce
	//var zz = $('#languages-other-en, mceContentBody').val();

	on = false;

	// Go through each textarea and see it's changed
	$('textarea').each(function(index)
	{
		// Get ids for each textarea
		var id = $(this).attr('id');

		// Get current value of textarea from tinymce
		var new_textarea_html = $('#' + id).val();
		new_textarea_html = new_textarea_html.replace(/\\n/gm, '')
		new_textarea_html = new_textarea_html.replace("\n", '')

		var initial_text = textareas_initial[index];

		// If textarea has changed, alert user
		if (initial_text != new_textarea_html)
		{
			on = true;
		}
	});

	if (on)
		return unloadMessage();
}

function unloadMessage()
{
	// The actual returned message doesn't seem to be displayed
	return 'You have entered new data on this page. If you navigate away from this page without first saving your data, the changes will be lost.';
}

/*******************************************************************************
* Set up TinyMCE.
*******************************************************************************/
function setup_tinymce()
{
	tinyMCE.init({
		mode : "exact",
		elements : "scheduling-other-en, scheduling-other-sp, hours-other-en, hours-other-sp, languages-other-en, languages-other-sp, description-en, description-sp, extended-description-en, extended-description-sp, mission-en, mission-sp, areas-other-en, areas-other-sp, eligibility-other-en, eligibility-other-sp, payments-other-en, payments-other-sp, documents-other-en, documents-other-sp",
		theme : "advanced",
		plugins : "preview, paste",
		content_css : "/css/tinymce.css",

		/**
		element_format : "html",
		entity_encoding : "raw",

		// Setting this blank means that no entity names, e.g. &amp; for &, will be used instead of characters
		// Seems to work ok using utf8 for browser and database
		entities : "",
		**/

		//media_strict : false,
		valid_elements : "br,p",
		verify_html : false,

		extended_valid_elements : "br,p",

		// Call function to initialize warning for user if they navigate away from form without saving
		oninit : setup_warn_form,


		setup : function(ed)
		{
			// Set up default to be PasteAsPlainText
			ed.onInit.add(function(ed)
			{
				ed.pasteAsPlainText = false;
				count_and_display_textarea();
			});

			// Count words and characters
			ed.onKeyUp.add(function(ed, e)
			{
				count_and_display_textarea();
			});

		},


		/**
		 // Theme options - button# indicated the row# only
		theme_advanced_buttons1 : "newdocument,|,bold,italic,underline,|,justifyleft,justifycenter,justifyright,fontselect,fontsizeselect,formatselect",
		theme_advanced_buttons2 : "cut,copy,paste,|,bullist,numlist,|,outdent,indent,|,undo,redo,|,link,unlink,anchor,image,|,code,preview,|,forecolor,backcolor",
		theme_advanced_buttons3 : "insertdate,inserttime,|,spellchecker,advhr,,removeformat,|,sub,sup,|,charmap,emotions",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : true
		**/

		 // Theme options - button# indicated the row# only "pasteword" removed (opens new window)
		theme_advanced_buttons1 : "cut,copy,pastetext,paste,",
		theme_advanced_buttons2 : "",
		theme_advanced_buttons3 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : true
		//(n.b. no trailing comma, this will be critical as you experiment later)
	});

}

/*****************************************************************************
This function does the actual work of counting words and characters and
displaying the information.
******************************************************************************/
function count_and_display_textarea()
{
	// Get id of textarea and path_row
	var editor_id = tinymce.DOM.get(tinyMCE.activeEditor.id);
	//var path_row = tinymce.DOM.get(tinyMCE.activeEditor.id + '_path_row');
	var parent_id = tinymce.DOM.get(tinyMCE.activeEditor.id + '_parent');

	// Get declared max number of characters for textarea
	var maxlength = $(editor_id).attr('maxlength');
	maxlength = parseInt(maxlength);

	// Get the editor contents, replace all the html, trim out extra space
	var text = (tinyMCE.activeEditor.getContent()).replace(/(<([^>]+)>)/g,"").replace(/\s+/g," ");
	text = $.trim(text);
	var words = text.split(' ').length;
	var characters = text.length;
	var chars_left = maxlength - characters;

	var info = words + " Words";
	//var info = words + " Words, " +  characters + " Characters.";
	//info += ' Max characters: ' + maxlength + '. Characters left: ' + chars_left;

	// Create id based on texarea, e.g. news-text-wc-counter
	var wc_id = editor_id.name.replace('textarea#', '') + '-wc-counter';

	// Remove any old text
	$('#' + wc_id).remove();

	// Append new text
	$(parent_id).after('<div id="' + wc_id + '" class="char-word-counter">' + info + '</div>');

	/*
	if (chars_left < 0)
		alert('You have exceeded the maximum number of characters for this field.');
	*/
}

/******************************************************************************
This function
******************************************************************************/
function setup_capture_agency_click()
{
	var currentHref = document.location.href;

	// If not on main agencies listing page, return
	if (currentHref.indexOf('/admin/agencies_main.php?show=all') < 0)
		return;

	// This is the cookie name
	var COOKIE_NAME = 'scroll_position';

	// Check to see if the user already has the cookie set to scroll
	var scrollPosition = getCookie(COOKIE_NAME);

	if (scrollPosition.length > 0)
	{
		// Scroll to the position of the last link clicked
		$(window).scrollTop(scrollPosition);
	}


	// Bind click of link  with class "capture-click" to edit agency
	$('table.table-vertical td a.capture-click').live('click', function(event)
	{
		var scroll_top = $(window).scrollTop();
		setCookie(COOKIE_NAME, scroll_top, 1);
	});


	// Bind click of link  with class "capture-click", id = "agency-names", and id="work-code" to edit agency
	$('table.table-vertical th a, p#agency-names, p#work-codes').live('click', function(event)
	{
		var scroll_top = $(window).scrollTop();
		deleteCookie(COOKIE_NAME);
	});

}

/******************************************************************************
Boring cookie helper functions
******************************************************************************/
function getCookie(name)
{
	if (document.cookie.length > 0)
	{
		c_start = document.cookie.indexOf(name + "=");

		if (c_start != -1)
		{
			c_start = c_start + name.length + 1;
			c_end = document.cookie.indexOf(";", c_start);
			if (c_end ==- 1) c_end = document.cookie.length;
			return unescape(document.cookie.substring(c_start, c_end));
		}
	}
	return "";
}

function setCookie(name, value, expiredays)
{
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + expiredays);
	document.cookie = name + "=" + escape(value) +
		((expiredays==null) ? "" : ";expires=" + exdate.toGMTString());
}

function deleteCookie(name)
{
	var exdate = new Date();
	exdate.setDate(exdate.getDate() - 10);

	var werwer = exdate.toGMTString();

	var ssss = name + "=; expires=" + werwer;

	var asdf = name + "=; expires=" + exdate.toGMTString();


	document.cookie = name + "=; expires=" + exdate.toGMTString();

	var xx = 1;
}

/******************************************************************************
This function hides the subcategories for any category where no subcategories
are selected. Toggling of the subcategories is done in the function
display_text() which was set up before this function and before I was using
jquery.
******************************************************************************/
function setup_categories()
{
	if ($('.categories').length == 0)
		return;

	// Loop through each county and hide list of towns if none are selected
	$('.categories').each(function(index)
	{
		if ($(this).find('input:checked').length == 0)
			$(this).find('ul').hide();
		else
			$(this).find('ul').show();
	});
}

/******************************************************************************
This function hides the towns for any counties where no towns are selected. It
then sets up toggling of county towns when the clicks the name of a county.
******************************************************************************/
function setup_service_areas()
{
	if ($('#AdminAgencyServiceAreasForm').length > 0)
	{
		// Loop through each county and hide list of towns if none are selected
		$('#AdminAgencyServiceAreasForm table td.county-td').each(function(index)
		{
			if ($(this).find('input:checked').length == 0)
				$(this).hide();
		});


		// Bind click of county name .thumbnail-link href for current and future clicks
		$('#AdminAgencyServiceAreasForm table th a').live('click', function(event)
		{
			// Prevent following of link
			event.preventDefault();

			// Hide or show list of towns in county
			$(this).closest('th').next('td').toggle();
		});
	}

	if ($('#ClientAgencyServiceAreasForm').length > 0)
	{
		// Loop through each county and hide list of towns if none are selected
		$('#ClientAgencyServiceAreasForm table td.county-td').each(function(index)
		{
			if ($(this).find('input:checked').length == 0)
				$(this).hide();
		});


		// Bind click of county name .thumbnail-link href for current and future clicks
		$('#ClientAgencyServiceAreasForm table th a').live('click', function(event)
		{
			// Prevent following of link
			event.preventDefault();

			// Hide or show list of towns in county
			$(this).closest('th').next('td').toggle();
		});
	}

}

/******************************************************************************
This function setups up word counters for Spanish textares so translaters
know how much to charge.
******************************************************************************/
function setup_word_counters()
{
	var currentHref = document.location.href;

	// Only add word counter for admin pages
	if (currentHref.indexOf('form=AdminAgency') < 0)
		return;

	$(function () {
		$('textarea.word-count').maxlength({
			'feedback' : '.wordsLeft'
		});

		$('textarea.word-count-brief').maxlength({
			'feedback' : '.wordsLeftBrief'
		});
		$('textarea.word-count-extended').maxlength({
			'feedback' : '.wordsLeftExtended'
		});

		$('textarea.word-count-mission').maxlength({
			'feedback' : '.wordsLeftMission'
		});
	});

}

/******************************************************************************
This function alters the style of the navigation bar to indicate urhere.
I added code from the original to shorten the href string so that it does
not include any bookmarks (....#bookmark). Otherwise, the strings would not
match and the urhere formatting would not be applied.
******************************************************************************/
function display_urhere_db()
{	var list; var page; var currentHref; var href; var anchorPosition;

	if ($('#navbar-db').length == 0)
		return;

	list = document.getElementById("navbar-db");
	page = list.getElementsByTagName("a");
	currentHref = document.location.href;

	anchorPosition = currentHref.indexOf("#");
	if (anchorPosition >= 0)
		currentHref = currentHref.substring(0, anchorPosition);

	currentHref = getSimpleHref(currentHref);

	for (var i = 0; i < page.length; i++)
	{	href = getSimpleHref(page[i].href)

		//alert('href = ' + href + '   ' + 'curhref = ' + currentHref);

		if (href == currentHref)
		{
			page[i].style.backgroundColor = "#fff";
			page[i].style.color = "#000";
			break;
		}
		else if (currentHref.indexOf('agency_') >= 0 && href == 'agencies_main.php')
		{
			page[i].style.backgroundColor = "#fff";
			page[i].style.color = "#000";
		}
	}

	display_subnav_urhere();
}

/*
This function was added because Mac Safari does not include the directory structure
before the href, so there was never a match. This function strips the beginning directory structure
away and just leaves the end part--such as about_us.htm
**************************************************************************************************/
function getSimpleHref(s)
{	var length;
	var anchorPosition = 0;

	while (anchorPosition >= 0)
	{	anchorPosition = s.indexOf('/');
		length = s.length;

		if (anchorPosition >= 0)
		{	s = s.substring(anchorPosition + 1, length);
		}
	}

	return(s);
}

/*******************************************************************************
This function sets the urhere for the sub navigation menu for the portfolio pages.
If there is no sub-nav ID on the page, then the function simply returns.
*******************************************************************************/
function display_subnav_urhere()
{
	var href;

	var list = document.getElementById('admin-subnav');

	if (list == null)
	{
		return;
	}

	var page = list.getElementsByTagName("a");
	var currentHref = document.location.href;

	var anchorPosition = currentHref.indexOf("#");
	if (anchorPosition >= 0)
		currentHref = currentHref.substring(0, anchorPosition);

	currentHref = getSimpleHref(currentHref);

	for (var i = 0; i < page.length; i++)
	{
		href = getSimpleHref(page[i].href)

		if (href == currentHref)
		{
			page[i].style.color = "#f8dfb2";
			page[i].style.textDecoration = "none";
			//page[i].style.backgroundColor = "#6e3631";
			page[i].parentNode.style.background = "#6e3631";			// Parent node is <li>

			break;
		}
	}
}

/***************************************************************************************************
This function checks or unchecks all the communities within a county for the Service Areas form or
all the subcategories within a category.
***************************************************************************************************/
function select_communities(href, select)
{
	// Parent node is <p>
	var p = $(href).parent();
	var ul = $(p).next('ul');

	// Check or uncheck depending on whether user select "Select All" or "Deselect all"
	$(ul).find('input').attr('checked', select);
}

/***************************************************************************************************
This function hides or displays the service hours that the agency is open by being called when the
form is displayed.
***************************************************************************************************/
function set_hours_selected(form_id)
{
	form = document.getElementById(form_id);
	inputs = form.getElementsByTagName("input");

	// Go through each input
	for (j = 0; j < inputs.length; j++)
	{
		// Only looking for radio buttons indicating Open or Closed for a given day
		if (inputs[j].type != 'radio')
			continue;

		var li = inputs[j].parentNode;
		var ul = li.parentNode;
		var th = ul.parentNode;
		var tr = th.parentNode;

		// Get the <td> element
		td = tr.getElementsByTagName("td");

		// Get the <div> elements in the <td>
		div = td[0].getElementsByTagName("div");

		// Get the <p> elements in the <td>
		p = td[0].getElementsByTagName("p");

		// If radio button is checked, see whether 1 (Open) or 0 (Closed)
		if (inputs[j].checked == true)
		{
			if (inputs[j].value == 1)
				open = 1;
			else
				open = 0;
		}
		else
			continue;

		if (open == 1)
			var display = '';
		else
			display = 'none';

		for (i = 0; i < div.length; i++)
			div[i].style.display = display;

		for (i = 0; i < p.length; i++)
		{
			//alert(p[i].innerHTML);

			if (p[i].innerHTML == "Open From:" || p[i].innerHTML == "Open To:")
				p[i].style.display = display;
		}
	}
}

/***************************************************************************************************
This function hides or displays the service hours that the agency is open based on clicking a radio
button.
***************************************************************************************************/
function hours_selected(open, input)
{
	//alert(open + '  ' + input);

	var li = input.parentNode;
	var ul = li.parentNode;
	var th = ul.parentNode;
	var tr = th.parentNode;

	// Get the <td> element
	td = tr.getElementsByTagName("td");

	// Get the <div> elements in the <td>
	div = td[0].getElementsByTagName("div");

	// Get the <p> elements in the <td>
	p = td[0].getElementsByTagName("p");

	if (open == 1)
		var display = '';
	else
		display = 'none';

	for (i = 0; i < div.length; i++)
		div[i].style.display = display;

	for (i = 0; i < p.length; i++)
	{
		if (p[i].innerHTML == "Open From:" || p[i].innerHTML == "Open To:")
			p[i].style.display = display;
	}
}


/***************************************************************************************************
This function hides or displays <tr> rows from the Service Ares form. If a user selects that their
agency services all NM communities, then all the counties and communities are hidden. Otherwise,
the communities are displayed.
***************************************************************************************************/
function all_nm_selected(service_all_nm, form_id)
{
	form = document.getElementById(form_id);

	// Get all <input> tags
	var inputs = form.getElementsByTagName("input");

	for (i = 0; i < inputs.length; i++)
	{
		if (inputs[i].type == 'checkbox' || inputs[i].type == 'radio')
		{
			if (inputs[i].id == 'service-all-nm1' || inputs[i].id == 'service-all-nm2')
			{
				continue;
			}

			// Get <li> elements
			var li = inputs[i].parentNode;
			var ul = li.parentNode;
			var td = ul.parentNode;
			var tr = td.parentNode;

			// If service for all NM, hide community checkboxes
			if (service_all_nm == 1)
			{
				// Hide
				tr.style.display = 'none';
				//Deselect check boxes
				//inputs[i].checked = false;
			}
			// If not service for all NM, show coommunity checkboxes
			else
			{
				// Show
				tr.style.display = '';
				//Deselect check boxes
				//inputs[i].checked = false;
			}
		}
	}
}

/**************************************************************************************************
This function changes the display from "none" to "block" or "block" to "none"of the selected
section. This only includes selected tags.
**************************************************************************************************/
function display_text(link)
{
	// Get <h3>
	var h3 = link.parentNode;
	// Get <div>
	var div = h3.parentNode;
	// Get <ul>
	var ul = div.getElementsByTagName('ul');
	// Get <p> for text field "Other"
	var p = div.getElementsByTagName('p');

	//var li = ul[0].getElementsByTagName('li');

	//for (var i = 0; i < li.length; i++)
	{
		if (ul[0].style.display == "block")
		{
			ul[0].style.display = "none";
			p[0].style.display = "none";
		}
		else
		{
			ul[0].style.display = "block";
			p[0].style.display = "block";
		}
	}

	return false;
}

/**************************************************************************************************
This function changes the display to "block".
**************************************************************************************************/
function display_categories(id)
{
	var h3 = $('h3');
	var num_h3 = h3.length;

	// Get last h3
	var this_h3 = h3[num_h3 - 1];

	// Display Select All / Deslect All
	$(this_h3).next('p').show();

	// Display <ul>
	$(this_h3).siblings('ul').show();


	/**
	var h3 = document.getElementsByTagName('h3');
	var num_h3 = h3.length;

	// Get last h3
	var this_h3 = h3[num_h3 - 1];

	// Get <div>
	var div = this_h3.parentNode;

	// Get <ul>
	var ul = div.getElementsByTagName('ul');
	ul[0].style.display = "block";

	// Display Select All / Deslect All
	this_h3.nextElementSibling.style.display = "block";
	**/
}

/**************************************************************************************************
This function changes the display to "block".
**************************************************************************************************/
function display_communities(link)
{
	/**
	var h3 = $(link).closest('div');
	var ul = $(link).closest('div').find('ul');
	var p = $(link).closest('div').find('p');

	var x = 1;

	var num_h3 = h3.length;

	// Get last h3
	var this_h3 = h3[num_h3 - 1];

	// Get <div>
	var div = this_h3.parentNode;

	// Get <ul>
	var ul = div.getElementsByTagName('ul');
	ul[0].style.display = "block";

	// Display Select All / Deslect All
	this_h3.nextElementSibling.style.display = "block";
	**/


	var h3 = document.getElementsByTagName('h3');
	var num_h3 = h3.length;

	// Get last h3
	var this_h3 = h3[num_h3 - 1];

	// Get <div>
	var div = this_h3.parentNode;

	// Get <ul>
	var ul = div.getElementsByTagName('ul');
	ul[0].style.display = "block";

	// Display Select All / Deslect All
	//this_h3.nextElementSibling.style.display = "block";
	$(this_h3).next('p').show();
}

/**************************************************************************************************
This function generates an alert box to confirm that user wants to delete something.
**************************************************************************************************/
function confirm_delete($str)
{
	return confirm('Are you sure you want to delete this ' + $str + '?');
}


// end hiding contents from old browsers  -->
// </script>

