jQuery.noConflict();

jQuery(document).ready(function($)
{
	// HANDLERS
	$('.toggle_t').bind( 'click', toggleArea ); // generic toggle
	$('#ac_venue, #ac_presenter').bind( 'blur', autoSearchTrigger ); // auto-complete
	$('.num_only').bind( 'keypress', numeralsOnly );

	// HANDLER FUNCTIONS
	function toggleArea(e)
	{
		var sh_match = $(this).text().match(/^(show|hide)/i);

		if ( sh_match )
		{
			var t_label = ( $(this).text().match(/^(show)/i) )? $(this).text().replace( 'Show', 'Hide' ) : $(this).text().replace( 'Hide', 'Show' );
			$(this).text( t_label );
		}

		$(this).next('.toggle_c').toggle();

		return false;
	}

	function autoSearchTrigger(e)
	{ 
		var ac_val = $.trim( $(this).val() );
		var ac_id  = $(this).attr('id');

		if ( ac_val !== '' && ac_val.length > 1 && ac_val !== last_ac_vals[ac_id] )
		{ // only search again if input has changed
			// verifies if the entered value was an existing option after the element loses focus.
			$(this).search();
		}
	}

	// GENERAL
	function init()
	{
		$('.toggle_c.closed, .toggle_t.hidden').hide();
		setupAutoComplete();
	}

	function setupAutoComplete()
	{
		$.ajaxSetup({type: 'POST'});

		var ac_params =
		{
			cacheLength: 100,
			delay: 400,
			max: 20,
			matchContains: true,
			minChars: 2,
			scroll: true,
			scrollHeight: 300,
			selectFirst: true
		}

		last_ac_vals = {ac_venue : '', ac_presenter : ''}; // tracking defaults

		$("#ac_venue").autocomplete( webserviceURL + '/venues', ac_params );
		$("#ac_presenter").autocomplete( webserviceURL + '/presenters', ac_params );

		$("#ac_venue, #ac_presenter").result( function( event, data )
		{
			var e_id = $(this).attr( 'id' );

			last_ac_vals[e_id] = $.trim( $(this).val() ); // update tracking

			if ( data )
			{
				$( '#' + e_id + '_id' ).val( data[1] );

				if ( $( '#' + e_id + '_nft' ).text().match(/^(hide)/i) )
				{
					$( '#' + e_id + '_nft' ).click(); // toggle the fieldset
				}
			}
			else
			{
				$( '#' + e_id + '_id' ).val( '' );

				if ( $( '#' + e_id + '_nft' ).text().match(/^(show)/i) )
				{
					$( '#' + e_id + '_nft' ).click(); // toggle the fieldset
				}
			}
		});
	}

	function numeralsOnly( evt )
	{
		evt = (evt) ? evt : event;
		var charCode = (evt.charCode) ? evt.charCode : ((evt.charCode) ? evt.keyCode : ((evt.which) ? evt.which :0 ));
		var ret = true;
		
		if ( charCode > 31 && (charCode < 48 || charCode > 57) )
		{
			ret = false;
		}

		return ret;
	}

	init();
});
