/*********************************************************
*
*  Copyright (C) 2001, AstroSoft Ltd. All Rights Reserved.
*  Description: Client-side library for A3VisualControls
*  AUTHOR(S):   Valentin Kolesov, Yury Belenky
*
*********************************************************/
var oldStyle;
var trimChars = new Array(9, 10, 11, 12, 13, 32, 133, 160, 5760, 8192, 8193, 8194, 8195, 8196, 8197, 8198, 8199,
			8200, 8201, 8202, 8203, 8232,8233, 12288, 65279);

if (getCookie("UseA3Alert") != null){
	if (getCookie("UseA3Alert").toLowerCase() == "true"){
		window.alert = function (msg) { A3alert(msg); }
        window.confirm = function (msg) { return A3confirm(msg); }
	}
}

function A3ReadOnly(readOnlyValue) {
	window.event.srcElement.selectedIndex = readOnlyValue;
}

function A3Focus(newStyle) {
  oldStyle = window.event.srcElement.className;
  window.event.srcElement.className = newStyle;
}
function A3Blur(mode) {

	var obj = window.event.srcElement;
	if (oldStyle!=undefined) obj.className = oldStyle;

	var prevCondition='';
	if (mode == true) prevCondition = LocalBlur();
    if (obj.controldescription != null)
    {
	    if (obj.value != '')
	    {
		    var oDesc = document.getElementById(obj.controldescription)
		    if (oDesc.AdvF4Id == null) CreateXMLDataIsland(obj,prevCondition);
		    else CreateF4XMLDataIsland(obj,window.self); //Call functions del AdvF4Int
	    }
	    else
	    {
		    var desc = document.getElementById(obj.controldescription);
		    desc.value = '';

		    if (desc.AdvF4Id != null)
		    {
    			var ctrlF4Adv = document.getElementById(desc.AdvF4Id);
	    		var ctrlguid= document.getElementById(ctrlF4Adv.guidID);
		    	ctrlguid.value='';
    		}
	    }
    }
}

function enableControl(objCtrl, enabled){
    if (objCtrl.className == "A3Enabled") { objCtrl.className = "A3Disabled"; }
    if (objCtrl.className == "A3Disabled") { objCtrl.className = "A3Enabled"; }

    objCtrl.setAttribute("disabled", !(enabled));
	for (var i = 0; i < objCtrl.children.length; i++){
	    var child = objCtrl.children[i];
    	if (objCtrl.className == "A3Enabled") { objCtrl.className = "A3Disabled"; }
	if (objCtrl.className == "A3Disabled") { objCtrl.className = "A3Enabled"; }
        child.setAttribute("disabled", !(enabled));
	    if (child.children.length > 0)
	        enableControl(child, enabled);
	}
}

function A3DescTxt()
{
	var oField = window.event.srcElement.field;	// provoques lost focus
	var oDescr = document.getElementById(window.event.srcElement.description);			// description

	if (window.event.srcElement.documentElement.text != 'False')
	{
		oDescr.value = window.event.srcElement.documentElement.text;
		if (window.onAfterXMLDescription) onAfterXMLDescription(oField);
	}
	else
	{
		oDescr.value = oDescr.defMessage;
	}
	PageProcess=false;
}

function ExpandMultiLine(txtCtrl){
	var strScript = "";
	var script1 = document.createElement("script");

	var txtCtrlHeight = txtCtrl.style.height;
        if (txtCtrlHeight == ""){ txtCtrlHeight = (txtCtrl.height != null) ? txtCtrl.height : txtCtrl.offsetHeight; }

    try{ eval("mltLHeights"); }
    catch (e){
        script1.text = "var mltLHeights = \"\"";
        document.body.previousSibling.appendChild(script1);
    }

    if (mltLHeights.indexOf(txtCtrl.id) == -1){
	mltLHeights += txtCtrl.id + "=" + txtCtrlHeight + "#@#";
    }

    if (txtCtrl.scrollTop == 0){ txtCtrlHeight = (parseFloat(txtCtrlHeight) + txtCtrl.scrollHeight).toString(); }
    else{ txtCtrlHeight = (parseFloat(txtCtrlHeight) + (txtCtrl.scrollHeight - txtCtrl.scrollTop)).toString(); }

    txtCtrl.style.height = (parseFloat(txtCtrlHeight) + txtCtrl.scrollTop + 15).toString();
}

function CollapseMultiLine(txtCtrl){
	if (mltLHeights != ""){
	    var strArr = mltLHeights.split("#@#");
	    for (var i = 0; i < strArr.length; i++){
	        if (strArr[i].indexOf(txtCtrl.id) != -1)
		        txtCtrl.style.height = strArr[i].split("=")[1];
			mltLHeights = mltLHeights.replace(strArr[i] + "#@#", "");
			break;
		}
		txtCtrl.scrollTop = 0;
	}
}

function AddCondition(condColumn,value,typeOf,formatDate,condition)
{
	if (condition == "")
	{
		if (formatDate == "") return condition + 'CondColumn=' + condColumn + '&Value=' + value + "&Tipo=" + typeOf;
		else return condition + 'CondColumn=' + condColumn + '&Value=' + value + "&Tipo=" + typeOf + '&formatDate=' + formatDate;
	}
	else
	{	var cDel = '@@@';
		var columns = condition.split("&")[0];
		var values = condition.split("&")[1];
		var typeOfData = condition.split("&")[2];
		var dateFormat = '';
		if (condition.split("&").length == 4)  dateFormat= condition.split("&")[3];

		if (dateFormat == "")
		{	if (formatDate == "") return columns + cDel + condColumn + '&' + values + cDel + value + '&' + typeOfData + cDel + typeOf;
			else return columns + cDel + condColumn + '&' + values + cDel + value + '&' + typeOfData + cDel + typeOf + '&formatDate=' + formatDate;
		}
		else
		{	if (formatDate == "") return columns + cDel + condColumn + '&' + values + cDel + value + '&' + typeOfData + cDel + typeOf + '&' + dateFormat;
			else return columns + cDel + condColumn + '&' + values + cDel + value + '&' + typeOfData + cDel + typeOf +  '&' + dateFormat + cDel + formatDate;
		}
	}
}

function CreateXMLDataIsland(obj,condition){
	PageProcess=true;
	var descr = document.getElementById(obj.controldescription);
	var oXML = document.createElement('XML');

	var value;
	var typeOfData;
	var formatDate = '';

	if (obj.number != null)
	{	value = obj.number;
		typeOfData = "NUM";
	}
	else
	{	if (obj.DateValue != null)
		{	value = obj.DateValue;
			typeOfData = "DATE";
			formatDate =obj.sourceFormat;
		}
		else
		{	value = obj.value;
			typeOfData = "STR";
		}
	}

	var strXML = '../A3SupportPages/A3DescText.aspx?DB=' + descr.DB + '&DBTable=' + descr.table + '&SelectCol=' + descr.sourcecolumn;

	//Añadir las propiedades para poder usar el securityparser en cliente al informar el código de un A3F4. MFP 13/04/2005
	if (descr.F4Security != 'undefined') strXML += '&F4Security=' + descr.F4Security;
	if (descr.F4Security){
		 strXML +=  '&F4SecID=' + descr.F4SecID + '&F4SecField=' + descr.F4SecField + '&F4SecType=' + descr.F4SecType;
	}
	//Añadir las propiedades para poder usar el securityparser en cliente al informar el código de un A3F4. MFP 13/04/2005

	var strCondition = AddCondition(descr.conditioncolumn,value,typeOfData,formatDate,condition);
	if (descr.ListID){ strCondition = AddCondition("ListID", descr.ListID, "NUM", "", strCondition); }
	oXML.src = strXML + '&' + strCondition;

	//oXML.id= obj.id + 'Desc';
	document.body.appendChild(oXML);
	descr.value = '';
	oXML.ondatasetcomplete = A3DescTxt;
	oXML.field = obj.id;
	oXML.description = descr.id;
	oXML.notFoundMessage = descr.defMessage;
}

function A3TxtKD() {
 if ((window.event.keyCode == 66) && (window.event.altKey == true)) OptClk(window.event.srcElement.id);
}

function validateControlKeys(ctrlID){
    var btnF4 = null;
    //ALT+Q
    if(window.event.altKey == true && (window.event.keyCode == 81 || window.event.keyCode == 113)){
        var btns = document.getElementsByTagName("button");
        for (var i = 0; i < btns.length; i++){
            if (btns[i].CodeFieldID == ctrlID.name){
                btnF4 = btns[i];
                break;
            }
        }
        if (btnF4 != null)
            btnF4.click();
    }
}

// ----------- NUMBER FUNCTIONS -----------------
var d,m,y,s1,s2,s3;

// Get thousand separator
function getThSeparator(){
var y,x;
    y=1234;
    x=y.toLocaleString();
    return x.substr(1,1);
}
function getLocaleDecSeparator(){
	var x,y;
	x=1.1;
	y=x.toLocaleString();
	return y.substr(1,1);
}

