var objhttp;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
	objhttp = new XMLHttpRequest();
    if (objhttp.overrideMimeType) 
    	objhttp.overrideMimeType('text/xml');
} 
else if (window.ActiveXObject) 
{ // IE
	try {
    	objhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } 
	catch (e) 
	{
	    try {
    	    objhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } 
		catch (e) {}
    }
 }	

var quanResults = 10;//quantity of suggestions to bring
var tagSug = "";//tag suggestions
var divPlace = -1;//place in suggestion div
var quanSug = 0;//quantity of suggestions
var searchTagLen = 0;//length of the search tag
var isLimited = false;
var lastSearchTags = new Array();//array of last search tags
var lastSearchTagsQuan = 9;//quantity of search tags tabs
var quanResultsInPage = 11;//quantity of results
var currentPressedTab = 0;//current pressed tab
var isEmptyResult = false;
var lastSearchTag = "";
var quanResultsToTag = 0;// quan results to current tag
var isAlphabSortMostPopularTags = true;
var quanMostPopularTags = 49;
var quanAllMostPopularTags = 10000;
var currentPage = 1;
var spaceForTabs = 738;
//hashtable for url tag hebrew encoding
//added by Igal 28/02/07
var hebrewChars = new Hashtable();
hebrewChars.put("א","E0");
hebrewChars.put("ב","E1");
hebrewChars.put("ג","E2");
hebrewChars.put("ד","E3");
hebrewChars.put("ה","E4");
hebrewChars.put("ו","E5");
hebrewChars.put("ז","E6");
hebrewChars.put("ח","E7");
hebrewChars.put("ט","E8");
hebrewChars.put("י","E9");
hebrewChars.put("ך","EA");
hebrewChars.put("כ","EB");
hebrewChars.put("ל","EC");
hebrewChars.put("ם","ED");
hebrewChars.put("מ","EE");
hebrewChars.put("ן","EF");
hebrewChars.put("נ","F0");
hebrewChars.put("ס","F1");
hebrewChars.put("ע","F2");
hebrewChars.put("ף","F3");
hebrewChars.put("פ","F4");
hebrewChars.put("ץ","F5");
hebrewChars.put("צ","F6");
hebrewChars.put("ק","F7");
hebrewChars.put("ר","F8");
hebrewChars.put("ש","F9");
hebrewChars.put("ת","FA");
// end of hebrew encoding

var sectionsNames = new Hashtable();
sectionsNames.put("market","שוק ההון");
sectionsNames.put("technology","היי-טק");
sectionsNames.put("realEstate","נדל\"ן");
sectionsNames.put("investorGuide","המדריך למשקיע");
sectionsNames.put("consumer","צרכנות");
sectionsNames.put("car","רכב");
sectionsNames.put("cars","רכב");
sectionsNames.put("General","כללי");
sectionsNames.put("hightech","היי-טק");
sectionsNames.put("advertise","פרסום ומדיה");
sectionsNames.put("world","בעולם");
sectionsNames.put("career","קריירה");
sectionsNames.put("law","משפט");
sectionsNames.put("walls","וול סטריט");
sectionsNames.put("blog","בלוג");
sectionsNames.put("startup","היי טק");
sectionsNames.put("communication","היי טק");
sectionsNames.put("internet","היי טק");
sectionsNames.put("foreign","מט\"ח");
sectionsNames.put("maof","מעו\"ף");
sectionsNames.put("nyStocks","וול סטריט");
sectionsNames.put("media","פרסום ומדיה");
sectionsNames.put("misc","קריירה");
sectionsNames.put("saving","תיירות");
sectionsNames.put("credit","אשראי");
sectionsNames.put("mortgage","משכנתא");
sectionsNames.put("loan","תקשורת");
sectionsNames.put("insurance","ביטוח");
sectionsNames.put("pension","פנסיה");
sectionsNames.put("banking","בנקאות");
sectionsNames.put("myMoney","כסף שלי");
sectionsNames.put("tax","מיסים");
sectionsNames.put("consultant","זירת היועצים");

