/*
  Additional javascript functions used for the Raphael project website.
*/

function onLoad() {}
function onResize() {}


function posDivider (eA, eB, sL, dir)
	{
	var seA = eA.getSize();
	var seB = eB.getSize();
	var peA = eA.getPosition();
	var peB = eB.getPosition();

	if (dir == 'vertical')
		{
		sL.style.height = (seT.y + seB.y) + 'px';
		sL.style.top = (peT.y) +'px';
		sL.style.left = (peT.x - 8) + 'px'; //8 pixels being 
		}
	else
		{
		dir = 'horizontal';
		}

	sL.style.height = (seT.y + seB.y) + 'px';
	sL.style.top = (peT.y) +'px';
	sL.style.left = (peT.x - 8) + 'px';

	$$('div.slider.advanced').each(function(el, i){
		var slider = new Slider(el, el.getElement('.knob'), {
			mode: dir,
			steps: 10,  // Steps from 0 to 9
			wheel: true, // Using the mousewheel is possible too
			onChange: function(){
				stuff (eT, eB, ((this.step)/10), (seT.y + seB.y - 12), peT.y );
			}, 
			onComplete: function(){
				stuff (eT, eB, ((this.step)/10), (seT.y + seB.y - 12), peT.y );
			},
			snap: true
		}).set(1);
	});

	}

function addSlider (nMp, nMc)
	{
  var par	= $(nMp);
  var chi = new Element("div", {
      'class': 'slider advanced'
      });
	
  	chi.setAttribute("id", nMc);
	var thisDiv = document.createElement("DIV");
  var thisDiv = new Element("div", {
      'class': 'knob'
      });
		thisDiv.setAttribute("id", "knob");
		thisDiv.setAttribute("style", "");
		thisDiv.setAttribute("background-image", "url('http://raphael/documentation/graphics/t1.png')");

 	chi.appendChild(thisDiv);
 	par.appendChild(chi);
	}

function posSlider (eT, eB, sL, sT)
	{
	var seT = eT.getSize();
	var seB = eB.getSize();
	var peT = eT.getPosition();
	var peB = eB.getPosition();

	if (sT)
		{var start = sT;}
	else
		{var start = 5;}

	sL.style.width = (seT.x + seB.x) + 3 + 'px';
	sL.style.top = (peT.y - 15) +'px';
	sL.style.left = (peT.x) + 'px';

	$$('div.slider.advanced').each(function(el, i){
		var slider = new Slider(el, el.getElement('.knob'), {
			offset: 8,
			mode: 'horizontal',
			steps: 10,  // Steps from 0 to 9
			wheel: true, // Using the mousewheel is possible too
			onChange: function(){
				stuff (eT, eB, ((this.step)/10), (seT.x + seB.x + 5), peT.x, sL );
			}, 
			onComplete: function(){
				stuff (eT, eB, ((this.step)/10), (seT.x + seB.x + 5), peT.x, sL );
				slPos = this.step;
			},
			snap: true
		}).set(start);
	});

	}


function stuff (eT, eB, ratio, max, top, nam)
	{
	//dc (eT+', '+eB+', '+ratio+', '+max+', '+top);
	var ps = eT.getPosition();
	var pk = $('knob').getPosition();
	var pr = $(nam).getPosition();

	var myT = new Fx.Tween(eT);
	var myB = new Fx.Tween(eB);

	var hT = (ratio * max);
	var hB = max - hT - 5;

	if (hB < 0) 
		{hB = 0;
		 myB.set('display', 'none');}
	else {myB.set('display', 'block');}
	var tB = ps.x + hT;

	myT.set('width', hT +'px');
	myB.set('width', hB + 'px');
	myB.set('left', hT + 10 + 'px');

	var p1 = eB.getPosition();
	var p2 = $('knob').getPosition();
	var s1 = eT.getSize();
	//dc (s1.x + ' : ' + s1.y +'<br>'+p1.x + ' : ' + p1.y + '<br>' + p2.x + ' : ' + p2.y);

	if (iip)
		{iip.refreshWindows();}
	}

function refreshAccordianSM (par, lw)
	{
	var pD = $(par).getSize();
	
	var wid;
	
	if(!lw)
		{lw = 0;}
	
	if (pD.x > 670)
	  {wid = 660;}
	else
		{wid = pD.x - lw;}
		
	$(par).setStyle('width', wid +'px');
		
	  //create our Accordion instance
  	// Anpassung IE6
	if(Browser.Engine.name == 'trident' && Browser.Engine.version == 4 ) 
	  {var heightValue='100%';}
  else
    {
    var heightValue='';
	
	// Selektoren der Container für Schalter und Inhalt
	var togglerName='dt.accordion_toggler_';
	var contentName='dd.accordion_content_';
	
	
	// Selektoren setzen
	var counter=1;	
	var toggler=$$(togglerName+counter);
	var content=$$(contentName+counter);
	
	while(toggler.length>0)
	{
		// Accordion anwenden
		new Accordion(toggler, content, {
			opacity: false,
			display: -1,
			alwaysHide: true,
			onComplete: function() { 
				var element=$(this.elements[this.previous]);
				if(element && element.offsetHeight>0) element.setStyle('height', heightValue);			
			},
			onActive: function(toggler, content) {
				toggler.addClass('open');
			},
			onBackground: function(toggler, content) {
				toggler.removeClass('open');
			}
		});
		
		// Selektoren für nächstes Level setzen
		counter++;
		toggler=$$(togglerName+counter);
		content=$$(contentName+counter);
	}}
}

function refreshAccordian(par, lw, fd)
	{	
	
	if ($(par))
		{
		var pD = $(par).getSize();
		
		if(!lw)
			{lw = 0;}
	
		if (pD.x > 670)
	  	{wid = 660;}
		else
			{wid = pD.x - lw;}
	
		$(par).setStyle('width', wid +'px');
		
	//IE6
	if(Browser.Engine.name == 'trident' && Browser.Engine.version == 4 ) 
	  {var heightValue='100%';}
  else
    {
    var heightValue='';
	
	var togglerName='dt.accordion_toggler_';
	var contentName='dd.accordion_content_';
	
	var counter=1;	
	var toggler=$$(togglerName+counter);
	var content=$$(contentName+counter);
	
	while(toggler.length>0)
	{
		// Accordion anwenden
		new Accordion(toggler, content, {
			opacity: false,
			display: -1,
			alwaysHide: true,
			onComplete: function() { 
				var element=$(this.elements[this.previous]);
				if(element && element.offsetHeight>0) element.setStyle('height', heightValue);			
			},
			onActive: function(toggler, content) {
				//add2DebugString('ACTIVATE ' + toggler.id);
				activate = toggler.id;
				toggler.addClass('open');
				updateImagesRelated2Text (toggler.id);
			},
			onBackground: function(toggler, content) {
				
				if (toggler.hasClass('open'))
					{
					//add2DebugString('BACK ' + toggler.id);
					if (toggler.id == activate)
						{activate = 0;}
					 toggler.removeClass('open');
				   closeChildren (toggler);
				   selectPToggler (toggler);}
				}
		});
		
		// Selektoren für nächstes Level setzen
		counter++;
		toggler=$$(togglerName+counter);
		content=$$(contentName+counter);
	}}
}
}


function closeChildren (el)
	{	
	if ($(el).nextSibling) 
		{
		var myElements = $(el).nextSibling.getElements('dt.open');
		myElements.each(function(item, index)
			{item.removeClass('open');
			 if (item.id == activate)
			 	{activate = 0;}
		 	 item.fireEvent('click', item, 1);});		
		}
	}
		
function	selectPToggler (el)
		{	
		var pTog = false;
		
		if (el.parentNode.parentNode.previousSibling)
			{pTog = el.parentNode.parentNode.previousSibling;}
			
		var clid = false;
		
		//need to check if any of the sibilings are open
		var skip = false;
		
		var pn = $(el).parentNode;
		var otherEls = $(pn).getElements('dt.open');
		otherEls.each(function(item, index)
			{if (item.hasClass('open'))
				{skip = true;}});	
				
		if (skip)
			{}
		else {
			if (pTog)
				{
				if (pTog.get('tag') == "dt" && pTog.hasClass('open'))
					{updateImagesRelated2Text (pTog.id);}
				if (pTog.get('tag') == "dt")
					{selectPToggler(pTog);}
				else
					{updateIIP();}
				}
			else
				{updateIIP();}
			}
		}

function clearTxDT (pdiv)
	{
	if ($(pdiv))
		{$(pdiv).getChildren().each( function(el) 
			{el.dispose();});}
	}
	
function updateIIP (arr)
	{
	var refresh = false;
	var uarr = new Object();
	
	if (!arr && usingDefault == true)
		{}
	else if (!arr)
		{uarr = defaultIIP;
		 usingDefault = true;
		 refresh = true;}	
	else if (arr['no_ims'] > 0)
		{uarr = arr;
		 usingDefault = false;
		 refresh = true;}	
	else if (usingDefault == false)
		{uarr = defaultIIP;
		 usingDefault = true;
		 refresh = true;}
	else
		{}
	
	if (refresh)
		{		
		no_ims = uarr['no_ims'];
		grid_rows = uarr['grid_rows'];
		grid_cols = uarr['grid_cols'];
		grid_max_x = uarr['grid_max_x'];
		grid_max_y = uarr['grid_max_y'];
		max_res = uarr['max_res'];
		sqlLimit = uarr['sqlLimit'];
		help = uarr['help'];
			
		grid_ims = grid_rows * grid_cols;
		grid_width = grid_cols * grid_max_x;
		grid_height = grid_rows * grid_max_y;
		all_ims= makeList (0, no_ims);
		start_point = 1;
		ims = '';
		
		if (grid_max_x && grid_max_x > grid_max_y)
			{var rlimit = 2 * grid_max_x;}
		else if (grid_max_x && grid_max_y > grid_max_x)
			{var rlimit = 2 * grid_max_y;}
		else
			{var rlimit = 20000;}

		if (grid_max_x < grid_max_y)
			{resolution_limit = rlimit * grid_cols;}
		else
			{resolution_limit = rlimit * grid_rows;}
	
		if ($('mainIIP'))
			{
			$('mainIIP').getChildren().each( function(el) 
				{el.dispose();});
			iip = new nIIP( 'mainIIP', server );
			}	
		}
	}

function updateImagesRelated2Text (id)
	{
	add2FunctionString ('updateSelectedText ('+id+')');	
		
	var search_path = "ajax.php?what=text2ims&val="+id+"&whichdb="+whichDB+"&whichtable="+whichTable;

	searchRequest = new Request( 
		{
		method: 'get',
		url: search_path,
		autoCancel: true, 
		async:true,  
    onRequest: function() {}, 
		onFailure: function() {alert('FAILED')}, 
    onComplete: function(response) { 
			var loc_pd = new Array ();
			
			add2DebugString(response);
			eval ("loc_pd = "+response);
			
			if (activate == loc_pd['id'])
				{updateIIP (loc_pd);}
			else if (activate == 0) 
				{updateIIP (loc_pd);}
			else
				{}
			}  
    });

	if(id > 0)
		{searchRequest.send();}
	}
	

function updateSelectedText (id, pdiv)
	{
	add2FunctionString ('updateSelectedText ('+id+')');
	var search_path = "ajax.php?what=txtdetails&val="+id+"&whichdb="+whichDB+"&whichtable="+whichTable;

	searchRequest = new Request( 
		{
		method: 'get',
		url: search_path,
		autoCancel: true, 
		async:true,  
    onRequest: function() { /*alert('Request made. Please wait...');*/ }, 
		onFailure: function() {alert('FAILED')}, 
    onComplete: function(response) { 
			var loc_pd = new Array ();
			eval ("loc_pd = "+response);
      refreshTxDT (loc_pd, pdiv);
			}  
    });

	if(id > 0)
		{searchRequest.send();}
  else
    {refreshTxDT (0, pdiv);}
	}
	
	
function refreshTxDT (str, pdiv)
	{
	if ($(pdiv))
		{
    var fdiv = $(pdiv);
  	  
		fdiv.getChildren().each( function(el) 
			{el.dispose();});
        
    var tdiv = new Element("div", {'id': 'imdLeft'});
      fdiv.appendChild(tdiv);
    var rdiv = new Element("div", {'id': 'imdRight'});
      fdiv.appendChild(rdiv);
    
		if (str['TextIdenifier'])
    	{
    	tdiv.setStyle('display', 'block'); 
    	newTandV (tdiv, 'Identifier: ', str['TextIdenifier'], 'mlevN_1', 'st');
    	newTandV (tdiv, 'Title: ', str['TextTitle'], 'mlevN_1', 'st');
    	
    	newTandV (tdiv, 'Author(s): ', str['Author'], 'mlevN_1', 'st');
    	newTandV (tdiv, 'Date: ', str['Date'], 'mlevN_1', 'st');
    	newTandV (tdiv, 'Updated: ', str['UpDate'], 'mlevN_1', 'st');
    	    	
    	if (!str['cats'])	{str['cats'] = ' --- ';}
    	if (!str['related'])	{str['related'] = ' --- ';}
    	
    	newTandV (tdiv, 'Categories: ', str['cats'], 'mlevN_1', 'st');
    	newTandV (tdiv, 'Related to: ', str['related'], 'mlevN_1', 'st');
    	newTandV (tdiv, 'Public: ', str['Public'], 'mlevN_1', 'st');
    	
    	if (!str['TextDescription'])
    		{str['TextDescription'] = ' --- ';}
    		
    	newTandV (tdiv, 'Description: ', str['TextDescription'], 'mlevN_1', 'st');
    	}
  	else
    	{tdiv.setStyle('display', 'none');}
		}
	}
	
