// ==UserScript==
// @name           Vox to Twitter
// @namespace      vox.com
// @include        http://www.vox.com/compose/posted*
// ==/UserScript==
var TWITTERAUTH = 'YOUR AUTH HERE';

var postLink;
var tinyURL;
var postTitle;

if (window.confirm("Tweet?")) {
	getPostTitle();
}

function getPostTitle(){
	// Get the URL of the post
	postLink = document.getElementsByClassName('list-icon-1')[0].childNodes[0].href;

	// Get the post title
	GM_xmlhttpRequest ({	method: 'GET',
					url: postLink, 
					onreadystatechange: function(responsedetails) {
						if (responsedetails.readyState == 4) {
							if (responsedetails.status == 200) {
								//pull the post title out of the response
								var parser = new DOMParser();
								var seResponse = parser.parseFromString(responsedetails.responseText, "application/xhtml+xml");
								postTitle = seResponse.getElementsByTagName("title")[0].childNodes[0].wrappedJSObject.data;
								postTitle = postTitle.replace(/ - Vox/, '');
								postTitle = postTitle.substring(0,90); //so it's not too long for the tweet
								console.log ("Title: " + postTitle);
								tinify();
							} 
							else {
								console.log ("Failed to get the Post Title.");
							}
						}
					}
				});
};
			
// Tinify it
function tinify () {
	GM_xmlhttpRequest ({	method: 'GET',
					url: 'http://tinyurl.com/api-create.php?url=' + postLink, 
					onreadystatechange: function(responsedetails) {
						if (responsedetails.readyState == 4) {
							if (responsedetails.status == 200) {
								tinyURL = responsedetails.responseText;
								console.log ("Tiny URL: " + tinyURL);
								postToTwitter(tinyURL);
							} 
							else {
								console.log ("Failed to get Tiny URL");
							}
						}
					}
				});
}
			

function postToTwitter(tinyURL) {
	GM_xmlhttpRequest ({	method: 'POST',
					url: 'http://twitter.com/statuses/update.xml',
					headers: {'Authorization':'Basic ' + TWITTERAUTH,
								'Content-type':'application/x-www-form-urlencoded'},
					data: 'status="' + urlencode('Blogging \"' + postTitle + '\" on Vox - ' + tinyURL) + '"', 
					onload: function(responseDetails){
						alert ("Done Tweeting");
					}
				});	
}

function urlencode(str) {
return escape(str).replace(/\+/g,'%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/@/g, '%40');
}