var sectionsUrl = new Hashtable();
sectionsUrl.put("media","/tmc/marketing.jhtml?layer=media");
sectionsUrl.put("car","/tmc/car.jhtml?layer=car");
sectionsUrl.put("cars","/tmc/car.jhtml?layer=car");
sectionsUrl.put("consumer","/tmc/consumer.jhtml?layer=consumer");
sectionsUrl.put("realEstate","/tmc/realEstate.jhtml?layer=realEstate");
sectionsUrl.put("law","/tmc/law.jhtml?layer=law");
sectionsUrl.put("market","/tmc/market.jhtml?layer=market");
sectionsUrl.put("career","/tmc/career.jhtml?layer=career");
sectionsUrl.put("walls","/tmc/wallStreet.jhtml?layer=walls");
sectionsUrl.put("hightech","/tmc/hightech.jhtml?layer=hightech");
sectionsUrl.put("world","/tmc/world.jhtml?layer=world");
sectionsUrl.put("investorGuide","/tmc/investorGuide.jhtml?layer=investorGuide");
sectionsUrl.put("technology","/tmc/hightech.jhtml?layer=hightech");
sectionsUrl.put("startup","/tmc/hightech.jhtml?layer=hightech");
sectionsUrl.put("communication","/tmc/hightech.jhtml?layer=hightech");
sectionsUrl.put("internet","/tmc/hightech.jhtml?layer=hightech");
sectionsUrl.put("foreign","/ibo/forex/index.html");
sectionsUrl.put("maof","/ibo/market/opt.html");
sectionsUrl.put("nyStocks","/tmc/wallStreet.jhtml?layer=walls");
sectionsUrl.put("General","/?layer=hp");
sectionsUrl.put("advertise","/tmc/marketing.jhtml?layer=media");
sectionsUrl.put("blog","/tmc/bloggers.jhtml");
sectionsUrl.put("misc","/tmc/career.jhtml?layer=career");
sectionsUrl.put("saving","/ibo/money/myMoneyIndexNew.jhtml?sectionName=saving");
sectionsUrl.put("credit","/ibo/money/myMoneyIndexNew.jhtml?sectionName=credit");
sectionsUrl.put("mortgage","/ibo/money/myMoneyIndexNew.jhtml?sectionName=mortgage");
sectionsUrl.put("loan","/ibo/money/myMoneyIndexNew.jhtml?sectionName=loan");
sectionsUrl.put("insurance","/ibo/money/myMoneyIndexNew.jhtml?sectionName=insurance");
sectionsUrl.put("pension","/ibo/money/myMoneyIndexNew.jhtml?sectionName=pension");
sectionsUrl.put("banking","/ibo/money/myMoneyIndexNew.jhtml?sectionName=banking");
sectionsUrl.put("myMoney","/ibo/money/myMoneyIndexNew.jhtml?sectionName=myMoney");
sectionsUrl.put("tax","/ibo/money/myMoneyIndexNew.jhtml?sectionName=tax");
sectionsUrl.put("consultant","/tmc/consultant.jhtml?layer=consultant");
	
function notShowTagsDefinition()
{
	var objTagDefinition = document.getElementById("tagDefinition");
	if (objTagDefinition)
		objTagDefinition.style.display = 'none';	
}					
function showTagsDefinition()
{
	var objTagDefinition = document.getElementById("tagDefinition");
	if (objTagDefinition){		
		if ((objTagDefinition.style.display == 'none') || (objTagDefinition.style.display == "")){
			var pL = 0;
			var pT = 0;	
			var objImg = document.getElementById("tagDefinitionImg");
	
			while(objImg.tagName != "BODY"){
				pL+=objImg.offsetLeft;
				pT+=objImg.offsetTop;
				objImg=objImg.offsetParent;			
			}		
			objTagDefinition.style.top = pT+30+"px"; 				
			objTagDefinition.style.left = pL+60+"px";				
			objTagDefinition.style.display = 'block';			
		}		
	}	
}	

function Set_Cookie( name, value, expires, path, domain, secure ) 
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	/*
	if the expires variable is set, make the correct 
	expires time, the current script below will set 
	it for x number of days, to make it for hours, 
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )	
		expires = expires * 1000 * 60 * 60 * 24;	
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" + value +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
	( ( path ) ? ";path=" + path : "" ) + 
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}
	
// this function gets the cookie, if it exists
function Get_Cookie( name ) 
{
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) )	
		return null;
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return document.cookie.substring( len, end );
}

/*show the last visited tags*/
function updateLastVisitedTags()
{
	var objLastTags = document.getElementById("lastVisitedTags");
	var lastVisStr="";
	var lastVisTags =  Get_Cookie("LAST_VISITED_TAGS");
	
	if (lastVisTags == null){//no such cookie		
		if (objLastTags) objLastTags.style.display = 'none';
		return;
	}		
	lastVisTags = unescape(lastVisTags);
	var lastVisTagsArr = lastVisTags.split('@@');				
	var lenArr = lastVisTagsArr.length;
	
	lastVisStr = lastVisStr.concat('<img src="/tmc/i/tags/chetz.gif" border="0"> <a class="lastVisitedTagsTitle">תגיות אחרונות שביקרת בהן:</a><br>');		
	lastVisStr	= lastVisStr.concat('<ul id="tagsMenu">');
	lastVisStr = lastVisStr.concat('<li><span class="lastVisitedTagsBraces">[&nbsp;</span></li>');
	for (var i = lenArr-1; i >= 0; i--){
		lastVisStr	= lastVisStr.concat('<li class="subItem">');
		if (i != (lenArr - 1)){
			lastVisStr	= lastVisStr.concat('<span>,<img src="/ibo/images/0.gif" width="7" height="1"></span>');
		}
		lastVisStr	= lastVisStr.concat('<a href="#" class="lastVisitedTagsTxt" onclick="onClickTag(\''+replaceCharsTo(lastVisTagsArr[i])+'\');">'+replaceSpace(lastVisTagsArr[i])+'</a>');
		lastVisStr  = lastVisStr.concat('<ul id="pAlertItem' + i + '" class="alertsMenu">');
		lastVisStr	= lastVisStr.concat(TM.TagsMenu.getPAlertsMenu( replaceCharsTo(lastVisTagsArr[i]), 'pAlertItem' + i, true));
		lastVisStr	= lastVisStr.concat('</ul>');
		lastVisStr	= lastVisStr.concat('</li>');
	}
	
	lastVisStr	= lastVisStr.concat('<li><span class="lastVisitedTagsBraces">&nbsp;]</span></li>');
	lastVisStr	= lastVisStr.concat('</ul>');
	
	if (objLastTags){
		objLastTags.innerHTML = lastVisStr;	
		objLastTags.style.display = 'block';
	}
	// Add the mouse events to the menu
	TM.TagsMenu.buildTags();
}
function removeLastVisitedTag(tag){
	var lastVisTags =  unescape(Get_Cookie("LAST_VISITED_TAGS"));
	var pattern = "@*" + unescape(tag);
	newLastVisTags = lastVisTags.replace(new RegExp(pattern),"");
	newLastVisTags = newLastVisTags.replace(/^@@/,"");
	Set_Cookie('LAST_VISITED_TAGS', escape(newLastVisTags), 365, '/', '.themarker.com', '' );//add cookie of tags
	updateLastVisitedTags();
}

