var commentTimeoutAmt = 1;
var cookieDomain = 'cbsnews.com';
var commentJustPosted = false;
var disabledMsg = "The Publish button will be enabled shortly.  We have temporarily disabled it so everyone has an opportunity to comment.";
var commentCount; // Total # of comments

function initCommentCheck(){
	var t = commentTimeLeft();
	var d = new Date();
	var n = d.getTime(d);
	var tr = t-n;
	if(tr>0){
		disableCommentButton();
		setTimeout("enableCommentButton()",tr);
	}
}

function commentTimeLeft(){
	var cookies = document.cookie.split(';');
	var c;
	var n = 'comments='
	for(var i=0; i<cookies.length; i++){
		c = cookies[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if(c.indexOf(n) == 0){
			return c.substring(n.length,c.length);
		}
	}
	return 0;
}

function enableCommentButton(){
	document.getElementById('cbs').disabled = false;
	document.getElementById('cbs').src = 'http://wwwimage.cbsnews.com/common/images/v2/button_publish.gif';
	document.getElementById('usability1').innerHTML =  '';
	document.cookie = 'comments=; expires=Thu, 01-Jan-1970 00:00:01 GMT; domain='+ cookieDomain + '; path=/';
}

function disableCommentButton(){
	document.getElementById('cbs').disabled = true;
	document.getElementById('cbs').src = 'http://wwwimage.cbsnews.com/images/2006/09/06/image1976172.gif';
	document.getElementById('usability1').innerHTML = disabledMsg;
}

function startCommentLimiter(){
	disableCommentButton();
	var d = new Date();
	d.setTime(d.getTime()+commentTimeoutTime());
	var exp = d.toGMTString();
	setTimeout("enableCommentButton()", commentTimeoutTime());
	document.cookie ='comments='+ d.getTime(exp) +'; expires=' + exp + '; domain='+ cookieDomain + '; path=/'
}

function commentTimeoutTime(){
	return commentTimeoutAmt*60*1000;
}

/**************************************************************/


function commentList(boardid, maxNumberofComments){
	this.comments = new Array();
	this.boardId = boardid;
	this.maxNumberofComments = maxNumberofComments;
}


function singlecomment(commentid, description, pubdate, userid){
	this.commentid= commentid;
	this.description = description;
	this.pubdate = pubdate;
	this.userid = userid;
}

function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
  var rv = -1; // Return value assumes failure
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}

var doc;
var aeOL = [];
function addEvent(o, n, f, l)
{
 var a = 'addEventListener', h = 'on'+n, b = '', s = '';
 if (o[a] && !l) return o[a](n, f, false);
 o._c |= 0;
 if (o[h])
 {
  b = '_f' + o._c++;
  o[b] = o[h];
 }
 s = '_f' + o._c++;
 o[s] = f;
 o[h] = function(e)
 {
  e = e || window.event;
  var r = true;
  if (b) r = o[b](e) != false && r;
  r = o[s](e) != false && r;
  return r;
 };
 aeOL[aeOL.length] = { o: o, h: h };
};

addEvent(window, 'unload', function() {
 for (var i = 0; i < aeOL.length; i++) with (aeOL[i])
 {
  o[h] = null;
  for (var c = 0; o['_f' + c]; c++) o['_f' + c] = null;
 }
});



function cancelEvent(e, c)
{
 e.returnValue = false;
 if (e.preventDefault) e.preventDefault();
 if (c)
 {
  e.cancelBubble = true;
  if (e.stopPropagation) e.stopPropagation();
 }
};


function HTMLHttpRequest(myName, callback) { with (this)
{
 this.myName = myName;
 this.callback = callback;

 // 'xmlhttp': Our preferred request object. 
 this.xmlhttp = null;
 
 this.iframe = null;
 window._ifr_buf_count |= 0;
 this.iframeID = 'iframebuffer' + window._ifr_buf_count++;
 this.loadingURI = '';
 
 


  // Attempt to init an XMLHttpRequest object where supported.
 if (window.XMLHttpRequest) 
 {
	  
	if(getInternetExplorerVersion()==-1){

  		xmlhttp = new XMLHttpRequest();
   	
  		if (xmlhttp.overrideMimeType) 
	   	{	   
		  xmlhttp.overrideMimeType('text/xml');
	   	}
	}else{
		
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");   
	}
 }else if(window.ActiveXObject){
     
	 //IE
	try {
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");            
         } catch (e) {
             try {
                 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
             } catch (e) {}
         }

  }
 
 
  if (!xmlhttp)
 {
	 if (document.createElement && document.documentElement &&
	   (window.opera || navigator.userAgent.indexOf('MSIE 5.0') == -1))
	  {
	   var ifr = document.createElement('iframe');
	   ifr.setAttribute('id', iframeID);
	   ifr.setAttribute('name', iframeID);
	   // Hide with visibility instead of display to fix Safari bug.
	   ifr.style.visibility = 'hidden';
	   ifr.style.position = 'absolute';
	   ifr.style.width = ifr.style.height = ifr.borderWidth = '0px';
	   iframe = document.getElementsByTagName('body')[0].appendChild(ifr);
	  }
	  else if (document.body && document.body.insertAdjacentHTML)
	  {
	   // IE5.0 doesn't like createElement'd frames (won't script them) and IE4 just plain
	   // doesn't support it. Luckily, this will fix them both:
	   document.body.insertAdjacentHTML('beforeEnd', '<iframe name="' + iframeID +
	    '" id="' + iframeID + '" style="display: none"></iframe>');
	  }
	
	  if (window.frames && window.frames[iframeID]) iframe = window.frames[iframeID];
	  iframe.name = iframeID;
 }
  return this;

}};

