// Ex Parte Meeting Request Form scripts:
document.title = 'Broadband Ex Parte Meeting Request - Broadband.gov';
// from: http://blog.bmn.name/2008/03/jquery-fadeinfadeout-ie-cleartype-glitch/
(function($) {
	$.fn.customFadeIn = function(speed, callback) {
		$(this).fadeIn(speed, function() {
			if(jQuery.browser.msie)
				$(this).get(0).style.removeAttribute('filter');
			if(callback != undefined)
				callback();
		});
	};
	$.fn.customFadeOut = function(speed, callback) {
		$(this).fadeOut(speed, function() {
			if(jQuery.browser.msie)
				$(this).get(0).style.removeAttribute('filter');
			if(callback != undefined)
				callback();
		});
	};
})(jQuery);

// Plugin to automatically resize TEXTAREA elements: http://james.padolsey.com/javascript/jquery-plugin-autoresize/
/*
 * jQuery autoResize (textarea auto-resizer)
 * @copyright James Padolsey http://james.padolsey.com
 * @version 1.04
 */
(function(a){a.fn.autoResize=function(j){var b=a.extend({onResize:function(){},animate:true,animateDuration:150,animateCallback:function(){},extraSpace:20,limit:1000},j);this.filter('textarea').each(function(){var c=a(this).css({resize:'none','overflow-y':'hidden'}),k=c.height(),f=(function(){var l=['height','width','lineHeight','textDecoration','letterSpacing'],h={};a.each(l,function(d,e){h[e]=c.css(e)});return c.clone().removeAttr('id').removeAttr('name').css({position:'absolute',top:0,left:-9999}).css(h).attr('tabIndex','-1').insertBefore(c)})(),i=null,g=function(){f.height(0).val(a(this).val()).scrollTop(10000);var d=Math.max(f.scrollTop(),k)+b.extraSpace,e=a(this).add(f);if(i===d){return}i=d;if(d>=b.limit){a(this).css('overflow-y','');return}b.onResize.call(this);b.animate&&c.css('display')==='block'?e.stop().animate({height:d},b.animateDuration,b.animateCallback):e.height(d)};c.unbind('.dynSiz').bind('keyup.dynSiz',g).bind('keydown.dynSiz',g).bind('change.dynSiz',g)});return this}})(jQuery);
	
// Plugin to provide word counter for TEXTAREA elements:
/*
* jQuery Simply Countable plugin
* Provides a character counter for any text input or textarea
* 
* @version  0.2
* @homepage http://github.com/aaronrussell/jquery-simply-countable/
* @author   Aaron Russell (http://www.aaronrussell.co.uk)
*
* Copyright (c) 2009 Aaron Russell (aaron@gc4.co.uk)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*/
(function($){$.fn.simplyCountable=function(options){options=$.extend({counter:'#counter',countType:'words',maxCount:200,countDirection:'up',safeClass:'safe',overClass:'over'},options);var countable=this;var countCheck=function(){if(options.countType==='words'){var count=options.maxCount-countable.val().split(/[\s]+/).length;if(countable.val()===''){count+=1;}}else{var count=options.maxCount-countable.val().length;}if(!$(options.counter).hasClass(options.safeClass)&&!$(options.counter).hasClass(options.overClass)){if(count<0){$(options.counter).addClass(options.overClass);}else{$(options.counter).addClass(options.safeClass);}}else if(count<0&&$(options.counter).hasClass(options.safeClass)){$(options.counter).removeClass(options.safeClass).addClass(options.overClass);}else if(count>=0&&$(options.counter).hasClass(options.overClass)){$(options.counter).removeClass(options.overClass).addClass(options.safeClass);}if(options.countDirection==='up'){count=count-(count*2)+options.maxCount;}$(options.counter).text(count);};countCheck();countable.keyup(countCheck);};})(jQuery);

