﻿// before uploading this file, remember to change _uploaded to true
// this is so that it calls the database query page on www.w3.org rather than on people
// this is for version 7 pickers

var _view = 'alphabet';
var _views = new Array;
var _hints = new Array;
var _uploaded = true;

function closewindow() {
    if (window.opener && window.opener.copyoutput) {
        window.opener.copyoutput(document.getElementById('output').value);
		}
	}

function showmatchingspan (node) {  
	// when you mouse over a shape at the top of the page in shape view, this highlights the related group below
	
	// remove any highlighting, eg. from search
	var shapes = document.getElementById('shape').getElementsByTagName( 'img' );
	for (var k=0; k<shapes.length; k++) {
		shapes[k].style.border = '2px solid white';
		}
	
	// paint the row 
	var targets = document.getElementById(node).getElementsByTagName( 'img' );
	for (var i=0; i<targets.length; i++) {
		targets[i].style.border = '2px solid orange';
		} 	
	
	// paint any additional cross-references
	if (document.getElementById(node).title) {
		var additions = document.getElementById(node).title.split(',');
		for (var i=0; i<additions.length; i++) {
			document.getElementById(additions[i]).style.border = '2px solid orange';
			}
		}
	}

function erasematchingspan (node) {
	// when you mouse out of a shape at the top of the page in shape view, this unhighlights the related group below
	
	// remove any highlighting, eg. from search
	var shapes = document.getElementById('shape').getElementsByTagName( 'img' );
	for (var k=0; k<shapes.length; k++) {
		shapes[k].style.border = '2px solid white';
		}
	}

function add(ch) { 
	// ch: string, the text to be added
	// _cluster: boolean, global variable, set if this is a consonant cluster (used for vowels that surround base)
	// _view: string, indicates which view is showing - this is important, since non-intelligent ordering is needed in the default view
	
	if (document.getElementById('output').style.display == 'none') { return; }
	var outputNode = document.getElementById( 'output' ); // points to the output textarea


	//IE support
	if (document.selection) { 
		outputNode.focus();
	    range = document.selection.createRange();
		
		range.text = ch; 
	    range.select(); 
		outputNode.focus();
		}
	// Mozilla and Safari support
	else if (outputNode.selectionStart || outputNode.selectionStart == '0') {
		var startPos = outputNode.selectionStart;
		var endPos = outputNode.selectionEnd;
		var cursorPos = startPos;
		var scrollTop = outputNode.scrollTop;
		var baselength = 0;
		
		outputNode.value = outputNode.value.substring(0, startPos)
              + ch
              + outputNode.value.substring(endPos, outputNode.value.length);
		cursorPos += ch.length;

		outputNode.focus();
		outputNode.selectionStart = cursorPos;
		outputNode.selectionEnd = cursorPos;
		outputNode.scrollTop = scrollTop;
		}
	else {
		outputNode.value += ch;
		outputNode.focus();
		}
		
	// normalize
	//var pairs = outputNode.value.match(/[\u0EC8\u0EC9\u0ECA\u0ECB][\u0E31\u0ECD\u0EC7\u0ECC\u0ECE\u0E38\u0E39\u0E3C\u0E35\u0E36\u0E37\u0E3A]/g);
	//if (pairs != null) {
		//for (var i=0; i<pairs.length; i++) { 
			//outputNode.value = outputNode.value.replace(pairs[i], pairs[i].charAt(1)+pairs[i].charAt(0));
			//}
		//}

	}

	

	
