/**************************************************************************
Librera JavaScript para the shaker                        
*************************************************************************/

/* ------------------------------------------------------------------------
// usos generales
-------------------------------------------------------------------------*/ 
function addEventToObject(obj,evt,func) {
	var oldhandler = obj[evt];
	obj[evt] = (typeof obj[evt] != 'function') ? func : function(ev){oldhandler(ev);func(ev);};
}

function stopDefaultAction(ev) {
	if (!ev) {ev = window.event;}
	if (ev.stopPropagation) {
		ev.stopPropagation(); 
	} else {
		ev.cancelBubble = true;
	}
	if (ev.preventDefault) {
		ev.preventDefault(); 
	} else { 
		ev.returnValue = false;
	}
	return false;
}

/* ------------------------------------------------------------------------
combo de login
-------------------------------------------------------------------------*/ 
var LoginBox = {
 visibilidad: 0,
 init : function()
 {
   var cmb = LoginBox;
   if (!document.getElementById) {return false;}
   var linklogind = $('link-login');
   var combo = $('combo-login');
   var linklogincomments = $('link-login-comments');

   if (!linklogind) {return false;}
   if (!combo) {return false;}
   if (navigator.userAgent.toLowerCase().indexOf('opera') != -1) {return false;}
   addEventToObject(linklogind,'onclick',cmb.click);

   // para comentarios
   if(linklogincomments) {addEventToObject(linklogincomments,'onclick',cmb.click);}
 },
 click : function(ev)
 {
   var cmb = LoginBox;
   if (!ev) {ev = window.event;}
 	 var elem;
	 if (ev.target) {
		elem = ev.target;
	 } else {
		elem = ev.srcElement;
	 }
   cmb.show(elem.id);
   stopDefaultAction(ev);
   return false;
 },
 show : function(targetid)
 {
   var cmb = LoginBox;
   var poslink = Position.cumulativeOffset($(targetid));
   var combo = $('combo-login');
   combo.style.visibility = 'visible';
   if(targetid=='link-login'){
     combo.style.left = (poslink[0] -(combo.offsetWidth-42)) + 'px';
     combo.style.backgroundPosition = 'top right';
     document.loginform.action = '/login/authenticate';
     document.loginform.target = '';

   } else {
     combo.style.left = poslink[0] + 'px';
     combo.style.backgroundPosition = '134% 0';
     combo.style.backgroundRepeat = 'repeat-x';
     document.loginform.action = '/login/authenticate/ajax';
     document.loginform.target = 'logoperations';
   }


   combo.style.top = (poslink[1] + $('link-login').offsetHeight + 2) + 'px';
   document.loginform.name.focus();
   cmb.visibilidad = 1;
 },
 hide : function()
 {
   var cmb = LoginBox;
   if ($('combo-login')) {$('combo-login').style.visibility = 'hidden';}
   cmb.visibilidad = 0;
 }
};

// definimos eventos
addEventToObject(window,'onresize',LoginBox.hide);



/* ------------------------------------------------------------------------
burbuja en perfil 
-------------------------------------------------------------------------*/ 
var perfilBubble = {
	visibilidad: 0,
	showit: 1,
	valor: 0,

	click : function(valor, ciudad, pais, amigo, nologueado, dominio, dominio_usuario)
	{
		var cmb = perfilBubble;
		if(cmb.valor == valor) {
			if (cmb.visibilidad === '0') {cmb.show(valor);} else { cmb.hide();}
		} else  {
			cmb.show(valor, ciudad, pais, amigo, nologueado, dominio, dominio_usuario);
		}
		return false;
	},
	show : function(valor, ciudad, pais, amigo, nologueado, dominio, dominio_usuario)
	{
		var cmb = perfilBubble;
		if(cmb.showit == 1 ){
			// reseteamos combos
			$('burbuja-perfil-load').style.display = 'none';
			$('burbuja-perfil-lista').style.display = 'block';


			var avatar = $('burbuja'+valor);
			var combo = $('burbuja-perfil');

			// update de los enlaces y de los datos
			var contenido = '';
			contenido += '<ul class="burbuja-perfil">';
			contenido += '	<li class="cerrar"><a href="#" onclick="perfilBubble.hide(); return false;"><img src="../imag/ed/bot_cerrar_mini.gif" alt="cerrar" /></a></li>';
			contenido += '	<li class="burbuja-perfil"><strong class="burbuja-perfil">'+valor+'</strong> ';

			contenido += '</li>';
			contenido += '	<li id="esamigo'+valor+'" class="burbuja-perfil">';

			$('burbuja-perfil-lista').innerHTML = contenido;

			// iniciamos el lightbox
			window.initLightbox();

			// posicion del avatar
			var posavatar = Position.cumulativeOffset(avatar);
			combo.style.visibility = 'visible';
			combo.style.left = (posavatar[0] - 6) + 'px';
			combo.style.top = (posavatar[1] + avatar.offsetHeight - 4) + 'px';

			cmb.visibilidad = 1;
			cmb.valor = valor;
		}

	},
	hide : function()
	{
		var cmb = perfilBubble;
		if ($('burbuja-perfil')) {$('burbuja-perfil').style.visibility = 'hidden';}
		cmb.visibilidad = 0;
	},
	setvalue : function(valor)
	{

	}
};

// definimos eventos
addEventToObject(window,'onresize',perfilBubble.hide);



/* ------------------------------------------------------------------------
Combo sharethis 
-------------------------------------------------------------------------*/ 
var shareThis = {
	visibilidad: 0,
	
	show : function(id)
	{
		var omb = shareThis;
			
			var combo = $('sharethis_combo_' + id);
			var linkshare = $('sharethis_' + id);
			var contenido = $('contenido');

			var poslinkshare = Position.cumulativeOffset(linkshare);
			var poscontenido = Position.cumulativeOffset(contenido);
			combo.style.visibility = 'visible';
			combo.style.left = (poscontenido[0] + ((contenido.offsetWidth - combo.offsetWidth)/2) ) + 'px';
			combo.style.top = (poslinkshare[1] + linkshare.offsetHeight + 2) + 'px';
			//$('sendfriend').style.display = 'none';	
			//$('datos_envio').style.display = 'block';

			omb.visibilidad = 1;
			return false;
	},
	hide : function(id)
	{
		var omb = shareThis;
		if ($('sharethis_combo_' + id)) {$('sharethis_combo_' + id).style.visibility = 'hidden';}
		omb.visibilidad = 0;
		return false;
	}

};

// definimos eventos
addEventToObject(window,'onresize',shareThis.hide);


/* ------------------------------------------------------------------------
Toggle para descripciones largas en sobre mi 
-------------------------------------------------------------------------*/ 