HTMLHttpRequest.prototype.parseForm = function(form) { with (this)
{
 // Parses a form DOM reference to an escaped string suitable for GET/POSTing.

 var str = '', gE = 'getElementsByTagName', inputs = [
  (form[gE] ? form[gE]('input') : form.all ? form.all.tags('input') : []),
  (form[gE] ? form[gE]('select') : form.all ? form.all.tags('select') : []),
  (form[gE] ? form[gE]('textarea') : form.all ? form.all.tags('textarea') : [])
 ];

 // Loop through each list of tags, constructing our string.
 for (var i = 0; i < inputs.length; i++)
  for (j = 0; j < inputs[i].length; j++)
   if (inputs[i][j])
   {
    var plus = '++'.substring(0,1); // CodeTrim fix.
    str += escape(inputs[i][j].getAttribute('name')).replace(plus, '%2B') +
     '=' + escape(inputs[i][j].value).replace(plus, '%2B') + '&';
   }

 // Strip trailing ampersand, because we can :)
 return str.substring(0, str.length - 1);
}};


HTMLHttpRequest.prototype.xmlhttpSend = function(uri, formStr) { with (this)
{
	
 // Use XMLHttpRequest to asynchronously open a URI, and optionally POST a provided
 // form string if any (otherwise, performs a GET).
 
 xmlhttp.open(formStr ? 'POST' : 'GET', uri, true);
 
 
 xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState == 4)
  {
	if (xmlhttp.status == 200) {
	  //alert(new XMLSerializer().serializeToString(xmlhttp.responseXML)); // FireFox Debugging
	  
	    //if (window.XMLHttpRequest)
	    if (window.XMLHttpRequest&& getInternetExplorerVersion () ==-1)
	 	{   
	
	      doc = xmlhttp.responseXML;
	  
	    //  alert(new XMLSerializer().serializeToString(xmlhttp.responseXML));
	   	}else{
		  	
		  doc = xmlhttp.responseText;
		  
		//  alert(doc);
		}  
				
		 var tmplist = null;
	     if (callback)  tmplist = callback(doc, loadingURI);  
	     loadingURI = '';
    }
  }
 };
 //if (formStr && xmlhttp.setRequestHeader&& window.XMLHttpRequest) 
  xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
 //xmlhttp.setRequestHeader('Accept','message/x-jl-formresult')

  xmlhttp.send(formStr);
 
 loadingURI = uri;
 return true;
}};



HTMLHttpRequest.prototype.iframeSend = function(uri, formRef) { with (this)
{
 if (!document.readyState) return false;

 if (formRef) {
	 formRef.setAttribute('target', iframeID);
	 //alert("HTMLHttpRequest.prototype.iframeSend formRef " + formRef);
 }
 else
 {
  var ifrDoc = iframe.contentDocument || iframe.document;

  if (!window.opera && ifrDoc.location &&
    ifrDoc.location.href != location.href) {
   	   ifrDoc.location=uri;
   	   
    }
  else 
    iframe.src = uri;
 }

 loadingURI = uri;
 
 setTimeout(myName + '.iframeCheck()', (window.opera ? 250 : 100));
 return true;
}};


HTMLHttpRequest.prototype.iframeCheck = function() { with (this)
{

 doc = iframe.contentDocument || iframe.document;
  var il = iframe.location;
  var dr = doc.readyState;

  
 if ((il && il.href && il.href.indexOf(loadingURI) >0) &&
     (dr == 'complete' || (!document.getElementById && dr == 'interactive')))
 {
	 
  if (callback) callback((doc.documentElement || doc), loadingURI);  
  loadingURI = '';
  
  //document.form.post.note.value ='';
 }
 else setTimeout(myName + '.iframeCheck()', 50);
 
 //document.post.reset();
 
}};




HTMLHttpRequest.prototype.load = function(uri) { with (this)
{
 // Call with a URI to load a plain text document.

 if (!uri || (!xmlhttp && !iframe)) return false;
 // Route the GET through an available transport layer.
 if (xmlhttp) return xmlhttpSend(uri, '');
 else if (iframe) return iframeSend(uri, null);
 else return false;
}};



HTMLHttpRequest.prototype.submit = function(formRef, evt) { with (this)
{
	
	
 evt = evt || window.event;
 if (!formRef || (!xmlhttp && !iframe)) return false;

 // Retrieve form information then decide what to do with it.
 var method = formRef.getAttribute('method'), uri = formRef.getAttribute('action');

 if (method && method.toLowerCase() == 'post')
 {
  // Send the URI and either a parsed form or a form reference to the transports.
  // Note we only cancel form for XMLHTTP, as IFRAMEs still need it to submit.
  //Shannon - BookMark
  if (xmlhttp) { cancelEvent(evt); return xmlhttpSend(uri, parseForm(formRef)) }
  else if (iframe) return iframeSend(uri, formRef);
  else return false;
 }
 else
 {
  // For GET requests, append ?querystring or &querystring to the GET uri and
  // forward it to the load() function. Always cancel form submit().
  return load(uri + (uri.indexOf('?') == -1 ? '?' : '&') + parseForm(formRef));
  cancelEvent(evt);
 }
}};



function RemoteFileLoader(myName)
{

 this.myName = myName;
 this.threads = [];
 this.loadingIDs = {};
 this.onload = null;
 
};


RemoteFileLoader.prototype.getThread = function(destId, isOpen ) { with (this)
{
 //alert("getThread-" + isOpen);
 var thr = -1;

 for (var id in loadingIDs)
 {
  // Same destination?
  if (id == destId)
  {
   thr = loadingIDs[id];
   break;
  }
 }
 if (thr == -1) for (var t = 0; t < threads.length; t++)
 {
  // Idle?
  if (!threads[t].loadingURI)
  {
   thr = t;
   break;
  }
 }
 if (thr == -1)
 {
  // Create a new HTMLHttpRequest with its own name as a reference to its array entry,
  // and no callback function as yet ;).
  thr = threads.length;
  threads[thr] = new HTMLHttpRequest(myName + '.threads[' + thr + ']', null);
  // Record this thread as loading for this destination, so it can be aborted later.
  loadingIDs[destId] = thr;
 }

 // Assign our callback function; it passed the destination to copyContent.
 threads[thr].callback = new Function('doc', 'uri', 'with (' + myName + ') { ' +
  'copyContent(doc, "' + destId + '","' + isOpen + '"); if (onload) onload(doc, uri, "' + destId + '") }');

 return threads[thr];
}};


