/**
 * @author Fernando Reig Aparicio
 * @copyright 2006
*/
	
	/**
	 * Dado el campo de un NIF se comprueba que se hayan puesto los 8 digitos del mismo y 
	 * en caso contrario se añaden 0 por la izquierda hasta llegar
	 * @param  HTMLInputElement campoNIF
	 */
	function corregirNIF(campoNIF){
		var nif = campoNIF.value;
		
		var r = /^([0-9]+)\-?([a-zA-Z])/;
		if (r.test(nif)){
			r.exec(nif);
			var num = new String(RegExp.$1);
			var letra = new String(RegExp.$2);
			
			nif = num+letra;
			while(nif.length<9){
				nif = "0"+nif;
			}
		}
		campoNIF.value = nif.toUpperCase();
	}
	
	function eliminarSeleccion(formu, nameSeleccion, seguridad, mensajeSeguridad){
		if (!haySeleccionados(nameSeleccion)){
			alert('Debe seleccionar antes los elementos a eliminar');
			return false;
		}
		if (seguridad)
		{
			var codigo = "ACEPTO";

			if (typeof(seguridad)=="string")
				codigo = seguridad;
			var mensaje = "¿Está seguro de querer eliminar todos los elementos seleccionados?";
			if (typeof(mensajeSeguridad)!="undefined" && mensajeSeguridad!="")
				mensaje = mensajeSeguridad;
			var s = prompt(mensaje + "\n"+ 
				"Teclee \""+codigo+"\" (sensible a mayúsculas) sin las comillas para continuar.","");
			if (s == null)
				return false;
			if (s != codigo)
			{
				alert("Palabra de confirmación errónea.");
				return  false;
			}
		}
		else
		if (!confirm("¿Está seguro de querer eliminar todos los elementos seleccionados?")){
			return false;
		}
	
		formu.accion.value='eliminar';
		if (Refresh && Refresh.submitForm)
			Refresh.submitForm(formu);
		else
			formu.submit();
	}
	
	function e_marcarCheckboxGeneral(event){
		var e;
		if (navigator.isIExplorer()){
			e = event.srcElement;
		}else{
			e = event.target;
		}
		(e.checked)?addCSSClass(getParentNode(e, 'tr'), 'seleccionado'):removeCSSClass(getParentNode(e,'tr'),'seleccionado');
		
		e = document.getElementById('chkTodos');
		var v = document.getElementsByName('seleccion');
		for (var i=0; i<v.length; i++){
			if (!v[i].checked){
				e.checked = false;	
				return true;
			}
		}
		e.checked = true;
	}

    var bTextareaWasTinyfied = false; //this should be global, could be stored in a cookie...
    function setTinyMCE(sEditorID) {
        var oEditor = document.getElementById(sEditorID);
        if(oEditor && !bTextareaWasTinyfied) {
            tinyMCE.execCommand('mceAddControl', true, sEditorID);
            bTextareaWasTinyfied = true;
        }
        return;
    }
    function unsetTinyMCE(sEditorID) {
        var oEditor = document.getElementById(sEditorID);
        if(oEditor && bTextareaWasTinyfied) {
            tinyMCE.execCommand('mceRemoveControl', true, sEditorID);
            bTextareaWasTinyfied = false;
        }
        return;
    }
	
	function enviarSeleccion(formu, nameSeleccion, accion, mensajeSeleccionar, mensajeConfirmacion){
		if (!haySeleccionados(nameSeleccion)){
			alert(mensajeSeleccionar);
			return false;
		}
		if (!confirm(mensajeConfirmacion)){
			return false;
		}
	
		formu.accion.value=accion;
		if (Refresh && Refresh.submitForm)
			Refresh.submitForm(formu);
		else
			formu.submit();
	}
	
	function unidadesSeleccionadas(formu){
		var v = formu.elements;
		
		for(var i=0; i<v.length; i++){
			if ((/^c[0-9]+::t[0-9]+$/.test(v[i].name)) && (parseInt(v[i].value)>0))
				return true;
		}
		
		return false;
	}
	
	//se espera un objeto asi: {existe: bool (si existe ya un archivo con el mismo nombre), idfile:string (id del control file del formulario)}
	function handlerComprobarExisteArchivo(o){
		var e;
		if (o.existe){
			alert("Ya existe otro archivo con el mismo nombre en el directorio del servidor.\n Seleccione otro archivo si no desea sobreescribir el actual.")
			e = document.getElementById(o.idfile);
			if(e){
				e.value = '';
			}
		}
	}
	
	function comprobarExisteArchivo(idfile, path, archivo){
		if  (typeof(myajax_js)=="undefined")
		{
			alert('ERROR: Debe incruirse la librería javascript myajax.js.');
			return false;
		}
		
		if (archivo=='')
			return false;
		else{
			var i = archivo.lastIndexOf('/');
			if (i==-1)
				i = archivo.lastIndexOf('\\');
			if (i>-1)
				archivo = archivo.substring(i+1);

			if (path.charAt(path.length-1)!='/')
				path += '/';
			archivo = path+archivo;
		}

		var x = new MyAjax('get', 'file_exists.asp', true, handlerComprobarExisteArchivo, 'idfile='+idfile+'&file='+archivo, MyAjax.RESPONSE_OBJECT); 
		x.send();
	}
	
	function cambiarMarca(marca_id)
	{
		var formu = document.getElementById('formVisualizarProductos');
		if (formu)
		{
			formu.marca_id.value = marca_id;
			formu.submit();
		}
		else
		{
			location.href='categorias.asp?marca_id='+marca_id;
		}
	}

	function cambiarCategoria(cat_id)
	{
		var formu = document.getElementById('formVisualizarProductos');
		if (formu)
		{
			formu.cat_id.value = cat_id;
			formu.submit();
		}
		else
		{
			location.href='categorias.asp?cat_id='+cat_id;
		}
	}