var SHADE = null;
var KEY_ESCAPE = 27;

function isIE(version)
{
	if(-1 != navigator.appName.indexOf('Microsoft'))
	{
		if(-1 != navigator.appVersion.indexOf('MSIE '+version))
		{
			return true;
		}
	}
	return false;
}
function getAbsoluteLeft(o) {
	oLeft = o.offsetLeft            // Get left position from the parent object
	while(o.offsetParent!=null) {   // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent    // Get parent object reference
		oLeft += oParent.offsetLeft // Add parent left position
		o = oParent
	}
	// Return left postion
	return oLeft
}
function getAbsoluteTop(o) {
	oTop = o.offsetTop            // Get top position from the parent object
	while(o.offsetParent!=null) { // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent  // Get parent object reference
		oTop += oParent.offsetTop // Add parent top position
		o = oParent
	}
	// Return top position
	return oTop
}
function getScreenWidth() { //{{{2
	if (document.all) return(document.body.clientWidth + document.body.scrollLeft)
	else return(window.innerWidth + window.scrollX)
}
function getScreenHeight() { //{{{2
	if (document.all) return(document.body.clientHeight + document.body.scrollTop)
	else return(window.innerHeight + window.scrollY)
}
function showHelp(span,yOffset)
{
	if(isIE(6))
	{
		return;
	}
	if(span.DIV==null)
	{
		span.DIV = document.createElement('DIV');
		span.DIV.innerHTML = span.title.replace("\r\n","<br/><br/>");
		span.DIV.innerHTML = span.DIV.innerHTML.replace('&lt;','<');
		span.DIV.innerHTML = span.DIV.innerHTML.replace('&gt;','>');
		//span.DIV.innerHTML = '<div>'+span.DIV.innerHTML+'</div>';
		var top = getAbsoluteTop(span)+yOffset;
		var left = getAbsoluteLeft(span)+5;


		span.DIV.style.border = '0px solid Gray';
		span.DIV.style.clear = 'none';
		span.DIV.style.color = 'Black';
		span.DIV.style.fontSize = '0.9em';
		span.DIV.style.left = (span.offsetWidth)+5+left+'px';
		span.DIV.style.padding = '5px';
		span.DIV.style.position = 'absolute';
		span.DIV.style.top = top+'px';
		span.DIV.style.zIndex = '1000';
		span.appendChild(span.DIV);
		span.title = '';
		span.BG = document.createElement('DIV');
		span.BG.style.clear = 'none';
		span.BG.style.left = (left+10)+'px';
		span.BG.style.padding = '0px';
		span.BG.style.position = 'absolute';
		span.BG.style.top = (top-15)+'px';
		span.BG.style.zIndex = span.DIV.style.zIndex-100;
		span.onmouseout = function(){this.DIV.style.display = this.BG.style.display = 'none';}
		if(span.DIV.offsetWidth>200)
		{
			span.DIV.style.width = '150px';
		}

		if(getAbsoluteLeft(span.DIV)+span.DIV.offsetWidth > getScreenWidth())
		{
			left-=(span.DIV.offsetWidth)+200;
			span.DIV.style.left = (span.offsetWidth)+5+left+'px';
			span.BG.style.left = (left+10)+'px';
		}

		span.style.height = span.DIV.offsetHeight+'px';

		var tbl = '';
		tbl+= '<table border="0" cellpadding="0" cellspacing="0" style="height:'+(span.DIV.offsetHeight+30)+'px;width:'+(span.DIV.offsetWidth+30)+'px;">';
		tbl+= '<tr><td style="background: url(/assets/images/tooltip/bg.png) no-repeat top left;"/>&nbsp;</td><td style="background:url(/assets/images/tooltip/bg.png) no-repeat top right;"/>&nbsp;</td></tr>';
		tbl+= '<tr><td style="background: url(/assets/images/tooltip/bg.png) no-repeat bottom left;"/>&nbsp;</td><td style="background:url(/assets/images/tooltip/bg.png) no-repeat bottom right;"/>&nbsp;</td></tr>';
		tbl+= '</table>';
		span.BG.innerHTML = tbl;
		span.appendChild(span.BG);
	}
	span.DIV.style.display='block';
	span.BG.style.display='block';
}
/**
* Load a subform record with ajax into it's subform
*/
function loadSubRecord(tableId,recordId)
{
	var url = '/admin/edit/index.php?table='+tableId+'&ID='+recordId+'&xml=1';
	//alert(url);
	var xmlHttp;
	try
	{
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	}
	catch (e)
	{
		// Internet Explorer
		try
		{
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			try
			{
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e)
			{
				alert("Your browser does not support AJAX!");
				return false;
			}
		}
	}
	xmlHttp.onreadystatechange=function()
	{
		if(xmlHttp.readyState==4)
		{
			//find the subform fields
			var fieldNodes = xmlHttp.responseXML.firstChild.getElementsByTagName('field');
			var inputTypes = ['INPUT','SELECT','TEXTAREA'];
			for(var i=0;i<inputTypes.length;i++)
			{
				var inputs = document.getElementsByTagName(inputTypes[i]);
				for(var j=0;j<fieldNodes.length;j++)
				{
					var fieldName = fieldNodes[j].getAttribute('name');
					for(var k=0;k<inputs.length;k++)
					{
						if(-1 != inputs[k].name.indexOf('fields['+tableId+']['+fieldName+']'))
						{
							var fieldValue = fieldNodes[j].getAttribute('value');
							switch(inputTypes[i])
							{
								case 'SELECT':
								for(var m=0;m<inputs[k].options.length;m++)
								{
									if(inputs[k].options[m].value==fieldValue)
									{
										inputs[k].options[m].selected = true;
									}
								}
								break;

								default:
								inputs[k].value = fieldValue;
								break;
							}
						}
						else
						{
							if(inputs[k].name=='AddSub['+tableId+']')
							{
								inputs[k].value==1 ? inputs[k].checked = true : inputs[k].checked = false;
							}
						}
					}
				}
			}
			showSubform(tableId);
		}
	}
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}
function showSubform(tableId)
{
	var inputs = document.getElementsByTagName('INPUT');
	for(var k=0;k<inputs.length;k++)
	{
		if(inputs[k].name=='AddSub['+tableId+']')
		{
			inputs[k].parentNode.parentNode.style.display = 'block';
		}
	}
}
function validateEditForm()
{

	var inputTypes = ['INPUT','SELECT','TEXTAREA'];
	for(var i=0;i<inputTypes.length;i++)
	{
		var inputs = document.getElementById('editForm').getElementsByTagName(inputTypes[i]);
		for(var j = 0;j<=inputs.length;j++)
		{
			try{
				if(!inputs[j].onchange())
				{
					return false;
				}
			}catch(e){

			}
		}
	}
	return true;
}


