/**********************************************************************
* DEFINICION DE VARIABLES GLOBALES
* Estas variables son usadas en toda la aplicacion
***********************************************************************/
var timerID;

/**********************************************************************
* Busca sobre la tabla celdas que contenga un texto que comience por: findValue
* PARAMETROS: findValue: Texto a buscar.
*             grid: Nombre de la tabla infragistics. Nombre final.        
***********************************************************************/
function FindValue(findValue, grid) 
{
    var re = new RegExp("^" + findValue);
    oUltraWebGrid1 = igtbl_getGridById(grid); 
    var oCell = oUltraWebGrid1.find(re);
    if(oCell != null) 
    {
        row = oCell.getRow();
        row.setSelected(true);
        oUltraWebGrid1.setActiveRow(row);
    }
}

/**********************************************************************
* Se encarga de solicitar nuevamente autenticacion al usuario al momento
* de perderse la session
* PARAMETROS: appPath -->  Path del WebSite
***********************************************************************/
function Reconnect(appPath, miliseconds)
{
    try
    {
        window.clearInterval(timerID);
        var args = new Array();
        var width  =450;
        var height = 300;
        
        args[0] = appPath;
        //grayOut(true,{'opacity':'25'});
        var result = window.showModalDialog(appPath + '/Reconnect.aspx?act=timeout', args, 'dialogHeight:'+ height +'px; dialogWidth:'+ width +'px; center: Yes; help: No; resizable: No; status: Yes;');
        if(result != null)
        {
            //Si existe respuesta por la ventana modal, debe procesar la respuesta
            //Reestablece la funcion que valida la sesion
            timerID = window.setInterval('ReconnectByTimeOut()', miliseconds); 
        }
        else
        {
            //Si no existe respuesta por la ventana modal, debe redireccionar a la pantalla default
            window.top.location.href = appPath + '/Logout.aspx';
        }
    }
    catch(err)
    {
    
    }
    //grayOut(false);
}

/***************************************************************
* FUNCION QUE LIMITA LA CANTIDAD DE TEXTO INGRESADO EN UN TEXTAREA
***************************************************************/
function TextAreaLimit(control, amount)
{
	var v=control.value;
	if(v.length>amount)
		control.value=v.substring(0,amount);
}

/****************************************************************
* Abre una Popup Centrada
*****************************************************************/
function OpenPopup(Url, Tittle, Width, Height, Resizable)
{
    if(!Width || Width == 0)
        Width = window.screen.availWidth - 20;
        
    if(!Height || Height == 0)
        Height = window.screen.availHeight - 120;
        
    var left = ((window.screen.availWidth-Width)/2)-5;
	var top  = ((window.screen.availHeight-Height)/2)-50;
	
	if(Resizable == null || Resizable == false)
		window.open(Url, Tittle, 'toolbar=yes,scrollbars=yes,location=no,status=yes,menubar=no,resizable=no,left='+ left +',top='+ top +',width='+ Width +',height='+ Height);	
	else
		window.open(Url, Tittle, 'toolbar=yes,scrollbars=yes,location=no,status=yes,menubar=no,resizable=yes,left='+ left +',top='+ top +',width='+ Width +',height='+ Height);
}

function Popup(linkControl, Width, Height, Resizable)
{
    OpenPopup(linkControl.href, '', Width, Height, Resizable);
    return false;
}