function delchar () { // this is still tbd
	var outputNode = document.getElementById('output');

	//IE support
	if (document.selection) {
		outputNode.focus();
	    document.selection.createRange().text = ''; 
		outputNode.focus();
//		if (sel.text.length > 0) {
//			sel.text = ch;
//			}
//		else {
//			sel.text = ch;
//			}
		}
	//Mozilla and Safari support
	else if (outputNode.selectionStart || outputNode.selectionStart == '0') {
		var startPos = outputNode.selectionStart;
		var endPos = outputNode.selectionEnd;
		var cursorPos = startPos;
		var scrollTop = outputNode.scrollTop;

		outputNode.value = outputNode.value.substring(0, startPos)
            + outputNode.value.substring(endPos, outputNode.value.length);

		outputNode.focus();
		outputNode.selectionStart = cursorPos;
		outputNode.selectionEnd = cursorPos;
		outputNode.scrollTop = scrollTop;
		}
	else {
		if (newLength > 0) {
			outputNode.value = outputText.substring(0, outputText.length-1 );
			}
		else { deleteAll(); }
		outputNode.focus();
		}
	}
	
	
function deleteAll () {
	var outputNode = document.getElementById( 'output' );
	outputNode.value = "";
	}

function selectFont ( newFont ) {
	document.getElementById( 'output' ).style.fontFamily = newFont;
	document.getElementById('fontgrid').style.fontFamily = newFont;
	//for (i=0; i<_views.length; i++) {
		//document.getElementById(_views[i]).style.fontFamily = newFont;
		//}
	document.getElementById('fontName').value="";
	}
	
function customFont ( newFont ) { 
	document.getElementById( 'output' ).style.fontFamily = newFont;
	document.getElementById('fontgrid').style.fontFamily = newFont;
	//for (i=0; i<_views.length; i++) {
		//document.getElementById(_views[i]).style.fontFamily = newFont;
		//}
	document.getElementById('fontList').value='0';
	}
	
function changeFontSize ( newSize ) {
	document.getElementById( 'output' ).style.fontSize = newSize + 'px';
	}
	

function searchFor ( str, scriptname ) {
	// set  border width according to current view
	var borderwidth = '1px';
	if (_view == 'shape') { borderwidth = '2px' } 

	var str = str.replace( /\:/g, '\\b' );
	var re = new RegExp(str, "i"); 
	var characters; 
	for (view=0; view<_views.length; view++) {
		if (document.getElementById(_views[view]).style.display != 'none') {
			characters = document.getElementById(_views[view]).getElementsByTagName( 'img' );
			}
		}
	for (var i = 0; i < characters.length; i++ ) {
		if (characters[i].className != 'ph') {
			characters[i].style.border = borderwidth+' solid white';
			titletext = characters[i].title.toLowerCase();
			titletext = titletext.replace(scriptname, '');
			if (titletext.search(re, 0) > -1 ) {
				characters[i].style.border = borderwidth+' solid red';
				}
			}
		}
	}
	

function convertCP2Char ( textString ) { 
  var outputString = '';
  textString = textString.replace(/[^a-fA-F0-9]/g, ' ');
  textString = textString.replace(/^\s+/, '');
  textString = textString.replace(/\s+$/, '');
  if (textString.length == 0) { return ""; }
        textString = textString.replace(/\s+/g, ' ');
  var listArray = textString.split(' ');
  for ( var i = 0; i < listArray.length; i++ ) {
    var n = parseInt(listArray[i], 16);
    if (n <= 0xFFFF) {
		outputString += String.fromCharCode(n);
		} 
	else if (n <= 0x10FFFF) {
		n -= 0x10000
		outputString += String.fromCharCode(0xD800 | (n >> 10)) + String.fromCharCode(0xDC00 | (n & 0x3FF));
		} 
	else {
		outputString += 'convertCP2Char error: Code point out of range: '+textString;
		}
	}
  return( outputString );
  }
	
	
	
function changeHighlight ( key ) {
	if (key == 'none' || key == 'off' || key == 'Off' ) { _highlightOn = false; }
	if (key == 'shape' ) { _highlightOn = 'true'; }
	}
	
	
