/************************ ON LOAD ******************************/
function adjustContent() {
	var filterBarElem = $('filter-bar');
	var theContentElem = $('the-content');
	
	if (filterBarElem && theContentElem) {
		adjustCollapseButton();
		
		var barHeight = (filterBarElem.getHeight() - 40);		
		if (theContentElem.getHeight() < barHeight) {
			theContentElem.setStyle({
				height: barHeight + 'px'
			});
		}	
	}
}

/************************ HELPERS ******************************/
function elementList(name, over) {
	var elem = $(name);
	
	if (elem) {
		if (over)
			elem.show();
		else
			elem.hide();
	}
}
function redirect(url) {
	window.location.replace(url); 
}
function clickedInsideElement(element, mouseEvent) {
	var mouse_x = Event.pointerX(mouseEvent);
	var mouse_y = Event.pointerY(mouseEvent);
	
	if (mouse_x == 0 || mouse_y == 0) return true;
	
	var elem_x = element.cumulativeOffset()[0];	
	var elem_y = element.cumulativeOffset()[1];

	var elem_height = element.getDimensions().height;
	var elem_width = element.getDimensions().width;
	
	return (mouse_x <= (elem_x + elem_width) && mouse_x >= elem_x && mouse_y <= (elem_y + elem_height) && mouse_y >= elem_y);
}

/************************ TIMEOUT ******************************/
var timeout = [];
function __setTimeout(f, time, the_timeout) {
	if (timeout[the_timeout] != null) 
		window.clearTimeout(timeout[the_timeout]);
	timeout[the_timeout] = window.setTimeout(f, time);
}

function __clearTimeout(the_timeout) {
	window.clearTimeout(timeout[the_timeout]);
}


/************************* LOADER ******************************/
var loaderCounts = {};
var loaderMsgs = [];

function renderLoader() {
	loaderMsgs.reverse();
	loaderMsgs = loaderMsgs.uniq();
	
	$('loader').show();
	$('loader-msg').update(loaderMsgs.join('<br />'));
	
	loaderMsgs.reverse();
}
function showLoader(msg) {
	if (!loaderCounts[msg])
		loaderCounts[msg] = 1;
	else {
		loaderCounts[msg]++;
	}
	
	loaderMsgs[loaderMsgs.size()] = msg;
	
	if (loaderMsgs.size() > 0)
		renderLoader();
}
function hideLoader(msg) {
	if (loaderCounts[msg]) {
		loaderCounts[msg]--;
		if (loaderCounts[msg] <= 0) {
			loaderCounts[msg] = null;
			loaderMsgs = loaderMsgs.without(msg);
		}
	}
	
	if (loaderMsgs.size() > 0) {
		renderLoader();
	}
	else {	
		$('loader').hide();	
		$('loader-msg').update('');
	}
}


/********************** ACCOUNT BAR ****************************/
function showCampaignMenu() {
	__clearTimeout('campaignmenu');
	$('campaign-menu').show();
}
function hideCampaignMenu() {
	__clearTimeout('campaignmenu');
	$('campaign-menu').hide();
}

function overCampaignMenu() {
	__setTimeout('showCampaignMenu()', 500, 'campaignmenu');
}
function outCampaignMenu() {
	__setTimeout('hideCampaignMenu()', 500, 'campaignmenu');	
}


/********************** CONFIG MENU ****************************/
function showConfigMenu() {
	var configTabElem = $('config-tab');
	var configMenuElem = $('config-menu');
	
	hideToolsMenu();
	hideEstatMenu();
	__clearTimeout('configmenu');
	if (!configTabElem.hasClassName('hover'))
		configTabElem.addClassName('hover');
	configMenuElem.show();
}
function hideConfigMenu() {
	var configTabElem = $('config-tab');
	var configMenuElem = $('config-menu');
	
	__clearTimeout('configmenu');
	if (configTabElem.hasClassName('hover'))
		configTabElem.removeClassName('hover');
	configMenuElem.hide();
}

function outConfigMenu() {
	__setTimeout('hideConfigMenu()', 300, 'configmenu');	
}


/*********************** TOOLS MENU ****************************/
function showToolsMenu() {
	var toolsTabElem = $('tools-tab');
	var toolsMenuElem = $('tools-menu');
	
	hideConfigMenu();
	hideEstatMenu();
	__clearTimeout('toolsmenu');
	if (!toolsTabElem.hasClassName('hover'))
		toolsTabElem.addClassName('hover');
	toolsMenuElem.show();
}
function hideToolsMenu() {
	var toolsTabElem = $('tools-tab');
	var toolsMenuElem = $('tools-menu');
	
	__clearTimeout('toolsmenu');
	if (toolsTabElem.hasClassName('hover'))
		toolsTabElem.removeClassName('hover');
	toolsMenuElem.hide();
}

function outToolsMenu() {
	__setTimeout('hideToolsMenu()', 300, 'toolsmenu');	
}


/*********************** ESTAT MENU ****************************/
function showEstatMenu() {
	var estatTabElem = $('estat-tab');
	var estatMenuElem = $('estat-menu');
	
	hideConfigMenu();
	hideToolsMenu();
	__clearTimeout('estatmenu');
	if (!estatTabElem.hasClassName('hover'))
		estatTabElem.addClassName('hover');
	estatMenuElem.show();
}
function hideEstatMenu() {
	var estatTabElem = $('estat-tab');
	var estatMenuElem = $('estat-menu');
	
	__clearTimeout('estatmenu');
	if (estatTabElem.hasClassName('hover'))
		estatTabElem.removeClassName('hover');
	estatMenuElem.hide();
}

function outEstatMenu() {
	__setTimeout('hideEstatMenu()', 300, 'estatmenu');	
}


/************************* STREAM ******************************/
var currentView = 'standard';

function selectStream(checkbox, id) {
	if (checkbox.checked)
		$('stream-selborder-' + id).addClassName('selected');
	else
		$('stream-selborder-' + id).removeClassName('selected');		
}
function selectStreamAlt(element, id, e) {
	var targ;
	
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3)
		targ = targ.parentNode;
	
	if (targ.tagName == 'TD' || targ.tagName == 'td')
		$('selector-checkbox-' + id).click();
}

