
function formatearDecimal(numero,cantDecimales){
	if (cantDecimales > 0){ 
		var i=0;
		var aux=1;
		for (i = 0; i< cantDecimales; i++){
			aux= aux * 10;
		}
		numero = numero * aux;
		numero = Math.round(numero);
		numero = numero/aux;
	}
	return numero;
}

 
// Muestra / Oculta divs
function switchContent(div){
	if (document.getElementById(div).style.display == ""){
		document.getElementById(div).style.display = "none";
		
	} else {
		document.getElementById(div).style.display = "";
	}
}



// windowClass
function openWindow(titulo, ancho, alto) {
    var win = new Window("win1", {className: "alphacube", url: "popUp.html", width:ancho, height:alto, title:titulo, maximizable: false, minimizable: false, showEffectOptions: {duration:3}});
	win.showCenter();
    win.setDestroyOnClose();
}


// Obtiene la fecha actual
function obtenerFecha(){
	
var mydate=new Date();
var year=mydate.getYear();

if (year < 1000){
	year+=1900;
}

var day=mydate.getDay();
var month=mydate.getMonth();
var daym=mydate.getDate();

if (daym<10){
	daym="0"+daym;
}

var dayarray=new Array("Dom.","Lun.","Mar.","Mie.","Jue.","Vie.","Sab.")
var montharray=new Array("Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre")

document.write(dayarray[day]+" "+daym+" de "+montharray[month]);

}



// REDIRECCIONA LA URL
function MM_goToURL() { //v3.0
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}


// ABRE POPUP
function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}


//MANEJO DE IMAGENES

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];}
}

//INVOCO A LAS FUNCIONES QUE DESPLIEGAN EL ARBOL DE CATEGORIAS PARA SABER A QUE CATEGORIA PERTENECE EL LISTADO
//OBTIENE UN PARAMETRO DE LA URL SEGUN EL STRPARAMNAME
function getURLParam(strParamName){
var strReturn = "";
var strHref = window.location.href;
if ( strHref.indexOf("&") > -1 ){
var strQueryString = strHref.substr(strHref.indexOf("&")).toLowerCase();
var aQueryString = strQueryString.split("&");
for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
if (aQueryString[iParam].indexOf(strParamName + "=") > -1 ){
	var aParam = aQueryString[iParam].split("=");
	strReturn = aParam[1];
	break;
}
	 }
}
return strReturn;
}

/************* FUNCIONES DEL MENU CATEGORIAS PUBLICAS DEL SITIO *****************/
/*
function mostrarCategorias(){
	var subcategorias = document.getElementsByClassName("listadoSubCategorias");

	for (var i = 0;i < subcategorias.length;i++ ) {
		if(subcategorias[i].style.display == "none"){
			subcategorias[i].style.display = "";
			document.getElementById("flecha").src="images/interna/btn-replegar.gif";
		}else{
			subcategorias[i].style.display = "none";
			document.getElementById("flecha").src="images/interna/btn-desplegar.gif";
		}		
	}
}
*/
function switchSubMenu(subMenu) {
	if (document.getElementById(subMenu).style.display == "none") {
		document.getElementById(subMenu).style.display = "";
	} else {
		document.getElementById(subMenu).style.display = "none";
	}
}

var categoria;
var rootcategoryId;
var arrayCategorias = new Array();
var arrayCategoriasPrimerNivel = new Array();

function contieneElemento(arreglo,elemento){
	 for (var i = 0; i < arreglo.length; i++){
      if (arreglo[i] == elemento){
          return true;
      }
   }
   return false;	
}

function desplegarMenuAjax(categoryId, rootCategoryId) {
	if(document.getElementById("cat_"+categoryId) != null){
		if("none" == document.getElementById("cat_"+categoryId).style.display){
			document.getElementById("cat_"+categoryId).style.display = "";
			document.getElementById("cat_"+categoryId).innerHTML = "Cargando..."; 
			document.getElementById("menu_"+categoryId).style.color = "#ec1c24";
			var url = 'subcategories-show-ajax.php';
			categoria = categoryId;
			rootcategoryId = rootCategoryId;
			var params = "categoryId="+categoryId+"&rootCategoryId="+rootcategoryId+"&rand=" +  Math.random();
			var ajaxRequest = new Ajax.Request(
			url	, 
			{
				method: 'post',
				parameters: params,
				onComplete:showMenuProductos
			});
		}else{
			document.getElementById("cat_"+categoryId).style.display = "none";
		}
	}		
}

