/*
    Gannett - Sitelife Integration JavaScript API 

    This script if responsible communicating with USAToday and SiteLife servers, 
    to deliver custom SiteLife widgets.  These widgets include:
        - User Avatar
        - Comments (Comment form and paginated comment list)
        - Review Widget (Review form and paginated review List)
        - Article Reaction Count Control
        - Article Recommend Control
        - Article Discovery Controls

    Dependancies:
        - SiteLife Direct Access API
            - prototype
            - scriptaculous

    References to integrated technologies: 
        - SiteLife DAAPI    http://sitelifestage.usatoday.com/api/index.htm         
        - AJAX              http://en.wikipedia.org/wiki/Ajax_%28programming%29
        - AHAH              http://microformats.org/wiki/rest/ahah        
        - Pork iFrames      http://www.schizofreend.nl/Pork.Iframe/
        - JSON Transforms   http://goessner.net/articles/jsont/
        - Prototype         http://www.prototypejs.org/
        - Scriptaculous     http://wiki.script.aculo.us/scriptaculous/
 
   Created: 1/10/07 by Josh West of Amentra, Inc for USAToday.com
    Modified: 4/04/2007 by Kevin Meredith and Sophak Phou of Amentra, Inc for GMTI.
        - Added functionality specifically for GMTI purposes
        - Removed USAToday specific functionality.
    Modified: 4/20/2007 by Kevin Meredith
        - Added contentURL to getArticleLink function
        - Added comment/recommend count to Discovery Actions
        - Added decodeURI() function to Discovery Actions title
   Modified: 07/17/2007 by Sophak Phou
            - Added function to populate dynamic html tags load onto page after initial onload function(DynamicArticleControls)
 Modified 3/3/2008 by SSS
	 - Added maximum comment character count to be dynamic
	 - Added sort order for article commnets
Modified 5/01/2008
	Added user friendly error message if, user enters space in comment box.                            
	Added a fix to clear the avatar variable to fix issue with wrong avatar on article pages & persona page occasionally.                       
	Added implementation to handle the time offset for Hawaii/Guam sites's comments.        
	Added new Reply-To and "New post" feature to article comments and also a new Full comments article page where user can view just comments.                                 
	Fixed a bug where sort option shows up if the article has only recommends and not comments. 
Modified 5/28/2008
	Added a feature to display the remaining number of characters
	Changed the pagination links on articlecomments to execute the full page refresh. 
	Page will also refresh whenever user submits the comments or changes the sort order. 
Modified 6/30/2008
	Added monitoring function to check avalaibility and rendring issues of daapi calls 
Modified 9/8/2008 by SSS
	Removed extra pluck batch call
	Fixed bug in UpdateArticleAction function
	Added Article authors id to batch call
	Added pagination link at top for full comment page 
Modified 9/25/2008 SSS
	Updated all the relative URL to fix issue with URL rewrite.
Modified 10/09/2008 SSS
	Added new function getDiscoveryTabcontent to support the frontpage tab module
	Updated the ArticleControls function.
Modified 03/27/2009 SSS
	Commented the unnecessary condition inside requestbatch function
	modifed the code to support the AT cookie expire function
Modified 05/08/2009 YT
	Added new function to support Comment Pre Moderation.
Modified 10/12/2009 SSS
	Added the code to scrub the HTML out of comment
 */
