// Gecho Content Handling Routines for Administration. All code and Concepts are the property of Pear Zoo Marketing and may not be used
// in any format manner or means, at all, ever.

var theObject;
var objectsHidden;
var filePop;
var theTriggerObj;
var triggerBox;
var helpArray = new Array;
var addedGechoMenu = new Array;
var winHeight;
var winWidth;
var startPos;
var gwindow;
var gwindowSpell;
var gwindowFile;
var editStuffing;
var advancedShow = false;
var showPageEdit = false;
var showAppzEdit = false;
var lastObject;
var beenCalled;
var ua = navigator.userAgent.toLowerCase();
var isIE = ((ua.indexOf("msie") != -1) && (ua.indexOf("opera") == -1) && (ua.indexOf("webtv") == -1));
var isGecko = (ua.indexOf("gecko") != -1);
var skipValidate;
rePosition();
createMenuLayer();
setEventHandler();

function setEventHandler (){
	if (document.addEventListener){
		// Intelligent browsers
		document.addEventListener("click", gechoChoose, true);
		document.addEventListener("mouseover", gechoChoose, true);
		document.addEventListener("mouseout", gechoChoose, true);
		window.addEventListener("resize", rePosition,true);
		window.addEventListener("unload", gclose, true);
	} else if (document.attachEvent) {
		// That beautiful browser IE
		document.attachEvent("onclick", gechoChoose);
		document.attachEvent("onmouseover", gechoChoose);
		document.attachEvent("onmouseout", gechoChoose);
		window.attachEvent("onresize", rePosition);
		window.attachEvent("onunload", gclose);
	}
}
function gechoChoose(e) { //v2.0
 var howWe;
 var whichEl;
 var eType;
 var retValue = true;
 var origElement;

 gshift();

 if (!e) e = window.event;
 if (e.srcElement){
  whichEl = e.srcElement;
 } else if (e.target){
  whichEl = e.target;
 } else {
  return;
 }
 
 origElement = whichEl;
 whichEl = gechoGetObject(whichEl);
 


    if ((e.ctrlKey == true && e.type == "click" ) || 
	(e.ctrlKey == false && e.type == "click" && (origElement.getAttribute('gechoid') == "parentObject" || origElement.getAttribute('gechoMenuLink') || origElement.getAttribute('gechoid') == "hiddenObject"))   ){
	
     if (e.stopPropagation) {
	e.stopPropagation();
     } else {
	e.cancelBubble = true;
	e.returnValue = false;
     }
     objectsHidden = true;
     showHide('OBJECT','hidden');
     howWe = whichEl.getAttribute('gechoid');
     showAgain(theObject);
     if (origElement.getAttribute('gechoid') == "hiddenObject"){
      showHide('OBJECT','visible');
      objectsHidden = false;
      document.getElementById('gMenu').style.visibility = "hidden";
      return;
     }
       objectsHidden = true;
       showHide('OBJECT','hidden');
       
     if (origElement.getAttribute('gechoid') == "parentObject"){
	if ( elementsParent(theObject)) {
		lastObject = theObject;
		var nextObject = gechoGetObject(elementsParent(theObject)); 
		if (sameObject( lastObject, nextObject)){
			whichEl = nextObject;
		} else {
			document.getElementById('parentObject').style.display = 'none';
			document.getElementById('parentObject').innerHTML = "";
			document.getElementById('parentObject').href = "#";
		}
	}
      } else if (origElement.getAttribute('gechoMenuLink') && e.type == "click" && addedGechoMenu[origElement.getAttribute('gechoMenuLink')] ) {
		document.getElementById('gMenu').style.visibility = "hidden";
		window.location = addedGechoMenu[origElement.getAttribute('gechoMenuLink')];
		return;
      } else {
       retValue = false;
      }
      
     if (whichEl.getAttribute('gechoid') && isGechObject(whichEl.getAttribute('gechoid')) == 'gecho'  ){
     
      theObject = whichEl;
      showAgain(theObject);
	
	setGechoMenu(whichEl, 'thisObjectEdit', 'Edit', '' ,whichEl.getAttribute('gechoid'));
	setGechoMenu(whichEl, 'thisRecordEdit', 'Edit', 'Table', whichEl.getAttribute('gechoid'));	
	setGechoMenu(whichEl, 'thisRecordAdd', 'Add', 'Table', whichEl.getAttribute('gechoid'));	
	setGechoMenu(whichEl, 'thisRecordDel', 'Del', 'Table', whichEl.getAttribute('gechoid'));	
	
	setGechoMenu(whichEl, 'thisPageEdit', 'Edit', 'Page', whichEl.getAttribute('gechoid'));	
	setGechoMenu(whichEl, 'thisPageAdd', 'Add', 'Page', whichEl.getAttribute('gechoid'));	
	setGechoMenu(whichEl, 'thisPageDel', 'Del', 'Page', whichEl.getAttribute('gechoid'));	
	
	setGechoMenu(whichEl, 'thisAppEdit', 'Edit', 'Appz', whichEl.getAttribute('gechoid'));	
	setGechoMenu(whichEl, 'thisAppAdd', 'Add', 'Appz', whichEl.getAttribute('gechoid'));	
	setGechoMenu(whichEl, 'thisAppDel', 'Del', 'Appz', whichEl.getAttribute('gechoid'));	
	
      var theP = elementsParent(whichEl);
      if ( theP ){
       if (isGechObject(whichEl.getAttribute('gechoid')) == "gecho" && sameObject(gechoGetObject(theP),whichEl) ){
        document.getElementById('parentObject').innerHTML = "Select more around this " + translateTag(whichEl.tagName);
        document.getElementById('parentObject').href = "#";
	document.getElementById('parentObject').style.display = '';
       } else {
	document.getElementById('parentObject').style.display = 'none';
        document.getElementById('parentObject').innerHTML = "";
        document.getElementById('parentObject').href = "#";
       }
      }
      if (objectsHidden == true){
       document.getElementById('hiddenObject').href = '#';
       document.getElementById('hiddenObject').innerHTML = "Show Hidden Objects";
      } else {
       document.getElementById('hiddenObject').href = '#';
       document.getElementById('hiddenObject').innerHTML = "";
      }

      if (howWe != "parentObject"){
       var altTop;
       var altLeft;
	if (isIE){
		altTop = document.body.scrollTop;
		altLeft = document.body.scrollLeft;
	} else {
		altTop = window.pageYOffset;
		altLeft = window.pageXOffset
	}
       document.getElementById('gMenu').style.left = e.clientX + altLeft + 'px';
       document.getElementById('gMenu').style.top = e.clientY + altTop + 'px';
       document.getElementById('gMenu').style.visibility = "visible";
      }

     }
    } else if (e.ctrlKey == false && ( e.type == "mouseover" || e.type == "mouseout" ) ) {
     
    // Mouseover functions
      if ( origElement.className == "gechoPop" && e.type == "mouseover" && origElement.innerHTML != "" ){
       origElement.className = "overCell";
       
      } else if (origElement.className == "overCell" && e.type == "mouseout"){
       origElement.className = "gechoPop";
      }
    } 
 return;
}

