var isIE = document.all?true:false;
var isNS = document.layers?true:false;

var isNS4 = (document.layers) ? true : false;
var isIE4 = (document.all && !document.getElementById) ? true : false;
var isIE5 = (document.all && document.getElementById) ? true : false;
var isNS6 = (!document.all && document.getElementById) ? true : false;

var scr_w = screen.availWidth;
var scr_h = screen.availHeight;

//if (document.layers)
//    document.captureEvents(Event.MOUSEMOVE);
//document.onmousemove = captureMousePosition;

var xMousePos = 0;
var yMousePos = 0;
var xMousePosMax = 0;
var yMousePosMax = 0;

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

    if (document.layers)
	{
        xMousePos = e.pageX;
        yMousePos = e.pageY;
        xMousePosMax = window.innerWidth+window.pageXOffset;
        yMousePosMax = window.innerHeight+window.pageYOffset;
    }
	else if (document.all)
	{
        xMousePos = e.clientX + document.body.scrollLeft;
        yMousePos = e.y + document.body.scrollTop;
        xMousePosMax = document.body.clientWidth + document.body.scrollLeft;
        yMousePosMax = document.body.clientHeight + document.body.scrollTop;
    }
	else if (document.getElementById)
	{
        xMousePos = e.pageX;
        yMousePos = e.pageY;
        xMousePosMax = window.innerWidth+window.pageXOffset;
        yMousePosMax = window.innerHeight+window.pageYOffset;
    }
}

function aleatorio(inferior,superior)
{
	var dif = superior - inferior + 1;
	var aleat = parseInt( Math.random() * 100000000 ) % dif;
	return parseInt(inferior) + aleat;
}

function nuevaVentana( name, w, h, url, opciones )
{
	if(!opciones) opciones = 'toolbar=no,location=no,directories=no,status=no,scrollbars=yes,resizable=yes,copyhistory=no';

	if( window.open ( url, name, opciones + ',width=' + w + ',height=' + h + '') )
		return true;

	return false;
}

function loading( msg )
{
	if(msg == null) msg = 'Cargando, por favor espere...';

	promptbox = document.createElement('div');
	promptbox.setAttribute ('id' , 'loading')
	document.getElementsByTagName('body')[0].appendChild(promptbox)
	promptbox = eval("document.getElementById('loading').style")
	promptbox.position = 'absolute'
	promptbox.top = 140
	promptbox.left = 200;//scr_w / 2 - 150;
	promptbox.width = 300

	var titulo = "<table cellspacing='0' cellpadding='0' border='0' width='100%'><tr valign='middle'><td class='titlebar'>Información</td><td align='right' class='titlebar' onClick='offLoading();' onMouseOver='manoOn(this);' onMouseOut='manoOff(this);'>[x]</td></tr></table>";
	var contenido = "<table cellspacing='0' cellpadding='4' border='0' width='100%' class='promptbox'><tr><td class='texto12b' align='center' valign='middle'>" + msg + "</td></tr></table>";
	var ventana = document.getElementById('loading');

	ventana.innerHTML = '<table bgcolor="#000000" cellspacing="0" cellpadding="1" border="0" width="100%"><tr><td>' + titulo + contenido + '</td></tr></table>';
}

function offLoading()
{
	document.getElementsByTagName("body")[0].removeChild(document.getElementById("loading"));

	if(window.stop)
		window.stop();
	else if(document.execCommand)
		document.execCommand("Stop")
}

function findPosX(obj)
{
	var curleft = 0;

	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;

	return curleft;
}

function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;

	return curtop;
}

/**
 * This array is used to remember mark status of rows in browse mode
 */
var marked_row = new Array;


/**
 * Sets/unsets the pointer and marker in browse mode
 *
 * @param   object    the table row
 * @param   integer  the row number
 * @param   string    the action calling this script (over, out or click)
 * @param   string    the default background color
 * @param   string    the color to use for mouseover
 * @param   string    the color to use for marking a row
 *
 * @return  boolean  whether pointer is set or not
 */