var descripcionToggle = {
	show : function()
	{
		if($('sobremi-layer-resumen')){
			$('sobremi-layer-resumen').style.display = 'none';
			$('sobremi-layer').style.display = 'block';
		}
	}	,
	hide : function()
	{
		if($('sobremi-layer-resumen')) {
			$('sobremi-layer-resumen').style.display = 'block';
			$('sobremi-layer').style.display = 'none';
		}
	}	
};


/* ------------------------------------------------------------------------
selecciona la plantilla actual y elimina la selección del resto
-------------------------------------------------------------------------*/ 

// function selectCurrentTemplate(current, className) {
//  var templates = $$('.template');
//  for(var i=0;i<templates.length;i++) {
//    var template = templates[i];
//    var links = $$('.'+className);
//    if (links.length > 0) {
//      for(var j=0;j<links.length;j++) {
//        links[j].removeClassName(className);  
//      }
//    }
//  }
//  $(current).addClassName(className);
// }

function selectCurrentTemplate(current, className) {
	var links = $$('.'+className);
	for(var j=0;j<links.length;j++) {
		links[j].removeClassName(className);	
	}
	$(current).addClassName(className);
}

function getFormValues(fobj){
	var str='';
	for(var i=0;i< fobj.elements.length;i++){
			value = fobj.elements[i].value;
			if ((fobj.elements[i].name == 'post[categories][]') || (fobj.elements[i].name == 'post[closed_trackbacks]') || (fobj.elements[i].name == 'post[closed_comments]') || (fobj.elements[i].name == 'tag[name]')) {
	      continue;
			}
			if (fobj.elements[i].name == 'post[body]') {
				if (encodeURIComponent) {
				    value = encodeURIComponent(value);
				} else {
				    value = escape(value);
				}
			}
			str+=fobj.elements[i].name+'='+value+'&';		
	}
	str=str.substr(0,(str.length-1));
	return str;
}


/* ------------------------------------------------------------------------
autosave 
-------------------------------------------------------------------------*/ 
var autoSave = {
	iniciado: 0,
	intervalo: '',
	titulo: '',
	cuerpo: '',

	init : function()
	{
		var as = autoSave;
		as.iniciado = 1;
		intervalo = 30000;
		titulo = $('title_aux').value;
		
		var ed = tinyMCE.get('texto_aux');
    var mode = '';
    if (!ed || ed.isHidden()) { 
      mode = 'html';
    } else {
			mode = 'design';
		}
		if (mode == 'html') {cuerpo = $('texto_aux').value;}
		else {
			if (mode == 'design') {
				if ($('texto_disenio'))
					{cuerpo = $('texto_disenio').contentWindow.document.body.innerHTML;}
				else {
					var ed = tinyMCE.get('texto_aux');			
					if (!ed || ed.isHidden()) { 
						cuerpo = $('texto_aux').value;
					} else {
						cuerpo = tinyMCE.get('texto_aux').getContent();
					}				
				}
			}
			else {
				if (mode == 'design_new_wysiwyg') {
					
				}
			}
		}
		// esperamos [intervalo] segundos para comenzar a autoguardar
		setTimeout(function() {autoSave.save();}, intervalo);
	},
	save : function ()
	{
		var as = autoSave;
		var actual = '';
		var ed;
		var ed = tinyMCE.get('texto_aux');
    var mode = '';
    if (!ed || ed.isHidden()) { 
      mode = 'html';
    } else {
			mode = 'design';
		}
		titulo = $('title_aux').value;
		if (mode == 'html') {cuerpo = $('texto_aux').value;}
		else {
			if ($('texto_disenio'))
				{actual = $('texto_disenio').contentWindow.document.body.innerHTML;}
			else {
				ed = tinyMCE.get('texto_aux');			
				if (!ed || ed.isHidden()) { 
					actual = $('texto_aux').value;
				} else {
					actual = tinyMCE.get('texto_aux').getContent();
				}				
			}
		}

		// El WYSIWYG vacío viene con un <br>
		if ((actual != '<br>') && (titulo != $('title_aux').value || cuerpo != actual)){

			titulo = $('title_aux').value;

			titulo = $('title_aux').value;
			if (mode == 'html') {cuerpo = $('texto_aux').value;}
			else {
				if ($('texto_disenio'))
					{cuerpo = $('texto_disenio').contentWindow.document.body.innerHTML;}
				else {
					ed = tinyMCE.get('texto_aux');			
					if (!ed || ed.isHidden()) { 
						cuerpo = $('texto_aux').value;
					} else {
						cuerpo = tinyMCE.get('texto_aux').getContent();
					}				
				}
			}

			document.newpostform.post_title.value = $('title_aux').value;
			document.newpostform.post_body.value = cuerpo;

			params = getFormValues($('newpostform'));

		  updater = new Ajax.Updater('status','/ap/posts/autosave', { method:'post', parameters:params, asynchronous:true,  onSuccess:autoSave.ok, onComplete:autoSave.activa });
		}
		setTimeout(function() { autoSave.save(); }, intervalo);
	},
	ok : function()
	{
		$('status').style.visibility = 'visible';
	},
	ko : function()
	{
		$('status').style.visibility = 'visible';
	},
	desactiva : function ()
	{
		$('botonBorrador').disabled = true;
		$('botonPublicar').disabled = true;
	},
	activa : function ()
	{
		$('botonBorrador').disabled = false;
		$('botonPublicar').disabled = false;
	}
};


/* ------------------------------------------------------------------------
cancelar eventos 
-------------------------------------------------------------------------*/ 

Event.observe(document, 'click', function(e){ 
	var elem;
	if (e.target) {elem = e.target;} else {elem = e.srcElement;}
	if(elem.parentNode.className != 'burbuja-perfil') {perfilBubble.hide();}
}, false);

/* ------------------------------------------------------------------------
funciones para step1 
-------------------------------------------------------------------------*/
function actualiza_nom(valor){
	if (valor === '') {$('nom-usuario').innerHTML = 'nombredeusuario';}
	else {$('nom-usuario').innerHTML = valor;}
}

function previsualizar_select(select_domain, preview_domain) {
	$("_preview_domain_id_").innerHTML = $("select_domain")[$("select_domain").selectedIndex].text;
}

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

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

function getExpDate(days, hours, minutes)
{
	var expDate = new Date();
	if(typeof(days) == "number" && typeof(hours) == "number" && typeof(hours) == "number")
	{
		expDate.setDate(expDate.getDate() + parseInt(days));
		expDate.setHours(expDate.getHours() + parseInt(hours));
		expDate.setMinutes(expDate.getMinutes() + parseInt(minutes));
		return expDate.toGMTString();
	}
}


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

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


function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	}
	else {
		window.onload = function() {
			oldonload();
			func();
		};
	}
}

function load_index_create_blog() {
	var cookie =  getCookie('index_lacoctelera');
	if (cookie) { 
		$('crea-tu-blog').style.display="none";
	}
}


function load_user_options() {
	var uploader_load_user_options = new Ajax.Updater('user-options','/ap/ap/get_user_options', {evalScripts: true});
}

