/*
Copyright (C) 2005 Copyleft México S. de R.L. <http://www.copyleft.com.mx>
Dine Administrator 1.0 by Jadiel Flores

This file is part of Dine Administrator

Dine Administrator is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

Dine Administrator is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Cyberbox.com Site Administrator, if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

<xmp>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE fusedoc SYSTEM "http://fusebox.org/fd4.dtd">
<fusedoc fuse="scripts.js">
	<responsibilities>
		Javascript functions
	</responsibilities>	
	<properties>
		<history author="Jadiel Flores" date="{ts '2004-07-14'}" email="jadiel@jadiel.com" role="Architect" type="Create">Coded today.</history>
	</properties>
</fusedoc>
</xmp>
*/

	
	/* class roll over */
	function roll_over(obj,state,clas){
		obj.className = clas;
	}

	/* 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 */
	function checkForm(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(!emailCheck(poForm.elements[i].value)){
										alert("Escriba una direccion de e-mail válida");
										poForm.elements[i].focus();
										return false;
									}
								}
								//check numeric values
								if((trim(poForm.elements[i].value) != "")&&(poForm.elements[i].alt=="numeric")){
									if(!checknumber(poForm.elements[i].value)){
										alert("El campo debe ser tipo numérico");
										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(!checkfilename(tmp_file_name)){
										alert("El nombre del archivo no puede contener caracteres especiales como letras acentuadas o espacios");
										tmp_file_obj.focus();
										return false;
									}
									if(!checkfiletype(tmp_file_name,tmp_file_types)){
										alert("Archivo inválido, verifique el tipo de archivo.");
										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;
	}
	
	/* validates an email address */
	function emailCheck(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;
	}
	
	/* open window */
	function openWin(Addr, Name, Options){
		var tmp = window.open(Addr, Name, Options);
	}
	
	/* validates a number */	
	function checknumber(poField){
		var x=poField;
		var anum=/(^\d+$)|(^\d+\.\d+$)/;
		if (anum.test(x))
			testresult=true;
		else{
			testresult=false;
		}
		return (testresult);
	}
	
	/* check if filename contains special chars */
	function checkfilename(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 checkfiletype(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;
	}
	
	/* show and hide a block */
	function displayBlock(elemID) {
		var DataID = elemID;
		if (DataID.style.display=="block") {
			DataID.style.display="none";
		} else {
			DataID.style.display="block";
		}
	}
	
	function showBlock(elemID) {
		var DataID = elemID;
		DataID.style.display="block";
	}
	
	function hideBlock(elemID) {
		var DataID = elemID;
		DataID.style.display="none";
	}
	
	function swBlock(elemID) {
		var DataID = document.getElementById(elemID);
		DataID.style.display="block";
	}
	
	function hdBlock(elemID) {
		var DataID = document.getElementById(elemID);
		DataID.style.display="none";
	}
	
	function set_true(elemID) {
		var DataID = document.getElementById(elemID);
		DataID.lang="true";
	}
	
	function set_false(elemID) {
		var DataID = document.getElementById(elemID);
		DataID.lang="false";
	}
	
	/* promts user logout */												
	function doLogout(pURL){
		if (window.confirm('¿Está seguro que desea terminar la sesión?'))
			window.location.href=pURL;
		else
			return;
	}
	
	/* confirm deletion */
	function cfm_delete(modName,itemID,itemName){
		if (window.confirm('¿Está seguro que desea eliminar '+itemName+'?'))
			self.location.href='index.asp?action='+modName+'.delete&'+itemID;
	}

	/* confirm status update */
	function cfm_status(modName,itemID,itemName,itemActive){
		if (itemActive){
			if (window.confirm('¿Está seguro que desea desactivar '+itemName+'?'))
				self.location.href='index.php?fuseaction='+modName+'.status&active=0&'+itemID;
		} else {
			if (window.confirm('¿Está seguro que desea activar '+itemName+'?'))
				self.location.href='index.php?fuseaction='+modName+'.status&active=1&'+itemID;
		}
	}
	
	/* change row style */
	function chgRow(setto, row){
		row.className = 'row'+setto;
	}
	
	/* ajax */
    var http_request = false;
    function makeRequest(url, funcion) {
		if(funcion==null)
			funcion = "processXML";
        http_request = false;
        if (window.XMLHttpRequest) { // Mozilla, Safari,...
            http_request = new XMLHttpRequest();
            if (http_request.overrideMimeType) {
                http_request.overrideMimeType('text/xml');
                // See note below about this line
            }
        } else if (window.ActiveXObject) { // IE
            try {
                http_request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }
        if (!http_request) {
            alert('Giving up :( Cannot create an XMLHTTP instance');
            return false;
        }
        http_request.onreadystatechange = eval(funcion);
        http_request.open('GET', url, true);
		http_request.setRequestHeader('SEND','true');
        http_request.send(null);
    }

    function makeHtmlRequest(url, funcion) {
		if(funcion==null)
			funcion = "processHTML";
        http_request = false;
        if (window.XMLHttpRequest) { // Mozilla, Safari,...
            http_request = new XMLHttpRequest();
            if (http_request.overrideMimeType) {
                http_request.overrideMimeType('text/xml');
                // See note below about this line
            }
        } else if (window.ActiveXObject) { // IE
            try {
                http_request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }
        if (!http_request) {
            alert('Giving up :( Cannot create an XMLHTTP instance');
            return false;
        }
        http_request.onreadystatechange = eval(funcion);
        http_request.open('GET', url, true);
		http_request.setRequestHeader('SEND','true');
        http_request.send(null);
    }

    function makeHtmlRequestPOST(url, vars, funcion) {
		if(funcion==null)
			funcion = "processHTML";
        http_request = false;
        if (window.XMLHttpRequest) { // Mozilla, Safari,...
            http_request = new XMLHttpRequest();
            if (http_request.overrideMimeType) {
                http_request.overrideMimeType('text/xml');
                // See note below about this line
            }
        } else if (window.ActiveXObject) { // IE
            try {
                http_request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {}
            }
        }
        if (!http_request) {
            alert('Giving up :( Cannot create an XMLHTTP instance');
            return false;
        }
        http_request.onreadystatechange = eval(funcion);
        http_request.open('POST', url, true);
		http_request.setRequestHeader('SEND','true');
		http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        http_request.send(vars);
    }

	function openHistory(liga){
		var tmp = window.open(liga, "history", "width=550,height=400,resizable=yes,scrollbars=yes,toolbar=yes");
	}

	function openPays(liga){
		var tmp = window.open(liga, "openPays", "width=550,height=400,resizable=yes,scrollbars=yes,toolbar=yes");
	}

	function number_format(num){
		var nStr = num.toFixed(2);
		nStr += '';
		x = nStr.split('.');
		x1 = x[0];
		x2 = x.length > 1 ? '.' + x[1] : '';
		var rgx = /(\d+)(\d{3})/;
		while (rgx.test(x1)) {
			x1 = x1.replace(rgx, '$1' + ',' + '$2');
		}
		return x1 + x2;
	} 
	function number_format_nocoma(num){
		var nStr = num.toFixed(2);
		nStr += '';
		x = nStr.split('.');
		x1 = x[0];
		x2 = x.length > 1 ? '.' + x[1] : '';
		var rgx = /(\d+)(\d{3})/;

//		while (rgx.test(x1)) {
//			x1 = x1.replace(rgx, '$1' + ',' + '$2');
//		}
		return x1 + x2;
	} 