function showAgain (eToDim){
	if (eToDim){
		
		if ( eToDim.getAttribute("highLighted") == null ){
			//alert('No HiLight :: Saving ' + eToDim.tagName + ' border to ' +  "#748C52 dotted 2px: from : " + eToDim.style.border);
			eToDim.setAttribute( "highLighted", eToDim.style.border );
			//alert('HiLight Saved to ' + eToDim.getAttribute("highLighted"));
			eToDim.style.border = "#748C52 dotted 2px";
		} else {
			//alert('Got HiLight :: Saving ' + eToDim.tagName + ' border to ' +  eToDim.getAttribute("highLighted") + " : from : " + eToDim.style.border);
			eToDim.style.border = eToDim.getAttribute("highLighted");
			if (isIE) { 
				eToDim.setAttribute("highLighted", null );
			} else {
				eToDim.removeAttribute("highLighted");
			}
		}
	}
}

function sameObject (one, two) {
	if (one.getAttribute('gechoid') && two.getAttribute('gechoid')){
		//alert(one.getAttribute('gechoid') + ' ' + two.getAttribute('gechoid'));
		var firstOne = one.getAttribute('gechoid').match(/gecho\_(\d+\_[a-z0-9]+)/i);
		var secOne = two.getAttribute('gechoid').match(/gecho\_(\d+\_[a-z0-9]+)/i);
		if (firstOne != null && secOne!= null ){
			//alert(firstOne[1] + ' ' + secOne[1]);
			if (firstOne[1] == secOne[1]){
				return true;
			} else {
				return false;
			}
		}
	} else {
		false;
	}
}
function toggleAdvForm( the ) {
	if (the.nodeType ==1){
		var children = the.childNodes;
		for (var i=0; i < children.length; i++){
			if (children[i].nodeType == 1){
				var displayType = children[i].getAttribute('gechodisplaymode');
				if (displayType == 'A'){
					if (children[i].style.display){
						if (children[i].style.display == 'none'){
							children[i].style.display = '';
						}
					} else {
						children[i].style.display = 'none';
					}
				}
				toggleAdvForm(children[i]);
			}
		}
	}
	

}
function toggleAdv( theCell ) {
	var theMenu = document.getElementById('gMenu');
	if (advancedShow ){
		theCell.innerHTML = "Show Advanced Menu";
		advancedShow = false;
		document.getElementById('gechoToggleTable').style.display = 'none';
	} else {
		theCell.innerHTML = "Hide Advanced Menu";
		advancedShow = true;
		document.getElementById('gechoToggleTable').style.display = '';
	}
}
function setGechoMenu (whichEl, fieldid, action, whole, gechoid ) {
var pretext;
var typeid;
var column;
var table;
var appzid;
	if (fieldid && document.getElementById(fieldid)){
					
		if (whole == 'Table'){
			pretext = whichEl.getAttribute('gechoItemName') ;
			if (gechoid.match(/gecho\_\d+\_page\_/i)){
				document.getElementById(fieldid).style.display = 'none';
				return;
			}
		} else if (whole == 'Page') {
			pretext = 'Page';	
			if (gechoid.match(/gecho\_\d+\_page\_/i) && showPageEdit ){
				gechoid = gechoPageEdit()
			} else {
				document.getElementById(fieldid).style.display = 'none';
				return;
			}
		} else if (whole == 'Appz' ){
			var appzid = gechoid.match(/gecho\_(\d+)\_([a-z]+)/i);
			if (appzid != null){
				if ( appzid [2] != "appz" && appzid[1] > 0 && showAppzEdit ){
					pretext = 'App (' + whichEl.getAttribute('gechoItemName') + ')' ;
					gechoid = 'gecho_' + appzid[1] + '_appz_appzname_' + appzid[1] + '_p_0';
				} else {
					document.getElementById(fieldid).style.display = 'none';
					return;
				}
			}
		} else {
			pretext = translateTag(whichEl.tagName);
		}
		typeid = gechoid.match(/gecho\_(\d+)\_([a-z0-9]+)\_([a-z0-9\@]+)\_(\d+)\_([a-z0-9]+)\_(\d+)/i);
		if (typeid != null){
			appzid = typeid[1];
			table = typeid[2];		
			column = typeid[3];
		}
		if ( (isBrandNewGecho(gechoid) == true && action != 'Add') || ( typeid == null ) || ( column == '@'  && ! whole ) ) {
			document.getElementById(fieldid).innerHTML = "";
			document.getElementById(fieldid).setAttribute("gechoLocation", "");
			document.getElementById(fieldid).style.display = 'none';
		} else {
			document.getElementById(fieldid).innerHTML = action + '  ' + pretext;
			document.getElementById(fieldid).setAttribute("gechoLocation", urlModify(gechoid, action, whole ));
			document.getElementById(fieldid).style.display = '';
		}   
	}
}
function getStyle(oElm, strCssRule){
    var strValue = "";
    if(document.defaultView && document.defaultView.getComputedStyle){
        strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
    }
    else if(oElm.currentStyle){
        strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
            return p1.toUpperCase();
        });
        strValue = oElm.currentStyle[strCssRule];
    }
    return strValue;
}


