﻿/******************************************************************************************
* Jan 2009
*******************************************************************************************
* Version tracker script which pulls all ins and del tag datestamps out of a documents
* and builds a drop down for users to toggle view
*******************************************************************************************
* datetime must be in the format YYYY-MM-DD
* the dash is necessary
* this is the standard date format generated by MS Word change tracking
********************************************************************************************
See guidance document \\Lon-fp-01\groups\Strategic Policy Directorate\Public Affairs\Corporate Affairs\Web\SRA\EBR\CHANGE TRACKER functions etc\Change Tracker Supporting Documentation.doc
********************************************************************************************/

/**
* FUNCTIONS TO BE ADDED TO THE BODY TAG IN ORDER FOR THIS FILE TO WORK
* <body onload="start(),url_switch(location.href),screen_res()">
*/

//var bod = document.getElementById('ctl00_bodyHome').setAttribute('onload','start()')

function start() {

/**
* Look for 'off' wrapped by the tag with id="creation-date"
* If its set to off don't do anything and switch off dynamic html elements in the template
*/
if(document.getElementById('creation-date').innerHTML == 'off') {

	if(document.getElementById('ui1')) {
		document.getElementById('ui1').style.display = 'none';
	}
	if(document.getElementById('document-date')) {
		document.getElementById('document-date').style.display = 'none';
	}
		
} else {

/*********** *********** *********** *********** *********** *********** *********** 
* the rest of the functions that the tracker uses 
*********** *********** *********** *********** *********** *********** ***********/

// global variables
thisisthis = new Date();
highlight_trigger = 0;
global_single_version = false;
expand_skip = 0;


/**
* Will check for the uniqueness of a value compared to an array. 
* Had to use this as the Javascript 1.6 function indexOf isn't supported for arrays in IE6 and older versions
* Returns TRUE if string 'e' appears in the array 'arrayname'
*/
function index_of(arrayname, e) {
	if(arrayname.length == 0 || arrayname.length == null || arrayname.length == "undefined") {
		// stops errors on the first time it loops
		return false;
	} else {
		for (var i = arrayname.length - 1; i >= 0; i--) {
			if(arrayname[i]==e)  {
			var match = true;
			}
		}

		if(match == true) {
			return true;
		} else {
			return false;
		}
	}
}


/**
* generic numeric sorts for arrays - ascending and descending
*/
function numOrdA(a, b){ return (a-b); }
function numOrdD(a, b){ return (b-a); }


/**
* next three functions get all datestamps of the ins and del tags on the page and put each type into an array
* call get_inserts_on_page() first as this one calls get_dels_on_page(), get_moves_on_page() and puts all data together
*/
function get_inserts_on_page() {
	var inserts = document.getElementsByTagName('ins');
	ins_array = new Array();
	
	// call get_dels_on_page and add results to array
	ins_array = get_dels_on_page();
	
	var move_array = get_moves_on_page();
	if(move_array.length > 0) {
		ins_array.push(move_array);
	}
	
	for (var i = inserts.length - 1; i >= 0; i--) {

		if (inserts[i].getAttribute('datetime')) {
			var ins_date = datestamp_to_number(inserts[i].getAttribute('datetime'));
			var ins_date = parseInt(ins_date);
			
			if (index_of(ins_array,ins_date) == false) {
				ins_array.push(ins_date);
			}
		}
	}
  
	// this array is used for the rest of this function
	return_ins_array = ins_array.sort( numOrdA );

	// this array is used for latest version date date
	var date_array = ins_array.reverse();

	// set global variable containing the latest version date (compared to today's date)
	//loop through array and save date if its <= today's date
	for (var i = date_array.length - 1; i >= 0; i--) {

		var hdate = hyphenDatesR(date_array[i]);
		hdate = datestamp_to_dateobject(hdate);
		hdate = hdate.getTime();
		var today = thisisthis.getTime();
		
		if(hdate <= today) {
			global_closest_date = date_array[i];
		}

	}

	if (return_ins_array==0) {
		return null;
	} else {
		return(return_ins_array);
	}
}

/**
* gets the deleted items on the page
*/
function get_dels_on_page() {   

	var deletions = document.getElementsByTagName('del');
	var del_array = new Array();
	
	// always add start date manually entered in ID="creation-date"
	if(document.getElementById('creation-date') != null) {
	
		if(document.getElementById('creation-date').innerHTML.indexOf('T') > 0) {
			var temp_date = document.getElementById('creation-date').innerHTML.split('T');
			creation_date = datestamp_to_number(temp_date[0]);
		} else {
			creation_date = datestamp_to_number(document.getElementById('creation-date').innerHTML);
		}
		
	} else {
		alert('No creation date specified. Please enter a date or place the text "off" in the div tag');
	}
	
	del_array.push(creation_date);
	
	for (var i = deletions.length - 1; i >= 0; i--) {
		if (deletions[i].getAttribute('datetime')) {
			var del_date = datestamp_to_number(deletions[i].getAttribute('datetime'));
			var del_date = parseInt(del_date);
			if (index_of(del_array,del_date) == false) {
				del_array.push(del_date);
			}
		}
	}
	del_array = del_array.sort( numOrdA );
	return(del_array);
}


/**
* gets the moved blocks on the page
*/
function get_moves_on_page() {
	var moves = document.getElementsByTagName('*');
	var move_array = new Array();
	
	for (var i = moves.length - 1; i >= 0; i--) {
		if(moves[i].getAttribute('class')) {
			var thismove = moves[i].getAttribute('class');
			
			if (thismove.indexOf('moved-from') != -1 || thismove.indexOf('moved-to') != -1) {
				var move_date = datestamp_to_number(parse_class_for_date(thismove));
				
				if(move_date != 'undefined') {
					var move_date = parseInt(move_date);
					if (index_of(move_array,move_date) == false && index_of(ins_array,move_date) == false) {
						move_array.push(move_date);
					}
				}
			}
		}
	}
	move_array = move_array.sort( numOrdA );
	return(move_array);
}


/**
* creates the seletion box for the UI 
* uses 'dates' array created by running get_inserts_on_page()
*/
function writeOutDates(dates) {
	var endDate = dates[0];

	dates.reverse(); 

	global_original_date = datestamp_to_number(document.getElementById('creation-date').innerHTML);
	// check to see if datetime has been used correctly in the document
	if (dates == null) {
		document.getElementById('j-version').innerHTML='<h2>Select version</h2><p class="date-error">Change dates have not been implemeted...</p>';

	// check if there is only one version of the document and therefore no need to write out select box
	} else if(dates.length == 1 && dates[0]) {
		document.getElementById('j-version').innerHTML='<h2>Select version</h2><p class="single-date">One version only in force from <span class="single-date2">'+slashDates(dates[0])+'</span> onward</p>';
		document.getElementById('document-date').innerHTML='Selected version in force from <br /><div id="latest-date">'+slashDates(dates[0]+'</div>');
		
		global_text_date = document.getElementById('creation-date').innerHTML;
		global_original_date = datestamp_to_number(document.getElementById('creation-date').innerHTML);
		global_single_version = true;

	} else {
		
		// create array to hold the HTML for all the generated options
		var datearray = new Array();
		var start_trigger = 0;
		
		for (var i = dates.length - 1; i >= 0; i--) {
			
			// first entry in drop down, so we'll modify the wording
			if(start_trigger ==0) {
				
				//create array for unspecified future change if SPECIAL CASe date is present
				if (dates[i] == '99990101') {
					datearray.push('<option value="'+dates[i]+'" id="'+dates[i]+'">Date to be confirmed</option>');
				} else {
					var starting_from = stick_brackets_on_it(date_number_to_object(dates[i]));
					
					datearray.push('<option value="'+dates[i]+'" id="'+dates[i]+'">'+starting_from+' onward</option>');
					start_trigger = 1;
					date_val_minus = hyphenDates(dates[i]);
				}
				
				
				} else {
			
				// loop through the rest
				var text_from_date = stick_brackets_on_it(date_number_to_object(dates[i]));
				
				var value = day_minus_one(date_val_minus);
				var to_date = day_minus_one(date_val_minus);
				var text_to_date = stick_brackets_on_it(to_date);
				
				//check if its the last and original date and set global variable to be used to hide functionality
				if(i == 0) {
					var dates_val = dates[i];
					var dates_id = dates[i];
					global_original_date = dates[i]; // global variable set
				} else {
					var dates_val = dates[i];
					var dates_id = dates[i];
				}

				datearray.push('<option value="'+dates_val+'" id="'+dates_id+'">'+text_from_date+' to '+text_to_date+'</option>');
				date_val_minus = hyphenDates(dates[i]);
			}
		}
		
		// write out whole drop down
		//document.getElementById('j-version').innerHTML='<h2>Select version</h2><p>Version in force from</p><form><select onChange="version_by_date(this.options[this.selectedIndex].value)"><!--option value="" id="select_one">Select other date...</option-->'+datearray+'</select></form>';
		document.getElementById('j-version').innerHTML='<h2>Select version</h2><p>Version in force from</p><select onChange="version_by_date(this.options[this.selectedIndex].value)"><!--option value="" id="select_one">Select other date...</option-->'+datearray.toString().replace(',','')+'</select>';
	}
}


/**
* Gets the most recent datestamp on page and calls version_by_date() to display the latest version 
* OR writes out an alert to the page telling user there is no versioning
*/
function show_now() {
	if(get_inserts_on_page()) {
		var x = get_inserts_on_page()
		version_by_date(x[0]);
	} else {
		document.getElementById('document-date').innerHTML='<span class="err">Change dates not implemeted.</span>';
	}
}


}

/**************************************************
* end of functions within start() function
**************************************************/


// call the initial functions after they've loaded
if(document.getElementById('creation-date').innerHTML != 'off') {
	writeOutDates(get_inserts_on_page());
	show_now();
}

} //end of main if else


