var bg_width = 1000;
var bg_height = 522;
var float_right, timeout;

function show_layer(bg) {
	$('#bg1, #bg2, #bg3, #bg4').hide();
	$('#bg'+bg).show();
}

$('.ctrl_layer').click(function(){
	$('.ctrl_layer').css('border', '2px solid #212d4b');
	$(this).css('border', '2px solid #fff');
	var layer = $(this).attr('id').replace(/ctrl_/, '');
	show_layer( layer );
});

$('.control .label').click(function(){
	if (timeout) clearTimeout(timeout);
	var target = $(this).parent().attr('id');
	var displayed = ( $('#'+target).css('right') == '0px' ? true : false ); // current block
	if (!displayed) {
		var one_displayed = false; // all blocks
		$('.control').each(function(){
		    if ($(this).css('right') == '0px') {one_displayed = true;}
		})
		if (one_displayed) {
			$('.control').animate({'right': float_right}, 300, function(){
				$('#'+target).animate({'right': '0px'}, 300);
			});
		} else {
			$('#'+target).animate({'right': '0px'}, 300);
		}
	} else {
		$('#'+target).animate({'right': float_right}, 300);
	}
});

$('#twitter').keyup(function(e){
	if (e.keyCode == 13) {
		$('#twitter_check').click();
	} else {
		update_brag();
	}
	// 27: escape
});

$('#src_check').click(function(){
	var src = $('#src').val();
	if ( src == '') {
		alert('Please input an image URL');
		return;
	}
	reinit_bg();
	ajax_begin('#src_check');
	var myImage = new Image();
	$('#main').css('background', '#fff url()');
	myImage.tile = $('#tile').attr('checked');
	myImage.src = src;
	myImage.onload = load_new_pic;
	myImage.onerror = loadFailure;
});

$('#twitter_check').click(function(){
	var twitter = $('#twitter').val();
	if (twitter == '') {
		alert('Please input a Twitter @name');
		return;
	}
	reinit_bg();
	ajax_begin('#twitter_check');
	$.getJSON("ajax.php?twitter="+twitter,
		function(data){
			if (data.status == 404) {
				alert('Twitter user not found! Please check (or Twitter may be down?)');
				ajax_end('#twitter_check');
				return;
			}
			var myImage = new Image();
			if (data.repeat == 'no-repeat') {
				$('#main').css('background', data.color+' url()');
				myImage.tile = false;
			} else {
				$('#main').css('background', data.color);
				myImage.tile = true;
			}
			myImage.src = data.bgurl;
			myImage.onload = load_new_pic;
			myImage.onerror = loadFailure;
	});

});

function load_new_pic() {
	var img = this;
	var width = parseInt(img.width / 1.904);
	var height = parseInt(img.height / 1.904);
	var tile = img.tile;
	img = '<img class="bgimg" src="'+img.src+'" width="'+width+'" height="'+height+'">';
	ajax_end('#twitter_check');
	ajax_end('#src_check');
	$('#check').append(img);
	if (tile) {
		tile_image(img, width, height);
	}
	$('#ctrl_5').click();
	$('#resolution .label').click();
    return true;
}

function reinit_bg() {
	$('#check').html('');
	$('#main').css('background', '#fff url("img/empty.png") top left no-repeat');
	$('#ctrl_5').click();
	ajax_end('#twitter_check');
}

function tile_image(img, width, height) {
	var h = height;
	var n = 0;
	do {
		$('#check').append(img);
		tile_row(img, width);
		$('#check').append('<br/>');
		h += height;
		n++;
	} while (h < (bg_height+height) || n < 2);
}

function tile_row(img, width) {
	var w = width;
	while (w <= bg_width) {
		$('#check').append(img);
		w += width;
	}
}

function loadFailure() {
	ajax_end('#twitter_check');
	ajax_end('#src_check');	
    alert('It seems the picture could not load. Try again later...');
	reinit_bg();
    return true;
}

function ajax_begin(el) {
	$(el).addClass('ajax').removeClass('button').html('&nbsp;&nbsp;&nbsp;');
}

function ajax_end(el) {
	$(el).removeClass('ajax').addClass('button').html('Check');
}