function elementsParent (e){
	if (e) {
		if (e.parentElement){
			return e.parentElement;
		} else if (e.parentNode){
			return e.parentNode;
		}else{
			return e;
		}
	}
}
// Function to build and insert ImageNode
function createInsertImage (whereAt, rte){
 var imageToAdd = document.createElement("img");
  imageToAdd.setAttribute("id","tempIEPasteImage");
 if (isIE){
   whereAt.insertAdjacentHTML('BeforeEnd', imageToAdd.outerHTML);
   return getDocumentFromEl(rte).getElementById("tempIEPasteImage");
 } else if (isGecko){
   whereAt.appendChild(imageToAdd);
   return imageToAdd;
 }
}


function gechoGetObject (whichEl){
 var origEl = whichEl;
   while (whichEl.tagName){
     if (whichEl.getAttribute("gechoid") ) {
          // Found Object return it
           return whichEl;
         }
         // Keep looking above
     whichEl = elementsParent(whichEl);
         if (whichEl == null) {
          break;
         }
   }
   return origEl;
}
function isBrandNewGecho (gechoid){
 var doing = gechoid.match(/gecho\_\d+\_[a-z0-9]+\_[a-z0-9\@]+\_(\d+)\_[a-z0-9]+\_(\d+)/i);
 if (doing != null){
  if (doing[1] == 0 ){
   return true;
  } else {
   return false;
  }
 } else {
  return false;
 }
}
function showHide (whichTags,visiB){
 var tricky = document.getElementsByTagName(whichTags);
 for (var i=0; i < tricky.length; i++){
  if (tricky[i].getAttribute('gechoid')){
   tricky[i].style.visibility = visiB;
  }
 }
}
function urlModify (gechoObject, gechoAction, theWhole) {
var theUrl = thisGechoPage();  //document.URL;
 if (theWhole == "Table"){
  gechoObject = gechoObject.replace(/_\d+$/gi,'_0');
 }
 if (theUrl.search(/\?/) > 0){
  theUrl = theUrl + ";geo=" + gechoObject + ';gwtd=' + gechoAction;
 } else {
  theUrl = theUrl + "?geo=" + gechoObject + ';gwtd=' + gechoAction;
 }
 return theUrl;
}

