function conf(msg){
	if(confirm(msg)) 
		return true;
	else return false
}
function popUp(url,ancho,alto,xtras){
	var win = window.open(url,'','width='+ancho+',height='+alto+xtras);
	if(!win) alert('Tiene las ventanas emergentes bloqueadas...');
	return false;
}
/* ********** [MOSTRAR OCULTAR CAPAS] ************* */
function mostrar(id_capa){
	var estado = document.getElementById(id_capa).style.display;
	var tipo = document.getElementById(id_capa).tagName;
	if(estado=='none'){
		document.getElementById(id_capa).style.display = 'block';
		if(tipo=='FORM') document.getElementById(id_capa).elements[1].focus();
	}else
		document.getElementById(id_capa).style.display = 'none';
}
/* **************** [FUNCION PARA TABS] *********************** */
var tab_ant = 1;
function TAB(tab){
	document.getElementById('BTN_'+tab_ant).className = 'tab_inactive';
	document.getElementById('BTN_'+tab).className = 'tab_active';
	//--------
	document.getElementById('tab_'+tab_ant).style.display = 'none';
	document.getElementById('tab_'+tab).style.display = 'block';
	tab_ant = tab;
	return false;
}
/* *****************************************************************
 Validacion de formularios
 =========================
 Ej. de uso:
 
 En el HEAD incluir el archivo JS:
 <script type="text/javascript" language="javascript" src="validaciones.js"></script>
 
 En el formulario se debe agregar el evento onsubmit():
 <form id="frm" name="frm" method="post" action="pagina.php" onsubmit="return submitForm(this);">
 
 A los campos que son requeridos se les agrega el atributo PD="TIPO_DATO|MENSAJE":
 <input name="nombre" type="text" id="nombre" PD="string|Nombre completo" />
 
 TIPO_DATO, puede ser: 
 - STRING
 - DATE
 - NUMBER
 - EMAIL
 - LIST
***************************************************************** */
function submitForm(obj){
	var campos = obj.elements;
	var Error = '';
	var primerCampo = false;
	var primerCampoTipo = 'STRING';
	//----
	for(i=0;i<campos.length;i++){
		var attr = campos[i].attributes;
		for(x=0;x<attr.length;x++){
			var flag = false;
			if(attr[x].name.toUpperCase()=='PD'){
				var res = attr[x].value.split(/\|/);
				var tipo = res[0].replace(/^\s+|\s+$/g, "");
				var label = res[1].replace(/^\s+|\s+$/g, "");
				var valor = campos[i].value;
				switch(tipo.toUpperCase()){
					case 'STRING':
						if(!PD_isString(valor)){
							Error += '- "'+label+'" es obligatorio y debe contener caracteres alfanumericos.\n';
							if(!primerCampo) primerCampo = campos[i];
						}
						flag = true;
						break;
					case 'NUMBER':
						if(!PD_isNumber(valor)){
							Error += '- "'+label+'" es obligatorio y debe contener un numero.\n';
							if(!primerCampo) primerCampo = campos[i];
						}
						flag = true;
						break;
					case 'FECHAS':
						//alert(valor);
						if(!PD_isNumber(valor)){
							Error += '- Fecha Final de reserva es anterior a la Fecha Inicial.\n';
							if(!primerCampo) primerCampo = campos[i];
						}
						flag = true;
						break;
					case 'FILE':
						if(!PD_isString(valor)){
							Error += '- "'+label+'" es obligatorio, debe seleccionar algun archivo valido.\n';
							if(!primerCampo) primerCampo = campos[i];
						}
						flag = true;
						break;
					case 'LIST':
						if(!PD_isString(valor)){
							Error += '- "'+label+'" es obligatorio, debe seleccionar alguna opcion.\n';
							if(!primerCampo){
								primerCampo = campos[i];
								primerCampoTipo = 'LIST';
							}
						}
						flag = true;
						break;
					case 'DATE':
							if(!isDate(valor)){
//if(!PD_isDate(valor)){
							Error += '- "'+label+'" es obligatorio y debe contener una fecha valida (dd/mm/AAAA).\n';
							if(!primerCampo) primerCampo = campos[i];
						}
						flag = true;
						break;
					case 'HOUR':
						if(!PD_isHour(valor)){
							Error += '- "'+label+'" es obligatorio y debe contener una hora valida (HH:mm).\n';
							if(!primerCampo) primerCampo = campos[i];
						}
						flag = true;
						break;
					case 'EMAIL':
						if(!PD_isEmail(valor)){
							Error += '- "'+label+'" es obligatorio y debe contener una direccion de correo valida.\n';
							if(!primerCampo) primerCampo = campos[i];
						}
						flag = true;
						break;
				}
			}
			if(flag) break;
		}
	}
	if(Error!=''){
		var cad = 'Se encontraron los siguientes errores:\n';
		cad += '---------------------------------------------\n';
		cad += Error;
		cad += '---------------------------------------------';
		alert(cad);
		if(primerCampoTipo=='STRING'){
			try{
				primerCampo.select();
			}catch(e){};
		}else{
			try{
				primerCampo.focus();
			}catch(e){};
		}
		return false;
	}
	return true;
}
function PD_isNumber(str){
	if(str.match(/^\d+$/))return true;
	else return false;
}
function PD_isString(str){
	var cad = str.replace(/^\s+|\s+$/g, "");
	if(cad!='') return true;
	else return false;
}
function PD_isDate(str){
	if(str.match(/\b(0?[1-9]|[12][0-9]|3[01])[- \/.](0?[1-9]|1[012])[- \/.](19|20)[0-9]{2}\b/)) {
		if(isDate(str))return true;
		else return false;
	}else return false;
}
function PD_isHour(str){
	if(str.match(/^([0-5]?[0-9]:)?([0-5]?[0-9])$/)) return true;
	else return false;
}
function PD_isEmail(str){
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(str)) return true;
	else return false;
}


var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		return false
	}
	return true
}

