// Get the document object to work on several navigators.
if (document.all && !document.getElementById) {
	doc = document.all;
    doc.getElementById = function(id) { return document.all[id] }
} else {
	doc = document;
}	

/* Set true if it is an Internet Explorer */
var IE = document.all? true: false;

/* Information about browser */
var ua = ' ' + navigator.userAgent.toLowerCase();
var operating_system;
if (navigator.appVersion.indexOf("Win") > 0) {
	operating_system = "Win";
}	
if (navigator.appVersion.indexOf("Mac") > 0) {
	operating_system = "Mac";
}
var is_id = (document.getElementById) ? true : false;
var is_IE = ua.indexOf('msie') >= 0;
var is_NN = (ua.indexOf('netscape') >= 0 || ua.indexOf('gecko') >= 0);
var iVersion = parseFloat(navigator.appVersion);
var sInfo;
if (is_IE) {
	sInfo    = navigator.appVersion.toLowerCase().indexOf('msie') + 5;
	iVersion = parseFloat(navigator.appVersion.substring(sInfo));
} else if (is_NN){
	sInfo    = ua.lastIndexOf('/') + 1;
	iVersion = parseFloat(ua.substring(sInfo,ua.length));
}
var version = iVersion;

// Capture events
/*if (document.layers) { // Netscape
	document.captureEvents(Event.KEYDOWN);
	document.onkeydown = captureShortKey;
	document.onfocus = function() { return false;};	
} else if (document.all) { // Internet Explorer
	document.onkeydown = captureShortKey;
	document.onfocus = function() { return false;};	
} else if (document.getElementById) { // Netcsape 6
	document.onkeydown = captureShortKey;
	document.onfocus = function() { return false;};	
}*/

function captureShortKey(e) {
	if (IE) {
		switch(event.keyCode) {
			case 113: {
					   delete_last_occurrence();
					   break;
					  }
		}
	} else {
		switch(e.keyCode) {
			case 113: {
					   delete_last_occurrence();
					   break;
					  }
		}
	}
}