function h ( node ) {
	// display character information
	span = document.createElement( 'span' );
	span.setAttribute( 'id', 'charname' );
	charinfo = document.createTextNode( node.title );
	span.appendChild(charinfo);
	var chardata = document.getElementById('chardata');	
	chardata.replaceChild( span, chardata.firstChild );
	
	if (_view == 'shape') {
		// remove any highlighting, eg. from search
		if (node.nodeName.toLowerCase() != 'td') {
			node.style.border = '2px solid white';
			}

		// highlight similar characters
		var colour = 'orange';
		var character = node.id; 
		if (_highlightOn) {
			for (var i=0; i<_hints.length; i++) { 
				if (_hints[i][0] == character ) { 
					for (var j=1; j<_hints[i].length; j++) {
						if (_hints[i][j] == 'a02B') { colour = 'orange'; }
						else {
							document.getElementById( _hints[i][j] ).style.border = '2px solid '+colour; 
							}
						}
					break;
					}
				}
			}
		}
	}


function u ( node ) {
	var borderwidth = '1px';
	if (_view == 'shape') { borderwidth = '2px' } 
	var character = node.id;
	for (var i=0; i<_hints.length; i++) { 
		if (_hints[i][0] == character) {
			for (var j=1; j<_hints[i].length; j++) {
				if (_hints[i][j] != 'a02B') { 
					document.getElementById( _hints[i][j] ).style.border = borderwidth+' solid white';
					}
				}
			break;
			}
		}
	}

	

	
	
function switchView (toView) {
	// toView: string, id of the div surrounding the content to be viewed
	// _view: string, stores the name of the div id so that addchar() can act in a view sensitive way
	
	_view = toView;
	
	var views = document.getElementById('tables').childNodes;
	for (var i=0; i<views.length; i++) {
		if (views[i].nodeName == 'DIV') { views[i].style.display = 'none'; }
		}
		
	document.getElementById(toView).style.display = 'block';
	}
	

	

function hideOutput () {
	document.getElementById('output').style.height = '0px'; 
	document.getElementById('restoreOutput').style.display = 'block';
	document.getElementById('buttons').style.display = 'none';
	}
	
function unhideOutput () {
	if (document.getElementById('output').style.display == 'none') {
		//document.getElementById('output').style.height = (document.getElementById('rows').value*100)+'px';
		document.getElementById('output').style.display = 'block';
		document.getElementById('buttons').style.display = 'block';
		document.getElementById('showOutput').replaceChild(document.createTextNode('Disable output'), document.getElementById('showOutput').firstChild);
		}
	else {
		document.getElementById('output').style.display = 'none';
		document.getElementById('buttons').style.display = 'none';
		document.getElementById('showOutput').replaceChild(document.createTextNode('Enable output'), document.getElementById('showOutput').firstChild);
		}
	}
	
	
function transcribe (node) {
	var chstring = node.value;
	var output = '';document.createTextNode('Picker')
	for (var i=0; i<chstring.length; i++) {
		var ch = map[chstring.charCodeAt(i)].trans;
		if (ch) { output += ch; }
		else { output += chstring.charAt(i); }
		}
	document.getElementById('latin').value = output;
	}


function showcodepoints (node) {
	var chstring = node.value;
	list = '';
	for (var i=0; i<chstring.length-1; i++) {
		hexcode = chstring.charCodeAt(i).toString(16).toUpperCase();
		if (hexcode.length < 2) { hexcode = '000'+hexcode; }
		if (hexcode.length < 3) { hexcode = '00'+hexcode; }
		if (hexcode.length < 4) { hexcode = '0'+hexcode; }
		list += hexcode+' ';
		}
	hexcode = chstring.charCodeAt(chstring.length-1).toString(16).toUpperCase();
	list += hexcode;
	
	codepoints = window.open('/rishida/scripts/uniview/getName.php?graphics=yes&list='+list, 'codepoints'); codepoints.focus();
	}
	
function showdetail (node) {
	var chstring = node.value;
	list = '';
	for (var i=0; i<chstring.length-1; i++) {
		hexcode = chstring.charCodeAt(i).toString(16).toUpperCase();
		if (hexcode.length < 2) { hexcode = '000'+hexcode; }
		if (hexcode.length < 3) { hexcode = '00'+hexcode; }
		if (hexcode.length < 4) { hexcode = '0'+hexcode; }
		list += hexcode+' ';
		}
	hexcode = chstring.charCodeAt(chstring.length-1).toString(16).toUpperCase();
	list += hexcode;
	
	if (_uploaded) {
	detail = window.open('http://www.w3.org/People/Ishida/php/showchars/index.php?codepoints='+list, 'detail'); detail.focus();
		}
	else { 
		detail = window.open('/rishida/scripts/showChars.php?codepoints='+list, 'detail'); detail.focus();
		}
	}
	
	
