$('#imagebox img').load(resizeImgX);
$('#imagebox img').ready(resizeImgX);

function resizeImgX() {
    var maxWidth = $('#imagebox').width();
    var originalWidth = $('#imagebox img').width();
    var originalHeight = $('#imagebox img').height();
    var percent = (maxWidth * 100) / originalWidth;
    
    if(originalWidth > maxWidth) {
        $('#imagebox img').css({'height':'auto','width':'100%'});
        $('#imagebox').css({'max-height': Math.round(percent / 100 * $('#imagebox').css('max-height').replace(/px/g,'')) + 'px'});
        $('#imagebox').prepend('<a id="theZoom" onclick="var w=window.open(\'\',this.target,\'width=' + originalWidth + ',height=' + originalHeight + ',scrollbars=yes\');w.focus();" title="Zoom" target="external" href="' + $('#imagebox img').attr('src') + '">' + Math.round(100-percent) + '%</a>');
    }
}

$('a[target=external]').click(function() {
    var w=window.open($(this).attr('href'), 'external', 'width=800,height=600,scrollbars=yes');
    w.focus();
});

$('#shortURL').click(function() {
	var imageLink = "http://imagehost.co.nz" + window.location.pathname;
	var login = "possum888";
	var apiKey = "R_bfc6c93c0e443b88edde5ffc1f490fa7";
	
	$('#shortURL').replaceWith("<div id=\"shortURL\">Getting...</div>");
	$.ajax({
		type: "GET",
		url: "http://api.bitly.com/v3/shorten",
		data: {login: login, apiKey: apiKey, longUrl: imageLink, format: "txt"},
		dataType: "text",
		success: function(shortURL) {
			$('#shortURL').replaceWith(shortURL);
		}
	});
});