function adjustStream(id) {
	adjustStreamSelector(id, true);
	adjustStreamTags(id);
	adjustStreamDelete(id);
}
function adjustSimpleStream(id) {
	adjustStreamTags(id);
	adjustStreamDelete(id);
}
function adjustPendingStream(id) {
	adjustPendingStreamDelete(id);
}
function adjustStreamTags(id) {
	var selectWidth = $('tag-hidden-list-' + id).getWidth();
	selectWidth = selectWidth + 50;
	
	var buttonWidth = $('tag-button-' + id).getWidth();
	var selectLeft = selectWidth - (buttonWidth - 12);
	
	$('tag-select-' + id).setStyle({
		width: selectWidth + 'px',
		left: '-' + selectLeft + 'px'
	});
}
function adjustStreamSelector(id, show) {
	var tdHeight = $('stream-selector-' + id).getHeight();
	if (show)
		var buttonHeight = $('search-collapse-' + id).getHeight();
	else
		var buttonHeight = $('search-show-' + id).getHeight();
	
	var topValue = ((tdHeight - buttonHeight) / 2) - 12;
	$('selector-checkbox-' + id).setStyle({
		top: '-' + topValue + 'px'
	});
}
function adjustStreamDelete(id) {
	var streamHeight = ($('stream-li-' + id).getHeight()) - 8;
	$('stream-delete-box-' + id).setStyle({
		height: streamHeight + 'px'
	});
}
function adjustPendingStreamDelete(id) {
	var streamHeight = ($('stream-pending-li-' + id).getHeight()) - 8;
	$('stream-pending-delete-box-' + id).setStyle({
		height: streamHeight + 'px'
	});
}

function showDeleteLink(id) {
	$('stream-delete-link-' + id).show();	
}
function hideDeleteLink(id) {
	$('stream-delete-link-' + id).hide();
}
function streamOver(id) {
	showDeleteLink(id);
	if (currentView == 'clean') {
		$('stream-actions-' + id).show();
		$('stream-tags-' + id).show();
		if ($('stream-replybutton-' + id))
			$('stream-replybutton-' + id).show();
	}
}
function streamOut(id) {
	hideDeleteLink(id);
	if (currentView == 'clean') {
		$('stream-actions-' + id).hide();
		$('stream-tags-' + id).hide();
		if ($('stream-replybutton-' + id))
			$('stream-replybutton-' + id).hide();
	}
}

function streamPendingOver(id) {
	showDeleteLink(id);
}
function streamPendingOut(id) {
	hideDeleteLink(id);	
}

function toggleItemReply(id) {
	if (currentView == 'standard') {
		if (($('stream-reply-' + id).visible() && !$('search-details-' + id).visible()) || (!$('stream-reply-' + id).visible() && $('search-details-' + id).visible()))
			toggleSearchDetails(id);
	}
		
	$('stream-reply-' + id).toggle();
}

function showSearchDetails(id) {
	$('search-show-' + id).hide();
	$('search-details-' + id).show();
	$('search-collapse-' + id).show();
	$('stream-li-' + id).removeClassName('with-no-details');
	adjustStreamSelector(id, true);
}
function hideSearchDetails(id) {
	$('search-details-' + id).hide();
	$('search-collapse-' + id).hide();
	$('search-show-' + id).show();
	$('stream-li-' + id).addClassName('with-no-details');
	adjustStreamSelector(id, false);
	
}
function toggleSearchDetails(id) {
	if ($('search-details-' + id).visible())
		hideSearchDetails(id);
	else
		showSearchDetails(id);
}

function classifyMouseOver(id, classif) {
	switch (classif)	{
		case 'positivo':
			$('button-neutro-' + id).addClassName('off');
			$('button-negativo-' + id).addClassName('off');
			break;
			
		case 'neutro':
			$('button-positivo-' + id).addClassName('off');
			$('button-negativo-' + id).addClassName('off');
			break;
			
		case 'negativo':
			$('button-positivo-' + id).addClassName('off');
			$('button-neutro-' + id).addClassName('off');
			break;
	}
}
function classifyMouseOut(id, classif) {
	$('button-positivo-' + id).removeClassName('off');
	$('button-neutro-' + id).removeClassName('off');
	$('button-negativo-' + id).removeClassName('off');
}

function beforeClassify(id, classif, force) {
		
	switch (classif)	{
		case 'positivo':
			if (force)
				$('button-positivo-' + id).addClassName('selected');
			else
				$('button-positivo-' + id).toggleClassName('selected');
			$('button-neutro-' + id).removeClassName('selected');
			$('button-negativo-' + id).removeClassName('selected');
			break;
			
		case 'neutro':
			$('button-positivo-' + id).removeClassName('selected');
			if (force)
				$('button-neutro-' + id).addClassName('selected');
			else
				$('button-neutro-' + id).toggleClassName('selected');
			$('button-negativo-' + id).removeClassName('selected');
			break;
			
		case 'negativo':
			$('button-positivo-' + id).removeClassName('selected');
			$('button-neutro-' + id).removeClassName('selected');
			if (force)
				$('button-negativo-' + id).addClassName('selected');
			else
				$('button-negativo-' + id).toggleClassName('selected');
			break;
			
		default:
			$('button-positivo-' + id).removeClassName('selected');
			$('button-neutro-' + id).removeClassName('selected');
			$('button-negativo-' + id).removeClassName('selected');
			break;
	}
	showLoader('Finalizando classificação');
	
}

function removeOverInTagList(id) {
	var tagsList = $('tag-list-inside-' + id).childElements();
	var tagsListLength = tagsList.length;
	
	for (var i = 0; i < tagsListLength; i++)
		tagsList[i].removeClassName('over');
}
function overInTagList(id) {
	var tagsList = $('tag-list-inside-' + id).childElements();
	var tagsListLength = tagsList.length;
	
	for (var i = 0; i < tagsListLength; i++) {
		if (tagsList[i].hasClassName('over'))
			return tagsList[i];
	}
	
	return false;
}
function nextInTagList(id) {
	var overTag = overInTagList(id);
	
	if (overTag) {
		var tagNext = overTag.next();
		if (tagNext) {
			overTag.removeClassName('over');
			tagNext.addClassName('over');
		}
	}
	else {
		var firstTag = $('tag-list-inside-' + id).firstDescendant();
		firstTag.addClassName('over');
	}
}
function previousInTagList(id) {
	var overTag = overInTagList(id);
	
	if (overTag) {
		var tagPrev = overTag.previous();
		if (tagPrev) {
			overTag.removeClassName('over');
			tagPrev.addClassName('over');
		}
	}
	else {
		var tagElems = $('tag-list-inside-' + id).childElements();
		var lastTag = tagElems[tagElems.length - 1];
		lastTag.addClassName('over');
	}
}
function selectInTagList(id) {
	var overTag = overInTagList(id);
	var chkTag = overTag.select('input.chk-tag-input');
	chkTag[0].click();
	hideTagList(id);
}

function overTagList(itemId, element) {
	removeOverInTagList(itemId);
	element.addClassName('over');
}
function outTagList(element) {
	element.removeClassName('over');
}