function user_comments_form(){
	// LoginBox.hide()
	var user_comments_form_uploader1 = new Ajax.Updater('user-options','/ap/ap/get_user_options', {evalScripts: true, onSuccess: function(request) {
		var user_comments_form_uploader2 = new Ajax.Updater('user-comments-form','/ap/ap/label?label=user-comments-form', {evalScripts: true}); 
	}});
}


/* ------------------------------------------------------------------------
Functiones antispam
-------------------------------------------------------------------------*/ 

function unset_focus() { if (document.dataform.lt.value==='0') { f=new Date(); document.dataform.lt.value=f.getTime(); } }
function enviaFormulario() { fechasubmit = new Date(); document.dataform.st.value = fechasubmit.getTime(); }

/**************************************************************************************
	contenido del antiguo edGeneral.js 
***************************************************************************************/

/* Adapted from http://www.kryogenix.org/code/browser/searchhi/ */
/* Improved with RoR trac(http://trac.edgewall.com)'s http://dev.rubyonrails.com/trac/trac.js */
function searchHighlight() {
	if (!document.createElement) {return;}

	var div = document.getElementById("contenido");
	if (!div) {return;}

	function getSearchWords(url) {
		if (url.indexOf('?') == -1) {return [];}
		qs = url.substr(url.indexOf('?')+1);
		qsa = qs.split('&');
		for (i=0;i<qsa.length;i++) {
			qsip = qsa[i].split('=');
			if (qsip.length < 2) {continue;}
			if (qsip[0] == 'q' || qsip[0] == 'p' || qsip[0] == 'what') { // q= for Google, p= for Yahoo, what= for shakers
				return unescape(qsip[1].replace(/\+/g,' ')).split(/\s+/);
			}
		}
		return [];
	}
		
	function highlightWord(node,word,searchwordindex) {
		// Do this node itself
		if (node.nodeType == 3) { // text node
			tempNodeVal = node.nodeValue.toLowerCase();
			tempWordVal = word.toLowerCase();
			ni = tempNodeVal.indexOf(tempWordVal);
			pn = node.parentNode;
			if (ni >= 0 && !/^searchword\d$/.test(pn.className)) {
				var span = document.createElement("span");
				span.className = "searchword" + (searchwordindex % 5);
				span.appendChild(document.createTextNode(node.nodeValue.substr(ni, word.length)));
				var newNode = node.splitText(ni);
				newNode.nodeValue = newNode.nodeValue.substr(word.length);
				pn.insertBefore(span, newNode);
				return true;	
			}
		} else if (!node.nodeName.match(/button|select|textarea/i)) {
			// Recurse into child nodes
			for (var i = 0; i < node.childNodes.length; i++) {
				if (highlightWord(node.childNodes[i], word, searchwordindex)) {i++;}
			}
		}
		return false;
	}

	var words = getSearchWords(document.URL);
	if (!words.length) {words = getSearchWords(document.referrer);}
	if (words.length) {
		for (var w in words) {
			if (words[w].length) {highlightWord(div, words[w], w);}
		}
	}
	
}

function jump_to(select) {
  if (select.value.length > 0 && select.value != 'null') {
    window.location.href = select.value;
    return true;
  }
  return false;
}


/**************************************************************************************
	contenido del antiguo apGeneral.js 
***************************************************************************************/

var xmlhttp=false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
  try {
  xmlhttp=new ActiveXObject("Msxml2.XMLHTTP")
 } catch (e) {
  try {
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
  } catch (E) {
   xmlhttp=false
  }
 }
@else
 xmlhttp=false
@end @*/

if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
 try {
  xmlhttp = new XMLHttpRequest();
 } catch (e) {
  xmlhttp=false;
 }
}

function previsualizar(id1, id2){
	var defvalue=(arguments.length==3)?arguments[2]:''; 
	var NewText = document.getElementById(id1).value;
	if (NewText.length === '0' && defvalue.length > 0) {NewText = defvalue; }
	if (NewText.length > 0) {
		splitText = NewText.split(/\n/).join("<br />");
		var DivElement = document.getElementById(id2);
		DivElement.innerHTML = splitText;
	}
}

function update_value(id1,id2) {
	var element_source = document.getElementById(id1);
	var element_target = document.getElementById(id2);
	element_target.href = 'ap/adminviews/edit/' + element_source.value;
}

function sanitize(from_id,to_id) {
        nicetitle = document.getElementById(to_id);
        titulo = document.getElementById(from_id);
                t = titulo.value;
                t = t.toLowerCase();
                b = "";
                c = "";
                for(i=0;i<t.length;i++) {
                        ch = t.charAt(i);
                                switch(ch) {
                                        case 'a':
                                        case 'b':
                                        case 'c':
                                        case 'd':
                                        case 'e':
                                        case 'f':
                                        case 'g':
                                        case 'h':
                                        case 'i':
                                        case 'j':
                                        case 'k':
                                        case 'l':
                                        case 'm':
                                        case 'n':
                                        case 'o':
                                        case 'p':
                                        case 'q':
                                        case 'r':
                                        case 's':
                                        case 't':
                                        case 'u':
                                        case 'v':
                                        case 'w':
                                        case 'x':
                                        case 'y':
                                        case 'z':
                                        case '1':
                                        case '2':
                                        case '3':
                                        case '4':
                                        case '5':
                                        case '6':
                                        case '7':
                                        case '8':
                                        case '9':
                                        case '0':
                                                b = b + ch;
                                                break;
                                        case 'á':
                                                b = b + 'a';
                                                break;
                                        case 'é':
                                                b = b + 'e';
                                                break;
                                        case 'í':
                                                b = b + 'i';
                                                break;
                                        case 'ó':
                                                b = b + 'o';
                                                break;
                                        case 'ú':
                                                b = b + 'u';
                                                break;
                                        case ' ':
                                                b = b + '-';
                                                break;
                                        default:
                                                b = b;
                                                break;
                                }
                }
                i = b.length-1;
                while (i > 0 && b[i] == '-') {
                        i--;
                }
                b = b.substring(0,i+1);
                nicetitle.value = b;
}


// fguillen 2008-11-25
// retorna el string sanitizado
function to_slug(string) {
  string = string.toLowerCase();
  var result = ""
  for(var i=0;i<string.length;i++) {
    var ch = string.charAt(i)
    switch(ch) {
      case 'a':
      case 'b':
      case 'c':
      case 'd':
      case 'e':
      case 'f':
      case 'g':
      case 'h':
      case 'i':
      case 'j':
      case 'k':
      case 'l':
      case 'm':
      case 'n':
      case 'o':
      case 'p':
      case 'q':
      case 'r':
      case 's':
      case 't':
      case 'u':
      case 'v':
      case 'w':
      case 'x':
      case 'y':
      case 'z':
      case '1':
      case '2':
      case '3':
      case '4':
      case '5':
      case '6':
      case '7':
      case '8':
      case '9':
      case '0':
        result = result + ch
        break
      case 'á':
        result = result + 'a'
        break
      case 'é':
        result = result + 'e'
        break
      case 'í':
        result = result + 'i'
        break
      case 'ó':
        result = result + 'o'
        break
      case 'ú':
        result = result + 'u'
        break
      case 'ñ':
        result = result + 'n'
        break
      case ' ':
        result = result + '-'
        break
      default:
        result = result + '-'
        break
      }
    }
  var i = result.length-1
  while (i > 0 && result[i] == '-') {
    i--
  }
  result = result.substring(0,i+1)
  return result
}


