// JScript File

/* Files required for this file to function correctly are as follows:

    #INCLUDE breakJson.js;
    #INCLUDE third_party_members.js
    
*/
/* Requires jQuery, jQuery Tools */


var msETSHandle =  null;
ETSService.prototype = new Ajax();

function ETSService() {
	this.method = "POST"; 
	this.headerName = "Content-Type";
	this.headerValue = "application/x-www-form-urlencoded; charset=UTF-8";
	this.content = ""; 
    this.url="";
	this.registry = new Array();
	msETSHandle = this;
}
ETSService.prototype.handleflagETS = function() {
       
	    if(msETSHandle.xmlHttp.readyState == 4) {
	    if(msETSHandle.xmlHttp.responseXML!=null)
		    msETSHandle.registry[0](msETSHandle.xmlHttp.responseXML, msETSHandle.xmlHttp.status == 200);
		
		msETSHandle.registry[0] = null;
	}
}


ETSService.prototype.flagETS = function(xml,callback) {
    this.registry[0] = callback;
    this.content = "sEtsEventXml=" + xml ;
    
//     var wl = document.URL
//	    var sUrl = "http://www.break.com";
//	    sUrl = (wl.indexOf('http')!=-1)?wl.substring(0,wl.indexOf('.com') + 4):sUrl;
	   // this.url=sUrl + "/CMSWebETSAPI.asmx/SubmitETSEventXML";
	   this.url="/WebAPI/InvokeCMS/CMSWebETSAPI/SubmitETSEventXML";
	    
	    
   // this.url="http://localhost/DNet.WebService.CMS/CMSWebETSAPI.asmx/SubmitETSEventXML";
   
    this.send(this.method, this.url, this.headerName, this.headerValue, null, null, this.content,this.handleflagETS);

   
}

 function ETSResponse(response, isOk){}
 function SendETSRequest(sXml){
       var oETSService = new ETSService();
       oETSService.flagETS(sXml,ETSResponse);
	}
	
// etsbase.js
//




function ETSBase(etsKey){
   this.etsKey = etsKey;
   this.controls = new Array();
}

ETSBase.prototype.addControl = function(controlId){
   this.controls.push(controlId);
}

