/*	FilmNZ 2005
	Site Scripts
	
	Created 270705 by DS	
	
	Updated by RM
	Last Updated by DS 021205
	
	Updated by DS 301105 - removed 7k of disused functions + commments:
	* Location Search Results' Image Details Toggler functions
	* emulate_link_active_state (used to restyle 'Filter Results' radio button labels to act like 'tabs')
	* hideshow_search_term_option (old tab hide/show mechanism)
	* check_radio_input (tabs?)
	* set focus (404 page and forms)
	* hideshow_el
	* replace_text
	
	Functions demarcated by 'function '
*/

	// init global vars:
	var global_phrase_pre_output = '';
	var global_keyword_pre_output = '';
	
	function clear_field(category, field_id)
	{
		field_el = document.getElementById(field_id);
		field_el.value = '';
		output_search_terms(category);
	}
	
	function select_checkbox(fieldset_id, text_to_match)
	{
		var fieldset_el = document.getElementById(fieldset_id);
		var fieldset_input = fieldset_el.getElementsByTagName('input');
		
		for (i=0; i<fieldset_input.length; i++)
		{
			/* 	parentNode =  <div class="checkbox-wrapper">
				parentNode.parentNode = <div class="row"> */
			var fieldset_input_parent_row = fieldset_input[i].parentNode.parentNode;
			var fieldset_input_label = fieldset_input_parent_row.getElementsByTagName('label')[0];
			var fieldset_input_label_text = fieldset_input_label.innerHTML;
			
			if (fieldset_input_label_text == text_to_match)
			{
				fieldset_input[i].checked = true;
			}		
		}
		if (fieldset_id.indexOf('region') != -1)
		{
			output_search_terms('region');
		}
	}

	function replace(string,text,by) 
	{
		// Replaces text with by in string
		var strLength = string.length, txtLength = text.length;
		if ((strLength == 0) || (txtLength == 0)) 
		{
			return string;
		}
	
		var i = string.indexOf(text);
		if ((!i) && (text != string.substring(0,txtLength))) 
		{	
			return string;
		}
		if (i == -1) 
		{
			return string;
		}
	
		var newstr = string.substring(0,i) + by;
	
		if (i+txtLength < strLength)
		{
			newstr += replace(string.substring(i+txtLength,strLength),text,by);
		}
		return newstr;
	}

	function select_checkboxes(category, fieldset_id, selection)
	{
		var fieldset_el = document.getElementById(fieldset_id);	
		var checkbox = fieldset_el.getElementsByTagName('input');
		
		for (i=0; i<checkbox.length; i++)
		{
			if (selection == 'all')
			{
				checkbox[i].checked = true;
			}
			if (selection == 'none')
			{
				checkbox[i].checked = false;
			}		
		}
		output_search_terms(category);	
	}
	
	function setEvent(id)
	{
		el = document.getElementById(id);
		el.onkeypress = function keyPress(evt) 
		{ 
			if (evt) 
			{
				keyCode = evt.keyCode;
			}
			else  
			{
				keyCode = event.keyCode;
			}
			if (keyCode == 13)
			{ 
				// disable ENTER as submit mechanism, or: output_search_terms('phrase')
				el.blur();
				el.focus();			
				
				// if generated character code is equal to ascii 13 (if enter key)
				/*
					output_search_terms('keywords');
					output_search_terms('regions');
					output_search_terms('seasons');
					output_search_terms('phrase');
					
					document.forms[0].submit()
				*/
				return false;
			}
			else
			{
				return true;
			}		
		}
	}
	
	function reset_form()
	{
		// added 080306 as current solution is only temporarily resetting form
		category_output = '';		
		category_pre_output = '';
		global_phrase_pre_output = '';
		global_keyword_pre_output = '';
		
		// clear hidden fields (wan't being done by document.forms['Form1'].reset() - because readonly? because between pre tags?? 
		document.getElementById("phrase-keyword-output").value = ""; 
		document.getElementById("region-output").value = ""; 
		document.getElementById("season-output").value = ""; 	
		
		document.forms['Form1'].reset(); // output_search_terms('keywords'); output_search_terms('regions'); output_search_terms('seasons'); output_search_terms('phrase');
	}
	
	function output_search_terms(category)
	{
		// textfield: read content of textfield in current category (Search by Phrase / Keyword(s))
		// checkboxes: read labels of all checked inputs in current category
		
		category_id = ('search-by-' + category); // to minimise parameter-related code on page
		
		// test: search-by-phrase returned correctly
		
		var allOutput = document.getElementById("searchTerms"); // The text box that contains all outputs -ryan
		
		var category_el = document.getElementById(category_id);
		var category_inputs = category_el.getElementsByTagName('input');
		var category_labels = category_el.getElementsByTagName('label');	
		
		var total_category_selections = 0;;
		var category_output = '';
	
		// read the input into the only field/label set in this fieldset
		// there could be multiple entries in the one textfield, but the user will have already separated these by commas
		if (category == 'phrase')
		{	
			// var input = category_inputs[0];
			
			category_output += document.getElementById('phrase').value;		
			
			// set focus to submit button
			searchButton = document.getElementById('ucTemplate_btnSearch');
			searchButton.focus();
			
			// test - category output returned ok
			// maybe hitting ENTER to submit is not triggering onChange action?
		}
		// read the selected inputs from multiple field/label sets in this fieldset	
		else
		{
			for (i=0; i<category_inputs.length; i++)
			{
				if (category_inputs[i].checked == true)
				{
					total_category_selections ++;
					
					// var input_row_parent = category_inputs[i].parentNode;
					// var input_label = input_row_parent.getElementsByTagName('label')[0];
					
					var input_label = category_labels[i];
					
					if (total_category_selections > 1)
					{
						category_output += ', ';
					}
	
					// category_output = input_label.innerHTML;		
					// - updated 080306 to string em (used to hide extra text needed for effective database querying)
					category_pre_output = input_label.innerHTML;					
					category_pre_output = replace(category_pre_output, '<em>', '');
					category_pre_output = replace(category_pre_output, '<EM>', '');			
					category_pre_output = replace(category_pre_output, '</em>', '');
					category_pre_output = replace(category_pre_output, '</EM>', '');			
					
					// - manually update a couple of tricky ones
					
						// Cities and Towns
						category_pre_output = replace(category_pre_output, 'Parks and Gardens', 'Parks');					
						category_pre_output = replace(category_pre_output, 'Ports and Wharves', 'Ports');			
						category_pre_output = replace(category_pre_output, 'Urban Roads', 'Roads ! Rural');			
						
						// Countryside		
						category_pre_output = replace(category_pre_output, 'Roads - Rural', 'Roads & Rural');
						
						// Trees
						category_pre_output = replace(category_pre_output, 'Autumn - Fall', 'Autumn');					

					category_output += category_pre_output;
				}
			}
		}
		
		// as phrase and keyword share a field their values are stored separately
		
		if (category == 'phrase')
		{
			global_phrase_pre_output = category_output; // reqd but doubles up output
		}	
		if (category == 'keyword')
		{
			global_keyword_pre_output = category_output;
		}		
		
		// identify output display field
		
		// 011105 - Note this is currently NOT for display output only for form output
		// 			Also currently they are ALL sharing one, which may be a problem
		
		if ((category == 'phrase') || (category == 'keyword'))
		{
			var output_field_id = ('phrase-keyword-output'); 
			// verified - hidden field
		}
		else
		{
			var output_field_id = (category + '-output');
			// region-output - verified
			// season-output - verified
		}
		
		var output_field_el = document.getElementById(output_field_id);	
		
		output_field_el.value = ''; // clear any previous output
		
		if ((category == 'phrase') || (category == 'keyword'))
		{
			if ((global_phrase_pre_output != '') && (global_keyword_pre_output != ''))
			{
				var divider = ', ';
			}
			else if ((global_phrase_pre_output != '') || (global_keyword_pre_output != ''))
			{
				var divider = '';
			}		
			output_field_el.value = global_phrase_pre_output + divider + global_keyword_pre_output;
			
			// output_field_el = hidden field, verified and being populated correctly
		}
		else
		{
			output_field_el.value = category_output;
		}
		
			// test: output_field_el verified
		
			// DISPLAY OUTPUT V2 (ryan, dan's fixes)		
			// *************************************
			
			allOutput.value = ""; // reset field
			
			// We put all outputs (hidden form fields) into a new field, this isnt used for searching simply displaying -ryan
			// Output in this order: Phrase/Keyword (Free Text/Keyword), Region, Season -dan
			// 311105: DS removed 'phrase' output (duplicating phrase/keyword) and comma output (commas were being output under wrong conditions)
			
			// PHRASE/KEYWORD
			
			// Remove any undefineds
			
			if (document.getElementById("phrase-keyword-output").value == "undefined") 
			{
				document.getElementById("phrase-keyword-output").value = ""; 
			}		
			
			if (document.getElementById("phrase-keyword-output").value.length > 0) 
			{
				// 080306 - default replace() function was only catching the first instance of &amp;
//				allOutput.value = document.getElementById("phrase-keyword-output").value.replace("&amp;", "&");				
				allOutput.value = replace(document.getElementById("phrase-keyword-output").value, '&amp;', '&');
			}				
	
			// insert a comma after if REGION or SEASON selections will be displayed after PHRASE/KEYWORD selections
			// REPLACED: if (document.getElementById("phrase-keyword-output").value.length > 0 && (document.getElementById("region-output").value.length > 0 || document.getElementById("season-output").value.length > 0 || document.getElementById("phrase").value.length > 0)) 			
			if (document.getElementById("phrase-keyword-output").value.length > 0 && (document.getElementById("region-output").value.length > 0 || document.getElementById("season-output").value.length > 0)) 
			{
				allOutput.value += ", "
			}
			
			// REGION
			
			if (document.getElementById("region-output").value.length > 0) 
			{
				// 080306 - default replace() function was only catching the first instance of &amp;					
//				allOutput.value += document.getElementById("region-output").value.replace("&amp;", "&");
				allOutput.value += replace(document.getElementById("region-output").value, '&amp;', '&');						
			} 
			
			// insert a comma after if SEASON selections will be displayed after REGION selections		
			// REPLACED: if (document.getElementById("region-output").value.length > 0 && (document.getElementById("season-output").value.length > 0 || document.getElementById("phrase").value.length > 0)) 
			if (document.getElementById("region-output").value.length > 0 && (document.getElementById("season-output").value.length > 0)) 		
			{
				allOutput.value += ", "
			}
			
			// SEASON
			
			if (document.getElementById("season-output").value.length > 0) 
			{
				// 080306 - default replace() function was only catching the first instance of &amp;				
//				allOutput.value += document.getElementById("season-output").value.replace("&amp;", "&");
				allOutput.value += replace(document.getElementById("season-output").value, '&amp;', '&');			
			} 						
	}

	function create_field_value_eraser(category, fieldset_id, field_id)
	{
		// generate paragraph containing link to trigger js function
		var clearing_link = document.createElement('a');
			clearing_link.setAttribute('href', 'javascript:clear_field(\'' + category + '\', \'' + field_id + '\')');
		var clearing_link_text = document.createTextNode('Clear field');	
			clearing_link.appendChild(clearing_link_text);			
			
		var clearing_para = document.createElement('p');		
			clearing_para.className = 'js-action';
			clearing_para.appendChild(clearing_link);		
		
			fieldset_el = document.getElementById(fieldset_id);
			fieldset_input = fieldset_el.getElementsByTagName('input');
			fieldset_label = fieldset_el.getElementsByTagName('label');
		
		for (i=0; i<fieldset_input.length; i++)
		{
			fieldset_input_id = fieldset_input[i].id;
			
			if (fieldset_input_id == field_id)
			{
				fieldset_el.insertBefore(clearing_para, fieldset_input[i]);			
			}
		}
		
	}
	
	function create_checkbox_checker(category, fieldset_id)
	{
		var select_para = document.createElement('p');
		
		var select_leader = document.createTextNode('Select: ');
		
		var select_all_link = document.createElement('a');
			select_all_link.setAttribute('href', 'javascript:select_checkboxes(\'' + category + '\', \'' + fieldset_id + '\', \'all\')');
		var select_all_link_text = document.createTextNode('All');	
			select_all_link.appendChild(select_all_link_text);		
		
		var select_divider = document.createTextNode(' / ');
		
		var select_none_link = document.createElement('a');
			select_none_link.setAttribute('href', 'javascript:select_checkboxes(\'' + category + '\', \'' + fieldset_id + '\', \'none\')');
		var select_none_link_text = document.createTextNode('None');
			select_none_link.appendChild(select_none_link_text);				
		
			select_para.appendChild(select_leader);		
			select_para.appendChild(select_all_link);		
			select_para.appendChild(select_divider);		
			select_para.appendChild(select_none_link);	
			
		var fieldset_el = document.getElementById(fieldset_id);	
	
		if (fieldset_el.nodeName.toLowerCase() != 'fieldset') // where the fieldset is wrapped in a .fieldset div which has the id (keyword categories)
		{
			var fieldset_parent = fieldset_el;
			fieldset_el = fieldset_parent.getElementsByTagName('fieldset')[0];
		}
	
		if (fieldset_el)
		{
			var fieldset_first_div = fieldset_el.getElementsByTagName('div')[0];	
			fieldset_el.insertBefore(select_para, fieldset_first_div);
		}
	}
	
	function hideshow_keyword_category(trigger, keyword_category_number)
	{
		//emulate_link_active_state(keyword_category_number, 'keyword-category-nav', 'li', false); We dont need to emulate links anymore -RM
		
		// hide/show matching category div
		if (keyword_category_number != 0) {
			//if we are initialising then we hide the keywords name
			document.getElementById('keywordsLabel').className = "category-h4-right";
		}
		keyword_categories = document.getElementById('keyword-categories');
		keyword_categories_fieldsets = keyword_categories.getElementsByTagName('div');
	
		var i; // i - used to test every list item
		var j=0; // j - used to match against only nested list items
	
		for (i=0; i<keyword_categories_fieldsets.length; i++)
		{
			// Cycle through all divs, to locate those with a class of 'fieldset'
			// Each 'fieldset' div is positioned absolutely to hide/show the fieldset contained within
			
			if (keyword_categories_fieldsets[i].className.indexOf('fieldset') != -1)
			{
				j++; // update the count of 'fieldset' divs
				
				if (j == keyword_category_number)
				{
					keyword_categories_fieldsets[i].className = 'fieldset shown';
				}
				else
				{
					keyword_categories_fieldsets[i].className = 'fieldset hidden';
				}
			}
		}
	}
	
	// RMs functions for tabbed browsing
	function doAdjust(tabNum) 
	{	
		/* I dont have a heck of alot of time, and because each tab is known im not going to go down
		the dan route of being ultra flexible, just a simple if else condition. to define what is visible and what is not*/
		document.getElementById("welcome").className ="";
		document.getElementById("keywords").className ="";
		document.getElementById("region").className ="";
		document.getElementById("season").className ="";
		document.getElementById("text").className ="";
		document.getElementById("reference").className ="";	
		document.getElementById(tabNum).className ="over";	
	
		document.getElementById("search-by-phrase-or-keyword").className ="tab hide";
		document.getElementById("search-by-region").className ="tab hide";		
		document.getElementById("search-by-season").className ="tab hide";
		document.getElementById("search-by-ref-number").className ="tab hide";
		document.getElementById("search-by-welcome-text").className ="tab hide";	
		document.getElementById("search-by-freetext").className ="tab hide";	
		
		if(tabNum == "welcome") 
		{
			document.getElementById("search-by-welcome-text").className ="tab";		
		} 
		else if(tabNum == "keywords") 
		{
				document.getElementById("search-by-phrase-or-keyword").className ="tab";
		} 
		else if(tabNum == "region") 
		{
				document.getElementById("search-by-region").className ="tab";		
		} 
		else if(tabNum == "season") 
		{
				document.getElementById("search-by-season").className ="tab";
		} 
		else if(tabNum == "reference") 
		{
				document.getElementById("search-by-ref-number").className ="tab";
		} 
		else if(tabNum == "text") 
		{
			document.getElementById("search-by-freetext").className ="tab";
		}
	}
	
	function generate_select_all_or_none_links()
	{
		// Create select all/none links (these links use js to check multiple checkboxes)			
		
		// KEYWORDS
		var keyword_categories = document.getElementById('keyword-categories');
		var keyword_categories_fieldsets = keyword_categories.getElementsByTagName('fieldset');
				
		for (i=0; i<keyword_categories_fieldsets.length; i++)
		{
			var category_id = ('category-' + (i+1));
			create_checkbox_checker('keyword', category_id);
		}
		
		// REGIONS
		create_checkbox_checker('region', 'region-north');
		create_checkbox_checker('region', 'region-south');
		
		// SEASONS
		create_checkbox_checker('season', 'seasons');
		
		// PHRASE
		create_field_value_eraser('phrase', 'search-by-phrase', 'phrase');
	}	

	function init_locationsearch(page_specific_function)
	{
		// RM - replace non java elements with java equivalents
		document.getElementById("search-term-type-anchors").className = "display-none"; 

		// RMs function for tabbed browsing
		doAdjust('welcome');
		hideshow_keyword_category('', 0);
		
		// Update some document text to include references to javascript-only functionality		
		var new_text = 'Please select locations from lists: '
		
		generate_select_all_or_none_links();

		if (page_specific_function == 'locationsearch')
		{		
			generate_safari_note();		
		}
		if (page_specific_function == 'locationsearchresults')
		{			
			generate_detail_toggler();
		}				
		else if (page_specific_function != 'locationsearchresults')
		{
			new_text = ''
		}		
	}