function closeCodepoints () {
	document.getElementById('codepoints').style.display = 'none';
	document.getElementById('shape').style.display = 'block';
	document.getElementById('chardata').style.display = 'block';
	document.getElementById('buttons').style.display = 'block';
	document.getElementById('latin').style.display = 'block';
	}

	

// INITIALISATION
function setMouseover ( node ) {
	node.onmouseover = function(){ h(node) };
	}
	
function setMouseout ( node ) {
	node.onmouseout = function(){ u(node) };
	}
	
function setShapeMouseover ( node ) {
	node.onmouseover = function(){ showmatchingspan(node.alt) };
	}
function setShapeMouseout ( node ) {
	node.onmouseout = function(){ erasematchingspan(node.alt) };
	}
	
function setOnclick ( node, ch ) {
	node.onclick = function(){ add(ch) };
	}
	
function setOnclickPhone ( node, ch ) {
	node.onclick = function(){ add(ch) };
	}
	
function titleSort (a, b) {
	return parseInt(a.title, 16)-parseInt(b.title, 16);
	}

function convertCharToId ( textString ) {
	// converts a character or sequence of characters to hex codepoint values preceded by 'a', as per the ids
	// copes with supplementary characters
	// textString: the character or sequence of characters to be converted
	textString = textString.replace(/\s/g, ''); // remove any spaces used for combining characters
	var codepoint = "";
	var haut = 0;
	var n = 0; 
	for (var i = 0; i < textString.length; i++) {
		var b = textString.charCodeAt(i); 
		if (b < 0 || b > 0xFFFF) {
			codepoint += 'Error: Initial byte out of range in convertCharToId: '+dec2hex(b);
			}
		if (haut != 0) { // we should be dealing with the second part of a supplementary character
			if (0xDC00 <= b && b <= 0xDFFF) {
				codepoint += dec2hex(0x10000 + ((haut - 0xD800) << 10) + (b - 0xDC00)) + ' ';
				haut = 0;
				continue;
				}
			else {
				codepoint += 'Error: Second byte out of range in getCPfromChar: '+dec2hex(haut);
				haut = 0;
				}
			}
		if (0xD800 <= b && b <= 0xDBFF) { //b is the first part of a supplementary character
			haut = b;
			}
		else { // this is not a supplementary character
//			codepoint += dec2hex(b);
//			codepoint += 'a'+b.toString(16).toUpperCase();
			var hexcp = b.toString(16).toUpperCase();
			if (hexcp.length < 4) { hexcp = '0'+hexcp; }
			codepoint += 'a'+hexcp;
			}
		} 
 //alert('>'+codepoint+'<');
	return codepoint;
	}
	
