// General EOL blog JavaScript functionality

Event.observe(window, 'load', function() {
	if ($('module_lists')) {
	var sfEls = document.getElementById("module_lists").getElementsByTagName("H3");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
		}
	}
});

Event.observe(window, 'load', function() {
	if ($('module_podcast')) {
	var sfEls = document.getElementById("module_podcast").getElementsByClassName("H4");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
		}
	}
});


//topics module js
function getTopicsList(edition){
	var pars = "";
	var seeAllFR = "Voir tous les th" + String.fromCharCode(232) +  "mes";
	var viewTop20FR = "Le top 20 des th" + String.fromCharCode(232) +  "mes";

	if ($('show_hide_topics').innerHTML == "See all" || $('show_hide_topics').innerHTML == "Alle" || $('show_hide_topics').innerHTML===seeAllFR || $('show_hide_topics').innerHTML == "Lista completa"){
		pars = 'topicMenu=showAll';
		topicsListPath = '/static/uberblog/topics/' + edition + '/topics-all.html';
	} else {
		pars = 'topicMenu=false';
		topicsListPath = '/static/uberblog/topics/' + edition + '/topics.html';
	};

	// this is a little hack to play nice with the accordion.
	$('hot_topics_list').parentNode.setStyle({
		height: 'auto'
	});

	new Ajax.Updater('hot_topics_list', '/uberblog/includes/jsp/railmods/topics.jsp', {
  		parameters: pars,
		onComplete: function(){
			if ($('show_hide_topics').innerHTML == "See all" || $('show_hide_topics').innerHTML == "Alle" || $('show_hide_topics').innerHTML===seeAllFR || $('show_hide_topics').innerHTML == "Lista completa"){
				$('show_hide_topics_val').value = $('show_hide_topics').innerHTML;
				if ( edition == 'de' || edition == 'it' ) {
					$('show_hide_topics').innerHTML = 'Top 20';
				} else if (edition == 'fr') {
					$('show_hide_topics').innerHTML = viewTop20FR;
				} else {
					$('show_hide_topics').innerHTML = 'View top 20';
				}
			} else {
				$('show_hide_topics').innerHTML = $('show_hide_topics_val').value;
				$('hot_topics_header').scrollTo();
			}
		}
	});
}

//topics module js
function getKristinTopicsList(edition){
	var pars = "";

	if ($('show_hide_topics').innerHTML==="See all"){
		new Ajax.Updater('categories_list', '/static/uberblog/modules/categories_watch_with_kristin-all.html', {
	  		parameters: pars,
			onComplete: function(){
				if ($('show_hide_topics').innerHTML==="See all"){
					$('show_hide_topics').update('View top 20');
				} else {
					$('show_hide_topics').update('See all');
					$('hot_topics_header').scrollTo();
				}
			}
		});
	} else {
		new Ajax.Updater('categories_list', '/static/uberblog/modules/categories_watch_with_kristin.html', {
	  		parameters: pars,
			onComplete: function(){
				if ($('show_hide_topics').innerHTML==="See all"){
					$('show_hide_topics').update('View top 20');
				} else {
					$('show_hide_topics').update('See all');
					$('hot_topics_header').scrollTo();
				}
			}
		});
	};

	// this is a little hack to play nice with the accordion.
	$('categories_list').parentNode.setStyle({
		height: 'auto'
	});
}
/* main accordion (top stories, hot topics, most commented) */
function loadAccordions() {
	var moduleLists = $('module_lists');
	if (moduleLists) {
		if ($$('accordion_toggle', moduleLists).size() > 0) {
			var photo_categories = new accordion('#module_lists', {
				onEvent: 'mouseover'
			});
			photo_categories.activate($$('#module_lists .accordion_toggle')[0]);
		}
	}
}
Event.observe(window, 'load', loadAccordions, false);

/* podcast player */
function loadPodcastPlayer() {
	var podcastModule = $('module_podcast');
	if (podcastModule) {
		if ($$('.podcast_toggle').size() > 0) {
			var podcast_row = new accordion('module_podcast', {
				classNames : {
					toggle : 'podcast_toggle',
					toggleActive : 'podcast_toggle_active',
					content : 'accordion_content'
				},
				onEvent: 'mouseover'
			});
			podcast_row.activate($$('#module_podcast .podcast_toggle')[0]);
		}
	}
}
Event.observe(window, 'load', loadPodcastPlayer, false);

