function textCounter(field, countfield, maxlimit) {
	if (field.value.length > maxlimit) // if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
		// otherwise, update 'characters left' counter
 	else 
	countfield.value = maxlimit - field.value.length;
}

function validaForm(ruta){


  

var propControl = new Array();
debecontar=0;
contar=0;
validar=0;
vacios=0;
	for(var i=0; i<ruta.elements.length; i++){
		controlAct=ruta.elements[i];
		if(ruta.elements[i].title.indexOf("*")!=-1){//si existe * entonces valida datos del control actual
			propControl = ruta.elements[i].title.split("*");
			//alert(propControl[1]);
			if(propControl[1].indexOf("r")!= -1){//si es diferente de -1 entonces es un control requerido
				if(controlAct.value=="" || controlAct.value=="0"){
					alert("El campo \""+propControl[0]+"\" es obligatorio");
					controlAct.focus();
					return false;
					break;
				}
			}
			if(propControl[1].indexOf("m")!= -1){//si es diferente de -1 entonces se debe validar el email
				if(emailCheck(controlAct.value)==0){
					alert("Ingrese un E-mail correcto");
					controlAct.focus();
					return false;
					break;
				}
			}if(propControl[1].indexOf("c")!= -1){
				debecontar=1;
				contar=contar+1;
				if(controlAct.value==""){
					vacios=vacios+1;
					if(contar==1){
						kontrol=controlAct;
						nombreKontrol=propControl[0];
					}
				}				
			}			
			if(propControl[1].indexOf("f")!= -1){
				if(checkDecimals(controlAct)==0){
					alert("El campo "+propControl[0]+" debe contener sólo números");
					controlAct.focus();
					controlAct.select();
					return false;
					break;
				}else{
					num=roundOff(controlAct.value, 2);
					//alert(num);
				}				
			}
			if(propControl[1].indexOf("p1")!= -1){//hay un "campo password"
				password1=controlAct.value;
			}
			if(propControl[1].indexOf("p2")!= -1){//hay un campo "repetir password"
				password2=controlAct.value;
				validar=1;
				ctrlRep=controlAct;
			}
		}
	}
	if(validar==1){
		if(password1!=password2){
			alert('Debe repetir correctamente la contraseña(t)');
			ctrlRep.focus();
			ctrlRep.select();
			return false;
		}
	}
	if(debecontar==1){
		if(contar==vacios){
			alert('No se puede enviar el formulario con todos los campos "'+nombreKontrol+'" vacíos');
			kontrol.focus();
			return false;
		}
	}
}

function roundOff(value, precision){
value = "" + value //convert value to string
precision = parseInt(precision);
var whole = "" + Math.round(value * Math.pow(10, precision));
var decPoint = whole.length - precision;

	if(decPoint != 0){
		result = whole.substring(0, decPoint);
		result += ".";
		result += whole.substring(decPoint, whole.length);
	}else{
		result = whole;
	}
	return result;
}


function checkDecimals(fieldName) {
decallowed = 2;  // cuantos decimales se desea
fieldValue=fieldName.value;
	if(fieldValue.length>=1){
		if (isNaN(fieldValue) || fieldValue == "") {
			/*alert("OJO! No has introducido un numero. Vuelve a intentarlo");
			fieldName.select();
			fieldName.focus();*/
			return 0;
		}
		else {
			if (fieldValue.indexOf('.') == -1) 
				fieldValue += ".";
			dectext = fieldValue.substring(fieldValue.indexOf('.')+1, fieldValue.length);
	
			if (dectext.length > decallowed){
				/*alert ("OJO!! Introduce un numero con " + decallowed + " decimales.  Intentalo de nuevo.");
				fieldName.select();
				fieldName.focus();*/
				return 0;
	      	}else {
			//alert ("OK!! Numero correcto.");
			return 1;
	      	}
		}
	}else{
		return 1;
	}
}


