function textCounter(field, countfield, maxlimit) {
try {
if (field.value.length > maxlimit) // if too long...trim it!
field.value = field.value.substring(0, maxlimit);
// otherwise, update 'characters left' counter
else 
countfield.innerHTML = maxlimit - field.value.length;
} catch (e) {}
}

function defaultInputContent(item, text, focused) {
	if (item.value == '') {
		item.value = text;
	} else if (item.value != text) {
		//item.value = text;
	} else {
		item.value = '';
	}
}

function escala_item(img, nMaxWidth, nMaxHeight , div, OnPostResize)
{

	var minwidth=100;
	var minheight=100;
	img.style.display = "block";
	var nImageWidth = img.width;
	var nImageHeight = img.height;
	img.style.display = "none";	
	
	if(div){
		document.getElementById('loading_image').innerHTML = '<p><img src="/images/loadingAnimation.gif"></p>';
		if((nImageWidth>minwidth && nImageHeight>minheight) || nImageWidth==0){ //ie7 pt
			document.getElementById('image_'+div).style.display = "block";
			if (document.getElementById('img_radio_'+div)) {
				if (document.getElementById('img_radio_'+div).type == 'radio') {
					document.getElementById('img_radio_'+div).checked = true;
				}
			}
			$blinddown('result');
		}
	}
	
	// only resize if we need to so the image doesn't stretch
	if (nImageWidth > nMaxWidth || nImageHeight > nMaxHeight)
	{
		var ratio = nImageWidth / nImageHeight;
		if (ratio > 1)
			nMaxHeight = nMaxWidth / ratio;
		else if (ratio < 1)
			nMaxWidth = nMaxHeight * ratio;
		else if (nMaxWidth > nMaxHeight)
			nMaxWidth = nMaxHeight;
		else if (nMaxHeight > nMaxWidth)
			nMaxHeight = nMaxWidth;

		img.height = Math.round(nMaxHeight);
		img.width = Math.round(nMaxWidth);
	}else if(nImageWidth==0){
		img.height = minheight;
		img.width = minwidth;
	}
	
	// image loaded and resized, so show it
	img.style.display = "block";
	
	if (OnPostResize)
	{
		OnPostResize(img);
	}
	if(div){
		document.getElementById('loading_image').innerHTML = '';
	}
}

function cambia(id) {
	//safe function to show an element with a specified id
	if (document.getElementById(id).style.display != 'block'){
	   var myConn = new XHConn();
	   if (myConn){
		    var fnWhenDone = function (oXML) { return false; };
			myConn.connect("/system/action/captcha/" , 'GET', '', fnWhenDone);
		}
		document.getElementById(id).style.display = 'block';
	}else {
		document.getElementById(id).style.display = 'none';
	}
}

/*-----------------------------------------------------------------------------*/

/** XHConn - Simple XMLHTTP Interface - bfults@gmail.com - 2005-04-08        **
 ** Code licensed under Creative Commons Attribution-ShareAlike License      **
 ** http://creativecommons.org/licenses/by-sa/2.0/                           **/
function XHConn()
{
  var xmlhttp, bComplete = false;
  try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
  catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
  catch (e) { try { xmlhttp = new XMLHttpRequest(); }
  catch (e) { xmlhttp = false; }}}
  if (!xmlhttp) return null;
  this.connect = function(sURL, sMethod, sVars, fnDone)
  {
    if (!xmlhttp) return false;
    bComplete = false;
    sMethod = sMethod.toUpperCase();

    try {
      if (sMethod == "GET")
      {
        xmlhttp.open(sMethod, sURL+"?"+sVars, true);
        sVars = "";
      }
      else
      {
        xmlhttp.open(sMethod, sURL, true);
        xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
        xmlhttp.setRequestHeader("Content-Type",
          "application/x-www-form-urlencoded");
      }
      xmlhttp.onreadystatechange = function(){
        if (xmlhttp.readyState == 4 && !bComplete)
        {
          bComplete = true;
          fnDone(xmlhttp);

        }};
      xmlhttp.send(sVars);
    }
    catch(z) { return false; }
    return true;
  };
  return this;
} 

/*-----------------------------------------------------------------------------*/

