// $Id: articleShare.js 5367 2008-09-18 22:28:38Z ccorliss $

function showHideSwap (id1, id2) {
	if (document.getElementById) {
		if (document.getElementById(id1).className == 'hide' && document.getElementById(id2).className == 'post') {
			document.getElementById(id1).className = 'show';
			document.getElementById(id2).className = 'postFrame';
		} else {
       		     	document.getElementById(id1).className = 'hide';
            		document.getElementById(id2).className = 'post';
		}
	}
}

function articleShare(site) {
	var popUpUrl;
    var title = getShareHeadline();
    var description = getShareDescription();
	switch (site) {
	case "newsvine":
		popUpUrl = generatePasskeyURL('newsvine');
		var keywords = getShareSection(); 
		if(typeof(getShareSubSection) == 'function') {
			if(getShareSubSection() != '') {
				keywords = keywords + ',' + getShareSubSection();
			}
		}
		if (getShareKeywords() != '') {
			keywords = keywords + ',' + getShareKeywords();
		}
		postPopUp('http://www.newsvine.com/_wine/save?ver=2&popoff=0&aff=nytimes&t=' + keywords + '&e=' + description + '&h=' + title + '&u=' + popUpUrl, 'newsvine', 'toolbar=0,status=0,height=445,width=650,scrollbars=yes,resizable=yes');
		s_code_linktrack('Article-Tool-Share-Newsvine');
		break;
	case "facebook":
		popUpUrl = generatePasskeyURL('facebook');
		postPopUp('http://www.facebook.com/sharer.php?u=' + popUpUrl + '&t=' + title, 'facebook', 'toolbar=0,status=0,height=436,width=646,scrollbars=yes,resizable=yes');
		s_code_linktrack('Article-Tool-Share-Facebook');
		break;
	case "digg":
		popUpUrl = generatePasskeyURL('digg');
		var topic = getShareSection();	
		postPopUp('http://digg.com/remote-submit?phase=2&url=' + popUpUrl + '&title=' + title + '&bodytext=' + description, 'digg', 'toolbar=0,status=0,height=450,width=650,scrollbars=yes,resizable=yes');
		s_code_linktrack('Article-Tool-Share-Digg');
		break;	
	case "permalink":
		popUpUrl = generatePasskeyURL('permalink');
		var section = getShareSectionDisplay();
		var byline = getShareByline();
		var pubdate = getSharePubdate();	
		postPopUp('http://www.nytimes.com/export_html/common/new_article_post.html?url=' + popUpUrl + '&title=' + title+ '&summary=' + description + '&section=' + section + '&pubdate=' + pubdate + '&byline=' + byline, 'permalink', 'toolbar=0,status=0,height=410,width=490,scrollbars=yes,resizable=no');
		s_code_linktrack('Article-Tool-Share-Permalink');
		break;	
	case "delicious":
		popUpUrl = generatePasskeyURL('delicious');
		postPopUp('http://del.icio.us/post?v=4&partner=nyt&noui&jump=close&url=' + popUpUrl + '&title=' + title + '&bodytext=' + description, 'delicious', 'toolbar=0,status=0,height=400,width=700,scrollbars=yes,resizable=no');
		s_code_linktrack('Article-Tool-Share-Delicious');
		break;			

	case "yahoobuzz":
		// fall-back behavior.  At least it'll just open the page in a new window/tab, but not downsized.
    		postPopUp( 'http://buzz.yahoo.com/article/new_york_times/'
			    + encodeURIComponent(getShareURL()),
			    'yahoobuzz',
                         'scrollbars=yes,resizable=yes'
		);
		s_code_linktrack('Article-Tool-Share-YahooBuzz');
		break;			

	case "mixx":
		try {
		    var popUpUrl = getShareURL();
		    var passKey  = encodeURIComponent( '?' + getSharePasskey() );
		    var otherParams = 
			     '&title='       + getShareHeadline()
			   + '&description=' + getShareDescription()
			   + '&tags='        + getShareKeywords()
			   + '&partner='     + 'NYT';
		    postPopUp( 
			   'http://mini.mixx.com/submit/story'
			   + '?page_url='    + getShareURL()
			   + passKey 
			   + otherParams,
			   'mixx',
			   'toolbar=0,status=0,height=550,width=700,scrollbars=yes,resizable=no'
		    );
		} catch(e) {
		    postPopUp( 
			   'http://mini.mixx.com/submit/story'
			   + '?page_url='    + getShareURL()
			   + '&title='       + getShareHeadline()
			   + '&partner='     + 'NYT'
			   ,
			   'mixx',
			   'toolbar=0,status=0,height=550,width=700,scrollbars=yes,resizable=no'
		    );
		}
		s_code_linktrack('Article-Tool-Share-Mixx');
		break;
	case "linkedin":
	  //http://www.linkedin.com/shareArticle?mini=true&url={articleUrl}&title={articleTitle}&summary={articleSummary}&source={articleSource}
	  postPopUp(
	     'http://www.linkedin.com/shareArticle?mini=true'
		   + '&url='         + getShareURL()
		   + '&title='       + getShareHeadline()
		   + '&summary='     + description
		   + '&source='      + 'The New York Times'
		   ,
		   'Linkedin',
		   'toolbar=0,status=0,height=550,width=700,scrollbars=yes,resizable=no'
	  )
	  s_code_linktrack('Article-Tool-Share-LinkedIn');
	     break;
	}
}

