// JavaScript Document

// Table Management Functions
// This function creates table dynamically,.
function createDynTable(row, col) {
        // get the reference for the body
        var mybody = document.getElementsByTagName("body")[0];

        // creates a <table> element and a <tbody> element
        mytable     = document.createElement("table");
        mytablebody = document.createElement("tbody");

        // creating all cells
        for(var j = 0; j < row; j++) {
            // creates a <tr> element
            mycurrent_row = document.createElement("tr");
            for(var i = 0; i < col; i++) {
                // creates a <td> element
                mycurrent_cell = document.createElement("td");
				
				// add edit cell;
				mycurrent_cell.ondblclick = function (evt) { editCell(this);};
                
				// creates a text node
                currenttext = document.createTextNode("cell is row "+j+", column "+i);
                // appends the text node we created into the cell <td>
                mycurrent_cell.appendChild(currenttext);
                // appends the cell <td> into the row <tr>
                mycurrent_row.appendChild(mycurrent_cell);
            }
            // appends the row <tr> into <tbody>
            mytablebody.appendChild(mycurrent_row);
        }
        // appends <tbody> into <table>
        mytable.appendChild(mytablebody);
        // appends <table> into <body>
        mybody.appendChild(mytable);
        // sets the border attribute of mytable to 2;
        mytable.setAttribute("border", "2");
		
		return mytable;
    }


// Insert row into table.
function insRowLast(table)
{

	//alert(table.rows);
	
	// noOfRpws in table.
	noOfRows = table.rows.length;
	// no of columns of last row.
	noOfCols = table.rows[noOfRows-1].cells.length;
	
	// insert row at last.
	var x=table.insertRow(noOfRows);
	
	// insert cells in row.
	for (var j = 0; j < noOfCols; j++) {
	
		newCell = x.insertCell(j);
		// make cell editable feature.
		newCell.ondblclick = function (evt) { editCell(this);};
		
		//newCell.innerHTML="NEW CELL" + j;
	}
	
	return x;
}


//delete row
function deleteRow(table, row)
{
	table.deleteRow(row);
}

//delete last row.
function deleteRow(table)
{
	noOfRows = table.rows.length;
	table.deleteRow(noOfRows-1);
}


//Example : In html file.
//<TD ONdblCLICK="editCell(this);">Data< /TD>

//added ONBLUR, cuz without that, u would recive an error if u had not
// edited the value in the input box
function editCell (cell) {
  if (document.all) {
    cell.innerHTML =
      '<INPUT ' +
      ' ID="editCell"' +
      ' ONCLICK="event.cancelBubble = true;"' + 
      ' ONCHANGE="setCell(this.parentElement, this.value)" ' +
      ' ONBLUR="setCell(this.parentElement, this.value)" ' +
      ' VALUE="' + cell.innerText + '"' +
      ' SIZE="' + cell.innerText.length + '"' +
      '>';
    document.all.editCell.focus();
    document.all.editCell.select();
  }
  else if (document.getElementById) {
    cell.normalize();
    var input = document.createElement('INPUT');
    input.setAttribute('value', cell.firstChild.nodeValue);
    input.setAttribute('size', cell.firstChild.nodeValue.length);
    input.onchange = function (evt) { setCell(this.parentNode, 
this.value); };
    input.onclick = function (evt) { 
      evt.cancelBubble = true;
      if (evt.stopPropagation)
        evt.stopPropagation();
    };
    cell.replaceChild(input, cell.firstChild);
    input.focus();
    input.select();
  }

}