function replaceCharsBack(str)
{	
	while(str.indexOf("~")!=-1)
		str =str.replace("~","\"");
	while(str.indexOf("*")!=-1) 
		str =str.replace("*","\'");	
	while(str.indexOf("^")!=-1) 
		str =str.replace("^","&");
	return str;
}

function replaceSpace(str)
{
	while(str.indexOf(" ")!=-1)
		str =str.replace(" ","&nbsp;");
	return str;
}

function replaceAndChar(str)
{
	while(str.indexOf("&amp;")!=-1)
		str =str.replace("&amp;","&");
	return str;
}

//init max length og searched tag
function initTagStaff(tagParam)
{	
	document.getElementById("tagName").maxChars = 30;	
	updateLastVisitedTags();	

	var tagObj = document.getElementById("tagName");
	
	if (tagObj && tagObj.value != "")	
		onClickTag(escape(tagObj.value));			
	else if (tagParam != null)		
		onClickTag(escape(replaceCharsBack(tagParam)));			
	
}

/*show most popular tags according the sort type - 1 means alphabetical sort, 2 - popularity order, 3 -show all tags*/
function sortMostPopular(type, isDisplayAll)
{	
	try{		
		var parameters = "quan="+quanMostPopularTags+"&&func=";
		
		if (type == 1){//alphabetical 
			parameters = parameters.concat("byCountDescByTagAscFunc");
			document.getElementById("sortAlph").className='popularTagsTitle';
			document.getElementById("sortPop").className='popularTagsTitleNotActive';			
		}
		else{
			parameters = parameters.concat("byCountDesc");			
			document.getElementById("sortAlph").className='popularTagsTitleNotActive';
			document.getElementById("sortPop").className='popularTagsTitle';			
		}
		sortMostPopularPost(parameters);								
	}
	catch(e){}
}

function sortMostPopularPost(parameters)
{
	objhttp.open ("POST", "/web2/tags/getMostPopularTags.jhtml", true);
	objhttp.onreadystatechange=getMostPopularTags;				
	objhttp.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded;");				
	objhttp.send(parameters);	
}

/*get most popular tags*/
function getMostPopularTags()
{	
	if ((objhttp.readyState==4) && (objhttp.status == 200))
	{			
		var respText = objhttp.responseText;//get response text	
		if(respText != "")//if there is response text
		{			
			respText=trimString(respText);
			var ar=respText.split("@@@");			
			var len=ar.length;

			divPlace = -1;
			if (len > 1){//there are suggestions	
				mostPopTags = '</td></tr></table>';						
				for (var i = len-1; i > 0; i--)
				{								
					if (trimString(ar[i]) == "")
						continue;										
					tmp=ar[i].split("@@");	
					mostPopTags = '<a class="popularTagsTxt" onmouseover="this.className=\'popularTagsTxtOver\';" onmouseout="this.className=\'popularTagsTxt\';" style="font-size:'+tmp[1]+'px; cursor:pointer;" dir="rtl" onclick="onClickTag(\''+escape(tmp[0])+'\');">'+tmp[0]+'</a><img src="/ibo/images/0.gif" width="6" height="1">'.concat(mostPopTags);								
				}	
				mostPopTags = '<table cellpadding="0" cellspacing="0" width="100%" border="0" bordercolor="pink" align="center" dir="rtl" class="popularTags"><tr><td class="popularTags popularTagsTxt" dir="rtl">'.concat(mostPopTags);																			
				document.getElementById("mostPopularTags").innerHTML = mostPopTags;
			}		
		}				
	}
}

/*treat key event for input tag field*/
function treatKey(evt, isFeature)
{	
	if (evt)//if there is event
	{			
		var sugDiv = document.getElementById("tagSuggestions");//tag suggestion div	
		//suggestion div not displayed or enter pressed while in the search tag field
		if (sugDiv && ((sugDiv.style.display == 'none') || ((divPlace == -1) && (evt.keyCode == 13))))
			checkSubmitSearch(evt.keyCode,isFeature);			
		else//suggestion div is displayed
			moveFocusInSuggestionDiv(evt.keyCode);					
	}
}


/*check whether the desired tag has already been searched*/
/*returns the place of the tag in the array or -1 if not exist*/
function checkIfTagInHistory(desiredTag)
{
	for(var cnt = 0; cnt < lastSearchTags.length; cnt++)			
		if (lastSearchTags[cnt] == desiredTag)
			return cnt;
	return -1;
}