ETSBase.prototype.execute = function(){
	
	var sXml = '<?xml version="1.0" encoding="utf-8" ?><Ets key="' +escape(this.etsKey)+ '">';
	var isValid = false;
	for(var i=0; i<this.controls.length; i++)
	{
		
		var sActCtrlValue = getctrlval(this.controls[i]);
		if(this.controls[i]=="ctl_search_tb_master")
			this.controls[i] = 'ctl_search_tb';
			
		if(sActCtrlValue != 'Videos and More' && sActCtrlValue.length > 0)
			isValid = true;
			
		sActCtrlValue = sActCtrlValue.replace(/</g,'');
		sActCtrlValue = sActCtrlValue.replace(/>/g,'');
		sActCtrlValue = sActCtrlValue.replace(/\"/g,'');
		sActCtrlValue = sActCtrlValue.replace(/\'/g,'');
	
		sXml += '<EtsControl key="' +escape(this.controls[i])+ '">' + encodeURI(sActCtrlValue) + '</EtsControl>';
		//  sXml += '<EtsControl key="' +escape(this.controls[i])+ '">test</EtsControl>';
	}
   
	sXml += '</Ets>';

	if(isValid){
		SendETSRequest(sXml);
	}
}
function replacestr(cstr)
{
//alert(cstr);

 var regex = /\</g;
    cstr = cstr.replace(regex, "");
    
     var regex1 = /\>/g;
    cstr = cstr.replace(regex1, "");
   

 
    return '';
}
function getctrlval(ctrls)
{
    if(ctrls=="ctl_search_tb")
    {
		return GenerateSearchString();
		/*
		if(document.getElementById("SearchTextbox1").type="text")
				return document.getElementById("SearchTextbox1").value;
		*/
    }
    if(ctrls=="ctl_search_tb_master")
    {
		return "";
		/*
		if(document.getElementById("SearchTextbox1").type="text")
				return document.getElementById("SearchTextbox1").value;
				*/
		
    }
    if(ctrls=="ctl_advanced_tb")
    {
		if(document.getElementById("txtSearchString").type="text")
		{		
			return document.getElementById("txtSearchString").value; 
		}	
    }
    if(ctrls=="Share")
    {
       return document.getElementById("hdnContentId").value;
    }
    
    return 'error';
}


// Conditional CDP JS Helpers
// Author: Gustavo Sandrigo
//Version: 0.5

/*
This requires breakJson.js
*/

jQuery(document).ready(checkUpdateRecommendationsTitle);

var pageNumber = 1;
var MAX_SIZE = 15;
var Featured_Max_Size = 6;

function conditional_RenderGoogleReferrerModules ()
{
	var targetDiv = "googleRefer";
	var divUmlWrap = "uml_wrap";
	var divUmlWrapFix = "uml_wrap_fix";
	var video_misc_published = "video_misc_published";
	if (referrer_IsSearchReferrer ())
	{
		//Figure out if NSFW Keywords
		var nsfwKeywords = new Array ("sex","xxx","hot girls", "kama sutra", "sex videos", "brianna frost", "kamasutra",
								"strip","young girls", "tila tequilla", "sex video", "tila tequila naked", "girls kissing",
								"2 girls 1 cup", "tila tequila nude", "tila tequila video", "kamasutra video", "playboy video",
								"playboy", "hot chicks", "karma sutra", "strip tease", "kama sutra video", "strip video", "vida guerra",
								"break.com spicy", "pictures", "girls gone wild video", "big boobs", "video sex", "large breasts",
								"lingerie");
		//alert ("test");
		var queryStringKey = "q";
		if (sendingURL.match("yahoo.com"))
		{
			queryStringKey = "p";
		}
		
		var queryVariable = getReferrerQueryString (queryStringKey) ;
		var searchTerm = ""
		if (queryVariable != null)
		{
			searchTerm = queryVariable.split("+").join(" ");
		}
		//alert (searchTerm);
		var foundNSFW = false;
		for (var i = 0 ; i < nsfwKeywords.length ; i++)
		{
			if (searchTerm.toLowerCase () == nsfwKeywords[i])
			{
					foundNSFW = true;
			}
		}
		//alert (foundNSFW);
		//We found a NSFW keyword.
		if (foundNSFW)
		{
			document.getElementById ("uml_nsfw").innerHTML = '<a class="fea_rgt_title" style="padding-right: 0pt;" href="javascript:memberMoviesEnter();">More NSFW Videos Here</a>';
			GetYouMightLikeNSFW();
			jQuery ("#"+targetDiv).addClass ("googleReferNoBackGround");
			document.getElementById (targetDiv).innerHTML = RenderReferrerGoogleNSFW (queryVariable, searchTerm);
			document.getElementById(targetDiv).style.display = "block";
			document.getElementById(divUmlWrap).style.display = "block";
			document.getElementById(divUmlWrapFix).style.display = "block";
			document.getElementById(divUmlWrapFix).style.display = "block";
			document.getElementById (video_misc_published).style.display="none";
			//document.getElementById(targetDiv).style.display = "block";
		}
		else 
		{

			GetYouMightLike ();
			jQuery ("#"+targetDiv).addClass ("googleReferNoBackGround");
			document.getElementById (targetDiv).innerHTML = RenderReferrerGoogle (queryVariable, searchTerm);
			document.getElementById(targetDiv).style.display = "block";
			document.getElementById(divUmlWrap).style.display = "block";
			document.getElementById(divUmlWrapFix).style.display = "block";
			document.getElementById(divUmlWrapFix).style.display = "block";
			document.getElementById (video_misc_published).style.display="none";
		}
	}
}


function RenderReferrerGoogle (query, queryCleaned)
{
	var html = "";
	html += 'After watching, to search for more ';         
	html += '<a href="http://my.break.com/Content/Search/Search.aspx?SEARCH1=Search&s='+query+'&SearchType=Main">'+queryCleaned; 
	html += '</a>, click <a href="http://my.break.com/Content/Search/Search.aspx?SEARCH1=Search&s='+query+'&SearchType=Main">here</a>.'; 
	return html;


}


function RenderReferrerGoogleNSFW (query, queryCleaned)
{
	var html = "";
	html += 'Looking for ';
	html += '<a href="http://my.break.com/Content/Search/Search.aspx?SEARCH1=Search&s='+query+'&SearchType=Main">'+queryCleaned;
	html += '</a>? Check out our <a href="javascript:memberMoviesEnter();">NSFW Videos</a> ';
	html += 'and <a href="javascript:memberPicturesEnter();">NSFW Galleries</a>.';

	return html;

}


function GetRecommendations(){
	GetMemberRecommendationsASHX(getCookieValue("MemberID"), pageNumber, MAX_SIZE, "renderRecommendations");
}
function GetMoreVideos(){
	GetMoreVideosFromUser(sGlobalContentID, pageNumber, MAX_SIZE, "renderMoreVideos");
}
function GetMoreVideosTVShows(){
	GetMoreVideosFromUserTVShows(sGlobalContentID, pageNumber, MAX_SIZE, "renderMoreVideosTVShows");
}
function GetFeatured(){
    GetPremiumVideos(Featured_Max_Size, "renderPremium");
}

function GetFeaturedCDPModule ()
{
	GetPremiumVideos(MAX_SIZE, "renderFeaturedCDPModule");

}

function GetRelated(){
	GetRelatedVideos(sGlobalContentID, "renderRelated");
}
function GetDugg(){
	GetMostDugg("renderMostDugg");
}
function GetYouMightLike(){
	GetYouMightLikeVideos(sGlobalContentID, "renderYouMightLike");
}
function GetYouMightLikeNSFW(){
	GetYouMightLikeNSFWVideos(sGlobalContentID, "renderYouMightLike");
}

function GetMemberRecommendationsASHX(memberId, page, pagesize, callbackFunc)
{   // if(memberId.length > 0)
    //{
		var recommendationJson = new BreakJSON();
		recommendationJson.sendBegin("http://websvc.break.com/cms/handlers/ratings/ratingsandrecommendationshandler.ashx?invoke=getrecommendations&memberid="+memberId+"&page="+page+"&pagesize="+pagesize+"&req=1", callbackFunc);
    //}
}
function GetMoreVideosFromUser(contentid, page, pagesize, callbackFunc){
	if(contentid.length > 0){
		var morevideosJson = new BreakJSON();
		morevideosJson.sendBegin("http://websvc.break.com/membership/handlers/profile/morefromthisuser/morefromthisuserhandler.ashx?invoke=getmorefromthisuser&cid=" + contentid, callbackFunc);
	}
}

function GetMoreVideosFromUserTVShows(contentid, page, pagesize, callbackFunc){
	
	if(contentid > 0){
		var morevideosJson = new BreakJSON();
		morevideosJson.sendBegin("http://websvc.break.com/membership/handlers/profile/morefromthisuser/morefromthisuserhandler.ashx?invoke=getmorefromthishuluuser&cid=" + contentid, callbackFunc);
	}
}

function GetPremiumVideos(pagesize, callback)
{ 
	var premVidJSON = new BreakJSON();
	premVidJSON.sendBegin("http://websvc.break.com/cms/Handlers/PremiumVideo/PremiumVideoHandler.ashx?invoke=getpremiumvideos&numResults=" + pagesize, callback);
}
function GetRelatedVideos(contentid, callback){
	var relatedVidJSON = new BreakJSON();
	relatedVidJSON.sendBegin("http://websvc.break.com/cms/Handlers/Content/ConditionalCDPHandler.ashx?invoke=getrelatedvideos&cid=" + contentid, callback);
}
function GetMostDugg(callback){
	var duggJSON = new BreakJSON();
	duggJSON.sendBegin("http://websvc.break.com/cms/Handlers/Digg/Digghandler.ashx?invoke=getmostdugg" , callback);
}
function GetYouMightLikeVideos(contentid, callback){
	var youmightlikeVidJSON = new BreakJSON();
	youmightlikeVidJSON.sendBegin("http://websvc.break.com/cms/Handlers/Content/ConditionalCDPHandler.ashx?invoke=getyoumightlike&numResults=2&cid=" + contentid , callback);
}
function GetYouMightLikeNSFWVideos(contentid, callback){
	var youmightlikeNSFWVidJSON = new BreakJSON();
	youmightlikeNSFWVidJSON.sendBegin("http://websvc.break.com/cms/Handlers/Content/ConditionalCDPHandler.ashx?invoke=getyoumightlikensfw&numResults=2&cid=" + contentid , callback);
}



function renderRecommendations(jsonData){
	var activediv = jQuery("#thumbstrip_rec");
	if ((jsonData.Response.Code == 0) && (jsonData.Response.Contents.MemberRecommendations) && (jsonData.Response.Contents.MemberRecommendations.Recommendation.length > 0))
	{
		fillThumbnailsRec(activediv, jsonData.Response.Contents.MemberRecommendations.Recommendation);
	}
	else
	{
		displayThumbError(activediv, 3);
	}
	tooltip.init(); // initialize qtip
	initThumbScroller(activediv)
}

function renderMoreVideos(jsonData){
	// this section is for the sidebar-morefromuser
	var activediv = jQuery("#sidebar-morefromuser");
	if ((jsonData.Response.Code == 0) && (jsonData.Response.MoreVideo))
	{
		fillSidebarMore(activediv, jsonData.Response.MoreVideo);
	}
	else
	{
		displayThumbError(activediv, 3);
	}
	tooltip.init();
	
    // this is for showcase cdp compatibility
	var activediv = jQuery("#thumbstrip_partner");
	if ((jsonData.Response.Code == 0) && (jsonData.Response.MoreVideo))
	{
		fillThumbnailsMore(activediv, jsonData.Response.MoreVideo);
	}
	else
	{
		displayThumbError(activediv, 3);
	}
	tooltip.init();
	initThumbScroller(activediv);

}

function renderMoreVideosTVShows(jsonData){
	var activediv = jQuery("#thumbstrip_ads");
	
	if ((jsonData.Response.Code == 0) && (jsonData.Response.MoreVideo))
	{
		fillThumbnailsMoreTvShows(activediv, jsonData.Response.MoreVideo);
	}
	else
	{
		displayThumbError(activediv, 3);
	}
	tooltip.init();
	initThumbScroller(activediv)
}

function renderPremium(jsonData){
	var activediv = jQuery("#side_featured");
	if((jsonData.premiumvideos) && (jsonData.premiumvideos.length))
	{
		fillThumbnailsPremium(activediv, jsonData.premiumvideos);
	}
	else
	{
		displayThumbError(activediv, 6);
	}
	tooltip.init();
}

function renderRelated(jsonData){
	var activediv = jQuery("#thumbstrip_related");
	if((jsonData.ContentRelatedVideos.Content) && (jsonData.ContentRelatedVideos.Content.length))
	{
		fillThumbnailsRelated(activediv, jsonData.ContentRelatedVideos.Content);
	}
	else
	{
		displayThumbError(activediv, 3);
	}
	tooltip.init();
}


function renderFeaturedCDPModule(jsonData){
	var activediv = jQuery("#thumbstrip_featured");
	if((jsonData.premiumvideos) && (jsonData.premiumvideos.length))
	{
		fillThumbnailsFeatured(activediv, jsonData.premiumvideos);
	}
	else
	{
		displayThumbError(activediv, 3);
	}
	tooltip.init();
	initThumbScroller(activediv)
}

function renderMostDugg(jsonData){
	var activediv = jQuery("#thumbstrip_dugg");
	if(jsonData.ContentList && jsonData.ContentList.Content){
		fillThumbnailsMostDugg(activediv, jsonData.ContentList.Content);
	}
	else {
		displayThumbError(activediv, 3);
	}
	tooltip.init();
	
	jQuery(function($){ // activate wrapper, remove css class when item is no longer top of sidebar
		$('#sidebar-module-digg').show();
		$('#sidebar-module-morevideoslikethis').removeClass('side-top-noad');
	});
	
}

function renderYouMightLike(jsonData){
	var activediv = jQuery("#thumbstrip_alsolike");
	if(jsonData.ContentYouMightLikeVideos && jsonData.ContentYouMightLikeVideos.Content){
		fillThumbnailsYouMightLike(activediv, jsonData.ContentYouMightLikeVideos.Content);
	}
	else {
		displayThumbError(activediv, 2);
	}
	tooltip.init();
}

function displayThumbError(div, length){
	var html = '';
	if (!((typeof(newCdp) == 'undefined')?false:newCdp))
	{
	//if (!newCdp) {
		for (i = 0; i < length; i++)
		{
			html += "<div class=\"rgt_fea_item\"><img src=\"http://media1.break.com/static/live/v1/img/site/img_na.gif\" border=\"0\" width=\"125\" alt=\"Video not available\"  class=\"module_thumb_fea\" /></div>";
		}
		div.html(html);
		div.parent().next().addClass('disabled');
		div.parent().siblings('.navi').css('visibility', 'hidden');
	}
	else {
		for (i = 0; i < 3; i++)
		{
			html += "<div class=\"related-videos-wrap\"><a href=\"\" class=\"break-link-img\"><img src=\"http://media1.break.com/static/live/v1/img/site/img_na.gif\" border=\"0\" width=\"75\" height=\"56\" alt=\"Video not available\" /></a></div>";
		}
		div.html(html);
	}
}


function fillThumbnailsFeatured(div, data){
	div.empty();
	if(data.length){
		var limit = MAX_SIZE;
		if(data.length < limit)
			limit = data.length;
		for(var i=0;i<limit;i++){
		    div.append(sidebarModuleRenderItem(tempFixThumbnailUrl(data[i].ThumbnailURL), data[i].ContentURL, data[i].ContentName, data[i].ContentDescription, data[i].ViewCount, data[i].CommentCount));
		}
	}
	else{
	    div.append(sidebarModuleRenderItem(tempFixThumbnailUrl(data.ThumbnailURL), data.ContentURL, data.ContentName, data.ContentDescription, data.ViewCount, data.CommentCount));
	}
}

function fillThumbnailsRec(div, data){
	div.empty();
	if(data.length){
		for(var i=0;i<data.length;i++){
		    div.append(thumbstripRenderItem(data[i].ThumbnailURL, data[i].ContentURL, data[i].ContentName, data[i].ContentDescription));
		}
	}
	else{
	    div.append(thumbstripRenderItem(data.ThumbnailURL, data.ContentURL, data.ContentName, data.ContentDescription));
	}
}
function fillSidebarMore(div, data){
	div.empty();
	// if the user has 10 or more videos
	if(data.length > 7){
	for(var i=0;i<data.length;i++){
		    div.append(sidebarModuleRenderItem(data[i].ThumbnailURL, data[i].StaticURL, data[i].ContentName, data[i].ContentDescription, data[i].viewcount, data[i].commentcount));
		}
		jQuery("#sidebar-module-morefromuser").show();
	}
	else{
			jQuery("#sidebar-module-morefromuser").hide();
	}
}
function fillThumbnailsMore(div, data){
	div.empty();
	if(data.length){
		for(var i=0;i<data.length;i++){
		    div.append(thumbstripRenderItem(data[i].ThumbnailURL, data[i].StaticURL, data[i].ContentName, data[i].ContentDescription));
		}
	}
	else{
		if (parseInt(data.ContentId) == parseInt(sGlobalContentID))
		{
			jQuery("#partnervids").hide();
		}
		else
		{
			div.append(thumbstripRenderItem(data.ThumbnailURL, data.StaticURL, data.ContentName, data.ContentDescription));
		}
	}
}


function fillThumbnailsMoreTvShows(div, data){
	div.empty();
	if(data.length){
		for(var i=0;i<data.length;i++){
		    div.append(thumbstripRenderItemTvShow(data[i].ThumbnailURL, data[i].StaticURL, data[i].ContentName, data[i].ContentDescription, data[i].Season, data[i].Episode));
		}
	}
	else{
		if (parseInt(data.ContentId) == parseInt(sGlobalContentID))
		{
			jQuery("#hulu").hide();
		}
		else
		{
			div.append(thumbstripRenderItemTvShow(data.ThumbnailURL, data.StaticURL, data.ContentName, data.ContentDescription, data.Season, data.Episode));
		}
	}
}

function fillThumbnailsPremium(div, data){
	div.empty();
	div.append("<div class=\"rgt_featured_title\">More Hot Videos</div>");
	if(data.length){
		for(var i=0;i<data.length;i++){
		    div.append(sideBarRenderItem(tempFixThumbnailUrl(data[i].ThumbnailURL), data[i].ContentURL, data[i].ContentName, data[i].ContentDescription));
		}
	}
	else{
	    div.append(sideBarRenderItem(tempFixThumbnailUrl(data.ThumbnailURL), data.ContentURL, data.ContentName, data.ContentDescription));
	}
}

function tempFixThumbnailUrl(url){
  var httpIndex = url.lastIndexOf("http");
  var cleanedUrl = url;
  if (httpIndex > 0){
	  /* Need to remove second instance of http */
	  cleanedUrl = url.substr(url.lastIndexOf("http"), url.length);
  }
  return cleanedUrl;
}

function fillThumbnailsRelated(div, data){
	div.empty();
	if(data.length){
		var limit = MAX_SIZE;
		if(data.length < limit)
			limit = data.length;
		for(var i=0;i<limit;i++){
		    div.append(thumbstripRenderItem(data[i].ThumbnailURL, data[i].ContentPageURL, data[i].ContentName, data[i].ContentDescription));
		}
	}
	else{
	    div.append(thumbstripRenderItem(data.ThumbnailURL, data.ContentPageURL, data.ContentName, data.ContentDescription));
	}
}

function fillThumbnailsYouMightLike(div, data){
	div.empty();
	if(data.length) {
		if (data.length >= 2){
			var limit = 2;
			for(var i=0;i<limit;i++){
				div.append(thumbstripRenderItem(data[i].ThumbNailURL, data[i].StaticURL, data[i].ContentName, data[i].ContentDescription));
		    }
		}
	}
	else{
	    div.append(thumbstripRenderItem(data.ThumbNailURL, data.StaticURL, data.ContentName, data.ContentDescription));
	}
}

function fillThumbnailsMostDugg(div, data){
	div.empty();
	if(data.length){
		var limit = MAX_SIZE;
		if(data.length < limit)
			limit = data.length;
		for(var i=0;i<limit;i++){
		    div.append(sidebarModuleRenderItem(data[i].ThumbnailURL, data[i].StaticURL, data[i].ContentName, data[i].ContentDescription));
		}
	}
	else{
	    div.append(sidebarModuleRenderItem(data.ThumbnailURL, data.StaticURL, data.ContentName, data.ContentDescription));
	}
}

function thumbStrip_html_entity_decode(str){
try
{
var tarea=document.createElement('textarea');
tarea.innerHTML = str; return tarea.value;
tarea.parentNode.removeChild(tarea);
}
catch(e)
{
//for IE add <div id="htmlconverter" style="display:none;"></div> to the page
document.getElementById("htmlconverter").innerHTML = '<textarea id="innerConverter">' + str + '</textarea>';
var content = document.getElementById("innerConverter").value;
document.getElementById("htmlconverter").innerHTML = "";
return content;
}
}

function sidebarModuleRenderItem(ThumbnailURL, ContentURL, ContentTitle, ContentDescription, ViewCount, CommentCount) {
	var re= /<\S[^><]*>/g
	var html = "";
	if (ContentTitle.length > 30)
		ContentTitle = ContentTitle.substring(0,30) + "...";
	if (ThumbnailURL =="")
		ThumbnailURL = "http://media1.break.com/static/live/v1/img/notavailable.gif";
		
	html += "<div class=\"related-videos-wrap\"><div class=\"related-videos-thumb\">";
	html += "<a class=\"break-link-img\" target=\"_top\" href=\"" + ContentURL + "\" title=\"" + thumbStrip_html_entity_decode(ContentDescription).replace(re, "").replace('"',"'").replace(/'&gt;/,"") + "\">";
	html += "<img src=\"" + ThumbnailURL + "\" border=\"0\" width=\"75\" height=\"56\" onError=\"thumberror(this);\"/></a>";
	html += "</a></div>";
	html += "<h2><a class=\"break-link\" target=\"_top\" href=\"" + ContentURL + "\">" + ContentTitle + "</a></h2>";
	html += "<div class=\"related-videos-views\">";
	html += "<span>Views: </span><span class=\"related-videos-viewscount\">" + ViewCount + "</span>";
	html += "</div>";
	html += "<div class=\"related-videos-comments\">";
	html += "<a class=\"break-link\" href=\"" + ContentURL + "?comments=1\" target=\"_top\">" + CommentCount+ "</a>";
	html +=	"<a href=\"" + ContentURL + "?comments=1\" target=\"_top\">";
	html += "<img border=\"0\" src=\"http://media1.break.com/static/live/v1/img/site/comments_icon_dk.gif\" /></a>";
	html += "</div>";
	html += "</div>";
	return html;
}

function thumbstripRenderItem(ThumbnailURL, ContentURL, ContentTitle, ContentDescription) {
	var re= /<\S[^><]*>/g
	var html = "";
	if (ThumbnailURL =="")
		ThumbnailURL = "http://media1.break.com/static/live/v1/img/notavailable.gif";
	html += "<div class=\"rgt_fea_item\">";
//shortcut ContentDescription.replace(re, "").replace('"',"'").replace(/'&gt;/,"")
	html += "<a href=\"" + ContentURL + "\" title=\"" + thumbStrip_html_entity_decode(ContentDescription).replace(re, "").replace('"',"'").replace(/'&gt;/,"") + "\">";
	html += "<img src=\"" + ThumbnailURL + "\" border=\"0\" width=\"125\" height=\"92\" class=\"module_thumb_fea\" onError=\"thumberror(this);\"/></a><br />";
	html += "<div style=\"padding-right:5px;\">";
	html += "<a href=\"" + ContentURL + "\" class=\"fea_rgt_title\">" + ContentTitle + "</a><br />";
	html += "</div></div>";
	return html;
}


function thumbstripRenderItemTvShow(ThumbnailURL, ContentURL, ContentTitle, ContentDescription, Season, Episode) {
	var re= /<\S[^><]*>/g
	var html = "";
	if (ContentTitle.length > 20)
		ContentTitle = ContentTitle.substring(0,20) + "...";
	if (ThumbnailURL =="")
		ThumbnailURL = "http://media1.break.com/static/live/v1/img/notavailable.gif";
	html += "<div class=\"rgt_fea_item\">";
	html += "<div style=\"padding-right:5px;\">";
		html += "<a href=\"" + ContentURL + "\" class=\"fea_rgt_title\">" + ContentTitle  + "</a><br />";
	html += "</div>";
	html += "<a href=\"" + ContentURL + "\" title=\"" + thumbStrip_html_entity_decode(ContentDescription).replace(re, "").replace('"',"'").replace(/'&gt;/,"") + "\">";
	html += "<img src=\"" + ThumbnailURL + "\" border=\"0\" width=\"125\" height=\"92\" class=\"module_thumb_fea\" onError=\"thumberror(this);\"/></a><br />";
	html += "<div style=\"padding-right:5px;\">";
	if (Season != null && Season > 0 && Episode != null && Episode > 0)
	{
	html += "<a href=\"" + ContentURL + "\" class=\"fea_rgt_title\"> Season " + Season + " : Episode " +Episode + "</a><br /></div>";
	}
	html += "</div>";
	return html;
}

function sideBarRenderItem(ThumbnailURL, ContentURL, ContentTitle, ContentDescription) {
    var re= /<\S[^><]*>/g
    var html = "";
    if (ThumbnailURL == "")
        ThumbnailURL = "http://media1.break.com/static/live/v1/img/notavailable.gif";

    html += "<div class=\"rgt_fea_item\">";
    html += "<a href=\"" + ContentURL + "\" title=\"" + thumbStrip_html_entity_decode(ContentDescription).replace(re, "").replace('"',"'").replace(/'&gt;/,"") + "\">";
    html += "<img src=\"" + ThumbnailURL + "\" width=\"125\" class=\"module_thumb_fea\" border=\"0\" />";
    html += "</a><br />";
	html += "<div style=\"padding-right:5px;\">";
    html += "<a href=\"" + ContentURL + "\" class=\"fea_rgt_title\">" + ContentTitle + "</a><br /></div></div>";

    return html;
}


function thumberror(image){
	image.src = "http://media1.break.com/static/live/v1/img/notavailable.gif";
}

function isUserLoggedIn(){
	if(GetCookie(loginstatus_ckMemberAuthentication) != "")
    {
        var DataVal = GetCookie("MemberData");
        if(DataVal == "")
        {
            return false;   
        }
        else
        {
            /* Check to make sure member is not from 3rd party and that if
              they are that they have not logged out from the 3rd party site */
            if (isRegMemberOrThirdPartyFullyLoggedIn()) {                
                return true;
            } else {            
                return false;
            }            
        }
    }
    else
    {
	    return false;
    }
}

function checkUpdateRecommendationsTitle(){
    if(isUserLoggedIn()){
		jQuery("#recvids_title_message").text("Recommended for " + GetNicknameFromCookie());
    }
}

function handlePostLink(link){
    if(!isUserLoggedIn()){
        return;
    }
    toggleBox('comment_bot',1);
	toggleBox('disable_comment_box',0);
    toggleBox('post_box', 1);
    return false;
}


function setCommentsCookie(val){
	var xp = new Date();
	set_cookie('showcommentsalltime', val, xp.getFullYear() + 2, xp.getMonth(), xp.getDate(), '/', 'break.com', false);
}

function changeCommentsCookie(checkBox){
	if(checkBox.checked){
		setCommentsCookie('1');
	}
	else{
		setCommentsCookie('0');
	}
}

function setFeaThumbsCookie(val){
	var xp = new Date();
	set_cookie('showfeathumbs', val, xp.getFullYear() + 2, xp.getMonth(), xp.getDate(), '/', 'break.com', false);
}

function changeFeaThumbsCookie(){
	var cookieState = getCookie('showfeathumbs');
	if(cookieState == 1){
		setFeaThumbsCookie('0');
	}
	else{
		setFeaThumbsCookie('1');
	}
}
//////
function setRecThumbsCookie(val){
	var xp = new Date();
	set_cookie('showrecthumbs', val, xp.getFullYear() + 2, xp.getMonth(), xp.getDate(), '/', 'break.com', false);
}

function changeRecThumbsCookie(){
	var cookieState = getCookie('showrecthumbs');
	if(cookieState == 1){
		setRecThumbsCookie('0');
	}
	else{
		setRecThumbsCookie('1');
	}
}

// Thumbnails animation
function adjustModuleCounter(module,diff) {
	switch(module) {
		case 'rec':
			counterRecommended += diff;
			break;
		case 'partner':
			counterPartner += diff;
			break;
		case 'related':
			counterRelated += diff;
			break;
		case 'ads':
			counterAds += diff;
			break;
		case 'dugg':
			counterDugg += diff;
			break;
		case 'featured':
			counterFeatured += diff;
			break;
		case 'channel':
			counterChannel += diff;
			break;
	}
}
		
function getCurrentCounter(module) {
	var result;
	switch(module) {
		case 'rec':
			result = counterRecommended;
			break;
		case 'partner':
			result = counterPartner;
			break;
		case 'related':
			result = counterRelated;
			break;
		case 'ads':
			result = counterAds;
			break;
		case 'dugg':
			result = counterDugg;
			break;
		case 'featured':
			result = counterFeatured;
			break;
		case 'channel':
			result = counterChannel;
			break;
	}
	return result;
}

function animateThumbs_gt(module,dir) {
	var scrollContainer = jQuery("#thumbstrip_" + module);
	var totalThumbs = scrollContainer.children().length;
	var currScrollPos = getCurrentCounter(module);
	var leftOffset = currScrollPos * 140;
		
	if(dir == '1') { // going up
		if(currScrollPos < totalThumbs - 5) {
			leftOffset = (leftOffset + 420);
			adjustModuleCounter(module,3);
		}
		else if(currScrollPos == totalThumbs - 5) {
			leftOffset = (leftOffset + 280);
			adjustModuleCounter(module,2);
		}
		else if(currScrollPos == totalThumbs - 4) {
			leftOffset = (leftOffset + 140);
			adjustModuleCounter(module,1);
		}
	}
	else { // going down
		if(currScrollPos > 2) {
			leftOffset = (leftOffset - 420);
			adjustModuleCounter(module,-3);
		}
		else if(currScrollPos == 2) {
			leftOffset = (leftOffset - 280);
			adjustModuleCounter(module,-2);
		}
		else if(currScrollPos == 1) {
			leftOffset = (leftOffset - 140);
			adjustModuleCounter(module,-1);
		}
		else {
			leftOffset = 0;
		}
	}
	leftOffset = leftOffset * -1;
	scrollContainer.animate({left: leftOffset}, 350);
}
	
function animateThumbs(module,dir) {
	var scrollContainer = jQuery("#thumbstrip_" + module);
	var totalThumbs = scrollContainer.children().length;
	var currScrollPos = getCurrentCounter(module);
	var leftOffset = currScrollPos * 170;
		
	if(dir == '1') { // going up
		if(currScrollPos < totalThumbs - 5) {
			leftOffset = (leftOffset + 510);
			adjustModuleCounter(module,3);
		}
		else if(currScrollPos == totalThumbs - 5) {
			leftOffset = (leftOffset + 340);
			adjustModuleCounter(module,2);
		}
		else if(currScrollPos == totalThumbs - 4) {
			leftOffset = (leftOffset + 170);
			adjustModuleCounter(module,1);
		}
	}
	else { // going down
		if(currScrollPos > 2) {
			leftOffset = (leftOffset - 510);
			adjustModuleCounter(module,-3);
		}
		else if(currScrollPos == 2) {
			leftOffset = (leftOffset - 340);
			adjustModuleCounter(module,-2);
		}
		else if(currScrollPos == 1) {
			leftOffset = (leftOffset - 170);
			adjustModuleCounter(module,-1);
		}
		else {
			leftOffset = 0;
		}
	}
	leftOffset = leftOffset * -1;
	scrollContainer.animate({left: leftOffset}, 350);
}

var sendingURL = document.referrer;
var googleRefTest = sendingURL.match(/google.com/);
var diggRefTest = sendingURL.match(/digg.com/);
var whichReferrer;

if (googleRefTest) {
	whichReferrer = 'google';
}
else if (diggRefTest) {
	whichReferrer = 'digg';
}
else {
	whichReferrer = 'none';
}

function referrer_IsSearchReferrer ( ) {
	var sendingURL = document.referrer;
	var googleRefTest = sendingURL.match("google.com") || sendingURL.match("bing.com") || sendingURL.match("yahoo.com");
	return googleRefTest ;
}

/*
 Functionality migrated from CDP template to reduce file size
*/

function ETSTrackSearchButtonEvent()
{
	var oETS = new ETSBase("B_SEARCH_EVNT");
	oETS.addControl("ctl_search_tb");
	oETS.execute();
}

function validateSearch()
{
	var searchTxt = document.getElementById('SearchTextbox1');
	var text = '';
	if(searchTxt == null)
	return false;
	text = searchTxt.value;
	text = text.replace(/^\s*|\s*$/g, "");
	return text.length != 0;
}

function ageInit()
{
   var index = -1;

   index = age.search(/uav=/gi);
   if(index != -1)
   {
	  age = age.substr(index+4, age.length);
	  index = age.search(/&/gi);
	  if(index != -1)
		 age = age.substr(0, index);
   }
}

function getCookieValue (cookieName)
{
  var exp = new RegExp (escape(cookieName) + "=([^;]+)");
  if (exp.test (document.cookie + ";"))
  {
	  exp.exec (document.cookie + ";");
	  return unescape(RegExp.$1);
  }
  else return false;
}

function openWidget(content_id)
{
	window.open("http://break.transpera.com/users/new?content_id=" + content_id,"","width=320,height=250,left=500,top=350")
}

function getQueryString(variable) 
{
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
	var pair = vars[i].split("=");
	if (pair[0] == variable) {
	  return pair[1];
	}
  }
  return "";
}

function getReferrerQueryString(variable) 
{
  var query = document.referrer;
  var queryStringParam = query.split ("?");
  var vars = "";
  //queryStringParam[1] contains everything after "?"
  if (queryStringParam[1] != null )
	 vars = queryStringParam[1].split("&");

  for (var i=0;i<vars.length;i++) {
	var pair = vars[i].split("=");
	if (pair[0] == variable) {
	  return pair[1];
	}
  }
  return "";
}


/*
Placehodler function for new comments checkbox functionality
*/
function showHideComments ()
{
  obj = document.getElementById("alwaysShowComments");
  if(obj.checked == true)
  {
	alert('show comments, set cookie');
  }
  else
  {
	alert('hide comments, set cookie');
  }
}

//flash player show/hide divs
function hideFlashPlayerDiv() { 
if (document.getElementById) { // DOM3 = IE5, NS6 
document.getElementById('defaultDiv').style.visibility = 'hidden'; 
} 
else { 
if (document.layers) { // Netscape 4 
document.defaultDiv.visibility = 'hidden'; 
} 
else { // IE 4 
document.all.defaultDiv.style.visibility = 'hidden'; 
} 
} 
} 
 
function showFlashPlayerDiv() { 
if (document.getElementById) { // DOM3 = IE5, NS6 
document.getElementById('defaultDiv').style.visibility = 'visible'; 
} 
else { 
if (document.layers) { // Netscape 4 
document.defaultDiv.visibility = 'visible'; 
} 
else { // IE 4 
document.all.defaultDiv.style.visibility = 'visible'; 
} 
} 
} 

function hideHPVSDiv() { 
if (document.getElementById) { // DOM3 = IE5, NS6 
document.getElementById('videoplayer').style.visibility = 'hidden'; 
} 
else { 
if (document.layers) { // Netscape 4 
document.videoplayer.visibility = 'hidden'; 
} 
else { // IE 4 
document.all.videoplayer.style.visibility = 'hidden'; 
} 
} 
} 
 
function showHPVSDiv() { 
if (document.getElementById) { // DOM3 = IE5, NS6 
document.getElementById('videoplayer').style.visibility = 'visible'; 
} 
else { 
if (document.layers) { // Netscape 4 
document.videoplayer.visibility = 'visible'; 
} 
else { // IE 4 
document.all.videoplayer.style.visibility = 'visible'; 
} 
} 
}

function memberEnterGotm(){
if((memberCookie || memberRememberCookie) != null) 
{
window.location="http://www.break.com/gotm/gotm.html";
}
else{
window.location="http://info.break.com/static/live/v1/pages/ageverification_gotm.html";
}
}

function openWidget(content_id) {
window.open("http://break.transpera.com/users/new?content_id=" + content_id,"","width=335,height=250,left=500,top=350,scrollbars=1")
}
//////////////////////////////////////

var inappropriateJson = new BreakJSON();
var promoteJson = new BreakJSON();
var contentId = "";
var thePopUpDiv = "addtofavspop";

function markInappropriateResponse(jsonData){

   inappropriateJson.sendEnd();
  
   if(jsonData.Response.Code == 0)
      displayResponse(thePopUpDiv,"This video has been marked as inappropriate.");
   else
      displayResponse(thePopUpDiv,jsonData.Response.Message);
   
}

function markSpamResponse(jsonData){

   inappropriateJson.sendEnd();
  
   if(jsonData.Response.Code == 0)
   {
      displayResponse(thePopUpDiv,"This video has been marked as spam.");
   }
   else
      displayResponse(thePopUpDiv,jsonData.Response.Message);
   
}

function closeSpamMsg(){

    document.getElementById("SpamMsgSpan").innerHTML = "";
    document.getElementById("SpamMsgAnchor").innerHTML = "";
}

function promoteToHomePageResponse(jsonData){
   
   promoteJson.sendEnd();
	
   if(jsonData.Response.Code == 0)
      displayResponse(thePopUpDiv,"Thank you for voting.");
   else
      displayResponse(thePopUpDiv,jsonData.Response.Message);
   
}

function markSpam(memberId, contentId, feedbackType, feedbackValue){

   var isUnique = true;
   var cookieIds = getCookie("spamid");
   var ip = "";
   
   if(cookieIds != null && cookieIds.indexOf(contentId) != -1) 
      isUnique = false;
   
   if(isUnique){
      setCookie("spamid", contentId, 10);
      inappropriateJson.sendBegin("http://websvc.break.com/CMS/Handlers/ContentFeedback/ContentFeedbackHandler.ashx?invoke=markspam&memberId=" +memberId+ "&contentId=" +contentId+ "&feedbackType=" +feedbackType+ "&feedbackValue=" +feedbackValue+ "&siteId=1", "markSpamResponse");
   }
   else
   {
        displayResponse(thePopUpDiv,"This video has already been marked as spam.");
	    //document.getElementById("SpamMsgSpan").innerHTML = "This video has already been marked as spam.";
	    //document.getElementById("SpamMsgAnchor").innerHTML = "<img src=\"http://media1.break.com/static/live/v1/img/contentdetail/close_button.jpg\" border=\"0\" />";
   }
}

function markInappropriate(memberId, contentId, feedbackType, feedbackValue){

   var isUnique = true;
   var cookieIds = getCookie("ids");
   var ip = "";
   
   if(cookieIds != null && cookieIds.indexOf(contentId) != -1) 
      isUnique = false;
   
   if(isUnique){
      setCookie("ids", contentId, 10);
      ip=getCookie("USERIP");
      if(ip == null)
         ip = "";
      inappropriateJson.sendBegin("http://websvc.break.com/CMS/Handlers/ContentFeedback/ContentFeedbackHandler.ashx?invoke=markinappropriate&memberId=" +memberId+ "&contentId=" +contentId+ "&ip=" +ip+ "&feedbackType=" +feedbackType+ "&feedbackValue=" +feedbackValue+ "&siteId=1", "markInappropriateResponse");
   }
   else
	displayResponse(thePopUpDiv,"This video has already been marked as inappropriate.");
}

function promoteToHomePage(memberId, contentId, feedbackType, feedbackValue){

   var isUnique = true;
   var cookieIds = getCookie("promotids");
   var ip = "";
   
   if(cookieIds != null && cookieIds.indexOf(contentId) != -1) 
      isUnique = false;
   
   if(isUnique){
      setCookie("promotids", contentId, 10);
      ip=getCookie("USERIP");
      if(ip == null)
         ip = "";
      inappropriateJson.sendBegin("http://websvc.break.com/CMS/Handlers/ContentFeedback/ContentFeedbackHandler.ashx?invoke=promotehomepage&memberId=" +memberId+ "&contentId=" +contentId+ "&ip=" +ip+ "&feedbackType=" +feedbackType+ "&feedbackValue=" +feedbackValue+ "&siteId=1", "promoteToHomePageResponse");
   }
}

function displayResponse(divId, message){

   document.getElementById("addtofavspop").innerHTML = message;
   toggleBox(divId, 1);
}

/*
function readFeedbackCookie(name)
{
   var nameEQ = name + "=";
   var ca = document.cookie.split(';');
   for(var i=0;i < ca.length;i++){
      var c = ca[i];
      while (c.charAt(0)==' ') 
         c = c.substring(1,c.length);
      if (c.indexOf(nameEQ) == 0) 
         return c.substring(nameEQ.length,c.length);
   }
   return "";
}
*/

// the below script is supposed to have the following work flow :
//
// { detect for flash version 8 or greater}
//        if(Flash 8 >) 
//                then play in 8
//        else
//             {detect for WMP 9 or greater}
//              if(WMV 9 >)
//                  then play WMP display get flash link    
//              else
//                  display get flash link.
//

//seting up the member variables...
var versionFlash = 8;
var versionWMV = 9;
var agt = navigator.userAgent.toLowerCase();
var ie  = (agt.indexOf("msie") != -1);
var ns  = (navigator.appName.indexOf("Netscape") != -1);
var win = ((agt.indexOf("win")!=-1) || (agt.indexOf("32bit")!=-1));
var mac = (agt.indexOf("mac")!=-1);
var opera = (agt.indexOf("Opera")!= -1);

//the list that will contain a comma seperated 
var pluginlist ="";

//checkin to see what browser we are working with and building a list of string.  
if (ie)
{	
    //alert("ie");    
    if(detectIEFlash("ShockwaveFlash.ShockwaveFlash") )
    {
        pluginlist += "Flash";
    }
    
    /*
    if(detectIEWMV("WMPlayer.OCX"))
    {
        pluginlist += "WindowsMediaPlayer";
    }
    */
    
    //alert(pluginlist);
}
else if (ns) 
{   
   //alert("ns");
   if(detectNSFlash("Shockwave Flash"))
	{
	    pluginlist += "Flash";
	}
	
	/*
	if(detectNSWMV("Windows Media Player Plug-in Dynamic Link Library"))
	{
	    pluginlist += "WindowsMediaPlayer";
	}
	*/
	
	//alert(pluginlist);
}
else
{
    //alert("other");
    nse = ""; 
	for (var i=0;i<navigator.mimeTypes.length;i++) 
	{
	    nse += navigator.mimeTypes[i].type.toLowerCase();
	}   
	pluginlist = otherDetect("application/x-shockwave-flash","Flash"); /*+ otherDetect("application/x-mplayer2","WindowsMediaPlayer");*/
	
	pluginlist = pluginlist.substring(0,pluginlist.length-1);
	
	//alert(pluginlist); 
}

//helper function for I.E that detects false player.. returns true or false. checking for versions
function detectIEFlash(ClassID) 
{ 
    result = false; 
    var fullVersion;
   
    try 
    {
		// version will be set for 9.X or greater players
		var axo = new ActiveXObject(ClassID);
		fullVersion = axo.GetVariable("$version");
	} 
	catch (e) {}
    if(fullVersion)
    {
        version = fullVersion.substring(3,fullVersion.length-7);
        
        var tempArray = fullVersion.split(' ');
        
        if(tempArray.length>1)
        	version = tempArray[1];
        	
        tempArray = version.split(',');
        if(tempArray.length>0)
        	version = tempArray[0];
        	
        if(!isNaN(version))
        {
            if(version >= versionFlash)
            {   //alert(version +" " + versionFlash);
                result = true;
            }
        }
    }
	return result;   
}

//helper function for I.E that detects WMV player.. returns true or false. checks the version.
function detectIEWMV(ClassID) 
{ 
    v_mediaplayer = 0;
    result = false; 
    
    document.write('<SCR' + 'IPT LANGUAGE=VBScript\> \n'); //FS hide this from IE4.5 Mac by splitting the tag
	document.write('on error resume next \n');
	document.write('set myObject = CreateObject("' + ClassID + '")\n');
	document.write('result = ( IsObject(myObject))\n');
	document.write('v_mediaplayer = myObject.versionInfo\n');
	document.write('</SCR' + 'IPT\> \n');
	//alert(v_mediaplayer);
	if(v_mediaplayer >= 9);
	    result = true;
    
    return false;
}

//helper function for detection other for moz returns true or false depending on flash/version.
function detectNSFlash(ClassID) 
{ 
    result = false;
    var flashVersion = 0;
    var thePlugin = navigator.plugins[ClassID]; 
    if(thePlugin)
    {
        if(thePlugin.description)
        {
            flashVersion = parseInt( thePlugin.description.replace( /^[^\d]*/,'')); 
            //alert(flashVersion);
        }
    }
    if(flashVersion >= versionFlash)
    {
        result = true;
    }
    return result;
 }

//helper function for detection for wmp in mozilla no version check??
function detectNSWMV(ClassID)
{
    result = false;
    var wmpPlugin = navigator.plugins[ClassID]; 
    if(wmpPlugin)
    {
         if(wmpPlugin.description)
         {
            result = true;
         }
     }
     return false;
}


//used for other broswers no version check here just sees if the plugin is avalible.
function otherDetect(ClassID,name)
{
    n = ""; 
    if (nse.indexOf(ClassID) != -1)
    {
        if (navigator.mimeTypes[ClassID].enabledPlugin != null) 
        {
            n = name+","; 
        }
        return n;
    }
}


//function checks which plug in is installed and acts accordingly.
function cookieDetect()
{
	if(navigator.userAgent.toLowerCase().indexOf("iphone") != -1)
	{
			  var obj = document.getElementById('playerwrap');
			  obj.innerHTML = '<div> <br> <EMBED SRC=\"http://media1.break.com/dnet/media/'+sGlobalContentFilePath+'/'+sGlobalFileName+'.jpg\" HREF=\"http://media1.break.com/dnet/media/'+sGlobalContentFilePath+'/'+sGlobalFileName+'.mp4\" TYPE=\"video/mp4\" TARGET=\"myself\" SCALE=\"1\"><br/><br/></div>';
	}
	else
	{
	    if(pluginlist)//making sure the pluginlist var is valid
	    {
	        if((pluginlist.indexOf("Flash")!=-1))
	        {
		        flashOutPut();
		        hideVideoSettingDiv();   
		}
	        else
	        {
	            nothingActivate();
	        }
	    }
	    else
	    {
	        nothingActivate();
	    } 
	}
}

function nothingActivate()
{
  obj = document.getElementById('defaultDiv');
  obj.innerHTML = '<div style="float;left;width:464px;"><a href="http://www.adobe.com/products/flashplayer/" target="_blank" style="text-decoration:none;"><img src="http://media1.break.com/static/live/v1/img/getflash/flash_icon_lrg.gif" border="0"/><br/>Get Flash</a><br/><br/><br/><br/></div>';
  hideVideoSettingDiv();
}

function hideVideoSettingDiv()
{
	var vsettingsDiv = document.getElementById('videoSettingDiv');
	if(vsettingsDiv != null)
	{
		vsettingsDiv.style.display="none";
	}
}

/////get cookie set cookie functions...////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) {
		expires = expires * 10000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+"="+escape( value ) +
		( ( expires ) ? ";expires="+expires_date.toGMTString() : "" ) + //expires.toGMTString()
		( ( path ) ? ";path=" + path : "" ) +
		( ( domain ) ? ";domain=" + domain : ".break.com" ) +
		( ( secure ) ? ";secure" : "" );
}



/**
 * @author gsandrigo
 */
// Requires ajaxbas.js
var mcsHandle = null;
 
DynamicStatsServices.prototype = new Ajax();
 
 function DynamicStatsServices() {
	this.method = "POST";
	this.headerName = "Content-Type";
	this.headerValue = "application/x-www-form-urlencoded; charset=UTF-8";
	this.url="";
	this.content="";
	this.registry = new Array();
	mcsHandle = this;
 }
 
 DynamicStatsServices.prototype.handlePostGetDynamicStats = function() {
	if(mcsHandle.xmlHttp.readyState == 4) {
		//if (mcs.xmlHttp.status != 200)
		//	alert(mcs.xmlHttp.status );
		mcsHandle.registry[0](mcsHandle.xmlHttp.responseXML, mcsHandle.xmlHttp.status == 200);
		mcsHandle.registry[0] = null;
	}
};

//DynamicStatsServices.prototype.handlePostContentComment = function() {
//	if(mcsHandle.xmlHttp.readyState == 4) {
//		mcsHandle.registry[1](mcsHandle.xmlHttp.responseXML, mcsHandle.xmlHttp.status == 200);
//		mcsHandle.registry[1] = null;
//	}
//};

DynamicStatsServices.prototype.handlePostContentComment = function() {
    //alert("here");
    if (mcsHandle.xmlHttp.readyState == 4) {
        //alert("Good post");
        mcsHandle.registry[1](mcsHandle.xmlHttp.responseXML, mcsHandle.xmlHttp.status == 200);
        //mcsHandle.registry[1] = null;
    } else {
        //alert("Bad post");
        mcsHandle.registry[1]("Yo Man Yo", true);
    }
};


DynamicStatsServices.prototype.handleThirdPartyComment = function() {
    if (mcsHandle.xmlHttp.readyState == 4) {
        mcsHandle.registry[2](mcsHandle.xmlHttp.responseText, mcsHandle.xmlHttp.status == 200);
        mcsHandle.registry[2] = null;
    }
};

DynamicStatsServices.prototype.postGetDynamicStats = function(contentId, callback) {
	this.registry[0] = callback;
	this.url = "/WebAPI/InvokeCMS/CMSWebDynamicStatsAPI/GetDynamicStats";
	this.content = "rType=JSON";
	this.content += "&siteKey=break";
	this.content += "&contentId=" + contentId;
	this.send(this.method, this.url, this.headerName, this.headerValue, null, null, this.content, this.handlePostGetDynamicStats);
};

DynamicStatsServices.prototype.postContentComment = function(siteId, encryptedMemberId, encryptedContentId, commentId, title, comment, callback) {
	this.registry[1] = callback;
	this.url = "/WebAPI/InvokeCMS/CMSWebCommentsAPI/PostContentComment";
	this.content = "siteId=1&encryptedMemberId=" + encryptedMemberId + "&encryptedContentId=" + encryptedContentId + "&commentId=" + escape(commentId) + "&title=" + encodeURIComponent(title) + "&comment=" + encodeURIComponent(comment);
	this.send(this.method, this.url, this.headerName, this.headerValue, null, null, this.content, this.handlePostContentComment);
};


DynamicStatsServices.prototype.postCommentToThirdParty = function(postTitle, postCaption, thirdPartyName, comment, pageUrl, videoDesc, videoUrl, videoThumbNail, videoTitle, callback) {
    this.registry[2] = callback;
    this.url = "/WebAPI/InvokeCMS/CMSWebCommentsAPI/PostCommentToThirdParty";
    this.content = "postTitle=" + encodeURIComponent(postTitle) + "&postCaption=" + encodeURIComponent(postCaption) + "&thirdPartyName=" + thirdPartyName + "&comment=" + comment + "&pageUrl=" + pageUrl + "&videoDesc=" + encodeURIComponent(videoDesc) + "&videoUrl=" + videoUrl + "&videoThumbNail=" + videoThumbNail + "&videoTitle=" + encodeURIComponent(videoTitle);
    this.send(this.method, this.url, this.headerName, this.headerValue, null, null, this.content, this.handleThirdPartyComment);
};

/**
 * @author gsandrigo
 * v2.05
 */

var mcs = new DynamicStatsServices();
var postReply = true;
var postedPopUpMessage = "<span style=\"font-family:verdana;font-size:10px;color:#000;\">Your comment has been received.<br>It will be posted shortly.</span>";
var xpos = 0;
var ypos = 0;
var TimeoutID;

var lastsubject = "";
var lastcomment = "";
var lastcommentreplyid;

var openReplies = -1;

var fromId = document.cookie;
var spamJson = new BreakJSON();

function ShowLinkbackBox(){
	var linkbackBox = document.getElementById("linkback_box");

	if(linkbackBox.style.display == "none"){
		linkbackBox.style.display = "block";
	}
	else{
		linkbackBox.style.display = "none";
	}
}

function getDynamicStats(contentId) {
	BrowserDetect.init();
	mcs.postGetDynamicStats(contentId, postDynamicStatsCallback);
}

function postDynamicStatsCallback(XmlDoc, isOk){
	
	if(!isOk && !((typeof(newCdp) == 'undefined')?false:newCdp)) {
      //error display default
	  documentWriter("comment_bot", renderDefultComments());
	  return;
   }
   
	if(!((typeof(newCdp) == 'undefined')?false:newCdp)) {
		document.getElementById("comment_bot").innerHTML = "";
	}

   var error = "parsing JSON.";
   try {
   		if (BrowserDetect.browser == "Firefox") {
   			XmlDoc.normalize();
		}
   		var messageNode = XmlDoc.getElementsByTagName("Message");

		var jsonDoc;
        jsonDoc = messageNode[0].firstChild.nodeValue;

		var objResp = eval('(' + jsonDoc + ')');

		error = "processing renderPosted";
		if (undefined != objResp.DynamicStats.Stats){
        	documentWriter("posted_box", renderPosted(objResp.DynamicStats.Stats));
		}

        error = "processing renderViews";
		if (undefined != objResp.DynamicStats.Stats){
        	documentWriter("stats_views", renderViews(objResp.DynamicStats.Stats));
        }

        error = "processing renderCommentCount";
		if (undefined != objResp.DynamicStats.Stats){
			var commentsDiv = 'stats_comments_uml';
			if(isUGC == false && whichReferrer != 'google') {
				commentsDiv = 'stats_comments';
			}
        	documentWriter(commentsDiv, renderCommentCount(objResp.DynamicStats.Stats));
        }
        if(!((typeof(newCdp) == 'undefined')?false:newCdp)) {
		
			error = "processing renderLowerCommentCount";
			
			if (undefined != objResp.DynamicStats.Stats){
				documentWriter("comments_count", renderLowerCommentCount(objResp.DynamicStats.Stats));
			}

			error = "processing renderComments";
				
			if (undefined != objResp.DynamicStats.CommentsDetail){
				
				currentComments = objResp.DynamicStats.CommentsDetail.Comment;
				renderComments(currentComments);
			}
			else{
				documentWriter("comment_bot", renderDefultComments());
			}
		
			var showComments = getCookie('showcommentsalltime');
			if(showComments == 1){
				document.getElementById("chk_comments").checked = true;
				toggleBox('disable_comment_box',0);
				toggleBox('comment_bot',1);
			}
		
			var feaThumbsCookie = getCookie('showfeathumbs');
			if(feaThumbsCookie == 1){
				toggleBox('featured_hide',0);
				toggleBox('featured_bot',0);
				toggleBox('featured_show',1);
			}
			var recThumbsCookie = getCookie('showrecthumbs');
			if(recThumbsCookie == 1){
				toggleBox('recommended_hide',0);
				toggleBox('recommended_bot',0);
				toggleBox('recommended_show',1);
			}
		
		}

        error = "processing linkbacks";
		if (undefined != objResp.DynamicStats.Linkbacks){
			renderLinkbacks(objResp.DynamicStats.Linkbacks.Linkback);
		}
		else{
			renderDefaultLinkbacks();
		}
	}


   catch(e){
        //alert("error " + error + " - " + e);
   }
   return;
}

function renderDefultComments(){
	var html = "";
	html += "No Comments.";
	return html;
}

function renderViews(stats){
	var html = "";
	html += placeCommasInNumber(stats.Views);
	return html;
}

function renderCommentCount(stats){
	var html = "";
	html += stats.Comments;
	return html;
}


function renderLowerCommentCount(stats){
	if(parseInt(stats.Comments) == 0)
	   return "0 Comments";
	   
	if(parseInt(stats.Comments) < 11)
	   return "1 - " + parseInt(stats.Comments) + " of " + parseInt(stats.Comments) + " Comments";
	else
	   return "1 - 10 of " + parseInt(stats.Comments) + " Comments";
}

function renderPosted(stats){
	var html = "";
	html += stats.Posted;
	return html;
}

function renderDefaultLinkbacks(){
	document.getElementById('whoslinking-module-wrap').style.display = 'block';
	document.getElementById("whoslinking-nocontent").style.display = "block";
}

function renderLinkbacks(linkbacks){
	document.getElementById('whoslinking-module-wrap').style.display = 'block';
	var linkbackBox = document.getElementById("whoslinking-linkback-content");
	linkbackBox.style.display = "block";	

	var linkbackContent = document.getElementById("linkbacks-content-wrap");
	linkbackContent.innerHTML = "";

	var linkbackArr = new Array();

	if(typeof(linkbacks.length) == "undefined")
		linkbackArr[0] = linkbacks;
	else
		linkbackArr = linkbacks;

	if (linkbackArr.length > 0){
		for(i = 0; i < linkbackArr.length; i++){
			var text = linkbackArr[i].ReferrerURL;
			if(text.length > 55)
				text = text.substring(0, 55) + "...";

			linkbackContent.innerHTML += "<div><span>" + linkbackArr[i].Views + "</span> views via <a class=\"break-link\" href=\"" + linkbackArr[i].ReferrerURL + "\">" + text + "</a></div>";
		}
	}
}

function renderComments(comments){
	var isChild = false;
	var isReply = false;
	var parent_node;
	var pendingChildren = new Array();

	if (comments.length > 0){
		//var bottom_border = document.getElementById("comments_divider_bottom");
		//bottom_border.style.visibility = "visible";
		var element = document.getElementById("comment_bot");
		for(i = 0; i < comments.length; i++){
			isChild = (comments[i].ContentCommentID == comments[i].ParentContentCommentID) ? false : true;
			node = document.createElement("div");
			if(isChild){
				node.innerHTML = buildReplyComment(comments[i].ContentCommentID, comments[i].DateCreated, comments[i].ByNickName, comments[i].ByAvatarURL, comments[i].Title, comments[i].DiscussionText);
				parent_node = document.getElementById("comment" + comments[i].ParentContentCommentID);
				if(parent_node != null){
					document.getElementById("container" + comments[i].ParentContentCommentID).appendChild(node);
	               			//parentContainer = document.getElementById("container" + comments[i].ParentContentCommentID);
	               			//parentContainer.insertBefore(node, parentContainer.firstChild);
	               }
	            else{
					if(typeof(pendingChildren[comments[i].ParentContentCommentID]) == 'undefined')
	                  pendingChildren[comments[i].ParentContentCommentID] = new Array();

	               pendingChildren[comments[i].ParentContentCommentID].push(node);
	            }
	         }
	         else {
	            node.innerHTML = buildComment(comments[i].ContentCommentID, comments[i].DateCreated, comments[i].ByNickName, comments[i].ByAvatarURL, comments[i].Title, comments[i].DiscussionText);
	            if(isReply)
	               element.insertBefore(node, element.firstChild);
	            else
	               element.appendChild(node);
			}
		}

		var morecomments = document.createElement("div");
		morecomments.setAttribute("class", "module_comment_ctrl");
		morecomments.setAttribute("className", "module_comment_ctrl");
		morecomments.innerHTML = "<a href=\"http://my.break.com/Content/Comment/ContentComment.aspx?ContentID=" + sGlobalContentID + "\">View All</a>";
		element.appendChild(morecomments);
		
		for(var key in pendingChildren){
	         try{
	            if(document.getElementById("container"+key) != null){
	               for(i=0; i<pendingChildren[key].length; i++)
	                  document.getElementById("container"+key).appendChild(pendingChildren[key][i]);
	            }
	         }
	         catch(e){
	            //discard it, we can't do anything with it anyways
	            continue;
	         }
	    }
	}
	else if(comments.ContentCommentID){
		//var bottom_border = document.getElementById("comments_divider_bottom");
		//bottom_border.style.visibility = "visible";
		var element = document.getElementById("comment_bot");
		node = document.createElement("div");
		node.innerHTML = buildComment(comments.ContentCommentID, comments.DateCreated, comments.ByNickName, comments.ByAvatarURL, comments.Title, comments.DiscussionText);
		element.appendChild(node);
	}
}

function documentWriter(divId, html){
	var div = document.getElementById(divId);
	if (div)
	{
		div.innerHTML = html;
	}
}

function buildComment(commentId, date, by, avatar, title, text) {
   var html = "";
   title = unescape(title);
   text = unescape(text);

	html += "<div class=\"comment_entry\" id=\"comment" + commentId + "\">";
	html += "<div class=\"comment_avatar\"><a href=\"http://www.break.com/" +by+ "\"><img src=\"" + avatar + "\" border=\"0\" width=\"50\" height=\"50\" class=\"comment_avatar\" onerror=\"onMissingAvatar(this)\" /></a></div>";
	html += "<div class=\"comment_nonavatar\">";
	html += "<div class=\"comment_entry_top\">";
	html += "<div class=\"comment_entry_date\">";
	html +=  GetSpamLink(commentId)  + date;
	if (canPost) {
	    html += writeReplyLink(commentId);
		/* html += " <a id=\"reply" +commentId+ "\" href=\"javascript:toggleBox('newPopup_post_reply" +commentId+ "', 1);javascript:toggleBox('post_box', 0); closeOpenReplies(" + commentId + ");\">REPLY</a>"; */
	}
	html += "</div>";
	//html += "<a href=\"http://www.break.com/" +by+ "\"><img src=\"" + avatar + "\" border=\"0\" width=\"18\" height=\"17\" onerror=\"onMissingAvatar(this)\" /></a>&nbsp;";
	html += "<a href=\"http://www.break.com/" +by+ "\" class=\"comment_entry_link\">" + by +"</a> says:";
	html += "</div>";
	html += "<div class=\"comment_entry_bot\">";
	html += "<div class=\"comment_quote_lft\">";
	html += "<img src=\"http://media1.break.com/static/live/v1/img/site/quote_gray_lft.gif\" border=\"0\" />";
	html += "</div>";
	html += "<div class=\"comment_quote\">" + text + "</div>";
	html += "<div class=\"comment_quote_rgt\"><img src=\"http://media1.break.com/static/live/v1/img/site/quote_gray_rgt.gif\" border=\"0\" /></div>";
	html += "</div>";
	html += "</div>";
	html += "</div>";
	html += "<!-- COMMENT REPLY start -->";
	html += "<div id=\"newPopup_post_reply" + commentId + "\" class=\"post_box\">";
	html += "<div class=\"post_box_wrap\">";
	html += "<a href=\"javascript:toggleBox('newPopup_post_reply" + commentId + "',0);\" class=\"comment_entry_link_sml\">Close</a><br /><br />";
	html += "<input type=\"button\" value=\"Post\" onclick=\"javascript:submitReplyComment(" + commentId + ");\" /><br />";
	html += "</div>";
	html += "<textarea class=\"post_text\" id=\"post_text" + commentId + "\"></textarea><div id=\"commentReplyBodyError"+ commentId + "\"></div>";
	html += "</div>";
	html += "<!-- COMMENT REPLY end -->";
	html += "<div id=\"container" + commentId + "\" style=\"padding-top:0;margin-top:0;\">";
   
   return html;

}


function writeReplyLink(commentId) {
    var html = "";   
    html += " <a id=\"reply" + commentId + "\" href=\"javascript:toggleBox('newPopup_post_reply" + commentId + "', 1);javascript:toggleBox('post_box', 0); closeOpenReplies(" + commentId + ");\">REPLY</a>";
    return html;
}

function noCallBack(result) {
    /* Placeholder. We are going to save the comment to Break regardless. */
}


function buildReplyComment(commentId, date, by, avatar, title, text, thirdPartyUserId, thirdPartyName){
   
   var html = "";

   title = unescape(title);
   text = unescape(text);

	html += "<div class=\"comment_entry_sml\" id=\"comment" +commentId+ "\">";
	html += "<div class=\"comment_avatar\"><a href=\"#\"><img src=\"" + avatar + "\" border=\"0\" width=\"50\" height=\"50\" class=\"comment_avatar\" onerror=\"onMissingAvatar(this)\" /></a></div>";
	html += "<div class=\"comment_nonavatar2\">";
	html += "<div class=\"comment_entry_top_sml\">";
	html += "<div class=\"comment_entry_date\"> " + GetSpamLink(commentId)  + date + " </div>";
	html += "<a href=\"http://www.break.com/" +by+ "\" class=\"comment_entry_link\">" + by +"</a> says:";
	html += "</div>";
	html += "<div class=\"comment_entry_bot_sml\">";
	html += "<div class=\"comment_quote_lft\"><img src=\"http://media1.break.com/static/live/v1/img/site/quote_gray_lft.gif\" border=\"0\" /></div>";
	html += "<div class=\"comment_quote_sml\">";
	html += text;
	html += "</div>";
	html += "<div class=\"comment_quote_rgt\"><img src=\"http://media1.break.com/static/live/v1/img/site/quote_gray_rgt.gif\" border=\"0\" /></div>";
	html += "</div>";
	html += "</div>";
	html += "</div>";  
   return html;
}

function GetSpamLink(commentId){
	var link = "";

	  if(canPost != ""){
      	   	link = "[ " + "<a href='javascript:SentSpam(" + commentId + ");'>spam</a>" + " ] ";
      	  }

	return link;
}

function SentSpam(commentId){

	if (IsLoggedIn())
	{
	var fromId = getEncodedMemberID();

	 spamJson.sendBegin("http://websvc.break.com/cms/Handlers/Spam/SpamHandler.ashx?invoke=reportcomment&memberId=" +fromId+ "&commentId=" + commentId, "updateCommentSpam");
	}
	else
	{
		openLoginOverlay();
	}
}

function updateCommentSpam(jsonData){
	alert("Thank you for Marking as Spam.");
}



function closeOpenReplies(commentId)
{
    if(openReplies > -1 && openReplies != commentId)
    {
        toggleBox("newPopup_post_reply" + openReplies, 0);
    }
    openReplies = commentId;
}

function onMissingAvatar(img){
   img.src = "http://media1.break.com/static/live/v1/img/site/avatar_mini.gif";
}

function IsMeaningless(str){
	var tempStr = str.split(" ");
	for (i = 0; i < tempStr.length; i++)
	{
		if(tempStr[i] != "")
		{
			return false;
		}
	}
	return true;
}

function submitReplyComment(commentReplyId){
	var subject = "";
	var comment = "";
	var isInError = false;
	var fromId = getEncodedMemberID();

	comment = document.getElementById("post_text" + commentReplyId).value;

	if(comment == ""  || IsMeaningless(comment)) {
	   displayMessage("commentReplyBodyError" + commentReplyId, "You must specify a comment.");
	   isInError = true;
	}

	if(isInError)
	   return;

	hideReplyMessage(commentReplyId);
	toggleBox("newPopup_post_reply" + commentReplyId, 0);
	//alert("Posting Comment?");
	mcs.postContentComment(siteId, fromId, sGlobalContentID, commentReplyId, subject, comment, postContentCommentCallback);
	lastcomment = comment;
    lastcommentreplyid = commentReplyId;
    lastsubject = subject;
        
    /* Check if they are with a third party and send comment to that site if they allow you to */
    if (thirdPartyIsLoggedIntoBreak()) {        
        ThirdPartyMember.checkPermissions(submitCommentToThirdPartySite, "publish_stream");
    }
}

function submitComment(){
	
	var subject = "";
	var comment = "";
	var isInError = false;
	var fromId = getEncodedMemberID();

	comment = document.getElementById("taReplyComments").value;
	if(comment == "" || IsMeaningless(comment)) {
	   displayMessage("commentBodyReplyError", "You must specify a comment.");
	   isInError = true;
	}


	if (!((typeof(newCdp) == 'undefined')?false:newCdp) )
	{
		if (fromId == null)
		isInError = true;
		
		if(isInError)
		   return;

		hideMessage();
		toggleBox('post_box', 0);
	}
	mcs.postContentComment(siteId, fromId, sGlobalContentID, 0, subject, comment, postContentCommentCallback);
	lastcomment = comment;
    lastcommentreplyid = 0;
    lastsubject = subject;
    
    /* Check if they are with a third party and send comment to that site if they allow you to */
    if (thirdPartyIsLoggedIntoBreak()) {        
        ThirdPartyMember.checkPermissions(submitCommentToThirdPartySite, "publish_stream");
    }
}
function submitCommentToThirdPartySite(result) {
    if (result !== null) {
        if (result.toString() === "0" || result.toString() === "false") { return; } /* The user didn't allow us to post to Facebook */
        /* The user accepted the request to post this comment to the 3rd party site, so make a call to the service to send this comment */
        ThirdPartyMember.getName(function(result) {

            var userInfo = result[0];
            var comment = lastcomment;
            if (comment === "" || comment === null) {
                return;
            }
            var postTitle = userInfo.first_name + " commented on the " + getMetaDataByName('embed_video_title') + " video";
            var attachments = { "name": postTitle, "href": window.location.href, "description": getMetaDataByName('embed_video_description'), "media": [{ "type": "video", "video_src": getMetaDataByName('embed_video_url'), "preview_img": getMetaDataByName('embed_video_thumb_url'), "video_title": getMetaDataByName('embed_video_title')}] };

            var actionLinks = [{ "text": "Watch Video", "href": window.location.href}];
            //FB.Connect.streamPublish(comment, attachments, actionLinks, null, null, function(result) { }, true);            
            mcs.postCommentToThirdParty(postTitle, "", ThirdPartyMember.getThirdPartyName(), comment, window.location.href, getMetaDataByName('embed_video_description'), getMetaDataByName('embed_video_url'), getMetaDataByName('embed_video_thumb_url'), getMetaDataByName('embed_video_title'), thirdPartyCommentSent);

        });       
    }
}


function thirdPartyCommentSent(result, isOk) {
    /* Use this function to debug the results from the 3rd party comment posting
        alert(result);
    */
}


function insertComment(commentReplyId, subject, comment, avatar, nickName){
	if(nickName == "")
		nickName = "You";
	var htmlNode;
	if (avatar == "")
		avatar = "http://media1.break.com/dnet/media/AVATARS/NeutralAvatar.jpg";


	var date = new Date();
	var dateString = (date.getMonth() + 1) + "/" + date.getDate() + "/" + date.getFullYear();
	var hs = date.getHours()
	var meridian = hs < 12 ? "AM" : "PM";
	if (hs > 12) {hs = hs-12;}

	dateString += " " + hs + ":" + date.getMinutes() + ":" + date.getSeconds() + " " + meridian;

	if(commentReplyId == 0){   //new post
		var tempstate = canPost;
		canPost = false;
		if (!((typeof(newCdp) == 'undefined')?false:newCdp))
		{
			htmlNode = buildComment(0, dateString, nickName, avatar, subject, comment);
		}
		else
		{
			htmlNode = RenderReplyComment (0, dateString, nickName, avatar, subject, comment);
		}
		canPost = tempstate;
		var commentBox = document.getElementById("comment_bot").innerHTML;
		commentBox = htmlNode + commentBox;
		document.getElementById("comment_bot").innerHTML = commentBox;
	}
	else{
		if (!((typeof(newCdp) == 'undefined')?false:newCdp))
		{
			htmlNode = buildReplyComment(1, dateString, nickName, avatar, subject, comment);
		}
		else
		{
			htmlNode = RenderReplyComment (1, dateString, nickName, avatar, subject, comment);
		}
		
		var containerNode = document.getElementById("container" + commentReplyId);
		var containerHTML = htmlNode + containerNode.innerHTML ;
		containerNode.innerHTML = containerHTML;
	}
	var bottom_border = document.getElementById("comments_divider_bottom");
	bottom_border.style.visibility = "visible";
}


function closeAllotherBoxes(){
	try{
		hideBox('popup_box_share',0);
	}
	catch(e){
		//alert("popup_box_share" + e);
	}
	try{
		hideBox('popup_box_embed',0);
	}
	catch(e){
		//alert("popup_box_embed" + e);
	}
	try{
		hideBox('popup_box_add',0);
	}
	catch(e){
		//alert("popup_box_add" + e);
	}
}

function displayMessage(divId, messageText){
   document.getElementById(divId).innerHTML = messageText;
   document.getElementById(divId).style.display="block";
}

function hideMessage() {
   document.getElementById("commentBodyReplyError").style.display="none";
   //document.getElementById("subjectReplyError").style.display="none";
}

function hideReplyMessage(commentId) {
   document.getElementById("commentReplyBodyError" + commentId).style.display="none";
   //document.getElementById("commentReplySubjectError" + commentId).style.display="none";
}

function postContentCommentCallback (xmlDoc, isOk) {
   if(!isOk) {
      //displayMessage("genericError", "Error saving comment.");
      return;
   }

   try {
      var responseNode = xmlDoc.documentElement;

      if(responseNode.getAttribute("Code")<0) {
		 if(responseNode.getAttribute("Code") < -2){
			displayMessage("genericError", responseNode.getAttribute("Message"));
			}
      }
	  else {
	  //document.getElementById("iReplySubject").value = "";
      document.getElementById("taReplyComments").value = "";

	  var avatar;
	  var nickName;
      var node = xmlDoc.documentElement;

	  for (i = 0; i < node.childNodes.length; i++)
	  {
	 		if (node.childNodes[i].nodeName == "avatarURL")
			{
				avatar = node.childNodes[i].firstChild.nodeValue;
			}
			else if (node.childNodes[i].nodeName == "memberNickname")
			{
				nickName = node.childNodes[i].firstChild.nodeValue;
			}
	  }
	  clearDefaultComment();
	  insertComment(lastcommentreplyid, lastsubject, lastcomment, avatar, nickName);
  	  }
      return;
   }
   catch(e) {
		document.getElementById("taReplyComments").value = "";
   }
}

function getEncodedMemberID(){
          var memberIdCookie = getCookie("MemberID");
          if(memberIdCookie != null)
            return memberIdCookie;
          else
            return null;
}

function placeCommasInNumber(number)
{
	number = '' + number;
	if (number.length > 3) {
	var mod = number.length % 3;
	var output = (mod > 0 ? (number.substring(0,mod)) : '');
	for (i=0 ; i < Math.floor(number.length / 3); i++) {
	if ((mod == 0) && (i == 0))
	output += number.substring(mod+ 3 * i, mod + 3 * i + 3);
	else
	output+= ',' + number.substring(mod + 3 * i, mod + 3 * i + 3);
	}
	return (output);
	}
	else return number;
}

function isThisFirstComment(div){
	if(div.text() == "No Comments."){
		return true;
	}
	else{
		return false;
	}
}
function clearDefaultComment(){
	var div = jQuery("#comment_bot");
	if(isThisFirstComment(div)){
		div.empty();
	}
}

var ms = new MemberServices();
try {
	var mgs = new MessageServices();
}
catch(e){}
var memberId = document.cookie;
try {
	var contentId = sGlobalContentID;
}
catch(e){}
var siteId = 1; 
var index = memberId.search(/MemberId=/gi);
var isAjaxLoggedIn = false;

//Gets the encrypted memberId from the cookie
if(index != -1){
memberId = memberId.substr(index+9, memberId.length);
index = memberId.search(/;/gi);
if(index != -1)
  memberId = memberId.substr(0, index);
isAjaxLoggedIn = true;
}
else{
//you're not logged in!!!!!
isAjaxLoggedIn = false;
}


//////////////////////////////////
// Global Async Initializer
//////////////////////////////////
function AsyncInit(AsyncType)
{
	if(AsyncType=="Blog")
	{
	  //Initialize Blog List
	  if(isAjaxLoggedIn)
	  {     
	     UpdateBlogMessage("Retrieving blog list...");                      
	     //Get blog list and load select box
	     getBlogLists();   
		 
		 document.BlogForm.blogtitle.value=sGlobalContentTitle;
	  }
	  else
	  {
	     UpdateBlogMessage("You must be logged in to use the Blog feature");
	     HideDiv("BlogSectionForm"); //hide form              
	  }

	}
}
//////////////////////////////////
// Blog Methods
//////////////////////////////////

//Blog it 
function BlogIt(objBtn)
{
	//Check login state one more time
	if(isAjaxLoggedIn)
	{
	 //HideDiv("BlogSectionForm"); //hide form  

	 UpdateBlogButton("Blogging..", false)
	 
	 var frmBlogForm = document.BlogForm; 
	 var sBlogTitle = frmBlogForm.blogtitle.value;
	 var sBlogText = frmBlogForm.blogtext.value;
	 var sBlogId = frmBlogForm.BlogList.options[frmBlogForm.BlogList.selectedIndex].value;
	 var sMessage = sBlogText + " ("  + sGlobalContentUrl +")";	 
	
	 if(sBlogTitle=="" ||
	 	sBlogText=="")
		{
			alert("You are missing some data, please check your form and try again.")
			UpdateBlogButton("Blog it!", true)
			return;
		}
	
	 ms.postBlogCommments(sBlogId,sBlogTitle,sMessage, postBlogCallback);

	}
}
//Callback for the posting blog WebMethod
function postBlogCallback(xmlDoc, isOk){
	if(!isOk) {
	  //An error occurred usually a 500 or 404 type error, feel free to handle it elegantly
	  return;
	}
	try{
	  var responseNode = xmlDoc.documentElement;

	  if(responseNode.getAttribute("Code")<0){
	     //The WebService returned but it failed to process your response, could be anything from
	     //failing to retrieve/save data to the db or a server-side rule validation etc. The
	     //Message attribute contains the error message returned from the WebMethod
	     //responseNode.getAttribute("Message"); 
		 HideDiv("BlogSectionForm")   
	     UpdateBlogMessage("Could not post to your blog, <a href=javascript:ShowDiv('BlogSectionForm');HideDiv('BlogSectionMessage');TurnBlogFormOn();>Click Here</a> to try again");
	  }
	  else{
	     //All is good, parse the xml if you need the data returned from the WebService,
	     //call another function to update the UI, it's up to you        
		 UpdateButtonState("Blog it!", true, "BlogItButton")
		 HideDiv("BlogSectionForm")   
	     UpdateBlogMessage("Blog was sent successfully, <a href=javascript:ShowDiv('BlogSectionForm');HideDiv('BlogSectionMessage');TurnBlogFormOn();>Click Here</a> to go back");
	 

	  }
	}
	catch(e){
	  //This should never happen but if it does it means the XML returned 
	  //was malformed (missing the response node or attributes etc)
	  alert(e)
	  
	  UpdateButtonState("Blog it!", true, "BlogItButton")
	  HideDiv("BlogSectionForm")  
	  UpdateBlogMessage("Could not post to your blog, <a href=javascript:ShowDiv('BlogSectionForm');HideDiv('BlogSectionMessage');TurnBlogFormOn();>Click Here</a> to try again");
	}
}
function TurnBlogFormOn()
{
	UpdateButtonState('Blog it!', true, 'BlogItButton')
}
//Callback for the getBlogLists WebMethod
function getBlogListsCallback(xmlDoc, isOk){
	if(!isOk) {
	  //An error occurred usually a 500 or 404 type error, feel free to handle it elegantly
	  return;
	}

	try{
	  var responseNode = xmlDoc.documentElement;
	  if(responseNode.getAttribute("Code")<0){
	     //The WebService returned but it failed to process your response, could be anything from
	     //failing to retrieve/save data to the db or a server-side rule validation etc. The
	     //Message attribute contains the error message returned from the WebMethod
	     //responseNode.getAttribute("Message"); 
	    UpdateBlogMessage("Could not retrieve your blog information, please try again later");
	  }
	  else{
	     //All is good, parse the xml if you need the data returned from the WebService,
	     //call another function to update the UI, it's up to you                   
	    UpdateBlogList (responseNode);

	  }
	}
	catch(e){
	  //This should never happen but if it does it means the XML returned 
	  //was malformed (missing the response node or attributes etc)
	}
}
//Calls the AJAX function for getting the user's blog list
function getBlogLists(){
	ms.retrieveBlogList(siteId, memberId, getBlogListsCallback);
} 
//Update blog list
function UpdateBlogList(xmlElement){

	var elements;
	var selectBlogList;
	var divBlogSectionForm;
	var blogId;
	var blogName;               

	divBlogSectionForm = document.getElementById("BlogSectionForm")
	selectBlogList = document.getElementById("BlogList");
	elements = xmlElement.getElementsByTagName("Blog");             

	if(elements.length > 0){      
	  ShowDiv("BlogSectionForm");//show form
	  HideDiv("BlogSectionMessage");//hide message
	  for(i=0;i<=elements.length;i++)
	  {
	      blogId = elements[i].getAttribute("BlogId");
	      blogName = elements[i].getAttribute("BlogName");                      
	      selectBlogList.options[i] = new Option(blogName,blogId);
	  }

	}
	else
	{
	  UpdateBlogMessage("You have not set up any blogs.  <a href='http://my.break.com/Member/Profile/MyProfile.aspx'>Click Here</a> to add your blog information");
	}
} 
function UpdateBlogButton(strValue,bIsEnabled)
{
	var objBtn = document.getElementById("BlogItButton")
	objBtn.value = strValue;
	objBtn.disabled = (bIsEnabled)?false:true;
}
function UpdateBlogMessage(strMessage)
{
	var divBlogSectionMessage = document.getElementById("BlogSectionMessage");
	ShowDiv("BlogSectionMessage");
	divBlogSectionMessage.innerHTML = strMessage;
}  

//////////////////////////////////
// Send To Friend Methods
//////////////////////////////////

var oSendToFriendTable = document.getElementById("SendToFriendTable")

//Process form fields and perform quick validation
function processQuickEmailFieldsAndSendEmail()
{
	var sName = document.getElementById("TellAFriend_SenderName");
	var sEmail = document.getElementById("TellAFriend_SenderEmail");
	var sFriends = document.getElementById("TellAFriend_RecipientEmail1");
	var sComments = document.getElementById("TellAFriend_QuickNoteToFriend");
	
    sFriends.value = sFriends.value.replace(/\s/g, "");
	//Do quick validation
	if(sName.value=="" ||
	   sEmail.value=="" ||
	   sFriends.value=="" ||
	   sComments.value=="")
	{
	  alert("Your are missing something in your form.")
	  return;
	}

	//Do a quick email validation
	if(!emailCheck(sEmail.value))
	{
	  alert("Your email is invalid")
	  return;
	}

	//Do a quick email validation for the friends
	var aEmails = sFriends.value.split(',');
	if(aEmails.length>0)
	{
	  for(i=0;i<aEmails.length;i++)
	  {
	    if(!emailCheck(aEmails[i]))
	    {
	      alert("Your friend(s) email is invalid: " + aEmails[i])
	      return;
	      break;                      
	    }
	  }
	}
	UpdateButtonState("Sending...", false, "SendToFriendButton")
	mgs.TellToFriendEmail(sName.value, sEmail.value, sFriends.value, sComments.value, sGlobalContentID, "sendToFriendCallback");
	
	//clearing out the form 
	sName.value = "";
	sEmail.value = "";
	sFriends.value = "";
	sComments.value = "";
}

//Callback for the sendToFriend WebMethod
//Callback for the sendToFriend WebMethod
function sendToFriendCallback(jsonData)
{
    if(jsonData.Response.Code < 0) 
    {
        //The WebService returned but it failed to process your response, could be anything from
	     //failing to retrieve/save data to the db or a server-side rule validation etc. The
	     //Message attribute contains the error message returned from the WebMethod
	     //responseNode.getAttribute("Message");
		 
    }
    else
    {
        //All is good, parse the xml if you need the data returned from the WebService
	     //call another function to update the UI, it's up to you    
		 UpdateButtonState("Send It", true, "SendToFriendButton")
		 
    }

}

//////////////////////////////////
// Add to Favorite Methods
//////////////////////////////////   

var divAddToFavoritesMessage = document.getElementById("AddToFavoritesMessage")

//Callback for the addToFavorites WebMethod
function addToFavoritesCallback(xmlDoc, isOk){
	if(!isOk) {
	  //An error occurred usually a 500 or 404 type error, feel free to handle it elegantly
	  return;
	}

	try{
	  var responseNode = xmlDoc.documentElement;
	  if(responseNode.getAttribute("Code")<0){
	     //The WebService returned but it failed to process your response, could be anything from
	     //failing to retrieve/save data to the db or a server-side rule validation etc. The
	     //Message attribute contains the error message returned from the WebMethod
	     //responseNode.getAttribute("Message"); 
	     if(divAddToFavoritesMessage!=null)
		 {		
		 	if(responseNode.getAttribute("Code")==-3)
			{				
				divAddToFavoritesMessage.innerHTML = "This content is already in your Favorites.";	
				return;
			}
		 
		 	if(responseNode.getAttribute("Message")!= "")
			{
				divAddToFavoritesMessage.innerHTML = responseNode.getAttribute("Message");				
			}
			else
			{	
				divAddToFavoritesMessage.innerHTML = "This content has been added to your Favorites.";		
			}
		 }
	  }
	  else{
	     //All is good, parse the xml if you need the data returned from the WebService
	     //call another function to update the UI, it's up to you
	     if(divAddToFavoritesMessage!=null)
		 {
		 	if(responseNode.getAttribute("Message")!= "")
			{
				divAddToFavoritesMessage.innerHTML = responseNode.getAttribute("Message");				
			}
			else
			{				
				divAddToFavoritesMessage.innerHTML = "This content has been added to your Favorites.";
			}			
		 }

	  }
	}
	catch(e){
	  //This should never happen but if it does it means the XML returned 
	  //was malformed (missing the response node or attributes etc)
	}
}    
//Calls the AJAX function for adding content to your favorites
function addToFavorites(){
	ms.saveToFavorites(1, getEncodedMemberID(), sGlobalContentID, addToFavoritesCallback);
}

/* @Afrew:   Creates a random number and associates a survey link with that number, 
*			 then switches the href of the survey link to calculated survey.
*  @Requires: jQuery
*  @Params:  N/A
*  @Returns: N/A
*
*/
jQuery(document).ready(generateSurveyHref);
function generateSurveyHref(){
	//jQuery random number generator plugin
	jQuery.extend({random: function(X){return Math.floor(X * (Math.random() % 1));},randomBetween: function(MinV, MaxV) {return MinV + jQuery.random(MaxV - MinV + 1);}});

	var destHref = null;
	var randNum = jQuery.randomBetween(1,2);
	
	switch (randNum){
		case 1: destHref = "http://www.surveymonkey.com/s.aspx?sm=Z6TPogdTANQ_2fqdtk20GcIA_3d_3d";
		break;
		case 2: destHref = "http://www.surveymonkey.com/s.aspx?sm=yJVnBpxhhexm6gePBjcwkg_3d_3d";
		break;
		//case 3: destHref = "http://www.surveymonkey.com/s.aspx?sm=j4t0M7PczrKgyqEuHQZ5PA_3d_3d";
		//break;
		//case 4: destHref = "http://www.surveymonkey.com/s.aspx?sm=ifA822ZzR7bZOzUk55tWkA_3d_3d";
		//break;
		//case 5: destHref = "http://www.surveymonkey.com/s.aspx?sm=VjNOq4N9gTdpNiVdpElx2w_3d_3d";
		//break;
		//case 6: destHref = "http://www.surveymonkey.com/s.aspx?sm=IUKzPYGJs94IaqZCyOtVYg_3d_3d";
		//break;
		//case 7: destHref = "http://www.surveymonkey.com/s.aspx?sm=zAu9jE2j7S_2bN0zF5JVgFBw_3d_3d";
		//break;
		//case 8: destHref = "http://www.surveymonkey.com/s.aspx?sm=y5TLHfNBK6SvtAouZt2zjw_3d_3d";
		//break;
		default : destHref = "http://www.surveymonkey.com/s.aspx?sm=Z6TPogdTANQ_2fqdtk20GcIA_3d_3d";
	}
	
	jQuery("#cdpSurveyLink").attr("href",destHref);
	return;
}
//////////////////////////////////
// For scrolling thumbnail modules
//////////////////////////////////
jQuery(function($) { // init static thumbs modules
	if ($('.scroll-static').length) {	
		$('.scroll-static').scrollable({
			size : 3,
			speed : 500,
			items : '.thumbstrip'
		});
		adjNaviOffset();
	}
});

function initThumbScroller(module) {
	jQuery(function($) {
		$(module).parent().scrollable({
			size : 3,
			speed : 500,
			items : '.thumbstrip'
		});
	});	
	adjNaviOffset();
}

function adjNaviOffset() {
	jQuery(function($) {
		var navbars = $('.navi');
		if(navbars.length) {
			navbars.each(function(i) {
			var target = navbars.eq(i);
			var numEl = target.children().length;
			var offset = 295 - ( (numEl - 1) * 8);
			if ( $(this).hasClass('gt-navi') ) { // game trailers version is thinner, adjusting
				offset -= 34; 
			}
			if (numEl > 1) {
				target.css('margin-left', offset+'px');
			}
		});
		}
	});
}

//////////////////////////////////
// Toggle Module (resuable) START
function toggleModule() {
	jQuery(function($) {
		//Custom Toggle Module - Initialize Toggle Modules
		$(document).ready(function(){
			if ($(".toggle-module").length) {
				$(".toggle-module").each(function() {
					//add open button to each toggle module
					$(".toggle-button", this).addClass("toggle-button-open");
					// if the toggle module is set to open then add the close button
					if ( $(this).hasClass("toggle-moduleopen") ) {
						$(".toggle-modulecontent", this).show();
						$(".toggle-button", this).addClass("toggle-button-close");
						$(".toggle-button", this).removeClass("toggle-button-open");		
					}
				});
			}
		});
		// Custom Toggle - Toggle Function
		$(".toggle-module-hotspot", this).click(function() {
			//if open then do this
			if ( $(this).parents(".toggle-module").hasClass("toggle-moduleopen") )
			{
				$(this).parents(".toggle-module").removeClass("toggle-moduleopen");
				$(this).parents(".toggle-module").find(".toggle-button").addClass("toggle-button-open");
				$(this).parents(".toggle-module").find(".toggle-button").removeClass("toggle-button-close");
				//$(this).parents(".toggle-module").find(".toggle-modulecontent").slideUp('fast');
				$(this).parents(".toggle-module").find(".toggle-modulecontent").hide();
				}
			// if closed then do this
			else
			{
				$(this).parents(".toggle-module").addClass("toggle-moduleopen");
				$(this).parents(".toggle-module").find(".toggle-button").addClass("toggle-button-close");
				$(this).parents(".toggle-module").find(".toggle-button").removeClass("toggle-button-open");
				//$(this).parents(".toggle-module").find(".toggle-modulecontent").slideDown('fast');
				$(this).parents(".toggle-module").find(".toggle-modulecontent").show();
			}
		});
	});
}
// Toggle Module (resuable) END
//////////////////////////////////

//////////////////////////////////
// Tab Toggle Module (resuable) START
function tabToggleModule () {
	jQuery(function($) {
		//Custom Tab Toggle Module - Initialize Toggle Modules
		$(document).ready(function(){
			// START initialize all content tabs
			if ($(".tab-header").length)
			{
				// START override tab-header-active if passed from url
				var strTabDefault = getQueryString('comments');
				if ( strTabDefault == 1 )
				{
					$(".tab-header").each(function() {
						$(".tab-header").removeClass("tab-header-active");
					});
					$("#tab-header-comments").addClass("tab-header-active");
				}
				// END override tab-header-active if passed from url
				// search for tab-header-active and make the tab and assoiated tab-content active
				$(".tab-header").each(function() {
					if ( $(this).hasClass("tab-header-active") )
					{
						var indexTabHeader = $(".tab-header").index(this);
						$(".tab-content").eq(indexTabHeader).show();
					}
					else
					{
						$(this).addClass("tab-header-inactive");
					}
				});
				if ( $(".tab-header:first").hasClass("tab-header-active") ) {
					$("#tab-header-left").removeClass("tab-header-left-inactive");
					$("#tab-header-left").addClass("tab-header-left-active");
				}
				else {
					$("#tab-header-left").addClass("tab-header-left-inactive");
				}
				if ( $(".tab-header:last").hasClass("tab-header-active") ) {
					$("#tab-header-right").removeClass("tab-header-right-inactive");
					$("#tab-header-right").addClass("tab-header-right-active");
				}
				else {
					$("#tab-header-right").addClass("tab-header-right-inactive");
				}
			}
			// END initialize all content tabs
			// START click function
			$(".tab-header").click(function() {
				$(".tab-header").each(function() {
					$(".tab-header").removeClass("tab-header-active");
					$("#tab-header-left").removeClass("tab-header-left-active");
					$("#tab-header-left").addClass("tab-header-left-inactive");
					$("#tab-header-right").removeClass("tab-header-right-active");
					$("#tab-header-right").addClass("tab-header-right-inactive");
					$(".tab-header").addClass("tab-header-inactive");
				});
				$(this).removeClass("tab-header-inactive");
				$(this).addClass("tab-header-active");
				if ( $(".tab-header:first").hasClass("tab-header-active") ) {
					$("#tab-header-left").removeClass("tab-header-left-inactive")
					$("#tab-header-left").addClass("tab-header-left-active");
				}
				if ( $(".tab-header:last").hasClass("tab-header-active") ) {
					$("#tab-header-right").removeClass("tab-header-right-inactive");
					$("#tab-header-right").addClass("tab-header-right-active");
				}
				
				var indexTabHeader = $(".tab-header").index(this);
				$(".tab-content").each(function() {
					$(".tab-content").hide();
				});
				$(".tab-content").eq(indexTabHeader).show();
			});
			// END click function
		});
	});
}
// Tab Toggle Module (resuable) END
//////////////////////////////////

jQuery(function($){
	$("#social-tools-wrap > div").add('.soc-ico-btn').hover(function() {
		$(this).find("> span").stop()
		.animate({opacity:1}, "fast")
		.css({'visibility':'visible'});

	}, function() {
		$(this).find("> span").stop()
		.animate({opacity:0}, "fast")
		.css({'visibility':'hidden'});
	});

	$("#social-tools-email").click(function() {
		$("#social-tools-email-wrap").toggle();
	});
	$("#social-tools-email-send").click(function() {
		$("#social-tools-email-wrap").hide();
	});
	
	$('#addtofavs').click(function() {
		if(IsLoggedIn()) {
			$('#addtofavspop').toggle();
		}
	});
	
	$('.s-icon-closebox').click(function(e){
		e.preventDefault();
		$(this).parent().hide();
	});
	
	$('.soc-ico-fb').click(function(){return fbs_click()});	
	$('.soc-ico-th-up').click(function(e){e.preventDefault();rate(1)});
	$('.soc-ico-th-dn').click(function(e){e.preventDefault();rate(-1)});
});

function writeMarkAsSpam(cid) {
	var markup;
	if((memberCookie || memberRememberCookie) != null){
	  var mid = getCookie("MemberID");
	  markup = "<div onclick=\"markSpam('"+mid+"','"+cid+"','4','1');\" id=\"marks\"><span>Mark as Spam</span></div>"; 
	}
	else {                                    
	  markup = "<div class=\"checkLogin\" id=\"marks\"><span>Mark as Spam</span></div>";
	}
	document.write(markup);
}

function writeMarkAsInappropriate(cid) {
	var markup;
	if((memberCookie || memberRememberCookie) != null) {
		var mid = getCookie("MemberID");
		markup = "<div onclick=\"markInappropriate('"+mid+"','"+cid+"','4','1');\" id=\"marki\"><span>Mark as Inappropriate</span></div>";
	}
	else{                                    
		markup = "<div class=\"checkLogin\" id=\"marki\"><span>Mark as Inappropriate</span></div>";
	}
	document.write(markup);
}

function writeVoteToHomepage(cid) {
	var markup;
	if((memberCookie || memberRememberCookie) != null) {
		var mid = getCookie("MemberID");
		markup = "<div onclick=\"promoteToHomePage('"+mid+"','"+cid+"','4','1');\" id=\"vote\"><span>Vote to Homepage</span></div>";
	}
	else {                                    
		markup = "<div class=\"checkLogin\" id=\"vote\"><span>Vote to Homepage</span></div>";
	}
	document.write(markup);
}

function writeAddToFavs() { // legacy, supports showcase CDP pages
	var atfMarkup;
	if(IsLoggedIn()) {
	  atfMarkup = '<a id="add" href="javascript:toggleBox(\'newPopup_add\', 1);addToFavorites();"><b>Add to Favs</b></a>';
	}
	else {
	  atfMarkup = '<a id="add" class="checkLogin" href=""><b>Add to Favs</b></a>';
	}
	document.write(atfMarkup);
}

function writeAddToFavorites() { // supports new cdp
	var atfMarkup;
	var msg = 'Add to Favorites';
	
	if(IsLoggedIn()) {
		atfMarkup = '<div id="addtofavs" onclick="addToFavorites();"><span>'+msg+'</span></div>';
	}
	else {
	  atfMarkup = '<div id="addtofavs" class="checkLogin"><span>'+msg+'</span></div>';
	}
	document.write(atfMarkup);
}

function fbs_click() {u=location.href;t=document.title;window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');return false;}

function diggRefer() {
	var sendingURL = document.referrer;
	var index = sendingURL.match(/digg.com/);
	var index2 = sendingURL.match("google.com") || sendingURL.match("bing.com") || sendingURL.match("yahoo.com");

	if(index) {
		jQuery(document).ready(GetDugg);
	}
	else if(index2) {
		conditional_RenderGoogleReferrerModules();
	}
}
//////////////////////////////////
// Comments functions START

var currentDisplayCriteria = 'date';
var currentPageNumber = 1;
var TotalRowCount = 1;

//Constant
var commentsPerPage = 10;

function CheckLoginComments ()
{
	openLoginOverlay();
}

function DisplayComments  (DisplayCriteria, ContentID, PageNumber)
{
	currentDisplayCriteria = DisplayCriteria;
	currentPageNumber = PageNumber;
	jQuery ('#comments-module-wrap').html('<div id="comment_bot" style="display:block">Loading Comments . . .</div>' );
	jQuery.getJSON('http://service.break.com/comment/detail/'+DisplayCriteria+'/'+ContentID+'/'+PageNumber+'/'+commentsPerPage+'?callback=?', function(data)
		{
			var commentHTML = '<div id="comment_bot" style="display:block"></div>';
			jQuery.each (data, function (i,item) {
				
				if (i == 0)
				{
					commentHTML = '';
					TotalRowCount = item.RowCount;
					
					commentHTML += RenderCommentHeader (data.length, item.RowCount);
					commentHTML += '<div id="comment_bot" style="display:block">';
				}
				if (item.ContentCommentID == item.ParentContentCommentID)
				{
					commentHTML += RenderParentComment (item);
				}
				else 
				{
					commentHTML += RenderChildComment (item);
				}
				if (i == data.length -1)
				{
					commentHTML += RenderCommentFooter (TotalRowCount);
					commentHTML += '</div>';
					
				}
			});
			jQuery ('#comments-module-wrap').html(commentHTML);
			/*jQuery(".checkLogin").click(function() {
						//alert ('test');
						if (jQuery.cookie("membernickname") != null) {
						if (!IsLoggedIn()) {
						ShowLoginBox();
						return false;
					}
					return true;
				}
				else {
						ShowRegistrationBox();
					return false;
				}
			});*/

		});
}

function RenderCommentHeader (ListedCount, TotalCount)
{
	var arr = new Array ();
	var finalPage = parseInt( Math.ceil(TotalCount / commentsPerPage));
	var firstNumber = (currentPageNumber == 1) ? 1 : parseInt( (currentPageNumber - 1) * commentsPerPage + 1);
	var lastNumber = ((currentPageNumber - 1) * commentsPerPage + ListedCount);
	arr.push ('<div class="clearboth"/>');
	arr.push ('<div style="float: left; margin-bottom: 10px;">'+firstNumber+'-'+lastNumber+' of '+TotalCount+' Comments</div>');
	if (currentDisplayCriteria == 'date')
	{
		arr.push ('<div style="float: right; margin-bottom: 10px;"> sort by: <a href="" onclick="DisplayComments(\'rating\','+sGlobalContentID+',1);return false;">rating</a> | date </div>');
	}
	else
	{
		arr.push ('<div style="float: right; margin-bottom: 10px;"> sort by: rating | <a href="" onclick="DisplayComments(\'date\','+sGlobalContentID+', 1);return false;">date</a> </div>');
	}
	return arr.join('');
}


function RenderCommentFooter (TotalCount)
{
	var finalPage = parseInt( Math.ceil(TotalCount / commentsPerPage));
	var arr = new Array ();
	arr.push ('<div style="float: right;">');
	if (finalPage <= 1)
	{
		return '';
	}
	if (currentPageNumber > 1)
	{
		arr.push ('<a class="break-link" href="" onclick="DisplayComments(\''+currentDisplayCriteria+'\','+sGlobalContentID+', 1);return false;">&lt;&lt;First </a>'); 
	}
	else
	{
		arr.push ('<span>&lt;&lt;First </span>'); 
	}
	if (currentPageNumber > 1 && currentPageNumber <= finalPage)
	{
		arr.push ('<a class="break-link" href="" onclick="DisplayComments(\''+currentDisplayCriteria+'\','+sGlobalContentID+','+(currentPageNumber-1)+');return false;">&lt;Previous </a>');
	}
	else
	{
		arr.push ('<span>&lt;Previous </span>'); 
	}
	if (currentPageNumber >= 1 && currentPageNumber< finalPage)
	{
		arr.push (' <a class="break-link"  href="" onclick="DisplayComments(\''+currentDisplayCriteria+'\','+sGlobalContentID+','+(currentPageNumber+1)+');return false;"> Next&gt;</a>'); 
	}
	else
	{
		arr.push ('<span> Next&gt;</span>'); 
	}
	if (currentPageNumber >= 1 && currentPageNumber < finalPage)
	{
		arr.push ('<a class="break-link" href="" onclick="DisplayComments(\''+currentDisplayCriteria+'\','+sGlobalContentID+','+finalPage+');return false;"> Last&gt;&gt;</a>');
	}
	else
	{
		arr.push ('<span> Last&gt;&gt;</span>'); 
	}
	arr.push ('</div>');
	return arr.join('');
}

function RateComment (ContentCommentID, rating)
{

	if (IsLoggedIn ())
	{
	//sample format: 	http://service.break.com/comment/rate/2578088/1/jLLXd06y8gXA6vQO1Yt1zQ==
		var memberid = jQuery.cookie('MemberID');
		var finalURL = 'http://service.break.com/comment/rate/'+ContentCommentID+'/'+rating+'/?callback=?';
		
		jQuery.getJSON (finalURL,function (data)
		{
			if (data.ContentCommentID > 0)
			{
				if (parseInt (data.Result) != 'NaN' && (parseInt (data.Result) == -1 || parseInt (data.Result) == 1))
				{
					var rating = parseInt(jQuery('#rating_display'+data.ContentCommentID).text());
					rating += parseInt (data.Result);
					jQuery('#rating_display'+data.ContentCommentID).text(rating);
				}
				if (data.Result == 'banned')
				{
					alert ("We have determined that you were abusing our Comments Rating System, so we are putting you in time out for 24 hours.  Also: get a life.");
				}
				if (data.Result == 'permanentban')
				{
					alert ("We have determined that you were abusing our Comments Rating System, so we are permanently banning you from using it.  You really need to take a good, long look in a mirror.");
				}
				if (data.Result == 0)
				{
					alert ("You have already rated for this comment.");
				}
			}
			
		});
	}
	else
	{
		openLoginOverlay();
	}

	
}

function CommentReply (ContentCommentID)
{
	if (IsLoggedIn ())
	{
		toggleBox('newPopup_post_reply'+ContentCommentID,1);
		closeOpenReplies(ContentCommentID);
	}
	else
	{
	openLoginOverlay();
	}
}

function RenderReplyComment (commentId, date, by, avatar, title, text) 
{

	var arr = new Array ();
	if (commentId == 0)
	{
		arr.push ('<div class="comment_entry" id="comment'+commentId+'">');
			arr.push ('<div class="comment_avatar">');
				arr.push ('<a href="http://www.break.com/'+by+'"><img width="50" height="50" border="0" src="'+avatar+'" class="comment_avatar" onerror="onMissingAvatar(this)"/></a>');
			arr.push ('</div>');
			arr.push ('<div class="comment_nonavatar">');
				arr.push ('<div class="comment_entry_top"><div class="comment_entry_date"> '+date +' </div><a href="http://www.break.com/'+by+'" class="comment_entry_link">'+by+'</a> says:')
				arr.push ('</div>');
				arr.push ('<div class="comment_entry_bot">');
					arr.push ('<div class="comment_quote_lft"><img border="0" src="http://media1.break.com/static/live/v1/img/site/quote_gray_lft.gif"/></div>');
					arr.push ('<div class="comment_quote">'+ text +'</div>');
					arr.push ('<div class="comment_quote_rgt"><img border="0" src="http://media1.break.com/static/live/v1/img/site/quote_gray_rgt.gif"/></div>');
				arr.push ('</div>');
			arr.push ('</div>');
		arr.push ('</div>');
	}
	else
	{
		arr.push ('<div class="comment_entry_sml" id="comment'+commentId+'">');
		arr.push ('<div class="comment_avatar"><a href="http://www.break.com/'+by+'"><img width="50" height="50" border="0" src="'+ avatar+'" class="comment_avatar" onerror="onMissingAvatar(this)"/></a>');
		arr.push ('</div>');
		arr.push ('<div class="comment_nonavatar2">');
		arr.push ('<div class="comment_entry_top_sml"><div class="comment_entry_date"> '+date+' </div><a href="http://www.break.com/'+by+'" class="comment_entry_link">'+by+'</a> says:</div>');
		arr.push ('<div class="comment_entry_bot_sml">');
		arr.push ('<div class="comment_quote_lft"><img border="0" src="http://media1.break.com/static/live/v1/img/site/quote_gray_lft.gif"/></div>');
		arr.push ('<div class="comment_quote_sml">'+ text +'</div>');
		arr.push ('<div class="comment_quote_rgt"><img border="0" src="http://media1.break.com/static/live/v1/img/site/quote_gray_rgt.gif" /></div>');
		arr.push ('</div>');
		arr.push ('</div>');
		arr.push ('</div>');
	}
	return arr.join('');
}

function RenderParentComment (data)
{
	var arr = new Array ();
	arr.push ('<div class="comment_entry" id="comment'+data.ContentCommentID+'">');
	arr.push ('<div class="comment_avatar">');
	arr.push ('<a href="http://www.break.com/'+data.ByNickName+'"><img width="50" height="50" border="0" src="'+data.ByAvatarURL+'" class="comment_avatar" onerror="onMissingAvatar(this)"/></a>');
	arr.push ('</div>');
	arr.push ('<div class="comment_nonavatar">');
	arr.push ('<div class="comment_entry_top"><div class="comment_entry_date"> [<a href=""  onclick="SentSpam('+data.ContentCommentID+');return false;">spam</a>] '+data.CommentEntryDate +' <a id="reply'+data.ContentCommentID+'" href="" onclick="CommentReply('+data.ContentCommentID+');return false;">REPLY</a> </div><a href="http://www.break.com/'+data.ByNickName+'" class="comment_entry_link">'+data.ByNickName+'</a> says:')
	arr.push ('</div>');
	arr.push ('<div class="comment_entry_bot">');
	arr.push ('<div class="comment_quote_lft"><img border="0" src="http://media1.break.com/static/live/v1/img/site/quote_gray_lft.gif"/>');
	arr.push ('</div>');
	arr.push ('<div class="comment_quote">'+ data.DiscussionText +'</div>');
	arr.push ('<div class="comment_quote_rgt"><img border="0" src="http://media1.break.com/static/live/v1/img/site/quote_gray_rgt.gif"/></div>');
	arr.push ('<div class="comment_rate">');
	arr.push ('Rate this comment: <a href="" class="checkLogin" border="0" onclick="RateComment('+data.ContentCommentID+',1);return false;"><img border="0" src="http://media1.break.com/static/live/v1/img/site/comments-ratings-up.gif"/></a><a href="" border="0" onclick="RateComment('+data.ContentCommentID+',-1);return false;"><img border="0"  src="http://media1.break.com/static/live/v1/img/site/comments-ratings-down.gif"/></a> Comment Rating: <span id="rating_display'+data.ContentCommentID+'">'+ data.RatingTotalCount+'</span></div>');
	arr.push ('</div>');
	arr.push ('</div>');
	arr.push ('</div>');
	arr.push ('<div class="post_box" id="newPopup_post_reply'+data.ContentCommentID+'"><div class="post_box_wrap"><a class="comment_entry_link_sml" href="" onclick="toggleBox(\'newPopup_post_reply'+data.ContentCommentID+'\',0);return false;">Close</a><br/><br/><input type="button" onclick="javascript:submitReplyComment('+data.ContentCommentID+');" value="Post"/><br/></div><textarea id="post_text'+data.ContentCommentID+'" class="post_text"/><div id="commentReplyBodyError'+data.ContentCommentID+'"/></div>');
	arr.push ('<div id="container'+data.ParentContentCommentID+'" style="padding-top: 0pt; margin-top: 0pt;"></div>');
	return arr.join('');
}

function RenderChildComment (data)
{
	var arr = new Array ();
	arr.push ('<div class="comment_entry_sml" id="comment'+data.ContentCommentID+'">');
	arr.push ('<div class="comment_avatar"><a href="http://www.break.com/'+data.ByNickName+'"><img width="50" height="50" border="0" src="'+ data.ByAvatarURL+'" class="comment_avatar" onerror="onMissingAvatar(this)"/></a>');
	arr.push ('</div>');
	arr.push ('<div class="comment_nonavatar2">');
	arr.push ('<div class="comment_entry_top_sml"><div class="comment_entry_date"> [<a href="" class="checkLogin" onclick="SentSpam('+data.ContentCommentID+');return false;">spam</a>] '+data.CommentEntryDate+' </div><a href="http://www.break.com/'+data.ByNickName+'" class="comment_entry_link">'+data.ByNickName+'</a> says:</div>');
	arr.push ('<div class="comment_entry_bot_sml">');
	arr.push ('<div class="comment_quote_lft"><img border="0" src="http://media1.break.com/static/live/v1/img/site/quote_gray_lft.gif"/></div>');
	arr.push ('<div class="comment_quote_sml">'+ data.DiscussionText +'</div>');
	arr.push ('<div class="comment_quote_rgt"><img border="0" src="http://media1.break.com/static/live/v1/img/site/quote_gray_rgt.gif" /></div>');
	arr.push ('<div class="comment_rate">');
	arr.push ('Rate this comment: <a href="" class="checkLogin" border="0" onclick="RateComment('+data.ContentCommentID+',1);return false;"><img border="0" return false;" src="http://media1.break.com/static/live/v1/img/site/comments-ratings-up.gif"/></a><a href="" class="checkLogin" border="0" onclick="RateComment('+data.ContentCommentID+',-1);return false;"><img border="0" src="http://media1.break.com/static/live/v1/img/site/comments-ratings-down.gif"/></a> Comment Rating: <span id="rating_display'+data.ContentCommentID+'">'+ data.RatingTotalCount+'</span></div>');
	arr.push ('</div>');
	arr.push ('</div>');
	arr.push ('</div>');
	return arr.join('');
}
// Comments functions END
//////////////////////////////////