/*********************************************************************************************************/
/* -------------------- PUBLIC FUNCTIONS which can be called direct from HTML -------------------------- */
/*********************************************************************************************************/


/**
* Switches the hide / show markup for current version based on applying class to body tag 
*/
function change_style(clazz) {
	// switch the show-hide tag's class 
	document.getElementById('show-hide').className = clazz;
	
	// change the link style so users know which view they've got
	var zapper = document.getElementById('style-zapper');
	if(clazz == 'hide-markup') {
		zapper.innerHTML='<p>Changes introduced <span id="global_text_date">'+global_text_date+'</span> are included but not highlighted.</p><div id="tooltipholder"><p><a href="#" class="tooltip" style="font-size:100%">Reason for changes<span id="tooltip">&nbsp;</span></a></p></div><button type="button" onclick="change_style(\'show-markup\');" id="highlight-on">Turn on highlighting</button>';
		// get html to insert into tooltip
		get_tooltip();
		// put date into hidden field for pdf generation
		var setChangeTrackerState = document.getElementById('show-hide').className;
		document.getElementById('ctl00_uxPrintPDF_uxPdfExportInfo').value=globalAccessDate+'&viewState='+setChangeTrackerState;
	} else {
		zapper.innerHTML='<p>Changes introduced <span id="global_text_date">'+global_text_date+'</span> are highlighted.</p><div id="tooltipholder"><p><a href="#" class="tooltip">Reason for changes<span id="tooltip">&nbsp;</span></a></p></div><button type="button" onclick="change_style(\'hide-markup\');" id="currentbut">Turn off highlighting</button>';
		// get html to insert into tooltip
		get_tooltip();
		// put date into hidden field for pdf generation
		var setChangeTrackerState = document.getElementById('show-hide').className;
		document.getElementById('ctl00_uxPrintPDF_uxPdfExportInfo').value=globalAccessDate+'&viewState='+setChangeTrackerState;
	}
}