function observeTagList(e, id) {
	var element = Event.element(e);
	if (!clickedInsideElement($('tag-select-' + id), e) && !clickedInsideElement($('tag-button-' + id), e))
		hideTagList(id);
}
var nav = [];
function showTagList(id) {
	$('tag-list-' + id).show();
	$('tag-button-' + id).addClassName('active');
	if (document)
		document.observe('click', function(e) {
			observeTagList(e, id);
		});
	$('search-tag-' + id).focus();
	
	shownTags = $('tag-list-inside-' + id).select('div').length; 
	
	if (nav[id])
		nav[id].enable();
	else
		nav[id] = new Ext.KeyNav("search-tag-" + id, {
		    "down": function(e) {
				nextInTagList(id);
		    },
		    "up": function(e) {
		    	previousInTagList(id);
		    },
		    "enter": function(e) {
		    	selectInTagList(id);
		    },
		    "esc": function(e) {
		    	hideTagList(id);
		    },
		    scope: this
		});
}
function hideTagList(id) {
	shownTags = 0;
	$('tag-list-' + id).hide();	
	$('tag-button-' + id).removeClassName('active');
	if (document)
		document.stopObserving('click', function(e) {
			observeTagList(e, id);
		});
	
	var inputElem = $('search-tag-' + id);
	inputElem.clear();
	filterTagBySearch(id, inputElem);
	removeOverInTagList(id);
	nav[id].disable();
}
function toggleTagList(id) {
	if ($('tag-list-' + id).visible())
		hideTagList(id);
	else
		showTagList(id);
}
function showCreateTag(title, question, itemId) {
	var tagNome = prompt(title, question);
	submitAddTag(itemId, tagNome, 0);
}

function toggleCurrentTags(id) {
	if ($('tags-current-resume-' + id).visible()) {
		showCurrentTags(id);
	}
	else {
		$('tags-current-' + id).hide();
		$('tags-current-resume-' + id).show();
	}
}

var shownTags = 0;
function filterTagBySearch(item_id, txt) {
	var shownTagsBefore = shownTags;
	var divs = $('tag-list-inside-' + item_id).select('div');
	var firstDiv = null;
	
	shownTags = 0;
	divs.each(function(div){
		if (div.id.indexOf(item_id + '-' + txt.value) == -1) {  
			div.style['display'] = 'none';
		}
		else {
			if (!firstDiv)
				firstDiv = div;
			div.style['display'] = 'block';
			shownTags++;
		}
	});	

	if (txt.value == '' && shownTagsBefore != shownTags)
		removeOverInTagList(item_id);
	
	if (firstDiv && shownTags != divs.length && shownTagsBefore != shownTags) {
		removeOverInTagList(item_id);
		firstDiv.addClassName('over');
	}
}
function selectFirstTagFiltered(e, item_id, txt) {
	if (Event.KEY_RETURN == e.keyCode) {
		var input = $('tag-list-inside-' + item_id).select('input:first')[0];
		input.click();		
	}
}

function showCurrentTags(id) {
	$('tags-current-resume-' + id).hide();
	$('tags-current-' + id).show();
}


/*********************** FILTER BAR ****************************/
function adjustCollapseButton() {
	var filterBarElem = $('filter-bar');
	var filterBarCollapseElem = $('filter-bar-collapse');
	
	if (filterBarCollapseElem) {
		filterBarCollapseElem.setStyle({
			height: '0px'
		});
		
		var barHeight = (filterBarElem.getHeight() - 40);	
	
		filterBarCollapseElem.setStyle({
			height: (barHeight - 20) + 'px'
		});	
	}
}

function toggleFilterBlock(id) {
	if (!$(id).visible())
		showFilterBlock(id);
	else
		hideFilterBlock(id);

	adjustContent();
}
function showFilterBlock(id) {
	$(id).show();
	$(id + '-link').removeClassName('plus');
}
function hideFilterBlock(id) {
	$(id).hide();
	$(id + '-link').addClassName('plus');
}

function toggleGenericList(radio, type) {	
	if (radio.value == 'todas') {
		disableGenericList(type, true);
	}
	else if (radio.value == 'nenhuma') {
		disableGenericList(type, false);
	}
	else {
		enableGenericList(type);
	}
}
function forceGenericList(type) {
	$('radio-' + type + '-algumas').click();
}
function enableGenericList(type) {
	var inputs = $$('input.radio-' + type + '-checkbox');
	var labels = $$('label.radio-' + type + '-label');
	
	for (var i = 0; i < inputs.length; i++) {
		inputs[i].enable();
		labels[i].removeClassName('disabled');
	}
}
function disableGenericList(type, value) {
	var inputs = $$('input.radio-' + type + '-checkbox');
	var labels = $$('label.radio-' + type + '-label');

	for (var i = 0; i < inputs.length; i++) {
		inputs[i].checked = value;
		inputs[i].disable();
		labels[i].addClassName('disabled');
	}
}

function toggleTiposList(radio) {	
	toggleGenericList(radio, 'tipos');
}
function forceTiposList() {
	forceGenericList('tipos');
}

function toggleTagsList(radio) {	
	toggleGenericList(radio, 'tags');
}
function forceTagsList() {
	forceGenericList('tags');
}





















function changeCampaign(id) {
	if (id) {
		if (id == 'novo')
			window.location.href = '/monitoramentos/add/';
		else
			window.location.href = '/monitoramentos/def/' + id;
	}
}

function adjustCharCounter(id, max) {
	if ($(id).getWidth() <= 0) {
		var width = parseInt($(id).getStyle('width').sub('px', '')) + 6;
		$(id + '-counter').setStyle({'width': width + 'px'});
	}
	else 
		$(id + '-counter').setStyle({'width': $(id).getWidth() + 'px'});
	decreaseCharCounter(id, max);
}

function decreaseCharCounter(id, max) {
	var chars = $(id).getValue().length;
	
	if (chars > max) {
		$(id).value = $(id).getValue().truncate(max, '');
		$(id).scrollTop = 10000;
	}
	else 
		$(id + '-counter-value').innerHTML = max - chars;
}

/************************ STREAMS ******************************/
function monitList(id, over) {
	elementList('monit-actions-' + id, over);
	elementList('monit-actions-out-' + id, !over);
}

function showClassificacaoCompleteMsg(id) {	
	/*$('monit-actions-msg-' + id).show();
	__setTimeout('hideClassificacaoCompleteMsg(' + id + ')', 1500, 'classific' + id);
	*/
	hideLoader('Finalizando classificação');
}

function hideClassificacaoCompleteMsg(id) {	
	hideClassificacaoMsg(id);
	__clearTimeout('classific' + id);
}

