(function(page){
	
	// public function
	page.init = function() {
		// change body class to js-enabled
		$('body').removeClass('js-disabled').addClass('js-enabled');
		// attach behaviours after body has loaded
		$(function(){
			// focus cursor to raw text box
			$('textarea.input-text').focus();
			// make raw text box elastic
			$('textarea.input-text').elastic();
			// accept tabs inside raw text box
			$('textarea.input-text').tabby();	
			// round corners on submit button
			$('a.op-encode').corner('3px');
			// make url-safe box elastic
			$('textarea.output-text').elastic();
			// bind events
			$('select.tools-links-select').bind('change',select_site);
			$('textarea.output-text').bind('keydown',prevent_typing); 
			$('textarea.output-text').bind('click',select_output_text);
			$('textarea.input-text').bind('keydown',update_char_counter);
			$('textarea.input-text').bind('keyup',update_char_counter);
			$('textarea.input-text').bind('keypress',submit_on_shift_enter);
			$('textarea.input-text').bind('keypress',reset_on_shift_escape);
			$('body').bind('keypress',submit_on_shift_enter);
			$('body').bind('keypress',reset_on_shift_escape);
			// apply click events to all anchors with js-op class
			$('a.js-op').each(function(){				
				// regex pattern used to get op-name
				var pattern = new RegExp('\\bop\\-[a-z0-9_]+\\b');
				// match class that is the op name
				var match = pattern.exec(this.className);
				if (match == null) return; 
				if (match.length < 1) return; 
				// get the op name
				var op = match[0];
				// bind click event to submit this anchor
				$(this).bind('click',function() { 
					return submit_op(op) 
				});
			});
			// update character counter 
			update_char_counter();	
		});
	}

	// private function
	function update_char_counter() {
		var charcount = $('textarea.input-text').val().length;
		$('p.character-counter').html(charcount);			
	};
	// private function
	function submit_op(op) {
		$('form.page-form input[name='+op+']').click();
		return false;
	}
	// private function
	function select_output_text() {
		var safetx = $('textarea.output-text');
		safetx.blur(); 
		safetx.select();
	}
	// private function
	function reset_page() {
		window.location = window.location.href;
	}
	// private function
	function select_site() {
		var siteurl = $('select.tools-links-select').val()
		window.location = siteurl;
	}
	// private function
	function submit_on_shift_enter(e) {
		if (e.keyCode==13 && e.shiftKey) {
			submit_op('op-encode');
			return false;
		}
	}
	// private function 
	function reset_on_shift_escape(e) {
		if (e.keyCode==27  && e.shiftKey) {
			reset_page();
			return false;
		}		
	}
	// private function
	function prevent_typing(e) {
		if (!e.ctrlKey && !e.metaKey && e.keyCode!=9) return false;		
	}
	
})(window.page = {});
