function showelementsofclass(type,classname, rootid)
{
	root = document.getElementById(rootid);
	if (rootid  && root)
	{
		classitems = YAHOO.util.Dom.getElementsByClassName(classname, type, root);
	}
	else
	{
		classitems = YAHOO.util.Dom.getElementsByClassName(classname, type);
	}

	for(i=0;i<classitems.length;i++)
	{
		if (type.toLowerCase() =='tr' && navigator.appName!='Microsoft Internet Explorer')
		{
			classitems[i].style.display='table-row';
		}
		else if (type.toLowerCase() == 'span')
		{
			classitems[i].style.display='inline';
		}
		else
		{
			classitems[i].style.display='block';
		}
	}
}

function hideelementsofclass(type,classname, rootid)
{
	root = document.getElementById(rootid);
	if (rootid  && root)
	{
		classitems = YAHOO.util.Dom.getElementsByClassName(classname, type, root);
	}
	else
	{
		classitems = YAHOO.util.Dom.getElementsByClassName(classname, type);
	}

	for(i=0;i<classitems.length;i++)
	{
			classitems[i].style.display='none';
	}
}

function showelementwithid(id)
{
	element = document.getElementById(id);
	if(element == null)
	{
		return;
	}
	type = element.tagName;
	if (type.toLowerCase() =='tr' && navigator.appName!='Microsoft Internet Explorer')
		{
			element.style.display='table-row';
		}
		else
		{
			element.style.display='block';
		}
}

function hideelementwithid(id)
{
	element = document.getElementById(id);
	if (element != undefined)
		element.style.display='none';
}


function toggleelementwithid(id)
{
	element = document.getElementById(id);
	if(element != undefined)
	{
		if(element.style.display=='none')
		{
			showelementwithid(id);
		}
		else
		{
			hideelementwithid(id);
		}
	}
}



function toggledivbyclass(name)
{
	classitems=YAHOO.util.Dom.getElementsByClassName(name, 'div');
	for(i=0;i<classitems.length;i++)
	{
		if(classitems[i].style.display!='none')
		{
			classitems[i].style.display='none';
		}
		else
		{
			classitems[i].style.display='block';
		}
	}
}
var timeout=Array;
function displaydiv(name)
{
	document.getElementById(name).style.display='block';
	window.clearTimeout(timeout[name]);
	timeout[name]=window.setTimeout("hidediv('"+name+"');",10000);
}


function displaydivinline(name)
{
	document.getElementById(name).style.display='inline';
	window.clearTimeout(timeout[name]);
	timeout[name]=window.setTimeout("hidediv('"+name+"');",10000);
}

function displayspan(name)
{
	document.getElementById(name).style.display='inline';
	window.clearTimeout(timeout[name]);
	timeout[name]=window.setTimeout("hidediv('"+name+"');",10000);
}
function hidediv(name)
{
	window.clearTimeout(timeout[name]);
	timeout[name]=window.setTimeout("document.getElementById('"+name+"').style.display='none'",100);
}
// Like displaydiv but without the timeout
function showdiv(id)
{
	document.getElementById(id).style.display='block';
}
function togglediv(name)
{
	if(document.getElementById(name).style.display!='none')
	{
		document.getElementById(name).style.display='none';
	}
	else
	{
		document.getElementById(name).style.display='block';
	}
}

function togglelabel(name,label1,label2)
{
	if (document.getElementById(name).innerHTML == label1)
		document.getElementById(name).innerHTML = label2;
	else
		document.getElementById(name).innerHTML = label1;
}

function toggledivandlabel(divname,labelname,hidelabel,showlabel)
{
	if(document.getElementById(divname).style.display!='none')
	{
		document.getElementById(divname).style.display='none';
		document.getElementById(labelname).innerHTML = showlabel;
	}
	else
	{
		document.getElementById(divname).style.display='block';
		document.getElementById(labelname).innerHTML = hidelabel;
	}
}


function nse(to,domain)
{
	document.location='mailto:'+to+'@'+domain;
}

