/*
 * Su.pr stumble upon / twitter js
 */

var supr = {
    api: "http://origin.extratv.warnerbros.com/_apps/supr/",
    methods: {
        SHORTEN : "shorten.php?"
    },
    params: {
        longUrl  : "",
		shortUrl : "",
		msg      : "",
        login    : "pepperdine2007"
    },

    init: function( url, msg ) {
		this.params.longUrl = url;
		this.params.msg = msg;
        this.shorten_url();
    },

    no_cache: function() {
        return "&nocache=" + (new Date()).getTime() + Math.floor(Math.random()*20000) + "&callback=?";
    },

    shorten_url: function() {
        $.getJSON( this.api + this.methods.SHORTEN + "longUrl=" + this.params.longUrl + "&login=" + this.params.login + this.no_cache(), this.callback_shorten );
    },
    callback_shorten: function( data ) {
        // ref: http://www.stumbleupon.com/developers/Supr:API_documentation/#shorten
        if ( data.errorCode == 0 ) {
			supr.params.shortUrl = data.results[supr.params.longUrl].shortUrl;
            supr.post();
            return;
        }
        alert(data.errorMessage);
    },

    post: function() {
		var tweet_url = "http://twitter.com/home?status=" + encodeURIComponent( this.params.msg + " " + this.params.shortUrl );
		TweetAndTrack.newWindow(tweet_url, "600", "400");
	}
};

var TweetAndTrack = {};
TweetAndTrack.open = function( targ, url ) {
	var child_spans = targ.getElementsByTagName('span');
	if (child_spans && child_spans.length > 0) {
		msg = child_spans[0].innerHTML.toString();
	} else {
		msg = '';
	}

	supr.init( url, msg );
    return false;
};

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();
	}
};