//global variables 
var PluckSocialArticle = new Array();
var PluckDiscoverContent = new Array();
var requestBatch;
var requests = new Array();
var maxRequestsPerBatch = 20;
var reqType;
var altFlag;
var imagePath;
var ContentImagesPath;
var prevReportAbuse;
var avatarCookie;
var reviewSortOrder="TimeStampDescending";
var commentSortOrder="TimeStampDescending";
var commentsPerPage = 10;
var reviewsPerPage=10;
var commentPageNo = 1;
var reviewPageNo = 1;
var abuseThreshold=2;
var IsCommentoutputDAAPI =false;
var IsReviewoutputDAAPI =false;
var discoveryWidget="";
var badWordsMessage = "Please edit or remove the following word(s), then resubmit your content:"
var discoverywidgetIsFilled = new Array();
var discoveryTimeZone=" CDT";
var varZIndex=999; //This is used for setting the Z-Index for resolving the UI overlap issue for Report Abuse in Review and Comment O/P widget
//Variable srequired for FB comment submission
var commentArticleId;
var commentTextId;
var userCommentText;
var FbLoggedIn;
var cookie_HWFaceBook = "HWFaceBook";
var cookie_AT = "AT";
var FbComments = "false";
var noAvatarImage;
var usercookie ="UserCookie";

//This is the object that builds the PluckSocialArticle
function fnPluckSocialArticle(articlekey,hpsection,divid,action,pageno,pageurl,pagetitle,section,categories,contentType)
{
	this.ArticleKey = articlekey; //contentid
	this.HPSection = hpsection; //section on the page
	this.Divid = divid; //div id
	this.Action = action; // action to be performed. can be Recommend,Rating,commentsCounter
	this.PageNo = pageno; //page no for pagination
	this.PageUrl = pageurl; //pageURL for updateArticleAction
	this.PageTitle = pagetitle; //title for UpdaetArticleAction
	this.Section = section; //section for updateArticleAction
	this.Categories = categories; //categories for updateArticleAction
	this.ContentType = contentType; //the content type. can have values: article,user,comment,review,gallery,photo,video
	this.IsUpdateArticle = true;
}


//This method is called form the UC. It takes the parameters & checks if the articleKey is already present. If not build the new PluckSocialArticle.
//If present update the PluckSocialArticle with the additional values for hpsection,divid,action,pageno,section,categories
function BuildPluckSocialArticle(articlekey,hpsection,divid,action,pageno,pageurl,pagetitle,section,categories,contentType)
{
	var articleId;
	var objArticle;
	var objArticleNew;
	pageurl = baseURL + pageurl;
	
	//variables for hpsection,divid,action,pageno,section,categories
	var arr_hpSection = new Array();
	var arr_divid = new Array();
	var arr_action = new Array();
	var arr_categories = new Array();	
	
	//flag to determine if the article key already exists or not.
	var articleFound = false;	
	
	//check if 	PluckSocialArticle has any article keys			
	if(PluckSocialArticle.length>0)
	{
		for(i=0;i<PluckSocialArticle.length;i++)
		{
			objArticle = PluckSocialArticle[i];
			articleId = objArticle.ArticleKey;
			
			//If the article Key exists
			if(articlekey == articleId)
			{	
				//set the flag to true
				articleFound = true;
				
				//get the hpsection,divid,action,pageno,section,categories arrays for this PluckSocialArticle instance
				arr_hpSection = objArticle.HPSection;
				arr_divid = objArticle.Divid;
				arr_action = objArticle.Action;
				arr_categories = objArticle.Categories;
				
				//update the arrays 
				arr_hpSection.push(hpsection);
				arr_divid.push(divid);
				arr_action.push(action);
													
				//Create the fnPluckSocialArticle object 
				objArticleNew = new fnPluckSocialArticle(articlekey,arr_hpSection,arr_divid,arr_action,pageno,pageurl,pagetitle,section,arr_categories,contentType);
				//Update the PluckSocialArticle instance with the above created new object
				PluckSocialArticle[i] = objArticleNew;							
			}
		}
		
		if(articleFound == false) //This articleKey does not exist
		{
			//Build the hpsection,divid,action,pageno,section,categories arrays
						
			arr_hpSection.push(hpsection);
			arr_divid.push(divid);
			arr_action.push(action);
			arr_categories.push(categories);
			
			//Create the fnPluckSocialArticle object & push it to PluckSocialArticle
			var objPluckSocialArticle = new fnPluckSocialArticle(articlekey,arr_hpSection,arr_divid,arr_action,pageno,pageurl,pagetitle,section,arr_categories,contentType);
			PluckSocialArticle.push(objPluckSocialArticle);
			
		}
	}
	else //this is the first initialization for PluckSocialArticle
	{
		//Build the hpsection,divid,action,pageno,section,categories arrays		
		arr_hpSection.push(hpsection);
		arr_divid.push(divid);
		arr_action.push(action);
		arr_categories.push(categories);
		
		//Create the fnPluckSocialArticle object & push it to PluckSocialArticle
		var objPluckSocialArticle = new fnPluckSocialArticle(articlekey,arr_hpSection,arr_divid,arr_action,pageno,pageurl,pagetitle,section,arr_categories,contentType);
		PluckSocialArticle.push(objPluckSocialArticle);
	}
}

function fnPluckDiscoverContent(section,categories,contributors,activity,contentType,age,numberOfDiscoveries,component,textTrimLength)
{
	this.Section = section;
	this.Categories = categories;
	this.Contributors = contributors;
	this.Activity = activity;
	this.ContentType = contentType;
	this.Age = age;
	this.NumberOfDiscoveries = numberOfDiscoveries;
	this.Component = component;
	this.TextTrimLength=textTrimLength;
}

function BuildPluckDiscoverContent(section,categories,contributors,activity,contentType,age,numberOfDiscoveries,component,textTrimLength)
{
	if(section != '' && categories != '' && contributors != '' && age > 0)
	{ 
		var objPluckDiscoverContent = new fnPluckDiscoverContent(section,categories,contributors,activity,contentType,age,numberOfDiscoveries,component,textTrimLength);
		PluckDiscoverContent.push(objPluckDiscoverContent);
	}
}

//----------------------------------start function is called for attaching function onload of body tag ----------------------
  addLoadListener(getArticleAction);
//----------------------------------- end function -------------------------------------------------------------------------------------
 
//This is called on page load. This makes a batch request for all the article keys present in PluckSocialArticle
function getArticleAction()
{
	var objPluckSocialArticle;
	var objPluckDiscoverContent;
	var objRequestKey;
	// clearing the request array     
    requests = [];	
	//requestBatch = new RequestBatch();	
	for(i=0;i<PluckSocialArticle.length;i++)
	{
		objPluckSocialArticle = PluckSocialArticle[i];
		//based on the content type build the appropriate object
		switch(objPluckSocialArticle.ContentType)
		{
			case "article":			
			objRequestKey = new ArticleKey(objPluckSocialArticle.ArticleKey);
			break;
			
			case "user":
			objRequestKey = new UserKey(objPluckSocialArticle.ArticleKey);
			break;
						
			case "comment":
			//we receive the id as "id:review". So split this & pass the exact id.
			var key1 = objPluckSocialArticle.ArticleKey.split(":")[0].toString();
			var articleKey = new ArticleKey(key1);
			objRequestKey = new CommentPage(articleKey,commentsPerPage,commentPageNo,commentSortOrder);
			break;
						
			case "review":
			//we receive the id as "id:review". So split this & pass the exact id.
			var key = objPluckSocialArticle.ArticleKey.split(":")[0].toString();
			var articleKey = new ArticleKey(key);
			//var articleKey = new ArticleKey(objPluckSocialArticle.ArticleKey); Jyothi: Original
			objRequestKey = new ReviewPage(articleKey,reviewsPerPage,reviewPageNo,reviewSortOrder);
			break;
						
			case "gallery":
			objRequestKey = new GalleryKey(objPluckSocialArticle.ArticleKey);
			break;
			
			case "photo":
			objRequestKey = new PhotoKey(objPluckSocialArticle.ArticleKey);
			break;
			
			case "video":
			objRequestKey = new VideoKey(objPluckSocialArticle.ArticleKey);
			break;
		}
		//push it into the requests array
		requests.push(objRequestKey);
		//requestBatch.AddToRequest(objRequestKey);		
	}
	var j;
	for(j=0;j<PluckDiscoverContent.length;j++)
	{
		var intermediateArray = new Array();
			
		objPluckDiscoverContent = PluckDiscoverContent[j];
		
		var searchSections = new Array(); 
		intermediateArray = objPluckDiscoverContent.Section.split(',');		
		for(k=0;k<intermediateArray.length;k++)
		{
			 searchSections[k] = new Section(intermediateArray[k]); 	
		}		       
  
        var searchCategories = new Array();
        intermediateArray = objPluckDiscoverContent.Categories.split(',');		
        for(k=0;k<intermediateArray.length;k++)
		{
			 searchCategories[k] = new Category(intermediateArray[k]); 	
		}   
          
        var activityDisco = new Activity(objPluckDiscoverContent.Activity);   
        var contentType = new ContentType(objPluckDiscoverContent.ContentType);   
        
        var limitToContributorsDisco = new Array();  
        intermediateArray = objPluckDiscoverContent.Contributors.split(',');	
         for(k=0;k<intermediateArray.length;k++)
		{
			 limitToContributorsDisco[k] = new UserTier(intermediateArray[k]); 	
		}	          
         
        var age = objPluckDiscoverContent.Age;  
        var maximumNumberOfDiscoveries = objPluckDiscoverContent.NumberOfDiscoveries;  
        var discoveryAction = new DiscoverContentAction(   
            searchSections,   
            searchCategories,   
            limitToContributorsDisco,   
            activityDisco,   
            contentType,   
            age,   
            maximumNumberOfDiscoveries);   
  
          //requestBatch.AddToRequest(discoveryAction);  
		//push it into the requests array
        requests.push(discoveryAction);  
	}
	
	//check if there are any requests to process
	if(requests.length > 0)
	{
		//requestBatch.BeginRequest(serverUrl, renderwidgetsCallback);
		startRequestProcess();
	}
}
function startRequestProcess()
{
	requestBatch = null;
	
	var totalRequestBatches;
	//if requests length is less than maxRequestsPerBatch then we need only one request batch
	if(parseInt(requests.length) < maxRequestsPerBatch)
	{
		totalRequestBatches = 1;
	}
	else if(parseInt(parseInt(requests.length)%parseInt(maxRequestsPerBatch)) == 0)
	{		
		totalRequestBatches = Math.floor(parseInt(requests.length)/parseInt(maxRequestsPerBatch));
	}
	else
	{
		totalRequestBatches = Math.floor(parseInt(requests.length)/parseInt(maxRequestsPerBatch)) + 1;
	}
		
	var iteration = 0;
	var i = 0;
	var boolEnd = false;
	
	//traverse for the desired no of iterations
	while(iteration < totalRequestBatches)
	{
		//start the request batch
		requestBatch = new RequestBatch();
		//add max requests to the request batch
		for(var j=0;j<maxRequestsPerBatch;j++)
		{
			if(i<requests.length)
			{
				requestBatch.AddToRequest(requests[i]);
				i++;
			}
			else
			{
				boolEnd = true;
				break;
			}
		}
		//begin the request batch
		requestBatch.BeginRequest(serverUrl, renderwidgetsCallback);
		//nullify the request batch so that we can batch the next set of requests
		requestBatch = null;
		//increment th eiteration count
		iteration = iteration + 1;
	}
	
}

function renderwidgetsCallback(responseBatch)
{		
	if (responseBatch.Responses.length == 0) 
	{	
    } 
    else
    {		    
		var responseObject;
		var responseKey;
		var isDiscoveryContent = false;
		var objPluckSocialArticle;
		var arr_Action = new Array();
		var i;
				
		//Traverse through each response 		
		for(i=0;i<responseBatch.Responses.length;i++)
		{
			if(responseBatch.Responses[i].Article != null)
			{
				responseKey = responseBatch.Responses[i].Article.ArticleKey.Key;					
			}
			else if (responseBatch.Responses[i].Comment != null)
			{
				responseKey = responseBatch.Responses[i].Comment.CommentKey.Key;						
			}
			else if(responseBatch.Responses[i].Review != null)
			{
				responseKey = responseBatch.Responses[i].Review.ReviewKey.Key;							
			}
			else if(responseBatch.Responses[i].User != null)
			{
				responseKey = responseBatch.Responses[i].User.UserKey.Key;				
			}
			else if(responseBatch.Responses[i].CommentPage != null)
			{
				responseKey = responseBatch.Responses[i].CommentPage.ArticleKey.Key;					
				//we need to add ":comment" to this id.
				responseKey = responseKey + ":comment";	//Jyothi					
			}
			else if(responseBatch.Responses[i].ReviewPage != null)
			{
				responseKey = responseBatch.Responses[i].ReviewPage.ArticleKey.Key;
				//we need to add ":review" to this id.
				responseKey = responseKey + ":review";	//Jyothi					
			} 
			else if(responseBatch.Responses[i].DiscoverContentAction != null)
			{
				isDiscoveryContent = true;
				var j;
				var DiscoverContentActionResponse = responseBatch.Responses[i].DiscoverContentAction;				
				for(j=0;j<PluckDiscoverContent.length;j++)
				{
					var objPluckDiscoverContent= PluckDiscoverContent[j];
					//try to match the section,categories,activity with the response properties so that we can determine which DiscoveryContent we received
					if(IsDiscoveryContentArticle(objPluckDiscoverContent,DiscoverContentActionResponse))
					{ 
						//call the appropriate function to render the content
						switch(discoveryWidget)											
						{							
							case "TopActiveFans":
							TopActiveFans(DiscoverContentActionResponse);
							break;
							case "FanMovieRating":
							FanMovieRating(DiscoverContentActionResponse,objPluckDiscoverContent.TextTrimLength);
							break;							
							case "RecentDiscussions":							
							RecentDiscussions(DiscoverContentActionResponse,objPluckDiscoverContent.TextTrimLength);
							break;
							case "RecentBlogPost":							
							RecentBlogPost(DiscoverContentActionResponse,objPluckDiscoverContent.TextTrimLength);
							break;
							case "RecentPhotos":							
							RecentPhotos(DiscoverContentActionResponse,objPluckDiscoverContent.TextTrimLength);
							break;
							case "MostRecommendedPhoto":
							MostRecommendedPhoto(DiscoverContentActionResponse,objPluckDiscoverContent.TextTrimLength);
							break;							
						}
						discoveryWidget="";
						//break;
					}
					else
					{
						TemporaryNoData(discoveryWidgetComponent);
					}
				}
			}						
			else
			{
				responseKey = 0;
			}
			if(responseKey != 0 && isDiscoveryContent == false)
			{
				var k;
				for(k=0;k<PluckSocialArticle.length;k++)
				{
					if(PluckSocialArticle[k].ArticleKey == responseKey)
					{
						objPluckSocialArticle = PluckSocialArticle[k];
					
						break;
					}
				}
						
				//check what is the content type so that appropriate object can be fetched form response
							
				switch(objPluckSocialArticle.ContentType)
				{
					case "article":			
					responseObject = responseBatch.Responses[i].Article;
									
					//make the IsUpdateArticle true if no.of recommendations, comments, reviews & ratings for the article are 0
					if(responseObject.Recommendations.NumberOfRecommendations == 0 && responseObject.Ratings.NumberOfRatings == 0 && responseObject.Comments.NumberOfComments == 0 && responseObject.Reviews.NumberOfReviews == 0)
					{
						objPluckSocialArticle.IsUpdateArticle = true;
					}	
					else
					{
						objPluckSocialArticle.IsUpdateArticle = false;
					}								
					break;				
					case "user":
					responseObject = responseBatch.Responses[i].User;
					break;
					
					case "comment":
					responseObject = responseBatch.Responses[i].CommentPage;
					break;				
					
					case "review":
					responseObject = responseBatch.Responses[i].ReviewPage;
					break;
									
					case "gallery":
					responseObject = responseBatch.Responses[i].Gallery;
					break;
					
					case "photo":
					responseObject = responseBatch.Responses[i].Photo;
					break;
					
					case "video":
					responseObject = responseBatch.Responses[i].Video;
					break;
				}			
							
				arr_Action= objPluckSocialArticle.Action;
				//Traverse through each action for this article & call appropriate methods
				for(j=0;j<arr_Action.length;j++)
				{	
					switch(arr_Action[j])
					{
						case "Recommend":
						renderRecommend(responseObject,k,j,objPluckSocialArticle.ContentType);
						break;
						case "Rating":
						renderRating(responseObject,k,j,objPluckSocialArticle.ContentType);
						break;
						case "commentsCounter":
						renderCommentsCounter(responseObject,k,j);
						break;	
						case "reviewPage":
						renderReviewPage(responseObject);
						break;				
						case "commentPage":	
						renderCommentPage(responseObject);
						break;				
					}				
				}
			}			
		}
		requestBatch = null;
    }
}