function generatePasskeyURL(tracker) {
	var shareURL = getShareURL();
	var queryStr = (decodeURIComponent(shareURL).indexOf('?') > 0) ? "&" : "?";

        switch (tracker){
                case "permalink": break;
                default: var passkey = getSharePasskey(); queryStr += (passkey != '') ? passkey + "&" : "";
        }
        queryStr += 'partner=' + tracker;
        queryStr += '&exprod=' + tracker;

        return shareURL + encodeURIComponent(queryStr);
}

function postPopUp(url, name, params) {
	var win = window.open(url, name, params);
}

function addPostItem(parentElement, sharelinkName, sharelinkText) {
	var imageHost = "http://graphics8.nytimes.com";
	var imagePath = "/images/article/functions/";
	if( document.createElement ){
		if( typeof(window.shareToolsExcludeList)!='undefined'
		    && typeof(window.shareToolsExcludeList[sharelinkName])!='undefined' ) {
		    return;
		}
		var postItem = document.createElement("LI");
		postItem.className = sharelinkName;
		
		var itemLink = document.createElement("A");
		itemLink.setAttribute("href", "javascript:articleShare('"+ sharelinkName +"');");
		itemLink.style.backgroundImage = "url('" + imageHost + imagePath + sharelinkName + ".gif')";
		itemLink.innerHTML = sharelinkText;

		postItem.appendChild(itemLink);
		parentElement.appendChild(postItem);
	}
}

function writePost(excludeList) {
	
	if( document.createElement ){
		var parentElement = document.getElementById('toolsList');
		
		//create post li
		var postElement = document.createElement( "LI");
		postElement.className = "post";
		postElement.setAttribute("id", "post");
		// create post link
		var postLink = document.createElement("A");
		postLink.setAttribute("href", "#");
		//postLink.setAttribute("onClick", "showHideSwap(\'postList\', \'post\'); return false;");
		postLink.onclick = function () { showHideSwap('postList', 'post'); return false; };
		postLink.innerHTML = " Share";

		postElement.appendChild(postLink);
		
		// create unordered list for post items
		var postList = document.createElement("UL");
		postList.setAttribute("id","postList");	
		postList.className = "hide";

		// If excludeList is supplied, it's a hash keyed on vendor names
		// (CSS class names for the vendor links, actually)
		if(typeof(excludeList)!='undefined') {
		    window.shareToolsExcludeList = excludeList;
		}
		
		//add post links
		addPosts(postList);
		
		postElement.appendChild(postList); 
		parentElement.appendChild(postElement); 
		instrumentYahooBuzzBadge();
	}

}