// Check number for correctness
function validateNumber(obj)
{
    var x,y,i,fract;

    // Determine and delete thousand separator
    x = obj.value;

    // Modificación para poder pulsar el signo negativo cuando no hay números. MFP 02/07/2004.
    //if (x.trim=='-') return 0;
    var xtemp = x.toString();
    while (xtemp.indexOf(' ') != -1) xtemp = xtemp.replace(' ','');
    if (xtemp == '-') return 0;
    // MFP 02/07/2004.

    while (x.indexOf(obj.thDelim) != -1) x = x.replace(obj.thDelim,'');
    x = x.replace(obj.decDelim,'.');

    y = obj.number;
    obj.number = Number(x);

    // If number is not valid then rollback
    if (isNaN(obj.number)) {
         obj.number = y;
         obj.value = renderNumber(obj);
         return 0;
    }

    x = x.replace('.',',')
    x = x.replace('-','')
    i = x.search(',');

    // If length of integer or fractional part exceeds limits - rollback
    if (i!=0 && i!=-1)
    {
      fract = x.length - i - 1;
      if ((fract>obj.fractLen) || (i>obj.intLen && x.substr(0,1) != '0'))
      {    obj.number = y;
           obj.value = renderNumber(obj);
           return 0;
      }
    }
	if (i == -1 && x.length > obj.intLen)
    {
      obj.number =y;
      obj.value = renderNumber(obj);
    }
}

function renderNumber(obj) {
	var intPart;
    var decPart = '';
	if (obj.value != '')
	{

//		if (obj.allowNegativeNum != "true" && obj.value != obj.number.toString()){
//			obj.number = parseFloat((obj.value.indexOf(",") != -1) ? obj.value.replace(",", ".") : obj.value);
//		}
		var strNum = obj.number.toString();

		var negative = false;
		if (strNum.charAt(0) == '-')
		{	negative = true;
			strNum = strNum.substr(1,strNum.length-1);
		}

		var indexDecSep = strNum.indexOf('.');

    	if (indexDecSep == -1) intPart = strNum;
    	else
    	{	intPart = strNum.substr(0,indexDecSep);
    		if (obj.fractLen != '0') decPart = strNum.substr(indexDecSep + 1,strNum.length -(indexDecSep + 1));
    	}

		if (obj.ThousandSeparators == 'true')
    	{	var i;
    		var j=0;
    		var result = '';
    		i = intPart.length-1;
    		while (i>=0)
    		{	result = intPart.charAt(i) + result;
    			i -= 1;
    			j += 1;
    			if (j % 3 == 0) result = obj.thDelim + result;
    		}
    		if (result.charAt(0) == obj.thDelim) result = result.substr(1,result.length);
    		if (negative == true) intPart = '-' + result;
    		else intPart = result;
    	}

		if (parseFloat(obj.fractLen)>= 0)
		{	if (obj.showDec == 'true')
			{
				while(decPart.length < parseFloat(obj.fractLen)) decPart = decPart + '0';
			}
			else
			{	if (decPart.length > 0)
				{
					while(decPart.charAt(decPart.length-1) == '0') decPart = decPart.substr(0,decPart.length-1);
				}
			}
		}

    	var strNumber;
		if (decPart == '') strNumber = intPart;
		else strNumber = intPart + obj.decDelim + decPart;

		if (obj.parseZeros == 'true')
		{
			while(strNumber.length < parseInt(obj.intLen)) strNumber = '0' + strNumber;
		}
		if (negative == true && strNumber.charAt(0) != "-")
		    obj.value = "-" + strNumber.toString();
		else
		    obj.value = strNumber;
		return strNumber;
	}
	else
	{
		//Cambio 7/10/2004
		if (obj.showDefVal == 'true')
		{
			var strNumber = "0";

            //INSERT AT 30/08/2007
    		if (parseFloat(obj.fractLen)>= 0){
    		    if (obj.showDec == 'true'){
			    	while(decPart.length < parseFloat(obj.fractLen)) decPart = decPart + '0';

			    	strNumber = strNumber + obj.decDelim + decPart;
			    }
			}else{
			    if (decPart.length > 0)
					while(decPart.charAt(decPart.length-1) == '0') decPart = decPart.substr(0,decPart.length-1);
			}
            //END INSERT
			if (obj.parseZeros == 'true')
			{
				while(strNumber.length < parseInt(obj.intLen)) strNumber = '0' + strNumber;
			}
			obj.value = strNumber;
			obj.number = strNumber;
		}
		else
			obj.value = '';
	}
}

// Only numeric keys and , . - allowed
function rejectInvalidKeys(obj)
{
	var c=window.event.keyCode;

    if ((c>47 && c<58) || (c==46) || (c==45) || (c==44))
    {
       //if (obj.thDelim.charCodeAt(0) == c) window.event.keyCode = '';
       if ((c==45) && (obj.allowNegativeNum != 'true')) window.event.keyCode='';
       if ((c==46) || (c==44)) window.event.keyCode=obj.decDelim.charCodeAt(0);
       if (((c==46) || (c==44)) && (obj.fractLen == '0')) {window.event.keyCode='';}
       return 0;
    }
    window.event.keyCode='';
}

//TRIM FUNCTION
//0 -> from left //1 -> from right //2 -> all
function trimJS(str, trimType){
	var startIndex = 0;
	var ch = "";
	var num = 0;

	if (trimType != 1){
        startIndex = 0;
	    while (startIndex < str.length){
	        var index = 0;
	        ch = str.substr(startIndex, 1);
	        while (index < trimChars.length){
	            if (trimChars[index] == ch.charCodeAt(0)){ break; }
	            index++;
	        }
	        if (index == trimChars.length){ break; }
	        startIndex++;
	    }
	}
	if (trimType != 0){
        num = str.length - 1;
        while (num >= startIndex){
            var numT = 0;
            ch = str.substr(num, 1);
            while (numT < trimChars.length){
                if (trimChars[numT] == ch.charCodeAt(0)){ break; }
                numT++;
            }
            if (numT == trimChars.length){ break; }
            num--;
        }
    }
    var length = (num - startIndex) + 1;
    if (length == str.length){ return str; }
    if (length == 0){ return ""; }
    return str.substr(startIndex, length);
}


// ----------- DATE FUNCTIONS -----------------
var d,m,y,s1,s2,s3;

// Return count of slashes in str
function countSlash(str) {
var c,pos;
  c=0;
  pos=0;
  while (str.indexOf('/',pos)!=-1) {
    pos=str.indexOf('/',pos)+1;
    c++;
  }
  return c;
}

// Convert date from sourceFormat into targetFormat
function convertDate(date,sourceFormat,targetFormat) {
   if (countSlash(date)==countSlash(targetFormat)) {
     if ((date.substr(0,1)!='/') && (date.substr(date.length-1,1)!='/'))  {
       parseDate(date,sourceFormat);
       return buildDate(targetFormat);
     }
   }
   return date;
}

// Create date string using targetFormat
function buildDate(targetFormat) {
  var tmp;

  tmp='';

  //Primer grupo de la fecha.
  switch (targetFormat.charAt(0)) {
    case 'd':
      if (d.length == 2)
        tmp = d + '/';
      else
        tmp = '0' + d + '/';

      break;
    case 'm':
      if (m.length == 2)
        tmp = m + '/';
      else
        tmp = '0' + m + '/';

      break;
    case 'y':
      tmp = y + '/';
  }

  //Segundo grupo de la fecha. Entre las barras
  if (countSlash(targetFormat) == 2) {
    switch (targetFormat.charAt(targetFormat.indexOf('/') + 1)) {
      case 'd':
        if (d.length == 2)
          tmp += d + '/';
        else
          tmp += '0' + d + '/';

        break;
      case 'm':
        if (m.length == 2)
          tmp += m + '/';
        else
          tmp += '0' + m + '/';

        break;
      case 'y':
        tmp += y + '/';
    }
  }

  //Tercer grupo de dígitos de la fecha.
  switch (targetFormat.charAt(targetFormat.length - 1)) {
    case 'd':
      if (d.length == 2)
        tmp += d;
      else
        tmp += '0' + d;

      break;
    case 'm':
      if (m.length == 2)
        tmp += m;
      else
        tmp += '0' + m;

      break;
    case 'y':
      tmp += y;
  }

  return tmp;
}