function checkSubmit(e) {
  var characterCode;

  if(e && e.which) {
    e = e;
    characterCode = e.which;
  }
  else{
    if (window.event) {
      e = event;
      characterCode = e.keyCode;
    }
  }
  if(characterCode == 13){
    return false;
  }
  else{
    return true;
  }
}

function getLastSpace(elem,car) {
    var pos = -1;
    for (var i = 0; i < elem.length; i++) {
      if (elem[i] == car) {
        pos = i;
      }
    }
    return pos;
}

function stripCounter(elem) {
  var newElem;
  var pos = elem.indexOf('(');
  if (pos >= 0) 
    {newElem = elem.substr(0,pos-1);}
  else
    {newElem = elem;}
  return newElem;
}

function hasSpaces(elem) {
  var count = 0;
  for (var i=0;i<=elem.length;i++) {
    if (elem[i] == ' ') 
      {count++;}
  }
  if (count > 0)
    {return true;}
  return false;
}

function addcategory() {
	Element.show('spinner');
  frm=document.getElementById('newpostform');
  url="ap/categories/newidfor?category="+frm.elements['newcategory'].value;
  brandnew=frm.elements['newcategory'].value;
	// Devolvemos si la cadena es vacia
	if (brandnew == '') { 
		Element.hide('spinner');
    Element.hide('agregarNuevaCategoria');
	  Element.show('link-anade');
		return false;
	}
  frm.elements['newcategory'].value='';
  xmlhttp.open("GET",url,true);
  xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState==4) {
			chkbx = '<input type="checkbox" name="post[categories][]" id="b" value="'+xmlhttp.responseText+'" checked ><label for="b">';
			chkbx += brandnew + '</label> <br>';
			document.getElementById('lista-categorias-1').innerHTML+= chkbx;
	  }
  };
  xmlhttp.setRequestHeader('Accept','message/x-formresult');
  xmlhttp.send(null);
	Element.hide('spinner');
  Element.hide('agregarNuevaCategoria');
  Element.show('link-anade');
  return false;
}

function toggleCheckBoxes(formId) {
  if(!document.forms[formId]) { return; }
  var objCheckBoxes = document.forms[formId].elements; 
  if(!objCheckBoxes) { return; }
  var countCheckBoxes = objCheckBoxes.length;
  if(!countCheckBoxes) {
    objCheckBoxes.checked = CheckValue;
  }
  else {
    for(var i = 0; i < countCheckBoxes; i++) {
      objCheckBoxes[i].checked = !objCheckBoxes[i].checked;
    }
  }
}

function toggleCheckBox(id) {
	var main_checkbox = document.getElementById(id);
	if (main_checkbox) {
		main_checkbox.checked = !main_checkbox.checked;
	}
}


function insertAtCursor(myField, myValue) {
  myField = document.getElementById(myField);
  //IE support
  if (document.selection) {
    myField.focus();
    sel = document.selection.createRange();
    sel.text = myValue;
  }
  //MOZILLA/NETSCAPE support
  else if (myField.selectionStart || myField.selectionStart == '0') {
    var startPos = myField.selectionStart;
    var endPos = myField.selectionEnd;
    myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
  } else {
    myField.value += myValue;
  }
}

function hideCSSEditing() {
  if (!document.getElementsByTagName) {return false;}
  var radios = document.getElementsByTagName('input');
  for (var i=0; i<radios.length; i++) {
    if (radios[i].name.match("layout") && radios[i].id != 'layout-miCSS') {
      radios[i].onclick = function() {
        var edita = document.getElementById('editaCSS');
        if (edita) {
          Element.hide('editaCSS');
        }
      };
    }
  }
}

function showCSSEditing() {
  if (!document.getElementsByTagName) {return false;}
  var editing = document.getElementById('layout-miCSS');
  if (editing) {
    editing.onclick = function() {
      $('editaCSS').toggle();
    };
  }
}

/**  huella de stats segun canales **/
var zonas = $H({
  'amor': ['amor', 'contactos', 'amigos', 'poemas', 'amistad', 'sentimientos', 'reflexiones', 'mujer', 'tristeza', 'vida', 'sexo', 'filosofia', 'soledad'], 
  'cine': ['cine', 'pelicula', 'peliculas', 'oscar', 'oscars', 'bardem', 'hollywood' ],
  'cultura': ['cultura', 'cuentos', 'arte', 'exposiciones', 'literatura', 'libros', 'lectura', 'novela'],
  'economia': ['economia', 'politica', 'dinero', 'hipoteca', 'banco', 'inversion', 'paro', 'natalidad', 'demografia', 'vivienda', 'trabajo'],
  'deportes': ['deportes', 'deporte', 'futbol', 'formula1', 'formula-1', 'alonso', 'baloncesto', 'nba', 'acb', 'atletismo', 'tenis', 'golf'],
  'educacion': ['educacion', 'universidad', 'colegio', 'estudios', 'estudiar', 'master', 'mba', 'padres', 'familia', 'sociedad', 'aprender'],
  'fotografia': ['fotografia', 'fotos', 'foto', 'canon', 'nikon', 'imagen', 'imagenes', 'macro', 'photoshop'],
  'humor': ['humor', 'chiste', 'video', 'videos', 'curiosidades', 'curiosidad', 'friki', 'freak', 'demografia', 'vivienda', 'trabajo'],
  'musica': ['musica', 'rock', 'pop', 'beatles', 'shakira', 'cancion', 'canciones', 'mp3', 'letras', 'videoclip'],
  'noche': ['noche', 'fiesta', 'diversion', 'salir', 'discoteca', 'bar', 'pub', 'bares', 'disco'],
  'tecnologia': ['tecnologia', 'internet', 'blog', 'tic', 'web', 'google', 'windows', 'microsoft', 'gadgets', 'apple', 'mac', 'iphone', 'telefono', 'movil'],
  'television': ['television', 'medios', 'radio', 'series', 'lost', 'perdidos', 'antena3', 'telecinco', 'la-sexta', 'tve', 'tv', 'guion', 'eurovision', 'medios', 'peridismo'],
  'viajes': ['viajes', 'viajar', 'avion', 'tren', 'agencia', 'turismo', 'vacaciones']
});

