/* basic form validation */
function check_form(poForm){
	for(i=0; i<poForm.elements.length; i++){
		if(poForm.elements[i].lang == "true"){
			//alert(poForm.elements[i].type); 
			switch (poForm.elements[i].type) {
				case "text":
				case "password":
				case "textarea":
				case "file":
					if(trim(poForm.elements[i].title)!=""){
						if(trim(poForm.elements[i].value) == ""){
							alert(poForm.elements[i].title);
							poForm.elements[i].value = "";
							poForm.elements[i].focus();
							return false;
						}
					}
					//custom validations
					if(poForm.elements[i].alt!=null){
						if(trim(poForm.elements[i].alt)!=''){
							//check email address
							if((trim(poForm.elements[i].value) != "")&&(poForm.elements[i].alt=="email")){
								if(!check_email(poForm.elements[i].value)){
									alert("Ingresa una cuenta de correo válida.");
									poForm.elements[i].focus();
									return false;
								}
							}
							//alert(poForm.elements[i].value);
							if((trim(poForm.elements[i].value) != "")&&(poForm.elements[i].alt=="integer")){
								
								if(!esnumero(poForm.elements[i].value)){
									alert("Por favor ingrese un número");
									poForm.elements[i].focus();
									return false;
								}
							}
							//check valid files
							if((trim(poForm.elements[i].value) != "")&&(poForm.elements[i].alt=="file")){
								var tmp_file_obj = poForm.elements[i];
								var tmp_file_name = trim(poForm.elements[i].value);
								var tmp_file_types = trim(poForm.elements[i].accept);
								if(!check_filename(tmp_file_name)){
									alert("The filename can not contain special characters");
									tmp_file_obj.focus();
									return false;
								}
								if(!check_filetype(tmp_file_name,tmp_file_types)){
									alert("Invalid file, check file type");
									tmp_file_obj.focus();
									return false;
								}
							}
						}
					}
					break;
				case "radio":
					elradio = eval("poForm."+poForm.elements[i].name);
					checado = false;
					if(isArray(elradio)){
						for(j=0; j<elradio.length; j++){
							if(elradio[j].checked)
								checado = true;
						}
					} else{
						if(elradio.checked)
							checado = true;
					}
					if(!checado){
						if(isArray(elradio)){
							alert(elradio[0].title);
							elradio[0].focus();
						} else{
							alert(elradio.title);
							elradio.focus();
						}
						return false;
					}
					break;
				case "select-one":
					if(poForm.elements[i].selectedIndex < 1){
						alert(poForm.elements[i].title);
						poForm.elements[i].focus();
						return false;
					}
					break;
				case "select-multiple":
					if(poForm.elements[i].selectedIndex < 1){
						alert(poForm.elements[i].title);
						poForm.elements[i].focus();
						return false;
					}
					break;
			}
		}
	}
	return true;
}

/* promts user logout */												
function doLogout(pURL){
	if (window.confirm('¿Está seguro que desea salir del sistema?')) {
		window.location.href = pURL;
	} else {
		return;
	}
}

/* get data returned by ajax */
function get_data() {
	if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200))
		document.getElementById('main_data').innerHTML = xmlhttp.responseText;
}

/* get logic returned by ajax */
function get_logic() {
	if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200))
		//alert(xmlhttp.responseText);
		eval(xmlhttp.responseText);
}

/* confirm delete */
function del(type, resource, item_name) {
	if((type==null) || (trim(type)==''))
		type = 'url';
	if (window.confirm('Esta seguro que desea eliminar: '+item_name+'?')) {
		if(type=='url') {
			self.location.href = resource;
		} else if(type=='js') {
			eval(resource);
		}
	}
}

/* confirm change */
function change(type, resource, item_name) {
	if((type==null) || (trim(type)==''))
		type = 'url';
	if (window.confirm('¿Está seguro que desea cambiar a la fase '+item_name+'?')) {
		if(type=='url') {
			self.location.href = resource;
		} else if(type=='js') {
			eval(resource);
		}
	}
}
/* show / hide menu */
function do_menu(el) {
	var menuobj = document.getElementById(el);
	(menuobj.style.display=='none') ? menuobj.style.display = 'block' : menuobj.style.display = 'none';	
}

/* remove trailing and leading blanks from a string */
function trim(s) {
	while (s.substring(0,1) == ' ') {
		s = s.substring(1,s.length);
	}
	while (s.substring(s.length-1,s.length) == ' ') {
		s = s.substring(0,s.length-1);
	}
	return s;
}

