var stopWords =["a","able","aboard","about","above","according","accordingly","across","actually","after","afterwards","again","against","ain’t","alguna","algunas","algunos","algún","all","allow","allows","almost","alone","along","already","also","although","always","am","amid","among","amongst","an","and","another","ante","anti","any","anybody","anyhow","anyone","anything","anyway","anyways","anywhere","apart","appear","appreciate","appropriate","aquel","aquella","aquellas","aquellos","are","aren’t","around","art","as","aside","ask","asking","associated","at","available","away","awfully","a’s","bajo","bastante","bastantes","be","became","because","become","becomes","becoming","been","before","beforehand","behind","being","believe","below","beside","besides","best","better","between","beyond","both","brief","but","by","cabe","cada","came","can","cannot","cant","can’t","cause","causes","certain","certainly","changes","chat","cierta","ciertas","cierto","ciertos","clearly","club","co","com","come","comes","concerning","consequently","consider","considering","contain","containing","contains","contra","corresponding","could","couldn’t","course","cualesquiera","cualquier","cualquiera","currently","cuál","cuáles","cuánta","cuántas","cuánto","cuántos","c’mon","c’s","de","definitely","demasiada","demasiadas","demasiado","demasiados","described","desde","despite","did","didn’t","different","do","does","doesn’t","doing","done","don’t","down","downwards","durante","during","each","edu","eg","eight","either","el","else","elsewhere","en","enough","entirely","entre","esa","esas","escasas","escasos","ese","esos","especially","esta","estas","este","estos","et","etc","even","ever","every","everybody","everyone","everything","everywhere","ex","exactly","example","except","excepting","excluding","famous","fan","far","few","fifth","first","five","followed","following","follows","for","former","formerly","forth","four","from","further","furthermore","get","gets","getting","given","gives","go","goes","going","gone","gossip","got","gotten","greetings","hacia","had","hadn’t","happens","hardly","has","hasn’t","hasta","have","haven’t","having","he","hello","help","hence","her","here","hereafter","hereby","herein","hereupon","here’s","hers","herself","he’s","hi","him","himself","his","hither","hopefully","how","howbeit","however","ie","if","ignored","immediate","in","inasmuch","inc","indeed","indicate","indicated","indicates","inner","inside","insofar","instead","into","inward","is","isn’t","it","its","itself","it’d","it’ll","it’s","i’d","i’ll","i’m","i’ve","just","keep","keeps","kept","know","known","knows","la","las","last","lately","later","latter","latterly","least","less","lest","let","let’s","like","liked","likely","little","lo","look","looking","looks","los","ltd","mainly","many","may","maybe","me","mean","meanwhile","mediante","menos","merely","mi","might","minus","mis","more","moreover","most","mostly","much","muchas","mucho","muchos","must","my","myself","más","mía","mías","mío","míos","name","namely","nd","near","nearly","necessary","need","needs","neither","never","nevertheless","new","news","next","nine","ninguna","ningunas","ningunos","ningún","no","nobody","non","none","noone","nor","normally","not","nothing","novel","now","nowhere","nuestra","nuestras","nuestro","nuestros","obviously","of","off","often","oh","ok","okay","old","on","once","one","ones","only","onto","opposite","or","other","others","otherwise","otra","otras","otro","otros","ought","our","ours","ourselves","out","outside","over","overall","own","para","particular","particularly","past","per","perhaps","placed","please","plus","poca","pocas","poco","pocos","por","portfoli","possible","presumably","probably","provides","que","quite","qué","qv","rather","rd","re","really","reasonably","regarding","regardless","regards","relatively","respectively","right","round","rt","said","same","save","saw","say","saying","says","second","secondly","see","seeing","seem","seemed","seeming","seems","seen","según","self","selves","sendas","sendos","sensible","sent","serious","seriously","seven","several","shall","she","should","shouldn’t","sin","since","site","six","so","sobre","some","somebody","somehow","someone","something","sometime","sometimes","somewhat","somewhere","soon","sorry","specified","specify","specifying","still","su","sub","such","sup","sure","sus","suya","suyas","suyo","suyos","take","taken","tal","tales","tanta","tantas","tanto","tantos","tell","tends","th","than","thank","thanks","thanx","that","thats","that’s","the","their","theirs","them","themselves","then","thence","there","thereafter","thereby","therefore","therein","theres","thereupon","there’s","these","they","they’d","they’ll","they’re","they’ve","think","third","this","thorough","thoroughly","those","though","three","through","throughout","thru","thus","to","toda","todas","todo","todos","together","too","took","toward","towards","tras","tried","tries","truly","try","trying","tu","tus","tuya","tuyas","tuyo","tuyos","twice","two","t’s","un","unas","under","underneath","unfortunately","unless","unlike","unlikely","unos","until","unto","up","upon","us","use","used","useful","uses","using","usually","value","varias","varios","various","versus","very","via","viz","vs","vuestra","vuestras","vuestro","vuestros","want","wants","was","wasn’t","way","we","welcome","well","went","were","weren’t","we’d","we’ll","we’re","we’ve","what","whatever","what’s","when","whence","whenever","where","whereafter","whereas","whereby","wherein","whereupon","wherever","where’s","whether","which","while","whither","who","whoever","whole","whom","whose","who’s","why","will","willing","wish","with","within","without","wonder","won’t","would","wouldn’t","yes","yet","you","your","yours","yourself","yourselves","you’d","you’ll","you’re","you’ve","zero"];

var Logger = {
    log: function(str) {
        if (window.console && console.log) {
            console.log(str);
        }
    }
}

var DOMBuilder = {
    build: function (obj) {
        if (obj.text) {
            var node = document.createTextNode(obj.text);
            return node;
        }
        
        if (!obj.tagName) {
            Logger.log("No tag name provided!");
            Logger.log(obj);
            return null;
        }
        
        var node = document.createElement(obj.tagName);
        for (var prop in obj) {
            switch (prop) {
                case 'tagName':
                    //do nothing
                    break;
                case 'children':
                    for (var i=0; i!=obj.children.length; i++) {
                        var child = DOMBuilder.build(obj.children[i]);
                        node.appendChild(child);
                    }
                    break;
                default:
                    node[prop] = obj[prop];
                    break;
            }
        }
        return node;
    }
}