/* 
	jQuery TextAreaResizer plugin (Modified for Broadband.gov: maximum value added for height of textarea)
	Created on 17th January 2008 by Ryan O'Dell 
	Version 1.0.4
	Converted from Drupal -> textarea.js
	Found source: http://plugins.jquery.com/misc/textarea.js
	$Id: textarea.js,v 1.11.2.1 2007/04/18 02:41:19 drumm Exp $
*/
(function($){var textarea,staticOffset;var iLastMousePos=0;var iMin=80;var iMax=320;var grip;$.fn.TextAreaResizer=function(){return this.each(function(){textarea=$(this).addClass('processed'),staticOffset=null;$(this).wrap('<div class="resizable-textarea"><span></span></div>').parent().append($('<div class="grippie"></div>').bind("mousedown",{el:this},startDrag));var grippie=$('div.grippie',$(this).parent())[0];grippie.style.marginRight=(grippie.offsetWidth-$(this)[0].offsetWidth)+'px'})};function startDrag(e){textarea=$(e.data.el);textarea.blur();iLastMousePos=mousePosition(e).y;staticOffset=textarea.height()-iLastMousePos;textarea.css('opacity',0.25);$(document).mousemove(performDrag).mouseup(endDrag);return false}function performDrag(e){var iThisMousePos=mousePosition(e).y;var iMousePos=staticOffset+iThisMousePos;if(iLastMousePos>=(iThisMousePos)){iMousePos-=5}iLastMousePos=iThisMousePos;iMousePos=Math.max(iMin,iMousePos);textarea.height(iMousePos+'px');if(iMousePos<iMin || iMousePos>iMax){endDrag(e)}return false}function endDrag(e){$(document).unbind('mousemove',performDrag).unbind('mouseup',endDrag);textarea.css('opacity',1);textarea.focus();textarea=null;staticOffset=null;iLastMousePos=0}function mousePosition(e){return{x:e.clientX+document.documentElement.scrollLeft,y:e.clientY+document.documentElement.scrollTop}}})(jQuery);

$(document).ready(function(){
	// DATES functionality:
	$('#available-dates').data('dVal', 'Enter date'); // store the default value
	if ( $('#available-dates p:gt(0):visible').length > 0 && $('#available-dates input:first').val() == $('#available-dates').data('dVal') ) {
		$('#available-dates input:first').val(''); 
	}
	$('#available-dates p:gt(0)').each(function(){
		var $dateInput = $(this).find('input');
		if ( $dateInput.val() == $('#available-dates').data('dVal') || $dateInput.val() == '' ) {
			$(this).customFadeOut('fast');
			$dateInput.val('');
		}
		$(this).append('<a href="#" class="date-remove remove">Remove Date</a>');
	});
	$('#available-dates').append('<a href="#" id="add-date-link">Add Additional Dates</a>');

	$('span.label').addClass('pointer').click(function(){
		$(this).parent().find('input:eq(0)').focus();
	});

	$('.date-remove').click(function(){
		$(this).parent().slideUp('fast').find('input').val('').end().find('.error').remove();
		if ( $('#available-dates p:visible').length == 5 ) {
			$('#add-date-link:hidden').customFadeIn('fast');
		}
		$('#add-date-link').focus();
		return false;
	});
	
	$('#add-date-link').click(function(){
		if ( $('#available-dates p:visible').length < 5 ) {
			$('#available-dates p:hidden:eq(0)').addClass('new').customFadeIn('fast', function(){
				$('#available-dates p.new').removeClass('new').find('input').val('').focus();
			});
			if( $('#available-dates p:visible').length == 5 ) {
				$(this).customFadeOut('fast');
			}
		}
		return false;
	});
	
	$('form.exparte').submit(function(){
		if ( $('#available-dates input:first').val() == '' ) {
			var count = 0;
			$('#available-dates p:gt(0) input').each(function(){
				if ( $(this).val() != '' && $(this).val() != $('#available-dates').data('dVal') ) {
					count++;
				}
			});
			if (count > 0) {
				$('#available-dates p:eq(0) input').val( $('#available-dates').data('dVal') );
			}
		}
		
		$('#available-dates p:gt(0) input').each(function(){
			if ( $(this).val() == '' ) $(this).val( $('#available-dates').data('dVal') ); // if empty, replace default value
		});
	});
	
	$('.datepicker').datepicker({
		beforeShowDay: $.datepicker.noWeekends,
		buttonImage: baseUrl + '/images/ico_calendar.gif',
		buttonImageOnly: false,
		buttonText: 'view calendar',
		maxDate: new Date(2011, 11, 31),
		minDate: +1,
		showOn: 'button'
	});
	
	$('.ui-datepicker-trigger').attr('title', $('.ui-datepicker-trigger img').attr('title')).find('img').css({height: '16px', width: '16px'});
	// end DATES
	
	// Toggle input field for Subject of "Other":
	if ( $('select[id$="subject-select"]').val().toLowerCase() != 'other' ) {
		$('label[id$="subject-other-label"]').customFadeOut('fast'); //.addClass('hidden');
	}
	
	$('select[id$="subject-select"]').change(function(){
		if( $(this).val().toLowerCase() == 'other' ) {
			$('label[id$="subject-other-label"]').customFadeIn('fast', function(){
				$('label[id$="subject-other-label"]').find('input').focus();
			});
		} else {
			$('label[id$="subject-other-label"]').customFadeOut('fast');
		}
	});

	// Apply the Textarea Resize and Simply Countable plugins to certain textareas:
	$('textarea:gt(0)')
		.each(function(i){
			$(this).parent().before('<p class="counter" id="counter-p' + i + '" style="display: none">You have used <strong id="counter' + i + '">0</strong> words (<em>approximate</em>)</p>');
			$(this).focus(function(){ $(this).parent().prevAll('.counter:hidden').customFadeIn('fast'); });
			$(this).simplyCountable({ counter: '#counter' + i });
		})
		.TextAreaResizer()
		.focus(function(){
			$(this).parents('.fieldset').parent().children('.counter:hidden').customFadeIn('fast'); 
		}
	);
});