function desplegarMenuSubCat(id, parentCategoryId){
	if(!contieneElemento(arrayCategorias, parentCategoryId)){
		arrayCategorias.push(parentCategoryId);
	}
	if(!contieneElemento(arrayCategorias,id)){
		arrayCategorias.push(id);
	}

	desplegarMenuAjax(id, parentCategoryId);
}


function desplegarMenu(id, parentCategoryId){
	arrayCategorias = new Array();
	if(!contieneElemento(arrayCategorias, parentCategoryId)){
		arrayCategorias.push(parentCategoryId);
	}
	if(!contieneElemento(arrayCategorias,id)){
		arrayCategorias.push(id);
	}
	desplegarMenuAjax(id, parentCategoryId);
}
/* LA IDEA DE ESTA FUNCION ES QUE SI TOCO UNA CATEGORIA DE NIVEL 1 SE REPLIEGUEN LOS ARBOLES 
   DE LAS DEMAS CATEGORIAS DE PRIMER NIVEL PARA QUE NO ME MUESTRE ESOS ARBOLES AL IR AL LISTADO DE
   NOTAS
 */
function desplegarMenuPrimerNivel(id, parentCategoryId){
	if(arrayCategoriasPrimerNivel != null){
	for(var i=0;i<arrayCategoriasPrimerNivel.length;i++){
		document.getElementById("cat_"+arrayCategoriasPrimerNivel[i]).style.display = "none";
	}
	}
	desplegarMenu(id, parentCategoryId);
}

function showMenuProductos(ajaxReq){
	//alert(ajaxReq.responseText.length);
	if(ajaxReq.responseText.length > 5){//puesto porque algo trae siempre el ajax. 
	   document.getElementById("cat_"+categoria).innerHTML = ajaxReq.responseText; 
	}else{
	   document.getElementById("cat_"+categoria).style.visibility='hidden';
	   document.getElementById("cat_"+categoria).style.display='none'; 
	}
}

function verListadoSubcategoria(rootCateg,parentCat, categ){
	params = "rootCategoryId="+rootCateg+"&parentCatId="+parentCat+"&categoryId="+categ;
	for(var indice = 0; indice < arrayCategorias.length; indice++){
		params = params+"&id"+(indice+1)+"="+arrayCategorias[indice];
	}
	location.href="Cms-listado.php?"+params;
}

function verListadoArticulos(rootCateg,parentCat, categ){
	// llamo primero a esta funcion para que se carguen las categorias que quiero que se envien por 'get'.
	desplegarMenuPrimerNivel(categ, parentCat);
	
	//acpn es el arrglo de categorias de nivel 1
	params = "rootCategoryId="+rootCateg+"&parentCatId="+parentCat+"&categoryId="+categ+"&acpn="+arrayCategoriasPrimerNivel;
	for(var indice = 0; indice < arrayCategorias.length; indice++){
		params = params+"&id"+(indice+1)+"="+arrayCategorias[indice];
	}
	location.href="Cms-listado.php?"+params;
}

function verDetalle(rootCateg,parentCat,categId,articuloId){

	params = "rootCategoryId="+rootCateg+"&parentCatId="+parentCat+"&categoryId="+categId+"&id="+articuloId+"&acpn="+arrayCategoriasPrimerNivel;
	for(var indice = 0; indice < arrayCategorias.length; indice++){
		params = params+"&id"+(indice+1)+"="+arrayCategorias[indice];
	}
	location.href="Cms-detalle.php?"+params;
}

/*************************** FUNCIONES DE ADMINISTRACION DE SUSCRIPCIONES A CURSOS **************************/