function setPointer(theRow, theRowNum, theAction, theDefaultColor, thePointerColor, theMarkColor)
{
    var theCells = null;

    // 1. Pointer and mark feature are disabled or the browser can't get the
    //    row -> exits
    if ((thePointerColor == '' && theMarkColor == '')
        || typeof(theRow.style) == 'undefined') {
        return false;
    }

    // 2. Gets the current row and exits if the browser can't get it
    if (typeof(document.getElementsByTagName) != 'undefined') {
        theCells = theRow.getElementsByTagName('td');
    }
    else if (typeof(theRow.cells) != 'undefined') {
        theCells = theRow.cells;
    }
    else {
        return false;
    }

    // 3. Gets the current color...
    var rowCellsCnt  = theCells.length;
    var domDetect    = null;
    var currentColor = null;
    var newColor     = null;
    // 3.1 ... with DOM compatible browsers except Opera that does not return
    //         valid values with "getAttribute"
    if (typeof(window.opera) == 'undefined'
        && typeof(theCells[0].getAttribute) != 'undefined') {
        currentColor = theCells[0].getAttribute('bgcolor');
        domDetect    = true;
    }
    // 3.2 ... with other browsers
    else {
        currentColor = theCells[0].style.backgroundColor;
        domDetect    = false;
    } // end 3

    // 3.3 ... Opera changes colors set via HTML to rgb(r,g,b) format so fix it
    if (currentColor.indexOf("rgb") >= 0)
    {
        var rgbStr = currentColor.slice(currentColor.indexOf('(') + 1,
                                     currentColor.indexOf(')'));
        var rgbValues = rgbStr.split(",");
        currentColor = "#";
        var hexChars = "0123456789ABCDEF";
        for (var i = 0; i < 3; i++)
        {
            var v = rgbValues[i].valueOf();
            currentColor += hexChars.charAt(v/16) + hexChars.charAt(v%16);
        }
    }

    // 4. Defines the new color
    // 4.1 Current color is the default one
    if (currentColor == ''
        || currentColor.toLowerCase() == theDefaultColor.toLowerCase()) {
        if (theAction == 'over' && thePointerColor != '') {
            newColor              = thePointerColor;
        }
        else if (theAction == 'click' && theMarkColor != '') {
            newColor              = theMarkColor;
            marked_row[theRowNum] = true;
            // Garvin: deactivated onclick marking of the checkbox because it's also executed
            // when an action (like edit/delete) on a single item is performed. Then the checkbox
            // would get deactived, even though we need it activated. Maybe there is a way
            // to detect if the row was clicked, and not an item therein...
            // document.getElementById('id_rows_to_delete' + theRowNum).checked = true;
        }
    }
    // 4.2 Current color is the pointer one
    else if (currentColor.toLowerCase() == thePointerColor.toLowerCase()
             && (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])) {
        if (theAction == 'out') {
            newColor              = theDefaultColor;
        }
        else if (theAction == 'click' && theMarkColor != '') {
            newColor              = theMarkColor;
            marked_row[theRowNum] = true;
            // document.getElementById('id_rows_to_delete' + theRowNum).checked = true;
        }
    }
    // 4.3 Current color is the marker one
    else if (currentColor.toLowerCase() == theMarkColor.toLowerCase()) {
        if (theAction == 'click') {
            newColor              = (thePointerColor != '')
                                  ? thePointerColor
                                  : theDefaultColor;
            marked_row[theRowNum] = (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])
                                  ? true
                                  : null;
            // document.getElementById('id_rows_to_delete' + theRowNum).checked = false;
        }
    } // end 4

    // 5. Sets the new color...
    if (newColor) {
        var c = null;
        // 5.1 ... with DOM compatible browsers except Opera
        if (domDetect) {
            for (c = 0; c < rowCellsCnt; c++) {
				if(theCells[c].getAttribute('bgcolor') == currentColor)
					theCells[c].setAttribute('bgcolor', newColor, 0);
            } // end for
        }
        // 5.2 ... with other browsers
        else {
            for (c = 0; c < rowCellsCnt; c++) {
				if(theCells[c].style.backgroundColor == currentColor)
					theCells[c].style.backgroundColor = newColor;
            }
        }
    } // end 5

    return true;
} // end of the 'setPointer()' function