/**
* Disables / enables elements based on the date selected by the user from the drop down box
*/
function version_by_date(date) {
	globalAccessDate=date;
	check = date.toString();

	today = new Date();
	// set global date for output to screen
	// [ brackets for dates in the future
	
	global_text_date = stick_brackets_on_it(date_number_to_object(date));
	if(date == 99990101) {
		global_text_date = '[date to be confirmed]';
	} else {
		global_text_date = stick_brackets_on_it(date_number_to_object(date));
	}
	// set selected date
	if(document.getElementById(date)) {
		var target = document.getElementById(date);
		global_date_range = target.innerHTML;
		/**
		if(target.nextSibling.nodeName == 'OPTION'){
			target.nextSibling.selected = true;
		} else {
			target.selected = true;
		}
		*/
		target.selected = true;
	} else {
		var s = document.getElementById('creation-date').innerHTML.split('-');
		if(s[2].indexOf('T') > 0 ) {
			var temp_date = s[2].split('T');		
		} else {
			var temp_date = s[2];
		}
		global_date_range = temp_date[0]+'/'+s[1]+'/'+s[0];
	}

	user_date = date_number_to_seconds(date);
		
	// check for zero input which means we're going to show all MAY NEED REMOVING !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	if(date == "0") {
		reset_tags();
		document.getElementById('document-date').innerHTML="Showing everything";

		var inserts = document.getElementsByTagName('ins');
		for (var i = inserts.length - 1; i >= 0; i--) {
			inserts[i].className = "current-ins";
		}
		
		var dels = document.getElementsByTagName('del');
		for (var i = dels.length - 1; i >= 0; i--) {
			dels[i].className = 'current-del';
		}
		
	} else {
		reset_tags(date);
		document.getElementById('document-date').innerHTML='Selected version in force from <br /><div id="latest-date">'+global_date_range+'</div>';
		
		/***************** sort out the del tags *****************/
		var deletions = document.getElementsByTagName('del');
			
		for (var i = deletions.length - 1; i >= 0; i--) {
			if (deletions[i].getAttribute('datetime')) {
				//convert extracted datestamp to date object for comparison
				var del_date = datestamp_to_dateobject(deletions[i].getAttribute('datetime'));
				var temp_class = deletions[i].className;
				if(del_date != 'undefined') {
					//compare dates
					if (del_date.getTime() < user_date) {
						deletions[i].className = "past-del";
					} else if (del_date.getTime() > user_date) {
						deletions[i].className = "future-del";
					} else {
						//if (temp_class == 'october') {
						//deletions[i].className = "current-del october";
						//} else {
						deletions[i].className = "current-del";
						//}
					}
				}
			}
		}

		/***************** sort out the ins tags *****************/
		var inserts = document.getElementsByTagName('ins');
			
		for (var i = inserts.length - 1; i >= 0; i--) {
			if (inserts[i].getAttribute('datetime')) {
				//convert extracted datestamp to date object for comparison
				var ins_date = datestamp_to_dateobject(inserts[i].getAttribute('datetime'));
				//compare dates
				if(ins_date != 'undefined') {
					if (ins_date.getTime() == user_date) {
						inserts[i].className = "current-ins";
					} else if (ins_date.getTime() < user_date) {
						inserts[i].className = "past-ins";
					} else {
						inserts[i].className = "future-ins";
					}
				}
			}
		}
		
		// sort out tags with class deleted-block / inserted-block / moved-from / moved-to
		var blok = document.getElementsByTagName('*');// get everything on the page

			for (var i = blok.length - 1; i >= 0; i--) {
				
				var	xclass = blok[i].className;
				
				if(xclass != "undefined" || xclass != null || xclass != '' || xclass!= 0) { // check element has a class
					
					if (xclass.indexOf('deleted-block') != -1) {
						
						var blok_date = datestamp_to_dateobject(parse_class_for_date(xclass));
						if(blok_date != 'undefined') {
							if (blok_date.getTime() == user_date) {
								xclass = xclass+' del-block-current';
								blok[i].className = xclass;
							} else if (blok_date.getTime() > user_date) {
								xclass = xclass+' del-block-future';
								blok[i].className = xclass;
							} else {
								xclass = xclass+' del-block-past';
								blok[i].className = xclass;
							}
						}
						
					} else if (xclass.indexOf('inserted-block') != -1) {
						
						var blok_date = datestamp_to_dateobject(parse_class_for_date(xclass));
						
						if(blok_date != 'undefined') {
							if (blok_date.getTime() == user_date) {
								xclass = xclass+' ins-block-current';
								blok[i].className = xclass;
							} else if (blok_date.getTime() < user_date) {
								xclass = xclass+' ins-block-past';
								blok[i].className = xclass;
							} else {
								xclass = xclass+' ins-block-future';
								blok[i].className = xclass;
							}
						}
						
					} else if(xclass.indexOf('moved-from') != -1) {
						//  sort move from blocks
						var blok_date = datestamp_to_dateobject(parse_class_for_date(xclass));
						
						if(blok_date != 'undefined') {
							if (blok_date.getTime() == user_date) {
								xclass = xclass+' moved-from-current';
								blok[i].className = xclass;
							} else if (blok_date.getTime() < user_date) {
								xclass = xclass+' moved-from-past';
								blok[i].className = xclass;
							} else {
								xclass = xclass+' moved-from-future';
								blok[i].className = xclass;
							}
						}
						
					} else if(xclass.indexOf('moved-to') != -1) {
						// sort move to blocks
						var blok_date = datestamp_to_dateobject(parse_class_for_date(xclass));
						if(blok_date != 'undefined') {
							if (blok_date.getTime() == user_date) {
								xclass = xclass+' moved-to-current';
								blok[i].className = xclass;
							} else if (blok_date.getTime() < user_date) {
								xclass = xclass+' moved-to-past';
								blok[i].className = xclass;
							} else {
								xclass = xclass+' moved-to-future';
								blok[i].className = xclass;
							}
						}
						
					} else {
						// do nowt
					}
				} // end of checking if class exists
			} // end of for loop
	}
	

	
	// create variable to hold object as its reused a lot
	var zapper = document.getElementById('style-zapper');
	// write out the highlight links with the date used
	// doing this after the RESET TAGS function on first time page is loaded
	if (highlight_trigger ==0) {
		zapper.innerHTML='<p>Changes introduced <span id="global_text_date">'+global_text_date+'</span> are highlighted.</p><div id="tooltipholder"><p><a href="#" class="tooltip">Reason for changes<span id="tooltip"></span></a></p></div><button type="button" onclick="change_style(\'hide-markup\');" id="highlight-off">Turn off highlighting</button>';
		zapper.setAttribute('class','on');
		highlight_trigger = 1;
	}
	
	if(global_single_version == false) {
	document.getElementById('global_text_date').innerHTML = global_text_date;
	}
	
	// check for single version state
	if(global_single_version) {
		zapper.setAttribute('class','off');
	}

	// switch off style zapper and amend list if this is the original version of the document
	var compare1 = date_number_to_seconds(date);
	var compare2 = date_number_to_seconds(global_original_date);
	
	if(compare1 == compare2) {
		zapper.className = 'hidden';
		document.getElementById('single-version').innerHTML = '<p>No changes to highlight</p>';
		if(document.getElementById('amend-list')) {
			document.getElementById('amend-list').style.display = 'none';
		}
	} else {
		zapper.className = '';
		document.getElementById('single-version').innerHTML = '';
		if(document.getElementById('amend-list')) {
			document.getElementById('amend-list').style.display = 'block';
		}
	}
	
	//switch on the document date ID as this is hidden by default so it doesn't show when js is off
	document.getElementById('document-date').className = '';
	
	//call function to create amendment list
	make_amendment_list();

	// get html to insert into tooltip
	get_tooltip();
	
	//change background gif
	compare_date(date);

	// call the function to create toc
	generated_toc.generate();
	
	// call function to retrigger the expandable menu 
	//uses a variable so that it doesn't trigger twice when the page loads
	
	if(expand_skip == 0) {
		expand_skip = 1;
	} else {
		expandMyList();
	}
	// put date into hidden field for pdf generation
	var setChangeTrackerState = document.getElementById('show-hide').className;
	document.getElementById('ctl00_uxPrintPDF_uxPdfExportInfo').value=date+'&viewState='+setChangeTrackerState;
	
}