function statsCanales(tags) {
  var zona = "home";
  if(tags === "") {
  
  } else {
    tags.each(function(tag) {
      zonas.each(function(pair) {
        if (pair.value.indexOf(tag) >= 0) {
          zona = pair.key;
          return false;
        }
      });
    });
  }
  return zona;
}

/****** Opciones de usuario ********/
function goToAnchor(anchor) {
   var thelocation = document.location.toString();
   var thelocationsplit = thelocation.split('#');
   document.location = thelocationsplit[0] + '#' + anchor;
}

function cleanAnchor() {
   var thelocation = document.location.toString();
   var thelocationsplit = thelocation.split('#');
   document.location = thelocationsplit[0];
}

function resizeImageContainer( imgWidth, imgHeight) {

	Element.setWidth('outerImageContainer', imgWidth + (borderSize * 2));
	Element.setHeight('outerImageContainer', imgHeight + (borderSize * 2));
	Element.setHeight( 'preview_blog', imgHeight + (borderSize * 2) - 41);
	Element.setWidth( 'preview_iframe', imgWidth + (borderSize * 2) );
	if (document.width > 1024) {
		Element.setWidth( 'preview_blog', imgWidth + (borderSize * 2) + 20 );
	} else {
		Element.setWidth( 'preview_blog', imgWidth + (borderSize * 2) );
	}
  Element.setHeight( 'preview_iframe', imgHeight + (borderSize * 2) - 41);

}


function preparePreview() {
	$('preview_template').show();
	var arrayPageSize = getPageSize();
	Element.setHeight('overlay', arrayPageSize[1]);		
	var appear = new Effect.Appear('overlay', { duration: 0.2, from: 0.0, to: 0.8 });	
	
	arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();
	var lightboxTop = arrayPageScroll[1] + (arrayPageSize[3] / 15);

	Element.setTop('lightbox', lightboxTop);
	Element.show('lightbox');
	if (document.width > 1024) {
		resizeImageContainer(1024, 520);
	} else {
		resizeImageContainer(980, 520);
	}
}


function cleanPasswords() {
	if (document.getElementById('original_password')) {
		document.getElementById('original_password').value = '';
	}
	if (document.getElementById('chpwd')) {
		document.getElementById('chpwd').value = '';
	}
}

function publishButtonDisableCallbacks() {
	if ($('botonBorrador')) { Event.observe("botonBorrador","click", function(){ window.onbeforeunload = function() { }; }); }
	if ($('botonPublicar')) { Event.observe("botonPublicar","click", function(){ window.onbeforeunload = function() { }; }); }
	if ($('modo_disenio'))  { Event.observe("modo_disenio","click", function(){  window.onbeforeunload = function() { }; }); }
	if ($('modo_html'))     { Event.observe("modo_html","click", function(){     window.onbeforeunload = function() { }; }); }
}

function estiloVideoActive(id) {
 estiloVideo();
 $(id).addClassName('active');	
	
}

function estiloVideo() {
	$$('.video').each(function(i){
		i.removeClassName('active');
	})
			
}


// onloads
/************* Photos && galleries ***************************/

/* Añade evento onClick en las galerías de los usuarios para las acciones 
de incluir elemento en galería */
function addClassesToGalleries() {
	var galleries = $$('.new_photo_gallery');
	for(var i=0;i<galleries.length;i++) {
		var gallery = galleries[i];
		gallery.onclick = function() {
			if (this.classNames().include('selected') == true ) {
				this.removeClassName('selected');
			} else {
				this.addClassName('selected');
			}
			if ($('galleries')) {
				$('galleries').value = '';
				for(var j=0;j<galleries.length;j++) {
					if (galleries[j].classNames().include('selected'))
						$('galleries').value += galleries[j].id+',';
				}
			}
			
		}
	}
}

/* Subida fotos: propagación de tags y personas */
function propagateTags(id, checkbox_id) {
	var checkbox = document.getElementById(checkbox_id);
	if (checkbox.checked == true ) {
		if (document.getElementById(id)) {
			var tag_list = document.getElementById(id).value;
			var input_tags = $$('.photo_tag_list');
			for(var i=0;i<input_tags.length;i++) {
				if (input_tags[i].id == id) {
					continue;
				}
				var input_values = input_tags[i].value + ' ' + tag_list;
				var array_of_values = input_values.split(' ').uniq();
				var new_value = '';
				for(var j=0;j<array_of_values.length;j++) {
					if (array_of_values[j].blank())
						continue;
					new_value += array_of_values[j] + ' ';
				}
				input_tags[i].value = new_value; 
			}
		}
	} else {		
		if (document.getElementById(id)) {
			var tag_list = document.getElementById(id).value;
			var tags = tag_list.split(' ').uniq();
			var input_tags = $$('.photo_tag_list');
			for(var i=0;i<input_tags.length;i++) {
				if (id == input_tags[i].id) {
					continue;
				}
				var input_values = input_tags[i].value;
				var array_of_values = input_values.split(' ').uniq();
				var new_value = '';
				for(var j=0;j<array_of_values.length;j++) {
					if (array_of_values[j].blank()) {
						continue;
					}
					if (tags.indexOf(array_of_values[j]) == -1) {
						new_value += array_of_values[j] + ' ';
					}
				}
				input_tags[i].value = new_value; 
			}
		}		
	}
}

function propagatePeople(id, checkbox_id) {
	var checkbox = document.getElementById(checkbox_id);
	if (checkbox.checked == true ) {
		if (document.getElementById(id)) {
			var people_list = document.getElementById(id).value;
			var input_people = $$('.photo_people');
			for(var i=0;i<input_people.length;i++) {
				var input_values = input_people[i].value + ' ' + people_list;
				var array_of_values = input_values.split(' ').uniq();
				var new_value = '';
				for(var j=0;j<array_of_values.length;j++) {
					if (array_of_values[j].blank())
						continue;
					new_value += array_of_values[j] + ' ';
				}
				input_people[i].value = new_value; 
			}
		}
	} else {
		if (document.getElementById(id)) {
			var people_list = document.getElementById(id).value;
			var array_people_list = people_list.split(' ').uniq();
			var input_people = $$('.photo_people');
			for(var i=0;i<input_people.length;i++) {
				if (id == input_people[i].id) {
					continue;
				}
				var input_values = input_people[i].value;
				var array_of_values = input_values.split(' ').uniq();
				var new_value = '';
				for(var j=0;j<array_of_values.length;j++) {
					if (array_of_values[j].blank())
						continue;
					if (array_people_list.indexOf(array_of_values[j]) == -1) {
						new_value += array_of_values[j] + ' ';
					} 
				}
				input_people[i].value = new_value; 
			}
		}
	}
}

