// Gecho Content Handling Routines for Display. 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.

// Browser center
var winHeight;
var winWidth;
var startPos;

var lastx;
var lasty;
var lastc = 1;

var beenCalled;
var skipValidate;

rePosition();
window.onresize = rePosition;

function rePosition () {
 if (document.all) {
  winHeight = document.body.clientHeight;
  winWidth = document.body.clientWidth;
  startPos = (winWidth / 2) - 7;
 } else {
  winHeight = window.innerHeight;
  winWidth = window.outerWidth;
  startPos = ((winWidth-44) / 2);
 }
}

// Ctach Clicks

if (document.addEventListener){
 document.addEventListener("click", gechoChoose, true);
 document.addEventListener("mouseover", gechoChoose, true);
} else if (document.attachEvent) {
 document.attachEvent("onclick", gechoChoose);
 document.attachEvent("onmouseover", gechoChoose);
}

// Bermuda Listener

function gechoChoose(e) {
 if (!e) e = window.event;

 if (e.ctrlKey == true){

  if (lastc == 1){
   lastx = e.clientX;
   lasty = e.clientY;
   lastc ++;
  } else if (lastc == 2){
   if (lastx < e.clientX && lasty > e.clientY){
    lastx = e.clientX;
    lasty = e.clientY;
    lastc ++;
   } else {
    lastc = 1;
   }
  } else if (lastc == 3){
   if (lastx < e.clientX && lasty < e.clientY){
    lastc = 1;
    lastx = 0;
    lasty = 0;
    window.parent.parent.location.pathname = 'admin.html';
   } else {
    lastc = 1;
   }
  }
 }
 return true;
}

// 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();
       e.scrollIntoView(true);
       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();
	   e.scrollIntoView(true);
           return false;
          }
        }
      }
      
            if (e.getAttribute('gechotype') != null && ( e.getAttribute('gechotype') == 'amount') ){
       var v = parseInt(e.value);       
       var vm = e.value.match(/^[\d]+\.[\d]{2}$/);
       
       if (  v < 1 || vm == null  ){
        alert(shortName + ' is a numeric field. Please supply a Number eg "123.00".');
       
        e.focus();
	if (e.scrollIntoView()) { e.scrollIntoView(); }
        return false;
       }
       
       var spl = e.value.split(".");
     
        if (  spl[1] < 0 || spl[1] == null  ){
        alert(shortName + ': No cents are allowed. Please supply  "00" cents e.g "123.00".');
       
        e.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') == 'tleader'){
       var idnumber = e.value.match(/^[a-zA-Z]{3}\d{3}$/);
       if (idnumber == null){
        alert('In order to have complete and correct access to this site, you must provide a valid Team Leader code.');
        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;
       }
      }
     }
 }
 return true;
}
function unique(a) {
	tmp = new Array(0);
	for(i=0;i<a.length;i++){
		if(!contains(tmp, a[i])){
			tmp.length+=1;
			tmp[tmp.length-1]=a[i];
		}
	}
	return tmp;
}
function contains(a, e) {
	for(j=0;j<a.length;j++)if(a[j]==e)return true;
	return false;
}
function sortit(a,b){
return(a-b)
}      
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;
}

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=0,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();
}

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(fieldName + '_Preview').body.innerHTML = document.getElementById(fieldName).value;
	} else {
		if ( ! beenCalled ){
			var stuff = document.getElementById("ClientGechoFrame");
			var newHeight;
			var oldHeight;
			document.body.style.color = "#FFFFFF";
			document.body.style.backgroundColor = "#FFFFFF";
			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]);
}
// 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 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 = '';
	}
}
//// 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';
    thething.focused = true;

if ( subtype != null ){
 special = subtype[1];
}
 var message = document.getElementById('MessageFromGechoForClient');
 if (message){
	message.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){
  }
 }
}
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();
}