function emailCheck (emailStr) {
if(emailStr.length>=1){
var emailPat=/^(.+)@(.+)$/
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
var validChars="\[^\\s" + specialChars + "\]"
var quotedUser="(\"[^\"]*\")"
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
var atom=validChars + '+'
var word="(" + atom + "|" + quotedUser + ")"
var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")

var matchArray=emailStr.match(emailPat)
if (matchArray==null) {
	return 0;
}
var user=matchArray[1]
var domain=matchArray[2]

if (user.match(userPat)==null) {
	return 0;
}

var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
		return 0;
	    }
    }
	return 1;
}

var domainArray=domain.match(domainPat)
if (domainArray==null) {
	return 0;
}
var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2 || 
    domArr[domArr.length-1].length>3) {
   return 0;
}

if (len<2) {
   return 0;
}

}else{
	return 1;
}

}

//**************************************formateo de textos**********************

<!--
// bbCode control by
// subBlue design
// www.subBlue.com

// Startup variables
var imageTag = false;
var theSelection = false;

// Check for Browser & Platform for PC & IE specific bits
// More details from: http://www.mozilla.org/docs/web-developer/sniffer/browser_type.html
var clientPC = navigator.userAgent.toLowerCase(); // Get client info
var clientVer = parseInt(navigator.appVersion); // Get browser version

var is_ie = ((clientPC.indexOf("msie") != -1) && (clientPC.indexOf("opera") == -1));
var is_nav  = ((clientPC.indexOf('mozilla')!=-1) && (clientPC.indexOf('spoofer')==-1)
                && (clientPC.indexOf('compatible') == -1) && (clientPC.indexOf('opera')==-1)
                && (clientPC.indexOf('webtv')==-1) && (clientPC.indexOf('hotjava')==-1));

var is_win   = ((clientPC.indexOf("win")!=-1) || (clientPC.indexOf("16bit") != -1));
var is_mac    = (clientPC.indexOf("mac")!=-1);


// Helpline messages
b_help = "Negrita: <b>texto</b>  (alt+b)";
i_help = "Cursiva: [i]texto[/i]  (alt+i)";
u_help = "Subrayado: [u]texto[/u]  (alt+u)";
q_help = "Cita: [quote]texto[/quote]  (alt+q)";
c_help = "Código: [code]código[/code]  (alt+c)";
l_help = "Lista: [list]texto[/list] (alt+l)";
o_help = "Lista ordenada: [list=]texto[/list]  (alt+o)";
p_help = "Insertar imagen: [img]http://url_imagen[/img]  (alt+p)";
w_help = "Insertar URL: [url]http://url[/url] o [url=http://url]texto URL[/url]  (alt+w)";
a_help = "Cerrar todos los marcadores de bbCode abiertos";
s_help = "Color: [color=red]texto[/color]  Nota: Puede usar color=#FF0000";
f_help = "Tamaño: [size=x-small]texto pequeño[/size]";

// Define the bbCode tags
bbcode = new Array();
bbtags = new Array('[b]','[/b]','[i]','[/i]','[u]','[/u]','[quote]','[/quote]','[code]','[/code]','[list]','[/list]','[list=]','[/list]','[img]','[/img]','[url]','[/url]');
imageTag = false;

// Shows the help messages in the helpline window
/*function helpline(help) {
	document.post.helpbox.value = eval(help + "_help");
}*/


// Replacement for arrayname.length property
function getarraysize(thearray) {
	for (i = 0; i < thearray.length; i++) {
		if ((thearray[i] == "undefined") || (thearray[i] == "") || (thearray[i] == null))
			return i;
		}
	return thearray.length;
}

// Replacement for arrayname.push(value) not implemented in IE until version 5.5
// Appends element to the array
function arraypush(thearray,value) {
	thearray[ getarraysize(thearray) ] = value;
}

// Replacement for arrayname.pop() not implemented in IE until version 5.5
// Removes and returns the last element of an array
function arraypop(thearray) {
	thearraysize = getarraysize(thearray);
	retval = thearray[thearraysize - 1];
	delete thearray[thearraysize - 1];
	return retval;
}


function checkForm() {

	formErrors = false;

	if (document.post.message.value.length < 2) {
		formErrors = "Debe escribir un mensaje para publicar";
	}

	if (formErrors) {
		alert(formErrors);
		return false;
	} else {
		bbstyle(-1);
		//formObj.preview.disabled = true;
		//formObj.submit.disabled = true;
		return true;
	}
}