function classificaComplete(request, id){
	var resp = request.responseText;
	
	showClassificacaoCompleteMsg(id);
}

function removerItemComplete(request, id) {
	var resp = request.responseText;
	
	if (resp == 'SEMPERMISSAO'){
		var texto = '<div style="text-align:center; color:red; font-weight:bolder; width:100%">' + StringsTraducao.SemPermissaoApagarItem + '</span>';
		new Insertion.Before('stream-li-'+id, texto);
	}
	else if (resp != 'OK') {
		var texto = '<div style="text-align:center; color:red; font-weight:bolder; width:100%">' + StringsTraducao.NaoPossivelRemover + '</span>';
		new Insertion.Before('stream-li-'+id, texto);
	}	
	else {
		Element.remove('stream-li-'+id);
	}

}

function getIdsParams () {
	var params = "";
	ids = $A($('streams').getElementsBySelector('[name="ids[]"]'));
	for (var index = 0, len = ids.length; index < len; ++index) {
		if (ids[index].value != "" && ids[index].checked ) { 
			params += 'ids[]=' + encodeURIComponent(ids[index].value);
	  		if (index < len - 1)
	  			params += '&';
  		}
  			
	}
	return params;
}

function checkUncheckAll(name, check) {
	ids = document.getElementsByName(name);
	for (var i = 0; i < ids.length; i++) {
  		if (ids[i].type == "checkbox" && ids[i].checked != check) {
  			ids[i].click();
  		}	  			
	}
}

function removerItens(select, value) {
	if (value == 'selecionados') {
		if (confirm(StringsTraducao.ConfirmacaoRemocao)) {
			new Ajax.Request('/itens/ajaxUnlink', {
				asynchronous: true,
				evalScripts: true,
				before: hideItens(),
				onComplete: function (request, json) {
					removerItensComplete(request, select);
				},
				parameters: getIdsParams()
			});
		}
		else {
			select.options[0].selected = true;
		}
	}
}

function hideItens() {
	itensToShow = 0;	
	ids = document.getElementsByName("ids[]");
	for (var index = 0, len = ids.length; index < len; ++index) {
  		if (ids[index].value != "" && ids[index].checked ) {
  			hideItem(ids[index].value, false);
  			itensToShow++;
  		}
  			
	}	
	
	setTimeout('showCachedItem(' + itensToShow + ');', 450);
}

function hideItem(id, showCached) {
	new Effect.Fade('stream-li-' + id, { duration:0.4});
	id.checked = false;
	if (showCached)
		setTimeout('showCachedItem(1)', 450);
}

function showCachedItem (num) {
	for (var i = 0 ; i < num ; i++) {
		if (cachedItens.size() == 0)
			break;
		Element.insert('streams', {bottom: cachedItens.first()});
		cachedItens.shift();
	}
}

function removerItensComplete(request, select) {
	var resp = request.responseText;	
	resp = eval(resp);

	select.options[0].selected = true;
}

function batchClassificarItens(select, value) {
	var classificacao = 3;
	if(value == 'positivo')
		classificacao = 3;
	else if(value == 'neutro')
		classificacao = 2;
	else if(value == 'negativo')
		classificacao = 1;
	else {
		select.options[0].selected = true;
		return false;
	}
	
	var ids = document.getElementsByName("ids[]");
	var itemId = 0;
	for(var index = 0, len = ids.length; index < len; ++index) {
  		if (ids[index].value != "" && ids[index].checked ) {
  			itemId = ids[index].value;
  			
			new Ajax.Updater('classificacao-item-' + itemId, '/itens/classifica/'+ classificacao + '/'+ itemId + '/1', {
				asynchronous:true, 
				evalScripts:true,
				before: beforeClassify(itemId, value, true),
				onComplete: function(itemIdClosure) {
								return (function(request, json) {
									classificaComplete(request, itemIdClosure);
									select.options[0].selected = true;
								});
				} (itemId),
				requestHeaders:['X-Update', 'classificacao-item-'+ itemId]
			});
  		}
	}
}

function batchTaguearItens(select, value) {
	var ids = document.getElementsByName("ids[]");
	
	var itemId = 0;
	var params = "";
	var tagNome = value;
	for(var index = 0, len = ids.length; index < len; ++index) {
  		if (ids[index].value != "" && ids[index].checked ) {
  			itemId = ids[index].value;
  			checkbox = $('chk-tag-' + itemId + '-' + tagNome.toLowerCase());
  			if (!checkbox.checked) {
  				checkbox.checked = true;
  				submitAddTag(itemId, tagNome, 0, checkbox);
  			}
		}
	}
	select.options[0].selected = true;
}

function switchBatchActions(select) {
	if (select.value) {
		var action = select.value.substr(0,3);
		var value = select.value.substr(4);
		
		if(action && value) {
			switch(action) {
				case 'cla':
					batchClassificarItens(select, value);
				break;
				case 'del':
					removerItens(select, value);
				break;
				case 'tag':
					batchTaguearItens(select, value);
				break;
			}
		}
	}
	else
		select.options[0].selected = true;
	
}


/************************ HIGHLIGHT ******************************/
/*
 * This is the function that actually highlights a text string by
 * adding HTML tags before and after all occurrences of the search
 * term. You can pass your own tags if you'd like, or if the
 * highlightStartTag or highlightEndTag parameters are omitted or
 * are empty strings then the default <font> tags will be used.
 */
function doHighlight(bodyText, searchTerm, highlightStartTag, highlightEndTag) 
{
  // the highlightStartTag and highlightEndTag parameters are optional
  if ((!highlightStartTag) || (!highlightEndTag)) {
    highlightStartTag = "<font style='color:blue; background-color:yellow;'>";
    highlightEndTag = "</font>";
  }
  
  // find all occurences of the search term in the given text,
  // and add some "highlight" tags to them (we're not using a
  // regular expression search, because we want to filter out
  // matches that occur within HTML tags and script blocks, so
  // we have to do a little extra validation)
  var newText = "";
  var i = -1;
  var lcSearchTerm = searchTerm.toLowerCase();
  var lcBodyText = bodyText.toLowerCase();
    
  while (bodyText.length > 0) {
    i = lcBodyText.indexOf(lcSearchTerm, i+1);
    if (i < 0) {
      newText += bodyText;
      bodyText = "";
    } else {
      // skip anything inside an HTML tag
      if (bodyText.lastIndexOf(">", i) >= bodyText.lastIndexOf("<", i)) {
        // skip anything inside a <script> block
        if (lcBodyText.lastIndexOf("/script>", i) >= lcBodyText.lastIndexOf("<script", i)) {
          newText += bodyText.substring(0, i) + highlightStartTag + bodyText.substr(i, searchTerm.length) + highlightEndTag;
          bodyText = bodyText.substr(i + searchTerm.length);
          lcBodyText = bodyText.toLowerCase();
          i = -1;
        }
      }
    }
  }
  
  return newText;
}