function updatePorqueCopy()
{
	try {
	if (document.getElementById('copy_option_move').checked == false ) {
		document.getElementById('porque_copy').disabled = false;
		document.getElementById('porque_copy').value = '';
		document.getElementById('porque_copy').style.backgroundColor = '';
		document.getElementById('copyItem_submit').value = 'copiar';
		document.getElementById('porque_options').style.display = '';
	} else {
		document.getElementById('porque_copy').disabled = true;
		document.getElementById('porque_copy').style.backgroundColor = '#cdcdcd';
		document.getElementById('porque_copy').value = '';
		document.getElementById('copyItem_submit').value = 'mover';
		document.getElementById('porque_options').style.display = 'none';
	}
	} catch (e) {
	  
	}
}

/**
 * Muestra u oculta un popup
 */
function parseAndFixPopUp(show) {
  win = document.getElementById('addItemPopUp');
  if (window.innerWidth) {
    leftPost = parseInt(window.innerWidth / 2 ) - parseInt(490/2);
  } else {
    leftPost = parseInt(document.body.clientWidth / 2 ) - parseInt(490/2);
  }
  if (show == 1) {
    win.style.display = '';
    $highlight('addItemPopUp',50);
    win.style.top = "100px";
    win.style.left = leftPost+"px";
  } else {
    win.style.display = 'none';
  }
}
function parseAndFixPopUp2(show) {
  win = document.getElementById('addItemPopUp2');
  if (window.innerWidth) {
    leftPost = parseInt(window.innerWidth / 2 ) - parseInt(490/2);
  } else {
    leftPost = parseInt(document.body.clientWidth / 2 ) - parseInt(490/2);
  }
  if (show == 1) {
    win.style.display = '';
    $highlight('addItemPopUp2',50);
    win.style.top = "100px";
    win.style.left = leftPost+"px";
  } else {
    win.style.display = 'none';
  }
}

function add_item(id,from_list) {
	document.getElementById('porque_copy').value = '';
  document.getElementById('item_id_copy').value = 0;
	document.getElementById('list_id_copy').value = 0;
  if (id == 0) {
   parseAndFixPopUp(0);
  } else {
   parseAndFixPopUp(1);
   document.getElementById('item_id_copy').value = id;
   document.getElementById('list_id_copy').value = from_list;
   updatePorqueCopy();
  }
}


function sendAddItemPopUp()
{
		id = $('item_id_copy').value;
	  lista_id = $('lista_id_copy').value;
	  porque = $('porque_copy').value;
		if ($('copy_option_move') != null) {
		 if ($('copy_option_move').checked == true) {
	     copy_options = 'move';
	   } else {
	     copy_options = 'copy';
	   }
	  } else {   
			 copy_options = $('copy_option_copy').value;
	  }
	  if (porque == '' && copy_options == 'copy') {
	    alert('Tienes que indicar para que quieres el regalo.');
	    return false;
	  } else if (lista_id == '') {
	    alert('Debes indicar a que lista deseas copiarlo.');
	    return false;
	  } else if (id == '') {
	    alert('No sabemos que quieres copiar.');
	    return false;
	  }
		
	  add_item(0);
	  add_item_post(id,lista_id,porque,copy_options);
}

function add_item_post(id,lista_id,porque,copy_option){
		document.getElementById('added_itemid'+id).innerHTML = '<img src="/images/loadingAnimation.gif">';
		var myConn = new XHConn();
		if (myConn){
			if (copy_option == 'move') {
	 		  var fnWhenDone = function (oXML) { window.location.reload(); };
			} else {
  			var fnWhenDone = function (oXML) { 
					if (document.getElementById('added_itemid'+id)!=null) { 
						document.getElementById('added_itemid'+id).innerHTML = '<img src="/images/agregado.gif">'; 
						// document.getElementById('add_itemid'+id).innerHTML = ''; 
					}
				};
			}
			myConn.connect("/system/action/additem/"+id+"?lista_id="+lista_id+"&copy_option="+copy_option+"&porque="+escape(porque)+"&null=" , 'GET', '', fnWhenDone);
		}
}

function add_item_cat(itemUrl, itemTitle, itemMLid) {
  parseAndFixPopUp2(1);
  win.style.top = "20px";
  document.getElementById('add_item').style.display = '';
  document.getElementById('item_url').value = unescape(itemUrl);
  document.getElementById('item_nombre').value = unescape(itemTitle);
  document.getElementById('ml_xml_id').value = itemMLid;
  busca_imagen('item_url','result');
  // document.getElementById('addItemForm').;
}

function validateCatalogoPopUp()
{
  var varRet = true;
  varRet = ($('item_url').value == '')?false:varRet; 
  varRet = ($('item_nombre').value == '')?false:varRet; 
  varRet = ($('item_tags').value == '')?false:varRet;
  varRet = ($('item_comentario').value == '')?false:varRet; 
  if (varRet == false) {
    alert('Completa correctamente los datos para poder agregar tu regalo.');
  } else {
    return true;
  }
  return false;
}