var CURRENT_FIELDSET = null;

window.onload = function()
{	
	try{
		var loc = new String(window.location);
		var subTableId = 0;

		//if((loc.indexOf('table=70') !=-1 || loc.indexOf('table=95') !=-1 || loc.indexOf('table=96') !=-1) && loc.indexOf('/admin/edit')!=-1)
		if(loc.indexOf('/admin/edit')!=-1)
		{
			// create a new panel for the nav
			var newPanel = document.createElement('DIV');
			newPanel.className = 'adminpanel';
			document.getElementById('leftnav').insertBefore(newPanel,document.getElementById('leftnav').firstChild);

			// Try and create the village halls edit form
			var heading = document.createElement('H2');
			heading.innerHTML = 'Edit <strong><em>'+CB_getHallName()+'</em></strong>';


			newPanel.appendChild(heading);
			var ul = document.createElement('UL');
			document.getElementById('editForm').style.display = 'none';
			var fieldsets = document.getElementById('editForm').childNodes;
			var subformOpen = document.getElementById('subformOpen').value;

			/**
			* Do the top level "Main Record" form
			*/
			var a = createFieldsetNavLink(fieldsets[0],0);
			if(null!=a)
			{
				var li = document.createElement('LI');
				li.appendChild(a);
				ul.appendChild(li);
			}

			if('0'==subformOpen)
			{
				a.onclick();
			}

			newPanel.appendChild(ul);
			var ul = document.createElement('UL');
			li.appendChild(ul);

			/**
			* Now do all the sub forms
			*/
			for(var i = 1 ; i < fieldsets.length ; i++)
			{
				if('fieldset'==fieldsets[i].nodeName.toLowerCase())
				{
					var legends = fieldsets[i].getElementsByTagName('LEGEND');
					var legend = legends[1];
					var m = legend.getElementsByTagName('INPUT')[0].name.match(/\[([0-9]+)\]/);
					subTableId = m[1];


					var a = createFieldsetNavLink(fieldsets[i],subTableId);
					if(null!=a)
					{
						var li = document.createElement('LI');
						li.appendChild(a);
						ul.appendChild(li);
					}


					if(subTableId==subformOpen && subTableId!=0)
					{
						a.onclick();
					}
				}
			}
			// Finally, create a footer for the bottom of the panel
			var footer = document.createElement('DIV');
			footer.className = 'footer';
			newPanel.appendChild(footer);
		}
	}catch(e){
		//alert(e);
	}


	try{
		document.getElementById('editForm').style.display = 'block';
	}catch(e){

	}


	try{
		new SlideShow('slideshow');
	}catch(e){

	}
}