/****************************************************************
* Howto Grey-Out The Screen
*****************************************************************/
function grayOut(vis, options) {
  // Pass true to gray out screen, false to ungray
  // options are optional.  This is a JSON object with the following (optional) properties
  // opacity:0-100         // Lower number = less grayout higher = more of a blackout 
  // zindex: #             // HTML elements with a higher zindex appear on top of the gray out
  // bgcolor: (#xxxxxx)    // Standard RGB Hex color code
  // grayOut(true, {'zindex':'50', 'bgcolor':'#0000FF', 'opacity':'70'});
  // Because options is JSON opacity/zindex/bgcolor are all optional and can appear
  // in any order.  Pass only the properties you need to set.
  var options = options || {}; 
  var zindex = options.zindex || 50;
  var opacity = options.opacity || 70;
  var opaque = (opacity / 100);
  var bgcolor = options.bgcolor || '#000000';
  var dark=document.getElementById('darkenScreenObject');
  if (!dark) {
    // The dark layer doesn't exist, it's never been created.  So we'll
    // create it here and apply some basic styles.
    // If you are getting errors in IE see: http://support.microsoft.com/default.aspx/kb/927917
    var tbody = document.getElementsByTagName("body")[0];
    var tnode = document.createElement('div');           // Create the layer.
        tnode.style.position='absolute';                 // Position absolutely
        tnode.style.top='0px';                           // In the top
        tnode.style.left='0px';                          // Left corner of the page
        tnode.style.overflow='hidden';                   // Try to avoid making scroll bars            
        tnode.style.display='none';                      // Start out Hidden
        tnode.id='darkenScreenObject';                   // Name it so we can find it later
    tbody.appendChild(tnode);                            // Add it to the web page
    dark=document.getElementById('darkenScreenObject');  // Get the object.
  }
  if (vis) {
    // Calculate the page width and height 
    if( document.body && ( document.body.scrollWidth || document.body.scrollHeight ) ) {
        var pageWidth = document.body.scrollWidth+'px';
        var pageHeight = document.body.scrollHeight+'px';
    } 
    else if( document.body.offsetWidth ) {
      var pageWidth = document.body.offsetWidth+'px';
      var pageHeight = document.body.offsetHeight+'px';
        } else {
            var pageWidth='100%';
            var pageHeight='100%';
    }   
    //set the shader to cover the entire page and make it visible.
    dark.style.opacity=opaque;                      
    dark.style.MozOpacity=opaque;                   
    dark.style.filter='alpha(opacity='+opacity+')'; 
    dark.style.zIndex=zindex;        
    //dark.style.backgroundColor=bgcolor;  
    dark.style.width= pageWidth;
    dark.style.height= pageHeight;
    dark.style.display='block';
  } 
  else 
  {
     //dark.style.display='none';
     dark.style.opacity=1;
     dark.style.MozOpacity=1;                   
     dark.style.filter='alpha(opacity='+ 100 +')';
     //dark.style.backgroundColor="";
  }
}

/****************************************************************
* Obtiene 3 pares de numeros randomicos separados por '-'. Tipo serial
*****************************************************************/
function GetRandomSerial()
{
    var intSegment1 = parseInt((9999 - 1000 + 1) * Math.random() + 1000);
    var intSegment2 = parseInt((9999 - 1000 + 1) * Math.random() + 1000);
    var intSegment3 = parseInt((9999 - 1000 + 1) * Math.random() + 1000);
    var trackingNumber = intSegment1 + "-" + intSegment2 + "-" + intSegment3;
    return trackingNumber;
}

/***************************************************************
* FUNCION QUE REMUEVE LOS ESPACIOS EN BLANCO
* A LA IZQUIERDA Y DERECHA DE UNA CADENA DE TEXTO
***************************************************************/
function Trim(str){
	if(str==null || str=="null")
		return "";
	var resultStr = "";
	resultStr = TrimLeft(str);
	resultStr = TrimRight(resultStr);
	return resultStr;
}

/***************************************************************
* FUNCION QUE REMUEVE LOS ESPACIOS EN BLANCO
* A LA DERECHA DE UNA CADENA DE TEXTO
***************************************************************/
function TrimRight( str ) {
	var resultStr = "";
	var i = 0;
	if (str+"" == "undefined" || str == null){	
		return null;
	}
	str += "";
	if (str.length == 0) 
		resultStr = "";
	else 
	{
  		i = str.length - 1;
  		while ((i >= 0) && (str.charAt(i) == " "))
 			i--;
  		resultStr = str.substring(0, i + 1);
  	}  	
  	return resultStr;  	
}

/***************************************************************
* FUNCION QUE REMUEVE LOS ESPACIOS EN BLANCO
* A LA IZQUIERDA DE UNA CADENA DE TEXTO
***************************************************************/
function TrimLeft( str ) {
	var resultStr = "";
	var i = len = 0;
	if (str+"" == "undefined" || str == null)	
		return null;
	str += "";
	if (str.length == 0) 
		resultStr = "";
	else 
	{	
  		len = str.length;		
  		while ((i <= len) && (str.charAt(i) == " "))
			i++;
		resultStr = str.substring(i, len);
  	}
  	return resultStr;
}

