// MooTools Plus, <http://www.tobymiller.com/plus>. Copyright (c) 2008 Toby Miller, MIT Style License.

/*
Script: Debug.js
	Output debug messages.

Usage:
	Debug.log('your message');
		or
	Debug.enable('http://www.yourdomain.com/debug.php'); // call once
	Debug.log('your message');

	Note: If you opt to use your own remote logger it should accept a query
	like this: http://www.yourdomain.com/debug.php?key=yourdomain.com&msg=hello

License:
	MIT-style license
*/
var Debug = {
	enable: function(){
		if (!this.enabled){
			this.enabled = true;
			this.ready = false;
			this.remote = (arguments.length > 0) ? arguments[0] : null;
			this.idx = 0;
			this.msgs = ['Debug:enable()'];
			this.outs = [];
		} else {
			this.msgs[this.msgs.length] = 'Debug:enable()';
			this.remote = (arguments.length > 0) ? arguments[0] : null;
			this.process();
		}
	},

	disable: function(){
		this.msgs[this.msgs.length] = 'Debug:disable()';
		if (this.enabled){
			this.enabled = false;
			this.remote = null;
		}
	},

	log: function(msg){
		if (typeof this.enabled == 'undefined') this.enable();
		this.msgs[this.msgs.length] = msg;
		this.process();
	},

	process: function(){
		if (this.enabled){
			if (this.msgs[this.idx]){
				this.ready = true;
				if (window.console){
					window.console.log(this.msgs[this.idx]);
					this.idx++;
					this.process();
				} else if (this.remote != null){
					var ts = new Date().getTime();
					var h = new Hash({'key': window.location.hostname, 'msg': this.msgs[this.idx]});
					var q = this.remote+'?ts='+ts+'&'+h.toQueryString();
					this.outs.push(new Asset.javascript(q));
					this.idx++;
					this.process();
				}
			}
		}
	}
};

/*
Script: EnhancedElement.js
	Define additional class names, styles, events, attributes, and properties to
	apply to html elements whenever JavaScript is enabled. These definitions
	are written into a JavaScript object inside an html comment block within the
	particular html element(s) being enhanced.

	Note: Since these instructions are ignored by search engines and screen
	readers they should never contain content or anything else that would
	prevent the current page from being contextually understandable.

	Usage:
	<tag>
		tag content
		<!--{
			'styles': {
				'color': '#f00',
				'background-color': '#000'
			},
			'class': 'harry',
			'className': 'monkey',
			'classes': ['harry', 'monkey', 'fever'],
			'attributes': {
				'checked': 'checked',
				'temperature': '99.7'
			},
			'property1': 'hello',
			'property2': ['hello', 'world'],
			'property3': {
				'key1': 'hello',
				'key2': 'there',
				'key3': 'world'
			},
			'events': {
				'mouseover': function(){ this.set('src', 'on.gif') }
				'mouseover': function(){ this.set('src', 'off.gif') }
			}
		}-->
	</tag>

License:
	MIT-style license
*/
var EnhancedElement = {
	enhance: function(){
		var selector = (arguments.length > 0) ? arguments[0] : ['address','a','big','blockquote','body','b','caption','center','cite','code','dd','dfn','dir','div','dl','dt','em','form','h1','h2','h3','h4','h5','h6','i','kbd','li','menu','ol','option','param','pre','p','samp','select','small','span','strike','strong','sub','sup','table','td','th','title','tr','tt','ul','u','var'];
		$$(selector).each(function(el){
			var html = el.innerHTML;
			el.getChildren().each(function(child){ html = html.replace(child.innerHTML, '') });
			html = html.replace(/[\n\r]*/g, '');
			var match = html.match(/^.*<!--\s*\{(.*)\}\s*-->.*$/);
			if (match){
				var enhanced = eval('({' + match[1] + '})');
				for (var name in enhanced){
					switch(name){
						case 'class':
						case 'className':
							el.addClass(enhanced[name]);
							break;
						case 'classes':
							for (var i = 0; i < enhanced[name].length; i++) el.addClass(enhanced[name][i]);
						case 'styles':
							for (var n in enhanced[name]) el.setStyle(n, enhanced[name][n]);
							break;
						case 'events':
							for (var n in enhanced[name]) el.addEvent(n, enhanced[name][n]);
							break;
						case 'attributes':
							for (var n in enhanced[name]) el.setAttribute(n, enhanced[name][n]);
							break;
						default:
							if (name.length > 0) el.setProperty(name, enhanced[name]);
							break;
					}
				}
			}
		});
	}
};
window.addEvent('domready', function(){ EnhancedElement.enhance(['a.mb','a.quick-look']) });

