//---------- usage:
// var shortener = new URLShortener(); 
// shortener.shorten(urlToShorten, callback);
//
// (the shortened bit.ly url will be passed as the first argument to the callback supplied.);
// eg: shortener.shorten("http://facebook.com", function(data){alert(data)});

function URLShortener() {
    urlscope                    = this;
	urlscope.bitlyLogin         = "alfagiulietta";
	urlscope.bitlyKey           = "R_b85ac2032e7c7cddaa67868d2fcadae2";
	urlscope.bitlyShortenURL    = "http://api.bit.ly/shorten?version=2.0.1&login=" + urlscope.bitlyLogin + "&apiKey=" + urlscope.bitlyKey + "&longUrl=";
    urlscope.bitlyExpandURL     = "http://api.bit.ly/expand?version=2.0.1&login=" + urlscope.bitlyLogin + "&apiKey=" + urlscope.bitlyKey + "&shortUrl=";
}


URLShortener.prototype.shorten = function(longURL,callback) {

	$.getJSON(urlscope.getShortenServiceURL(longURL), function(data){callback(urlscope.shortenResponseHandler(data))});
}

URLShortener.prototype.getShortenServiceURL = function(longURL) {
	return urlscope.bitlyShortenURL + encodeURIComponent(longURL) + "&callback=?";
}

URLShortener.prototype.expand = function(shortURL,callback) {
	$.getJSON(urlscope.getExpandServiceURL(shortURL), function(data){callback(urlscope.expandResponseHandler(data))});
}

URLShortener.prototype.getExpandServiceURL = function(shortURL) {
	return urlscope.bitlyExpandURL + encodeURIComponent(shortURL) + "&callback=?";
}

URLShortener.prototype.shortenResponseHandler = function(data){

	if (data.statusCode == "OK") {
		for (var x in data.results) {
			var result = data.results[x];
			var shortUrl = result.shortUrl;
			var userHash = result.userHash;
			return shortUrl;
		}
	} else {
	    // log?
	}
}

URLShortener.prototype.expandResponseHandler = function(data){
	if (data.statusCode == "OK") {
		for (var x in data.results) {
			var result = data.results[x];
			var longUrl = result.longUrl;
			var userHash = result.userHash;
			return longUrl;
		}
	} else {
	    // log?
	}
}