RemoteFileLoader.prototype.loadInto = function(uri, destId)
{
 // Pass the file onto the load method of the selected thread.
 var t = this.getThread(destId, null); 
 t.load(uri); 
 
};


RemoteFileLoader.prototype.submitInto = function(formRef, destId, event)
{
	//reset page number
	pagenumberflag = 0;

	// Check post time left
	if(commentTimeLeft() > 0){
		alert(disabledMsg);
		var frm = document.getElementById('post');
		frm.setAttribute('action', '#'); // clear action
		window.location.reload(); // reload the page
		return false;
	} else {
		//set flag indicate post
		commentJustPosted = true;

		// Pass the file onto the submit method of the selected thread.
		return this.getThread(destId, null).submit(formRef, event);
	}

};

RemoteFileLoader.prototype.loadcounttotal = function(uri, destId, isOpen)
{
 // Pass the file onto the load method of the selected thread.
 
 var t = this.getThread(destId, isOpen); 
 t.load(uri);  
};

function checkstatus(checkdate){
	
	var s;
	var now = new Date();
	var entrydate = new Date(checkdate);
	//alert("entry date - " + entrydate.toGMTString());
	//alert("current date - " + now.toGMTString());
	if (entrydate.getTime() > now.getTime()-3*24*60*60*1000) {s = "open"}
	else{s = "closed"}
	return s
}


RemoteFileLoader.prototype.loadcounts = function(loadAreaId, storyidflag, checkdate){ 
	
	var futdate = new Date();
	var rand = futdate.getTime();	
	this.loadAreaId = loadAreaId;
	this.storyidflag = storyidflag;
	var isOpen = checkstatus(checkdate);

	this.loadcounttotal('http://www.cbsnews.com/msgboard/htmlc/content/readcache.php?cache_file='+ storyidflag + '&amp;ms='+rand, ''+loadAreaId+'', isOpen);
};



RemoteFileLoader.prototype.copyContent = function(domDoc, destId, isOpen)
{
	
	if (isOpen && (isOpen == 'open' || isOpen == 'closed')){			
		processRaw(domDoc, destId, isOpen);
	}else{
		
		// Start Timeout
		if(commentJustPosted){
			startCommentLimiter();
		} else {
			initCommentCheck();
		}	

		var t;
	     if (window.XMLHttpRequest&&getInternetExplorerVersion () ==-1)
	 	{   
		   t = processForOther(domDoc, destId);
	      
	  	}else{
		   t = processForIE(domDoc, destId);
		   
		}  
		if(t) {
				formatList(t, destId);
				if(document.post){
					document.post.reset();
				}		
		}
	}
	  
};





function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=")
  if (c_start!=-1)
    { 
    c_start=c_start + c_name.length+1 
    c_end=document.cookie.indexOf(";",c_start)
    if (c_end==-1) c_end=document.cookie.length
    return unescape(document.cookie.substring(c_start,c_end))
    } 
  }
return null
}


function removeElementforIE(){
 var d = document.getElementById('outter');
 var olddiv = document.getElementById('logindiv');

 d.removeChild(olddiv);

 var d1 = document.getElementById('outter1');
 var olddiv1 = document.getElementById('accdiv');

 d1.removeChild(olddiv1);
}

function removeChildrenFromNode(node)
{
   if(node == undefined &&
        node == null)
   {
	   
      return;
   }
   
   var len = node.childNodes.length;
   
	if (node.hasChildNodes())
	{
	  node.removeChild(node.firstChild);
	}
}

function appendChildrenToNode(node, newNode)
{
   if(node == undefined &&
        node == null)
   {
	   
      return;
   }
	  node.appendChild(newNode);
}





function processForIE(domDoc, destId){	
	var xmldoc = new ActiveXObject("Msxml2.DOMDocument.3.0");

	xmldoc.loadXML(domDoc);	
	
	var err =xmldoc.selectSingleNode("//err");

    if(err){	
	    alert("ERROR - " + err.firstChild.nodeValue); 	
		enableCommentButton();
		return null;
	}
	
	if (xmldoc.selectSingleNode("//boardID")==null) {return null;}

	
	var boardID = xmldoc.selectSingleNode("//boardID").text;

	//var maxNumberofComments = 0;
    //if(xmldoc.selectSingleNode("//moreComment")){
      //maxNumberofComments = xmldoc.selectSingleNode("//moreComment").text;
    //}
    var maxNumberofComments = 0;
    if(xmldoc.selectSingleNode("//count")){
      maxNumberofComments = xmldoc.selectSingleNode("//count").text;
	  commentCount = maxNumberofComments;
   	  if(document.getElementById('vWatch-commentCount')){
          document.getElementById('vWatch-commentCount').innerHTML = commentCount;
      }
   	  if(document.getElementById('commentsCount')){
          if(commentCount > 0){
              document.getElementById('commentsCount').innerHTML = '| <a href="#ccmm" class="blog_small"><img src="http://wwwimage.cbsnews.com/common/images/v3/icon_comment.gif" class="inlineIcon" alt="Comments" /><em>' + commentCount + '</em></a>';
          } else {
              document.getElementById('commentsCount').innerHTML = '';
          }
      }
    }
    
    var currentid = 0;    
    if(xmldoc.selectSingleNode("//loginid")){
      currentid = xmldoc.selectSingleNode("//loginid").text;
    }
    var currentpass = 0;    
    if(xmldoc.selectSingleNode("//encpass")){
      currentpass = xmldoc.selectSingleNode("//encpass").text;
    }
    

    //alert("seting up cookie");
   if(currentid != 0 && currentpass !=0){	   

   		var expires_date = new Date( today.getTime() + (60*60*24*30) );
   		document.cookie = "login="+ escape(currentid) + ";expires="+ expires_date.toGMTString()+ ";path=/;domain=cbsnews.com;";
   		//document.cookie = "userid="+ escape(currentid) + ";expires="+ expires_date.toGMTString()+ ";path=/;domain=cbsnews.com;";
   		document.cookie = "password="+ currentpass + ";expires="+ expires_date.toGMTString()+ ";path=/;domain=cbsnews.com;";
   		document.cookie = "dm_user=userid%3D"+ escape(currentid) + "%26password%3D"+ currentpass+";expires="+ expires_date.toGMTString()+ ";path=/;domain=cbsnews.com;";
   		 		
   		
   		removeElementforIE();
   		   		
   		appendChildrenToNode(document.getElementById("outter"), document.createTextNode('You are logged in as ' + escape(currentid) +'. Click '));
   		var link = document.createElement("a");
        link.setAttribute("href","/htdocs/registration/logout.php?success_page=" + document.location.href );
   		var text = document.createTextNode("here ");
        link.appendChild(text);
        appendChildrenToNode(document.getElementById("outter"), link);
        appendChildrenToNode(document.getElementById("outter"), document.createTextNode('to logoff. '));
        


  }
    
    var list1 = new commentList(boardID, maxNumberofComments);
	
	
	var descriptions = xmldoc.selectNodes("//board/comments/comment/description");
	var pubdates = xmldoc.selectNodes("//board/comments/comment/pubdate");
	var commentIDs = xmldoc.selectNodes("//board/comments/comment/commentID");
	var userIDs = xmldoc.selectNodes("//board/comments/comment/userid");

	for (i=0; i<descriptions.length; i++)
    {
      list1.comments[i] = new singlecomment(commentIDs.nextNode.text, descriptions.nextNode.text, pubdates.nextNode.text, userIDs.nextNode.text);
   	} 
   	
   

   return list1;

}