/*TOOLTIP*/
/*compara string con expresion regular determinada*/
function OnlyMatch(regex,string) //regex:: exp. regular con la que comparar , string:: string que debe comparar
{
    var pattern;

    //CARACTERES LATINOS :: letras mayusculas y minusculas, tildes, espacios, guión
    if(regex == 'letras')
        pattern = /^[a-zA-ZñÑáéíóúÁÉÍÓÚ\s-]+$/;
	//NÚMEROS :: acepta sólo números de 0 a 9, sin espacios ni guiones
    if(regex == 'numeros')
        pattern = /^[0-9]+$/;
	//LETRAS&NUMEROS :: acepta sólo caracteres alfanumericos, tildes, espacios, guión
    if(regex == 'alfanumericos')
        pattern = /^[a-zA-Z0-9ñÑáéíóúÁÉÍÓÚ\s-]+$/;
	//PASSWORD :: acepta sólo caracteres alfanumericos, tildes, guión
    if(regex == 'password')
        pattern = /^[a-zA-Z0-9-]+$/;
	//DIRECCION :: acepta caracteres alfanumericos, tildes, espacios, guión, º # ()
    if(regex == 'direccion')
        pattern = /^[a-zA-Z0-9ñÑáéíóúÁÉÍÓÚ\s-#º)(]+$/;
	//TELÉFONOS :: acepta sólo números de 0 a 9, guiones, paréntesis, el signo +
    if(regex == 'telefono')
        pattern = /^[0-9-\+)(]+$/;
    //MAIL :: algo @ algo . sigla
    if(regex == 'mail')
        pattern = /^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$/;
    if(regex == 'url')
        pattern = /^[a-zA-Z0-9ñÑáéíóúÁÉÍÓÚ\s-\.\/:\?=]+$/;

    if(pattern.test(string))
		return true;
	else
		return false;

}


function checkLength(myinput,min,max,required)
{
    var text = myinput;

	if(required == 0 && text == "")
	{
	  return false;
	}
    if(text.length >= min )
        if((text.length <= max && max != 0) || max == 0)
		{
			return true;
		}
        else
		{
			return false;
		}
    else
	{
		return false;
	}

	return true;
}

function checkRegex(myinput,tipo,required)
{
    var text = myinput;

	if(!required && text == "")
	{
	  return false;
	}

    if(OnlyMatch(tipo,text))
	{
		return true;
	}
    else
	{
		return false;
	}

	return true;
}

function checkRegexRange(myinput,tipo,min,max,required)
{
    var text = myinput;

	if(!required && text == "")
	{
	  return true;
	}

    if(!OnlyMatch(tipo,text) || text.length < min)
	{
	  return false;
	}
	else if(text.length > max && max != 0)
	{
	  return false;
	}
    else
		return true;

	return true;
}

/*crea Select list pasando numeros como parametro para evitar lineas de codigo HTML*/
function LlenarSelectNumeros(selectbox,desde,hasta) //selectbox:: id de <select /> donde se crearan opciones , desde::hasta:: rango de numeros
{
	selectbox.options.length = 0;
	var opcion, i = desde;

	if(desde > hasta)
	{
	  while(i >= hasta)
	  {
		obj = document.createElement('option');
		obj.value = i;
		obj.appendChild( document.createTextNode(i) );
		selectbox.appendChild( obj );
		i--;
	  }
	}
	else
	{
	  while(i <= hasta)
	  {
		obj = document.createElement('option');
		obj.value = i;
		obj.appendChild( document.createTextNode(i) );
		selectbox.appendChild( obj );
		i++;
	  }
	}
	return true;
}


function ValidarRut(rut, dv)
{
  rut = parseInt(rut,10);
  rut = rut.toString();

  var suma = 0;
  var tur = "";

  for(var i = rut.length - 1; i >=0; i--) tur += rut.charAt(i);

  var mult = 2;
  for (i = 0; i <= tur.length; i++)
  {
    if (mult > 7) mult = 2;
    suma = mult * tur.substring(i,i+1) + suma;
    mult++;
  }

  var valor = 11 - (suma % 11);
  if (valor == 11) codigo_veri = "0";
  else if (valor == 10) codigo_veri = "k";
  else codigo_veri = valor;

  if(dv.toLowerCase() != codigo_veri)
	return false;
  else
	return true;

}

function KeyPress(obj, e)
{
	var tecla = (document.all) ? e.keyCode : e.which;

	if (tecla == 13)
	{
		obj.blur();
		return false;
	}

	return true;
}


function Numerico(e,puntos)
{
	var key = window.event ? e.keyCode : e.which;

	if(puntos)
	{
		if( key == '46')
			return false;
	}

	if (key != '13' && key > '45' && key < '59' && key != '47' || key == '8' || key == '0')
	{
		var keychar = String.fromCharCode(key);
		return (keychar);
	}
	else
		return false;
}