var gsl = {
    
    /*************************************************************************/
    /* Site Configurations ***************************************************/
    enabled: true,
    sitelifeApiUrl: "",
    personaHrefEnabled: true,
    personaHrefURL: "",
    commentCountHrefEnabled: true,
    reviewCountHrefEnabled: true,
    recommendCountHrefEnabled: true,
	reportabuseposx:"",
	reportabuseposy:"",
	fullcommentpage:0,
	totalnocomments:0,
	resized:false,
	params:"",
    /* Default Configuration *************************************************/
    /*************************************************************************/
    linkLblUrl: new Array(),
    linkUrl: new Array(),
    linkUIDEnabled: new Array(),
    personaHref:" ",
    personaUserKey:" ",
	dynElement:null,
	wilDaapiWork:"true",
	plkIframeId:99,
	initDaapiReq:"http://sitelife."+ document.domain +"/ver1.0/Content/images/no-user-image.gif",
	pluckSigninPage:"/apps/pbcs.dll/section?category=Pluck_signin",	
    // Page Configuration Settings (modify on individual pages -or- in environment config)
    exceptionLogging: false,    // on/off - log gsl exceptions    
    apiLogging: false,          // on/off - log sitelife calls
    widgetLogging: false,       // on/off - log interactions with custom sitelife widgets
    Debug: 1,                   // on/off - if debugDiv exists display debugging info
    _updateArticle: false,      // DO NOT MODIFY!
    _keyUsed: false,
    IsOdd:1,
	plkreplycomment:"",
    /*************************************************************************/
    /* Fronts Controls *******************************************************/
    // Fronts Controls Environment Configuration
    requestsPerBatch: 10,
    
    // Fronts Controls Page Configuration
    discoveryAge: "12",    // number of days for discovery widgets
    
    /*************************************************************************/
    /* GMTI SiteLife Library Initialization **********************************/

    initialSetup: function(userID) {
        try {
		    if(this.enabled==true) {
				this.checkDaapiAvailable();
				if (this.wilDaapiWork=="true"){
	        		 if($("gslComments")) {
						//check is user is recaching the page
						var checkURL = window.location.href.toLowerCase();
						if((checkURL.indexOf("cmsedit") > 0 || checkURL.indexOf("cmsstage") > 0 || checkURL.indexOf("cmsqa") > 0) && checkURL.indexOf("nocache=1") > 0)
							{
							var SetContentPolicy = "";
							//if so, check CommentPreModeration value
							if(typeof(CommentPreModeration) != undefined && CommentPreModeration == 'checked')
								{
								SetContentPolicy = "ApprovalRequired";
								} else {
										SetContentPolicy = "Allowed";
										}
							gsl.CommentPreModeration(SetContentPolicy);
							}
						this.Comments(); 
					}
					 else if($("gslReviews")) {   this.Reviews();   } 
					//if(typeof(contentID) != "undefined") { this.AddThisArticle(); }
	                if(gsl.ArticleControls) { gsl.ArticleControls(); }  // Scans page for Article Controls
				}
				else
					document.getElementById("IE6Error").style.display ="block"; 
            }   
        } catch(e) {
            this.showException("initialSetup", e);
        }
    },
	//Make a Call to Set Comment Policy for that article
	CommentPreModeration: function(SetContentPolicy) {
			var rb= new RequestBatch();
			var setPolicyRequest = new SetContentPolicyAction(new ArticleKey(contentID), new UserTier("Standard"), new ContentPolicyActionType("Comment"), new ContentPolicy(SetContentPolicy));
            rb.AddToRequest(setPolicyRequest);
            //rb.BeginRequest(serverUrl, OnSetComplete);
			this.sitelifeRequest(rb, "Set Comments Policy", this.OnSetComplete); 
	},
	//Dislpay what Pluck returns back
	OnSetComplete: function(ReturnedJSON) {
		//Don't do anything in the Call back function for now.
    },


  _templates: {'comments': {'loaded': false}, 'reviews': {'loaded': false}},
    _avatarOverride: false,
    _updateArticle: false,
    
    /*************************************************************************/
    /* SiteLife User *********************************************************/
    
    getUserPhotoLink: function(pid, photo) {
        if(pid != "anonymous"){
            var personaHtml= "<img src='" + photo + "' alt='User Image'/>"; 
            gsl.personaHref = photo;
            if(gsl.personaHrefEnabled){
                var personaHtmlHref = "<a href='" + gsl.sitedomain+gsl.personaHrefURL + '&U=' + pid + "'>" +personaHtml+ "</a>";
                personaHtml = personaHtmlHref;
            }
            return personaHtml;
        }
        else return "";
    },

    getUserPersona: function(pid) {
        return gsl.sitedomain + gsl.personaHrefURL + '&U=' + pid;
    },
    
    
    getUserHandle: function() {
        var cookie = GDN.Cookie.Get("at");
		return gsl.TempGetnamevalue(cookie,"a");
    },
    
    getUserHandleLink: function(pid, handle,aboutme,age,location,sex) {
        var personaHref= this.getUserPersona(pid);
      
	  var handleHtml= "<a href='" + gsl.sitedomain+gsl.personaHrefURL + "&U=" + pid + "'><b>" + handle + "</b></a>"; 
        return handleHtml;       
    },
    
    getUserPid: function() {
       return GDN.Cookies.Pluck.GetValue("UserId");
    },
    
    getUserMsgsLink: function(msgs) {
        var msgLink = "<a href='" + this.personaUrl + "?plckPersonaPage=PersonaMessages'>" + msgs + " messages</a>";
        return msgLink;
    },

   /*************************************************************************/
    /* Report Abuse - ra *****************************************************/
    
    getReportAbuseLink: function(type, key, reported) {
        var raHtml= "";
        
        if (reported==true) {
            raHtml += "<span id='gslReportAbuse:" + type + ":" + key + "' class='gslAbuseReported'>Reported</span>"; 
        } else {    
            raHtml += "<span id='gslReportAbuse:" + type + ":" + key + "' class='gslReportAbuseLink'>";    
            raHtml += "<a href='#none' onclick=\"javascript:gsl.ReportAbuse(event, '" + type + "', '" + key + "'); return false;\">Report Abuse</a>";			
            raHtml += "</span>"; 
        }
        return raHtml;    
    },
	
	getReplyToLink: function(key) {
	var replyhtml= "<a class='reply' href='javascript:gsl.addquote(\""+key+"\")';>Reply to this Post</a>";
	return replyhtml;
	},
	
	ReportAbuse: function(evt, type, key) {
      this._showDivAtMouse(evt, "gslReportAbuseForm");
        $("gslReportAbuseType").value= type;
        $("gslReportAbuseKey").value= key;
    },
    
    reportAbuseSubmit: function() {
        var key= $("gslReportAbuseKey").value;
        var type= $("gslReportAbuseType").value;
        var text= $("gslReportAbuseCommentText").value;
        var reason= $("gslReportAbuseReason").value;
       this.reportAbuseClose();

        var cntKey= null;
        if (type == 'comment') {
            cntKey= new CommentKey(key);
        } else if (type == 'article') {
            cntKey= new ArticleKey(key);
        } else if (type == 'review') {
            cntKey= new ReviewKey(key);
        } else if (type == 'photo') {
            cntKey= new PhotoKey(key);
			//gpg.pgAbuseArray[$("gsl_pg_currentno").value]= true;
			if (typeof(gpg.localMasterPGArray)!='undefined')
			gpg.localMasterPGArray[gpg.globalpgpageno][$("gsl_pg_currentno").value].CurrentUserHasReportedAbuse = "true";
		}		

        var raReq= new RequestBatch();	 
        raReq.AddToRequest(new ReportAbuseAction(cntKey, reason, text)); 
        this.sitelifeRequest(raReq, "SubmitReportAbuse", this._reportAbuseCallback);
        
        var raLink= $("gslReportAbuse:"+type+":"+key);
        if(raLink) raLink.innerHTML= this.getReportAbuseLink(type, key, true);   
    },
    
    _reportAbuseCallback: function(res) {
        if(res.Messages.length > 0 && res.Messages[0].Message=="ok") {
        } else {
            alert("Report Abuse Failed: " + res.Messages[0].Message);
        }
    },
    
    reportAbuseClose: function() {
        this._hideDiv("gslReportAbuseForm");
        $("gslReportAbuseKey").value= "";
        $("gslReportAbuseType").value= "";
        $("gslReportAbuseCommentText").value= "";
        $("gslReportAbuseReason").value= "Obscenity or vulgarity";       
    },   
        

  /*************************************************************************/
    /* Comments - com ********************************************************/
    
    Comments: function() {
        // expects <div id="gslComments"></div> to exist on page
        // <div id="gslCountControl"> and <div id="gslRecommendControl"> optional
        
        // Load Comment Templates
		 gsl._templates.comments['loaded']= true;
      
		  if(gsl.reactionsClosed==false) {
            gsl.updateReactionFormHead('comment');
        }
		 gsl.getReactions('comment');  
		
    },
          
    /*************************************************************************/
    /* Reviews - rev *********************************************************/    

    Reviews: function() {
        // expects <div id="gslReviews"></div> to exist on page
        // <div id="gslCountControl"> and <div id="gslRecommendControl"> optional
        
        // Load Review Templates
        gsl._templates.reviews['loaded']= true; 
               if(gsl.reactionsClosed==false) {
         
            gsl.updateReactionFormHead('review');
        }  
		gsl.getReactions('review'); 		
    },
    
    getReviewCountControl: function(count, link) {
        var revCntCtl="";
        revCntCtl= "<span class='gslReviewsLink'><a href='" + link + "' alt='Go to reviews'><span class='gslReviewsLabel'>Reviews</span><span class='gslReviewsCount'>" + gsl.niceNumber(count) + "</span></a></span>";        
        return revCntCtl;        
    },
    
    getRatingControl: function(rating, enabled) {
        var ratCtl= "";      
        if(enabled==true && this._templates.reviews['loaded']==true) {
            ratCtl= this._templates.reviews['ratingControl'];           
        } else {
            ratCtl = "<img alt='' src='" + this.ratingStarsUrl + "null_zero.jpg' border='0' />";
            ratCtl += "<img alt='' src='" + this._getRatingImageUrl('0') + "' border='0'>";
        }       
        return ratCtl;
    },
 
    getRatingImage: function(rating) {
        var ratHtml= "<img alt='' src='" + this._getRatingImageUrl(rating) + "' border='0'>";
        return ratHtml;  
    },
    
    _getRatingImageUrl: function(rating) {
        var starsUrl = "";
        var ratNum = parseInt(Math.round(rating));
        switch(ratNum) {
            case 1: starsUrl = this.ratingStarsUrl + "00.jpg"; break;
            case 2: starsUrl = this.ratingStarsUrl + "05.jpg"; break;
            case 3: starsUrl = this.ratingStarsUrl + "10.jpg"; break;
            case 4: starsUrl = this.ratingStarsUrl + "15.jpg"; break;
            case 5: starsUrl = this.ratingStarsUrl + "20.jpg"; break;
            case 6: starsUrl = this.ratingStarsUrl + "25.jpg"; break;
            case 7: starsUrl = this.ratingStarsUrl + "30.jpg"; break;
            case 8: starsUrl = this.ratingStarsUrl + "35.jpg"; break;
            case 9: starsUrl = this.ratingStarsUrl + "40.jpg"; break;
            default: starsUrl = this.ratingStarsUrl + "00.jpg"; break; 
        }
        return starsUrl;
    },

    _fillRatingStar: function(ratingStars, ratingField, rating) {
        var ratStars= $(ratingStars);
        var ratField= $(ratingField);
        
        var oldRating= parseInt(ratField.value,10);
        var newRating= rating;
        
        if (newRating < 1 && oldRating >= newRating) { newRating = oldRating};
        
        if (newRating >=1 && newRating <= 9) {
            ratStars.src = this._getRatingImageUrl(newRating);
        } else {
            ratStars.src = this._getRatingImageUrl('0');
        }
    },
    
    _setRating: function(ratingField, rating) {
        var ratField= $(ratingField);
        ratField.value= rating;
    },
	
	addquote:function(key) {
	var content;
	if(key){
		var author = $("author_"+key).value;
		content = $("body_"+key).value;
		gsl.plkreplycomment = content;
	}
	var form_id = "gslComFormBody";
	var form_el = $(form_id);
	if(content){
		author = author.replace(/.+<b>([^<]+)<\/b>.+/i, "$1");
		content = "[QUOTE]"+content+"[/QUOTE]\n";
		$('gslQuoteAuthor').value = "<span class='author'>"+author+"</span>";
		form_el.value = content;
	} else {
		form_el.value = "";
	}
	var frmEl = $("gslComFormBody");
		if (!frmEl.disabled){
			frmEl.scrollTo();
			frmEl.focus();
			gsl.char_count(frmEl);
		}
	},

    /*************************************************************************/
    /* Reactions - aka Comments and Reviews Common Logic *********************/
   
    getReactions: function(type, page) {
   
		gsl.params = new String(window.location.href.toString().replace(/^[^\?]+\?/,"")).toQueryParams();
		if (typeof(gsl.params["pluckarticleid"]) != 'undefined' ){
			$("pluckarticleid").style.display ="block";
			$("pluckarticleid").innerHTML = "Pluck Article ID = " + contentID;
			}
			if (gsl.fullcommentpage)
					window["contentID"] = gsl.params["key"];
		if (typeof(gsl.params["page"])!='undefined') gsl.params["page"] = gsl.params["page"].replace("#pluckcomments","");
		page = gsl.params["page"] || 1;
		if (typeof(gsl.params["s"])=='undefined') gsl.params["s"]=$('gslSortOrder').value ;
	
		this.commentSortOrder = ((gsl.params["s"] == "a") ? "TimeStampAscending" : "TimeStampDescending");
		//After 1.2.4 please delete or change the follwoing first if condition 
		if (typeof($("gslCharCount"))!='undefined' || gsl.fullcommentpage){
			if(this.commentSortOrder=="TimeStampAscending") {
				$('gslSortOrder').value = "a";
			} else {
				$('gslSortOrder').value = "d";
			}
		}
		else
			$('gslSortOrder').value = this.commentSortOrder;
		
		if(typeof($("gslCharCount"))!='undefined') $("gslCharCount").innerHTML = gsl.commentMaxChars;
		this.commentSortOrder = ((this.commentSortOrder=="") ? "TimeStampDescending" : this.commentSortOrder);
        var articleKey= this.getArticleKey();
        
        var rb= new RequestBatch();
         
        if (type=='comment') {
            rb.AddToRequest(new CommentPage(new ArticleKey(articleKey),gsl.requestsperBatch,page,this.commentSortOrder));
        } else if (type=='review') {
            rb.AddToRequest(new ReviewPage(new ArticleKey(articleKey),gsl.requestsperBatch,page,this.reviewSortOrder));
        } else {
            this.showException("getReactions: type not specified");
        }
       
        rb.AddToRequest(new ArticleKey(articleKey));
		if(typeof(contentAutID)!= 'undefined' && contentAutID != "") 
			rb.AddToRequest(new UserKey(contentAutID));
        this.sitelifeRequest(rb, "LoadReactions", this._getReactionsCallback);   
    },
    
    _getReactionsCallback: function(resBatch) {
        var rPage= null;
        var rList= null;
        var rType= null;
        var article= null;
        var i= 0;
        for ( i=0; i<resBatch.Responses.length; i++) {
            var res = resBatch.Responses[i];           
            if (res.CommentPage != null) {
                rPage= res.CommentPage;
                rList= res.CommentPage.Comments;
                rType= 'comment';   
             } else if (res.ReviewPage != null) {
                rPage= res.ReviewPage;
                rList= res.ReviewPage.Reviews;
                rType= 'review';        
            } else if (res.Article != null ) {
                article= res.Article;
			
				if (res.Article.Comments.NumberOfComments > 1 && (typeof($("gslsort"))!='undefined' && $("gslsort")!=''))
				$("gslsort").style.display ="block";	
				if (gsl.fullcommentpage){
					window["contentURL"] = article.PageUrl;
					window["contentTitle"] =article.PageTitle;
					var titleLink = document.createElement("a");
					titleLink.setAttribute("href", article.PageUrl);
					titleLink.innerHTML = article.PageTitle;
					$("gslTitleName").innerHTML = "for <span></span>";
					var el = $("gslTitleName").getElementsByTagName("span")[0];
					el.appendChild(titleLink);	
				}
				gsl.totalnocomments= parseInt(res.Article.Comments.NumberOfComments);
				
				// var bylinedivs= document.getElementsByClassName("ratingbyline");
				// for(i=0; i<bylinedivs.length; i++) {
				// var bylinediv = bylinedivs[0];
				
            
			 } else if (res.User != null ) {
					if (typeof($("gslshowAuthImg"))!='undefined' ) {
					var authdiv = $("gslshowAuthImg");
					var authdivtext = "";
					authdivtext = "<a href=\"/apps/pbcs.dll/section?category=pluckpersona&U="+res.User.UserKey.Key +"\" alt='Go to Author persona'>";
					authdivtext +="<img src=\""+res.User.AvatarPhotoUrl+"\" alt=\"Author Image\">";
					authdivtext +="<\/img><\/a>";
					authdiv.innerHTML = authdivtext;
					
				}
				}
        }
        // save reponses page for debugging purposes (javascript:alert(gsl.responses.toJSONString().replace(/:{/g, ":\n{").replace(/},/g, "},\n"));)
        if (resBatch.Responses) { gsl.responses = resBatch.Responses; }        
            
        // set UpdateArticleAction flag if article has not been updated yet
        //if(!article || (article && (!article.Section || article.Categories.length==0))) {      
         //   gsl._updateArticle= true;
       // }
		
		 gsl._updateArticle = gsl._compareArticleInfo(article);
		if (gsl._updateArticle && gsl.updateOnLoad) {
                    var rb = new RequestBatch();
                    gsl.sitelifeRequest(rb, "UpdateArticle", gsl._upArtCB);
			}
        if(rPage) {                     // populate summary
            if (rType=='comment') {
                var comCnt= (typeof(gslComCountOffset)!='undefined' && gslComCountOffset!='')? gslComCountOffset : 0; 
                comCnt= parseInt(comCnt) + parseInt(rPage.NumberOfComments)
				
            } else if (rType=='review') {
                var smryHtml= "<div class='gslRevSmry'><span class='gslRevSmryCount'>Reviews: (" + gsl.niceNumber(rPage.NumberOfReviews) + ")</span>";
                if (gsl.ratingsEnabled==true)
                    smryHtml += "<span class='gslRevSmryRating'>Average Rating: <span class='gslRevSmryRatingStars'>" + gsl.getRatingImage(rPage.AverageReviewRating) + "</span></span></div>";
                
                $("gslReactionSummary").innerHTML= smryHtml;
            } 
        }
    
        if(rList) {                     // populate coment/review list
            var rListHtml= "";
            for (i=0; i<rList.length; i++) {
                rListHtml += gsl._getReactionHtml( rType, rList[i] );
            } 
            $("gslReactionList").innerHTML= rListHtml;
		}
        
        if(rPage){    			// populate pagination control
		//After 1.2.4 please delete or change the follwoing first if condition 
			if (typeof($("gslCharCount"))=='undefined' && gsl.fullcommentpage)
				 $("gslPagination2").innerHTML= gsl.getPaginationControl(rType, rPage);
			 else
			 {
				if (gsl.fullcommentpage && $("gslPagination_Top")!=null)
					$("gslPagination_Top").innerHTML= gsl.getPaginationControl(rType, rPage);
				$("gslPagination").innerHTML= gsl.getPaginationControl(rType, rPage);
			}
		}
        // var cntCtl= $("gslCommentsCount");
        // if (cntCtl) {        // populate comment/review count control
            // if (rType=='comment') {
				//cntCtl.innerHTML="";
                // var comCnt= (typeof(gslComCountOffset)!='undefined' && gslComCountOffset!='')? gslComCountOffset : 0; 
                // if (article) { 
                    // comCnt= parseInt(comCnt) + parseInt(article.Comments.NumberOfComments) 
                // } 				
				// cntCtl.innerHTML ="("+comCnt+")";
            // } else if (rType=='review') {  
                // var revCnt=0;
                // if (article) {
                    // revCnt= article.Reviews.NumberOfReviews;
                // }    
                // cntCtl.innerHTML= gsl.getReviewCountControl(revCnt, "#gslPageReturn"); // output review count control
            // }
        // } 
		// else
		// {
			 if (rType=='comment') {
				//cntCtl.innerHTML="";
                var comCnt= (typeof(gslComCountOffset)!='undefined' && gslComCountOffset!='')? gslComCountOffset : 0; 
				  if(rPage){   
				   comCnt= parseInt(comCnt) + parseInt(rPage.NumberOfComments) 
				   } else if (article) { 
                    comCnt= parseInt(comCnt) + parseInt(article.Comments.NumberOfComments) 
                } 
				var articlekey = gsl.getArticleKey();
				if (typeof($("gslCtl-article|comments|"+articlekey))!='undefined' && $("gslCtl-article|comments|"+articlekey) != null){
					var bylinecontrolcomment = $("gslCtl-article|comments|"+articlekey);
					bylinecontrolcomment.innerHTML = gsl.getCommentCountControl(parseInt(rPage.NumberOfComments),"");
				} else if (comCnt == "1"){					
					if(comCtl=$('gslCtl|comments|'+articlekey))
						comCtl.innerHTML="";
					comCtl.innerHTML= gsl.getCommentCountControl(comCnt, "#gslPageReturn"); // output comment count control
				}
				if (typeof($("gslCtl-article|recommends|"+articlekey))!='undefined' && $("gslCtl-article|recommends|"+articlekey) !=null){
					var recCtl=$('gslCtl-article|recommends|'+articlekey);
		            var recCount=0; 
		            var recd=false;
		            if (article && article.Recommendations ) {
		                recCount=parseInt(article.Recommendations.NumberOfRecommendations);
		                recd= (article.Recommendations.CurrentUserHasRecommended=="True")? true : false;
		            }
		            recCtl.innerHTML= gsl.getRecommendCountControl('articles',articlekey, recCount, recd);
				}
			}
		//}
		// This section is obsolete ..need to test it and take it out in future release. 2/20/2009-SSS
		if (typeof($("gslRecommendControl"))!='undefined' && $("gslRecommendControl") !=null){
	        var recCtl= $("gslRecommendControl");
	        if (recCtl) {        // populate content control
	            var recd=false;
	            var recCnt=0;
	            var artKey= gsl.getArticleKey();
	            if (article) {
	                recd= (article.Recommendations && article.Recommendations.CurrentUserHasRecommended=='True')? true: false;
	                recCnt= article.Recommendations.NumberOfRecommendations;
	                artKey= article.ArticleKey.Key;
	            }
	            
	            recCtl.innerHTML= gsl.getRecommendCountControl('article', artKey, recCnt, recd); 
	        }
		}
    },    

    _getReactionHtml: function(type, reaction) {
        var reacHtml= "";
		var IsBlockedUserloggedin = false;
		var classalt ="";
		
		if(GDN.Cookie.Exists("at") && gsl.getUserPid() == reaction.Author.UserKey.Key)
			IsBlockedUserloggedin =true;
			
		if (reaction.AbuseReportCount < gsl.MaxNumberofAbuse){
		
		    if(reaction.Author.IsBlocked!="True" || IsBlockedUserloggedin){
			    
		        var authorKey= reaction.Author.UserKey.Key;
		            var recd= (reaction.CurrentUserHasRecommended=="True")? true: false;
		            var rptd= (reaction.CurrentUserHasReportedAbuse=="True")? true: false;
		            var staffMark= (reaction.Author.UserTier=="Editor" || reaction.Author.UserTier=="Staff")? gsl.SiteStaffText : "";
		            var recNum= reaction.NumberOfRecommendations;
					var sitetimezone = 	((typeof(gsl.TimeZonewords) != "undefined") && (typeof(gsl.TimeZoneoffset) != "undefined"))? gsl.TimeZonewords:"";
		            recNum= (!recNum)? '0': recNum;
					
		        if (type=='comment') {
				 var comKey= reaction.CommentKey.Key;
				var reportabusetext = (reaction.Author.UserTier=="Editor" || reaction.Author.UserTier=="Staff")?"":this.getReportAbuseLink('comment',comKey,rptd);
		           
		            if (gsl.IsOdd == 1) {
						classalt="odd";
						gsl.IsOdd = 0;
						}
						else{
						classalt="even";
						gsl.IsOdd = 1;
						}
		            var commentData= {
		                'authorIcon': this.getUserPhotoLink(authorKey, reaction.Author.AvatarPhotoUrl),
		                'authorHandle': this.getUserHandleLink(authorKey, reaction.Author.DisplayName,reaction.Author.AboutMe,reaction.Author.Age,reaction.Author.Location,reaction.Author.Sex),
		                'commentTimestamp': this.niceDate(reaction.PostedAtTime)+" "+sitetimezone,
		                'commentBody': reaction.CommentBody,
		                'commentKey': comKey,
		                'recommendLink': this.getRecommendCountControl('comments',comKey,recNum,recd),
						
		                'reportAbuseLink': reportabusetext,
		                'staffMark': staffMark,
		                'siteofOrigin':reaction.SiteOfOrigin,
						'alt':classalt,
						'authorNameHandle':reaction.Author.DisplayName,
						'replylink':this.getReplyToLink(comKey),
						'newpostLink':'<a class="newpost" href="javascript:gsl.addquote(null);">New post</a>'
		            };
		           
		            try {       
		                reacHtml= this._transform(commentData, $("comment").innerHTML);
		            } catch(e) {
		                this.showException("_getReactionHtml() comment transform" , e);
		            } 
		            
		        } else if (type=='review') {
		            var revKey= reaction.ReviewKey.Key;
		            var rating= "";
		            if (this.ratingsEnabled==true)
		                rating= this.getRatingImage(reaction.ReviewRating);
		            
		            var reviewData= {
		                'authorIcon': this.getUserPhotoLink(authorKey, reaction.Author.AvatarPhotoUrl),
		                'authorHandle': this.getUserHandleLink(authorKey, reaction.Author.DisplayName),
		                'reviewTimestamp': this.niceDate(reaction.PostedAtTime),
		                'reviewTitle': reaction.ReviewTitle,
		                'reviewRating': rating,
		                'reviewBody': reaction.ReviewBody,
		                'reviewKey': revKey,
		                'recommendLink': this.getRecommendCountControl('review',revKey,recNum,recd),
		                'reportAbuseLink': this.getReportAbuseLink('review',revKey,rptd),
		                'staffMark': staffMark
		            };
		          
		            try {       
		                reacHtml= this._transform(reviewData, $("review").innerHTML);
		            } catch(e) {
		                this.showException("_getReactionHtml() review transform" , e);
		            }       
		        }
			}	
		}
	//	}
        return reacHtml;  
    },
 
    updateReactionFormHead: function(type, signOut) {
        if ( this.reactionsClosed==false && (this._templates.comments['loaded']==true || this._templates.reviews['loaded']==true )) {
            
            var reacFormHead= $("gslReactionFormHead");
            if(reacFormHead) {
                var headHtml= ""; 
               if (!GDN.Cookie.Exists("at")) {
                    // no transform necessary for logged out template
					 if (type=='comment') {
                    $("headLoggedIn").style.display = "none";
                    $("headLoggedOut").style.display ="block";
					}
					else if (type=='review') {
					$("headLoggedIn").style.display = "none";
                    $("headLoggedOut").style.display ="block";
					}
                           
                } else {
                   // Currently we dont need to get userinfo at login header section
                   // var uHandleLink= this.getUserHandleLink(this.getUserPid(), this.getUserHandle());
                   // var headerData= { 'userHandleLink':uHandleLink };
                    var headerTemplate= "";
                    if (type=='comment') {
                        $("headLoggedIn").style.display = "block";
                        $("headLoggedOut").style.display ="none";
						 headerTemplate= document.getElementById("headLoggedIn").innerHTML;
                    } else if (type=='review') {
                        $("headLoggedIn").style.display = "block";
                        $("headLoggedOut").style.display ="none";
						 headerTemplate= document.getElementById("headLoggedIn").innerHTML;
                    } 
                    
                    try {
						
						var maxcharacters={'maxchars':gsl.commentMaxChars};
                        headHtml= this._transform(maxcharacters, headerTemplate);
                    } catch (e) {
                        this.showException("updateReactionFormHead() head transform" , e);
                    }         
                } 
                document.getElementById("headLoggedIn").innerHTML= headHtml;
            }        
            
            if (type=='comment') {
                var comBody= $("gslComFormBody");
                var comBtn= $("gslComFormSubmit");
                if(comBody && comBtn) {
                    if (!GDN.Cookie.Exists("at")) {     
                        comBody.disabled = true;
                        comBody.value="";  
                        comBtn.disabled = true;                                     
                    } else {
                        comBody.disabled = false; 
						comBody.value=""; 
                        comBtn.disabled = false; 
                    }
                }           
            } else if (type=='review') {
                var revTitle= $("gslRevFormTitle");
                var revRating= $("gslRevFormRatingControl");
                var revBody= $("gslRevFormBody");
                var revBtn= $("gslRevFormSubmit");
                if(revTitle && revRating && revBody && revBtn) {
                    if (!GDN.Cookie.Exists("at")) {      
                        revTitle.disabled= true; 
                        revTitle.value="";
                        if (this.ratingsEnabled==true) {
                            revRating.innerHTML= this.getRatingControl(0, false);
                        } else {
                            revRating.innerHTML="";
                        }
                        revBody.disabled= true; 
                        revBody.value="";
                        revBtn.disabled= true;                                                             
                    } else {
                        revTitle.disabled= false; 
                        if (this.ratingsEnabled==true) {
                            revRating.innerHTML= this.getRatingControl(0, true); 
                        } else {
                            revRating.innerHTML="";
                        }
                        revBody.disabled= false; 
                        revBtn.disabled= false; 
                    }
                }
            } 
            
            // Reset Error block in form
            var errorNode=$("gslFormError");
            if (errorNode) errorNode.innerHTML="";             

            
        } 
    },    
    
    getPaginationControl: function(type, page) {
        var reacCount= (type=='comment')? page.NumberOfComments: page.NumberOfReviews;
        var plusMinus= this.paginationLinks;
        var pageControl= "";	
		var new_url = "";

		//After 1.2.4 please delete or change the follwoing first if condition 
		if (typeof($("gslCharCount"))=='undefined' && !gsl.fullcommentpage){
		var tempsortselected = "";
		if(gsl.params["s"]=="TimeStampAscending") {
				tempsortselected = "a";
			} else {
				tempsortselected = "d";
			}
		new_url= (gsl.fullcommentpage)? "/apps/pbcs.dll/section?Category=pluckcomments&key="+gsl.params["key"]+"&s="+tempsortselected+"&page=":contentURL+"&s="+tempsortselected+"&page=";
        }
		else
		new_url= (gsl.fullcommentpage)? "/apps/pbcs.dll/section?Category=pluckcomments&key="+gsl.params["key"]+"&s="+gsl.params["s"]+"&page=":contentURL+"&s="+gsl.params["s"]+"&page=";
		
		        if (reacCount > gsl.requestsperBatch) {
            var pageDiv = parseInt(reacCount)/gsl.requestsperBatch;
            if (pageDiv > parseInt(pageDiv)) {
                pageDiv += 1;
            }
            pageDiv = parseInt(pageDiv);

            var ll, ul;
            var rPoP = page.OnPage;
            var pnp = rPoP-1;
            
            if (rPoP != 1) {
            pageControl += " <a href=\""+new_url+"#pluckcomments\" alt='Go to first page'>First</a> ";
			pageControl += " <a href=\""+new_url+pnp.toString()+"#pluckcomments\" alt='Go to previous page'><<</a> ";

            }
            ll = rPoP - plusMinus;
            ul = parseInt(rPoP) + plusMinus;

            if (ll < 1) {
                ll =1;
            } 
            if (ul>pageDiv) {
                ul = pageDiv;
            }
            
            for (var i=ll; i<=ul; i++)
            {
                if (rPoP != i) {
                    pageControl += " <a href=\""+new_url+i.toString()+"#pluckcomments\">" + i + "</a> ";
                } else pageControl += " " + i + " ";
            }
            pnp = pnp+2;
            if (rPoP != pageDiv) {
          	pageControl += " <a href=\""+new_url+pnp.toString()+"#pluckcomments\" alt='Go to next page'>>></a> ";
			pageControl += " <a href=\""+new_url+pageDiv.toString()+"#pluckcomments\" alt='Go to last page'>Last</a>";            
            }
			if(typeof($("gslfullpagecomment"))!='undefined' && $("gslfullpagecomment")!='' && !gsl.fullcommentpage){
			pageControl += "<div class='gslfullpage' style='display:none'>"+
				"<a class='button clear' href='javascript:gsl.redirectToCommentPage();'>"+
				"Full page view"+
				"</a> <em>See more comments per page and quote other replies</em>"+
				"</div>";
			}
        } 
        
        return pageControl;
    },
	
    submitReaction: function() {
        var type= $("gslReactionType").value;
        var tmpl= ""; 
        var body= "";
        var bwfBody= "";
        var max= 0;
        var err= $("gslFormError"); 
        err.innerHTML= "";
        var emptyFlag= false;
        
         if (type=='comment') {
            tmpl= this._templates.comments;
            body= $("gslComFormBody").value; 
            bwfBody= body; 
            max= this.commentMaxChars;
            
            if (body.length==0 || !this.hasWhiteSpace(body)) {
                err.innerHTML= $('missingInputError').innerHTML;
                setTimeout("$('gslComFormBody').focus()", 1); 
                return false;
            }
			if (this.checkBodyLength(body, max)==false) {
				var data= {'maxchars':max};
				err.innerHTML= this._transform(data, $('entryTooLongError').innerHTML);
				return false;
			}
				var el = $("gslComFormBody");
				if (el.value.indexOf("[QUOTE]") != -1 || el.value.indexOf("[\QUOTE]") != -1 ){
					return_str = el.value.sub(/\[QUOTE\](.*)\[\/QUOTE\]/, "");
					return_str = return_str.replace(/<(.|\n)*?>/g, ""); 	
					return_str = "<p class='replyingto'>Replying to "+ $('gslQuoteAuthor').value + ":</p>" +
								  "<blockquote>" + gsl.plkreplycomment + "</blockquote>" + return_str;
					
				} else {
					return_str = el.value.replace(/<(.|\n)*?>/g, ""); 		
				}
				el.value =return_str;
		} else if (type=='review') {
            tmpl= this._templates.reviews;
            var revTitle= $("gslRevFormTitle").value;
            var revRating= (ratNode= $("gslRevFormRating"))? ratNode.value : 0;
            body= $("gslRevFormBody").value;
            bwfBody= body + " " + revTitle;
            max= this.reviewMaxChars;
            emptyFlag= (body.length==0 || revTitle.length==0)? true: false;
            
            if (body.length==0 || revTitle.length==0) {
				err.innerHTML= $('missingInputError').innerHTML;
                if (revTitle.length==0) { setTimeout("$('gslRevFormTitle').focus()", 1); }
                else if (body.length==0) { setTimeout("$('gslRevFormBody').focus()", 1); }
                return false;
            }
        }
        
       
			
            this._submitReactionToSiteLife();
        
       
          
    },
	
	hasWhiteSpace:function (s){
     reWhiteSpace = new RegExp(/^\s+$/);

     // Check for white space
     if (reWhiteSpace.test(s)) {
         
          return false;
     }
	return true;
	},
	
	redirectToCommentPage:function (){
	
		if (gsl.totalnocomments>gsl.requestsperBatch){
			var base_url = "/apps/pbcs.dll/section?Category=pluckcomments&key="+gsl.getArticleKey();
			var dir = gsl.commentSortOrder;
			if(dir == "TimeStampAscending"){
				base_url += "&s=a";
			} else {
				base_url += "&s=d";
			}
			window.location.href = base_url;
		}
		else
			window.location.href = "#pluckcomments";
	},
 	
    _submitReactionToSiteLife: function() {
        var type= $("gslReactionType").value;
        var title= document.title;
        var articleKey= this.getArticleKey();    
        var articleLink= this.getArticleLink(document.location.toString().split('#')[0]+"#gslPageReturn");
        var rb= new RequestBatch();

        if (type=='comment') { 
            var comBody= $("gslComFormBody").value;
			comBody= this.return2br(comBody);
            rb.AddToRequest(new CommentAction(new ArticleKey(articleKey), articleLink, title, comBody));
			
			//Add another request to check if User is Standard
			var userKey = new UserKey(gsl.getUserPid()); 
			rb.AddToRequest(userKey);
   
            $("gslComFormBody").value= "";
            
        } else if (type=='review') {
            var revTitle= $("gslRevFormTitle").value;
            var revRating= (this.ratingsEnabled==true)? $("gslRevFormRating").value : 0;
            var revBody= $("gslRevFormBody").value;
            rb.AddToRequest(new ReviewAction(new ArticleKey(articleKey), articleLink, title, revTitle, revRating, revBody, null, null));
            
            $("gslRevFormTitle").value = "";
            $("gslRevFormBody").value = "";
            if (this.ratingsEnabled==true) {
                this._setRating('gslRevFormRating', 1);
                this._fillRatingStar('gslRevFormStars', 'gslRevFormRating', -1);  
            }
        }
        
        this.sitelifeRequest(rb, "SubmitReaction", this._submitReactionToSiteLifeCallback);   
    },
    
    _submitReactionToSiteLifeCallback: function(res) {
        var type= $("gslReactionType").value;
        
        for (var i=0; i<res.Messages.length; i++) {
            var msg = res.Messages[i];
            if (msg.Message != "ok") {
				if (msg.Message.indexOf("User not allowed to execute command")!= -1) {
					msg.Message = "We are sorry, your session has been expired, you will be redirected to sign in page";
					window.location.href = gsl.pluckSigninPage + "&destination=" +encodeURIComponent(location.href);
				}
					$("gslFormError").innerHTML = msg.Message;
			        gsl.showException("_submitReactionToSiteLifeCallback" + msg.Message);
            } else {
                    var reacCount =  gsl.totalnocomments;
					var curPage = parseInt(gsl.params["page"] || 1);
					var pageDiv = Math.ceil(reacCount / gsl.requestsperBatch);
					var desc = ((gsl.params["s"] == "a") ? false : true);
					var npage;
					var response= res.Responses[i];
					var resUserTier = response.User.UserTier;
					if(desc && curPage>1){
						npage = 1;
					} else if(!desc && curPage<pageDiv){
						npage = pageDiv;
					}	
					if(npage){	
						var new_url = (gsl.fullcommentpage)? "/apps/pbcs.dll/section?Category=pluckcomments&key="+gsl.params["key"]+"&s="+gsl.params["s"]+"&page=":contentURL+"&s="+gsl.params["s"]+"&page=";
						window.location.href = new_url + npage.toString();
					} else {
						//Display message if Comments are premoderated
						if(typeof(CommentPreModeration) != 'undefined' && CommentPreModeration == 'checked' && resUserTier == 'Standard'){
							var err= $("gslFormError");
							if($("gslFormPreModeration")){err.innerHTML = $("gslFormPreModeration").innerHTML;}
						} else {
						//Otherwise refresh the page to get comment from pluck and show it in the page
						window.location.reload();
						}
					}
                }
				
        }
    },
    	
    checkBodyLength: function(body, max) {
        if (body.length <= max) { 
            return true;
        } else {
            return false;
        }
    },    
    //Convert carrage returns - line feeds to HTML <br />
	return2br:function (dataStr) {
        return dataStr.replace(/(\r\n|[\r\n])/g, "<br />");
    },
    /*************************************************************************/
    /* Article - art *********************************************************/ 
    
    getArticleKey: function() {   
    /* need to know where they have their articleKey */ 
        var id = (typeof(contentID)!='undefined') ? contentID : null;
        if (id == null) {gsl.showDebug("No contentID found.  Returned null");}
        return id;
    },


    getArticleTitle: function() {
        // if gsl.contentTitle is not set, then parse it out of the browser title bar
        var title= contentTitle || "";
        if(title == ""){
            title= document.title;   // Will need to strip off what ever comes in as the title
            title= title.split('#')[0];  
        }                   // strip off any #anchor/fragment
        return title;
    },

	getArticleLink: function(artId) {
        var linkURL = (typeof(contentURL) != 'undefined') ? contentURL : document.location.toString().split('#')[0];
        return linkURL;
    },
          
    // Using the 'section' discovery variable for content type (story, blog, photo, etc)   
    getArticleSection: function() {
        return new Section(this.getArticleKey().split(".")[3]);  
    },     
       
    // Using 'categories' discovery array for listing which news sections the article appears in 
    getArticleCats: function(cats) {
        if(!cats) {
            var sArtKey = gsl.getArticleKey().split(".");
            cats = new Array();
            for (x=4; x<sArtKey.length; x++) {
                cats[x-4] = sArtKey[x];
            }
        } else {
            cats= (cats && cats!='')? cats.split(".") : new Array();
        }
        var categories= new Array();            // SiteLife Category object array
        for (i=0; i<cats.length; i++) {
            categories[i]= new Category(cats[i]);
        }
        return categories;
    }, 

    _compareArticleInfo: function(article) {
        // Call UpdateArticleAction if no article info
        if(!article || (article && (!article.Section || article.Categories.length==0))) {
           return true;
        }   
        
        // Call UpdateArticleAction if section has changed
        var sec= this.getArticleSection();  
        if ( article && (article.Section && sec.Section && (article.Section.Name.toLowerCase() != sec.Section.Name))) {
            return true;
        }
        
        // Call UpdateArticleAction if categories have changed
        var cats= this.getArticleCats();  
        if ( article && article.Categories && article.Categories.length > 0) { 
            
            if (article.Categories.length != cats.length) {
                return true;
            }
            
            var i=0;
            for (i=0; i<article.Categories.length; i++) {
                if(cats[i].Category.Name.toLowerCase() != article.Categories[i].Name) {
                    return true;
                }  
            }
        } 
		 if ((typeof(contentTitle) != "undefined") && article && article.PageTitle && (article.Categories.length > 0)) { 
            if (article.PageTitle != contentTitle) {
                return true;
            }
        } 
		 if ((typeof(contentURL) != "undefined") && article && article.PageTitle && (article.Categories.length > 0)) { 
            if (article.PageUrl != contentURL) {
                return true;
            }
        } 
	   
        return false;       
    },
       
    /*************************************************************************/
    /* Comments - com ********************************************************/
       
    getCommentCountControl: function(count, link) {
        var comCntCtl="";
        var strCount= gsl.niceNumber(count);
        var strLabel= gsl.commentLbl || "Comments";
        if (count==0) {
            strCount= "0";
            strLabel= gsl.NocommentLbl || "Comment";
        }
        comCntCtl+= "<span class='gslCommentsLink'>";
        if(gsl.commentCountHrefEnabled)
            comCntCtl+= "<a href='"+link+"' title='Go to comments' alt='Go to comments'>";
			
        comCntCtl+= "<span class='gslCommentsLabel'>"+strLabel+"</span>";
		if (count!=0){
        comCntCtl+= "<span id='gslCommentsCount' class='gslCommentsCount'>("+strCount+")</span>";
		}
        if(gsl.commentCountHrefEnabled)
            comCntCtl+= "</a>";
        comCntCtl+= "</span>";
        
        return comCntCtl;        
    },
                 
    /*************************************************************************/
    /* Reviews - rev *********************************************************/ 
       
    getReviewCountControl: function(count, link) {    
        var revCntCtl="";
        var strCount= gsl.niceNumber(count);
        var strLabel= gsl.reviewLbl || "Reviews";
        if (count==0) {
            strCount= "0";
            strLabel= gsl.reviewLbl || "Review";
        } 
        revCntCtl+= "<span class='gslReviewsLink'>";
        if(gsl.reviewCountHrefEnabled)
            revCntCtl+= "<a href='"+link+"' title='Go to reviews' alt='Go to reviews'>";
        revCntCtl+= "<span class='gslReviewsLabel'>"+strLabel+"</span>";
        revCntCtl+= "<span class='gslReviewsCount'>("+strCount+")</span>";
        if(gsl.reviewCountHrefEnabled)
            revCntCtl+= "</a>";
        revCntCtl+= "</span>";                     
        
        return revCntCtl;        
    },
    
    /*************************************************************************/
    /* Recommend - rec *******************************************************/ 
    
    getRecommendCountControl: function(type, key, recCount, recommended) {
        var recHtml= "";

        if (key==null || key.split('.')[0]=="") {
            recHtml += "<span class='gslDisabledRecommendLink'>";
            recHtml += "<span class='gslRecommendLabel'>"+gsl.recommendLbl+"</span>";
            recHtml += "<span class='gslDisabledRecommendCount'>(0)</span>";
            recHtml += "</span>";    
        } else {
            if (recommended==true) {
                recHtml += "<span class='gslRecommended'>";
                recHtml += "<span class='gslRecommendLabel'>"+gsl.recommendedLbl+"</span>";
                recHtml += "<span class='gslRecommendedCount'>(" + gsl.niceNumber(recCount) + ")</span>";
                recHtml += "</span>";            
            } else {  
                var strCount= gsl.niceNumber(recCount);             
                if (recCount==0) {
                    strCount= "0";
                }
                recHtml += "<span id='gslRecommend:" + type + ":" + key + "'>"; 
				recHtml += "<span class='gslRecommendLink'>";
                if(gsl.recommendCountHrefEnabled)
                    recHtml += "<a href=\"javascript:void(\'Recommend\')\" title='Recommend this article' alt='Recommend this article' onclick=\"gsl.Recommend('" + type + "','" + key + "','" + recCount + "');\">";
                recHtml += "<span class='gslRecommendLabel'>"+gsl.recommendLbl+"</span>";
                if (recCount==0){
				recHtml += "<span class='gslRecommendCount'></span>";
				} else {
                recHtml += "<span class='gslRecommendCount'>(" + strCount + ")</span>";
				}
                if(gsl.recommendCountHrefEnabled)
                    recHtml += "</a>";
                recHtml += "</span>";      
                recHtml += "</span>";
            }
        }
        return recHtml;
    },
   
    Recommend: function(type, key, recCount) {        
        var recKey= null;
        if (type=='comments') {
            recKey= new CommentKey(key);
        } else if (type=='reviews') {
            recKey= new ReviewKey(key);
        } else if (type=='articles') {
            recKey= new ArticleKey(key);
        } else if (type=='photo') {
            recKey= new PhotoKey(key);
			if(typeof(gpg)!='undefined'){
			gpg.localMasterPGArray[gpg.globalpgpageno][$("gsl_pg_currentno").value].CurrentUserHasRecommended = "True";
			gpg.localMasterPGArray[gpg.globalpgpageno][$("gsl_pg_currentno").value].NumberOfRecommendations = parseInt(gpg.localMasterPGArray[gpg.globalpgpageno][$("gsl_pg_currentno").value].NumberOfRecommendations) +1;
			}
		} else if (type=='saxophoto') {
            recKey= new ArticleKey(key);
			if(typeof(gpg)!='undefined'){
			gpg.localMasterPGArray[gpg.globalpgpageno][$("gsl_pg_currentno").value].CurrentUserHasRecommended = "True";
			gpg.localMasterPGArray[gpg.globalpgpageno][$("gsl_pg_currentno").value].NumberOfRecommendations = parseInt(gpg.localMasterPGArray[gpg.globalpgpageno][$("gsl_pg_currentno").value].NumberOfRecommendations) +1;
			}
        }		
        
        var rb= new RequestBatch();	 
        rb.AddToRequest(new RecommendAction(recKey)); 
        this.sitelifeRequest(rb, "SubmitRecommend", this._recommendCallback);
        
        var recLink= $("gslRecommend:"+type+":"+key);
        if(recLink) {
            var num= parseInt(recCount,10);
            num += 1;
            recLink.innerHTML= this.getRecommendCountControl(type, key, num, true);
        }
    },
    
    _recommendCallback: function(res) {
        if(res.Messages.length > 0 && res.Messages[0].Message=="ok") {
            gsl.showDebug("Recommend Successful");  
        } else {
            gsl.showDebug("Recommend Failed: " + res.Messages[0].Message);
        }   
        
        // save responses page for debugging purposes (javascript:alert(gsl.lastRecommendRes.toJSONString().replace(/:{/g, ":\n{").replace(/},/g, "},\n"));)
        if (gsl.Debug && res.Responses) { gsl.lastRecommendRes= res.Responses; } 

    },
    
    setSortOrder:function(){
		var sortCtrlselected = $("gslSortOrder").options[$("gslSortOrder").selectedIndex].value;
		// After 1.2.4 release please delete following condition 
		if (typeof($("gslCharCount"))=='undefined' && !gsl.fullcommentpage){
			if (sortCtrlselected == "TimeStampAscending")
				sortCtrlselected = "a";
			else
				sortCtrlselected = "d";
		}
		var new_url = (gsl.fullcommentpage)? "/apps/pbcs.dll/section?Category=pluckcomments&key="+gsl.params["key"]+"&s="+sortCtrlselected:contentURL + "&s=" + sortCtrlselected;
		window.location.href = new_url;
	}, 
              
    /*************************************************************************/
    /* AJAX Transport Functions **********************************************/
   
    sitelifeRequest: function(slBatch, action, callback) {

        // Add UpdateArticleAction to batch, if update article flag is set then 
        if (this._updateArticle==true) {
	        var articleKey= this.getArticleKey();
            var articleLink= this.getArticleLink();
            var title= this.getArticleTitle();
            var section= this.getArticleSection();
            var cats= this.getArticleCats();
            slBatch.AddToRequest(new UpdateArticleAction(new ArticleKey(articleKey), articleLink, title, section,cats));
            gsl.showDebug("Updating Article:"+articleKey+" title:"+title+" URL:"+articleLink+" section:"+section+" cats:"+cats);
        }
	  
        this.logSiteLife("gslRequest:"+action);
        var This= this;
        var callbackWrap= function(response) {
            try {
	            gsl.logSiteLife("gslResponse:"+action);
                callback(response);
            } catch(e) {
                gsl.showException("SL Request Callback Wrapper", e);
            }
        };     
        try {    
            slBatch.BeginRequest(this.sitelifeApiUrl, callbackWrap); 
        } catch(e) {
            this.showException("SL Request", e);
        }
    },
    
    isSitelifeAvailable: function() {
        // check for the existence of a sitelife class 
        if(typeof(DiscoverArticlesAction)!='undefined') {
            return true;
        } else {
            return false;
        }    
    },
    
    logSiteLife: function(msg) {         
        gsl.showDebug(msg);
    },
    
    /*************************************************************************/
    /* Utility Functions *****************************************************/
    
     _mouseX: function(evt) {
        if (evt.pageX) return evt.pageX;
        else if (evt.clientX)
            return evt.clientX + (document.documentElement.scrollLeft ?
            document.documentElement.scrollLeft :
            document.body.scrollLeft);
        else return null;
    },
    
    _mouseY: function(evt) {
        if (evt.pageY) return evt.pageY;
        else if (evt.clientY)
            return evt.clientY + (document.documentElement.scrollTop ?
            document.documentElement.scrollTop :
            document.body.scrollTop);
        else return null;
    },
    
    _hideDiv: function(id){
        document.getElementById(id).style.display = "none";
    },
    
    _showDivAtMouse: function(evt, id) {
        posx = this._mouseX(evt) - 170;
        posy = this._mouseY(evt);
        document.getElementById(id).style.left = posx + "px";
        document.getElementById(id).style.top = posy + "px";
        document.getElementById(id).style.display = "block";
    },
  
    niceNumber: function(num) {
        num= num.toString();
        if(num.length<=3) {
            return (num=="")? "0" : num;
        } else {
            var niceNum= "";
            try {
                if(mod=(num.length%3)) {
                    niceNum= num.substr(0, mod)+",";
                }                
                for(i=0; i<=(num.length/3)-1; i++) {
                    if(i!=0) { niceNum= niceNum + ","; }
                    niceNum= niceNum + num.substr((3*i)+mod, 3);
                }
            } catch(e) {
                return num;
            }     
            return niceNum;
        }
    },
     
    /*************************************************************************/
    /* Debugging Functions ***************************************************/
    
    showDebug: function(debugtext) {
        if (this.Debug==1) {
            if($("debug"))
            {
                if(($("debug")).innerHTML == "")
                    ($("debug")).innerHTML += "<br /><br />DEBUG LOG<br />==========<br />";
                datestamp = new Date();
                ($("debug")).innerHTML += datestamp.toLocaleTimeString() +": "+ debugtext + "<br>";
            }
        }
    },
    
    showException: function(location, ex) {
        var msg= " ";
        if(ex && ex.name && ex.message) {
            msg= "Javascript Exception in " + location + ": " + ex.name + " - " + ex.message;
        } else {
            msg= "Error in " + location + " - " + ex;
        }
        this.showDebug(msg);
        
    },

    /*************************************************************************/
    /* Article Functions - art ***********************************************/ 
	 AddThisArticle: function(){
        var rb= new RequestBatch();
        rb.AddToRequest(new ArticleKey(gsl.getArticleKey()));
        try{
            gsl.sitelifeRequest(rb, "Add this article", this._loadATACallback);
        } catch(e) {
            this.showException("SL Request", e);
        }
    },
    
    _loadATACallback: function(result) {
        for (var i=0; i<result.Responses.length; i++) {
            var res= result.Responses[i];
            if(res.Article != null) { 
                gsl._updateArticle = gsl._compareArticleInfo(res.Article);
                if (gsl._updateArticle && gsl.updateOnLoad) {
                    var rb = new RequestBatch();
                    gsl.sitelifeRequest(rb, "UpdateArticle", gsl._upArtCB);
                }
            }
        }
    },
	
	DynamicArticleControls: function(elementID) {
	    if (elementID){
	        gsl.dynElement = $(elementID);
	        if(gsl.ArticleControls) { gsl.ArticleControls(); }
	        gsl.dynElement = null;
	    } else return;
	},
		
    ArticleControls: function() {   
        // 1. Find set of HTML elements with class "gslArticleControl" on the page. 
		    var artCtls= document.getElementsByClassName("gslArticleControl");
	       this._processDiscoveryForAll(artCtls);
    }, 

	getDiscoveryTabContent:function() {
	//  Get All the divs present on the frontpage tab module for discovery action 
		 var artClassCtls= document.getElementsByClassName("gslArticleControlTab");
		 var combinedArtCtls = new Array();
		 var count=0;
		  if (artClassCtls.length > 0) {
		   gsl.discoveryAge= $("gslDiscoveryAge").value;
			for(inc=0; inc<artClassCtls.length; inc++) {
				var artCtlsTab = artClassCtls[inc].getElementsByClassName("gslArticleControl");
				//Concat the all the arrays present on the tab so that thier will be only one pluck call 
				for(cntarr=0; cntarr<artCtlsTab.length; cntarr++) {
						combinedArtCtls[count] = artCtlsTab[cntarr];
						count++;
						}
			}
			//Call the existing discvoery function to process the discovery action.
			this._processDiscoveryForAll(combinedArtCtls);
		}
	},

	_processDiscoveryForAll: function(artCtls) {
        // 1. Parse out Article or Discovery Widget info from the HTML element's id
        // 2. Build batch(es) of Article and Discovery requests
        // 
        // Article Controls:
        //      <div id="gslCtl|[ControlType]|[ArticleKey]" class="gslArticleControl"></div>
        //      Ex: <div id="gslCtl|comments|123456789.story" class="gslArticleControl"></div>
        // Article control element id breakdown - 
        //      gslCtl | [control type] | [article id]
        //      [ControlType] = comments, reviews, or recommend
        //      [ArticleId] = unique id of article (not containing a pipe |)
        // 
        // Discovery Widgets:
        //     <div id="gslCtl|[ControlType]|[Activity]|[Section]|[Categories]|[Index]" class="gslArticleControl"></div>
        //     Ex: <div id="gslCtl|discovery|Recent|story|money.life" class="gslArticleControl"></div>
        // Discovery widget element id breakdown -
        //     gslCtl | [ControlType] | [Activity] | [Section] | [Categories] | [Index]
        //     [ControlType]= discovery
        //     [Activity]   = Recent, Commented, Reviews, or Recommended
        //     [Section]    = article type - story, blog, etc.
        //     [Categories] = period deliminated article sections - news, money, travel, money.life, news.sports, etc.
        //     [Index]      = Index of discovery widget (valid index is 1 through 10 per discovery search)

	  if (artCtls.length > 0) {
	            var controls= new Array();
	            var i=0;
	            
	            var reqBatch;  
	            var ctlCount=0;
	            for(i=0; i<artCtls.length; i++) {
	                
	                // 2. Parse out Article or Discovery Widget info from the HTML element's id
	                var ctlIda= artCtls[i].id.split("|");   //split control id attribute by pipe delimiter
	                
	                var cid;
	                var type="";
	                // Will need to find gslCtl in all templates and switch to new name, gslCtl
	                if (ctlIda[0]=='gslCtl' && ctlIda.length==3) { 
	                    cid= ctlIda[2];
	                    type= ctlIda[1];    // count or recommend
	                } else if (ctlIda[0]=='gslCtl' && ctlIda.length==6) {
	                    cid= ctlIda[2]+ctlIda[3]+ctlIda[4]; //activity + section + categories;
	                    type= ctlIda[1];    // discovery
	               } else {
	                    this.showDebug("Malformed gslArticleControl Id (1)");
	                }
	                
	                // if the article id "<articleNum>.<articleType>" is blank then 
	                // clear the contents of the control and skip adding it to batch 
	                if(cid.split(".")[0]=="") {
	                    try {
	                        // clear node contents
	                        if (artCtls[i]) { artCtls[i].innerHTML= ""; }
	                    } catch(e) { }
	                    this.showException("Empty Article Id"); // log the issue in omniture
	                    continue;   // skip the rest of the loop
	                }            
	                
	                // 3. Build batch(es) of Article and Discovery requests 
	                if(!controls[cid]) {                 
	                    controls[cid]=cid;
	                    ctlCount += 1;
	                    
						//if(cid!=contentID) {
		                    if(!reqBatch) {
		                        reqBatch= new RequestBatch(); 
		                    }
		                    if (type=="comments" || type=="reviews" || type=="recommends" || type=="ratings" ) { 
		                        this.showDebug("adding article control to batch: " + type + " cid:"+ cid);   
		                        reqBatch.AddToRequest(new ArticleKey(cid));  
		                    } else if (type=="discovery") {
		                        var activity= ctlIda[2];
		                        var section= ctlIda[3];
		                        var categories= ctlIda[4];
		                        var contribs= new Array(new UserTier("All"));
		                        var maxIndex= this._findDiscoveryMaxIndex(activity, section, categories);
		                        this.showDebug("adding discovery control to batch: " + type + " cid:"+ cid);   
								reqBatch.AddToRequest(new DiscoverArticlesAction(new Array(new Section(section)), this.getArticleCats(categories), contribs, new Activity(activity), this.discoveryAge, maxIndex));    
		                    } else {
		                        this.showDebug("Malformed gslArticleControl Id (2) - type: " + type + " cid: "+cid);
		                    }
		                                 
		                    if(ctlCount!=1 && (ctlCount%this.requestsPerBatch)==0) {
		                        this.sitelifeRequest(reqBatch, "LoadArticleCtls", this._ArticleControlsCallback);     
		                        reqBatch = null;
		                    }
						//}
	                }
	            }
	            
	            if(ctlCount > 0 && (ctlCount%this.requestsPerBatch)!=0 && !gsl.ie6Error) {
	                this.sitelifeRequest(reqBatch, "LoadArticleCtls", this._ArticleControlsCallback); 
	            }
	        }
	},
	
    _findDiscoveryMaxIndex: function(activity, section, categories) {
        // find max disovery widget index
        var j=1;
        for(j=1; j<=10; j++) {
            var discElem= $('gslCtl|discovery|'+activity+'|'+section+'|'+categories+'|'+j);
            if(!discElem) {
                return j-1;
            }
        }   
        return 10; 
    },

    _ArticleControlsCallback: function(result) {
        var j=0;
        var k=0;
        // Process Controls Successfully Retrieved
        for ( j=0; j<result.Responses.length; j++) {
            if (result.Responses[j].Article) {
                
                // Process Article Control
                var article= result.Responses[j].Article;
                gsl._processArticleControl(article.ArticleKey.Key, article);
                
            } else if (result.Responses[j].DiscoverArticlesAction) {
            
                // Process Discovery Widget
                var disovAction= result.Responses[j].DiscoverArticlesAction;
                var discArts= result.Responses[j].DiscoverArticlesAction.DiscoveredArticles;
                var k=0;
                for ( k=0; k<discArts.length; k++) {
                    var discov= discArts[k]; 
                    if (discov) {
                        gsl._processDiscoveryControl(discov, k+1, disovAction.SearchSections, disovAction.SearchCategories, disovAction.Activity.Name);
                    }
                }                
            } 
        } 
        
        // Process ArticlesKeys That Were Not Found
        for ( j=0; j<result.Messages.length; j++) {
            // When ArticleKey is not found, this is returned as a message
            // "Unable to find data on request:[ArticleRequest] ArticleKey = [RequestedArticleKey]; Key = [RequestedArticleKey]"
            var msg="";
            article= {}; // clear out article
            // If the msg is the unable to find message
            if( (msg=result.Messages[j].Message) && msg.substr(0,14)=="Unable to find") {
                // get the article key
                var key="";
                try {
                    // No article record -> Populate article control anyway
                    key= msg.split("= [")[1].split("];")[0];
                    gsl._processArticleControl(key, article);
                    
                } catch(e) {
                    gsl.showException("Unable to extract ArticleKey from batch", e);
                    continue;
                }
            }
        }  
        if (gsl.Debug && result.Responses) { gsl.lastArtCtlRes= result.Responses; }     
    },

    _processArticleControl: function(key, article) {
        // Populate all controls that coorespond to the SiteLife article object <acticle>    
        this.showDebug("processing article control - key: "+key);    
        var revCtl;
        if (revCtl=$('gslCtl|reviews|'+key)) {
            var revCnt= (article.Reviews)? article.Reviews.NumberOfReviews : 0;    // get review count 
            var revLink="";
            if (typeof(gslReviewLinks)!='undefined') {
                revLink= (link=gslReviewLinks[key])? link: gsl.getArticleLink(key);
                revLink += "#gslPageReturn";
            } else {
                revLink= gsl.getArticleLink(key) + "#gslPageReturn";
            }        
            revCtl.innerHTML= gsl.getReviewCountControl(revCnt, revLink); 
        }
        //#gslPageReturn is the anchor to link to on the page
        var comCtl;
        if (comCtl=$('gslCtl|comments|'+key)) {
            var comLink="";   
            var comCnt= (article.Comments)? article.Comments.NumberOfComments : 0;    // get comment count                  
            if (typeof(gslComCountOffset)!='undefined') {
                comCnt = parseInt(comCnt) + parseInt((offset=gslComCountOffset[key])? offset: 0); // add offset to review count (typepad legacy support)
            }
            if (typeof(gslCommentLinks)!='undefined') {
                comLink= (link=gslCommentLinks[key])? link: gsl.getArticleLink(key);
                comLink += "#gslPageReturn";
            } else {
                comLink= gsl.getArticleLink(key) + "#gslPageReturn";
            }
            comCtl.innerHTML= gsl.getCommentCountControl(comCnt, comLink);                     
        }
        
        var recCtl;
        if (recCtl=$('gslCtl|recommends|'+key)) {
            var recCount=0; 
            var recd=false;
            if (article.Recommendations) {
                recCount= article.Recommendations.NumberOfRecommendations;
                recd= (article.Recommendations.CurrentUserHasRecommended=="True")? true : false;
            }
            recCtl.innerHTML= gsl.getRecommendCountControl('articles', key, recCount, recd);
        }
        

    },

    _processDiscoveryControl: function(article, index, sections, categories, activity) {
        // Populate the discovery widget
        var strSections= this._getNameValues(sections);
        var strCats= this._getNameValues(categories);
        
        this.showDebug("processing article: "+article.ArticleKey.Key+" index: "+index+" sections: "+strSections+" cats: "+categories+" activity: "+activity);
        
        var ctlNode= $('gslCtl|discovery|'+activity+'|'+strSections+'|'+strCats+'|'+index);
        if (ctlNode) {
            var key= article.ArticleKey.Key;
            var title= (article.PageTitle)? article.PageTitle : activity+' '+strSections+' '+strCats;
            var link= (article.PageUrl)? article.PageUrl : this.getArticleLink(key);
             if (activity == "Commented") 
                var number = article.Comments.NumberOfComments;
            else if (activity == "Rated")
                var number = article.Ratings.NumberOfRatings;
            else if (activity == "Recommended")
                var number = article.Recommendations.NumberOfRecommendations;
            else if (activity == "Reviewed")
                var number = article.Reviews.NumberOfReviews;
            else 
                var number = null;
            ctlNode.innerHTML= this.getDiscoveryLinkControl( index, title, link, activity, number);

        }
    },

    _getNameValues: function(arr, delim) {
        var valArray= new Array();
        var i=0;
        for (i=0; i<arr.length; i++) {
            valArray[i]= arr[i].Name;
        }
        return valArray.join(delim);
    },

    getDiscoveryLinkControl: function(index, title, href, type, count) {
        var discCtl="";
      
        discCtl+= "<span class='gslDiscoveryControl'>";
        //discCtl+= " <span class='gslDiscoveryIndex'>"+index+".</span>";
        discCtl+= " <span class='gslDiscoveryLink'>";
        discCtl+= "  <span class='gslDiscovery" + type + "'>";
        discCtl+= "   <a href='"+href+"' title='Go to article' alt='Go to article'>"+unescape(title)+"</a>";
        if (count != null) {discCtl+= "    <span class='gslDiscoveryCount'>("+count+")</span>";}
        discCtl+= "  </span>";
        discCtl+= "  <div class='gslDiscoverySeparator'></div>";
        discCtl+= " </span>";
        discCtl+= "</span>";
        
        return discCtl;  
    },
    
    /*************************************************************************/
    /* SiteLife Thumbnail Functions ******************************************/
    
	checkDaapiAvailable: function(){
	var getpk1cookie = GDN.Cookies.Session.GetValue("pk1");
	if (typeof(getpk1cookie) == "undefined" || getpk1cookie == null )
		gsl.checkpluckconnectivity();
	else
		this.wilDaapiWork = getpk1cookie;
	},
	
	checkpluckconnectivity:function() {
		 var form = this._generateForm(this.plkIframeId,gsl.initDaapiReq, "");
		 try {
		 this._iframeinitialize(form,"",this.plkIframeId);
		 document.body.removeChild(document.body.lastChild);
		  document.body.removeChild(document.body.lastChild);
		 GDN.Cookies.Session.SetValue("pk1",escape(this.wilDaapiWork));
		 }
		 catch (e) {
		 this.wilDaapiWork = "false";
		 GDN.Cookies.Session.SetValue("pk1",escape(this.wilDaapiWork));
		 document.body.removeChild(document.body.lastChild);
		  document.body.removeChild(document.body.lastChild);
		 }
   },
   
	_iframeinitialize: function(form, options,count){
		if (!options) options = {};
		this.form = form;
		document.iframeLoaders[count] = this;
		this.transport = this._getTransport();
		if (((navigator.vendor && (navigator.vendor.indexOf('Apple')) > -1) || window.opera) // safari and opera only
     && (/\/Direct\/Process(\?|$)/.test(form.action)) && form.elements && (form.elements.length == 1)) { // only change calls that contain 1 element and whose actions end with /Direct/Process
			var url = form.action + '?jsonRequest=' + escape(form.elements[0].value), // change form submit to string; similar to changing form method to get
					doc = this.transport.contentWindow || this.transport.contentDocument; // retrieve the document of the iframe
			if (url.length < 80000) { // allow fallback to normal submission (80k is the max length for urls in safari)
				if (doc.document) // make sure we have the document and not the window
					doc = doc.document;
				try { // if this fails, fallback to normal submission
					doc.location.replace(url); // use location.replace to overwrite elements in history 
					return;
				} catch (e) { };
			}
		}
		form.target= 'frame_'+this.plkIframeId;
		form.setAttribute("target", 'frame_'+this.plkIframeId); // in case the other one fails.
		form.submit();
	},

	_getTransport: function() {
		var divElm = document.createElement('DIV'), frame;
		divElm.setAttribute('style', 'width: 0; height: 0; margin: 0; padding: 0; visibility: hidden; overflow: hidden');
		if (navigator.userAgent.indexOf('MSIE') > 0 && navigator.userAgent.indexOf('Opera') == -1) {// switch to the crappy solution for IE
			divElm.style.width = 0;
			divElm.style.height = 0;
			divElm.style.margin = 0;
			divElm.style.padding = 0;
			divElm.style.visibility = 'hidden';
			divElm.style.overflow = 'hidden';
			divElm.innerHTML = '<iframe name=\"frame_'+this.plkIframeId+'\" id=\"frame_'+this.plkIframeId+'\" src=\"about:blank\" onload=\""></iframe>';
		} else {
			frame = document.createElement("iframe");
			frame.setAttribute("name", "frame_"+this.plkIframeId);
			frame.setAttribute("id", "frame_"+this.plkIframeId);
			divElm.appendChild(frame);
		}
		document.body.appendChild(divElm);
		return frame;
	},
	
	_generateForm:function (formId, serverUrl, inputVal) {
	    // create the form
		var form = document.createElement("form");
		form.acceptCharset = "UTF-8";
		form.name = "f" + formId;
		form.id = "f" + formId;
		form.action = serverUrl;
		// Firefox has a behavior on refresh that displays a popup confirming that is it reloading a form.
		// We work around this by attempting to perform a get action if the size is below a threshold, else
		// we will run as a post
		form.method = "post";
	    if(navigator.userAgent.toLowerCase().indexOf('firefox') != -1) {
		    var fullRequestURL = serverUrl;
	        if (fullRequestURL.length < 15000) {
	            // we plan to perform a get, so we need to parse the sid out of the url and place it
	            // inside the form
	            var sidPos = serverUrl.indexOf('sid=');
	            if (sidPos != -1) {
	                var endPos = serverUrl.indexOf('&', sidPos);
	                var sid = serverUrl.substring(sidPos + 'sid='.length, endPos == -1 ? serverUrl.length : endPos);
		            var sidInputElem = document.createElement("input");
		            sidInputElem.name = "sid";
		            sidInputElem.type = "hidden";
		            sidInputElem.value = sid;
		            form.appendChild(sidInputElem);
		            // remove the sid from the url
		            form.action = serverUrl.substring(0, sidPos-1);
	            }
	            form.method = "get";
	        }
	    }		
		// append the form to the document body
		// users must be cautious of when they call this due to a bug in IE
		// see http://support.microsoft.com/kb/927917 for details
		document.body.appendChild(form);
		return form;
	}, 

	getUserAvatarAddress: function(){
		gsl.personaHref= null;
		 if(this.enabled==true) {
		 this._updateArticle=false;
	        var rb= new RequestBatch();
	        rb.AddToRequest(new UserKey());
	        try{
	            gsl.sitelifeRequest(rb, "LoadAvatarAddress", this._loadUAACallback);
	        } catch(e) {
	            this.showException("SL Request", e);
	        }
		 }
    },
    
    _loadUAACallback: function(result)
    {
	
        for (var i=0; i<result.Responses.length; i++) {
            var res= result.Responses[i];
            if (res.User != null) {
                var user=res.User;
                gsl.personaUserKey = user.UserKey.Key;
                gsl.personaHref = user.AvatarPhotoUrl;
            }
        }
    },

    _upArtCB: function(response) {
        if (response.Messages[0].Message != "ok") 
            showDebug("SiteLife Error: "+response.Messages[0].Message);
    },

    populateAvatar: function(pid, photo) {
        if($("gslAvtPhoto"))
           $("gslAvtPhoto").innerHTML = gsl.getUserPhotoLink(pid, photo);
    }, 
  
   _transform: function(data, template) {
        var self = data;
        var rules = { "self" : unescape(template) };
  
        var T = {
          output: false,
          init: function() {
             for (var rule in rules)
                if (rule.substr(0,4) != "self")
                   rules["self."+rule] = rules[rule];
             return this;
          },
          apply: function(expr) {
             var trf = function(s){ return s.replace(/{([A-Za-z0-9_\$\.\[\]\'@\(\)]+)}/g,
                                      function($0,$1){return T.processArg($1, expr);})},
                 x = expr.replace(/\[[0-9]+\]/g, "[*]"), res;
             if (x in rules) {
                if (typeof(rules[x]) == "string")
                   res = trf(rules[x]);
                else if (typeof(rules[x]) == "function")
                   res = trf(rules[x](eval(expr)).toString());
             }
             else
                res = T.eval(expr);
             return res;
          },
          processArg: function(arg, parentExpr) {
             var expand = function(a,e){return (e=a.replace(/^\$/,e)).substr(0,4)!="self" ? ("self."+e) : e; },
                 res = "";
             T.output = true;
             if (arg.charAt(0) == "@")
                res = eval(arg.replace(/@([A-za-z0-9_]+)\(([A-Za-z0-9_\$\.\[\]\']+)\)/,
                                       function($0,$1,$2){return "rules['self."+$1+"']("+expand($2,parentExpr)+")";}));
             else if (arg != "$")
                res = T.apply(expand(arg, parentExpr));
             else
                res = T.eval(parentExpr);
             T.output = false;
             return res;
          },
          eval: function(expr) {
             var v = eval(expr), res = "";
             if (typeof(v) != "undefined") {
                if (v instanceof Array) {
                   for (var i=0; i<v.length; i++)
                      if (typeof(v[i]) != "undefined")
                         res += T.apply(expr+"["+i+"]");
                }
                else if (typeof(v) == "object") {
                   for (var m in v)
                      if (typeof(v[m]) != "undefined")
                         res += T.apply(expr+"."+m);
                }
                else if (T.output)
                   res += v;
             }
             return res;
          }
        };
        
        try {
            return T.init().apply("self");    
        } catch(e) {
            this.showException("_transform()" , e);
            return " ";
        }
    },
    
    
    
        niceDate: function(date){
        var retDate= date;
        if( typeof(niceDate)=='undefined') {
			if(typeof(gsl.TimeZoneoffset) != "undefined" && gsl.TimeZoneoffset !="" )
				retDate= this.convertTimeZone(date);
			else
				retDate= date;
        } else {
            try {
				if(typeof(gsl.TimeZoneoffset) != "undefined" && gsl.TimeZoneoffset !="")
					retDate=this.convertTimeZone(date);
				else
					retDate= niceDate(date);
            } catch(e) {
                retDate= date;  
            }
        }
        return retDate;
    },
	
	convertTimeZone:function(pkdate){
	try{    
    var datetimeobjs =  pkdate.split(" ");
	var dateobjs = datetimeobjs[0].split("/");
	var ampm = "";
	var plucktime = new Date();
	var parseformat = gsl_dateFormat.i18n.monthNames[dateobjs[0]-1]+ ", " + dateobjs[1] + " " + dateobjs[2] +" " + datetimeobjs[1] +" " + datetimeobjs[2];
	plucktime.setTime(Date.parse(parseformat));
	plucktime.setTime(plucktime.getTime() + gsl.TimeZoneoffset * 3600000 );
	var dtformat= gsl_dateFormat(plucktime, "mm/dd/yyyy h:MM:ss tt");
	 
	} catch(e) {
            this.showException("convertTimeZone", e);
        }
		return dtformat;
	},
	
	TempGetnamevalue:function (query,queryname){
		keypairs = new Object();
		  numKP = 1;
		    // Local vars used to store and keep track of name/value pairs
		    // as we parse them back into a usable form.
		  while (query.indexOf('&') > -1) {
		    keypairs[numKP] = query.substring(0,query.indexOf('&'));
		    query = query.substring((query.indexOf('&')) + 1);
		    numKP++;
		      // Split the query string at each '&', storing the left-hand side
		      // of the split in a new keypairs[] holder, and chopping the query
		      // so that it gets the value of the right-hand string.
		  }
		  keypairs[numKP] = query;
		    for (i in keypairs) {
		    keyName = keypairs[i].substring(0,keypairs[i].indexOf('='));
		      // Left of '=' is name.
		    keyValue = keypairs[i].substring((keypairs[i].indexOf('=')) + 1);
		      // Right of '=' is value.
			
			  if (keyName == queryname){
			  return keyValue;
			  }
		    while (keyValue.indexOf('+') > -1) {
		      keyValue = keyValue.substring(0,keyValue.indexOf('+')) + ' ' + keyValue.substring(keyValue.indexOf('+') + 1);
		        // Replace each '+' in data string with a space.
		    }
		 keyValue = unescape(keyValue);
			
		}
	},
	
	char_count:function (el) {
	try{   
		if (typeof($("gslCharCount"))!='undefined'){
			remain = gsl.commentMaxChars - el.value.length; 
			$('gslCharCount').innerHTML = remain;
			if(remain==0) 
				alert("No characters remaining.");
			 else if(remain < 500 && gsl.resized == false) {
				$('gslComFormBody').setStyle({height: "170px"});
				gsl.resized = true;
			}
		  }
		} catch(e) {
			this.showException("Character count function", e);
        }
	}
	
    
};
/*
	Date Format 1.1
	(c) 2007 Steven Levithan <stevenlevithan.com>
	MIT license
	With code by Scott Trenda (Z and o flags, and enhanced brevity)
*/

/*** dateFormat
	Accepts a date, a mask, or a date and a mask.
	Returns a formatted version of the given date.
	The date defaults to the current date/time.
	The mask defaults ``"ddd mmm d yyyy HH:MM:ss"``.
*/
var gsl_dateFormat = function () {
	var	token        = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloZ]|"[^"]*"|'[^']*'/g,
		timezone     = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (value, length) {
			value = String(value);
			length = parseInt(length) || 2;
			while (value.length < length)
				value = "0" + value;
			return value;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask) {
		// Treat the first argument as a mask if it doesn't contain any numbers
		if (
			arguments.length == 1 &&
			(typeof date == "string" || date instanceof String) &&
			!/\d/.test(date)
		) {
			mask = date;
			date = undefined;
		}

		date = date ? new Date(date) : new Date();
		if (isNaN(date))
			throw "invalid date";

		var dF = gsl_dateFormat;
		mask   = String(dF.masks[mask] || mask || dF.masks["default"]);

		var	d = date.getDate(),
			D = date.getDay(),
			m = date.getMonth(),
			y = date.getFullYear(),
			H = date.getHours(),
			M = date.getMinutes(),
			s = date.getSeconds(),
			L = date.getMilliseconds(),
			o = date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "a.m." : "p.m.",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4)
			};

		return mask.replace(token, function ($0) {
			return ($0 in flags) ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
gsl_dateFormat.masks = {
	"default":       "ddd mmm d yyyy HH:MM:ss",
	shortDate:       "m/d/yy",
	mediumDate:      "mmm d, yyyy",
	longDate:        "mmmm d, yyyy",
	fullDate:        "dddd, mmmm d, yyyy",
	shortTime:       "h:MM TT",
	mediumTime:      "h:MM:ss TT",
	longTime:        "h:MM:ss TT Z",
	isoDate:         "yyyy-mm-dd",
	isoTime:         "HH:MM:ss",
	isoDateTime:     "yyyy-mm-dd'T'HH:MM:ss",
	isoFullDateTime: "yyyy-mm-dd'T'HH:MM:ss.lo"
};

// Internationalization strings
gsl_dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask) {
	return gsl_dateFormat(this, mask);
};
