var base_url="/";
var base_static="/";
/*
 * SimpleModal 1.2.3 - jQuery Plugin
 * http://www.ericmmartin.com/projects/simplemodal/
 * Copyright (c) 2009 Eric Martin
 * Dual licensed under the MIT and GPL licenses
 * Revision: $Id: jquery.simplemodal.js 185 2009-02-09 21:51:12Z emartin24 $
 */
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(g($){m f=$.Q.1R&&1d($.Q.1B)==6&&E 11[\'2b\']!="1O",V=D,w=[];$.v=g(a,b){G $.v.12.1l(a,b)};$.v.H=g(){$.v.12.H()};$.1P.v=g(a){G $.v.12.1l(3,a)};$.v.1K={W:2a,1C:\'q-F\',1x:{},21:\'q-n\',20:{},1Z:{},u:2p,H:1p,1U:\'<a 2i="2h" 2g="2d"></a>\',Z:\'q-H\',r:D,1h:L,1g:D,1f:D,1c:D};$.v.12={7:D,4:{},1l:g(a,b){8(3.4.j){G L}V=$.Q.1R&&!$.28;3.7=$.U({},$.v.1K,b);3.u=3.7.u;3.19=L;8(E a==\'1O\'){a=a 26 1A?a:$(a);8(a.16().16().24()>0){3.4.X=a.16();8(!3.7.1h){3.4.22=a.2x(1p)}}}o 8(E a==\'2w\'||E a==\'1t\'){a=$(\'<1s/>\').2t(a)}o{2s(\'2r 2q: 2o j 2l: \'+E a);G L}3.4.j=a.14(\'q-j\').C(3.7.1Z);a=D;3.1T();3.1S();8($.1o(3.7.1f)){3.7.1f.1n(3,[3.4])}G 3},1T:g(){w=3.1m();8(f){3.4.x=$(\'<x 2f="2e:L;"/>\').C($.U(3.7.2c,{1k:\'1j\',W:0,r:\'1i\',A:w[0],B:w[1],u:3.7.u,K:0,y:0})).M(\'z\')}3.4.F=$(\'<1s/>\').1N(\'1M\',3.7.1C).14(\'q-F\').C($.U(3.7.1x,{1k:\'1j\',W:3.7.W/1e,A:w[0],B:w[1],r:\'1i\',y:0,K:0,u:3.7.u+1})).M(\'z\');3.4.n=$(\'<1s/>\').1N(\'1M\',3.7.21).14(\'q-n\').C($.U(3.7.20,{1k:\'1j\',r:\'1i\',u:3.7.u+2})).1J(3.7.H?$(3.7.1U).14(3.7.Z):\'\').M(\'z\');3.1b();8(f||V){3.1a()}3.4.n.1J(3.4.j.1I())},1H:g(){m a=3;$(\'.\'+3.7.Z).1G(\'1L.q\',g(e){e.29();a.H()});$(11).1G(\'1F.q\',g(){w=a.1m();a.1b();8(f||V){a.1a()}o{a.4.x&&a.4.x.C({A:w[0],B:w[1]});a.4.F.C({A:w[0],B:w[1]})}})},1E:g(){$(\'.\'+3.7.Z).1D(\'1L.q\');$(11).1D(\'1F.q\')},1a:g(){m p=3.7.r;$.27([3.4.x||D,3.4.F,3.4.n],g(i,e){8(e){m a=\'k.z.18\',N=\'k.z.1W\',17=\'k.z.25\',T=\'k.z.1z\',S=\'k.z.1y\',1r=\'k.z.23\',1v=\'k.R.18\',1u=\'k.R.1W\',J=\'k.R.1z\',I=\'k.R.1y\',s=e[0].2v;s.r=\'2u\';8(i<2){s.10(\'A\');s.10(\'B\');s.Y(\'A\',\'\'+17+\' > \'+a+\' ? \'+17+\' : \'+a+\' + "l"\');s.Y(\'B\',\'\'+1r+\' > \'+N+\' ? \'+1r+\' : \'+N+\' + "l"\')}o{m b,13;8(p&&p.1Y==1Q){m c=p[0]?E p[0]==\'1t\'?p[0].1X():p[0].P(/l/,\'\'):e.C(\'K\').P(/l/,\'\');b=c.1V(\'%\')==-1?c+\' + (t = \'+I+\' ? \'+I+\' : \'+S+\') + "l"\':1d(c.P(/%/,\'\'))+\' * ((\'+1v+\' || \'+a+\') / 1e) + (t = \'+I+\' ? \'+I+\' : \'+S+\') + "l"\';8(p[1]){m d=E p[1]==\'1t\'?p[1].1X():p[1].P(/l/,\'\');13=d.1V(\'%\')==-1?d+\' + (t = \'+J+\' ? \'+J+\' : \'+T+\') + "l"\':1d(d.P(/%/,\'\'))+\' * ((\'+1u+\' || \'+N+\') / 1e) + (t = \'+J+\' ? \'+J+\' : \'+T+\') + "l"\'}}o{b=\'(\'+1v+\' || \'+a+\') / 2 - (3.2n / 2) + (t = \'+I+\' ? \'+I+\' : \'+S+\') + "l"\';13=\'(\'+1u+\' || \'+N+\') / 2 - (3.2m / 2) + (t = \'+J+\' ? \'+J+\' : \'+T+\') + "l"\'}s.10(\'K\');s.10(\'y\');s.Y(\'K\',b);s.Y(\'y\',13)}}})},1m:g(){m a=$(11);m h=$.Q.2k&&$.Q.1B>\'9.5\'&&$.1P.2j<=\'1.2.6\'?k.R[\'18\']:a.A();G[h,a.B()]},1b:g(){m a,y,1q=(w[0]/2)-((3.4.n.A()||3.4.j.A())/2),1w=(w[1]/2)-((3.4.n.B()||3.4.j.B())/2);8(3.7.r&&3.7.r.1Y==1Q){a=3.7.r[0]||1q;y=3.7.r[1]||1w}o{a=1q;y=1w}3.4.n.C({y:y,K:a})},1S:g(){3.4.x&&3.4.x.15();8($.1o(3.7.1g)){3.7.1g.1n(3,[3.4])}o{3.4.F.15();3.4.n.15();3.4.j.15()}3.1H()},H:g(){8(!3.4.j){G L}8($.1o(3.7.1c)&&!3.19){3.19=1p;3.7.1c.1n(3,[3.4])}o{8(3.4.X){8(3.7.1h){3.4.j.1I().M(3.4.X)}o{3.4.j.O();3.4.22.M(3.4.X)}}o{3.4.j.O()}3.4.n.O();3.4.F.O();3.4.x&&3.4.x.O();3.4={}}3.1E()}}})(1A);',62,158,'|||this|dialog|||opts|if||||||||function|||data|document|px|var|container|else||simplemodal|position|||zIndex|modal||iframe|left|body|height|width|css|null|typeof|overlay|return|close|st|sl|top|false|appendTo|bcw|remove|replace|browser|documentElement|bst|bsl|extend|ieQuirks|opacity|parentNode|setExpression|closeClass|removeExpression|window|impl|le|addClass|show|parent|bsh|clientHeight|occb|fixIE|setPosition|onClose|parseInt|100|onShow|onOpen|persist|fixed|none|display|init|getDimensions|apply|isFunction|true|hCenter|bsw|div|number|cw|ch|vCenter|overlayCss|scrollTop|scrollLeft|jQuery|version|overlayId|unbind|unbindEvents|resize|bind|bindEvents|hide|append|defaults|click|id|attr|object|fn|Array|msie|open|create|closeHTML|indexOf|clientWidth|toString|constructor|dataCss|containerCss|containerId|orig|scrollWidth|size|scrollHeight|instanceof|each|boxModel|preventDefault|50|XMLHttpRequest|iframeCss|Close|javascript|src|title|modalCloseImg|class|jquery|opera|type|offsetWidth|offsetHeight|Unsupported|1000|Error|SimpleModal|alert|html|absolute|style|string|clone'.split('|'),0,{}))


// Google analytics
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-19412090-1']);
_gaq.push(['_trackPageview']);

(function() {
  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();


function menealo(user, id)
{
	var url = base_url + "backend/menealo.php";
	var content = "id=" + id + "&user=" + user + "&key=" + base_key + "&u=" + document.referrer;
	url = url + "?" + content;
	disable_vote_link(id, -1, "...", '');
	$.getJSON(url,  
		 function(data) {
				parseLinkAnswer(id, data);
		}
	);
	reportAjaxStats('vote', 'link');
}

function menealo_comment(user, id, value)
{
	var url = base_url + "backend/menealo_comment.php";
	var content = "id=" + id + "&user=" + user + "&value=" + value + "&key=" + base_key;
	url = url + "?" + content;
	$.getJSON(url, 
		 function(data) {
			if (data.error) {
				alert("Error: "+data.error);
				return false;
			} else {
				$('#vc-'+id).html(data.votes+"");
				$('#vk-'+id).html(data.karma+"");
				if (data.image && data.image.length > 0) {
					$('#c-votes-'+id+'>a>img').first().attr('src', data.image);
				}
        if (data.image2 && data.image2.length > 0) {
          $('#c-votes-'+id+'>a>img').last().attr('src', data.image2);
        }
			}
		}
	);
	reportAjaxStats('vote', 'comment');
}

function menealo_post(user, id, value)
{
	var url = base_url + "backend/menealo_post.php";
	var content = "id=" + id + "&user=" + user + "&value=" + value + "&key=" + base_key;
	url = url + "?" + content;
	$.getJSON(url,
		 function(data) {
			if (data.error) {
				alert("Error: "+data.error);
				return false;
			} else {
				$('#vc-'+id).html(data.votes+"");
				$('#vk-'+id).html(data.karma+"");
				if (data.image.length > 0) {
					$('#c-votes-'+id).html('<img src="'+data.image+'"/>');
				}
			}
		}
	);
	reportAjaxStats('vote', 'post');
}


function disable_vote_link(id, value, mess, background) {
	if (value < 0) span = '<span class="negative">';
	else span = '<span>';
	$('#a-va-' + id).html(span+mess+'</span>');
	if (background.length > 0) $('#a-va-' + id).css('background', background);
}

function parseLinkAnswer (id, link) {
	$('#problem-' + id).hide();
	if (link.error || id != link.id) {
		disable_vote_link(id, -1, "grr...", '');
		alert("Error: "+link.error);
		return false;
	}
	votes = parseInt(link.votes)+parseInt(link.anonymous);
	if ($('#a-votes-' + link.id).html() != votes) {
		$('#a-votes-' + link.id).hide();
		$('#a-votes-' + link.id).html(votes+"");
		$('#a-votes-' + link.id).fadeIn('slow');
	}
	$('#a-neg-' + link.id).html(link.negatives+"");
	$('#a-usu-' + link.id).html(link.votes+"");
	$('#a-ano-' + link.id).html(link.anonymous+"");
	$('#a-karma-' + link.id).html(link.karma+"");
	disable_vote_link(link.id, link.value, link.vote_description, '');
	return false;
}

function securePasswordCheck(field) {
	if (field.value.length > 5 && field.value.match("^(?=.{6,})(?=(.*[a-z].*))(?=(.*[A-Z0-9].*)).*$", "g")) {
		if (field.value.match("^(?=.{8,})(?=(.*[a-z].*))(?=(.*[A-Z].*))(?=(.*[0-9].*)).*$", "g")) {
			field.style.backgroundColor = "#8FFF00";
		} else {
			field.style.backgroundColor = "#F2ED54";
		}
	} else {
		field.style.backgroundColor = "#F56874";
	}
	return false;
}

function checkEqualFields(field, against) {
	if(field.value == against.value) {
		field.style.backgroundColor = '#8FFF00';
	} else {
		field.style.backgroundColor = "#F56874";
	}
	return false;
}

function enablebutton (button, button2, target)
{
	var string = target.value;
	if (button2 != null) {
		button2.disabled = false;
	}
	if (string.length > 0) {
		button.disabled = false;
	} else {
		button.disabled = true;
	}
}

function checkfield (type, form, field)
{
	var url = base_url + 'backend/checkfield.php?type='+type+'&name=' + encodeURIComponent(field.value);
	$.get(url,
		 function(html) {
			if (html == 'OK') {
				$('#'+type+'checkitvalue').html('<span style="color:black">"' + encodeURI(field.value) + '": ' + html + '</span>');
				form.submit.disabled = '';
			} else {
				$('#'+type+'checkitvalue').html('<span style="color:red">"' + encodeURI(field.value) + '": ' + html + '</span>');
				form.submit.disabled = 'disabled';
			}
		}
	);
	return false;
}

function check_checkfield(fieldname, mess) {
	field = document.getElementById(fieldname);
	if (field && !field.checked) {
		alert(mess);
		// box is not checked
		return false;
	}
}

function report_problem(frm, user, id) {
	if (frm.ratings.value == 0)
		return;
	if (! confirm("confirme desea votar: «" + frm.ratings.options[frm.ratings.selectedIndex].text +"»") ) {
		frm.ratings.selectedIndex=0;
		return false;
	}
	var content = "id=" + id + "&user=" + user + '&value=' +frm.ratings.value + "&key=" + base_key + "&u=" + document.referrer;
	var url=base_url + "backend/problem.php?" + content;
	$.getJSON(url,
		 function(data) {
			parseLinkAnswer(id, data);
		}
	);
	reportAjaxStats('vote', 'link');
	return false;
}

// Get voters by Beldar <beldar.cat at gmail dot com>
// Generalized for other uses (gallir at gmail dot com)
function get_votes(program,type,container,page,id) {
	var url = base_url + 'backend/'+program+'?id='+id+'&p='+page+'&type='+type+"&key="+base_key;
	$('#'+container).load(url);
	reportAjaxStats('html', program);
}

// Modal functions
//
$.extend($.modal.defaults, {
	closeHTML: '<a class="modalCloseImg" title="Close">x</a>',
	opacity: "50"
});

function modal_from_ajax(url, title) {
	if (typeof(title) == "undefined") title = '&nbsp';

	$.modal('<div class="header" id="modalHeader"><div id="modalTitle">'+title+'</div></div><div class="content" id="modalContent">cargando...</div>',
			{});
	$.get(url, function(data){
	// create a modal dialog with the data
		$('#modalContent').html(data);
	});
	reportAjaxStats('modal', 'view');
}

// This function report the ajax request to stats events if enabled in your account
// http://code.google.com/intl/es/apis/analytics/docs/eventTrackerOverview.html
function reportAjaxStats(category, action) {
  if (_gaq) {
    _gaq.push(['_trackEvent', category, action]);
  }
  /*
	if (pageTracker._trackEvent) {
		pageTracker._trackEvent(category, action);
	}
  */
}

function bindTogglePlusMinus(img_id, link_id, container_id) {
	$(document).ready(function (){ 
		$('#'+link_id).bind('click',
			function() {
				if ($('#'+img_id).attr("src") == plus){
					$('#'+img_id).attr("src", minus);
				}else{
					$('#'+img_id).attr("src", plus);
				}
				$('#'+container_id).slideToggle("fast");
				return false;
			}
		);
	});
}


/*/  
 *  JSOC - An object Cache framework for JavaScript
 *  version 0.12.0 [beta]
 * http://dev.webframeworks.com/dist/JSOC-license.txt
 * version: 0.12.0
/*/

JSOC = function(){
    var Cache = {};
    return {
        "get":function(n){
            var obj = {}, val = Cache[n];
            obj[n] = val;
            if(val) return obj;
        },
        "getMulti":function(l){
            var a = [];
            for (var k in l) a.push(this.get(l[k]));
            return a;
        },
        "getType":function(t){
            var a = [];
            for (var o in Cache) if(typeof(Cache[o])==t.toLowerCase()){a.push(this.get(o))}
            return a;
        },
        "set":function(n,v){
            if(Cache[n]) delete(Cache[n]);
            Cache[n]=v;
            if (arguments[2]){
                var ttl = arguments[2].ttl || null;
                if(ttl) var self = this, to = setTimeout(function(){self.remove(n)}, ttl);
            }
            return (Cache[n])?1:0;
        },
        "add":function(n,v){
            if(!Cache[n]){
                Cache[n]=v;
                if (arguments[2]){
                    var ttl = arguments[2].ttl || null;
                    if(ttl) var self = this, to = setTimeout(function(){self.remove(n)}, ttl);
                }
                return (Cache[n])?1:0;
            }
        },
        "replace":function(n,v){
            if(Cache[n]){
                delete(Cache[n]);
                Cache[n]=v;
                if (arguments[2]){
                    var ttl = arguments[2].ttl || null;
                    if(ttl) var self = this, to = setTimeout(function(){self.remove(n)}, ttl);
                }
                return (Cache[n])?1:0;
            }
        },
        "remove":function(n){
            delete(Cache[n]);
            return (!Cache[n])?1:0;
        },
        "flush_all":function(){
            for(var k in Cache) delete(Cache[k]);
            return 1;
        }
    }
}

/**************************************
Tooltips functions
***************************************/
/**
  Stronglky modified, onky works with DOM2 compatible browsers.
  	Ricardo Galli
  From http://ljouanneau.com/softs/javascript/tooltip.php
 */

if (typeof(JSOC) != "undefined") {
	// create the tooltip object
	function tooltip(){}
	// setup properties of tooltip object
	tooltip.id="tooltip";
	tooltip.main=null;
	tooltip.offsetx = 10;
	tooltip.offsety = 10;
	tooltip.shoffsetx = 8;
	tooltip.shoffsety = 8;
	tooltip.x = 0;
	tooltip.y = 0;
	tooltip.tooltipText=null;
	tooltip.title_saved='';
	tooltip.saveonmouseover=null;
	tooltip.timeout = null;
	tooltip.active = false;

	tooltip.cache = new JSOC();

	tooltip.ie = (document.all)? true:false;		// check if ie
	if(tooltip.ie) tooltip.ie5 = (navigator.userAgent.indexOf('MSIE 5')>0);
	else tooltip.ie5 = false;
	tooltip.dom2 = ((document.getElementById) && !(tooltip.ie5))? true:false; // check the W3C DOM level2 compliance. ie4, ie5, ns4 are not dom level2 compliance !! grrrr >:-(
}


/**
* Open ToolTip. The title attribute of the htmlelement is the text of the tooltip
* Call this method on the mouseover event on your htmlelement
* ex :  <div id="myHtmlElement" onmouseover="tooltip.show(this)"...></div>
*/

tooltip.show = function (event, text) {
      // we save text of title attribute to avoid the showing of tooltip generated by browser
	if (this.dom2  == false ) return false;
	if (this.tooltipText == null) {
		this.tooltipText = document.createElement("div");
		this.tooltipText.setAttribute("id", "tooltip-text");
		document.body.appendChild(this.tooltipText);
	}
	this.saveonmouseover=document.onmousemove;
	document.onmousemove = this.mouseMove;
	this.mouseMove(event); // This already moves the div to the right position
	this.setText(text);
	this.tooltipText.style.visibility ="visible";
	this.active = true;
	return false;
}


tooltip.setText = function (text) {
	this.tooltipText.innerHTML=text;
	return false;
}

/**
* hide tooltip
* call this method on the mouseout event of the html element
* ex : <div id="myHtmlElement" ... onmouseout="tooltip.hide(this)"></div>
*/
tooltip.hide = function (event) {
	if (this.dom2  == false) return false;
	document.onmousemove=this.saveonmouseover;
	this.saveonmouseover=null;
	if (this.tooltipText != null ) {
		this.tooltipText.style.visibility = "hidden";
		this.tooltipText.innerHTML='';
	}
	this.active = false;
}



// Moves the tooltip element
tooltip.mouseMove = function (e) {
   // we don't use "this", but tooltip because this method is assign to an event of document
   // and so is dreferenced

	if (tooltip.ie) {
		tooltip.x = event.clientX;
		tooltip.y = event.clientY;
	} else {
		tooltip.x = e.pageX;
		tooltip.y = e.pageY;
	}
	tooltip.moveTo( tooltip.x +tooltip.offsetx , tooltip.y + tooltip.offsety);
}

// Move the tooltip element
tooltip.moveTo = function (xL,yL) {
	if (this.ie) {
		xL +=  document.documentElement.scrollLeft;
		yL +=  document.documentElement.scrollTop;
	}
	if (this.tooltipText.clientWidth > 0  && document.documentElement.clientWidth > 0 && xL > document.documentElement.clientWidth * 0.55) {
		xL = xL - this.tooltipText.clientWidth - 2*this.offsetx;
	}
	this.tooltipText.style.left = xL +"px";
	this.tooltipText.style.top = yL +"px";
	xLS = xL + this.shoffsetx;
	yLS = yL + this.shoffsety;
}

// Show the content of a given comment
tooltip.c_show = function (event, type, element, link) {
      // we save text of title attribute to avoid the showing of tooltip generated by browser
	if (this.dom2  == false ) return false;
	if (element == 0 && link > 0) { // It's a #0  from a comment
		this.ajax_delayed(event,'get_link.php',link);
		return;
	}
	if (type == 'id') {
		target = $('#c-'+element+'>:first');
		author_target = $('#cauthor-'+element);
		if (target.length == 0 || author_target.length == 0)  {
			this.ajax_delayed(event,'get_comment_tooltip.php',element+"&link="+link);
			return;
		}
		text = '<strong>'+author_target.html()+'</strong><br/>'+target.html();
	} else if (type == 'order') {
		this.ajax_delayed(event,'get_comment_tooltip.php',element+"&link="+link);
		return;
	} else {
		text = element;
	}
	return this.show(event, text);
}


tooltip.clear = function (event) {
	if (this.timeout != null) {
		clearTimeout(this.timeout);
		this.timeout = null;
	}
	this.hide(event);
}

tooltip.ajax_delayed = function (event, script, id, maxcache) {
	maxcache = maxcache || 600000; // 10 minutes in cache
	if (this.active) return false;
	if ((object = this.cache.get(script+id)) != undefined) {
		tooltip.show(event, object[script+id]);
	} else {
		this.show(event, "cargando...");
		this.timeout = setTimeout("tooltip.ajax_request('"+script+"', '"+id+"', "+maxcache+")", 100);
	}
}

tooltip.ajax_request = function(script, id, maxcache) {
	var url = base_url + 'backend/'+script+'?id='+id;
	tooltip.timeout = null;
	$.ajax({
		url: url,
		dataType: "html",
		success: function(html) {
			tooltip.cache.set(script+id, html, {'ttl':maxcache});
			tooltip.setText(html);
		}
	});
	reportAjaxStats('tooltip', 'ajax');
}



$(document).ready( function() {

    /*
    // load reduggy.net feed from client - REDUGGY HAS GONE
    var box = $("#reduggyBoxContent");
    if (!box.length == 0) return;

    $.getJSON('http://query.yahooapis.com/v1/public/yql?q='+encodeURIComponent("select * from rss where url='http://reduggy.net/rss2.php' limit 10")+'&format=json&callback=?', function(data) {

        if (data.query.results) {

          var r = data.query.results.item;
          var s = "";

          for (var k in r) {
              s+='<li><a href="'+r[k].link+'" >'+r[k].title+'</a> &nbsp; <a href="http://chuza.gl/submit.php?url='+encodeURIComponent(r[k].url)+'"><img src="/img/mnm/no-gravatar-2-20.jpg" /></a> </li>';
          }
          box.html(s);
        }

    });
    */

    $('#seeeverything').click( function(e) {
      e.preventDefault();

      var currentStatus = $('#seeeverything').html();
      if (currentStatus.substr(-1,1) == '»') {
        $('#catlistmenu').css('white-space','normal');
        $('#seeeverything').html($('#menosText').val());
      } else {
        $('#catlistmenu').css('white-space','nowrap');
        $('#seeeverything').html($('#maisText').val());
      }

    });

});




//** new coments **//
// new comments global var
// 2 status: 0 = normal and #comment_number_to_reply
var Comment = {
  status:0,
  padding:0,
  level:0
}

$(document).ready( function() {
  $("#comentarNoticia").click( function () {
      Comment.padding = 0;
      $("div .commentform").insertAfter(".comments-list");
      Comment.status = 0;
      $("[name=reply_id]").val("0");
  });

  $("a.fold").click( function(ev) {
      ev.preventDefault();
      e = $(this);
      if (e.hasClass("folded")) {
          e
           .removeClass("folded")
           .html("(-)")
           .siblings("span").show()
           .parent().siblings("div.cmt").show();
      } else {
          e
           .addClass("folded")
           .html("(+)")
           .siblings("span").hide()
           .parent().siblings("div.cmt").hide();
      }
  });

  $("#selectCommentOrder").change( function() {
      $.ajax({
          url: base_url + 'backend/set_comment_order.php',
          data: { order:$(this).val() },
          success: function() {
            window.location.reload();
          },
          error: function() {
            alert("Erro trocando a orde dos comentarios");
          },
          dataType:'text'
      });
  });

  //login_dialog();

});

function login_dialog() {
  $('#loginDialog').modal();
}

function comment_reply(id,c_id) {
  // 1st part
  padding = $("c-"+id).attr("name")
  $("div .commentform").insertAfter($("#c-"+id+" > .comment-body")).css("padding-left",Comment.padding+"px");
  $("#comentarNoticia").css("visibility","visible");
  Comment.status = c_id;
  $("[name=parent_id]").val(c_id);

  //2nd part (original)
	//ref = '#' + id + ' ';
	textarea = $('#comment');
	if (textarea.length == 0 ) return;
  /*
	var re = new RegExp(ref);
	var oldtext = textarea.val();
	if (oldtext.match(re)) return;
	if (oldtext.length > 0 && oldtext.charAt(oldtext.length-1) != "\n") oldtext = oldtext + "\n";
	textarea.val(oldtext + ref);
  */
	textarea.get(0).focus();
}

function post_load_form(id, container) {
	var url = base_url + 'backend/post_edit.php?id='+id+"&key="+base_key;
	$.get(url, function (html) {
			if (html.length > 0) {
				if (html.match(/^ERROR:/i)) {
					alert(html);
				} else {
					$('#'+container).html(html);
				}
				reportAjaxStats('html', 'post_edit');
			}
		});
}


function post_new() {
	post_load_form(0, 'addpost');
}

function post_edit(id) {
	post_load_form(id, 'pcontainer-'+id);
}

function post_reply(id, user) {
	ref = '@' + user + ',' + id + ' ';
	textarea = $('#post');
	if (textarea.length == 0) {
		post_new();
	}
	post_add_form_text(ref, 1);
}

function post_add_form_text(text, tries) {
	if (! tries) tries = 1;
	textarea = $('#post');
	if (tries < 20 && textarea.length == 0) {
			tries++;
			setTimeout('post_add_form_text("'+text+'", '+tries+')', 50);
			return false;
	}
	if (textarea.length == 0 ) return false;
	var re = new RegExp(text);
	var oldtext = textarea.val();
	if (oldtext.match(re)) return false;
	if (oldtext.length > 0 && oldtext.charAt(oldtext.length-1) != ' ') oldtext = oldtext + ' ';
	textarea.val(oldtext + text);	
	textarea.get(0).focus();
}

// See http://www.shiningstar.net/articles/articles/javascript/dynamictextareacounter.asp?ID=AW
function textCounter(field,cntfield,maxlimit) {
	if (field.value.length > maxlimit)
	// if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
	// otherwise, update 'characters left' counter
	else
		cntfield.value = maxlimit - field.value.length;
}



/************************
Simple format functions
**********************************/
/*
  Code from http://www.gamedev.net/community/forums/topic.asp?topic_id=400585
  strongly improved by Juan Pedro López for http://meneame.net
  2006/10/01, jotape @ http://jplopez.net
*/

function applyTag(id, tag) {
	obj = document.getElementById(id);
	if (obj) wrapText(obj, tag, tag);
	return false;
}

function wrapText(obj, tag) {
	if(typeof obj.selectionStart == 'number') {
		// Mozilla, Opera and any other true browser
		var start = obj.selectionStart;
		var end   = obj.selectionEnd;

		if (start == end || end < start) return false;
		obj.value = obj.value.substring(0, start) +  replaceText(obj.value.substring(start, end), tag) + obj.value.substring(end, obj.value.length);
	} else if(document.selection) {
		// Damn Explorer
		// Checking we are processing textarea value
		obj.focus();
		var range = document.selection.createRange();
		if(range.parentElement() != obj) return false;
		if (range.text == "") return false;
		if(typeof range.text == 'string')
	        document.selection.createRange().text =  replaceText(range.text, tag);
	} else
		obj.value += text;
}

function replaceText(text, tag) {
		return '<'+tag+'>'+text+'</'+tag+'>';
}