var gossip = {
	ie7 : null,
	ie8 : null,
	lastUpdate : null,
	timerUpdate : 60,
	updateParameters: {},
	updates : new Array(),
	
	getStream: function(sliceId) {
		
		var service = "/slice";
		var parameters = gossip.updateParameters[sliceId];
		if (parameters == null) {
			return;
		}
		var list = parameters.list;
		
		new Ajax.PeriodicalUpdater({success: list}, gossip.base+service, {
			parameters: parameters,
			evalScripts: true,
			insertion: 'top',
			frequency: gossip.timerUpdate
		});
	},
	
	removeElement: function(id){
		var elements = $$("ul#"+id+" li");
		var ul = $(id);
		var length = 0;
		if (elements != null && ul != null ){
			length = elements.length;
			if (length > 0){
				elements[length-2].addClassName("last");
				ul.removeChild(elements[length-1]);
			}
		}
	},
	
	updateStream: function(id,fixed){
		var className = "update_hidden";
		var elements = $$("#"+id+" ."+className);
		var length = elements.length;
		if (length > 0) {
			
			if (!fixed) {
				//gossip.simpleRemove(id);
				gossip.removeElement(id);
			} else {
				gossip.removeFromFixedBox(id);
			}
			
			var element = elements[length-1];
			var timeToShow = gossip.timerUpdate*1000/ length;
			element.removeClassName(className);
			var height = element.offsetHeight;
			var step = 20;
			var mod = height % step; 
			if (mod != 0) {
				height = height - mod + step;
			}
			element.style.marginTop = -height + "px";
			setTimeout("gossip.updateStream('"+id+"');", timeToShow);
			//remove(twitterUpdateBar);
			gossip.slideDown(element.id,-height,20,step,50);
		}
	},
	
	/*Mueve en intervalos un item de twitter o de stories*/
	slideDown: function(id,current,target,step,time) {
		var element = $(id);
		var newMargin = (current+step)
		element.style.marginTop = newMargin + "px";
		if (newMargin != target) {
			setTimeout("gossip.slideDown('"+id+"',"+newMargin+","+target+","+step+","+time+")", time);
		}	
	},
	
	updateTimestamp: function(className,stamps,noAgo,noAbout) {
		var elements = $$(className);
		var element = null;
		var id = null;
		var numericId = null;
		for (var i=0; i != elements.length; i++) {
			element = elements[i];
			id = element.id;
			numericId = id.indexOf("_")>=0 ? id.split("_")[1] : id;
			/*
			if (element != null && id != null) {
				var elem = document.getElementById(id);
				elem.innerHTML = remaining.getString(-remaining.getSeconds(stamps[numericId],gossip.currentTime), null, true);
			}*/
			//element.innerHTML = "(" + stamps + "-" + numericId + "-" + stamps[numericId] + "-" + gossip.currentTime + ")";
			element.innerHTML = remaining.getString(-remaining.getSeconds(stamps[numericId],gossip.currentTime), null, true, null,noAgo,noAbout);
		}
	},
	
	removeFromFixedBox: function(id) {
		var containerCelebrityTweets = document.getElementById(id);
		if(containerCelebrityTweets != null){
			var maxHeight = containerCelebrityTweets.offsetHeight;
			var elements = $$("ul#"+id+" li");
			
			var totalHeight = 0;
			var lastVisible = -1;
			for (var i=0; i!=elements.length; i++) {
				var item = elements[i];
				var itemHeight = item.offsetHeight + 20;
				if (totalHeight + itemHeight > maxHeight) {
					lastVisible = i-1;
					break;
				}
				lastVisible = i;
				totalHeight += itemHeight;
			}
			
			if(elements[lastVisible]){
				if(elements[lastVisible].className.indexOf("last") < 0){
					//if(!element[lastVisible]){
						elements[lastVisible].className += " last";
					//}
				}
			}
			
			for (var j=elements.length-1; j>lastVisible; j--) {
				var elem = elements[j];
				
				containerCelebrityTweets.removeChild(elem);
			}
		}
	}
};

String.prototype.escapeHTML = function (){
  return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
};

String.prototype.trim = function() {
	return this.replace(/^\s+/g,"").replace(/\s+$/g,"");
};

gossip.ie7 = (navigator.appVersion.indexOf("MSIE 7.")==-1) ? false : true;
gossip.ie8 = (navigator.appVersion.indexOf("MSIE 8.")==-1) ? false : true;

function getStyle(className) {
	var i = 0;
	if ($("instantPulpCSS") != null) {
		for(i=0; i<document.styleSheets.length;i++){
			if(document.styleSheets[i].href == $("instantPulpCSS").href)
				break;
		}
	}
	if (document.styleSheets.length > 0) {
	    var classes = document.styleSheets[i].rules || document.styleSheets[i].cssRules
	    for(var x=0;x<classes.length;x++) {
	    	if (classes[x].selectorText) {
		        if(classes[x].selectorText.toLowerCase()==className) {
		        	return classes[x];
		        }
	    	}
	    }
	    return null;
	} else {
		return null;
	}
}

function getMaxHeight(rule) {
	var style = getStyle(rule);
	if(style == null) {
		return null;
	}
	var cssHeight = style.maxHeight?style.maxHeight:style.style.maxHeight;
	cssHeight = cssHeight.trim().replace(/^(\d+)\s*(px)?$/,"$1");
	return parseInt(cssHeight);
}

gossip.topTitleMaxHeight = getMaxHeight(".hot_list td div.title");
gossip.fashionMaxHeight = getMaxHeight("#trending_fashion_fake_rule_max_heigth");
gossip.relatedNewsMaxHeight = getMaxHeight("#related_news_title_max_height");
	
function ellipsis(rule, maxHeight) {
	//alert("rule="+rule+" maxHeight="+maxHeight);
	var elements = $$(rule);
	for (var j=0; j!=elements.length; j++) {
		var element = elements[j];
		//alert(element.offsetHeight + " " + element.innerHTML);
		if (element.offsetHeight > maxHeight) {
			var text = element.innerHTML;
			var i = 0;
			while (element.offsetHeight > maxHeight && i < text.length) {
				element.innerHTML = text.substring(0,text.length - i).trim() + "...";
				i++;
			}
		}
	}
}

function scale(realw, realh, x, y, w, h, target, tw, th,i) {
	var iw = Math.min(tw,realw);
	var ih = Math.min(th,realh);
	var ii = Math.min(iw,ih);
	
	if (w < ii) {
	    dif = ii - w;
	    x -= dif/2;
	    y -= dif/2;
	    h += dif;
	    w += dif;
	    
	    if (y < 0) {
	        y = 0;
	    }
	    if (y > realh - ii) {
	        y = realh - ii;
	    }
	    if (x < 0) {
	        x = 0;
	    }
	    if (x > realw - ii) {
	        x = realw - ii;
	
	    }
	}
	
    var middleImage = document.getElementById(target);	
    middleImage.style.position = "absolute";
    middleImage.style.top = -Math.ceil((y*th)/w)+"px";
    middleImage.style.left = -Math.ceil((x*tw)/h)+"px";
    middleImage.style.height = Math.ceil((realh*th)/h)+"px";
    middleImage.style.width = Math.ceil((realw*tw)/w)+"px";
}