function propagatePrivacity(id, className, mainCheckBoxId) {
	if ($(mainCheckBoxId).checked == false) {
		return;
	}
	var mainValue = null;
	var checkBoxId = "privacity_"+id+"_public";
	if ($(checkBoxId).checked == true) {
		mainValue = $(checkBoxId).value;
	} else {
		checkBoxId = "privacity_"+id+"_only_friends";
		if ($(checkBoxId).checked == true) {
			mainValue = $(checkBoxId).value;
		} else {
			checkBoxId = "privacity_"+id+"_only_owner";
			if ($(checkBoxId).checked == true) {
				mainValue = $(checkBoxId).value;
			}
		}
	}
	var checkBoxes = $$('.'+className);
	for(var i=0;i<checkBoxes.length;i++) {
		var checkBox = checkBoxes[i];
		if (checkBox.value == mainValue) {
			checkBox.checked = true;
		} else {
			checkBox.checked = false;
		}
	}
}

/* ******* serialización del formulario de nueva galería *********** */
function serializeGalleryElements() {
  return $H({ 'gallery[name]': document.getElementById('new_gallery_title').value, 'gallery[description]': document.getElementById('new_gallery_desc').value }).toQueryString();
}  

/* ********** asignar al elemento BrowseButton el selector de ficheros ********** */
// Este método lo invoca el SWFUpload cuando termina la carga de ficheros
function swfUploadLoaded() {
	if (document.getElementById("BrowseButton")) {
		document.getElementById("BrowseButton").onclick = function () { swfu.selectFiles(); return false;};
	}	
}

/* fotos extensión */
function rotateImage(id, image_url, degrees, id_store_rotation) {
	var real_degrees = degrees + parseInt($(id_store_rotation).value);
	if (real_degrees >= 360 || real_degrees <= -360) {
		real_degrees = 0;
	} 
	$(id_store_rotation).value = real_degrees;
	$(id).src = image_url + '?degrees='+real_degrees;
}
// 

/** fotos: add_people_widget() **/
function add_people_widget(box) {
  if(box == 'add_people_lc') {
    // $('add_people_lc').show();
    //     $('add_people_invite').hide();
    //     $('add_people_webmail').hide();
    
    Effect.BlindDown('add_people_lc');
    Effect.BlindUp('add_people_invite');
    Effect.BlindUp('add_people_webmail');

    $('add_people_lc_h').addClassName('h4_open');
    $('add_people_invite_h').removeClassName('h4_open');
    $('add_people_webmail_h').removeClassName('h4_open');
  }
  
  if(box == 'add_people_invite') {
    // $('add_people_lc').hide();
    //     $('add_people_invite').show();
    //     $('add_people_webmail').hide();
    
    Effect.BlindUp('add_people_lc');
    Effect.BlindDown('add_people_invite');
    Effect.BlindUp('add_people_webmail');

    $('add_people_lc_h').removeClassName('h4_open');
    $('add_people_invite_h').addClassName('h4_open');
    $('add_people_webmail_h').removeClassName('h4_open');
  }
  
  if(box == 'add_people_webmail') {
    // $('add_people_lc').hide();
    //     $('add_people_invite').hide();
    //     $('add_people_webmail').show();

    Effect.BlindUp('add_people_lc');
    Effect.BlindUp('add_people_invite');
    Effect.BlindDown('add_people_webmail');
    
    $('add_people_lc_h').removeClassName('h4_open');
    $('add_people_invite_h').removeClassName('h4_open');
    $('add_people_webmail_h').addClassName('h4_open');
  }
}

function switchddPeopleWidgetTab(tab) {
  if(tab == 'friends_coc') {
    $('apn_cont_friends_coc').show(); 
    $('apn_cont_friends_ext').hide(); 
    $('apn_lnk_friends_coc').addClassName('active');
    $('apn_lnk_friends_ext').removeClassName('active');
  }
  if(tab == 'friends_ext') {
    $('apn_cont_friends_coc').hide(); 
    $('apn_cont_friends_ext').show(); 
    $('apn_lnk_friends_coc').removeClassName('active');
    $('apn_lnk_friends_ext').addClassName('active');
  }
  
}

// fguillen: 2008.11.11
// efecto buscador entre tus contactos del webmail
function search_on_webmail_results( term ){
  $$('div.person').each(
      function(item){
        Element.classNames(item).each(
            function(clas){
                reg = new RegExp( term );
                if( reg.test(clas) ){
                    item.show();  // mostrar
                } else {
                    item.hide();  // ocultar
                }
            }
        )
      }
    );
}

function alerta(){
  alert("hola");
}
function isdefined(variable) {
	return (typeof(window[variable]) == "undefined")?  false: true;
}

// Precarga de fotos
function preLoadPhotos(previous_photo, next_photo) {
	if (previous_photo != ''){
		var previous_photo_preload = new Image(1,1);
		previous_photo_preload.src = previous_photo;
	}
	if (next_photo != ''){
		var next_photo_preload = new Image(1,1);
		next_photo_preload.src = next_photo;
	}
}

function adaptSize(textarea) {
  line_height_value = textarea.getStyle('line-height');
  line_height	= parseInt(line_height_value);
  
  // En Safari el line-height el line-height por defecto nos devolverá "normal", con lo cual establecemos el line_height a 16 pixeles
  if(isNaN(line_height)) {
    line_height = 15;
  }

  extra = line_height*2;
  
	min_height = parseInt(textarea.getStyle('min-height'));
	if(min_height == 0) { // Si no hay min-height el tamaño minimos sera el del numero de filas por alto de linea
    min_height = textarea.rows*line_height + extra;
	}
	
	max_height = parseInt(textarea.getStyle('max-height'));
  
  dummy = $(textarea.id+'_adapt_dummy');
  
  if( dummy == null) {
    textarea.insert({after:'<div id="'+textarea.id+'_adapt_dummy"></div>'});
    
    dummy = textarea.next();
    
    dummy.setStyle({
      'font-size'   : textarea.getStyle('font-size'),
      'font-family' : textarea.getStyle('font-family'),
      'width'       : textarea.getStyle('width'),
      'padding'     : textarea.getStyle('padding'),
      'line-height' : line_height_value,
      'overflow-x'  : 'hidden',
      'position'    : 'absolute',
      'top'         : '0px',
      'left'        : '-9999px'
    });
  }
  
  // Strip HTML tags
	var html = textarea.value.replace(/(<|>)/g, '');
	
	if(Prototype.Browser.IE) {
	  html = html.replace(/\n/g, '<BR>new');
	}
	else
	{
	  html = html.replace(/\n/g, '<br>new');
	}
  
  if(textarea.value == '') {    
    textarea.setStyle({'height' : min_height + 'px'});
  } else {
    if(dummy.innerHTML != html) {
      dummy.innerHTML = html;
    
      if(max_height > 0 && dummy.getHeight() + extra > max_height) {
        textarea.setStyle({'overflow-y': 'auto'});
        textarea.setStyle({'height' : max_height + 'px'});
      }
      else {
        textarea.setStyle({'overflow-y': 'hidden'});
        
        if(textarea.getHeight() < (dummy.getHeight() + extra) || (dummy.getHeight() < textarea.getHeight())) {
          new_height = dummy.getHeight() + extra;

          // Si tenemos min-height y el texto ocupa en el div oculto menos que el minimo, el textarea sera de min_height de alto
          if(min_height > 0 && new_height < min_height)
            new_height = min_height;
          else if(new_height <= extra)
            new_height = extra+line_height;
          
          textarea.setStyle({'height' : new_height + 'px'});
        }
      }
    }
  }
}

