if (typeof(BitlyApi) == 'undefined')
    var BitlyApi = {}; // BitlyApi namespace. You sholdn't need to access methods here. Instead, use an instance of BitlyApiClient().

if (typeof(BitlyCB) == 'undefined')
    var BitlyCB = {}; // global namespace for your callback methods. Allows you to define callabacks from within other method calls.

BitlyApi.loadScript = function(_src) {
  var e = document.createElement('script');
  e.setAttribute('language','javascript');
  e.setAttribute('type', 'text/javascript');
  e.setAttribute('src',_src); document.body.appendChild(e);
}

BitlyApi.call = function(method, params, callback_method_name) {
    var s = "http://api.bit.ly/" + method;
    var url_args = [];
    if (callback_method_name) url_args.push("callback=" + callback_method_name);

    for (var name in params) {
        url_args.push(name + "=" + encodeURIComponent(params[name]));
    }

    s += "?" + url_args.join("&");
    BitlyApi.loadScript(s);
}

var BitlyApiClient = function(login, apiKey, version){
    this.login = login || "otmusers";	// TODO - defined in TwitterApiModel
    this.apiKey = apiKey || "R_b6ef2b8f51e95235a66782ab88355bde";
    this.version = version || "2.0.1";
};

/*
# utils

*/
BitlyApiClient.prototype.extractBitlyHash = function(bitly_url_or_hash) {
    if (bitly_url_or_hash == null) {
        return null;
    } else {
        var m = bitly_url_or_hash.match(/\/([^\/]+)$/);
        if (m) {
            return m[1];
        }
        else {
            return bitly_url_or_hash;
        }
    }
}

BitlyApiClient.prototype.createElement = function(element_type, attrs) {
  var el = document.createElement(element_type);
  for (var k in attrs) {
    if (k == "text") {
      el.appendChild(document.createTextNode(attrs[k]));
    } else {
      this.setAttribute(el, k, attrs[k]);
    }
  }
  return el;
}

BitlyApiClient.prototype.setAttribute = function(element, attribute_name, attribute_value) {
  if (attribute_name == "class") {
    element.setAttribute("className", attribute_value); // set both "class" and "className"
  }
  return element.setAttribute(attribute_name, attribute_value);
}

/*
# API

Generic API caller for more advanced API usage. Allows you to specify extra params for method calls with options. Eg, you can call the /info API and ask for a subset of data using the 'keys' param.
*/
BitlyApiClient.prototype.call = function(method, params, callback_method_name) {
    params['version'] = this.version;
    params['login'] = this.login;
    params['apiKey'] = this.apiKey;
    return BitlyApi.call(method, params, callback_method_name);
}

// shorten a long url
BitlyApiClient.prototype.shorten = function(longUrl, callback_method_name) {
    return this.call('shorten', {'longUrl': longUrl}, callback_method_name);
}

/*
# INSTANTIATE CLIENT
*/
var BitlyClient = new BitlyApiClient();

/*
    requires bitly javascript api:
    http://code.google.com/p/bitly-api/wiki/JavascriptClientApiDocumentation
*/

var TweetAndTrack = {};
TweetAndTrack.open = function(targ, url) {
    var child_spans = targ.getElementsByTagName('span');
    if (child_spans && child_spans.length > 0) {
        var msg = child_spans[0].innerHTML.toString();
    } else {
        msg = '';
    }

    var callback_name = url.replace(/\W/g, '');
    BitlyCB[callback_name] = function(data) {
        var result = TweetAndTrack.popResult(data);
        var tweet_url = "http://twitter.com/home?status=" + encodeURIComponent(result.shortUrl + " " + msg);
        TweetAndTrack.newWindow(tweet_url, "600", "400");
    };
    BitlyClient.shorten(url, 'BitlyCB.' + callback_name);
    return false;
};

TweetAndTrack.popResult = function(data) {
    // Results are keyed by longUrl, so we need to grab the first one.
    for (var r in data.results) {
        return data.results[r];
    }
};

TweetAndTrack.newWindow = function(url, width, height) {
  var a = function() {
    if(!window.open(url,'t','scrollbars=yes,toolbar=1,resizable=1,status=1,width='+width+',height='+height))document.location.href=url;
  };

  if( /Firefox/.test(navigator.userAgent)) {
    setTimeout(a,0);
  } else {
    a();
  }
};