/*  Search Twitter  */
function slideDown(id,current,target,step,time) {
	var elementToDown = document.getElementById(id);
	var newMargin = (current+step);
	var newValue = newMargin + "px";

	elementToDown.style.marginTop = newValue;
	if (newMargin != target) {
		setTimeout("slideDown('"+id+"',"+newMargin+","+target+","+step+","+time+")", time);
	}	
}

function changeView(time, classVisible, classInvisible, list){

	var invisibles = $$("#"+list + " ."+classInvisible);
	var element = invisibles[invisibles.length - 1];
	var invisibleElem = false;
	if(element != null){
		invisibleElem = true;
	}
	
	if(time > 0){
		if(invisibleElem){
			invisibleElem = true;
			element.className = classVisible;
			
			move(classVisible,classInvisible,list);
	
			var height = element.offsetHeight;
			var mod = height % qSteps;
	
			if (mod != 0) {
				height = height - mod - qSteps;
			}
	
			element.style.marginTop = -height + "px";
			slideDown(element.id,-height,20,qSteps,15);
		}
	}
	
	if(!invisibleElem){
		var ul = document.getElementById(list);
		ul.style.height = 'auto';
	}
	
	if(classVisible == 'oneriot_visible'){
		setTimeout("changeView("+reloadTimeMilisOneRiot+",'"+classVisible+"','"+classInvisible+"','"+list+"')", reloadTimeMilisOneRiot);
	}else{
		setTimeout("changeView("+reloadTimeMilisTwitter+",'"+classVisible+"','"+classInvisible+"','"+list+"')", reloadTimeMilisTwitter);
	}
}

function replaceUrl(text){
	  var url_match = /https?:\/\/([-\w\.]+)+(:\d+)?(\/([-\w/_\.]*(\?\S+)?)?)?/;
	      
	  if(url_match.test(text)){
		  var modifyText = text;
		  var init;
		  var end;
		  var i = 0;
		  while(modifyText.length > 0 && url_match.test(modifyText)){
			  var url = url_match.exec(modifyText);
			  
			  url+="";
			  url = url.substr(0,url.indexOf(","));
			  
			  text = text.replace(url,"<a href='"+url+"' target='_blank' rel='nofollow'>"+url+"</a>");
			  
			  init = modifyText.indexOf(url);
			  end = init + url.length;
			  
			  modifyText = modifyText.substr(end);
			  
			  i++;
		  }
	  }
	  
	  return text;
}

function parse(data, parentDivId, divId, ulId){
	
	if(parentDivId == null){
		parentDivId = "twitter_search_items";
	}
	
	if(divId == null){
		divId = "result";
	}
	
	if(ulId == null){
		ulId = "twitsList";
	}
	
	var result = document.getElementById(divId); //'result'
	var ul = document.getElementById(ulId); //'twitsList'
	var prevElement = null;
	var containerHeight = ul.offsetHeight;
	var elementsHeight = 0;
	var twitterList = new Array();

	if(data.results && data.results != ''){
		var container = document.getElementById(parentDivId);//"twitter_search_items"
		container.className = "bar_container";
		
		var initVisible = Math.ceil((data.results.length - qTwits)/2);
		var endVisible = initVisible + qTwits;
		var i = 0;
		
		//var temp = "";
		
        data.results.each(function(result){
        	twitterList[i] = result.text;
        	
	        var bigDiv = document.createElement('div');
			bigDiv.className = 'display';

	        var divImg = document.createElement('div');
			divImg.className = 'thumb_small';
	        
	        var img = document.createElement('img');
			img.src = result.profile_image_url;

			divImg.appendChild(img);

	        var infoDiv = document.createElement('div');
	        infoDiv.className = 'info';
	        
	        var anchorUsername = document.createElement('a');
	        anchorUsername.className = 'username';
	        anchorUsername.target = '_target';
			anchorUsername.href = 'http://twitter.com/'+result.from_user;
			anchorUsername.innerHTML = result.from_user;
	        
	        var txt = document.createElement('p');
	        txt.className = 'desc';
	        txt.innerHTML = replaceUrl(result.text);
	        
	        var infoDetailsDiv = document.createElement('div');
	        infoDetailsDiv.className = 'info_details';

			var creationTime = new Date(result.created_at).getTime();
			var currentTime = new Date().getTime();
			
			//alert("created_at " + new Date(result.created_at) + " , creationTime " + creationTime + " , date " + new Date() + " , currentTime " + currentTime);
			
	        var time = document.createElement('p');
	        time.className = 'time';
			time.innerHTML = remaining.getString(-remaining.getSeconds(creationTime,currentTime),null,true);
	        
	        var via = document.createElement('p');
	        via.className = 'via';
	        via.innerHTML = ' via ';

			var init = result.source.indexOf("href=&quot;")+11;
			var end = result.source.substr(init,result.source.length).indexOf("&quot;");
	        var fromUrl = result.source.substr(init,end);

	        init = result.source.indexOf("&gt;")+4;
	        end = result.source.substr(init,result.source.length).indexOf("&lt;");
	        
	        var fromName = result.source.substr(init,end);
	        var source = document.createElement('a');
	        source.href = fromUrl;
			source.innerHTML = fromName;
		        
	        var clearDiv = document.createElement('div');
	        clearDiv.className = 'clear';

        	var element = document.createElement('li');
        	element.id = result.id;

        	if(ulId == "twitsList"){
        		if(i >= initVisible && i < endVisible ){
        			element.className = 'search_visible';
        		}else{
        			element.className = 'search_invisible';
        		}
        	}else{
        		if((data.results.length - i) > qTwits){
            		element.className = 'search_invisible';
            	} else{
            		element.className = 'search_visible';
    	        }
        	}
        	
        	//temp = temp + " - " + element.id + "[" + element.className + "]";
        	
        	infoDetailsDiv.appendChild(time);
			infoDetailsDiv.appendChild(via);
			infoDetailsDiv.appendChild(source);

			infoDiv.appendChild(anchorUsername);
			infoDiv.appendChild(txt);
			infoDiv.appendChild(infoDetailsDiv);
	        
	        bigDiv.appendChild(divImg);
			bigDiv.appendChild(infoDiv);
	        bigDiv.appendChild(clearDiv);

			var list = document.getElementById(ulId);//'twitsList'

			element.appendChild(bigDiv);
			list.appendChild(element);
			i++;
        });
        
        //alert("temp " + temp);
        
        if(ulId == "twitsList"){
        	particularMove('search_visible','search_invisible',ulId);
        }else{
        	move('search_visible','search_invisible',ulId);//'twitsList'
        }
        
        changeView(0,'search_visible','search_invisible',ulId);//'twitsList'
        
        if(ulId == "twitsList") {
        	if ($("uniqueTagCloud") != null) {
        		tagClouds(twitterList,"uniqueTagCloud", data.query);
        	}
        }
	}else{
		result.removeChild(ul);
		result.className = 'no_tweets';
		result.innerHTML = 'There is no related tweets';
		
		displayRightBarItems(true,false);
 	}
}

