/* Javascript formatting and general page layout functions for database-view pages
 * Includes table striping function, plus form-field 'hover' names (labels inside fields until
 * clicked).
 * 
 */

//Taken from A List Apart Zebra Tables article

  // this function is needed to work around 
  // a bug in IE related to element attributes
  function hasClass(obj) {
     var result = false;
     if (obj.getAttributeNode("class") != null) {
         result = obj.getAttributeNode("class").value;
     }
     return result;
  }   

 // Stripes a table with given id (requires corresponding CSS rules).
 function stripe(id) {
    // the flag we'll use to keep track of 
    // whether the current row is odd or even
    var even = false;
  
    // if arguments are provided to specify the colours
    // of the even & odd rows, then use the them;
    // otherwise use the following defaults:
    var evenColor = arguments[1] ? arguments[1] : "#fff";
    var oddColor = arguments[2] ? arguments[2] : "#eee";
  
    // obtain a reference to the desired table
    // if no such table exists, abort
    var table = document.getElementById(id);
    if (! table) { return; }
    
    // by definition, tables can have more than one tbody
    // element, so we'll have to get the list of child
    // &lt;tbody&gt;s
    var tbodies = table.getElementsByTagName("tbody");

    // and iterate through them...
    for (var h = 0; h < tbodies.length; h++) {
    
     // find all the &lt;tr&gt; elements... 
      var trs = tbodies[h].getElementsByTagName("tr");
      
      // ... and iterate through them
      for (var i = 0; i < trs.length; i++) {

        // avoid rows that have a class attribute
        // or backgroundColor style
        if (! hasClass(trs[i]) &&
            ! trs[i].style.backgroundColor) {
 		  
          // get all the cells in this row...
          var tds = trs[i].getElementsByTagName("td");
        
          // and iterate through them...
          for (var j = 0; j < tds.length; j++) {
        
            var mytd = tds[j];

            // avoid cells that have a class attribute
            // or backgroundColor style
            if (! hasClass(mytd) &&
                ! mytd.style.backgroundColor) {
        
              mytd.style.backgroundColor =
                even ? evenColor : oddColor;
            
            }
          }
        }
        // flip from odd to even, or vice-versa
        even =  ! even;
      }
    }
  }//end stripe()


//--------------------------------------------------------------------

function initOverLabels () {
  if (!document.getElementById) return;      

  var labels, id, field;

  // Set focus and blur handlers to hide and show 
  // labels with 'overlabel' class names.
  labels = document.getElementsByTagName('label');
  for (var i = 0; i < labels.length; i++) {

    if (labels[i].className == 'overlabel') {

      // Skip labels that do not have a named association
      // with another field.
      id = labels[i].htmlFor || labels[i].getAttribute('for');
      if (!id || !(field = document.getElementById(id))) {
        continue;
      } 

      // Change the applied class to hover the label 
      // over the form field.
      labels[i].className = 'overlabel-apply';

      // Hide any fields having an initial value.
      if (field.value !== '') {
        hideLabel(field.getAttribute('id'), true);
      }

      // Set handlers to show and hide labels.
      field.onfocus = function () {
        hideLabel(this.getAttribute('id'), true);
      };
      field.onblur = function () {
        if (this.value === '') {
          hideLabel(this.getAttribute('id'), false);
        }
      };

      // Handle clicks to label elements (for Safari).
      labels[i].onclick = function () {
        var id, field;
        id = this.getAttribute('for');
        if (id && (field = document.getElementById(id))) {
          field.focus();
        }
      };

    }
  }
};


function hideLabel (field_id, hide) {
  var field_for;
  var labels = document.getElementsByTagName('label');
  for (var i = 0; i < labels.length; i++) {
    field_for = labels[i].htmlFor || labels[i].getAttribute('for');
    if (field_for == field_id) {
      labels[i].style.textIndent = (hide) ? '-1000px' : '0px';
      return true;
    }
  }
}


//--------------------------------

//AJAX - Resultset table re-querying code (onclick table rows...)

function createXMLHttpRequest() {

  var ua;

  if(window.XMLHttpRequest) {
    try {
      ua = new XMLHttpRequest();
    } catch(e) {
      ua = false;
    }
  } else if(window.ActiveXObject) {
    try {
      ua = new ActiveXObject("Microsoft.XMLHTTP");
    } catch(e) {
      ua = false;
    }
  }
  return ua;
}



function showAll() {
  if (!document.getElementById) return;

  var hiddenfield = document.getElementById('qid');
  hiddenfield.value = '%';
  document.showcontact.submit();
/* can only hope that this reloads the page */
}