function highlight(n) {
        var div = document.getElementById(n);
        if(!div)
                return;
		div.style.background="rgb(230,240,255)";
}
function nohighlight(n) {
        var div = document.getElementById(n);
        if(!div)
                return;
		div.style.background="transparent";
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function ConfirmBlockDelete()
{
return confirm("This will delete the block AND ALL CHILD BLOCKS it may contain.");
}
function ConfirmFolderDelete()
{
return confirm("=== CAUTION ===\n\nThis will delete the folder and ALL PAGES AND SUBFOLDERS\nit may contain.");
}
function ConfirmPageDelete()
{
return confirm("This will delete the page and any contents.");
}
function ConfirmDelete()
{
return confirm("Are you sure you want to delete?");
}
function NotNull(name)
{
	if(document.getElementById(name).value=='')
		alert('You must put a reason for deleting the items.');
	return document.getElementById(name).value!='';
}

/*does all processing on genenric amounts of linked selects!!!
<script type="text/javascript">
<!--
selects=new Array();
selects[0]=document.forms['FrmAdminControl'].elements['test.0'];
selects[1]=document.forms['FrmAdminControl'].elements['test.1'];
selects[2]=document.forms['FrmAdminControl'].elements['test.2'];

initLinkedSelect(selects);
-->

requires following names on options so we know what goes where

<select name"=test.0">
<option value="dog">Dog</option>
<option value="cat">Cat</option>
</select>
<select name="test.1">
<option value="dog-fido">Fido</option>
<option value="dog-rover">Rover</option>
<option value="cat-boots">Boots</option>
<option value="cat-pussy">Pussy</option>
</select>
<select> name="test.2">
<option value="dog-fido-dead">Dead</options>
...
...
</select>
*/



// using a Select create divs with id equal to a options value and watch the div appear!
//set onchange="SelectDivFromDropDown(this)
function SelectDivFromDropDown(select)
{
	for(i=0;i<select.options.length;i++)
	{
		if(select.options[i].value && document.getElementById(select.options[i].value))
			document.getElementById(select.options[i].value).style.display='none';
	}
	if(document.getElementById(select.value))
		document.getElementById(select.value).style.display='block';
}

function LoadIframeFromForm(sURL,sFormName,sDivName,sExtraGetVars)
{
	//Get the URL
	var sURL='';
	sURL=SendAsGetToURL(sURL,sFormName)+sExtraGetVars;
	var ifrmdoc = getIframeDocument('frame.'+sFormName);

	if(document.getElementById(sDivName).style.display!='none')
	{
		document.getElementById(sDivName).style.display='none';
	}
	else
	{
		document.getElementById(sDivName).style.display='block';
		//Redirect the iframe.
		ifrmdoc.body.innerHTML='<p>Loading</p>';
		ifrmdoc.location.replace(sURL);
	}
}

function DocumentLocationFromFormField(sURLPrefix,sFormName,sFieldName,sExtraGetOptions)
{
	sURL = eval('document.'+sFormName+'.'+sFieldName+'.value');
	if (sURL=='')
	{
		return false;
	}

	if (sURL[0] == '#')
	{
		document.location=sURL;
		return false;
	}

	sURL=sURLPrefix+sURL;
	// Same as current page (possible different anchor)?
	if (document.location.href.replace(/[#|\?].*$/,'') == sURL.replace(/[#|\?].*$/,''))
	{
		document.location='#'+sURL.replace(/^.*#/,'');
		return false;
	}
	if (sExtraGetOptions)
		sURL += '?'+sExtraGetOptions;
	document.location = sURL;
	return false;
}

function OpenWindowFromForm(sURL,sFormName,sExtraGetOptions)
{
	sURL=SendAsGetToURL(sURL,sFormName)+sExtraGetOptions;
	window.open(sURL,"","width=200,height=200,location=yes,scrollbars");
}

function SendAsGetToURL(sURL,sFormName)
{
	var sGetString='';
	if(FormCollection[sFormName])
	{
		for (sFieldName	in FormCollection[sFormName])
		{
			if(eval('document.'+sFormName+'.'+sFieldName+'.type')=='checkbox')
			{

				if (eval('document.'+sFormName+'.'+sFieldName+'.checked'))
					sGetString+=sFieldName+'='+eval('document.'+sFormName+'.'+sFieldName+'.checked')+'&';
			}
			else
			{
				sGetString+=sFieldName+'='+eval('document.'+sFormName+'.'+sFieldName+'.value')+'&';
			}

		}
	}
	return sURL+'?'+sGetString;

}
function getIframeDocument(id) {
	if(document.frames)
		return document.frames[id].document;
	var ifrm = getid(id);
	if(ifrm.contentDocument)
		return ifrm.contentDocument;
	else if(ifrm.contentWindow)
		return ifrm.contentWindow.document;
	else if(ifrm.document)
		return ifrm.document;
}
function getid(id) {
	if(document.getElementById)
		return document.getElementById(id);
	else if(document.all)
		return document.all(id);
	return false;
}

function PleaseWait(button)
{
	button.value='PLEASE WAIT';
	button.style.color='red';
	button.onclick= function() {
		alert('Please Wait');
		return false;
	}
	return false;
}

function SendFormValue(ToURL,FormElement,GetVarName)
{
	document.location.replace(ToURL+'?'+GetVarName+'='+FormElement.value);
}
function setIDHTMLToVal(fieldElement,someID)
{
	span=getElementById(someID);
	if(span)
	{
		span.innerHTML=this.value;
	}
}
function docnoperm(s)
{
	alert(s);
	return false;
}

function PutFormHere(sFormName,oParent)
{
	var oForm;
	oForm=document.getElementById(sFormName);
	if(oForm)
	{
		oParent.appendChild(oForm);
	}
}
function SetHiddenValue(sFormName,sFieldName,sValue)
{
	var oForm;
	oForm=document.getElementById(sFormName);
	if(oForm && oForm.elements[sFieldName])
	{
		oForm.elements[sFieldName].value=sValue;
	}
	else
	{
		alert('could not find element '+sFieldName);
	}
}
function MoveCommentFormHere(sElementName,sValue)
{
	oElement=document.getElementById(sElementName);
	SetHiddenValue('FrmComment','parentcommentid',sValue);
	PutFormHere('FrmComment',oElement);
	return false;
}
function ConfirmRecursiveCommentDelete()
{
	return confirm("Are you sure you want to delete this comment\nincluding all those comments made upon it?");
}
function ConfirmArticleDelete()
{
	return confirm("Are you sure you want to delete this item\nincluding all those comments made upon it?");

}

function SetupCommentReply(fromdiv_id, commentid)
{
	fromdiv = document.getElementById(fromdiv_id); 	// fromdiv: the div of the comment
	todiv = document.getElementById('contextcomment'); 	// todiv: an empty dive just above the reply form
	jumptothread_div = document.getElementById('jumptothread'); // jumptothread_div: a second empty div just above the reply form
	title = document.getElementById('formtitle'); // reply form title
	link = document.getElementById('comment_'+commentid);
	link.href='javascript:void(0);';

	// Copy the comment to just above the reply box
	todiv.innerHTML = fromdiv.innerHTML;
	todiv.style.display = 'block';

	// Add a link to jump back to the thread of the comment from the reply
	jumptothread_div.innerHTML = '<a class="link" href="#anchor_comment_' + commentid + '">Jump to thread</a>';
	jumptothread_div.style.display = 'block';

	// Set the title of the reply box
	title.innerHTML = '<strong>Reply to comment</strong>';
	// Set some form inputs so that the reply ends up in the right place in the tree when the form is submitted
	document.forms.FrmComment.parentcommentid.value = commentid;
	// jump to the reply
	ScrollToElement(todiv);
	return false;
}

function ScrollToElement(element)
{
 	var desty = element.offsetTop;
	var thisNode=element;
	 while (thisNode.offsetParent &&
       (thisNode.offsetParent != document.body)) {
	   thisNode = thisNode.offsetParent;
	   desty += thisNode.offsetTop;
	 }
	window.scrollTo(0,desty);
}

function ScrollToID(id)
{
	var id=document.getElementById(id);
	ScrollToElement(id);
}

function SetupNewComment()
{
		// Set the title of the reply box
	title = document.getElementById('formtitle');
	title.innerHTML = '<strong>Add a comment</strong>';
	// Set some form inputs so that the reply ends up in the right place in the tree when the form is submitted
	document.forms.FrmComment.parentcommentid.value = '';
	// Hide the reply divs
	todiv = document.getElementById('contextcomment');
	jumptothread_div = document.getElementById('jumptothread');
	todiv.innerHTML = '';
	jumptothread_div.innerHTML = '';
	return false;
}



function showDebugWindow() {
  window.top.debugWindow =
      window.open("",
                  "Debug",
                  "left=0,top=0,width=300,height=700,scrollbars=yes,"
                  +"status=yes,resizable=yes");
  window.top.debugWindow.opener = self;
  // open the document for writing
  window.top.debugWindow.document.open();
  window.top.debugWindow.document.write(
      "<HTML><HEAD><TITLE>Debug Window</TITLE></HEAD><BODY><PRE>\n");
}

function debugToWindow(text) {
  if (window.top.debugWindow && ! window.top.debugWindow.closed) {
    window.top.debugWindow.document.write(text+"\n");
  }
  else
  {
  	showDebugWindow();
  	 window.top.debugWindow.document.write(text+"\n");
  }
}

function _builddebugstr(obj)
{
	var temp = ""
	for (x in obj)
	{
		 if(typeof(x)=='object')
			temp += _builddebugstr(obj[x]);
		else
			temp += x + ": " + obj[x] + "\n";
	}
	return temp;
}


function debugObject(obj)
{
	if (obj == undefined)
		debugToWindow('undefined');
	else
	{
		var temp = "";
		temp = _builddebugstr(obj);
		debugToWindow(temp);
	}
}

function ClearForm(frm)
{
    for (n=0; n<frm.elements.length; n++)
    {
      switch (frm.elements[n].type)
      {
      	case 'hidden':
      	case 'button':
      	case 'submit':
      		break;
        case 'text':
        case 'textarea':
        case 'password':
        case 'fileupload':
        case 'radio':
        frm.elements[n].value = '';
        break;
        case 'checkbox':
        frm.elements[n].checked = false;
        break;
        case 'select-one':
        case 'select-multiple':

        // this test avoids the reseting of date fields.
        if (frm.elements[n].options[0].value == 'Any' || frm.elements[n].options[0].value == '__Any__' || frm.elements[n].options[0].value == '')
        	frm.elements[n].selectedIndex = 0;
        break;

        default :
        	// DS: I think it's better to silently fail on production sites...
//        	alert('Element of type ' + frm.elements[n].type);

      }
      // if any of the search elements have onchange javascript then run it
      if (frm.elements[n].onchange != undefined)
      {
      	frm.elements[n].onchange({target: frm.elements[n]}); // CB: dummy event object works around bug in checkbox group widget
      }
    }
  }


function SetInitialI18NWidget()
{
	HideNonPreferredI18NWidgets();
	ShowPreferredI18NWidget();
}

function HideNonPreferredI18NWidgets()
{
	for (sWidgetID in aI18NWidgets)
	{
		for(sLangID in aLangs)
		{
			oWidget=document.getElementById(aI18NWidgets[sWidgetID]+aLangs[sLangID]);
			if(oWidget)
			{
				if(aLangs[sLangID]!=sPreferredLang)
				{
					oWidget.style.display='none';
					oFlag=document.getElementById(aI18NWidgets[sWidgetID]+aLangs[sLangID]+'_img');
					oFlag.style.border = '0px solid black';
				}
			}
		}
	}
}

function ShowPreferredI18NWidget()
{
	for (sWidgetID in aI18NWidgets)
	{
		for(sLangID in aLangs)
		{
			oWidget=document.getElementById(aI18NWidgets[sWidgetID]+aLangs[sLangID]);
			if(oWidget)
			{
				if(aLangs[sLangID]==sPreferredLang)
				{
					oWidget.style.display='inline';

					oFlag=document.getElementById(aI18NWidgets[sWidgetID]+aLangs[sLangID]+'_img');
					oFlag.style.border = '1px solid black';
				}
			}
		}
	}
}


function SetPreferredI18NWidget(sLang)
{
	sPreferredLang=sLang;
}

function SwapI18NWidget(sLang)
{
	SetPreferredI18NWidget(sLang);
	HideNonPreferredI18NWidgets();
	ShowPreferredI18NWidget();
}

function ChangeI18NWidgetsFromCheckBox(sLang,oCheckBox)
{
	if(oCheckBox.checked)
	{
		for (sWidgetID in aI18NWidgets)
		{
			oWidget=document.getElementById(aI18NWidgets[sWidgetID]+sLang);
			oWidget.style.display='inline';
			oImage=document.getElementById(aI18NWidgets[sWidgetID]+sLang+'_img');
			oImage.style.display='inline';
		}
	}
	else
	{
		for (sWidgetID in aI18NWidgets)
		{
			oWidget=document.getElementById(aI18NWidgets[sWidgetID]+sLang);
			oWidget.style.display='none';
			oImage=document.getElementById(aI18NWidgets[sWidgetID]+sLang+'_img');
			oImage.style.display='none';
		}

	}
}

function PreventI18NFlagJS()
{
	var done='';
	for (sWidgetID in aI18NWidgets)
	{
		for(sLangID in aLangs)
		{
			oImage=document.getElementById(aI18NWidgets[sWidgetID]+aLangs[sLangID]+'_img');
			if(oImage)
			{
				oImage.onclick=function() {};
				if(aLangs[sLangID]!=sPreferredLang)
					oImage.style.display='none';
			}
		}
	}

}

function moveElementToElement(elementId,moveToElementId)
{
	var moveToElement = document.getElementById(moveToElementId);
	var moveToX = findPosX(moveToElement);
	var moveToY = findPosY(moveToElement);
	moveObject(elementId, moveToX, moveToY);
}


function moveObject(id,x,y)
{
	var styleObject = getStyleObject(id);
    if(styleObject)
    {
		styleObject.left = x;
		styleObject.top = y;
		return true;
    }
    else
    {
		return false;
    }
}
var xOffset = 30;
var yOffset = -5;


function showPopupDiv(targetID, event)
{
	// hide any other popups that are still open
	if (window.currentPopupID)
	{
		var CurrentPopupStyle = getStyleObject(currentPopupID);
		if (CurrentPopupStyle)
		{
			CurrentPopupStyle.visibility = 'hidden';
			window.currentPopupID = false;
		}
	}
	if(event)
	{

		var moveToX = (event.pageX)?event.pageX + xOffset:event.x + xOffset + ((document.body.scrollLeft)?document.body.scrollLeft:0);
		var moveToY = (event.pageY)?event.pageY + yOffset:event.y + yOffset + ((document.body.scrollTop)?document.body.scrollTop:0);
		moveObject(targetID, moveToX, moveToY);
		var styleObject = getStyleObject(targetID);
    	if(styleObject)
    	{
			styleObject.visibility = 'visible';
			window.currentPopupID = targetID;
    	}
	}
}

function hidePopupDiv(targetID)
{
	var styleObject = getStyleObject(targetID);
    	if(styleObject)
    	{
			styleObject.visibility = 'hidden';
			window.currentPopupID = false;
    	}
}

function hidePopupDivDelay(targetID)
{
	window.setTimeout("hidePopupDiv('"+targetID+"')",20);

}

function getStyleObject(objectId) {
    // cross-browser function to get an object's style object given its id
    if(document.getElementById && document.getElementById(objectId)) {
	// W3C DOM
	return document.getElementById(objectId).style;
    } else if (document.all && document.all(objectId)) {
	// MSIE 4 DOM
	return document.all(objectId).style;
    } else if (document.layers && document.layers[objectId]) {
	// NN 4 DOM.. note: this won't find nested layers
	return document.layers[objectId];
    } else {
	return false;
    }
} // getStyleObject



//Some basic AJAX stuff

function createRequestObject() {
    var ro;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer"){
        ro = new ActiveXObject("Microsoft.XMLHTTP");
    }else{
        ro = new XMLHttpRequest();
    }
    return ro;
}

var http = createRequestObject();
var logIdToUpdate='';

function sndMenuReq(action,obj) {
 	sndReq(action,'div'+obj.id)
}

function sndReq(action,idToUpdate) {
    http.open('get', action);
    http.onreadystatechange = handleResponse;
    http.send(null);
	logIdToUpdate=idToUpdate;
	element=document.getElementById(logIdToUpdate);
	if(element && element.innerHTML=='')
	{
		element.innerHTML='<em>Loading...</em>';
	}
}
function handleResponse() {
    if(http.readyState == 4){
        var response = http.responseText;
		element=document.getElementById(logIdToUpdate);
		if(element)
			element.innerHTML=response;
    }
}

function createCMSFolder(urlToCreate)
{
	var now= new Date();
	var action = '?aj=1&folder='+urlToCreate+'&_tr=FrmMakeCMSFolder&_ts='+Math.round(now.getTime()/1000);
	var main=document.getElementById('Main');
	main.innerHTML='<em>Loading ...</em>';
    http.open('get', action);
    http.onreadystatechange = handleResponseCreateCMSFolder;
    http.send(null);
	logIdToUpdate='Main';
	element=document.getElementById(logIdToUpdate);
	if(element && element.innerHTML=='')
	{
		element.innerHTML='<em>Loading...</em>';
	}
	window.scrollTo(0,0);
}

function handleResponseCreateCMSFolder() {
    if(http.readyState == 4){
        var response = http.responseXML.documentElement;
		var innerHTML='';
		var js='';
		var bGotJS;
		var items;
		element=document.getElementById(logIdToUpdate);
		items=response.getElementsByTagName('content');
		for(i=0;i<items.length;i++)
		{
	        if (items[i].childNodes.length > 1)
			{
        	    innerHTML+= items[i].childNodes[1].nodeValue;
    	    } else {
	            innerHTML+= items[i].firstChild.nodeValue;
			}
		}
		if(element)
			element.innerHTML=innerHTML;
		bGotJS=false;
		items=response.getElementsByTagName('jscript');
		for(i=0;i<items.length;i++)
		{
			bGotJS=true;
	        if (items[i].childNodes.length > 1)
			{
        	    js+= items[i].childNodes[1].nodeValue;
    	    } else {
	            js+= items[i].firstChild.nodeValue;
			}
		}
		eval(js);

    }
}

function createCMSPage(urlToCreate)
{
	var now= new Date();
	var action = '?aj=1&page='+urlToCreate+'&_tr=FrmMakeCMSPage&_ts='+Math.round(now.getTime()/1000);
	var main=document.getElementById('Main');
	main.innerHTML='<em>Loading ...</em>';
	sndReq(action,'Main');
	window.scrollTo(0,0);
}

function displayMap(id)
{
	var oChosenElement;
	var oUnChosenElement;
	for(i=0;i<20;i++)
	{
		oUnChosenElement= document.getElementById('map_'+i)
		if (oUnChosenElement)
		{
			oUnChosenElement.style.display='none';
		}
	}
	oChosenElement=document.getElementById(id);
	if(oChosenElement)
		oChosenElement.style.display='block';
}

function CharsRemaining(textarea)
{
	var max = parseInt(textarea.getAttribute("maxlength"), 10);
	var curr = textarea.value.length;
	return max - curr;
}

function CharsRemaining(textarea)
{
	var max = parseInt(textarea.getAttribute("maxlength"), 10);
	// Ensure that newlines are counted as 2 chars so that the count is standardised across browsers.
	var curr = expandNewlines(textarea.value).length;
	return max - curr;
}
 
/**
	When counting text in textareas we need to ensure that all newlines are two chars. 
	Deal with differing representations of newlines in text areas across browsers.
	(IE uses \r\n, FF and chrome use \n W3C standard says \r\n.)
	When form is submitted it will contain \r\n so this is what PHP will count.
	This function replaces all instances of \n with \r\n
*/
function expandNewlines(string)
{
	// Regex to find any \n not preceeded by a \r.
	// /(?!\r)\n/g, "\r\n");
	// Can you guess which browsers dont support lookaheads in regular expressions?
	// Use an inelegent pair of string replacements instead.
	var expandedString = string.replace(/\n/g, "\r\n").replace(/\r\r\n/g, "\r\n");
	return expandedString;
}


function isMaxLength(obj){
var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
if (obj.getAttribute && obj.value.length>mlength)
obj.value=obj.value.substring(0,mlength)
}

function IsNumeric(sText)

{
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;


   for (i = 0; i < sText.length && IsNumber == true; i++)
      {
      Char = sText.charAt(i);
      if (ValidChars.indexOf(Char) == -1)
         {
         IsNumber = false;
         }
      }
   return IsNumber;

   }

  function findPosX(obj)
  {
    var curleft = 0;
    if(obj.offsetParent)
        while(1)
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
  }

  function findPosY(obj)
  {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
  }

  // returns true if given x,y coords are within the boundry of the elmenent
  function coordsInElement(x,y,elementId)
  {
  	e = document.getElementById(elementId);
  	x1pos = findPosX(e);
  	x2pos = x1pos + e.offsetWidth;
  	y1pos = findPosY(e);
  	y2pos = y1pos + e.offsetHeight;
  	if (x >= x1pos && x <= x2pos && y >= y1pos && y <= y2pos)
  		return true;

  	return false;

  }

  // Stop events from bubbling up the DOM.
  // Example usage: onClick="alert('Gufnork fluff!'); stopEventPropogation(event)"
  function stopEventPropagation(event)
  {
  	if (event.stopPropagation)
  	{
  		// Moz
  		event.stopPropagation();
  	}
  	else
  	{
  		// IE
  		window.event.cancelBubble = true;
  	}

  }

  // Return the nearest parent node of specified tagname
  function parentNodeOfType(element, tagname)
  {
  	var pa=element.parentNode;
	while(pa.tagName.toLowerCase()!=tagname.toLowerCase() && pa.parentNode)
	{
		pa=pa.parentNode;
	}

	if (pa.tagName.toLowerCase() == tagname.toLowerCase())
	{
		return pa;
	}

	return undefined;
  }

function eventTarget(event)
{
	if (!event)
		event = window.event;

	if (event.target)
	{
  		element = event.target;
  	}

  	if (event.srcElement)
  		element = event.srcElement;

  	if (element.nodeType == 3) // defeat Safari bug
		element = element.parentNode;

	return element;
}

function showNextTableRow(e)
{
	var thisElement = eventTarget(e);

	if (thisElement.tagName == 'TR')
		tr = thisElement;
	else
		tr = parentNodeOfType(thisElement,'TR');
	if (!tr)
		return;

	nextIndex = tr.rowIndex+1;
	nextTr = tr.parentNode.parentNode.rows[nextIndex];
	nextTr.style.display='';
}

function hideThisTableRow(e)
{
	thisElement = eventTarget(e);
	if (thisElement.tagName == 'TR')
		tr = thisElement;
	else
		tr = parentNodeOfType(thisElement,'TR');

	if (!tr)
		return;
	tr.style.display='none';
}

function hideNextTableRow(e)
{
	var thisElement = eventTarget(e);
	if (thisElement.tagName == 'TR')
		tr = thisElement;
	else
		tr = parentNodeOfType(thisElement,'TR');

	if (!tr)
		return;

	nextIndex = tr.rowIndex+1;
	nextTr = tr.parentNode.parentNode.rows[nextIndex];
	nextTr.style.display='none';
}

function hidePrevTableRow(e)
{
	var thisElement = eventTarget(e);

	if (thisElement.tagName == 'TR')
		tr = thisElement;
	else
		tr = parentNodeOfType(thisElement,'TR');

	if (!tr)
		return;

	prevIndex = tr.rowIndex-1;
	prevTr = tr.parentNode.parentNode.rows[prevIndex];
	prevTr.style.display='none';
}

function showPrevTableRow(e)
{
	var thisElement = eventTarget(e);

	if (thisElement.tagName == 'TR')
		tr = thisElement;
	else
		tr = parentNodeOfType(thisElement,'TR');

	if (!tr)
		return;

	prevIndex = tr.rowIndex-1;
	prevTr = tr.parentNode.parentNode.rows[prevIndex];
	prevTr.style.display='';
}

/* Adds a class to an elements class attribute */
function addClass(element, addClass)
{
	if (!hasClass(element, addClass))
	{
		element.className += (element.className ? ' ' : '') +  addClass;
		return true;
	}
	return false;
}

/* Returns true if element has given class */
/* specify a single class */
/*
Interesting fact about IE 7 (and probably 6). 'class' is a reserved word so IE will produce some vague and entirely useless error message if 'class' is used as
the name of a variable.  Someone should send MS developers on a course in writing error messages, or shoot them.
*/
function hasClass(element, className)
{
	if (element.className == '')
	{
		return false;
	}

	return new RegExp('\\b' + className + '\\b').test(element.className);
}

/* Removes class from elements class attribute */
function removeClass(element, removeClass)
{
	if (hasClass(element, removeClass))
	{
		element.className  = element.className.replace(element.className.indexOf(' ' + removeClass) >= 0 ? ' ' + removeClass : removeClass)

	}
}