function setCell (cell, value) {
  if (document.all)
    cell.innerText = value;
  else if (document.getElementById)
    cell.replaceChild(document.createTextNode(value), cell.firstChild);
}

	// Validation functions
	
	
	/***********************************************
	* Required field(s) validation v1.10- By NavSurf
	* Visit Nav Surf at http://navsurf.com
	* Visit http://www.dynamicdrive.com/ for full source code
	***********************************************/
	
	function formCheck(formobj){
		
		// dialog message
		var alertMsg = "Please complete the following fields:\n";
		
		var l_Msg = alertMsg.length;
		
		for (var i = 0; i < fieldRequired.length; i++){
			var obj = formobj.elements[fieldRequired[i]];
			//alert(obj.type);
			if (obj){
				switch(obj.type){
					
				case "select-one":
					
					//alert(obj.selectedIndex);
					//alert(obj.options[obj.selectedIndex].text);
					if (obj.selectedIndex == 0 || obj.options[obj.selectedIndex].text == ""){
						alertMsg += " - " + fieldDescription[i] + "\n";
					}
					break;
				case "select-multiple":
					if (obj.selectedIndex == -1){
						alertMsg += " - " + fieldDescription[i] + "\n";
					}
					break;
				case "text":
				//case "file":
				case "textarea":
					if (obj.value == "" || obj.value == null){
						alertMsg += " - " + fieldDescription[i] + "\n";
					}
					break;
				default:
				}
				if (obj.type == undefined){
					var blnchecked = false;
					for (var j = 0; j < obj.length; j++){
						if (obj[j].checked){
							blnchecked = true;
						}
					}
					if (!blnchecked){
						alertMsg += " - " + fieldDescription[i] + "\n";
					}
				}
			}
		}

		if (alertMsg.length == l_Msg){
			return true;
		}
		else{
			alert(alertMsg);
			return false;
		}
	}
	
// Utility for checking checkboxes on PHP file

<!-- 	
// by Nannette Thacker
// http://www.shiningstar.net
// This script checks and unchecks boxes on a form
// Checks and unchecks unlimited number in the group...
// Pass the Checkbox group name...
// call buttons as so:
// <input type=button name="CheckAll"   value="Check All"
	//onClick="checkAll(document.myform.list)">
// <input type=button name="UnCheckAll" value="Uncheck All"
	//onClick="uncheckAll(document.myform.list)">
// -->

<!-- Begin
function checkAll(field)
{
for (i = 0; i < field.length; i++)
	field[i].checked = true ;
}

function uncheckAll(field)
{
for (i = 0; i < field.length; i++)
	field[i].checked = false ;
}
//  End -->



var formblock;
var forminputs;

function prepare() {
	formblock= document.getElementById('form_assign_event');
	if (undefined != formblock ){
		forminputs = formblock.getElementsByTagName('input');
	}
}



function select_all(name, value) {
	for (i = 0; i < forminputs.length; i++) {
		// regex here to check name attribute
		var regex = new RegExp(name, "i");
		if (regex.test(forminputs[i].getAttribute('name'))) {
			if (value == '1') {
				forminputs[i].checked = true;
			} 
			else {
				forminputs[i].checked = false;
			}
		}
	}
}

if (window.addEventListener) {
	window.addEventListener("load", prepare, false);
} 
else if (window.attachEvent) {
	window.attachEvent("onload", prepare)
} 
else if (document.getElementById) {
	window.onload = prepare;
}

function hasSelectCheckbox(name)
{
	for (i = 0; i < forminputs.length; i++) {
		// regex here to check name attribute
		var regex = new RegExp(name, "i");
		if (regex.test(forminputs[i].getAttribute('name'))) {
			if (forminputs[i].checked) {
				return true;
			}
		}
	}
	return false;
}

// String trim functions
function leftTrim(sString)
{
	while (sString.substring(0,1) == ' ')
	{
		sString = sString.substring(1, sString.length);
	}
	return sString;
}

function rightTrim(sString)
{
	while (sString.substring(sString.length-1, sString.length) == ' ')
	{
		sString = sString.substring(0,sString.length-1);
	}
	return sString;
}

function trimAll(sString)
{
	while (sString.substring(0,1) == ' ')
	{
		sString = sString.substring(1, sString.length);
	}
		
	while (sString.substring(sString.length-1, sString.length) == ' ')
	{
		sString = sString.substring(0,sString.length-1);
	}
	
	return sString;
}