function deshabilitarInputsRestantes(){
	var inputs = document.getElementsByClassName("checkboxSolicitud");
	for(var ind = 0;ind<inputs.length;ind++){
		if(!inputs[ind].checked){
			inputs[ind].disabled="disabled";
		}
	}		
}

function habilitarInputs(){
	var inputs = document.getElementsByClassName("checkboxSolicitud");
	for(var ind = 0;ind<inputs.length;ind++){
		inputs[ind].disabled="";
	}			
}
function contabilizador(){
	var cupos = document.getElementById("cuposCursos").value;
	document.getElementById("cuposCursos").value = parseInt((cupos - 1));	
}

function contabilizadorElemento(elemento){
	var cupos;
	if(elemento.checked){
		cupos = document.getElementById("cuposCursos").value;
		resta = parseInt((cupos)) - 1;
		if(resta <= 0){
			deshabilitarInputsRestantes();
			document.getElementById("cuposCursos").value = 0;
		}else{
			document.getElementById("cuposCursos").value = resta;
		}	
	}else{
		cupos = document.getElementById("cuposCursos").value;
		suma = parseInt((cupos)) + 1
		if(suma > 0){
			habilitarInputs();
			document.getElementById("cuposCursos").value = suma;
		}else{
			document.getElementById("cuposCursos").value = suma;
		}	
	}	
}

/********************************* contador para limitar el tamaño del ingreso de texto en un textarea  ******************************************/

var maximoTotal = 105;


function textCounter(field, countfield) {
	// si supera el maximo lo corto hasta el permitido
	if (field.value.length > maximoTotal){
		field.value = field.value.substring(0, maximoTotal);
	}else{ 
		// caso contrario actualizo el conteo restante
		countfield.value = maximoTotal - field.value.length;
	}
}

/********************************* funciones para el calculador de litros ***********************************/

function mostrarCalculador(){
	if(document.getElementById("calculadorLitros").style.display == "none"){
		document.getElementById("calculadorLitros").style.display = "";
	}else{
		document.getElementById("calculadorLitros").style.display = "none"; 
	}
} 

function calcular(){
	if(valid.validate()){
		var sumaCampos = 0;
		var restaCampos = 0;
		var total = 0;
		var rendimientoProducto = 0;
		var arregloResultadosParciales = new Array();
		for(var i=1;i < 5;i++){
			var campoA = document.getElementById("alto"+i).value;
			var campoB = document.getElementById("ancho"+i).value;
			sumaCampos = sumaCampos+(campoA * campoB);
			arregloResultadosParciales.push((campoA * campoB));
		}

		// hago la multiplicacion con los valores del techo
		var largoTecho = document.getElementById("largotecho").value;
		var anchoTecho = document.getElementById("anchotecho").value;
		var multiplicacionTecho = (largoTecho * anchoTecho);
		sumaCampos = sumaCampos + multiplicacionTecho;

		// hago la multiplicacion con los valores de la resta
		var largoResta = document.getElementById("largoresta").value;
		var anchoResta = document.getElementById("anchoresta").value;
		multiplicacionAberturas =  (largoResta * anchoResta);
		restaCampos = sumaCampos - multiplicacionAberturas;
		rendimientoProducto = document.getElementById("rendimiento").value;
		/*if(rendimientoProducto < 1){
			rendimientoProducto = 1;
		}*/
		total = restaCampos * rendimientoProducto;

		// cargo las sumas parciales en los respectivos campos.
		
		for(var ind=1;ind < 5;ind++){
			document.getElementById("pared"+ind).disabled = "";
			document.getElementById("pared"+ind).value = arregloResultadosParciales[(ind-1)];
		}

		// completo el campo techo
		document.getElementById("techo").disabled = "";
		document.getElementById("techo").value = multiplicacionTecho;

		// completo el campo aberturas
		document.getElementById("aberturas").disabled = "";
		document.getElementById("aberturas").value = multiplicacionAberturas;
		
		
		// completo el campo superficie
		document.getElementById("superficie").value = restaCampos;
		document.getElementById("total").value = formatearDecimal(total,2);//.toFixed(2);
		//document.getElementById("total").focus();
	}	
		 
}