/* check if object is an array */
function isArray(obj){
	return(typeof(obj.length)=="undefined")?false:true;
}

/* basic form validation */

	
/* validates an email address */
function check_email(emailStr) {
	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 false
	}
	var user=matchArray[1]
	var domain=matchArray[2]
	if (user.match(userPat)==null) {
	    return false
	}
	var IPArray=domain.match(ipDomainPat)
	if (IPArray!=null) {
		for (var i=1;i<=4;i++) {
			if (IPArray[i]>255) {
				return false
			}
		}
		return true
	}
	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
		return false
	}
	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 false
	}
	if (len<2) {
		alert(errStr)
		return false
	}
	return true;
}
	
/* check if filename contains special chars */
function check_filename(fileName) {
	var donde = fileName.lastIndexOf('\\');
	var ArregloChars = new Array('á','é','í','ó','ú',' ','ñ','Á','É','Í','Ó','Ú','Ñ','/','*','?');
	for(i=0;i<16;i++) {
		if(fileName.indexOf(ArregloChars[i], donde) >= 0) 
			return false;
	}
	return true;
}
	
/* check if file is of specified type */
function check_filetype(filePath, fileTypes) {
	var fileName = new Array();
	fileName = filePath.split('.');
	var fileExt = fileName[fileName.length-1];
	fileExt = fileExt.toLowerCase()
	var aFileTypes = fileTypes.split(',');
	var counter=0;
	var found=0;
	while (counter < aFileTypes.length) {
		if(fileExt==aFileTypes[counter]) {
			found=1;
			break;
		}
	  counter+=1;
	}
	if(!found) {
		return false;
	}
	return true;
}


/* validates a number */	
function check_number(num){
	var x = num;
	var anum = /(^\d+$)|(^\d+\.\d+$)/;
	if (anum.test(x))
		testresult=true;
	else
		testresult=false;

	return (testresult);
}

/* format number */
function format_number(amount) {
	var minus = '';
	var i = parseFloat(amount);
	
	if(isNaN(i)) 
		i = 0.00; 
	if(i < 0) 
		minus = '-';
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) 
		s += '.00';
	if(s.indexOf('.') == (s.length - 2)) 
		s += '0';
		
	s = minus + s;
	return s;
}