/**
	Executa uma busca no conteudo do div e grifa todos os termos do Array neste div
*/
function divHighlight(idDiv, searchText) {
	var highlightStartTag = '<span class="highlight">';
	var highlightEndTag = '</span>';
	divHighlightGeneral(idDiv,searchText,highlightStartTag,highlightEndTag);
}

function divHighlightSearch(idDiv, searchText) {
	var highlightStartTag = '<span class="highlight-green">';
	var highlightEndTag = '</span>';
	divHighlightGeneral(idDiv,searchText,highlightStartTag,highlightEndTag);
}


function divHighlightGeneral(idDiv, searchText, highlightStartTag, highlightEndTag) {	
	var div = $(idDiv);
	if(!div) return false;
	
	var bodyText = div.innerHTML;

	bodyText = linkify_plain(bodyText);

	searchTextArrayOr = searchText.split(" OR ");
	for(var j = 0; j < searchTextArrayOr.length; j++) {
		searchTextPart = searchTextArrayOr[j];
		searchTextPart = searchTextPart.replace(/^\s+|\s+$/g,"");
		searchTextPart = searchTextPart.replace(/&quot;/g,'"'); 

		var theLength = searchTextPart.length;
		var entreAspas = searchTextPart.charAt(0) == '"' && searchTextPart.charAt(theLength-1) == '"';
		entreAspas = entreAspas || searchTextPart.charAt(0) == "'" && searchTextPart.charAt(theLength-1) == "'"; 
		
		var searchArray;
		if (entreAspas) {
	    	searchArray = [searchTextPart.substr(1, theLength-2)];
	  	} else {
	    	searchArray = searchTextPart.split(" ");
	  	}	
		
		for (var i = 0; i < searchArray.length; i++) {
			if(searchArray[i] && searchArray[i] != "OR" && searchArray[i] != "or" && searchArray[i] != "AND" && searchArray[i] != "and")
	    		bodyText = (doHighlight(bodyText, searchArray[i], highlightStartTag, highlightEndTag));
		}
	}	
	
	div.update(bodyText);
	
	return true;
}

/************************ FIM DO HIGHLIGHT ******************************/

function linkify_plain(text) {
	if( !text ) return text;
	text = text.replace(/(href\s*=\s*['"]|src\s*=\s*['"]|)?((?:http:\/\/|ftp:\/\/|mailto:)[^.,<>"'\s\r\n\t]+(?:\.(?![.<>"'\s\r\n])[^.,!<>"'\s\r\n\t]+)+)/gi,function(url){
		nice = url;
		if( url.match('^href="?'))
			return url;
		
		if( url.match('^src="?'))
			return url;
					
		return '<a target="_blank" href="'+ url +'">'+ url +'</a>';
	});
	return text;
}
	
	
	

///////////////////////////////
// 		TAGS
///////////////////////////////

var arrayTags = null;

function submitAddRemoveTag(itemId, tagNome, tagId, checkbox) {
	if (checkbox.checked) {
		submitAddTag(itemId, tagNome, tagId);
	}
	else {
		submitDelTag(itemId, tagNome, tagId);
	}
	$('search-tag-' + itemId).focus();
}

function refreshSelectTags(tagNome, itemIdCriouTag) {
	var select, optionNova;
	var idsItens = document.getElementsByName("ids[]");
	
	//tag ja existente??
	if(idsItens.length) {
		itemId = idsItens[0].value;
		if($('tag-list-' + itemId)) {
			tags = $('tag-list-' + itemId).select('input[type=checkbox]');
			for(var i = 0, len = tags.length; i < len; ++i)
				if(tags[i].value == tagNome)
					return false; //tag ja existia
		}
	}
	
	//adiciona essa tag aos selects dos itens
	for(var index = 0, len = idsItens.length; index < len; ++index) {
		itemId = idsItens[index].value;
		if($('tag-list-inside-' + itemId)) {
			idChkTmp = 'tag-'+ itemId + '-' + new Date().getTime();
			marcarCheck = (itemId == itemIdCriouTag);
						
			checkboxTag = '<div class="checkbox"><input type="checkbox" onclick="submitAddRemoveTag('+ itemId+ ', \''+ tagNome + '\', 0, this)" id="'+ idChkTmp +'" value="'+ tagNome + '" '+ (marcarCheck ? ' checked="checked" ' : '') +' name="data['+ tagNome + ']"><label for="'+ idChkTmp +'">'+ tagNome + '</label></div>';
			new Element.insert('tag-list-inside-' + itemId, {'bottom': checkboxTag});
		}
	}
	
	//adiciona essa tag ao select do batch na ultima posicao
	if($('selectBatchActions-top')) {
		select = $('selectBatchActions-top');
		optionNova = document.createElement('option');
	    optionNova.text = tagNome;
	    optionNova.value = 'tag:' + tagNome;
		try {
	    	select.add(optionNova, null); // standards compliant; doesn't work in IE
	    }
	    catch(ex) {
	    	select.add(optionNova); // IE only
	    }
	}

	if($('selectBatchActions-bottom')) {
		select = $('selectBatchActions-bottom');
		optionNova = document.createElement('option');
	    optionNova.text = tagNome;
	    optionNova.value = 'tag:' + tagNome;
		try {
	    	select.add(optionNova, null); // standards compliant; doesn't work in IE
	    }
	    catch(ex) {
	    	select.add(optionNova); // IE only
	    }
	}
	
	//adiciona essa tag ao menu filtro
	checkboxTag = '<div class="checkbox"><input type="checkbox" disabled="disabled" value="'+ tagNome + '" id="tag-'+ tagNome + '" name="t[]" class="radio-tags-checkbox"><label for="tag-'+ tagNome + '" class="radio-tags-label disabled">'+ tagNome + '</label></div>';
	new Element.insert('radio-tags-list', {'bottom': checkboxTag});
	
	return true;
}

function submitAddTag(itemId, tagNome, tagId) {
	var params = "data[Item][id]=" + itemId;
	params += "&data[Tag][nome]=" + encodeURIComponent(tagNome);
	
	if ($('tags-current-resume-' + itemId).visible())
		showCurrentTags(itemId);

	tagElement = '<span id="tag-name-' + tagNome + '-' + itemId + '">' + tagNome + '<br /></span>';
	new Element.insert('tags-current-' + itemId, {'bottom': tagElement});
	
	new Ajax.Request('/tags/add/', {
		asynchronous:true,
		evalScripts:true,
		before: showLoader('Finalizando tagueamento'),
		onComplete: function (request, json) {
			submitAddTagComplete(request, itemId);
		},
		parameters:params
	});
}