/**
* Parse the fieldsets in #editForm to create links in the navigation bar to
* show and hide them in turn
*/
function createFieldsetNavLink(fieldset,tableId)
{
	var legends = fieldset.getElementsByTagName('LEGEND');
	var legend = legends[0].firstChild.nodeValue;
	var a = document.createElement('A');
	fieldset.A = a;
	fieldset.style.display = 'none';
	a.FIELDSET = fieldset;
	a.TABLE = tableId;
	a.FORM = fieldset.form;
	a.onclick = function()
	{
		if(undefined!=CURRENT_FIELDSET)
		{
			try{
				CURRENT_FIELDSET.style.display = 'none';
				CURRENT_FIELDSET.A.parentNode.className = '';
			}catch(e){
				alert(e);
			};
		}
		CURRENT_FIELDSET = this.FIELDSET;
		CURRENT_FIELDSET.style.display = 'block';

		document.getElementById('subformOpen').value = tableId;
		this.parentNode.className = this.className = 'current';

	}
	a.href = '#';
	var txt = document.createTextNode(legend);
	a.appendChild(txt);

	return a;

	return null;
}



/**
* Parse through the fields in the editForm to determine the name of
* the Hall being edited
*/
function CB_getHallName()
{
	/**
	* temp as hall names generally too big for the side nav header
	*/
	return 'Hall';


	var inputs = document.getElementById('editForm').getElementsByTagName('INPUT');
	for(var i = 0;i<inputs.length;i++)
	{
		if(-1 != inputs[i].name.indexOf('[name]'))
		{
			return inputs[i].value;
		}
	}
}



/**
* @desc Create and show an iframe to display the attributes list-records embedded into the page
*/
function showAttributeAdder(a)
{
	var iframe;
	var width = 650;
	var height = 500;
	var url = '/admin/list/index.php?table=165';



	if(isIE(6))
	{
		a.href = url;
		a.setAttribute('target','_blank');
		return;
	}



	//Put the rest of the form into shade
	SHADE = new Image();
	SHADE.src = '/assets/shells/CommunityBuildings/images/bgShade.png';
	SHADE.style.height = document.body.parentNode.scrollHeight+'px';
	SHADE.style.left = '0px';
	SHADE.style.position = 'absolute';
	SHADE.style.top = '0px';
	SHADE.style.width = document.body.parentNode.offsetWidth+'px';
	document.body.appendChild(SHADE);



	if (document.all)
	{
		iframe = document.createElement('<iframe onload="window.iframeLoaded();" frameborder="0" allowtransparency="true"></iframe>');
	}
	else
	{
		iframe = document.createElement('IFRAME');
	}
	iframe.src = url;
	iframe.style.border = '0';
	iframe.style.left = '25%';
	iframe.style.display = 'none';
	iframe.style.height = height+'px';
	iframe.style.marginLeft = (-width/2)+'px';
	iframe.style.position = 'absolute';
	iframe.style.top = getAbsoluteTop(a)-100+'px';
	iframe.style.width = width+'px';


	window.iframeLoaded = function()
	{
		var iframeDoc;

		if(document.all)
		{
			iframeDoc = iframe.contentWindow.document;
		}
		else
		{
			iframeDoc = iframe.contentDocument;
		}


		var mainContainer = iframeDoc.getElementById('main');
		var contentContainer = iframeDoc.getElementById('content');

		/**
		* Add some extra styling
		*/
		var l = iframeDoc.createElement('LINK');
		l.rel = 'stylesheet';
		l.href = '/assets/shells/CommunityBuildings/stylesheets/iframe.css';
		iframeDoc.body.appendChild(l);
		/**
		* And a close button
		*/
		var i = iframeDoc.createElement('INPUT');
		i.className = 'closeButton';
		i.type = 'button';
		i.value = 'Close Window';
		i.onclick = function(){
			iframe.close();
		}
		iframeDoc.body.appendChild(i);

		iframe.close = function()
		{
			this.parentNode.removeChild(this);
			SHADE.parentNode.removeChild(SHADE);
		}
		iframeDoc.onkeydown = document.body.onkeydown = function(e)
		{
			var keynum;
			if(window.event) // IE
			{
				keynum = window.event.keyCode;
			}
			else if(undefined!=e.which) // Netscape/Firefox/Opera
			{
				keynum = e.which;
			}

			if(keynum==KEY_ESCAPE)
			{
				iframe.close();
			}

		}
		iframe.style.display = 'block';
		iframe.focus();
		iframe.scrollIntoView();
	}

	iframe.onload = iframeLoaded;
	document.body.appendChild(iframe);
}