function rowclick(rowid) {
  if (!document.getElementById) return;

  var hiddenfield = document.getElementById('qid');
  hiddenfield.value = rowid;
  document.showcontact.submit();
/* can only hope that this reloads the page */
}

//--------------------------------------

//AJAx-ish edit-contact form: adding/removing address and email address editing groups,
//plus overall form validation functions.

function validateEditForm() {
   
   
}


/*
 * Definitive ref page for this: http://www.w3schools.com/js/js_obj_htmldom.asp
 */
function expandAddresses() {
  var adds = document.getElementById("addresslist");
  var addcount = adds.getElementsByTagName("div").length;
  if (!addcount) addcount = 0;
  adds.innerHTML += "<div class=\"addrgroup\" id=\"addr"+addcount+"\">&nbsp;Address " + (addcount+1) +"<br />\n" +
  "<label>street</label><textarea name=\"streets\" class=\"f\" rows=\"3\" cols=\"30\"></textarea><br />" +
  "<label>town</label><input type=\"text\" name=\"town\" class=\"f\"></input><br />\n"+
  "<label>region</label><input type=\"text\" name=\"region\" class=\"f\"></input><br />\n"+
  "<label>pcode</label><input type=\"text\" name=\"pcode\" class=\"f\"></input><br />"+
  "<label>country</label>";
//<input type=\"text\" name=\"country\" class=\"f\"></input>
  countryChooser(adds);
  adds.innerHTML += " </div>";
//insert placeholder html for country box, then call insertCountryChooser()
}

function countryChooser(container,selectediso) {
   var clist = document.getElementById("countrylist");
   container.appendChild(clist); //does this copy the element, or just weird out the page?

   var newclist = container.getElementsByTagName("select"); //assumes country list is only select box on the page.
   newclist.id = "";
   //newclist.style.display = "block";
   /* newclist. */
   for (var i=0; i<newclist.length; i++) {
      var o = newclist.options[i];
      if (o.value=selectediso) {
         o.selected = true;
      }
   }
}


function contractAddresses() {
  var adds = document.getElementById("addresslist");
  var additems = adds.getElementsByTagName("div");
  var len = additems.length;
  if (len > 0) {
    var remdiv = additems[additems.length-1]; /* for 'remove last entry' */
  /* var remdiv = additems[divnum]; unworkable unless re-indexing all other members of the list when parts are removed*/
    adds.removeChild(remdiv);
  }
}


function expandEmails() {
  var ems = document.getElementById("emaillist");
  var ecount = ems.getElementsByTagName("div").length;
  if (!ecount) ecount = 0;
  ems.innerHTML += "<div class=\"emailfield\" id=\"email"+ecount+"\"><br />\n" +
  "<label>email " + (ecount+2) +"</label><input type=\"text\" name=\"email"+ecount+"\" class=\"f\"></input></div>";
}

function contractEmails() {
  var ems = document.getElementById("emaillist");
  var emlitems = ems.getElementsByTagName("div");
  var len = emlitems.length;
  if (len > 0) {
    var remdiv = emlitems[emlitems.length-1]; /* for 'remove last entry' */
    ems.removeChild(remdiv);
  }
}


function expandCategories() {
  var cats = document.getElementById("categorylist");
  var ccount = cats.getElementsByTagName("div").length;
  if (!ccount) ccount = 0;
  cats.innerHTML += "<div class=\"catfield\" id=\"cat"+ccount+"\"><br />\n" +
  "<label>category " + (ccount+2) +"</label><input type=\"text\" name=\"cat"+ccount+"\" class=\"f\"></input></div>";
}

function shrinkList(listID) {//"categorylist"
  var list = document.getElementById(listID);
  var listitems = list.getElementsByTagName("div");
  var len = listitems.length;
  if (len > 0) {
    var remdiv = listitems[listitems.length-1]; /* for 'remove last entry' */
    list.removeChild(remdiv);
  }
}



//insert categories..


//'insert' div has class 'addrgroup' and id addr1 / addr2 ...?


