/*
* Licensed to the Apache Software Foundation (ASF) under one or more
*  contributor license agreements.  The ASF licenses this file to You
* under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.  For additional information regarding
* copyright in this work, please see the NOTICE file in the top level
* directory of this distribution.
*/
/* (C) Copyright IBM Corp. 2007, 2008 All Rights Reserved. */


//var recommendCollection = new Object ();


var helpWindow;

function openHelpWindow(url, width, height) {
	 if (!width) {
		 width = window.screen.width / 4;
		 if (width < 950)
			 width = 950;
	 }
	 if (!height) {
		 height = window.screen.height / 4;
		 if (height < 550)
			 height = 550;
	 }
	
	 if (typeof(helpWindow) != "undefined")
	 	helpWindow.close();
	
	 var options = 'height=' + height + ',width=' + width + ',status=yes,toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=yes';
	 helpWindow = window.open(BlogsBaseUrl+url, 'help', options);
	
	 if (window.focus)
		 helpWindow.focus();
}

/* This function is used to set cookies */
function setCookie(name,value,expires,path,domain,secure) {
  document.cookie = name + "=" + escape (value) +
    ((expires) ? "; expires=" + expires.toGMTString() : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : "");
}

/* This function is used to get cookies */
function getCookie(name) {
	var prefix = name + "=" 
	var start = document.cookie.indexOf(prefix) 

	if (start==-1) {
		return null;
	}
	
	var end = document.cookie.indexOf(";", start+prefix.length) 
	if (end==-1) {
		end=document.cookie.length;
	}

	var value=document.cookie.substring(start+prefix.length, end) 
	return decodeURIComponent(value);
}