/**
* makes the datetime YYYYMMDD into hyphen delimited date for user DD-MM-YYYY
*/
function hyphenDates(dates) {
	var newdates = dates.toString();
	var year = newdates.slice(0,4);
	var month = newdates.slice(4,6);
	var day = newdates.slice(6,8);
	var stuff = day+'-'+month+'-'+year;
	return stuff;
}
	

/**
* makes the datetime YYYYMMDD into slash delimited date DD/MM/YYYY
*/
function slashDates(dates) {
	var newdates = dates.toString();
	var year = newdates.slice(0,4);
	var month = newdates.slice(4,6);
	var day = newdates.slice(6,8);
	var stuff = day+'/'+month+'/'+year;
	return stuff;
}
	

/**
* makes the datetime YYYYMMDD into slash delimited date BUT REVERSED YYYY/MM/DD
*/
function hyphenDatesR(dates) {
	var newdates = dates.toString();
	var year = newdates.slice(0,4);
	var month = newdates.slice(4,6);
	var day = newdates.slice(6,8);
	var stuff = year+'-'+month+'-'+day;
	return stuff;
}


/**
* uses the global_closest_date and compares the user date 
* changes the background image of the document based on the result
*/
function compare_date(date_in) {

	var date1 = date_number_to_seconds(date_in);
	
	
	var previewCL = document.getElementById('preview-article');
	
	if(date1 < date_number_to_seconds(global_closest_date)) {
		previewCL.className='past-version';
	} else if(date1 == date_number_to_seconds(global_closest_date)) {
		previewCL.className='current-version';
	} else {
		previewCL.className='future-version';
	}

}