/***************************************************************
* REMUEVE UN ITEM DE UN DROWNDOWNLIST A PARTIR DEL ID DEL MISMO
***************************************************************/
function RemoveOption(ddlDrowDown, value) 
{
    var i;
    try
    {
        for(i = ddlDrowDown.length - 1; i>=0; i--)
	    {
	        try
	        {
	            var ddlValue = ddlDrowDown.options[i].value;
	            if(ddlValue != null && ddlValue == value)
	            {
	                ddlDrowDown.options[i] = null;
	                //ddlDrowDown.length = ddlDrowDown.length - 1;
	            }
            }
            catch(err1)
            {
            
            }
	    } 
    }
    catch(err)
    {
        alert("RemoveOption: " + i + " ---" + err.description);
    }
}

/***************************************************************
* REMUEVE UN ITEM DE UN DROWNDOWNLIST A PARTIR DEL ID DEL MISMO
***************************************************************/
function DeleteOptions(ddlDrowDown) 
{
    try
    {
        ddlDrowDown.length = 0;
    }
    catch(err)
    {
        alert("DeleteOptions: " + err.description);
    }
}

/***************************************************************
* VALIDA SI EXISTE UNA OPCION
***************************************************************/
function ExistOption(ddlDrowDown, value) 
{
    try
    {
        for(var i = 0; i<ddlDrowDown.length; i++)
	    {
	        var ddlValue = ddlDrowDown.options[i].value;
	        if(ddlValue == value)
	        {
	            return true;
	        }
	    }       
    }
    catch(err)
    {
        alert("ExistsOption: " + err.description);
    }
    return false;
}

/***************************************************************
* REMUEVE UN ITEM DE UN DROWNDOWNLIST A PARTIR DEL ID DEL MISMO
***************************************************************/
function AddOption(ddlDrowDown, optionText, optionValue, index)
{
    if(ddlDrowDown.length >= index)
    {
        //Aumenta el tamano al control
        ddlDrowDown.length = ddlDrowDown.length + 1;
        //Recorre el control moviendo los items a su siguiente posicion
        for(var i =  ddlDrowDown.length - 1; i > index; i--)
        {
            ddlDrowDown.options[i].text = ddlDrowDown.options[i - 1].text;
            ddlDrowDown.options[i].value = ddlDrowDown.options[i - 1].value;
        }
        //Setea el nuevo item
        
        ddlDrowDown.options[index].text = optionText;
        ddlDrowDown.options[index].value = optionValue;
    }
}

/***************************************************************
* ADICIONA UN ITEM DE UN DROWNDOWNLIST A PARTIR DEL ID DEL MISMO
***************************************************************/
function AddNewOption(ddlDrowDown, optionText, optionValue)
{
    //Aumenta el tamano al control
    ddlDrowDown.length = ddlDrowDown.length + 1;
    //Setea el nuevo item    
    ddlDrowDown.options[ddlDrowDown.length - 1].text = optionText;
    ddlDrowDown.options[ddlDrowDown.length - 1].value = optionValue;
}

/***************************************************************
* VALIDA SI EXISTE UNA OPCION
***************************************************************/
function RenameOption(ddlDrowDown, value, optionText) 
{
    try
    {
        for(var i = 0; i<ddlDrowDown.length; i++)
	    {
	        var ddlValue = ddlDrowDown.options[i].value;
	        if(ddlValue == value)
	        {
	            ddlDrowDown.options[i].text = optionText;
	            return true;
	        }
	    }       
    }
    catch(err)
    {
        alert("ExistsOption: " + err.description);
    }
    return false;
}

/**************************************************************
* Obtiene los valores concatenados por el caracter entregado
**************************************************************/
function GetOptionsAsString(ddlDrowDown, character)
{
    var opts = "";
    var len = ddlDrowDown.length;
    for(var i = 0; i< len; i++)
    {
        var opt = ddlDrowDown.options[i].value;
        opts += opt + character;
    }
    return opts;
}

/**************************************************************
* Obtiene el nombre de la pagina en ejecucion
**************************************************************/
function GetPageName()
{
    var sPath = window.location.pathname;
    var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
    return sPage;
}

/**************************************************************
* Format DateTime,
* el Formato aun no es soportado, pero es para futuras versiones
**************************************************************/
function DateFormat(date, format)
{
    var dd = date.getDate();
    var mm = date.getMonth()+1;//January is 0!
    var yyyy = date.getFullYear();
    var time = date.toLocaleTimeString();
    if(dd<10){dd='0'+dd}
    if(mm<10){mm='0'+mm}
    var result = mm+ '/'+ dd+ '/'+ yyyy + ' ' + time;
    return result;
}