/*assignment of the tag search field, return true/false depending on success*/
function assigTagSearchField(val)
{
	var tagObj = document.getElementById("tagName");
	if (tagObj){
		tagObj.value = val;
		tagObj.focus();
		return true;
	}
	return false;
}

/*turn on the desired tub*/
function turnOnTagTab(curr)
{
	if (assigTagSearchField(lastSearchTags[curr]) == false)
		return;	
	//turn on the new tab
	document.getElementById("rightTagTab"+curr).className = 'rightTagTabOn';
	document.getElementById("closeTagTab"+curr).className = 'closeTagTabOn';
	document.getElementById("rightSpaceTagTab"+curr).className = 'backTagTabOn10';	
	document.getElementById("backTagTab"+curr).className = 'backTagTabOn tagTabTxt';
	document.getElementById("backTagTab"+curr).onclick = 'void(0);';
	document.getElementById("leftTagTab"+curr).className = 'leftTagTabOn';	
}

/*show pages list under the results*/
function showPagesList()
{
	var NUM_PAGES_DISPLAY = 20; //number pages to display on the fooer
	var lastPage;
	var pagesList = "";
	var quanPages = Math.floor(quanResultsToTag / 11);

	var remain = quanResultsToTag % 11;
	var startPage = Math.floor( (currentPage / NUM_PAGES_DISPLAY - 0.01));

	startPage = startPage * NUM_PAGES_DISPLAY;
	if (remain != 0)
		quanPages++;	

	if (quanPages > 1){//only one page	
		lastPage = startPage + NUM_PAGES_DISPLAY;
		if(lastPage > quanPages){
			lastPage = quanPages;
		}
		for (var cnt = startPage+1; cnt <= lastPage; cnt++){
			if (cnt == currentPage)	{
				pagesList = pagesList+'<a class="tagsPagesNumTxtBlue">'+cnt+'</a>&nbsp;';	
			}
			else {
				pagesList = pagesList+'<a class="tagsPagesTxtGrey" onclick="getSearchResults(\''+escape(lastSearchTag)+'\',\''+cnt+'\');" style="cursor:pointer;">'+cnt+'</a>&nbsp;';			
			}
		}
		pagesList = '<span dir=ltr>'+pagesList+'</span>';

		if (currentPage == 1)
			pagesList = pagesList+'&nbsp;&nbsp;&nbsp;<a class="tagsPagesNotActive">לכתבות הקודמות&nbsp;>></a>';
		else
			pagesList = pagesList+'&nbsp;&nbsp;&nbsp;<a class="tagsPagesTxtBlue" onclick="getSearchResults(\''+escape(lastSearchTag)+'\',\''+(currentPage - 1)+'\');" style="cursor:pointer;">לכתבות הקודמות&nbsp;>></a>';

		if (currentPage == quanPages)			
			pagesList = '<a class="tagsPagesNotActive"><<&nbsp;לכתבות הבאות</a>&nbsp;&nbsp;&nbsp;'+pagesList;
		else
			pagesList = '<a class="tagsPagesTxtBlue" onclick="getSearchResults(\''+escape(lastSearchTag)+'\',\''+(currentPage*1 + 1)+'\');" style="cursor:pointer;"><<&nbsp;לכתבות הבאות</a>&nbsp;&nbsp;&nbsp;'+pagesList;
		
		document.getElementById("tagsPages").innerHTML = pagesList;	
		document.getElementById("tagsPages").style.display = 'block';
	}
	else
		document.getElementById("tagsPages").style.display = 'none';
}
/*construct a cookie of last tags*/
function lastTagsConstructor(newTag)
{
	var retVal;
	var lastVisTags =  Get_Cookie("LAST_VISITED_TAGS");

	if (lastVisTags != null){//there are tags in cookie
		lastVisTags = unescape(lastVisTags);
		var placeNewTagInAllTags = lastVisTags.indexOf(newTag);
		if (placeNewTagInAllTags != -1){//this tag is already in the cookie
			
			if (lastVisTags.length == newTag.length)//this is the only tag in the cookie
				return;
				
			if (placeNewTagInAllTags == (lastVisTags.length - newTag.length))//in the end
				return;//ok
				
			if (placeNewTagInAllTags == 0)//the first one
				lastVisTags = lastVisTags.substring(newTag.length+2,lastVisTags.length);											
			else{//in the middle
				var tempStr = lastVisTags.substring(0,placeNewTagInAllTags-1);//before the tag
				lastVisTags = tempStr + lastVisTags.substring(placeNewTagInAllTags+newTag.length+1,lastVisTags.length);
			}

			lastVisTags = lastVisTags.concat('@@'+newTag);//add the new tag in the end of the list		
		}
		else{//no such tag in cookie
			lastVisTags = lastVisTags.concat('@@'+newTag);//add the new tag
			var quanCommas = calculateQuanCommas(lastVisTags);

			while (quanCommas > 9){//if there are 11 tags - delete the first one	
				var firstApp = lastVisTags.indexOf('@@');
				lastVisTags = lastVisTags.substring(firstApp+2, lastVisTags.length)				
				quanCommas--;
			}
		}
		Set_Cookie('LAST_VISITED_TAGS', escape(lastVisTags), 365, '/', '.themarker.com', '' );//add cookie of tags
	}
	else//no such cookie
		Set_Cookie('LAST_VISITED_TAGS', escape(newTag), 365, '/', '.themarker.com', '' );//add cookie of tags	
}

