/*if (user.VERIFIED == '' || user.VERIFIED == '0') { // if the user is unverified, setup alert
	var regAlertMessage = 'In order to participate in FOXSports.com community applications (Post comments, messages and create blogs) you will first need to verify your email (<a href="/register">edit<\/a>).<br\/> Would you like to verify now?'; 
	var verifyYesFunc = 'takeToVerify('+user.USER_ID+',"'+window.location.pathname + window.location.search+'");';
	var verifyNoFunc = 'No';		
	
}
*/
function pageRefresh(){
	window.location.replace( window.location );
}
setTimeout( "pageRefresh()", 600*1000 );



// ---------------------------------------------------------//
// TABLE SORTING FOR PREVIOUS YEAR RESUTLS //
// ---------------------------------------------------------//
/*function InitPage(){
	try{
		Spry.$$("#sc3").forEach(function(n)
		{
			dt = window[n.id] = new Spry.Widget.DynamicTable(n);
			dt.setColumnType(["Driver", "Laps_Complete", "Laps_Led", "Earnings"], "number");
			
		});
		
		Spry.$$("#sc3 th.sortable").setStyle("cursor: pointer; -Moz-user-select: none; -khtml-user-select: none;");
		Spry.$$("#sc3 tr:nth-child(2n+2)").addClassName("on");
		
	}catch(e){}
}

Spry.Utils.addLoadListener(InitPage);*/

// ---------------------------------------------------------//
// COMMENTS //
// ---------------------------------------------------------//
var xmlComments = "/widget/comments";
var dsCommentsMain = new Spry.Data.XMLDataSet('', 'root/topic', {useCache:false});
var dsCommentsPagination = new Spry.Data.XMLDataSet('', 'root/pagination', {useCache:false});
var dsComments = new Spry.Data.NestedXMLDataSet(dsCommentsMain, "posts/post", {useCache:false, filterDataFunc: modifyMe}); // Get the XML Data

dsComments.setColumnType('body','html'); // show the html in the comment