function submitAddTagComplete(request, itemId) {
	if(!itemId)
		return false;
	
	hideLoader('Finalizando tagueamento');
	
	var obj = eval('(' + request.responseText + ')');
	
	var msg = '';
	
	if(obj.status == 'ok') {
		refreshSelectTags(obj.tag.nome, itemId);
	}
	/* INTERCON */
	else if(obj.status == 'semPermissao') {
		msg = '<span class="orange">' + StringsTraducao.SemPremissaoCriarTag + '</span>';
		$('tagMessage-'+itemId).update(msg);
		$('tagMessage-'+itemId).show();
		Effect.Fade('tagMessage-'+itemId, { duration: 3.0 });
	}
	/* INTERCON */	
	else if(obj.status == 'jaAdicionada') {
		msg = '<span class="orange">' + StringsTraducao.TagJaAdicionada + '</span>';
		$('tagMessage-'+itemId).update(msg);
		$('tagMessage-'+itemId).show();
		Effect.Fade('tagMessage-'+itemId, { duration: 3.0 });
	}
	else { //status = erro
		msg = '<span style="font-weight:bolder; color:red">' + ScriptsTraducao.ErroAdicionarTag + '</span>';
		$('tagMessage-'+itemId).update(msg);
		$('tagMessage-'+itemId).show();
		Effect.Fade('tagMessage-'+itemId, { duration: 3.0 });
	}

}


function submitDelTag(itemId, tagNome, tagId) {
	new Element.remove('tag-name-' + tagNome + '-' + itemId);

	new Ajax.Request('/tags/del/', 
					{asynchronous:true,
					evalScripts:true,
					onComplete: function (request, json) {delTagComplete(request, itemId, tagId); Element.hide('loadingTag-'+itemId);},
					onLoading: function (request) {Element.show('loadingTag-'+itemId);},
					parameters:'data[Item][id]='+itemId+'&data[Tag][id]='+tagId
					}
			);
}

function delTagComplete(request, itemId, tagId) {
	if(!itemId || !tagId)
		return false;

	var obj = eval('(' + request.responseText + ')');
	
	var msg = '';
	if(obj.status == 'ok') {
		/*
		new Element.remove('tag-' + itemId + '-'+ tagId);
		new Element.remove('tag-inline-' + itemId + '-'+ tagId);
		*/
	}
	else { //status = erro
		msg = '<span class="orange">' +  StringsTraducao.ErroRemoverTag + '</span>';
		$('tagMessage-'+itemId).update(msg);
		$('tagMessage-'+itemId).show();
		Effect.Fade('tagMessage-'+itemId, { duration: 3.0 });
	}
}

function isEnterKey(e) {
     var key;
     key = (window.event) ? window.event.keyCode : e.which; //IE or Firefox
     return (key == 13) ? true : false;
}
	
function agendaPost (item) {
	$('agenda-post-' + item).toggle();
	$('label-agenda-post-' + item).toggle();
	
	date = new Date();
	date.setTime(date.getTime()+1000*60*5);
	
	$('pubDate-' + item).value = ((date.getDate() < 10) ? '0' + date.getDate() : date.getDate()) + "/" + ((date.getMonth() + 1 < 10) ? '0' + (date.getMonth() + 1): date.getMonth() + 1) + "/" + date.getFullYear();
	$('pubHour-h-' + item).value = (date.getHours() < 10) ? '0' + (date.getHours()) : date.getHours();
	$('pubHour-m-' + item).value = (date.getMinutes() < 10) ? '0' + date.getMinutes() : date.getMinutes();
	
	return false;
}

function changeRpp(select) {
	redirect(select.value);
}


var arrayRulesValidation = new Array();
arrayRulesValidation[1] = {"FonteCampo1": {"rule": "isLengthGreaterThanAndSmallerThan", 
							  "param2": 2,
							  "param3": 140,
							  "msgError": StringsTraducao.ExpressaoBuscaDoisACentoQuarentacaracteres
							 }
				  };
arrayRulesValidation[2] = {"FonteCampo1": {"rule": "isLengthGreaterThan", 
										  "param2": 2,
							  			  "param3": '', 
										  "msgError": StringsTraducao.IDusuarioMinimoCaracteres
										 }
							  };
arrayRulesValidation[3] = {"FonteCampo1": {"rule": "isLengthGreaterThan", 
							  "param2": 2,
							  "param3": '', 
							  "msgError": StringsTraducao.IDusuarioMinimoCaracteres
							 }
				  };
arrayRulesValidation[4] = {"FonteCampo1": {"rule": "isLengthGreaterThan", 
							  "param2": 2,
							  "param3": '', 
							  "msgError": StringsTraducao.ExpressaoBuscaMinimoCaracteres
							 }
				  };				  
arrayRulesValidation[5] = {"FonteCampo1": {"rule": "isLengthGreaterThan", 
							  "param2": 2,
							  "param3": '', 
							  "msgError": StringsTraducao.IDusuarioMinimoCaracteres
							 }
				  };
arrayRulesValidation[6] = {"FonteCampo1": {"rule": "isUrl",
							  "param2": '',
							  "param3": '',				
							  "msgError": StringsTraducao.URLInvalida
							 }
				  };
arrayRulesValidation[7] = {"FonteCampo1": {"rule": "isUrl",
							  "param2": '',
							  "param3": '',
							  "msgError": StringsTraducao.URLInvalida
							 }
				  };
arrayRulesValidation[8] = {"FonteCampo1": {"rule": "isNumeric",
							  "param2": '',
							  "param3": '',
							  "msgError": StringsTraducao.IDdaComunidadeInvalida
							 }
				  };
arrayRulesValidation[9] = {"FonteCampo1": {"rule": "isLengthGreaterThan", 
							  "param2": 2,
							  "param3": '', 
							  "msgError": StringsTraducao.ExpressaoBuscaMinimoCaracteres
							 }
				  };	
arrayRulesValidation[10] = {"FonteCampo1": {"rule": "isAlphaNumeric",
							  "param2": '',
							  "param3": '',
							  "msgError": StringsTraducao.IDdoVideoInvalido
							 }
				  };
arrayRulesValidation[11] = {"FonteCampo1": {"rule": "isLengthGreaterThan", 
							  "param2": 2,
							  "param3": '', 
							  "msgError": StringsTraducao.ExpressaoBuscaMinimoCaracteres
							 }
				  };
arrayRulesValidation[12] = {"FonteCampo1": {"rule": "isUrl",
							  "param2": '',
							  "param3": '',
							  "msgError": StringsTraducao.URLInvalida
							 }
				  };