// Parse day,month,year from date using format
function parseDate(date,format){
  s1 = date.substr(0,date.indexOf('/')); // Part before the first slash
  s3 = date.substr(date.lastIndexOf('/')+1,date.length-date.lastIndexOf('/')-1);// Part after the last slash
  if (date.indexOf('/')!=date.lastIndexOf('/')) {
    s2=date.substr(date.indexOf('/')+1,date.lastIndexOf('/')-date.indexOf('/')-1);// Part between slashes (if present)
  } else {
    s2 = '';
  }

  if (s1 == '  ')
    s1 = 0;
  else
    while (s1.indexOf(' ') != -1) s1 = s1.replace(' ', '');

  if (s3 == '  ' || s3 == '    ')
    s3 = 0;
  else
    while (s3.indexOf(' ') != -1) s3 = s3.replace(' ', '');

  if (format.substr(0,1)=='d') d = s1;
  if (format.substr(0,1)=='m') m = s1;
  if (format.substr(0,1)=='y') y = s1;

  if (format.substr(format.length-1,1)=='d') d = s3;
  if (format.substr(format.length-1,1)=='m') m = s3;
  if (format.substr(format.length-1,1)=='y') y = s3;

  if (s2 != '') {
    if (s2 == '  ')
      s2 = 0;
    else
      while (s2.indexOf(' ') != -1) s2 = s2.replace(' ','');

    if (format.substr(format.indexOf('/')+1,1)=='d') d = s2;
    if (format.substr(format.indexOf('/')+1,1)=='m') m = s2;
    if (format.substr(format.indexOf('/')+1,1)=='y') y = s2;
  }
}

// Check date for correctness
function isDate(date,format) {
  // Construct Date object from d,m,y (month begins from 0!)
  // Then compare d,m,y with dateparts of date object. If they are equal - date is valid
  var dt;

  parseDate(date, format);

  if (d == null) d = '1';
  if (y == null) {
    var hoy = new Date();
    y = hoy.getFullYear();
  }

  if (d == '0' || m == '0' || y == '0') {
    return false;
  } else {
    try {
      var result = false;
      var calcm = eval(m - 1);

      // Componer el año con cuatro dígitos.
      if (y.length != 4) {
        if (eval(y) < 30)
          y = String(eval(2000) + eval(y));
        else
          y = String(eval(1900) + eval(y));
      }

      dt = new Date(y, calcm, d);         //Create Date object.

      if (dt.getMonth() != calcm || dt.getDate() != eval(d)) {
        result = false;
      } else {
        result = (dt.getFullYear() == y && y > 1752);
      }
    } catch (e) {}

    return result;
  }
}

function isValidDate(date,formatDate) {
  var i;
  // If date is completely entered we can validate
  // Slashes are not at the edges of string
  if ((date.substr(0,1)!='/') && (date.substr(date.length-1,1)!='/'))  {
    // Slashes count in date = Slashes count in format string
    if (countSlash(date)==countSlash(formatDate)) {
      if ((formatDate!='dd/mm/yyyy') && (formatDate!='mm/yyyy')) {
        // If date is valid (e.g. not 31 Feb)
        i=date.length-date.lastIndexOf('/')-1;
        if (i>2) return 0;
        if (isDate(date,formatDate))
           return 1; // Date is valid
        else
           return 0; // Date is not valid
      }
      // Four digit year completely entered
      i=date.length-date.lastIndexOf('/')-1;
      if (((formatDate=='dd/mm/yyyy') || (formatDate=='mm/yyyy')) && (i>=4)) {
        if (i>4) return 0;
        // If date is valid (e.g. not 31 Feb)
        if (isDate(date,formatDate))
           return 1;
        else
           return 0;
      }
    }
  }
  return 2; // Date is not completely entered
}

function validateDate(obj){
	var oldDate, res,i;
	var DateObt;
	var CadTemp = obj.value;

	// Comprobar si no tiene datos. MFP 23/06/2004.
	while (CadTemp.indexOf('/') != -1) CadTemp = CadTemp.replace('/','');
	while (CadTemp.indexOf(' ') != -1) CadTemp = CadTemp.replace(' ','');
	//if (obj.value=='') return true;
	if (CadTemp == '') return true;

	oldDate = obj.DateValue;

    // Hacer una sola llamada a convertDate. MFP 22/06/2004.
    DateObt = convertDate(obj.value, obj.clientFormat, obj.formatDate);

	res=isValidDate(DateObt, obj.formatDate);

    i=obj.value.length-obj.value.lastIndexOf('/')-1;
    if ((obj.formatDate=='dd/mm/yyyy') || (obj.formatDate=='mm/yyyy')) {
      if (i>4) res=0;
    } else {
      if (i>2) res=0;
    }

	// If date is valid - update obj.DateValue
    if (res==1) {
       // Hacer una sola llamada a convertDate. MFP 22/06/2004.
       //obj.DateValue=convertDate(obj.value,obj.clientFormat,obj.formatDate);
       obj.DateValue = DateObt;

       if (obj.clientFormat!= obj.formatDate)
         obj.value=parseClientFormat(obj.clientFormat);
       else
         obj.value=obj.DateValue;

       return true;
    }
    if (res == 2)
    {
		alert(obj.ErrorMessage + ' (' + obj.ErrClientFormat + ')');
		event.returnValue = false;
	}
	if (res == 0)
	{
		alert(obj.errMsgDate);
		event.returnValue = false;
	}
    /*if (obj.errMsgDate == null) {
		alert(obj.ErrorMessage + ' (' + obj.ErrClientFormat + ')');
		event.returnValue = false;
	} else {
		alert(obj.ErrorMessage + ' (' + obj.errMsgDate + ')');
		event.returnValue = false;
	}*/

	obj.focus();
    obj.DateValue = oldDate;
    return false;
}

function parseClientFormat(clientFormat) {
	var auxClientDate='';
	var arrClientFormat=clientFormat.split('/');
	var i;

	for (i=0;i<arrClientFormat.length;i++)
	{
		if (arrClientFormat[i].substr(0,1)=='d')
		{
			if (auxClientDate == '')
			  auxClientDate=auxClientDate + d;
			else
			  auxClientDate=auxClientDate + '/'+ d;
		}

		if (arrClientFormat[i].substr(0,1)=='m')
		{
			if (auxClientDate == '')
			  auxClientDate=auxClientDate + m;
			else
			  auxClientDate=auxClientDate + '/'+ m;
		}

		if (arrClientFormat[i].substr(0,1)=='y') {
			if (auxClientDate == '')
			{
				auxClientDate=auxClientDate + y;
			}
			else
			{
				auxClientDate=auxClientDate + '/'+ y;
			}
		}
	}//end for

	return auxClientDate;
}//end function


// Only numeric keys and / allowed
function rejectInvalidKeysDate() {
var c;
  c=window.event.keyCode;

  if ((c>47 && c<58) || (c==47)) {
    return 0;
  }
  window.event.keyCode='';
}

// MFP. Inclusión de máscaras en INPUTDATE. 21/06/2004. *******************************************

