_ie = navigator.userAgent.indexOf("MSIE") > 0;
var eliminar        = false;
var filaActual      = null;
var tipoFilaActual  = null;
var espacio         = new Array();
var autoCompleteArray = new Array();

/** Permite confirmar una pregunta (theQuery) y en caso afirmativo,
    crea la variable get isConfirmed y redirecciona al programa
    destino (theLink) */
function confirmLink( theLink, theQuery ) {
    var isConfirmed = confirm( theQuery );
    if ( isConfirmed ) {
        theLink.href += '&isConfirmed=1';
    }
    return isConfirmed;
}

/** Llamada desde el programa opener o solicitante de datos */
function picker( campoDestino, programaDestino, espacio_actual ) {
    if ( buscar == null ||  buscar.location == null || buscar.close ) {
        var buscar = self.open( programaDestino,
                              'pick',
                              'alwaysRaised,width=450,height=400,scrollbars' );
    }
    if ( window.focus ) {
        buscar.focus();
    }
    self.actual = campoDestino;
    return false;
}

function pickerWithParameters( campoDestino, programaDestino ) {
    if ( buscar == null ||  buscar.location == null || buscar.close ) {
        var buscar = self.open( programaDestino,
                              'pick',
                              'alwaysRaised,width=450,height=400,scrollbars' );
    }
    if ( window.focus ) {
        buscar.focus();
    }
    self.actual = campoDestino;
    return false;
}

/** Selección de campo y actualización de datos del programa de origen */
function setPickerValue( idData, idDataShow, dataToUpdate, dataToShow ) {
    opener.document.getElementById( idData ).value = dataToUpdate;
    var e = opener.document.getElementById( idDataShow );
    while ( e.hasChildNodes() ) {
        e.removeChild( e.firstChild );
    }
    
        // Esta instrucción no es compatible con el IE6
        // etxt = document.createTextNode( dataToShow ); 
    etxt = opener.document.createTextNode( dataToShow );
    e.appendChild( etxt );
    opener.focus();
    window.close();
    return false;
}

function removePickerValue( idData, idDataShow ) {
    var eHidden = document.getElementById( idData );
    eHidden.value = '';
    var e = document.getElementById( idDataShow );
    while ( e.hasChildNodes() ) {
        e.removeChild( e.firstChild );
    }
    return false;
}

/** Selección en el programa destino o el que elige los datos */
function setvalue( codigo, texto ) {
    opener.document.getElementById( opener.actual ).options[0].text = texto;
    opener.document.getElementById( opener.actual ).options[0].value = codigo;
    opener.focus();
    window.close();
    return false;
}

/** Selección en el programa destino o el que elige los datos */
function setcomplexchoicevalue( codigo, texto ) {
    alert( codigo );
/*    
    alert( opener.document.getElementById( opener.actual ) );
    opener.document.getElementById( opener.actual ).options[0].value = codigo;
    opener.focus();
    window.close();*/
    return false;
}

/** Selección en el programa destino conociendo el id */
function setvalueid( codigo, texto, id ) {
    var control = opener.document.getElementById( id );
    var hiddden_control = opener.document.getElementById( id + '_hidden' );
    alert( control.id );
    alert( hidden_control.id );
    
    if ( control.options ) {
         control.options[0].text = texto;
         control.options[0].value = codigo;
    } else {
        if ( control.value ) {
            control.value = texto;
        } else {
            if ( control.innerHTML ) {
                control.innerHTML = texto;
            }
        }
    }
    if ( hiddden_control ) {
        hiddden_control.value = codigo;
    } else {
        if ( hiddden_control.value ) {
            hiddden_control.value = codigo;
        }
    }
    opener.focus();
    window.close();
    return false;
}

/** Selección de la lista de personas encontradas con datos similares */
function setvaluelist( codigo, texto ) {
    document.getElementById( "id_persona_picker" ).options[0].text = texto;
    document.getElementById( "id_persona_picker" ).options[0].value = codigo;
    return false;
}

function limpiarCombo( combo ) {
    for (var i=combo.options.length-1; i>=0; i--) {
        combo.options[i] = null;
    }
    combo.selectedIndex = -1;
}

/** Significado de los índices en cada espacio de trabajo
    0 Entrada de datos
    1 Controles a ser grabados
    2 Textos asociados a los controles
    3 Prefijo de los controles de la ventana
    4 Ventana asociada
    5 Número de controles
    6 Solicitud de borrar
    7 Fila actual
    8 Clase css de la fila actual
    9 Ventana popup
*/