function emoticon(text) {
	text = ' ' + text + ' ';
	if (document.post.message.createTextRange && document.post.message.caretPos) {
		var caretPos = document.post.message.caretPos;
		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text + ' ' : text;
		document.post.message.focus();
	} else {
	document.post.message.value  += text;
	document.post.message.focus();
	}
}

function bbfontstyle(bbopen, bbclose) {
	if ((clientVer >= 4) && is_ie && is_win) {
		theSelection = document.selection.createRange().text;
		if (!theSelection) {
			document.post.message.value += bbopen + bbclose;
			document.post.message.focus();
			return;
		}
		document.selection.createRange().text = bbopen + theSelection + bbclose;
		document.post.message.focus();
		return;
	} else {
		document.post.message.value += bbopen + bbclose;
		document.post.message.focus();
		return;
	}
	storeCaret(document.post.message);
}


function bbstyle(bbnumber,ruta,control) {
	donotinsert = false;
	theSelection = false;
	bblast = 0;

	if (bbnumber == -1) { // Close all open tags & default button names
		while (bbcode[0]) {
			butnumber = arraypop(bbcode) - 1;
			control.value += bbtags[butnumber + 1];
			buttext = eval('ruta.addbbcode' + butnumber + '.value');
			eval('ruta.addbbcode' + butnumber + '.value ="' + buttext.substr(0,(buttext.length - 1)) + '"');
		}
		imageTag = false; // All tags are closed including image tags :D
		control.focus();
		return;
	}

	if ((clientVer >= 4) && is_ie && is_win)
		theSelection = document.selection.createRange().text; // Get text selection

	if (theSelection) {
		// Add tags around selection
		document.selection.createRange().text = bbtags[bbnumber] + theSelection + bbtags[bbnumber+1];
		control.focus();
		theSelection = '';
		return;
	}

	// Find last occurance of an open tag the same as the one just clicked
	for (i = 0; i < bbcode.length; i++) {
		if (bbcode[i] == bbnumber+1) {
			bblast = i;
			donotinsert = true;
		}
	}

	if (donotinsert) {		// Close all open tags up to the one just clicked & default button names
		while (bbcode[bblast]) {
				butnumber = arraypop(bbcode) - 1;
				control.value += bbtags[butnumber + 1];
				buttext = eval('ruta.addbbcode' + butnumber + '.value');
				eval('ruta.addbbcode' + butnumber + '.value ="' + buttext.substr(0,(buttext.length - 1)) + '"');
				imageTag = false;
			}
			control.focus();
			return;
	} else { // Open tags

		if (imageTag && (bbnumber != 14)) {		// Close image tag before adding another
			control.value += bbtags[15];
			lastValue = arraypop(bbcode) - 1;	// Remove the close image tag from the list
			ruta.addbbcode14.value = "Img";	// Return button back to normal state
			imageTag = false;
		}

		// Open tag
		control.value += bbtags[bbnumber];
		if ((bbnumber == 14) && (imageTag == false)) imageTag = 1; // Check to stop additional tags after an unclosed image tag
		arraypush(bbcode,bbnumber+1);
		eval('ruta.addbbcode'+bbnumber+'.value += "*"');
		control.focus();
		return;
	}
	storeCaret(ruta.control);
}

// Insert at Claret position. Code from
// http://www.faqts.com/knowledge_base/view.phtml/aid/1052/fid/130
function storeCaret(textEl) {
	if (textEl.createTextRange) textEl.caretPos = document.selection.createRange().duplicate();
}

//-->

// esta parte es  la pagina onde va el formulario
function checkRuc(cc){
  if ( cc.value.length == 8 || cc.value.length == 11 ){
    if ( esnulo(cc.value) || !esnumero(cc.value) || !valruc(cc.value) ){
      alert('El Número de RUC no es válido ...')
      cc.focus();
    } else {
      document.selectForm1.submit();
    }
  }else{
    alert('El Número de RUC no es válido ...')
    cc.focus();
  }
}
function inicio(){
   document.selectForm2.coddpto.value = document.selectForm2.dpto.value;
   document.selectForm2.codprov.value = document.selectForm2.prov.value;
   document.selectForm2.dpto.value="";
   cargaProv('document.selectForm2.dpto','document.selectForm2.dist','document.selectForm2.prov','document.selectForm2.coddpto','document.selectForm2.codprov',document.selectForm2.coddpto.value,1)
}
function checkNombre(cc){
 if( !longitudmayor( trim(cc.value) ,0) || (trim(cc.value).substring(0,1)=='*') ){
    alert('La Razón social no es válida ...')
    cc.focus();
 } else{
    document.selectForm2.razon.value = cc.value.toUpperCase()
    document.selectForm2.submit();
 }
}