Spry.Utils.addLoadListener(function(){ // Attach a spry listener... when the data ready, do the following:
									
	Spry.$$(".commentNavigation").setAttribute("spry:detailregion", "dsCommentsPagination"); // setup the comment pagination region
	
	if (uid == "0" || uid == ""){ // check for user id
		Spry.$$(".add-comm").setAttribute("href", passportLoginURL); // pass in the passportLogin
		Spry.$$(".add-comm").setAttribute("title", "Log in to add a comment"); // add the correct title to the anchor
		Spry.$$(".add-comm").setAttribute("spry:content", "Log in to add a comment"); // add the correct content to the anchor
	}else{
		if (user.VERIFIED == '' || user.VERIFIED == '0') { // if the user is unverified, setup alert			
			Spry.$$(".add-comm").setAttribute("onclick", "pgVerifyEmail();"); // set the verify onclick
			
		} else { // if they are verified, allow to add comments
			Spry.$$(".add-comm").setAttribute("onclick", "addComments();");	// set the addcomments			
		}
		Spry.$$(".add-comm").setAttribute("title", "Add a Comment"); // set the new title
		Spry.$$(".add-comm").setAttribute("spry:content", "Add a Comment"); // set the new innerHTML
	}
	
	
	
	
	Spry.$$("#comment-counter").setAttribute("spry:if", "{dsCommentsPagination::pageCount}"); // make sure there are comments
	Spry.$$("#comment-counter").setAttribute("spry:content", "Page {dsCommentsPagination::currentPage} of {dsCommentsPagination::pageCount}"); // if so, show the page numbering 
	Spry.$$("#member-comment-next").setAttribute("spry:if", "{dsCommentsPagination::pageCount}"); // check for page comments
	Spry.$$("#member-comment-next").setAttribute("onclick", "pageComments(this, '{dsCommentsPagination::nextPage}')"); // if so, setup next page
	Spry.$$("#member-comment-prev").setAttribute("spry:if", "{dsCommentsPagination::pageCount}"); // check for page comments
	Spry.$$("#member-comment-prev").setAttribute("onclick", "pageComments(this, '{dsCommentsPagination::previousPage}')"); // if so, setup next page
	
	Spry.$$("#race-box-content").setAttribute("spry:region", "dsComments"); // setup the comments region
	
	Spry.$$("#commNotification").setAttribute("spry:if", '{dsComments::ds_UnfilteredRowCount} == 0');// show notification if no comments are available
	Spry.$$(".namedAncor").setAttribute("name", '{dsComments::postId}');// setup the anchor
	
	Spry.$$(".comment").setAttribute("spry:repeat", "dsComments"); // repeat the spry children
	Spry.$$(".comment").setAttribute("spry:if", "{dsComments::postId}"); // check for a post ID
	Spry.$$(".comment").setAttribute("spry:even", "on"); // if so, then setup the "odd/even" states
	
	Spry.$$(".copy").setAttribute("spry:content", '{dsComments::body}'); // attach the body of the comments
	Spry.$$(".comm-user").setAttribute("alt", '{dsComments::userName}'); // set the user name in the image alt
	Spry.$$(".comm-user-link").setAttribute("title", '{dsComments::userName}'); // set the title of the user link
	Spry.$$(".user-name").setAttribute("spry:content", '{dsComments::userName}'); // attatch the user name
	Spry.$$(".user-name").setAttribute("title", '{dsComments::userName}'); // set the title
	Spry.$$(".post-date").setAttribute("spry:content", '{dsComments::postDate}'); // attach the post date of the comment

	Spry.$$(".comm-user-link").setAttribute("href", 'http://community.foxsports.com/{dsComments::userName}');// setup the users profile link
	
	Spry.$$(".report-abuse").setAttribute("onclick", 'reportMe("{dsCommentsMain::topicID}", "{dsComments::postId}")'); // setup the report abuse link

	Spry.Data.initRegions(); // initialize the the regions
	pageComments('', 1); // kick off the comments
});


// Comments Thumbnail Replacement //
Spry.Data.Region.addObserver("race-box-content", { onPostUpdate: function(){ // set observer for when the thumbnail achors get loaded
	var rows = dsComments.getData(); // get the thumbnails

	for (var i = 0; i < rows.length; i++){ // loop through the thumbnails
		var row = rows[i]; // get the rows
		var rid= row.ds_RowID; // get the individual rowId
		var o = document.getElementById("fs-user_" + rid); // get the first thumbnail in the set

		if (o) // checks to see if the thumbnail image actually exists in the markup
			o.src = row.avatarURLSmall; // if so, then set the image source
		
	} 

}});


function modifyMe(ds, row, rowIndex){ // escape the url for titles with special characters
	//row['postDate'] = row['postDate'].replace(" ", "<br\/>");// run the escape
	return row; // return the escaped value
}



function addComments(){	// Add Comments Expander
	Spry.Effect.DoSlide('add-comments', {duration:300, from:"0px", to:"100%", toggle:true}); // do the spry slide out effect
	
}

function pageComments(me, showPage){ // Page through comments
	if (uid == "0" || uid == ""){ // check for user id (check to see if they are logged in)	
		dsCommentsMain.setURL(xmlComments+'?contentId='+commId+'&forumKey=nascarRaceTrax&page_no='+showPage); // set the url	
	} else {
		dsCommentsMain.setURL(xmlComments+'?contentId='+commId+'&forumKey=nascarRaceTrax&page_no='+showPage+'&ran='+Math.round((Math.random() * 10000) + 1)); // break cache
	}
	dsCommentsMain.loadData(); // load in the new comments  
	
	dsCommentsMain.addObserver({ onPostLoad: function() { // launch this when the data is confirmed loaded
	dsCommentsMain.removeObserver(this); // remove this observer

		var sigh = dsCommentsMain.getDocument(); // get the original DOM XML document
		dsCommentsPagination.setDataFromDoc(sigh); // load the data.
		
		}
	});	
}