function calculateQuanCommas(str)
{
	var quanCommas = 0;	
	var commaPlace = str.indexOf('@@');
	
	while (commaPlace != -1){
		quanCommas++;
		str = str.substring(commaPlace+2);
		commaPlace = str.indexOf('@@');
	}

	return quanCommas;
}
function calculateQuanPossibleTabs()
{
	var totalTabsLength = 0;
	for (var i = 0; i < lastSearchTags.length; i++)
	{
		if (lastSearchTags[i].length > 6)
			totalTabsLength = totalTabsLength + 25+8*lastSearchTags[i].length;
		else
			totalTabsLength = totalTabsLength + 75;
	}		

	if (totalTabsLength > spaceForTabs)
		lastSearchTags.shift();		
}

/*show the tabs and the result of the current searched tag*/
function showTabsAndResults(isUpdateCookies)
{	
	if (currentPage == 1)
	{
		var place = checkIfTagInHistory(lastSearchTag);

		if (isEmptyResult == true){//no results
			assigTagSearchField("");
			searchTagLen = 0;				
			return;
		}

		if (place == -1){//not in history						
			lastSearchTags.push(lastSearchTag);//adds to the end						
			if (lastSearchTags.length > lastSearchTagsQuan)//if no place in the bar
				lastSearchTags.shift();//delete the first one				
			calculateQuanPossibleTabs();				
			tagToTurnOn = lastSearchTags.length - 1; 									
		}
		else
			tagToTurnOn = place;

		if (isUpdateCookies == true){
			lastTagsConstructor(lastSearchTag);
			updateLastVisitedTags();
		}
		showTagsTabBar();//show the updated tabs bar			
		turnOnTagTab(tagToTurnOn);
		currentPressedTab = tagToTurnOn;
	}
	showPagesList();
	notDisplaySuggestionDiv();
}

function onClickTag(desiredTag)
{	
	desiredTag = replaceCharsBack(unescape(desiredTag));

	if (desiredTag != lastSearchTag){		
		if (assigTagSearchField(desiredTag) == false)
			return;	

		lastSearchTag = desiredTag;		
		searchTagLen = lastSearchTag.length;
		getSearchResults(escape(lastSearchTag), 1);//get the search results			
	}	
}

function onClickTagFromFeature(desiredTag)
{	
	desiredTag = replaceCharsBack(unescape(desiredTag));
	if (assigTagSearchField(desiredTag) == false)
		return;	
	if (domain == undefined)
		domain = "";
	top.location = domain + '/web2/tags.jhtml?tag='+replaceSpecialChars(document.getElementById("tagName").value);	
}

/*submit the tag search*/
function checkSubmitSearch(keyCode, isFeature)
{
	if (keyCode == 13){//enter pressed				
		var whatToSearch = document.getElementById("tagName").value;		
		if (isFeature == true){			
			if (domain == undefined)
				domain = "";
			top.location = domain+'/web2/tags.jhtml?tag='+replaceSpecialChars(whatToSearch);		
		}
		else{						
			lastSearchTag = whatToSearch;
			getSearchResults(escape(whatToSearch), 1);//get the search results		
			if (divPlace == -1)
				notDisplaySuggestionDiv();			
		}
	}
}

function onClickTab(cnt)
{
	lastSearchTag = lastSearchTags[cnt];
	getSearchResults(escape(lastSearchTags[cnt]),1);
}

function closeTab(cnt)
{
	lastSearchTags.splice(cnt,1);
	if (currentPressedTab != cnt){//if close not active
		if (currentPressedTab > cnt)
			currentPressedTab--;			
		showTagsTabBar();
		turnOnTagTab(currentPressedTab);
	}
	else{		
		if (lastSearchTags.length > 0){
			if ((cnt-1) > -1)
				lastSearchTag = lastSearchTags[cnt-1];
			else
				lastSearchTag = lastSearchTags[cnt];			
			getSearchResults(escape(lastSearchTag), 1, false);//get the search results		
		}	
		else{//the single tab was deleted
			document.getElementById("tagsSearchResults").innerHTML = "";
			document.getElementById("tagsPages").innerHTML = "";	
			document.getElementById("tagsPages").style.display = 'none';	
			document.getElementById("tagsRss").innerHTML = "";		
			document.getElementById("tagsCellolar").style.display = 'none';
			showTagsTabBar();
			assigTagSearchField("");			
		}
	}
}