/* load in-blog brightcove videos on demand */
function loadInBlogVideo(id) {
	$('inBlogVideo_'+id).update('<embed src="http://services.brightcove.com/services/viewer/federated_f8/1396519019" bgcolor="#FFFFFF" flashVars="videoRef='+id+'&playerId=1396519019&viewerSecureGatewayURL=https://services.brightcove.com/services/amfgateway&servicesURL=http://services.brightcove.com/services&cdnURL=http://admin.brightcove.com&domain=embed&autoStart=true&" base="http://admin.brightcove.com" name="flashObj" width="425" height="366" seamlesstabbing="false" type="application/x-shockwave-flash" swLiveConnect="true" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" wmode="transparent"></embed>');
}

// CSS Browser Selector   v0.2.5
// Documentation:         http://rafael.adm.br/css_browser_selector
// License:               http://creativecommons.org/licenses/by/2.5/
// Author:                Rafael Lima (http://rafael.adm.br)
// Contributors:          http://rafael.adm.br/css_browser_selector#contributors
// used for font difference between mac/pc in right column modules
var css_browser_selector = function() {
	var
		ua=navigator.userAgent.toLowerCase(),
		is=function(t){ return ua.indexOf(t) != -1; },
		h=document.getElementsByTagName('html')[0],
		b=(!(/opera|webtv/i.test(ua))&&/msie (\d)/.test(ua))?('ie ie'+RegExp.$1):is('gecko/')? 'gecko':is('opera/9')?'opera opera9':/opera (\d)/.test(ua)?'opera opera'+RegExp.$1:is('konqueror')?'konqueror':is('applewebkit/')?'webkit safari':is('mozilla/')?'gecko':'',
		os=(is('x11')||is('linux'))?' linux':is('mac')?' mac':is('win')?' win':'';
	var c=b+os+' js';
	h.className += h.className?' '+c:c;
}();




//---------------------------  COMMENTS JS STUFF  --------------------------------

// COMMENTS: an object containing functions and attributes necessary to
// handle the progressive AJAX loading of comments
//
// NOTE: Also checks to see if comments exist and only performs
// 		the functionality if they were detected on the page!
//
// Charlie Markovich - 5/12/08

var memberId = null;
var contentId = null;

/*** captcha related ***/
var coID;


/*** required for comment retrieval ***/
var totalCommentsFound = 0;
var totalCommentsShowing = 50;
var totalCommentsPosted = 0;
var commentSetSize = 50; // Total comments limit set per query

/*** how to load first set (server-side vs ajax) ***/
var loadInitialSet = false; // if false, will load via ajax
if (loadInitialSet == false) { totalCommentsShowing = 0; }

/*** store the form submission link ***/
var submitActive = false;


// an easier way to stick in a captcha (with room for improvement)
Captcha = {
	Load: function(el) {
		if($(el)){
			var captchaID = (Math.floor(Math.random()*191))+1;
			$(el).innerHTML = '<img src="http://images.eonline.com/static/redcarpet/globes2007/everywhere/shoutouts/images/'+captchaID+'.jpg" border="0" alt="" />'
							+ '<input type="hidden" value="'+captchaID+'" id="'+el+'_captchaID" class="hidden" />';
		}
	}
}

Comments = {
	/*AddFormDescriptors: function() {
		// adds form descriptors in the input fields themselves
		if ($('comment_guest')) {
			$('name').value = nameDescriptor;
			Event.observe('name', 'focus', function() {
				$('name').value = '';
			});
			Event.observe('name', 'blur', function() {
				if ($('name').value == '') {
					$('name').value = nameDescriptor;
				}
			});

			$('uword').value = uwordDescriptor;
			Event.observe('uword', 'focus', function() {
				$('uword').value = '';
			});
			Event.observe('uword', 'blur', function() {
				if ($('uword').value == '') {
					$('uword').value = uwordDescriptor;
				}
			});
		}
	},*/
	ChangeButtonStatus: function(memberSubmit, nonMemberSubmit) {
		// changes submit button text depending on if user is logging in or not
		var buttonText = document.getElementById("anonPostButton");
		if (document.user_comments.passwd.value.length > 0) {
			buttonText.innerHTML = memberSubmit;
		} else {
			buttonText.innerHTML = nonMemberSubmit;
		}
	},
	DisableSubmitButton: function(posting) {
		$("anonPostButton").innerHTML = posting;
		$("comment_text").addClassName("disabled");
	},
	EnableSubmitButton: function(postBtn) {
		$("anonPostButton").innerHTML = postBtn;
		$("comment_text").removeClassName("disabled");
	}
}

