var fbcUrl = 'http:\/\/'+location.host+location.pathname;
var fbcPath = location.pathname;
var galleryLikeURL = '';
var cnnIE = (navigator.userAgent.toLowerCase().indexOf('msie') == -1)?false:true;
var cnnIE6 = (navigator.userAgent.toLowerCase().indexOf('msie 6') == -1)?false:true;
var cnnFF = (navigator.userAgent.toLowerCase().indexOf('firefox') == -1)?false:true;
var cnnChrome = (navigator.userAgent.toLowerCase().indexOf('chrome') == -1)?false:true;
var fbcTitle = document.title;
var fbcNumposts = 10;
var twitterSource = 'CNNMoney&related=LaMonicaBuzz:Get breaking incisive market commentary from CNNMoney.com';
var linkedInSource = 'CNNMoney';
var cnnSocialDescription = '';
var linkedInLoaded = false;

var h1s = document.getElementsByTagName('h1');
if(fbcUrl.indexOf('bestcompanies/2011/snapshots')!=-1){
	cnnSocialDescription = encodeURIComponent(document.title);
}
else if(h1s.length == 1){
	cnnSocialDescription = encodeURIComponent(h1s[0].innerHTML.replace(/<(?:.|\s)*?>/g,''));
}
else{
	var metas = document.getElementsByTagName('meta');
	for(var m = 0; m < metas.length; m++ )
	{
		if(metas[m].name.toLowerCase() == "description"){
			if(metas[m].content != ""){
				cnnSocialDescription = encodeURIComponent(metas[m].content);
				break;
			}
			else{
				cnnSocialDescription = encodeURIComponent(document.title);
				break;
			}
		}
	}
}

if(fbcUrl.indexOf('.fortune')!=-1) { twitterSource = 'FortuneMagazine'; linkedInSource = 'Fortune Magazine'; }
//if(fbcUrl.indexOf('.moremoney.blogs' )!=-1 || fbcUrl.indexOf('moneymag' )!=-1) { twitterSource = 'MoneyMagazine'; }

if (fbcPath.match('gallery|video')) { fbcNumposts = 5; }