function crear_espacio( espacio_actual, columnas, prefijo, nombre_ventana ) {
    espacio[espacio_actual] = new Array();

    espacio[espacio_actual][0] = new Array();
    espacio[espacio_actual][1] = new Array();
    espacio[espacio_actual][2] = new Array();
    espacio[espacio_actual][3] = prefijo;
    espacio[espacio_actual][4] = document.getElementById( nombre_ventana );
    espacio[espacio_actual][5] = columnas;
    espacio[espacio_actual][6] = false;
    espacio[espacio_actual][7] = null;

    for ( i = 0; i < columnas; i++ ) {
        nombre = prefijo + '_entrada_' + i;
        espacio[espacio_actual][0][i] = document.getElementById( nombre );
        espacio[espacio_actual][1][i] = '';
        espacio[espacio_actual][2][i] = '';
    }
    hideForm( espacio_actual );
}

function hideForm( index ) {
    espacio[index][4].style.visibility = 'hidden';
    espacio[index][4].style.display = 'none';
}

function select_combo( espacio_actual, id_fila_actual, fila, clase, error ) {
    if ( espacio[espacio_actual][6] ) {
        espacio[espacio_actual][6] = false;
        return false;
    }
    fila.className = clase + '_click';
    espacio[espacio_actual][7] = fila;
    espacio[espacio_actual][8] = clase;
    for ( i = 0; i < espacio[espacio_actual][5]; i++ ) {
        nombre_valor = espacio[espacio_actual][3] + '_valor_' + i + '_' + id_fila_actual;
        espacio[espacio_actual][1][i] = document.getElementById( nombre_valor );
        nombre_texto = espacio[espacio_actual][3] + '_texto_' + i + '_' + id_fila_actual;
        espacio[espacio_actual][2][i] = document.getElementById( nombre_texto );
        espacio[espacio_actual][0][i].setAttribute( "value", espacio[espacio_actual][1][i].value );
        if ( espacio[espacio_actual][0][i].className == 'pick' ) {
            espacio[espacio_actual][0][i].options[0].value = espacio[espacio_actual][1][i].value;
            espacio[espacio_actual][0][i].options[0].text = espacio[espacio_actual][2][i].innerHTML;
        }
    }
    espacio[espacio_actual][9] = window.open( '',
                                              'sac_popup_' + espacio_actual,
                                              'width=680,height=300'
                                              + ',menubar=0'
                                              + ',toolbar=0'
                                              + ',status=0'
                                              + ',scrollbars=1'
                                              + ',resizable=1' );
    ventana = espacio[espacio_actual][9].document;
    if ( error != null && error != '' ) {
        textoError = '<br /><span class="error">' + error + '</span>';
    } else {
        textoError = '';
    }
    ventana.write(
        '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
        + '<html><head><title>Sac Edit -  </title>'
        + '<link href="http://test.devenet.net/contabilidad/styles/style_tpl_area_de_trabajo.css" rel="stylesheet" type="text/css" />'
        + '</head>'
        + '<body onload="self.focus()">'
        + '<fieldset>'
        + espacio[espacio_actual][4].innerHTML
        + textoError
        + '</fieldset>'
        + '</body></html>'
        );
    ventana.close();
     if ( !_ie ) { 
         alert( 'Edición local de datos' ); 
     } 
    espacio[espacio_actual][9].focus();
     for ( i = 0; i < espacio[espacio_actual][5]; i++ ) { 
         if ( espacio[espacio_actual][0][i].className != 'picker' ) { 
             campo = ventana.getElementById( espacio[espacio_actual][3] + '_entrada_' + i ); 
             campo.value = espacio[espacio_actual][1][i].value; 
         } 
     } 
    return false;
}

function grabar_espacio( espacio_actual ) {
    for ( i = 0; i < espacio[espacio_actual][5]; i++ ) {
        nombre_popup = espacio[espacio_actual][3] + '_entrada_' + i;
        campo = espacio[espacio_actual][9].document.getElementById( nombre_popup );
        espacio[espacio_actual][1][i].value = campo.value;
        switch ( espacio[espacio_actual][0][i].className ) {
            case 'pick':
            case 'combo':
                if ( campo.selectedIndex >= 0 ) {
                    espacio[espacio_actual][2][i].innerHTML = campo.options[campo.selectedIndex].text;
                } else {
                    espacio[espacio_actual][2][i].innerHTML = '';
                }
                break;
            case 'text':
            case 'numeric':
                espacio[espacio_actual][2][i].innerHTML = campo.value;
                break;
        }
    }
    espacio[espacio_actual][7].className = espacio[espacio_actual][8];
    espacio[espacio_actual][9].close();
    return false;
}

function ignorar_espacio( espacio_actual ) {
    espacio[espacio_actual][9].close();
    espacio[espacio_actual][7].className = espacio[espacio_actual][8];
    return false;
}