function IsDiscoveryContentArticle(objPluckDiscoverContent,DiscoverContentActionResponse)
{		
	var IsObjectFound=false;
	discoveryWidgetComponent="";
	if(objPluckDiscoverContent.Section.toLowerCase() == DiscoverContentActionResponse.SearchSections[0].Name.toLowerCase() && objPluckDiscoverContent.Categories.toLowerCase() == DiscoverContentActionResponse.SearchCategories[0].Name.toLowerCase() && objPluckDiscoverContent.Activity.toLowerCase() == DiscoverContentActionResponse.Activity.Name.toLowerCase())
	{	
		var InnerObject = DiscoverContentActionResponse.DiscoveredContent[0];	
		if (InnerObject instanceof Object)
		{
					if (typeof InnerObject.PhotoKey != "undefined")
					{
						if(InnerObject.PhotoKey.Key != null) { discoveryWidget = "RecentPhotos"; IsObjectFound=true;}
					}
					else if(typeof InnerObject.BlogKey != "undefined")
					{
						if(InnerObject.BlogKey.Key != null) { discoveryWidget = "RecentBlogPost"; IsObjectFound=true;}
					}
					else if(typeof InnerObject.ForumDiscussionKey != "undefined")
					{
						if(InnerObject.ForumDiscussionKey.Key != null) 
						{	discoveryWidget = "RecentDiscussions"; 	IsObjectFound=true; }
					}
					else if(typeof InnerObject.PersonaPrivacyMode != "undefined")
					{
						if(InnerObject.PersonaPrivacyMode != null) { discoveryWidget = "TopActiveFans"; IsObjectFound=true;}
					}
					else if(typeof InnerObject.Section.Name != "undefined")
					{
						if(DiscoverContentActionResponse.Activity.Name != null)
						{
							if(DiscoverContentActionResponse.Activity.Name =="Rated" && InnerObject.Section.Name=="film")
							{ 	discoveryWidget = "FanMovieRating";  IsObjectFound=true;		}
							else if(DiscoverContentActionResponse.Activity.Name =="Recommended" && InnerObject.Section.Name=="image")
							{  discoveryWidget = "MostRecommendedPhoto";  IsObjectFound=true; } 
						}
					}					
		}		
		//return true;		
		if(discoverywidgetsCheckIsFilled(objPluckDiscoverContent.Component)==false) 
		{ 
			discoveryWidgetComponent=objPluckDiscoverContent.Component;
		}
		else
		{
			discoveryWidgetComponent="";		
		}
		
		if(IsObjectFound==true && objPluckDiscoverContent.Component==discoveryWidget) 
		{
			 discoverywidgetIsFilled.push(objPluckDiscoverContent.Component);  return true;
		}
	}
	else
	{
		if(discoverywidgetsCheckIsFilled(objPluckDiscoverContent.Component)==false) { 
			discoveryWidgetComponent=objPluckDiscoverContent.Component;		
		}
		else
		{
			discoveryWidgetComponent="";		
		}
		return false;
	}
}
   
function discoverywidgetsCheckIsFilled(discoverywidgetname)
{
	var widgetsAlreadyFilled=false;
	for(j=0;j<discoverywidgetIsFilled.length;j++)
	{	
		if(discoverywidgetIsFilled[j]==discoverywidgetname)
		{
			widgetsAlreadyFilled=true;
			break;
		}
	}						
	if(widgetsAlreadyFilled==true) { return true; }
	else { return false; }
}   
    
function renderRecommend(responseObject,artcleIndex,actionIndex,contentType)
{
	var objArticle = PluckSocialArticle[artcleIndex];
	var action = objArticle.Action[actionIndex];	
	var ele = document.getElementById(objArticle.Divid[actionIndex]);
	if(ele != null)
	{	
		//check content type & appropriatley build the html & update page elements            
		switch(contentType)
		{
			case "article":					
				if(responseObject.Recommendations.CurrentUserHasRecommended == "False")
				{
					ele.innerHTML='Recommend';					
					ele.className ='SiteLife_Recommend';			
					//added for To show Seperate Recommend Counter
					var recommendCounterspan = document.getElementById("span_"+ objArticle.Divid[actionIndex]);							
					if (recommendCounterspan !=null)
					{
						recommendCounterspan.innerHTML='(' + responseObject.Recommendations.NumberOfRecommendations  + ')';	
					}
				}
				else
				{	
					ele = document.getElementById("recommend_"+ objArticle.Divid[actionIndex]);					
					ele.innerHTML ='Recommended';
					ele.className ='SiteLife_Recommended';	
					//added for To show Seperate Recommend Counter
					var recommendspan = document.createElement('span');										
					recommendspan.innerHTML='(' + responseObject.Recommendations.NumberOfRecommendations  + ')';
					ele.appendChild(recommendspan);
					
				}	
			break;
			
			case "user":
				ele.innerHTML ='Recommended ('+ responseObject.NumberOfRecommendations + ')';
			break;
			
			case "comment":
			case "review":
			case "gallery":
			case "photo":
			case "video":
				if(responseObject.CurrentUserHasRecommended == "False")
				{
					ele.innerHTML ='Recommend ('+ responseObject.NumberOfRecommendations + ')';
				}
				else
				{
					ele.innerHTML ='Recommended ('+ responseObject.NumberOfRecommendations + ')';
				}	
			break;		
		}
		// update page elements
			 	
	}
}

function renderRating(responseObject,artcleIndex,actionIndex,contentType)
{
	var objArticle = PluckSocialArticle[artcleIndex];
	var action = objArticle.Action[actionIndex];
	var Rating;
	var eleAvg = document.getElementById(objArticle.Divid[actionIndex]+ "_avg");
	var eleNoAvg = document.getElementById(objArticle.Divid[actionIndex]+ "_noavg");
	var eleUser = document.getElementById(objArticle.Divid[actionIndex]+ "_user");
		
	if(eleAvg != null)//Display average rating
	{	
		//check content type & appropriatley build the html & update page elements    		   
		switch(contentType)
		{
			case "article":				
				
				Rating = Math.ceil(responseObject.Ratings.AverageRating - .5);										
		
				if(Rating==0)
				{
					//eleAvg.innerHTML="<img src='http://pratima.hollywood.com/images/users_0.gif'/>";
					//eleAvg.innerHTML="<img src='" + imagePath + "users_0.gif'/>";					
					if(eleNoAvg!=null)
					{
						//eleNoAvg.innerHTML="<img src='" + imagePath + "users_0.gif'/>";
						eleNoAvg.style.display="block";
						
						eleAvg.style.display="none";
					}
				}
				else
				{
					eleNoAvg.style.display="none";
						
					eleAvg.style.display="block";
					
					var eleMainDiv = document.getElementById(objArticle.Divid[actionIndex]+ "_MainDiv");
					var mainDivClass = document.getElementById(objArticle.Divid[actionIndex]+ "_class");
					
					if(eleMainDiv!=null && mainDivClass!=null)
					{
						eleMainDiv.className = mainDivClass.value;
					}
						
					DefaultRate(objArticle.Divid[actionIndex],'' + responseObject.ArticleKey.Key  + '_StarsImageAvg',Rating);
				}
				//set the hidden variable
				var totalRatingsCount = document.getElementById(objArticle.Divid[actionIndex]+ "_TotalNumberOfRatings");
				var averageRating = document.getElementById(objArticle.Divid[actionIndex]+ "_AverageRating");
				
				if(totalRatingsCount != null)
				{
					if(responseObject.Ratings.NumberOfRatings != "")
					{
						totalRatingsCount.value = responseObject.Ratings.NumberOfRatings;
					}
					else
					{
						totalRatingsCount.value = 0;
					}
				}
				if(averageRating!=null)
				{
					if(isNaN(parseInt(responseObject.Ratings.AverageRating)))
					{
						averageRating.value = 0;
					}
					else
					{
						averageRating.value = responseObject.Ratings.AverageRating;						
					}
				}	
														
			break;			
		}				 	
	}
	if(eleUser != null) //dispaly user rating
	{
		//check content type & appropriatley build the html & update page elements    
		switch(contentType)
		{		   
			case "article":	
				//get the hidden variable elements for total no of ratings & average rating
				//Update the hidden variable values 
				
				
				if(responseObject.Ratings.CurrentUserRating == 0)
				{
					//ele.innerHTML = 'Average Rating:' + responseObject.Ratings.AverageRating;
					Rating = 0;										
					DefaultRate(objArticle.Divid[actionIndex],'' + responseObject.ArticleKey.Key  + '_StarsImage',Rating);					
				}
				else
				{
					//ele.innerHTML = 'User Rating:' + responseObject.Ratings.CurrentUserRating;					
					Rating = Math.ceil(responseObject.Ratings.CurrentUserRating - .5);
					DefaultRate(objArticle.Divid[actionIndex],'' + responseObject.ArticleKey.Key  +'_StarsImage',Rating);
					AfterUserRated(objArticle.Divid[actionIndex]+ "_user",responseObject.ArticleKey.Key,Rating);	
				}	
			break;
		}
	}
}

function renderCommentsCounter(responseObject,artcleIndex,actionIndex)
{
	var objArticle = PluckSocialArticle[artcleIndex];
	var action = objArticle.Action[actionIndex];
		
	var ele = document.getElementById(objArticle.Divid[actionIndex]);
	if(ele != null)
	{	                
		// update page elements			
		var eleanchor = document.getElementById("span_" + objArticle.Divid[actionIndex]);			
		if(eleanchor!=null)
		{
			eleanchor.innerHTML='(' + responseObject.Comments.NumberOfComments + ')';	
		}	
	}
}

// TOP ACTIVE FANS 
function TopActiveFans(DiscoverContentActionResponse)
{	
	var ele = document.getElementById("TopActiveFans");
	ele.className="pl08 pr08";
	if(ele!=null)
	{
		ele.innerHTML="";
		var html="";
		for (var i = 0; i < DiscoverContentActionResponse.DiscoveredContent.length; i++) 
		{
			var FanData = DiscoverContentActionResponse.DiscoveredContent[i];
			if (FanData != null)
			{
				if (i%3==0 || i==0)
				{
					var div1 = document.createElement('div');
					div1.className="pt20";
				}
				var div2 = document.createElement('div');
				div2.className="fll pl05";
				html='<a href="' + baseURL + '/MyHollywood/UserProfile/?UserId=' + FanData.UserKey.Key + '">';
				html +='<img id="" src="' + FanData.AvatarPhotoUrl + '" alt="' + FanData.DisplayName + '" title="' + FanData.DisplayName + '" width="37" height="32" class="bo0">';
				html +='</a>';
				div2.innerHTML=html;				
				div1.appendChild(div2);				
				if ((i+1)%3==0)
				{
					var divBR= document.createElement('br');
					divBR.clear="all";
					div1.appendChild(divBR);
				}
				ele.appendChild(div1);
			}			
		}
	}
}

// FAN MOVIE RATING 
function FanMovieRating(DiscoverContentActionResponse,textlength)
{
	var ele = document.getElementById("litFanMovieRating");
	if(ele!=null)
	{
		ele.innerHTML="";
		for (var i = 0; i < DiscoverContentActionResponse.DiscoveredContent.length; i++) 
		{
			var MovieData = DiscoverContentActionResponse.DiscoveredContent[i];
			if (MovieData != null)
			{
				var div1 = document.createElement('div');
				if(i==0)
				{
				  div1.className="bc06 pl05 hp100";
				}
				else
				{
				  div1.className="pt10";
				}
								
				var divcount = document.createElement('div');
				divcount.className="fll fs12 b";
				divcount.innerHTML=i+1;
				
				var div3 = document.createElement('div');
				div3.className="tal fll pl10 w275";
				
				var div4 = document.createElement('div');
				div4.className="fs12 b";
				
				var PTanchor = document.createElement('a');
				PTanchor.href=MovieData.PageUrl; 
				PTanchor.innerHTML =textTrimming(MovieData.PageTitle,textlength);
				div4.appendChild(PTanchor);
				
				var divRating = document.createElement('div');				
				divRating.className="pt05 ratenoborder w130 tal fs12 b fll";
				var ratecount=parseInt(MovieData.Ratings.AverageRating,0);				
				// this will add RedStar Images 				           
				for (var imgCntr=1; imgCntr<=ratecount; imgCntr++) {					
					var imageR= document.createElement('img');
					imageR.border=0;
					imageR.src= imagePath + 'RedStar_sel.gif';					
					divRating.appendChild(imageR);
					divRating.appendChild(imageR);
				}
				// this will add Gray Images 	
				for ( imgCntr = (parseInt(ratecount,0) + 1); imgCntr <= 5 ; imgCntr++ ){ 
					var imageG= document.createElement('img');
					imageG.border=0;
					imageG.src= imagePath + 'star_unsel.gif';					
					divRating.appendChild(imageG);				
				}
					
				var divRatingspan = document.createElement('div');	
				divRatingspan.className="fll pt08 fs12";
						
				var ratespan = document.createElement('span');				
				ratespan.innerHTML='(' + MovieData.Ratings.NumberOfRatings  + ')';					
				divRatingspan.appendChild(ratespan);
					
				var ratespanbr = document.createElement('br');
				ratespanbr.clear="all";	
				
				var div5 = document.createElement('div');
				div5.className="pt05 fs11";
				
				var html="";
				html +='<div class="fll"><a href="/movies/movie_showtimes.aspx?id=' + MovieData.ArticleKey.Key + '">Showtimes</a></div>'
				html +='<div class="fll pl05 pr05">&#8226;</div>'
				html +='<div class="fll"><a href="/movies/movie_showtimes.aspx?id=' + MovieData.ArticleKey.Key + '">Tickets</a></div>'
				html +='<br clear="all" />'
                div5.innerHTML=html;
				
				var divLink = document.createElement('div');
				divLink.className="pt05 fs11";
				
				html='';
				html +='<div class="pt02">';
				html +='<div class="fll"><a href="/MyHollywood/Movie/Reviews/' + MovieData.ArticleKey.Key + '">See Reviews</a></div>';
				html +='<div class="fll pl05 pr05">&#8226;</div>';
				html +='<div class="fll w110"><a href="/MyHollywood/Movie/Reviews/' + MovieData.ArticleKey.Key + '">Write your Reviews</a></div>';
				html +='<br clear="all" />';
				html +='</div>';
				divLink.innerHTML=html;
				
				var divComment =document.createElement('div');
				divComment.className="pt02 fs11";
				html='';
				html +='<a class="pluckCommentCntr" href="' + MovieData.PageUrl + '">Comments</a>';														
				html +='<span class="blueCounter"> ('+ MovieData.Comments.NumberOfComments + ')</span>';
				//html +='<br clear="all" />';				
				divComment.innerHTML=html;
				
				div3.appendChild(div4);
				div3.appendChild(divRating);
				div3.appendChild(divRatingspan);
				div3.appendChild(ratespanbr);
				div3.appendChild(div5);
				div3.appendChild(divLink);
				
				div3.appendChild(divComment);
				
				div1.appendChild(divcount);								
				div1.appendChild(div3);				
				
				var breakbr =document.createElement('br');
				breakbr.clear="all";
				div1.appendChild(breakbr);
				
				if(i==0)
				{
				  var divTopCurve = document.createElement('div');
				  var divBottomCurve = document.createElement('div');
				  
				  divTopCurve.className="pt10";
				  
				  html='';
				  html +='<img src="' + imagePath + 'fan_rat_top_cur.gif"/>';														
				  divTopCurve.innerHTML=html;
				
				  html='';
				  html +='<img src="' + imagePath + 'fan_rat_bot_cur.gif"/>';														
				  divBottomCurve.innerHTML=html;
				    
				  ele.appendChild(divTopCurve);
				  ele.appendChild(div1);
				  ele.appendChild(divBottomCurve);
				}
				else
				{
				  ele.appendChild(div1);
				}
			}
		}				
		
	}
}


// THIS FUNCTION IS USED TO DISPLAY DATA TEMPERARY NOT AVAILABLE 
function TemporaryNoData(Discoverwidgetsname)
{
	var ele;
	switch(Discoverwidgetsname)											
	{							
		case "TopActiveFans":
			ele = document.getElementById("TopActiveFans");
			break;
		case "FanMovieRating":
			ele = document.getElementById("litFanMovieRating");
			break;		
		case "RecentDiscussions":
			ele = document.getElementById("recentDiscussionContent");
			break;
		case "RecentBlogPost":
			ele = document.getElementById("recentBlogPostContent");
			break;
		case "RecentPhotos":
			ele = document.getElementById("recentPhotosContent");
			break;							
		case "MostRecommendedPhoto":
			ele=document.getElementById("recommendedPhotosContent");
			break;
	}
	
	if(ele!=null)
	{
		var html="";
		html +='<div class="pt10 pl10 fs11">';
		html +='Data temporarily unavailable';
		html +='</div>'; 
		ele.innerHTML=html;
	}	
}

// RECENT DISCUSSION FORUMS POSTS
function RecentDiscussions(DiscoverContentActionResponse,textlength)
{
	var ele = document.getElementById("recentDiscussionContent");	
	if(ele!=null)
	{
		var html="";
		html +='<div id="Summary_Container" class="Summary_Container">';
		html +='<div style="display: inline;">';
		html +='<div class="Summary_Container">'; 
		
		for (var i = 0; i < DiscoverContentActionResponse.DiscoveredContent.length; i++) 
		{
				var DiscussionData = DiscoverContentActionResponse.DiscoveredContent[i];
				if (DiscussionData != null)
				{	    
					if(i%2==0)
						{	
							html +='<div class="Summary_ForumsContainer">';              
							html +='<div class="Summary_ForumsTitle">';                
							html +='<a href="' + DiscussionData.DiscussionUrl +'">' + textTrimming(DiscussionData.DiscussionTitle,textlength) + '</a>';            
							html +='</div>';            
							html +='<div class="Summary_ForumsIn">In: ';
							html +='<a href="/Forums/Home.aspx?plckForumPage=Forum&plckForumId=' + DiscussionData.ForumKey.Key + '">Fourms</a>';                                            
							html +='</div>';      
							html +='</div>'; 
						}
						else
						{
							// for alternate color  
							html +='<div class="Summary_ForumsContainer Summary_ForumsAltColor">';              
							html +='<div class="Summary_ForumsTitle">';                
							html +='<a href="' + DiscussionData.DiscussionUrl +'">' + textTrimming(DiscussionData.DiscussionTitle,textlength) + '</a>';            
							html +='</div>';            
							html +='<div class="Summary_ForumsIn">In: ';
							html +='<a href="/Forums/Home.aspx?plckForumPage=Forum&plckForumId=' + DiscussionData.ForumKey.Key + '">Fourms</a>';                                            
							html +='</div>';      
							html +='</div>'; 
						}				
				}
		}
		html +='</div></div></div>';	
		ele.innerHTML=html;
	}
	
}