function busca_imagen(campo,target,id){
		var url=document.getElementById(campo).value;
		document.getElementById(target).innerHTML = '<div style="float:right"><img src="/images/loadingAnimation.gif"></p></div>';
		var myConn = new XHConn();
		if (myConn){
			var peticion = function (oXML) {  
					document.getElementById(target).innerHTML = oXML.responseText; 
					
				};
			myConn.connect("/system/action/parser" , "GET", 'url='+escape(url)+"&id="+id, peticion);
	}
}

function comentar(item){
	document.getElementById('comentarios').innerHTML = '<p><img src="/images/loadingAnimation.gif"></p>';
	var myConn = new XHConn();
	if (myConn){
		var peticion = function (oXML) {  document.getElementById('comentarios').innerHTML = oXML.responseText; };
		myConn.connect("/system/action/comment/" , 'POST', 'comentario='+document.getElementById('comentario').value+"&item="+item, peticion);
		document.getElementById('comentario').value='';
	}
}

function del_comment(item,id_comment){
	if (confirm('Confirma que desea eliminar el comentario ?')){
		document.getElementById('comentarios').innerHTML = '<p><img src="/images/loadingAnimation.gif"></p>';
		var myConn = new XHConn();
		if (myConn){
			var peticion = function (oXML) {  document.getElementById('comentarios').innerHTML = oXML.responseText; };
			myConn.connect("/system/action/comment/" , 'POST', 'del_comment='+id_comment+"&item="+item, peticion);
			document.getElementById('comentario').value='';
		}
	}
}

function elimina_amigo(amigo){
   if (confirm('Confirma que desea eliminar el amigo '+amigo+' ?')){
		var myConn = new XHConn();
		if (myConn){
			var peticion = function (oXML) {  location. reload() };
			myConn.connect("/system/action/delfriend/"+amigo , 'GET', '', peticion);
		}     
   }
} 

function busca_amigo(usuario){
	document.getElementById('fiend_resultado').innerHTML = '<p><img src="/images/loadingAnimation.gif"></p>';
	var myConn = new XHConn();
	if (myConn){
		var peticion = function (oXML) {  document.getElementById('fiend_resultado').innerHTML = oXML.responseText; };
		usuario = (usuario!=null)?'usuario='+usuario+'&':'';
		myConn.connect("/system/action/busca_amigo" , 'POST', usuario+'string='+document.getElementById('busca_friend').value, peticion);
	}
}

function invitar_amigo(){
	document.getElementById('amigo_resultado').innerHTML = '<p><img src="/images/loadingAnimation.gif"></p>';
	var myConn = new XHConn();
	if (myConn){
		var peticion = function (oXML) {  document.getElementById('amigo_resultado').innerHTML = oXML.responseText; };
		myConn.connect("/system/action/invita_amigo" , 'POST', 'email='+document.getElementById('invita_amigo').value, peticion);
	}
}

function agregar_amigo(amigo){
	   document.getElementById('agregar_amigo').innerHTML = '<p><img src="/images/loadingAnimation.gif"></p>';
		var myConn = new XHConn();
		if (myConn){
			var peticion = function (oXML) {  document.getElementById('agregar_amigo').innerHTML = '' };
			myConn.connect("/system/action/addfriend/"+amigo , 'GET', '', peticion);
		}     
} 

function agregar_amigo_perfil(amigo){
	   document.getElementById('agregar_amigo_'+amigo).innerHTML = '<p><img src="/images/loadingAnimation.gif"></p>';
		 document.getElementById('agregar_amigo').innerHTML = '<p><img src="/images/loadingAnimation.gif"></p>';
		var myConn = new XHConn();
		if (myConn){
			var peticion = function (oXML) {  
				document.getElementById('agregar_amigo_'+amigo).innerHTML = '';
				document.getElementById('agregar_amigo').innerHTML = '';
			};
			myConn.connect("/system/action/addfriend/"+amigo , 'GET', '', peticion);
		}     
} 

function agregar_amigo_2(amigo){
	  document.getElementById('agregar_amigo_'+amigo).innerHTML = '<img src="/images/loadingAnimation.gif">';
		var myConn = new XHConn();
		if (myConn){
			var peticion = function (oXML) {  document.getElementById('agregar_amigo_'+amigo).innerHTML = '' };
			myConn.connect("/system/action/addfriend/"+amigo , 'GET', '', peticion);
		}
		if (document.getElementById('lista_amigos')!=null) {
		  updateListaAmigos('lista_amigos');
		} 
} 