arrayRulesValidation[13] = {"FonteCampo1": {"rule": "isLengthGreaterThan", 
							  "param2": 2,
							  "param3": '', 
							  "msgError": StringsTraducao.ExpressaoBuscaMinimoCaracteres
							 }
				  };
arrayRulesValidation[14] = {"FonteCampo1": {"rule": "isLengthGreaterThan", 
							  "param2": 2,
							  "param3": '', 
							  "msgError": StringsTraducao.ExpressaoBuscaMinimoCaracteres
							 }
				  };
arrayRulesValidation[15] = {"FonteCampo1": {"rule": "isLengthGreaterThan", 
							  "param2": 2,
							  "param3": '', 
							  "msgError": StringsTraducao.ExpressaoBuscaMinimoCaracteres
							 }
				  };	
arrayRulesValidation[16] = {"FonteCampo1": {"rule": "isLengthGreaterThan", 
							  "param2": 2,
							  "param3": '',
							  "msgError": StringsTraducao.ExpressaoBuscaMinimoCaracteres
							 }
				  };
arrayRulesValidation[17] = {"selectTwitterCampo1id": {"rule": "isLengthGreaterThan", 
							  "param2": 2,
							  "param3": '', 
							  "msgError": StringsTraducao.SelecioneUsuario
							 }
				  };
arrayRulesValidation[18] = {"selectTwitterCampo1id": {"rule": "isLengthGreaterThan", 
							  "param2": 2,
							  "param3": '', 
							  "msgError":  StringsTraducao.SelecioneUsuario
							 }
				  };
arrayRulesValidation[19] = {"FonteCampo1": {"rule": "isUrl",
							  "param2": '',
							  "param3": '',
							  "msgError": StringsTraducao.URLInvalida
							 }
				  };
arrayRulesValidation[20] = {"FonteCampo1": {"rule": "isLengthGreaterThan", 
							  "param2": 2,
							  "param3": '',
							  "msgError": StringsTraducao.ExpressaoBuscaMinimoCaracteres
							 }
				  };

var rulesValidation = arrayRulesValidation[1]; //variavel GLOBAL utilizada pelo onsubmit do formulario