function tagClouds(data, tagCloudId, keyword){
	var qWords = 1;
	var qSentences = 25;
	var qDifference = 20; 
	var minFontSize = 12;
	var maxFontSize = 30;
	var referenceFontSize = maxFontSize - minFontSize;
	var frequency = {};
	var present;
	
	var cleanList = new Array();
	
	for (var k=0; k!=data.length; k++) {
		var similar = false;
		var text = data[k];
		
		if(!similar){
			cleanList.push(text);
		}
	}
	
	for(var c = 0; c < cleanList.length; c++){
		var sentence = cleanList[c].gsub(/(ftp|http|https):\/\/[^\s]+/," ");
		
		sentence = sentence.unescapeHTML();
		
		var sentences = sentence.split(/[,.;:+=|]/);

		present = new Array();
		
		for(var s = 0; s < sentences.length; s++){
			var words = sentences[s].split(/\s-\s|\s'|'\s|\s|[^-A-Za-z0-9'$€@&#]/);
			var w = "";
			
			for(var i = 0; i < words.length; i++){
				w = "";
				var k = 0;
				for(var j = i; j < words.length && k < qWords; j++){
					w += " " + words[j].toLowerCase();
					
					w = trim(w);
					
					if(w.length > 0){
						var contain = false;
						var l;
						for(l = 0; l < present.length; l++){
							if(present[l] == w){
								contain = true;
								break;
							}
						}
						
						if(!contain){
							present.push(w);
						
							if(frequency[w] != null){
								frequency[w] += 1;
							}else{
								frequency[w] = 1;
							}
						}
					}
					k++;
				}
			}
		}
    }
	
	var keyList = new Array();
	var valueList = new Array();
	
	//Ordena los elementos por longitud
	for(x in frequency){
		var j;
		var keyFreq = x;
		
		for(j = 0; j < keyList.length; j++){
			var keySize = keyList[j];
			
			if(keySize.length <= keyFreq.length){
				break;
			}
		}
		
		keyList.splice(j,0,x);
	}
	
	var keyFreqList = new Array();
	
	//Ordena los elementos por frecuencia de aparicion
	for(var i = 0; i < keyList.length; i++){
		var j;
		
		var kSize = keyList[i];
		
		for(j = 0; j < keyFreqList.length; j++){
			var kFreq = keyFreqList[j];
			if((frequency[kFreq] == frequency[kSize]) && (kFreq.length < kSize.length)){
				break;
			}else if(frequency[kFreq] < frequency[kSize]){
				break;
			}
		}
		
		keyFreqList.splice(j,0,keyList[i]);
	}
	
	keyList = new Array();

	//Ordena los elementos sin substrings
	var scape_codes_match = /^\&[^;]+;$/;
	
	for(var i = 0; i < keyFreqList.length; i++){
		var contain = false;
		var keyFreq = keyFreqList[i];
		
		for(var j = 0; j < keyList.length; j++){
			var keyFinal = keyList[j];
			if(keyFinal.indexOf(keyFreq) >= 0){
				contain = true;
				break;
			}
		}
		
		if(!contain){
			var index = stopWords.binarySearch(keyFreq.toLowerCase(), function(a,b) {if (a>b) {return 1;} else if (a<b) {return -1} else {return 0;}});
			
			if (index != null) {
				contain = true;
			}
			
			if(!contain){
				//Quita el keyword de la nube
				if(keyword.toLowerCase().indexOf(keyFreq.toLowerCase()) >= 0 || keyFreq.length < 2 /*|| scape_codes_match.test(keyFreq)*/){
					contain = true;
				}
				
				if(!contain){
					keyList.push(keyFreqList[i]);
					valueList.push(frequency[keyFreqList[i]]);
				}
			}
		}
	}
	
	var tagCloud = document.getElementById(tagCloudId);
	var mixTags = new Array();
	
	if(tagCloud.hasChildNodes()){
		while(tagCloud.childNodes.length >= 1 ){
			tagCloud.removeChild(tagCloud.firstChild);       
	    }
	}
	
	for(var m = 0; m < keyList.length && m < qSentences;m++){
		mixTags[m] = m;
	}
	
	var maxValue = valueList[0];
	var minValue = valueList[mixTags.length-1];
	var referenceValue = maxValue - minValue;
	
	mixTags = mezclar(mixTags);
	
	for(var i = 0; i < mixTags.length; i++){
		var mix = mixTags[i];
		var cloudAnchor;
		var sizeFont = Math.floor((((valueList[mix]-minValue)*referenceFontSize)/referenceValue)+minFontSize);
		
		sizeFont+="px";
		
		if(keyList[mix].indexOf("@") == 0){
			cloudAnchor = document.createElement("a");
			cloudAnchor.href = "http://twitter.com/"+keyList[mix].substr(1,keyList[mix].length-1);
			cloudAnchor.target = "_blank";
		}
		else if(keyList[mix].indexOf("#") == 0){
			cloudAnchor = document.createElement("a");
			cloudAnchor.href = "http://twitter.com/#search?q=%23"+keyList[mix].substr(1,keyList[mix].length-1);
			cloudAnchor.target = "_blank";
		}else{
			cloudAnchor = document.createElement("span");
		}
		
		cloudAnchor.innerHTML = keyList[mix];
		cloudAnchor.style.fontSize = sizeFont;
		
		tagCloud.appendChild(cloudAnchor);
		tagCloud.appendChild(document.createTextNode(" "));
	}
	
	if(mixTags.length > 0){
		tagCloud.style.display = "block";
	}
}

Array.prototype.binarySearch = function binarySearch(find, comparator) {
	  var low = 0, high = this.length - 1,
	      i, comparison;
	  while (low <= high) {
	    i = parseInt((low + high) / 2, 10);
	    comparison = comparator(this[i], find);
	    if (comparison < 0) {low = i + 1;continue;};
	    if (comparison > 0) {high = i - 1;continue;};
	    return i;
	  }
	  return null;
	};

function mezclar(x) {
  // Vamos a recorrer la lista desde el final
  var i = x.length;
  while (i>0) {
      // aleatoriamente elegimos otro elemento entre [0] e [i] (incluido)
      k = Math.floor(Math.random()*i);
      i--;
      //intercambiamos x[i] con x[k]
      var temp = x[i];
      x[i] = x[k];
      x[k] = temp;
  }
  return x;
}

function trim(str){
    if(!str || typeof str != 'string')
        return null;

    return str.replace(/^[\s]+/,'').replace(/[\s]+$/,'').replace(/[\s]{2,}/,' ');
}

function particularMove(classVisible, classInvisible, list) {
	var visibles = $$("#"+list + " ."+classVisible);
	var invisibles = $$("#"+list + " ."+classInvisible);
	var list = document.getElementById(list);
	var maxHeight = list.offsetHeight;
	var totalHeight = 0;
	var lastVisible = -1;
	for (var i=0; i!=visibles.length; i++) {
		var item = visibles[i];
		var itemHeight = item.offsetHeight + 20;
		if (totalHeight + itemHeight > maxHeight) {
			lastVisible = i-1;
			break;
		}
		lastVisible = i;
		totalHeight += itemHeight;
	}

	visibles[lastVisible].className += " last";

	var init = Math.ceil((invisibles.length + visibles.length - qTwits)/2);
	//var temp = "";
	
	for (var j=visibles.length-1; j>lastVisible; j--) {
		visibles[j].className = classInvisible;
		list.insertBefore(visibles[j],invisibles[0]);
		//temp = temp + " - visibles[" + j + "] " + visibles[j].id;
	}
	
	//alert("primer temp " + temp);
	//temp = "";
	
	for(var k = init; k < invisibles.length; k++){
		//temp = temp + " - invisibles[" + k + "] " + invisibles[k].id; 
		list.insertBefore(invisibles[k], invisibles[0]);
	}
	
	//alert("otro temp " + temp);
}

function move(classVisible, classInvisible, list) {
	var visibles = $$("#"+list + " ."+classVisible);
	var invisibles = $$("#"+list + " ."+classInvisible);
	var list = document.getElementById(list);
	var maxHeight = list.offsetHeight;
	
	var totalHeight = 0;
	var lastVisible = -1;
	for (var i=0; i!=visibles.length; i++) {
		var item = visibles[i];
		var itemHeight = item.offsetHeight + 20;
		if (totalHeight + itemHeight > maxHeight) {
			lastVisible = i-1;
			break;
		}
		lastVisible = i;
		totalHeight += itemHeight;
	}

	visibles[lastVisible].className += " last";

	for (var j=visibles.length-1; j>lastVisible; j--) {
		visibles[j].className = classInvisible;
		list.insertBefore(visibles[j],invisibles[0]);
	}
}

function search(keyword){
	keyword = encodeURI(keyword);

	var list = document.getElementById('twitsList');

	if(list != null){
		//Le quita los elementos viejos
		while ( list.childNodes.length >= 1 )
	    {
	        list.removeChild(list.firstChild);       
	    }
	}
	
	var script = document.createElement("script");
	script.src = "http://search.twitter.com/search.json?&q="+keyword+"&lang=en&rpp=100&callback=searchCallback";
	
	script.id = "searchTwitter";
	document.getElementsByTagName("head")[0].appendChild(script);
}

function searchCallback(data) {
	var result = document.getElementById('result');
	var ul = document.createElement('ul');
	
	ul.id = 'twitsList';
	ul.className = 'on_twitter_search';
	ul.style.overflow = 'hidden';
	ul.style.height = '700px';

	result.appendChild(ul);

	if(data.results && data.results != ''){
        //parse(data);
        parse(data, "twitter_search_items", "result", "twitsList");
	}else{
		var keyword = data.query.replace(/,/gi, " OR ");

		var script = document.createElement("script");
		script.src = "http://search.twitter.com/search.json?&q="+keyword+"&lang=en&rpp=100&callback=parse";
		script.id = "searchTwitter";
		document.getElementsByTagName("head")[0].appendChild(script);
 	}
}

function getTimeLine(keyword){
	keyword = encodeURI(keyword);
	
	var list = document.getElementById('timeLineList');//twitsList

	if(list != null){
		//Le quita los elementos viejos
		while ( list.childNodes.length >= 1 ){
	        list.removeChild(list.firstChild);       
	    }
	}
	
	var script = document.createElement("script");
	script.src = "http://search.twitter.com/search.json?&q=from%3A"+keyword+"&rpp=100&callback=getTimeLineCallback";
	script.id = "timeLineTwitter"; //searchTwitter
	document.getElementsByTagName("head")[0].appendChild(script);
}

function getTimeLineCallback(data) {
	var result = document.getElementById('timeLine');//result
	var ul = document.createElement('ul');
	
	ul.id = 'timeLineList';
	ul.className = 'on_twitter_search';
	ul.style.overflow = 'hidden';
	ul.style.height = '700px';

	result.appendChild(ul);

	if(data.results && data.results != ''){
		parse(data, "twitter_timeLine_items", "timeLine", "timeLineList");
	}else{
		//alert("getTimeLineCallback NO DATA RESULTS!!!");
 	}
}

function setSource(idElem, urlTotal){
	 var elem = document.getElementById(idElem);
	 var urlRoot = urlTotal.substr(0,urlTotal.indexOf("/"));
	 
	 if(urlRoot.indexOf("http://") < 0){
		 urlRoot = "http://"+urlRoot;
	 }
	 
	 if(elem != null){
		 elem.href = urlRoot;
	 }
}

function displayRightBarItems(twitter,oneriot) {
	if (twitter) {
		gossip.twitterEmpty = true;
	} 
	if (oneriot) {
		gossip.oneriotEmpty = true;
	}
	
	if (gossip.twitterEmpty && gossip.oneriotEmpty) {
		var items = $$('.bar_container.hidden');
		for (var i=0; i!=items.length; i++) {
			items[i].removeClassName("hidden");
		}
	}
}

FB.Event.subscribe('auth.authResponseChange', function(response) {
    if (response.authResponse) {
    	var facebookSpan = document.getElementById("facebook_message_span");
    	if(facebookSpan != null){
    		facebookSpan.style.display = "none";
    	}
    } else {
    	var facebookSpan = document.getElementById("facebook_message_span");
    	if(facebookSpan != null){
    		facebookSpan.style.display = "inline";
    	}
    }
});

function showFacebookFields(){
    $("fcbk_login_div").className = "hidden";
    $("fcbk_login_div2").className = "hidden";

    $("socialUser").value = socialUser.id;
    $("socialUser_c").value = socialUser.id;

    $("myUserSocialPict").src = "http://graph.facebook.com/"+socialUser.id+"/picture?type=square";
    $("myUserSocialName").innerHTML = socialUser.name;
}

function hideFacebookFields(){
    $("socialUser").value = "";
    $("socialUser_c").value = "";

    $("myUserSocialPict").src = srcTempImg;
    $("myUserSocialName").innerHTML = "You";
}

function edit() {
	var root = contextPath;
	if (root == "") {
		root = "/";
	}
	window.open(root + window.editURL);
}

function ban(admin, argUrl) {
	
    var root = contextPath;
    if (root == "") {
        root = "/";
    }
    var url = root;
    if (window.blockURL) {
        url += blockURL;
            //alert("blockURL = " + blockURL);
    } else {
        url += argUrl;
            //alert("argURL = " + argUrl);
    }
    var userResponse = true;
    if (!admin) {
        userResponse = confirm("Are you sure you want to block this story?");
    }

    if (userResponse) {
        var request = new Ajax.Request(url,{
            onSuccess: function(transport) {
                var json = null;
                try {
                    json = (transport.responseText).evalJSON();
                } catch (e) {
                }
                if (json != null && json.result == 'OK') {
                    if (admin) {
                        window.location.reload();
                    } else {
                        if (json.block) {
                            alert("Success. The story was blocked.");
                        } else {
                            alert("Success. The story was unblocked.");
                        }
                    }

                }else if (json != null && json.result == 'INVALID') {
                    if (json.block) {
                        alert("Failure. The story is already blocked.");
                    } else {
                        alert("Failure. The story is not blocked.");
                    }
                } else {
                    alert('Sorry, something went wrong...');
                }
            },
            onFailure: function(){ 
                alert('Sorry, something went wrong...');
            }
        });
    }
}

function getComments() {
    var root = contextPath;
    if (root == "") {
        root = "/";
    }
    if (root.charAt(root.length - 1) != "/") {
        root += "/";
    }
    
    var url = root + "get-comments?articleId=" + articleId + "&page=" + commentsPage;
    if (commentsFilter) {
        url += "&type=" + commentsFilter;
    }
    
    var request = new Ajax.Request(url, {
        onSuccess: renderComments,
        onFailure: function() {
            if (window.console) {
                console.log("error getting comments");
            }
            //alert('Sorry, something went wrong...');
        }
    });
}

function putInCommentsMap(comment, level) {
    comment.level = level;
    allComments[comment.id] = comment;
    
    if (comment.children) {
        for (var i = 0; i != comment.children.length; i++) {
            putInCommentsMap(comment.children[i], level + 1);
        }
    } 
}

function loadMoreComments() {
    commentsPage++;
    getComments();
}

function renderCommentRec(ul,comment,level) {
    var li = getCommentLi(comment);
    li.addClassName("level_"+level);
    ul.appendChild(li);
    
    if (comment.children) {
        for (var i=0; i!=comment.children.length; i++) {
            renderCommentRec(ul, comment.children[i], level + 1);
        }
    }
}

function renderComments(response) {
    var json = null;
    try {
        json = (response.responseText).evalJSON();
    } catch (e) {
        Logger.log("error parsing JSON response");
        Logger.log(e);
    }
    if (json != null) {
        
        commentsReady = true;
        commentsResponse = json;
        
        var ul = $("comment_list");
        var loadMore = $("loadMore");
        if (loadMore) {
            ul.removeChild(loadMore);
            locaMore = null;
        }
        
        var comments = json.comments;
        for (var i=0; i!= comments.length; i++) {
            var comment = comments[i];
            putInCommentsMap(comment, 0);
            renderCommentRec(ul, comment, 0);
            
        }
        if (json.moreAvailable) {
            loadMore = DOMBuilder.build({
                tagName: "li",
                id: "loadMore",
                children: [{
                    tagName: 'a',
                    href: "javascript:loadMoreComments();",
                    children:[{
                        text: "load more"
                    }]
                }]
            });
                
            ul.appendChild(loadMore);
        }
        
        fixComments();
        
        if (justCreated != null) {
            //Navigate to the new comment
            if((document.location.toString()).indexOf("#") != -1){
                window.location = (window.location.toString()).split("#")[0] + "#comment_"+justCreated;
            }else{
                window.location += "#comment_"+justCreated;
            }
            
            var message = $$("#comment_" + justCreated +" .comment_message");
            if (message.length == 0) {
                //reaction
                $("comment_" + justCreated).addClassName("comment_added");
            } else {
                message[0].addClassName("comment_added");
            }
            
            justCreated = null;
        }
        
        var shareCounters = $$(".share .commentCount .counter");
        for (var i=0; i!=shareCounters.length; i++) {
            var span = shareCounters[i];
            span.innerHTML = "" + json.commentsCount;
        }
        
        var commentsTabLabel = $$("#labelCommentsCounter .counter")[0];
        commentsTabLabel.innerHTML = "" + json.commentsCount;
        
        var reactionsTabLabel = $$("#labelReactionsCounter .counter")[0];
        reactionsTabLabel.innerHTML = "" + json.reactionsCount;
        
        for (var reactionKey in json.reactionCounters) {
            var value = json.reactionCounters[reactionKey];
            $("counter_" + reactionKey).innerHTML = (value > 0) ? ""+value : "";
        }
    }
}

function getCommentLi(comment, isNew) {
        
    if (comment.type == "REACTION") {
        
        return DOMBuilder.build({
            tagName: 'li',
            id: 'comment_R',
            children: [{
                tagName: 'div',
                id: 'comment_' + comment.id,
                children: [{
                    tagName: 'a',
                    className: 'username',
                    href: comment.author.profileUrl,
                    target: '_blank',
                    rel: 'nofollow',
                    children: [{
                        text: comment.author.name
                    }]
                },{
                    tagName: 'div',
                    className: 'expressionComment',
                    children: [{
                        text: comment.text
                    }]
                },{
                    tagName: 'a',
                    children: [{
                        text: " this"
                    }]
                },{
                    tagName: 'a',
                    className: 'timing',
                    id: 'time_' + comment.id
                }]
            }]
        });
        
    } else {
        
        return DOMBuilder.build({
            tagName: 'li',
            id: 'comment_C',
            children: [{
                tagName: 'div',
                id: 'comment_' + comment.id,
                children: [{
                    tagName: 'div',
                    className: 'comment_thumb_small',
                    children: [{
                        tagName: 'img',
                        src: comment.author.profileImageUrl,
                        //src: "http://graph.facebook.com/"+comment.author.remoteId+"/picture?type=square",
                        alt: comment.author.name
                    },{
                        tagName: 'a',
                        className: 'username',
                        href: comment.author.profileUrl,
                        target: '_blank',
                        rel: 'nofollow',
                        children: [{
                            text: comment.author.name
                        }]
                    }]
                },{
                    tagName: 'div',
                    className: 'comment_info',
                    children: [{
                        tagName: 'div',
                        className: 'comment_message' + (isNew?" comment_added":"") + " " + comment.status,
                        children: [{
                            tagName: 'a',
                            children: [{
                                text: comment.text
                            }]
                        }]
                    },{
                        tagName: 'div',
                        className: 'comment_time',
                        children: [{
                            tagName: 'a',
                            className: 'time',
                            id: 'time_' + comment.id
                        },{
                            tagName: "span",
                            innerHTML: '&nbsp;&nbsp;&nbsp;&nbsp;'
                        },{
                            tagName: 'a',
                            className: 'delete_comment hidden',
                            id: 'reply_' + comment.id,
                            href: "javascript:replyTo('" + comment.id + "');",
                            children: [{
                                text: 'reply'
                            }]
                        },{
                            tagName: "span",
                            innerHTML: '&nbsp;&nbsp;&nbsp;&nbsp;'
                        },{
                            tagName: 'a',
                            className: 'delete_comment hidden',
                            id: 'delete_' + comment.id,
                            href: "javascript:deleteComment('" + comment.id + "');",
                            children: [{
                                text: 'delete'
                            }]
                        },{
                            tagName: 'a',
                            className: 'delete_comment hidden',
                            id: 'flag_' + comment.id,
                            href: "javascript:flagComment('" + comment.id + "');",
                            children: [{
                                text: 'flag'
                            }]
                        }]
                    }]
                },{
                    tagName: 'div',
                    className: 'clear'
                }]
            }]
        });
    }
}

function replyTo(parentId) {
    
    var parent = allComments[parentId];
    if (parent == null) {
        Logger.log("parent not found");
        return;
    }
    
    var authorNode = $("parentAuthor");
    var textNode = $("parentText");
    var replayHint = $("parentHint");
    var parentField = $("parentId");
    
    parentField.value = parentId;
    
    authorNode.innerHTML = "";
    authorNode.appendChild(document.createTextNode(parent.author.name));
    
    textNode.innerHTML = "";
    textNode.appendChild(document.createTextNode(parent.text));
    
    replayHint.removeClassName("hidden");
    
    if((document.location.toString()).indexOf("#") != -1){
        window.location = (window.location.toString()).split("#")[0] + "#addComment";
    }else{
        window.location += "#addComment";
    }
    $('text_c').focus();
}

function cancelNestedComment() {
    
    var authorNode = $("parentAuthor");
    var textNode = $("parentText");
    var replayHint = $("parentHint");
    var parentField = $("parentId");
    
    parentField.value = "";
    authorNode.innerHTML = "";
    textNode.innerHTML = "";
    
    replayHint.addClassName("hidden");
    
    $('text_c').focus();
}

function fixComments() {
    
    if (!commentsReady) {
        //nothing to do
        return;
    }
    
    for (var id in allComments) {
        if ($("comment_"+id) == null) {
            //not visible
            continue;
        }
        var comment = allComments[id];

        if (comment.type == "COMMENT") {

            var replyLink = $("reply_" + comment.id);
            var delLink = $("delete_" + comment.id);
            var flagLink = $("flag_" + comment.id);

            if (comment.status != 'DEFAULT' && comment.status != 'APPROVED_BY_ADMIN') {
                replyLink.addClassName("hidden");
                delLink.addClassName("hidden");
                flagLink.addClassName("hidden");
            } else if (userReady && comment.author.source == "FACEBOOK" && comment.author.remoteId == socialUser.id) {
                if (comment.level < maxCommentsNestedLevel) {
                    replyLink.removeClassName("hidden");
                } else {
                    replyLink.addClassName("hidden");
                }
                delLink.removeClassName("hidden");
                flagLink.addClassName("hidden");
            } else {
                if (comment.level < maxCommentsNestedLevel) {
                    replyLink.removeClassName("hidden");
                } else {
                    replyLink.addClassName("hidden");
                }
                flagLink.removeClassName("hidden");
                delLink.addClassName("hidden");
            }
        }
        try {
        setTimesAgo(comment.id, comment.createdAt);
        } catch (ex) {
            Logger.log(ex);
        }
    }
}

function doReaction(word){
    if(!blockReactions){
        blockReactions = true;
        if($("socialUser").value != ""){
            $("text").value = word;                                
            var actionTmp = word;

            new Ajax.Request(contextPath + '/comment',
            {
                method:'post',
                encoding: 'UTF-8',
                parameters: {id: $("save_c_id").value, text: word, 
                    type: 'R'}, 
                onSuccess: function(transport){
                    blockReactions = false;
                    var json = (transport.responseText).evalJSON();
                    if(json.error != null){
                        alert('Sorry, error: '+json.error);
                    }else{
                        if(json.comment != null){ //SHOW NEW COMMENT
                            
                            justCreated = json.comment.id;
                            toggleComments('A');
                        }

                        //GOOGLE ANALYTICS EVENT TRACKING
                        //alert("_trackEvent "+GA.REACTIONS.CAT+" "+actionTmp+" "+ gaEventLabel);
                        _gaq.push(['_trackEvent', GA.REACTIONS.CAT, actionTmp, gaEventLabel]);
                    }
                },
                onFailure: function(){ 
                    alert('Sorry, something went wrong...')
                    blockReactions = false;
                }
            });
            //$("reactionForm").submit();
        }else{
            $("fcbk_login_div").className = "show";
            blockReactions = false;
        }
    }
}

function doComment(){
    if(!blockComments){
        blockComments = true;
        if($("socialUser_c").value != ""){
            if( $("text_c").value.strip() != ""){ //STRIP = TRIM
                if($("text_c").value.length <= limit){

                    var shareFacebookVal = (($("shareFacebook").checked == 1) ? "on" : "off");
                    var shareTwitterVal = (($("shareTwitter").checked == 1) ? "on" : "off");
                   //	alert("parameters "+$("save_c_id").value+ " action "+$("save_c_action").value+ " text " + $("text_c").value+ " FCBK "+ shareFacebookVal+ " TwiTTer "+ shareTwitterVal);
                    new Ajax.Request(contextPath + '/comment',
                    {
                        method:'post',
                        encoding: 'UTF-8',
                        parameters: {id: $("save_c_id").value, parentId: $("parentId").value, text: $("text_c").value, 
                            shareFacebook: shareFacebookVal, shareTwitter: shareTwitterVal, type: "C"}, 
                        onSuccess: function(transport){
                            blockComments = false;
                            var json = (transport.responseText).evalJSON();
                            if(json.error != null){
                                if(json.error == "max_comments_reached"){
                                    $("error_comments").style.display = "block";
                                    //GOOGLE ANALYTICS EVENT TRACKING
                                    //alert("_trackEvent "+GA.COMMENTS.CAT+" "+GA.COMMENTS.ACT.MAX_REACHED+" "+ gaEventLabel);
                                    _gaq.push(['_trackEvent', GA.COMMENTS.CAT, GA.COMMENTS.ACT.MAX_REACHED, gaEventLabel]);
                                }else{
                                    alert('Sorry, error: '+json.error);
                                }
                            }else{
                                $("text_c").value = "";
                                cancelNestedComment();
                                
                                if(json.postToTwitter != null){
                                    alert('Twitter is opening in a new window in order to post your tweet');
                                    window.open(json.postToTwitter);
                                }
                                if(json.comment != null){
                                    //SHOW THE NEW COMMENT
                                    justCreated = json.comment.id;
                                    toggleComments('A');
                                }

                                //GOOGLE ANALYTICS EVENT TRACKING
                                if ($("shareFacebook").checked == 1 ) {
                                    _gaq.push(['_trackEvent', GA.COMMENTS.CAT, GA.COMMENTS.ACT.POST_FCBK, gaEventLabel]);
                                }
                                if ($("shareTwitter").checked == 1 ) {
                                    _gaq.push(['_trackEvent', GA.COMMENTS.CAT, GA.COMMENTS.ACT.POST_TWITTER, gaEventLabel]);
                                }
                                _gaq.push(['_trackEvent', GA.COMMENTS.CAT, GA.COMMENTS.ACT.COMMENT, gaEventLabel]);
                            }
                        },
                        onFailure: function(){ 
                            alert('Sorry, something went wrong...')
                            blockComments = false; 
                        }
                    });	
                    //$("commentForm").submit();
                }else{
                    alert("Your comment must have less than "+limit+" characters");
                    blockComments = false;
                }
            }else{
                alert("Please, write your comment");
                blockComments = false;
            }
        }else{
            $("fcbk_login_div2").className = "show";
            blockComments = false;
        }
    } else {
        Logger.log("comment in progress!");
    }
}

function deleteComment(idComment){
    if(!blockDelete){
        blockDelete = true;
        new Ajax.Request(contextPath + '/delete-comment',
            {
                method:'post',
                encoding: 'UTF-8',
                parameters: {idComment: idComment}, 
                onSuccess: function(transport){
                    blockDelete = false;
                    var json = (transport.responseText).evalJSON();
                    if(json.error != null){
                        alert('Sorry, error: '+json.error);
                    }else if(json.success != null){
                        
                        $$("#comment_" + json.idComment + " .comment_message a")[0].innerHTML = removedByAuthorText;
                        $$("#comment_" + json.idComment + " .comment_message")[0].addClassName("REMOVED_BY_AUTHOR");
                        $("delete_" + json.idComment).addClassName("hidden");
                        $("reply_" + json.idComment).addClassName("hidden");
                        
                        //GOOGLE ANALYTICS EVENT TRACKING
                        //alert("_trackEvent "+GA.COMMENTS.CAT+" "+GA.COMMENTS.ACT.DEL_COMMENT+" "+ gaEventLabel);
                        _gaq.push(['_trackEvent', GA.COMMENTS.CAT, GA.COMMENTS.ACT.DEL_COMMENT, gaEventLabel]);
                    }
                    
                },
                onFailure: function(){
                    alert('Sorry, something went wrong...');
                    blockDelete = false; 
                }
            });
    }
}

function flagComment(idComment){
    
    new Ajax.Request(contextPath + '/flag-comment',
        {
            method:'post',
            encoding: 'UTF-8',
            parameters: {idComment: idComment}, 
            onSuccess: function(transport){
                var json = (transport.responseText).evalJSON();
                if(json.error != null){
                    alert('Sorry, error: '+json.error);
                }else if(json.success != null){
                    
                    $$("#comment_" + json.idComment + " .comment_message a")[0].innerHTML = waitingForReviewText;
                    $$("#comment_" + json.idComment + " .comment_message")[0].addClassName("WAITING_FOR_REVIEW");
                    $("flag_" + json.idComment).addClassName("hidden");
                    $("reply_" + json.idComment).addClassName("hidden");
                    
                    //GOOGLE ANALYTICS EVENT TRACKING
                    //alert("_trackEvent "+GA.COMMENTS.CAT+" "+GA.COMMENTS.ACT.DEL_COMMENT+" "+ gaEventLabel);
                    _gaq.push(['_trackEvent', GA.COMMENTS.CAT, GA.COMMENTS.ACT.DEL_COMMENT, gaEventLabel]);
                }
            },
            onFailure: function(){
                alert('Sorry, something went wrong...');
            }
        });
}

function toggleComments(type) {

    var ul = $("comment_list");
    while (ul.childNodes.length > 0) {
        var child = ul.childNodes[0];
        ul.removeChild(child);
    }

    commentsPage = 1;
    
    switch (type) {
        case 'A':
            commentsFilter = null;
            break;
        case 'R':
            commentsFilter = "REACTION";
            break;
        case 'C':
            commentsFilter = "COMMENT";
            break;
        default:
            Logger.log("Not implemented, type="+type);
            break;
    }
        
    $("comment_tabs_A").className = (type == "A") ? "selected" : "";
    $("comment_tabs_R").className = (type == "R") ? "selected" : "";
    $("comment_tabs_C").className = (type == "C") ? "selected" : "";
    
    getComments();
}