function processForOther(domDoc, destId){
	
	// Firefox3 throws an error if there's no comments, so fail nicely.
	if(!domDoc){
		return null;
	}

	var err =domDoc.getElementsByTagName("err")[0];
	
    if(err){	
	    alert("ERROR - " + err.firstChild.nodeValue); 	
		enableCommentButton();
		return null;
	}
   
   var boardID =0;
   if(domDoc.getElementsByTagName("boardID")  && domDoc.getElementsByTagName("boardID").length > 0){  		 
      boardID = domDoc.getElementsByTagName("boardID")[0].firstChild.nodeValue;
   }
   
   var maxNumberofComments = 0;
   if(domDoc.getElementsByTagName("count")[0]){
     maxNumberofComments = domDoc.getElementsByTagName("count")[0].firstChild.nodeValue;
     commentCount = maxNumberofComments;
	 if(document.getElementById('vWatch-commentCount')){
         document.getElementById('vWatch-commentCount').innerHTML = commentCount;
	 }
 	 if(document.getElementById('commentsCount')){
         if(commentCount > 0){
             document.getElementById('commentsCount').innerHTML = '| <a href="#ccmm" class="blog_small"><img src="http://wwwimage.cbsnews.com/common/images/v3/icon_comment.gif" class="inlineIcon" alt="Comments" /><em>' + commentCount + '</em></a>';
             
         } else {
      	     document.getElementById('commentsCount').innerHTML = '';
         }
      }
   } 
   
   //var maxNumberofComments = 0;
   //if(domDoc.getElementsByTagName("moreComment")[0]){
    // maxNumberofComments = domDoc.getElementsByTagName("moreComment")[0].firstChild.nodeValue;
   //} 

   var currentid = 0;
   if(domDoc.getElementsByTagName("loginid")[0]){
     currentid = domDoc.getElementsByTagName("loginid")[0].firstChild.nodeValue;
   }
   

   
   var currentpass = 0;
   if(domDoc.getElementsByTagName("encpass")[0]){
     currentpass = domDoc.getElementsByTagName("encpass")[0].firstChild.nodeValue;
   }
   

   if(currentid != 0 && currentpass !=0){

   		var expires_date = new Date( today.getTime() + (60*60*24*30) );
   		document.cookie = "login="+ escape(currentid) + ";expires="+ expires_date.toGMTString()+ ";path=/;domain=cbsnews.com;";
   		//document.cookie = "userid="+ escape(currentid) + ";expires="+ expires_date.toGMTString()+ ";path=/;domain=cbsnews.com;";
   		document.cookie = "password="+ currentpass + ";expires="+ expires_date.toGMTString()+ ";path=/;domain=cbsnews.com;";
   		document.cookie = "dm_user=userid%3D"+ escape(currentid) + "%26password%3D"+ currentpass+";expires="+ expires_date.toGMTString()+ ";path=/;domain=cbsnews.com;";
   		removeChildrenFromNode(document.getElementById("outter"));
   		removeChildrenFromNode(document.getElementById("outter1"));
   		appendChildrenToNode(document.getElementById("outter"), document.createTextNode('You are logged in as ' + escape(currentid) +'. Click '));
   		var link = document.createElement("a");
        link.setAttribute("href","/htdocs/registration/logout.php?success_page=" + document.location.href );
   		var text = document.createTextNode("here ");
        link.appendChild(text);
        appendChildrenToNode(document.getElementById("outter"), link);
        appendChildrenToNode(document.getElementById("outter"), document.createTextNode('to logoff. '));
        
  }
  
   var list1 = new commentList(boardID, maxNumberofComments);
   
   var commentList1 = domDoc.getElementsByTagName("comment");
   
   var commentNode;
   
   for(var i = 0; i< commentList1.length; i++){	   
     commentNode = domDoc.getElementsByTagName("comment")[i]; 
     list1.comments[i] = new singlecomment(commentNode.childNodes[0].firstChild.nodeValue, commentNode.childNodes[1].firstChild.nodeValue, commentNode.childNodes[2].firstChild.nodeValue,commentNode.childNodes[3].firstChild.nodeValue);
  }
  
  if(currentid != 0 && currentpass !=0){
   		var expires_date = new Date( today.getTime() + (60*60*24*30) );
   		document.cookie = "login="+ currentid + ";expires="+ expires_date.toGMTString()+ ";path=/;domain=cbsnews.com;";
   		document.cookie = "password="+ currentpass + ";expires="+ expires_date.toGMTString()+ ";path=/;domain=cbsnews.com;";
   		document.cookie = "dm_user=userid%3D"+ escape(currentid) + "%26password%3D"+ currentpass+";expires="+ expires_date.toGMTString()+ ";path=/;domain=cbsnews.com;";

  }
  
  return list1;

}