function makeAdaptable(textarea) {
  textarea.observe('keyup', function(event) {
    adaptSize(this);
  });
  adaptSize(textarea);
}

function adaptableTextareas() {
  $$('textarea.auto_adaptable').each(function(elem, index){
    makeAdaptable(elem);
  });
}

/** MENUS DESPLEGABLES **/ 
function showAccountMenu(status) {
  if(status == 'on') {
    $('account_menu').show();
    $('link_your_account').addClassName('lya_hover');
  }
  if(status == 'off') {
    $('account_menu').hide();
    $('link_your_account').removeClassName('lya_hover');
  }
}
function showMenu(zone, status) {
  if(status == 'on') {
    $('menu_' + zone).show();
  }
  if(status == 'off') {
    $('menu_' + zone).hide();
  }
}

/* ########## module invitations:INI ########### */
function add_remove_webmail_contact_invitation( object ){
  if( object.checked ){
    $('selected_emails').value += object.value + "\n";
  } else {
    $('selected_emails').value = $('selected_emails').value.replace( object.value + "\n", '' );
  }
}

function add_webmail_contact_invitation( object ){
  if( object.value.trim != '' ){
    $('selected_emails').value += object.value + "\n";
  }
  object.value = '';
}

function invitations_reset_form(){
  $('apn_webmail_result').hide();
  $('add_emails').value = '';
  $('selected_emails').value = '';
  $('submit_invitations').disabled = false;
  $('apn_wm_cr_cont').show();
  new Effect.Highlight('apn_wm_cr_cont');  
}

function show_options_section(section_id, content_section_id){
	$$('.edit_container').each(function(e){e.hide();});
  $$('.edit_link').each(function(e){e.removeClassName('selected');});
  $('content_'+content_section_id).show();
	$('link_'+content_section_id).addClassName('selected');
  $$('.edit_content').each(function(e){e.hide();});
  $$('.edit_link_sub').each(function(e){e.removeClassName('selected');});
  $(section_id).show();
  $('link_'+section_id).addClassName('selected');
}

// function toggle_apn_email_manual_submit( object ){
//   alert( object.value )
//   if( object.value.trim != '' ){
//     $('apn_email_manual_submit').disabled = true;
//   } else {
//     $('apn_email_manual_submit').disabled = false;
//   }
// }
/* ########## module invitations:END ########### */

function showDesp(id) {
  if( $('select_' + id).visible() ) {
    $('select_' + id).hide();
  }
  else {
    $('select_' + id).show();
  }
}

DropMenu = {
  init: function(ident) { 
    var menu = $(ident + "_menu");
    var desp = $(ident + "_desp");
      
    if(menu && desp) {
      menu.observe('click', function() { DropMenu.showMenu(ident); });
      menu.observe('mouseout', function() { DropMenu.hideMenu(ident); });
      desp.observe('mouseover', function() { DropMenu.showMenu(ident); });
      desp.observe('mouseout', function() { DropMenu.hideMenu(ident); });
    }
  },
  showMenu: function(ident) {
      var menu = $(ident + "_menu");
      var desp = $(ident + "_desp");
      var pos = Position.cumulativeOffset(menu);
      menu.style.top = (pos[1] + menu.offsetHeight) + "px";
      menu.style.left = pos[0] + "px";
      desp.show();
      //alert('sifd');
  },
  hideMenu: function(ident) {
      var desp = $(ident + "_desp");
      desp.hide();
  }
  // hideAllMenus: function(group) {
  //     $$("." + group).each(function(e){
  //       e.hide();
  //     });
  //   }
}

Event.observe(window, 'load', function (){ 
   // all my menus
   // DropMenu.init("blogs");
   //    DropMenu.init("fotos");
   //    DropMenu.init("menu");
   DropMenu.init("photos_nav");
});

// Event.observe(document, 'click', (function(event){
//   var target = Event.findElement(event, 'div.fakeclass');
//     if (target == document) {
//       DropMenu.hideAllMenus("fakeclass");
//     }
// }).bind(this));

/** Main menu **/
// asignamos comportamientos al main menu

// menu de navegacion en editar perfil del front
function edit_profile(option) {
  if(option == 'personal_data') {
    $('link_personal_data').addClassName('active');
    $('link_avatar').removeClassName('active');
    $('link_notifications').removeClassName('active');
    $('edit_personal_data').show();
    $('edit_avatar').hide();
    $('edit_notifications').hide();
  }
  if(option == 'avatar') {
    $('link_personal_data').removeClassName('active');
    $('link_avatar').addClassName('active');
    $('link_notifications').removeClassName('active');
    $('edit_personal_data').hide();
    $('edit_avatar').show();
    $('edit_notifications').hide();
  }
  if(option == 'notifications') {
    $('link_personal_data').removeClassName('active');
    $('link_avatar').removeClassName('active');
    $('link_notifications').addClassName('active');
    $('edit_personal_data').hide();
    $('edit_avatar').hide();
    $('edit_notifications').show();
  }
}

function fuzzyTime() {
	var now = new Date();
	var now_ms = now.getTime();
	var offset = now.getTimezoneOffset();
	offset = offset * 60 * 1000;
  var overwrite = true;
  
	$$(".fuzzy").each(function (elem,index) {
		var timeString = elem.readAttribute('timestamp');

		if (!timeString) {
			return;
		}

		var year = timeString.substring(0,4);
		var month = timeString.substring(4,6);
		var day = timeString.substring(6,8);
		var hour = timeString.substring(8,10);
		var minute = timeString.substring(10,12);
		var second = timeString.substring(12,14);

		var newDate = new Date();
		newDate.setFullYear(year);
		newDate.setMonth(month - 1);
		newDate.setDate(day);
		newDate.setHours(hour);
		newDate.setMinutes(minute);
		newDate.setSeconds(second);
    
		var ms = newDate.getTime();
		ms -= offset;
		newDate.setTime(ms);
    
		var difference = now_ms - newDate.getTime();
		var dateString = "";

		if (difference > (1000 * 60 * 60 * 24 * 30)) {
			overwrite = false;
		}
		else if (difference >= (1000 * 60 * 60 * 24)) {
			var days = Math.floor(difference / (1000 * 60 * 60 * 24));
			dateString = "hace ";
			dateString += days + " día";
			if (days != 1) dateString += "s";
		}
		else if (difference >= (1000 * 60 * 60)) {
			var hours = Math.floor(difference / (1000 * 60 * 60));
			dateString = "hace ";
			dateString += hours + " hora";
			if (hours != 1) dateString += "s";
		}
    else if(difference >= 0) {
			var minutes = Math.floor(difference / (1000 * 60));

			if (minutes < 1) {
				dateString = "hace menos de un minuto";
			}
			else {
			  dateString = "hace "
				dateString += minutes + " minuto";
				if (minutes != 1) dateString += "s";
			}
		}

    if(overwrite)
		  elem.innerHTML = dateString;
	});
}