// Función que sólo acepta las teclas válidas para el control A3InputDate.
// Las teclas permitidas son: TAB, backspace, números con teclado alfanumérico,
// números con teclado numérico, cursores izquierda y derecha, tecla inicio, tecla fin y
// barra espaciadora.
function ParseTeclaDate(oFecha) {
  var CodChar = event.keyCode;
  var Seleccion = document.selection.createRange();
  var ValorFecha = oFecha.value;
  var PosCur = 0;

  // Teclas TAB, cursor izquierda, cursor derecha, tecla fin o tecla inicio.
  if (CodChar == 9 || CodChar == 37 || CodChar == 39 || CodChar == 35 || CodChar == 36) return true;

  // Tecla backspace.
  if (CodChar == 8) {
    if (Seleccion.text.length > 0) {
      // Eliminar los dígitos pero dejar los caracteres de máscara en la selección.
      var CadTemp = '';
      for (var cont = 0; cont < Seleccion.text.length; cont++) {
        var Car = Seleccion.text.charAt(cont);
        if (Car != '/') Car = ' ';
        CadTemp += Car;
      }

      //Modificación para que no se lance dos veces el evento onChange. MFP 19/01/2005.
      //Seleccion.text = CadTemp;
      //Seleccion.move('character', -1 * CadTemp.length);
      //Obtener la posición del cursor.
      while (Seleccion.move('character', -1)) PosCur++;

      //Modificar el texto seleccionado con la máscara creada.
      if (PosCur > 0) {
		//En medio de la cadena.
        oFecha.value = ValorFecha.substring(0, PosCur) + CadTemp + ValorFecha.substring(PosCur + CadTemp.length, ValorFecha.length);

        if (ValorFecha.charAt(PosCur) == '/')
			Seleccion.move('character', PosCur + 1); //Si la posición inicial es carácter de máscara, poner cursor en la siguiente.
		else
			Seleccion.move('character', PosCur);
      } else {
        //En el inicio de la cadena.
        oFecha.value = CadTemp + ValorFecha.substring(CadTemp.length, ValorFecha.length);
        Seleccion.collapse();
      }
      //Modificación para que no se lance dos veces el evento onChange. MFP 19/01/2005.
    } else {
      // Obtener la posición del cursor.
      while (Seleccion.move('character', -1)) PosCur++;

      if (PosCur > 0) {
        // Borrar un dígito.
        if (ValorFecha.charAt(PosCur - 1) == '/') {
          // Saltar carácter de máscara.
          oFecha.value = ValorFecha.substring(0, PosCur - 2) + ' ' + ValorFecha.substring(PosCur - 1 , ValorFecha.length);
          Seleccion.move('character', PosCur - 2);
        } else {
          oFecha.value = ValorFecha.substr(0, PosCur - 1) + ' ' + ValorFecha.substring(PosCur , ValorFecha.length);

          // Si el carácter anterior es de máscara, saltarlo.
          if (oFecha.value.charAt(PosCur - 2) != '/')
            Seleccion.move('character', PosCur - 1);
          else
            Seleccion.move('character', PosCur - 2);
        }
      }
    }

    Seleccion.select();
  }

  // Tecla suprimir.
  if (CodChar == 46) {
    if (Seleccion.text.length > 0) {
      // Eliminar los dígitos pero dejar los caracteres de máscara en la selección.
      var CadTemp = '';
      for (var cont = 0; cont < Seleccion.text.length; cont++) {
        var Car = Seleccion.text.charAt(cont);
        if (Car != '/') Car = ' ';
        CadTemp += Car;
      }

      //Modificación para que no se lance dos veces el evento onChange. MFP 19/01/2005.
      //Seleccion.text = CadTemp;
      //if (CadTemp.substr(0, 1) == '/')
      //  Seleccion.move('character', -1 * (CadTemp.length - 1));
      //else
      //  Seleccion.move('character', -1 * CadTemp.length);
      //Obtener la posición del cursor.
      while (Seleccion.move('character', -1)) PosCur++;

      //Modificar el texto seleccionado con la máscara creada.
      if (PosCur > 0) {
        //En medio de la cadena.
        oFecha.value = ValorFecha.substring(0, PosCur) + CadTemp + ValorFecha.substring(PosCur + CadTemp.length, ValorFecha.length);

        if (ValorFecha.charAt(PosCur) == '/')
		  Seleccion.move('character', PosCur + 1); //Saltar carácter de máscara.
        else
          Seleccion.move('character', PosCur); //Cursor en el inicio de la selección.
      } else {
        //Inicio de la cadena.
        oFecha.value = CadTemp + ValorFecha.substring(CadTemp.length, ValorFecha.length);
        Seleccion.collapse();
      }
      //Modificación para que no se lance dos veces el evento onChange. MFP 19/01/2005.
    } else {
      // Obtener la posición del cursor.
      while (Seleccion.move('character', -1)) PosCur++;

      if (PosCur < ValorFecha.length) {
        // Borrar un dígito.
        if (ValorFecha.charAt(PosCur) == '/') {
          // Saltar carácter de máscara.
          oFecha.value = ValorFecha.substring(0, PosCur + 1) + ' ' + ValorFecha.substring(PosCur + 2, ValorFecha.length);
          Seleccion.move('character', PosCur + 1);
        } else {
          oFecha.value = ValorFecha.substring(0, PosCur) + ' ' + ValorFecha.substring(PosCur + 1, ValorFecha.length);
          Seleccion.move('character', PosCur);
        }
      } else
		Seleccion.move('character', PosCur);
    }

    Seleccion.select();
  }

  // Pulsado un dígito numérico.
  if (((CodChar > 47 && CodChar < 58) || (CodChar > 95 && CodChar < 106) || CodChar == 32) && event.altKey == false && event.ctrlKey == false && event.shiftKey == false) {
    if (CodChar > 57) CodChar -= 48; //Pulsada tecla del teclado numérico.
    var CharKeyed = String.fromCharCode(CodChar);

    if (Seleccion.text.length > 0) {
      // Si el primer carácter es de máscara, se debe eliminar de la selección.
      if (Seleccion.text.charAt(0) == '/') Seleccion.moveStart('character');

      // Eliminar los dígitos pero dejar los caracteres de máscara en la selección.
      var CadTemp = CharKeyed;
      for (var cont = 1; cont < Seleccion.text.length; cont++) {
        var Car = Seleccion.text.charAt(cont);
        if (Car != '/') Car = ' ';
        CadTemp += Car;
      }

      Seleccion.text = CadTemp;
      Seleccion.move('character', -1 * (CadTemp.length - 1));
    } else {
      // Obtener la posición del cursor.
      while (Seleccion.move('character', -1)) PosCur++;

      if (PosCur < ValorFecha.length) {
        // Insertar el dígito introducido.
        if (ValorFecha.charAt(PosCur) == '/') {
          // Saltar carácter de máscara.
          oFecha.value = ValorFecha.substring(0, PosCur + 1) + CharKeyed + ValorFecha.substring(PosCur + 2, ValorFecha.length);
          Seleccion.move('character', PosCur + 2);
        } else {
          oFecha.value = ValorFecha.substring(0, PosCur) + CharKeyed + ValorFecha.substring(PosCur + 1, ValorFecha.length);

          // Si el siguiente carácter es de máscara, saltarlo.
          if (oFecha.value.charAt(PosCur + 1) != '/')
            Seleccion.move('character', PosCur + 1);
          else
            Seleccion.move('character', PosCur + 2);
        }
      }
    }

    Seleccion.select();
  }

  // Tecla "/" del teclado y tecla / del teclado numérico.
  if ((event.shiftKey && CodChar == 55) || CodChar == 111) {
    // Obtener la posición del cursor.
    while (Seleccion.move('character', -1)) PosCur++;
    if (PosCur > 0) Seleccion.move('character', PosCur);

    // Buscar la primera aparición de un carácter de máscara.
    var PosMascara;
    PosMascara = ValorFecha.substring(PosCur + 1, ValorFecha.length).indexOf('/');
    if (PosMascara > -1) {
      // Desplazar el cursor a la siguiente posición del carácter de máscara.
      PosMascara += PosCur + 1;
      Seleccion.move('character', PosMascara - PosCur + 1);
      Seleccion.select();
    }
  }

  // Cancelar el evento de tecla pulsada.
  event.cancel = true;
  return false;
}

// Si el control está vacío al obtener el foco, se muestra la máscara si no hay ningún valor.
// Si hay algún dato, se debe formatear adecuadamente.
function GFInputDate(oFecha) {
  var rango = document.selection.createRange();

  if (oFecha.value == '') {
    // El campo está vacío, se muestra la máscara.
    switch (oFecha.clientFormat) {
      case 'dd/mm/yyyy':
        oFecha.value = '  /  /    ';
        break;
      case 'dd/mm/yy':
        oFecha.value = '  /  /  ';
        break;
      case 'dd/mm':
        oFecha.value = '  /  ';
        break;
      case 'mm/yyyy':
        oFecha.value = '  /    ';
        break;
      case 'mm/yy':
        oFecha.value = '  /  ';
    }

    // Mover el cursor a la primera posición del control.
    rango.collapse();
    rango.select();
  } else {
    // Si hay un valor en el control, formatearlo como una fecha para evitar que hayan menos
    // dígitos que los necesarios.
    var valor = oFecha.value;
    var PonerMascara = false;
    var CadTemp;
    var valornuevo = '';

    if ((valor.charAt(0)!= '/') && (valor.charAt(valor.length - 1)!= '/')) {
      if (countSlash(valor) == countSlash(oFecha.clientFormat)) {
        // Formatear el día.
        CadTemp = valor.substr(0, valor.indexOf('/'));
        if (CadTemp == '')
          valornuevo += '  ';
        else {
          if (CadTemp.length < 2)
            valornuevo += '0' + CadTemp;
          else
            valornuevo += CadTemp;
        }

        // Formatear el mes en caso de que esté en la parte central.
        if (valor.indexOf('/') != valor.lastIndexOf('/')) {
          CadTemp = valor.substr(valor.indexOf('/') + 1, valor.lastIndexOf('/')- valor.indexOf('/') - 1)
          if (CadTemp == '')
            valornuevo += '/' + '  ';
          else {
            if (CadTemp.length < 2)
              valornuevo += '/0' + CadTemp;
            else
              valornuevo += '/' + CadTemp;
          }
        }

        // Formatear el mes o el año, situado en la parte final.
        var longitud = oFecha.clientFormat.substr(oFecha.clientFormat.lastIndexOf('/') + 1, oFecha.clientFormat.length - 1 - oFecha.clientFormat.lastIndexOf('/')).length;
        CadTemp = valor.substr(valor.lastIndexOf('/') + 1, valor.length - 1 - valor.lastIndexOf('/'));
        if (CadTemp == '')
          if (longitud == 2)
            valornuevo += '/' + '  ';
          else
            valornuevo += '/' + '    ';
        else {
          // El final de la fecha es un mes.
          if (oFecha.clientFormat.charAt(oFecha.clientFormat.length - 1) == 'm') {
            if (CadTemp.length < 2)
              valornuevo += '/0' + CadTemp;
            else
              valornuevo += '/' + CadTemp;
          } else {
            // El final de la fecha es un año.
            if (CadTemp.length < longitud) {
              var fecha = new Date();

              if (longitud == 2)
                valornuevo += '/' + String(fecha.getFullYear()).substr(2); //Asignar el año actual.
              else
                valornuevo += '/' + fecha.getFullYear(); //Asignar el año actual.
            } else
              valornuevo += '/' + CadTemp;
          }
        }

        // Comprobar si ha habido modificación.
        if (oFecha.value != valornuevo) {
          oFecha.value = valornuevo;

          // Mover el cursor a la primera posición del control.
          rango.collapse();
          rango.select();
        }
      } else {
        PonerMascara = true;
      }
    } else {
      PonerMascara = true;
    }

    if (PonerMascara) {
	  switch (oFecha.clientFormat) {
	    case 'dd/mm/yyyy':
		  oFecha.value = '  /  /    ';
		  break;
	    case 'dd/mm/yy':
		  oFecha.value = '  /  /  ';
		  break;
	    case 'dd/mm':
		  oFecha.value = '  /  ';
		  break;
	    case 'mm/yyyy':
		  oFecha.value = '  /    ';
		  break;
	    case 'mm/yy':
		  oFecha.value = '  /  ';
	  }

      // Mover el cursor a la primera posición del control.
      rango.collapse();
      rango.select();
    }
  }

  oFecha.oldvalue = oFecha.value //Guardar el valor del control al tomar el foco. MFP 19/01/2004.
}