function translateTag (thisTagName){
 if ( (thisTagName.charAt(0) == "h" || thisTagName.charAt(0) == "H") && ( thisTagName.charAt(1) > "0" && thisTagName.charAt(1) < "9" ) ){
  return "Heading";
 } if ( thisTagName == "IMG" ) {
  return "Image";
 } if ( thisTagName == "INPUT" ) {
  return "Input Field";
 } if ( thisTagName == "TABLE" ) {
  return "Table";
 } if ( thisTagName == "TD" ) {
  return "Table Cell";
 } if ( thisTagName == "P" ) {
  return "Paragraph";
 } if ( thisTagName == "A" ) {
  return "Link";
 } if ( thisTagName == "UL"  || thisTagName == "OL" ) {
  return "List";
 } if ( thisTagName == "LI" ) {
  return "List Item";
 } if ( thisTagName == "OBJECT" ) {
  return "Media Object";
 } if ( thisTagName == "DIV" ) {
  return "Layer Object";
 } if ( thisTagName == "FONT" ) {
  return "Text";
 } if ( thisTagName == "SPAN" ) {
  return "Area";  
 } if ( thisTagName == "B" ) {
  return "Bold Text";
 } if ( thisTagName == "I" ) {
  return "Italic Text";
 } if ( thisTagName == "SELECT" ) {
  return "Drop Box";
 }
}
function isGechObject (objectid){
var prefix ="";
 if (objectid != null ){
  for (var a=0; a<5; a++){
    prefix = prefix + objectid.charAt(a);
  }
  return prefix;
 }
}
function shortPopUp( url, name, width, height, scrollbars ) {
        var top  = "100";
        var left = "100";
        var basket;
        var str;

        if( scrollbars == null ) scrollbars = "1";

        str  = "";
        str += "resizable=1,titlebar=0,menubar=0,";
        str += "toolbar=0,location=0,directories=0,status=1,";
        str += "scrollbars=" + scrollbars + ",";
        str += "width="
        + width + ",";
        str += "height=" + height + ",";
        str += "top=" + top + ",";
        str += "left=" + left;
        basket = window.open( url, name, str );
        basket.focus();
}

// Spell checking routines

function makeWordList (textStuff){

  var r = getDocumentFromEl(textStuff).body.createTextRange();
      r.moveToElementText( getDocumentFromEl(textStuff).body );

  var oR = r.duplicate();
  var count = 0;
  var isMoreText = true;
  var retstring;
  r.move("word",0);
  isMoreText = r.moveEnd("word",1);
   while(isMoreText && oR.inRange(r) ){
   var theWord;
   if(r.text.match(/[\ \n\r]+$/)) r.moveEnd("character",-1);
   theWord = r.text.replace(/[^a-z]/gi ,"");
   if (theWord.match(/[a-z]+/gi)){
    if (retstring){
     retstring = retstring + "," + count + ":" + theWord;
    } else {
     retstring = count + ":" + theWord;
    }
   }
   count ++;
   r.move("word",1);
   isMoreText = r.moveEnd("word",1);
  }
  return retstring;
}


// Javascript called during Gecho Layer opreations;
function cleanHTML(myName) {
      var theDoc = getDocumentFromEl(myName);
      var code = theDoc.body.innerHTML;
      // removes all empty <p> tags
      code = code.replace(/<p([^>])*>(&nbsp;)*\s*<\/p>/gi,"")
      // removes all span and font tags
      code = code.replace(/<\/?(font|span)[^>]*>/gi,"")
      // removes all Class attributes on a tag eg. '<p class=asdasd>xxx</p>' returns '<p>xxx</p>'
      code = code.replace(/<([\w]+) class=([^ |>]*)([^>]*)/gi, "<$1$3")
      // removes all style attributes eg. '<tag style="asd asdfa aasdfasdf" something else>' returns '<tag something else>'
      code = code.replace(/<([\w]+) style="([^"]*)"([^>]*)/gi, "<$1$3")
      // gets rid of all xml stuff... <xml>,<\xml>,<?xml> or <\?xml>
      code = code.replace(/<\\?\??xml[^>]>/gi, "")
      // get rid of ugly colon tags <a:b> or </a:b>
      code = code.replace(/<\/?\w+:[^>]*>/gi, "")
      // get rid of silly space tags
      code = code.replace(/&nbsp;/gi, "")
      theDoc.body.innerHTML = code;
}