/* ################# */
/** Templatis : INI **/
/* ################ */
function show_design_option(option) {
  if(option == 'pred') {
    $('lnk_opt_des_pred').addClassName('active');
    $('lnk_opt_des_pers').removeClassName('active');
    $('lnk_opt_des_edit').removeClassName('active');
    $('options_design_predefined').show();
    $('options_design_pers').hide();
    $('options_design_edit').hide();
  }
  if(option == 'pers') {
    $('lnk_opt_des_pred').removeClassName('active');
    $('lnk_opt_des_pers').addClassName('active');
    $('lnk_opt_des_edit').removeClassName('active');
    $('options_design_predefined').hide();
    $('options_design_pers').show();
    $('options_design_edit').hide();
  }
  if(option == 'edit') {
    $('lnk_opt_des_pred').removeClassName('active');
    $('lnk_opt_des_pers').removeClassName('active');
    $('lnk_opt_des_edit').addClassName('active');
    $('options_design_predefined').hide();
    $('options_design_pers').hide();
    $('options_design_edit').show();
  }
}

function iframe_content_access(){
	Element.addMethods('iframe', {
		document: function(element) {
		  element = $(element);
		  if (element.contentWindow)
		      return element.contentWindow.document;
		  else if (element.contentDocument)
		      return element.contentDocument;
		  else
		      return null;
		}
	});
}

/*
* fguillen 2009-06-11: 
* 
* look into the content of an iframe a add a pair key=value parameters
* to all links on that iframe
*/
function adding_parameter_to_all_links_on_iframe( iframe_id, param_name_value ){
	for( n=0; n < $(iframe_id).document().links.length; n ++ ){
	  href = $(iframe_id).document().links[n].href;
	  if( href.indexOf('?') == -1 && href.indexOf('#') == -1 ) {
	    $(iframe_id).document().links[n].href = href + '?' + param_name_value;
	  } else if( href.indexOf('?') != -1 && href.indexOf('#') == -1 ) {
	    $(iframe_id).document().links[n].href = href + '&' + param_name_value;
	  } else if( href.indexOf('?') != -1 && href.indexOf('#') != -1 ) {
	    hash_index = href.indexOf('#');
	    $(iframe_id).document().links[n].href = 
	      href.substring(0, hash_index ) + 
	      '&' + param_name_value + 
	      href.substring( hash_index );
	  } else if( href.indexOf('?') == -1 && href.indexOf('#') != -1 ) {
	    hash_index = href.indexOf('#');
	    $(iframe_id).document().links[n].href = 
	      href.substring(0, hash_index ) + 
	      '?' + param_name_value + 
	      href.substring( hash_index );
	  }
	}
}

/*
* fguillen 2009-06-11: 
* 
* add a pair key=value parameters
* to all links on this page
*/
function adding_parameter_to_all_links( param_name_value ){
	$$('a').each(
		function(anchor, index) {
		  href = anchor.href;
		  if( href.indexOf('?') == -1 && href.indexOf('#') == -1 ) {
		    anchor.href = href + '?' + param_name_value;
		  } else if( href.indexOf('?') != -1 && href.indexOf('#') == -1 ) {
		    anchor.href = href + '&' + param_name_value;
		  } else if( href.indexOf('?') != -1 && href.indexOf('#') != -1 ) {
		    hash_index = href.indexOf('#');
		    anchor.href = 
		      href.substring(0, hash_index ) + 
		      '&' + param_name_value + 
		      href.substring( hash_index );
		  } else if( href.indexOf('?') == -1 && href.indexOf('#') != -1 ) {
		    hash_index = href.indexOf('#');
		    anchor.href = 
		      href.substring(0, hash_index ) + 
		      '?' + param_name_value + 
		      href.substring( hash_index );
		  }
		}
	)
}

/* fguillen 2009-06-12: 
* 
*/
function select_templati( templati_id ){
	$('templati_activation_id_public_box').value = templati_id; 
	$('templati_activation_id_my_box').value = templati_id; 
	$('templati_activation_id_public_box2').value = templati_id; 
	$('templati_activation_id_my_box2').value = templati_id; 
	// $('new_layout').value = templati_id;
	selectCurrentTemplate_templati('templati_link_' + templati_id, 'active');
}


/*
* from: http://www.netlobo.com/url_query_string_javascript.html
*
* extracts the parameter value from the url params
* example:
*
*   http://www.foo.com/index.html?bob=123&frank=321&tom=213#top
*   var frank_param = gup( 'frank' );
*/
function gup( name ){
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

/*
* fguillen 2009-06-24: 
* gup versión for the params begining on the anchor mark of the url
* 
* example:
*
*   http://www.foo.com/index.html#bob=123;frank=321;tom=213
*   var frank_param = gup( 'frank' );
* 
*/
function gup_anchor_zone( name ){
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\#;]"+name+"=([^&#;]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

// fguillen 2009-06-25: 
// Muestra los mensajes flash del algunas cosas de templati
//
function templati_show_ajax_messages_div( sufijo ){
	$('templati_ajax_messages').show();
	// new Effect.Highlight('templati_ajax_messages_' + sufijo );
	Effect.Fade('templati_ajax_messages', {delay: 5.0, duration: 3.0});
}

// /* Charge on background the form for templati preview or save
// */
// function templati_charge_preview_save( url ){
//   new Ajax.Request(
//     url,
//     {
//       method:'get',
//       onSuccess: function(transport){
//         var response = transport.responseText || "no response text";
//         $('preview_save_form').innerHTML(response);
//       },
//       onFailure: function(){ alert('error al cargar el div preview_save') }
//     }
//   );
// }

// fork del selectCurrentTemplate para templatis
//
function selectCurrentTemplate_templati(current) {
	var links = $$('.templati_link');
	for(var j=0;j<links.length;j++) {
		links[j].removeClassName('active');	
	}
	$(current).addClassName('active');
}

/* ################# */
/** Templatis : END **/
/* ################ */

/** ONLOADS **/
addLoadEvent(hideCSSEditing);
addLoadEvent(showCSSEditing);
addLoadEvent(searchHighlight);
addLoadEvent(cleanPasswords);
addLoadEvent(publishButtonDisableCallbacks);
addLoadEvent(adaptableTextareas);
addLoadEvent(fuzzyTime);



