// JavaScript Document
var validate = Array ();

function busca_new()
{
	if($('T8').present())
	{
		if($('T8').value.length >= 4)
		{
			$('frm_search').submit();
		}
		else
		{
			alert('More than 3 characteres');
		}
	}
	else
	{
		alert('More than 3 characteres');
	}
}

function ocultar()
{
	$('cargador').style.visibility = 'hidden';
}

//funcion que envia el formulario
function add_user()
{	
	var i = 0;
	var bool = false;
	while(i < validate.length && !bool)
	{
		if(validate[i])
		bool = true;		
		i++;		
	}
	
	if($('T4').present())
	{
		if(!bool)
		{
			$('frm_user').submit();		
		}
	}
	else{ $('username').innerHTML = 'Error: debe especificar un nombre de usuario'; }
}

/*
* Funcion para enmviar una formulario
*/
function SendForm(idform)
{
	
		var i = 0;
	var bool = false;
	while(i < validate.length && !bool)
	{
		if(validate[i])
		bool = true;		
		i++;		
	}
	
	if($('T3').present() && $('S1').present())
	{
		if(!bool)
		{
			$(idform).submit();		
		}
	}
	
/*	var i = 0;
    var count = 0;
	var bool = false;
	for(var i = 0; i < validate.length; i++)
	{
		if(validate[i] == false)
		{
			count++;
	    }				
				
	}	
		if(count == 0)
		{
			$(idform).submit();	
			bool = true;
		}
	return bool;*/
}


/*
  * El parametro orderToValidate es para poner en una lista el numero 
  del campo que se esta validando, este debe ser un numero consecutivo
  comienza desde cero: 0
*/
function campObligatorio(idcontrol ,divError, MsgError, orderToValidate)
{	    
	if(!$(idcontrol).present())
	{
		$(divError).innerHTML = MsgError;		
		validate[orderToValidate] = true;		
	}
	else 
	   {
		  validate[orderToValidate] = false;
		  $(divError).innerHTML = '';
		}		
}

function eliminarUser(url)
{
	if(confirm('Esta seguro que desea realizar esta acción.'))
	{
		new Ajax.Updater('update', url, {onLoaded: $('cargador').style.visibility = 'visible', onComplete: ocultar});
	}
}

function buscar_sections(url)
{
  url+='?'+$('frmsearchsection').serialize();
  new Ajax.Updater('update', url, {onLoaded: $('cargador').style.visibility = 'visible', onComplete: ocultar});
}

function del_news(url)
{
  url+='?'+$('frm_news').serialize();
  new Ajax.Updater('update', url, {onLoaded: $('cargador').style.visibility = 'visible', onComplete: ocultar});
}

 function EnterForm(e, url)
  {
	  if(e.keyCode == 13)
	   Login(url);
	  else if(e.which == 13)
	   Login(url); 
  }


  function Login(url)
  {
	  if($('T8').present() && $('T9').present())
	  {
		  url +='?'+$('frm').serialize();		  
		  new Ajax.Request(url, {onSuccess: isValidLogin});
	  }
	  else
	  {
		  alert('Debe llenar todos los campos.');		  
	  }
  }
  
  function isValidLogin(respuesta)
  {	       
	  switch(respuesta.responseText)
	  {
		  case 'type1':
		  {
			  document.location = 'index.php?secc=type1';			  
			  break;
		  }
		   case 'admin':
		  {
			  document.location = 'index.php';			 
			  break;
		  }
		  default :
		  {$('error').innerHTML = respuesta.responseText;}		  
	  } 	 
	  
  }
  
  /*
   * funcion que valida dos fechas con el formato Y-mm-dd
   * lo que hace es validar que date1 sea menor o igual que date2
  */
  function comparaFechas(date1, date2)
  {	 
    var bool = false; 
    var listDate1 = date1.split("-");
	var listDate2 = date2.split("-");
	date1 = listDate1[0]+"/"+listDate1[1]+"/"+listDate1[2];
	date2 = listDate2[0]+"/"+listDate2[1]+"/"+listDate2[2];	    
	
	  try
	  {	
		  if(Date.parse(date1) <= Date.parse(date2))
		  {
			   bool = true;
		  }
	  }
	  catch(e)
	  {
		  alert('Error: verifique las fechas.');
	  }
	 
	 return bool;		 
  }
  
  
  function BuscarNewsType1(url)
  {
	//pregunto si el formulario tiene algun campo lleno
	if($('T1').present() || $('T2').present() ||$('T3').present() || $('T4').present() || $('T6').present())
	{		
	 // varialble para determinar si ha habido algun error 
	  var bool = true;
	  if($('T2').present() || $('T3').present())
	  { 
		  if(comparaFechas($('T2').value, $('T3').value))
		  {
			 //implemetar el busqueda
		  }else{ bool = false; alert('Atención: hay errores en las fechas proporcionadas, \n debe tener en cuenta que DATE FROM tiene \n ser menor o igual que DATE TO.'); }
	  }
	  else
	  {
		  //compruebo que el campo titulo tenga valor
		  if($('T1').present())
		  {
			  //valido que tenga al menos 4 caracteres
			  if($('T1').value.length >= 4)
			  {
				 // implementar aqui busqueda
			  }
			  else{ bool = false; alert('Error: para iniciar la búsqueda debe introducir mínimo 4 caractéres.'); }
		  }		 
	  }
	  
	  if(bool)
	  {
		  url += '&'+$('frm').serialize();		  
		  new Ajax.Updater('update', url, {onLoaded: $('cargador').style.visibility = 'visible', onComplete: ocultar});
	  }
	}
	else
	alert('Atención: debe suministrar algún método de búsqueda.')
  }

function cancel_headlines()
{
	document.getElementById('D71').value = 1;
	limpiar_sub_section_personalizada(1);
	document.getElementById('txt_cancel').value = 1;
	document.getElementById('D77').value = 5;
	document.getElementById('table_width').value = 400;
	document.getElementById('T10').value = 'none';
	document.getElementById('T11').value = 'none';
	document.getElementById('T12').value = 'none';
	document.getElementById('T13').value = 'none';
	document.getElementById('frm_content').submit();
}

function copy_clip(meintext)
{
if (window.clipboardData)
    {

    // the IE-manier
   window.clipboardData.setData("Text", meintext);

   // waarschijnlijk niet de beste manier om Moz/NS te detecteren;
   // het is mij echter onbekend vanaf welke versie dit precies werkt:
   }
   else if (window.netscape)
   {

   // dit is belangrijk maar staat nergens duidelijk vermeld:
   // you have to sign the code to enable this, or see notes below
   alert(1)
   netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

   // maak een interface naar het clipboard
   alert(document.classes.length)
   alert(Components)
   alert(Components.classes.length)
   var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
   alert(clip)
   if (!clip) return;
   
   alert(2)

   // maak een transferable
   var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
   if (!trans) return;

   // specificeer wat voor soort data we op willen halen; text in dit geval
   trans.addDataFlavor('text/unicode');

   // om de data uit de transferable te halen hebben we 2 nieuwe objecten
   // nodig om het in op te slaan
   var str = new Object();
   var len = new Object();

   var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);

   var copytext=meintext;

   str.data=copytext;

   trans.setTransferData("text/unicode",str,copytext.length*2);

   var clipid=Components.interfaces.nsIClipboard;

   if (!clip) return false;

   clip.setData(trans,null,clipid.kGlobalClipboard);

   }
   alert("Following info was copied to your clipboard:\n\n" + meintext);
   return false;
} 