function clearResults(){
	var inputs = document.getElementsByTagName("input");
	for(var i = 0;i < inputs.length;i++){
		if(inputs[i].id != "rendimiento" && inputs[i].type == "text"){
			inputs[i].value = "";
		}
	}
}

function cargarRendimiento(valor, idElementoProducto){
	var listadoNombres = document.getElementsByClassName("listadoProductos");
	
	for(var ind = 0;ind < listadoNombres.length;ind++){
		listadoNombres[ind].style.color = "#293895";
	}
	document.getElementById(idElementoProducto).style.color="#EC1C24";
	document.getElementById("rendimiento").value = formatearDecimal(valor,2);
	document.getElementById("rendimiento").focus();
	document.getElementById("idProducto").value = idElementoProducto;
	//document.getElementById("rendimiento").value = valor;
	
	//document.getElementById("alto1").focus();
	calcular();
}



function cargaListadoProductos(categoryId, numeroPestania, valorArgentina, valorUruguay){
	
	var links = document.getElementsByClassName('categoriasProductosCalc');
	
	for(var i=0; i<links.length;i++){
		links[i].style.color='#686868';
	}
	
	document.getElementById(categoryId).style.color='red';
	
	var listadoElementos = document.getElementsByClassName('listadoProductosXCategoria');
	
	for(var j=0;j<listadoElementos.length;j++){
		listadoElementos[j].innerHTML = "";
	}
	// muestro la pestaña activa.
	if(numeroPestania == 1){
		document.getElementById("arquitectonicoH").style.display = "";
		document.getElementById("industriaH").style.display = "none";
		document.getElementById("automotorH").style.display = "none";
	}else if(numeroPestania == 2){
		document.getElementById("industriaH").style.display = "";
		document.getElementById("arquitectonicoH").style.display = "none";
		document.getElementById("automotorH").style.display = "none";
	}else if(numeroPestania == 3){
		document.getElementById("automotorH").style.display = "";
		document.getElementById("industriaH").style.display = "none";
		document.getElementById("arquitectonicoH").style.display = "none";
	}
	// pongo el gif para avisar que el envio se esta procesando.
	document.getElementById("listadoProductosCategoria"+categoryId).innerHTML = "<img src='images/cargando.gif'/>";
	var params = "categoryId="+categoryId+"&rand=" +  Math.random()+"&argentina="+valorArgentina+"&uruguay="+valorUruguay;
	var url = "calculo-litros-ajax-productos.php";
	var ajaxRequest = new Ajax.Request(
	url	, 
	{
		method: 'post',
		parameters: params,
		onComplete:function showProductList(transport){
			          document.getElementById("listadoProductosCategoria"+categoryId).innerHTML = transport.responseText;
             	    }

	});
}


function cargaCategorias(parentCategoryId, numeroPestania, idDivRespuesta){
	//alert('asd');
	
	var listadoElementos = getElementsByClassName("listadoProductosXCategoria");
	for(var i=0;i<listadoElementos.length;i++){
		listadoElementos[i].innerHTML = "";
	}
	// muestro la pestaña activa.
	if(numeroPestania == 1){
		document.getElementById("arquitectonicoH").style.display = "";
		document.getElementById("industriaH").style.display = "none";
		document.getElementById("automotorH").style.display = "none";
	}else if(numeroPestania == 2){
		document.getElementById("industriaH").style.display = "";
		document.getElementById("arquitectonicoH").style.display = "none";
		document.getElementById("automotorH").style.display = "none";
	}else if(numeroPestania == 3){
		document.getElementById("automotorH").style.display = "";
		document.getElementById("industriaH").style.display = "none";
		document.getElementById("arquitectonicoH").style.display = "none";
	}
	// pongo el gif para avisar que el envio se esta procesando.
	document.getElementById(idDivRespuesta).innerHTML = "<img src='images/cargando.gif'/>";
	var params = "parentCategoryId="+parentCategoryId+"&rand=" +  Math.random();
	var url = "calculo-litros-ajax-categorias.php";
	var ajaxRequest = new Ajax.Request(
	url	, 
	{
		method: 'post',
		parameters: params,
		onComplete:function showCategoryList(transport){
					 document.getElementById(idDivRespuesta).innerHTML = transport.responseText;
				   }
	});
	
}