/*show the tags tab bar*/
function showTagsTabBar()
{		
	var tagsBarHtml = '<table cellpadding="0" cellspacing="0" width="100%" border="0" align="center" dir="rtl"><tr><td width="30"></td>';
	
	for(var cnt = 0; cnt < lastSearchTags.length; cnt++)
	{
		tagsBarHtml = tagsBarHtml.concat('<td rowspan="2" id=rightTagTab'+cnt+' class="rightTagTabOff"></td>');
		tagsBarHtml = tagsBarHtml.concat('<td rowspan="2" id=closeTagTab'+cnt+' class="closeTagTabOff" onclick="closeTab('+cnt+')">&nbsp;</td>');		
		tagsBarHtml = tagsBarHtml.concat('<td rowspan="2" id=rightSpaceTagTab'+cnt+' class="backTagTabOff10"></td>');		
		
		if (lastSearchTags[cnt].length > 6)	
			tagsBarHtml = tagsBarHtml.concat('<td rowspan="2" id=backTagTab'+cnt+' class="backTagTabOff tagTabTxt" style="width:'+8*lastSearchTags[cnt].length+';" align=right valign=bottom onclick="onClickTab(\''+cnt+'\');">'+lastSearchTags[cnt]+'</td>');
		else
			tagsBarHtml = tagsBarHtml.concat('<td rowspan="2" id=backTagTab'+cnt+' class="backTagTabOff tagTabTxt" align=right valign=bottom onclick="onClickTab(\''+cnt+'\');">'+lastSearchTags[cnt]+'</td>');
	
		tagsBarHtml = tagsBarHtml.concat('<td rowspan="2" id=leftTagTab'+cnt+' class=leftTagTabOff></td>');							
	}

	tagsBarHtml = tagsBarHtml.concat('<td>&nbsp;</td></tr>');
	
	if (lastSearchTags.length != 0)
		tagsBarHtml = tagsBarHtml.concat('<tr><td class="tagTabsUnderLine"></td><td class="tagTabsUnderLine"></td></tr>');
	else
		lastSearchTag = "";

	tagsBarHtml = tagsBarHtml.concat('</table>');
	
	var tagsBarObj = document.getElementById("tagTabsBar");
	if (tagsBarObj)
		tagsBarObj.innerHTML = tagsBarHtml;	
}

/*move the focus in the suggestions div*/
function moveFocusInSuggestionDiv(keyCode)
{
	var lastLine = divPlace;//keep the last line

	if ((keyCode == 38) && (divPlace > 0))//up
		divPlace = divPlace - 1;
	else if ((keyCode == 40) && ((divPlace+1) < quanSug))//down
		divPlace = divPlace + 1;
	else if ((keyCode == 13) && (divPlace > -1) && (divPlace < quanSug)){//enter
		var elmTagName = document.getElementById("sugName"+divPlace);				
		if (elmTagName)
			chooseTag(escape(replaceAndChar(elmTagName.innerHTML)));			
		return;
	}
	else
		return;
	//if up or down
	var elm = document.getElementById("sugLine"+divPlace);//paint the new line
	if (elm)
		elm.style.backgroundColor='b7caeb';									
	
	var elmLast = document.getElementById("sugLine"+lastLine);//unpaint the last line				
	if (elmLast)
		elmLast.style.backgroundColor='white';						
}

/*display and place tag suggestion div*/
function displayTagSuggestionsDiv()
{	
	var pL = 0;
	var pT = 0;	
	var obj = document.getElementById("tagName");
	var sugDiv = document.getElementById("tagSuggestions");		

	while(obj.tagName != "BODY"){
		pL+=obj.offsetLeft;
		pT+=obj.offsetTop;
		obj=obj.offsetParent;			
	}		
	sugDiv.style.top = pT+20+"px"; 				
	sugDiv.style.left = pL+"px";			
	sugDiv.innerHTML = tagSug;
	sugDiv.style.display = "block";				
}

/*choose tag from the suggestion div, the tag is encoded*/
function chooseTag(tag)
{	
	document.getElementById("tagName").value = unescape(tag);//decode the tag
	notDisplaySuggestionDiv();
	searchTagLen = document.getElementById("tagName").value.length;
}

/*mouse over tag suggestion line*/
function mouseOverTagSugLine(place)
{
	var elmLast = document.getElementById("sugLine"+divPlace);//paint the last line in white				
	if (elmLast)
		elmLast.style.backgroundColor='white';			
				
	var elm = document.getElementById("sugLine"+place);//paint the current line
	if (elm)
		elm.style.backgroundColor='b7caeb';	
	
	divPlace = place;	
}

/*mouse out tag suggestion line*/
function mouseOutTagSugLine(place)
{
	var elm = document.getElementById("sugLine"+place);
	if ((elm) && (divPlace == place))
	{	
		elm.style.backgroundColor = 'white'
		divPlace = place;		
	}
}

/*limit the tag search field if there is a tag with no suggestions*/
function limitTagName(isLimit)
{
	var subStr =document.getElementById("tagName");
	if (subStr){
		if (isLimit == true)
			subStr.maxChars = document.getElementById("tagName").value.length;
		else
			subStr.maxChars = 30;
	}	
}

/*check whether the tag is over the limit*/
function limitText(evt,field) {
	if (evt.which && evt.which == 8) 
		return true; // allow Netscape backspace
	else		
		return (field.value.length < field.maxChars);	
}

/*not display the suggestion div*/
function notDisplaySuggestionDiv()
{
	var sugDiv = document.getElementById("tagSuggestions");
	if (sugDiv)					
		sugDiv.style.display = 'none';	
}