/* re-format number */
function re_format_number(amount) {
	var minus = '';
	var delimiter = ","; 
	var a = amount.split('.',2)
	var d = a[1];
	var i = parseInt(a[0]);
	
	if(isNaN(i)) 
		return '';
	if(i < 0) 
		minus = '-';
	i = Math.abs(i);
	var n = new String(i);
	var a = [];
	while(n.length > 3) {
		var nn = n.substr(n.length-3);
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	if(n.length > 0) 
		a.unshift(n); 
	n = a.join(delimiter);
	if(d.length < 1) 
		amount = n;
	else 
		amount = n + '.' + d;

	amount = minus + amount;
	return amount;
}

/* replace all ocurrences of char */
function replace_all(str, from, to) {
	var idx = str.indexOf(from);
	while (idx > -1) {
		str = str.replace(from,to);
		idx = str.indexOf(from);
	}
	return str;
}

/* format as quantity (int) */
function quantity_format(el) {
	var output = '0';
	var num = el.value;
	var regexnum = /(^\d+$)/;
	var intpart;
	
	num = replace_all(num,",","");
	
	if (regexnum.test(num)){
		output = format_number(num);
		output = re_format_number(output);
		intpart = output.split('.');
		output = intpart[0];
	}
	el.value = output;
}

/* format as numeric (double) */
function numeric_format(el) {
	var output = '0.00';
	var num = el.value;
	var regexnum = /(^\d+$)|(^\d+\.\d+$)/;
	
	num = replace_all(num,",","");
	
	if (regexnum.test(num)){
		output = format_number(num);
		output = re_format_number(output);
	}
	el.value = output;
}

/* format as currency $(double) */
function currency_format(el) {
	var output = '0.00';
	var num = el.value;
	var regexnum = /(^\d+$)|(^\d+\.\d+$)/;
	var minus = '';
	
	if(num.substring(0,1)=='-') {
		num = replace_all(num,"-","");
		minus = '-';
	}
	
	num = replace_all(num,"$","");
	num = replace_all(num,",","");
	
	if (regexnum.test(num)){
		output = format_number(num);
		output = re_format_number(output);
	}
	el.value = minus+'$'+output;
}

/* format as percent %(double) */
function percent_format(el) {
	var output = '0.00';
	var num = el.value;
	var regexnum = /(^\d+$)|(^\d+\.\d+$)/;
	
	num = num.replace("%","");
	num = replace_all(num,",","");
	
	if (regexnum.test(num)){
		output = format_number(num);
		output = re_format_number(output);
	}
	el.value = output+'%';
}

/* sets a safe number */
function clean_currency(val) {
	var num = val;
	
	num = num.replace("$","");
	num = num.replace("%","");
	num = replace_all(num,",","");
	
	return num;
}

/* clear options for select control */
function clear_select(el) {
	for(i=document.getElementById(el).options.length; i>0; i--) {
		if(document.getElementById(el).options[i] != null) 
			document.getElementById(el).options[i] = null;
	}
}

/* set child name and id */
function set_name(el, val, idx) {
	el.firstChild.name = val + idx;
	el.firstChild.id = val + idx;
	if(trim(el.firstChild.title)!='')
		el.firstChild.title = el.firstChild.title + idx;
}

/* delete items from dynamic table */
function del_item(el, count, rowid, num, hide) {
	var elem = document.getElementById(el);
	var items = document.getElementById(count);

	for(i=elem.rows.length-1; i>=0; i--) {
		if(elem.rows[i].id == rowid) {
			elem.deleteRow(i);
			if(num>1)
				elem.deleteRow(i);
			break;
		}
	}
		
	if(elem.rows.length==hide) {
		if(hide)
			elem.style.display = 'none';
		items.value = 0;
	}
}

/* get the value for radio button */
function get_val_radio(obj,cnt) {
	for(i=1; i<=cnt; i++) {
		if(document.getElementById(obj+i).checked)
			return document.getElementById(obj+i).value;
	}
}

/* get the values for a select multiple */
function get_val_select(obj) {
	var obj_list = '';
	for(i=0; i<obj.options.length; i++) {
		if(obj.options[i].selected)
			obj_list = obj_list + obj.options[i].value + ',';
	}
	if(obj_list=='')
		return '0';
	else
		return obj_list.substring(0,obj_list.length-1);
}

function loading_items() {
	var html = '';
	html = html + '<tr>';
	html = html + '<td style="padding-left: 167px;"></td>';
	html = html + '<td><div class="loading"><img src="images/icn_loading.gif" width="15" height="15" alt="Loading" title="Loading" border="0" /> please wait a moment while loading data ...</div></td>';
	html = html + '</tr>';
	document.getElementById('materials').innerHTML = html;
}
function esnumero(valor){ 
      //intento convertir a entero. 
     //si era un entero no le afecta, si no lo era lo intenta convertir 
     valor = parseInt(valor) 

      //Compruebo si es un valor numérico 
      if (isNaN(valor)) { 
            //entonces (no es numero) devuelvo el valor cadena vacia 
            return (false); 
      }else{ 
            //En caso contrario (Si era un número) devuelvo el valor 
            return (true) ;
      } 
} 


// return the value of the radio button that is checked
// return an empty string if none are checked, or
// there are no radio buttons
function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}


function MM_preloadImages() { //v3.0
	var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
	var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
	if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
	var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
	var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
		d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
		if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
		for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
		if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
	var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
	if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}


function popColorPickerAdmin(objName){
			//preload should contain '#' hash, followed by 6 digit hex color code
			preload = '#' + document.getElementById(objName).value;
			//detail factor, see class.TrueColorPicker.php
			df = 64;
			//Modify these
				//Where to pop the color picker window
				_top = 230;
				_left = 220;
				//Where the index.php exists
				path = '../includes/TrueColorPicker/';
			if(preload != ''){
				preload = encodeURIComponent(preload);
			}
			window.open(path + 'index.php?objName='+objName+'&df='+df+'&preload=' + preload, null,'width=420, height=290, top='+_top+', left='+_left+', help=no, status=no, scrollbars=no, resizable=no, dependent=yes,status=no', true);
		}
		

function tam_paginas(entradaPagesize){
	document.buscar.pagesize.value = entradaPagesize;
	document.buscar.submit();
}

function ordenar_por(entradaOrder){
	document.buscar.order.value = entradaOrder;
	if (document.buscar.ascdesc.value == "ASC"){
		document.buscar.ascdesc.value = "DESC";
	}else if (document.buscar.ascdesc.value == "DESC"){
		document.buscar.ascdesc.value = "ASC";
	}
	document.buscar.submit();
}
