
	/**
	*
	*	CRX LTDA
	*
	**/
	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;
		}
	 
	}
	
	
	/**
	 * Concatenates the values of a variable into an easily readable string
	 * by Matt Hackett [scriptnode.com]
	 * @param {Object} x The variable to debug
	 * @param {Number} max The maximum number of recursions allowed (keep low, around 5 for HTML elements to prevent errors) [default: 10]
	 * @param {String} sep The separator to use between [default: a single space " "]
	 * @param {Number} l The current level deep (amount of recursion). Do not use this parameter: it"s for the function"s own use
	 */
	function print_r(x, max, sep, l) {
		l = l || 0;
		max = max || 10;
		sep = sep || " ";
		if (l > max) {
			return "[WARNING: Too much recursion]\n";
		}
		var
			i,
			r = "",
			t = typeof x,
			tab = "";
		if (x === null) {
			r += "(null)\n";
		} else if (t == "object") {
			l++;
			for (i = 0; i < l; i++) {
				tab += sep;
			}
			if (x && x.length) {
				t = "array";
			}
			r += "(" + t + ") :\n";
			for (i in x) {
				try {
					r += tab + "[" + i + "] : " + print_r(x[i], max, sep, (l + 1));
				} catch(e) {
					return "[ERROR: " + e + "]\n";
				}
			}
		} else {
			if (t == "string") {
				if (x == "") {
					x = "(empty)";
				}
			}
			r += "(" + t + ") " + x + "\n";
		}
		alert(r);
		return r;
	};
	var_dump = print_r;
	
	function unserialize(data){
	// http://kevin.vanzonneveld.net
	// +		 original by: Arpad Ray (mailto:arpad@php.net)
	// +		 improved by: Pedro Tainha (http://www.pedrotainha.com)
	// +		 bugfixed by: dptr1988
	// +			revised by: d3x
	// +		 improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// %						note: We feel the main purpose of this function should be to ease the transport of data between php & js
	// %						note: Aiming for PHP-compatibility, we have to translate objects to arrays 
	// *			 example 1: unserialize("a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}");
	// *			 returns 1: ["Kevin", "van", "Zonneveld"]
	// *			 example 2: unserialize("a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}");
	// *			 returns 2: {firstName: "Kevin", midName: "van", surName: "Zonneveld"}
		var error = function (type, msg, filename, line){throw new window[type](msg, filename, line);};
		var read_until = function (data, offset, stopchr){
			var buf = [];
			var chr = data.slice(offset, offset + 1);
			var i = 2;
			while(chr != stopchr){
				if((i+offset) > data.length){
					error("Error", "Invalid");
				}
				buf.push(chr);
				chr = data.slice(offset + (i - 1),offset + i);
				i += 1;
			}
			return [buf.length, buf.join("")];
		};
		var read_chrs = function (data, offset, length){
			buf = [];
			for(var i = 0;i < length;i++){
				var chr = data.slice(offset + (i - 1),offset + i);
				buf.push(chr);
			}
			return [buf.length, buf.join("")];
		};
			var _unserialize = function (data, offset){
			 if(!offset) offset = 0;
			 var buf = [];
			 var dtype = (data.slice(offset, offset + 1)).toLowerCase();
			 
			 var dataoffset = offset + 2;
			 var typeconvert = new Function("x", "return x");
			 var chrs = 0;
			 var datalength = 0;
			 
			 switch(dtype){
				case "i":
				 typeconvert = new Function("x", "return parseInt(x)");
				 var readData = read_until(data, dataoffset, ";");
				 var chrs = readData[0];
				 var readdata = readData[1];
				 dataoffset += chrs + 1;
				break;
				case "b":
				 typeconvert = new Function("x", "return (parseInt(x) == 1)");
				 var readData = read_until(data, dataoffset, ";");
				 var chrs = readData[0];
				 var readdata = readData[1];
				 dataoffset += chrs + 1;
				break;
				case "d":
				 typeconvert = new Function("x", "return parseFloat(x)");
				 var readData = read_until(data, dataoffset, ";");
				 var chrs = readData[0];
				 var readdata = readData[1];
				 dataoffset += chrs + 1;
				break;
				case "n":
				 readdata = null;
				break;
				case "s":
				//CRX 2009 LOS CHARS UTF VALEN * 2
				var ccount = read_until(data, dataoffset, ":");
				var chrs = ccount[0];
				var stringlength = ccount[1];
				dataoffset += chrs + 2;
				
				var readData = read_chrs(data, dataoffset+1, parseInt(stringlength));
				var chrs = readData[0];
				var readdata = readData[1];
				dataoffset += chrs + 2;
				if(chrs != parseInt(stringlength) && chrs != readdata.length){
				error("SyntaxError", "String length mismatch");
				}
				break;
				case "a":
				 var readdata = {};
				 
				 var keyandchrs = read_until(data, dataoffset, ":");
				 var chrs = keyandchrs[0];
				 var keys = keyandchrs[1];
				 dataoffset += chrs + 2;
				 
				 for(var i = 0;i < parseInt(keys);i++){
					var kprops = _unserialize(data, dataoffset);
					var kchrs = kprops[1];
					var key = kprops[2];
					dataoffset += kchrs;
					
					var vprops = _unserialize(data, dataoffset);
					var vchrs = vprops[1];
					var value = vprops[2];
					dataoffset += vchrs;
					
					readdata[key] = value;
				 }
				 
				 dataoffset += 1;
				break;
				default:
				 error("SyntaxError", "Unknown / Unhandled data type(s): " + dtype);
				break;
			 }
			 return [dtype, dataoffset - offset, typeconvert(readdata)];
			};
		return _unserialize(data, 0)[2];
	}
	
	function Escribeme( campo ) {
		gId(campo).readOnly = false;
		gId(campo).focus();
	}
	
	function gId(element) {
		if (!document.getElementById(element)) {
			alert("Error al traer elemento:\n"+ element);
			return false;
		}
		return document.getElementById(element);
	}
	

	function IsNumero(sText) {
	   var ValidChars = "0123456789.";
	   var IsNumber=true;
	   var Char;

	 
	   for (i = 0; i < sText.length && IsNumber == true; i++) 
		  { 
		  Char = sText.charAt(i); 
		  if (ValidChars.indexOf(Char) == -1) 
			 {
			 IsNumber = false;
			 }
		  }
	   return IsNumber; 
	}
	
	function IsNumeric(sText) {
		/*
		var ValidChars = "0123456789.";
		var IsNumber=true;
		var Char;
		for (i = 0; i < sText.length && IsNumber == true; i++) { 
			Char = sText.charAt(i); 
			if (ValidChars.indexOf(Char) == -1) {
				IsNumber = false;
			}
		}
		return IsNumber;
		*/
		return (parseInt(sText)==sText-0);
	}

	function replaceHtml(el, html) {
		if (html == "") {html ="<!-- IE FIX -->"};
		if (el != null) {
			var oldEl = (typeof el === "string" ? gId(el) : el);
			var newEl = document.createElement(oldEl.nodeName);
			// Preserve the elements id and class (other properties are lost)
			newEl.id = oldEl.id;
			newEl.className = oldEl.className;
			// Replace the old with the new
			newEl.innerHTML = html;
			oldEl.parentNode.replaceChild(newEl, oldEl);
		}
		/* Since we just removed the old element from the DOM, return a reference
		to the new element, which can be used to restore variable references. */
		return newEl;
	}

	function IsMobile() {
		var is_firefox = /firefox/.test( navigator.userAgent.toLowerCase() );
	}
	function ExtraeDato(pagina , url) {
			inicio = pagina.indexOf("<crx>");
			fin = pagina.lastIndexOf("</crx>");
			if (inicio >=0 ) {
				dato = pagina.substring(inicio + 5 , fin );
				return ( dato );
			} else {
				alert ("Error al extraer datos\n(" + url + ")");
				return "";
			}
	}

	function getXMLHttp() {
		var xmlHttp
		try {
			//Firefox, Opera 8.0+, Safari
			xmlHttp = new XMLHttpRequest();
		}
		catch(e) {
			//Internet Explorer
			try {
				xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
			}
			catch(e) {
				try {
					xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
				}
				catch(e) {
					alert("Su Navegador no soporta AJAX!")
					return false;
				}
			}
		}
		return xmlHttp;
	}
	
	function micontroller() {
		str = Ccontroller;
		str = str.slice(0,1).toUpperCase() + str.slice(1);
		l = String(str).length - 1;
		str = String(str).substring(0,l);
		return str
	}


	function normaliza(n_action, global) {
		global = (typeof global == 'undefined') ? false : global;
		//normaliza una direccion por ejemplo si es sitio/app/controller/edit/33 0 .../add la accion actual entrega /app/controller/
		//solo sirve para acciones con parametros opcionales (edit - add)
		direccion = location.href;
		n_adireccion = direccion.split("/");
		n_prefijo = n_adireccion[0];
		n_webroot =  Cwebroot + "/";
		n_controller =  Ccontroller + "/";
		if ( ( n_prefijo == "http:" ) || ( n_prefijo == "https:" ) ) {
			n_sitio = n_prefijo + "//" + n_adireccion[2] + "/";
			final = "";
			if (global == true) {
				final = n_sitio + n_webroot + n_action;
			} else {
				final = n_sitio + n_webroot + n_controller + n_action;
			}
			return final;
		} else {
			alert("Error al normalizar la dirección\n" + direccion)
			return pagina;
		}
	}
	function redirect(url){
		url = normaliza(url, true);
		window.location = url;
	}
	function FunctionAjax(url, global) {
		//Llama a php y trae el dato listo para javascript
		// DATO <crx>datos serializados</crx>
		global = (typeof global == 'undefined') ? false : global;
		var xmlHttp = getXMLHttp();
		url = normaliza(url, global);
		xmlHttp.open("POST", url , false);
		xmlHttp.send(null);
		return eval('(' + ExtraeDato(xmlHttp.responseText , url) + ')');
	}
	
	function CheckInt(Val) {
			//Verifica si una variable es entera
		if (Val != parseInt(Val)) {
			return false;
		} else {
			return true;
		}
	}
	
	function CheckFloat(Val) {
			//Verifica si una variable es entera
		if (Val != parseFloat(Val)) {
			return false;
		} else {
			return true;
		}
	}

	function ForceInt(Val) {
			//fuerza una variable a entero, retorna cero si es erroneo.
		if (Val != parseInt(Val)) {
			return 0;
		} else {
			return Val;
		}
	}

	function ProcedureAjax(url,global) {
		global = (typeof global == 'undefined') ? false : global;
		//Ejecuta php sin retorno
		var xmlHttp = getXMLHttp();
		xmlHttp.open("POST", normaliza(url,global), false);
		xmlHttp.send(null);
		return true;
	}

	function HtmlAjax(url, global) {
		//Retorna html puro entre los div <crx></crx>
		global = (typeof global == 'undefined') ? false : global;
		var xmlHttp = getXMLHttp();
		xmlHttp.open("POST", normaliza(url, global), false);
		xmlHttp.send(null);
		return ExtraeDato(xmlHttp.responseText , url);
	}

	function DivAjax(url, div, global) {
		//Reemplaza un div con el html de php
		global = (typeof global == 'undefined') ? false : global;
		ret = HtmlAjax( url, global );
		replaceHtml( div, ret );
		//var is_chrome = /chrome/.test( navigator.userAgent.toLowerCase() );
		//var is_msie = /msie/.test( navigator.userAgent.toLowerCase() );
		//var is_safari = /safari/.test( navigator.userAgent.toLowerCase() );
		var is_firefox = /firefox/.test( navigator.userAgent.toLowerCase() );
		if (is_firefox) {
			var is_firefox3 = /3./.test( navigator.userAgent.toLowerCase() );
		} else {
			var is_firefox3 = false;
		}
		if (!is_firefox3) {parseScript( ret );};
		return true;
	}
	
	function HtmlAjax2(url) {
		//Retorna html puro entre los div <crx></crx>
		var xmlHttp = getXMLHttp();
		xmlHttp.open("POST", normaliza(url), false);
		xmlHttp.send(null);
		return xmlHttp.responseText;
	}

	function DivAjax2(url, div) {
		//Reemplaza un div con el html de php
		replaceHtml( div, HtmlAjax2( url ) )
	}
	
	function number_format( number, decimals, dec_point, thousands_sep ) {
		var n = number, prec = decimals;
		n = !isFinite(+n) ? 0 : +n;
		prec = !isFinite(+prec) ? 0 : Math.abs(prec);
		var sep = (typeof thousands_sep == "undefined") ? ',' : thousands_sep;
		var dec = (typeof dec_point == "undefined") ? '.' : dec_point;

		var s = (prec > 0) ? n.toFixed(prec) : Math.round(n).toFixed(prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;

		var abs = Math.abs(n).toFixed(prec);
		var _, i;

		if (abs >= 1000) {
				_ = abs.split(/\D/);
				i = _[0].length % 3 || 3;

				_[0] = s.slice(0,i + (n < 0)) +
							_[0].slice(i).replace(/(\d{3})/g, sep+'$1');

				s = _.join(dec);
		} else {
				s = s.replace('.', dec);
		}

		return s;
	}


	
	function ToRut(numero) {
		aux = numero;
		ddv = "X";
		factor = 2;
		suma = 0;
		while (aux != 0) {
			digito = aux % 10;
			suma = suma + factor * digito;
			aux/= 10;
			factor++;
			if (factor == 8) factor = 2;
		}
		ddv = parseInt(11 - (suma % 11));
		if (ddv == 10) ddv = "K";
		if (ddv == 11) ddv = "0";
		if (numero != '') return number_format(numero, 0, ",", ".") + "-" + ddv;
	}
	
	//FUNCIONES DE INDEX
	function Ordena(campo) {
		DivAjax( "ordena/" + campo , gId("ResultadoDiv") );
	}

	function CambiaLimite() {
		limite = gId("Limite").value;
		limite = parseInt(limite);
		limite = limite.toString();
		if ( (limite == gId("Limite").value) && (limite >= 0) ) {
			//DivAjax( "inicio" , gId("ResultadoDiv") );
			DivAjax( "cambialimite/"+limite , gId("ResultadoDiv") );
		} else {
			alert("Limite No Valido");
		}
	}
	
	function CambiaPagina() {
		pagina = gId("PaginaActual").value;
		pagina = parseInt(pagina);
		pagina = pagina.toString();
		if ( (pagina == gId("PaginaActual").value) && (pagina > 0) ) {
			DivAjax( "cambiapagina/"+pagina , gId("ResultadoDiv") );
		} else {
			alert("Pagina No Valida");
		}
	}

	function Siguiente() {
		DivAjax( "siguiente" , gId("ResultadoDiv") );
	}

	function Previo() {
		DivAjax( "previo" , gId("ResultadoDiv") );
	}

	function Inicio() {
		DivAjax( "inicio" , gId("ResultadoDiv") );
	}

	function Final() {
		DivAjax( "fin" , gId("ResultadoDiv") );
	}
	
	function AcompleteAll(name) {
		$(name).value = '*';
		$(name+'Id').value = '';
		$(name).focus();
		LlamaEvento($(name),'keydown');
	}
	
	function AcompleteEdit(name,id,value) {
		
		gId(name+'Id').value = id;
		gId(name).value = value;
		gId(name+'Check').value = value;
	}
	
	function AcompleteClean(name) {
		gId(name).value = '';
		gId(name+'Id').value = '';
		LlamaEvento(gId(name),'blur');
		gId(name).focus();
	}
	
	function ActualizaDv(prefijo,strrut) {
		if (strrut > 0) {
			var arut = new Array(8);
			var i, j, dv;
			for (i=1; i<9;i++) {
				arut[i]=0; 
			}
			
			i=0;
			for (j = (9-(strrut.length)); j<9;j++) {
				if (( strrut.substr(i,1) >= 0) & ( strrut.substr(i,1) <= 9)) {
					arut[j] = strrut.substr(i,1); i++; 
				} else { 
					
					i=0; 
					break; 
				}
			}
				
			if (i>0) {
				dv = 11 - (( (arut[1]*3) + (arut[2]*2) + (arut[3]*7) + (arut[4]*6) + (arut[5]*5) + (arut[6]*4) + (arut[7]*3) + (arut[8]*2) )%11)
				if (dv === 10) {
					dv = "K"; 
				} else if (dv === 11) {
					dv = "0"; 
				}
				
				gId(prefijo+"Dv").value=dv
			}
		} else {
			gId(prefijo+"Dv").value=""
		}
	}

	function FocoSig(idBuscado) {
		var els = document.forms[0].elements; 
		f=0;
		for(i=0; i<els.length; i++){ 	
			if (f == 1) {
				els[i].focus;
				if (els[i].type == "text") {
					els[i].focus;
					break;
				}
			}
			if (els[i].id == idBuscado) {
				f=1;
			}
		}
	}
	
	function MenuIE6() {
		var ieversion=/*@cc_on function(){ switch(@_jscript_version){ case 1.0:return 3;
		case 3.0:return 4;case 5.0:return 5; case 5.1:return 5; case 5.5:return 5.5;
		case 5.6:return 6; case 5.7:return 7; }}()||@*/0;

		/* Si es Internet Explorer 6 */
		if (ieversion == 6) {
			/*pngfix();
			//pngfix();
			/* Código para IE 6, podemos importar por ejemplo un stilo css esclusivo */
			/*document.write('<style type="text/css"> @import url("stilo-ie6.css");</style>');*/
			/*if (document.all&&document.getElementById) {
				navRoot = document.getElementById("navcrx");
				if (navRoot != null) {
					for (i=0; i<navRoot.childNodes.length; i++) {
						node = navRoot.childNodes[i];
						if (node.nodeName=="LI") {
							node.onmouseover=function() {
								this.className+=" over";
							}
							node.onmouseout=function() {
								this.className=this.className.replace(" over", "");
							}
						}
					}
				}
			}*/
			alert("CRX ERP Requiere Internet Explorer 7 o Superior.");
		}
	}
	
	function ControlFoco() {
		//Pone foco en el primero
		var topSearchElement = document.getElementById("searchtermTopForm");
		var e = $A(document.getElementsByTagName("*")).find(function(e) {
		return (((e.tagName.toUpperCase() == "INPUT" && (e.type == "text" || e.type == "password")) || e.tagName.toUpperCase() == "TEXTAREA" || e.tagName.toUpperCase() == "SELECT") && (e != topSearchElement)) ;	});
		if (e) e.focus();
		//Mueve foco al siquiente en los Dv
		test = document.forms[0];
		if (test != null) {
			var idx = 0, el, els = document.forms[0].elements;
				while (el = els.item(idx++))
				if (el.id == "Dv")
					{
						el.nextIdx = idx;
						el.onfocus = function()
							{
								this.form.elements[this.nextIdx].focus();
							}
					}
				el = els[idx-2];
				
				if (el != null) {
					if (el.readOnly) el.nextIdx = 0;
				}
		}
	}
	
	function LlamaEvento(element,event){
		if (document.createEventObject){
			// dispatch for IE
			var evt = document.createEventObject();
			return element.fireEvent('on'+event,evt)
		} else {
			// dispatch for firefox + others
			var evt = document.createEvent("HTMLEvents");
			evt.initEvent(event, true, true ); // event type,bubbling,cancelable
			return !element.dispatchEvent(evt);
		}
	}
	
	function RedondeoEsquinas() {
		var ieversion=/*@cc_on function(){ switch(@_jscript_version){ case 1.0:return 3;
		case 3.0:return 4;case 5.0:return 5; case 5.1:return 5; case 5.5:return 5.5;
		case 5.6:return 6; case 5.7:return 7; }}()||@*/0;

		/* Si es Internet Explorer 6 */
		if (ieversion==6 || ieversion==7) {
			var settings = {
			tl: { radius: 4 },
			tr: { radius: 4 },
			bl: { radius: 4 },
			br: { radius: 4 },
			antiAlias: true
			};

				/*
				Usage:

				curvyCorners(settingsObj, selectorStr);
				curvyCorners(settingsObj, Obj1[, Obj2[, Obj3[, . . . [, ObjN]]]]);

				selectorStr ::= complexSelector [, complexSelector]...
				complexSelector ::= singleSelector[ singleSelector]
				singleSelector ::= idType | classType
				idType ::= #id
				classType ::= [tagName].className
				tagName ::= div|p|form|blockquote|frameset // others may work
				className : .name
				selector examples:
				  #mydiv p.rounded
				  #mypara
				  .rounded
				*/
		curvyCorners(settings, "fieldset");
		curvyCorners(settings, "actions LI");
		}
	}
	
	function AutoCompletar(campo, accion){

		new Ajax.Autocompleter( campo , campo + "_autoComplete", accion, {afterUpdateElement:function(text, li){gId(campo+"Id").value = li.id;gId(campo+"Check").value = text.value;}});
		
		
		Event.observe(campo, "blur", function (event){
					 var element = Event.element(event);
					 if(gId(element.id).value != gId(campo+"Check").value){
						gId(element.id).value = "";
						gId(campo+"Id").value = "";
						gId(campo+"Check").value = "";
					}
				}
				);
		Event.observe(campo, "keyup", function (event){
					var element = Event.element(event);
					if(gId(element.id).value != gId(campo+"Check").value){
						gId(campo+"Id").value = "";
						gId(campo+"Check").value = "";
					}
				}
				);
	}
	
	function parseScript(_source) {
		var source = _source;
		var scripts = new Array();
		
		// Strip out tags
		while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
			var s = source.indexOf("<script");
			var s_e = source.indexOf(">", s);
			var e = source.indexOf("</script", s);
			var e_e = source.indexOf(">", e);
			
			// Add to scripts array
			scripts.push(source.substring(s_e+1, e));
			// Strip from source
			source = source.substring(0, s) + source.substring(e_e+1);
		}
		
		// Loop through every script collected and eval it
		for(var i=0; i<scripts.length; i++) {
			try {
				eval(scripts[i]);
			}
			catch(ex) {
				// do what you want here when a script fails
			}
		}
		
		// Return the cleaned source
		return source;
	}
	
	function pngfix(){
		var clear="./img/clear.gif"; //path to clear.gif
		var els=document.getElementsByTagName('*');
		var ip=/\.png/i;
		var i=els.length;
		while(i-- >0){
			var el=els[i];
			var es=el.style;
			if(el.src&&el.src.match(ip)&&!es.filter){
				es.height=el.height;
				es.width=el.width;
				es.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+el.src+"',sizingMethod='crop')";
				el.src=clear;
			} else {
				var elb=el.currentStyle.backgroundImage;
				if(elb.match(ip)){
					var path=elb.split('"');
					var rep=(el.currentStyle.backgroundRepeat=='no-repeat')?'crop':'scale';
					es.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+path[1]+"',sizingMethod='"+rep+"')";
					es.height=el.clientHeight+'px';es.backgroundImage='none';
					var elkids=el.getElementsByTagName('*');
					if (elkids){
						var j=elkids.length;
						if(el.currentStyle.position!="absolute")es.position='static';
						while (j-- >0)if(!elkids[j].style.position)elkids[j].style.position="relative";
					}
				}
			}
		}
	}
	
	
	/*FUNCIONES DE LOS EDIT*/
	
	function Desbloquear() {
		BloqueaDivs("Name","Referencia");
		if (document.getElementById("Referencia")) ActivaDrop("Referencia");
	}

	function Bloquear() {
		DesbloqueaDivs("Name","Referencia","SINREF");
		if (document.getElementById("Referencia")) DesactivaDrop("Referencia");
	}
	
	
	function ActivaDrop(campo){
		ancho = gId(campo).style.width.substr(0,gId(campo).style.width.length-1);
		ancho = parseInt(ancho) - 4;
		ancho = ancho + "%";
		gId(campo).style.width= ancho;
		gId("Drop"+campo).style.display="";
	}
	
	function DesactivaDrop(campo){
		ancho = gId(campo).style.width.substr(0,gId(campo).style.width.length-1);
		ancho = parseInt(ancho) + 4;
		ancho = ancho + "%";
		gId(campo).style.width= ancho;
		gId("Drop"+campo).style.display="none";
	}
	
	function DesbloqueaDivs(campo,campoasoc,defval){
		gId("Bloqueado").value="0";
		gId("DesbloquearDiv").style.display="";
		gId("BloquearDiv").style.display="none";
		gId(campo+"Div").style.display="none";
		gId("Free"+campo+"Div").style.display="inline";
		gId("Free"+campo+"Div").style.clear="none";
		gId("Free"+campo+"Div").value="";
		if (document.getElementById(campoasoc)) {
			gId(campo+"Id").value="0";
			gId(campo+"Check").value="0";
			gId(campo).value="";
		}
		if (document.getElementById(campoasoc)) {
			gId(campoasoc).value=defval;
			gId(campoasoc).disabled=true;
			gId(campoasoc+"Id").value="0";
			gId(campoasoc+"Check").value="0";
		}
	}
	
	function BloqueaDivs(campo,campoasoc){
		gId("Bloqueado").value="1";
		gId("DesbloquearDiv").style.display="none";
		gId("BloquearDiv").style.display="";
		gId(campo+"Div").style.display="";
		gId("Free"+campo+"Div").style.display="none";
		gId("Free"+campo+"Div").value="";
		if (document.getElementById(campoasoc)) {
			gId(campoasoc).value=""
			gId(campoasoc).disabled=false;
		}
	}
	
	function CambioCliente() {
		controller = micontroller();
		cliente_id=gId("ClienteId").value;
		cliente_id=parseInt(cliente_id);
		if (cliente_id > 0) {
			rarreglo = FunctionAjax("clientes/cambiocliente/" + cliente_id,true);
			gId(controller+"ClienteId").value=rarreglo[0]["Cliente"]["id"];
			gId(controller+"Clientename").value=rarreglo[0]["Cliente"]["name"];
			gId(controller+"Rut").value=rarreglo[0]["Cliente"]["rut"];
			gId(controller+"Giro").value=rarreglo[0]["Cliente"]["giro"];
			gId(controller+"Direccion").value=rarreglo[0]["Cliente"]["direccion"];
			gId(controller+"Ciudad").value=rarreglo[0]["Cliente"]["ciudad"];
			gId(controller+"Comuna").value=rarreglo[0]["Comuna"]["name"];
			gId(controller+"Telefono").value=rarreglo[0]["Cliente"]["telefono"];
			if ( $(controller+"Formapagoname") ) {
				gId(controller+"Formapagoname").value=rarreglo[0]["Formapago"]["name"];
				gId("FormapagoCheck").value=rarreglo[0]["Formapago"]["name"];
				gId("Formapago").value=rarreglo[0]["Formapago"]["name"];
				gId("FormapagoId").value=rarreglo[0]["Formapago"]["id"];
			}
		} else {
			gId(controller+"Giro").value="";
			gId(controller+"Direccion").value="";
			gId(controller+"Ciudad").value="";
			gId(controller+"Comuna").value="";
			gId(controller+"Telefono").value="";
			if ( $(controller+"Formapagoname") ){
				//gId(controller+"Formapagoname").value="";
				//gId("Formapago").value="";
				//gId("FormapagoCheck").value="";
				//gId("FormapagoId").value="";
			}
		}
	} 
	
	function CambioContacto() {
		controller = micontroller();
		contacto_id=gId("ContactoId").value;
		contacto_id=parseInt(contacto_id);
		if (contacto_id > 0) {
			rarreglo = FunctionAjax("cambiocontacto/" + contacto_id);
			gId(controller+"Contactoname").value=rarreglo[0]["Contacto"]["name"];
		} else {
			gId(controller+"Contactoname").value="";
		}
	} 
	

	
	
	
	function Ndireccion(type) {
		controller = micontroller();
		if (type == "clientes") {
			tabla_id=gId("ClienteId").value;
		} else {
			tabla_id=gId("ProveedoreId").value;
		}
		if (tabla_id != "") {
			gId("DireccionIndex").value = parseInt(gId("DireccionIndex").value) + 1;
			direccion_index=gId("DireccionIndex").value;
			rarreglo = FunctionAjax("../" + type + "/cdireccion/" + tabla_id + "/" + direccion_index);
			gId(controller+"Direccion").value=rarreglo["direccion"];
			gId(controller+"Ciudad").value=rarreglo["ciudad"];
			gId(controller+"Comuna").value=rarreglo["comuna"];
			gId(controller+"Telefono").value=rarreglo["telefono"];
			total=rarreglo["total"];
			if (direccion_index < 0) {
				gId("DireccionIndex").value=total;
			}
			if (direccion_index > total) {
				gId("DireccionIndex").value=0;
			}
		}
	} 
	
	function Pdireccion(type) {
		controller = micontroller();
		if (type == "clientes") {
			tabla_id=gId("ClienteId").value;
		} else {
			tabla_id=gId("ProveedoreId").value;
		}
		if (tabla_id != "") {
			gId("DireccionIndex").value = parseInt(gId("DireccionIndex").value) - 1;
			direccion_index=gId("DireccionIndex").value;
			rarreglo = FunctionAjax("../" + type + "/cdireccion/" + tabla_id + "/" + direccion_index);
			gId(controller+"Direccion").value=rarreglo["direccion"];
			gId(controller+"Ciudad").value=rarreglo["ciudad"];
			gId(controller+"Comuna").value=rarreglo["comuna"];
			gId(controller+"Telefono").value=rarreglo["telefono"];
			total=rarreglo["total"];
			if (direccion_index < 0) {
				gId("DireccionIndex").value = total;
			}
			if (direccion_index > total) {
				gId("DireccionIndex").value=0;
			}
		}
	} 
	
	function CambioProveedore() {
		controller = micontroller();
		Proveedore_id=gId("ProveedoreId").value;
		if (Proveedore_id != "") {
			rarreglo = FunctionAjax("cambioproveedore/" + Proveedore_id);
			gId(controller+"ProveedoreId").value=rarreglo[0]["Proveedore"]["id"];
			gId(controller+"Proveedorename").value=rarreglo[0]["Proveedore"]["name"];
			gId(controller+"Rut").value=rarreglo[0]["Proveedore"]["rut"];
			gId(controller+"Giro").value=rarreglo[0]["Proveedore"]["giro"];
			gId(controller+"Direccion").value=rarreglo[0]["Proveedore"]["direccion"];
			gId(controller+"Ciudad").value=rarreglo[0]["Proveedore"]["ciudad"];
			gId(controller+"Comuna").value=rarreglo[0]["Comuna"]["name"];
			gId(controller+"Telefono").value=rarreglo[0]["Proveedore"]["telefono"];
			if ( $(controller+"Formapagoname") ) {
				gId(controller+"Formapagoname").value=rarreglo[0]["Formapago"]["name"];
				gId("FormapagoCheck").value=rarreglo[0]["Formapago"]["name"];
				gId("Formapago").value=rarreglo[0]["Formapago"]["name"];
				gId("FormapagoId").value=rarreglo[0]["Formapago"]["id"];
			}
		} else {
			gId(controller+"Giro").value="";
			gId(controller+"Direccion").value="";
			gId(controller+"Ciudad").value="";
			gId(controller+"Comuna").value="";
			gId(controller+"Telefono").value="";
			if ( $(controller+"Formapagoname") ) {
				gId(controller+"Formapagoname").value="";
				gId("Formapago").value="";
				gId("FormapagoCheck").value="";
				gId("FormapagoId").value="";
			}
		}
	} 
	
	function EliminaLinea(linea) {
		controller = micontroller();
		DivAjax( "eliminalinea/" + linea , gId("ResponseLineas") );
		if(controller != 'Inventario' && controller != 'Mteorico' && controller != 'Formato' && controller != 'Voucher')
			ActualizaValores();
		if(controller == 'Mteorico')
			ActualizaMteorico();
		if(controller == 'Voucher')
			ActualizaMonto();
	}

	function CambioName() {
		controller = micontroller();
		articulo_id=gId("NameId").value;
		controller = typeof(controller) != 'undefined' ? controller : 'None';
		if(controller != 'Inventario') {
			CambioArticulo(articulo_id);
		} else {
			CambioArticuloInventario(articulo_id);
		}
	}

	function CambioReferencia() {
		controller = micontroller();
		articulo_id=gId("ReferenciaId").value;
		controller = typeof(controller) != 'undefined' ? controller : 'None';
		if(controller == 'Inventario') {
			CambioArticuloInventario(articulo_id);
		} else {
			CambioArticulo(articulo_id);
		}
	}
	
	function CambioCantidad() {
		articulo_id=gId("ReferenciaId").value;
		gId("LastArticuloId").value = -1;
		CambioArticulo(articulo_id);
	} 
	
	function CambioArticulo(id) {
		if (document.getElementById('Cantidad')) {
				cantidad = gId('Cantidad').value;
		}
		controller = micontroller();
		cantidad = typeof(cantidad) != 'undefined' ? cantidad : 1;
		if ( id != "" && gId("LastArticuloId").value != id && id > 0) {
			rarreglo = FunctionAjax("articulos/cambioarticulo/" + id + '/' + cantidad, true);
			gId("ReferenciaId").value=id;
			if ( gId("Referencia").value == '') {
				gId("ReferenciaCheck").value=rarreglo[0]["Articulo"]["referencia"];
				gId("Referencia").value=rarreglo[0]["Articulo"]["referencia"];
			}
			gId("NameId").value=id;
			if ( gId("Name").value == '' || gId("LastArticuloId").value != id) {
				gId("NameCheck").value=rarreglo[0]["Articulo"]["name"];
				gId("Name").value=rarreglo[0]["Articulo"]["name"];
			}
			if(controller != 'Otrabajo') {
				if (gId("Unitario").value ==0 || gId("LastArticuloId").value != id) {
					ActualizaUnitario(rarreglo);
				}
				ActualizaPrecios();
			}
			gId("LastArticuloId").value = id;
			ActualizaInfo();
		} else {
			if (!(id > 0)) {
				gId('info0').value = "";
				gId('info1').value = "";
				gId('info2').value = "";
			}
		}
	}
	function ActualizaInfo() {
		controller = micontroller();
		id = gId('ReferenciaId').value;
		info = FunctionAjax("articulos/infoarticulo/" + id,true);
		gId('info0').value = "ARTICULO: " + info[0]["Articulo"]["name"] + "\t REFERENCIA:" + info[0]["Articulo"]["referencia"] + "\t STOCK: " + info[0]["Articulo"]["stock"];
		gId('info1').value = "UNIDAD DE MEDIDA: " + info[0]["Medida"]["name"] + "\t EMBALAJE: " + info[0]["Embalaje"]["name"];
		if (controller != "Cimportacione") 
			gId('info2').value = "MONEDA: " + info[0]["Moneda"]["name"];
	}
	function ActualizaUnitario(rarreglo) {
			controller = micontroller();
			tmp = controller.substring(0,1);
			if (controller != "Cimportacione") {
				if ( tmp != "V" ) {
					if ( parseInt(rarreglo[0]["Articulo"]["cambio"]) == 0 && rarreglo[0]["Articulo"]["moneda_id"] != "1" ) SinCambio(rarreglo[0]["Articulo"]["moneda_id"]);
					gId("Unitario").value=(rarreglo[0]["Articulo"]["precio_compra"]);
				} else {
					if ( parseInt(rarreglo[0]["Articulo"]["cambio"]) == 0 && rarreglo[0]["Articulo"]["moneda_id"] != 1 ) SinCambio(rarreglo[0]["Articulo"]["moneda_id"]);
					gId("Unitario").value=(rarreglo[0]["Articulo"]["precio_venta"]);
				}
			} else {
				if ( rarreglo[0]["Articulo"]["moneda_id"] != gId("MonedaId").value ) {
					gId("Unitario").value=0;
				} else {
					gId("Unitario").value=(rarreglo[0]["Articulo"]["precio_importacion"]);
				}
			}
	}
	
	function SinCambio(moneda_id){
		alert ("No se ha definido el cambio para el dia de hoy, No se puede continuar");
		redirect("cambios/sincambio/" + moneda_id);
	}
	
	function CambioArticuloInventario(id) {
		controller = micontroller();
		
		if ( id != "" && gId("LastArticuloId").value != id) {
			rarreglo = FunctionAjax("articulos/cambioarticulo/" + id, true);
			gId("ReferenciaCheck").value=rarreglo[0]["Articulo"]["referencia"];
			gId("ReferenciaId").value=id;
			gId("Referencia").value=rarreglo[0]["Articulo"]["referencia"];
			gId("NameCheck").value=rarreglo[0]["Articulo"]["name"];
			gId("NameId").value=id;
			gId("Name").value=rarreglo[0]["Articulo"]["name"];
			tmp = controller.substring(0,1)

			gId("LastArticuloId").value = id;
		}
	}
		
	function CambioBodega() {
		if (gId("Bodega").readOnly == false) {
			if ( gId("BodegaId") > 0 ) {
				controller = micontroller();
				bodega_id=gId("BodegaId").value;
				bodega_id=parseInt(bodega_id);
				ret = FunctionAjax("articulos/cambiobodega/" + controller + "/" + bodega_id,true);
				if (!ret['ret']) {
					alert("La bodega no se puede cambiar si existen lineas en el documento");
					gId("Bodega").value=ret['bodega_name'];
					gId("BodegaCheck").value=ret['bodega_name'];
					gId("BodegaId").value=ret['bodega_id'];
				}
			}
		}
	} 
	
