
/** 
 * Recueración abreviada de un elemento por su ID
 */
function el(id) { 
	return document.getElementById(id);
}

/**
 * Clase que contiene utilidades 
 * varias
 */
function JUtil() {}
JUtil.IE  = 1001;
JUtil.MOZ = 1002;
JUtil.getNav = function() {
    var isIE = navigator.userAgent.toLowerCase().indexOf("msie") > -1? true : false;
    var isMoz = document.implementation && document.implementation.createDocument;
    if ( isIE ) return this.IE;
    if ( isMoz) return this.MOZ;
}   
var isIE = JUtil.getNav()==JUtil.IE? true : false;



/* Métodos añadidos al objeto string */
String.prototype.urlEncode = function () {

	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var plaintext = this;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "%20";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode <= 255) {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;

}

String.prototype.padRight = function(num,caract) {
	if ( !caract ) caract = " ";
	var cad = "";
	cad += this;	
	for(var i=0;i<(num-this.length);i++) cad+=caract;
	
	return cad;
}


/** 
 * Selecciona un elemento del select
 */
function seleccionar(form_select,seleccion) {
	for(i=0;i<(form_select.length);i++) {
		if (form_select.options[i].value==seleccion) {
				form_select.options[i].selected=true;
		}
	}	
}

/**
 * Añade una opción al select
 */
function anadir(form_select,valor,texto,marcado,clase) {
	form_select.length++;
	form_select.options[form_select.length-1].text=texto;
	form_select.options[form_select.length-1].value=valor;
	form_select.options[form_select.length-1].selected=marcado;	
	form_select.options[form_select.length-1].className = clase;
}

/* Validación de cadenas */
digito="0123456789";
puntoDecimal=".,";
caracterMayuscula="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
caracterMinuscula="abcdefghijklmnopqrstuvwxyz";
caracer = caracterMayuscula + caracterMinuscula;
alfaNumerico=digito+caracterMayuscula+caracterMinuscula;
signos="_-.";
arroba="@";
cadenaValida= alfaNumerico+signos+arroba;


/**
 * Validación de una cadena
 */
function validarCadena(mascara,cadena) {
	if (cadena.length==0) return false;

	for(i=0;i<cadena.length;i++) {
		if (mascara.indexOf(cadena.charAt(i))==-1) return false;
	}

	return true;
}

/**
 * Validación de un email
 */
function esEmail(cadena) {
	
	if(!validarCadena(cadena,arroba))
		{error='cadena sin arroba';return false;}
	
	parte = cadena.split("@");

	aaaa=parte[0];
	
		
	ultimoPunto = parte[1].lastIndexOf(".");	
	if (ultimoPunto==-1)
		{error='El email no tiene dominio';return false;}		
	
	bbbb=parte[1].slice(0,ultimoPunto);
	
	if (bbbb.length<2)
		{error='bbbb no puede ser menor que 2';return false;}
	
	if (!validarCadena(alfaNumerico+signos,aaaa+bbbb))
			{error='cadena sin arroba';return false;}
	

	cc=parte[1].slice(ultimoPunto+1);


	if (cc.length<2 || cc.length>4)
		{error='cadena sin arroba';return false;}
	if (!validarCadena(caracterMayuscula+caracterMinuscula,cc))
		{error='cadena sin arroba';return false;}	

	return true;

}

/** 
 * Método de redondeo de un número
 */
function roundOff(value, precision) {
		
      value = "" + value //convert value to string
      precision = parseInt(precision);

      var whole = "" + Math.round(value * Math.pow(10, precision));
      if ( precision == 0) return whole;
      var decPoint = whole.length - precision;

      if(decPoint != 0)
      {

              result = whole.substring(0, decPoint);

		result += ",";
              result += whole.substring(decPoint, whole.length);

		if (result==",0") result="0,00";
      }
      else
      {

              result = "0,"+whole;
      }

      return result;
}
    
/**
 * Limpia un número de ceros a la izquieda
 */    
function limpiaCeros( cadena )  {
    temp="";
    numeros=0;
    for(i=0;i<cadena.length;i++)
    {
        if ( cadena.charAt(i)!="0" || numeros>0)
        {  
           temp+=cadena.charAt(i);
           numeros++;
        } 
    }
	
	return temp;
}

/**
 * Aplica una mascara a una cadena
 * @param (String) mask 	Máscara a aplicar
 * @param (String) cadena	Cadena
 * @param (String) align	Alineamiento de la cadena ('left', 'right')
 */
function mascara(  mask , cadena , align ) {
    var i;
    if ( !align  ) align="left";
    if ( !mask   ) return cadena;
	if ( !cadena ) return ""; 

	// Alineamiento del texto a la derecha
    if ( align == "right" ) {
        cad = "";
        for(i=0;i<mask.length-cadena.length;i++) {
            cad+=mask.charAt(i);
        } 
        cad += cadena; 
    }
    
    // Alineamiento del texto a la izquierda
    if ( align == "left" ) {
        cad = cadena;
        for(i=cadena.length;i<mask.length;i++) {
            cad+=mask.charAt(i);
        } 
    }
    
    return cad;
}