/**
* scan custom classes (inserted-block, deleted-block, moved-to, moved-from) and extract date
*/
function parse_class_for_date(clas) {
	var classdate = [];
	classdate = clas.split(" ");
	cdate = classdate[1];
	if(cdate.indexOf('T')!=-1){cdate.split('T');cdate=cdate[0];}
	return cdate; 
}


/**
* converts datestamp yyyy-mm-dd to a javascript date object which enables calculation
*/
function datestamp_to_dateobject(date) {
	input_date = date.split('-');
	var return_date = new Date();
	// set to something at start of month first coz changing these on last days of month screws it (year is ok)
	return_date.setFullYear(2000);
	return_date.setDate(1);
	return_date.setMonth(0);
	//if(input_date[2] == undefined){alert(date);}
	if(input_date[2].indexOf('T') != -1) {
		sthis_day = input_date[2].split("T");
		this_day = sthis_day[0];
	} else {
		this_day = input_date[2];
	}

	
	return_date.setMonth(input_date[1] - 1);
	return_date.setYear(input_date[0]);
	return_date.setDate(this_day);
	return_date.setHours(0);
	return_date.setMilliseconds(0);
	return_date.setMinutes(0);
	return_date.setSeconds(0);
	return return_date;
}


/**
* converts datenumber yyyymmdd to time in seconds which enables calculation
*/
function date_number_to_seconds(indate) {
	indate = indate.toString();
	var year = indate.slice(0,4);
	var month = indate.slice(4,6);
	var day = indate.slice(6,8);
	var user_date = new Date();
	// set to something at start of month first coz changing these on last days of month screws it (year is ok)
	user_date.setFullYear(2000);
	user_date.setDate(1);
	user_date.setMonth(0);
	
	
	user_date.setMonth(month-1);
	user_date.setYear(year);
	user_date.setDate(day);
	user_date.setHours(0);
	user_date.setMilliseconds(0);
	user_date.setMinutes(0);
	user_date.setSeconds(0);
	return user_date.getTime();
}