function initialise() {
	// _views: array, listing ids of all view divs
	
	// set up hinting: creates an 2-d array of id values for characters in the features list
	for (var i=0; i<features.length; i++) { 
		_hints[i] = features[i].split(','); 
		for (var j=0; j<_hints[i].length; j++) {
			if (_hints[i][j].charAt(0) != 'a') {
				_hints[i][j] = convertCharToId(_hints[i][j]);
				}
			}
		}

	// set up a list of all views in global _views variable
	var viewnodes = document.getElementById('tables').childNodes;
	var count = 0;
	for (i=0; i<viewnodes.length; i++) {
		if (viewnodes[i].nodeName == 'DIV') { _views[count] = viewnodes[i].id; count++; }
		}

	// set mouseover/mouseout functions for all imgs in all views
	for (i=0; i<_views.length; i++) {
		var characters = document.getElementById(_views[i]).getElementsByTagName( 'img' );
		for (var j = 0; j < characters.length; j++ ) {
			if (characters[j].className != 'ph') { 
				setMouseover(characters[j]);
				setMouseout(characters[j]);
				}
			}
		}
	if (document.all) {  // stop IE changing the focus when clicking on an img
		document.getElementById('alphabet').onselectstart = function () { return false };
		}
		
	// set different behaviour for shape keys
	var shapes = document.getElementById('shapekey').getElementsByTagName( 'img' );
	for (var j = 0; j < shapes.length; j++ ) {
			setShapeMouseover(shapes[j]);
			setShapeMouseout(shapes[j]);
			}

	// set onclick for phonemic graphics
	var phones = document.getElementById('phonic').getElementsByTagName( 'img' );
	for (var n = 0; n < phones.length; n++ ) {
			setOnclickPhone(phones[n], phones[n].alt); 
			}

	// set onclick for alphabet graphics
	var alpha = document.getElementById('alphabet').getElementsByTagName( 'img' );
	for (var n = 0; n < alpha.length; n++ ) {
			if(alpha[n].alt != 'Click for advanced view.') { setOnclickPhone(alpha[n], alpha[n].alt); }
			}

	// set onclick for shape graphics
	shapes = document.getElementById('shapebucket').getElementsByTagName( 'img' );
	for (var n = 0; n < shapes.length; n++ ) {
			if (shapes.className != 'shapekey') { 
				setOnclickPhone(shapes[n], shapes[n].alt); 
				shapes[n].style.cursor="pointer";
				}
			}

	// highlight all images in shapes view that have hints associated
	shapes = document.getElementById('shapebucket').getElementsByTagName( 'img' );
	for (var k=0; k<shapes.length; k++) {
		for (var i=0; i<_hints.length; i++) { 
			if (_hints[i][0] == shapes[k].id ) { 
				shapes[k].style.backgroundImage = 'url(images/plus.png)'; 
				}
			}
		}

	// set up font grid
	var container = document.getElementById('fontgrid');
	var width = eval(container.title);
	var table = container.appendChild(document.createElement('table'));
	var tbody = table.appendChild(document.createElement('tbody'));
	var charNodes = document.getElementById('alphabet').getElementsByTagName( 'img' );
	var characters = new Array;
	var count = 0;
	for (i=0; i<charNodes.length; i++) {
		if (charNodes[i].className != 'nogrid') {
			//idvalue = charNodes[i].id;
			//codes = idvalue.split('x');
			//idvalue = '';
			//for (var n=1; n<codes.length; n++){ idvalue += String.fromCharCode(parseInt(codes[n], 16)); }
			//characters[count] = { title: charNodes[i].title, alt: idvalue }; 
			characters[count] = { title: charNodes[i].title, alt: charNodes[i].alt }; 
			count++;
			}
		}
	characters.sort(titleSort);
	
	var height = characters.length/width;

	for (i=0; i<height; i++) {
		var tr = tbody.appendChild( document.createElement( 'tr' ));
		
		for (j=i*width; j<((i*width)+width); j++) { 
			if (j<characters.length) {
				td = tr.appendChild( document.createElement( 'td' ));
				var text = document.createTextNode('\u00A0'+characters[j].alt);
				td.title = characters[j].title;
				td.appendChild(text);
				setMouseover(td);
				setMouseout(td);
				td.className = 'add'+characters[j].alt;
				setOnclick(td, characters[j].alt);
				}
			}
		}
	// set the font from what's currently indicated in the font selection boxes
	customfont = document.getElementById('fontName').value; 
	listfont = document.getElementById('fontList').value; 
	if (customfont) { container.style.fontFamily = customfont; }
	else { container.style.fontFamily = listfont; }
	//container.appendChild(closeSA);
	if (document.all) {  // stop IE changing the focus when clicking on an img
		for (i=0; i<_views.length; i++) {
			document.getElementById(_views[i]).onselectstart = function () { return false };
			}
		}
	document.getElementById('output').focus();
	}

window.onload = function() { initialise(); };
var _highlightOn = true;