/* Cadena para codificación en base64 */
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

/**
 * Método para codificar a base64
 */
function encode64(input) {
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   do {
      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);

      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;

      if (isNaN(chr2)) {
         enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
         enc4 = 64;
      }

      output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + 
         keyStr.charAt(enc3) + keyStr.charAt(enc4);
   } while (i < input.length);
   
   return output;
   
}


/*--------------------------------------------------------------------
    Objeto select
-----------------------------------------------------------------------*/
function JSelect(select,textoInicial,valorInicial) {
    this.select = select;
    this.textoInicial = ((textoInicial+"").length>0) ? textoInicial : "";
    this.valorInicial = ((valorInicial+"").length>0) ? valorInicial : "";
    // Funciones
    this.addValue = JSelectAddValue;
    this.ini      = JSelectIni;
    this.seleccionar = JSelectSeleccionar;
    this.clear	  = JSelectClear;
    
    this.ini();
}    

function JSelectClear()
{
	this.select.length = 0;
}

function JSelectAddValue(codigo,valor,selected) {
    selected = (selected) ? true : false;
    anadir(this.select, codigo, valor, selected);
}
    
function JSelectIni() {
    this.select.length = 0;
    if ( this.textoInicial.length > 0 ) {
        this.addValue(this.valorInicial,this.textoInicial,true);
    }
}
function JSelectSeleccionar(value) {
    seleccionar(this.select,value);
}    


function showPopup(url)
{
	iWidth = 600;
	iHeight = 600;
	iLeft = (window.screen.width - iWidth ) / 2
	iTop = (window.screen.height - iHeight ) / 2
	window.open(url,"_blank","menubar=no, scrollbars=yes, statusbar=no, left="+iLeft+", top="+iTop+", width="+iWidth+", height="+iHeight+",");
}


function _JSelect(idSelect) {
	this.select = el(idSelect);
	
	this.add = function(text,value,selected) {
		
		this.select.options[this.select.options.length] = new Option(text,value,false,selected);
	}
	
	this.clear = function(num) {
		if( !num ) num = 0;
		this.select.options.length = num;
	}	
}

Array.prototype.indexOf = function(value) {
	for(var i in this) {
		if ( this[i] == value ) return i;
	}
	return -1;
}

Array.prototype.ini = function(length,value) {
	for(var i=0;i<length;i++) this[i] = value;
}

Array.prototype.max = function(index,value) {
	if ( this[index] < value ) this[index] = value;
}


function JDictionary() {
	this.length = 0;
	this.arrKeys = new Array();
	this.arrValues = new Array();
	
	this.add = function(key,value) {
		if ( this.arrKeys.indexOf(key)>=0) return;
		this.arrKeys[this.length] = key;
		this.arrValues[this.length] = value;
		this.length++;
	}
	
	this.get = function(key) {
		var index = this.arrKeys.indexOf(key);
		if ( index < 0 ) return "";
		return this.arrValues[index];
	}	
}

/**
*
*  UTF-8 data encode / decode
*  http://www.webtoolkit.info/
*
**/
 
var Utf8 = {
 
	// public method for url encoding
	encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// public method for url decoding
	decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
}


function cp_aceptar() {
	$.get(urlBase+"index.php?accion=control_parental",function(data) {
		if ( data == 'OK') $("#cp_overlay,#cp_html").remove();
	});
	
}

function cp_cancelar() {
	window.open(urlCancel,"_top");	
}

function controlParental() {
	
	// Overlay
	var div = document.createElement("div");
	$(div).addClass("cp_overlay");
	$(div).attr("id","cp_overlay");
	$(div).html("qsd");
	$(div).css({
		height : 4000
	});
	
	$(document.body).append(div);
	
	// Texto
	
	var div = document.createElement("div");
	$(div).load(urlBase+"controlParental.php",function() {
		
		$(div).css({
			
			zIndex : 1000,
			backgroundColor: "yellow",
			position : "absolute",
			left : "50%",
			top : "50%"
		});
		
		
		var table = document.createElement("table");
		$(table).html("<tr><td style='vertical-align:middle;text-align:center;'>"+$(div).html()+"</td></tr>");
		$(table).css({
			width : "100%",
			height : "100%",
			position : "absolute",
			zIndex : "1000",
			left : 0,
			top : 0
			
		});
		$(table).attr("id","cp_html");
		$(document.body).append(table);
		
		
	});
	
	
	
	
}

/**
 * Parsea una cadena en json y devuelve el objeto
 * @return obj
 */
String.prototype.parseJSon = function(){
    try {
        eval("obj = "+this+";");
        return obj;
    } 
    catch (err) {
        return {};
    }
    
};