/////////////////////////////////////////////////////////////////***********
/**************************************************************
* Chequea/Deschequea los nodos hijos. Recursivo por Evento
**************************************************************/
function CheckChilds(treeId, nodeId, bChecked)
{
    try
    {
        //alert("CheckChilds");
        var node = igtree_getNodeById(nodeId);
        if(node != null)
        {
            var childNodes = node.getChildNodes();
            if(childNodes.length > 0)
            {
                for(i=0; i<childNodes.length; i++)
                {
                    childNodes[i].setChecked(bChecked);
                }
            }
        }
    }
    catch(err)
    {
        window.status = "WebTree, CheckChilds: " + err.description;
    }
}

/**************************************************************
* Chequea el nodo Padre
**************************************************************/
function CheckParent(treeId, nodeId, bChecked)
{
    try
    {
        var node = igtree_getNodeById(nodeId);
        if(node != null)
        {
            var parentNode = node.getParent();
            if(parentNode != null)
            {
                parentNode.setChecked(bChecked);
            }
        }
    }
    catch(err)
    {
        window.status = "WebTree, CheckParent: " + err.description;
    }
}

/**************************************************************
* Usado para LIMPIAR todos los items, colocando como no seleccionados
**************************************************************/
function SetSelectedNodesALL(treeId, selected) {
    var Ids = "";
    try {
        var tree = igtree_getTreeById(treeId);
        if (tree != null) {
            var nodes = tree.getNodes();
            var i;
            for (i = 0; i < nodes.length; i++) 
            {
                SetSelectedNodes(nodes[i].getChildNodes(), selected);
            }
        }
    }
    catch (err) {
        window.status = "GetSelectedNodesOfLevel: " + err.description;
    }
    return Ids;
}

/**************************************************************
* Usado para LIMPIAR todos los items, colocando como no seleccionados
**************************************************************/
function SetSelectedNodes(nodes, selected) {
    try {
        if (nodes != null) {
            var i;
            for (i = 0; i < nodes.length; i++) {
                //Si esta en ese nivel
                nodes[i].setChecked(selected);

                //Mira al siguiente nivel
                var hasChildren = nodes[i].hasChildren();
                if (hasChildren == true) {
                    var childNodes = nodes[i].getChildNodes();
                    if (childNodes.length > 0) {
                        SetSelectedNodes(childNodes, selected);
                    }
                }
            }
        }
    }
    catch (err) {
        window.status = "WebTreet, SetSelectedNodes: " + err.description;
    }
}

/**************************************************************
* Setea los items del arbol a partir de un string ID separado por un caracter ';'
* Ejemplo: ID1;ID2;ID3, .... Solo busca por el paren con ID
**************************************************************/
function SetSelectedItemsOfParent(treeId, parentID, itemsIDs) {
    try {
        SetSelectedNodesALL(treeId, false);
        var tree = igtree_getTreeById(treeId);
        if (tree != null) {
            var nodes = tree.getNodes();
            var i;
            for (i = 0; i < nodes.length; i++) {
                //Si se encuentra el Parent
                if (nodes[i].getTag() == parentID) {
                    var hasChildren = nodes[i].hasChildren();
                    if (hasChildren == true) {
                        var childNodes = nodes[i].getChildNodes();
                        if (childNodes.length > 0) {
                            SetSelectedItemsOnNode(childNodes, itemsIDs);
                        }
                    }
                }
            }
        }
    }
    catch (err) {
        window.status = "WebTree, SetSelectedItemsOfParent: " + err.description;
    }
}

/**************************************************************
* Setea los items del arbol a partir de un string ID separado por un caracter ';'
* Ejemplo: ID1;ID2;ID3, .... Solo busca por el paren con ID
**************************************************************/
function SetSelectedItemsOnNode(nodes, itemsIDs) {
    try {
        var items = itemsIDs.split(";");
        var j;
        var i;
        for (j = 0; j < items.length; j++) 
        {
            for (i = 0; i < nodes.length; i++) {
                //Si se encuentra el Paren
                if (nodes[i].getTag() == items[j]) {
                    nodes[i].setChecked(true);
                    break;
                }
            }
        } 
    }
    catch (err) {
        window.status = "WebTree, SetSelectedItemsOnNode: " + err.description;
    }
}