/*get suggestion tags*/
function getTags()
{		
	if ((objhttp.readyState==4) && (objhttp.status == 200))
	{			
		var respText = objhttp.responseText;//get response text	
		if(respText != "")//if there is response text
		{			
			respText=trimString(respText);
			var ar=respText.split("@@@");			
			var len=ar.length;

			divPlace = -1;
			if (len > 1){//there are suggestions							
				limitTagName(false);							
				tagSug = "</table>";
				for (var i = len-1; i > 0; i--)
				{								
					if (trimString(ar[i]) == "")
						continue;					
					tmp=ar[i].split("@@");				
					tagSug = '<tr id=sugLine'+(i-1)+' onclick="chooseTag(\''+escape(tmp[0])+'\');" onmouseover="mouseOverTagSugLine('+(i-1)+');" onmouseout="mouseOutTagSugLine('+(i-1)+');"><td id=sugName'+(i-1)+' class=tagSuggestionName align=right>'+tmp[0]+'</td><td class=tagSuggestionCounter align=left>'+tmp[1]+'</td></tr>'.concat(tagSug);								
				}	
				tagSug = '<table cellpadding=0 cellspacing=0 border=0 dir=rtl width=100% bgcolor=white>'.concat(tagSug);								
				displayTagSuggestionsDiv(tagSug);					
			}		
			else{//no suggestions
				limitTagName(true);
				notDisplaySuggestionDiv();							
			}
			quanSug = len-1;
		}				
	}
}
//get suggestion tags - ajax call*/
function getSuggestionsFromUrl()
{
	try{					
		var parameters = "subStr="+buildURL(document.getElementById("tagName").value)+"&&quanResults="+quanResults;

		objhttp.open ("POST", "/web2/tags/getTagSuggestions.jhtml", true);
		objhttp.onreadystatechange=getTags;				
		objhttp.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded;");				
		objhttp.send(parameters);			
	}catch(e){}
}

/*get the automatic complete for the tags search*/
function getSuggestions()
{			
	var subStr =document.getElementById("tagName").value;

	if (subStr.length == 0){//no tag for search
		limitTagName(false);
		notDisplaySuggestionDiv();		
		searchTagLen = 0;
	}
	else if ((subStr.length == 1) && (subStr == " ")){//space in the search		
		document.getElementById("tagName").value = "";
		searchTagLen = 0;
	}	
	else if ((subStr.length == (searchTagLen + 1)) || (subStr.length == (searchTagLen - 1)))//one char difference from the last ajax update
	{		
		limitTagName(true);
		searchTagLen = subStr.length;
		getSuggestionsFromUrl();
	}	
	else if (subStr.length != searchTagLen){		
		searchTagLen = subStr.length;
		getSuggestionsFromUrl();
	}
}

function overTagName(isIn,elm)
{
	if (isIn == true)//in
		elm.className='tagResNameOver tagBack';					
	else//out
		elm.className='tagResName';		
}

