(function(){ 
var $= function(id){ 
	return document.getElementById(id);
}, _ARTICLE_CACHE= {}, 
GArticle= function(id){ 
	if(id in _ARTICLE_CACHE) return _ARTICLE_CACHE[id]; 
	this.id= id; 
	this.remoteneedsinfo= false; 
	this.commentcount= 0; 
	this.recommendcout= 0; 
	this.comments= []; 
	_ARTICLE_CACHE[id]= this; 
	return this; 

}
GEL.namespace('GEL.legacy.SiteLife'); 
GEL.legacy.SiteLife.gsl = window.gsl= {
    
    /*************************************************************************/
    /* Site Configurations ***************************************************/
    enabled: true,
    SiteStaffText: (function(){ 
    	if(GEL.thepage && GEL.thepage.pageinfo && GEL.thepage.pageinfo.url && GEL.thepage.pageinfo.url.domainname) 
    		return GEL.thepage.pageinfo.url.domainname + " Staff";
	else 
		return " Staff "; 
	})(), 
    sitelifeApiUrl: GEL.config.sitelifeurl ? 
    	GEL.config.sitelifeurl : 
	'http://sitelife.' + GEL.config.domain + 
		'/ver1.0/Direct/Process?sid=sitelife.' + GEL.config.domain,
    personaHrefEnabled: true,
    personaHrefURL: "/apps/pbcs.dll/section?category=pluckpersona",
    recommendLbl: 'Recommend',
    recommendedLbl: 'Recommended',
    commentCountHrefEnabled: true,
    reviewCountHrefEnabled: true,
    requestsperBatch: 5,
    recommendCountHrefEnabled: true,
	reportabuseposx:"",
	reportabuseposy:"",
	fullcommentpage:0,
	totalnocomments:0,
	resized:false,
	params:"",
	plkreplycomment:"",
    /* 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",	
	//initDaapiReq:"http://sitelife."+ document.domain +"/ver1.0/Direct/Process", 
	
    // 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: 0,                   // on/off - if debugDiv exists display debugging info
    _updateArticle: false,      // DO NOT MODIFY!
    _keyUsed: false,
    IsOdd:1,
    MaxNumberofAbuse: 3, 
    commentMaxChars: 1000,
    
    // Fronts Controls Page Configuration
    discoveryAge: "7",    // number of days for discovery widgets
    
    /*************************************************************************/
    /* GMTI SiteLife Library Initialization **********************************/

    initialSetup: function(userID) {
	if(GEL.env.ua.ie) 
		this.checkDaapiAvailable();
	else 
		this.wilDaapiWork= true; 
	if(!this.wilDaapiWork) {
		var _el= $("IE6Error"); 
		if(_el) _el.style.display= "block"; 
		return; 
	}
	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.InsertBannerEveryComment= 2; 
	this.bannerposition= "300x250_1"; 
	this.updateReactionFormHead(); 
	this.Comments();
	gsl.ArticleControls(); 
     	return false; 
    },
    addControlEvents:function(){ 
    /* 
    TODO: Need to turn the whole comment area into a GEL widget
             so these things can be added via Controller
    */

    	var 
		_sortList= GEL.ement("gslSortOrder"), 
		_commentHider= GEL.ement("toggle_comments"),
		_commentSubmit= GEL.ement("gslComFormSubmit"), 
		_reactionList= GEL.ement("comment_container"),
		_commentText= GEL.ement("gslComFormBody"),
		_hideCommentPref= GEL.env.persistentcache.getValue("hidecomments"),
		_loginEl= GEL.ement("headLoggedIn"), 
		_logoutEl= GEL.ement("headLoggedOut")
	; 
	_sortList.on("change", function(type,event){ 
		var _me= event.getTarget(),_val; 
		_val= _me.value; 
		gsl.setSortOrder(_val); 
	}); 
	_commentHider.on("click", function(type,event){ 
		if(_reactionList.isVisible()){ 
			this.addClassName("show"); 
			this.removeClassName("hide"); 
			GEL.env.persistentcache.setValue("hidecomments", 1); 
		}else { 
			this.addClassName("hide"); 
			this.removeClassName("show"); 
			GEL.env.persistentcache.deleteValue("hidecomments"); 
		}
		_reactionList.toggle(); 
	}); 
	if(_hideCommentPref) { 
		_commentHider.fire("click", _commentHider); 
	}
	_commentText.on("keyup", (function(maxchars){ 
		var _cEl= GEL.ement("gslCharCount").getElement();
		return function(type,domEvent){ 
			var _c= this.getElement().value.length; 
			var _left= maxchars - _c;
			_left= _left <= 0 ? 0 : _left; 
			_cEl.innerHTML= _left; 
		}

	})(gsl.commentMaxChars)); 
	if(GEL.env.user.isloggedin){
		onLogin(); 
	}else { 
		onLogout(); 
	}
	GEL.env.user.on("login", onLogin);  
	GEL.env.user.on("logout", onLogout);  
	function enable(){ 
		for (var i=0;i<arguments.length;i++) {
			arguments[i].getElement().disabled= false; 
		}
	}
	function disable(){ 
		for (var i=0;i<arguments.length;i++) {
			arguments[i].getElement().disabled= true; 
		}
	}
	function onLogin(){ 
		enable(_commentSubmit, _commentText); 
		_loginEl.css({display: "block"});
		_logoutEl.css({display: "none"}); 
	}
	function onLogout(){ 
		disable(_commentSubmit, _commentText); 
		_loginEl.css({display: "none"});
		_logoutEl.css({display: "block"}); 
	}

    }, 

	//Make a Call to Set Comment Policy for that article
	CommentPreModeration: function(SetContentPolicy) {
		var rb= new RequestBatch(), 
		  _artKey= gsl.getArticleKey()
		;
		var setPolicyRequest = new SetContentPolicyAction(
			new ArticleKey(_artKey), 
			new UserTier("Standard"), 
			new ContentPolicyActionType("Comment"), 
			new ContentPolicy(SetContentPolicy)
		);
        	rb.AddToRequest(setPolicyRequest);
		this.sitelifeRequest(rb, "Set Comments Policy", this.OnSetComplete); 
	},
	OnSetComplete: function(ReturnedJSON) {
		//Don not do anything in the Call back function for now.
    	},
    _templates: {'comments': {'loaded': false}, 'reviews': {'loaded': false}},
    _avatarOverride: 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.personaHrefURL + 
			'&U=' + pid + "\">" +personaHtml+ "</a>";
                personaHtml = personaHtmlHref;
            }
            return personaHtml;
        }
        else return "";
    },

    getUserPersona: function(pid) {
        return gsl.personaHrefURL + '&U=' + pid;
    },
    
    
    getUserHandle: function() {
        var cookie = GEL.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.personaHrefURL + "&U=" + pid + "\">" + 
	  	"<b>" + handle + "</b></a>"; 
        return handleHtml;       
    },
    
    getUserPid: function() {
    	if(GEL.env.user) return GEL.env.user.uid;
	else return ''; 
    },
    
    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'><span class=icon></span>Reported</span>"; 
        } else {    
            raHtml += "<span id='gslReportAbuse:" + type + ":" + key + "' class='gslReportAbuseLink'>";    
            raHtml += "<span class=icon></span><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() {
	gsl._templates.comments['loaded']= true;
	/*
	if(! gsl.reactionsClosed) {
            gsl.updateReactionFormHead('comment');
        }
	*/
	 gsl.getReactions('comment');  
		
    },
         
    /*************************************************************************/
    /* Reactions - aka Comments and Reviews Common Logic *********************/
   
    getReactions: function(type,noCount) {
        	var 
			articleKey= this.getArticleKey(),
			gslCharCntEl= $('gslCharCount'), 
			gslSortOrder= $('gslSortOrder'),
			_sortOrder, rb= new RequestBatch()
		;
		gsl.params = 
			GEL.env.url.qsv;
		gsl.params.page= gsl.params.page || 1;
		_sortOrder= 's' in gsl.params ? 
			gsl.params.s : gslSortOrder.value; 
		_sortOrder=  _sortOrder == "a" ? 
			"TimeStampAscending" : "TimeStampDescending";
        	rb= new RequestBatch();
            	rb.AddToRequest(
			new CommentPage(
				new ArticleKey(articleKey),
				gsl.requestsperBatch,
				gsl.params.page,
				_sortOrder
			)
		);
		noCount= (typeof noCount == 'undefined' || !noCount)? false : true;  
		if(!noCount) 
        		rb.AddToRequest(new ArticleKey(articleKey));
		if(typeof(contentAutID)!= 'undefined' && contentAutID != "") 
			rb.AddToRequest(new UserKey(contentAutID));
        	this.sitelifeRequest(rb, "LoadReactions", this._getReactionsCallback(articleKey));   
    	},
   // Refactored!  04/30/09 WFA 
    _getReactionsCallback: function(articlekey){ 

			var _art= {}, 
			_self= gsl
		; 

			if(articlekey) 
			_art= new GArticle(articlekey); 
			return function(resBatch) {
					if(
					typeof resBatch != 'object' ||
					typeof resBatch.Responses == 'undefined'
				)throw new Error("_getReactionsCallback(): Received no resBatch argument"); 
				if(gsl.reloadAds && GEL.thepage.bannerLocator){
					GEL.thepage.bannerLocator.loadBanners(); 	
					GEL.thepage.viewTracker.trackView();
					gsl.reloadAds= false; 
				}
					var 
					i=0, 
					response, 
					responseType
				;
				gsl.responses= resBatch.Responses; 
				if(resBatch.Messages[0].Message.toLowerCase() != "ok")
					_art.remoteneedsinfo= true; 
				for (;i<resBatch.Responses.length;i++) {
					response= resBatch.Responses[i];
					responseType= ( function(){ 
						if(response.CommentPage) return 'comment'; 
						else if(response.ReviewPage) return 'review'; 
						else if(response.Article) return 'article';
						else return null;
					})(); 
					
					switch(responseType) {
						case 'comment': 
							_updateReactionList('comment', response); 
							break; 
						case  'review': 
							_updatePageReviews(response); break; 
						case  'article':
							//_self.checkArticleInfo(response.Article); 
							_updatePageComments(response); 
							_updatePageRecs(response); 
							break; 
						default: 
							GEL.log ("I have a type of " + repsonseType);
							break;  
					}
				}
				
				/*
				-Updating an article should be separate from the switch statement
				-We don't wont to update an article in the full comment page article
				*/
				if(gsl.fullcommentpage!=1){
					_self._updateArticle = (function(){
						for(var j=0;j<gsl.responses.length;j++){
							if(typeof(gsl.responses[j].Article)!='undefined')
								return _self._compareArticleInfo(gsl.responses[j].Article)
						}
							return false
					})(); 
				}

				if(_art.remoteneedsinfo){ 
					_updatePageRecs(); 
					_updatePageComments(); 
				}
				if(_self._updateArticle) { 
					_self.sitelifeRequest(); 
				}
			}
		function _updatePageRecs(response){ 
			var 
				artKey= gsl.getArticleKey(), 
				_c= typeof response == 'object' && response.Article ? 
					response.Article.Recommendations.NumberOfRecommendations : 
					0,
				_parentEl= null; 
			var _canRec= typeof response == 'object' && response.Article ? 
				(response.
				Article.
				Recommendations.
				CurrentUserHasRecommended == 'True' ? 
					false : true
				):true;
			_parentEl= $('gslCtl-article|recommends|'+artKey); 

			if(typeof _parentEl == 'undefined' || !_parentEl || !_parentEl.appendChild) { 
				return; 
			}
			var _recEl= gsl.getRecommendCountDOM(_c,'article', artKey, _canRec); 
			if(typeof _recEl != 'undefined' && _recEl && _parentEl.childNodes.length == 0) 
				_parentEl.appendChild(_recEl); 
		}
		function _updatePageComments(response){
			var commentCount= typeof response == 'object' && response.Article ? 
				parseInt(response.Article.Comments.NumberOfComments) : 
				0,
				artKey= gsl.getArticleKey(), 
				_parentEl= null, 
				_el= null,
				_text= ''; 
			_parentEl= $('gslCtl-article|comments|'+artKey); 
			if(
				typeof _parentEl == 'undefined' 	
				|| !_parentEl 
				|| !_parentEl.appendChild
			) {
				return; 
			}
				_el= gsl.getCommentCountDOM(commentCount, "javascript:gsl.redirectToCommentPage({commentCount:"+commentCount+"})"); 
			if (_parentEl.childNodes.length == 0) {
			_parentEl.appendChild(_el); 
			}
		}
		function _updateReactionList(type,response){
			var _list= response.CommentPage.Comments,
				_c = response.CommentPage.NumberOfComments,
				i=0,
				_updateElement= GEL.ement("gslReactionList"),
				_paginationContainer= GEL.ement("gslPagination"),
				_paginationContainerTop= GEL.ement("gslPaginationTop"),
				_paginationContainerBottom= GEL.ement("gslPaginationBottom"),
				_f = GEL.ement("gslfullpage"),
				_t = GEL.ement("gslTitle"),
				_className= '',
				_addClassFn= GEL.elementUtil.addClassName, 
				_firstDiv= null,
				_el= null,
				_a = document.createElement('a'),
				_e = document.createElement('em'),
				_ta = document.createElement('a'),
				_h = document.createElement('h1'),
				_d = document.createElement('div'),
				_pd = document.createElement('div'),
				_s = document.createElement('span'),
				_pt = GEL.ement("pluckalerttext"),
				_p = GEL.ement("pluckarticleid"),
				_de = GEL.ement("gslfullpagelink"),
				_sc = GEL.ement("gslTitle-Comments-Span"),
				_curl = window.location.href.toLowerCase(),
				_u
			;
			
			if (!_pt.isattach && typeof(_curl.indexOf("pluckarticleid")) != 'undefined' && _curl.indexOf("pluckarticleid") > 0){
				_pd.appendChild(document.createTextNode("Pluck Article ID = " + gsl.getArticleKey()));
				_pd.className =("pluckalerttext");
				_pd.setAttribute('id','pluckalerttext');
				_p.element.appendChild(_pd);
				$("pluckarticleid").style.display ="block";
			}
				
			if(!_updateElement.isattach)
				throw new Error ("Cannot find reaction list element"); 
			_updateElement.clear(); 
			
			/*Article Comments Pagination*/
			if(!_self.paginator){ 
				if(_paginationContainer.isattach){
					_self.paginator= gsl.getPaginator(type, response.CommentPage);
					_self.paginator.addClassName("comment-pagination"); 
					_self.paginator.attach(_paginationContainer); 
				}
			}else { 
				_self.paginator.setPage(gsl.params.page);
			}
			
			/*Full Page Article Comments Pagination*/
			if(!_self.paginatorTop && !_self.paginatorBottom){ 
				if(_paginationContainerTop.isattach && _paginationContainerBottom.isattach && !_self.paginatorTop && !_self.paginatorBottom){
					_self.paginatorTop= gsl.getPaginator(type, response.CommentPage);
					_self.paginatorTop.addClassName("comment-pagination"); 
					_self.paginatorTop.attach(_paginationContainerTop);
					_self.paginatorBottom= gsl.getPaginator(type, response.CommentPage);
					_self.paginatorBottom.addClassName("comment-pagination"); 
					_self.paginatorBottom.attach(_paginationContainerBottom);
				}
			}else{
				_self.paginatorTop.setPage(gsl.params.page);
				_self.paginatorBottom.setPage(gsl.params.page)
			}		
			
			/*Full comments Link*/
			if(_c>gsl.requestsperBatch && !_de.isattach && gsl.fullcommentpage!=1){
				_d.className = 'gslfullpagelink';
				_d.setAttribute('id','gslfullpagelink');
				_a.className = 'button';
				_a.setAttribute('href','javascript:gsl.redirectToCommentPage({commentCount:'+_c+'});');
				_a.appendChild(document.createTextNode("FULL PAGE VIEW \u00a0"));
				_e.appendChild(document.createTextNode("See more comments per page and quote other replies"));
				_d.appendChild(_a);
				_d.appendChild(_e);
				_f.element.appendChild(_d);
			}
			
			/*Full Page Article Comments :pluckcomments page Title*/
			if(gsl.fullcommentpage==1 && !_sc.isattach){
				_ta.setAttribute('href',gsl.getArticleLink());
				_ta.appendChild(document.createTextNode(gsl.getArticleTitle()));
				_s.setAttribute('id','gslTitle-Comments-Span');
				_s.className = 'gslTitle-Comments';
				_s.appendChild(document.createTextNode("Comments for "));
				_h.appendChild(_ta);
				_t.element.appendChild(_s);
				_t.element.appendChild(_h); 
			}
			
			var _displayCount=1; 
			for(;i<_list.length;i++) { 
				_el= gsl._getReactionDOM(type, _list[i]),
					_className = _displayCount % 2 == 0 ? 'even' : 'odd' ; 	
				if(typeof _el == 'undefined' || !_el || 
					typeof _el.childNodes == 'undefined' || !_el.childNodes) {
					continue; 
				}
				for(var j=0;j<_el.childNodes.length;j++) 
					if(
						_el.childNodes[j].tagName && 
						_el.childNodes[j].tagName.toLowerCase() == 'div' 
					) 
						_addClassFn( _el.childNodes[j], _className); 
				_updateElement.element.appendChild(_el); 
				_displayCount++; 
			}
		}

    },
    _getReactionDOM: function(type, reaction){ 
    	if(reaction.AbuseReportCount >= gsl.MaxNumberofAbuse) return null; 
	else if(reaction.Author.IsBlocked.toLowerCase() == 'true') return null; 
	var 
		author= reaction.Author.UserKey.Key, 
		recommended= reaction.CurrentUserHasRecommended.toLowerCase() == 'true' ? 
			true : false, 
		rptdAbuse= reaction.CurrentUserHasReportedAbuse.toLowerCase() == 'true' ? 
			true : false, 
		staffMrk= (
			reaction.Author.UserTier.toLowerCase() == 'editor'  || 
			reaction.Author.UserTier.toLowerCase() == 'staff'
			) ?  
				gsl.SiteStaffText : "",
		recNum= reaction.NumberOfRecommendations ? 
				reaction.NumberOfRecommendation : 0, 
		tz= (
			typeof gsl.TimeZonewords != 'undefined' && 
			typeof gsl.TimeZoneoffset != 'undefined' 
		    ) ? 
			gsl.TimeZonewords : "", 
		key= type == 'comment' ? 
			reaction.CommentKey.Key :  reaction.ReviewKey.Key, 
		_templateEl = $(type),
		rptAbuseLink= staffMrk == '' ? 
			this.getReportAbuseLink(type, key, rptdAbuse) : "",
		_canRec= true, 
		_recLink= "", 
		_str
	; 
	if(!_templateEl) throw new Error ("Cannot find template for type " + type); 
       	_canRec= reaction.CurrentUserHasRecommended.toLowerCase() == 
		'true' ? false : true; 
        _recLink= gsl.getRecommendCountDOM(
		reaction.NumberOfRecommendations ? reaction.NumberOfRecommendations : 0,
		'comments',key,_canRec
	); 
	_str= this._transform({ 
		authorIcon: this.getUserPhotoLink(author, reaction.Author.AvatarPhotoUrl), 
		authorHandle: this.getUserHandleLink(author, 
			reaction.Author.DisplayName,
			reaction.Author.AboutMe,
			reaction.Author.Age,
			reaction.Author.Location,
			reaction.Author.Sex
		),
		commentTimestamp: this.niceDate(reaction.PostedAtTime) + " " + tz,
		commentBody: gsl.addblockquoteshtml(gsl.getrawcomment(reaction.CommentBody)), 
		commentKey: key, 
		reportAbuseLink: rptAbuseLink, 
		staffMark: staffMrk, 
		siteofOrigin: reaction.SiteOfOrigin, 
		alt: "", 
		authorNameHandle: reaction.Author.DisplayName, 
		replylink: this.getReplyToLink(key), 
		newpostLink: '<a class=newpost href=javascript:gsl.addquote(null);>New Post</a>'
	}, _templateEl.innerHTML); 
	var el= GEL.ement("DIV", {}); 	
	el.setHTML(_str); 
	var _recParent= el.get('.gslComRec')[0]; 
	if(!_recParent) return el.element; 
	_recParent.appendChild(_recLink); 
	return el.element; 
    },

	getrawcomment:function(combody) {
	 combody= gsl.addblockquotestext(combody);
	 combody= combody.replace(/<(.|\n)*?>/g, "");
	 return combody;
	},

	addblockquotestext:function(rawcombody) {
	//replace blockquote html to text
	rawcombody= rawcombody.replace(/<blockquote>/g,"\[blockquote\]");
	rawcombody= rawcombody.replace(/<\/blockquote>/g,"\[\/blockquote\]");
	return rawcombody;
	}, 
	
	
	addblockquoteshtml:function(rawcombody) {
	//replace text to HTML before displaying 
	rawcombody= rawcombody.replace(/\[\/QUOTE\]/g,"<\/blockquote>");
	rawcombody= rawcombody.replace(/\[QUOTE\]/g,"<blockquote>");
	rawcombody= rawcombody.replace(/\[\/blockquote\]/g,"<\/blockquote>");
	rawcombody= rawcombody.replace(/\[blockquote\]/g,"<blockquote>");
	return rawcombody;
	}, 
	
	
	
    addquote: function (key) { 
	var content, author, form_el=$("gslComFormBody"); 
	if (key) { 
		author = $("author_" + key).value; 
		content = $("body_" + key).value; 
		gsl.plkreplycomment = content;
	} 
	if (content) { 
		author = author.replace(/.+<b>([^<]+)<\/b>.+/i, "$1"); 
		content = "[QUOTE]" + content + "[/QUOTE]\n"; 
		$("gslQuoteAuthor").value = author;
		form_el.value = content; 
	} else { 
		form_el.value = ""; 
	} 
	if(form_el.disabled) return; 
	form_el.scrollIntoView(); 
	form_el.focus(); 
	gsl.commentMaxChars
	var _cEl= GEL.ement("gslCharCount").getElement(), _max= gsl.commentMaxChars, _left;
	_left= _max - form_el.value.length; 
	_cEl.innerHTML= _left; 
    },
    updateReactionFormHead: function(type, signOut) {
    	var 
		maxChars= {maxchars: gsl.commentMaxChars}, 
		headerTemplate= '',headHtml= '',
		loginEl= $("headLoggedIn")
	;
	if(!loginEl) return; 
    	if(this.reactionsClosed )
		return; 
  	headerTemplate= loginEl.innerHTML;
	try {
              headHtml= this._transform(maxChars, headerTemplate);
         } catch (e) {
             this.showException("updateReactionFormHead() head transform" , e);
         }         
        loginEl.innerHTML= headHtml;
	$("gslCharCount").innerHTML= maxChars.maxchars;  
	this.addControlEvents(); 
    },    
    getPaginator: function(type, page,currentPage){
    	var countKey= type =='comment' ? 'NumberOfComments' : 'NumberOfReviews'; 
	currentPage= currentPage || gsl.params.page || 1; 
	var 
		_maxPages= 4, 
		_count= page[countKey],
		_perPageCount= page.NumberPerPage, 
		_paginationEl= GEL.ement("UL", {}),
		_pageLI= document.createElement("LI"),
		totalPages=0
	;
	_totalPages= 
		parseInt( _count / _perPageCount );
	if(_count % _perPageCount != 0 ) 
		_totalPages += 1; 
	var _pc= _maxPages >= _totalPages ? 
			_totalPages : _maxPages; 
	makePages(1, _pc, 1); 
	if(_totalPages <= 1) _paginationEl.css({display: 'none'}); 
	else _paginationEl.css({display: 'block'}); 
	_paginationEl.on("click", (function(){ var _self= _paginationEl ; 
		return function(type, gDomEvent){ 
			// I know, this is Really Bad
			var tgt= gDomEvent.getTarget(); 
			if(tgt.tagName.toLowerCase() == 'ul') return; 
			var page= 1, 
			    str= tgt.textContent || tgt.innerText; 
			if(str == '<<') page= gsl.params.page - 1; 
			else if (str == '>>') page= gsl.params.page + 1; 
			else if (str == 'First') page= 1; 
			else if (str == 'Last') page= _totalPages; 
			else { 
				page= parseInt(str); 
			}
			if(page == gsl.params.page) return; 
			if(gsl.fullcommentspage) 
				gsl.reloadAds= true; 
			gsl.params.page= page; 
			gsl.getReactions("comment", true); 
			tgt.className += " clicked";
		} 
	})() ); 
	_paginationEl.setPage= function(pageNo){ 
		var _oldPage= 1, 
			_anchor= gsl.fullcommentpage ? 
				document.body :  null, 
			currPage=0;
		for(var i=0;i<this.element.childNodes.length;i++) {
			var _el= this.element.childNodes[i]; 
			_el= GEL.ement(_el); 
			var currPage= 
				parseInt(_el.innerHTML); 
			if(currPage == pageNo)
				_el.addClassName("on"); 
			else if(_el.hasClassName( "on") ) {
				_oldPage= i+1; 
				_el.removeClassName("on"); 
			}
			
		}
		var newFirst= pageNo - _maxPages, 
			newLast= pageNo + _maxPages; 
		newFirst= newFirst <= 0 ? 1 : newFirst; 
		newLast= newLast > _totalPages ? _totalPages : newLast; 
		_paginationEl.clear(); 
		makePages(newFirst, newLast, pageNo); 

		if(_anchor)
			_anchor.scrollIntoView(); 
			
	}
	function makePages(first, last, currentPage){ 
		var i= first,
			_paginationContainerTop= GEL.ement("gslPaginationTop"),
			_paginationContainerBottom= GEL.ement("gslPaginationBottom");
		
		if (first > 1) { 
			_pageLI= document.createElement("LI"); 
			_pageLI.appendChild(document.createTextNode("1")); 
			_paginationEl.appendChild(_pageLI); 
		}
		
		if(currentPage!=1 && _totalPages>1){
			_pageLI= document.createElement("LI"); 
			_pageLI.appendChild(document.createTextNode("First"));
			_paginationEl.appendChild(_pageLI); 
		}
		
		if(currentPage!=1){
			_pageLI= document.createElement("LI"); 
			_pageLI.appendChild(document.createTextNode("<<"));
			_paginationEl.appendChild(_pageLI); 
		}
		
		for (;i<=last;i++){
			_pageLI= document.createElement("LI"); 
			_pageLI.appendChild(document.createTextNode(i) ); 
			_paginationEl.appendChild(_pageLI); 
			if(i==currentPage) 
				GEL.elementUtil.addClassName(_pageLI, 'on'); 
		}
		
		if(currentPage < _totalPages){ 
			_pageLI= document.createElement("LI"); 
			_pageLI.appendChild(
				document.createTextNode(">>")
			); 
			_paginationEl.appendChild(_pageLI); 
		}
		
		if(last<_totalPages){ 
			_pageLI= document.createElement("LI"); 
			_pageLI.appendChild(
				document.createTextNode(_totalPages)
			); 
			_paginationEl.appendChild(_pageLI); 
		}
		
		if(currentPage!=_totalPages && _totalPages>1){
			_pageLI= document.createElement("LI"); 
			_pageLI.appendChild(document.createTextNode("Last"));
			_paginationEl.appendChild(_pageLI); 
		}
	}
	return _paginationEl; 

    },
    checkArticleInfo: function(plckArt){ 
    	 var _plckInfo= { 
	 	key: plckArt.ArticleKey.Key, 
		link: plckArt.PageUrl, 
		title: plckArt.PageTitle
	 },
	     _currInfo= { 
	     	key: this.getArticleKey(), 
		link: this.getArticleLink(),  
		title: this.getArticleTitle()
	 }, 
	 _gArt= new GArticle(this.getArticleKey())
	 ; 

	 if(gsl.fullcommentpage) 
	 	return true; 
	 if(_gArt.remoteneedsinfo){ 
	 	this._updateArticle= true; 
		return true; 
	}
	this._updateArticle= 
		GEL.objectUtil.isEqual(_plckInfo,_currInfo) ? false : true; 
	return this._updateArticle; 
    }, 
    submitReaction: function() {
        var 
		type= $("gslReactionType").value,
        	tmpl= "", 
       		body= "",
       		max= 0,
		el= $("gslComFormBody"), 
		re= new RegExp(/\[QUOTE\]/), 
		return_str= '', 
       		err= $("gslFormError")
	; 
        err.innerHTML= "";
        var emptyFlag= false;
        tmpl= this._templates.comments;
        body= el.value; 
        max= this.commentMaxChars;
        
        if (body.length==0 || !this.hasWhiteSpace(body)) {
            err.innerHTML= $('missingInputError').innerHTML;
	    setTimeout(function(){ el.focus();}, 1); 
            return false;
        }
	if (!this.checkBodyLength(body, max)){
		var data= {'maxchars':max};
		err.innerHTML= this._transform(data, $('entryTooLongError').innerHTML);
		return false;
	}

	if (
		body.indexOf("[QUOTE]") != -1 
		|| body.indexOf("[\QUOTE]") != -1 
	){
		body = 
			"Replying to "+ 
			$('gslQuoteAuthor').value + ":" +
			gsl.addblockquoteshtml(gsl.getrawcomment(body));
			
	}
	else 
		body = gsl.getrawcomment(body);
	var _gArt= new GArticle(this.getArticleKey()); 
	if(_gArt.remoteneedsinfo) this._update= true; 
        this._submitReactionToSiteLife(type, body);
    },
	
    hasWhiteSpace:(function(){ 
    	var _re= new RegExp(/^\s+$/); 
    	return function (s){
     		return !_re.test(s); 
	}
    })(),
	
	redirectToCommentPage:function (options){
		var options= options || {},
			commentCount = 'commentCount' in options ? options.commentCount : 0;

		if (commentCount>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";
			}
			base_url += "&art_url="+encodeURIComponent(gsl.getArticleLink())+"&art_title="+escape(gsl.getArticleTitle());
			window.location.href = base_url;
		} else
			window.location.href = "#pluckcomments";
	},
 	
    _submitReactionToSiteLife: function(type,comBody) {
        var 
		title= this.getArticleTitle(), 
        	articleKey= this.getArticleKey(),    
        	articleLink= this.getArticleLink(),
		userKey = new UserKey(gsl.getUserPid()), 
        	rb= new RequestBatch()
	;
	comBody= this.return2br(comBody);
        rb.AddToRequest(
	    	new CommentAction(new ArticleKey(articleKey), 
	   	 	articleLink, 
			title, 
			comBody
	    	)
	);
	rb.AddToRequest(userKey);
        $("gslComFormBody").value= "";
        this.sitelifeRequest(rb, "SubmitReaction", this._submitReactionToSiteLifeCallback);   
    },
	articleCommentB: function(){
		if(	typeof(GEL.thepage.pageinfo.sn.pluck.CommentCount)!='undefined' &&
			typeof(GEL.thepage.pageinfo.sn.pluck.CommentUrl)!='undefined'
		){
			var	
				_parentDiv = GEL.ement("ArticleCommentBox"),
				_i= GEL.thepage.pageinfo.sn.pluck.CommentCount,
				_link = GEL.thepage.pageinfo.sn.pluck.CommentUrl,
				_comments = document.createElement('div'),
				_noComments = document.createElement('div'),
				_comments_pad = document.createElement('div'),
				_comments_left = document.createElement('div'),
				_comments_right = document.createElement('div'),
				_h = document.createElement('h3'),
				_a = document.createElement('a'),
				_p = document.createElement('p'),
				_pc = document.createElement('p'),
				_txt = (_i>0)?"Read and share your thoughts on this story.":"Be the first to share your thoughts on this story.",
				_mainDiv = (_i>0)?_comments:_noComments
			;

			_comments.className =("articlecommentslink");
			_noComments.className =("articlecommentslink-nocomments");
			_comments_pad.className =("articlecommentslink-padding");
			_comments_left.className =("articlecomments-left");
			_comments_right.className =("articlecomments-right");
			_a.setAttribute('title','Go to comments');
			_a.setAttribute('href',_link);
			
			_a.appendChild(document.createTextNode("Comments >>"));
			_p.appendChild(document.createTextNode(_txt));
			_pc.appendChild(document.createTextNode(_i))
			_h.appendChild(_a);
			_comments_right.appendChild(_h);
			_comments_right.appendChild(_p);
			if(_i>0)
				_comments_left.appendChild(_pc);
				
			_mainDiv.appendChild(_comments_pad);
			_mainDiv.appendChild(_comments_left);
			_mainDiv.appendChild(_comments_right);
			_parentDiv.element.appendChild(_mainDiv);
			
			GEL.log("Attaching Comment Box");
		} else
			GEL.log("Failed to attach Comment Box: Check that GEL.thepage.pageinfo.sn.pluck.CommentUrl & GEL.thepage.pageinfo.sn.pluck.CommentCount exist");
	},
    
    _submitReactionToSiteLifeCallback: function(res) {
        var msg= '';
        for (var i=0; i<res.Messages.length; i++) {
            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";
			GEL.env.user.onLogout(); 
			
			setTimeout(function() {
				window.location.href = gsl.pluckSigninPage + 
				"&destination=" +encodeURIComponent(location.href);
			}, 4000);
		}
		$("gslFormError").innerHTML = msg.Message;
                gsl.showException("_submitReactionToSiteLifeCallback" + msg.Message);
		return false; 
            } 
	    handleSubmission(res.Responses[i]); 
   	}
	function handleSubmission(response){ 
		var 
         		reacCount =  gsl.totalnocomments;
			curPage = parseInt(gsl.params["page"] || 1),
			pageDiv = Math.ceil(reacCount / gsl.requestsperBatch),
			desc = ((gsl.params["s"] == "a") ? false : true),
			resUserTier = response.User.UserTier, 
			npage= 0
		;
		if(desc && curPage>1){
			npage = 1;
		} else if(!desc && curPage<pageDiv){
			npage = pageDiv;
		}	
		if(npage){	
			new_url = (gsl.fullcommentpage)? 
				"/apps/pbcs.dll/section?Category=pluckcomments&key="+
					gsl.params["key"]+"&s="+
					gsl.params["s"]+
					"&page=":
				this.getArticleUrl() + "&s="+gsl.params["s"]+"&page="
			;
			window.location.href = new_url + npage.toString();
		} else {
			if(
				typeof CommentPreModeration  != 'undefined'  &&
				CommentPreModeration == 'checked' && 
				resUserTier == 'Standard'
			){
				err= $("gslFormError");
				if($("gslFormPreModeration")){
					err.innerHTML = $("gslFormPreModeration").innerHTML;
				}
			}else {
				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() {   
		if('key' in GEL.env.url.qsv) 
			return GEL.env.url.qsv.key; 
		if(
			'pageinfo' in GEL.thepage && 
			'sn' in GEL.thepage.pageinfo && 
			'pluck' in GEL.thepage.pageinfo.sn
		) 
			return GEL.thepage.pageinfo.sn.pluck.id;
		var id = (typeof(contentID)!='undefined') ? contentID : null;
			return id;
    },
    setArticleKey: function(id){ gsl.params.articlekey= id; },
    getArticleTitle: function() {
        // if gsl.contentTitle is not set, then parse it out of the browser title bar
		var _t;
		if('art_title' in GEL.env.url.qsv)
			return unescape(GEL.env.url.qsv.art_title);
			
		if( typeof GEL == 'object' && 
			typeof GEL.thepage.pageinfo == 'object'  && 
			typeof GEL.thepage.pageinfo.title=='string' 
		) { 
			return GEL.thepage.pageinfo.title; 
		}
		return document.title; 
    },

    /// This method makes no sense to me.  Why would it?  It relies on a global 
    //  variable here with out any indication of where or how it is defined!! 
    //      TODO: Identify how this is used and replace it! 
    getArticleLink: function(artId) {
		if('art_url' in GEL.env.url.qsv)
			return unescape(GEL.env.url.qsv.art_url);
			
        var 
		_pi= GEL.thepage.pageinfo, 
		linkURL= 
				'sn' in _pi && 'pluck' in _pi.sn ?  
				GEL.thepage.pageinfo.sn.pluck.url : 
				document.location.toString().split('#')[0]
		;
        return linkURL;
    },
    getSLControlLink: function(el) { 
    	var parent= el.parentNode; 
	if (parent) { 
		if (parent.tagName == 'A')  return parent.href; 
		var a= parent.getElementsByTagName('A'); 
		for (var i=0;i<a.length;i++) 
			return a[i].href; 	
	}
	return null; 
    }, 
    // 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 gsl.getArticleTitle() != "undefined" && 
	 	article && 
		article.PageTitle && 
		article.Categories.length > 0 && 
		article.PageTitle != gsl.getArticleTitle()
	) { 
                return true;
	}else if ( typeof gsl.getArticleLink() != "undefined" && 
		article && 
		article.PageTitle && 
		article.Categories.length > 0 && 
		article.PageUrl != gsl.getArticleLink() 
	) { 
                return true;
        }else { 
        	return false;       
	}
    },
       
    /*************************************************************************/
    /* Comments - com ********************************************************/
    getCommentCountDOM: function(count,link){
    	count= gsl.niceNumber(count); 
    	var comLnkEl= document.createElement('span'), 
		l= null; 
	comLnkEl.className="gslCommentsLink"; 
	if ( link ) {
		l= document.createElement('a'); 
		l.href=link; 
		l.setAttribute('title', 'Go to comments'); 
		comLnkEl.appendChild(l); 
	}else
		l= comLnkEl; 
	var lbl= document.createElement('span'); 
	lbl.className='gslCommentsLabel'; 
	lbl.appendChild(document.createTextNode(gsl.commentLbl||"Comments")); 
	var cntLbl= document.createElement('span'); 
	cntLbl.className= 'gslCommentsCount';
	cntLbl.appendChild(document.createTextNode('(' + count + ')'));
	l.appendChild(lbl); 
	l.appendChild(cntLbl); 
	return comLnkEl;
    },
       getRecommendCountDOM:function(count,type,key,canRecommend){ 
		var recEl= document.createElement("span"), 
			_recElLinkSpan= document.createElement("span"),
			_iconEl= document.createElement("span"), 
			count= count; /*  || strCount;*/
		recEl.appendChild(_iconEl); 
		var elId= 'gslRecommend:'+type+':'+key; 
		if(typeof canRecommend =='undefined') 
			canRecommend= true; 
		recEl.setAttribute("id", elId);  
		var recMsg= "Recommend this article", 
			recLbl= document.createElement("span"); 
		recLbl.className= 'gslRecommendLabel'; 
		recLbl.appendChild(document.createTextNode(gsl.recommendLbl)); 
		var countEl= document.createElement("span");
		countEl.className="gslRecommendCount";
                if (count>0)
			countEl.appendChild(document.createTextNode('('+count+ ')')); 

                if(canRecommend){
			_iconEl.className= "recommendicon"; 
			var recLink= document.createElement("a"); 
			recLink.href= 'javascript: void("Recommend")'; 
			recLink.title= recMsg; // 'Recommend this article'; 
			recLink.alt= recMsg; //REcommend this article
			var _gel= GEL.ement(recLink); 
			_gel.on( 'click',
				(function(_t,_k,_c){ 
					return function(){ gsl.Recommend(_t,_k,_c) }
				})(type,key,count)
			); 
			recLink.appendChild(recLbl); 
			recLink.appendChild(countEl); 
			_gel.attachToElement= recEl; 
			_gel.attach(); 
		}else{
			_iconEl.className= "recommendedicon"; 
			recEl.appendChild(recLbl); 
			recEl.appendChild(countEl); 
		}
		return recEl; 
        },
                
    /*************************************************************************/
    /* Recommend - rec *******************************************************/ 
    
    getRecommendCountControl: function(type, key, recCount, recommended) {
	return this.getRecommendCountDOM(recCount, type, key, !recommended); 
    },
    Recommend: function(type, key, recCount) {        
        var 
		recKey= null, 
		_art= new GArticle(key), 
		recLink= $("gslRecommend:" + type + ":" + key)
	;
        if (type=='comments') {
            recKey= new CommentKey(key);
        } else if (type=='articles' || type =='article') {
            recKey= new ArticleKey(key);
        } else if (type=='photo' || type == 'saxophoto') {
            recKey= type == 'photo' ? 
	    	new PhotoKey(key): new ArticleKey(key);
	    if(typeof gpg == 'undefined') return;  
  	    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;
        }		
	if(_art.remoteneedsinfo) 
		this._updateArticle= true; 
        var rb= new RequestBatch();	 
        rb.AddToRequest(new RecommendAction(recKey)); 
        this.sitelifeRequest(rb, "SubmitRecommend", this._recommendCallback);
	if(!recLink) return; 

        var num= parseInt(recCount,10);
        num += 1;
        var _gel= GEL.ement(recLink.parentNode),
		_control= this.getRecommendCountControl(type,key,num,true)
	;
	_gel.clearElement(); 
	_gel.appendChild(_control); 
    },
    
    _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);
        }   
    },
    
    setSortOrder:function(val){
		gsl.params.s= val; 
		this.getReactions('comment', true);
    }, 
              
    /*************************************************************************/
    /* AJAX Transport Functions **********************************************/
   
    sitelifeRequest: function(slBatch, action, callback) {
        // Add UpdateArticleAction to batch, if update article flag is set then 
	slBatch= slBatch || new RequestBatch(); 
	callback= callback || new Function(); 
        if (this._updateArticle==true) {
	    var articleKey= this.getArticleKey(),
            	articleLink= this.getArticleLink(),
            	title= this.getArticleTitle(),
            	section= this.getArticleSection(),
            	cats= this.getArticleCats()
	    ;
            slBatch.AddToRequest(
	    	new UpdateArticleAction(
			new ArticleKey(articleKey), 
			articleLink, 
			title, 
			section,
			cats
		)
	);
    	GEL.log("Updating Article:"+articleKey+
		"\ntitle:"+title+
		"\nURL:"+articleLink+
		"\nsection:"+section+
		"\ncats:"+cats
	);
		var gArt= new GArticle(articleKey); 
		this._updateArticle= false; 
		gArt.remoteneedsinfo= false; 
        }
	  
        var callbackWrap= function(response) {
            try {
                callback(response);
            } catch(e) {
		GEL.logEx(e); 
            }
        };     
        slBatch.BeginRequest(this.sitelifeApiUrl, callbackWrap); 
    },
    
    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) {
    	return GEL.log(debugtext);
	return;
        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) {
		GEL.logEx(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() {   
	    //var artCtls= document.getElementsByClassName("gslArticleControl");
	    return; 
	    var _els= GEL.thepage.$(".gslArticleControl"); 
	    if(_els.length > 0) 
	    	this.processDiscovery(_els);
    }, 
	getDiscoveryTabContent:function() {},
	_processDiscoveryForAll: function(artCtls) {},
    	_findDiscoveryMaxIndex: function(activity, section, categories) {}, 
	checkDaapiAvailable: function(){
		this.wilDaapiWork= gsl.checkpluckconnectivity();
	},
	getDiscovery: (function(){ 
		var _a= [];

		return function(id){
			_a.push(id);
			GEL.use("util.Selector",  function(){
				gsl.getDiscovery=  processForAll;
			});
		}
		function processForAll(id){
			for(var i=0;i<id.length;i++)
				GEL.log("looking at " + id[i]); 	
		}
	})(),
	checkpluckconnectivity:function() {
		 var form= generateForm (this.plkIframeId,gsl.initDaapiReq, ""); 
		 try {
			new iframe(form, {}, this.plkIframeId); 
		 	document.body.removeChild(document.body.lastChild);
		  	document.body.removeChild(document.body.lastChild);
		 }
		 catch (e) {
		 	document.body.removeChild(document.body.lastChild);
		  	document.body.removeChild(document.body.lastChild);
		 	return false;
		 }
		 return true; 
   	},
	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);
		    GEL.logEx(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(gsl.TimeZoneoffset) != "undefined" && 
		gsl.TimeZoneoffset !="" 
	)
		date= this.convertTimeZone(date);
	retDate= date;
	if(typeof niceDate != 'undefined') {
		try { retDate= niceDate(date); }
		catch(e){ retDate= date;}; 
	}
	return retDate; 
    },
	
    convertTimeZone:function(pkdate){
    	var 
		datetimeobjs =  pkdate.split(" ");
		dateobjs = datetimeobjs[0].split("/"),
		ampm = "",
		plucktime = new Date(),
		parseformat = gsl_dateFormat.i18n.monthNames[dateobjs[0]-1]+ 
			", " + dateobjs[1] + 
			" " + dateobjs[2] +
			" " + datetimeobjs[1] +
			" " + datetimeobjs[2],
		dtformat= ''
	;
	try{
		plucktime.setTime(Date.parse(parseformat));
		plucktime.setTime(plucktime.getTime() + gsl.TimeZoneoffset * 3600000 );
		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);
			
		}
	}
};
/*
	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);
};
})(); 
