(function (m, i) { // Prevent calls to Firebug from causing errors
    if (!window.console || !console.firebug) {
        window.console = {};
        for (i = 0; i < 16; i += 1) {
            window.console[m[i]] = function () {};
        }
    }
})('log debug info warn error assert dir dirxml group groupEnd time timeEnd count trace profile profileEnd'.split(' '));
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

var littleroom = {};

littleroom.boxes = function() {
	var boxes = [], order = [], hue = 20, stepSize = 10, time = 100, lc;
	var sb = [
		[46,22],[86,58],[97,85],[97,83],[88,53],[45,20],
		[86,58],[49,99],[26,98],[29,98],[48,94],[91,47],
		[97,84],[27,98],[49,97],[55,96],[41,96],[99,67],
		[97,81],[32,97],[54,96],[58,96],[45,95],[99,62],
		[89,51],[48,93],[41,96],[45,95],[47,89],[91,35],
		[45,19],[92,44],[99,64],[99,60],[91,34],[35,16]
	];
	function cycle() {
		if (!order.length) {
			order = shuffle();
			hue = (hue + stepSize) % 360;
		}
		var id = order.pop(), b = boxes[id], c = $HSB(hue, b.s, b.b);
		b.fx.start(c);
	}
	function shuffle() {
		var f = function(){ return Math.round( Math.random() ) - 0.5; };
		for (var i=0, a=[]; i < 36; i++) a.push(i);
		return a.sort(f).sort(f).sort(f); // shuffle three times
	}
	function click(e) {
		e = new Event(e);
		var c = e.target.getStyle('background-color');
		$(document.body).setStyle('background-color',c);
		c = new Color(c).hsb;
		littleroom.sliders.set(c);
	}
	function step() {
		var b = $(document.body);
		var c = new Color(b.getStyle('background-color')).hsb;
		var h = (c[0] + 2) % 360;
		c[0] = h;
		littleroom.sliders.set(c);
		b.setStyle('background-color', c.hsbToRgb());
		littleroom.boxes.setLinkColor(h);
	}
	return {
		initialize: function(){
			var bxz = $('boxez'), bg = $(document.body).getStyle('background-color');
			this.body = new Color(bg).hsb;
			lc = new Color($E('a').getStyle('color')).hsb;
			(36).times(function(id){
				var el = new Element('div',{ id:id }).setStyle('background-color',bg).addEvent('click',click).injectInside(bxz);
				var fx = new Fx.Style(el, 'background-color', { duration:time });
				boxes.push({ id:id, el:el, fx:fx, s:sb[id][0], b:sb[id][1] });
			});
			var corner = new Element('div',{ id:'corner', title:'Draggable...' }).injectInside('menu');
			bxz.makeDraggable();
			$('content').makeDraggable({ handle:corner, onDrag: step });
			bxz.setProperty('title','Click to change the background-color');
			littleroom.tips = new Tips($$('#boxez','#corner','a'), { offsets:{ x:0, y:19 } });
			cycle.periodical(time);
		},
		setLinkColor: function(h){
			if (!$chk(h)) h = new Color($(document.body).getStyle('background-color')).hsb[0];
			$$('a').setStyle('color', [h,lc[1],lc[2]].hsbToRgb());
		}
	};
}();

littleroom.sliders = function(){
	var hsb, h, s, b, be, foliage;
	function adapt(p,v,el) {
		hsb[p] = v;
		var rgb = hsb.hsbToRgb(), hex = rgb.rgbToHex();
		$('rgb').setText('rgb: ' + rgb.join(', '));
		$('hex').setText('hex: ' + hex);
		$(document.body).setStyle('background-color',rgb);
		border();
		if (!p) littleroom.boxes.setLinkColor(v);
		$(el).setText(v);
	}
	function border() {
		var inv = hsb[2] < 60, bc = inv ? hsb[2] +10 : hsb[2] -10;
		// var bc = (100 - hsb[2] / 4) - 20;
		// console.log('bc:', bc);
		be.setStyle('border-color', [hsb[0],hsb[1],bc].hsbToRgb());
		if (!window.ie6) foliage.className = inv ? 'white' : 'black';
	}
	return {
		initialize: function(){
			hsb = new Color($(document.body).getStyle('background-color')).hsb;
			be = $$(document.body,'#content');
			if (!window.ie6) foliage = new Element('div', { id:'foliage' }).injectTop(document.body);
			h = new Slider($('hArea'), $('hKnob'), { steps:360, onChange: function(v){ adapt(0,v,'hValue'); }}).set(hsb[0]);
			s = new Slider($('sArea'), $('sKnob'), { steps:100, onChange: function(v){ adapt(1,v,'sValue'); }}).set(hsb[1]);
			b = new Slider($('bArea'), $('bKnob'), { steps:100, onChange: function(v){ adapt(2,v,'bValue'); }}).set(hsb[2]);
		},
		set: function(hsb){
			hsb = hsb;
			h.set(hsb[0]);
			s.set(hsb[1]);
			b.set(hsb[2]);
		}
	};
}();

