// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

function box(object_name) 
{	
	var object = $(object_name);
	if (object.style.display != "block") 
	{
		object.style.display = "block";
	} 
	else 
	{
		object.style.display= "none"
	}
}


function open_or_close(caller_name, object_name) {
	if (document.getElementById) {
		
		var object = $(object_name);
		var caller = $(caller_name);
		
		if (object.style.display != "block") {
			object.style.display = "block";
			caller.style.listStyleImage = "url(../media/imagenes/template/arrow_less.gif)";
			setCookie("klerix_" + object_name, true);
		} else {
			object.style.display= "none"
			caller.style.listStyleImage = "url(../media/imagenes/template/arrow_plus.gif)";
			setCookie("klerix_" + object_name, false);
		}
	}
}

function check_open_or_close(caller_name, object_name, defaul) {
	if (document.getElementById) {
		if(defaul == undefined) { defaul = false;}
		
		var object = $(object_name);
		var caller = $(caller_name);
		
		var remember = getCookie("klerix_" + object_name);
		if (remember == undefined){ remember = defaul; }
		
		if (remember == "true") {
			caller.style.listStyleImage = "url(../media/imagenes/template/arrow_less.gif)";
			object.style.display = "block";
		} else if (remember == "false") {
			caller.style.listStyleImage = "url(../media/imagenes/template/arrow_plus.gif)";
			object.style.display= "none";
		}
	}
}

function ajax_load(layer_id, url, params)
{
	show_spinner('spinner.gif', 'Cargando...');
	$(layer_id).innerHTML = "Cargando...";
	
	new Ajax.Request(url,
	  {
	    method: 'get',
		parameters: params,
	    onSuccess: function(transport){
	      var response = transport.responseText || "no hay respuesta";
		  $(layer_id).innerHTML = response;
		  hide_spinner();
	    },
	    onFailure: function(){ alert('Error: no se ha podido encontrar la pagina requerida...') }
	  });
}

function ajax_load_or_close(layer_id, url, params)
{
	var object = $(layer_id);
	if (object.style.display != "block") 
	{
		ajax_load(layer_id, url, params);
		object.style.display = "block";
	} 
	else 
	{
		object.style.display= "none"
	}
}

function live_update(obj, id) {
	if (id != '') {
		show_spinner();
		var table_name = obj.name.substring(0, obj.name.indexOf('['))
		var col_name = obj.name.substring(obj.name.indexOf('[') + 1, obj.name.indexOf(']'))
		alert("UPDATE " + table_name + " SET `" + col_name + "`='" + obj.value + "' WHERE `id`='" + id + "'");
	}
}