// Si el control está vacío al perder el foco, se borra la máscara.
function LFInputDate(oFecha) {
  var valor = oFecha.value;

  // Eliminar los caracteres de máscara y los blancos.
  while (valor.indexOf('/') != -1) valor = valor.replace('/','');
  while (valor.indexOf(' ') != -1) valor = valor.replace(' ','');

  if (valor == '')
    // Si no hay números, quitar la máscara.
	oFecha.value = valor;
  else {
    // Si hay números, formatearlos según el formato de dígitos esperado.
    var formato = oFecha.clientFormat;
    var IndFormato;
    var IndValor;
    var FechaTemp = '';

    valor = oFecha.value.replace(/\s+$/g,'');
    while (valor.indexOf('/') != -1) valor = valor.replace('/','');

    IndFormato = formato.length - 1;
    IndValor = valor.length - 1;

    while (IndValor > -1) {
      if (formato.substr(IndFormato, 1) != '/'){
        FechaTemp = valor.substr(IndValor, 1) + FechaTemp;
        IndValor--;
      } else
        FechaTemp = '/' + FechaTemp;

      IndFormato--;
    }

    oFecha.value = FechaTemp;
  }
}

// Función para el onBlur del A3InputDate. MFP 20/01/2005.
function BlurA3InputDate(oControl){
  if (oControl.oldvalue != oControl.value) {
    oControl.DateValue = oControl.value
    oControl.onchange();
  } else {
    LFInputDate(oControl);
    return validateDate(oControl);
  }
}

// Función para el onChange del A3InputDate. MFP 20/01/2005.
function ChangeA3InputDate(oControl){
  LFInputDate(oControl);
  return validateDate(oControl);
}
// MFP. Inclusión de máscaras en INPUTDATE. 21/06/2004. *******************************************


// ----------- END DATE FUNCTIONS -----------------------



// ----------- A3AutManButton FUNCTIONS -----------------

function A3AutManClick(obj)
{
	var img = obj.all(0);

	var buttonEnabled = false;
	if (obj.getAttribute("disabled") != null) buttonEnabled = true;
	var pathImg = obj.getAttribute("pathImage");
	switch(obj.state)
	{
		case "manual":
			document.all("h"+obj.id).value = 0;
			obj.state = "automatic";
			if (buttonEnabled == true) img.src = pathImg + obj.getAttribute("automaticimage");
			else img.src =  pathImg + obj.getAttribute("automaticimagedisabled");
			break;
		case "automatic":
			if (obj.getAttribute("type") == 'autman')
			{
				document.all("h"+obj.id).value = 2;
				obj.state = "manual";
				if (buttonEnabled == true) img.src =  pathImg + obj.getAttribute("manualimage");
				else img.src =  pathImg + obj.getAttribute("manualimagedisabled");
			}
			else
			{
				document.all("h"+obj.id).value = 1;
				obj.state = "semi";
				if (buttonEnabled == true) img.src =  pathImg + obj.getAttribute("semiautomaticimage");
				else img.src =  pathImg + obj.getAttribute("semiautomaticimagedisabled");
			}
			break;
		case "semi":
			document.all("h"+obj.id).value = 2;
			obj.state = "manual";
			if (buttonEnabled == true) img.src =  pathImg + obj.getAttribute("manualimage");
			else img.src =  pathImg + obj.getAttribute("manualimagedisabled");
			break;
	}

}

function A3AutoManSetState(ID, State, Status){
	obj = document.all(ID);
	obj.state = State;
	if (Status.toLowerCase == "disable")
	obj.disabled = "Disabled"
}


// VALIDATORS

var serverValue = new Boolean;

function getFormatDate(obj)
{	return(document.getElementById(obj).formatDate);}

function getFormatClient(obj)
{	return(document.getElementById(obj).clientFormat);}

function getThousandSeparator(obj)
{	return(document.getElementById(obj).thDelim);}

function getDecSeparator(obj)
{	return(document.getElementById(obj).decDelim);}

function getNumber(obj)
{	return(document.getElementById(obj).number);}

function StringToDate(value, srvFormat)
{
	var fecha = new Date();
	parseDate(value,srvFormat);

	//Se usaba el año sin comprobar si el formato de la fecha realmente lo contiene. MFP 26/07/2004.
	if (y != null) {
	  if (y.length < 4) {
	    if (eval(y) < 30 )
	      y = String(eval(2000) + eval(y));
	    else
	      y = String(eval(1900) + eval(y));
	  }

	  fecha.setFullYear(y);
	}
	//MFP 26/07/2004.

	fecha.setMonth(m-1);

	//Se usaba el día sin comprobar si el formato de la fecha realmente lo contiene. MFP 26/07/2004.
	if (d != null) fecha.setDate(d);
	//MFP 26/07/2004.

	fecha.setHours(0,0,0,0);
	return(fecha);
}

function A3RequiredFieldValidatorEvaluateIsValid(val) {
    var value = ValidatorGetValue(val.controltovalidate);
    if (ValidatorTrim(value).length == 0) return false;
    return true;
}

function A3RangeValidatorEvaluateIsValid(val)
{
	var value = ValidatorGetValue(val.controltovalidate);
    if (ValidatorTrim(value).length == 0) return true;

    serverValue = true;

    return (ValidationCompare(value, val.minimvalue, "GreaterThanEqual", val) &&
            ValidationCompare(value, val.maximvalue, "LessThanEqual", val));
}

function A3CompareValidatorEvaluateIsValid(val)
{
	var value = ValidatorGetValue(val.controltovalidate);
    if (ValidatorTrim(value).length == 0) return true;
    var compareTo = "";
    var compareTo1 = "";

    srvCliDif = SrvCliLanguageDif(val.controltovalidate)

    if (null == document.all[val.controltocompare]) {
        if (typeof(val.valuetocompare) == "string") {
            serverValue = true;
            compareTo = val.valuetocompare;}
    }
    else {
        serverValue = false;
        compareTo = ValidatorGetValue(val.controltocompare);
    }

    return ValidationCompare(value, compareTo, val.operator, val);
}

function convertClientValue(op,dataType,val)
{
	if (dataType == "Date")
	{	var srvFormat = getFormatDate(val.controltovalidate);
		var cliFormat = getFormatClient(val.controltovalidate);
		if (srvFormat != cliFormat) op = convertDate(op,srvFormat,cliFormat);
		return StringToDate(op,srvFormat);
	}
	else if(dataType == "Integer")
	{	var thDelim = getThousandSeparator(val.controltovalidate);
		return(Number(op.replace(thDelim,'')));
	}
	else if(dataType == "Double")
	{
		var thDelim = getThousandSeparator(val.controltovalidate);
		var decDelim = getDecSeparator(val.controltovalidate);

		if (thDelim == '.')
		{	op = op.replace('.','');
			op = op.replace(',','.');}

		if (thDelim == ',') op = op.replace(',','');
		return parseFloat(op);
	}
	else if(dataType == "String")
	{
		return op.toString();
	}
}

function convertDataType(op,dataType,val,serverValue)
{
	if (dataType == "Date")
	{	var srvFormat = getFormatDate(val.controltovalidate);
		var cliFormat = getFormatClient(val.controltovalidate);

		if (serverValue == false)
		{
			if (srvFormat != cliFormat) op = convertDate(op,srvFormat,cliFormat);
		}

		return StringToDate(op,srvFormat);
	}

	if (dataType == "Integer")
	{
		var thDelim = getThousandSeparator(val.controltovalidate);
		return(Number(op.replace(thDelim,'')));

	}
	if (dataType == "Double")
	{
			var thDelim = getThousandSeparator(val.controltovalidate);
			var decDelim = getDecSeparator(val.controltovalidate);

			/* Para realizar correctamente las comparaciones: 15.000,02 -> 15000.02 */
			/* En español -> a inglés */

			if (serverValue == false)	{
				if (thDelim == '.')	{
					op = op.replace('.','');
					op = op.replace(',','.');
				}

				if (thDelim == ',') op = op.replace(',','');
			}

			/*if (thDelim == ',') op = op.replace(',','.');*/
			return parseFloat(op);

	}
	if (dataType == "String")
	{
		return op.toString();
	}
}