function updateListaAmigos(item_id){
  document.getElementById(item_id).innerHTML = '<img src="/images/loadingAnimation.gif">';
  var myConn = new XHConn();
  if (myConn){
    var peticion = function (oXML) {  document.getElementById(item_id).innerHTML = oXML.responseText; };
    myConn.connect("/system/action/list_amigos", 'GET', '', peticion);
  }
}

function eliminar_item(id, nombre){
   if (confirm('Eliminar '+nombre+' ?')){
	   document.getElementById('edit_item_'+id).style.display = "none";
	   document.getElementById('item_'+id).style.display = "block";
	   $opacity('item_'+id, 100, 20, 600);
	   document.getElementById('item_del_'+id).innerHTML = '<p><img src="/images/loadingAnimation.gif"></p>';
	   var myConn = new XHConn();
	   if (myConn){
			var fnWhenDone = function (oXML) { $blindup('item_'+id);document.getElementById('item_'+id).innerHTML = '';document.getElementById('item_bar_'+id).innerHTML = ''; };
			myConn.connect("/system/action/delitem/"+id , 'GET', '', fnWhenDone);
		}
		
		
   }
} 
function reserva_item(id){
	   document.getElementById('item_reserva_'+id).innerHTML = '<p><img src="/images/loadingAnimation.gif"></p>';
	   var myConn = new XHConn();
	   if (myConn){
			var fnWhenDone = function (oXML) {document.getElementById('item_reserva_'+id).innerHTML = '<span class="cancelar_reserva"><a href="#" onclick="reserva_cancela('+id+'); return false;">CANCELAR RESERVA</a></span>';  document.getElementById('producto_res_'+id).style.background = 'url(/imagenes/reservado.jpg) right bottom;'; };
			myConn.connect("/system/action/reserveitem/"+id , 'GET', '', fnWhenDone);
		}		
}
function reserva_item_full(id){
	   document.getElementById('item_reserva_'+id).innerHTML = '<p><img src="/images/loadingAnimation.gif"></p>';
	   var myConn = new XHConn();
	   if (myConn){
			var fnWhenDone = function (oXML) {document.getElementById('item_reserva_'+id).innerHTML = '<span class="cancelar_reserva"><a href="#" onclick="reserva_cancela_full('+id+'); return false;">CANCELAR RESERVA</a></span>';  document.getElementById('producto_res_'+id).innerHTML = '<img src="/imagenes/reservado_full.jpg">'; };
			myConn.connect("/system/action/reserveitem/"+id , 'GET', '', fnWhenDone);
		}		
} 

function reserva_cancela(id){
	 if (confirm('Seguro que desea cancelar la reserva?')){
	   document.getElementById('item_reserva_'+id).innerHTML = '<p><img src="/images/loadingAnimation.gif"></p>';
	   var myConn = new XHConn();
	   if (myConn){
			var fnWhenDone = function (oXML) {document.getElementById('item_reserva_'+id).innerHTML = '<span class="item_reservar"><a href="#" onclick="reserva_item('+id+'); return false;">RESERVAR</a></span>';  document.getElementById('producto_res_'+id).style.background = 'none'; };
			myConn.connect("/system/action/reservecancel/"+id , 'GET', '', fnWhenDone);
		}
	 }
} 

function reserva_cancela_full(id){
	 if (confirm('Seguro que desea cancelar la reserva?')){
	   document.getElementById('item_reserva_'+id).innerHTML = '<p><img src="/images/loadingAnimation.gif"></p>';
	   var myConn = new XHConn();
	   if (myConn){
			var fnWhenDone = function (oXML) {document.getElementById('item_reserva_'+id).innerHTML = '<span class="item_reservar"><a href="#" onclick="reserva_item_full('+id+'); return false;">RESERVAR</a></span>';  document.getElementById('producto_res_'+id).innerHTML = ''; };
			myConn.connect("/system/action/reservecancel/"+id , 'GET', '', fnWhenDone);
		}
	 }
}



function editar_item(id){
	 document.getElementById('edit_item_'+id).style.display = "block";
	 document.getElementById('edit_item_'+id).innerHTML = '<p><img src="/images/loadingAnimation.gif"></p>';
	 document.getElementById('item_'+id).style.display = "none";
	 var myConn = new XHConn();
		if (myConn){
			var peticion = function (oXML) {  document.getElementById('edit_item_'+id).innerHTML = oXML.responseText;  };
			myConn.connect("/system/action/edititem/"+id , 'GET', '', peticion);
		}     
} 