//To send/edit a comment
PostComments = {

	Save: function(blog, url, contentDBID, memberId, commentId, thanksMessage, postButton, yourName, enterCode, posting, mustEnterComment, mustEnterUsername, mustEnterCaptcha) {
		if(submitActive != true) {	// check to see if a submission is already taking place
			submitActive = true;
			Comments.DisableSubmitButton(posting);	// disable the submit button to prevent duplicate submissions
			var isMemberComment = false;
			var isValid = true;
			if ($('comments_message')) {
				$('comments_message').remove();
			}
		    Delete_Cookie("PostCookie","/",".eonline.com");
			Set_Cookie("PostCookie",coID,5,"/",".eonline.com");
			var captchaId = '';
			var captchaEntry = '';
			if ($('uword')) {
				captchaEntry = hex_md5(document.getElementById('uword').value);
				captchaId = $F('comment_captcha_captchaID');
			}
			if($('commentTextArea').value == '') {
				alert(PostComments.HtmlEntityDecode(mustEnterComment));
				isValid = false;
			}
			var nextIndex = parseInt(totalCommentsFound)+1+totalCommentsPosted;
			var pars = 'mode=save'+'&contentDBID='+escape(contentDBID)+'&commentId='+escape(commentId)
					  +'&memberId='+escape(memberId)+'&pageURL='+escape(url)+'&blog='+escape(blog)+'&nextIndex='+escape(nextIndex)
					  +'&captchaId='+escape(captchaId)+'&comment='+escape($('commentTextArea').value);
			if($('usrEmail') && $('passwd')) {
				if ($('passwd').value != '') isMemberComment = true;
				pars= pars+'&memberEmail='+$('usrEmail').value+'&password='+$('passwd').value;
			}
			if ($('name') && !isMemberComment) {
				if($('name').value == yourName) {
					alert(PostComments.HtmlEntityDecode(mustEnterUsername));
					isValid = false;
					Comments.EnableSubmitButton(postButton);	// enable the submit button to allow submitting again
					submitActive = false;
				}
				if($('uword').value == enterCode || $('uword').value == '') {
					alert(PostComments.HtmlEntityDecode(mustEnterCaptcha));
					isValid = false;
					Comments.EnableSubmitButton(postButton);	// enable the submit button to allow submitting again
					submitActive = false;
				}
				pars= pars+'&username='+$('name').value+'&captcha='+captchaEntry;
			}
			if(isValid) {
				new Ajax.Updater('comments_set', '/uberblog/includes/jsp/editComment.jsp?'+pars, {
					method:'post',
					postBody:pars,
					insertion: Insertion.Bottom,
					onComplete: function() {
						Captcha.Load('comment_captcha');	// reload the captcha after a submission
						if ($('uword')) $('uword').value = '';				// clear the captcha word field
						new Effect.Highlight('comments_message');
					},
					onSuccess: function() {
						$('commentTextArea').value = '';	// clear the textarea
						totalCommentsPosted++;
						$$('.total_comments').each(function(e) {
							e.update(parseInt(totalCommentsFound)+1);
						});
						if(isMemberComment) {
							$('comment_guest').hide();
							$('comment_member').hide();
						};
						alert(PostComments.HtmlEntityDecode(thanksMessage));
						Comments.EnableSubmitButton(postButton);	// enable the submit button to allow submitting again
						submitActive = false;
					},
					onFailure: function() {
						Comments.EnableSubmitButton(postButton);	// enable the submit button to allow submitting again
						submitActive = false;
					}
				});
			}
		}
	},
	Delete: function(commentId) {
		var pars = 'commentId='+commentId+'&mode=delete';
		new Ajax.Request('/uberblog/includes/jsp/editComment.jsp?'+pars);
	},
	ReportAbuse: function(commentId, thankYouInput, commentReported, confirmReport1, confirmReport2) {
		var confirmReport = confirmReport1 + "\n\n" + confirmReport2;
		var pars = 'commentId='+commentId+'&mode=report';
		if (confirm(PostComments.HtmlEntityDecode(confirmReport))) {
			new Ajax.Request('/uberblog/includes/jsp/editComment.jsp?'+pars, {
				onComplete: function() {
					alert (PostComments.HtmlEntityDecode(thankYouInput));
					$('report_'+commentId).update(PostComments.HtmlEntityDecode(commentReported));
					$('report_'+commentId).removeAttribute('href');
					$('report_'+commentId).addClassName('reported');
				}
			});
		}
	},
	GiveProps: function(commentId) {
		var pars = 'commentId='+commentId+'&mode=props';
		new Ajax.Request('/uberblog/includes/jsp/editComment.jsp?'+pars);
	},
	HtmlEntityDecode: function (str) {		  
		var ta=document.createElement("textarea");
		ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
		return ta.value;
	}
}