// Check for email validation
	function emailCheck (emailStr) {
	
	/* The following variable tells the rest of the function whether or not
	to verify that the address ends in a two-letter country or well-known
	TLD.  1 means check it, 0 means don't. */
	
	var checkTLD=1;
	
	/* The following is the list of known TLDs that an e-mail address must end with. */
	
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	
	/* The following pattern is used to check if the entered e-mail address
	fits the user@domain format.  It also is used to separate the username
	from the domain. */
	
	var emailPat=/^(.+)@(.+)$/;
	
	/* The following string represents the pattern for matching all special
	characters.  We don't want to allow special characters in the address. 
	These characters include ( ) < > @ , ; : \ " . [ ] */
	
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	
	/* The following string represents the range of characters allowed in a 
	username or domainname.  It really states which chars aren't allowed.*/
	
	var validChars="\[^\\s" + specialChars + "\]";
	
	/* The following pattern applies if the "user" is a quoted string (in
	which case, there are no rules about which characters are allowed
	and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
	is a legal e-mail address. */
	
	var quotedUser="(\"[^\"]*\")";
	
	/* The following pattern applies for domains that are IP addresses,
	rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
	e-mail address. NOTE: The square brackets are required. */
	
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	
	/* The following string represents an atom (basically a series of non-special characters.) */
	
	var atom=validChars + '+';
	
	/* The following string represents one word in the typical username.
	For example, in john.doe@somewhere.com, john and doe are words.
	Basically, a word is either an atom or quoted string. */
	
	var word="(" + atom + "|" + quotedUser + ")";
	
	// The following pattern describes the structure of the user
	
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	
	/* The following pattern describes the structure of a normal symbolic
	domain, as opposed to ipDomainPat, shown above. */
	
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
	
	/* Finally, let's start trying to figure out if the supplied address is valid. */
	
	/* Begin with the coarse pattern to simply break up user@domain into
	different pieces that are easy to analyze. */
	
	var matchArray=emailStr.match(emailPat);
	
	if (matchArray==null) {
	
	/* Too many/few @'s or something; basically, this address doesn't
	even fit the general mould of a valid e-mail address. */
	
	alert("Email address seems incorrect (check @ and .'s)");
	return false;
	}
	var user=matchArray[1];
	var domain=matchArray[2];
	
	// Start by checking that only basic ASCII characters are in the strings (0-127).
	
	for (i=0; i<user.length; i++) {
	if (user.charCodeAt(i)>127) {
	alert("Ths username contains invalid characters.");
	return false;
	   }
	}
	for (i=0; i<domain.length; i++) {
	if (domain.charCodeAt(i)>127) {
	alert("Ths domain name contains invalid characters.");
	return false;
	   }
	}
	
	// See if "user" is valid 
	
	if (user.match(userPat)==null) {
	
	// user is not valid
	
	alert("The username doesn't seem to be valid.");
	return false;
	}
	
	/* if the e-mail address is at an IP address (as opposed to a symbolic
	host name) make sure the IP address is valid. */
	
	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) {
	
	// this is an IP address
	
	for (var i=1;i<=4;i++) {
	if (IPArray[i]>255) {
	alert("Destination IP address is invalid!");
	return false;
	   }
	}
	return true;
	}
	
	// Domain is symbolic name.  Check if it's valid.
	 
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++) {
	if (domArr[i].search(atomPat)==-1) {
	alert("The domain name does not seem to be valid. Also check for trailing spaces.");
	return false;
	   }
	}
	
	/* domain name seems valid, but now make sure that it ends in a
	known top-level domain (like com, edu, gov) or a two-letter word,
	representing country (uk, nl), and that there's a hostname preceding 
	the domain or country. */
	
	if (checkTLD && domArr[domArr.length-1].length!=2 && 
	domArr[domArr.length-1].search(knownDomsPat)==-1) {
	alert("The address must end in a well-known domain or two letter " + "country.");
	return false;
	}
	
	// Make sure there's a host name preceding the domain.
	
	if (len<2) {
	alert("This address is missing a hostname!");
	return false;
	}
	
	// If we've gotten this far, everything's valid!
	return true;
	}