/* This function is used to delete cookies */
function deleteCookie(name,path,domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

function rememberUser(theForm) {
    var expires = new Date();
    expires.setTime(expires.getTime() + 24 * 365 * 60 * 60 * 1000); // sets it for approx 365 days.
    // sets it for entire domain, so freeroller will remember for all users
    setCookie("commentAuthor",theForm.name.value,expires,"/"); 
    setCookie("commentEmail",theForm.email.value,expires,"/");
    setCookie("commentUrl",theForm.url.value,expires,"/");
}

function forgetUser(theForm) {
    deleteCookie("commentAuthor","/");
    deleteCookie("commentEmail","/");
    deleteCookie("commentUrl","/");
}

/* This function is used to show/hide elements with a display:none style attribute */ 
function toggle(targetId) {
    if (document.getElementById) {
        target = document.getElementById(targetId);
    	if (target.style.display == "none") {
    		target.style.display = "";            
    	} else {
    		target.style.display = "none";
    	}
    }
}

/* The toggleFolder and togglePlusMinus functions are for expanding/contracting folders */
function toggleFolder(targetId) {
    var expanded;
    if (document.getElementById) {
        target = document.getElementById(targetId);
    	if (target.style.display == "none") {
    		target.style.display = "";    
            expanded = true;        
    	} else {
    		target.style.display = "none";
            expanded = false;
    	}
        togglePlusMinus("i" + targetId);
        
        // set a cookie to remember this preference
        var expires = new Date();
        expires.setTime(expires.getTime() + 24 * 365 * 60 * 60 * 1000); // sets it for approx 365 days.
        setCookie("rfolder-"+targetId,expanded,expires,"/");
    }
}

function togglePlusMinus(targetId) {
    if (document.getElementById) {
        target = document.getElementById(targetId);
    	if (target.innerHTML == "+") {
    		target.innerHTML = "-";
    	} else {
    		target.innerHTML = "+";
    	}
    }
}

/* This function is to set folders to expand/contract based on a user's preference */
function folderPreference(folderId) {
    var folderCookie = getCookie("rfolder-"+folderId);
    if (folderCookie != null) { // we have user's last setting
        folder = document.getElementById(folderId);
        plusMinus = document.getElementById("i"+folderId);
        if (folderCookie == "true") { // show
            folder.style.display = "";
            plusMinus.innerHTML = "-";
        } else { // hide
            folder.style.display = "none";
            plusMinus.innerHTML = "+"; 
        }
    }
}

function toggleNextRow(e) {
    if (e.type == "checkbox") {
        var checked = e.checked;
    } else if (e.type == "radio") {
        var v = e.value;
        var checked = (v == "1" || v == "y" || v == "true") ? true : false;
    }
    // var nextRow = e.parentNode.parentNode.nextSibling;
    // the above doesn't work on Mozilla since it treats white space as nodes
    var thisRow = e.parentNode.parentNode;
    var tableBody = thisRow.parentNode;
    var nextRow = tableBody.getElementsByTagName("tr")[thisRow.rowIndex+1];
    
    if (checked == true) {
        nextRow.style.display = "";
    } else {
        nextRow.style.display = "none";
    }
}

function toggleControl(toggleId, targetId) {
    var expanded;
    if (document.getElementById) {
        target = document.getElementById(targetId);
        toggle = document.getElementById(toggleId);
    	if (target.style.display == "none") {
    		target.style.display = "";  
            expanded = true;  
                  
    	} else {
    		target.style.display = "none";  
            expanded = false;
    	}
        togglePlusMinus("i" + targetId);
        
        // set a cookie to remember this preference
        var expires = new Date();
        expires.setTime(expires.getTime() + 24 * 365 * 60 * 60 * 1000); // sets it for approx 365 days.
        setCookie("control-"+targetId,expanded,expires,"/");
    }
}

function isblank(s) {
   for (var i=0; i<s.length; s++) {
      var c = s.charAt(i);
      if ((c!=' ') && (c!='\n') && (c!='')) return false;
   }
    return true;
}

// Show the document's title on the status bar
window.defaultStatus=document.title;

// addTag is used in the autocompleter
var addTag = function(t, autocomplete) 
{
	if (autocomplete)
	{
		var lastTokenPos = $('tagsAsString').value.lastIndexOf(" ");
		var newValue = $('tagsAsString').value.substr(0, lastTokenPos + 1);
		var whitespace = $('tagsAsString').value.substr(lastTokenPos + 1).match(/^\s+/);
	    if (whitespace)
	        newValue += whitespace[0];
	    $('tagsAsString').value = newValue + t;
    /*
    	// format: type#term^term_id
    	lastTokenPos = $('hiddenTags').value.lastIndexOf(" ");
		newValue = $('hiddenTags').value.substr(0, lastTokenPos + 1);
		whitespace = $('hiddenTags').value.substr(lastTokenPos + 1).match(/^\s+/);
	    if (whitespace)
	        newValue += whitespace[0];
	    $('hiddenTags').value = newValue + type+"#"+t+"^"+termid+" ";
	*/	    
		return;
	}
}

// addTag2
var addTag2 = function() 
{
	var tid1 = $('rootTagComboBox').value;
	var tid2 = $('branchTagComboBox').value;
	var tid3 = $('leafTagComboBox').value; 
	
	if(tid1 == "-1")
		return;
		
	var tagid = tid1;
	var tag = $('rootTagComboBox').options[$('rootTagComboBox').options.selectedIndex].text;
	
	if(tid2 != "-1")
	{
		tagid += "#"+tid2;
		tag += ":"+$('branchTagComboBox').options[$('branchTagComboBox').options.selectedIndex].text;
	}
	if(tid3 != "-1")
	{
		tagid += "#"+tid3;
		tag += ":"+$('leafTagComboBox').options[$('leafTagComboBox').options.selectedIndex].text;
	}

	var itemId = tag+"^"+tagid;
    
	var parent = $('suggestedTagList');
	if(parent.hasChildNodes())
	{
		var children = parent.childNodes;
		var isExist = false;
		var len = children.length;
		for(var i=0; i<len; i++)
		{
			var text = children[i].getAttribute('id');
			if(text == itemId)
			{
				isExist = true;
				alert(tagExistMsg);
				break;
			}
		}
	}
	// format: structure_tag^tagid1:tagid2:tagid3
	if(!isExist)
	{
		var li = document.createElement('li');
		li.setAttribute( 'id', itemId );
		var txt = document.createTextNode(tag);
		
		var a = document.createElement('a')
    	a.href = '#';
    	a.setAttribute('id', 'remove_'+tag);
    	a.onclick = function(){removeTag(itemId);return false;}   
    	
		var img = document.createElement('img');
		img.src = contextPath + '/roller-ui/images/remove.gif';
  		a.appendChild(img);
    
	    li.appendChild(txt);
	    li.appendChild(a);
		parent.appendChild(li);
		
		lastTokenPos = $('hiddenTagsDropdownAdd').value.lastIndexOf(" ");
		newValue = $('hiddenTagsDropdownAdd').value.substr(0, lastTokenPos + 1);
		whitespace = $('hiddenTagsDropdownAdd').value.substr(lastTokenPos + 1).match(/^\s+/);
		if (whitespace)
	    	newValue += whitespace[0];
		$('hiddenTagsDropdownAdd').value = newValue +itemId+" ";
		
		resetSuggestedTagMenu();
	}

	parent.style.display = "";
	
	return;
	
}

function resetSuggestedTagMenu()
{
	$('rootTagComboBox').options[0].selected  = true;
	options = $('branchTagComboBox').options;
	resetSuggestedDefault(options);
	options = $('leafTagComboBox').options;
	resetSuggestedDefault(options);
}

function resetSuggestedDefault(options)
{
	options.length = 0;
	opt = document.createElement('option');
	opt.value = "-1";
	opt.text = selectTag;
	options.add(opt);
}

function removeTag(tagId)
{
	lastTokenPos = $('hiddenTagsDropdownRemove').value.lastIndexOf(" ");
	newValue = $('hiddenTagsDropdownRemove').value.substr(0, lastTokenPos + 1);
	whitespace = $('hiddenTagsDropdownRemove').value.substr(lastTokenPos + 1).match(/^\s+/);
	if (whitespace)
	   	newValue += whitespace[0];
	$('hiddenTagsDropdownRemove').value = newValue + tagId +" ";	
		
	$(tagId).parentNode.removeChild($(tagId));
}

// this will activate some of the footer links
function activateFooterLinks()
{
	var parent = document.getElementById('lotusFooterULTools');
	if(parent != null)
	{
		var children = parent.getElementsByTagName('LI');
	
		var len = children.length;
		for(var i=1; i < len; i++)
		{
			var li = children[i];
			var a =	li.getElementsByTagName('a');
			var oldClassName = a[0].className;
			var idx = oldClassName.indexOf('lotusHidden');
			if(idx != -1) {
			    a[0].className = oldClassName.substring(0, idx) + oldClassName.substring(idx + 11);
			}
		}
	}
	/*
	<li>
	<a href="http://blogsdev.notesdev.ibm.com/blogs/nav/toolbox?appName=blogs" >How to Bookmark</a>
	</li>				
	<li>
	<a href="http://blogsdev.notesdev.ibm.com/blogs/roller-ui/admin/rollerConfig.do?method=edit" class="lotusHidden lotusAdminLink" >Administration</a>
	</li>				
	<li><a href="http://blogsdev.notesdev.ibm.com/blogs/roller-ui/servermetrics.do" class="lotusHidden lotusAdminLink" >Server Metrics</a>
	</li>
	*/
//lotusFooterULTools
//lotusHidden 
}





// see _header.vm for defined values

function getEntryRatingBracket(rating) {
  return Math.min(Math.floor(rating / 10),8);
}

var linkListID;

// display the entry rating
// showEntryRating('/blogs','http://blogsdev.notesdev.ibm.com/blogs/han/entry/blog_test_1',0,0,'rating4AFG092D7C36370B415F8CAFAB0E21000534', true)
// the last paramater indicates rating can be added (true) or not (false)
// the newnamelist is coming from the RatingServlet.java during the response
function showEntryRating(baseurl, entry, rating, fmtRating, count, fmtCount, theContainer, edit, home, nonce, newnamelist, altText) {
  var container = document.getElementById(theContainer);
  //debugger;
  // this creates a map collection of all entries with names who has rated them
  var listID = "recommendationList"+theContainer;
  // for the action link popup
  linkListID = listID+"link";
  	
  //recommendCollection[listID]=recommenteeArray;
  if (container == null) return;
  container.innerHTML = ""; // clear the container
  var auth = (user != null) ? user.auth : false;
  var rated = (user != null) ? user.rated : false;
  var nobr = document.createElement('nobr');
  
  var anchor = document.createElement('a');
  anchor.href = "#";
  
  var img = document.createElement('img');
  var bracket = count > 0 ? getEntryRatingBracket(count) + 1 : 0;
  img.border = '0';
  // this is for IE
  //img.alt = count + " " + RatingStar;
  img.src = BlogsBaseUrl + '/nav/common/styles/images/iconRating' + bracket + '.gif';
  img.alt = altText;
  
  
  //else if((recommenteeArray != null && recommenteeArray != "") || 
  //			  (newnamelist != null && newnamelist != ""))
  // IE, we can assign the function to the element directly
  if(navigator.userAgent.indexOf('MSIE') !=-1)
  {
    anchor.onmouseover = function(){MenuPopup.showMenu( listID, event, { focus: this } );}
    anchor.onfocus = function(){MenuPopup.showMenu( listID, event, { focus: this } );}
    anchor.onblur = function(){MenuPopup.returnFocusElement = false;MenuPopup.hideMenu();}
    anchor.onclick = function(){return false;}                                         
  }
  else  // For Firefox we have to register the event  
  {
    anchor.addEventListener("mouseover", function (event)
                                        {
                                            MenuPopup.showMenu( listID, event, { focus: this } )
                                        }, 
                                        true);
    anchor.addEventListener("focus", function (event)
                                        {
                                            MenuPopup.showMenu( listID, event, { focus: this } )
                                        }, 
                                        true);
    anchor.addEventListener("blur", function (event)
                                        {
                                            MenuPopup.hideMenu()
                                        }, 
                                        true);
    anchor.setAttribute("onclick", "return false;");
  }
  //img.onmouseout = function(){MenuPopup.hideMenu();}
  
  var canRate = (edit && auth && !rated) ? true : false;
  
  if (edit && auth && !rated) {
    var a = document.createElement('a')
    a.href = '#';
    a.title = RatingRecommand;
    a.rating = 5;
    a.entry = entry;
    a.baseurl = baseurl;
    a.nonce = nonce;
    a.onclick = function() { submitRatingForm(this.entry, this.rating, this.baseurl, false, this.nonce); }    
    var add = document.createElement('img');
    add.border = '0';
    add.src = BlogsBaseUrl + '/nav/common/styles/images/iconAddRating.gif';    
    add.alt = RatingRecommand;
    a.appendChild(add);
    nobr.appendChild(a);
  }
  
  anchor.appendChild(img);
  nobr.appendChild(anchor);
  
  
  var c = document.createElement('sup');
  c.className = 'ratingcount';
  c.innerHTML = " " + (count > 0 ? fmtCount : "0");
  
  nobr.appendChild(c);
  

// creates the name list container to be used for display
// recommenteeArray is the old list, newnamelist is the new one from RatingServlet
// home: is this coming from the homepage or not
  var listContainer = constructRecommendedByList(listID, recommenteeArray, canRate, rated, home, newnamelist);
  // construct the popup for the action link that is only in the entry page
  if(!home)
  {
  	var linkListContainer = constructRecommendedByListLink(linkListID, recommenteeArray, canRate, rated, newnamelist);
  	nobr.appendChild(linkListContainer);
  }
  nobr.appendChild(listContainer);
  
  // this is for Firefox
  //container.title = count + " " + RatingRecommendation;
  container.appendChild(nobr);

}

// creates or gets the id = 'rating' form
// 
// isComment, true or false, true is comment, false is entry
function submitRatingForm(entry, value, baseurl, isComment, nonce, theContainer) {

  var doc = getFrameDoc('ratingframe', baseurl, isComment);
  if (doc != null) {
    var form = doc.getElementById('rating');
    if (form == null) {
      form = doc.createElement('form');
      form.id = 'rating';
      form.method = 'post';
      form.action = entry;
      var rating = doc.createElement('input');
      rating.type = 'hidden';
      rating.name = 'rating';
      rating.value = value;
      form.appendChild(rating);
      if(isComment)
      {
      	var commentid = doc.createElement('input');
      	commentid.type = 'hidden';
      	commentid.name = 'commentid';
      
      	commentid.value = theContainer;
      	form.appendChild(commentid);
      }
      var dangerousurlnonce = doc.createElement('input');
      dangerousurlnonce.type = 'hidden';
      dangerousurlnonce.name = 'dangerousurlnonce';
      dangerousurlnonce.value = nonce;
      form.appendChild(dangerousurlnonce);

      // this works
      // during the initial call of the iframe creation the body is null
      // I guess this is due to not all the scripts in header have finished
      // loading yet and we can't wait for them to finish, it will take a while
      // and slow the app. so we will try to manually create a BODY element
      // maybe there is a better solution, maybe
      // doc.open(); doc.write(); doc.close()
      if(navigator.userAgent.indexOf('MSIE') !=-1) {
        doc.appendChild(doc.createElement("body"));
      }
      doc.body.appendChild(form);
      if (navigator.userAgent.indexOf('Gecko') !=-1) {
        setTimeout('submitRatingForm("' + entry + '",'+ value +',"' + baseurl + '",' + isComment + ',"' + nonce + '","' + theContainer + '")',10);
        return;
      }
    } 
    form.submit();  
  }
}


function getFrameDoc(frame, baseurl, isComment) {
//debugger;
  //strange, returning an iframe from within getFrame doesn't work on IE
  // have to use getElementById() to get it
  getFrame(frame, baseurl, isComment);
  var frameObj = document.getElementById(frame);
  if (frameObj != null) {
   var doc = null;
   if (frameObj.contentDocument) {
        // NS6
      doc = frameObj.contentDocument; 
    } else if (frameObj.contentWindow) {
        // IE5.5 and IE6
      doc = frameObj.contentWindow.document;
    } else if (frameObj.document) {
        // IE5
      doc = frameObj.document;
    }
    return doc;
  } else return null; 
}

// creates or gets a hidden iframe with id sets to 'ratingframe'
// sets the src url to the rating forward url
function getFrame(frame, baseurl, isComment) {
	//debugger;
  var iframe = document.getElementById(frame);
  if (!iframe) {
    try {
      iframe = document.createElement('iframe');
      iframe.setAttribute('id',frame);
      iframe.setAttribute('name', 'myframe');
      iframe.style.visibility = 'hidden';
      iframe.style.height = '0';
      iframe.style.width = '0';
      iframe.style.border = '0px';
      if(isComment)
      {
      	iframe.src = baseurl + "/roller-ui/rendering/rating/comment";
	  }
	  else
	  {
	  	iframe.src = baseurl + "/roller-ui/rendering/rating/entry";
      }
      iframe = document.body.appendChild(iframe);
      if (document.frames) {
        // IE5 Mac only
        iframe = document.frames[frame];
      }
    } catch (exception) {
        // IE5 Win only
      if(isComment)
      {
      	siframe = '<iframe id="' + frame + '" src="' + baseurl + '/roller-ui/rendering/rating/comment" style="visibility:hidden;height:0;width:0"></iframe>';
      }
      else
      {
      	siframe = '<iframe id="' + frame + '" src="' + baseurl + '/roller-ui/rendering/rating/entry" style="visibility:hidden;height:0;width:0"></iframe>';
      }
      document.body.innerHTML += siframe;
      iframe = new Object();
      iframe.document = new Object();
      iframe.document.location = new Object();
      iframe.document.location.iframe = document.getElementById(frame);
      iframe.document.location.replace = function(href) {
        this.iframe.src = href;
      }
    }  
  }
  //setTimeout( "getFrame(" + frame + "," + baseurl +")", 100 );
  
}

function constructRecommendedByList(listID, namelist, canRate, rated, home, newnamelist)
{
	
    // create the 'div' holder
	var listContainer = document.getElementById(listID);
    
    if(!listContainer)
    {
        listContainer = document.createElement('div');
    }
    // clean up everything inside the container first
    listContainer.innerHTML="";
    
    listContainer.setAttribute( 'id', listID );
    
    // for home/dashboard page, we don't want to display the popup if name list is empty
    if(home && (namelist == null || namelist == "") && (newnamelist == null || newnamelist == ""))
    	return listContainer;
    
    listContainer.className="ratingPopup popup";		

	var listLabel = document.createElement('h3');
	listLabel.setAttribute('style', 'text-align:left;');
	
		// create the 'textarea'
	var popupTextarea = document.createElement('textarea');
	popupTextarea.setAttribute( 'style', 'border:0px solid gray;padding:3px;background-color:#fff;' );
	popupTextarea.setAttribute( 'readonly', 'readonly');
	// if newnamelist is not empty that means we are getting this from the RatingServlet
	// lets use the updated list
	if(newnamelist !="" && newnamelist!=null)
	{
		popupTextarea.value = newnamelist;
		canRate = false;
		rated = true;
	}
	else
		popupTextarea.value = namelist;
	
  	
	//listLabel.inngerHTML="";
	if(home)
	{
	    listLabel.innerHTML =RatingRecommentedBy;
	}
	else
	{
	    if(canRate)
	    {
	    	if(popupTextarea.value == null || popupTextarea.value == "")
	    		listLabel.innerHTML = RatingClickToRate;
		    else
		    	listLabel.innerHTML = RatingClickToRate + "<br>" + RatingRecommentedBy;
	    }
	    else if(!canRate && rated)
	    {
	    	if(popupTextarea.value == null || popupTextarea.value == "")
	    		listLabel.innerHTML =RatingRated;
	    	else
		    	listLabel.innerHTML =RatingRated + "<br>" + RatingRecommentedBy;
	    }
	    else if(!canRate && !rated)
	    {
	    	if(popupTextarea.value == null || popupTextarea.value == "")
	    		listLabel.innerHTML ="<a href='"+BlogsBaseUrl+"/roller-ui/login-redirect.jsp?redirect="+entrylink+"'>"+RatingLoginToRate + "</a>";
		    else
		    	listLabel.innerHTML ="<a href='"+BlogsBaseUrl+"/roller-ui/login-redirect.jsp?redirect="+entrylink+"'>"+RatingLoginToRate + "</a>" + "<br>" + RatingRecommentedBy;
	    }
	}
	// create the 'fieldset'
    //var popupFieldset = document.createElement('fieldset');
	
	//popupFieldset.appendChild(popupTextarea);
	listContainer.appendChild(listLabel);	
	if(popupTextarea.value != null && popupTextarea.value != "")
		listContainer.appendChild(popupTextarea);
	
    return listContainer;

}

// display the entry rating
// showEntryRating('/blogs','http://blogsdev.notesdev.ibm.com/blogs/han/entry/blog_test_1',0,0,'4AFG092D7C36370B415F8CAFAB0E21000534', true)
// the last paramater indicates rating can be added (true) or not (false)
// the newnamelist is coming from the RatingServlet.java during the response
function showCommentRating(baseurl, entry, rating, fmtRating, count, fmtCount, theContainer, edit, nonce, newnamelist, altText) {
  
  var container = document.getElementById(theContainer);
  //debugger;
  // this creates a map collection of all entries with names who has rated them
  var listID = "recommendationList"+theContainer;
  //recommendCollection[listID]=recommenteeArray;
  if (container == null) return;
  container.innerHTML = ""; // clear the container
  var auth = (user != null) ? user.auth : false;
  var rated = (user != null) ? user.rated : false;
  var nobr = document.createElement('nobr');
  
  var anchor = document.createElement('a');
  anchor.href = "#";
  
  var img = document.createElement('img');
  var bracket = count > 0 ? getEntryRatingBracket(count) + 1 : 0;
  img.border = '0';
  // this is for IE
  //img.alt = count + " " + RatingStar;
  img.src = BlogsBaseUrl + '/nav/common/styles/images/iconRating' + bracket + '.gif';
  img.alt = altText;
    			  
  // IE, we can assign the function to the element directly
  if(navigator.userAgent.indexOf('MSIE') !=-1)
  {
    anchor.onmouseover = function(){MenuPopup.showMenu( listID, event, { focus: this } );}
    anchor.onfocus = function(){MenuPopup.showMenu( listID, event, { focus: this } );}
    anchor.onblur = function(){MenuPopup.returnFocusElement = false;MenuPopup.hideMenu();}
    anchor.onclick = function(){return false;}                                        
  }
  else  // For Firefox we have to register the event  
  {
    anchor.addEventListener("mouseover", function (event)
                                        {
                                            MenuPopup.showMenu( listID, event, { focus: this } )
                                        }, 
                                        true);
    anchor.addEventListener("focus", function (event)
                                        {
                                            MenuPopup.showMenu( listID, event, { focus: this } )
                                        }, 
                                        true);
    anchor.addEventListener("blur", function (event)
                                        {
                                            MenuPopup.hideMenu()
                                        }, 
                                        true);
    anchor.setAttribute("onclick", "return false;");
  }
  //img.onmouseout = function(){MenuPopup.hideMenu();}
  
  var canRate = (edit && auth && !rated) ? true : false;
  
  if (edit && auth && !rated) {
    var a = document.createElement('a')
    a.href = '#';
    a.title = RatingRecommandComment;
    a.rating = 5;
    a.entry = entry;
    a.baseurl = baseurl;
    a.nonce = nonce;
    a.onclick = function() { submitRatingForm(this.entry, this.rating, this.baseurl, true, this.nonce, theContainer); }    
    var add = document.createElement('img');
    add.border = '0';
    add.src = BlogsBaseUrl + '/nav/common/styles/images/iconAddRating.gif';    
    add.alt = RatingRecommandComment;
    a.appendChild(add);
    nobr.appendChild(a);
  }
  
  anchor.appendChild(img);
  nobr.appendChild(anchor);
  
  var c = document.createElement('sup');
  c.className = 'ratingcount';
  c.innerHTML = " " + (count > 0 ? fmtCount : "0");
  
  nobr.appendChild(c);
  

// creates the name list container to be used for display
// recommenteeArray is the old list, newnamelist is the new one from RatingServlet
// home: is this coming from the homepage or not
  var listContainer = constructRecommendedByList(listID, recommenteeArray, canRate, rated, false, newnamelist);
  nobr.appendChild(listContainer);
  
  // this is for Firefox
  //container.title = count + " " + RatingRecommendation;
  container.appendChild(nobr);

}


function constructRecommendedByListLink(listID, namelist, canRate, rated, newnamelist)
{
	
    // create the 'div' holder
	var listContainer = document.getElementById(listID);
    
    if(!listContainer)
    {
        listContainer = document.createElement('div');
    }
    // clean up everything inside the container first
    listContainer.innerHTML="";
    
    listContainer.setAttribute( 'id', listID );
    listContainer.className="infoBox popup";		

	var listLabel = document.createElement('h3');
	listLabel.setAttribute('style', 'text-align:left;');
	
		// create the 'textarea'
	var popupTextarea = document.createElement('textarea');
	popupTextarea.setAttribute( 'style', 'border:1px solid gray;background-color:#fff;' );
	popupTextarea.setAttribute( 'readonly', 'readonly');
	// if newnamelist is not empty that means we are getting this from the RatingServlet
	// lets use the updated list
	if(newnamelist !="" && newnamelist!=null)
	{
		popupTextarea.value = newnamelist;
		canRate = false;
		rated = true;
	}
	else
		popupTextarea.value = namelist;
	
  	
	
	    if(canRate)
	    {
		    listLabel.innerHTML = RatingRecommand + ".<br>" + RatingRecommentedBy;
	    }
	    else if(!canRate && rated)
	    {
		    listLabel.innerHTML =RatingRated + "<br>" + RatingRecommentedBy;
	    }
	    else if(!canRate && !rated)
	    {
		    listLabel.innerHTML ="<a href='"+BlogsBaseUrl+"/roller-ui/login-redirect.jsp?redirect="+entrylink+"'>"+RatingLoginToRate + "</a>" + "<br>" + RatingRecommentedBy;
	    }
	
	// create the 'fieldset'
    //var popupFieldset = document.createElement('fieldset');
	
	//popupFieldset.appendChild(popupTextarea);
	listContainer.appendChild(listLabel);	
	listContainer.appendChild(popupTextarea);
	
    return listContainer;

}

var TagCloudUtils = new Object();

TagCloudUtils.TagStatDetail = new Object();

TagCloudUtils.TagStatDetail.current = new Object();
TagCloudUtils.TagStatDetail.current.request = null;
TagCloudUtils.TagStatDetail.current.menu = null;

TagCloudUtils.TagStatDetail.display = function(tagid, type, elemid, event, focus) {
    var copiedEvent = new Object();
    copiedEvent.target = event.target;
    copiedEvent.srcElement = event.srcElement;
    copiedEvent.clientX = event.clientX;

    if(TagCloudUtils.TagStatDetail.current.request) {
        TagCloudUtils.TagStatDetail.current.request.transport.abort();
    }
    
    MenuPopup.hideMenu();
    
    TagCloudUtils.TagStatDetail.current.request = 
        TagCloudUtils.TagStatDetail.current.request = 
        new Ajax.Request(BlogsBaseUrl + "/roller-services/json/tag_stat_detail/?term=" + tagid + "&type=" + type, {
            method: 'get',
            onSuccess: function(transport){
                eval("var response = " + transport.responseText);
                if(response.tagcounts && response.tagcounts.length > 0) {
                    var s = "";
                    for(var i = 0; i < response.tagcounts.length; i++) {
                        if(i > 0) {
                            s = s + "<BR>"
                        }
                        
                        var t = response.tagcounts[i];
                        s = s + t.tag + "&nbsp;";
                        if(bidir == 'rtl') {
                            s = s + "<span dir='rtl'>";
                        }
                        s = s + "(" + t.count + ")";
                        if(bidir == 'rtl') {
                            s = s + "</span>";
                        }
                    }
                    var elem = document.getElementById(elemid);
                    elem.innerHTML = s;
                    MenuPopup.showMenu( elemid, copiedEvent, { focus: focus } );
                    
                    TagCloudUtils.TagStatDetail.current.request = null;
                    TagCloudUtils.TagStatDetail.current.menu = elemid;
                }
            },
            onFailure: function(){ }
        });
};

TagCloudUtils.TagStatDetail.registerEvent = function(tagid, type, popupid, elemid) {
    var elem = document.getElementById(elemid);
    if(navigator.userAgent.indexOf('MSIE') !=-1) {
       elem.onmouseover = function(){
           TagCloudUtils.TagStatDetail.display(tagid, type, popupid, event, elem);
       };  
       elem.onmouseout = function() {
           MenuPopup.hideMenu();
       };                                      
    }
    else  // For Firefox we have to register the event  
    {
       elem.addEventListener("mouseover", 
                            function (event) {
                                TagCloudUtils.TagStatDetail.display(tagid, type, popupid, event, elem);
                            }, 
                            true);
       elem.addEventListener("mouseout", 
                            function (event) {
                                MenuPopup.hideMenu();
                            }, 
                            true);
    }
};

//for tags div toggle function
function toggleSubs(divToggle, divToggleImg, dogearContextPath) {
    var el = document.getElementById(divToggle);
    var img = document.getElementById(divToggleImg);
    if (el.style.display != "none") {
        Effect.toggle(divToggle, "slide", {duration:0.5});
        img.className = "lotusSprite lotusArrow lotusTwistyClosed";
    } else {
        Effect.toggle(divToggle, "slide", {duration:0.5});
        img.className = "lotusSprite lotusArrow lotusTwistyOpen";
    }
}


//for addmember widget
function escapeInlineText(text) {
    return escapeText(text, true);
};

function escapeText(text, inline) {
   var escapeBuffer = document.getElementById("escapeBufferDiv");
    
    if (!escapeBuffer) {
        var tmp = document.createElement("div");
        tmp.id = 'escapeBufferDiv';
        document.body.appendChild(tmp);
        escapeBuffer = tmp;
    }
    
    //escapeBuffer.innerHTML = '';
    escapeBuffer.appendChild(document.createTextNode(text));
    var escaped = escapeBuffer.innerHTML;
    escapeBuffer.innerHTML = '';
    
    if (inline) {
        escaped = escape_q(escaped);
    }

    return escaped;
};
        

function escape_q(s)
{
    var t = '';
    for (var i = 0; i < s.length; i++)
    {
        var c = s.charAt(i) ;
        if (c == '"') {
          t += "&#34;";
        } else if (c == "'" ) {
          t += "&#39;";
        } else if  (c == '\\') {
            t += "&#92;&#92;";
        } else {
            t += c;
        }
    }
    return t;
};