function basicRefresh () {	
	
	$('page').style.display = 'none';
  var winD = Window.getSize();
	var winW = winD.x, winH = winD.y;
	
	if (winW < 1025)
	  {winW = 1024;}
	if (winH < 601)
	  {winH = 600;}
		
	if ($('popupContents'))
		{popup();}
  if ($('debugPage').getStyle('display') != 'none')
    {$('debugPage').setStyle('display', 'none');}
		
	checkResolution ();

	if (Browser.Engine.trident)
		{var sb = 20;} // Allows for the thickness of the scroll bar
	else
		{var sb = 0;}
	
	$('leftEdge').style.height = (winH) + 'px';
	$('rightEdge').style.height = (winH) + 'px';
	$('rightEdge').style.left = (winW - 35) + 'px';
	$('MainMenu').style.height = (winH - 150) + 'px';

	var myRP = document.getElementById('rightPanel');
	var myRT = document.getElementById('rightTitle');
		 
	if ($('displayOptions'))
		{myRT.style.width 	= (winW - 310 - sb - 55) - 50 + 'px';
 		 $('displayOptions').style.width 	= 40 + 'px';
 		 $('displayOptions').style.left 	= 310 + (winW - 310 - sb - 55) - 40 + 'px';}
	else
		{myRT.style.width 	= (winW - 310 - sb - 55) + 'px';}
	
	$('lowerLinks').style.top	= winH - 35 + 'px';
	$('lowerLinks').style.width	= (winW - 310 - sb - 55) + 'px';

 	myRP.style.left = 310 + 'px';
	myRP.style.top = 142 + 'px';
 	myRP.style.width 	= (winW - 310 - sb - 55) + 'px';
	myRP.style.height = (winH - 142 - 45) + 'px';
	
	if ($('bodyLeft'))
		{$('bodyLeft').style.width = ((winW - 310 - sb - 55)/2) -5 + 'px';
		 $('bodyLeft').style.height = (winH - 142 - 45) + 'px';}
	if ($('bodyRight'))
		{$('bodyRight').style.width = ((winW - 310 - sb - 55)/2) -5 + 'px';
		 $('bodyRight').style.left = ((winW - 310 - sb - 55)/2) + 5 + 'px';
		 $('bodyRight').style.height = (winH - 142 - 45) + 'px';}
	
	$('toplinks').style.width = (winW + sb - 85) + 'px';

	if (document.getElementById('imframe'))
		{var myFR = document.getElementById('imframe');
  	myFR.style.width 	= (winW - 310 - sb - 45) + 'px';
		myFR.style.height = (winH - 140 - 15) + 'px';		
		myFR.src = myFR.src;}		
    
  if ($('captions'))
    {$('captions').style.width = ((winW - 310 - sb - 55) * 0.6) + 'px';}
	    
	$('page').style.display = 'block';	
		
	if ($('titleTable'))
		{var ttS = $('titleTable').getSize();
		 $('titleTable').style.top	= (80 - ttS.y)/2 + 'px';}
 
	if ($('slDiv'))
		{var slD = $('slDiv').getPosition($('leftEdge'));
		 $('slDiv').style.height = (winH - 35) - slD.y + 'px';}
		 
	if ($('detailLoop'))
	  {var ger = $('detailLoop').getPosition(); 

		 var nh = winH - ger.y - 80;	  
	   var dlw = winW - ger.x - 55;
    
     if (Browser.Engine.trident)
      {dlw = dlw - 20;}
			
		if (dlw > 500)
			{dlw = 500;}
  			  
		 $('detailLoop').setStyles({top: '10px'});
     $('detailLoop').setStyles({width: dlw +'px', height: nh+'px'});
     $('comm').setStyles({width: dlw +'px'});
		}
			 
	if ($('basicinfo'))
	  {var ger = $('basicinfo').getPosition(); 
		 var nh = winH - ger.y - 80;	   
		 $('basicinfo').setStyles({height: nh +'px'});}
		 
	if ($('whatsincluded'))
	  {var ger = $('whatsincluded').getPosition(); 
		 var nh = winH - ger.y - 50;	   
		 $('whatsincluded').setStyles({height: nh +'px'});}
		 
	if ($('mainIIP')) {
		if (iip) {iip.refreshWindows();}}
		
	if ($('mainIIP') && $('mainCom'))
		{doMorphs.delay(200);}
		
	var allParas = $(document.body).getElements('div.newTitle');

  allParas.each(function(item, index){
		var tb = item.firstChild;
		var cs = $(tb).getSize();
		$(item).setStyles({height: cs.y + 2 +'px'});
		});

	}
	

function basicRefreshEdit () {	
	$('page').style.display = 'none';
  var winD = Window.getSize();
	var winW = winD.x, winH = winD.y;

	if (Browser.Engine.trident)
		{var sb = 20;} // Allows for the thickness of the scroll bar
	else
		{var sb = 0;}
	
	$('leftEdge').style.height = (winH) + 'px';
	$('rightEdge').style.height = (winH) + 'px';
	$('MainMenu').style.height = (winH - 150) + 'px';

	$('leftPanel').style.display = 'none';

	if ($('logo'))	
		{var tp = $('logo').parentNode; //logo pops up if not removed.
 	 	 tp.removeChild($('logo'));}

	var myRP = document.getElementById('rightPanel');
	var myRT = document.getElementById('rightTitle');

	var uw =  (winW - sb - 55 - 55);

 	myRT.style.width 	= uw + 'px';

 	myRP.style.left = 50 + 'px';
	myRT.style.left = 50 + 'px';

	myRP.style.top = 142 + 'px';
 	myRP.style.width 	= uw + 'px';
	myRP.style.height = (winH - 142 - 15) + 'px';

	$('toplinks').style.width = (winW + sb - 85) + 'px';

	if (document.getElementById('imframe'))
		{var myFR = document.getElementById('imframe');
  	myFR.style.width 	= (winW - 310 - sb - 45) + 'px';
		myFR.style.height = (winH - 140 - 15) + 'px';		
		myFR.src = myFR.src;}

	$('page').style.display = 'block';	
	}

	function clearForm() {
		var form = document.forms['page_details'];
    var formKids = form.childNodes;
    var i, elm;
    
  	for( i=0, elm; elm=formKids[i++]; )
	   	{if (elm.value)
			  {elm.value ='';}}
		}

	function doForm(which, what) {
		clearForm();

    if (which == "newpage")
      {document.forms['page_details'].action = what;}		
    else if (which && what)
			{document.forms['page_details'][which].value = what;}

		popup(1);
		document.forms['page_details'].submit();
		}

	function udForm(which, what) {	

    if (which == "newpage")
      {document.forms['page_details'].action = what;}		
    else if (which && what)
			{document.forms['page_details'][which].value = what;}
		}

	function goForm() {
		popup(1);
		document.forms['page_details'].submit();
		}	

function posDiv (id, l, t, w, h)
	{
	if ($(id))
		{
		if (l) {$(id).style.left = l;}
		if (t) {$(id).style.top = t;}
		if (w) {$(id).style.width = w;}
		if (h) {$(id).style.height = h;}
		}
	else
		{alert ('Sorry '+id+' is missing');}
	}

function mkAccordian (hei)
	{
	var thisAc = new Accordion($('accordion'), 'h3.toggler', 'div.element', {
		opacity: false,
		fixedHeight: hei +'px',
			onActive: function(toggler, element){
				toggler.setStyle('color', '#41464D');
			},
			onBackground: function(toggler, element){
				toggler.setStyle('color', '#a7a6a4');
			}
		});

	return  (thisAc);
	}


//function buildLDSub (rows, cols, IDa, IDb, thisSel, thisTxt, readOnly, other)
function buildLDSub (hei, wid, thisTag, thisTagNo, thisArr, readOnly, other, noadd)
  {
	var tt = thisTag+"["+thisTagNo+"]";
	var tt3 = thisTag+"["+thisTagNo+"]"+"[3]["+NoT[thisTag]+"]";
	var tt4 = thisTag+"["+thisTagNo+"]"+"[4]["+NoT[thisTag]+"]";

	var cells = new Array;  

	var ta = makeInput ('textarea', tt3+"[O]", thisArr["3"]["O"], hei, wid, readOnly);
  	cells[0] = buildCell (ta, wid);
	var lan = array2dropdown (tt4+"[O]", mylanguage, thisArr["4"]["O"], '', readOnly);
  	cells[1] = buildCell (lan, '100px', 'padt2');

	cells[2] = buildCell (makeInput ('hidden', tt3+"[ID]", thisArr["3"]["ID"], 0, 0, 0), '75px', 'padt2');
	cells[2].appendChild(makeInput ('hidden', tt3+"[S]", thisArr["3"]["S"], 0, 0, 0));
	cells[2].appendChild(makeInput ('hidden', tt3+"[P]", thisArr["3"]["P"], 0, 0, 0));
	cells[2].appendChild(makeInput ('hidden', tt4+"[ID]", thisArr["4"]["ID"], 0, 0, 0));
	cells[2].appendChild(makeInput ('hidden', tt4+"[S]", thisArr["4"]["S"], 0, 0, 0));
	cells[2].appendChild(makeInput ('hidden', tt4+"[P]", thisArr["4"]["P"], 0, 0, 0));

	if (readOnly)
		{cells[3] =  buildCell (makeInput ('hidden', tt4+"[O]", thisArr["4"]["O"], 0, 0, 0));}
	else
		{
    if (noadd) {}
    else if (other)
     {cells[3] =  buildCell (removeRow(), '75px', 'padt2');}
    else
     {cells[3] =  buildCell (addTranslation("ADD", wid, hei, thisTag, thisTagNo), '75px', 'padt2');}
    }
 
	NoT[thisTag]++;

  return (buildRow (cells));
  }

function addTranslation (txt, wid , hei, thisTag, thisTagNo)
	{
	var ft = new Element("font", {
    'class': 'info_link',
    'events': {
        'click': function(){
 					var tcell = $(this).parentNode;
				 	var trow = $(tcell).parentNode;
 					var ttblB = $(trow).parentNode;  
    
					var passVals = {"3":{"ID":"","S":"","P":"","O":""}, 
												  "4":{"ID":"","S":"","P":"","O":""}};
				  var row = buildLDSub (hei, wid, thisTag, thisTagNo, passVals, 0, 1);
					$(ttblB).appendChild(row);}
    	}});

	var ftv = document.createTextNode(txt);
	$(ft).appendChild(ftv);

	return (ft);
	}


function buildTxtRow(thisTag, thisArray, thisVals, readOnly) 
	{
	var par = $(thisTag);
  
	// set hei and wid for the inputs
	var winD = Window.getSize();
	var winW = winD.x;
	if (Browser.Engine.trident) {var sb = 20;} // Allows for the thickness of the scroll bar
	else {var sb = 0;}	
  var rest = winW - sb - 625;  
	var wid = rest - 205;
  var hei = 30;
  if (wid < 50) {wid = 150;}
	if (thisTag == 'txt') {hei = 80;}
	if (thisTag == 'con') {hei = 160;}

	//If no values are passed define empty quad set of triples
	if (!thisVals["1"])
		{thisVals = {
				"1":{"ID":"","S":"","P":"","O":""}, 
				"2":{"ID":"","S":"","P":"","O":""}, 
				"3":{"0":{"ID":"","S":"","P":"","O":""}}, 
				"4":{"0":{"ID":"","S":"","P":"","O":""}}};}
  
	//Construct inputs for triples 1 and 2
	var cells = new Array;
	var tt = thisTag+"["+No[thisTag]+"]";

  var fp = 
		array2dropdown (tt+"[1][P]", thisArray, thisVals["1"]["P"], '', readOnly);
  	cells[0] = buildCell (fp, '215px', 'padt3');

	cells[1] = buildCell (makeInput ('hidden', tt+"[1][ID]", thisVals["1"]["ID"], 0, 0), '5px', '');
	cells[1].appendChild(makeInput ('hidden', tt+"[1][S]", thisVals["1"]["S"], 0, 0));
	cells[1].appendChild(makeInput ('hidden', tt+"[1][O]", thisVals["1"]["O"], 0, 0));

	cells[1].appendChild(makeInput ('hidden', tt+"[2][ID]", thisVals["2"]["ID"], 0, 0));
	cells[1].appendChild(makeInput ('hidden', tt+"[2][S]", thisVals["2"]["S"], 0, 0));
	cells[1].appendChild(makeInput ('hidden', tt+"[2][P]", thisVals["2"]["P"], 0, 0));
	cells[1].appendChild(makeInput ('hidden', tt+"[2][O]", thisVals["2"]["O"], 0, 0));
	
  var trows = new Array;

  var j=0;
	var fst = 0;
  for(var id in thisVals["3"]) 
		{
		if(typeof thisVals["3"][id] == 'object')
      {
			var passVals = {"3":thisVals["3"][id], "4":thisVals["4"][id]};
			trows[j] = buildLDSub (hei, wid, thisTag, No[thisTag], passVals, readOnly, fst);
			fst = 1;
      j++;
			}
		}

  var labDetails = buildTable(trows, 'language');		
  cells[2] = buildCell (labDetails, rest+'px');

	if (readOnly)
		{var whichLabH = makeInput ('hidden', thisTag+"["+No[thisTag]+"]"+'[P]', 
        thisVals["P"], 0, 0, 0);
     cells[3] = buildCell (whichLabH, '45px');}
	else
		{
    if (thisTag != 'con')
      {var remRow = removeRow();
       cells[3] = buildCell (remRow, '45px', 'alr');}
    else
      {cells[3] = buildCell ('', '45px', 'alr');}
    }
  
  var rows = new Array;
	rows[0] = buildRow (cells);
  
  par.appendChild(buildTable(rows));

	No[thisTag]++;
  }
	
	
function buildFileUploadRow(thisTag) 
	{
	var par = $(thisTag);
  
	// set hei and wid for the inputs
	var winD = Window.getSize();
	var winW = winD.x;
	if (Browser.Engine.trident) {var sb = 20;} // Allows for the thickness of the scroll bar
	else {var sb = 0;}	
  var rest = winW - sb - 625;  
	var wid = rest - 205;
  var hei = 80;
  if (wid < 50) {wid = 150;}

	//Construct inputs for triples 1 and 2
	var cells = new Array;
	
	cells[0] = buildCell (makeFileUpload ('uploadedfile'));
	  
  var rows = new Array;
	rows[0] = buildRow (cells);  
  par.appendChild(buildTable(rows));

	//No[thisTag]++;
  }

//buildTxtRowN('popInfoNew', thisLProps, txtInput.value, type_id, idInput.id, txtInput.id);
function buildTxtRowN(thisTag, thisArray, thisVal, type) 
	{
  var par = $(thisTag);
  var winD = par.getSize();
	var winW = winD.x;

	if (Browser.Engine.trident) {var sb = 20;}
	else {var sb = 0;}	
	var rest = winW - 185 - 45 -sb;
  var wid = rest - 165;
  var hei = 30;
  if (wid < 50) {wid = 150;}
  
	var cells = new Array;
  var whichLab = array2dropdown ('newProp', thisArray, '', '', '');
  cells[0] = buildCell (whichLab, '185px', 'padt3');

	var thista = makeInput ('textarea', 'newLabel', thisVal, hei, wid, 0);
	var thislan = array2dropdown ('newLan', mylanguage, 1, '', 0);	

  var cellsB = new Array;
	  cellsB[0] = buildCell (thista, wid);
	  cellsB[1] = buildCell (thislan, '100px', 'padt2');
	  cellsB[2] = buildCell ('', '75px', 'padt2');

  var trows = new Array;
	 	trows[0] = buildRow (cellsB);
    
  var labDetails = buildTable(trows, 'language');
  cells[1] = buildCell (labDetails, rest+'px');

	var typeID  = makeInput ('hidden', 'newType', type, 0, 0);
  cells[2] = buildCell (typeID, '45px', 'alr');
  
  var rows = new Array;
	rows[0] = buildRow (cells);
  
  par.appendChild(buildTable(rows));
  }

function updateRange ()
	{	
	var ft = new Element("font", {
      'class': 'info_link'
      });
      
	ft.addEventListener('onchange',function (e) {
		var val = this.value;
	 	var Ccell = this.parentNode;
 		var Rcell = (Ccell.nextSibling).nextSibling;
		var Rsel = Rcell.firstChild;

		while (Rsel.firstChild) 
		 {Rsel.removeChild(Rsel.firstChild);};

		for (keyVar in myPTArr[val])
			{var opt = document.createElement("option"); 
			 var optt=document.createTextNode(thisArray[keyVar]);
			 opt.appendChild(optt);
			 opt.setAttribute("value", keyVar);
			 Rsel.appendChild(opt);}
		},false);
	var ftv = document.createTextNode("Delete");
	ft.appendChild(ftv);

	return (ft);
	}