//****************************************

/**
 * Sets/unsets the pointer in browse mode
 *
 * @param   object   the table row
 * @param   object   the color to use for this row
 *
 * @return  boolean  whether pointer is set or not
 */
function setPointer(theRow, thePointerColor)
{
    if (thePointerColor == '' || typeof(theRow.style) == 'undefined') {
        return false;
    }
    if (typeof(document.getElementsByTagName) != 'undefined') {
        var theCells = theRow.getElementsByTagName('td');
    }
    else if (typeof(theRow.cells) != 'undefined') {
        var theCells = theRow.cells;
    }
    else {
        return false;
    }

    var rowCellsCnt  = theCells.length;
    for (var c = 0; c < rowCellsCnt; c++) {
        theCells[c].style.backgroundColor = thePointerColor;
    }

    return true;
} // end of the 'setPointer()' function

// permite el ingreso sólo de números en una caja de texto--->>>>>>>>>>> onKeypress="if (event.keyCode < 45 || event.keyCode > 57) event.returnValue = false;"

function OpenNewWindow(url,name,w,h) 
{
	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	var v = window.open(url,name,'toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=no,width='+w+',height='+h+',top='+wint+',left='+winl);
}

function Trim(String) {
   if (String == null) {
      return (false);
   }
   return String.replace(/(^\s+)|(\s+$)/g,"");
}

function validarEmail(valor) {
  if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(valor)){
    return (true)
  } else {
    return (false);
  }
 }

function validar_contactos()
{
   
   if(document.forms[0].txt_nombre.value=="")
   {
	 alert("Debe ingresar su nombre");
	 document.forms[0].txt_nombre.focus();
	 return false;
   }
   if(document.forms[0].txt_nombre.value.length < 4)
   {
	 alert("El nombre no debe ser menor de 4 caracteres");
	 document.forms[0].txt_nombre.focus();
	 return false;
   }
   
   if(document.forms[0].txt_mail.value=="")
   {
	 alert("Debe ingresar su e-mail");
	 document.forms[0].txt_mail.focus();
	 return false;
   }
   if(!validarEmail(document.forms[0].txt_mail.value))
   {
	 alert("Debe ingresar un e-mail valido");
	 document.forms[0].txt_mail.focus();
	 return false;
   }
   
   if(document.forms[0].txt_mail.value.length < 6)
   {
	 alert("El mail no debe ser menor de 6 caracteres");
	 document.forms[0].txt_nombre.focus();
	 return false;
   }
   
    if(document.forms[0].txa_mensaje.value=="")
  {
	 alert("Debe ingresar el mensaje");
	 document.forms[0].txa_mensaje.focus();
	 return false;
  }
  return true;
}

function validar_conad()
{
   if(Trim(document.forms[0].txtCorreo.value)=="")
   {
	 alert("Debe ingresar su e-mail");
	 document.forms[0].txtCorreo.focus();
	 return false;
   }
   if(!validarEmail(Trim(document.forms[0].txtCorreo.value)))
   {
	 alert("Debe ingresar un e-mail valido");
	 document.forms[0].txtCorreo.focus();
	 return false;
   }
   if(Trim(document.forms[0].txtTexto.value)=="<P>&nbsp;</P>")
   {
	 alert("Debe ingresar el texto");
	 //document.forms[0].txtTexto.focus();
	 return false;
   }
   
   return true;
}

function teclado(e)
{
  //65 90  97 122
  if ((e.keyCode > 64 && e.keyCode < 123) || e.keyCode==32)
  {
	   return true;
  }
  return false;

  
}