/**
* converts datenumber yyyymmdd to javascript date object
*/
function date_number_to_object(indate) {

	indate = indate.toString();
	var year = indate.slice(0,4);
	var month = indate.slice(4,6);
	var day = indate.slice(6,8);
	var user_date = new Date();
	
	// set to something at start of month first coz changing these on last days of month screws it (year is ok)
	user_date.setFullYear(2000);
	user_date.setDate(1);
	user_date.setMonth(0);
	
	user_date.setMonth(month-1);
	user_date.setYear(year);
	user_date.setDate(day);
	user_date.setHours(0);
	user_date.setMilliseconds(0);
	user_date.setMinutes(0);
	user_date.setSeconds(0);
	return user_date;
}

/**
* converts our date format to date object and subtracts one day
*/
function day_minus_one(date) {
	var tempdate = date.split('-');
	var xdate = new Date();
	// set to something at start of month first coz changing these on last days of month screws it (year is ok)
	xdate.setFullYear(2000);
	xdate.setDate(1);
	xdate.setMonth(0);
	// now get date
	xdate.setFullYear(tempdate[2]);
	xdate.setMonth(tempdate[1]-1);
	xdate.setDate(tempdate[0]);
	// bump back one day
	xdate.setDate(xdate.getDate() - 1);
	return xdate;
}


/**
* Checks if a number is only one character long and adds preceding zero
*/
function date_format(date_number) {
	if(date_number < 10) {
		return '0'+date_number+'';
	} else {
		return date_number;
	}
}


/**
* Resets all tags so that we don't get markup leaking through as user clicks through versions
*/
function reset_tags(date) {
	// reset ins tags
	var inserts = document.getElementsByTagName('ins');
	for (var i = inserts.length - 1; i >= 0; i--) {
		inserts[i].className = "";
		inserts[i].setAttribute('style','');
	}
	// reset del tags
	var dels = document.getElementsByTagName('del');
	for (var i = dels.length - 1; i >= 0; i--) {
		dels[i].className = "";
		dels[i].setAttribute('style','');
	}
	// reset the special block level classes
	var blox = document.getElementsByTagName('*');
	for (var i = blox.length - 1; i >= 0; i--) {
		if (blox[i].className) {
			var blox_class = blox[i].className;
			if( (blox_class.indexOf('deleted-block') != -1) ) {
				var xdate = blox_class.split(' ');
				xdate = xdate[1];
				blox[i].className = 'deleted-block '+xdate+'';
				blox[i].setAttribute('style','');
			} else if( (blox_class.indexOf('inserted-block') != -1) ) {
				var indate = blox_class.split(' ');
				indate = indate[1];
				blox[i].className = 'inserted-block '+indate+'';
				blox[i].setAttribute('style','');
			} else if( (blox_class.indexOf('moved-from') != -1) ) {
				var indate = blox_class.split(' ');
				indate = indate[1];
				blox[i].className = 'moved-from '+indate+'';
				blox[i].setAttribute('style','');
			} else if( (blox_class.indexOf('moved-to') != -1) ) {
				var indate = blox_class.split(' ');
				indate = indate[1];
				blox[i].className = 'moved-to '+indate+'';
				blox[i].setAttribute('style','');
			} else {
				//do nowt
			}
		}
	}
}