function sprintf() {
	if (!arguments || arguments.length < 1 || !RegExp)
	{
		return;
	}
	var str = arguments[0];
	var re = /([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X)(.*)/;
	var a = b = [], numSubstitutions = 0, numMatches = 0;
	while (a = re.exec(str))
	{
		var leftpart = a[1], pPad = a[2], pJustify = a[3], pMinLength = a[4];
		var pPrecision = a[5], pType = a[6], rightPart = a[7];
		
		//alert(a + '\n' + [a[0], leftpart, pPad, pJustify, pMinLength, pPrecision);

		numMatches++;
		if (pType == '%')
		{
			subst = '%';
		}
		else
		{
			numSubstitutions++;
			if (numSubstitutions >= arguments.length)
			{
				alert('Error! Not enough function arguments (' + (arguments.length - 1) + ', excluding the string)\nfor the number of substitution parameters in string (' + numSubstitutions + ' so far).');
			}
			var param = arguments[numSubstitutions];
			var pad = '';
				   if (pPad && pPad.substr(0,1) == "'") pad = leftpart.substr(1,1);
			  else if (pPad) pad = pPad;
			var justifyRight = true;
				   if (pJustify && pJustify === "-") justifyRight = false;
			var minLength = -1;
				   if (pMinLength) minLength = parseInt(pMinLength);
			var precision = -1;
				   if (pPrecision && pType == 'f') precision = parseInt(pPrecision.substring(1));
			var subst = param;
				   if (pType == 'b') subst = parseInt(param).toString(2);
			  else if (pType == 'c') subst = String.fromCharCode(parseInt(param));
			  else if (pType == 'd') subst = parseInt(param) ? parseInt(param) : 0;
			  else if (pType == 'u') subst = Math.abs(param);
			  else if (pType == 'f') subst = (precision > -1) ? Math.round(parseFloat(param) * Math.pow(10, precision)) / Math.pow(10, precision): parseFloat(param);
			  else if (pType == 'o') subst = parseInt(param).toString(8);
			  else if (pType == 's') subst = param;
			  else if (pType == 'x') subst = ('' + parseInt(param).toString(16)).toLowerCase();
			  else if (pType == 'X') subst = ('' + parseInt(param).toString(16)).toUpperCase();
		}
		str = leftpart + subst + rightPart;
	}
	return str;
}

/* Check wether a string is a numeric string */
function is_numeric(string) {
	for (var index = 0; index < string.length; index++) {
		var character = string.charAt(index);
		var char_code = character.charCodeAt(0);
		if ((char_code < 48) || (char_code > 57)) {
			return false;
		}
	}	
	return true;	
}

/* Check wether a string is an alphanumeric string */
function is_alphanumeric(string) {
	for (var index = 0; index < string.length; index++) {
		var character = string.charAt(index);
		var char_code = character.charCodeAt(0);
		if ((char_code < 48) || (char_code > 57 && char_code < 65) || ((char_code > 90) && (char_code < 97)) || (char_code > 122)) {
			return false;
		}
	}
	return true;	
}

/* Check wether a string is empty */
function empty_field(field) {
	if (field.value == '') {
		return true;
	} else {
		return false;
	}
}

/* Check for a correct email address */
/*function correct_email(email) {
	if (email.value.indexOf('@', 0) == -1 ||
    	email.value.indexOf('.', 0) == -1) { 
		return false;
	} else {
		return true;
	}
} */

function correct_email(emailStr) {
	var emailPat     = /^(.+)@(.+)$/;
	var specialChars = "\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
	var validChars   = "\[^\\s" + specialChars + "\]";
	var firstChars   = validChars;
	var quotedUser   ="(\"[^\"]*\")";
	var ipDomainPat  = /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	var atom         = "(" + firstChars + validChars + "*" + ")";
	var word         = "(" + atom + "|" + quotedUser + ")";
	var userPat      = new RegExp("^" + word + "(\\." + word + ")*$");
	var domainPat    = new RegExp("^" + atom + "(\\." + atom +")*$");
	var matchArray   = emailStr.match(emailPat);
	if (matchArray == null) {
	alert("La dirección de correo electrónico no fue ingresada correctamente.")
	return false
	}
	var user   = matchArray[1];
	var domain = matchArray[2];
	if (user.match(userPat) == null) {
	  alert("El nombre de usuario de la dirección de correo electrónico no es válido.");
	  return false;
	}
	var IPArray = domain.match(ipDomainPat);
	if (IPArray != null) {
		for (var i = 1; i <= 4; i++) {
    	    if (IPArray[i]>255) {
        	    alert("La dirección IP no es válida");
                return false;
            }
      	}
      	return true;
  	}
	var domainArray = domain.match(domainPat);
	if (domainArray == null) {
		alert("La dirección de dominio del correo electrónico no es válida.");
	  	return false;
	}
	var atomPat = new RegExp(atom,"g");
	var domArr  = domain.match(atomPat);
	var len     = domArr.length;
	if ((domArr[domArr.length-1].length < 2) ||
	    (domArr[domArr.length-1].length > 3)) {
		// the address must end in a two letter or three letter word.
		alert("La dirección del dominio del correo electrónico debe finalizar con \ntres letras de dominio (.com, .org) ó dos letras de país (.ar, .uk).");
		return false;
	}
	if ((domArr[domArr.length-1].length == 2) && (len < 3)) {
		var errStr = "La dirección del dominio del correo electrónico finaliza con dos caracteres, pero";
		errStr     += " falta el nombre del host y la categoría (.com, .gov, .edu).";
		alert(errStr);
		return false;
	}
	if ((domArr[domArr.length-1].length == 3) && (len < 2)) {
		var errStr = "La dirección del nombre del host en la dirección de correo electrónico no es válida.";
		alert(errStr);
		return false;
	}
	return true;
}

/* check all the checkboxes ina  group */
function check_all(trigger, check_array_name) {
	if (trigger.checked == 1) {
		check_array = doc.getElementsByName(check_array_name);	
		for (i = 0; i < check_array.length; i++) {
			check_array[i].checked = 1;
		}
	} else {
		check_array = doc.getElementsByName(check_array_name);	
		for (i = 0; i < check_array.length; i++) {
			check_array[i].checked = 0;
		}		
	}		
}

function confirm_admition(user) {
	if (confirm("¿Está seguro que desea admitir a " + user + "?")) {
		return true;
	} else {
		return false;
	}	
}

function confirm_delete(user) {
	if (confirm("¿Está seguro que desea eliminar a " + user + "?")) {
		return true;
	} else {
		return false;
	}
}

function select_all(aForm) {
	var list     = document.getElementById('permissions_to_add');	
	var listSize = list.length;
	for (i = 0; i < listSize; i++) {
		list.options[i].selected = true;
	}	
	aForm.submit();
	return true;
}

function showHide(panelName) {
	panel = document.getElementById(panelName);
	if (panel.style.display == "inline") {
		panel.style.display = "none";
	} else {
		panel.style.display = "inline";	
	}
}

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;
}

function getFocus(aFieldName) {
	document.getElementById(aFieldName).focus;
}