function eliminarTransaccion( espacio_actual, id_fila_actual ) {
    espacio[espacio_actual][6] = true;
    if ( !confirm( 'Los datos de la fila serán eliminados. ¿Desea continuar con la eliminación?'  ) ) {
        return false;
    }
    for ( i = 0; i < espacio[espacio_actual][5]; i++ ) {
        nombre = espacio[espacio_actual][3] + '_valor_' + i + '_' + id_fila_actual;
        espacio[espacio_actual][1][i] = document.getElementById( nombre );
        nombre = espacio[espacio_actual][3] + '_texto_' + i + '_' + id_fila_actual;
        espacio[espacio_actual][2][i] = document.getElementById( nombre );
        espacio[espacio_actual][1][i].value = '';
        switch ( espacio[espacio_actual][0][i].className ) {
            case 'pick':
                espacio[espacio_actual][2][i].innerHTML = '---';
                break;
            case 'combo':
                espacio[espacio_actual][2][i].innerHTML = '---';
                break;
            case 'text':
                espacio[espacio_actual][2][i].innerHTML = '';
                break;
            case 'numeric':
                espacio[espacio_actual][2][i].innerHTML = 0;
                break;
        }
    } 
}

function autoComplete( input_box, field, id_value, id_text ) {
    var textBox = document.getElementById( id_text );
    var valueBox = document.getElementById( id_value );
    var entry = autoComplete[field][input_box.value];
    if ( textBox && valueBox ) {
        if ( input_box.value == '?' ) {
            input_box.value = '';
            popup = window.open( '', id_text, 'width=680,height=400'
                                 + ',menubar=0'
                                 + ',toolbar=0'
                                 + ',status=0'
                                 + ',scrollbars=1'
                                 + ',resizable=1' );
            popup.document.valueBox = input_box;
            popup.document.textBox = textBox;
            datos = autoComplete[field];
            popup.document.write(
              '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
              + '<html><head><title>Sac Edit -  </title>'
              + '<link href="http://test.devenet.net/contabilidad/styles/style_tpl_area_de_trabajo.css" rel="stylesheet" type="text/css" />'
              + '</head>'
              + '<body onload="self.focus()">'
              + '<fieldset>'
              + '<legend>Buscar</legend>'
            );
            for ( i in datos ) {
                 popup.document.write(
                    '\n<li><a href="javascript:opener.document.getElementById( \''
                    + input_box.id + '\' ).value=\'' + i 
                    + '\';opener.document.getElementById( \''
                    + id_value + '\' ).value=\'' + datos[i]['value'] 
                    + '\';opener.document.getElementById( \''
                    + id_text + '\' ).innerHTML=\'' + datos[i]['text']
                    + '\';close()" >'
                    + datos[i]['text'] + '</a></i>' );
            }
            popup.document.write( '</fieldset></body></html>' );
            popup.document.close();
        }
        if ( autoComplete[field] && autoComplete[field][input_box.value] ) {
            textBox.innerHTML = entry['text'];
            valueBox.value    = entry['value'];
        } else {
            textBox.innerHTML = '';
            valueBox.value    = 0;
        }
    }
}

function deleteMultipleEditable( prefijo, row, cols, rowId ) {
    if ( !confirm( 'Los datos de la fila serán eliminados. ¿Desea continuar con la eliminación?'  ) ) {
        return false;
    }
    rowEl = document.getElementById( rowId );
    tdsEl = rowEl.getElementsByTagName( 'td' );
    for ( i = 0; i < tdsEl.length - 1 ; i++ ) {
        tdsEl[i].style.textDecoration = 'line-through';
        tdsEl[i].style.color = 'red';
    }
    
    // rowEl.style.textDecoration = 'line-through';
    // rowEl.style.color = 'red';
    
    for ( i = 0; i < cols; i++ ) {
        var control = document.getElementById( prefijo + '_valor_' + i + '_' + row );
        if ( control && control.value ) {
            control.value = '';
        }
        if ( control && control.options) {
            var theEmptyOption = 0;
            var flagEmptyOption = false; 
            var newOption = new Option('Elegir', '');
            newOption.selected='selected';
            for ( j = 0; j < control.options.length; j++ ) {
                if ( control.options[j].value == 0
                     || control.options[j].value == '' ){
                    theEmptyOption = j;
                    flagEmptyOption = true; 
                }
            }
            if ( flagEmptyOption == true ) {  

               control.options[theEmptyOption].text = 'Elegir';
               control.options[theEmptyOption].value = '';
               control.options[theEmptyOption].selected = 'selected';

            } else{
               control.options[control.options.length] = newOption;
            }  

        }
        var control = document.getElementById( prefijo + '_texto_' + i + '_' + row );
        if ( control && control.innerHTML ) {
            control.innerHTML = '';
        }
        var control = document.getElementById( prefijo + '_caja_' + i + '_' + row );
        if ( control && control.value ) {
            control.value = '';
        }
    }
    var eliminar = document.getElementById( prefijo + '_delete_' + row );
    if ( eliminar && eliminar.value ) {
        eliminar.value = '1';
    }
    parentEl = eliminar.parentNode;
    while ( parentEl.hasChildNodes() ) {
        parentEl.removeChild( parentEl.firstChild );
    }
    span = document.createElement( 'span' );
    parentEl.style.backgroundColor = '#fffbe2';  
        
    span.style.color = 'red';    
    newEl = document.createTextNode( 'El registro será borrado al "Grabar cambios".' );
    span.appendChild( newEl );
    parentEl.appendChild( span );    
    return false;
}
function _ac( field, code, text, value ) {
    if ( !autoComplete[field] ) {
        autoComplete[field] = new Array;
    }
    if ( autoComplete[field][code] ) {
        return;
    }
    autoComplete[field][code] = new Array;
    autoComplete[field][code]['text']=text;
    autoComplete[field][code]['value']=value;
}