/**
* get datestamp and convert to number so that we can sort it numerically
*/
function datestamp_to_number(datestamp) {

	var mydate = datestamp.split("-");
	
	if (mydate.length > 1) { // check for correct date format
		var this_day = mydate[2];
		
		if(this_day.indexOf('T') != -1) {
			sthis_day = this_day.split("T");
			this_day = sthis_day[0];
		}
		var this_month = mydate[1];
		var this_year = mydate[0];
		var mydate2 = parseInt(this_year+''+this_month+''+this_day);
		return mydate2;

	} else { // wrong format without - marks
		return parseInt(mydate);
	}
}


/**
* creates a list of the CURRENT amendments on the page
*/
function make_amendment_list() {
	// check the div is there before anything
	if(document.getElementById('amend-list')) {
	
		var output_html = new Array();
		var guidance_output_html = new Array();
		var regulation_output_html = new Array();
		var dl_output_html = new Array();
		var tsearch = document.getElementsByTagName('*');
		var dlsearch = document.getElementsByTagName('dl');
		
		output_html.push('<div id="amend-title-container"><p id="ul-amend-title" class="on" onclick="toggle_display(\'ul-amend\')"><a href="javascript:void(0)" id="amend-title">Quick links to amendments</a></p></div><ul id="ul-amend" class="on">');		
		
		for(var i = 0; i < tsearch.length; i++) {
			// search for IDs containing TOA
			if((tsearch[i].id.indexOf('TOA') != -1) && (tsearch[i].innerHTML.indexOf('current-del') > 0 || tsearch[i].innerHTML.indexOf('current-ins') > 0)) {
				// make a better formatted name for the link
				var id_name = tsearch[i].id.replace(/TOA-/,'');
				id_name = id_name.replace(/-/g,' ');
				id_name = id_name.replace(/:_/g,'&#40;');
				id_name = id_name.replace(/_:/g,'&#41;');
				//guidance_output_html.push('<li><a href="#'+tsearch[i].id+'" onclick="change_style(\'show-markup\')">'+id_name+'</a></li>');
				guidance_output_html.push('<li><a href="#'+tsearch[i].id+'">'+id_name+'</a></li>');
			}
		}
		
		for(var i = 0; i < dlsearch.length; i++) {
			// do rule 24 definition lists
			if((dlsearch[i].innerHTML.indexOf('current-del') > 0 || dlsearch[i].innerHTML.indexOf('current-ins') > 0) && dlsearch[i].id != '') {
				// make a better formatted name for the link
				id_name = dlsearch[i].id.replace(/-/g,' ');
				dl_output_html.push('<li><a href="#'+dlsearch[i].id+'" onclick="change_style(\'show-markup\')">'+id_name+'</a></li>');
			}
		}
		output_html.push(guidance_output_html);
		output_html.push(regulation_output_html);
		output_html.push(dl_output_html);
		output_html.push('</ul>');
		output_html = output_html.toString();
		output_html= output_html.replace(/,/g,'');
		document.getElementById('amend-list').innerHTML = output_html;
	}
}


/**
* toggles display for the amendment lists
*/
function toggle_display(ident) {
	var toggle = document.getElementById(ident).className;
	
	if(toggle == 'off') {
		document.getElementById(ident).className = 'on';
		document.getElementById('amend-title').innerHTML = 'Hide quick links to amendments';
		document.getElementById('ul-amend-title').className = 'on';
		// force changes to highlight
		change_style('show-markup');
	} else {
		document.getElementById(ident).className = 'off';
		document.getElementById('amend-title').innerHTML = 'Quick links to amendments';
		document.getElementById('ul-amend-title').className = 'off';
		// force changes to hide
		change_style('hide-markup');
	}
}


/**
* changes the version when date YYYMMDD is appended to the uri using ?
*/
function url_switch(uri) {
	if(uri.indexOf('?') != -1) {
		if(uri.indexOf('?id=') > 0 && uri.indexOf('&') == -1) {return;}
		var loc = uri.toString().replace('&print_page=true','');
		
		
		var viewState = null;

		if(document.getElementById('creation-date').innerHTML == 'off') {
			return;
		} else if(loc.indexOf('ref=search') > 0) {
			return;
		} else {
			// here's where we actually do anything
			var parseThis = loc.split('?');
		
			if(parseThis[1].indexOf('&') != -1) {

				var getDate = parseThis[1].split('&');
				var viewState = parseThis[1].split('viewState=');
				change_style(viewState[1]);
				version_by_date(getDate[1]);
				
			} else {
				if(parseThis[1] == 0 || parseThis[1] == null || parseThis[1] == undefined) {
					// do nowt
				} else {
					
					version_by_date(parseThis[1]);
				}
			}
		}
	}
}