function fonteChange() {
	var n = $('tipoFonte').value;
	$('campo1').style['display'] = 'none';
	$('campo2').style['display'] = 'none';
	$('campo2texto').style['display'] = 'none';
	
	$('campo1value').style['display'] = 'none';
	$('campo1ContasTwittervalue').style['display'] = 'none';
	$('campo2textovalue').style['display'] = 'none';
	
	rulesValidation = {};
	$("FonteCampo1MsgError").style['display'] = 'none';
	$("FonteCampo2MsgError").style['display'] = 'none';
	$("FonteCampo2textoMsgError").style['display'] = 'none';
	
	$('FonteCampo1').name = 'data[Fonte][campo1]';
	$('selectTwitterCampo1id').name = 'campo1Twitter';
	$('FonteCampo2').options.length = 0;
			
	switch (n) {
		case "1":
			$('form-service-icon').className = 'service-icon twitter';
			$('campo1name').update(StringsTraducao.ExpressaoBusca);
			$('campo2name').update(StringsTraducao.Lingua);
			$('campo1').style['display'] = 'block';
			$('campo1value').style['display'] = 'block';
			$('campo2').style['display'] = 'block';
			
			$('FonteCampo2').options[$('FonteCampo2').options.length] = new Option(StringsTraducao.Portugues, 'pt', false, true);
			$('FonteCampo2').options[$('FonteCampo2').options.length] = new Option(StringsTraducao.Ingles, 'en', false, false);
			$('FonteCampo2').options[$('FonteCampo2').options.length] = new Option(StringsTraducao.Espanhol, 'es', false, false);
			$('FonteCampo2').options[$('FonteCampo2').options.length] = new Option(StringsTraducao.Todas, 'all', false, false);
			
			rulesValidation = arrayRulesValidation[1];
			$('dicaBusca').update(StringsTraducao.DicaTwitter); 
			break;
		case "2":		
			$('form-service-icon').className = 'service-icon twitter';
			$('campo1name').update(StringsTraducao.ExpressaoBusca);
			$('campo2name').update('');
			$('campo1').style['display'] = 'block';
			$('campo1value').style['display'] = 'block';
			rulesValidation = arrayRulesValidation[2];

			$('dicaBusca').update(''); 
			break;
		case "3":
			$('form-service-icon').className = 'service-icon slideshare';
			$('campo1name').update(StringsTraducao.IDusuario);
			$('campo2name').update('');
			$('campo1').style['display'] = 'block';
			$('campo1value').style['display'] = 'block';
			rulesValidation = arrayRulesValidation[3];

			$('dicaBusca').update(''); 
			break;
		case "4":
			$('form-service-icon').className = 'service-icon youtube';
			$('campo1name').update(StringsTraducao.ExpressaoBusca);
			$('campo2name').update('');
			$('campo1').style['display'] = 'block';
			$('campo1value').style['display'] = 'block';

			$('campo2name').update('Língua:');
			$('campo2').style['display'] = 'block';
			$('FonteCampo2').options[$('FonteCampo2').options.length] = new Option(StringsTraducao.Portugues, 'pt', false, true);
			$('FonteCampo2').options[$('FonteCampo2').options.length] = new Option(StringsTraducao.Ingles, 'en', false, false);
			$('FonteCampo2').options[$('FonteCampo2').options.length] = new Option(StringsTraducao.Espanhol, 'es', false, false);
			$('FonteCampo2').options[$('FonteCampo2').options.length] = new Option(StringsTraducao.Todas, 'all', false, false);
			
			rulesValidation = arrayRulesValidation[4];
			$('dicaBusca').update(StringsTraducao.DicaYoutube); 
			break;
		case "5":
			$('form-service-icon').className = 'service-icon youtube';
			$('campo1name').update(StringsTraducao.IDusuario);
			$('campo2name').update('');
			$('campo1').style['display'] = 'block';
			$('campo1value').style['display'] = 'block';
			rulesValidation = arrayRulesValidation[5];

			break;
		case "6":
			$('form-service-icon').className = 'service-icon wordpress';
			$('campo1name').update(StringsTraducao.URL);
			$('campo2name').innerHTML = '';
			$('campo1').style['display'] = 'block';
			$('campo1value').style['display'] = 'block';
			rulesValidation = arrayRulesValidation[6];

			$('dicaBusca').update(''); 
			break;
		case "7":
			$('form-service-icon').className = 'service-icon rss';
			$('campo1name').update(StringsTraducao.URL);
			$('campo2textoname').update(StringsTraducao.NomeRSS);
			$('campo1').style['display'] = 'block';
			$('campo2texto').style['display'] = 'block';
			$('campo1value').style['display'] = 'block';
			$('campo2textovalue').style['display'] = 'block';
			
			rulesValidation = arrayRulesValidation[7];
			
			$('dicaBusca').update(''); 
			break;
		case "8":
			$('form-service-icon').className = 'service-icon orkut';
			$('campo1name').update(StringsTraducao.IDComunidade);
			$('campo2textoname').update(StringsTraducao.NomeComunidade);
			$('campo1').style['display'] = 'block';
			$('campo2texto').style['display'] = 'block';
			$('campo1value').style['display'] = 'block';
			$('campo2textovalue').style['display'] = 'block';
			rulesValidation = arrayRulesValidation[8];

			$('dicaBusca').update(''); 
			break;
		case "9":
			$('form-service-icon').className = 'service-icon technorati';
			$('campo1name').update(StringsTraducao.ExpressaoBusca);
			$('campo2name').update('');
			$('campo1').style['display'] = 'block';
			$('campo1value').style['display'] = 'block';
			rulesValidation = arrayRulesValidation[9];
		
			$('dicaBusca').update('<b>Dica:</b> Você pode utilizar algumas técnicas para melhorar suas buscas. Use "-" antes de palavras que deseja excluir dessa busca. Exemplo: "house -lan", procura por "house" mas ignora se encontrar a palavra "lan" junto. Use aspas para procurar expressões to tipo: "quero comprar". <a href="http://blog.scup.com.br/entenda-a-logica-de-busca-nas-principais-midias-sociais" target="_blank">Veja mais detalhes aqui</a>'); 
			break;
		case "10":
			$('form-service-icon').className = 'service-icon youtube';
			$('campo1name').update(StringsTraducao.IDVideo);
			$('campo2name').udpate('');
			$('campo1').style['display'] = 'block';
			$('campo1value').style['display'] = 'block';
			rulesValidation = arrayRulesValidation[10];

			$('dicaBusca').update(''); 
			break;	
		case "11":
			$('campo1name').update(StringsTraducao.ExpressaoBusca);
			$('campo2name').update('');
			$('campo1').style['display'] = 'block';
			$('campo1value').style['display'] = 'block';
			rulesValidation = arrayRulesValidation[11];
			
			$('dicaBusca').update(''); 
			break;
		case "12":
			$('form-service-icon').className = 'service-icon google';
			$('campo1name').update(StringsTraducao.URLFeed);
			$('campo2name').update('');
			$('campo1').style['display'] = 'block';
			$('campo1value').style['display'] = 'block';
			rulesValidation = arrayRulesValidation[12];

			$('dicaBusca').update(''); 
			break;
		case "13":
			$('form-service-icon').className = 'service-icon flickr';
			$('campo1name').update(StringsTraducao.ExpressaoBusca);
			$('campo2name').update('');
			$('campo1').style['display'] = 'block';
			$('campo1value').style['display'] = 'block';
			rulesValidation = arrayRulesValidation[13];
			
			$('dicaBusca').update(''); 
			break;			
		case "14":
			$('form-service-icon').className = 'service-icon yahoo';
			$('campo1name').update(StringsTraducao.ExpressaoBusca);
			$('campo2name').update('');
			$('campo1').style['display'] = 'block';
			$('campo1value').style['display'] = 'block';
			rulesValidation = arrayRulesValidation[14];

			$('dicaBusca').update(''); 
						
			break;			
		case "15":
			$('form-service-icon').className = 'service-icon google';
			$('campo1name').update(StringsTraducao.ExpressaoBusca);
			$('campo2name').update('');
			$('campo1').style['display'] = 'block';
			$('campo1value').style['display'] = 'block';
			rulesValidation = arrayRulesValidation[15];
	
			$('dicaBusca').update(StringsTraducao.DicaBlogs); 
			break;
		case "16":
			$('form-service-icon').className = 'service-icon backtype';
			$('campo1name').update(StringsTraducao.ExpressaoBusca);
			$('campo2name').update('');
			$('campo1').style['display'] = 'block';
			$('campo1value').style['display'] = 'block';
			rulesValidation = arrayRulesValidation[16];

			$('dicaBusca').update(''); 			
			break;
		case "17":
			$('form-service-icon').className = 'service-icon twitter';
			$('FonteCampo1').name = 'campo1Input';
			$('selectTwitterCampo1id').name = 'data[Fonte][campo1]';
			
			$('campo1name').update(StringsTraducao.Usuario);
			$('campo2name').update('');
			$('campo1').style['display'] = 'block';
			$('campo1ContasTwittervalue').style['display'] = 'block';
			rulesValidation = arrayRulesValidation[17];

			$('dicaBusca').update(StringsTraducao.DicaTwitterUsuario); 			
			break;
		case "18":
			$('form-service-icon').className = 'service-icon google';
			$('campo1name').update(StringsTraducao.ExpressaoBusca);
			$('campo2name').update(StringsTraducao.Lingua);
			$('campo1').style['display'] = 'block';
			$('campo1value').style['display'] = 'block';
			$('campo2').style['display'] = 'block';

			$('FonteCampo2').options[$('FonteCampo2').options.length] = new Option(StringsTraducao.Portugues, 'pt', false, true);
			$('FonteCampo2').options[$('FonteCampo2').options.length] = new Option(StringsTraducao.Ingles, 'en', false, false);
			$('FonteCampo2').options[$('FonteCampo2').options.length] = new Option(StringsTraducao.Espanhol, 'es', false, false);
			$('FonteCampo2').options[$('FonteCampo2').options.length] = new Option(StringsTraducao.Todas, 'all', false, false);
			
			rulesValidation = arrayRulesValidation[9];
		
			$('dicaBusca').update(StringsTraducao.DicaBlogs); 
			break;
		case "19":
			$('form-service-icon').className = 'service-icon reclameaqui';
			$('campo1name').update(StringsTraducao.URLReclameAqui);
			$('campo2name').update('');
			$('campo1').style['display'] = 'block';
			$('campo1value').style['display'] = 'block';
			rulesValidation = arrayRulesValidation[19];
		
			$('dicaBusca').update(StringsTraducao.DicaReclameAqui); 
			break;
		case "20":
			$('form-service-icon').className = 'service-icon facebook';
			$('campo1name').update(StringsTraducao.ExpressaoBusca);
			$('campo1').style['display'] = 'block';
			$('campo1value').style['display'] = 'block';

			rulesValidation = arrayRulesValidation[20];
		
			$('dicaBusca').update(StringsTraducao.DicaFacebook); 
			break;
	}

}