function checkThingEvent ()
	{
	var ft = new Element("font", {
  	'class': 'info_link',
		'events': {
	    'click': function(){
	 	    var Dcell = this.parentNode;
        var inpt = Dcell.firstChild;
 		    var Rcell = Dcell.previousSibling;
				var IDCell = Rcell.previousSibling;
				var IDInput = IDCell.childNodes[2];
	      var Ccell = IDCell.previousSibling;
        var val = Ccell.firstChild.value;
        var valR = Rcell.firstChild.value;
        var thing = myPTArr[val][valR];
		
				popup ();
				thingFindPopup (valR, inpt, IDInput, thing);
				}}},false);

	var ftv = document.createTextNode("CHECK");
	$(ft).appendChild(ftv);

	return (ft);
	}


function thingFindPopup_sub1 (txt1, txt2, idInput, txtInput)
	{
	var cells = new Array;
	
	var pt = new Element("p", {'class': 'ptitle'},false);
	var ptt = document.createTextNode(txt1);
		$(pt).appendChild(ptt);

	if (txt2 == 'enter')
		{var cA = new Element("a", {'class': 'info_link', 'events': {'click': function(){
			thingNewTriples (idInput, txtInput, $('newType').value, $('newProp').value, 
				$('newLabel').value, $('newLan').value);
			}}},false);}
	else
		{var cA = new Element("a", {'class': 'info_link', 'events': {'click': function(){
			popup();}}},false);}

	var cAt = document.createTextNode(txt2);
		$(cA).appendChild(cAt);

	cells[0] = buildCell (pt, '', 'padt3');
	cells[1] = buildCell (cA, '45px', 'alr');
	
	var rows = new Array;
	rows[0] = buildRow (cells);
 
	return (buildTable(rows));
	}


function thingNewTriples (idInput, txtInput, type, pre, sub, lan)
	{
	var search_path = "ajax.php?type_id="+type+"&pre="+pre+"&sub="+sub+"&lan="+lan;

	searchRequest = new Request( 
		{
		method: 'get',
		url: search_path,
		autoCancel: true, 
		async:false,  
    onRequest: function() {}, 
		onFailure: function() {}, 
    onComplete: function(response) {
			eval (response); //returns newID
			$(idInput).value = newID;
			$(txtInput).value = sub;
			popup();
			} 			  
    });

	searchRequest.send();
	}

function exTh_sub1 (val1, val2, idInput, txtInput)
	{
	var ft = new Element("font", {
	 	'class': 'info_link',
		'events': {
	   'click': function(){
			$(idInput).value = val1;
			$(txtInput).value = val2;
			popup ();
		}}},false);

	return (ft);
	}

function existingThings (thing, thisList, thisLProps, idInput, txtInput)
	{
	var rows = new Array;
	var cno = 0;

	for (keyVar in thisList)
		 {
			var cells = new Array;
		
			var ft1 = exTh_sub1 (keyVar, thisList[keyVar][1], idInput, txtInput);
			var ft1v = document.createTextNode("Use");
			$(ft1).appendChild(ft1v);

			var ft2 = new Element("font", {
		  	'class': ''},false);
			var ft2v = document.createTextNode(thing);
				$(ft2).appendChild(ft2v);

			var ft3 = new Element("font", {
		  	'class': ''},false);
			var ft3v = document.createTextNode(thisLProps[thisList[keyVar][0]]);
				$(ft3).appendChild(ft3v);

			var ft4 = new Element("font", {
		  	'class': ''},false);
			var ft4v = document.createTextNode(thisList[keyVar][1]);
				$(ft4).appendChild(ft4v);
			
			cells[0] = buildCell (ft1, '', 'padt3');
			cells[1] = buildCell (ft2, '', 'padt3');
			cells[2] = buildCell (ft3, '', 'padt3');
			cells[3] = buildCell (ft4, '', 'padt3');
			rows[cno] = buildRow (cells);
			cno++;
			}

	return (buildTable(rows));	
	}


function thingEditPopup (thingID)
	{	  
	searchRequest = new Request( 
		{
    method: 'post',
    url: 'ajax.php',
    data: {'thing_id':thingID, 'which':'thingForm'},
		autoCancel: true, 
		async:false,  
    onRequest: function() {}, 
		onFailure: function() {}, 
    onComplete: function(response) {
			eval (response); 
		
	 		var winD = $('popupContents').getSize();
			var winH = winD.y;
		  var lh = winH - 40 - 40 - 100;

			var d1 = new Element("div", {'class': 'popInfo'},false);
		  	d1.setStyle('height', '40px');
				d1.injectInside( 'popupContents' );
			var d2 = new Element("div", {'class': 'popInfo'},false);
		 		d2.setStyle('height', lh +'px');
				d2.injectInside( 'popupContents' );
			var d3 = new Element("div", {'class': 'popInfo'},false);
		  	d3.setStyle('height', '40px');
				d3.injectInside( 'popupContents' );
			var d4 = new Element("div", {'class': 'popInfo', 'id': 'popInfoNew'},false);
			  d4.setStyle('height', '50px');
				d4.injectInside( 'popupContents' );

		  var tt = thingFindPopup_sub1 (txt, 'cancel');
				$(tt).injectInside( d1 );
			} 			  
    });

	searchRequest.send();
	}

function thingFindPopup (type_id, txtInput, idInput, thing)
	{
	var search_path = "ajax.php?type_id="+type_id+"&str="+txtInput.value;
	
	searchRequest = new Request( 
		{
		method: 'get',
		url: search_path,
		autoCancel: true, 
		async:false,  
    onRequest: function() {}, 
		onFailure: function() {}, 
    onComplete: function(response) {
			eval (response); 
			//list put into array thisList
			//current LProps put into array thisLProps

      if (txtInput.value)
        {var txt = "Existing "+thing+" instances that match : '"+txtInput.value+"'";}
      else
        {var txt = "Current "+thing+" instances in the system:";}
	 		var winD = $('popupContents').getSize();
			var winH = winD.y;
		  var lh = winH - 40 - 40 - 100;

			var d1 = new Element("div", {'class': 'popInfo'},false);
		  	d1.setStyle('height', '40px');
				d1.injectInside( 'popupContents' );
			var d2 = new Element("div", {'class': 'popInfo'},false);
		 		d2.setStyle('height', lh +'px');
				d2.injectInside( 'popupContents' );
			var d3 = new Element("div", {'class': 'popInfo'},false);
		  	d3.setStyle('height', '40px');
				d3.injectInside( 'popupContents' );
			var d4 = new Element("div", {'class': 'popInfo', 'id': 'popInfoNew'},false);
			  d4.setStyle('height', '50px');
				d4.injectInside( 'popupContents' );

		  var tt = thingFindPopup_sub1 (txt, 'cancel');
				$(tt).injectInside( d1 );

      if (listCount)
        {var ft2 = existingThings (thing, thisList, thisLProps, idInput.id, txtInput.id);
				  $(ft2).injectInside( d2 );}

			var tt3 = thingFindPopup_sub1 ('Create new: '+thing, 'enter', idInput.id, txtInput.id);
				$(tt3).injectInside( d3 );

		  buildTxtRowN('popInfoNew', thisLProps, txtInput.value, type_id);
			} 			  
    });

	searchRequest.send();
	}


function buildRefRow(thisTag, thisArray, thisVals, readOnly, notab) 
	{
	var par = $(thisTag);
 	var winD = Window.getSize();
	var winW = winD.x;	
	if (Browser.Engine.trident) {var sb = 20;} // Allows for the thickness of the scroll bar
	else {var sb = 0;}
	var wid = winW - sb - 875 - 45;
  if (wid < 50) {wid = 150;}

	if (!thisVals["1"])
		{thisVals = {
				"1":{"ID":"","S":"","P":"","O":""}, 
				"2":{"R":"","V":""}};}
	if (!thisVals["2"])
		{thisVals["2"] = {"R":"","V":""};}

  var cells = new Array;

	if (thisTag.tagName == 'TBODY')
		{var tt = "ref["+No['ref']+"]";}
	else
		{var tt = thisTag+"["+No[thisTag]+"]";}

	var whichRef = array2dropdown (tt+"[1][P]", thisArray, thisVals["1"]["P"], thisTag, readOnly);

	if (!thisVals["1"]["P"])
		{var fopt = whichRef.firstChild;
		 thisVals["1"]["P"] = fopt.value;
		}
	
  cells[0] = buildCell (whichRef, '150px', 'padt3');

  var h1  = makeInput ('hidden', tt+"[1][ID]", thisVals["1"]["ID"], 0, 0);
  	cells[1] = buildCell (h1, '5px');
  var h2  = makeInput ('hidden', tt+"[1][S]", thisVals["1"]["S"], 0, 0);
		cells[1].appendChild(h2);

  var c2w = "245px";
  
  if (myCL[thisVals["1"]["P"]])
    {
		var range = array2dropdown (tt+"[1][O]", myPTArr[thisVals["1"]["P"]], 
	    thisVals["1"]["O"], 'range', readOnly);
	  cells[2] = buildCell (range, c2w, 'padt3');
		cells[3] = buildCell ('', '', 'padt3');
	  var h3  = makeInput ('hidden', tt+"[2][V]", thisVals["2"]["V"], 0, 0);
			cells[1].appendChild(h3);
	  var h4  = makeInput ('hidden', tt+"[2][R]", thisVals["2"]["R"], 0, 0);
			cells[1].appendChild(h4);
		}
	else if (myPTArr[thisVals["1"]["P"]][62])
    {
		var range = array2dropdown (tt+"[2][R]", myPTArr[thisVals["1"]["P"]], 
	    thisVals["2"]["R"], 'range', readOnly);
	  cells[2] = buildCell (range, c2w, 'padt3');

		var value  = makeInput ('text', tt+"[1][O]", thisVals["1"]["O"], wid, 0);
		cells[3] = buildCell (value, '', 'padt3');
	  var h3  = makeInput ('hidden', tt+"[2][V]", thisVals["2"]["V"], 0, 0);
			cells[1].appendChild(h3);
		}
	else
		{
	  var h3  = makeInput ('hidden', tt+"[1][O]", thisVals["1"]["O"], 0, 0);
			cells[1].appendChild(h3);

		range = array2dropdown (tt+"[2][R]", myPTArr[thisVals["1"]["P"]], 
    	thisVals["2"]["R"], 'range', readOnly);
	  cells[2] = buildCell (range, c2w, 'padt3');

		if (!thisVals["2"]["R"])
			{var sopt = range.firstChild;
			 thisVals["2"]["R"] = sopt.value;
			}

  	if (!thisVals["2"]["V"])
			{thisVals["2"]["V"] = ''}

    var value  = makeInput ('text',tt+"[2][V]", thisVals["2"]["V"], wid, 0);
			cells[3] = buildCell (value, '', 'padt3');
		var ft = checkThingEvent ();
			cells[3].appendChild(ft);
		}

	if (readOnly)
		{var whichRefH = makeInput ('hidden', tt+"[1][P]", thisVals["1"]["P"], 0, 0, 0);
     cells[4] = buildCell (whichRefH, '45px');}
	else
		{var remRow = removeRow();
     cells[4] = buildCell (remRow, '45px', 'alr');}
  
  var rows = new Array;
	rows[0] = buildRow (cells);
  
	if (notab)
		{par.appendChild(rows[0]);}
	else
		{par.appendChild(buildTable(rows));}

	if (thisTag.tagName == 'TBODY')
		{No['ref']++;}
	else
		{No[thisTag]++;}
  }

function makeInput (type, id, value, noA, noB, readOnly)
	{
	if (type == 'textarea')
		{
		var thisInput = document.createElement("textarea");
		$(thisInput).setStyle("height", noA + 'px');
		$(thisInput).setStyle("width", noB + 'px');
		var theText = document.createTextNode(value);
  	thisInput.appendChild(theText);
		}
	else if (type == 'checkbox')
		{
		var thisInput = document.createElement("input");
		$(thisInput).setAttribute("type", type);
    if (value)
      {$(thisInput).setAttribute("CHECKED", true);}
		}
	else 
		{
		var thisInput = document.createElement("input");
		$(thisInput).setAttribute("type", type);
		$(thisInput).setStyle("width", noA + 'px');
		//$(thisInput).setAttribute("size", noA);
		$(thisInput).setAttribute("max", noB);
		$(thisInput).setAttribute("value", value);
		}

	//alert (id);
	$(thisInput).setAttribute("id", id);
	$(thisInput).setAttribute("name", id);

	if (readOnly)
		{$(thisInput).setAttribute("readonly", "READONLY");}

	return (thisInput);
	}

function makeFileUpload (name)
	{
  var thisDiv = new Element("div", {'class': ''});
  var thisDivUL = new Element("div", {'id': 'fup_'+name, 'class': ''});
  var thisDivEX = new Element("div", {'id': 'ex_'+name, 'class': ''});
	
	var thisInput = document.createElement("input");
	$(thisInput).setAttribute("type", 'hidden');
	$(thisInput).setAttribute("name", 'MAX_FILE_SIZE');
	$(thisInput).setAttribute("value", '10000000000');
	
	$(thisDivUL).appendChild(thisInput); 
	
	thisInput = document.createElement("input");
	$(thisInput).setAttribute("type", 'file');
	$(thisInput).setAttribute("name", name);
	
	$(thisDivUL).appendChild(thisInput);
	
	var br = document.createElement("br");	
	var ph = false;
	if (subpage == 25)
		{//var ft1 = buildFont ('External Image (Need to enter pyramid server and pyramid(path)): ', '', 'cls', '');
		 var ft1 = buildTickbox ('External Image (Need to enter pyramid server and pyramid(path)): ', 'externalImage', '', '');
		 //thisInput = makeInput ("checkbox", 'externalImage', '', '', '', '');
		 ph = buildTickbox ('Place holder image (Entering record but image file not yet available): ', 'placeHolder', '', '');
		 //thisInput_ph = makeInput ("checkbox", 'placeHolder', '', '', '', '');
		 }
	else
		{//var ft1 = buildFont ('External File (Need to enter full web path, web server, and add a filename & identifier): ', '', 'cls', '');
		 var ft1 = buildTickbox ('External File (Need to enter full web path, web server, and add a filename & identifier): ', 'externalImage', '', '');
		 //thisInput = makeInput ("checkbox", 'externalFile', '', '', '', '');
		 }
	
	var thisInput = $(ft1).firstChild.firstChild.firstChild.firstChild.nextSibling.firstChild;

	$(thisInput).addEvent('change', function(event){
		if (this.checked)
			{$('fup_'+name).setStyle("display", 'none');}
		else
			{$('fup_'+name).setStyle("display", 'block');}
    });
	
	$(thisDivEX).appendChild(ft1);
	//$(thisDivEX).appendChild(thisInput);
	
	if (ph)
		{$(thisDivEX).appendChild(ph);}
	
	$(thisDiv).appendChild(thisDivUL);
	$(thisDiv).appendChild(thisDivEX);

	return (thisDiv);
	}