function postComments(me){ // Post a comment
	
	var newComment = escape(document.forms['comm'].comment2add.value); // get the comments
	var userId = uid; // get the users ID
	
	var req = Spry.Utils.loadURL("POST", "/widget/addComments", true, runComments, {postData:"userId="+userId+"&forumKey=nascarRaceTrax&topicKey="+commId+"&comment="+newComment, headers: { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" } }); // send the comments (loadComments) is going to run when we get a response back
	

	
} 

function reportMe(tid, pid){ // Report a comment
	//var url = "http://community.foxsports.com/boards/report.aspx?topic_id=" + tid.toString() + "&post_id=" + pid.toString();	
	//var reportIt = window.open(url, 'popwin', "width=500, height = 400 ,menubar=no,status=no,location=no,toolbar=no,scrollbars=no");
	var url = "/widget/contentCheck/userInput?topic_id=" + tid.toString() + "&post_id=" + pid.toString();	
	var reportIt = window.open(url, 'popwin', "width=680, height=582 ,menubar=no,status=no,location=no,toolbar=no,scrollbars=no,resizable=no");
	
	reportIt.focus();
}

function runComments(req){	// Reload comments AFTER a new one has posted
	if(req){ // check if this is a response call
		var text = req.xhRequest.responseText; // get the response text
		if(text){ // if there is text
			document.comm.comment2add.value = '';	// clear the value of the comment field		
						
			Spry.Effect.DoSlide('add-comments', {duration:300, from:"0px", to:"100%", toggle:true, finish: function(){
																													
					var freshData = Spry.Utils.stringToXMLDoc(text); // turn the results into XML DOM
					dsCommentsMain.setDataFromDoc(freshData); // load the data.																								
																													
				}
			}); // to close up the comments		
			
		}
	}	
}

// ---------------------------------------------------------//
// SHOW ALL RACE TRAX FUNCTION //
// ---------------------------------------------------------//
var hideMe;
function showAllTrax(me, options){
	
	var options = options || {};
	var off = options.off || false;
	var popup = options.popup || null;
	hideMe = options.hide || hideMe;
	
	if(off == false){
		takeOver(true, {'zindex':'50', 'bgcolor':'#000', 'opacity':'70'});
		var traxHolder = document.getElementById("inside-the-trax");
		var traxStories = traxHolder.getElementsByTagName("DIV");
		var traxStoriesHolder = '';
		
		for(var i=0; i<traxStories.length; i++){
			traxStoriesHolder += traxStories[i].innerHTML;
		}
		
		if(popup){
			Spry.Effect.DoFade(popup, {duration:300, from:"0", to:"100", setup:function(){document.getElementById(popup).style.zIndex=999}});		
			document.getElementById("trax-blog").innerHTML = traxStoriesHolder;			
		}
		if(hideMe){
			document.getElementById(hideMe).style.display="none";	
		}
		
		takeOverOn=true;
	}else{
		Spry.Effect.DoFade(popup, {duration:300, from:"100", to:"0", finish:function(){
				document.getElementById(popup).style.zIndex=-1;				
				takeOver(false);
				takeOverOn=false;
				if(hideMe){
					document.getElementById(hideMe).style.display="block";	
				}
			}
		});
		
	}	
	
	
}

// ---------------------------------------------------------//
// TAB NAVIGATION FUNCTION //
// ---------------------------------------------------------//
function showTab(me, options){ // show tabs
	var options = options || {};
	var tab = options.tab || null; // capture the selected direction
	
	var tabHolder = me.parentNode.parentNode.childNodes; // Get the top UL
	var tabInfoHolder = me.parentNode.parentNode.parentNode.childNodes; // Get the top DIV
	var tabInfo = document.getElementById(tab); // get the correct content
		
	for(var i=0; i<tabInfoHolder.length; i++){ // cycle through the div's
		if(tabInfoHolder[i].className == "race-box-content"){ // find the current one
			tabInfoHolder[i].className = "race-box-content off";	// turn it off
			tabInfo.className = "race-box-content"; // turn the selected one on
		}
	}
	
	for(var i=0; i<tabHolder.length; i++){ // cycle through the li's
		if(tabHolder[i].className == "on"){ // if they li's class is "on"		
			tabHolder[i].className = " ";	 // turn it off			
			me.parentNode.className = "on" // turn the selected tab on		
			return;
		}
	}	
	
}

// ---------------------------------------------------------//
// INSIDE THE TRAX HEIGHT FIX //
// ---------------------------------------------------------//
function raceInfoExpand(){
	var tabsHolder = document.getElementById('race-nav'); // get a hold of the navigation tabs
	var tabs = tabsHolder.getElementsByTagName("li")
	var itt = document.getElementById('inside-the-trax'); // het a hold to the inside-the-trax div
	
	for(i=0; i<tabs.length; i++){ // loop through the tabs
		if(tabs[0].className == "on"){  // if the first one is "ON"
			itt.style.height = "238px"; // reset the inside-the-trax divs height
			return; // stop the script
		}
	}
	
}



// DATA GATHERING
function createRequestObject() {
	var req;
	if(window.XMLHttpRequest){
	  // Firefox, Safari, Opera...
	  req = new XMLHttpRequest();
	} else if(window.ActiveXObject) {
	  // Internet Explorer 5+
	  req = new ActiveXObject("Microsoft.XMLHTTP");
	} else {
	  // There is an error creating the object,
	  // just as an old browser is being used.
	  alert('Problem creating the XMLHttpRequest object');
	}
	return req;
}
var http = createRequestObject(); // Make the XMLHttpRequest object




function updateTheTrax(options){
	
try{	

	var options = options || {};
	var tab = options.tab || 'Practice';
	var raceId = options.raceId || '';
	var loc;
	var htmlLoc;
	
	switch(tab){
		case "Race Week":
			loc = "/name/public/insideTheTrax/info/"+raceId;
		break;
		case "Practice":
			loc = "/name/public/insideTheTrax/practice/"+raceId;
		break;
		case "Qualifying":
			loc = "/name/public/insideTheTrax/qualifying/"+raceId;
		break;
		case "Live":			
			var loc = "/name/public/insideTheTrax/live/"+raceId;
		break;
		case "Cautions":
			htmlLoc = "rbc-cautions";
			var loc = "/name/public/insideTheTrax/cautions/"+raceId; 		
		break;
		case "Off":	
			htmlLoc = "rbc-off";
			var loc = "/name/public/insideTheTrax/live/"+raceId; 
		break;
	}
	
	if(!htmlLoc){	
		htmlLoc = "rbc-live";
		http.open('get', loc);				
	}
	// Send off the response
	http.onreadystatechange = function handleResponse() {
	   if(http.readyState == 4 && http.status == 200){
		
		  var response = http.responseText;
		  if(response) {
			document.getElementById("inside-the-trax").className = "race-box";
			document.getElementById(htmlLoc).innerHTML = response;			
		  }
	   }
	};
	http.send(null);
	setTimeout("updateTheTrax({raceId: '"+raceId+"', tab: '"+tab+"'})", 60000);
	
}catch(e){/* ignore */}

}


 function setCookie(c_name,value,expiredays)

                {

                var exdate=new Date();

                exdate.setDate(exdate.getDate()+expiredays);

                document.cookie=c_name+ "=" +escape(value)+

                ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());

                }

                

                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 "";

                }

                

                

                var cookieName = "SESSION_COOKIE"

                var SESSION_ID=Math.floor(Math.random()*10000000)

                if( getCookie( cookieName ) == "" )

                {

                                setCookie( cookieName, SESSION_ID );

                }