function ValidationCompare(operand1, operand2, operator, val)
{
	var dataType = val.type;
    var op1, op2;


    if ((op1 = convertClientValue(operand1, dataType, val)) == null) return false;
    if (operator == "DataTypeCheck") return true;
    if ((op2 = convertDataType(operand2, dataType, val, serverValue)) == null) return true;

    switch (operator) {
        case "NotEqual":
	      return (op1 != op2);
        case "GreaterThan":
	    return (op1 > op2);
        case "GreaterThanEqual":
            return (op1 >= op2);
        case "LessThan":
	    return (op1 < op2);
        case "LessThanEqual":
	    return (op1 <= op2);
        default:
	    return (op1 == op2);
    }
}

function SrvCliLanguageDif(val){
	var srvDate = getFormatDate(val);
	var cliDate = getFormatClient(val);
	var thSeparator = getThousandSeparator(val);
	var decSeparator = getDecSeparator(val);
	if (decSeparator == ',') return false;
	return true;
}

function A3InputsPaste(obj, maxLength)
{
    //se dispone a false el returnValue del obj. event para permitir que si se hace boton derecho
    //aparezca el menu emergente de copia, pegar...
	event.returnValue = false;
	var textToPaste = window.clipboardData.getData("Text");
	if (textToPaste.length > maxLength){
	    if (obj.value.length == 0)
	        obj.value = textToPaste.substring(0, maxLength - 1);
	    else
	        obj.value +=  textToPaste.substring(0, maxLength - obj.value.length);
	}
	else{
	    if (obj.value.length == 0)
	        obj.value = textToPaste;
	    else
		    obj.value += textToPaste.substring(0, maxLength - obj.value.length);
	}
}

function A3MaxString(obj, Maxlength)
{
	if(obj.value.length > Maxlength - 1)
	{
		obj.value = obj.value.substring(0, Maxlength);
		return false;
	}
}
function DisplayZerosAtBeginning(me,Maxlength)
{
	if (me.value!="" && isNaN(me.value)==false)
	{
		while (me.value.length<Maxlength)
		{
			me.value = 0 + me.value;
		}
	}
}


/**************************************************************************************************
Funciones Para la A3Combo

***************************************************************************************************/
//var inputText;
//var combo;
var PopUpCombo = null;

function Options(ComboId,TableId,InputTextId,Width,MaxOptions)
{
	var inputText=document.getElementById(InputTextId);
	var combo=document.getElementById(ComboId);
	CheckEventCombo("onclick",combo);
	if(inputText.readOnlyValue=='false')
	{
		if (PopUpCombo==null)
		{
			ComboBlur(inputText);

			if (combo.all.length > 0)
			{
				PopUpComboF(combo,TableId,Width,MaxOptions,inputText);
			}
		}
		else
		{
			PopUpCombo.hide();
			InputFocus(inputText.id);
			PopUpCombo=null;
		}
	}
}

function PopUpComboF(combo,TableId,Width,MaxOptions,inputText)
{
	var Height=0;
	var iWidth;
	var y;
	var x=0;
	PopUpCombo = window.createPopup();
	var oPopBody = PopUpCombo.document.body;
	var Table = document.createElement("TABLE");
	var TableC = document.getElementById(TableId);
	y=TableC.offsetHeight;
	iWidth=TableC.offsetWidth;

	StylePopUp(Table);
	Table.CellSpacing = 0;
    Table.CellPadding = 0;
	Table.Width="100%"
	var i;
	var Text;
	var value;
	var objFocus;
	for (i=0; i <combo.all.length; i++)
	{
		Text = combo.options(i).text;
		value = combo.options(i).value;
		var NewW = CalculateWidth(Text);
		if (Width == 0)
		{
			if (NewW > iWidth)
			{
				iWidth = NewW;
			}
		}
		if (i<MaxOptions)
		{
			Height += 14;
		}
		Table.appendChild(TableRow(Text,value,i,combo.selectedIndex,inputText,combo));
		objFocus=combo.selectedIndex;
	}
	if (Width != 0)
	{
		iWidth = Width;
	}
	if (i>MaxOptions)
	{
		iWidth += 19;
	}

	var script1=oPopBody.document.createElement("script");
	script1.text = PrintScript(objFocus);
	oPopBody.document.body.previousSibling.appendChild(script1);

	Height+=2;
	var DIV= document.createElement("DIV");
	DIV.style.width=iWidth;
	DIV.style.height=Height;

	if(inputText.readOnlyValue=='false')
		StyleDIV(DIV,"black 1px solid");
	else
		StyleDIV(DIV,"#c0c8ab 1px solid");

	DIV.appendChild(Table)
	oPopBody.innerHTML=DIV.outerHTML;
	if (window.screen.height < window.event.screenY + Height + document.getElementById(TableId).offsetHeight)
	{
		y =- Height;
	}
	if(window.screen.width<iWidth)
	{
		iWidth=window.screen.width-8;
	}
		PopUpCombo.show(0,y,iWidth,Height,document.getElementById(TableId));

	if (objFocus >=0)
	{
		PopUpCombo.document.getElementById('TD' + objFocus).focus();
	}
}

function TableRow(Text,valueID,value,Index,inputText,combo)
{
	var TR = document.createElement("TR");
	var TD = document.createElement("TD");
	var Div =document.createElement("DIV");
	TD.id = "TD" + value;
	TD.Height="13px";
	TD.onmouseover="webComboHighLight(this);"
	TD.onmouseout="webComboNoLight(this);"
	TD.style.cursor = "default";
	TD.valueID = parseString(valueID);
	TD.onClick="WebComboClick(this,\"" + parseString(inputText.valueID) + "\",\"" + value + "\",'" + inputText.id + "','" + combo.id + "')";
	TD.onkeydown="WebComboKeyDown(this," + value + ");";//,'" + valueID + "');";//+ "," + inputText + "," + combo + ")";
	TD.onkeyup="parent.execScript('CancelScroll();', 'javascript');"
	TD.onblur="ClosePopUp();"

	Div.innerText=" " + Text;
	Div.noWrap = true;

	if(inputText.readOnlyValue=='true')
	{
		TD.style.background = "#e0e8db";
		TD.style.color = "#666666";
	}
	if (value == Index)
	{
		TD.style.background = "highlight";
		TD.style.color = "white";
	}
	TD.appendChild(Div);
	TR.appendChild(TD);
	return TR;
}

function onclickFunction(Text,valueID,value,InputTextId,ComboId)
{
	var inputText=document.getElementById(InputTextId);
	var combo=document.getElementById(ComboId);
	if(inputText.readOnlyValue=='false')
	{
		//MFP 31/08/2004. Modificación para el caso de que se haya definido una función para el
		//evento OnbeforeUpdate del combo.
		while (Text.indexOf('&quot;') > -1)
		{
			Text = Text.replace('&quot;','"');
		}

		if (eval(combo.onbeforeupdate) != null) {
			if (combo.fireEvent('onbeforeupdate')) {
				inputText.innerText = Text;
				inputText.valueID = valueID;
				combo.options[value].selected = true;
				CheckEventCombo("onclick",combo);
				CheckEventCombo("onchange",combo);
			}
		} else {
			inputText.innerText = Text;
			inputText.valueID = valueID;
			combo.options[value].selected = true;
			CheckEventCombo("onclick",combo);
			CheckEventCombo("onchange",combo);
		}
		//MFP 31/08/2004.

		//Modificación para añadir un ToolTip cuando el texto quede cortado. MFP 03/03/2005.
		var oDivTexto = document.createElement("SPAN")
		oDivTexto.style.display = "inline";
		oDivTexto.style.visibility = "hidden";
		oDivTexto.className = inputText.className;
		oDivTexto.innerText = Text;
		document.body.appendChild(oDivTexto);
		var LongTexto = oDivTexto.offsetWidth;
		document.body.removeChild(oDivTexto);
		if (LongTexto > inputText.offsetWidth)
			inputText.title = Text;
		else
			inputText.title = "";
		//Modificación para añadir un ToolTip cuando el texto quede cortado. MFP 03/03/2005.
	}
}

function CheckEventCombo(ev,combo)
{
	if(eval("combo." + ev)!= null) combo.fireEvent(ev);
}

function StylePopUp(obj)
{
	obj.style.fontSize="9pt";
	obj.style.fontFamily="Arial,'Microsoft Sans Serif'";
	obj.style.color="black";
	obj.style.backgroundColor="White";

}

function StyleDIV(obj,style)
{
	obj.style.borderRight = style;
	obj.style.borderLeft = style;
	obj.style.borderTop = style;
	obj.style.borderBottom = style;
	//obj.className=style;
	obj.style.overflowY="auto";
	obj.style.overflowX="hidden";
}
function CalculateWidth(text)
{
	var Widht;
	var DIV = document.createElement("DIV");
	StylePopUp(DIV);
	DIV.innerText = " " + text;
	DIV.noWrap=true;
	DIV.style.display = "inline";
	DIV.style.visibility = "hidden";
	document.body.appendChild(DIV);
	Widht=DIV.offsetWidth;
	document.body.removeChild(DIV);
	return Widht + 4;
}