function makePyrThumb (id, path, width, file, server)
	{	
	var thisDiv = new Element("div", {
    'class': 'tt'
    });
	
	var thisImg = document.createElement("img");
	$(thisImg).setStyle("height", 'auto');
	$(thisImg).setStyle("width", width + 'px');

	if (!server)
		{server = "/fcgi-bin/iipsrv.fcgi?";}
		
  //var src = "/fcgi-bin/iipsrv.fcgi?FIF="+path+"&QLT=75&cnt=1&jtl=0,0";
  var src = server+"FIF="+path+"&QLT=75&cnt=1&jtl=0,0";
	$(thisImg).setAttribute("src", src);
	$(thisImg).setAttribute("alt", file);
	
	$(thisImg).setAttribute("id", id);
	$(thisImg).setAttribute("name", id);
	$(thisImg).setStyle('cursor', 'pointer');
		
  $(thisImg).addEvent('click', function(event){
    ppResize (this);});

  $(thisDiv).appendChild(thisImg);   
	var thisSpan = document.createElement("span");
  $(thisSpan).addEvent('click', function(event){
    var theIm = this.parentNode.firstChild;
    //alert (theIm.src);
    ppResize (theIm);
    });
	var thisTxt = document.createTextNode('Click to enlarge image');
  $(thisSpan).appendChild(thisTxt);      
  $(thisDiv).appendChild(thisSpan);      
	return (thisDiv);
	}

function ppResize (thing)
  {
  if( ims = /^(.+QLT=[0-9]+[&]cnt=[0-9]+[&])jtl=[0-9,]+/i.exec($(thing).src))
  {
  var ra = $(thing).height/$(thing).width;
      
  var winWidth = document.getWidth();
  var winHeight = Window.getHeight();
  	  
  var nx = Math.round(winWidth);
  var ny = Math.round(nx * ra);
  	  
  if (ny > (winHeight))
    {ny = Math.round(winHeight);
     nx = Math.round(ny / ra);}
  	     
  var pupsrc = ims[1]+'WID='+nx+'&CVT=JPEG';
  var nthisImg = document.createElement("img");
	$(nthisImg).setAttribute("src", pupsrc);
	$(nthisImg).setAttribute("alt", "Click any where to close image");
      
  nx = Math.round(nx * 0.8);
  ny = Math.round(ny * 0.8);
  var nt = Math.round((winHeight-ny)/2);
  var nl = Math.round((winWidth-nx)/2);
  	    
  $(nthisImg).setStyle("width", nx + 'px');
	$(nthisImg).setStyle("height", 'auto');
  $(nthisImg).addEvent('click', function(event){
    popup();});
        	    
  popup();      
      
	$('popupContents').setProperty('class', 'tt');
	$('popupContents').setStyle('cursor', 'pointer');
	$('popupContents').setStyle('left', nl + 'px');
	$('popupContents').setStyle('top', nt + 'px');    
	$('popupContents').setStyle('width', 'auto');
	$('popupContents').setStyle('height', 'auto');
  $('popupContents').appendChild(nthisImg);   
	
	var thisSpan = document.createElement("span");
  $(thisSpan).addEvent('click', function(event){
    popup();});
	var thisTxt = document.createTextNode('Click any where to close image');
  $(thisSpan).appendChild(thisTxt);      
  $('popupContents').appendChild(thisSpan);  
  }}
  

function ppWait (message)
  {
  var winWidth = document.getWidth();
  var winHeight = Window.getHeight();
       	    
  popup(1);   
  //alert ('just called popup');   
      
	$('popupContents').setProperty('class', 'tt');   
	$('popupContents').setStyle('width', 'auto');
	$('popupContents').setStyle('height', 'auto');

	$('popupBack').setStyle('opacity', '0.75');
	$('popupBack').setStyle('filter', 'alpha(opacity=75)');
	$('popupBack').setStyle('text-align', 'center');
	
	var pt = new Element("p", {'class': 'pWait'},false);
	var ptt = document.createTextNode(message);
		$(pt).appendChild(ptt);
		
	$('popupBack').appendChild(pt);
	
  //var ppcWidth = $(pt).getWidth();
  //var ppcHeight = $(pt).getHeight(); 
  //var x = (winWidth / 2) - (ppcWidth / 2);
  //var y = (winHeight / 2) - (ppcHeight / 2); 
	//$(pt).setStyle('float', 'middle');     
  }

function removeRow ()
	{
	
	var ft = new Element("font", {
    'class': 'info_link',
    'events': {

        'click': function(){
 					var tcell = this.parentNode;
				 	var trow = tcell.parentNode;
				 	var ttblB = trow.parentNode;

					var match;
          var tag;

          if (match = /([a-zA-Z]+)(\[[0-9]+\])(\[[0-9]+\])(\[.\])$/i.exec(trow.firstChild.firstChild.id )) 
            {tag = match[1]+match[2]+match[3];}
          else  
            {match = /([a-zA-Z]+)(\[[0-9]+\])(\[[0-9]+\])(\[[0-9]+\])(\[.\])$/i.exec(trow.firstChild.firstChild.id );
             tag = match[1]+match[2]+match[3]+match[4];}

          var which = match[1];
					var trip = {
						"ID":eval('$(\''+tag+'[ID]\').value'),
						"S":eval('$(\''+tag+'[S]\').value'),
						"P":eval('$(\''+tag+'[P]\').value'),
						"O":eval('$(\''+tag+'[O]\').value')};
           
          var getVars = "id="+trip["ID"]+"&s="+trip["S"]+"&p="+trip["P"]+"&o="+trip["O"];

          if (match[3] != "[1]")
            {
            var ptag = match[1]+match[2]+"[2]";
					  var ptrip = {
						  "ID":eval('$(\''+ptag+'[ID]\').value'),
  						"S":eval('$(\''+ptag+'[S]\').value'),
  						"P":eval('$(\''+ptag+'[P]\').value'),
	  					"O":eval('$(\''+ptag+'[O]\').value')};

            getVars = getVars + "&pid="+ptrip["ID"]+"&ps="+ptrip["S"]+"&pp="+
              ptrip["P"]+"&po="+ptrip["O"];
            }
				
          if (trip["ID"])
            {
					  if (which == "ref")
						  {var answer = confirm('Are you sure you want to delete this link ?');
	  					 getVars = getVars + "&delete="+which;}
	  				else
						  {
				  		if (trip["P"] == 58)
					  		{var answer = confirm('Are you sure you want to delete this text ?');
					  		 getVars = getVars + "&delete="+which+"&value=1";}
					  	else
					  		{
					  		if (which == "lab")
					  			{var rw_mat = /has (.+)$/i.exec(myLProps[trip["P"]]);
					  			 var answer = confirm('Are you sure you want to delete this '+
                    rw_mat[1]+'?');}  
					  		else //if (which == "txt")
					  			{var rw_mat = /has (.+)$/i.exec(myCProps[trip["P"]]);
					  			 var answer = confirm('Are you sure you want to delete this '+
                    rw_mat[1]+'?');}

					  		getVars = getVars + "&delete="+which;
                }
              }

            if (answer)
						  {
						  var search_path = "ajax.php?"+getVars;
						  //openWindow (search_path);
						  searchRequest = new Request( 
						  	{
						  	method: 'get',
						  	url: search_path,
						  	autoCancel: true, 
						  	async:false,  
						    onRequest: function() {}, 
						  	onFailure: function() {}, 
						    onComplete: function(response) {
						  	  //alert ('Delete Done');
						  	  $(ttblB).removeChild(trow);
						  	} 			  
						  });

						  searchRequest.send();
						  }
					  }
          else
            {$(ttblB).removeChild(trow);}
        }
    	}});

	var ftv = document.createTextNode("Delete");
	$(ft).appendChild(ftv);

	return (ft);
	}


function array2dropdown (thisID, thisArray, selected, och, ro)
	{
	var dropDown = new Element("select", {
    'size': 0,
    'id': thisID,
    'name': thisID});

		if (ro == 2)
			{dropDown.setAttribute("disabled", 1);}
		else if (ro)
			{dropDown.setAttribute("disabled", 1);}
 		else if (och)
			{
			if (och == 'ref' || och.tagName == 'TBODY')
				{
				//$(dropDown).addEventListener('change',function (e) {
				var dropDown = $(dropDown).set({    
					'events': {
						'change': function(e){

					var val = this.value;
				 	var thisCell = this.parentNode;
				 	var thisRow = thisCell.parentNode;
				 	var thisTBody = thisRow.parentNode;
				 	var thisTable = thisTBody.parentNode;
				 	var thisPCell = thisTable.parentNode;

          while (thisTBody.firstChild) 
					 {thisTBody.removeChild(thisTBody.firstChild);};

          var thisVals = {
    				"1":{"ID":"","S":"","P":val,"O":""}, 
				    "2":{"R":"","V":""}};

          buildRefRow(thisTBody, myOProps, thisVals, 0, true); 
					}}},false);
				}

			if (och == 'sp')
				{
				var dropDown = $(dropDown).set({    
					'events': {
						'change': function(e){
            if($('lcdd'))
              {udForm('category', $('lcdd').value);}
            udForm('object', $(this).value);
            udForm('object_code', '');
            udForm('start', '0');
            goForm();
					}}},false);
				}
			if (och == 'sc')
				{
				var dropDown = $(dropDown).set({    
					'events': {
						'change': function(e){
            udForm('object', $('lpdd').value);
            udForm('category', $(this).value);
            udForm('start', '0');
            goForm();
					}}},false);
				}
			if (och == 'range')
				{
/*
				dropDown.addEventListener('change',function (e) {
					var val = this.value;
				 	var Rcell = this.parentNode;
			 		var Dcell = Rcell.nextSibling;
          var inpt = Dcell.firstChild;

          if (val == 62) 
						{}
          else if (myCL[val]) 
						{}
					else //thing link
						{alert (inpt.value);
            inpt.setAttribute("value", 'ThindID: '+val);}
					},false);
*/
				}
/*
			dropDown.addEventListener('change',function (e) {

			 	var tcell = this.parentNode;
			 	var trow = tcell.parentNode;
				var cell2 = trow.childNodes[1];
				var dd = cell2.childNodes[0];
				var cell3 = trow.childNodes[2];
				var inpt = cell3.childNodes[0];		
				var cell4 = trow.childNodes[3];
				var inpt2 = cell4.childNodes[0];			
				 	
				var match = /.+[\[]([0-9])+[\]]/i.exec(dd.name);
				var tno = match[1];

				if (this.value == 10)
					{
					cell3.removeChild(inpt);
					inpt = array2dropdown ("ref["+tno+"]", mycategory, 38);
					cell3.appendChild(inpt);
					}
				else if (inpt.type != 'text')
					{
					cell3.removeChild(inpt);
					inpt = makeInput ('text', "ref["+tno+"]", '', 30, 75);
					cell3.appendChild(inpt);	
					inpt = makeInput ('text', "refO["+tno+"]", '', 1, 3);
					cell4.appendChild(inpt);	
					}
				else {}

				dd.options[0].selected = "SELECTED";
				dd.setAttribute("disabled", 1);

				if (this.value == 5)
					{
					var currentTime = new Date();
					var month = currentTime.getMonth() + 1;
					var day = currentTime.getDate();
					var year = currentTime.getFullYear();
					inpt.value = year+'-'+month+'-'+day;
					}
				else if (this.value == 6 ||this.value == 7)
					{dd.removeAttribute("disabled");
					 dd.options[4].selected = "SELECTED";}
				else
					{inpt.value = '';}

			},false);*/
			}

	for (keyVar in thisArray)
		{
		var opt = document.createElement("option"); 
		var optt=document.createTextNode(thisArray[keyVar]);
		opt.appendChild(optt);
		opt.setAttribute("value", keyVar);
		if (keyVar == selected)
			{opt.setAttribute("selected", "SELECTED");}
		dropDown.appendChild(opt);
		}

	return (dropDown);
	}
	

function array2hidden (formID, thisArray)
	{
	var thisForm = $(formID);

	for (keyVar in thisArray)
		{
		if ($type(thisArray[keyVar]) == "object")
			{
			var objArray = thisArray[keyVar];
				for (keyB in objArray)
					{var hi = makeInput ('hidden', keyVar+'[]', objArray[keyB], 0, 0);
					 thisForm.appendChild(hi);}
			}
		else
			{
			var hi = makeInput ('hidden', keyVar, thisArray[keyVar], 0, 0);
			thisForm.appendChild(hi);
			}
		}
	}

function buildCell(contents, width, cls, cspan, rspan, cid)
  {
  
  if (!cls)
    {cls = 'nocss';}
    
  if (!cid)
    {cid = '';}
    
  if (!width)
    {width = 'auto';}
  if (!cspan)
    {cspan = 1;}
  if (!rspan)
    {rspan = 1;}
    
  var cell = new Element("td", {
    'id': cid,
    'class': cls,
    'colspan': cspan,
    'rowspan': rspan,
    'width': width,
    'valign': 'top'
    });
	
	if (contents) {cell.appendChild(contents);}

  return (cell);  
  }


function buildTickbox (txt, tbid, tcls, dcls)
	{
	if (!dcls)
    {dcls = '';}
	if (!tcls)
    {tcls = 't3';}
			
  var cd = new Element("div", {
      'class': dcls
    });	
  
  var tft = new Element("font", {
    'class': tcls
    });
    
  var tftv = document.createTextNode(txt);
	  tft.appendChild(tftv);
  
  var cb = makeInput ("checkbox", tbid, '', '', '', '');
	
	var cells = new Array;  
  var rows = new Array;
  cells[0] = buildCell (tft, '', 'noWrap', 1, 1);
  cells[1] = buildCell (cb, '100%', '', 1, 1); 
 	rows[0] = buildRow (cells);
	var tbc = buildTable(rows, '');
	
	cd.appendChild(tbc);
	return (cd);
	}
	
function buildFont (ttxt, txt, cls, oc, dcls, nodiv, tcls)
	{
	if (!dcls)
    {dcls = '';}
	if (!tcls)
    {tcls = 't3';}
		
  var cd = new Element("div", {
      'class': dcls
    });
  
  if (ttxt)
    { 
    var tft = new Element("font", {
      'class': tcls
      });
    
    var tftv = document.createTextNode(ttxt);
	  tft.appendChild(tftv);
	  cd.appendChild(tft); 
    }

  if (!cls)
    {cls = 'nocss';}
  if (!oc)
    {oc = '';}
  
  var ft = new Element("font", {
    'class': cls
    });

  //if (oc)
  //  {$(ft).addEventListener('click',function (e) {
  //    eval (oc);},false);}
		
	if (oc)
    {$(ft).addEvent('click',function (e) {
      eval (oc);},false);}

	var ftv = document.createTextNode(txt);
	ft.appendChild(ftv);
	
	if (nodiv)
		{return (ft);}
	else
		{cd.appendChild(ft);
		 return (cd);}
	}
	
function subForm (txt, cls, frm)
	{
  if (!cls)
    {cls = 'nocss';}
    
  var ft = new Element("a", {
    'class': cls,
    'events': {
      'click': function(e){
        var cfrm = eval ('document.'+frm);
        cfrm.submit();}
    }});

	var ftv = document.createTextNode(txt);
	ft.appendChild(ftv);
	return (ft);
	}
	