/**************************************************************
* Obtiene un String con ID, Level separado por un caracter
* Ejemplo: ID,Level|
**************************************************************/
function GetSelectedItems(treeId)
{
    var Ids = "";
    try
    {
        var tree = igtree_getTreeById(treeId);
        if(tree != null)
        {
            var nodes = tree.getNodes();
            Ids = GetSelectedNodes(nodes);
        }
    }
    catch(err)
    {
        window.status = "WebTree, GetSelectedItems: " + err.description;
    }
    return Ids;
}

/**************************************************************
* Obtiene un String con ID separado por un caracter ';'
* Ejemplo: ID1;ID2;ID3, .... Solo busca por un Nivel especifico
**************************************************************/
function GetSelectedItemsOfLevel(treeId, level)
{
    var Ids = "";
    try
    {   
        var tree = igtree_getTreeById(treeId);
        if(tree != null)
        {
            var nodes = tree.getNodes();
            Ids = GetSelectedNodesOfLevel(nodes, level);
        }
    }
    catch(err)
    {
        window.status = "WebTree, GetSelectedItemsOfLevel: " + err.description;
    }
    return Ids;
}

/**************************************************************
* Obtiene un String con ID separado por un caracter ';'
* Ejemplo: ID
**************************************************************/
function GetSelectedNodesOfLevel(nodes, level)
{
    var Ids = "";
    try
    {
        var i;
        for(i=0; i<nodes.length; i++)
        {
            //Si esta en ese nivel
            if(nodes[i].getLevel() == level)
            {
                //y esta chequeado, lo incluye
                var checked = nodes[i].getChecked();
                if(checked == true)
                {
                    //Si esta chequeado, no mira los items Hijos
                    Ids += nodes[i].getTag() + ";";
                }            
            }
            else
            {
                //Mira al siguiente nivel
                var hasChildren = nodes[i].hasChildren();
                if(hasChildren == true)
                {
                    var childNodes =  nodes[i].getChildNodes();
                    if(childNodes.length > 0)
                    {
                        Ids += GetSelectedNodesOfLevel(childNodes, level);
                    }
                }
            }
        }
    }
    catch(err)
    {
        window.status = "GetSelectedNodesOfLevel: " + err.description;
    }
    return Ids;
}

/**************************************************************
* Obtiene un String con ID, Level separado por un caracter
* Ejemplo: ID,Level|
**************************************************************/
function GetSelectedNodes(nodes)
{
    var Ids = "";
    try
    {
        var i;
        for(i=0; i<nodes.length; i++)
        {
            var checked = nodes[i].getChecked();
            if(checked == true)
            {
                //Si esta chequeado, no mira los items Hijos
                Ids += nodes[i].getTag() + "," + nodes[i].getLevel() + "|";
            }
            else
            {
                //Si no esta chequeado el item Padre, mira los nodos hijos
                var hasChildren = nodes[i].hasChildren();
                if(hasChildren == true)
                {
                    var childNodes =  nodes[i].getChildNodes();
                    if(childNodes.length > 0)
                    {
                        Ids += GetSelectedNodes(childNodes);
                    }
                }
            }
        }
    }
    catch(err)
    {
        window.status = "WebTree, GetSelectedNodes: " + err.description;
    }
    return Ids;
}

/**************************************************************
* Convierte metros a millas
**************************************************************/
function MetersToMiles(meters) {
    var result = 0;
    try {
        var kilometers = (meters / 1000);
        result = kilometers * 0.621371192;
    }
    catch(err)
    {

    }
    return result;
}

/**************************************************************
* Redondea un numero
**************************************************************/
function RoundNumber(num, dec) 
{
    var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
    return result;
}

/*************************************************************
* Muestra la ventana modal
*************************************************************/
function ShowInfraPopup(clientID) {
    try {
        $find(clientID).set_windowState($IG.DialogWindowState.Normal);
        return false;
    }
    catch (err) 
    {
        alert("ShowInfraPopup: " + err.description);
    }
}

/*************************************************************
* Valida si esta abierta la ventana modal
*************************************************************/
function IsOpenedInfraPopup(clientID) {
    var result = false;
    try {
        if($find(clientID).get_windowState() != $IG.DialogWindowState.Hidden)
            result = true;
    }
    catch (err) {

    }
    return result;
}