// littleroom.sliders = {
// 	init: function(){
// 		this.hsb = new Color($(document.body).getStyle('background-color')).hsb;
// 		this.h = new Slider($('hArea'), $('hKnob'), { steps:360,
// 			onChange: function(v){
// 				littleroom.sliders.adapt(0,v,'hValue');
// 			}
// 		}).set(this.hsb[0]);
// 		this.s = new Slider($('sArea'), $('sKnob'), { steps:100,
// 			onChange: function(v){
// 				littleroom.sliders.adapt(1,v,'sValue');
// 			}
// 		}).set(this.hsb[1]);
// 		this.b = new Slider($('bArea'), $('bKnob'), { steps:100,
// 			onChange: function(v){
// 				littleroom.sliders.adapt(2,v,'bValue');
// 			}
// 		}).set(this.hsb[2]);
// 	},
// 	set: function(hsb){
// 		this.hsb = hsb;
// 		this.h.set(hsb[0]);
// 		this.s.set(hsb[1]);
// 		this.b.set(hsb[2]);
// 	},
// 	// setBody: function(c){
// 	// 	c = new Color(c);
// 	// 	var bc = c.hsb[2] < 60 
// 	// }
// 	adapt: function(p,v,el){
// 		this.hsb[p] = v;
// 		var rgb = this.hsb.hsbToRgb(), hex = rgb.rgbToHex();
// 		$('rgbhex').setText('rgb: '+rgb+' hex: '+hex)
// 		// console.log('rgb: %s hex: %s', rgb, hex);
// 		$(document.body).setStyle('background-color',rgb);
// 		if (!p) littleroom.boxes.setLinkColor(v);
// 		$(el).setText(v);
// 	}
// };

littleroom.parseUri = function(sourceUri){
	var uri = {}, uriPartNames = ['source','protocol','authority','domain','port','path','directoryPath','fileName','queryString','anchor'];
	var uriParts = new RegExp('^(?:([^:/?#.]+):)?(?://)?(([^:/?#]*)(?::(\\d*))?)?((/(?:[^?#](?![^?#/]*\\.[^?#/.]+(?:[\\?#]|$)))*/?)?([^?#/]*))?(?:\\?([^#]*))?(?:#(.*))?').exec(sourceUri || location.href);
	for (var i=0;i<10;i++) uri[uriPartNames[i]] = (uriParts[i] ? uriParts[i] : '');
	if (uri.directoryPath) uri.directoryPath = uri.directoryPath.replace(/\/?$/, '/');
	// uri.query = uri.queryString.toQueryParams();
	
	// if (uri.queryString) {}
	// uri.query = {};
	// 
	
	return uri;
}

littleroom.cipher = {
	hide: function(string){
		return string.replace(/[a-z0-9]+/g, function(match){
			return (parseInt(match, 36) * 2).toString(36);
		}).replace(/[^a-z0-9]/g, function(match){
			return '_' + match.charCodeAt().toString(36) + '_';
		});
	},
	show: function(enkoded){
		return ('<' + enkoded.replace(/_[^_]+_/g,function(match){
			return '>' + String.fromCharCode(parseInt(match.replace('_',''), 36)) + '<';
		}) + '>').replace(/<[^>]*>/g,function(match){
			match = match.replace(/[<>]/g, '');
			return match ? (parseInt(match, 36) / 2).toString(36) : '';
		});
	},
	secret: function(){
		// www.contactify.com/79ec0
		var m = this.show('qlr0q_1a_nk_1s_x8l16_1a_pd8');
		var a = new Element('a',{ 'title':m, 'href':'mailto:'+m }).setText(m);
		var p = new Element('p').setText('mail (and google talk): ').adopt(a).injectInside('contact');
	}
};

littleroom.sections = function(){
	var links, span;
	function setSpan(el) {
		var text = el.getText(), old = span.getProperty('i');
		el.replaceWith(span.setText(text).setProperty('i',el.getProperty('i')));
		if ($chk(old)) links[old].injectInside($$('#menu li')[old]);
		littleroom.tips.toolTip.setStyle('visibility','hidden');
		return text;
	}
	return {
		initialize: function(){
			links = $$('#menu a');
			links.each(function(el,i){
				el.setProperty('i',i).addEvent('click', function(e){
					e = new Event(e).stop();
					littleroom.sections.select(e.target);
				});
			});
			span = new Element('span');
			var first = location.href;
			if (first.contains('#')) first = first.substr(first.indexOf('#')+1);
			this.select($(first) || links[0]);
		},
		select: function(el){
			$$('.section').setStyle('display','none');
			$(setSpan(el)).setStyle('display','');
			littleroom.boxes.setLinkColor();
		}
	};
}();

// http://del.icio.us/feeds/json/inmyhead?raw&count=10
littleroom.stalk = function(){
	var delicious = {};
	return {
		initialize: function(){
			var url = '/proxy.php?url=http://del.icio.us/feeds/json/inmyhead?raw&count=5';
			new Ajax(url,{ onSuccess: function(text){
				delicious.posts = Json.evaluate(text);
			}}).request();
			url = '/proxy.php?url=http://del.icio.us/feeds/json/tags/inmyhead?raw&atleast=3';
			new Ajax(url,{ onSuccess: function(text){
				delicious.tags = Json.evaluate(text);
			}}).request();
		}
	};
}();

window.addEvent('domready', function(){
	littleroom.cipher.secret();
	littleroom.boxes.initialize();
	littleroom.sliders.initialize();
	littleroom.sections.initialize();
	// littleroom.stalk.initialize();
	littleroom.uri = littleroom.parseUri();
    // $$('a[rel=external]:href').setProperty('target', '_blank');
	$$('.section a').each(function (a) {
	    if (a.getProperty('href').test('^http://')) a.setProperty('target', '_blank');
	});
});