/* Galleries and Quizzes have multiple pages, so they should all be represented by the same url for digg, facebook, + tweetmeme */
try{
if (fbcPath.match('gallery')||fbcPath.match('quizzes')) {
	if(fbcUrl.indexOf('index.html')!=-1)
		galleryLikeURL = fbcUrl;
	else if(fbcUrl.indexOf('.html')!=-1){	//drop off everything after the last '/' and append /index.html 
		var lastPos = fbcUrl.lastIndexOf('\/');
		galleryLikeURL = fbcUrl.substring(0,lastPos)+'/index.html';
	}
	else{
			if(fbcUrl.charAt(fbcUrl.length-1)=='/'){ galleryLikeURL=fbcUrl+'index.html' }
			else{ galleryLikeURL=fbcUrl+'/index.html' }
	}
	try{
		if (fbcUnique==true) {
			var fbcXid = fbcPath;
			fbcXid = fbcXid.replace('\.html','');
			fbcXid = fbcXid.replace('index','');
			fbcXid = fbcXid.replace(/\//g,'\_');
		} else { var fbcXid = fbcPath.substr(1, fbcPath.lastIndexOf('\/')-1); fbcXid = fbcXid.replace(/\//g,'\_'); }
	}catch(e){ var fbcXid = fbcPath.substr(1, fbcPath.lastIndexOf('\/')-1); fbcXid = fbcXid.replace(/\//g,'\_'); }
	fbcUrl = galleryLikeURL;
} else if (fbcPath.match('bplive/2010/snapshots') && typeof cityId != 'undefined') {
	        var fbcXid = fbcPath.substr(1, fbcPath.lastIndexOf('.html')-1);
	        fbcXid = fbcXid.replace(/\//g,'\_');
} else if (fbcPath.match('bestjobs/2010/snapshots') && typeof jobId != 'undefined') {
	        var fbcXid = fbcPath.substr(1, fbcPath.lastIndexOf('.html')-1);
	        fbcXid = fbcXid.replace(/\//g,'\_');
} else if (typeof cnnmCommentId != 'undefined') {
                var fbcXid = fbcPath.substr(1, fbcPath.lastIndexOf('.html')-1);
		fbcXid = fbcXid.replace(/\//g,'\_');	
} else {
	var fbcXid = fbcPath.substr(1, fbcPath.lastIndexOf('\/')-1);
	fbcXid = fbcXid.replace(/\//g,'\_');
}
}catch(e){}
//CSUITE comments
try{
        if(typeof cnnCSuiteMedia.fb_id != null){ fbcXid = cnnCSuiteMedia.fb_id.replace(/\//g,'\_'); }
}catch(e){}


function removeFBIE6(){
	try { if( document.getElementById('cnnfb_connect')!= null ) document.getElementById('cnnfb_connect').style.display = "none"; }catch(e){}
	try { if( document.getElementById('fb-activity')!= null ) document.getElementById('fb-activity').style.display = "none"; }catch(e){}
	try { if( document.getElementById('fb-recommend')!= null ) document.getElementById('fb-recommend').style.display = "none"; }catch(e){}
	try { if( document.getElementById('shareIE2')!= null ) document.getElementById('shareIE2').style.display = "none"; }catch(e){}
	try { if( document.getElementById('social-share-video')!= null ) document.getElementById('social-share-video').style.display = "none"; }catch(e){}
	try { if( document.getElementById('quiz-share-widget')!= null ) document.getElementById('quiz-share-widget').style.display = "none"; }catch(e){}
	try { if( document.getElementById('gallery-share-widget')!= null ) document.getElementById('gallery-share-widget').style.display = "none"; }catch(e){}
	try { if( document.getElementById('blog-share-widget')!= null ) document.getElementById('blog-share-widget').style.display = "none"; }catch(e){}
}

function addFBActivity(){
	if( !jQuery.belowthefold('#fb-activity',{threshold : 0, container: window}) ) {
		try{ jQuery(window).unbind('scroll', addFBActivity); }catch(e){}
		var e = document.createElement('script');
		e.type = 'text/javascript';
		e.src = 'http://connect.facebook.net/en_US/all.js';
		e.async = true;
		document.getElementById('fb-root').appendChild(e);
	}
}
function addFBComments(){
	if( !jQuery.belowthefold('#cnnfb_connect',{threshold : 0, container: window}) ) {
		jQuery(window).unbind('scroll', addFBComments)
		try { document.getElementById('cnnfb_connect').innerHTML = '<fb:comments width="455" numposts="'+fbcNumposts+'" candelete="true" canpost="true" url="'+fbcUrl+'" title="'+fbcTitle+'" xid="'+fbcXid+'" quiet="true" simple="1" css="http://i.cdn.turner.com/money/.element/ssi/css/1.0/fbcomments.css"></fb:comments>'; }catch(e){}
		FB.XFBML.parse();
	}
}
function getFBShareCount()
{
	//if(fbShareAttempts>2){ return; }
	//fbShareAttempts++;
	FB.api({ method: 'fql.query', query: 'SELECT share_count FROM link_stat WHERE url="'+fbcUrl+'"'}, function(response) {
		//try{ console.log(response); }catch(e){}
		if(!isNaN(response[0].share_count)){
			try{ addFBShareCount(response[0].share_count); }catch(e){}
		}
		//else{
			//getFBShareCount();
		//}
	});
}
function addFBShareCount(share_count){
	var fbcount = parseInt(share_count);
	if(fbcount < 10000 )
		document.getElementById('fb-share-counter-link').innerHTML = fbcount;
	else if(fbcount < 1000000)
		document.getElementById('fb-share-counter-link').innerHTML = Math.round(fbcount/1000)+'K';
	else
		document.getElementById('fb-share-counter-link').innerHTML = Math.round(fbcount/1000000)+'M';	
}
function addLIShareCount(count) {
	document.getElementById('linkedin-share-counter').getElementsByTagName('a')[0].className = "";
	var licount = parseInt(count);
	if( (licount == 0)||(isNaN(licount)) )
		document.getElementById('linkedin-share-counter').getElementsByTagName('a')[0].className = "linked";
	else if(licount < 10000)
		document.getElementById('linkedin-share-counter').getElementsByTagName('a')[0].innerHTML = count;
	else if(licount < 1000000)
		document.getElementById('linkedin-share-counter').innerHTML = Math.round(fbcount/1000)+'K';
	else
		document.getElementById('linkedin-share-counter').innerHTML = Math.round(fbcount/1000000)+'M';
}
function callLIAPI() {
	try{ IN.Tags.Share.getCount(fbcUrl, addLIShareCount); }catch(e){ document.getElementById('linkedin-share-counter').getElementsByTagName('a')[0].className = "linked"; }
}
function getLIShareCount() {
	if(linkedInLoaded) return;
	linkedInLoaded = true;
	setTimeout(callLIAPI,1000);
}

//FB Callback Function
window.fbAsyncInit = function() {

	FB.init({apiKey : '64b385429f05b2492d713f343d05ba02',status : true,cookie : true,xfbml : true});
	
	//FB Activity Widget
	if( document.getElementById('fb-activity')!= null )
		document.getElementById('fb-activity').innerHTML = '<div class="boxHeading">Facebook Activity</div><fb:activity site="money.cnn.com" width="334" height="274" header="false" border_color="#ffffff"></fb:activity>';

	//FB Like
	if(galleryLikeURL != ''){
		try{ document.getElementById('fb-recommend').innerHTML = '<fb:like action="recommend" href="'+galleryLikeURL+'" background="none" show_faces="false" width="450" layout="standard" ref="fbLike"></fb:like>'; }catch(e){}
		try{ document.getElementById('fb-recommend-widget').innerHTML = '<fb:like action="recommend" href="'+galleryLikeURL+'" background="none" show_faces="false" width="315" layout="standard" ref="fbLike"></fb:like>'; }catch(e){}
	}
	else{
		if( document.getElementById('fb-recommend')!= null ) {
			//Best Places to Live or any page with a short FB Like Button
			if(document.getElementById('fb-recommend').className=="button_count") {
				try{ document.getElementById('fb-recommend').innerHTML = '<fb:like action="recommend" href="'+fbcUrl+'" background="none" show_faces="false" layout="button_count" ref="fbLike"></fb:like>'; }catch(e){}
			}
			else {
				try{ document.getElementById('fb-recommend').innerHTML = '<fb:like action="recommend" href="'+fbcUrl+'" background="none" show_faces="false" width="450" layout="standard" ref="fbLike"></fb:like>'; }catch(e){}
			}
		}
		try{ document.getElementById('fb-recommend-widget').innerHTML = '<fb:like action="recommend" href="'+fbcUrl+'" background="none" show_faces="false" width="315" layout="standard" ref="fbLike"></fb:like>'; }catch(e){}
	}
		
	//FB Share Button
	try{ document.getElementById('fb-share-counter').innerHTML = '<a href="http://www.facebook.com/sharer.php?u='+escape(fbcUrl)+'&t='+escape(fbcTitle)+'" id="fb-share-counter-link" target="_blank" onclick="if(document.getElementById(\'fb-share-counter-link\').innerHTML==\'9999\')document.getElementById(\'fb-share-counter-link\').innerHTML=\'10K\';else if((document.getElementById(\'fb-share-counter-link\').innerHTML.indexOf(\'K\')==-1)&&(document.getElementById(\'fb-share-counter-link\').innerHTML.indexOf(\'M\')==-1))document.getElementById(\'fb-share-counter-link\').innerHTML = parseInt(document.getElementById(\'fb-share-counter-link\').innerHTML)+1;"></a>'; }catch(e){}

	//FB Share Count
	try{
		if( document.getElementById('fb-share-counter')!= null ){
			getFBShareCount();
		}
	}catch(e){}

	//Twitter Button
	try{ document.getElementById('twitter-share-counter').innerHTML = '<iframe id="twitter-iframe" src="http://platform.twitter.com/widgets/tweet_button.html?via='+twitterSource+'&text='+cnnSocialDescription+'&count=vertical&url='+encodeURIComponent(fbcUrl)+'" frameborder="0" height="63" scrolling="no" width="55"></iframe>'; }catch(e){}

	//LinkedIn API
	try{
		if(fbcUrl.indexOf('/video')==-1)
		{
			try{
				var sctag = document.createElement("script");
				sctag.setAttribute("type","text/javascript");
				sctag.setAttribute("src","http://platform.linkedin.com/in.js");
				document.getElementsByTagName("head")[0].appendChild(sctag);
			}catch(e){}
			try{ sctag.onload = getLIShareCount; }catch(e){}
			try{ sctag.onreadystatechange = getLIShareCount; }catch(e){}
		}
	}catch(e){}

	//LinkedIn Button
		try{ document.getElementById('linkedin-share-counter').innerHTML = '<a href="http://www.linkedin.com/shareArticle?mini=true&source='+linkedInSource+'&url='+encodeURIComponent(fbcUrl)+'&title='+cnnSocialDescription+'" onclick="if(this.innerHTML==\'9999\')this.innerHTML=\'10K\';else if((this.innerHTML.indexOf(\'K\')==-1)&&(this.innerHTML.indexOf(\'M\')==-1)&&(this.innerHTML!=\'\'))this.innerHTML = parseInt(this.innerHTML)+1;" target="_blank"></a>' }catch(e){}

	//Best Jobs Share Buttons
	try{
		if( document.getElementById('best-jobs-share') != null ){
			var bestContainer = document.getElementById('best-jobs-share');
			var LIs = bestContainer.getElementsByTagName('li');
			LIs[1].innerHTML = '<iframe title="'+cnnSocialDescription+'" style="width: 55px; height: 20px;" src="http://platform.twitter.com/widgets/tweet_button.html?count=none&amp;text='+cnnSocialDescription+'&amp;url='+encodeURIComponent(fbcUrl)+'" allowtransparency="true" tabindex="0" class="twitter-share-button twitter-count-vertical" frameborder="0" scrolling="no"></iframe>';
			LIs[2].className = 'last';
			LIs[2].innerHTML = '<fb:like href="'+fbcUrl+'" background="none" show_faces="false" layout="button_count" ref="fbLike"></fb:like>';
		}
	}catch(e){}

	//Comments
	try{
		if( document.getElementById('cnnfb_connect')!= null && (galleryLikeURL != '' || fbcPath.indexOf('bplive')!=-1 || (typeof cnnCSuiteMedia.fb_id != null) ) ){
			try { document.getElementById('cnnfb_connect').innerHTML = '<fb:comments width="550" numposts="'+fbcNumposts+'" candelete="true" canpost="true" url="'+fbcUrl+'" title="'+fbcTitle+'" xid="'+fbcXid+'" quiet="true" simple="1" css="http://i.cdn.turner.com/money/.element/ssi/css/1.0/fbcomments.css"></fb:comments>'; }catch(e){}
		}
	}catch(e){}
	try{	
		if( document.getElementById('cnnfb_connect')!= null && typeof cnnmCommentId != 'undefined' ){
			try { document.getElementById('cnnfb_connect').innerHTML = '<fb:comments width="550" numposts="'+fbcNumposts+'" candelete="true" canpost="true" url="'+fbcUrl+'" title="'+fbcTitle+'" xid="'+fbcXid+'" quiet="true" simple="1"></fb:comments>'; }catch(e){}
		}
	}catch(e){}	

	FB.XFBML.parse();
};

(function() {
	try{
		if(!cnnIE6) {
			if( document.getElementById("fb-root")== null && !cnnIE ){
				var fbroot = document.createElement("div");
				fbroot.setAttribute("id","fb-root");
				document.body.appendChild(fbroot);
			}
			else if( document.getElementById("fb-root")== null && cnnIE )
			{
				try{
					document.write('<div id="fb-root"></div>');
				}catch(e){}
			}
			if((!cnnFF) && (location.host!='tech.fortune.cnn.com')){
				var e = document.createElement('script');
				e.type = 'text/javascript';
				e.src = 'http://connect.facebook.net/en_US/all.js';
				e.async = true;
				document.getElementById('fb-root').appendChild(e);
			}
			else{
				try{
					jQuery(document).ready(function(){
						var e = document.createElement('script');
						e.type = 'text/javascript';
						e.src = 'http://connect.facebook.net/en_US/all.js';
						e.async = true;
						document.getElementById('fb-root').appendChild(e);
					});
				}catch(e){ 
					var e = document.createElement('script');
					e.type = 'text/javascript';
					e.src = 'http://connect.facebook.net/en_US/all.js';
					e.async = true;
					document.getElementById('fb-root').appendChild(e); 
				}
			}
		}
		else {
			removeFBIE6();
		}
	}catch(e){}
}());