// RECENT BLOG POST
function RecentBlogPost(DiscoverContentActionResponse,textlength)
{
	var ele = document.getElementById("recentBlogPostContent");
	if(ele!=null)
	{
		var html="";
		html +='<div id="Summary_Container1" class="Summary_Container1">';
		html +='<div style="display: inline;">';
		html +='<div class="Summary_Container">';    
		html +='<table class="Summary_BlogTable" cellpadding="0" cellspacing="0">';    		        	            
		html +='<tbody>';
		
		for (var i = 0; i < DiscoverContentActionResponse.DiscoveredContent.length; i++) 
		{
				var RecentBlogData = DiscoverContentActionResponse.DiscoveredContent[i];
				if (RecentBlogData != null)
					{
						if(i%2==0)
						{
								html +='<tr>';                
								html +='<td class="Summary_BlogTableLeft">';                                                                            
								html +='<a href="/MyHollywood/UserProfile/?UserId=' + RecentBlogData.PostAuthor.UserKey.Key + '&plckUserId=' + RecentBlogData.PostAuthor.UserKey.Key + '" onclick="">';
								html +='<img id="" src="' + RecentBlogData.PostAuthor.AvatarPhotoUrl + '" alt="" class="PluckUserAvatar">';
								html +='</a>';            
								html +='</td>';        
								html +='<td class="Summary_BlogTableRight">';            
								html +='<div class="Summary_BlogTitle">';                                    
								html +='<a href="' + RecentBlogData.Url + '">' + textTrimming(RecentBlogData.PostTitle,textlength) + '</a>';                            
								html +='</div>';                        
								html +='<div class="Summary_BlogBy"><span>By </span>'; 
								html +='<a id="" href="/MyHollywood/UserProfile/?UserId=' + RecentBlogData.PostAuthor.UserKey.Key + '&plckUserId=' + RecentBlogData.PostAuthor.UserKey.Key + '" target="_parent">'  + RecentBlogData.PostAuthor.DisplayName + '</a>:';                                            
								html +='</div>';            
								html +='<div class="Summary_BlogTime">' + RecentBlogData.PostDate + ' ' +  discoveryTimeZone + '</div>';        
								html +='</td>';     
								html +='</tr>'; 
						}
						else
						{
						
								html +='<tr class="Summary_BlogAltTRColor">';                							               
								html +='<td class="Summary_BlogTableLeft">';                                                                            
								html +='<a href="/MyHollywood/UserProfile/?UserId=' + RecentBlogData.PostAuthor.UserKey.Key + '&plckUserId=' + RecentBlogData.PostAuthor.UserKey.Key + '" onclick="">';
								html +='<img id="" src="' + RecentBlogData.PostAuthor.AvatarPhotoUrl + '" alt="" class="PluckUserAvatar">';
								html +='</a>';            
								html +='</td>';        
								html +='<td class="Summary_BlogTableRight">';            
								html +='<div class="Summary_BlogTitle">';                                    
								html +='<a href="' + RecentBlogData.Url + '">' + textTrimming(RecentBlogData.PostTitle,textlength) + '</a>';                            
								html +='</div>';                        
								html +='<div class="Summary_BlogBy"><span>By </span>'; 
								html +='<a id="" href="/MyHollywood/UserProfile/?UserId=' + RecentBlogData.PostAuthor.UserKey.Key + '&plckUserId=' + RecentBlogData.PostAuthor.UserKey.Key + '" target="_parent">'  + RecentBlogData.PostAuthor.DisplayName + '</a>:';                                            
								html +='</div>';            
								html +='<div class="Summary_BlogTime">' + RecentBlogData.PostDate + ' ' + discoveryTimeZone + '</div>';          								      
								html +='</td>';     
								html +='</tr>'; 
						}		
					}
		}
		html +='</tbody></table></div></div></div>';
		ele.innerHTML=html;
	}
}

// RECENT PHOTOS
function RecentPhotos(DiscoverContentActionResponse,textlength)
{
		var ele = document.getElementById("recentPhotosContent");
		if(ele!=null)
		{
			var html="";
			html +='<div id="Summary_Container" class="Summary_Container">';
			html +='<div style="display: inline;">';
			html +='<div class="Summary_Container">';
			html +='<table class="Summary_PhotoTable" cellpadding="0" cellspacing="0">';
			html +='<tbody>';
			
			for (var i = 0; i < DiscoverContentActionResponse.DiscoveredContent.length; i++) 
			{
				var UserPhotoData = DiscoverContentActionResponse.DiscoveredContent[i];
					if (UserPhotoData != null)
					{
						if(i%2==0)
						{
							html +='<tr>';        
							html +='<td class="Summary_PhotoTableLeft">';                                                    
							html +='<a href="' + UserPhotoData.PhotoUrl + '">';           
							html +='<img src="' + UserPhotoData.Image.Small + '">';                
							html +='</a>';                    
							html +='</td>';        
							html +='<td class="Summary_PhotoTableRight">';            
							html +='<div class="Summary_PhotoTitle">';                                    
							html +='<a href="' + UserPhotoData.PhotoUrl + '"> ' + textTrimming(UserPhotoData.Title,textlength) + '</a>';                            
							html +='</div>';            
							html +='<div class="Summary_PhotoIn">In: ';                                    
							html +='<a href="/MyHollywood/UserProfile/?UserId=' + UserPhotoData.Author.UserKey.Key + '&plckUserId=' + UserPhotoData.Author.UserKey.Key + '&plckPersonaPage=PersonaGallery&plckGalleryID=' + UserPhotoData.GalleryKey.Key + '">My Gallery</a>';
							html +='<br>';
							html +='</div>';
							html +='<div class="Summary_PhotoBy"> By: <a id="" href="/MyHollywood/UserProfile/?UserId=' + UserPhotoData.Author.UserKey.Key+ '&plckUserId=' + UserPhotoData.Author.UserKey.Key + '" target="_parent">'+ UserPhotoData.Author.DisplayName + '</a>';                                              
							html +='</div> ';       
							html +='</td>';     
							html +='</tr>';
						}
						else
						{
							html +='<tr class="Summary_PhotoAltTRColor">';        
							html +='<td class="Summary_PhotoTableLeft">';                                                    
							html +='<a href="' + UserPhotoData.PhotoUrl + '">';           
							html +='<img src="' + UserPhotoData.Image.Small + '">';                
							html +='</a>';                    
							html +='</td>';        
							html +='<td class="Summary_PhotoTableRight">';            
							html +='<div class="Summary_PhotoTitle">';                                    
							html +='<a href="' + UserPhotoData.PhotoUrl + '"> ' + textTrimming(UserPhotoData.Title,textlength) + '</a>';                            
							html +='</div>';            
							html +='<div class="Summary_PhotoIn">In: ';                                   
							html +='<a href="/MyHollywood/UserProfile/?UserId=' + UserPhotoData.Author.UserKey.Key + '&plckUserId=' + UserPhotoData.Author.UserKey.Key + '&plckPersonaPage=PersonaGallery&plckGalleryID=' + UserPhotoData.GalleryKey.Key + '">My Gallery</a>';
							html +='<br>';
							html +='</div>';
							html +='<div class="Summary_PhotoBy"> By: <a id="" href="/MyHollywood/UserProfile/?UserId=' + UserPhotoData.Author.UserKey.Key+ '&plckUserId=' + UserPhotoData.Author.UserKey.Key + '" target="_parent">'+ UserPhotoData.Author.DisplayName + '</a>';                                              
							html +='</div> ';       
							html +='</td>';     
							html +='</tr>';
						}
					}
			}//End FOR
			html +='</tbody></table></div></div></div>';
			ele.innerHTML=html;
		}
}
// MOST RECOMMENDED PHOTOS
function MostRecommendedPhoto(DiscoverContentActionResponse,textlength)
{
	var ele = document.getElementById("recommendedPhotosContent");
	if(ele!=null)
	{
		var html="";
		var dynamic_divId="";
		var dynamic_spanId="";	
		var recommendCtrlName="";			
		for (var i = 0; i < DiscoverContentActionResponse.DiscoveredContent.length; i++) 
		{
			var RecommendedPhotosData = DiscoverContentActionResponse.DiscoveredContent[i];
			if (RecommendedPhotosData != null)
			{
				recommendCtrlName='anchor_' + RecommendedPhotosData.ArticleKey.Key + '_UC_Pluck_MostRecommendedPhoto';
				dynamic_divId='recommend_anchor_' + RecommendedPhotosData.ArticleKey.Key + '_UC_Pluck_MostRecommendedPhoto';
				dynamic_spanId='span_anchor_' + RecommendedPhotosData.ArticleKey.Key + '_UC_Pluck_MostRecommendedPhoto';
				if(i%2==0)
				{	
					html +='<div class="pt08 pl05">';					
					html +='<div class="w150 pr05 fll">';
					html +='<div><a href="' + RecommendedPhotosData.PageUrl + '"><img src="' + ContentImagesPath + 'cms/143x124/' + RecommendedPhotosData.ArticleKey.Key + '.jpg" alt="' + RecommendedPhotosData.PageTitle + '" title="' + RecommendedPhotosData.PageTitle + '" width="143" height="124" class="bo0 boc00"></a></div>';
					html +='<div class="">';
					html +='<div class="fs12 b tc01 pt05 wp100"><a href="' + RecommendedPhotosData.PageUrl + '">' + textTrimming(RecommendedPhotosData.PageTitle,textlength) + '</a></div>';
					
					//recomend widget	checking whether current user has recommended or not
					if(RecommendedPhotosData.Recommendations.CurrentUserHasRecommended == "True")	
					{
						html +='<div id="'+ dynamic_divId + '" class="SiteLife_Recommended">Recommended';
						html +='<span>(' + RecommendedPhotosData.Recommendations.NumberOfRecommendations + ')</span>';
						html +='</div>';
					}
					else
					{			
						html +='<div id="'+ dynamic_divId + '">';
						html +='<a class="SiteLife_Recommend"  href="javascript:;" onclick="discoverContentRecommendAction(\'' + RecommendedPhotosData.ArticleKey.Key + '\',\'' + recommendCtrlName + '\');" >Recommend</a>';
						html +='<span id="' + dynamic_spanId + '" class="blueCounter"> (' + RecommendedPhotosData.Recommendations.NumberOfRecommendations + ')</span>';				
						html +='</div>';
					}
					
					// comments counter widget
					html +='<div class="pt05">';
					html +='<a class="pluckCommentCntr" href="' + RecommendedPhotosData.PageUrl + '">Comments</a>';														
					html +='<span class="blueCounter"> ('+ RecommendedPhotosData.Comments.NumberOfComments + ')</span>';	
					html +='</div>';
					html +='</div>';
					html +='</div>';
				}
				else
				{
					html +='<div class="w150 pl05 fll">';
					html +='<div><a href="' + RecommendedPhotosData.PageUrl + '"><img src="' + ContentImagesPath + 'cms/143x124/' + RecommendedPhotosData.ArticleKey.Key + '.jpg" alt="' + RecommendedPhotosData.PageTitle + '" title="' + RecommendedPhotosData.PageTitle + '" width="143" height="124" class="bo0 boc00"></a></div>';
					html +='<div class="">';
					html +='<div class="fs12 b tc01 pt05 wp100"><a href="' + RecommendedPhotosData.PageUrl + '">' + textTrimming(RecommendedPhotosData.PageTitle,textlength) + '</a></div>';
				
					//recomend widget	checking whether current user has recommended or not
					if(RecommendedPhotosData.Recommendations.CurrentUserHasRecommended == "True")	
					{
						html +='<div id="'+ dynamic_divId + '" class="SiteLife_Recommended">Recommended';
						html +='<span>(' + RecommendedPhotosData.Recommendations.NumberOfRecommendations + ')</span>';
						html +='</div>';
					}
					else
					{			
						html +='<div id="'+ dynamic_divId + '">';
						html +='<a  href="javascript:;"  class="SiteLife_Recommend" onclick="discoverContentRecommendAction(\'' + RecommendedPhotosData.ArticleKey.Key + '\',\'' + recommendCtrlName + '\');" >Recommend</a>';
						html +='<span id="' + dynamic_spanId + '" class="blueCounter"> (' + RecommendedPhotosData.Recommendations.NumberOfRecommendations + ')</span>';				
						html +='</div>';
					}
					
					// comments counter widget
					html +='<div class="pt05">';
					html +='<a class="pluckCommentCntr" href="' + RecommendedPhotosData.PageUrl + '">Comments</a>';														
					html +='<span class="blueCounter"> ('+ RecommendedPhotosData.Comments.NumberOfComments + ')</span>';	
					html +='</div>';
					html +='</div>';
					html +='</div>';
					html +='<br clear="all"></div>';
				}					
			}		
		}		
		ele.innerHTML=html;
	}
}

// TEXT TRIMMING FUNCTION 
function textTrimming(trimText,trimLength)
{
	var Ttext;
	Ttext=trimText;
	if(trimText.length>=trimLength && trimLength >0)
	{	
		Ttext=trimText.substring(0,trimLength-3)+ "...";		
	}
	return Ttext;
}

function discoverContentRecommendAction(id,recommendCtrlName)
{
	requestBatch = null;	
	requestBatch = new RequestBatch();
	requestBatch.AddToRequest(new RecommendAction(new ArticleKey(id)));	

		// update the UI from Recommend to Recommended
		var ele = document.getElementById("span_" + recommendCtrlName);			
		if(ele!=null)
		{
			var noOfRecommendations = ele.innerHTML.toString();
			noOfRecommendations = noOfRecommendations.split('(')[1].split(')')[0];
			noOfRecommendations = parseInt(noOfRecommendations.toString()) + 1;
							
			var ele1 = document.getElementById("recommend_"+ recommendCtrlName);				
			ele1.innerHTML = 'Recommended';
			ele1.className ='SiteLife_Recommended';
			// To Recommended Counter Seperately by using span tag
			var recommendedspan = document.createElement('span');				
			recommendedspan.innerHTML='(' + noOfRecommendations.toString()  + ')';
			ele1.appendChild(recommendedspan);		
		}
	requestBatch.BeginRequest(serverUrl, recommendActionCallback);
	requestBatch = null;
}