/*
Script: EnhancedForm.js
	Define custom css sprites, effects, and controls to apply to form field
	elements whenever JavaScript is enabled. This libary relies on a server side
	component (i.e. php, ruby, java, etc) to convert css sprite images into
	custom form field background images. This library is completely cross
	browser, cross platform and, since it is an enhancement, backward compatible
	for users without JavaScript enabled (the non-enhanced experience is used
	instead).

	Note: Since these enhancements are ignored by browsers with JavaScript
	disabled you should develop your forms to work as if JavaScript were not an
	option. This way your forms will remain accessible to all users while
	providing the enhanced experience to most users (especially important if
	being used on an e-commerce or monetary dependent form).

	Usage:
	@TODO

License:
	MIT-style license
*/
var EnhancedForm = {
	enhance: function(){
		var selector = (arguments.length > 0) ? arguments[0] : ['.enhanced textarea','.enhanced select','.enhanced button','.enhanced input'];
		$$(selector).each(function(el){
			switch(el.tagName){
				case 'TEXTAREA':
					EnhancedForm.enhanceTextarea(el);
				break;
				case 'SELECT':
					EnhancedForm.enhanceSelect(el);
				break;
				case 'BUTTON':
					EnhancedForm.enhanceButton(el);
				break;
				case 'INPUT':
					switch(el.get('type')){
						case 'checkbox':
							EnhancedForm.enhanceInputCheckbox(el);
						break;
						case 'radio':
							EnhancedForm.enhanceInputRadio(el);
						break;
						case 'text':
							EnhancedForm.enhanceInputText(el);
						break;
						case 'password':
							EnhancedForm.enhanceInputPassword(el);
						break;
						case 'file':
							EnhancedForm.enhanceInputFile(el);
						break;
						case 'button':
							EnhancedForm.enhanceInputButton(el);
						break;
						case 'submit':
							EnhancedForm.enhanceInputSubmit(el);
						break;
						case 'reset':
							EnhancedForm.enhanceInputReset(el);
						break;
					}
				break;
			}
		});
	},

	writeTemplate: function(content){
		return('<html><head><link rel="stylesheet" type="text/css" href="/css/enhanced-form.css" /></head><body id="enhanced-body" class="enhanced-inputtext">'+content+'</body></html>');
	},

	enhanceTextarea: function(){
	},

	enhanceSelect: function(){
	},

	enhanceInputCheckbox: function(){
	},

	enhanceInputRadio: function(){
	},

	enhanceInputText: function(el){
		// gather field dimensions
		var w = el.getSize().x;
		var h = el.getSize().y + 6;

		// create a container for layering elements
		var container = new Element('div', {
			'id': 'enhanced-' + el.get('name'),
			'styles': {
				'position': 'relative'
			}
		});

		// create a text sample for measurement purposes
		var sample = new Element('div', {
			'class': 'innertext',
			'styles': {
				'overflow': 'hidden',
				'white-space': 'nowrap',
				'position': 'absolute',
				'top': -10000,
				'left': -10000
			}
		}).set('text', 'sample');
		sample.inject(container);

		// generate the field image
		var img = new Element('img', {
			'src': 'test.php?w=' + w + '&h=' + h,
			'width': w,
			'height': h,
			'styles': {
				'position': 'absolute',
				'top': 0,
				'left': 0
			}
		});
		img.inject(container);

		// generate the new input element (designMode iframe)
		var iframe = new Element('iframe', {
			'id': 'enhanced-inputtext-' + el.get('name'),
			'styles': {
				'position': 'absolute',
				'top': 0,
				'left': 0,
				'width': w,
				'height': h,
				'border': 1,
				'frameborder': 1
			}
		});
		iframe.inject(container);

		// generate the pre-cursor iframe element (for measuring left text)
		var left_iframe = new Element('iframe', {
			'id': 'enhanced-lefttext-' + el.get('name'),
			'styles': {
				'position': 'absolute',
				'top': '-10000px',
				'left': '-10000px',
				'width': w,
				'height': h,
				'border': 1,
				'frameborder': 1
			}
		});
		left_iframe.inject(container);

		// generate the post-cursor iframe element (for measuring right text)
		var right_iframe = new Element('iframe', {
			'id': 'enhanced-righttext-' + el.get('name'),
			'styles': {
				'position': 'absolute',
				'top': '-10000px',
				'left': '-10000px',
				'width': w,
				'height': h,
				'border': 1,
				'frameborder': 1
			}
		});
		right_iframe.inject(container);

		// place the container on screen so the new elements inherit tangible dimensions
		container.inject(el, 'after');

		// calculate padding for input field
		var padding = (h - sample.getSize().y) / 2;

		// reposition iframe to fit within field image boundaries
		iframe.setStyles({
			'top': padding + 'px',
			'left': (padding * 1.5) + 'px',
			'width': (w - (padding * 3)) + 'px',
			'height': (h - (padding * 2)) + 'px'
		});

		// add content to iframe element (must be done after page load)
		window.addEvent('load', function(){
			// enable design mode
			this.contentDocument.designMode='on';

			// load current content template into iframe
			var template = EnhancedForm.writeTemplate(el.get('value'));
			iframe.contentWindow.document.open();
			iframe.contentWindow.document.write(template);
			iframe.contentWindow.document.close();

			// and left iframe
			left_iframe.contentWindow.document.open();
			left_iframe.contentWindow.document.write(template);
			left_iframe.contentWindow.document.close();

			// and right iframe
			right_iframe.contentWindow.document.open();
			right_iframe.contentWindow.document.write(template);
			right_iframe.contentWindow.document.close();

			// attach interaction events
			var doc = (!iframe.contentWindow.document.$family) ? new Document(iframe.contentWindow.document) : iframe.contentWindow.document;
			doc.addEvents({
				'focus': function(){
					//console.log('focus');
				}.bind(doc),
				'click': function(){
					//console.log('click');
					//var r = this.createRange();
					//console.log(r);
				}.bind(doc),
				'keyup': function(){
					var val = doc.body.innerHTML;
					var idx = iframe.contentWindow.getSelection().anchorOffset;
					var left_val = doc.body.innerHTML.substring(0, idx);
					var right_val = doc.body.innerHTML.substring(idx);
					var r = doc.createRange();
					var w = r.startContainer.activeElement.clientWidth;

					console.log('w = ' + w);
					console.log('xw = ' + sample.getSize().x);
					console.log('val = ' + val);
					console.log('left_val = ' + left_val);
					console.log('right_val = ' + right_val);
					console.log('aoffset = ' + iframe.contentWindow.getSelection().anchorOffset);
					console.log('\n');
					/*
					var r = this.createRange();
					console.log(this.getSelection());
					console.log(r);
					console.log(r.startContainer.activeElement.clientWidth);
					console.log(r.startContainer.activeElement.scrollWidth);
					*/
				}
			});
		}.bind(iframe));

		/*
		el.addEvent('keyup', function(){
			$('enhanced-' + this.get('name')).getElement('.innertext').set('text', this.get('value'));
		});
		*/
	},

	enhanceInputPassword: function(){
	},

	enhanceInputFile: function(){
	},

	enhanceButton: function(){
	},

	enhanceInputButton: function(){
	},

	enhanceInputSubmit: function(){
	},

	enhanceInputReset: function(){
	}
};
window.addEvent('domready', function(){ EnhancedForm.enhance(['a.mb','a.quick-look']) });