function formatList(commentList, destId){	
	//alert("i am new");

	var dest = document.getElementById ? document.getElementById(destId) :
  		(document.all ? document.all[destId] : null);
	var srcHTML = "";	
	
	// If logged in, and just posted, start timeout
	if(commentJustPosted && getCookieValue("login")){
		startCommentLimiter();
	} else {
		initCommentCheck();
	}	
	
	
	//for page number display
	

	var table_start = "<div class='navigation bodysmall'>"
	var table_end = "</div>"
		 
		
	
	var pagedisplay_top = table_start;
	var pagedisplay_btn = table_start;
	
	if (commentList.maxNumberofComments >9){	
	    if (pagenumberflag ==0 && (commentList.maxNumberofComments > (pagenumberflag+1)*10)){
			pagedisplay_top = pagedisplay_top +  "<div class='navButton'><A href = '#ccmm' onclick='morecomments()' class='blog_postlink'><img src='http://wwwimage.cbsnews.com/common/images/v2/button_next.gif' border='0' hspace='1' alt='Next Comment Page'></A></div>";
			pagedisplay_btn = pagedisplay_btn +  "<div class='navButton'><A href = '#ccmm' onclick='morecomments()' class='blog_postlink'><img src='http://wwwimage.cbsnews.com/common/images/v2/button_next.gif' border='0' hspace='1' alt='Next Comment Page'></A></div>";
		}else if(pagenumberflag >0 ){
			if(commentList.maxNumberofComments > (pagenumberflag+1)*10){
				pagedisplay_top = pagedisplay_top +  "<div class='navButton'><A href = '#ccmm' onclick='previouscomments()' class='blog_postlink'><img src='http://wwwimage.cbsnews.com/common/images/v2/button_previous.gif' border='0' hspace='1' alt='Previous Comment Page'></A> <A href = '#ccmm' onclick='morecomments()' class='blog_postlink'><img src='http://wwwimage.cbsnews.com/common/images/v2/button_next.gif' border='0' hspace='1' alt='Next Comment Page'></A></div> ";
				pagedisplay_btn = pagedisplay_btn +  "<div class='navButton'><A href = '#ccmm' onclick='previouscomments()' class='blog_postlink'><img src='http://wwwimage.cbsnews.com/common/images/v2/button_previous.gif' border='0' hspace='1' alt='Previous Comment Page'></A> <A href = '#ccmm' onclick='morecomments()' class='blog_postlink'><img src='http://wwwimage.cbsnews.com/common/images/v2/button_next.gif' border='0' hspace='1' alt='Next Comment Page'></A></div> ";
			}else {
				pagedisplay_top = pagedisplay_top +  "<div class='navButton'><A href = '#ccmm' onclick='previouscomments()' class='blog_postlink'><img src='http://wwwimage.cbsnews.com/common/images/v2/button_previous.gif' border='0' hspace='1' alt='Previous Comment Page'></A></div> ";
				pagedisplay_btn = pagedisplay_btn +  "<div class='navButton'><A href = '#ccmm' onclick='previouscomments()' class='blog_postlink'><img src='http://wwwimage.cbsnews.com/common/images/v2/button_previous.gif' border='0' hspace='1' alt='Previous Comment Page'></A></div> ";
			}  
		}  
	}
	
	var totalPageNumber= Math.round(commentList.maxNumberofComments/10 + 0.4);
	//if(totalPageNumber >2){
		pagedisplay_top = pagedisplay_top  + "<strong>" + "Page " + (pagenumberflag+1) + " of " + totalPageNumber + "</strong> |";
//	}else{
//		pagedisplay_top = pagedisplay_top  + "<b>" + "Page " + (pagenumberflag+1) + " of " + totalPageNumber + "</b> ";
//	}
	pagedisplay_btn = pagedisplay_top;
	
	
	
	
	//if(totalPageNumber >1){
	
		if(pagenumberflag == 0){
			pagedisplay_top = pagedisplay_top + "<A href = '#ccmm' onclick='loadByPagenumber(0)' class='linksmall'> <strong> First  </strong></A>|";		
			pagedisplay_btn = pagedisplay_btn + "<A href = '#ccmm' onclick='loadByPagenumber(0)' class='linksmall'> <strong> First  </strong></A>|";		
		}else{
			pagedisplay_top = pagedisplay_top + "<A href = '#ccmm' onclick='loadByPagenumber(0)' class='linksmall'> First  </A>|";		
			pagedisplay_btn = pagedisplay_btn + "<A href = '#ccmm' onclick='loadByPagenumber(0)' class='linksmall'> First  </A>|";		
		}

		if(totalPageNumber <5){
		    for(j = 0; j < totalPageNumber ; j++){
				if(pagenumberflag == j){
					pagedisplay_top = pagedisplay_top + "<A href = '#ccmm' onclick='loadByPagenumber("+ j + ")' class='linksmall'>  <strong style='color: #000;'>"+ (j+1) + " </strong></A>";
					pagedisplay_btn = pagedisplay_btn + "<A href = '#ccmm' onclick='loadByPagenumber("+ j + ")' class='linksmall'>  <strong style='color: #000;'>"+ (j+1) + " </strong></A>";
				}else{
					pagedisplay_top = pagedisplay_top + "<A href = '#ccmm' onclick='loadByPagenumber("+ j + ")' class='linksmall'>  "+ (j+1) + " </A>";
					pagedisplay_btn = pagedisplay_btn + "<A href = '#ccmm' onclick='loadByPagenumber("+ j + ")' class='linksmall'>  "+ (j+1) + " </A>";
				}
			}
		}else if (pagenumberflag <3){		
		  //need more from right side
		  	for(j = 0; j < 5 ; j++){
				if(pagenumberflag == j){
					pagedisplay_top = pagedisplay_top + "<A href = '#ccmm' onclick='loadByPagenumber("+ j + ")' class='linksmall'>  <strong style='color: #000;'>"+ (j+1) + " </strong></A>";
					pagedisplay_btn = pagedisplay_btn + "<A href = '#ccmm' onclick='loadByPagenumber("+ j + ")' class='linksmall'>  <strong style='color: #000;'>"+ (j+1) + " </strong></A>";
				}else{
					pagedisplay_top = pagedisplay_top + "<A href = '#ccmm' onclick='loadByPagenumber("+ j + ")' class='linksmall'>  "+ (j+1) + " </A>";
					pagedisplay_btn = pagedisplay_btn + "<A href = '#ccmm' onclick='loadByPagenumber("+ j + ")' class='linksmall'>  "+ (j+1) + " </A>";
				}
			}
		  
		}else if((totalPageNumber - pagenumberflag)<3){
		  //need more from left side
		    var needed = 4 -(totalPageNumber - pagenumberflag);
		  	for(j = (pagenumberflag-needed); j < (pagenumberflag + (totalPageNumber - pagenumberflag))  ; j++){
				if(pagenumberflag == j){
					pagedisplay_top = pagedisplay_top + "<A href = '#ccmm' onclick='loadByPagenumber("+ j + ")' class='linksmall'>  <strong style='color: #000;'>"+ (j+1) + " </strong></A>";
					pagedisplay_btn = pagedisplay_btn + "<A href = '#ccmm' onclick='loadByPagenumber("+ j + ")' class='linksmall'>  <strong style='color: #000;'>"+ (j+1) + " </strong></A>";
				}else{
					pagedisplay_top = pagedisplay_top + "<A href = '#ccmm' onclick='loadByPagenumber("+ j + ")' class='linksmall'>  "+ (j+1) + " </A>";
					pagedisplay_btn = pagedisplay_btn + "<A href = '#ccmm' onclick='loadByPagenumber("+ j + ")' class='linksmall'>  "+ (j+1) + " </A>";
				}
			}
		}else{
			for(j = (pagenumberflag-2); j < pagenumberflag + 3 ; j++){
				if(pagenumberflag == j){
					pagedisplay_top = pagedisplay_top + "<A href = '#ccmm' onclick='loadByPagenumber("+ j + ")' class='linksmall'>  <strong style='color: #000;'>"+ (j+1) + " </strong></A>";
					pagedisplay_btn = pagedisplay_btn + "<A href = '#ccmm' onclick='loadByPagenumber("+ j + ")' class='linksmall'>  <strong style='color: #000;'>"+ (j+1) + " </strong></A>";
				}else{
					pagedisplay_top = pagedisplay_top + "<A href = '#ccmm' onclick='loadByPagenumber("+ j + ")' class='linksmall'>  "+ (j+1) + " </A>";
					pagedisplay_btn = pagedisplay_btn + "<A href = '#ccmm' onclick='loadByPagenumber("+ j + ")' class='linksmall'>  "+ (j+1) + " </A>";
				}
			}
		} 

		if(pagenumberflag == (totalPageNumber-1)){
			pagedisplay_top = pagedisplay_top + "|<A href = '#ccmm' onclick='loadByPagenumber("+ (totalPageNumber-1) + ")' class='linksmall'> <strong> Last </strong></A>";	
			pagedisplay_btn = pagedisplay_btn + "|<A href = '#ccmm' onclick='loadByPagenumber("+ (totalPageNumber-1) + ")' class='linksmall'> <strong> Last </strong></A>";	
		}else{
			pagedisplay_top = pagedisplay_top + "|<A href = '#ccmm' onclick='loadByPagenumber("+ (totalPageNumber-1) + ")' class='linksmall'> Last </A>";
			pagedisplay_btn = pagedisplay_btn + "|<A href = '#ccmm' onclick='loadByPagenumber("+ (totalPageNumber-1) + ")' class='linksmall'> Last </A>";
		}
	//}
    	
	
	pagedisplay_top = pagedisplay_top + table_end;// + "</td><td align='right'>";
	pagedisplay_btn = pagedisplay_btn + table_end; //+ "</td><td align='right'>";
		
	/*if (commentList.maxNumberofComments >9){	
	    if (pagenumberflag ==0 && (commentList.maxNumberofComments > (pagenumberflag+1)*10)){
			pagedisplay_top = pagedisplay_top +  "<div style='float: right;'><A href = '#ccmm' onclick='morecomments()' class='blog_postlink'><img src='http://wwwimage.cbsnews.com/common/images/v2/button_next.gif' border='0' hspace='1' alt='Next Comment Page'></A></div>" + table_end;
			pagedisplay_btn = pagedisplay_btn +  "<div style='float: right;'><A href = '#ccmm' onclick='morecomments()' class='blog_postlink'><img src='http://wwwimage.cbsnews.com/common/images/v2/button_next.gif' border='0' hspace='1' alt='Next Comment Page'></A></div>" + table_end;
		}else if(pagenumberflag >0 ){
			if(commentList.maxNumberofComments > (pagenumberflag+1)*10){
				pagedisplay_top = pagedisplay_top +  "<div style='float: right;'><A href = '#ccmm' onclick='previouscomments()' class='blog_postlink'><img src='http://wwwimage.cbsnews.com/common/images/v2/button_previous.gif' border='0' hspace='1' alt='Previous Comment Page'></A> <A href = '#ccmm' onclick='morecomments()' class='blog_postlink'><img src='http://wwwimage.cbsnews.com/common/images/v2/button_next.gif' border='0' hspace='1' alt='Next Comment Page'></A></div> " + table_end;
				pagedisplay_btn = pagedisplay_btn +  "<div style='float: right;'><A href = '#ccmm' onclick='previouscomments()' class='blog_postlink'><img src='http://wwwimage.cbsnews.com/common/images/v2/button_previous.gif' border='0' hspace='1' alt='Previous Comment Page'></A> <A href = '#ccmm' onclick='morecomments()' class='blog_postlink'><img src='http://wwwimage.cbsnews.com/common/images/v2/button_next.gif' border='0' hspace='1' alt='Next Comment Page'></A></div> " + table_end;
			}else {
				pagedisplay_top = pagedisplay_top +  "<div style='float: right;'><A href = '#ccmm' onclick='previouscomments()' class='blog_postlink'><img src='http://wwwimage.cbsnews.com/common/images/v2/button_previous.gif' border='0' hspace='1' alt='Previous Comment Page'></A></div> " + table_end;
				pagedisplay_btn = pagedisplay_btn +  "<div style='float: right;'><A href = '#ccmm' onclick='previouscomments()' class='blog_postlink'><img src='http://wwwimage.cbsnews.com/common/images/v2/button_previous.gif' border='0' hspace='1' alt='Previous Comment Page'></A></div> " + table_end;
			}  
		}  
	}
	*/

	if(totalPageNumber >1){
		srcHTML = srcHTML + pagedisplay_top;
	}
	
	//end of page number display
	
	
	var dNode;
	var pNode;
	var iNode;
	var uNode;
	
	//added for caching top 10 pages and page seperation
	var startIndex = 0;
	var endIndex = commentList.comments.length;
	
	if(commentList.comments.length >10) {
//		alert("startIndex - " + startIndex + " endIndex - " + endIndex);
		startIndex= pagenumberflag*10; 		
		if (endIndex > (startIndex +10)) endIndex = startIndex + 10;
	}
	
	
//	alert("startIndex - " + startIndex + " endIndex - " + endIndex);
	for (i=startIndex; i<endIndex; i++)
    {
       dNode = commentList.comments[i].description;
       pNode = commentList.comments[i].pubdate;
       iNode = commentList.comments[i].commentid;
       uNode = commentList.comments[i].userid;
       if (dNode != null) 
       {	       
	      var tempwords = new Array();
	      tempwords = dNode.split(' ');
		  var formattedNode ='';
		  var maxlength =40;
				 
		  for (p=0; p<tempwords.length; p++){		
   		      while(tempwords[p] && tempwords[p].length>maxlength){
	   	           formattedNode = formattedNode + tempwords[p].substring(0,maxlength)+ '<br>';
	   	           tempwords[p] = tempwords[p].substring(maxlength);	   		           
   		    	}
   	       	  formattedNode = formattedNode + tempwords[p]+ ' ';  		        	
   		  }	
	   
   		 // alert(formattedNode);
       
	       srcHTML = srcHTML + "<div class='userComment'><div class='userCommentTxt'>" + formattedNode + "</div><br/><hr class='dotted'/><div class='userCommentAuthor' align='right' style='font-size: 11px;'><cite>Posted by <strong class='userCommentName largehead_black' style='font-size: 11px;'>" + uNode + "</strong> at " + pNode + "</cite></div>"
	   					 + "<div class='reportComment' align='right'><A href=\"javascript:window.open('http://www.cbsnews.com/msgboard/htmlc/content/report.php?boardId=" 
	       			     + commentList.boardId + "&commentId="+ iNode +"', 'report', 'width=500,height=420,status=no,toolbar=no,scrollbars=no');void(null);\" class=\"linksmall\">+ report abuse</A></div>"
	       			     + "</div>";
       }
    }
   	
	
	if(totalPageNumber >1){
    	srcHTML = srcHTML + pagedisplay_btn;
	}

    dest.innerHTML = srcHTML.replace(/\\n/g, "<br>");  
    
   
}