/*get tag search results*/
function getResults(isUpdateCookies)
{	
	var date, author, headline, slug, section, tmpCnt, arcLen, resArc, quanTalkbacks, curTag;
	var articlePage = "/tmc/article.jhtml";
	
	if ((objhttp.readyState==4) && (objhttp.status == 200))
	{		
		var respText = objhttp.responseText;//get response text	
		if(respText != "")//if there is response text
		{				
			respText = trimString(respText);			
			var ar = respText.split("@@@");			
			var len = ar.length;
			
			if (len > 2){//there are suggestions																
				isEmptyResult = false;
				var results = '<tr><td height="24"></td></tr></table>';
				for (var i = len-1; i > 1; i--)
				{			
					ar[i] = trimString(ar[i]);		

					if (ar[i] == "")
						continue;		
					
					arc = ar[i].split("@@");	
							
					arcLen = arc.length;
					slug = trimString(arc[0]);
					date = trimString(arc[1]);
					headline = trimString(arc[2]);
					author = trimString(arc[3]);
					quanTalkbacks = trimString(arc[4]);
					section = trimString(arc[5]);
					
					if (section == "consultant"){
						articlePage = "/tmc/articleSmall.jhtml";
					}
					resArc = '<tr><td height="11"></td></tr><tr><td><span class="tagResDate">'+date+'</span>&nbsp;<span class="tagResAuthor">'+author+'</span></td></tr>';
					resArc = resArc.concat('<tr><td><a href="' + articlePage + '?log=tag&ElementId='+buildURL(slug)+'" target="_blank" class="headlines">'+headline+'</a></td></tr><tr><td height="4"></td></tr>');
					resArc = resArc.concat('<tr><td>');
									
					if ((quanTalkbacks != null) && (quanTalkbacks > 1))
						resArc = resArc.concat('<a class="talkbackCount" href="/tmc/article.jhtml?log=tag&ElementId='+buildURL(slug)+'" target="_blank">'+quanTalkbacks+' תגובות</a>&nbsp;|&nbsp;');					
					
					resArc = resArc.concat('<span class="tagTitle">תגיות:</span><img src="/ibo/images/0.gif" width="4" height="1">');
					for (tmpCnt = 6; tmpCnt < arcLen; tmpCnt++){//show all tags
						if (tmpCnt > 6)//not first
							resArc = resArc.concat('<span class="tagResName">,&nbsp;</span>');
						curTag = trimString(arc[tmpCnt]);
						resArc = resArc.concat('<img src="/ibo/images/0.gif" width=1 height=1><span style="cursor:pointer;" class="tagResName" onmouseover="overTagName(true,this);" onmouseout="overTagName(false,this);" onclick="onClickTag(\''+escape(curTag)+'\');">'+curTag+'</span>');
					}				
						
					if ((section != null) && (section != "")){
						if (sectionsNames.get(section) == undefined)
							resArc = resArc.concat('<img src="/ibo/images/0.gif" border="0" width="5">|<img src="/ibo/images/0.gif" border="0" width="5"><span class="tagTitle">מדור:<img src="/ibo/images/0.gif" width="4" height="1"></span><a class="tagResArcSection" onmouseover="this.className=\'tagResArcSectionOver\';"  onmouseout="this.className=\'tagResArcSection\';" href="'+sectionsUrl.get('General')+'">'+sectionsNames.get('General')+'</span>');
						else
							resArc = resArc.concat('<img src="/ibo/images/0.gif" border="0" width="5">|<img src="/ibo/images/0.gif" border="0" width="5"><span class="tagTitle">מדור:<img src="/ibo/images/0.gif" width="4" height="1"></span><a class="tagResArcSection" onmouseover="this.className=\'tagResArcSectionOver\';"  onmouseout="this.className=\'tagResArcSection\';" href="'+sectionsUrl.get(section)+'">'+sectionsNames.get(section)+'</span>');
					}
					resArc = resArc.concat('</td></tr>');
					
					if (i != (len - 1))//not the last article	
						resArc = resArc.concat('<tr><td height="13"></td></tr><tr><td class="dotsSepBetweenArc"></td></tr>');
					results = resArc.concat(results);					
				}
				results = '<table cellpadding=0 cellspacing=0 border=0 dir=rtl width=100% bordercolor=pink bgcolor=white><tr></tr>'.concat(results);		
				var searchTag = getUrlEncodingForRSS(replaceCharsTo(lastSearchTag));				
				var baseRssLink = '/tmc/content/xml/rss/sections/tagfeed.jhtml?tagvalue=';
				
				var rssLink = baseRssLink+searchTag;
				
				document.getElementById("tagsSearchResults").innerHTML = results;										
		
				if (lastSearchTag == "אינטרנט"){
					results = '<td align="left" valign="bottom" width=100%><span style="float:right;">כתבות אינטרנט: כל החדשות וכל מה שחם ברשת האינטרנט!</span> &nbsp;<span class="tagsRssText">'+lastSearchTag+'</span></td><td align="left" valign="center"><a href="'+rssLink+'" target="_blank" ><img src="/tmc/i/tags/RSS.gif"  border="0" ></a></td></tr></table>';
				}else{
					results = '<td align="left" valign="bottom" width=100%>&nbsp;<span class="tagsRssText">'+lastSearchTag+'</span></td><td align="left" valign="center"><a href="'+rssLink+'" target="_blank" ><img src="/tmc/i/tags/RSS.gif"  border="0" ></a></td></tr></table>';
				}					 
				results = '<table cellpadding=0 cellspacing=0 border=0 dir=rtl width=100% bordercolor=pink bgcolor=white><tr>'.concat(results);
							
				document.getElementById("tagsRss").innerHTML = results;	
				
				
				results = '<div class="tagsRssText"  id="pAlertGlobalLink">';
				results += TM.TagsMenu.getPalertsLink(replaceCharsTo(lastSearchTag), 'pAlertGlobalLink');
				results += '</div>'

				document.getElementById("tagsCellolar").innerHTML = results;	
			}		
			else{//no results
				isEmptyResult = true;	
				if(lastSearchTag != undefined)	
					lastSearchTag = lastSearchTags[currentPressedTab];
				else
					lastSearchTag = "";
				alert("לא נמצאו תוצאות חיפוש עבור התגית שחיפשת");				
			}
			quanResultsToTag = ar[1];
		}	
		else
			isEmptyResult = true;			
		showTabsAndResults(isUpdateCookies);
	}
	isEmptyResult = false;
}

/*get search results for the desired tag - ajax call*/
function getSearchResults(tagForSearch, page, isUpdateCookies)
{		
	try{	
		tagForSearch = unescape(tagForSearch);		
		if (isUpdateCookies == null)
			isUpdateCookies = true;
			
		currentPage = page;

		var fromArc = (page - 1) * quanResultsInPage + 1;		

		var parameters = "tag="+buildURL(tagForSearch)+"&&from="+fromArc+"&&howMany="+quanResultsInPage;		
		objhttp.open ("POST", "/web2/tags/getTagSearchResults.jhtml", true);
			objhttp.onreadystatechange=function callGetResults(){getResults(isUpdateCookies)};				
		objhttp.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded;");				
		objhttp.send(parameters);			
	}catch(e){}	
}

function getUrlEncodingForRSS(hebrewValue)
{
	var i = 0;
	var s= "";
	while(i < hebrewValue.length) {
		c = hebrewValue.charAt(i++);
		
		t = hebrewChars.get(c);
		if(t!=undefined)
		{
			s += '\%'+t;
		}
		else{
			s += c;
		}
		
	}	
	
	return s;
}

function replaceCharsTo(str)
	{
		str =str.replace('\"','~');
		str =str.replace('\'','*');
		str =str.replace('&','^');
		return str;
	}	