function showCategoryList(ajaxReq){
	document.getElementById("listadoCategorias").innerHTML = ajaxReq.responseText;
}

function guardarNota(){
    var campoDescripcion = tinyMCE.get('descripcion').getContent();
    var checkArg = document.getElementById("Argentina").checked;
    var checkUru = document.getElementById("Uruguay").checked;
	if(valid.validate()){
	   	
	
		if(campoDescripcion != "" && (checkArg == true || checkUru == true)){
		  document.cms.submit();	
		}else{
			alert("Corrobore que haya completado todos los campos obligatorios");
			//document.getElementById("errorDescripcion").style.display = "";
			/* 
			   Esta truchada la hago para que si tengo un error de campo requerido vacio 
			   dentro del campo descripción que se muestre el mensaje de arriba y que se haga una
			   subida hasta el tope superior de la pagina.   
			*/
			location.href = "#toppage";
		}
	}
}

function guardarNotaColorshop(){
    var campoDescripcion = tinyMCE.get('descripcion').getContent();
    if(valid.validate()){
		if(campoDescripcion != ""){
		  document.cms.submit();	
		}else{
			alert("Corrobore que haya completado todos los campos obligatorios");
			//document.getElementById("errorDescripcion").style.display = "";
			/* 
			   Esta truchada la hago para que si tengo un error de campo requerido vacio 
			   dentro del campo descripción que se muestre el mensaje de arriba y que se haga una
			   subida hasta el tope superior de la pagina.   
			*/
			location.href = "#toppage";
		}
	}
}
/*
Developed by Robert Nyman, http://www.robertnyman.com
Code/licensing: http://code.google.com/p/getelementsbyclassname/
*/
var getElementsByClassName = function (className, tag, elm){
if (document.getElementsByClassName) {
	getElementsByClassName = function (className, tag, elm) {
		elm = elm || document;
		var elements = elm.getElementsByClassName(className),
			nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
			returnElements = [],
			current;
		for(var i=0, il=elements.length; i<il; i+=1){
			current = elements[i];
			if(!nodeName || nodeName.test(current.nodeName)) {
				returnElements.push(current);
			}
		}
		return returnElements;
	};
}
else if (document.evaluate) {
	getElementsByClassName = function (className, tag, elm) {
		tag = tag || "*";
		elm = elm || document;
		var classes = className.split(" "),
			classesToCheck = "",
			xhtmlNamespace = "http://www.w3.org/1999/xhtml",
			namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
			returnElements = [],
			elements,
			node;
		for(var j=0, jl=classes.length; j<jl; j+=1){
			classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
		}
		try	{
			elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
		}
		catch (e) {
			elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
		}
		while ((node = elements.iterateNext())) {
			returnElements.push(node);
		}
		return returnElements;
	};
}
else {
	getElementsByClassName = function (className, tag, elm) {
		tag = tag || "*";
		elm = elm || document;
		var classes = className.split(" "),
			classesToCheck = [],
			elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
			current,
			returnElements = [],
			match;
		for(var k=0, kl=classes.length; k<kl; k+=1){
			classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
		}
		for(var l=0, ll=elements.length; l<ll; l+=1){
			current = elements[l];
			match = false;
			for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
				match = classesToCheck[m].test(current.className);
				if (!match) {
					break;
				}
			}
			if (match) {
				returnElements.push(current);
			}
		}
		return returnElements;
	};
}
return getElementsByClassName(className, tag, elm);
};
// No focus 
function noFocus() { 
anclas=document.getElementsByTagName("a").length; 
for (i=0;i<anclas;i++) 
document.getElementsByTagName("a").item(i).onfocus=new Function("if(this.blur)this.blur()")  
 }
 