var xmlHttp = null;

var baseaddr = "http://latinlexicon.org/";
//var base_AJAX_address = "http://latinlexicon.org/ajax/";
var base_AJAX_address = "/ajax/";

// in milliseconds
var ajax_request_timeout_in_ms = 10000;
var ajax_request_timeout_timer = undefined;
var ajax_request_typing_delay_in_ms = 250;
var ajax_request_delay_timer = undefined;
var ajax_request_delay_timer_2 = undefined;
var ajax_request_previous_request = undefined;

var old_orthography_id = null;

try
{
	xmlHttp = create_cross_browser_xmlHttp_object();
}
catch( e )
{
	if(  e instanceof String )
	{
		alert( e );
	}

	alert( "Can't create xmlHttp transport object." );
}	

function ajax_request_timeout()
{
	alert( "I can't fulfill the AJAX request because it timed out. \n\n" + 
		"Wait 10 seconds and try again.");
	
	xmlHttp.abort();
}

function create_cross_browser_xmlHttp_object()
{
	var xmlHttp;
	
	try
	{
		// Firefox, Opera 8.0+, Safari
		xmlHttp = new XMLHttpRequest();
	}
	catch (e)
	{
		// Internet Explorer
		try
		{
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			try
			{
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e)
			{
				throw "Your browser does not support AJAX!" 
			}
		}
	}
	
	return xmlHttp;
}

function urlencode(str) 
{
	str = escape(str);
	str = str.replace('+', '%2B');
	str = str.replace('%20', '+');
	str = str.replace('*', '%2A');
	str = str.replace('/', '%2F');
	str = str.replace('@', '%40');
	return str;
}

function urldecode(str) 
{
	str = str.replace('+', ' ');
	str = unescape(str);
	return str;
}

/** 
	*
	*/
function CollectFormForAjax( form_id )
{
	var data = new Object();
				
	// ex: form_id = #permit_form
	// @TODO EXCLUDE RADIO ELEMENTS
	$( form_id + " input, " +
		form_id + " button, " +
		form_id + " textarea" ).each
	(
		function( index, element_dom )
		{
			// If the input is a checkbox and if it's not checked,
			// then simply ignore it
			if( element_dom.type == "checkbox" 
				&& element_dom.checked == false )
			{				
				return true;
			}

			// NOTE: There is a bug in IE 7 
			// If a button/input/etc tag does not contain a value attribute, IE 7 will set its value 
			// to the ENTIRE tag!	In that case, we know the value is completely empty
			if( element_dom.value == element_dom.innerHTML )
			{
				element_dom.value = "";				
				//return true;
			}

			if( typeof( element_dom.value ) == "undefined"
				|| element_dom.value == ""
				|| element_dom.value == null 
				|| element_dom.value == "undefined" )
			{
				element_dom.value = "";
				//return true;
			}

			if( typeof( element_dom.name ) == "undefined"
				|| element_dom.name == "" 
				|| element_dom.name == null )
			{
				return true;			
			}
						
			// If the index doesn't exist, then make it a value
			if( typeof( data[element_dom.name] ) == "undefined" )
			{
				data[element_dom.name] = element_dom.value;						
			}
			else
			{
				// if the index is already an array, then push another value onto the array
				if( data[element_dom.name] instanceof Array )
				{
					tmparr.push( data[element_dom.value] );
				}
				
				// otherwise create a new array and push the value onto the array
				else
				{
					var tmparr = new Array();
					tmparr.push( tmparr );
					tmparr.push( data[element_dom.value] );
				}											
			}					
		}
	);

	/*
	var keys = new Array();
	var newdata = new Array();
	for( k in data )
	{
		keys.push(k);
	}
	
	keys.sort
	( 
		function(x, y)
		{
			var a = String(x).toUpperCase(); 
      var b = String(y).toUpperCase(); 
						
			val1 = a > b;
			val2 = a < b;
			return val1 - val2;
		} 
	);
	
	debugger;

	for( var i = 0; i < keys.length; i++ )
	{
		newdata[keys[i]] = data[keys[i]];
	}	
	
	data = newdata;
	*/
	

	// ex: form_id = #permit_form
	$( form_id + " select" ).each
	(
		function( index, element )
		{
			$( element ).find( "option:selected" ).each
			(
				function( subindex, subelement )
				{

					if( typeof( data[element.name] ) == "undefined" )
					{
						data[element.name] = subelement.value;						
					}
					else
					{
						if( data[element.name] instanceof Array )
						{
							tmparr.push( data[subelement.value] );
						}
						else
						{
							var tmparr = new Array();
							tmparr.push( tmparr );
							tmparr.push( data[subelement.value] );
						}											
					}		
					
				}
			);
			
						
		}
	);

	
	return data; 
}


//var baseaddr = ".";

/*
if(  document.getElementsByTagName ) 
{
	var elems = document.getElementsByTagName( 'base' );

	if(  elems.length ) 
	{
		baseaddr = elems[ 0 ].href;
	}
}
*/