//--------------------------------------------------------------------------------------
// 
// 
// 
//
//--------------------------------------------------------------------------------------
function installValueCollector(jQueryInputStr, jQueryOutputStr, delimiter, inputCount)
{
	$(document).ready(function()
	{
		concatenateValues(jQueryInputStr, jQueryOutputStr, delimiter, inputCount);
		$(jQueryInputStr).change( function()
		{
			concatenateValues(jQueryInputStr, jQueryOutputStr, delimiter, inputCount);
		});
	});
}


function concatenateValues(jQueryInputStr, jQueryOutputStr, delimiter, inputCount)
{
	var inputObjs = $(jQueryInputStr);
	var outputObj = $( $(jQueryOutputStr)[0] );

	var result = "";
	var count = 0;
	for(var i=0; i<inputCount; i++)
	{
		var inputItem = $( inputObjs[i] );
		if ( inputItem.val() == "" ) continue;
		if ( count > 0)
		{
			result += delimiter;
		}

		count ++;
		result += inputItem.val();
	}

	outputObj.val( result );
}


//
//	concatenate with specified delimiter for each input element
//
function installValueCollector2(jQueryInputStr, jQueryOutputStr, arrDelimiter, defaultValue)
{
	$(document).ready(function()
	{
		concatenateValues2(jQueryInputStr, jQueryOutputStr, arrDelimiter, defaultValue);
		$(jQueryInputStr).change( function()
		{
			concatenateValues2(jQueryInputStr, jQueryOutputStr, arrDelimiter, defaultValue);
		});
	});
}


function concatenateValues2(jQueryInputStr, jQueryOutputStr, arrDelimiter, defaultValue)
{
	var inputObjs = $(jQueryInputStr);
	var inputCount = Math.max(inputObjs.length, arrDelimiter.length);
	
	var outputObj = $( $(jQueryOutputStr)[0] );

	var result = "";

	for(var i=0; i<inputCount; i++)
	{
		var inputItem = $( inputObjs[i] );
		if ( inputItem.val() == "" ) continue;

		result += arrDelimiter[i] + inputItem.val();
	}

	outputObj.val( ( (result=="") ? defaultValue : result ) );
}


//--------------------------------------------------------------------------------------
// 
// 
//  Participant / Bureau 
//    - function prefix : pb_
// 
//
//--------------------------------------------------------------------------------------
var pb_delimiter = '; ';

function setupParticipantBureauInput(delimiter)
{
	pb_delimiter = delimiter;
	
	$(document).ready( function()
	{
		pb_setupMultiCheckboxItemField("#editParticipants", "#hideParticipants", "#selectAllParticipants", "#clearAllParticipants", 
				"#divPaticipantCheckPanel", "textarea.taSelectedParticipants", "input.chkParticipant" );
	
		pb_setupMultiCheckboxItemField("#editBureaus", "#hideBureaus", "#selectAllBureaus", "#clearAllBureaus", 
				"#divBureauCheckPanel", "textarea.taSelectedBureaus", "input.chkBureau" );
	
		$('textArea.taOtherParticipants').change( function() {
			pb_updateHiddenFinalParticipant();
		});
		
	});
}