function isblank(s) {
 for(var i=0;  i < s.length; i++){
  var c = s.charAt(i);
  if ( (c != ' ') && (c != '\n') && (c != '') ){
   return false;
  }
 }
 return true;
}
//// Context sensitive help and field expansion / contraction
function gechoJfocus( shortname, descrip, thething ) {
var fieldname = thething.getAttribute('name');
var subtype =  fieldname.match(/\_([a-z0-9]+$)/i);
var special = 'normal';
var expand = thething.getAttribute("gechoexpand");
	thething.focused = true;
	
	if (expand && expand != 'no'){
		thething.setAttribute("gechoexpand", thething.style.height);
		thething.style.height = "300px";
	}
	if ( subtype != null ){
		special = subtype[1];
	}
	document.getElementById('MessagefromGecho').innerHTML = '<h1>The ' + shortname + ' Field</h1><p>' + descrip + '</p>';
	if (isblank(thething.innerHTML)){
		var content = thething.name.match(/([a-z0-9]+)_([a-z0-9]+)$/i);
		if (content != null){
		}
	}
}
// Context sensitive help and field expansion / contraction
function gechoJblur( thething ) {
var fieldname = thething.name;
var subtype   =  fieldname.match(/([a-z0-9]+)_([a-z0-9]+$)/i);
var special   = 'normal';
var expand = thething.getAttribute("gechoexpand");
var straight;
	
	if (expand && expand != 'no'){
		thething.style.height = expand;
	}
	if ( subtype != null ){
		special  = subtype[2];
		straight = subtype[1];
	}
	document.getElementById('MessagefromGecho').innerHTML = '<h1>Gecho Content Management.</h1><p>Thank you for using Gecho Content Management by Pear Zoo Marketing.</p>';
}
// Provide Element that started it all
function provideElement (rte){
var oRTE;
var myPic;
 if (document.all) {
  oRTE = frames[rte];
  //get current selected range
  var selection = oRTE.document.selection;
  if (selection != null) {
          rng = selection.createRange();
  }
  if (oRTE.document.selection.type.toLowerCase() == "control" ){
    myPic = rng.item(0);
  } else if (oRTE.document.selection.type.toLowerCase() == "text" || oRTE.document.selection.type.toLowerCase() == "none") {
    myPic = rng.parentElement();
  }
 } else {
  oRTE = document.getElementById(rte).contentWindow;
  //get currently selected range
  var selection = oRTE.getSelection();
  rng = selection.getRangeAt(selection.rangeCount - 1).cloneRange();
  var p = rng.commonAncestorContainer;

  if (!rng.collapsed && rng.startContainer == rng.endContainer && rng.startOffset - rng.endOffset <= 1 && rng.startContainer.hasChildNodes()){
   p = rng.startContainer.childNodes[rng.startOffset];
  }
  while (p.nodeType == 3) {
   p = p.parentNode;
  }
  myPic = p;
 }
 return myPic;
}
// Popup the file Manager Window
function gechoSpawn ( triggerObj, address, pageno, appzid ){
  theTriggerObj = triggerObj;
  address = address.replace(/pg\=\d+/i,'pg=' + pageno + ';appzid=' + appzid );
  gwindowFile = open(address, "FileManager", "width=500,height=400,status=yes,scrollbars=yes,resize=yes" );
}
// Takes select values and returns it to either text field or into an image tag.
function gechoCarryValue( thisHere ){
//var stuff = opener.theTriggerObj;
 if (window.opener && thisHere ){
  if (opener.theTriggerObj.tagName.toUpperCase() == "IMG"){
   opener.theTriggerObj.removeAttribute("width");
   opener.theTriggerObj.removeAttribute("height");
   opener.theTriggerObj.setAttribute("border", "0");
   opener.theTriggerObj.setAttribute("src", thisHere);
  } else {
   opener.theTriggerObj.value = thisHere;
  }
 }
}