function cambia_estado(id){
	document.getElementById('item_'+id).style.display = "block";
	document.getElementById('edit_item_'+id).style.display = "none";
}

function modifica_item(id){
	var url=document.getElementById('edit_item_url_'+id).value;
	var item_nombre=document.getElementById('item_nombre_'+id).value;
	var currency=document.getElementById('currency_'+id).value;
	var item_precio=document.getElementById('item_precio_'+id).value;
	var item_prioridad=document.getElementById('item_prioridad_'+id).value;
	var item_tags=document.getElementById('item_tags_'+id).value;
	var item_comentario=document.getElementById('item_comentario_'+id).value;
	inputs = document.getElementsByTagName("input");
	var image=false;
	for(i=0,tope=inputs.length;i<tope;i++){
		e=inputs[i];
		if(e.name == 'image'+id && e.checked == true){
			image=e.value;
		}
	}
	
	document.getElementById('edit_item_'+id).style.display = "block";
	document.getElementById('edit_item_'+id).innerHTML = '<p><img src="/images/loadingAnimation.gif"></p>';
	document.getElementById('item_'+id).style.display = "none";
	var myConn = new XHConn();
	if (myConn){
		var peticion = function (oXML) {  document.getElementById('edit_item_'+id).innerHTML = oXML.responseText;  };
		myConn.connect("/system/action/edititem/"+id , 'POST', 'item_url='+escape(url)+'&item_nombre='+item_nombre+'&currency='+currency+'&item_precio='+item_precio+'&item_prioridad='+item_prioridad+'&item_tags='+item_tags+'&item_comentario='+item_comentario+"&image="+escape(image), peticion);
	} 
}
function nextStepAddList(step,im,dt,day,month,year) {
  document.getElementById('lista_tipo').value = step;
  var today = new Date();
  if (im == 1) {
    document.getElementById('bloque_lista_imagen').style.display = '';
  } else {
    document.getElementById('bloque_lista_imagen').style.display = 'none';
  }
  if (dt == 1) {
    document.getElementById('bloque_lista_fecha').style.display = '';
    if (day != 0) {
      document.getElementById('lista_fecha_Day').value = day;
    }
    if (month != 0) {
      document.getElementById('lista_fecha_Month').value = month;
    }
	if (year != null) {
		document.getElementById('lista_fecha_Year').value = year;
	} else {
		document.getElementById('lista_fecha_Year').value = year;
	}
    if (day && month && year == null) {
      document.getElementById('bloque_lista_fecha').style.display = 'none';
    }
  } else {
    document.getElementById('lista_fecha_Day').value = 0;
    document.getElementById('lista_fecha_Month').value = 0;
    document.getElementById('lista_fecha_Year').value = 0;
    document.getElementById('bloque_lista_fecha').style.display = 'none';
  }
  
  document.getElementById('step_tipo_listas').style.display = 'none';
  document.getElementById('step_detalles').style.display = '';
  document.getElementById('lista_nombre').focus();
}

function editList(lista_id) {
   var myConn = new XHConn();
   if (myConn){
		var fnWhenDone = function (oXML) {
				eval("var lista_data = " + oXML.responseText + ";");
				document.getElementById('loadingListas').innerHTML = '';
				if (document.getElementById('step_detalles').style.display != '') cambiaAdd('add_lista');
				//alert(lista_data.lista_tipo+', '+lista_data.tipo_upload_imagen+', '+lista_data.tipo_fechado+', '+lista_data.lista_fecha_dia+', '+lista_data.lista_fecha_mes+', '+lista_data.lista_fecha_anio);
				nextStepAddList(lista_data.lista_tipo,lista_data.tipo_upload_imagen,lista_data.tipo_fechado,lista_data.lista_fecha_dia,lista_data.lista_fecha_mes,lista_data.lista_fecha_anio);
				document.getElementById('titulo_lista_form').innerHTML = 'Editar lista '+lista_data.lista_nombre;
				document.getElementById('lista_id').value = lista_data.lista_id;
				document.getElementById('lista_nombre').value = lista_data.lista_nombre;			
			}
		document.getElementById('loadingListas').innerHTML = '<img src="/images/loadingAnimation.gif">';
		myConn.connect("/system/action/get_lista_data/"+lista_id , 'GET', '', fnWhenDone);
	}
}