function recommendAction(id)
{	
	requestBatch = null;	
	requestBatch = new RequestBatch();
	var i;
	var callLinkRecommend = true;
	var blnUpdate = false;
	var objPluckSocialArticle;
	
	for(i=0;i<PluckSocialArticle.length;i++)
	{
		
		if(PluckSocialArticle[i].ArticleKey == id)
		{
			objPluckSocialArticle = PluckSocialArticle[i];
			break;
		}
	}	
	
		
	//check for the type & build appropriate request 
	switch(objPluckSocialArticle.ContentType)
	{
		case "article":			
		requestBatch.AddToRequest(new RecommendAction(new ArticleKey(id)));	
		//check if UpdateArticleAction needed for this id & accordinly add to the request
		if(objPluckSocialArticle.IsUpdateArticle == true)
		{	
			blnUpdate = true;
			requestBatch = updateArticle(id,objPluckSocialArticle.PageUrl,objPluckSocialArticle.PageTitle,objPluckSocialArticle.Section,objPluckSocialArticle.Categories);
			//since UpdateArticleAction is called above, make the flag to false for this article
			objPluckSocialArticle.IsUpdateArticle = false;				
		}			
		break;
		case "user":
		requestBatch.AddToRequest(new RecommendAction(new UserKey(id)));
		break;
		case "comment":
		requestBatch.AddToRequest(new RecommendAction(new CommentKey(id)));
		break;		
		case "gallery":
		requestBatch.AddToRequest(new RecommendAction(new GalleryKey(id)));
		break;
		case "photo":
		requestBatch.AddToRequest(new RecommendAction(new PhotoKey(id)));
		break;
		case "video":
		requestBatch.AddToRequest(new RecommendAction(new VideoKey(id)));
		break;
	}
	
	//traverse through the PluckSocialArticle & update the UI accordingly	
	for(j=0;j<objPluckSocialArticle.Action.length;j++)
	{
		if(objPluckSocialArticle.Action[j] == "Recommend")
		{	
			//var ele = document.getElementById(objPluckSocialArticle.Divid[j]);			
			var ele = document.getElementById("span_" + objPluckSocialArticle.Divid[j]);			
			if(ele!=null)
			{
				var noOfRecommendations = ele.innerHTML.toString();
				noOfRecommendations = noOfRecommendations.split('(')[1].split(')')[0];
				noOfRecommendations = parseInt(noOfRecommendations.toString()) + 1;
								
				var ele1 = document.getElementById("recommend_"+ objPluckSocialArticle.Divid[j]);				
				ele1.innerHTML = 'Recommended';
				ele1.className ='SiteLife_Recommended';
				// To Recommended Counter Seperately by using span tag
				var recommendedspan = document.createElement('span');				
				recommendedspan.innerHTML='(' + noOfRecommendations.toString()  + ')';
				ele1.appendChild(recommendedspan);									
			}
						
			//check if Linkobject needs to be recommended
			if(callLinkRecommend == true)
			{
				//check if there is any linked id & if so call teh recommend action for the linked id also							
				var eleLinked = document.getElementById("linked_" + objPluckSocialArticle.Divid[j]);
								
				if(eleLinked != null)
				{
					//get the values for the linked object
					var objLinked = eleLinked.value.split("@@@@@");					
					
					//If length not equal to 5 then there is something wrong as the linked object will have 5 properties: id, title, url, section, categories
					if(objLinked.length != 5)
					{
					}
					else
					{
						requestBatch.AddToRequest(new RecommendAction(new ArticleKey(objLinked[0])));
						callLinkRecommend = false;
						
						//check if the update article action needs to be called
						if(blnUpdate == true)
						{
							var arrayCat = new Array();
							arrayCat = objLinked[4].split(','); 							
							requestBatch = updateArticle(objLinked[0],baseURL + objLinked[1],objLinked[2].replace(/#@#/g,'"'),objLinked[3],arrayCat);
							blnUpdate = false;
						}
					}
				}
			}
		}
	}
	
	requestBatch.BeginRequest(serverUrl, recommendActionCallback);
	requestBatch = null;
}

function recommendActionCallback(responseBatch)
{	
	//successfully recommended
	if(responseBatch.Messages[0].Message == "ok")
	{
	}
	//not recommended properly
	else
	{
		//do something
	}
}

function ratingAction(id,rating)
{	
	requestBatch = null;
	requestBatch = new RequestBatch();
	var i;
	var objPluckSocialArticle;
	
	for(i=0;i<PluckSocialArticle.length;i++)
	{
		if(PluckSocialArticle[i].ArticleKey == id)
		{
			objPluckSocialArticle = PluckSocialArticle[i];
			break;
		}
	}
	//check for the type & build appropriate request	
	switch(objPluckSocialArticle.ContentType)
	{
		case "article":					
		requestBatch.AddToRequest(new RateAction(new ArticleKey(id),rating));
		//check if UpdateArticleAction needed for this id & accordinly add to the request
		if(objPluckSocialArticle.IsUpdateArticle == true)
		{	
			requestBatch = updateArticle(id,objPluckSocialArticle.PageUrl,objPluckSocialArticle.PageTitle,objPluckSocialArticle.Section,objPluckSocialArticle.Categories);
			//since UpdateArticleAction is called above, make the flag to false for this article
			objPluckSocialArticle.IsUpdateArticle = false;				
		}				
		break;
		case "user":
		requestBatch.AddToRequest(new RateAction(new UserKey(id),rating));
		break;
		case "comment":
		requestBatch.AddToRequest(new RateAction(new CommentKey(id),rating));
		break;
		case "review":		
		requestBatch.AddToRequest(new RateAction(new ReviewKey(id),rating));		
		break;		
	}
	
	//traverse through the PluckSocialArticle & update the UI accordingly
	for(j=0;j<objPluckSocialArticle.Action.length;j++)
	{
		if(objPluckSocialArticle.Action[j] == "Rating")
		{	
			//var objPluckSocialArticle = PluckSocialArticle[i];					
			var eleUser = document.getElementById(objPluckSocialArticle.Divid[j]+ "_user");	
			
			if(eleUser!=null)
			{
				//update with current user rating				
				DefaultRate(objPluckSocialArticle.Divid[j],'' + id  + '_StarsImage',rating);			
				AfterUserRated(objPluckSocialArticle.Divid[j]+ "_user",id,rating);					
			}
			
			var eleAvg = document.getElementById(objPluckSocialArticle.Divid[j]+ "_avg");	
			var eleNoAvg = document.getElementById(objPluckSocialArticle.Divid[j]+ "_noavg");	
			
			if(eleAvg!=null)				
			{
				if(eleNoAvg!=null)
				{
					eleNoAvg.style.display = "none";
					eleAvg.style.display = "block";
				}
				
				var eleMainDiv = document.getElementById(objPluckSocialArticle.Divid[j]+ "_MainDiv");
				var mainDivClass = document.getElementById(objPluckSocialArticle.Divid[j]+ "_class");
				if(eleMainDiv!=null && mainDivClass!=null)
				{
					eleMainDiv.className = mainDivClass.value;
				}
				
				//update with current user rating to Average Rating				
				var totalRatingsCount = document.getElementById(objPluckSocialArticle.Divid[j]+ "_TotalNumberOfRatings");
				if(totalRatingsCount.value=="")
				{
					totalRatingsCount.value = 0;
				}
				
				var averageRating = document.getElementById(objPluckSocialArticle.Divid[j]+ "_AverageRating");
				
				if(averageRating.value=="")
				{
					averageRating.value = 0;
				}
				
				if(totalRatingsCount !=null && averageRating !=null)
				{
					rating = CalculateAverageRating(parseFloat(averageRating.value),parseFloat(totalRatingsCount.value),parseFloat(rating));
					
					totalRatingsCount.value = parseInt(totalRatingsCount.value) + 1;
					averageRating.value = rating;				
				}
				var obj = id +	'_StarsImageAvg'			
				DefaultRate(objPluckSocialArticle.Divid[j],obj,rating);
			}
		}
	}
		
	requestBatch.BeginRequest(serverUrl, rateActionCallback);
	requestBatch = null;
}

function rateActionCallback(responseBatch)
{
	//successfully rated
	if(responseBatch.Messages[0].Message == "ok")
	{	
			
	}
	//not rated properly
	else
	{
		//do something
	}
}

function CalculateAverageRating(currAvgRating,totalRatings,userRating)
{
	//calculate the new average rating
	var newAvgRating;
	newAvgRating = parseFloat((currAvgRating * totalRatings)+ userRating);
	newAvgRating = Math.ceil(parseFloat((newAvgRating/(totalRatings + 1))) - .5);
		
	//return the new calculated avg rating
	return newAvgRating;
}

 // ---------------------- function of Rating widget using DAAPI  ----------------------------------------
var browserName=navigator.appName; 

function RateThis(obj, defaultRate, i)
{
	var objName;
	var imgCntr;	
	if ( typeof(obj) == 'string' )
		{ objName = obj;	}
	else {	 objName = obj.id;	 }			 
	
	objName = objName.substring(0, objName.length-1);
	objName = objName + 'Image';			
	if ( i > 0 )
	{	
		if ( document.images )
		{	for ( imgCntr = 1 ; imgCntr <= i; imgCntr++ )
			{	obj = document.getElementById(objName + imgCntr);
				if(obj !=null) 
				{	if (browserName=="Microsoft Internet Explorer")
					{	obj.style.visibility = 'visible'; 	}			
					else { obj.setAttribute('style','visibility:visible'); }
				}								
			}
				
			for ( imgCntr = (i+ 1); imgCntr <= 5 ; imgCntr++ ) 
			{
				obj = document.getElementById(objName + imgCntr);
				if(obj !=null) 
				{ if (browserName=="Microsoft Internet Explorer")
					{	obj.style.visibility = 'hidden'; }			
					else {  obj.setAttribute('style','visibility:hidden'); }	
				}
			}
		}	
	}
	else
	{
		if ( document.images ) 
		{   for ( imgCntr = 1; imgCntr <= (parseFloat(defaultRate,0)) ; imgCntr++ )
			{ 
				obj = document.getElementById(objName + imgCntr); 
				if(obj !=null) 
				{ if (browserName=="Microsoft Internet Explorer")
					{obj.style.visibility = 'visible'; }			
					else { obj.setAttribute('style','visibility:visible');	}
				}							
			}
			
			for ( imgCntr = (parseFloat(defaultRate,0)+1); imgCntr <= 5 ; imgCntr++ )
			{ obj = document.getElementById(objName + imgCntr);
				if(obj !=null)
				{	if (browserName=="Microsoft Internet Explorer")
					{	obj.style.visibility = 'hidden'; }			
					else { 	obj.setAttribute('style','visibility:hidden'); }	
				}					
			} // FOR END
		} //IF END
	} // ELSE END
} //FUCNTION END
    
    
function DefaultRate(divelement,obj, rate)
{
	var objName;
	var imgCntr;	
	if ( typeof(obj) == 'string' )
	{	objName = obj; }
	else { objName = obj.id;}
		
	if ( document.images ) 
	{	
		for ( imgCntr = 1; imgCntr <= (parseFloat(rate,0)) ; imgCntr++ ){			
			obj = document.getElementById(objName + imgCntr);				
			if(obj !=null) { 						
				if (browserName=="Microsoft Internet Explorer")
				{	
				obj.parentNode.style.visibility = 'visible';	
					obj.style.visibility = 'visible';	
				}			
				else 
				{
				obj.parentNode.style.visibility = 'visible';		 
					obj.setAttribute('style','visibility:visible'); 
				}
				}	
			}
			
		for ( imgCntr = (parseFloat(rate,0) + 1); imgCntr <= 5 ; imgCntr++ ){ 
			obj = document.getElementById(objName + imgCntr); 				
			if(obj !=null) { 
				if (browserName=="Microsoft Internet Explorer")
				{
				obj.parentNode.style.visibility = 'visible';	
					obj.style.visibility = 'hidden';	
					}			
				else {
				obj.parentNode.style.visibility = 'visible';	
					obj.setAttribute('style','visibility:hidden'); 	
					}
			}
		}
	}
}
    
function AfterUserRated(divelement,obj,rate)
{
	
	var objDiv = document.getElementById(divelement);
	if(objDiv !=null)
	{
		while (objDiv.firstChild != null) {			    
			document.getElementById(divelement).removeChild(document.getElementById(divelement).firstChild);
		}       			
		for ( imgCntr = 1; imgCntr <= (parseFloat(rate,0)) ; imgCntr++ ){
			var divItem = document.createElement('div');
			divItem.className="ratingsel fll";
            
			var imgh =document.createElement('img');
			
           imgh.src= imagePath+ 'RedStar_sel.gif'; 
           imgh.border=0;           
           divItem.appendChild(imgh); 
           objDiv.appendChild(divItem);
		}
							
			
		for ( imgCntr = (parseFloat(rate,0) + 1); imgCntr <= 5 ; imgCntr++ ){ 
			var divItem = document.createElement('div');
			divItem.className="ratingnosel fll";
            
			var imgh =document.createElement('img');
           imgh.src= imagePath + 'star_unsel.gif'; 
           imgh.border=0;           
           divItem.appendChild(imgh); 
           objDiv.appendChild(divItem);
		}
	}
}



// ---------------------- function of Rating widget using DAAPI  ----------------------------------------


function updateArticle(artKey,pageUrl,pagetitle,artSection,artCat)
{	
	//pageUrl = baseURL + pageUrl;
	
	var articleKey = new ArticleKey(artKey);	
	var section = new Section(artSection); 
	var cat = new Array();
	for(i=0;i<artCat.length;i++)
	{
		cat[i]=new Category(artCat[i]);
	}	
	var updateAction = new UpdateArticleAction(articleKey, pageUrl, pagetitle, section, cat); 
	requestBatch.AddToRequest(updateAction); 
	return requestBatch;
}

//REVIEWS


function reviewAction(id,reviewTitle,reviewRating,reviewBody,reviewPros,reviewCons)
{
	var onPageUrl;
	var onPageTitle;
	requestBatch = null;
	requestBatch = new RequestBatch();
	reviewTitle = encodeHtml(reviewTitle);
	reviewTitle = buildURL(reviewTitle);
	reviewPros = encodeHtml(reviewPros);
	reviewPros = buildURL(reviewPros);
	reviewCons = encodeHtml(reviewCons);
	reviewCons = buildURL(reviewCons);
	reviewBody = encodeHtml(reviewBody);
	reviewBody = buildURL(reviewBody);
	reviewPageNo=1; // As user submitted its rweviews irrespective of which page he is currently on, resetting reviewPageNo to 1 to see its reviews.
	for(i=0;i<PluckSocialArticle.length;i++)
	{
		if(PluckSocialArticle[i].ArticleKey == id)
		{
			onPageUrl = PluckSocialArticle[i].PageUrl;
			onPageTitle = PluckSocialArticle[i].PageTitle;
		}
	}
	requestBatch.AddToRequest(new ReviewAction(new ArticleKey(id), onPageUrl, onPageTitle, reviewTitle,reviewRating, reviewBody, reviewPros, reviewCons));
	requestBatch.AddToRequest(new ReviewPage(new ArticleKey(id),reviewsPerPage,reviewPageNo,reviewSortOrder));
	requestBatch.AddToRequest(new RateAction(new ArticleKey(id),reviewRating));
	
	
	//traverse through the PluckSocialArticle & update the UI, IsUpdateArticle accordingly
	for(i=0;i<PluckSocialArticle.length;i++)
	{		
		if(PluckSocialArticle[i].ArticleKey == id)
		{
			var objPluckSocialArticle = PluckSocialArticle[i];
							
			if(objPluckSocialArticle.ContentType == "article")
			{
				//check if UpdateArticleAction needed for this id & accordinly add to the request
				if(objPluckSocialArticle.IsUpdateArticle == true)
				{
					requestBatch = updateArticle(id,objPluckSocialArticle.PageUrl,objPluckSocialArticle.PageTitle,objPluckSocialArticle.Section,objPluckSocialArticle.Categories);
					//since UpdateArticleAction is called above, make the flag to false for this article
					objPluckSocialArticle.IsUpdateArticle = false;					
				}				
			}				
					
			break;
		}
	}	
	
	requestBatch.BeginRequest(serverUrl, reviewActionCallback); 
	requestBatch = null;
}

function reviewActionCallback(responseBatch)
{
	//succesfully submitted the review
	if (responseBatch.Messages[0].Message == 'ok') 
    {
		//clear the comtent submitted by user
		document.getElementById('UC_Pluck_ReviewInput_ReviewText').value="";
		document.getElementById('UC_Pluck_ReviewInput_ReviewTitle').value="";
		document.getElementById('UC_Pluck_ReviewInput_ReviewPros').value="";
		document.getElementById('UC_Pluck_ReviewInput_ReviewCons').value="";
		document.getElementById('RatingValue').value="";
		
		ReviewRateThis(document.getElementById('Stars1'),'0',0);
		ReviewRateThis(document.getElementById('Stars2'),'0',0);
		ReviewRateThis(document.getElementById('Stars3'),'0',0);
		ReviewRateThis(document.getElementById('Stars4'),'0',0);
		ReviewRateThis(document.getElementById('Stars5'),'0',0);
		
		if(IsReviewoutputDAAPI == true) {
			var objresponse = responseBatch.Responses[0].ReviewPage;
			renderReviewPage(objresponse);
			document.location.href="#reviewBlock";	
		}
		else if(IsReviewoutputDAAPI ==false) {			
			CommentRefreshPage();
		}
    }
    //error in submitting the review
    else
    {
		//do something
		document.getElementById('ReviewsBadWordsError').innerHTML =  badWordsMessage + getBadWords(responseBatch.Messages[0].Message);
		if(IsReviewoutputDAAPI == false)//REST
		{
			var reviewcontainer=document.getElementById('UC_Pluck_Review_RestReviewBlock');
			if(reviewcontainer !=null) {	reviewcontainer.style.display="block";    }
		}
		else //DAAPI
		{
			renderReviewPage(responseBatch.Responses[0].ReviewPage);
			//document.location.href="#reviewBlock";	
			document.location.href="#ReviewError";
		}
    }
}
//Start: Reviews input 
function reviewRatingAction(obj,Rating) 
{	
	document.getElementById('RatingValue').value=Rating;
}


function ReviewSetThis(obj, defaultRate, i)
{
	var objName;
	var imgCntr;	
	if ( typeof(obj) == 'string' )
	{ 
		objName = obj;	
	}
	else 
	{	 
		objName = obj.id;	 
	}			 
	objName = objName.substring(0, objName.length-1);
	objName = objName;			
	
	if ( i > 0 )
	{	
		if ( document.images )
		{	
			for ( imgCntr = 1 ; imgCntr <= i; imgCntr++ )
			{	
				obj = document.getElementById(objName + imgCntr);
				if(obj !=null) 
				{
					if (browserName=="Microsoft Internet Explorer")
					{	
						obj.style.visibility = 'visible'; 	
					}			
					else 
					{ 
						obj.setAttribute('style','visibility:visible'); 
					}
				}								
			}
				
			for ( imgCntr = (i+ 1); imgCntr <= 5 ; imgCntr++ ) 
			{
				obj = document.getElementById(objName + imgCntr);
				if(obj !=null) 
				{ 
					if (browserName=="Microsoft Internet Explorer")
					{	
						obj.style.visibility = 'hidden'; 
					}			
					else 
					{  
						obj.setAttribute('style','visibility:hidden'); 
					}	
				}
			}
		}	
	}
}

function ReviewRateThis(obj, defaultRate, i)
{
	var objName;
	var imgCntr;	
	if ( typeof(obj) == 'string' )
	{ 
		objName = obj;	
	}
	else 
	{	 
		objName = obj.id;	 
	}			 
	
	objName = objName.substring(0, objName.length-1);
	objName = objName + 'Image';			
	if ( i > 0 )
	{	
		if ( document.images )
		{	
			for ( imgCntr = 1 ; imgCntr <= i; imgCntr++ )
			{	
				obj = document.getElementById(objName + imgCntr);
				if(obj !=null) 
				{	
					if (browserName=="Microsoft Internet Explorer")
					{	
						obj.style.visibility = 'visible'; 	
					}			
					else 
					{ 
						obj.setAttribute('style','visibility:visible'); 
					}
				}								
			}
				
			for ( imgCntr = (i+ 1); imgCntr <= 5 ; imgCntr++ ) 
			{
				obj = document.getElementById(objName + imgCntr);
				if(obj !=null) 
				{ 
					if (browserName=="Microsoft Internet Explorer")
					{	
						obj.style.visibility = 'hidden'; 
					}			
					else 
					{  
						obj.setAttribute('style','visibility:hidden'); 
					}	
				}
			}
		}	
	}
	else
	{
		if ( document.images ) 
		{   for ( imgCntr = 1; imgCntr <= (parseFloat(defaultRate,0)) ; imgCntr++ )
			{ 
				obj = document.getElementById(objName + imgCntr); 
				if(obj !=null) 
				{ 
					if (browserName=="Microsoft Internet Explorer")
					{
						obj.style.visibility = 'visible'; 
					}			
					else 
					{ 
						obj.setAttribute('style','visibility:visible');	
					}
				}							
			}
			
			for ( imgCntr = (parseFloat(defaultRate,0)+1); imgCntr <= 5 ; imgCntr++ )
			{ 
				obj = document.getElementById(objName + imgCntr);
				if(obj !=null)
				{	
					if (browserName=="Microsoft Internet Explorer")
					{	
						obj.style.visibility = 'hidden'; 
					}			
					else 
					{ 	
						obj.setAttribute('style','visibility:hidden'); 
					}	
				}					
			} 
		} 
		if(document.getElementById('RatingValue').value!="")
		{
			ReviewSetThis(obj,'0',	document.getElementById('RatingValue').value);
		}
	} 
}
    
function SubmitInputReview(id,arg_reviewTitle,arg_reviewText,arg_reviewPros,arg_reviewCons) 
{	
	//Jyothi: Refresh the ads on the page & invoke hitbox
	RefreshFrames();

    document.getElementById('ReviewsBadWordsError').innerHTML = "";
    
    var reviewText = document.getElementById(arg_reviewText).value.trim();
    var reviewTitle = document.getElementById(arg_reviewTitle).value.trim();
    var reviewPros = document.getElementById(arg_reviewPros).value.trim();
    var reviewCons = document.getElementById(arg_reviewCons).value.trim();    
    var rating=document.getElementById('RatingValue').value;
    if (reviewTitle == '')  
    {        
		document.getElementById("ReviewError").innerHTML = "* Please provide a headline";
		return false;
    }
    else if (reviewText == '')  
    {        
		document.getElementById("ReviewError").innerHTML = "* Please provide a text";
		return false;
    }
    else if (rating == '')  
    {        
		document.getElementById("ReviewError").innerHTML = "* Please provide a rating";
		return false;
    }
    else 
    {					
		document.location.href="#reviewBlock";
		document.getElementById("ReviewError").innerHTML="";	
		//this is added for showing loading images when Review submit and hide it when reviews output is loaded.
		var ele = document.getElementById('reviewsLoading');
		var loadingimage =document.createElement('img');
        loadingimage.src=imagePath + "Loading.gif"; 
        loadingimage.border=0;           
        ele.appendChild(loadingimage);			
		ele.style.display="inline";
		
		var reviewbk =document.getElementById('reviewBlock');
		if(reviewbk !=null) {		reviewbk.style.display="none";		}
		var searchPagination = document.getElementById('searchPagination');
		if(searchPagination !=null) {		searchPagination.style.display="none";	 	 }
		
		// this code of checking IsReviewoutputDAAPI ==false when Always REST is set from webconfig file
		if(IsReviewoutputDAAPI == false) {
				var reviewcontainer=document.getElementById('UC_Pluck_Review_RestReviewBlock');
				if(reviewcontainer !=null) {	reviewcontainer.style.display="none";    }
		}
			
		reviewText=reviewText.substring(0,1000);
		reviewTitle=reviewTitle.substring(0,500);
		reviewAction(id,reviewTitle, rating ,reviewText,reviewPros,reviewCons);	  // this function avaiable in HPSocialcustom.js to Add the review		
		return false;
	}		
}
//End: Reviews input 

//Start: Comments input
 function SubmitInputComment(id,commenttext) 
 {	
        //Jyothi: Clear the badwords error msg
	    document.getElementById('CommentBadWordsError').innerHTML = "";
		//If user entered empty string then provide teh appropriated error msg
	    var text =document.getElementById(commenttext).value;						
	    if (text.trim() == '') 
	    {
		    document.getElementById("CommentError").innerHTML = "* Please provide a comment";
		     document.getElementById(commenttext).focus();
		    return false;
	    }
	    
        var fbCheck = document.getElementById('fb_connect_checkbox');
        //check if user wants to post comment to facebbok
        if(fbCheck.checked)
        {            
            //store id & comment text
            commentArticleId = id;
            commentTextId = commenttext; 
            userCommentText = document.getElementById(commenttext).value;;
            
            //Check if user connected to FB             
            if(isFBUserLoggedIn() && (GetCookie(cookie_AT) != null) && (isFBUserExistsInHW() == true))
            {
                submitPluckComment(id,commenttext);
                return false;
            }
            else
            {
                //open FB connect pop up                
                assignSrc('CommentPage');
                return false;
            }
            
        }
        else
        {
            submitPluckComment(id,commenttext);
            return false;
        }
        			
 }
 
 function isFBUserLoggedIn()
 {
    var exits = false;
    try
    {
        if(slFB.currentUserFacebookId())
        {
            exits = true;
        }
        else
        {
            exits = false;
        }
    }
    catch(e)
    {
    }    
    finally
    {
        return exits;
    }
    
 }
    
 function submitPluckComment(id,commenttext)
 {
        var flag_commentuser_Add=false;
        try {
            //check the validation of user name and emailid
            if(document.getElementById('CommentInput_username') !=null) {
                      
                var username = document.getElementById('CommentInput_username').value;
                if(username !=null) {
                    if(username.trim() =='' || username.length==0) {
                        document.getElementById("CommentError").innerHTML = "* Please provide Your Name";
                        document.getElementById('CommentInput_username').focus();
                        return false; 
                    }
                    var emailid = document.getElementById('CommentInput_emailId').value;                
                    if(checkEmail(emailid)==false) {
                        document.getElementById("CommentError").innerHTML = "* Please provide valid E-mail";
                        document.getElementById('CommentInput_emailId').focus();
                        return false;
                    }
                    flag_commentuser_Add =true;                    
                    var en_u=encode_value(username);
                    var en_e=encode_value(emailid);
                    var en_value= "name="+en_u+"&email="+en_e;                    
                    createCookie(usercookie,en_value,1);                    
                }
            }
        }
        catch(e) {        
        }
        
        hidePopUp();
        //Jyothi: Refresh the ads on the page & invoke hitbox
	    RefreshFrames();
		
	    //Jyothi: Clear the badwords error msg
	    document.getElementById('CommentBadWordsError').innerHTML = "";
		
	    var text =document.getElementById(commenttext).value;						
	    if (text.trim() == '') 
	    {
		    document.getElementById("CommentError").innerHTML = "* Please provide a comment";
		    document.getElementById(commenttext).focus();
		    return false;
	    }
	     else 
	     {
			
		    //this is added for showing loading images when comment submit and hide it when comment output is loaded
		    var ele = document.getElementById('commentsLoading');
		    var loadingimage =document.createElement('img');
            loadingimage.src= imagePath + "Loading.gif"; 
            loadingimage.border=0;           
            ele.appendChild(loadingimage);			
		    ele.style.display="inline";	
			
		    var commentbk =document.getElementById('commentBlock');
		    if(commentbk !=null) 
		    {		
			    commentbk.style.display="none";	   
		    }
		    var searchPagination = document.getElementById('searchPagination');
		    if(searchPagination !=null) 
		    {	
			    searchPagination.style.display="none"; 		
		    }
			
			
		    // this code of checking IsCommentoutputDAAPI ==false when Always REST is set from webconfig file
		    if(IsCommentoutputDAAPI==false) 
		    {
			    var commentcontainer=document.getElementById('Comments_OuterContainer');
			    if(commentcontainer !=null) 
			    {	
				    commentcontainer.style.display="none";   
			    }
		    }
		    //document.getElementById("CommentError").innerHTML="";	
		    text=text.substring(0,1000);	
		    if(flag_commentuser_Add==true){
		        text =text+'\n--'+username;
		    }			
		    commentInputAction(id,text);
		    //document.getElementById(commenttext).value = "";
		    return false;		  
	    }
 }
 
 function CommentRefreshPage()
 {
      //this function is called when CommentOutput is set to REST so we need to refresh page.
      window.location.reload(true);
 }

//End: Comments input 
//Start: Common
      
function MaxLength(control, limitToLength) 
{
	var str = control.value;
	if(! str || str.length == 0) return false;

	var matches = str.match(/\r|\n/g);
	if(! matches) return false;
	var offSet = matches.length;
	if (str.length > (limitToLength + offSet)) 
	{
		control.value = str.substring(0, limitToLength + offSet);
	}
	return false;
} 
//End: Common
//Start: Comments output 
function renderCommentPage(commentPage)
{	
	var commentBlock = document.getElementById('commentBlock');		
    var commentBlockHtml = "";
    commentBlockHtml="<div class='Reviews_Headline tal'  >Comments ("+commentPage.NumberOfComments+")</div>";
  	for(var i=0; i < commentPage.Comments.length; i++) 
	{   
		commentBlockHtml += getCommentHtml(commentPage.Comments[i],commentPage.ArticleKey.Key);   
	}  
    commentBlock.innerHTML = commentBlockHtml;
    
    renderCommentPagination(commentsPerPage,commentPageNo,commentPage.NumberOfComments,commentPage.ArticleKey.Key,commentPage)
	var ele = document.getElementById('commentsLoading');
	ele.innerHTML="";
	ele.style.display="none";
	commentBlock.style.display="block";
	var searchPagination = document.getElementById('searchPagination');
	searchPagination.style.display="inline";	
	IsCommentoutputDAAPI=true; 		
	//document.location.href="#CommentsInput";
}

function renderCommentPagination(numberPerPage, onPage, totalItems,articleKey,commentPage) 
{
	
	//set the hbx parameters
	for(i=0;i<PluckSocialArticle.length;i++)
	{
		if(PluckSocialArticle[i].ArticleKey == articleKey)
		{
			hbxPagename = "("+ articleKey + ")" + PluckSocialArticle[i].Categories;
			hbxContentCategory = PluckSocialArticle[i].Section;
			break;
		}		
	}
	
	
	var firstPage = 1;
    var nextPage = Number(onPage) + 1;
    var prevPage = Number(onPage) - 1;
    var lastPage = Math.ceil(totalItems/numberPerPage);
	var presentPage=1;
	var startcounter =1;
	var stopcounter =10;
	var MaxIndex =10;
	var Pagechecking =3;
	
	if(lastPage > 10)
	{
		if(parseInt(onPage) + 2 > Pagechecking) { presentPage =onPage; }			
		if(presentPage >Pagechecking) { startcounter =parseInt(presentPage) - 3; }			
		if(startcounter > 1) 
		{ 	
		    stopcounter =parseInt(presentPage) + 4;  
		    if(stopcounter > lastPage)
		    {
		        stopcounter = lastPage;
		    }
		}									
		firstPage=startcounter;					
		if(stopcounter >10 && stopcounter <=lastPage)  { lastPage=stopcounter;	}
		else if(lastPage > MaxIndex) { lastPage=MaxIndex; }
		if(firstPage <0)  { firstPage =1; }
	}    
        
    var firstItem = onPage * numberPerPage - numberPerPage + 1;
    if (totalItems == 0) {
        firstItem = 0;
    }        

    var lastItem = onPage * numberPerPage;
    if (lastItem > totalItems) {
        lastItem = totalItems;
    }

    // write out footer
    var html = '';	
    if (firstPage < lastPage) {
        if (prevPage >= firstPage) {
			html +='<img id="ImgBack" class="curp" align="absmiddle" onclick="RefreshFrames();getCommentPage(' + prevPage + ','+ articleKey +');" src="' + imgbackpath + '" />';
            html += ' <a class="tc01 fs11 pl05 pr05 tam" href="javascript:;" class="PrevNext" onclick="RefreshFrames();getCommentPage(' + prevPage + ','+ articleKey +');" >Back</a>';                
        }
        
        for (i = firstPage; i <= lastPage; i++) {
        
			if (i == onPage && i==1) {
				html += '<span class="CurrentPage b">' + i + '</span>';
			} else if (i == onPage && i!=1) {
				html += '| <span class="CurrentPage b">' + i + '</span>';
			} else if (i==firstPage && i!=onPage) {
			    html += '<a href="javascript:;" class="GoToPage" onclick="RefreshFrames();getCommentPage(' + i + ','+ articleKey +');">' + i + '</a>';
			} else {
				html += '| <a href="javascript:;" class="GoToPage" onclick="RefreshFrames();getCommentPage(' + i + ','+ articleKey +');">' + i + '</a>';
			}			    
		}
        if (nextPage <= lastPage) {
            html += '<a class="tc01 fs11 pl05 pr05 tam" href="javascript:;" class="PrevNext" onclick="RefreshFrames();getCommentPage(' + nextPage + ','+ articleKey +');">Next</a>';
            html +='<img id="ImgNext" class="curp" align="absmiddle" onclick="RefreshFrames();getCommentPage(' + nextPage + ','+ articleKey +');" src="' + imgNextpath + '" />';
        }
    }
    var searchPagination = document.getElementById('searchPagination');	
    searchPagination.innerHTML =html;
}

function commentRecommendAction(id,articleKey)
{	
	//update the UI
	var recommendText = "recommendDiv_"+ id.toString();
	var recommendCount = "recommendCount_"+ id.toString();
	var ele = document.getElementById(recommendText);
	var ele1 = document.getElementById(recommendCount);
	if(ele!=null && ele1!=null)
	{
		var noOfRecommendations = ele1.innerHTML.toString();		
		noOfRecommendations = noOfRecommendations.split('(')[1].toString().split(')')[0];
		noOfRecommendations = parseInt(noOfRecommendations.toString()) + 1;
		
		var html="";
		html +="<div class='SiteLife_Recommended' >Recommended";
        html += "<span id='recommend_"+ id.toString() +"' > ("+noOfRecommendations.toString()+") </span></div>";
			
		ele.innerHTML = html;
	}					
					
	var key = id.split(':')[1];		
	requestBatch = null;
	requestBatch = new RequestBatch();	
	//requestBatch.AddToRequest(new RecommendAction(new CommentKey(key)));	
	requestBatch.AddToRequest(new RecommendAction(new CommentKey(id)));	
	requestBatch.BeginRequest(serverUrl, reviewRecommendActionCallback); 		
}


function commentReportAbuse(id,articleKey) 
{ 
	//update the UI
	var reason = document.getElementById("abuseReportReason").value;
	var description = document.getElementById("abuseReportDesc").value;
	var reportAbuseId = "reportAbuseDiv_" + id.toString();
	var ele = document.getElementById(reportAbuseId);
	if(ele!=null)
	{
		ele.innerHTML ="<span class='Reported' >Reported</span>";
	}
	  	
    var key = id.split(':')[1];	
	requestBatch = null;
	requestBatch = new RequestBatch();	
	//requestBatch.AddToRequest(new ReportAbuseAction(new CommentKey(key),reason, description));	
	requestBatch.AddToRequest(new ReportAbuseAction(new CommentKey(id),reason, description));	
	
	requestBatch.BeginRequest(serverUrl, commentAbuseReported); 
}
function commentAbuseReported(responseBatch) 
{
    //succesfully reported abuse
    if (responseBatch.Messages[0].Message == 'ok') 
    {
		
    }
    //error in reporting the abuse
    else
    {
		//do something
    }
}

// ask the server for a page of results
function getCommentPage(pageNumber,article_Key) 
{	
	// Display the Loading image
	document.location.href="#commentBlock";
	var ele = document.getElementById('commentsLoading');
	var loadingimage =document.createElement('img');
    loadingimage.src= imagePath + "Loading.gif"; 
    loadingimage.border=0;           
    ele.appendChild(loadingimage);			
	ele.style.display="inline";	
	// hiding the Comment Output Block
	var commentbk =document.getElementById('commentBlock');
	if(commentbk !=null) {		commentbk.style.display="none";	   }
	var searchPagination = document.getElementById('searchPagination');
	if(searchPagination !=null) {	searchPagination.style.display="none"; 		}
	
	requestBatch = new RequestBatch();
	requestBatch.AddToRequest(new CommentPage(new ArticleKey(article_Key.toString()),commentsPerPage,pageNumber,commentSortOrder));	
	
	commentPageNo = 	pageNumber;		
	requestBatch.BeginRequest(serverUrl, commentpaginationCallback);
}

function commentpaginationCallback(responseBatch)
{
	if (responseBatch.Responses.length == 0) 
	{	
	} 
	else
	{		    
		renderCommentPage(responseBatch.Responses[0].CommentPage);
		document.location.href="#commentBlock";
	}
}

function getCommentHtml(comment,articleKey) 
{   
    var html = "<div class='";
    if(altFlag==0)
	{   
	    altFlag=1;
        html +="Reviews_RowColor";
	}
    else
    {   altFlag=0;
        html +="Reviews_AltRowColor";
    }	
	
	var commentBlockFlag=false;
	if(comment.CommentBody.indexOf("comment is abusive and has been removed")>=0)
	{
		commentBlockFlag=true;
	}
	if ((comment.Author.IsBlocked == 'True') || (comment.AbuseReportCount > abuseThreshold))
    {
        commentBlockFlag=true;
    }   
	
    html += "'><div class='Reviews_UserImage fll'>";
    // Checking If user is anonymous then remove the anchor tag and place the simple image tag
	if(comment.Author.DisplayName !='anonymous') 
	{
		html += "<a href='/MyHollywood/UserProfile.aspx?UserId="+ comment.Author.UserKey.Key + "&plckPersonaPage=PersonaHome'><IMG class='PluckUserAvatar' id='' alt='User Image' src='" + comment.Author.AvatarPhotoUrl+"' /></a>"; 
	}
    else
    {
		html += "<IMG class='PluckUserAvatar' id='' alt='User Image' src='" + comment.Author.AvatarPhotoUrl+"' />"; 
    }
    // this if block code will remove the Blocked comment body with standard abusive comment
    if(commentBlockFlag==true)
    {   
        html +="<br/></div><div class='Reviews_Right'>";      
        html +="<div class='Reviews_From'></div>";
        if(comment.Author.DisplayName !='anonymous')
        {
            html +="<div class='Reviews_ReviewText'>"+ comment.Author.DisplayName + "'s comment is abusive and has been removed" +"</div><br clear='all'/>";
        }
        else
        {
            html +="<div class='Reviews_ReviewText'>anonymous's comment is abusive and has been removed" +"</div><br clear='all'/>";	        
  	    }
        html +="</div><br clear='all'/></div> <br clear='all'/>";        
	}
	else
	{
	    var Comm_Userindex=0;
	    html +="<br/>wrote: </div><div class='Reviews_Right'>";
	    // Checking If user is anonymous then remove the anchor tag and place the simple text
	    if(comment.Author.DisplayName !='anonymous') 
	    {
		    html +="<div class='Reviews_From'><a href='/MyHollywood/UserProfile.aspx?UserId="+ comment.Author.UserKey.Key + "&plckPersonaPage=PersonaHome'>"+comment.Author.DisplayName +"</a> wrote: </div>";
	    }
	    else
	    {   
	        //debugger;
	        try {
		        if(comment.CommentBody.indexOf('\n--')>0) {
		               Comm_Userindex = comment.CommentBody.indexOf('\n--');
		               var comm_len =comment.CommentBody.length;  // 3 value is add for '\n--'
		               var Comm_username = comment.CommentBody.substring(parseInt(Comm_Userindex+3),comm_len);
		               html +="<div class='Reviews_From'>" + Comm_username + " wrote: </div>";
		        }
		        else{
		               html +="<div class='Reviews_From'>" + comment.Author.DisplayName + " wrote: </div>";
		        }
		    }
		    catch(e) {		    
		    }   
	    }	    
	    //Mantis #1549 added the class ofh wp100 to wrap the comment body	    
	    try {
	        if(Comm_Userindex >0) {	        
	            var Comm_body = comment.CommentBody.substring(0,Comm_Userindex);
	            html +="<div class='Reviews_ReviewText ofh wp100'>"+Comm_body+"</div>";
	        }
	        else{
	            html +="<div class='Reviews_ReviewText ofh wp100'>"+comment.CommentBody+"</div>";
	        }
	    }
	    catch(e){
	    }	   
	    var PostedAtTime=comment.PostedAtTime;
	    var PostedAtTimeArr=PostedAtTime.split(':');
	    PostedAtTime=PostedAtTimeArr[0]+":"+PostedAtTimeArr[1]+" "+PostedAtTimeArr[2].split(' ')[1]+" CDT";
	    html +="<div class='Reviews_NestedTable'><div class='Reviews_NestedDate'>"+PostedAtTime+"</div>";
	    html +="<div class='Reviews_NestedRecommend' id='recommendDiv_"+ comment.CommentKey.Key +"'>";

	    if(comment.CurrentUserHasRecommended=="True")
        {
		    html +="<div class='SiteLife_Recommended' >Recommended";
		    html += "<span id='recommendCount_"+ comment.CommentKey.Key +"' > ("+comment.NumberOfRecommendations+") </span></div></div>";  
        }
        else
        {
		    html +="<A class='SiteLife_Recommend' href='javascript:;' onclick='commentRecommendAction(\""+ comment.CommentKey.Key +"\", \""+ articleKey +"\");' >Recommend</A>";
		    html += "<span id='recommendCount_"+ comment.CommentKey.Key +"' > ("+comment.NumberOfRecommendations+") </span></div>";
        }
        
        varZIndex--;    
        html +="<div class='Reviews_NestedReport' style='z-index:" + varZIndex + "' id='reportAbuseDiv_"+ comment.CommentKey.Key +"'>";
	
        if(comment.CurrentUserHasReportedAbuse == "False") 
	    {
		    html += "<a class='ReportAbuse curp' id='reportAbuse_"+ comment.CommentKey.Key +"'  href='javascript:;'  onclick= 'showObject(\"ReportAbuse_Menu_"+ comment.CommentKey.Key+"\");' >Report Abuse</A>";
		    html += "<div class='ReportAbuse_Container dno' id='ReportAbuse_Menu_"+ comment.CommentKey.Key +"'>";
		    html += "<span class='fll pl03 pr02'>Report item as: (required) </span> ";
		    html += "<a onclick='document.getElementById(\"ReportAbuse_Menu_"+ comment.CommentKey.Key+"\").style.display=\"none\";return false;' href='#none' class='ml05'>X</a> ";
		    html += "<div class='ReportAbuse_Interior'>	";
		    html += "<select id='abuseReportReason'>";
		    html += "<option value='Obscenity/vulgarity' selected='selected'>Obscenity/vulgarity</option>";
		    html += "<option value='Hate speech'>Hate speech</option>";
		    html += "<option value='Personal attack'>Personal attack</option>";
		    html += "<option value='Advertising/spam'>Advertising/spam</option>";
		    html += "<option value='Copyright/plagiarism'>Copyright/plagiarism</option>";
		    html += "<option value='Other'>Other</option>";
		    html += "</select>";
		    html += "</div>";
		    html += "<div class='ReportAbuse_SectionHead'>";
		    html += "Comment: (optional)";
		    html += "</div>";
		    html += "<div class='ReportAbuse_Comment'>";
		    html += "<textarea id='abuseReportDesc'></textarea>";
    		
		    html += "<input type='button' value='Submit Report' onclick='hideObject(\"ReportAbuse_Menu_"+ comment.CommentKey.Key+"\");commentReportAbuse(\"" + comment.CommentKey.Key + "\",\""+ articleKey +"\");'/> ";
    		
		    html += "</div>  "; 
		    html += "</div>";							
	     } 
	     else 
	     {
		    html += "<span class='Reported' >Reported</span>";
	     }   
	    html +=" </div></div></div><br clear='all'/></div> <br clear='all'/> ";
	}
    return html;  
}
//End: Comments output


//Start: Reviews output
function renderReviewPage(reviewPage)//,artcleIndex,actionIndex)
{	
	var reviewBlock = document.getElementById('reviewBlock'); 
	
    var reviewBlockHtml = "";
    reviewBlockHtml="<div class='Reviews_Headline tal'  >Reviews ("+reviewPage.NumberOfReviews+")</div>";
        
	for(var i=0; i < reviewPage.Reviews.length; i++) 
	{   
		reviewBlockHtml += getReviewHtml(reviewPage.Reviews[i],reviewPage.ArticleKey.Key);   
	}  

    reviewBlock.innerHTML = reviewBlockHtml;

	renderReviewPagination(reviewsPerPage,reviewPageNo,reviewPage.NumberOfReviews,reviewPage.ArticleKey.Key,reviewPage)
	var ele = document.getElementById('reviewsLoading');
	ele.innerHTML="";
	ele.style.display="none";
	var reviewbk =document.getElementById('reviewBlock');
	reviewbk.style.display="block";	
	var searchPagination = document.getElementById('searchPagination');
	searchPagination.style.display="inline"; 	
	//document.location.href="#reviewBlock";
	IsReviewoutputDAAPI=true; 	
}


function getReviewHtml(review,articleKey) 
{   	
	if ((review.Author.IsBlocked == 'True') || (review.AbuseReportCount > abuseThreshold))
	{
	return "";
	}
	var html = "<div class='"
	if(altFlag==0)
	{
        altFlag=1;
        html +="Reviews_RowColor"
	}
    else
    {
        altFlag=0;
        html +="Reviews_AltRowColor"
    }
    html += "'><div class='Reviews_UserImage fll'>"
    
    html += "<a href='/MyHollywood/UserProfile.aspx?UserId="+ review.Author.UserKey.Key + "&plckPersonaPage=PersonaHome'><IMG class='PluckUserAvatar' id='' alt='User Image' src='"+review.Author.AvatarPhotoUrl+"' /></a>" 
	html +="<br/>wrote: </div><div class='Reviews_Right'>"
	// Checking If user is anonymous then remove the anchor tag and place the simple text
	if(review.Author.DisplayName !='anonymous') 
	{
		html +="<div class='Reviews_From'><a href='/MyHollywood/UserProfile.aspx?UserId="+ review.Author.UserKey.Key + "&plckPersonaPage=PersonaHome'>"+review.Author.DisplayName +"</a> wrote: </div>"
	}
	else
	{
		html +="<div class='Reviews_From'>" + review.Author.DisplayName + " wrote: </div>"
	}	
	html +="<div class='Reviews_Headline'>"+review.ReviewTitle + "<div class='ratenoborder'>"
				
	for(var i=0;i<review.ReviewRating;i++)
	{
		html +="<IMG alt='' src='"+ imagePath + "RedStar_sel.gif' border='0' />"
	}
	
	for(var j=0;j<5-review.ReviewRating;j++)
	{
		html +="<IMG alt='' src='"+ imagePath + "star_unsel.gif' border='0' />"
	}
	 //Start Mantis #1549 added the class ofh wp100 to wrap the comment body
	html +="</div></div><div class='Reviews_ReviewText ofh wp100'>"+review.ReviewBody+"</div>"
	//TODO: Jyothi - rel 58 - start - QA 3355
	if(review.ReviewPros != "")
	{
		html +="<div class='Reviews_Pros ofh wp100'><SPAN class='Reviews_FieldHead'>"
		html +="Pros: </SPAN>"+review.ReviewPros+"</div>"
	}
	if(review.ReviewCons != "")
	{
		html +="<div class='Reviews_Cons ofh wp100'><SPAN class='Reviews_FieldHead'>Cons: </SPAN>"+review.ReviewCons+"</div>"
	}	
	//End Mantis #1549 
	//TODO: Jyothi - rel 58 - end - QA 3355
	
	var PostedAtTime=review.PostedAtTime;
	var PostedAtTimeArr=PostedAtTime.split(':');
	PostedAtTime=PostedAtTimeArr[0]+":"+PostedAtTimeArr[1]+" "+PostedAtTimeArr[2].split(' ')[1]+" CDT";
	html +="<div class='Reviews_NestedTable'><div class='Reviews_NestedDate'>"+PostedAtTime+"</div>"
	html +="<div class='Reviews_NestedRecommend' id='recommendDiv_"+ review.ReviewKey.Key +"'>"

	if(review.CurrentUserHasRecommended=="True")
    {
		html +="<div class='SiteLife_Recommended' >Recommended"
		html += "<span id='recommendCount_"+ review.ReviewKey.Key +"' > ("+review.NumberOfRecommendations+") </span></div></div>"
    }
    else
    {
		html +="<A class='SiteLife_Recommend' href='javascript:;'  onclick='reviewRecommendAction(\""+ review.ReviewKey.Key +"\", \""+ articleKey +"\");' >Recommend</A>"
		html += "<span id='recommendCount_"+ review.ReviewKey.Key +"' > ("+review.NumberOfRecommendations+") </span></div>"
    }
    varZIndex--;                    
    html +="<div class='Reviews_NestedReport' style='z-index:" + varZIndex + "' id='reportAbuseDiv_"+ review.ReviewKey.Key +"'>"
	
    if(review.CurrentUserHasReportedAbuse == "False") 
	{
	
		html += "<a class='ReportAbuse curp' id='reportAbuse_"+ review.ReviewKey.Key +"'  href='javascript:;'  onclick= 'showObject(\"ReportAbuse_Menu_"+ review.ReviewKey.Key+"\");' >Report Abuse</A>"
		html += "<div class='ReportAbuse_Container dno' id='ReportAbuse_Menu_"+ review.ReviewKey.Key +"'>"
		html += "<span class='fll pl03 pr02'>Report item as: (required) </span> "
		html += "<a onclick='document.getElementById(\"ReportAbuse_Menu_"+ review.ReviewKey.Key+"\").style.display=\"none\";return false;' href='#none' class='ml05'>X</a> "
		html += "<div class='ReportAbuse_Interior'>	"
		html += "<select id='abuseReportReason'>";
		html += "<option value='Obscenity/vulgarity' selected='selected'>Obscenity/vulgarity</option>";
		html += "<option value='Hate speech'>Hate speech</option>";
		html += "<option value='Personal attack'>Personal attack</option>";
		html += "<option value='Advertising/spam'>Advertising/spam</option>";
		html += "<option value='Copyright/plagiarism'>Copyright/plagiarism</option>";
		html += "<option value='Other'>Other</option>";
		html += "</select>";
		html += "</div>"
		html += "<div class='ReportAbuse_SectionHead'>"
		html += "Comment: (optional)"
		html += "</div>"
		html += "<div class='ReportAbuse_Comment'>"
		html += "<textarea id='abuseReportDesc'></textarea>"
		
		html += "<input type='button' value='Submit' onclick='hideObject(\"ReportAbuse_Menu_"+ review.ReviewKey.Key+"\");reviewReportAbuse(\"" + review.ReviewKey.Key + "\",\""+ articleKey +"\");'/> "
		
		html += "</div>  " 
		html += "</div>";
							
	} 
	else 
	{
		html += "<span class='Reported' >Reported</span>";
	}
    
	html +=" </div></div></div><br clear='all'/></div> <br clear='all'/> "
	
    return html;
}


function reviewReportAbuse(id,articleKey) 
{ 
	//update the UI
	var reason = document.getElementById("abuseReportReason").value;
	var description = document.getElementById("abuseReportDesc").value;
	var reportAbuseId = "reportAbuseDiv_" + id.toString();
	var ele = document.getElementById(reportAbuseId);
	if(ele!=null)
	{
		ele.innerHTML ="<span class='Reported' >Reported</span>";
	}
	  	
    var key = id.split(':')[1];	
	requestBatch = null;
	requestBatch = new RequestBatch();	
	//requestBatch.AddToRequest(new ReportAbuseAction(new ReviewKey(key),reason, description));	
	requestBatch.AddToRequest(new ReportAbuseAction(new ReviewKey(id),reason, description));	
	
	//requestBatch.AddToRequest(new ReviewPage(new ArticleKey(articleKey),reviewsPerPage,reviewPageNo,reviewSortOrder));	
	requestBatch.BeginRequest(serverUrl, reviewAbuseReported); 
	requestBatch = null;
}

function reviewAbuseReported(responseBatch) 
{
    //succesfully reported abuse
	if (responseBatch.Messages[0].Message == 'ok') 
    {
		
    }
    //error in reporting the abuse
    else
    {
		//do something
    }
}

function reviewRecommendAction(id,articleKey)
{	
	//update the UI	
	var recommendText = "recommendDiv_"+ id.toString();
	var recommendCount = "recommendCount_"+ id.toString();
	var ele = document.getElementById(recommendText);
	var ele1 = document.getElementById(recommendCount);
	if(ele!=null && ele1!=null)
	{
		var noOfRecommendations = ele1.innerHTML.toString();		
		noOfRecommendations = noOfRecommendations.split('(')[1].toString().split(')')[0];
		noOfRecommendations = parseInt(noOfRecommendations.toString()) + 1;
		
		var html="";
		html +="<div class='SiteLife_Recommended' >Recommended";
        html += "<span id='recommend_"+ id.toString() +"' > ("+noOfRecommendations.toString()+") </span></div>";
			
		ele.innerHTML = html;
	}					
					
	var key = id.split(':')[1];	
	requestBatch = null;
	requestBatch = new RequestBatch();	
	//requestBatch.AddToRequest(new RecommendAction(new ReviewKey(key)));	
	requestBatch.AddToRequest(new RecommendAction(new ReviewKey(id)));	
	
	//requestBatch.AddToRequest(new ReviewPage(new ArticleKey(articleKey),reviewsPerPage,reviewPageNo,reviewSortOrder));	
	requestBatch.BeginRequest(serverUrl, reviewRecommendActionCallback);
	requestBatch = null; 		
}

function reviewRecommendActionCallback(responseBatch)
{	
	//succesfully recommended
	if (responseBatch.Messages[0].Message == 'ok') 
    {
    
    }
    //error in recommending the review
    else
    {
		//do something
    }
}



function renderReviewPagination(numberPerPage, onPage, totalItems,articleKey,reviewPage) 
{
	//set the hbx parameters
	for(i=0;i<PluckSocialArticle.length;i++)
	{
		if(PluckSocialArticle[i].ArticleKey == articleKey)
		{
			hbxPagename = "("+ articleKey + ")" + PluckSocialArticle[i].Categories;
			hbxContentCategory = PluckSocialArticle[i].Section;
			break;
		}		
	}
		
	var firstPage = 1;
    var nextPage = Number(onPage) + 1;
    var prevPage = Number(onPage) - 1;
    var lastPage = Math.ceil(totalItems/numberPerPage);
	var presentPage=1;
	var startcounter =1;
	var stopcounter =10;
	var MaxIndex =10;
	var Pagechecking =3;
	
	if(lastPage > 10)
	{
		if(parseInt(onPage) + 2 > Pagechecking) { presentPage =onPage; }			
		if(presentPage >Pagechecking) { startcounter =parseInt(presentPage) - 3; }			
		if(startcounter > 1) 
		{ 	
		    stopcounter =parseInt(presentPage) + 4;
		    if(stopcounter > lastPage)
		    {
		        stopcounter = lastPage;
		    }
	    }									
		firstPage=startcounter;					
		if(stopcounter >10 && stopcounter <=lastPage)  { lastPage=stopcounter;	}
		else if(lastPage > MaxIndex) { lastPage=MaxIndex; }
		if(firstPage <0)  { firstPage =1; }
	}    
        
    var firstItem = onPage * numberPerPage - numberPerPage + 1;
    if (totalItems == 0) {
        firstItem = 0;
    }        

    var lastItem = onPage * numberPerPage;
    if (lastItem > totalItems) {
        lastItem = totalItems;
    }

    // write out footer
    var html = '';	
    if (firstPage < lastPage) {
        if (prevPage >= firstPage) {
			html +='<img id="ImgBack" class="curp" align="absmiddle" onclick="RefreshFrames();getReviewPage(' + prevPage + ','+ articleKey +');" src="' + imgbackpath + '" />';
            html += ' <a class="tc01 fs11 pl05 pr05 tam" href="javascript:;" class="PrevNext" onclick="RefreshFrames();getReviewPage(' + prevPage + ','+ articleKey +');" >Back</a>';                
        }
        for (i = firstPage; i <= lastPage; i++) {
			if (i == onPage && i==1) {
				html += '<span class="CurrentPage b">' + i + '</span>';
			} else if (i == onPage && i!=1) {
				html += '| <span class="CurrentPage b">' + i + '</span>';
			} else if (i==firstPage && i!=onPage) {
			    html += '<a href="javascript:;" class="GoToPage" onclick="RefreshFrames();getReviewPage(' + i + ','+ articleKey +');">' + i + '</a>';
			} else {
				html += '| <a href="javascript:;" class="GoToPage" onclick="RefreshFrames();getReviewPage(' + i + ','+ articleKey +');">' + i + '</a>';
			}			    
		}
        if (nextPage <= lastPage) {
            html += '<a class="tc01 fs11 pl05 pr05 tam" href="javascript:;" class="PrevNext" onclick="RefreshFrames();getReviewPage(' + nextPage + ','+ articleKey +');">Next</a>';
            html +='<img id="ImgNext" class="curp" align="absmiddle" onclick="RefreshFrames();getReviewPage(' + nextPage + ','+ articleKey +');" src="' + imgNextpath + '" />';
        }
    }
    document.getElementById('searchPagination').innerHTML =html;
}

// ask the server for a page of results
function getReviewPage(pageNumber,article_Key) 
{	
	// Start Display the Loading image
	document.location.href="#reviewBlock";
	var ele = document.getElementById('reviewsLoading');
	var loadingimage =document.createElement('img');
    loadingimage.src= imagePath + "Loading.gif"; 
    loadingimage.border=0;           
    ele.appendChild(loadingimage);			
	ele.style.display="inline";	
	// hiding the Comment Output Block	
	var reviewbk =document.getElementById('reviewBlock');
	if(reviewbk !=null) {		reviewbk.style.display="none";	   }
	var searchPagination = document.getElementById('searchPagination');
	if(searchPagination !=null) {	searchPagination.style.display="none"; 		}	
	// End of Display the Loading Image
	
	requestBatch = null;
	requestBatch = new RequestBatch();
	requestBatch.AddToRequest(new ReviewPage(new ArticleKey(article_Key.toString()),reviewsPerPage,pageNumber,reviewSortOrder));	
	
	reviewPageNo = 	pageNumber;		
	requestBatch.BeginRequest(serverUrl, paginationCallback);
	requestBatch = null;
}

function paginationCallback(responseBatch)
{
	if (responseBatch.Responses.length == 0) 
	{	
	} 
	else
	{		    
		renderReviewPage(responseBatch.Responses[0].ReviewPage);
	}
}

// Hides a given object by id.
function hideObject(objectID) 
{	
	if(document.getElementById(objectID)!=null)
	{
		document.getElementById(objectID).style.display = "none";
	}
}
// Shows a given object by id.
function showObject(objectID) 
{
	hideObject(prevReportAbuse)
	document.getElementById(objectID).style.display = "inline";
	prevReportAbuse=objectID;
}

//COMMENTS
function commentInputAction(id,commentbody)
{
	requestBatch = null;
	requestBatch = new RequestBatch();               
	commentbody = encodeHtml(commentbody);		
	commentbody = buildURL(commentbody);
	commentPageNo=1; // As user submitted its comment irrespective of which page he is currently on resetting commentpageno to 1 to see its comments.
	//traverse through PluckSocialArticle & get the exact item
	for(i=0;i<PluckSocialArticle.length;i++)
	{
		if(PluckSocialArticle[i].ArticleKey == id)
		{
			var objPluckSocialArticle = PluckSocialArticle[i];
			switch(objPluckSocialArticle.ContentType)
			{
				case "article":							
				requestBatch.AddToRequest(new CommentAction(new ArticleKey(id),objPluckSocialArticle.PageUrl,objPluckSocialArticle.PageTitle,commentbody));								
				requestBatch.AddToRequest(new CommentPage(new ArticleKey(id),commentsPerPage,commentPageNo,commentSortOrder));
				//check if Updateartcle needs to be invoked
				if(objPluckSocialArticle.IsUpdateArticle == true)
				{
					requestBatch = updateArticle(id,objPluckSocialArticle.PageUrl,objPluckSocialArticle.PageTitle,objPluckSocialArticle.Section,objPluckSocialArticle.Categories);
					//since UpdateArticleAction is called above, make the flag to false for this article
					objPluckSocialArticle.IsUpdateArticle = false;
				}
				break;
				case "gallery":
				requestBatch.AddToRequest(new CommentAction(new GalleryKey(id),objPluckSocialArticle.PageUrl,objPluckSocialArticle.PageTitle,commentbody));
				break;
				case "photo":
				requestBatch.AddToRequest(new CommentAction(new PhotoKey(id),objPluckSocialArticle.PageUrl,objPluckSocialArticle.PageTitle,commentbody));
				break;
				case "video":
				requestBatch.AddToRequest(new CommentAction(new VideoKey(id),objPluckSocialArticle.PageUrl,objPluckSocialArticle.PageTitle,commentbody));
				break;
			}
									
			break;	
		}
	}
	requestBatch.BeginRequest(serverUrl, commentInputActionCallback);		
	requestBatch = null;
}

function commentInputActionCallback(responseBatch)
{
	//succesfully commented		
	if (responseBatch.Messages[0].Message == 'ok') 
    {
		//clear the input submitted by the user as well as the error message
		document.getElementById('CommentError').innerHTML="";
		var ele = document.getElementById('hdnCommentTextId');			
		document.getElementById(ele.value).value = "";
		
		var fbCheck = document.getElementById('fb_connect_checkbox');
		var objresponse = responseBatch.Responses[0].CommentPage;
				
		if(IsCommentoutputDAAPI ==true) {		    
            	
			renderCommentPage(objresponse);	
			
			//Update the commenst counter on the page
			updateCommentsCounter(objresponse.ArticleKey.Key,objresponse.NumberOfComments);	
						
            //check if user wants to post comment to facebbok
            if(fbCheck.checked)
            {
                submitFBComment(objresponse);
            }
            document.location.href="#commentBlock";		
		}
		else if(IsCommentoutputDAAPI ==false) {
		    //check if user wants to post comment to facebbok
            if(fbCheck.checked)
            {
                submitFBComment(objresponse);
            }
            else
            {
                CommentRefreshPage();
            }	
		}
    }
    //error in comment action
    else
    {
		//do something
		document.getElementById('CommentBadWordsError').innerHTML =  badWordsMessage + getBadWords(responseBatch.Messages[0].Message);
		
		if(IsCommentoutputDAAPI == false) //REST implementation
		{
			var commentcontainer=document.getElementById('Comments_OuterContainer');
			if(commentcontainer !=null) 
			{	
				commentcontainer.style.display="block";   
			}
		}
		else //DAAPI implementation
		{
			renderCommentPage(responseBatch.Responses[0].CommentPage);
		}
    }
}

function submitFBComment(objresponse)
{   
    if(slFB.connectEnabled())
    {
        //get the appropriate article details
        for(var i=0; i<PluckSocialArticle.length; i++)
        {
            if(PluckSocialArticle[i].ArticleKey == objresponse.ArticleKey.Key)
            {
                var objFb = PluckSocialArticle[i];
                var previewImages = []; 
                var excerpt = 'excerpt';                
                slFB.submitArticleComment(objFb.PageTitle.toString(),objFb.PageUrl.toString(),excerpt.toString(),userCommentText,previewImages,FBCommentCallback);                
                break;
            }
        }                    
    }
}

function FBCommentCallback()
{  
    var ele = document.getElementById('hdnCommentTextId');
    var ele1 = document.getElementById(ele.value);
    ele1.focus();
    if(IsCommentoutputDAAPI ==false)
    {
        CommentRefreshPage();
    }
}

function getBadWords(errorText)
{
	var badWords = errorText.split('example:');	
	var temp;
	var arrBadwords = new Array();
	temp = badWords[1].substring(0, badWords[1].length -2);
	arrBadwords = temp.split(',');
	badWords = ""
	
	//remove the duplicate words and build the badwords string
	for(i=0;i<arrBadwords.length;i++)
	{		
		for(j=0;j<arrBadwords.length;j++)
		{
			if(i!=j && arrBadwords[i]!="" && arrBadwords[j]!= "")
			{
				if(arrBadwords[i] == arrBadwords[j])
				{
					arrBadwords	[j] = ""
				}
			}
		}
		if(arrBadwords[i] != "")
		{
			badWords = badWords + arrBadwords[i] + ",";
		}
	}
	
	return badWords.substring(0, badWords.length -1);
}

//This function is called to update the comments counter on the page after a comment has been submitted using comments input
function updateCommentsCounter(articleId,totalComments)
{	
	var i;
	var objPluckSocialArticle;
	//Traverse through teh entire pluckSocialArticle & find the required article
	for (i=0;i<PluckSocialArticle.length;i++)
	{
		if(PluckSocialArticle[i].ArticleKey == articleId)
		{
			objPluckSocialArticle = PluckSocialArticle[i];
			break;
		}
	}
	
	if(objPluckSocialArticle != null)
	{
		var arr_Action= objPluckSocialArticle.Action;
		for(i=0;i<arr_Action.length;i++)
		{
			if(arr_Action[i] == "commentsCounter")
			{					
				var ele = document.getElementById(objPluckSocialArticle.Divid[i]);
				if(ele != null)
				{	                
					// update page elements			
					var eleanchor = document.getElementById("span_" + objPluckSocialArticle.Divid[i]);			
					if(eleanchor!=null)
					{
						eleanchor.innerHTML='(' + totalComments + ')';	
					}	
				}				
			}
		}
	}
}

function encodeHtml(body)
{	
	var stripped="";
	if(body.length>0){
	var stripped=body.replace(/</g,"&lt;");
	stripped=stripped.replace(/>/g,"&gt;");
	stripped=stripped.replace(/\u2019/g,"&#8217;");
	stripped=stripped.replace(/\u201C/g,"&#8220;");
	stripped=stripped.replace(/\u201D/g,"&#8221;");
	stripped=stripped.replace(/\r\n/g,"\n");
	stripped=stripped.replace(/\n/g,"<br />\n");}
	return stripped;
}

function buildURL(inputVal)
{
	
	inputVal = inputVal.replace(/((http:\/\/|www.)[^ ]+)/g,'<a href="http://$1" rel="nofollow" target="_blank">$1</a>');
	inputVal = inputVal.replace("http://http://","http://");	
			
	return inputVal;
}	
//-------------------------------------Start of search DAAPI Functions ---------------------------------------------
function memberSearch(e) 
{
	if (e.keyCode == 13)
	{
		e.cancelBubble = true;
		e.returnValue = false;		
		getPage(1);
		RefreshFrames();
	}
}

var ResultCountperRow =0;
 // Make a single request of the DAAPI
     function talkToServer(request) {	
        if(typeof searchvalue == "undefined")
        {
             var searchvalue = "";
        }
    	     	
		if(searchvalue.value !="")
		{			
			var requestBatch_Search = new RequestBatch();
			requestBatch_Search.AddToRequest(request);
			requestBatch_Search.BeginRequest(serverUrl, customCallBack);			
        }        
    }
        
	
     // ask the server for a page of results
    function getPage(pageNumber) {
		wipeObject('tblSearchResultItems');
		startTime = new Date();  		        
		if (searchvalue.value.length == 0) 
		{
				var ele = document.getElementById("MainContent");
				if(ele!= null)
				{
					ele.style.display = "block";
				}	
				noItemsFound('tblSearchResultItems',false);
		}
		else 
		{	
			// showing the loading image
				var loadingimage =document.getElementById("searchLoading");	
				if(loadingimage !=null)
				loadingimage.style.display="inline";
				
				var ele = document.getElementById("MainContent");
				if(ele!= null)
				{
					ele.style.display = "block";
					// hide the search pagination div
					var divsearchpagination =document.getElementById("searchPagination");	
					if(divsearchpagination !=null)
					divsearchpagination.style.display="none";
					// hide the search result text div
					var divsearchresulttext =document.getElementById("searchingtextresult");	
					if(divsearchresulttext !=null)
					divsearchresulttext.style.display="none";
				}			
            talkToServer(new SearchAction(searchType, searchvalue.value, NumberPerPage, pageNumber));            
        }        
    }
    
// Display all messages contained in a ResponseBatch.
    function displayMessages(responseBatch) {
		var message = '';
		for (var i = 0; i < responseBatch.Messages.length; i++) {
			message += '<p>' + responseBatch.Messages[i].Message + '</p>';
		}
        if(message){ 			
			document.getElementById('tblSearchResultItems').innerHTML =message;			
		}
    }

    // called in response to talkToServer()
    // displays server message if not "ok"
    // dispatches responses
    function customCallBack(responseBatch) {
			
        if (responseBatch.Responses.length == 0) { 
            if (responseBatch.Messages.length == 1 && responseBatch.Messages[0].Message == 'ok') return;
            displayMessages(responseBatch); 
            return;
        }        
        for (var i = 0; i < responseBatch.Responses.length; i++) { 
		    var response = responseBatch.Responses[i];		    
            dispatchResponse(response);
            if(searchvalue.value !=''&& response.SearchResult.NumberOfSearchResults != '0')
			{			
				var searchText=document.getElementById('searchingtextresult');				
				searchText.innerHTML='Results for <b>' +  searchvalue.value + '</b>';
				//searchText.innerHTML='Results about <b>' + response.SearchResult.NumberOfSearchResults + '</b> for <b>' +  searchvalue.value + '</b>';
			}
        }
		// hidding loading images         
		var ele = document.getElementById('searchLoading');		
		ele.style.display="none";
		// showing the search pagination div
		var divsearchpagination =document.getElementById("searchPagination");	
		if(divsearchpagination !=null)
		divsearchpagination.style.display="inline";
		// showing the search result text div
		var divsearchresulttext =document.getElementById("searchingtextresult");	
		if(divsearchresulttext !=null)
		divsearchresulttext.style.display="inline";
		
        /*
        if(searchvalue.value !='')
		{			
			var searchText=document.getElementById('searchingtextresult');
			searchText.innerHTML='Results for users with <b>' +  searchvalue.value + '</b> as DisplayName';
		}
		*/
		
    }

    // decides what action to take based on what's in the response
    function dispatchResponse(response) {
		if (response.SearchResult !=null) {
		    // remove any existing content	
		     wipeObject('tblSearchResultItems');	    
				if (response.SearchResult.NumberOfSearchResults == '0') {				
					noItemsFound('tblSearchResultItems',true);
				} else {	     	
						renderSearchUsers(response.SearchResult);
				}
        }        
    }
   

    // if the server returns no items for a list, display an appropriate message
    function noItemsFound(objectID,noResultFlag) {  
		
		var searchText=document.getElementById('searchingtextresult');
		searchText.innerHTML='';
				      
        var trItem = document.createElement('tr');
        var tdItem = document.createElement('td');
        if(noResultFlag ==true) 
        {
			tdItem.innerHTML = '<span class="fs12 b tal pl05 pt05 pb10">We are sorry - this search produced no matching data.</span>';
        }
        else
        {
			tdItem.innerHTML = '<span class="fs12 b tal pl05 pt05 pb10">Please provide the search text.</span>';
        }
        trItem.appendChild(tdItem)	
        
        var tbdy = document.createElement('tbody'); 
		tbdy.appendChild(trItem);
        document.getElementById(objectID).appendChild(tbdy);       
       
        renderPagination(9, 1, 0)
    }
    

    // Renders paginated-related pages elements, including the header
    // and the previous/next footer.
    function renderPagination(numberPerPage, onPage, totalItems) {
	    var firstPage = 1;
        var nextPage = Number(onPage) + 1;
        var prevPage = Number(onPage) - 1;
        var lastPage = Math.ceil(totalItems/numberPerPage);
        
         // start ravi changes limited Page on Pagination Control on date : 4/7/2008
			var presentPage=1;
			var startcounter =1;
			var stopcounter =10;
			var MaxIndex =10;
			var Pagechecking =3;
			
			if(lastPage > 10)
			{
				if(parseInt(onPage) + 2 > Pagechecking) { presentPage =onPage; }			
				if(presentPage >Pagechecking) { startcounter =parseInt(presentPage) - 3; }			
				if(startcounter > 1) { 	stopcounter =parseInt(presentPage) + 4;  }									
				firstPage=startcounter;					
				if(stopcounter >10 && stopcounter <=lastPage)  { lastPage=stopcounter;	}
				else if(lastPage > MaxIndex) { lastPage=MaxIndex; }
				if(firstPage <0)  { firstPage =1; }
			}    
		// end ravi 
        
        var firstItem = onPage * numberPerPage - numberPerPage + 1;
        if (totalItems == 0) {
            firstItem = 0;
        }        

        var lastItem = onPage * numberPerPage;
        if (lastItem > totalItems) {
            lastItem = totalItems;
        }

        // write out footer
        var html = '';	
        if (firstPage < lastPage) {
            if (prevPage >= firstPage) {
				html +='<img id="ImgBack" class="curp" align="absmiddle" onclick="javascript:getPage(' + prevPage + '); RefreshFrames();" src="' + imgbackpath + '" />';
                html += ' <a class="tc01 fs11 pl05 pr05 tam" href="javascript:;" class="PrevNext" onclick="getPage(' + prevPage + '); RefreshFrames();" >Back</a>';                
            }
            for (i = firstPage; i <= lastPage; i++) {
			    if (i == onPage && i==1) {
				    html += '<span class="CurrentPage b">' + i + '</span>';
				} else if (i == onPage && i!=1) {
				    html += '| <span class="CurrentPage b">' + i + '</span>';
			    } else if (i==firstPage && i!=onPage) {
			        html += '<a href="javascript:;" class="GoToPage" onclick="getPage(' + i + '); RefreshFrames();">' + i + '</a>';
			    } else {
				    html += '| <a href="javascript:;" class="GoToPage" onclick="getPage(' + i + '); RefreshFrames();">' + i + '</a>';
			    }			    
		    }
            if (nextPage <= lastPage) {
                html += '<a class="tc01 fs11 pl05 pr05 tam" href="javascript:;" class="PrevNext" onclick="getPage(' + nextPage + '); RefreshFrames();">Next</a>';
                html +='<img id="ImgNext" class="curp" align="absmiddle" onclick="javascript:getPage(' + nextPage + '); RefreshFrames();" src="' + imgNextpath + '" />';
            }
        }
        document.getElementById('searchPagination').innerHTML =html;		
    }
    
   
    // output user search results
    function renderSearchUsers(searchResult) {			
		ResultCountperRow=0;				
        for (var i = 0, users = searchResult.SearchResults, user; user=users[i]; i++) {			
            var britem =document.createElement('br');
            britem.setAttribute('clear','all');
            
            if(ResultCountperRow ==0)
            {				
				var trItem = document.createElement('tr');
				trItem.setAttribute('valign', 'top');
            }
            
            var tdItem = document.createElement('td');
            tdItem.width=100;
            tdItem.align = "center";
            tdItem.className = 'tdimage bc06 pl10 pt10 pb10 pr10 tac';
            
            // create img line	
            var imganchor = document.createElement('a');
            imganchor.href='/MyHollywood/UserProfile.aspx?UserId=' 
                + user.UserKey.Key + '&plckPersonaPage=PersonaHome&UserName='+ user.DisplayName;
            
		   var imgh =document.createElement('img');
           imgh.src=user.AvatarPhotoUrl; 
           imgh.border=0;               
           imganchor.appendChild(imgh);
           tdItem.appendChild(imganchor);
           
           var bre = document.createElement('br');
           tdItem.appendChild(bre);
            
            // create link
            var anchor = document.createElement('a');
            anchor.href = '/MyHollywood/UserProfile.aspx?UserId=' 
                + user.UserKey.Key + '&plckPersonaPage=PersonaHome&UserName='+ user.DisplayName;
            
            if(user.DisplayName.length > 18){
				anchor.innerHTML = insertWhitespace(user.DisplayName);         
            }            
            else {
				anchor.innerHTML = user.DisplayName;     
            }       
               
            tdItem.appendChild(anchor);            
            ResultCountperRow =ResultCountperRow + 1;        	
			trItem.appendChild(tdItem)	
			 
			var tbdy = document.createElement('tbody'); 
			tbdy.appendChild(trItem);
						
			var searRes= document.getElementById('tblSearchResultItems');			
			searRes.appendChild(tbdy);
			
			// add to list 
			if(searchResult.NumberOfSearchResults >3 && ResultCountperRow ==3)	{				
				ResultCountperRow=0;                    
			}                
        }      
         
      renderPagination(searchResult.NumberPerPage, searchResult.OnPage, searchResult.NumberOfSearchResults);
    }
       
      // to insert the white space after 18 characters
      function insertWhitespace(username)
      {		
		var T_username_len = username.length;
		var Ret_userName='';		
		var firstline =18;
		var secondline = 2*18;
	    
		if(T_username_len > firstline) {
			if(T_username_len > secondline) {					
					Ret_userName = username.substring(0, firstline) + " " + username.substring(secondline, (T_username_len - secondline)) + " ..";
			}
			else {					
					Ret_userName = username.substring(0, firstline) + " " + username.substring(firstline,T_username_len);
			}
		}	
		else {				
				Ret_userName = username; 
		}
		return Ret_userName;
      } 
    
     // removes all child objects from a given object
    function wipeObject(objectID) {
		var removeSearchresult= document.getElementById('tblSearchResultItems');		
       while (removeSearchresult.firstChild != null) {			    
           document.getElementById('tblSearchResultItems').removeChild(document.getElementById('tblSearchResultItems').firstChild);
        }       
    }


    var startTime;
    var searchType = 'User';
    var NumberPerPage =9;

function StartupUserKey()
{	
  talkToServer(new UserKey(''));
}

//-------------------------------------End of Search DAAPI Function --------------------------------------------
/*
//This is the object that builds the User
function fnUser(userKey,displayName,eMail,avatarPhotoURL,userTier,lastUpdated,age,sex,aboutMe,location,isBlocked,recommendationsCount,messagesCount,friendsCount,pendingFriendsCount,messagesOpenToAll,personaPrivacyMode,customAnswers,extendedProfile,dob,commentsVisible,photosVisible,IsEmailNotificationsEnabled,selectedStyleId,signature)
{
	this.UserKey = userKey;
	this.DisplayName = displayName;
	Email;
	AvatarPhotoURL;
	UserTier;
	LastUpdated;
	Age;
	Sex;
	AbboutMe;
	Location;
	IsBlocked;
	RecommendCount;
	MessageCount;
	FriendsCount;
	PendingFriendsCount;
	MesssageOpenToAll;
}
*/

//function to retreive avatar image of the user
function getAvatarImage()
{
	var userId = document.getElementById('hdn_avatarUserID');
    try {
	    // create a request batch
        var requestBatch = new RequestBatch();
        // add the userKey to the request
        var userKey = new UserKey(userId.value);
        requestBatch.AddToRequest(userKey); 
        // initiate the request.  The response will be passed to the renderUserData() method.
        requestBatch.BeginRequest(serverUrl, renderUserData);
    }
    catch(e) {
        // set the default avatar image      
        var avaimg = document.getElementById('imgAvatar'+userId.value)
        if(avaimg !=null){  avaimg.src = "http://sitelifestage.hollywood.com/ver1.0/Content/images/no-user-image.gif"; }
    }
	
}

function renderUserData(responseBatch) 
{
	if (responseBatch.Responses.length == 0) 
	{
    } 
    else
    {
		// get the user object out of the response
        var user = responseBatch.Responses[0].User; 
        document.getElementById('imgAvatar' + user.UserKey.Key).src = user.AvatarPhotoUrl;
		
	    //create the AvatarImage cookie & set the value for this.
	    document.cookie = avatarCookie + "=" + user.AvatarPhotoUrl + ";path=/;domain=" + document.domain;	
		
    }
}


/******************** Facebook methods *******************/
var fbUserId;
var signInDiv;
var loggedInDiv;
var loginDiv;
var divLinkAc;	
var termsDiv;
var linkDiv;
var txtDisplayName;
var newMemErrorDiv;

//addLoadListener(initialiseFB);

function initialiseFB()
{	        	    
    slFB.init(FBInitialised);	    	        	    
}
function FBInitialised()
{
   
}

function isFBPicExists()
{
    var exists;
    var FBCookie = GetCookie(cookie_HWFaceBook);
    if(FBCookie)
    {        
        var FBValues = FBCookie.split('&');
  
        if(FBValues.length > 2)
        {
            exists = true;
        } 
        else
        {
            exists = false;
        }               
    }
 
    return exists;
}

function getFBImage(callback)
{
    if(!isFBPicExists())
    {
        
        var uid = slFB.currentUserFacebookId();
	    var fql = 'SELECT name,  pic_square_with_logo FROM user WHERE uid='+uid;

		    FB.Facebook.apiClient.fql_query(fql, function(result) 
		    {						
			    var pic_value = result[0].pic_square_with_logo;			    
			    if(pic_value == '')
			    {
			        pic_value = "http://static.ak.connect.facebook.com/pics/q_silhouette_logo.gif";
			    }			
    		    
		        //update HWFBCookie
		        var FBCookie = GetCookie(cookie_HWFaceBook);
		        
		        /* Fix for IE, which does not like value having &amp; */
		        pic_value = unescape(pic_value)
		        pic_value = pic_value.replace(/&amp;/g,"&");
		        pic_value = encodeURIComponent(pic_value);
                if(FBCookie)
                {               
                    document.cookie = cookie_HWFaceBook + "=" + FBCookie + "&pic=" + pic_value + ";path=/;domain=" + document.domain;
                    if(callback)
                    {
                        callback();
                    }
                }               
		    });
    }    
}

function setFBImage()
{
    if(isFBPicExists())
    {           
        var pic_value = decodeURIComponent(getCookieParam(cookie_HWFaceBook,"pic"));
        //update the image on the UI
        var eleId = noAvatarImage;					;
	    if(document.getElementById(eleId))//if no user logged in
	    {
	        var ele = document.getElementById(eleId);
	        ele.innerHTML = "<img id='imgAvatar_noUser' src='" + pic_value + "' height='32' width='32' />";	        
	        ele.className= "fll pl10 pt07";        
	    }
	    else  //if user logged in
	    {	
	        if(document.getElementById('imgAvatar_userLoggedin'))
	        {		    
	            document.getElementById('imgAvatar_userLoggedin').src = pic_value;
	        }
	        else
	        {
	            var ele = document.getElementById('hdn_avatarUserID');
	            if(ele)
	            {
	                var ele1 = "imgAvatar" + ele.value;
	                if(document.getElementById(ele1))
	                {
	                    document.getElementById(ele1).src = pic_value;
	                }
	            }
	        }
    	    
	    }			
    	
	    //update the pluck avatar cookie    		
        document.cookie = avatarCookie + "=" + pic_value + ";path=/;domain=" + document.domain;
    }
    else
    {
        getFBImage(setFBImage);
    }
}

function updateLinkScreen()
{
    var FBDisplayName = getCookieParam(cookie_HWFaceBook,"d");
    var fbPhoto = decodeURIComponent(getCookieParam(cookie_HWFaceBook,"pic"));
    if(fbPhoto.toString() != "")                
    {        
        linkDiv.innerHTML = "<img src='" + fbPhoto + "' class='pr10' />Welcome, " + FBDisplayName.toString();
    }
    loginDiv.style.display = "none";
    divLinkAc.style.display = "block";
    termsDiv.style.display = "none";
    //set the focus to display name on linking screen
    setFocus();	    
    showPopUp();
}

function FBLogin()
{	 
    hidePopUp();   
    slFB.login(onSuccessfullLogin);
}

function onSuccessfullLogin()
{ 
    //get the logged in user FB ID
    fbUserId = slFB.currentUserFacebookId();   
   
    //Invoke the webservice passing the fbId
    HWWebUI.FBIntegrate.AuthenticateFBUser(fbUserId.toString(),AuthenticateFBUserCallback);           
}

function AuthenticateFBUserCallback(result)
{
    //if webservice does not return 1, then show the modal dialog
    if(result != 1 && linkDiv)
    {                       
        if(!isFBPicExists())
        {
            getFBImage(updateLinkScreen);
        }                
        else
        {
            updateLinkScreen();
        }      
    }
    else
    {
        updateDisplayName();
        setFBImage();
        if(FbComments == true)
        {
            submitPluckComment(commentArticleId,commentTextId);
        }        
    }
}

function setFocus()
{
    try
    {
        txtDisplayName.focus();
    }
    catch(e)
    {
        setTimeout(setFocus,500);
    }
    
}

function insertNewFBUser(displayName)
{
    HWWebUI.FBIntegrate.CreateNewFaceBookMember(fbUserId,displayName,insertNewFBUserCallback);
}

function insertNewFBUserCallback(result)
{  
    if(result == 1) //success
    {
        updateDisplayName();
	    setFBImage();
        //if want to post FB comments
        if(FbComments == true)
        {	
            submitPluckComment(commentArticleId,commentTextId);
        }	    	           
    }
    else
    {
        newMemErrorDiv.className = "h15 bo1 boc03 mt10 fs11 b tc06 mb10 pb02 pt02 pl05";
        newMemErrorDiv.innerHTML = "Sorry...an error occured.";
    }
}

function linkAccounts(hwUserName,hwPassword)
{
    HWWebUI.FBIntegrate.LinkFaceBookUserLogin(fbUserId,hwUserName,hwPassword,linkAccountsCallback);
}

function linkAccountsCallback(result)
{
    //if webservice returns 1
    if(result == 1)
    {
        updateDisplayName();
	    setFBImage();
        //if want to post FB comments
        if(FbComments == true)
        { 
            submitPluckComment(commentArticleId,commentTextId);
        } 
    }
    else
    {
       newMemErrorDiv.className = "h15 bo1 boc03 mt10 fs11 b tc06 mb10 pb02 pt02 pl05";
       newMemErrorDiv.innerHTML = "Invalid Username / Password.";
    } 	        	               
}

function isFBUserExistsInHW()
{
    var exists = false;   
    var FBExists = getCookieParam(cookie_HWFaceBook,"userexist");
    if(FBExists == "1")
    {
        exists = true;
    }
    else
    {
        exists = false;
    } 
    return exists;  
}

function updateDisplayName()
{
    hidePopUp();
    var ATCookieValue = GetCookie(cookie_AT);
    if(ATCookieValue !=null) {           
         var userDisplayName= unescape(getCookieParam(cookie_AT,"a"));
         var plckLoginId = getCookieParam(cookie_AT,"u");          
         if(signInDiv)
         {
            signInDiv.innerHTML = "";                
            signInDiv.innerHTML = "<div class='b h25 pb02 ofh'>Welcome <br/><a href='/MyHollywood/UserProfile/?UserId=" + plckLoginId + "&plckUserId=" + plckLoginId +"' class='memberLink'>" + userDisplayName + "</a></div><div><a onclick='javascript:doSignOut();' href='javascript:;' id='signout'>Sign Out</a></div>";                
         } 
         if(loggedInDiv)
         {
            loggedInDiv.innerHTML = "";                
            loggedInDiv.innerHTML = "<div class='b h25 pb02 ofh'>Welcome <br/><a href='/MyHollywood/UserProfile/?UserId=" + plckLoginId + "&plckUserId=" + plckLoginId +"' class='memberLink'>" + userDisplayName + "</a></div><div><a onclick='javascript:doSignOut();' href='javascript:;' id='signout'>Sign Out</a></div>"; 
         } 
         // update the comment Input widget if available
         updateCommentInputUI();
    }   
}

function getCookieVal (offset) 
{
    var endstr = document.cookie.indexOf (";", offset);
    if (endstr == -1) { endstr = document.cookie.length; }
    return (document.cookie.substring(offset, endstr));
}

function GetCookie (name) 
{
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;
  while (i < clen) {
    var j = i + alen;
    if (document.cookie.substring(i, j) == arg) {
      return getCookieVal (j);
      }
    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0) break; 
    }
  return null;
}

function getCookieParam(name,key)
{
    var _cookie = GetCookie(name);
    if(_cookie)
    {
        var _cookieValues = _cookie.split('&');
        var _param;
        for(var i=0;i<_cookieValues.length;i++)
        {
            _param = _cookieValues[i].split('=');
            if(_param[0] == key)
            {
                return _param[1].toString();
            }
        }
        if(i == _cookieValues.length)
        {
            return null;
        }
    }
    else
    {
        return null;
    }
}

function showPopUp()
{      
    var modalId = _popUpExt1;
    var AddModal = $find(modalId);
    var ele = document.getElementById('loginLoading');
    ele.style.display="none";    
    if(AddModal)
    {
        AddModal.show();         
    }
    else
    {
        modalId = _popUpExt2;
        AddModal = $find(modalId);        
        if(AddModal)
        {
            AddModal.show();         
        }
    }        
}

function FBSignOut()
{
   if(isFBUserLoggedIn())
   {       
        slFB.logout(FBLogoutCallback);
        //to resolve the delay issue in IE6 & IE7
        setTimeout(callFBLogoutCallback,5000);
   }
   else
   {
        var currentURL=document.location.href;
	    var currentURLArr=currentURL.split("#");
	    document.location.href=currentURLArr[0];
   }
}

function FBLogoutCallback()
{     
    var currentURL=document.location.href;
	var currentURLArr=currentURL.split("#");
	document.location.href=currentURLArr[0];	 
}
function callFBLogoutCallback()
{
    FBLogoutCallback();
}

function checkEmail(inputvalue){	
    var pattern=/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
    if(pattern.test(inputvalue)){         
		return true;
    }else{   
		return false;
    }
}

function encode_value(value) {
  var coded_string = ""  
  for (var counter = 0; counter < value.length; counter++) {  
    coded_string += value.charCodeAt(counter)    
    if (counter < value.length - 1) {
      coded_string += "+"
    }
  }
  return coded_string
}

function decode_value(coded_string) {
  var value = ""  
  var code_array = coded_string.split("+")  
  for (var counter = 0; counter < code_array.length; counter++) {
    value += String.fromCharCode(code_array[counter])
  }
  return value
}

function createCookie(name,value,hours) {
	if (hours) {
		var date = new Date();
		date.setTime(date.getTime()+(hours*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/;domain=" + document.domain;
}

function getCommmentUserField() {
    var username=getCookieParam(usercookie,"name"); 
    if(username !=null) {   
        if(document.getElementById("CommentInput_username").value !=null) {
            document.getElementById("CommentInput_username").value = decode_value(username);
        }
    }
    var useremail =getCookieParam(usercookie,"email");
    if(useremail !=null) {
        if(document.getElementById("CommentInput_emailId").value !=null) {
            document.getElementById("CommentInput_emailId").value =decode_value(useremail);
        }
    }
}

function getCommmentDisplayName() {
    var displayname=getCookieParam(cookie_AT,"a"); 
    if(displayname !=null) {   
        if(document.getElementById("CommentInput_displayName") !=null) {
            document.getElementById("CommentInput_displayName").innerHTML ='"'+ displayname +'"';
        }
    }
}

function updateCommentInputUI() {
    var commentInputLoginDiv = document.getElementById('commentInputLogin');
    if(commentInputLoginDiv !=null) {
        var displayname=getCookieParam(cookie_AT,"a"); 
        var html='<div class="title_Text pt05 tal"><div class="fs11 pr04 fll pl05">The comments will be tracked under your Display Name </div>';
        html+='<div id="CommentInput_displayName" class="fll b">"'+ displayname + '"</div><br clear="all" /></div>';
        commentInputLoginDiv.innerHTML = html; 
        var text =document.getElementById('hdnCommentTextId').value;						
	    if (text != null) {	
	        document.getElementById(text).focus();	    		    
	    }       
    }
}