// Called on submission of Gecho form. Does type, required and password checking
function gechoJsubmit(f) {
 if (skipValidate) return true;
 for (var i=0; i < f.length; i++){
     var e = f.elements[i];
     var shortName = e.getAttribute('helplabel');
     if (shortName) {
        shortName = '"' + shortName + "'";
     } else {
	shortName = 'This Field';
     }
     if ( (e.value == null) || (e.value == "") || isblank(e.value) ){
      if ( (e.getAttribute('gechoreq') != null && ( e.getAttribute('gechoreq') == 'Y' )) || (e.getAttribute('gechotype') == 'pass') ){
       alert( shortName +' is required. Please supply a value.');
       e.focus();
       if (e.scrollIntoView()) { e.scrollIntoView(); }
       return false;
      }
     } else {
      if (e.getAttribute('gechotype') == 'pass'){
       var passmatch = e.getAttribute('name').match(/([a-z0-9]+)_Confirm$/);
        if (passmatch != null){
          var pass1 = f.elements[passmatch[1]];
          var pass2 = f.elements[passmatch[0]];
          if (pass1.value != pass2.value ){
           alert('Your passwords do not match. Please re-enter them.');
           pass2.focus();
	   if (e.scrollIntoView()) { e.scrollIntoView(); }
           return false;
          }
        }
      }
      if (e.getAttribute('gechotype') != null && ( e.getAttribute('gechotype') == 'number' || e.getAttribute('gechotype') == 'price'  || e.getAttribute('gechotype') == 'sales' || e.getAttribute('gechotype') == 'total') ){
       var v = parseFloat(e.value);
       var vm = e.value.match(/^[\d\.]+$/);
       if (isNaN(v) || vm == null ){
        alert(shortName + ' is a numerical field. Please supply a Number.');
        e.focus();
	if (e.scrollIntoView()) { e.scrollIntoView(); }
        return false;
       }
      }
      if (e.getAttribute('gechotype') != null && e.getAttribute('gechotype') == 'numlist'){
	var numlist = e.value.split(/\,/);
	
	if (numlist.length > 0){
		numlist.sort(sortit);
		for (var cci=0; cci < (numlist.length); cci++){
			
			if ( numlist[cci].match(/^\d+$/) == null ){
				alert (shortName + " must be a comma-separated list of numbers. Please remove all spaces and letters. Only numbers and commas are allowed.");
				e.focus();
				if (e.scrollIntoView()) { e.scrollIntoView(); }
				return false;
			} 
		}
		e.value = unique(numlist).join(',');
	}
      }
      if (e.getAttribute('gechotype') != null && e.getAttribute('gechotype') == 'idnumber'){
       var idnumber = e.value.match(/\d+/);
       if (idnumber == null){
        alert('Please supply a valid South African Identity Number. If you are from outside SA, or don\'t have an ID Number, please enter your cell phone number (with no spaces or punctuation). This number must be unique, it will become your user name.');
        e.focus();
	if (e.scrollIntoView()) { e.scrollIntoView(); }
        return false;
       }
      }
      if (e.getAttribute('gechotype') != null && e.getAttribute('gechotype') == 'email'){
       var idnumber = e.value.match(/^[A-Z0-9._%-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}$/i);
       if (idnumber == null){
        alert('Please supply a valid email address.');
        e.focus();
	if (e.scrollIntoView()) { e.scrollIntoView(); }
        return false;
       }
      }
      if (e.getAttribute('gechotype') != null && e.getAttribute('gechotype') == 'owncode'){
       var idnumber = e.value.match(/\d{3}$/);
       if (idnumber == null){
        alert('Please provide a valid personal code.');
        e.focus();
	if (e.scrollIntoView()) { e.scrollIntoView(); }
        return false;
       }
      }

      if (e.getAttribute('gechotype') != null && e.getAttribute('gechotype') == 'datetime'){
       var datestuff = e.value.match(/\d\d\d\d\-[\d]+\-[\d]+\:| [\d]+\:[\d]+\:[\d+]/);
       if (datestuff == null){
        alert(shortName + ' is a date and time field. Please supply a Date and Time in this format YYYY-MM-DD:HH:mm:ss.');
        e.focus();
	if (e.scrollIntoView()) { e.scrollIntoView(); }
        return false;
       }
      }
     }
 }
  f.gsubmit.style.visibility = "hidden";
  return true;
}


// File Manager Navigation Stuff;
function clearCells (thisTable){
 while (thisTable != null ){
  if (thisTable.tagName.toLowerCase() == 'table'){
   break;
  } else {
   thisTable = elementsParent(thisTable);
  }
 }
 if (thisTable != null){
  for (var i=0; i < thisTable.getElementsByTagName('td').length; i++){
   if (thisTable.getElementsByTagName('td')[i].className == "overFMCell"){
    thisTable.getElementsByTagName('td')[i].className = "gechoFM";
   }
  }
 }
}
// Get tablename from the name of the form that called us. Get an object for this table's default values.
function  gechoDefaults ( formName ) {
 var f = document.getElementById(formName);
 if (f.getAttribute('gechoname') != null){
  var tableName = f.getAttribute('gechoname').match(/([a-z0-9]+)\_GechoForm/i);
  if ( tableName != null ){
   var doing = window.location.search.match(/geo\=gecho\_(\d+)\_[a-z0-9]+\_[a-z0-9\@]+\_(\d+)\_[a-z0-9]+\_(\d+)\;gwtd\=([a-z]+)/i);
   if (doing != null){
    // Only add defaults when adding a new record based on 0 and 0
    if (doing[2] == 0 && doing[3] == 0 && doing[4] == 'Add' ){
     for (var i=0; i < f.length; i++){
      var e = f.elements[i];
      var fieldz;
      eval('fieldz = window.table_' + tableName[1] + '_' + doing[1] );
      if (fieldz != null){
       if (fieldz[e.name] != null){
        e.value = fieldz[e.name];
       }
      }
     }
    }
   }
  }
 }
}

function gclose (){
  if (gwindow && !gwindow.closed){
   gwindow.close();
  }
  if (gwindowSpell && !gwindowSpell.closed){
   gwindowSpell.close();
  }
  if (gwindowFile && !gwindowFile.closed){
   gwindowFile.close();
  }
}
function gshift (){
  if (gwindow && !gwindow.closed){
   gwindow.focus();
  }
  if (gwindowSpell && !gwindowSpell.closed){
   gwindowSpell.focus();
  }
  if (gwindowFile && !gwindowFile.closed){
   gwindowFile.focus();
  }
}