function postArray (thisArray)
  {
  var cd = document.createElement("div");
  var inpt;
  
  for (keyVar in thisArray)
		{inpt = makeInput ('hidden', keyVar, thisArray[keyVar], 0, 0);
		 cd.appendChild(inpt);}
		 
  return (cd);
  }

function eventButton (text, process, thing_id, target, arr, conformation)
	{
  var cd = document.createElement("div", {
      'class': 'lineup'});      
  
   arr["process"] = process;
  
  if (thing_id)
    {var formName = process + "_" + thing_id;}
  else
    {var formName = "frm_" + process;}
    
  var frm = document.createElement("form", {
      'class': 'lineup'});
    frm.setAttribute("name", formName);
    frm.setAttribute("action", target);
    frm.setAttribute("method", "post");
  var lin = new Element("a", {
      'class': 'info_link'});
  var ltxt = document.createTextNode(text);
	  lin.appendChild(ltxt);
	  frm.appendChild(lin);
  
  if (arr)
    {var harr = postArray (arr);
     frm.appendChild(harr);}
	  
  $(lin).addEvent('click', function(event){
   var thisFrm = $(this).parentNode;
   var thisPro = $(this).nextSibling.firstChild.value;
   
   if (thisPro == "delete")
     {
     var answer = confirm('Are you sure you want to delete this entry');
    
    if (answer)
      {thisFrm.submit();}
     }
  else
    {thisFrm.submit();}
   });
	
	$(frm).addClass('lineup');
	$(cd).setProperty('class','lineup');
	$(cd).appendChild(frm);
	return (cd);
	}
	
function eventButtonAJ (text, process, thing_id, target, arr, conformation)
	{
  var cd = document.createElement("div", {
      'class': 'lineup'});
			      
  //arr["process"] = process;
  
  if (thing_id) {var formName = process + "_" + thing_id;}
  else {var formName = "frm_" + process;}
    
  var frm = document.createElement("form", {
      'class': 'lineup'});
    frm.setAttribute("name", formName);
    frm.setAttribute("action", target);
    frm.setAttribute("method", "post");
  var lin = new Element("a", {
      'class': 'info_link'});
  var ltxt = document.createTextNode(text);
	  lin.appendChild(ltxt);
	  frm.appendChild(lin);
  
  if (arr)
    {var harr = postArray (arr);
     frm.appendChild(harr);}
		 
	var oarr = {"oldprocess":process, "oldID":thing_id};
	frm.appendChild(postArray (oarr));
     
  $(lin).addEvent('click', function(event){
    if (process == 'deleteimage')
      {ppWait ('Deleting Image.');}
    else if (process == 'hideim')
      {ppWait ('Hiding Image.');}
    else if (process == 'showim')
      {ppWait ('Revealing Image.');
       process = 'hideim';}//Code already does reveal, don't need to rewrite
    else if (process == 'delete')
      {ppWait ('Deleting data, please wait.');}
    else
      {ppWait ('Processing Image, once complete you will have to refresh the page to update the image on your screen.');}
    var thisFrm = $(this).parentNode;
    var thisPro = $(this).nextSibling.firstChild.value;
			
    var localRequest = new Request( 
      {
      method: 'post', url: 'ajax.php',			
      data: {'thing_id':thisFrm.oldID.value, 'process':thisFrm.oldprocess.value, 'formName':thisFrm.name},
      encoding:'UTF-8', autoCancel: true, async:false,  
      onRequest: function() {}, onFailure: function() {}, 
      onComplete: function(response) {
        eval(response);}});
   
   if (process == "deleteimage" || process == "delete")
     {
     var answer = confirm('Are you sure you want to delete this entry');
    
    if (answer)
      {localRequest.send();}
		else
			{thisFrm.submit();}
     }
  else
    {localRequest.send();}
   });
	
	$(frm).addClass('lineup');
	$(cd).setProperty('class','lineup');
	$(cd).appendChild(frm);
	return (cd);
	}


function buildForm (id, action)
	{
  var fr = document.createElement("form");
    fr.setAttribute("id", id);
    fr.setAttribute("action", action);

	return (fr);
	}

function buildRow (arr, cls)
  {  
	var cells = arr.length;
  
  if (!cls)
    {cls = 'nocss';}
    
  var row = new Element("tr", {
    'class': cls
    });

  for(var j=0; j<cells; j++) 
		{var cell = arr[j];
		 row.appendChild(cell);}

  return (row);
  }


function buildTable (arr, cls, wid, cid)
	{ 
	var rows = arr.length;

  if (!cls)
    {cls = 'dynam';}
  if (!cid)
    {cid = '';}
    
  var tbl = new Element("table", {
    'class': cls,
    'id': cid
    });
    
	var tblBody = document.createElement("tbody");

  for(var j=0; j<rows; j++) 
		{var row = arr[j];
		 tblBody.appendChild(row);}

	tbl.appendChild(tblBody);  

  if (wid)
    {tbl.setAttribute("width", wid);}
  else
    {tbl.setAttribute("width", "100%");}
	
	return (tbl);
	}

function makeList (str, end)
	{
	var thisArr= [];

	for(var j=str; j<end; j++ )
		{thisArr[j] = j;}

	return (thisArr);
	}

function newLab() 
	{buildTxtRow('lab', myLProps, myVals);}
function newRef() 
	{buildRefRow('ref', myOProps, myVals);}
function newTxt() 
	{buildTxtRow('txt', myCProps, myVals);}

function removeChildrenFromNode(node)
	{
	if(node)
		{while (node.hasChildNodes())
			{node.removeChild(node.firstChild);}}
	}

function toggleDebug ()
  {  
  if ($('debugPage').getStyle('display') == 'none')
    {
		var winWidth = Window.getWidth();
  	var winHeight = Window.getHeight();

		$('debugPage').setStyle('display', 'block');
		$('debugPage').setStyle('width', winWidth + 'px');
		$('debugPage').setStyle('height', winHeight + 'px');
    }
  else
    {$('debugPage').setStyle('display', 'none');}
  } 
	
function getElementsByClassName(strClassName, strTagName, oElm) 
	{
  add2FunctionString ('getElementsByClassName('+strClassName+', '+strTagName+', '+oElm+')', 0, 0, 0); 
  var arrElements = (strTagName == "*" && document.all) ? 
		document.all : oElm.getElementsByTagName(strTagName);

  var arrReturnElements = new Array();
  
	strClassName = strClassName.replace(/\-/g, "\\-");
  
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
  var oElement;
  
	for(var i=0; i<arrElements.length; i++){
  	oElement = arrElements[i];      
    if(oRegExp.test(oElement.className)) {
    	arrReturnElements.push(oElement);}}

	return (arrReturnElements)
	}   

function popup (lock)
	{
	var tips = getElementsByClassName("ctip", "div", document);
	
	for(var i=0; i<tips.length; i++) 
		{tips[i].destroy();}
			 
	if ($('popupContents'))
		{
		$('popup').removeEvents('click');
		removeChildrenFromNode($('popup'));
		$('popup').setStyle('display', 'none');
		}
	else
		{
		//alert ('Display PopUp');
		var winWidth = Window.getWidth();
  	var winHeight = Window.getHeight();

		$('popup').setStyle('display', 'block');
		$('popup').setStyle('width', winWidth + 'px');
		$('popup').setStyle('height', winHeight + 'px');

// Create our main window target div, add our events and inject inside the frame
/*	 var ela = new Element('div', {'id': 'iebug',
      styles: {
				width: winWidth + 'px',
				height: winHeight + 'px'}} );

		var fred = "<!--IFRAME IE HACK to cover SELECT dropdown list boxes. Iframe needs to be resized for window height and width. --><iframe id=\"iebugiframe\" src=\"javascript:'';\" marginwidth=\"0\" marginheight=\"0\" align=\"bottom\" scrolling=\"no\" frameborder=\"0\" style=\"position:absolute; left:0; top:0px; width:"+ winWidth + "px; height:"+ winHeight + "px; display:block; filter:alpha(opacity=0);\" ></iframe>";
*/

 // Create our main window target div, add our events and inject inside the frame
    var el = new Element('div', {'id': 'popupBack'} );
    el.injectInside( 'popup' );
    if(lock){$('popupBack').setStyle('cursor', "wait");}
    else {$('popupBack').addEvent('click', function()
			{popup();});}
    var el2 = new Element('div', {'id': 'popupContents'} );
    el2.injectInside( 'popup' );
		}
	}

function openWindow ( t_href, t_html, debg)
	{
	if (debg)
		{winRef = window.open( t_href+'&debug=1', t_html);}
	else
		{winRef = window.open( t_href, t_html);}
	}

function showDB (obj) 
	{
	var str2 = "";
	var full = false;
	
	if (obj)
		{		
		for ( keyVar in obj ) 
			{
			var m1 = /.+NODE/i.exec(keyVar);
			var m2 = /DOCUMENT_P+./i.exec(keyVar);
	
			if (full)
				{str2 = str2 + keyVar + ' : ' + obj[keyVar]+"<br><br>";}
			else if 
				(
					(
						(typeof obj[keyVar]) == 'number' || 
						(typeof obj[keyVar]) == 'object' || 
						(typeof obj[keyVar]) == 'string'
					)	 
						&& keyVar != 'innerHTML' && !m1 && !m2
				)
				{str2 = str2 + keyVar + ' : ' + obj[keyVar]+"\n";}
			}
		}	

	alert (str2);
	}

function buildImList(thisTag, thisArr)
  {
  for(var id in thisArr) 
		{
		if(typeof thisArr[id] == 'object')
      {
      buildImRow(thisTag, thisArr[id]); 
			}
		}
  }
  
function buildThingList(thisTag, thisArr)
  {
  if (subpage)
  	{
	var varArr = {"process":"new", "subpage":subpage};
  	var nthing = eventButton ('New', 'new', '', '', varArr, '');  
  	$('addNew').appendChild(nthing);
	}
  
  for(var id in thisArr) 
		{
		if(typeof thisArr[id] == 'object')
      {
      buildThingRow(thisTag, thisArr[id]); 
			}
		}
  }


function editIm (txt, which)
	{  
	var cd = new Element("div", {
    'class': 'lineup'});
		
	var ft = new Element("a", {
    'class': 'info_link',
    'events': {
        'click': function(){
 					var tcell = $(this).parentNode.parentNode.parentNode.parentNode.parentNode.parentNode;
				 	var trow = $(tcell).parentNode;
				 	var crow = $(trow).nextSibling;
				 	var drow = $(trow).nextSibling.nextSibling.nextSibling.nextSibling;

          var imID = $(tcell).firstChild.nextSibling.value;
          var imCap = crow.firstChild.firstChild.value;
          var imDes = drow.firstChild.nextSibling.firstChild.value;
          var imNat = $('cb_'+imID).checked;
          
        	searchRequest = new Request( 
        		{
        		method: 'post',
        		url: 'ajax.php',
            data: {'image_id':imID, 'image_cap':imCap, 'image_des':imDes, 'image_nat':imNat, 'which':'caption'},
            encoding:'UTF-8',
        		autoCancel: true, 
        		async:false,  
            onRequest: function() {}, 
        		onFailure: function() {alert('problem')}, 
            onComplete: function(response) {
        			eval (response); //returns tbID

              $(tbID).removeClass("imListC"); 
              } 			  
           });

	        searchRequest.send();
          }
    	}});

	var ftv = document.createTextNode(txt);
	$(ft).appendChild(ftv);
	$(cd).appendChild(ft);

	return (cd);
	}
	
	
function buildThingForm ()
  {	
  popup();
        			
  $('popupContents').setStyle('top', '10%');
  $('popupContents').setStyle('height', '80%');
  
  var frFin = new Element('form', {	
	  'id': 'finished',	
	  'name': 'finished',
	  'enctype': 'multipart/form-data',
	  'method': 'post'
	  });

  var frData = new Element('form', {	
  	'id': 'data',	
  	'name': 'data',
  	'enctype': 'multipart/form-data',
  	'method': 'post'
  	});

  var ft1 = buildFont ('', 'Edit Entry:', 't1', '');
  var ft2 = buildFont ('Names, labels or identifiers:', ' ADD ', 'info_link', 'newLab()');
  var ft3 = buildFont ('Comment details and translations:', ' ADD ', 'info_link', 'newTxt()');
  var ft4 = buildFont ('Additional properties and links:', ' ADD ', 'info_link', 'newRef()');

  var ft5 = subForm ('Return to list', 'info_link', 'finished');
  var ft6 = document.createTextNode(' - ');
  var ft7 = subForm ('confirm Edits', 'info_link', 'data');

  var cells = new Array;  
  var rows = new Array;

// Table tba
 //// ROW 1
  cells[0] = buildCell (ft2, '100%', '', 1, 1); 
 	rows[0] = buildRow (cells);
  cells = new Array;
//// ROW 2
  cells[0] = buildCell ('', '', '', 2, 1, 'lab');
 	rows[1] = buildRow (cells);
var tba = buildTable(rows, '');

cells = new Array;  
rows = new Array;

// Table tbb
 //// ROW 1
  cells[0] = buildCell (ft3, '100%', '', 1, 1); 
 	rows[0] = buildRow (cells);
  cells = new Array;
//// ROW 2
  cells[0] = buildCell ('', '', '', 2, 1, 'txt');
 	rows[1] = buildRow (cells);
var tbb = buildTable(rows, '');

cells = new Array;  
rows = new Array;

// Table tbc
 //// ROW 1
  cells[0] = buildCell (ft4, '100%', '', 1, 1); 
 	rows[0] = buildRow (cells);
  cells = new Array;
//// ROW 2
  cells[0] = buildCell ('', '', '', 2, 1, 'ref');
 	rows[1] = buildRow (cells);
var tbc = buildTable(rows, '');

cells = new Array;  
rows = new Array;

 //// ROW 1
  cells[0] = buildCell (ft1, '', '', 1, 1); 
  cells[1] = buildCell ('', '', '', 1, 1, 'ph1'); 
  cells[2] = buildCell (ft5, '100px', 'noWrap', 1, 1); 
  	cells[2].appendChild(ft6);
  	cells[2].appendChild(ft7);
 	rows[0] = buildRow (cells);
  cells = new Array;
//// ROW 2
  cells[0] = buildCell (tba, '', '', 3, 1);
    cells[0].setAttribute('bgcolor', 'white');
 	rows[1] = buildRow (cells);
  cells = new Array;  
//// ROW 3
  cells[0] = buildCell (tbb, '', '', 3, 1);
    cells[0].setAttribute('bgcolor', 'white');
 	rows[2] = buildRow (cells);
  cells = new Array;  
//// ROW 4
  cells[0] = buildCell (tbc, '', '', 3, 1);
    cells[0].setAttribute('bgcolor', 'white');
 	rows[3] = buildRow (cells);
  cells = new Array;  

var tb = buildTable(rows, 'editTable', '100%', 'editTable');

frData.appendChild(tb);
$('popupContents').appendChild(frFin);
$('popupContents').appendChild(frData);
}

