var _baseurl = "http://static.tommed.co.uk/d2"
goog.require('goog.dom')
goog.require('goog.ui.Dialog')
goog.provide('tommed')

/**
 * Usage text which can be written to a page when calling: tommed.help() in the body of a page.
 */
tommed._usage = [
	' Use this script when you want a page to adopt the d2 style.',
	' Example:',
	' ',
	'   <!doctype html>',
	'   <html lang="en">',
	'   <head>',
	'    <script src="'+_baseurl+'/../js/closure/goog/base.js"></script>',
	'    <script src="'+_baseurl+'/run.js"></script>',
	'   </head>',
	'   <body>',
	'     <script>tommed.draw_header({title:"Page Title Here"})</script>',
	'        <!--Your content here--> ',
	'     <script>tommed.draw_footer()</script>',
	'   </body>',
	'   </html>'
	].join('\n')

function _add_link(url, rel) {
	rel = rel || 'stylesheet'
	var script = document.createElement('link')
	script.rel = rel
	script.href =  url
	document.write(_html(script))
}

function _isff() {
	return navigator.userAgent.indexOf('Firefox')>0
}

function _write(html) {
	document.write(html)
}

function _add_script(url, async) {
	var script = document.createElement('script')
	script.async = false
	script.type = "text/javascript"
	script.src = url
	document.write(_html(script))
}
function _qrlink() {
	return ['QRCode', 'javascript:void(_do_qrcode());', true]
}

function _do_qrcode() {
	var url = 'http://myqr.co/api/embed.png?apikey=n0eObOFC0JGkitU93Xbig25OufifnuMKu0zGOeiP&'+
		  'type=url&size=l&url='+escape(document.location.href)
	var dialog = new goog.ui.Dialog()
	dialog.setTitle('QRCode for this page')
	dialog.setContent('<div style="text-align:center"><img src="%"/></div>'.replace('%',url))
	dialog.setButtonSet(null)
	dialog.setVisible(true)
}

// add the link to the stylesheet
_add_link(_baseurl+'/style.css')
_add_link(_baseurl+'/../js/closure/goog/demos/css/dialog.css')

/**
 * Escapes html characters.
 */
tommed.escapeHTML = function(html) {
	return html.split("&").join("&amp;").split( "<").join("&lt;").split(">").join("&gt;")
}

/**
 * Writes usage info on the page
 */
tommed.help = function() {
	document.write("<h3>Help</h3><pre>"+tommed.escapeHTML(tommed._usage)+"</pre>")
}

/**
 * Merges two hashes. Honouring the last over the first arg.
 * @param base: The hash containing defaults
 * @param opts: The hash which takes prescedance.
 */
tommed.merge = function(base, opts) {
	for (item in opts) {
		base[item] = opts[item]
	}
	return base
}

/**
 * Information about this particular page.
 * This information will be merged with the options passed into
 * tommed.draw_header.
 */
var _pageopts = {
	title:'Untitled Page',      // page title
	analytics:'UA-1554800-11',  // analytics account code
	menu:[_qrlink()],           // page menu
	home:'/',	            // link to go home
	}

/**
 * Draw this page's header.
 * @param pageTitle: The title of this page.
 */
tommed.draw_header = function(opts) {
	if (opts != null) {
		_pageopts = tommed.merge(_pageopts, opts)
	}
	document.write([
		'<div id="canvas"><h1><a href="'+_pageopts.home+'">tommed</a></h1>',
		'<h2>',
		tommed.escapeHTML(_pageopts.title),
		'</h2>'
		].join('\n'))
	if (_pageopts.menu != null && _pageopts.menu.length > 0) {
		var menu = goog.dom.createDom('ul', {className:'main-menu'})
		for (var i=0; i<_pageopts.menu.length; i++) {
			var mi = _pageopts.menu[i]
			var elem = goog.dom.createDom('li', {}, 
			           goog.dom.createDom('a', {href:mi[1]}, mi[0]))
			if (mi.length > 2 && mi[2] == true) {
				elem.childNodes[0].target = "_blank"
			}
			menu.appendChild(elem)
		}
		document.write(_html(menu))
	}
}

function _html(elem) {
	if (_isff()) {
		return new XMLSerializer().serializeToString(elem)
	} else {
		return elem.outerHTML
	}
}

/**
 * Draw this page's footer.
 */
tommed.draw_footer = function() {
	document.write('</div>')
	tommed._draw_analytics(_pageopts.analytics)
}

/**
 * Draw the analytics code.
 * This is called by tommed.draw_footer, so if you use this, you don't need to call this.
 * @param code: The site code.
 */
tommed._draw_analytics = function(code) {
	var _gaq = _gaq || [];
	_gaq.push(['_setAccount', code]);
	_gaq.push(['_trackPageview']);
	(function() {
	var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
	('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
	var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
	})();
}


/**
 * Start drawing a sidebar.
 */
tommed.draw_sidebar_start = function() {
	goog.dom.$('canvas').style.paddingRight = "300px"
	document.write('<div id="sidebar">')
}

/**
 * Finish drawing a sidebar.
 */
tommed.draw_siebar_end = function() {
	document.write('</div>')
}