function getDocumentFromEl ( elName ){
 var theDocc;
  if (document.getElementById(elName).contentWindow){
   theDocc = document.getElementById(elName).contentWindow.document;
  } else if (document.getElementById(elName).contentDocument){
   theDocc = document.getElementById(elName).contentDocument;
  }
  return theDocc;
}

function gLoadContent( fieldName, formName ){
	
	if ( fieldName != 'gechoDef' ) {
		//getDocumentFromEl('new_' + fieldName + '_Preview').body.innerHTML = document.getElementById(fieldName).value;
	} else {
		if ( ! beenCalled ){
			var stuff = document.getElementById("CleanGechoFrame");
			var newHeight;
			var oldHeight;
			gechoDefaults(formName);
			toggleAdvForm(stuff);
			oldHeight = stuff.offsetHeight;
			if (oldHeight > winHeight){
				newHeight = (winHeight + 50);
			} else {
				newHeight = (oldHeight + 30);
			}
			window.resizeTo( 700, newHeight );
			beenCalled = 1;
			
		}	
	}
	clearInterval(timeOutId[fieldName]);
}

function rePosition () {
var x,y;
	if (self.innerHeight) {
		// Normal Browsers
		x = self.innerWidth;
		y = self.innerHeight;
		startPos = ((x-16) / 2);
	}
	else if (document.documentElement && document.documentElement.clientHeight) {
		// Explorer 6 Strict Mode
		x = document.documentElement.clientWidth;
		y = document.documentElement.clientHeight;
		startPos = (x / 2) - 7;
	}
	else if (document.body){
		// Non Strict Explorer
		x = document.body.clientWidth;
		y = document.body.clientHeight;
		startPos = (x / 2) - 7;
	}
}

function gMenuClick (theItem){
 var theHeight = winHeight + 50;
 var theWidth  = 700;
 var fromLeft = 0;
 var fromTop = 0;
 var pstuff = 'height=' + theHeight + ',width=' + theWidth + ',left=' + fromLeft + ',top=' + fromTop +  ',scrollbars=1, resizable=1';

 gwindow = window.open(theItem.getAttribute('gechoLocation'), 'gechoLayerWindow', pstuff );
 document.getElementById('gMenu').style.visibility = 'hidden';
 gwindow.window.focus();
}