function editImFull (txt, which)
	{  
		
	
  
	var ft = new Element("font", {
    'class': 'info_link',
    'events': {
        'click': function(){
 					var tcell = $(this).parentNode.parentNode;
				 	var trow = $(tcell).parentNode;
				 	var crow = $(trow).nextSibling;

          var imID = $(this).nextSibling.value;
         
        	searchRequest = new Request( 
        		{
        		method: 'post',
        		url: 'ajax.php',
            data: {'thing_id':imID, 'subpage':subpage, 'object':object, 'start':listStart, 'which':'captionFull', 'process':'edit'},
            encoding:'UTF-8',
        		autoCancel: true, 
        		async:false,  
            onRequest: function() {}, 
        		onFailure: function() {alert('problem')}, 
            onComplete: function(response) {
        			eval (response); //returns tbID
        			setVars();
        			buildThingForm ();
        			doBuild();
			        } 			  
           });

	        searchRequest.send();
          }
    	}});

	var ftv = document.createTextNode(txt);
	$(ft).appendChild(ftv);

	return (ft);
	}

function buildImRow(thisTag, thisVals, readOnly) 
	{
  add2FunctionString ('buildImRow('+thisTag+', '+thisVals+', '+readOnly+')');
  var par = $(thisTag);
  
	// set hei and wid for the inputs
	var winD = Window.getSize();
	var winW = winD.x;
	if (Browser.Engine.trident) {var sb = 20;} // Allows for the thickness of the scroll bar
	else {var sb = 0;}	

  var test = winW - 501;
  var rest = winW - sb - 501;  
	var wid2 = 250;  
	var wid = rest - wid2 + 15;
  var hei = 50;
  var hei2 = 100;
  if (wid < 50) {wid = 150;}
	if (thisTag == 'txt') {hei = 120;}
  
  var upd = editIm ('Update', '');  
	
  var varArr = {"process":"edit", "thing_id":thisVals["id"], 
  	"subpage":subpage, "whichList":'caption', "category":category,  
  	"start":start, "object":object};
  var fupd = eventButton ('Edit', 'edit', thisVals["id"], '', varArr, ''); 
		
	varArr = {"subpage":subpage, "category":category, "start":start, 
		"object":object, "limit":listLimit, "action":"data.php"};		
  var del = eventButtonAJ ('Delete', 'deleteimage', thisVals["id"], '', varArr, '');  
  
  var imTag = makePyrThumb (thisVals["id"], thisVals["pyramid"], 100, thisVals["filename"], thisVals["server"]);
  var cid = makeInput ('hidden', "id_"+thisVals["id"], thisVals["id"], 0, 0);
  var ft1 = buildFont ('Name: ', thisVals["filename"], 'cls', '');
  var ft2 = buildFont ('Categories: ', thisVals["cats"], 'cls', '');
  var ft3 = buildFont ('Related To: ', thisVals["related"], 'cls', '');
  var ft4 = buildFont ('Caption: ', '', 'cls', ''); 
  var ft7 = buildFont ('Description: ', '', 'cls', ''); 
  var ft5 = buildFont ('Path: ', thisVals["pyramid"], 'cls', ''); 
  var tar = makeInput ('textarea', "caption_"+thisVals["id"], 
      thisVals["caption"], hei, wid, readOnly); 
  var tar2 = makeInput ('textarea', "description_"+thisVals["id"], 
      thisVals["description"], hei2, wid, readOnly); 

  var ft6 = buildFont ('Needs Attention: ', '', '', ''); 
  var nat = makeInput ('checkbox', "cb_"+thisVals["id"], thisVals["needsAttention"], 0, 0);  
  
	var ln = new Element("div", {
    'class': 'lineup'});
  var lnb = document.createTextNode(' - ');
    ln.appendChild(lnb);  
	var ln2 = new Element("div", {
    'class': 'lineup'});
  var lnc = document.createTextNode(' - ');
    ln2.appendChild(lnc);

  var cells = new Array;  
  var rows = new Array;
	
	//// ROW 1
  cells[0] = buildCell (upd, '10px', 'padt3', 1, 1);
  cells[1] = buildCell (ln,  '1px', 'padt3', 1, 1);
  cells[2] = buildCell (del,  '10px', 'padt3', 1, 1);
  cells[3] = buildCell (ln2,  '1px', 'padt3', 1, 1);
  cells[4] = buildCell (fupd,  '10px', 'padt3', 1, 1);	
 	rows[0] = buildRow (cells);
	var tclb = buildTable(rows, "");
    tclb.setAttribute("width", 'auto');
	
	cells = new Array;  
  rows = new Array;

//// ROW 1
  cells[0] = buildCell (imTag, '100px', 'padt3grey', 1, 7);
  cells[1] = buildCell (ft1, wid2 + 'px', 'padt3h', 1, 2);
    cells[1].setAttribute("height", '45px');
  cells[2] = buildCell (ft4, '', 'padt3', 1, 1);
  cells[3] = buildCell (tclb, '10px', 'padt3', 2, 1);
    cells[3].appendChild(cid);
    cells[3].setAttribute("align", 'right');
 	rows[0] = buildRow (cells);
  cells = new Array;
//// ROW 2
  cells[0] = buildCell (tar, wid + 'px', 'padt3', 3, 2);
 	rows[1] = buildRow (cells);
  cells = new Array;  
//// ROW 3  
  cells[0] = buildCell (ft2, wid2 + 'px', 'padt3h', 1, 2);
  cells[0].setAttribute("height", '45px');
  rows[2] = buildRow (cells); 
  cells = new Array;   
//// ROW 4
  cells[0] = buildCell (ft7, '', 'padt3', 3, 1);
 	rows[3] = buildRow (cells);
  cells = new Array;  
//// ROW 5  
  cells[0] = buildCell (ft3, wid2 + 'px', 'padt3h', 1, 2);
  cells[1] = buildCell (tar2, wid + 'px', 'padt3', 3, 2);
  rows[4] = buildRow (cells);
  cells = new Array;   
//// ROW 6
  rows[5] = buildRow (cells);
  
//// ROW 7
  cells[0] = buildCell (ft5, '', 'padt5', 2 ,1);
  cells[1] = buildCell (ft6, '', 'padt5', 1 ,1);
    cells[1].setAttribute("align", 'right');
  cells[2] = buildCell (nat, '', '', 1 ,1);
  rows[6] = buildRow (cells);

  var tb = buildTable(rows, "imList");
    tb.setAttribute("id", 'imageTable_'+thisVals["id"]);
		
	if ($('mainCom'))
		{var mcD = $('mainCom').getSize();
		 tb.setAttribute("width", mcD.x - 30 + 'px');}
	else
		{tb.setAttribute("width", rest + 'px');}
		
  par.appendChild(tb);

  $("caption_"+thisVals["id"]).addEvent('keydown', function(event){
 	 var tcell = $(this).parentNode;
	 var trow = $(tcell).parentNode;
	 var tbl = $(trow).parentNode.parentNode; 
   tbl.addClass("imListC"); 
   });   
   
  $("description_"+thisVals["id"]).addEvent('keydown', function(event){
 	 var tcell = $(this).parentNode;
	 var trow = $(tcell).parentNode;
	 var tbl = $(trow).parentNode.parentNode; 
   tbl.addClass("imListC"); 
   });
   
  $("caption_"+thisVals["id"]).addEvent('mousedown', function(event){
 	 var tcell = $(this).parentNode;
	 var trow = $(tcell).parentNode;
	 var tbl = $(trow).parentNode.parentNode; 
   tbl.addClass("imListC"); 
   });   
   
  $("description_"+thisVals["id"]).addEvent('mousedown', function(event){
 	 var tcell = $(this).parentNode;
	 var trow = $(tcell).parentNode;
	 var tbl = $(trow).parentNode.parentNode; 
   tbl.addClass("imListC"); 
   });

  $("cb_"+thisVals["id"]).addEvent('click', function(event){
 	 var tcell = $(this).parentNode;
	 var trow = $(tcell).parentNode;
	 var tbl = $(trow).parentNode.parentNode; 
   tbl.addClass("imListC"); 
   });
  }  
  
function buildThingRow(thisTag, thisVals, readOnly) 
	{
	var par = $(thisTag);
  
	// set hei and wid for the inputs
	var winD = Window.getSize();
	var winW = winD.x;
	if (Browser.Engine.trident) {var sb = 20;} // Allows for the thickness of the scroll bar
	else {var sb = 0;}	

  var test = winW - 501;
  var rest = winW - sb - 501;  
	var wid2 = 350;  
	var wid = rest - wid2+ 15;
  var hei = 100;
  if (wid < 50) {wid = 150;}
	if (thisTag == 'txt') {hei = 120;}
  
  //var varArr = {"process":"edit", "thing_id":thisVals["id"], "subpage":thisVals["type_id"]};
	 
  var varArr = {"process":"edit", "thing_id":thisVals["id"], 
  	"subpage":subpage, "category":category, "start":start, "object":object};
		
  var edt = eventButton ('Edit', 'edit', thisVals["id"], '', varArr, '');
	
	var ln = new Element("div", {
    'class': 'lineup'});
  var lnb = document.createTextNode(' - ');
	
    ln.appendChild(lnb);  
	var delprocess = "delete";
	
	if (thisVals["type_id"] == "25")
		{delprocess = "deleteimage";}
		
	var varArr2 = {"subpage":subpage, "category":category, "start":listStart, 
		"limit":listLimit, "object":object, "action":"data.php"};
  var del = eventButtonAJ ('Delete', delprocess, thisVals["id"], '', varArr2, ''); 
	
  var tid;

  if (thisVals["pyramid"])
    {tid = makePyrThumb (thisVals["id"], thisVals["pyramid"], 50, "No Image", thisVals["server"]);}
  else
    {tid = buildFont ('', thisVals["id"], 'cls', '');}
    
  var cid = makeInput ('hidden', "id_"+thisVals["id"], thisVals["id"], 0, 0);
  var ft1 = buildFont ('Identifier: ', thisVals["identifier"], 'cls', '');
  var ft2 = buildFont ('Categories: ', thisVals["cats"], 'cls', '');
  var ft3 = buildFont ('Details: ', thisVals["caption"], 'cls', '');

  var cells = new Array;  
  var rows = new Array;
		
	//// ROW 1
  cells[0] = buildCell (del, '10px', 'padt3', 1, 1);
  cells[1] = buildCell (ln,  '1px', 'padt3', 1, 1);
  cells[2] = buildCell (edt,  '10px', 'padt3', 1, 1);
 	rows[0] = buildRow (cells);
	var tclb = buildTable(rows, "");
    tclb.setAttribute("width", 'auto');
	
	cells = new Array;  
  rows = new Array;
	
//// ROW 1
  cells[0] = buildCell (tid, '50px', 'padt3grey', 1, 2);
    cells[0].setAttribute("align", 'center');
  cells[1] = buildCell (ft1, wid2 + 'px', 'padt3h', 1, 1);
    cells[1].setAttribute("height", '20px');
  cells[2] = buildCell (ft3, '', 'padt3', 1, 2);
  cells[3] = buildCell (tclb, '10px', 'padt3', 1, 1);
    cells[3].appendChild(cid);
    cells[3].setAttribute("align", 'center');
 	rows[0] = buildRow (cells);
  cells = new Array;
//// ROW 2
  cells[0] = buildCell (ft2, wid2 + 'px', 'padt3', 1, 1);
  cells[1] = buildCell (cid, '10px', 'padt3', 1, 1);
    //cells[1].appendChild(cid);
    cells[1].setAttribute("align", 'center');
 	rows[1] = buildRow (cells);
  cells = new Array;
  
  var tb = buildTable(rows, "imList");
    tb.setAttribute("id", 'thingTable_'+thisVals["id"]);
	
	if ($('mainCom'))
		{var mcD = $('mainCom').getSize();
		 tb.setAttribute("width", mcD.x - 30 + 'px');}
	else
		{tb.setAttribute("width", rest + 'px');}
		
  par.appendChild(tb);
  }

function setListButtons () 
	{
  if ($('lleft'))
    {
    $('lleft').addEvent('click', function(event){
       var nst = ($('start').value * 1) - listLimit;
       if (nst < 0)
        {$('start').value = 0;}
       else
        {$('start').value = nst;}
  
       document.page_details.submit();
       });
    }

  if ($('lright'))
    {
    $('lright').addEvent('click', function(event){
       var nst = ($('start').value * 1) + listLimit;
       if (nst < (listTotal - listLimit))
        {$('start').value = nst;}
      else
        {$('start').value = (listTotal - listLimit);}
    
        document.page_details.submit();
       });
    }
  }
  
	
function add2DebugString (obj, indent, depth, bd) 
  {
	var currentTime = new Date();
	var ctime = currentTime.getTime();
	
  var ws = 1;
  var output = '';
  var db = $('debString');

  indent = (!indent) ? 0 : indent;
  depth = (!depth) ? 0 : depth;

  if (depth > MAX_DEPTH) {
    var tb = document.createElement("b");
    addSpaces(db, indent);
    tb.appendChild(document.createTextNode('Maximum Depth Reached')); 
    db.appendChild(document.createElement("br")); 
    db.appendChild(tb); 
    db.appendChild(document.createElement("br")); 
    return;}

  if (typeof(obj) == "object") {
    if (indent == 0)
      {
      var tb = document.createElement("b");
      tb.appendChild(document.createTextNode(typeof(obj)));
      db.appendChild(tb); 
      db.appendChild(document.createElement("br"));
      indent++;  
      addSpaces(db, indent); 
      db.appendChild(document.createTextNode('(')); 
      db.appendChild(document.createElement("br")); 
      } 
      
    //indent++;
    var child = '';

    for (var key in obj) {
      try {child = obj[key];}

      catch (e) {child = '*Unable To Evaluate*';}
      addSpaces(db, indent);
      db.appendChild(document.createTextNode('['+key+'] => ')); 
      
      if (typeof(child) == "object") 
        {
        indent++;
        db.appendChild(document.createTextNode(typeof(child))); 
        db.appendChild(document.createElement("br"));  
        addSpaces(db, indent);
        db.appendChild(document.createTextNode('('));  
        db.appendChild(document.createElement("br"));
        
        addSpaces(db, indent);
        db.appendChild(document.createTextNode(')'));  
        db.appendChild(document.createElement("br"));
        indent--;
        }
      else 
        {db.appendChild(document.createTextNode(child+' ['+typeof(child)+']'));  
         db.appendChild(document.createElement("br"));}
      }
      
    indent--;
        
    if (indent == 0)
      { 
      db.appendChild(document.createTextNode(') ['+ctime+']')); 
      db.appendChild(document.createElement("br")); 
      return;
      }
    }
  else 
    {  
		obj = obj + ' ['+ctime+']';
    if (bd)
      {			
      db.appendChild(document.createElement("br")); 
      var tb = document.createElement("b");
      tb.appendChild(document.createTextNode(obj)); 
      }
    else
      {var tb = document.createTextNode(obj);}

    addSpaces(db, indent); 
    db.appendChild(tb); 
    db.appendChild(document.createElement("br")); 
    //db.appendChild(document.createElement("br")); 
    return;
    }
  }
  
  	