// From: javascript from http://scr.im/ (hey, check this site, it's awesome:)
function share(dest) {
	var url=encodeURIComponent(location.href);
	var title=encodeURIComponent(document.title);
	switch (dest) {
	case 'ff':
		$('body').append('<script type="text/javascript" src="http://friendfeed.com/share/bookmarklet/javascript"></script>');
		break;
	case 'delicious':
		window.open('http://delicious.com/save?v=5&amp;noui&amp;jump=close&amp;url='+url+'&amp;title='+title, 'delicious','toolbar=no,width=550,height=550');
		break;
	case 'facebook':
		window.open('http://www.facebook.com/share.php?u='+url, 'fb','toolbar=no,width=1000,height=550');
		break;
	case 'stumble':
		window.open('http://www.stumbleupon.com/submit?url='+url+'&title='+title, 'su','toolbar=no,width=1000,height=550');
		break;
	case 'twitter':
		window.open('http://twitter.com/home?status=Check%20your%20Twitter%20profile%20with%20different%20screen%20size:%20http://twtbg.me/', 'tw','toolbar=no,width=800,height=550');
		break;
	}
	return false;
}

$(document).ready(function(){
	// From: http://chris-barr.com/entry/disable_text_selection_with_jquery/
	$.extend($.fn.disableTextSelect = function() {
		return this.each(function(){
			if($.browser.mozilla){//Firefox
				$(this).css('MozUserSelect','none');
			}else if($.browser.msie){//IE
				$(this).bind('selectstart',function(){return false;});
			}else{//Opera, etc.
				$(this).mousedown(function(){return false;});
			}
		});
	});
	$('.label').disableTextSelect();//No text selection
	float_right = $('.control').css('right');
	$('#ctrl_5').click();
	timeout = setTimeout(function(){$('#source .label').click();}, 2000);
	update_brag();
});

// From: http://code.google.com/p/sprintf/
function str_repeat(i, m) { for (var o = []; m > 0; o[--m] = i); return(o.join('')); }

// From: http://code.google.com/p/sprintf/
function sprintf () {
  var i = 0, a, f = arguments[i++], o = [], m, p, c, x;
  while (f) {
    if (m = /^[^\x25]+/.exec(f)) o.push(m[0]);
    else if (m = /^\x25{2}/.exec(f)) o.push('%');
    else if (m = /^\x25(?:(\d+)\$)?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(f)) {
      if (((a = arguments[m[1] || i++]) == null) || (a == undefined)) throw("Too few arguments.");
      if (/[^s]/.test(m[7]) && (typeof(a) != 'number'))
        throw("Expecting number but found " + typeof(a));
      switch (m[7]) {
        case 'b': a = a.toString(2); break;
        case 'c': a = String.fromCharCode(a); break;
        case 'd': a = parseInt(a); break;
        case 'e': a = m[6] ? a.toExponential(m[6]) : a.toExponential(); break;
        case 'f': a = m[6] ? parseFloat(a).toFixed(m[6]) : parseFloat(a); break;
        case 'o': a = a.toString(8); break;
        case 's': a = ((a = String(a)) && m[6] ? a.substring(0, m[6]) : a); break;
        case 'u': a = Math.abs(a); break;
        case 'x': a = a.toString(16); break;
        case 'X': a = a.toString(16).toUpperCase(); break;
      }
      a = (/[def]/.test(m[7]) && m[2] && a > 0 ? '+' + a : a);
      c = m[3] ? m[3] == '0' ? '0' : m[3].charAt(1) : ' ';
      x = m[5] - String(a).length;
      p = m[5] ? str_repeat(c, x) : '';
      o.push(m[4] ? a + p : p + a);
    }
    else throw ("Huh ?!");
    f = f.substring(m[0].length);
  }
  return o.join('');
}

function update_brag() {
	var name = $('#twitter').val() || 'ozh';
	$('#brag_name, #brag_name_2').text(name);
	var sel = $('#brag_text :checked');
	var cool = $(sel[0]).val();
	var res = $(sel[1]).val();
	$('#brag_url').attr('href', $('#brag_url').text() );
	var brag = "@%s, your Twitter page looks like %s on %s resolutions! Check it out: http://twtbg.me/?t=%s";
	brag = encodeURIComponent(sprintf(brag, name, cool, res, name));
	$('#brag_button').attr('href', 'http://twitter.com/home?status='+brag);
}

$('#brag_text :radio').click(function(){update_brag();});

$(document).ready(function(){
	if ($.browser.msie) {
		$('body').append('<span id="msie"><span style="display:none">Ho... you are using Internet Explorer.<br/>Sorry then, we have a problem. This site is not working with this totally wacked out browser.<br/>Why not run a<br/><a href="http://getfirefox.com/">free, highly flexible (and secure) alternative</a>?<br/><small>Seriously dude, MSIE sucks. It\'s an utter pain to spend hours making scripts work in this shitty browser.</small></span></span>');
		$('#msie span').fadeOut('1');
		$('body').css({'overflow-y':'hidden','height':'99%'});
		$('#msie').animate({'lineHeight': '70px'}, 2000);
		$('#msie span').fadeIn(2000);
	}
});