function entry_feedback( p1, p2, p3, p4 )
{
	if(  p1 == 4 || p1 == 5 )
	{
		// the user pressed cancel
		if(  p3 == null )
		{
			return;
		}
		
		p3 = p3.replace( /^\s+|\s+$/ig, "" );
		
		if(  p3 == "null" || p3 == "undefined" || p3 == "''" || p3 == "" )
		{
			alert( "Sorry, I can't submit a blank answer!" );
			return;
		}
	}

	p1 = urlencode( p1 );
	p2 = urlencode( p2 );
	p3 = urlencode( p3 );
	p4 = urlencode( p4 );

	//var gateway = baseaddr + "/ajax/entry_feedback.php?p1=" 
	//	+ p1 + "&p2=" + p2 + "&p3=" + p3 + "&p4=" + p4;

	var gateway = "/ajax/entry_feedback.php?p1=" 
		+ p1 + "&p2=" + p2 + "&p3=" + p3 + "&p4=" + p4;

	try
	{
		debugger;
		oldAjaxImage = document.getElementById( ajaxImage ).src;
				
		document.getElementById( ajaxImage ).src = imgRefresh;

		xmlHttp.open( "GET", gateway, true );
		
		// This is for Google Analytics
		var short_gateway_arr = gateway.split( baseaddr );
		var short_gateway = short_gateway_arr[short_gateway_arr.length - 1];
		_gaq.push( [ '_trackPageview', short_gateway ] );
		
		xmlHttp.onreadystatechange = function()
		{
			if(  xmlHttp.readyState == 4 )
			{
				//document.myForm.time.value = xmlHttp.responseText;
		
				if(  xmlHttp.status == 200 || xmlHttp.status == 302 )
				{
					var tmp_str = xmlHttp.responseText.replace( /^\s+|\s+$/g, '' ); 

					if(  tmp_str.length > 0 )
					{
						alert( tmp_str );
					}
				}
				else
				{
					if(  xmlHttp.status == 0 ) 
					{
						// This just means we aborted the connection
					}
					else
					{
						alert( "I encountered error " + 
							xmlHttp.status + " (" + xmlHttp.statusText + ") " + 
							"while trying to communicate with the AJAX gateway." );							
					}
				}
		
				document.getElementById( ajaxImage ).src = oldAjaxImage;
			}			
		}
		xmlHttp.send( null );	
		//alert( ajaxImage );

	}
	catch( e )
	{
		alert( "I could not open the AJAX gateway.\n\n" + gateway );
		document.getElementById( ajaxImage ).src = oldAjaxImage;
	}

}

/**
	*
	*
	*/
function ajax_latin_and_english_lexicon_lookup_event( evt, language )
{
	var lookup_input_element_id = "lookup_input_element";
	var lookup_select_element_id = "lookup_select_element";

	// for Internet Explorer compatibility
	if(  !evt )
	{
		evt = window.event;
	}

	var input_element = document.getElementById( lookup_input_element_id )

	if(  input_element == null )
	{
			alert( "input element not found" );
			return false;
	}		

	var select_element = document.getElementById( lookup_select_element_id )

	if(  select_element == null )
	{
			alert( "select element not found" );
			return false;
	}		

	switch( evt.type )
	{
			case "keydown":
			
				if(  evt.keyCode == "38" ) // up arrow
				{
					if(  select_element.options.selectedIndex >= 0
							&& select_element.selectedIndex > 0 )
					{
						select_element.selectedIndex--;						
						lookup_entry( select_element.options[select_element.options.selectedIndex].value );						
					}
				}
			
				else if(  evt.keyCode == "40" ) // down arrow
				{
					if(  select_element.options.selectedIndex >= 0
							&& select_element.selectedIndex < ( select_element.options.length - 1 ) )
					{
						select_element.selectedIndex++;
						lookup_entry( select_element.options[select_element.options.selectedIndex].value );
					}
					
				}
			
				break;
				
			case "keyup":			
			
				keychar = String.fromCharCode( evt.keyCode );
				
				if(  ( keychar >= 'A' && keychar <= 'Z' )				// A-Z
					|| ( keychar >= 'a' && keychar <= 'z' ) 			// a-z (probably unnecessary but just in case)
					|| ( evt.keyCode == 8 )  											// backspace
					|| ( evt.keyCode == 46 ) )										// delete
				{
					if(  language == 'english' )
					{
						ajax_english_lexicon_lookup( input_element.value );
					}
					else
					{
						ajax_latin_lexicon_lookup( input_element.value );
					}
				}
				
				else if(  evt.keyCode == "13" ) // enter key
				{
					if(  select_element.options.selectedIndex >= 0 )
					{					
						lookup_entry( select_element.options[select_element.options.selectedIndex].value );
					}
				}

				else if(  evt.keyCode == "27" ) // escape key
				{
					input_element.focus();
					input_element.value = '';
				}
				
				break;

			case "keypress":							
				break;
			
			case "mousedown":
				break;
				
			case "mouseup":
				break;
				
			default:
				alert( evt.type );
	}
}

/**
	*
	*
	*/