function add2FunctionString (obj, indent, depth, bd) 
  {
  var ws = 1;
  var output = '';
  var db = $('funString');

  indent = (!indent) ? 0 : indent;
  depth = (!depth) ? 0 : depth;

  if (depth > MAX_DEPTH) {
    var tb = document.createElement("b");
    addSpaces(db, indent);
    tb.appendChild(document.createTextNode('Maximum Depth Reached')); 
    db.appendChild(document.createElement("br")); 
    db.appendChild(tb); 
    db.appendChild(document.createElement("br")); 
    return;}

  if (typeof(obj) == "object") {
    if (indent == 0)
      {
      var tb = document.createElement("b");
      tb.appendChild(document.createTextNode(typeof(obj)));
      db.appendChild(tb); 
      db.appendChild(document.createElement("br"));
      indent++;  
      addSpaces(db, indent); 
      db.appendChild(document.createTextNode('(')); 
      db.appendChild(document.createElement("br")); 
      } 
      
    //indent++;
    var child = '';

    for (var key in obj) {
      try {child = obj[key];}

      catch (e) {child = '*Unable To Evaluate*';}
      addSpaces(db, indent);
      db.appendChild(document.createTextNode('['+key+'] => ')); 
      
      if (typeof(child) == "object") 
        {
        indent++;
        db.appendChild(document.createTextNode(typeof(child))); 
        db.appendChild(document.createElement("br"));  
        addSpaces(db, indent);
        db.appendChild(document.createTextNode('('));  
        db.appendChild(document.createElement("br"));
        
        addSpaces(db, indent);
        db.appendChild(document.createTextNode(')'));  
        db.appendChild(document.createElement("br"));
        indent--;
        }
      else 
        {db.appendChild(document.createTextNode(child+' ['+typeof(child)+']'));  
         db.appendChild(document.createElement("br"));}
      }
      
    indent--;
        
    if (indent == 0)
      { 
      db.appendChild(document.createTextNode(')')); 
      db.appendChild(document.createElement("br")); 
      return;
      }
    }
  else 
    {    
    if (bd)
      {
      db.appendChild(document.createElement("br")); 
      var tb = document.createElement("b");
      tb.appendChild(document.createTextNode(obj)); 
      }
    else
      {var tb = document.createTextNode(obj);}

    addSpaces(db, indent); 
    db.appendChild(tb); 
    db.appendChild(document.createElement("br")); 
    return;
    }
  }


function str_repeat(str, repeat) 
  {
  var output = '';
  for (var i = 0; i < repeat; i++) {
    output += str;}

  return output;
  }
  
function addSpaces (obj, repeat) 
  {
  for (var i = 0; i < repeat; i++) {
    var ft = new Element("font", {
      'class': 'spaces'});
    obj.appendChild(ft); 
    }
    
  return;
  }

var MAX_DEPTH = 10;

function print_r(obj, indent, depth) {

  var ws = '    ';
  var output = '';

  indent = (!indent) ? 0 : indent;
  depth = (!depth) ? 0 : depth;

  if (depth > MAX_DEPTH) {
    return str_repeat(ws, indent) + '*Maximum Depth Reached*\n'; }

  if (typeof(obj) == "object") {
    output += (indent == 0) ? typeof(obj) + '\n(\n' : '';
    indent++;

    var child = '';

    for (var key in obj) {
      try {child = obj[key];}

      catch (e) {child = '*Unable To Evaluate*';}

      output += str_repeat(ws, indent) + '['+key+'] => ';
      
      if (typeof(child) == "object") 
        {
        indent++;
        output += typeof(child) + '\n';
        output += str_repeat(ws, indent) + '(\n';
        output += print_r(child, indent, depth+1);
        output += str_repeat(ws, indent) + ')\n';
        indent--;
        }
      else 
        {output += child + '\n';}
      }

    indent--;
    output += (indent == 0) ? ')\n' : '';
    return output;
    }
  else {return str_repeat(ws, indent) + obj + '\n';}
}

// Can use this function to reset css or other specifications for smaller 
// resolution screens.
function checkResolution ()
  {
  // set hei and wid for the inputs
	var winD = Window.getSize();
	var winW = winD.x;
	var winH = winD.y;
	var s1 = '';
	var s2 = '';
	var s3 = '';
	
	if (winW < 1100 && !object)
	  {s1 = '1.6em'; s2 = '1.0em'; s3 = '0.65em';}
	else if (winW < 1150)
	  {s1 = '1.2em'; s2 = '1.0em'; s3 = '0.65em';}
  else if (winW < 1250)
	  {s1 = '1.3em'; s2 = '1.1em'; s3 = '0.7em';}
  else if (winW < 1350)
	  {s1 = '1.6em'; s2 = '1.2em'; s3 = '0.8em';}
  else
	  {s1 = '1.8em'; s2 = '1.4em'; s3 = '1em';}
	
	var allParas = $(document.body).getElements('p');
  allParas.each(function(item, index){      
  	if (item.hasClass('ptitle2') || item.hasClass('ptitle'))
	    {item.setStyle('font-size', s1);}
  	if (item.hasClass('pother'))
    	{item.setStyle('font-size', s2);}        
  	}); //The optional second argument for binding isn't used here.
		
	if (!subpage)
		{var subpage = "ignore";}
		
	if (subpage == 'wsn')
		{
		if (winW < 1150)
		  {s1 = '1.2em'; s2 = '1.0em'; s3 = '0.65em';}
  	else if (winW < 1250)
		  {s1 = '1.3em'; s2 = '1.1em'; s3 = '0.7em';}
	  else if (winW < 1350)
		  {s1 = '1.6em'; s2 = '1.2em'; s3 = '0.8em';}
  	else
	  	{s1 = '1.8em'; s2 = '1.4em'; s3 = '1em';}
		
		var allParas = $(document.body).getElements('p');
	  allParas.each(function(item, index){      
  		if (item.hasClass('ptitle2n'))
	    	{item.setStyle('font-size', s1);}
  		if (item.hasClass('pothern'))
	  		{item.setStyle('font-size', s2);}        
  		}); //The optional second argument for binding isn't used here.
		}
		
	if ($('comm')) {$('comm').setStyle('font-size', s3);}
}

function buildExploreDiv (index, parentDiv)
	{
	removeChildrenFromNode($(parentDiv));
	//pageDetails is a GLBOALS JS variable
	var vars = pageDetails[index]['details'];
	var sD = $(parentDiv).getSize();
	var sW = sD.x, sH = sD.y;	  
	var th = 40;
	var ch = sH - th;
	var ct = th;	
	var which = vars['which'];
	var tag = initialCap(which);	
	
	if (ch < 250) {ch = 250;}
	var wdDiv = new Element("div", {
		'id': parentDiv+'_Details'});
	$(parentDiv).appendChild(wdDiv); 
	wdDiv.setStyles({'height': ch + 'px', 'top': ct +'px', 'left': '0px'});
		
	//Search specific variables and build page
	if (which == "image")
		{
		$(parentDiv+'_Details').addClass('targetframe');		
	
		iipIms[parentDiv] = new IIP_Gallery( parentDiv+'_Details', {
  		image: 'blank',
			externalVars: 'pageDetails["'+index+'"]',
  		searchSQL: vars,
  		zoom: 1,
  		centerzoom: 1,
  		render: 'random',
			furtherdetails: true,
			furtherdetailsEdit: true,
  		hideNav: false,
  		hideIcon: false
  		}); 
		}
	else //which == "text"
		{
		$(parentDiv+'_Details').addClass('pageframe');	
		
		txtList[parentDiv] = new rrrTxt( parentDiv+'_Details', {
  		searchSQL: vars,
			externalVars: 'pageDetails["'+index+'"]',
			furtherdetails: true,
			furtherdetailsEdit: true
  		}); 				
		}
		
	buildSearchDiv (index, parentDiv, th);	
	}
	
// Use a AJAX request to get the text details
// Can be called by both the IIPGallery & rrrText Classes, via externalFunction
function checkLink (process, subject, predicate, object, edit){    
  searchRequest = new Request(
  	{
  	method: 'post',
  	url: 'exploreAjax.php',
   	data: {'which': 'textLink', 'process':process, 'subject':subject, 'predicate':predicate, 'object':object },
   	encoding:'UTF-8',
  	autoCancel: true, 
  	async:false,  
   	onRequest: function() {}, 
  	onFailure: function() {alert('problem')}, 
   	onComplete: function(response) {
			//alert (response);
			var loc_vals = new Array ();				
			eval ('loc_vals = ' + response);		
						
			if (message)
				{alert (message);}
									
			refreshFD (loc_vals, "pageright_Details_furtherDetails", edit)
			}
  	});
	
	searchRequest.send(); 
  }
	
//Can be called by both the IIPGallery & rrrText Classes
function externalFunction (detailsPrefix, which, selected, edit)
	{	
	add2DebugString("RUN externalFunction ");
	/*
	var pageDetails = {
	"image":{"details":{"which":"image","searchObject":{},"searchCategory":{},"searchDetail":{}}, "selected":new Object()},
	"text":{"details":{"which":"text","searchObject":{},"searchCategory":{},"searchDetail":{}}, "selected":new Object()}
	}
	*/
	
	eval ('pageDetails["'+detailsPrefix+'"]["selected"]["id"] = "'+selected+'"');
	
	var pr = 40;
	var pr2 = 252;
	var str = false;
	
	var ldiv = "pageright_Details_link";
	if ($(ldiv))
		{removeChildrenFromNode($(ldiv));}
	
	if (selected)
		{		
		if (which == "image")
			{var other = "text";}
		else
			{var other = "image";}
			
		var sb = pageDetails["text"]["selected"]['id'];
		var ob = pageDetails["image"]["selected"]['id'];
			
		if(sb == 0 || ob == 0)
			{str = false;}
		else
			{str = 'Selected text'+'('+sb+') is related to selected image'+'('+ob+')';
		   var str2 = 'Selected text'+'('+sb+') was transcribed from selected image'+'('+ob+')';}
			 		
		if ($(ldiv) && sb)
			{		
			if (str)
				{
				var cfont = buildFont ('', str, 't3', '', 'textTitle'); 
			 	$(cfont).setProperty('align', 'center');
			 	$(ldiv).appendChild(cfont);		 		 
				
				cfont.addEvent('click', function(event){
					checkLink ('add', sb, pr, ob, edit);});
					
				var cfont = buildFont ('', str2, 't3', '', 'textTitle'); 
		 		$(cfont).setProperty('align', 'center');
		 		$(ldiv).appendChild(cfont);		 		 
				
				cfont.addEvent('click', function(event){
					checkLink ('add', sb, pr2, ob, edit);});
				}
			}			
		}
	}
	
function initialCap(str) {
	if (str)
		{return (str.substr(0, 1).toUpperCase() + str.substr(1));}
	}
	

function buildLimitString (title, index, parentDiv)
	{
	var vars = pageDetails[index]['details'];
	var which = vars['which'];
	if (which == "image")
		{var tag = "Caption";}
	else
		{var tag = initialCap(which);}
	
	var limStr = new Element("div", {
    'class': 'cls',
		'id': 'limStr'+tag});
		
	var cells = new Array;  
  var rows = new Array;

	var list = new Array;
	var lno = 0;
	
	for (var key in vars) 
		{
		if (key == 'which' || key == 'searchSpecific')
			{}
		else
			{
			for (var key2 in vars[key])
				{
				var locStr = "";
				var strA = "";
				
				var myRe = /^([!])*(.+)/;
				var myArray = myRe.exec(vars[key][key2]);

				if (myArray[1] == "!")
					{strA = " (NOT)";}
				
				var strB = myArray[2];				
			
				if (key == "searchObject")
			 	{locStr = "Painting"+strA+":'"+strB+"' ";}
				else if (key == 'searchDetail')
			 	{locStr = tag+strA+":'"+strB+"' ";}
				else if (key == "searchCategory")
			 	{locStr = "Category"+strA+":'"+strB+"' ";}
				
				var curSet=new Array(locStr, key, key2);
				list[lno] = curSet;
				lno++;	
				}
			}		
		}
	
	if (lno > 0)
		{	
		var tcft = buildFont ('', title, 't3b', '', '', true);
		limStr.appendChild(tcft);
	
		for ( var i=0, len=lno; i<len; ++i )
			{		
			var oc = 'delete pageDetails["'+index+'"]["details"]["'+list[i][1]+'"]['+
			list[i][2]+']; '+'buildExploreDiv ("'+index+'", "'+parentDiv+'"); ';

			var cft = buildFont ('', list[i][0], 't3bc', oc, '', true);
			
			limStr.appendChild(cft);
								
			if ((lno > 2 && i == (lno - 2)) || (lno == 2 && i < (lno - 1)))
				{var xft = buildFont ('', ' and ', 't3', '', '', true);
			 	limStr.appendChild(xft);			 	
				}
			else if (lno > 2 && i < (lno - 1))
				{var xft = buildFont ('', ', ', 't3', '', '', true);
			 	limStr.appendChild(xft);			 	
				}
			}
		}	
		
	return (limStr);
	}
		