function createYahooBuzzOnLoad() {
	
	// An event listener is attached once the badge is loaded so that 
	// function itself is separated from the dom ref via a closure to prevent IE 6 memory leakage.
	window.yahooBuzzOnLoad = function () {
		var onclick = function () {
			// this is the onclick handler that gets attached to the badge.
			s_code_linktrack('Article-Tool-Share-YahooBuzz');
		};
		return function () {
		    if(typeof(window['yahooBuzzOnLoad'])!='function') {
			    window.yahooBuzzOnLoad=null; // clean up the global.
		    }
			var badge = document.getElementById('yahooBuzzBadge-form');
			if ( badge ) {
				if ( badge.addEventListener ) {
					badge.addEventListener('click', onclick, true);
				} else if ( badge.attachEvent ) {
					badge.attachEvent('click', onclick);
				} else {
					// can't put an onclick directly, or it'll break the badge.
					// This is an edge case, so losing non-mousers is not very significant.
					badge.onmousedown = onclick;
				}
			}
		}
	}();
	
};

function instrumentYahooBuzzBadge() {
	
	if ( document.getElementById('yahooBuzzBadge') ) {
		// already instrumented. Abort.
		return;
	}
	
	var list = document.getElementById('postList');
	if ( !list ) {
		// haven't created the list yet. Abort.
		return;
	}
	
	createYahooBuzzOnLoad();
	
	var postLinks = list.getElementsByTagName('a');
	for ( var i = 0, l = postLinks.length; i < l; i ++ ) {
		var href = postLinks[i].href;
		href = href.toLowerCase();
		if ( href.indexOf('buzz') !== -1 && href.indexOf('yahoo') !== -1 ) {
			// works whether it's the real URL or the javascript: with yahoobuzz in the call.
			var badge = postLinks[i];
			badge.id = 'yahooBuzzBadge';
		}
	}
	
	// Y! Buzz requires its own script be included dynamically like this ...
	var artUriYahoo = decodeURIComponent(getShareURL());
	document.write(
	        '<script badgetype="text" src="http://d.yimg.com/ds/badge.js">new_york_times:'
		 + artUriYahoo
		 + '</script>'
	);
}

function addPosts(shareList) {	
		
		if(document.getElementById) {	
			var sList;
				
			if(typeof(shareList)=='string') {
				sList = document.getElementById(shareList); 
				}
			
			else if(typeof(shareList)=='object') { 
				sList = shareList;
			}
			
			else {
				return false;
			}

			addPostItem(sList, "linkedin", "Linkedin");
			addPostItem(sList, "digg", "Digg");
			addPostItem(sList, "facebook", "Facebook");
			addPostItem(sList, "mixx", "Mixx");
			addPostItem(sList, "yahoobuzz", "Yahoo! Buzz");
			addPostItem(sList, "permalink", "Permalink");
		}
}


function toggleShareTab(shareButton, postList, excludeList) {

	if(document.getElementById && document.getElementById(shareButton) && document.getElementById(postList)) {

		if(typeof(excludeList)!='undefined') {
		    window.shareToolsExcludeList = excludeList;
		}

		addPosts(postList);
		var shareSpan = document.getElementById(shareButton)
		var listContainer = document.getElementById(postList)
		var shareLink = shareSpan.getElementsByTagName("a")

		if(shareLink && listContainer){

			shareLink[0].onclick = function() {
				if(this.parentNode.className=="")
					{
					 this.parentNode.className="open";
					 listContainer.style.display="block";
					 return false;
					} else { this.parentNode.className="";
						 listContainer.style.display="none";
						 return false;
						}
			} 
		} 
	} 
	else return false;
}