function pb_updateHiddenFinalParticipant()
{
	var txt = $('textarea.taSelectedParticipants').val();
	txt += $('textarea.taSelectedBureaus').val();
	txt += $('textarea.taOtherParticipants').val();
	
	$("input.hdnParticipantAll").val( txt );
}


function CFieldIds(aEditId, aHideId, aSelectAllId, aClearAllId, divCheckPanelId, classTextArea, classCheckBoxes)
{
	this.aEdit = aEditId;
	this.aHide = aHideId;
	this.aSelectAll = aSelectAllId;
	this.aClearAll = aClearAllId;
	this.divCheckPanel = divCheckPanelId;
	this.classTextArea = classTextArea;
	this.classCheckBoxes = classCheckBoxes;
}



function pb_setupMultiCheckboxItemField(aEditId, aHideId, aSelectAllId, aClearAllId, divCheckPanelId, classTextAreaInput, classCheckBoxes)
{
	
	var cfId = new CFieldIds(aEditId, aHideId, aSelectAllId, aClearAllId, divCheckPanelId, classTextAreaInput, classCheckBoxes);
	
	$( cfId.aClearAll ).click( function() {
		pb_setAllCheckValue( $( cfId.classCheckBoxes ), false );
		pb_readSelectedCheckboxValues(cfId);
		return false;
	});
	
	$( classTextAreaInput ).attr('readonly', true);

	$( cfId.aSelectAll ).click( function() {
		pb_setAllCheckValue( $( cfId.classCheckBoxes ), true );
		pb_readSelectedCheckboxValues(cfId);
		return false;
	});

	$( cfId.aHide ).click( function() {
		pb_setCheckboxListVisibility( cfId, false );
		return false;
	});

	$( cfId.aEdit ).click( function() {
		pb_setCheckboxListVisibility( cfId, true );
		return false;
	});
	
	$( cfId.classCheckBoxes ).click( function() {
		pb_readSelectedCheckboxValues(cfId);
	});
	
	pb_reflectCheckboxChecked( $( cfId.classCheckBoxes ), $( cfId.classTextArea ).val() );

}



function pb_setCheckboxListVisibility(cfId, isShow)
{
	var editVisible = (isShow) ? "none" : "inline";
	var contVisible = (isShow) ? "inline" : "none";
	var listVisible = (isShow) ? "block" : "none";
	
	$( cfId.aEdit ).css("display", editVisible);
	$( cfId.aHide ).css("display", contVisible);
	$( cfId.aSelectAll  ).css("display", contVisible);
	$( cfId.aClearAll ).css("display", contVisible);
	$( cfId.divCheckPanel ).css("display", listVisible);
}


function pb_readSelectedCheckboxValues(cfId)
{
	var textArea = $( $( cfId.classTextArea )[0] );
	var selectedValues = pb_readSelectedCheckboxValues2( $( cfId.classCheckBoxes )  );
	textArea.val(selectedValues);
	pb_updateHiddenFinalParticipant();
}


function pb_readSelectedCheckboxValues2(arrCheckBoxes)
{
	var selectedValues = "";
	var count = 0;
	for(var i=0; i<arrCheckBoxes.length; i++)
	{
		var chk = arrCheckBoxes[i];
		if ( chk.checked )
		{
			if ( count++ > 0 ) selectedValues += pb_delimiter;
			selectedValues += $(chk).val();
		}
	}
	
	return selectedValues;
}

function pb_setAllCheckValue(arrChkBoxes, isChecked)
{
	for(var i=0; i<arrChkBoxes.length; i++)
	{
		arrChkBoxes[i].checked = isChecked; 
	}
}


function pb_reflectCheckboxChecked(arrCheckBoxes, selectedValues )
{
	if ( selectedValues == undefined || selectedValues == null || selectedValues == "" )
	{
		return;
	}
	var arrSelectedValues = selectedValues.split(pb_delimiter);
	pb_setAllCheckValue( arrCheckBoxes, false );
	for(var i=0; i<arrSelectedValues.length; i++)
	{
		pb_setCheckboxByValue( arrCheckBoxes, arrSelectedValues[i].trim(), true);
	}
}

function pb_setCheckboxByValue(arrCheckBoxes, value, isChecked)
{
	for(var i=0; i<arrCheckBoxes.length; i++)
	{
		var chk = $(arrCheckBoxes[i]);
		if ( chk.val() == value )
		{
			chk.attr("checked", isChecked);
		}
	}
}