function processRaw(domDoc, destId, isOpen){
	
	var count = 0;
	 if (window.XMLHttpRequest&&getInternetExplorerVersion () ==-1){
		 
		if (domDoc.getElementsByTagName("count")[0]){
			count = domDoc.getElementsByTagName("count")[0].firstChild.nodeValue;
	    }	 	
	}else{
		var xmldoc = new ActiveXObject("Msxml2.DOMDocument.3.0");
		xmldoc.loadXML(domDoc);	
		
		if (xmldoc.selectSingleNode("//count")) {
			count = xmldoc.selectSingleNode("//count").text;
		}
		
	}
	
	var dest = document.getElementById ? document.getElementById(destId) :
  	(document.all ? document.all[destId] : null);

	if(isOpen == 'open' && count == 0){
		dest.innerHTML = 'Comment On This Post'; 
	}else{
		dest.innerHTML = 'Comments <img src="http://www.cbsnews.com/common/images/v3/icon_comment.gif" class="inlineIcon" alt="Comments" />' + count;
	}
	
}

				function isChecked(){
				    b = document.post.agree;
					if(!b){
						return true;
					}else{
						if(!b.checked){
					   		alert('You must accept the Rules of Engagement to post to this Web site');
					   		return false;
						}
					}
					return true;			
			    }
				
				function ismaxlength(obj){
				var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
				if (obj.getAttribute  && obj.value.length < mlength){
				alert("Comments are limited to 1500 characters.");obj.value=obj.value.substring(0,mlength);}
				}
				
				

				var login;
            	var password;
				
				