function CambioBodega2() {
		if (gId("Bodega2").readOnly == false) {
			if ( gId("Bodega2Id") > 0 ) {
				controller = micontroller();
				bodega_id=gId("Bodega2Id").value;
				bodega_id=parseInt(bodega_id);
				ret = FunctionAjax("articulos/cambiobodega/" + controller + "/" + bodega_id,true);
				if (!ret['ret']) {
					alert("La bodega no se puede cambiar si existen lineas en el documento");
					gId("Bodega2").value=ret['bodega_name'];
					gId("Bodega2Check").value=ret['bodega_name'];
					gId("Bodega2Id").value=ret['bodega_id'];
				}
			}
		}
	}

function CambioBodega3() {
		if (gId("Bodega3").readOnly == false) {
			if ( gId("Bodega3Id") > 0 ) {
				controller = micontroller();
				bodega_id=gId("Bodega3Id").value;
				bodega_id=parseInt(bodega_id);
				ret = FunctionAjax("articulos/cambiobodega/" + controller + "/" + bodega_id,true);
				if (!ret['ret']) {
					alert("La bodega no se puede cambiar si existen lineas en el documento");
					gId("Bodega3").value=ret['bodega_name'];
					gId("Bodega3Check").value=ret['bodega_name'];
					gId("Bodega3Id").value=ret['bodega_id'];
				}
			}
		}
	} 
	
	function CambiaDescripcion(nlinea) {
//			Ext.MessageBox.show({
//				title: 'Articulo',
//				msg: 'Ingrese nueva descripción:',
//				width:300,
//				buttons: Ext.MessageBox.OKCANCEL,
//				multiline: true,
//				value : gId("LineaName"+nlinea).value,
//				fn: function res(btn,text) {
//						if (btn == 'ok') {
//							controller = micontroller();
//							name = crxurlencode(text);
//							//alert(name);
//							DivAjax("articulos/cambiodescripcion/" + controller + "/" + nlinea + "/" + name  , gId("ResponseLineas") ,true);
//						}
//					}
//			});
		controller = micontroller();
		var opciones="toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=yes, width=750, height=300";
		window.open(normaliza("articulos/cambialinea/" + controller + "/" + nlinea,true),"",opciones);
	}
	
	
	function ImprimeLineas(div) {
		div = typeof(div) != 'undefined' ? div : "ResponseLineas";
		switch(div) {
			case 'ResponseLineas':  DivAjax("imprimelineas" , gId(div) ); break;
			case 'ResponseLineas2': DivAjax("imprimelineas2" , gId(div) ); break;
			case 'ResponseLineas3': DivAjax("imprimelineas3" , gId(div) ); break;
		}
	}

	function CambioFormapago() {
		controller = micontroller();
		formapago_id=gId("FormapagoId").value;
		if (formapago_id != "") {
			gId(controller+"Formapagoname").value=gId("Formapago").value;;
		} else {
			gId(controller+"Formapagoname").value="";
		}
	}
	
	function Decimal(val) {
		val = val.toString();
		val = val.replace(",",".");
		return parseFloat(val);
	}
	
	function Aprox(val) {
		//return Math.round(parseFloat(val)*100)/100;
		return Math.round(parseFloat(val));
	}
	
	function ActualizaPrecios() {
		gId("Unitario").value = gId("Unitario").value.replace(",",".");
		unitario = parseFloat(gId("Unitario").value);
		if (unitario != gId("Unitario").value) {
			unitario = 0;
		}
		
		//cantidad = parseInt(gId("Cantidad").value);
		
		cantidad = Decimal(gId("Cantidad").value);
		
		if (cantidad < 0) {
			cantidad = 0;
		}
		
		total = unitario * cantidad;
		if ( document.getElementById("Descuento") ) {
			pdescuento = parseInt(gId("Descuento").value);
			if (pdescuento.toString() == gId("Descuento").value) {
				descuento = parseInt( total * (pdescuento/100) );
			} else {
				descuento = 0;
			}
		} else {
			descuento = 0;
		}
		controller = micontroller();
		if (controller == 'Otrabajo' || controller == 'Vcotizacione' || controller == 'Cimportacione'  ) {
			gId("Total").value = total;
		} else {
			gId("Total").value = Aprox(total - descuento);
		}
	}
	
	function CambioDctoTotal() {
		controller = micontroller();
		if ( document.getElementById(controller+"Dctototal") ) {
			dctototal = gId(controller+"Dctototal").value;
			if (dctototal >= 0 && dctototal <= 100) {
				ActualizaValores();
			} else {
				gId(controller+"Dctototal").value=0;
				alert("¡El descuento no es Valido!");
			}
		}
	}

	function CambioImpuestoEspecifico() {
		controller = micontroller();
		if ( document.getElementById(controller+"Impespecifico") ) {
			if (IsNumeric(gId(controller+"Impespecifico").value)) {
				impespecifico = parseInt(gId(controller+"Impespecifico").value);
				if (impespecifico >= 0) {
					ActualizaValores();
					//gId(controller+"Total").value = parseInt(gId(controller+"Total").value) + impespecifico ;
				}
			} else {
				alert("Monto no valido");
				ActualizaValores();
				gId(controller+"Impespecifico").value = 0;
			}
		}
	}
	function Peso(nStr) {
		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 TogleExenta () {
		ProcedureAjax("/exenta");
		ActualizaValores();
	}
	
	function TogleImportaciones (inicial) {
		inicial = typeof(inicial) != 'undefined' ? inicial : false;
		if ($('ProveedoreImportaciones').checked==true) {
			$('Extranjero').style.display = "";
			$('Nacional').style.display = "none";
			$('NacionalA').style.display = "none";
			if (!inicial) {
				$('PaiseId').value="";
				$('Paise').value="";
				$('PaiseCheck').value="";
				$('ProveedoreRut').value="0";
				$('ComunaId').value="0";
				$('Comuna').value="";
				$('ComunaCheck').value="";
			}
		} else {
			$('Extranjero').style.display = "none";
			$('Nacional').style.display = "";
			$('NacionalA').style.display = "";
			if (!inicial) {
				$('ProveedoreRut').value="";
				$('ComunaId').value="";
				$('Comuna').value="";
				$('ComunaCheck').value="";
			}
		}
	}
	
	function InicializaDcto(dcto) {
		if (dcto >= 0) {
			controller = micontroller();
			gId(controller+"Dctototal").value = dcto;
		}
	}
	
	function ActualizaValores() {
		controller = micontroller();
		
		if ( document.getElementById(controller+"Dctototal") ) {
			dcto = gId(controller+"Dctototal").value;
		} else {
			dcto=0;
		}
		if ( document.getElementById(controller+"Impespecifico") ) {
			impespecifico = gId(controller+"Impespecifico").value;
			rarreglo = FunctionAjax("actualizavalores/"+dcto+"/"+impespecifico);
		} else {
			rarreglo = FunctionAjax("actualizavalores/"+dcto);
		}
		if (document.getElementById(controller+"Impespecifico") ) {
			gId(controller+"Impespecifico").value = rarreglo["impespecifico"];
		}
		if (document.getElementById(controller+"Iva") ) {
			gId(controller+"Iva").value = rarreglo["iva"];
		}
		if (document.getElementById(controller+"Neto") ) {
			gId(controller+"Neto").value = rarreglo["neto"];
		}
		if (document.getElementById(controller+"Netoexento") ) {
			gId(controller+"Netoexento").value = rarreglo["netoexento"];
		}
		if (document.getElementById(controller+"Totalme") ) {
			gId(controller+"Totalme").value = rarreglo["totalme"];
		}	
		
		if (controller != "Cimportacione") {
			gId(controller+"Total").value = rarreglo["total"];
		} else {
			gId(controller+"Total").value = rarreglo["total"];
			ActualizaImportacion();
		}
		
		if (controller == "Articulo") {
			gId(controller+"PrecioVenta").value = rarreglo["total"];
		}
	}
	
	function AgregaArticuloPopup(articulo_id,referencia,name) {
		window.opener.document.getElementById("Name").value = name;
		window.opener.document.getElementById("NameCheck").value = name;
		window.opener.document.getElementById("NameId").value = articulo_id;
		window.opener.document.getElementById("Referencia").value = referencia;
		window.opener.document.getElementById("ReferenciaCheck").value = referencia;
		window.opener.document.getElementById("ReferenciaId").value = articulo_id;
		window.close();
		window.opener.CambioArticulo(articulo_id);
		
	}
	function BuscadorArticulos() {
		var opciones="toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=800, height=400";
		window.open(normaliza("/articulos/index_buscar",true),"",opciones);
	}
	
	function CambiaPrecioMedida() {
		id = gId("ReferenciaId").value;
		if (id>0) {
			tienemedida = FunctionAjax("articulos/verificapreciomedida/" + id , true);
			if (tienemedida == false) {
				alert("El articulo, no posee factores calculables.");
				return;
			}
			
			cantidad = gId("Cantidad").value;
			rarreglo = FunctionAjax("articulos/cambioarticulo/" + id + '/' + cantidad, true);
			ActualizaUnitario(rarreglo);
			controller = micontroller();
			articulo_id=gId("NameId").value;
			rarreglo = FunctionAjax("articulos/cambioarticulo/" + articulo_id, true);
			gId("ReferenciaCheck").value=rarreglo[0]["Articulo"]["referencia"];
			gId("ReferenciaId").value=id;
			gId("Referencia").value=rarreglo[0]["Articulo"]["referencia"];
			gId("NameCheck").value=rarreglo[0]["Articulo"]["name"];
			gId("NameId").value=id;
			gId("Name").value=rarreglo[0]["Articulo"]["name"];
			var opciones="toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=yes, width=750, height=300";
			window.open(normaliza("articulos/cambiapreciomedida/"+id,true),"",opciones);
		} else {
			alert("Seleccione un articulo, primero.");
			
		}
	}
	
	function CambiaMedida() {
		id = gId("ReferenciaId").value;
		if (id>0) {
			tienemedida = FunctionAjax("articulos/verificamedida/" + id , true);
			if (tienemedida == false) {
				alert("El articulo, no posee factores.");
				return;
			}
			
			cantidad = gId("Cantidad").value;
			rarreglo = FunctionAjax("articulos/cambioarticulo/" + id + '/' + cantidad, true);
			ActualizaUnitario(rarreglo);
			controller = micontroller();
			articulo_id=gId("NameId").value;
			rarreglo = FunctionAjax("articulos/cambioarticulo/" + articulo_id, true);
			gId("ReferenciaCheck").value=rarreglo[0]["Articulo"]["referencia"];
			gId("ReferenciaId").value=id;
			gId("Referencia").value=rarreglo[0]["Articulo"]["referencia"];
			gId("NameCheck").value=rarreglo[0]["Articulo"]["name"];
			gId("NameId").value=id;
			gId("Name").value=rarreglo[0]["Articulo"]["name"];
			var opciones="toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=yes, width=750, height=300";
			window.open(normaliza("articulos/cambiamedida/"+id,true),"",opciones);
		} else {
			alert("Seleccione un articulo, primero.");
			
		}
	}
	
	function FijaMedida(medida_id) {
		ret = FunctionAjax("articulos/fijamedida/" + medida_id, true);
		window.opener.document.getElementById("Unitario").value = window.opener.document.getElementById("Unitario").value * ret['factor'];
		//window.opener.document.getElementById("Medidaid").value = medida_id;
		window.opener.ActualizaPrecios();
		window.opener.ActualizaInfo();
		window.close();
	}
	
	function LiberaMedida() {
		ProcedureAjax("articulos/liberamedida", true);
	}
	function PersonalizaLinea() {
		id = gId("ReferenciaId").value;
		if (id>0) {
			ret = FunctionAjax("/articulos/checkpersonalizar/"+id, true);
			if (ret) {
				//FIJO LOS DATOS ORIGINALES
				controller = micontroller();
				articulo_id=gId("NameId").value;
				
				
				rarreglo = FunctionAjax("articulos/cambioarticulo/" + articulo_id, true);
				gId("ReferenciaCheck").value=rarreglo[0]["Articulo"]["referencia"];
				gId("ReferenciaId").value=id;
				gId("Referencia").value=rarreglo[0]["Articulo"]["referencia"];
				gId("NameCheck").value=rarreglo[0]["Articulo"]["name"];
				gId("NameId").value=id;
				gId("Name").value=rarreglo[0]["Articulo"]["name"];
				
				
				var opciones="toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=yes, width=750, height=300";
				window.open(normaliza("/articulos/personalizar/"+id,true),"",opciones);
			} else {
				alert("La familia del articulo no es personalizable.");
			}
		} else {
			alert("Seleccione un articulo, primero.");
		}
	}
	function AgregaCliente() {
		
		var opciones="toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=yes, width=750, height=500";
		window.open(normaliza("/clientes/add/1",true),"",opciones);
	}
	function AgregaContacto() {
		
		var opciones="toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=yes, width=750, height=350";
		window.open(normaliza("/contactos/add/1",true),"",opciones);
	}
	function AgregaLinea() {
		//DEBE ESPERAR QUE EL ARTICULO SE SELECCIONE Y CALCULE
		controller = micontroller();
		if (controller != 'Voucher' && controller != 'Vouchermodelo' && controller != 'Formato' && controller != 'Inventario') {
			id = gId("ReferenciaId").value;
			if (id!="") {
				if (id > 0) {
					condecimales = FunctionAjax("articulos/condecimales/" + id, true);
				} else {
					//LAS LINEAS DE TEXT SIEMPRE PERMITEN DECIMALES
					condecimales = true;
				}
				
				gId("Cantidad").value = gId("Cantidad").value.replace(",",".");
				

				if ( IsNumero(gId("Cantidad").value) == false ) {
						alert("Debe ingresar la cantidad.");
						return;
				}
				cantidad = parseFloat(gId("Cantidad").value);
				cantidad_int = parseInt(gId("Cantidad").value);

				if (!condecimales && cantidad != cantidad_int) {
					alert("La unidad de medida no admite decimales.");
					return;
				}
				
				referencia = gId("Referencia").value;
				name = gId("Name").value; 
				
				if(document.getElementById("Bloqueado")) {
					if (gId("Bloqueado").value!="1") {
						name = gId("FreeName").value; 
					}
				}
				if (name=="") {
						alert("Debe ingresar la descripcion.");
						return;
					}
					gId("Unitario").value = gId("Unitario").value.replace(",",".");
					unitario = parseFloat(gId("Unitario").value);
					if (controller != 'Vncredito') {
						if (unitario != gId("Unitario").value) {
								alert("Debe ingresar el precio unitario.");
								return;
						}
						if (unitario < 0) {
								alert("El precio debe ser mayor o igual a cero.");
								return;
						}
					} else {
						if (unitario != gId("Unitario").value) {
							unitario = 0;
						}
					}
				if ( document.getElementById("Descuento") ) {
					descuento = parseInt(gId("Descuento").value);
					if (descuento.toString() != gId("Descuento").value) {
						alert("Error en el descuento.");
						return;
					}
					if (descuento > 100) {
						alert("El descuento no puede superar el 100%.");
						return;
					}
					if (descuento < 0) {
						alert("El descuento no puede ser inferior al 0%.");
						return;
					}
				} else {
					descuento=0;
				}
				if ( document.getElementById(controller+"Impespecifico") ) {
					impespecifico = parseInt(gId(controller+"Impespecifico").value);
				} else {
					impespecifico=0;
				}
				if (controller == 'Cimportacione' || controller == 'Otrabajo' || controller == 'Vcotizacione' ) {
					total = parseFloat(gId("Total").value);
				} else {
					total = parseInt(gId("Total").value);
				}
				
				if (controller != 'Otrabajo' && controller != 'Vncredito' && controller != 'Cfactura' && controller != 'Vcotizacione') {
					if (total.toString() != gId("Total").value || total<=0) {
							alert("Error al calcular, reintente.");
							return;
					}
				} else {
					//if (aid!=0 && ){
					//	alert("No puede ser un Articulo");
					//	return;
					//};
					gId("Total").value = gId("Total").value;
					if (total.toString() != gId("Total").value ) {
							alert("Error al calcular.");
							return;
					}
				}
			
					gId('info0').value = "";
					gId('info1').value = "";
					gId('info2').value = "";
				
				CreaLinea(id, cantidad, referencia, name.toUpperCase() , unitario, descuento, total, 0);
				ActualizaValores();
				if (document.getElementById('BodegaId') && controller != 'Produccione') {
					gId('Bodega').readOnly=true;
					gId('ControlesBodega').style.display='none';
				}
			} else {
				alert("Seleccione un articulo.");
			}
		}
		if (controller=="Voucher"){
			AgregaLineaVoucher();
		}
		if (controller=="Vouchermodelo"){
			AgregaLineaVoucherModelo();
		}
		if (controller=="Formato"){
			AgregaLineaFormato();
		}
		if (controller == 'Inventario') {
			AgregaLineaInventario();
		}
		if(controller == 'Po') {
			CambioMontoCaja();
		}
		LiberaMedida();
	}
	

	function AgregaLineaInventario() {
		//DEBE ESPERAR QUE EL ARTICULO SE SELECCIONE Y CALCULE
		controller = micontroller();
			id = gId("ReferenciaId").value;
			if (id!="") {
				gId("Cantidad").value = gId("Cantidad").value.replace(",",".");
				cantidad = parseFloat(gId("Cantidad").value);
				if (cantidad.toString() != gId("Cantidad").value) {
						alert("Debe ingresar la cantidad.");
						return;
					}
				if(gId("Cantidad").value < 0) {
					alert("La cantidad debe ser positiva.");
					return;
				}
				referencia = gId("Referencia").value;
				name = gId("Name").value; 
	
				if (name=="") {
					alert("Debe ingresar la descripcion.");
					return;
				}
							
				CreaLineaInventario(id, cantidad, referencia, name.toUpperCase() , 0);
				
				if (document.getElementById('BodegaId')) {
					gId('Bodega').readOnly=true;
					gId('ControlesBodega').style.display='none';
				}
			} else {
				alert("Seleccione un articulo.");
			}
	}

	function CreaLinea(id, cantidad, referencia, name, unitario, descuento, total, inicial) {
		name = name.replace( "/", "-");
		referencia = referencia.replace( "/", "-");
		name = crxurlencode(name);
		referencia = crxurlencode(referencia);
		if ( document.getElementById("Descuento") ) {
			DivAjax( "agregalinea/" + id + "/" + cantidad + "/" + referencia + "/" + name + "/" + unitario + "/" + descuento + "/" + total + "/" + inicial , gId("ResponseLineas") );
		} else {
			DivAjax( "agregalinea/" + id + "/" + cantidad + "/" + referencia + "/" + name + "/" + unitario + "/" + total + "/" + inicial , gId("ResponseLineas") );
		}
		
	if(document.getElementById("Bloqueado")) {

		if (gId("Bloqueado").value=="1") {
			gId("Referencia").value="";
			gId("ReferenciaCheck").value="";
			gId("ReferenciaId").value="";
		} else {
			gId("ReferenciaId").value="0";
			gId("Referencia").value="SINREF";
			gId("ReferenciaCheck").value="SINREF";
			gId("FreeName").value="";
		}
	}
		gId("ReferenciaId").value="0";
		gId("Referencia").value="";
		gId("ReferenciaCheck").value="";
		
	if(document.getElementById("Bloqueado")) {
		gId("FreeName").value="";
	}
		gId("Cantidad").value="1";
		//gId("Cantidad").focus();
		
		gId("Name").value="";
		gId("NameCheck").value="";
		gId("NameId").value="0";
		gId("Unitario").value="";
		
		if ( document.getElementById("Descuento") ) {
			gId("Descuento").value="0";
		}
		
		gId("Total").value="";gId("LastArticuloId").value = -1;
		gId("Cantidad").focus();
		
	}


	function CreaLineaInventario(id, cantidad, referencia, name, unitario, descuento, total, inicial) {
		name = name.replace( "/", "-");
		referencia = referencia.replace( "/", "-");
		name = crxurlencode(name);
		if ( document.getElementById("Descuento") ) {
			DivAjax( "agregalinea/" + id + "/" + cantidad + "/" + referencia + "/" + name + "/" + unitario + "/" + descuento + "/" + total + "/" + inicial , gId("ResponseLineas") );
		} else {
			DivAjax( "agregalinea/" + id + "/" + cantidad + "/" + referencia + "/" + name + "/" + unitario + "/" + total + "/" + inicial , gId("ResponseLineas") );
		}
			gId("Referencia").value="";
			gId("ReferenciaCheck").value="";
			gId("ReferenciaId").value="";
		
		gId("ReferenciaId").value="0";
		gId("Referencia").value="";
		gId("ReferenciaCheck").value="";
		
		gId("Cantidad").value="1";
		//gId("Cantidad").focus();
		
		gId("Name").value="";
		gId("NameCheck").value="";
		gId("NameId").value="0";
				
		if ( document.getElementById("Descuento") ) {
			gId("Descuento").value="0";
		}
		
		gId("LastArticuloId").value = -1;
		gId("Cantidad").focus();
		
	}

	function CambioIva() {
		controller = micontroller();
		iva= gId(controller + "Iva").value;
		if (CheckInt(iva)) {
			alert("IVA OK");
		} else {
			alert("Error en el IVA.");
		}
	}
	function CambioVfactura() {
		controller = micontroller();
		vfactura_id=gId("VfacturaId").value;
		if (vfactura_id != "") {
			var tmp=gId("Vfactura").value.split(" ");
			gId("Vfactura").value = tmp[0];
			gId("VfacturaCheck").value = tmp[0];
			rarreglo = FunctionAjax("cambiovfactura/" + vfactura_id);
			gId(controller+"ClienteId").value=rarreglo[0]["Cliente"]["id"];
			gId(controller+"Clientename").value=rarreglo[0]["Cliente"]["name"];
			gId(controller+"Rut").value=rarreglo[0]["Cliente"]["rut"];
			gId(controller+"Rut").value=rarreglo[0]["Cliente"]["rut"];
			gId(controller+"Giro").value=rarreglo[0]["Cliente"]["giro"];
			gId(controller+"Direccion").value=rarreglo[0]["Cliente"]["direccion"];
			gId(controller+"Ciudad").value=rarreglo[0]["Cliente"]["ciudad"];
			gId(controller+"Comuna").value=rarreglo[0]["Comuna"]["name"];
			gId(controller+"Telefono").value=rarreglo[0]["Cliente"]["telefono"];
			ImprimeLineas();
			ActualizaValores();
		} else {
			gId(controller+"Giro").value="";
			gId(controller+"Direccion").value="";
			gId(controller+"Ciudad").value="";
			gId(controller+"Comuna").value="";
			gId(controller+"Telefono").value="";
		}
	}
	
	function CambioDocumentotipo(tipo)
	{
		documentotipo_id = gId("DocumentotipoId").value;
		if(documentotipo_id != "") {
			//setear sesion con documentotipo_id
			ProcedureAjax("cambiodocumentotipo/" + documentotipo_id);
			gId("DocumentoId").value='';
			gId("Documento").value='';
			gId("DocumentoCheck").value='';
			
			if (tipo == 'V') {
				gId(controller+"ClienteId").value='';
				gId(controller+"Clientename").value='';
			} 
			if (tipo == 'C') {
				gId(controller+"ProveedoreId").value='';
				gId(controller+"Proveedorename").value='';
			}
			
			gId(controller+"Rut").value='';
			gId(controller+"Rut").value='';
			gId(controller+"Giro").value='';
			gId(controller+"Direccion").value='';
			gId(controller+"Ciudad").value='';
			gId(controller+"Comuna").value='';
			gId(controller+"Telefono").value='';
			
			
		}
	}
	
	function CambioDocumento() {
		controller = micontroller();
		documento_id=gId("DocumentoId").value;
		if (documento_id != "") {
			var tmp=gId("Documento").value.split(" ");
			gId("Documento").value = tmp[0];
			gId("DocumentoCheck").value = tmp[0];
			rarreglo = FunctionAjax("cambiodocumento/" + documento_id);
			gId(controller+"ClienteId").value=rarreglo[0]["Cliente"]["id"];
			gId(controller+"Clientename").value=rarreglo[0]["Cliente"]["name"];
			gId(controller+"Rut").value=rarreglo[0]["Cliente"]["rut"];
			gId(controller+"Rut").value=rarreglo[0]["Cliente"]["rut"];
			gId(controller+"Giro").value=rarreglo[0]["Cliente"]["giro"];
			gId(controller+"Direccion").value=rarreglo[0]["Cliente"]["direccion"];
			gId(controller+"Ciudad").value=rarreglo[0]["Cliente"]["ciudad"];
			gId(controller+"Comuna").value=rarreglo[0]["Comuna"]["name"];
			gId(controller+"Telefono").value=rarreglo[0]["Cliente"]["telefono"];
			ImprimeLineas();
			ActualizaValores();
		} else {
			gId(controller+"Giro").value="";
			gId(controller+"Direccion").value="";
			gId(controller+"Ciudad").value="";
			gId(controller+"Comuna").value="";
			gId(controller+"Telefono").value="";
		}
	}
	
	function CambioDocumentoCompra() {
		controller = micontroller();
		documento_id=gId("DocumentoId").value;
		if (documento_id != "") {
			var tmp=gId("Documento").value.split(" ");
			gId("Documento").value = tmp[0];
			gId("DocumentoCheck").value = tmp[0];
			rarreglo = FunctionAjax("cambiodocumento/" + documento_id);
			gId(controller+"ProveedoreId").value=rarreglo[0]["Proveedore"]["id"];
			gId(controller+"Proveedorename").value=rarreglo[0]["Proveedore"]["name"];
			gId(controller+"Rut").value=rarreglo[0]["Proveedore"]["rut"];
			gId(controller+"Rut").value=rarreglo[0]["Proveedore"]["rut"];
			gId(controller+"Giro").value=rarreglo[0]["Proveedore"]["giro"];
			gId(controller+"Direccion").value=rarreglo[0]["Proveedore"]["direccion"];
			gId(controller+"Ciudad").value=rarreglo[0]["Proveedore"]["ciudad"];
			gId(controller+"Comuna").value=rarreglo[0]["Comuna"]["name"];
			gId(controller+"Telefono").value=rarreglo[0]["Proveedore"]["telefono"];
			ImprimeLineas();
			ActualizaValores();
		} else {
			gId(controller+"Giro").value="";
			gId(controller+"Direccion").value="";
			gId(controller+"Ciudad").value="";
			gId(controller+"Comuna").value="";
			gId(controller+"Telefono").value="";
		}
	}

	function CambioCfactura() {
		controller = micontroller();
		cfactura_id=gId("CfacturaId").value;
		if (cfactura_id != "") {
			var tmp=gId("Cfactura").value.split(" ");
			gId("Cfactura").value = tmp[0];
			gId("CfacturaCheck").value = tmp[0];
			rarreglo = FunctionAjax("cambiocfactura/" + cfactura_id);
			gId(controller+"ProveedoreId").value=rarreglo[0]["Proveedore"]["id"];
			gId(controller+"Proveedorename").value=rarreglo[0]["Proveedore"]["name"];
			gId(controller+"Rut").value=rarreglo[0]["Proveedore"]["rut"];
			gId(controller+"Rut").value=rarreglo[0]["Proveedore"]["rut"];
			gId(controller+"Giro").value=rarreglo[0]["Proveedore"]["giro"];
			gId(controller+"Direccion").value=rarreglo[0]["Proveedore"]["direccion"];
			gId(controller+"Ciudad").value=rarreglo[0]["Proveedore"]["ciudad"];
			gId(controller+"Comuna").value=rarreglo[0]["Comuna"]["name"];
			gId(controller+"Telefono").value=rarreglo[0]["Proveedore"]["telefono"];
			ImprimeLineas();
			ActualizaValores();
		} else {
			gId(controller+"Giro").value="";
			gId(controller+"Direccion").value="";
			gId(controller+"Ciudad").value="";
			gId(controller+"Comuna").value="";
			gId(controller+"Telefono").value="";
		}
	}
	
	function FiltroIndex(){
		php_params = "";
		for(var i=0; i<arguments.length; i++) {
			tmpval = gId(arguments[i]).value
			tmpval = tmpval.replace("/","");
			if (tmpval == "") tmpval = "null";
			php_params = php_params + "/" + tmpval;
		}
		DivAjax("filtrar" + php_params, gId("ResultadoDiv") );
	}
	
	function MiCiudad() {
		controller = micontroller();
		comuna_id = gId("ComunaId").value;
		if (comuna_id > 0) {
			ciudad = FunctionAjax("/comunas/miciudad/"+comuna_id , true);
			gId(controller+"Ciudad").value = ciudad;
		}
	}
	function crxurlencode(s) {
		s = s.replace(/\n/g,"-CRX_ENTER-");
		s = s.replace(/\//g,"-CRX_SLASH-");
		s = s.replace(/\'/g,"-CRX_QUOTE-");
		s = s.replace(/\#/g,"-CRX_CAT-");
		s = s.replace(/\%/g,"-CRX_PORC-");
		s = s.replace('&',"-CRX_AMP-");
		s = s.replace(/\?/g,"-CRX_QUESTION-");
		s = s.replace(/\+/g,"-CRX_PLUS-");
		s = s.replace(/\,/g,"-CRX_COMA-");
		s = s.replace(/\:/g,"-CRX_2P-");
		s = s.replace(/\./g,"-CRX_PUNTO-");
		s = encodeURIComponent(s);
		return s.replace(/~/g,'%7E').replace(/%20/g,'+');
	}

		
	function SemanaSiguiente(){
		DivAjax("nextsemana", $("ResultadoDiv") );
	}
	function SemanaPrevia(){
		
		DivAjax("prevsemana", $("ResultadoDiv") );
	}
	function CopiarReserva(id){
		//DivAjax("copiarreserva/"+id+"/'.$year.'/'.$month.'/'.$day.'/", $("ResultadoDiv") );
	}

 
	function optimiza_tablas_mobile(tbl, do_show) {

		var stl;
		var n = 3;
		if (do_show) stl = 'block'
		else         stl = 'none';
		//var tbl  = document.getElementById('id_of_table');
		var rows = tbl.getElementsByTagName('tr');
		for (var row=0; row<rows.length;row++) {
			
			var cels = rows[row].getElementsByTagName('th')
			if (cels.length > i) {
				for (var col_no=0; col_no < cels.length; col_no++) {
					if ((col_no >= n) && (col_no != cels.length - 1 )) {
						cels[col_no].style.display=stl;
					}
				}
			}
			
			var cels = rows[row].getElementsByTagName('td')
			if (cels.length > i) {
				for (var col_no=0; col_no < cels.length; col_no++) {
					if ((col_no >= n) && (col_no != cels.length - 1)) {
						cels[col_no].style.display=stl;
					}
				}
			}
			
		}
	}

	function getElementsByClass( searchClass, domNode, tagName) { 
		if (domNode == null) domNode = document;
		if (tagName == null) tagName = '*';
		var el = new Array();
		var tags = domNode.getElementsByTagName(tagName);
		var tcl = " "+searchClass+" ";
		for(i=0,j=0; i<tags.length; i++) { 
			var test = " " + tags[i].className + " ";
			if (test.indexOf(tcl) != -1) 
				el[j++] = tags[i];
		} 
		return el;
	} 