function createMenuLayer() {
 document.writeln('<div gechoid="gMenu" id="gMenu" class="gPopUpMenu"> ');
 document.writeln('  <table width="190" border="0" cellpadding="0" cellspacing="0" class=gMenuClass>');
 document.writeln('    <tr><td></td></tr>');
 document.writeln('    <tr><td onClick="gMenuClick(this)" class="gechoPop" id="thisObjectEdit" gechoid="thisObjectEdit" ></td></tr>');
 document.writeln('    <tr><td class="gechoPop"  id="parentObject" gechoid="parentObject" ></td></tr>');
 document.writeln('    <tr ><td onClick="gMenuClick(this)" class="gechoPop"  id="thisRecordEdit" gechoid="thisRecordEdit" ></td></tr>');
 document.writeln('    <tr ><td onClick="gMenuClick(this)" class="gechoPop"  id="thisRecordAdd"  gechoid="thisRecordAdd"  ></td></tr>');
 document.writeln('    <tr ><td onClick="gMenuClick(this)" class="gechoPop"  id="thisRecordDel"  gechoid="thisRecordDel"  ></td></tr>');
 document.writeln('    <tr><td><hr width="95%"></td></tr>');
 document.writeln('    <tr><td class="gechoPop" onclick="toggleAdv(this);" id="gechoToggleAdv"  gechoid="gechoToggleAdv" >Show Advanced Menu</td></tr>');
 document.writeln('    <tr><td><table  cellspacing="0" cellpadding="2" id="gechoToggleTable" width="190" style="display:none">');
 document.writeln('     <tr ><td  onClick="gMenuClick(this)" class="gechoPop"  id="thisPageEdit" gechoid="thisPageEdit" ></td></tr>');
 document.writeln('     <tr ><td  onClick="gMenuClick(this)" class="gechoPop"  id="thisPageAdd"  gechoid="thisPageAdd"  ></td></tr>');
 document.writeln('     <tr ><td  onClick="gMenuClick(this)" class="gechoPop"  id="thisPageDel"  gechoid="thisPageDel"  ></td></tr>');
 document.writeln('     <tr ><td  onClick="gMenuClick(this)" class="gechoPop"  id="thisAppEdit" gechoid="thisAppEdit" ></td></tr>');
 document.writeln('     <tr ><td  onClick="gMenuClick(this)" class="gechoPop"  id="thisAppAdd"  gechoid="thisAppAdd"  ></td></tr>');
 document.writeln('     <tr ><td  onClick="gMenuClick(this)" class="gechoPop"  id="thisAppDel"  gechoid="thisAppDel"  ></td></tr>');
 document.writeln('     <tr><td class="gechoPop"  id="hiddenObject" gechoid="hiddenObject" >Show Hidden Objects</td></tr>');
 document.writeln('    </table>');
 document.writeln('    <tr><td><hr width="95%"></td></tr>');
 document.writeln('    <tr><td class="gechoPop" onclick="goGechoLogout();" id="gechoLogout"  gechoid="gechoLogout" >Log out</td></tr>');
 document.writeln('    <tr><td class="gechoPop" onclick="document.getElementById(\'gMenu\').style.visibility=\'hidden\'; showHide(\'OBJECT\',\'visible\');  showAgain(theObject); theObject = null; objectsHidden = false;" id="gechoCancel"  gechoid="gechoCancel" >Cancel</td></tr>');
 document.writeln('    <tr><td></td></tr>');
 document.writeln('  </table> ');
 document.writeln('</div>');
 document.writeln('');

}
function testNodes (){
	for (var newMenuItem in addedGechoMenu){
		var insertion = document.getElementById('gechoLogout');
		var newRow = document.createElement("Tr");
		var newCell = document.createElement("td");
		var newLabel = document.createTextNode(newMenuItem);
			newCell.appendChild(newLabel);
			newRow.appendChild(newCell);
			//newCell.setAttribute('onclick','window.location="' + addedGechoMenu[newMenuItem] + '"'); 
			newCell.className = 'gechoPop'; newCell.setAttribute('class','gechoPop'); newCell.setAttribute('id','gechoAddedMenu' + newMenuItem); 
			newCell.setAttribute('gechoid','gechoAddedMenu' + newMenuItem); newCell.setAttribute('gechoMenuLink', newMenuItem );
			insertion.parentNode.parentNode.insertBefore( newRow,  insertion.parentNode );
	}
}
function comboBoxAdd ( fieldname, shortdesc, init ){
	var dropbox = document.getElementById( fieldname );
	var combo = document.getElementById( 'gecho_combo_' + fieldname );
	var i;
	
	if (combo && dropbox){	
		for (i=0; i<dropbox.options.length; i++){
			if ( dropbox.options[i].value == combo.value && ! init ){
				// Hide combo and show dropBox
				combo.style.display = 'none';
				dropbox.style.display = '';
				return false;
			} else if ( init && dropbox.options[i].text == 'Add ' + shortdesc ){
				return false;
			}
		}
		if (init){
			dropbox.options[i] = new Option('Add ' + shortdesc, "" , false, false );
			return true;
		} else {
			dropbox.options[i] = new Option('New ' + shortdesc + ' : ' + combo.value,  combo.value, false, true );
			combo.style.display = 'none';
			dropbox.style.display = '';
			return true;
		}
	} else {
		alert(fieldname);
	}
}
function comboBoxSelect ( fieldname, shortdesc, copy ){
	var dropbox = document.getElementById( fieldname );
	var combo = document.getElementById( 'gecho_combo_' + fieldname );
	if ( dropbox.options[dropbox.selectedIndex].text == 'Add ' + shortdesc ){
		alert("You may now add an appropriate value to the " + shortdesc + " field");
		dropbox.selectedIndex = -1;
		dropbox.style.display = 'none';
		combo.style.display = '';
		combo.focus();
	} else if ( copy ){
		dropbox.style.display = 'none';
		combo.value = dropbox.value;
		combo.style.display = '';
		combo.focus();
	}
}
function editComboOption ( fieldname ){
	var dropbox = document.getElementById( fieldname );
	var combo = document.getElementById( 'gecho_combo_' + fieldname );
		dropbox.style.display = 'none';
		combo.value = dropbox.value;
		combo.style.display = '';
		combo.focus();
}
function killStyles (){
	
	var theBody = document.getElementsByTagName("body");
	for (var i=0; i < theBody.length; i++ ){
		//theBody[i].setAttribute("bgcolor","#FFFFFF");
		//theBody[i].setAttribute("text","#000000");
	}
	document.body.style.color = "#FFFFFF";
	document.body.style.backgroundColor = "#FFFFFF";
	
}
//Ajax Stuff from Here
function GetXmlHttpObject(){ 
	var objXMLHttp=null;
	if (window.XMLHttpRequest){
		objXMLHttp=new XMLHttpRequest();
	}else if (window.ActiveXObject){
		objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	return objXMLHttp;
} 
function stateChanged(){ 
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){ 
		//Do something with the response here.
		document.getElementById("txtHint").innerHTML=xmlHttp.responseText 
	} 
} 
function showHint(str){
	if (str.length==0){ 
		document.getElementById("txtHint").innerHTML=""
		return
	}
	xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null){
		alert ("Browser does not support HTTP Request")
		return
	} 
	var url="gethint.asp"
	url=url+"?q="+str
	url=url+"&sid="+Math.random()
	xmlHttp.onreadystatechange=stateChanged 
	xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlHttp.open("GET",url,true)
	xmlHttp.send(null)
} 