/**
* get latest datestamp on page and call the versioning function to display the latest version 
* OR writes out an alert to the page telling user there is no versioning
* THIS HAS BEEN DUPLICATED FROM show_now() IN THIS SCRIPT SO THAT IT CAN BE ACTIONED FROM HTML
*/
function show_now_url(input) {
	// do nothing if this document has creation date set to off
	if(document.getElementById('creation-date').innerHTML == 'off') {
		return;
	}
	version_by_date(input);
}


/**
* keyboard shortcut for changing style
* this first part adds a listener and is not within a function as we need it to run automatically
*/
if (document.addEventListener) {
	// non-IE bit
	document.addEventListener('keypress',eventkeyup,false );
} else {
	//IE bit
	document.attachEvent('onkeypress',eventkeyup );
}
// this is the function called by the listener above
function eventkeyup(e) {
	if (e.keyCode == 83 || e.charCode == 83){
		var current_clazz = document.getElementById('show-hide').className;
		if(current_clazz == 'show-markup') {
			change_style('hide-markup');
		} else {
			change_style('show-markup');
		}
	}
}


/**
* extracts the current part of id="amendment-information" and puts it into the tooltip
*/
function get_tooltip() {
	var current_flag = false;
	var amendHTML ='';
	if(document.getElementById('amendment-information')){
		var paras = document.getElementById('amendment-information').getElementsByTagName('ins');
	
		for (var i = paras.length - 1; i >= 0; i--) {
			if(paras[i].className == 'current-ins') {
				amendHTML = paras[i].innerHTML.toString();
				current_flag = true;
			}
		}
	}

	if(current_flag == true) {
		document.getElementById('tooltipholder').style.display = 'block';
		document.getElementById('tooltip').innerHTML = amendHTML;
	} else {
		document.getElementById('tooltipholder').style.display = 'none';
	}

}


/**
* sets position for small screen width based on user resizing their browser window

window.onresize = function screen_width() {
	if(navigator.appVersion.indexOf('MSIE 6.0') < 0 && window.innerWidth < 1000) {// Mozilla
		document.getElementById("ui1").style.position = 'absolute';
		document.getElementById("ui1").style.top = '37em';
		document.getElementById("ui1").style.background = '#fff';
		document.getElementById("ui1").style.left = '20px';// sets position for small screen width
		if(document.getElementById("tooltipholder")) {
			document.getElementById("tooltipholder").className = 'left';
		}
	} else if(navigator.appVersion.indexOf('MSIE 6.0') > 0 && document.documentElement.clientWidth < 1000) {// IE
		document.getElementById("ui1").style.position = 'absolute';
		document.getElementById("ui1").style.top = '37em';// sets position for small screen width
		document.getElementById("ui1").style.left = '20px';// sets position for small screen width
		if(document.getElementById("tooltipholder")) {
			document.getElementById("tooltipholder").className = 'left';
		}
	} else {
		document.getElementById("ui1").style.left = '810px';
		document.getElementById("ui1").style.top = '167px';
		if(document.getElementById("tooltipholder")) {
				document.getElementById("tooltipholder").className = '';
		}
	}
}
*/

/**
* checks window size and changes the UI location needs to be triggered by body onload=(xyz).
*/
function check_res() {
	if(navigator.appVersion.indexOf('MSIE 6.0') < 0 && window.screen.width <= 800) {
		document.getElementById("ui1").style.position = 'fixed';
		document.getElementById("ui1").style.background = '#ffffff';
		document.getElementById("ui1").style.top = '100px';// sets position for small screen width
		document.getElementById("ui1").style.left = '20px';// sets position for small screen width
		if(document.getElementById("tooltipholder")) {
			document.getElementById("tooltipholder").className = 'left';
		}
	}
}

/**
* check if the date is in the future and put square brackets around - if true.
* input date must be a date object
*/
function stick_brackets_on_it(date_for_brackets) {
	var now = new Date();
	now = now.getTime();
	var date_output_day = date_format(date_for_brackets.getDate());
	var date_output_month = date_format(date_for_brackets.getMonth()+1);
	var date_output_year = date_for_brackets.getFullYear();
	var date_output = date_output_day+'/'+date_output_month+'/'+date_output_year
	// the [] for future dates
	if(date_for_brackets.getTime() > now) {
		return '['+date_output+']';
	} else {
		return date_output
	}
}