/*
function initOverLabels () {
  if (!document.getElementById) return;      

  var labels, id, field;

  // Set focus and blur handlers to hide and show 
  // labels with 'overlabel' class names.
  labels = document.getElementsByTagName('label');
  for (var i = 0; i < labels.length; i++) {

    if (labels[i].className == 'overlabel') {

      // Skip labels that do not have a named association
      // with another field.
      id = labels[i].htmlFor || labels[i].getAttribute('for');
      if (!id || !(field = document.getElementById(id))) {
        continue;
      } 

      // Change the applied class to hover the label 
      // over the form field.
      labels[i].className = 'overlabel-apply';

      // Hide any fields having an initial value.
      if (field.value !== '') {
        hideLabel(field.getAttribute('id'), true);
      }

      // Set handlers to show and hide labels.
      field.onfocus = function () {
        hideLabel(this.getAttribute('id'), true);
      };
      field.onblur = function () {
        if (this.value === '') {
          hideLabel(this.getAttribute('id'), false);
        }
      };

      // Handle clicks to label elements (for Safari).
      labels[i].onclick = function () {
        var id, field;
        id = this.getAttribute('for');
        if (id && (field = document.getElementById(id))) {
          field.focus();
        }
      };

    }
  }
};
 */
 
/*
function view_address() {
	var address_to_replace=document.getElementById("e").firstChild;
	real_address=address_to_replace.nodeValue.replace("[at]", "@");
	address_to_replace.nodeValue=real_address; 
	address_to_replace.parentNode.setAttribute("href", "mailto:"+real_address); 
}
window.onload = function() { view_address(); }
*/



/* EMP (email protector) */

// This script is (c) copyright 2006 Jim Tucek under the
// GNU General Public License (http://www.gnu.org/licenses/gpl.html)
// For more information, visit www.jracademy.com/~jtucek/email/ 
// Leave the above comments alone!

var decryption_cache = new Array();

function decrypt_string(crypted_string,n,decryption_key,just_email_address) {
	var cache_index = "'"+crypted_string+","+just_email_address+"'";

	if(decryption_cache[cache_index])					// If this string has already been decrypted, just
		return decryption_cache[cache_index];				// return the cached version.

	if(addresses[crypted_string])						// Is crypted_string an index into the addresses array
		var crypted_string = addresses[crypted_string];			// or an actual string of numbers?

	if(!crypted_string.length)						// Make sure the string is actually a string
		return "Error, not a valid index.";

	if(n == 0 || decryption_key == 0) {					// If the decryption key and n are not passed to the
		var numbers = crypted_string.split(' ');			// function, assume they are stored as the first two
		n = numbers[0];	decryption_key = numbers[1];			// numbers in crypted string.
		numbers[0] = ""; numbers[1] = "";				// Remove them from the crypted string and continue
		crypted_string = numbers.join(" ").substr(2);
	}

	var decrypted_string = '';
	var crypted_characters = crypted_string.split(' ');

	for(var i in crypted_characters) {
		var current_character = crypted_characters[i];
		var decrypted_character = exponentialModulo(current_character,n,decryption_key);
		if(just_email_address && i < 7)				// Skip 'mailto:' part
			continue;
		if(just_email_address && decrypted_character == 63)	// Stop at '?subject=....'
			break;
		decrypted_string += String.fromCharCode(decrypted_character);
	}
	
	decryption_cache[cache_index] = decrypted_string;			// Cache this string for any future calls

	return decrypted_string;
}

function decrypt_and_email(crypted_string,n,decryption_key) {
	if(!n || !decryption_key) { n = 0; decryption_key = 0; }
	if(!crypted_string) crypted_string = 0;

	var decrypted_string = decrypt_string(crypted_string,n,decryption_key,false);
	parent.location = decrypted_string;
}

function decrypt_and_echo(crypted_string,n,decryption_key) {
	if(!n || !decryption_key) { n = 0; decryption_key = 0; }
	if(!crypted_string) crypted_string = 0;

	var decrypted_string = decrypt_string(crypted_string,n,decryption_key,true);
	document.write(decrypted_string);
	return true;
}

// Finds base^exponent % y for large values of (base^exponent)
function exponentialModulo(base,exponent,y) {
	if (y % 2 == 0) {
		answer = 1;
		for(var i = 1; i <= y/2; i++) {
			temp = (base*base) % exponent;
			answer = (temp*answer) % exponent;
		}
	} else {
		answer = base;
		for(var i = 1; i <= y/2; i++) {
			temp = (base*base) % exponent;
			answer = (temp*answer) % exponent;
		}
	}
	return answer;
}


if(!addresses) var addresses = new Array();
addresses.push("16019 3149 6068 2889 13774 13208 8612 3223 10281 12902 3223 13894 8612 2889 12902 8612 4273 13208 2889 13894 11098 13208 2889 6648 6693 12902 3223 6693 11931 1762 11436 3342 11931 6648 15214 2563 12902 8612 10545 9490 2563 6648 10646 265 13894 2829 11931 13774 12660 4447");


// -->