function ComboFocus(inputText)
{
	//inputText=InputText;
	if(inputText.readOnlyValue=='false')
	{
		inputText.className="A3AdvComboIFocus";
	}
}

function ComboKeyDown(ComboId,InputTextid)
{
	var value;
	var Text;
	var valueID;
	var inputText=document.getElementById(InputTextid);
	var combo=document.getElementById(ComboId);
	value=combo.selectedIndex;
	switch(event.keyCode)
	{
		case (38):
			if(value > 0)
			{
				value -=1;
				Text=combo.options[value].text;
				valueID=combo.options[value].value;
				onclickFunction(Text,valueID,value,inputText.id,combo.id);
			}
		break;
		case (40):
			if(value < combo.options.length - 1)
			{
				value +=1;
				Text=combo.options[value].text;
				valueID=combo.options[value].value;
				onclickFunction(Text,valueID,value,inputText.id,combo.id);
			}
		break;
	}
	InputFocus(inputText.id);
}

function InputFocus(InputTextId)
{
	var inputText=document.getElementById(InputTextId);
	inputText.focus();
	if(inputText.readOnlyValue=='false')
	{
		inputText.className="A3AdvComboIFocus"
	}
}

function ComboBlur(InputText)
{
	if(InputText.readOnlyValue=='false')
	{
		InputText.className="A3AdvComboI"
	}
}

function CancelScroll()
{
	document.body.scroll='auto';
	document.forms(0).style.width = "";
}

function SavePosicionScroll()
{

	if(document.body.scroll != 'no')
	{
		document.body.scroll='no'
		document.forms(0).style.width = document.forms(0).offsetWidth - 17;
	}
}

function PrintScript(objFocus)
{
	var Script='var objFocus=' + objFocus + ';var objbackground,objcolor;';
	Script+='function WebComboClick(obj,inputTextValueId,value,inputText,comboid)';
	Script+='{';
	Script+='	if (inputTextValueId!=obj.valueID)';
	Script+='	{';
	Script+="		parent.execScript('onclickFunction(\"' + parseString(obj.innerText) + '\",\"' + obj.valueID + '\",\"' + value + '\",\"' + inputText + '\",\"' + comboid + '\")', 'javascript');";
	Script+='	}';
	Script+='	parent.execScript("if(PopUpCombo!=null){PopUpCombo.hide(); PopUpCombo = null;}", "javascript");';
	Script+='	parent.execScript("InputFocus(\'" + inputText + "\');","javascript");';
	Script+='}';
	Script+='function webComboHighLight(obj)';
	Script+='{';
	Script+='	objbackground=obj.style.background;';
	Script+='	objcolor=obj.style.color;';
	Script+='	obj.style.background = "highlight";';
	Script+='	obj.style.color = "white";';
	Script+='	if (obj != document.getElementById("TD" + objFocus))';
	Script+='	{';
	Script+='		document.getElementById("TD" + objFocus).style.background = objbackground;';
	Script+='		document.getElementById("TD" + objFocus).style.color = objcolor;';
	Script+='	}';
	Script+='	obj.focus();';
	Script+='}';
	Script+='function webComboNoLight(obj)';
	Script+='{';
	Script+='	objFocus=obj.id.replace("TD","");';
	Script+='}';
	Script+='function WebComboKeyDown(obj,value)';
	Script+='{';
	Script+='	switch(event.keyCode)';
	Script+='	{';
	Script+='		case(38):';
	Script+='			if (value>0)';
	Script+='			{';
	Script+='				value -= 1;	';
	Script+='			}';
	Script+='		break;';
	Script+='		case (40):';
	Script+='			value +=1;';
	Script+='		break;';
	Script+='		case (13):';
	Script+='			obj.click();';
	Script+='		break;';
	Script+='	}';
	Script+='	if (document.getElementById("TD" + value)!= null)';
	Script+='	{';
	Script+='		webComboNoLight(obj);';
	Script+='		var NewObj = document.getElementById("TD" + value);';
	Script+='		webComboHighLight(NewObj);';
	Script+='		webComboNoLight(NewObj);';
	Script+='		NewObj.focus();';
	Script+='	}';
	Script+='   parent.execScript("SavePosicionScroll();", "javascript");';
	Script+='}';
	Script+='function ClosePopUp()';
	Script+='{';
	Script+='	parent.execScript("PopUpCombo = null;", "javascript");';
	Script+='}';
	Script+='function parseString(text)';
	Script+='{';
	Script+='	while (text.indexOf(String.fromCharCode(34)) > -1)';
	Script+='	{';
	Script+='		text = text.replace(String.fromCharCode(34),"&quot;");';
	Script+='	}';
	Script+='	return text;';
	Script+='}';

	return Script;
}

function ChangePropertyCombo(objCombo) {
	if (objCombo.getAttribute('readonlyvalue') == null){
		if(objCombo.style.display == "")
			document.getElementById(objCombo.id + "_Table").style.display = "inline";
		else
			document.getElementById(objCombo.id + "_Table").style.display = objCombo.style.display;

		if(objCombo.selectedIndex == -1){
			document.getElementById(objCombo.id + "_InputText").innerText= "";
			document.getElementById(objCombo.id + "_InputText").valueID= "";
		}else{
			if(document.getElementById(objCombo.id + "_InputText").valueID != objCombo.options[objCombo.selectedIndex].value)
			{
				document.getElementById(objCombo.id + "_InputText").innerText = " " + objCombo.options[objCombo.selectedIndex].text;
				document.getElementById(objCombo.id + "_InputText").valueID = objCombo.options[objCombo.selectedIndex].value;
			}
		}
	}else{
		if (objCombo.style.display == "")
			document.getElementById(objCombo.id + '_InputText').style.display = "inline";
		else
			document.getElementById(objCombo.id + '_InputText').style.display = objCombo.style.display;
		if(objCombo.selectedIndex == -1){
			document.getElementById(objCombo.id + "_InputText").innerText= "";
			document.getElementById(objCombo.id + "_InputText").valueID= "";
		}else{
			if(document.getElementById(objCombo.id + "_InputText").valueID != objCombo.options[objCombo.selectedIndex].value)
			{
				document.getElementById(objCombo.id + "_InputText").innerText = " " + objCombo.options[objCombo.selectedIndex].text;
				document.getElementById(objCombo.id + "_InputText").valueID = objCombo.options[objCombo.selectedIndex].value;
			}
		}
		
	}
/*
	if(objCombo.disabled == true || objCombo.readonly=="")
		A3ComboDisabled(objCombo.id )
	else
		A3ComboEnabled(objCombo.id )

	CalculateDivCombo(objCombo.id)
*/
}

function changeComboSelectedItem(cmbId, indx){
	var cmb = document.getElementById(cmbId);

	cmb.selectedIndex = indx;
	document.getElementById(cmbId + "_InputText").innerText = cmb.options[indx].text;
	document.getElementById(cmbId + "_InputText").valueID = cmb.options[indx].value;
}

var disabled = false;
function A3ComboDisabled(objId)
{
	if (document.getElementById(objId + "_Table") != null){
		document.getElementById(objId + "_Table").className="A3AdvDisabledComboT";
		document.getElementById(objId + "_InputText").className="A3DisabledCombo";
		document.getElementById(objId + "_InputText").readOnlyValue="true";

		//Asignar el tabIndex a -1 para que el control no tome el foto. MFP 27/01/2005.
		document.getElementById(objId + "_InputText").oldtabIndex = document.getElementById(objId + "_InputText").tabIndex
		document.getElementById(objId + "_InputText").tabIndex = -1;
		//Asignar el tabIndex a -1 para que el control no tome el foto. MFP 27/01/2005.

		//Modificación para poder desactivar correctamente la combo desde cliente. MFP 09/12/2004.
		document.getElementById(objId + "_Button").className="A3ButtonHide";
		document.getElementById(objId + "_Button").readonly=true;
		//Modificación para poder desactivar correctamente la combo desde cliente. MFP 09/12/2004.

		if (disabled == false){
			var onChange = document.getElementById(objId).onchange;
			if (document.getElementById(objId).oldchange != null){
				document.getElementById(objId).onchange = document.getElementById(objId).oldchange;
				disabled = true;
				//document.getElementById(objId).disabled = true; //Modificado para que el control viaje a servidor. MFP 27/01/2004.
			}

			if (onChange != null) document.getElementById(objId).oldchange = onChange;
		}
	}
}