/*Gets displayed if comments are activated on page*/
function displayForm(entryDate,storyid, storyurl){
				var now = new Date();
				var entryDate = new Date(entryDate);

                    
	            var args = document.cookie.split('; ');
	            for (var i=0; i<args.length; i++) {
	                        var arg = args[i].split('=');
	                        if (arg[0] == "dm_user") {
	                                    args = unescape(arg[1]).split('&');
	                                    for (var j=0; j<args.length; j++) {
	                                                arg = args[j].split('=');
													
	                                                if (arg[0] == "userid") {
	                                                            login = arg[1];
	
	                                                }else if (arg[0] == "password") {
	                                                            password = arg[1];
	                                                }
	                                    }
	                                    break;
	                        }
	            }


            if(!getCookieValue('login')){
                        var edate = new Date( today.getTime() + (60*60*24*30) );
                        document.cookie = "login="+ escape(login) + ";expires="+ edate.toGMTString()+ ";path=/;domain=cbsnews.com;";
                        document.cookie = "password="+ password + ";expires="+ edate.toGMTString()+ ";path=/;domain=cbsnews.com;";
            }


				
				
					var post = "(No HTML; Comments are limited to 1500 characters.)";
					var logInTxt = 'Login Name&nbsp;<a href="http://www.cbsnews.com/htdocs/registration/forgot_login.php" class="linksmall" target="_new">Forgot Login Name?</a><BR/>';
					var pswrdTxt = 'Password&nbsp;<a href="http://www.cbsnews.com/htdocs/registration/forgot_password.php" class="linksmall" target="_new">Forgot Password?</a><BR/>';


		if (true == false) {	  //can still post
//		if (entryDate.getTime() > now.getTime()-3*24*60*60*1000) {	  //can still post
					document.write('<a name="Post"></a>');

					document.write('<div class="userCommentBox">');
						document.write('<div class="graybox userCommentBoxInner">');

							document.write('<span class="head_black" name="post">Post A Comment</span>');
							document.write('<form name="post" id="post" action="http://www.cbsnews.com/msgboard/htmlc/content/comments.php" method="post" onsubmit="if(!isChecked()){return false;} else {docClickLoader.submitInto(this, \'loadArea\', event);} ">');
							
							if (!login || !password) {
							document.write('<p class="bodysmall userCommentReg">You must be <a href="/htdocs/registration/register.php?success_page='+ storyurl +'" class="linksmall"><strong>registered</strong></a> to comment on CBSNews.com.</p>');

							document.write('<div id="outter"><div id="logindiv">');
							document.write('<div class="userCommentLogin body">');
								document.write('<strong><label for="login">Log-in Name:&nbsp;</label></strong>');
								document.write(logInTxt);
								document.write('<br/>');
								document.write('<span><input type="text" id="login" name="login" size="31" maxlength="40" /></span>');
							document.write('</div>');

							document.write('<div class="body userCommentPass">');
								document.write('<strong><label for="password">Password:&nbsp;</label></strong>');
								document.write(pswrdTxt);
								document.write('<br/>');
								document.write('<span><input id="password" type="password" name="password" size="31" maxlength="20" /></span>');
							document.write('</div>');
							document.write('</div></div>');
							}                //end of if not logged in
							else {
								document.write('<input type="hidden" name="login" size="25" value="' + login + '"/>');
								document.write('<input type="hidden" name="enc_password" size="25" value="' + password + '"/>');
								document.write('You are logged in as <i>' + login + '</i>. Click <a href="http://www.cbsnews.com/htdocs/registration/register.php?action=logout&amp;login_page=' + document.location.href + '" class="linksmall">here</a> to logoff.<br/><br/>');
							}
							
							document.write('<br/>');
							document.write('<span class="body"><strong><label for="note">Your Comment:</label> </strong></span>(No HTML; Comments are limited to 1500 characters.)<br />');
							document.write('<textarea name="note" id="note" rows="6" cols="55" maxlength="1500"></textarea>');
							document.write('<input type="hidden" name="mp_id" value="0" />');
							document.write('<input type="hidden" name="board_id" value="' + storyid +'"/>');
							document.write('<input type="hidden" name="page_number" value="0" />');
							
							if (!login || !password) {
							document.write('<div id="outter1"><div id="accdiv"><p style="margin-bottom: 0px;">Your acceptance of the <a href="http://www.cbsnews.com/stories/2005/10/20/utility/main959709.shtml" class="linksmall" target="_new"><strong>Rules of Engagement</strong></a> is required for you to post comments.</p>');
							document.write('<p style="margin-top: 4px;"><input type="checkbox" name="agree"/> <label for="agree">Accept</label></p></div></div>');
							}
							document.write('<input name="submit" id="cbs" type="image" src="http://wwwimage.cbsnews.com/common/images/v2/button_publish.gif"/>');
							document.write('<div id="usability1"></div>');
							document.write('</form>');
						document.write('</div>');
					document.write('</div>');
		}
		else{
			if(typeof cbsVar_tmpl != 'undefined' && cbsVar_tmpl == 'watch_video'){
				/*document.write('<FONT COLOR="#990000"><b>Comments Are Closed For This Video</b></font>');*/         //comments closed
				/*document.write('<BR/><BR/>Commenting closes 72 hours after this video was published. ');*/
				document.write('<FONT COLOR="#990000"><b>Commenting is currently down for maintenance.</b></font> ');
				document.write('<BR/>Please check back later.');
				/*document.write('If you would like to make a comment, you may: ');
				document.write('<a href="/sections/home/main100.shtml" class="link">comment on today\'s videos</a> or <a href="http://www.cbsnews.com/htdocs/feedback/fb_news_form.shtml" onclick="new cbsPopup(\'feedback\').open(this.href); return false;" class="link">contact CBSNews.com</a>');*/
				document.write('<BR/><BR/>');
			} else {
				/*document.write('<FONT COLOR="#990000"><b>Comments Are Closed For This Story</b></font>'); */        //comments closed
				document.write('<FONT COLOR="#990000"><b>Commenting is currently down for maintenance.</b></font> ');//<BR/><BR/>Commenting closes 72 hours after this story was published.
				document.write('<BR/>Please check back later.');
				/*document.write('If you would like to make a comment, you may: ');
				document.write('<a href="/sections/home/main100.shtml" class="link">comment on today\'s stories</a> or <a href="http://www.cbsnews.com/htdocs/feedback/fb_news_form.shtml" onclick="new cbsPopup(\'feedback\').open(this.href); return false;" class="link">contact CBSNews.com</a>');*/
				document.write('<BR/><BR/>');
			}
		}			
		
		//document.write('<FONT COLOR="#990000"><b>Comments Are Temporarily Closed For This Story</b></font>'); 
}         //end of displayForm function