GetComments = {

	CalculateNextSetSize: function(){
		// check to see if the comments remaining are less than the commentSetSize
		var commentsRemaining = totalCommentsFound - totalCommentsShowing;
		if (commentsRemaining < commentSetSize) {
			commentSetSize = commentsRemaining;
		}
	},

	GetNextPage: function(){
		contentId = $('contentId').value; // Get content Id from dom hidden field
		memberId = $('memberId').value; // Get content Id from dom hidden field

		GetComments.CalculateNextSetSize();

		// Update the list with additional comments found
		new Ajax.Updater('display_next_set', '/uberblog/chatter/includes/jsp/getPageOfComments.jsp', {
			method: 'get',
			insertion: Insertion.Before,
			onComplete: function(){
				GetComments.TogglePreloader();
			},
			parameters: {offset: totalCommentsShowing, length: commentSetSize, memberId: memberId, contentId: contentId}
		});

		// increment total comments showing count
		totalCommentsShowing = totalCommentsShowing + commentSetSize;

		//Set the link text
		var linkText = "Im empty";
		var commentsRemaining = 0;
		if (totalCommentsShowing < totalCommentsFound){
			GetComments.CalculateNextSetSize();
			linkText = "Show the next " + (totalCommentsShowing + 1) + " - " + (totalCommentsShowing + commentSetSize) + " of " + totalCommentsFound + " comments";
			$('display_next_link').innerHTML = linkText;
		} else {
			$('display_next_set').hide();
		}
	},

	// If more comments available then display the preloader animation
	TogglePreloader : function(/*resultsShowing, totalResults*/){
		if ($('preloader_graphic').style.display == "block"){
			$('preloader_graphic').style.display = 'none';
		} else {
			$('preloader_graphic').style.display = 'block';
		}
	}
}

// Register the listeners after the page has been fully loaded
Event.observe( window, 'load', function() {
	// Determine if comments are on the page or not
	// if not then don't execute the following code
	if ($('comments_set')){
		totalCommentsFound = $('totalComments').value;

		// Register the event listener for the more comments button
		// if there is another set to load
		if ($('display_next_link')) {
			Event.observe('display_next_link', 'click', function() {
				GetComments.TogglePreloader();
				GetComments.GetNextPage(); // Add comments to the list
			});
		};

		// load first set via ajax if not loaded server-side
		if (loadInitialSet == false && totalCommentsFound > 0) {
			GetComments.TogglePreloader();
			GetComments.GetNextPage();
		}

		// Load captcha
		Captcha.Load('comment_captcha');

		// load form field descriptors
		//Comments.AddFormDescriptors();
	}
});

//------------------------Cookie Stuff---------------------------
function Get_Cookie( 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 ) );
}

	// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) {
	if ( Get_Cookie( name ) ) document.cookie = name + "=" + ( ( path ) ? ";path=" + path : "") + ( ( domain ) ? ";domain=" + domain : "" ) + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
function Set_Cookie(cookieName,cookieValue,nDays, path, domain) {
 	var today = new Date();
 	var expire = new Date();
 	if (nDays==null || nDays==0) nDays=1;
 		expire.setTime(today.getTime() + 3600000*24*nDays);
 		document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString()+";path="+path+";domain="+domain;
}
//----------------------End Cookie Stuff---------------------------


//------------------------window reload on interval---------------------------
function refreshiframe(iframe,milli) {
    var refresh = $(iframe);
	setTimeout("refreshiframe('"+iframe+"','"+milli+"')", milli);
	refresh.src=refresh.src;

}
//----------------------End window reload on interval---------------------------