function ajax_latin_lexicon_lookup( word )
{
	if(  ajax_request_delay_timer != undefined )
	{
		clearTimeout( ajax_request_delay_timer );		
	}

	word = word.replace( /^\s+|\s+$/g, '' ); 
	word = word.replace( /'/g, '' );

	ajax_request_delay_timer = setTimeout( "ajax_latin_lexicon_lookup_keyboard_delay( '" + word + "' )", 
		ajax_request_typing_delay_in_ms );
}

/**
	*
	*
	*/
function ajax_latin_lexicon_lookup_keyboard_delay( word )
{
	var lookup_select_element_id = "lookup_select_element";

	p1 = urlencode( word );

	p1 = p1.replace( /^\s+|\s+$/g, '' ); 

	var el = document.getElementById( lookup_select_element_id )

	if(  el == null )
	{
			alert( "select element not found" );
			return false;
	}		

	if(  p1.length == 0 )
	{		
		el.options.length = 0;
		return;
	}

	//var gateway = baseaddr + "/ajax/lookup.php?p1=" + p1;
	var gateway = "/ajax/lookup.php?p1=" + p1;
	
	try
	{		
		el.disabled = true;
		
		xmlHttp.open( "GET", gateway, true );

		// This is for Google Analytics
		var short_gateway_arr = gateway.split( baseaddr );
		var short_gateway = short_gateway_arr[short_gateway_arr.length - 1];
		_gaq.push( [ '_trackPageview', short_gateway ] );

		xmlHttp.onreadystatechange = 	xmlHttp.onreadystatechange = function()
		{
			switch( xmlHttp.readyState )
			{
				/*
				
				0 = open has not yet been called
				1 = send has not yet been called but open has been called
				2 = send has been called but no response from server
				3 = data is in the process of being received from the server
				4 = response from server has arrived				
				
				*/
			
				case 4:
	
					var el = document.getElementById( lookup_select_element_id )

					if(  el == null )
					{
							alert( "select element not found" );
							return false;
					}

					el.disabled = false;
	
					if(  xmlHttp.status == 200 || xmlHttp.status == 302 )
					{
						var split_res = xmlHttp.responseText.split( "|" );
											
						el.options.length = 0;
						
						for ( si = 0; si < split_res.length - 2; si++ )
						{
							var pair = split_res[si+1].split( "=" );
							
							key = pair[1];
							value = pair[0];
							
							// Select the first word in the list automatically
							if(  si == 0 )
							{
								el.options[si] = new Option( value, key, true, true );
							}
							else
							{
								el.options[si] = new Option( value, key );
							}								

							el.options[si].setAttribute( "title", value );								
													
						}													
					}
					else
					{
						if(  xmlHttp.status == 0 ) 
						{
							// This just means we aborted the connection
						}
						else
						{
							alert( "I encountered error " + 
								xmlHttp.status + " (" + xmlHttp.statusText + ") " + 
								"while trying to communicate with the AJAX gateway." );							
						}
					}
				
					break;
					
				default:
					// ignore everything else 
			}
			
		}
		xmlHttp.send( null );	
	}
	catch( e )
	{
		alert( e );
		
		alert( "I could not open the AJAX gateway.\n\n" + gateway );
		
		return false;
	}
	
	return true;
}

/**
	*
	*
	*/
function ajax_english_lexicon_lookup( word )
{
	if(  ajax_request_delay_timer != undefined )
	{
		clearTimeout( ajax_request_delay_timer );		
	}

	word = word.replace( /^\s+|\s+$/g, '' ); 
	word = word.replace( /'/g, '' );

	ajax_request_delay_timer = setTimeout( "ajax_english_lexicon_lookup_keyboard_delay( '" + word + "' )", 
		ajax_request_typing_delay_in_ms );
}

function ajax_english_lexicon_lookup_keyboard_delay( word )
{
	var lookup_select_element_id = "lookup_select_element";

	p1 = urlencode( word );

	p1 = p1.replace(/^\s+|\s+$/g, ''); 

	var el = document.getElementById( lookup_select_element_id )

	if(  el == null )
	{
			alert( "select element not found" );
			return false;
	}		

	if(  p1.length == 0 )
	{
		var el = document.getElementById( lookup_select_element_id )
		el.options.length = 0;
		return;
	}

	//var gateway = baseaddr + "/ajax/lookup_english.php?p1=" + p1;
	var gateway = "/ajax/lookup_english.php?p1=" + p1;

	try
	{
		el.disabled = true;

		xmlHttp.open( "GET", gateway, true );

		// This is for Google Analytics		
		var short_gateway_arr = gateway.split( baseaddr );
		var short_gateway = short_gateway_arr[short_gateway_arr.length - 1];
		_gaq.push( [ '_trackPageview', short_gateway ] );


		xmlHttp.onreadystatechange = function()
		{
			switch( xmlHttp.readyState )
			{
				/*
				
				0 = open has not yet been called
				1 = send has not yet been called but open has been called
				2 = send has been called but no response from server
				3 = data is in the process of being received from the server
				4 = response from server has arrived				
				
				*/
			
				case 4:
		
					if(  xmlHttp.status == 200 || xmlHttp.status == 302 )
					{
						var split_res = xmlHttp.responseText.split( "|" );
						
						var el = document.getElementById( lookup_select_element_id )
		
						if(  el == null )
						{
								alert( "select element not found" );
								return false;
						}

						el.disabled = false;

						el.options.length = 0;
						
						for ( si = 0; si < split_res.length - 2; si++ )
						{
							var pair = split_res[si+1].split( "=" );
							
							key = pair[1];
							value = pair[0];
							
							if(  si == 0 )
							{
								el.options[si] = new Option( value, key, true, true );
							}
							else
							{
								el.options[si] = new Option( value, key );
							}
							
							el.options[si].setAttribute( "title", value );								
							
						}				
					}
					else
					{
						if(  xmlHttp.status == 0 ) 
						{
							// This just means we aborted the connection
						}
						else
						{
							alert( "I encountered error " + 
								xmlHttp.status + " (" + xmlHttp.statusText + ") " + 
								"while trying to communicate with the AJAX gateway." );							
						}
					}
				
					break;
					
				default:
					// not used
			}
		}
		xmlHttp.send( null );	
	}
	catch( e )
	{
		alert( e );
		
		alert( "I could not open the AJAX gateway.\n\n" + gateway );
		
		return false;
	}
	
	return true;
}

function lookup_input_focus() 
{
	var temp_function = function() 
	{
		var lookup_input_element_id = "lookup_input_element";
	
		var input_element = document.getElementById( lookup_input_element_id )
	
		if(  input_element == null )
		{
				alert( "input element not found" );
				return false;
		}		
		
		input_element.focus();
	} 
	
	var generic_timer = setTimeout(	temp_function, ajax_request_typing_delay_in_ms );
}

function lookup_entry( orthography_id )
{	
	if(  ajax_request_delay_timer_2 != undefined )
	{
		clearTimeout( ajax_request_delay_timer_2 );		
	}
							
	orthography_id = orthography_id.replace( /^\s+|\s+$/g, '' ); 
	orthography_id = orthography_id.replace( /'/g, '' );

	if(  orthography_id != old_orthography_id )
	{
		ajax_request_delay_timer_2 = setTimeout( "lookup_entry_keyboard_delay( '" + orthography_id + "' )", 
			ajax_request_typing_delay_in_ms );

		old_orthography_id = orthography_id;
	}

	$("#error_history_dialog").dialog( "close" );
	
	lookup_input_focus();
}

function lookup_entry_keyboard_delay( orthography_id )
{	
	var lookup_div_element_id = "lookup_div_element";

	p1 = urlencode( orthography_id );

	p1 = p1.replace(/^\s+|\s+$/g, ''); 

	if(  p1.length == 0 )
	{
		return;
	}

	//var gateway = baseaddr + "/ajax/lookup_entry.php?p1=" + p1.toString();
	var gateway = "/ajax/lookup_entry.php?p1=" + p1.toString();

	try
	{
		xmlHttp.open( "GET", gateway, true );

		// This is for Google Analytics		
		var short_gateway_arr = gateway.split( baseaddr );
		var short_gateway = short_gateway_arr[short_gateway_arr.length - 1];
		_gaq.push( [ '_trackPageview', short_gateway ] );


		xmlHttp.onreadystatechange = function()
		{
			switch( xmlHttp.readyState )
			{
				/*
					
					0 = open has not yet been called
					1 = send has not yet been called but open has been called
					2 = send has been called but no response from server
					3 = data is in the process of being received from the server
					4 = response from server has arrived				
					
					*/
				
					case 4:
				
						if(  xmlHttp.status == 200 || xmlHttp.status == 302 )
						{
							//alert( xmlHttp.responseText );
							//alert( xmlHttp.responseXML );
	
							var txt = xmlHttp.responseText;
							//alert( split_res[1] );
							
							var el = document.getElementById( lookup_div_element_id )
				
							if(  el == null )
							{
									alert( "div element not found" );
									return false;
							}
																									
							el.innerHTML = txt;
							
							// check for scripts
							$( el ).find( "script" ).each
							(
								function( index, element )
								{
									//alert( element.text );
									try
									{
										eval( element.text );
									}
									catch( e )
									{
										alert( element.text );
									}
								}
							);
							
							initChecks();
							initialize_orthography_editor();
							initialize_short_definitions_editor();
				
						}
						else
						{
							if(  xmlHttp.status == 0 ) 
							{
								// This just means we aborted the connection
							}
							else
							{
								alert( "I encountered error " + 
									xmlHttp.status + " (" + xmlHttp.statusText + ") " + 
									"while trying to communicate with the AJAX gateway." );							
							}
						}

						error_history_dialog();
					
						break;
						
					default:
						// Not used
			}		
		}		
		xmlHttp.send( null );	
	}
	catch( e )
	{
		alert( e );
		
		alert( "I could not open the AJAX gateway.\n\n" + gateway );
		
		return false;
	}
	
	return true;
}

var saved_tags = new Array();
var saved_section_tags = new Array();

function clear_text( id )
{
	var element = document.getElementById( id );
	
	if(  element == null )
	{
		alert( "input element not found" );
		return false;
	}
	
	element.value = "";
	element.focus();
}

function clear_select( id )
{
	var element = document.getElementById( id );
	
	if(  element == null )
	{
		alert( "select element not found" );
		return false;
	}
	
	element.options.length = 0;
}

function clear_search( id )
{
	var element = document.getElementById( id );
	
	if(  element == null )
	{
		alert( "text element not found" );
		return false;
	}
	
	link_search( element );
}

function link_search( text_box )
{
	// only fill out the saved_tags once
	if(  saved_tags.length == 0 )
	{
		// get all the div tags in the document
		var div_tags = document.getElementsByTagName( "div" );
		
		// iterate the div tags
		for ( si = 0; si < div_tags.length; si++ )
		{
			var tag = div_tags[si];
	
			// find the div tags named "link_container"
			if(  tag.className == "link_container" )
			{
				// grab all the "a" tags
				var sub_tags = tag.getElementsByTagName( "a" );

				// get the link description
				var keyword_string = sub_tags[0].innerHTML;
	
				// grab all the "div" tags
				var sub_tags = tag.getElementsByTagName( "div" );
				
				// get the full description, convert to lower case
				keyword_string += " " + sub_tags[0].innerHTML;
				keyword_string = keyword_string.toLowerCase();
	
				// set a variable inside the "div" tag
				tag.keyword_string = keyword_string;
	
				// save the "div" tag (as a pointer!)
				saved_tags[saved_tags.length] = tag;
			}

			// find the div tags named "link_section_container"
			if(  tag.className == "link_section_container" )
			{
				// save the "div" tag (as a pointer!)
				saved_section_tags[saved_section_tags.length] = tag;
			}

		}
	}

	// grab the value of the text box ("what the user typed")
	var search_string = text_box.value;
	search_string = search_string.toLowerCase();
	
	// split it up into an array
	var search_array = search_string.split( " " );
	
	// make a list of tags to show (these are all pointers!)
	var show_list = new Array();
	
	// iterate through the list of saved tags to determine
	// if this link matches or not
	for ( si = 0; si < saved_tags.length; si++ )
	{
		var tag_item = saved_tags[si];
		
		show_list[si] = 0; 
		
		for ( ssi = 0; ssi < search_array.length; ssi++ )
		{
			var search_item = search_array[ssi];

			if(  tag_item.keyword_string.indexOf( search_item ) != -1 )
			{
				show_list[si]++;
			}
		}
		
		if(  show_list[si] == search_array.length )
		{
			tag_item.style.display = "block";
		}
		else
		{
			tag_item.style.display = "none";			
		}
		
	}
	
	/* ONLY SHOW LINK SECTIONS WHICH HAVE MORE THAN ONE VISIBLE LINK_CONTAINER */
		
	// iterate the section tags
	for ( si = 0; si < saved_section_tags.length; si++ )
	{
		var tag = saved_section_tags[si];

		// grab all the "div" tags
		var sub_tags = tag.getElementsByTagName( "div" );
	
		var show_section = 0;
		
		for ( ti = 0; ti < sub_tags.length; ti++ )
		{
			if(  sub_tags[ti].style.display == "block" )
			{
				show_section++;
			}
		}
		
		if(  show_section > 0 )
		{
			tag.style.display = "block";
		}
		else
		{
			tag.style.display = "none";
		}
		
	}


}

/**
	*
	*/
function error_history_dialog()
{	
	$("#error_history_dialog").dialog
	( 
		{ 
			minWidth: 720,  
			autoOpen: false
		} 
	);

	$("#app_status_dialog").dialog
	( 
		{ 
			minWidth: 512,  
			autoOpen: false,
			buttons: 
			[
				{
					text: "Clear",
					click: app_status_dialog_close
				}
			]
		} 
	);

	$("#app_status").button
		(
			{
				icons: 
				{
					primary: "ui-icon-alert",
				},
				text: false
			}
		).click
		( 
			app_status_dialog_open
		);
		
	$(".error_history_button").button
		(
			{
				icons: 
				{
					primary: "ui-icon-alert"
				}								
			}
		).click
		( 
			error_history_dialog_open
		);
}

/**
	*
	*/
function error_history_dialog_open()
{	
	//var orthography_id = $("#orthography_id").val();
	var orthography_id = $(this).attr( "orthography_id" );

	$("#error_history_dialog").data( "orthography_id", orthography_id );
	
	$("#error_history_dialog").html( "" );

	$("#error_history_dialog").dialog( "open" );

	var gateway = analytics_gateway( 'form.php' );
	
	$.ajax
	(
		{
			data: 
			{
				fn: "error_history",	// form name							
				c: 1, // command
				o: orthography_id, // orthography_id							
			},
			dataType: "json",
			type: "POST",
			success: error_history_dialog_initialize,
			error: error_procedure,
			url: gateway
		}
	)
		
} // _error_history_dialog_open

/** error_history_dialog_initialize()
	*
	*/
function error_history_dialog_initialize( data, textStatus, XMLHttpRequest ) 
{ 
	$("#error_history_dialog").html( data.form ); 

	$("#error_history_dialog .delete_changes").button
	(
		{
			icons: 
			{
				primary: "ui-icon-cancel"
			}
		}
	).click
	(
		error_history_dialog_delete					
	);
								
	$("#error_history_dialog .save_changes").button
	(
		{
			icons: 
			{
				primary: "ui-icon-disk"
			}
		}
	).click
	(
		error_history_dialog_save
	);

	$("#error_table textarea").click
	(
		function()
		{
			$(this).parents("tr").find(".save_changes").show();
		}
	);
	
}	// error_history_dialog_initialize

/**
	*
	*/
function error_history_dialog_delete()
{
	var result = confirm( "Deleting is permanent. Are you sure?" );
	
	if( result == false )
	{
		return;
	}

	//var orthography_id = $("#orthography_id").val();
	var orthography_id = $("#error_history_dialog").data( "orthography_id" );

	var gateway = analytics_gateway( 'form.php' );

	$.ajax
	(
		{
			data: 
			{
				fn: "error_history",				// form name							
				c: 3,										// command = delete
				o: orthography_id, // orthography_id																
				oe: $(this).attr( "orthography_error_id" ), 	// orthography_error_id					
			},
			dataType: "json",
			type: "POST",
			success: function( data, textStatus, XMLHttpRequest ) 
			{ 
				if( data.errorNumber != 0 )
				{
					error_procedure( XMLHttpRequest, data.errorText, data.errorNumber );
				}
				else
				{
					error_history_dialog_initialize( data );									
				}
			
				//error_history_dialog_open();																	
			},
			error: error_procedure,
			url: gateway
		}
	);
	
} // error_history_dialog_delete

/**
	*
	*/
function error_history_dialog_save()
{
	$(this).hide();

	//var orthography_id = $("#orthography_id").val();
	var orthography_id = $("#error_history_dialog").data( "orthography_id" );

	var gateway = analytics_gateway( 'form.php' );
	
	$.ajax
	(
		{
			data: 
			{
				fn: "error_history",				// form name							
				c: 2,										// command = save
				o: orthography_id, // orthography_id							
				oe: $(this).attr( "orthography_error_id" ), 	// orthography_error_id							
				fixed_note: $(this).parents("tr").find(".fixed_note").val()
			},
			dataType: "json",
			type: "POST",
			success: function( data, textStatus, XMLHttpRequest ) 
			{ 
				if(  data.errorNumber != 0 )
				{
					error_procedure( XMLHttpRequest, data.errorText, data.errorNumber );
				}
				else
				{
					error_history_dialog_initialize( data );									
				}
			
			},
			error: error_procedure,
			url: gateway
		}
	);
	
} // error_history_dialog_save

/**
	*
	*/
function app_status_dialog_open()
{	
	$("#app_status_dialog").dialog( "open" );
}

/**
	*
	*/
function app_status_dialog_close()
{ 
	$(this).dialog("close").html(""); 
	$("#app_status").removeData( "error_list" ).hide();
}

/** wait_procedure()
	*
	*/
function wait_procedure( str )
{
	// TODO: fill this in
}

/** error_procedure()
	*
	*/
function error_procedure( XMLHttpRequest, textStatus, errorThrown )
{
	$(".dialog_box").dialog( "close" );

	$("#app_status").show();

	var error_list = $("#app_status").data( "error_list" );

	if(  error_list == undefined )
	{		
		var error_list = Array();
	}

	error_list.push( textStatus + " (" + errorThrown + ")" );

	$("#app_status").data( "error_list", error_list );
	
	var inner = "";
	for( var si = 0; si < error_list.length; si++ )
	{
		if(  error_list[si] )
		{
			inner += "<tr><td>" + ( si + 1 ) + "</td><td>" + error_list[si] + "</td></tr>";
		}
	}

	$("#app_status_dialog").html( "<table cellpadding=\"5\" cellspacing=\"0\" border=\"1\" width=\"\100%\">" + inner + "</table>" );
			
} // error_procedure()

/** analytics_gateway()
	*
	*/
function analytics_gateway( filename )
{
	// This is for Google Analytics
	var gateway = base_AJAX_address + filename;
	var short_gateway_arr = gateway.split( baseaddr );
	var short_gateway = short_gateway_arr[short_gateway_arr.length - 1];
	_gaq.push( [ '_trackPageview', short_gateway ] );

	return gateway;	
	
} // analytics_gateway()

/**
	*
	*/
function latin_and_english_search( language )
{
	$( "#lookup_input_element" ).keydown
	(	
		function( evt )
		{
			var select_element = $( "#lookup_select_element" )[0];			
		
			if( evt.keyCode == "38" ) // up arrow
			{
				if( select_element.options.selectedIndex >= 0
						&& select_element.selectedIndex > 0 )
				{
					select_element.selectedIndex--;
					lookup_entry( select_element.options[select_element.options.selectedIndex].value );						
				}
				
				return false;
			}
		
			else if( evt.keyCode == "40" ) // down arrow
			{
				if( select_element.options.selectedIndex >= 0
						&& select_element.selectedIndex < ( select_element.options.length - 1 ) )
				{
					select_element.selectedIndex++;
					lookup_entry( select_element.options[select_element.options.selectedIndex].value );
				}
				
				return false;
			}
			
		}
	);
	
	$( "#lookup_input_element" ).keyup
	(
		function( evt )
		{			
			var select_element = $( "#lookup_select_element" );												
		
			var keychar = String.fromCharCode( evt.keyCode );
			
			if( ( keychar >= 'A' && keychar <= 'Z' )				// A-Z
				|| ( keychar >= 'a' && keychar <= 'z' ) 			// a-z (probably unnecessary but just in case)
				|| ( evt.keyCode == 8 )  											// backspace
				|| ( evt.keyCode == 46 ) )										// delete
			{
				if( language == 'english' )
				{
					//ajax_english_lexicon_lookup( $( "#lookup_input_element" ).val() );
					var gateway = "lookup_english_json.php";
				}
				else
				{			
					var gateway = "lookup_json.php";
				}
					//select_element.attr( "disabled", "disabled" );
					//select_element.disable();

					if( ajax_request_delay_timer != undefined )
					{
						clearTimeout( ajax_request_delay_timer );
					}
						
					var latin_and_english_search_keyboard_delay = function() 
					{

						if( ajax_request_previous_request != undefined
							&& ajax_request_previous_request.readyState != 4 )
						{
							ajax_request_previous_request.abort();
						}
						
						ajax_request_previous_request = $.ajax
						(
							{
								url: base_AJAX_address + gateway, 
								dataType: "json",
								data: { "p1" : $( "#lookup_input_element" ).val() },
								type: "POST",
								success: function( data, message, XHR )
								{
									var select_element = $( "#lookup_select_element" );			
									var first = true;										
									
									select_element.disable();
									select_element.empty();
									
									//error_procedure( null, data.optgroup.length, null );
										
									$(data.optgroup).each
									(						
										function( index, element )
										{
											var optgroup = document.createElement( "optgroup" );
											
											if( 'label' in element )
											{
												optgroup.label = element.label;
											}
											else
											{
												optgroup.label = "undefined";
											}
											
											$(element.options).each
											(
												function( subindex, subelement )
												{
													if( first )
													{
														var option = document.createElement( "option" );
														option.value = subelement.id;
														option.appendChild( document.createTextNode( subelement.form ) ); 
														option.selected = true; 
														first = false;
													}
													else
													{
														var option = document.createElement( "option" );
														option.value = subelement.id;
														option.appendChild( document.createTextNode( subelement.form ) ); 
														first = false;
													}
													
													optgroup.appendChild( option );										
												}									
											)
											
											select_element.append( optgroup );
											select_element.scrollTop( 0 );											
											select_element.enable();					
										}
									)
									
									var gateway = analytics_gateway( 'lookup_json.php?p1=' + $( "#lookup_input_element" ).val() );

								}
							}
						);			
					}
					
					ajax_request_delay_timer = setTimeout
					( 
						latin_and_english_search_keyboard_delay,
						ajax_request_typing_delay_in_ms 
					);
						
					//select_element.removeAttr( "disabled" );					
				//}
			}
			
			else if( evt.keyCode == "13" ) // enter key
			{
				if( select_element[0].options.selectedIndex >= 0 )
				{					
					lookup_entry( select_element[0].options[select_element[0].options.selectedIndex].value );
				}
			}

			else if( evt.keyCode == "27" ) // escape key
			{
				$( "#lookup_input_element" ).focus().val( '' );
			}			

		}
	);
}

function display_by_id( id ) 
{
	var e = document.getElementById( id ); 
	
	if ( e )
	{
		e.style.display = "block"
	}
	else
	{
		error_procedure( null, id + " does not exist.", null );
	}
}

function suppress_display_by_id( id ) 
{
	var e = document.getElementById( id ); 
	
	if ( e )
	{
		e.style.display = "none"
	}
	else
	{
		error_procedure( null, id + " does not exist.", null );
	}
}

function toggle_containers_by_part_of_speech( dialog )
{
	var part_of_speech_id = dialog.find( "#part_of_speech_id" ).val();
	
	display_by_id( "orthography_container" );

	suppress_display_by_id( "nominative_container" );
	suppress_display_by_id( "genitive_container" );
	suppress_display_by_id( "gender_container" );
	suppress_display_by_id( "mostly_plural_noun_container" );
	
	suppress_display_by_id( "present_container" );
	suppress_display_by_id( "infinitive_container" );
	suppress_display_by_id( "perfect_container" );
	suppress_display_by_id( "p3_container" );
	suppress_display_by_id( "fap_container" );
	suppress_display_by_id( "pap_container" );
	
	suppress_display_by_id( "deponent_verb_container" );
	suppress_display_by_id( "impersonal_verb_container" );
	suppress_display_by_id( "defective_verb_container" );
	
	suppress_display_by_id( "adjective_class_container" );
	suppress_display_by_id( "preposition_class_container" );
	suppress_display_by_id( "pronoun_class_container" );
	suppress_display_by_id( "noun_class_container" );
	suppress_display_by_id( "verb_class_container" );
	
	switch( Number( part_of_speech_id ) )
	{
		case 2: // "adjective"

			display_by_id( "nominative_container" );
			display_by_id( "genitive_container" );		
			display_by_id( "adjective_class_container" );
					
			break;

		case 3: // "adverb"
		case 8: // "conjunction"
		case 12: // "cross-reference"
		case 5: // "interjection"
		case 11: // "participle"

			// nothing to display
		
			break;

		case 1: // "noun"
		
			display_by_id( "nominative_container" );
			display_by_id( "genitive_container" );
			display_by_id( "gender_container" );
			display_by_id( "mostly_plural_noun_container" );
			display_by_id( "noun_class_container" );

			break;
						
		case 7: // "preposition"
		
			display_by_id( "preposition_class_container" );

			break;			

		case 6: // "pronoun"
		
			display_by_id( "nominative_container" );
			display_by_id( "genitive_container" );		
			display_by_id( "pronoun_class_container" );

			break;			

		case 4: // "verb"

			display_by_id( "present_container" );
			display_by_id( "infinitive_container" );
			display_by_id( "perfect_container" );
			display_by_id( "p3_container" );
			display_by_id( "fap_container" );
			display_by_id( "pap_container" );
			
			display_by_id( "deponent_verb_container" );
			display_by_id( "impersonal_verb_container" );
			display_by_id( "defective_verb_container" );

			display_by_id( "verb_class_container" );

			break;
			
		default: // "unknown"
		
			alert( "Unknown part of speech." );
			
	}
}

/**
	*
	*
	*/
function initialize_orthography_editor()
{
	// Grab the English definition elements (which are ordered lists)
	$( ".flash_card_front" ).each
	(
		function( index, element )
		{
			var orthography_id = $(this).attr( "data-orthography-id" );
			
			if( typeof( orthography_id ) == "undefined" )
			{
				return;
			}
			
			//error_procedure( null, orthography_id, null );

			var edit_button = $( '<button">Edit Orthography</button>' ).button
			(
				{
					icons: 
					{
						primary: 'ui-icon-pencil'
					},
					text: false
				}
			).click
			(
				function( event, ui )
				{
					var button = $(this);
					
					var dialog = $( '<div>' ).dialog
					(
						{
							width: 720,
							height: 480,
							modal: true,
							title: 'Edit Orthography ID #' + orthography_id,
							buttons: 
							{
								'Save': function() 
								{
									var form = $(this).find( "form" )[0];
									
									if( typeof( form ) == "undefined" )
									{
										dialog.dialog( 'destroy' );
										dialog.remove();
										return false;
									}
									
									var id = "#" + form.id;
																		
									var post_data = CollectFormForAjax( id );		

									post_data.fn = "orthography";  				// form name
									post_data.c = 2;											// command = SAVE
									post_data.o = orthography_id;					// orthography_id
							
									wait_procedure( "Saving orthography information..." );
									
									var gateway = analytics_gateway( 'form.php' );
									
									$.ajax
									(
										{
											url: gateway, 
											data: post_data,
											success: function( data, textStatus, XHR ) 
											{
												if( data.errorNumber == 0 )
												{
													$( id + " input" ).removeClass( "ui-state-error" )
													$( id + " textarea" ).removeClass( "ui-state-error" )
													$( id + " select" ).removeClass( "ui-state-error" )			

													dialog.dialog( 'destroy' );
													dialog.remove();
												}

												// validation error
												else if( data.errorNumber == 512 )
												{
													$( data.errorList.reverse() ).each
													(
														function( index, element )
														{
															$( id + " input" ).removeClass( "ui-state-error" )
															$( id + " textarea" ).removeClass( "ui-state-error" )
															$( id + " select" ).removeClass( "ui-state-error" )
															
															$( "#" + element.id ).addClass( "ui-state-error" ).focus();
															$( "#" + element.name ).addClass( "ui-state-error" ).focus();
															
															error_procedure( null, element.message, null );
														}
													);
												}
												
												// some other error
												else
												{
													alert( "Error: " + data.errorText );
												}
												
											}
										}
									);																		
								},
								
								'Cancel': function() 
								{
									dialog.dialog( 'destroy' );
									dialog.remove();
								},
								
							}
						}
					).append
					( 
						$('<img>').attr( { src: '/images/spinner_16x16.gif', title: 'Loading...' } ) 
					);

					var gateway = analytics_gateway( 'form.php' );
				
					$.ajax
					(
						{
							url: gateway,
							data: 
							{
								fn: 'orthography',						// form name							
								c: 1, 												// command = RENDER
								o: orthography_id, 						// orthography_id
							},
							success: function( data, textStatus, XHR )
							{
								if( data.errorNumber != 0 )
								{
									dialog.html( "Error: " + data.errorText );	
									return;						
								}
								
								dialog.html( data.form );

								dialog.find( "#part_of_speech_id" ).change
								(
									function( event_object )
									{
										toggle_containers_by_part_of_speech( dialog );
									}
								);								
																
								// orthographies
								hide_extra_form_inputs( dialog, "orthography" );

								// presents
								hide_extra_form_inputs( dialog, "present" );

								// infinitives
								hide_extra_form_inputs( dialog, "infinitive" );

								// perfects
								hide_extra_form_inputs( dialog, "perfect" );

								// p3s
								hide_extra_form_inputs( dialog, "p3" );

								// faps
								hide_extra_form_inputs( dialog, "fap" );

								// paps
								hide_extra_form_inputs( dialog, "pap" );

								// nominatives
								hide_extra_form_inputs( dialog, "nominative" );
																								
								// genitives
								hide_extra_form_inputs( dialog, "genitive" );

								// show/hide all inputs based on part of speech
								toggle_containers_by_part_of_speech( dialog, "part_of_speech_id" );

								
							}
						}
					)
				
					return false;
				}
			);	

			var edit_button_container = $( '<div style="float: right; height: 1px; overflow: visible; margin-left: 3px;">' );

			edit_button_container.append( edit_button );

			edit_button_container.insertBefore( $(this).find( ".flash_card_source" ) );

		}
	)
	
	
} // initialize_orthography_editor

/** 
	*
	*/
function hide_extra_form_inputs( dialog, input_name )
{
	dialog.find( '#' + input_name + '_container input.' + input_name ).each
	(
		function( index, element )
		{
			if( $(this).is(":hidden") )
			{
				//error_procedure( null, this.name, null );
				return true;
			}
			
			var val = $(this).val();
			
			if( val.length == 0  
				&& index != 0 )
			{
				$(this).hide();											
			}
			else
			{
				$(this).prev().prev().show();
				last = this;
			}
			
			$(this).focus
			(
				function( event, ui )
				{
					$(this).next().next().show();
				}
			);
			
		}
	)
}

/**
	*
	*/
function initialize_short_definitions_editor()
{	
	// Grab the English definition elements (which are ordered lists)
	$( ".flash_card_english_def" ).each
	(
		function( index, element )
		{
			var lemma_id = $(this).attr( "data-lemma-id" );
			
			if( typeof( lemma_id ) == "undefined" )
			{
				return;
			}
			
			//error_procedure( null, lemma_id, null );

			var edit_button = $( '<button style="float:right">Edit Definitions</button>' ).button
			(
				{
					icons: 
					{
						primary: 'ui-icon-pencil'
					},
					text: false
				}
			).click
			(
				function( event, ui )
				{
					var button = $(this);
					
					var dialog = $( '<div>' ).dialog
					(
						{
							width: 720,
							height: 480,
							modal: true,
							title: 'Edit Lemma ID #' + lemma_id,
							buttons: 
							{
								'Save': function() 
								{
									var form = $(this).find( "form" )[0];
									
									if( typeof( form ) == "undefined" )
									{
										dialog.dialog( 'destroy' );
										dialog.remove();
										return false;
									}
									
									var id = "#" + form.id;
																		
									var post_data = CollectFormForAjax( id );		

									post_data.fn = "short_definitions";  	// form name
									post_data.c = 2;											// command = SAVE
									post_data.l = lemma_id;								// lemma_id
							
									wait_procedure( "Saving short definitions..." );
									
									var gateway = analytics_gateway( 'form.php' );
									
									$.ajax
									(
										{
											url: gateway, 
											data: post_data,
											success: function( data, textStatus, XHR ) 
											{
												if( data.errorNumber == 0 )
												{
													$( id + " input" ).removeClass( "ui-state-error" )
													$( id + " textarea" ).removeClass( "ui-state-error" )
													$( id + " select" ).removeClass( "ui-state-error" )			

													dialog.dialog( 'destroy' );
													dialog.remove();

												}

												// validation error
												else if( data.errorNumber == 512 )
												{
													$( data.errorList.reverse() ).each
													(
														function( index, element )
														{
															$( id + " input" ).removeClass( "ui-state-error" )
															$( id + " textarea" ).removeClass( "ui-state-error" )
															$( id + " select" ).removeClass( "ui-state-error" )
															
															$( "#" + element.id ).addClass( "ui-state-error" ).focus();
															$( "#" + element.name ).addClass( "ui-state-error" ).focus();
															
															error_procedure( null, element.message, null );
														}
													);
												}
												
												// some other error
												else
												{
													alert( "Error: " + data.errorText );
												}
												
											}
										}
									);																		
								},
								
								'Cancel': function() 
								{
									dialog.dialog( 'destroy' );
									dialog.remove();
								},
								
							}
						}
					).append
					( 
						$('<img>').attr( { src: '/images/spinner_16x16.gif', title: 'Loading...' } ) 
					);

					var gateway = analytics_gateway( 'form.php' );
				
					$.ajax
					(
						{
							url: gateway,
							data: 
							{
								fn: 'short_definitions',			// form name							
								c: 1, 												// command = RENDER
								l: lemma_id, 									// lemma_id							
							},
							success: function( data, textStatus, XHR )
							{
								if( data.errorNumber != 0 )
								{
									dialog.html( "Error: " + data.errorText );	
									return;						
								}
								
								dialog.html( data.form );
																
								// definitions																
								dialog.find( '.definition_container input.definition' ).each
								(
									function( index, element )									
									{
										var val = $(this).val();
										
										if( val.length == 0  
											&& index != 0 )
										{
											$(this).hide();											
										}
										else
										{
											last = this;
										}
										
										$(this).focus
										(
											function( event, ui )
											{
												$(this).next().show();
											}
										);
										
									}
								)
							}
						}
					)
				
					return false;
				}
			);	

			edit_button.insertBefore( $(this) );

		}
	)
}

$(document).ready
(
	function()
	{
		$.ajaxSetup
		(
			{
				dataType: 'json',
				type: 'POST',
				error: error_procedure,
			}
		);		

		initialize_orthography_editor();
		initialize_short_definitions_editor();
	}
);

$(document).ready( error_history_dialog );