function setCommonListener( idValue, functionName ) {
    addEventById( idValue, "click", functionName );
    addEventById( idValue, "keypress", functionName );
    if (_ie) {
        addEventById( idValue, "dblclick", functionName );
    }
}

function addEventById( idValue, eventName, functionName ) {
    var element = document.getElementById( idValue );
    addEvent( element, eventName, functionName );
}

/*  Copyright Mihai Bazon, 2002-2005  |  www.bazon.net/mishoo */
function getElement(ev) {
	var f = _ie ? window.event.srcElement : ev.currentTarget;
	while (f.nodeType != 1 || /^div$/i.test(f.tagName))
		f = f.parentNode;
	return f;
};


/*  Copyright Mihai Bazon, 2002-2005  |  www.bazon.net/mishoo */
function addEvent(element, evname, func) {
	if (element.attachEvent) { // IE
		element.attachEvent("on" + evname, func);
	} else if (element.addEventListener) { // Gecko / W3C
		element.addEventListener(evname, func, true);
	} else {
		element["on" + evname] = func;
	}
};

function copy_clip(textToCopy, message) {
    if (window.clipboardData) {
        window.clipboardData.setData('Text', textToCopy);
    } else if (window.netscape) { 
            // This fails unless "signed.applets.codebase_principal_support" is true
        try { netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect'); }
        catch(e) { return false; }
        var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
        if (!str) return false;
        str.data = textToCopy;
        var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
        if (!trans) return false;
        trans.addDataFlavor("text/unicode");
        trans.setTransferData("text/unicode",str,textToCopy.length * 2);
        var clipid = Components.interfaces.nsIClipboard;
        var clip = Components.classes["@mozilla.org/widget/clipboard;1"].getService(clipid);
        if (!clip) return false;
        clip.setData(trans,null,clipid.kGlobalClipboard);
    }
    alert( message + ':\n\n' + textToCopy);
    return false;
}

var memClip = new Array();
function addCopyToMemClip( id, content ) {
    if ( memClip[id] == undefined ) {
        memClip[id] = content;
    } else {
        memClip[id] += content;
    }
}

/* Autocomplete */
function _( etiqueta, id ) {
    var element = new Array( etiqueta, id );
    return element;
}

function clearCombo( combo ) {
    for ( var i=combo.options.length-1; i>=0; i-- ) {
        combo.options[i] = null;
    }
    combo.selectedIndex = -1;
}

function populateChildAndParent( aParent, aChild, idParent, idChild, valor ) {
    populate( idParent, aParent );
    for ( var i = 0; i < aChild.length; i++ ) {
        for ( var j = 0; j < aChild[i].length; j++ ) {
            if ( aChild[i][j][1] == valor ) {
                var parent = window.document.getElementById( idParent );
                var child = window.document.getElementById( idChild );
                parent.selectedIndex = i;
                populate( idChild, aChild[i] );
                child.selectedIndex = j;
            }
        }
    }  
}

function populate( idHTML, arrayName ) {
    var control = window.document.getElementById( idHTML );
    clearCombo( control );
    for ( var i = 0; i < arrayName.length; i++ ) {
        control.options[control.options.length] = new Option(
            arrayName[i][0], arrayName[i][1] );
    }
}

function combo_js( parent, idChild, aChild ) {
    var current = parent.options[parent.selectedIndex].value;
    populate( idChild, aChild[current] );
}