function ietruebody() {
	return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

var is_fadin = false;
function show_spinner(theimg, thetxt) {
	if (document.getElementById) {
		is_fadin = true;
		if (theimg == null) { theimg = 'spinner.gif'}
		if (thetxt == null) { thetxt = 'Cargando...'}
		var spinner = document.getElementById("spinner");
		
		spinner.style.display = "block";
		spinner.innerHTML = "<img src='../media/imagenes/icons/" + theimg + "' alt ='...' align='left' />&nbsp;&nbsp;" + thetxt
		spinner.style.top = (ietruebody().scrollTop + ietruebody().clientHeight / 4) + "px";
		spinner.style.left = ((ietruebody().clientWidth / 2) - (spinner.offsetWidth / 2)  )+ "px";
		opacity("spinner", 0, 100, 1000);
	}
}

function hide_spinner() {
	if (is_fadin)
	{
		setTimeout('opacity("spinner", 100, 0, 1000);', 1000)
		setTimeout("$('spinner').style.left = '-2000px'", 2001);
	}
	else
	{
		opacity("spinner", 100, 0, 1000);
		setTimeout("$('spinner').style.left = '-2000px'", 1001);
	}
}


// Esta es la función que usa Heinle para recuperar una cookie
// name - nombre de la cookie deseada
// devuelve un string conteniendo el valor de la cookie especificada o null si la cookie no existe

function getCookie(name){
  var cname = name + "=";               
  var dc = document.cookie;             
  if (dc.length > 0) {              
    begin = dc.indexOf(cname);       
    if (begin != -1) {           
      begin += cname.length;       
      end = dc.indexOf(";", begin);
      if (end == -1) end = dc.length;
        return unescape(dc.substring(begin, end));
    } 
  }
  return null;
}


// Esta es una adaptación de la función de Dorcht para colar una cookie
// name - nombre de la cookie
// value - valor de la cookie
// [expires] - fecha de caducidad de la cookie (por defecto, el final de la sesión)
// [path] - camino para el cual la cookie es válida (por defecto, el camino del documento que hace la llamada)
// [domain] - dominio para el cual la cookie es válida (por defecto, el dominio del documento que hace la llamada)
// [secure] - valor booleano que indica si la trasnmisión de la cookie requiere una transmisión segura
// al especificar el valor null, el argumento tomará su valor por defecto

function setCookie(name, value, expires, path, domain, secure) {
  document.cookie = name + "=" + escape(value) + 
  ((expires == null) ? "" : "; expires=" + expires.toGMTString()) +
  ((path == null) ? "" : "; path=" + path) +
  ((domain == null) ? "" : "; domain=" + domain) +
  ((secure == null) ? "" : "; secure");
}


// Esta es una adaptación de la función de Dorcht para borrar una cookie
// name - nombre de la cookie
// [path] - camino de la cookie (debe ser el mismo camino que el especificado al crear la cookie)
// [domain] - dominio de la cookie (debe ser el mismo dominio que el especificado al crear la cookie)
// se considera el camino y dominio por defecto si se especifica null o no se proporcionan argumentos

function delCookie (name,path,domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
    ((path == null) ? "" : "; path=" + path) +
    ((domain == null) ? "" : "; domain=" + domain) +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

/***********************************************
* Link Floatie script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/

var floattext=new Array()
floattext[0]='- <a href="http://www.javascriptkit.com/cutpastejava.shtml">Free JavaScripts</a><br>- <a href="http://www.javascriptkit.com/javaindex.shtml">JavaScript Tutorials</a><br>- <a href="http://www.javascriptkit.com/dhtmltutors/index.shtml">DHTML/ CSS Tutorials</a><br>- <a href="http://www.javascriptkit.com/jsref/">JavaScript Reference</a><br><div align="right"><a href="javascript:hidefloatie()">Hide Box</a></div>'
floattext[1]='Some other floatie text'

var fadespeed = 0 //speed of fade (5 or above). Smaller=faster.

var baseopacity=0
function slowhigh(which2){
	imgobj=which2
	browserdetect=which2.filters? "ie" : typeof which2.style.MozOpacity=="string"? "mozilla" : ""
	instantset(baseopacity)
	highlighting=setInterval("gradualfade(imgobj)",fadespeed)
}

function instantset(degree){
	cleartimer()
	if (browserdetect=="mozilla")
		imgobj.style.MozOpacity=degree/100
	else if (browserdetect=="ie")
		imgobj.filters.alpha.opacity=degree
}

function cleartimer(){
	if (window.highlighting) clearInterval(highlighting)
}

function gradualfade(cur2){
	if (browserdetect=="mozilla" && cur2.style.MozOpacity<1)
		cur2.style.MozOpacity=Math.min(parseFloat(cur2.style.MozOpacity)+0.1, 0.99)
	else if (browserdetect=="ie" && cur2.filters.alpha.opacity<100)
		cur2.filters.alpha.opacity+=10
	else if (window.highlighting)
		clearInterval(highlighting)
}

function ietruebody(){
	return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function paramexists(what){
	return(typeof what!="undefined" && what!="")
}


function showfloatie(thetext, e, optbgColor, optWidth, optHeight){
	var dsocx=(window.pageXOffset)? pageXOffset: ietruebody().scrollLeft;
	var dsocy=(window.pageYOffset)? pageYOffset : ietruebody().scrollTop;
	var floatobj=document.getElementById("dhtmlfloatie")
	
	floatobj.style.left="-900px"
	floatobj.style.display="block"
	//floatobj.style.backgroundColor=paramexists(optbgColor)? optbgColor : floatiebgcolor
	//floatobj.style.width=paramexists(optWidth)? optWidth+"px" : floatiewidth
	//floatobj.style.height=paramexists(optHeight)? optHeight+"px" : floatieheight!=""? floatieheight : ""
	
	floatobj.innerHTML = thetext
	
	var floatWidth=floatobj.offsetWidth>0? floatobj.offsetWidth : floatobj.style.width
	var floatHeight=floatobj.offsetHeight>0? floatobj.offsetHeight : floatobj.style.width
	var winWidth=document.all&&!window.opera? ietruebody().clientWidth : window.innerWidth-20
	var winHeight=document.all&&!window.opera? ietruebody().clientHeight : window.innerHeight
	
	e = window.event? window.event : e
	floatobj.style.left=dsocx+winWidth-floatWidth-5+"px"
	
	//if (e.clientX>winWidth-floatWidth && e.clientY+20>winHeight-floatHeight)
		//floatobj.style.top=dsocy+5+"px"
	//else
		floatobj.style.top=dsocy+winHeight-floatHeight-5+"px"
	slowhigh(floatobj)
}

var cancel = false;
function ajaxfloatie(file, param)
{
	cancel = false;
	var ajaxRequest = new Ajax.Request(
	    file,
	    {
	            method: 'get',
	            parameters: param,
	            asynchronous: true,
	            onComplete: callback_ajaxrequestfloatie
	    });
}

function callback_ajaxrequestfloatie(xmlHttpRequest, responseHeader)
{
	if (!cancel)
	{
		showfloatie(xmlHttpRequest.responseText, window.event)
	}
}

function hidefloatie(){
	cancel = true;
	var floatobj=document.getElementById("dhtmlfloatie")
	floatobj.style.display="none"
}


/***********************************************
* Cool DHTML tooltip script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/

var offsetxpoint=-60 //Customize x offset of tooltip
var offsetypoint=20 //Customize y offset of tooltip
var ie=document.all
var ns6=document.getElementById && !document.all
var enabletip=false
var tipobj=document.all? document.all["dhtmltooltip"] : document.getElementById? document.getElementById("dhtmltooltip") : ""

function ietruebody(){
	return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function ttt(thetext, thecolor, thewidth){
	if (ns6||ie){
		tipobj = document.all? document.all["dhtmltooltip"] : document.getElementById? document.getElementById("dhtmltooltip") : ""
		if (typeof thewidth!="undefined") tipobj.style.width=thewidth+"px"
		if (typeof thecolor!="undefined" && thecolor!="") tipobj.style.backgroundColor=thecolor
		tipobj.innerHTML=thetext
		enabletip=true
		return false
	}
}

function positiontip(e){
	if (enabletip){
		var curX=(ns6)?e.pageX : event.clientX+ietruebody().scrollLeft;
		var curY=(ns6)?e.pageY : event.clientY+ietruebody().scrollTop;
		//Find out how close the mouse is to the corner of the window
		var rightedge=ie&&!window.opera? ietruebody().clientWidth-event.clientX-offsetxpoint : window.innerWidth-e.clientX-offsetxpoint-20
		var bottomedge=ie&&!window.opera? ietruebody().clientHeight-event.clientY-offsetypoint : window.innerHeight-e.clientY-offsetypoint-20
		
		var leftedge=(offsetxpoint<0)? offsetxpoint*(-1) : -1000
		
		//if the horizontal distance isn't enough to accomodate the width of the context menu
		if (rightedge<tipobj.offsetWidth)
			//move the horizontal position of the menu to the left by it's width
			tipobj.style.left=ie? ietruebody().scrollLeft+event.clientX-tipobj.offsetWidth+"px" : window.pageXOffset+e.clientX-tipobj.offsetWidth+"px"
		else if (curX<leftedge)
			tipobj.style.left="5px"
		else
			//position the horizontal position of the menu where the mouse is positioned
			tipobj.style.left=curX+offsetxpoint+"px"
		
		//same concept with the vertical position
		if (bottomedge<tipobj.offsetHeight)
			tipobj.style.top=ie? ietruebody().scrollTop+event.clientY-tipobj.offsetHeight-offsetypoint+"px" : window.pageYOffset+e.clientY-tipobj.offsetHeight-offsetypoint+"px"
		else
			tipobj.style.top=curY+offsetypoint+"px"
		
		tipobj.style.visibility="visible"
	}
}

function httt(){
	if (ns6||ie){
		enabletip=false
		tipobj.style.visibility="hidden"
		tipobj.style.left="-1000px"
		tipobj.style.backgroundColor=''
		tipobj.style.width=''
	}
}

document.onmousemove=positiontip


function opacity(id, opacStart, opacEnd, millisec) {
    //speed for each frame
    var speed = Math.round(millisec / 100);
    var timer = 0;

    //determine the direction for the blending, if start and end are the same nothing happens
    if(opacStart > opacEnd) {
        for(i = opacStart; i >= opacEnd; i--) {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
		setTimeout("is_fadin=false", timer * speed);
		return timer * speed;
    } else if(opacStart < opacEnd) {
        for(i = opacStart; i <= opacEnd; i++)
            {
            setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
		setTimeout("is_fadin=false", timer * speed);
    }
}

//change the opacity for different browsers
function changeOpac(opacity, id) {
    var object = document.getElementById(id).style;
    object.opacity = (opacity / 100);
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
    object.filter = "alpha(opacity=" + opacity + ")";
} 


//Validar mail
function Validate_String(string, return_invalid_chars)
 {
 valid_chars = '1234567890-_.^~abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
 invalid_chars = '';
 
 if(string == null || string == '')
    return(true);
 
 //For every character on the string.   
 for(index = 0; index < string.length; index++)
    {
    var ch = string.substr(index, 1);                        
    
    //Is it a valid character?
    if(valid_chars.indexOf(ch) == -1)
      {
      //If not, is it already on the list of invalid characters?
      if(invalid_chars.indexOf(ch) == -1)
        {
        //If it's not, add it.
        if(invalid_chars == '')
           invalid_chars += ch;
        else
           invalid_chars += ', ' + ch;
        }
      }
    }                     
    
 //If the string does not contain invalid characters, the function will return true.
 //If it does, it will either return false or a list of the invalid characters used
 //in the string, depending on the value of the second parameter.
 if(return_invalid_chars == true && invalid_chars != '')
   {
   last_comma = invalid_chars.lastIndexOf(',');
   
   if(last_comma != -1)
      invalid_chars = invalid_chars.substr(0, $last_comma) + 
      ' and ' + invalid_chars.substr(last_comma + 1, invalid_chars.length);
              
   return(invalid_chars);
   }
 else
   return(invalid_chars == ''); 
 }


function validate_email_address(email_address)
 {
 //Assumes that valid email addresses consist of user_name@domain.tld
 at = email_address.indexOf('@');
 dot = email_address.indexOf('.');
 
 if(at == -1 || 
    dot == -1 || 
    dot <= at + 1 ||
    dot == 0 || 
    dot == email_address.length - 1)
    return(false);
    
 user_name = email_address.substr(0, at);
 domain_name = email_address.substr(at + 1, email_address.length);                  
 
 if(Validate_String(user_name) === false || 
    Validate_String(domain_name) === false)
    return(false);                     
 
 return(true);
 }
 
function es_mail(ob)
{
	if(!validate_email_address(ob.value))
	{
		ob.style.border = "1px red solid";
		$('mail_valido').innerHTML = '<img src="../media/imagenes/icons/cancel.png" alt=""/> El mail no es v&aacute;lido.';
	}
	else
	{
		ob.style.border = "1px green solid";
		$('mail_valido').innerHTML = '<img src="../media/imagenes/icons/accept.png" alt=""/> El mail es v&aacute;lido.';
	}
}