function buildSearchDiv (index, parentDiv, hei)
	{
	var vars = pageDetails[index]['details'];
	var which = vars['which'];	
	var tag = initialCap(which);
	var lim = hei - 4;
	
	//Build Search Div
		
	var sDiv = new Element("div", {
    'class': 'searchframe',
		'id': 'search'+parentDiv});
		$(parentDiv).appendChild(sDiv); 
		sDiv.setStyles({
			'height': hei + 'px', 'top': '0px', 
			'left': '0px'});
	
	var sfDiv = new Element("div", {
    'class': 'floatframe',
		'id': 'float'+parentDiv});
		$(parentDiv).appendChild(sfDiv); 
		sfDiv.setStyles({'height': lim + 'px', 'top': '0px', 
			'left': '0px'});
	var ts = sfDiv.getSize();
	
	if (tag == "Image")
		{var ud = "Caption";}
	else
		{var ud = "Text";}

	var opts = {
		"searchDetail":"Within "+ud, 
		"searchObject":"Related to Painting", 
		"searchCategory":"Related to Category", 
		"!searchDetail":"Not in "+ud, 
		"!searchObject":"Exclude Painting", 
		"!searchCategory":"Exclude Category"};
			
	var limStr =	buildLimitString (tag+'s Limited by: ', index, parentDiv);
			
	var sim = new Element("img", {
    'src': 'graphics/search2.png',
    'class': 'button',
		'id': 'searchIcon_'+parentDiv});

	sim.setStyles({'width': '24px', 'height': '24px', 'top': '0px', 'left': '0px'});

	var mySMorph = new Fx.Morph('float'+parentDiv);
	sim.addEvent('click', function(e){
		var cs = $(this).parentNode.parentNode.parentNode.parentNode.parentNode.getSize();
		
		if (cs.y > (lim + 3))
			{var ns = lim;}
		else
			{var ns = lim + 30;}

		mySMorph.start({height: ns + 'px'});});
				
	var ob1 = buildFont ('', 'Search: ', 't3b', ''); 
	var ob2 = array2dropdown ("limitby"+parentDiv, opts, 0, "", ""); 
	var ob3 = makeInput ('text', "keysearch"+parentDiv, "enter value", 150, "", 0); 
	$(ob3).addEvent('focus', function(event){
		if (document.getElementById('keysearch'+parentDiv).value == 'enter value')
			{document.getElementById('keysearch'+parentDiv).value='';}});
	$(ob3).addEvent('keydown', function(event){
		if (event.key == "enter")
			{$('gosearch'+parentDiv).fireEvent('click', $('gosearch'+parentDiv), 1);}
		});	
	var ob4 = makeInput ('button', "gosearch"+parentDiv, "Go", 40, "", 0); 	
	$(ob4).addEvent('click', function(event){
 		var tinp = $(this).previousSibling;
		var tsel = $(this).previousSibling.previousSibling;
	
		var dArr = pageDetails[index]['details'];
				
		var myRe = /^([!])*(.+)/;
		var myArray = myRe.exec(tsel.value);
		var usel = myArray[2];
		var uinp = tinp.value;
		if (myArray[1] == "!")
			{uinp = "!"+uinp;}
			
		var no = 0;
		for(i in dArr[usel]) {no++;}
		dArr[usel][no+""] = uinp;
			 
		buildExploreDiv (index, parentDiv);		
  });
	
	ob2.setStyle('margin-left', '5px');
	ob2.setStyle('margin-right', '5px');
	ob3.setStyle('margin-right', '5px');
	ob4.setStyle('margin-right', '5px');
	ob1.appendChild(ob2);
  ob1.appendChild(ob3);
 	ob1.appendChild(ob4);
		
	var ob5;
	var ob6;
	
	if (limStr.firstChild)
		{ob5 = new Element("img", {
    	'src': 'graphics/clear.png',
    	'class': 'button',
			'id': 'clearIcon_'+parentDiv});
		 ob5.setStyles({'width': '24px', 'height': '24px', 'top': '0px', 'left': '0px'});	
		 $(ob5).addEvent('click', function(event){
			pageDetails[index] = {"details":{"which":which,
				"searchObject":{},"searchCategory":{},"searchDetail":{}}, 
				"selected":new Object()};
			buildExploreDiv (index, parentDiv);			
  		});
			
		ob6 = limStr;
		}
	else
		{ob5 = new Element("div", {});
		 ob5.setStyles({'width': '24px', 'height': '24px', 'top': '0px', 'left': '0px'});
		 ob6 = buildFont ('', 'Displaying all '+tag+'s: ', 't3b', ''); 
		 }
		 
	ob6.setStyle('overflow', 'auto');
	ob6.setStyle('width', ts.x - 65 + 'px');
	ob6.setStyle('height', 30 + 'px');
	ob6.setStyle('padding-top', '5px');	
	ob6.setStyle('margin-bottom', '2px');	
	
  var cells = new Array;  
  var rows = new Array;
	
  cells = new Array;
	cells[0] = buildCell (ob6, '', 'noWrapPL', 1, 1);
	cells[1] = buildCell (ob5, '24px', '', 1, 1);
	cells[2] = buildCell (sim, '24px', '', 1, 1); 
  	cells[2].setAttribute("text-align", "right");
  	cells[2].setAttribute("align", 'right');
	rows[0] = buildRow (cells);
	cells = new Array;
	cells[0] = buildCell (ob1, '', 'noWrapPL', 3, 1);
	rows[1] = buildRow (cells);
	
  var tb = buildTable(rows, "simple");
  sfDiv.appendChild(tb);	
  	tb.setAttribute("width", '100%');
		
	    new Tips( '#searchIcon_'+parentDiv, {
	  className: 'tip', // We need this to force the tip in front of nav window
	  // We have to first set opacity to zero to fix a bug in mootools 1.2
	  // where the tip appears without any fade in the first time it is loaded
	  onShow: function(t){ t.setStyle('opacity',0); t.fade(0.7); },
	  onHide: function(t){ t.fade(0); }
    });
		
    $('searchIcon_'+parentDiv).store('tip:text', '<h2>Search Options</h2>'+
			'');
	}
	
function buildTextDivs (vars, textDiv)
	{
  searchRequest = new Request( 
  	{
  	method: 'post',
  	url: 'exploreAjax.php',
    data: {'which': 'text', 'searchSQL':vars, 'textDiv': textDiv},
    encoding:'UTF-8',
  	autoCancel: true, 
  	async:false,  
    onRequest: function() {}, 
  	onFailure: function() {alert('problem')}, 
    onComplete: function(response) {
			var loc_vals = new Array ();
					
			if (response)
			  {eval ('loc_vals = ' + response);}
				
			var first;
			var fDiv;
								
			for (var key in loc_vals) 
				{
				var cfont = refreshTextTitle (cDiv, loc_vals[key]["title"], loc_vals[key]["id"]);
				
				if (!first)
					{first = loc_vals[key];
					 fDiv = cfont;}
					
				$(cDiv).appendChild(cfont);
				} 
				
		fDiv.addClass('textTitleOpen');
		getTextDetails (first['id'], fDiv);		
		}
  });
	
	searchRequest.send(); 
	}
	
function refreshTextTitle (cDiv, ctitle, cid)
	{
	// Try to limit the titles in list to one line
	var cs = $(cDiv).getSize();
	var lim = (cs.x/7.5);
				
	var clen = ctitle.length;
				
	if (clen > lim)
		{ctitle = ctitle.substring(0,(lim - 5)) + ' ...';}
					
	var cfont = buildFont ('', ctitle, 't3', '', 'textTitle'); 
	var ciid = makeInput ('hidden', "id_"+cid, cid, 0, 0, false); 
  $(cfont).appendChild(ciid);	
  $(cfont).addEvent('click', function(event){
		var myElements = $$('.textTitleOpen');
		myElements.each(function(item, index){
  		item.removeClass('textTitleOpen');
			resetTextTitle (item.firstChild.nextSibling.value, cDiv, item);			
			}); 
			
		this.addClass('textTitleOpen');
		var cid = this.firstChild.nextSibling.value;
		getTextDetails (cid, this);
		updateSelectedText (cid, $(cDiv).nextSibling.id);
		});
		
	return (cfont);
	}


function getTextDetails (cid, textDiv)
	{
  searchRequest = new Request( 
  	{
  	method: 'post',
  	url: 'exploreAjax.php',
    data: {'which': 'textDetails', 'cid':cid, 'textDiv': textDiv},
    encoding:'UTF-8',
  	autoCancel: true, 
  	async:false,  
    onRequest: function() {}, 
  	onFailure: function() {alert('problem')}, 
    onComplete: function(response) {
			var loc_vals = new Object();
			loc_vals["Selected Text: "] = new Object();

			eval ('loc_vals = ' + response);
			titleToAcc (loc_vals, textDiv);				
		}
  });
	
	searchRequest.send();  
	}
	
	
function titleToAcc (vars, tDiv)
	{
	removeChildrenFromNode($(tDiv));
	tDiv.removeEvents();
	
	var pDiv = new Element('div', {'class': ''});
	$(tDiv).appendChild(pDiv); 
	var cid = makeInput ('hidden', "id_"+vars['id'], vars['id'], 0, 0, false); 
  $(tDiv).appendChild(cid);	
	
	var acDl = new Element('dl', {'class': 'accordion', 'id': 'accordion_'+pDiv+'_'+vars['id']});
	$(pDiv).appendChild(acDl);
	var acDtT = new Element('dt', {'class': 'accordion_toggler_1', 'id':vars['id']});
	$(acDl).appendChild(acDtT); 
	var acTN = document.createTextNode(vars['title']);
	 $(acDtT).appendChild(acTN);
			
	// Accordian content goes into this one.
	var acDtC = new Element('dd', {'class': 'accordion_content_1'});
	$(acDl).appendChild(acDtC);
			
	var cont = buildTextAccSub1 (vars['content'], vars['contentLan']);
	$(acDtC).appendChild(cont);
			
	if (vars['description'])
		{var contD = document.createTextNode(vars['description']);
		 var p1 = new Element('p', {'class': 'justc'});
		 $(p1).appendChild(tftv);
		 $(acDtC).appendChild(p1);}
			 
	if (vars['children'])
	   {var ch1 = buildTextAccSub2 (vars['children'], 2, 4);
		 $(acDtC).appendChild(ch1);}	
				
	var br = new Element('br');
		$(pDiv).appendChild(br); 
			
	//refreshAccordian(pDiv, '', $(pDiv).parentNode.nextSibling.id);
	}
	
function resetTextTitle (cid, textDiv, oldDiv)
	{
  searchRequest = new Request( 
  	{
  	method: 'post',
  	url: 'exploreAjax.php',
    data: {'which': 'textDetails', 'cid':cid, 'textDiv': textDiv},
    encoding:'UTF-8',
  	autoCancel: true, 
  	async:false,  
    onRequest: function() {}, 
  	onFailure: function() {alert('problem')}, 
    onComplete: function(response) {
			//removeChildrenFromNode($(textDiv));
			var loc_vals = new Object();			
			eval ('loc_vals = ' + response);
			
			var newDiv = refreshTextTitle (textDiv, loc_vals["title"], loc_vals["id"]);
			var newChildren = newDiv.getChildren();
			removeChildrenFromNode(oldDiv);
			oldDiv.adopt(newChildren);			
			}
  });
	
	searchRequest.send();  
	}
	
function buildTextAcc (vars, pDiv)
	{
	removeChildrenFromNode($(pDiv));
	var first;
	var firstID;
	
	for (var key in vars) 
		{
		var tDiv = new Element('div', {'class': 'fdTitle'});
			$(pDiv).appendChild(tDiv); 
		var tDiv2 = new Element('div', {'class': 'tdiv3'});
			$(tDiv).appendChild(tDiv2);
		var tFont = buildFont ('', key, 'mlevl_1', ''); 
			$(tDiv2).appendChild(tFont);
			
		for (var key2 in vars[key]) 
			{
			if (!first)
				{first = 'accordion_'+pDiv+'_'+vars[key][key2]['id'];
				 firstID = vars[key][key2]['id'];}
				
			var acDl = new Element('dl', {'class': 'accordion', 'id': 'accordion_'+pDiv+'_'+vars[key][key2]['id']});
				$(pDiv).appendChild(acDl);
			var acDtT = new Element('dt', {'class': 'accordion_toggler_1', 'id':vars[key][key2]['id']});
				$(acDl).appendChild(acDtT); 
			var acTN = document.createTextNode(vars[key][key2]['title']);
	  		$(acDtT).appendChild(acTN);
			
			// Accordian content goes into this one.
			var acDtC = new Element('dd', {'class': 'accordion_content_1'});
				$(acDl).appendChild(acDtC);
			
			var cont = buildTextAccSub1 (vars[key][key2]['content'], vars[key][key2]['contentLan']);
				$(acDtC).appendChild(cont);
			
			if (vars[key][key2]['description'])
				{var contD = document.createTextNode(vars[key][key2]['description']);
			 var p1 = new Element('p', {'class': 'justc'});
			 	$(p1).appendChild(tftv);
			 	$(acDtC).appendChild(p1);}
			 
			if (vars[key][key2]['children'])
	    	{var ch1 = buildTextAccSub2 (vars[key][key2]['children'], 2, 4);
				 $(acDtC).appendChild(ch1);}	
			}
			
		var br = new Element('br');
			$(pDiv).appendChild(br); 
			
		}
	
	refreshAccordian(pDiv, '', $(pDiv).parentNode.nextSibling.id);
	//updateSelectedText (firstID, $(pDiv).parentNode.nextSibling.id);
	//alert (first);refreshAccordian
	$(first).firstChild.fireEvent('click', $(first).firstChild, 250);
	}
	
	
function buildTextAccSub2 (vars, ln, lim)
	{	
	var nln = ln + 1;

	if (ln > lim)
		{
		var cont = new Element('div', {'class': 'simple'});
			
		for (var key in vars) 
			{
			var tf1 = document.createTextNode(vars[key]['title']);
			var p1 = new Element('p', {'class': 'justa'});
			$(p1).appendChild(tf1);
			$(cont).appendChild(p1); 
			
			var contC = buildTextAccSub1 (vars[key]['content'], vars[key]['contentLan']);
				$(cont).appendChild(contC);

			if (vars[key]['description'])
				{
				var tf2 = document.createTextNode(vars[key]['description']);
				var p2 = new Element('p', {'class': 'justa'});
				$(p2).appendChild(tf2);
				$(cont).appendChild(p2); 
		 		}

			if (vars[key]['children'])
	  		{var cc = buildTextAccSub2 (vars[key]['children'], nln, lim);
				$(cont).appendChild(cc); }	
			}
		}
	else
		{
		var cont = new Element('dl', {'class': 'accordion'});
			
		for (var key in vars) 
			{
			var acDtT = new Element('dt', {'class': 'accordion_toggler_'+ln, 'id':vars[key]['id']});
			var acTN = document.createTextNode(vars[key]['title']);
	  		$(acDtT).appendChild(acTN);
				$(cont).appendChild(acDtT); 
			
			// Accordian content goes into this one.
			var acDd = new Element('dd', {'class': 'accordion_content_'+ln});
			
			var contC = buildTextAccSub1 (vars[key]['content'], vars[key]['contentLan']);
				$(acDd).appendChild(contC);
			
			if (vars[key]['description'])
				{var contD = document.createTextNode(vars[key]['description']);
			 var p1 = new Element('p', {'class': 'justc'});
			 	$(p1).appendChild(contD);
			 	$(acDd).appendChild(p1);}
			 
			if (vars[key]['children'])
	    	{var ch1 = buildTextAccSub2 (vars[key]['children'], nln, lim);
				 $(acDd).appendChild(ch1);}	
				 
			
			$(cont).appendChild(acDd);
			}
		}
		
	return (cont);
	}
	
function buildTextAccSub1 (vars, lan)
	{
	if (vars)
	{
	var no = 0;
	for (var key in lan) 
    {no++;}
    
  if (no > 1)
  	{var w = 100/(no);}
  else
    {var w = 100;}
    
  var cells = new Array; 
	var rows = new Array;
  var cno = 0;
  var rno = 0;
	
	for (var key in vars) 
    {          
    for (var key2 in vars[key])
      {
			var use = "NE";
			if (lan[key] == 1) {use = 1;}
					 
			var tftv = document.createTextNode(vars[key][key2]);
			var pn = new Element('p', {'class': 'just'});
			$(pn).appendChild(tftv); 
			cells[cno] = buildCell (pn, '', '', 1, 1);
				cells[cno].setAttribute('width', w+'%');
			cno++;}
		
		rows[rno] = buildRow (cells);
		cells = new Array;
		cno = 0;
		rno++;
    }
   
  var tb = buildTable(rows, 'simple');
	tb.setAttribute('width', '100%');
	}
	else
		{var tb = new Element("div", {});}
  
	return (tb);
	}

function homePageClicks ()
	{
	if ($('hp1'))
    {$('hp1').addEvent('click', function(event){
      window.location='http://www.nationalgallery.org.uk/paintings/rese'+
				'arch/studying-raphael/';});}
				
	if ($('hp2'))
    {$('hp2').addEvent('click', function(event){doForm('subpage', 248)});}
				
	if ($('hp3'))
    {
    $('hp3').addEvent('click', function(event){doForm('subpage', 'wsn')});}
}