function A3ComboEnabled(objId)
{
	if (document.getElementById(objId + "_Table")!= null){
		document.getElementById(objId + "_Table").className="A3AdvComboT";
		document.getElementById(objId + "_InputText").className="A3AdvComboI";
		document.getElementById(objId + "_InputText").readOnlyValue="false";
		document.getElementById(objId + "_InputText").disabled = false;

		//Asignar el antiguo tabIndex. MFP 27/01/2005.
		if (document.getElementById(objId + "_InputText").oldtabIndex != null)
			document.getElementById(objId + "_InputText").tabIndex = document.getElementById(objId + "_InputText").oldtabIndex;
		//Asignar el antiguo tabIndex. MFP 27/01/2005.

		document.getElementById(objId + "_Button").className="A3AdvComboB";
		document.getElementById(objId + "_Button").readonly=false;

		if (disabled == true){
			var onChange = document.getElementById(objId).oldchange;
			if (document.getElementById(objId).onchange != null){
				document.getElementById(objId).oldchange=document.getElementById(objId).onchange;
				disabled = false;
				//document.getElementById(objId).disabled = false; ////Modificado para que el control viaje a servidor. MFP 27/01/2004.
			}

			if (onChange != null) document.getElementById(objId).onchange=onChange;
		}
	}
}

var ArrayCombo="";
function CalculateDivCombo(idCombo)
{
	var WidthRest = 5; //Imprescindible que esta variable contenga 5.
	if (idCombo == null)
	{
		var i;
		var ACombo = new Array();
		ACombo = ArrayCombo.split("|");
		for (i=0; i<ACombo.length; i++)
		{
			if (ACombo[i] != "")
			{
				idCombo=ACombo[i];
				if(document.getElementById(idCombo)!=null && document.getElementById(idCombo).style.display != 'none')
				{
					var Width;
					var Texto = document.getElementById(idCombo + "_InputText").innerText;

					//Modificación para añadir un ToolTip cuando el texto quede cortado. MFP 03/03/2005.
					var oDivTexto = document.createElement("SPAN")
					oDivTexto.style.display = "inline";
					oDivTexto.style.visibility = "hidden";
					oDivTexto.className = document.getElementById(idCombo + "_InputText").className;
					oDivTexto.innerText = Texto.slice(1);
					document.body.appendChild(oDivTexto);
					var LongTexto = oDivTexto.offsetWidth;
					document.body.removeChild(oDivTexto)
					//Modificación para añadir un ToolTip cuando el texto quede cortado. MFP 03/03/2005.

					document.getElementById(idCombo + "_InputText").innerText = "";
					if (document.getElementById(idCombo + "_Table") != null){
						Width = document.getElementById(idCombo + "_Table").offsetWidth;
						if (Width == 0)
							document.getElementById(idCombo + "_Table").FirstRender = true;
						else{
							var WidthButton = document.getElementById(idCombo + "_Button").offsetWidth;
							if (Width - WidthButton - WidthRest >= 0){
								document.getElementById(idCombo + "_InputText").style.width = Width - WidthButton - WidthRest;// NewWidth

								//Modificación para añadir un ToolTip cuando el texto quede cortado. MFP 03/03/2005.
								if (LongTexto > Width - WidthButton - WidthRest)
									document.getElementById(idCombo + "_InputText").title = Texto.slice(1);
								else
									document.getElementById(idCombo + "_InputText").title = "";
								//Modificación para añadir un ToolTip cuando el texto quede cortado. MFP 03/03/2005.
							}
						}
						document.getElementById(idCombo + "_InputText").innerText = Texto;
					}
				}
			}
		}
	}
	else
	{
		if(document.getElementById(idCombo)!=null && document.getElementById(idCombo).style.display != 'none')
		{
			var Width;
			var Texto = document.getElementById(idCombo + "_InputText").innerText;

			//Modificación para añadir un ToolTip cuando el texto quede cortado. MFP 03/03/2005.
			var oDivTexto = document.createElement("SPAN")
			oDivTexto.style.visibility = "hidden";
			oDivTexto.style.display = "inline";
			oDivTexto.className = document.getElementById(idCombo + "_InputText").className;
			oDivTexto.innerText = Texto.slice(1);
			document.body.appendChild(oDivTexto);
			var LongTexto = oDivTexto.offsetWidth;
			document.body.removeChild(oDivTexto);
			//Modificación para añadir un ToolTip cuando el texto quede cortado. MFP 03/03/2005.

			document.getElementById(idCombo + "_InputText").innerText = "";
			
			if (document.getElementById(idCombo + "_Table") != null){
				Width = document.getElementById(idCombo + "_Table").offsetWidth ;
				var WidthButton = document.getElementById(idCombo + "_Button").offsetWidth;
				if (Width - WidthButton - WidthRest >= 0){
					document.getElementById(idCombo + "_InputText").style.width = Width - WidthButton - WidthRest;// NewWidth
					document.getElementById(idCombo + "_Table").CountResize = (document.getElementById(idCombo + "_Table").CountResize * 1) + 1;

					//Modificación para añadir un ToolTip cuando el texto quede cortado. MFP 03/03/2005.
					if (LongTexto > Width - WidthButton - WidthRest)
						document.getElementById(idCombo + "_InputText").title = Texto.slice(1);
					else
						document.getElementById(idCombo + "_InputText").title = "";
					//Modificación para añadir un ToolTip cuando el texto quede cortado. MFP 03/03/2005.
				}
				document.getElementById(idCombo + "_InputText").innerText = Texto;
			}
		}
	}
}

function parseString(text)
{
	//Parseo "
	while (text.indexOf('"') > -1)
	{
		text = text.replace('"','&quot;');
	}
	return text;
}
//Parar el cambio de tamaño tras 300 vueltas y desactivarlo durante 80 ms.
//antes de poder volver a hacer cambio de tamaño. MFP 01/09/2004.
var TimerRedraw = null;
function ResetCountResize(idCombo) {
	document.getElementById(idCombo + "_Table").CountResize = 0;
	TimerRedraw = null;
}
//MFP 01/09/2004.

//MFP 21/01/2005.
function A3ComboResize(oCombo, idCombo){
	if (oCombo.FirstRender){
		CalculateDivCombo(idCombo)
		oCombo.FirstRender = false;
	} else {
		if (oCombo.CountResize < 300)
			if (oCombo.FirstRender) { CalculateDivCombo(idCombo); }
		else {
			if (TimerRedraw == null)
				TimerRedraw = window.setTimeout('ResetCountResize(\'' + idCombo + '\')',80);
		}
	}
}
//MFP 21/01/2005.
/**************************************************************************************************
Fin de las funciones de la A3Combo
***************************************************************************************************/
// Funciones Alert y Confirm

// Funcion ShowA3Alert encargada de abrir la página A3alert.aspx en modo modal.
function ShowA3alert(Application, Page, Mensaje,  mesType){
	// Se Informan los parametros a mandar al A3Modal
	var Parameters = new Array(6);
	Parameters[0] = Application;
	Parameters[1] = encodeURI(Page + Mensaje + "&mesType=" + mesType);
	Parameters[2] = this;
	
	// Determino las dimensiones de la ventana a mostrar.
	var cantCarac = Mensaje.length;
	
	var mWidth = 160 + cantCarac * 6;
	var mHeight = 180;
	
	if(mWidth > 800)
	{
	    mWidth = 800;
	    mHeight = 180 + Math.round((cantCarac / 110) - 1) * 12;
	}
	
	mHeight = mHeight > 600 ? 600 : mHeight;
	mWidth = mWidth < 360 ? 360 : mWidth;
	
	// Se Informa los Argumentos del ShowModalDialog
	var Arguments = "dialogheight: " + mHeight + "px;";
	Arguments += "dialogwidth: " + mWidth + "px;";
	Arguments += "center: yes; help: no; resizable: no; scroll: no; status: no";
	
	// Se realiza la llamada al ShowModalDialog
	var showImageFrame = false;
    if (top.isLoginPage == undefined){ top.isLoginPage = false; }
	var mdlPage = (top.isLoginPage) ? "A3SupportPages/A3Modal.html": "../A3SupportPages/A3Modal.html";

	return showModalDialog(mdlPage + "?hif=" + showImageFrame.toString(), Parameters, Arguments);
}

// Funcion A3Alert (reemplaza el alert de html) recibiendo el mensaje como parámetro.
function A3alert(Mensaje){

	var Page = "../A3SupportPages/A3alert.aspx?Msj=";
	var Application = 'A3';
	var mesType = 'I';

	return ShowA3alert(Application,Page, Mensaje, mesType);
}

// Funcion A3Confirm (reemplaza el confirm de html) recibiendo el mensaje como parámetro
function A3confirm(Mensaje){
	var Page = "../A3SupportPages/A3alert.aspx?Msj=";
	var Application = 'A3';
	var mesType = 'C';

	return ShowA3alert(Application, Page, Mensaje, mesType);
}

function GetBrowserVersion(){
	version=0
	if (navigator.appVersion.indexOf("MSIE")!=-1){
		temp=navigator.appVersion.split("MSIE")
		version=parseFloat(temp[1])
	}
	return version;
}

function getCookie(sName){
    var start = document.cookie.indexOf(sName + "=");
	var len = start + sName.length + 1;
	if ((!start) && (sName != document.cookie.substring(0, sName.length)))
	  return null;
	if (start == -1)
	   return null;
	var end = document.cookie.indexOf(";", len);
	if (end == -1) end = document.cookie.length;
	   return unescape(document.cookie.substring(len, end));
}
