$(document).ready(function() {
	//header logo
	$(".logo").jQIR("png", siteUrl+"/serve/");
	// Accordion
	$("#accordion").accordion({ header: "h3" });
	// Graph
	$('.graphTab').width(600);
	$('.graphTab').height(300);
	// Tabs
	$('.tabs').tabs();
	//Buttons
	$( ".button" ).button();
	//Buttons
	$( ".buttonDisabled" ).button({ disabled: true });
	//content
	$('.content').scale9Grid({top:40,bottom:40,left:40,right:40});
	//h1
	$('h1').scale9Grid({top:0,bottom:0,left:20,right:70});
	//h2
	$('h2').scale9Grid({top:0,bottom:0,left:20,right:70});
	//Errors
	$( ".error" ).each(function(index) {
		$(this).replaceWith('<div class="ui-widget error"><div class="ui-state-error ui-corner-all errorMessage"><p><span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span>'+$(this).text()+'</p></div></div>');
	});
	//Infos
	$( ".info" ).each(function(index) {
		$(this).replaceWith('<div class="ui-widget info"><div class="ui-state-highlight ui-corner-all infoMessage"> <p><span class="ui-icon ui-icon-info" style="float: left; margin-right: .3em;"></span>'+$(this).text()+'</p></div></div>');
	});
	//remove links to homepage on homepage
	var path = location.pathname.substring(1);
	//alert(path);
	if ( path ){
		if(path.indexOf('/main')!=-1){
			$('.nav a[href$="' + path + '"]').hide();
		}
	}
	//emails
	var spt = $('span.mailme');
	var at = / at /;
	var dot = / dot /g;
	var addr = $(spt).text().replace(at,"@").replace(dot,".");
	$(spt).after('<a href="mailto:'+addr+'" title="Send an email">'+ addr +'</a>')
	.hover(function(){window.status="Send a letter!";}, function(){window.status="";});
	$(spt).remove();
	//change all dates to local time
	$('.date').each(function(index) {
		var timestamp = $(this).text();
		var regex = /^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/;
		var parts = timestamp.replace(regex,"$1 $2 $3 $4 $5 $6").split(' ');
		var date = new Date(parts[0],parts[1]-1,parts[2],parts[3],parts[4],parts[5]);
		var dateNow = new Date();
		var offset = dateNow.getTimezoneOffset();
		date.setMinutes(date.getMinutes()-offset);
		var dateString = date.toLocaleDateString()+" "+date.toLocaleTimeString();
		$(this).text(dateString);
	});
	//show hide question options
    $(".questionOptionListPreview").before("<p class='showOptionsLink'><a href='' title='Show options'>+ Show answers</a></p>");
	$(".questionOptionListPreview").hide();
	$(".showOptionsLink a").click(onClickShowOptions);
 });
 function onClickShowOptions(event){
	$(this).text('- Hide answers');
	$(this).parents('.question').children('.questionOptionListPreview').show('blind');
	$(this).unbind('click', onClickShowOptions );
	$(this).click(onClickHideOptions);
	// Stop the link click from doing its normal thing
	event.preventDefault();
 }
 function onClickHideOptions(){
	$(this).text('+ Show answers');
	$(this).parents('.question').children('.questionOptionListPreview').hide('blind');
	$(this).unbind('click', onClickHideOptions );
	$(this).click(onClickShowOptions);
	// Stop the link click from doing its normal thing
	event.preventDefault();
 }
// helper for returning the weekends in a period
function weekendAreas(axes) {
	var markings = [];
	var d = new Date(axes.xaxis.min);
	// go to the first Saturday
	d.setUTCDate(d.getUTCDate() - ((d.getUTCDay() + 1) % 7))
	d.setUTCSeconds(0);
	d.setUTCMinutes(0);
	d.setUTCHours(0);
	var i = d.getTime();
	do {
	// when we don't set yaxis, the rectangle automatically
	// extends to infinity upwards and downwards
	markings.push({ xaxis: { from: i, to: i + 2 * 24 * 60 * 60 * 1000 } });
	i += 7 * 24 * 60 * 60 * 1000;
	} while (i < axes.xaxis.max);

	return markings;
}
//graph tooltip
function showTooltip(x, y, contents) {
	$('<div id="tooltip" class="graphTooltip">' + contents + '</div>').css( {
		position: 'absolute',
		top: y - 25,
		left: x + 5,
		border: '1px solid #fdd',
		padding: '2px',
		'background-color': '#fee',
		opacity: 0.80
	}).appendTo("body");
}
//analytics
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-357076-4']);
_gaq.push(['_trackPageview']);
_gaq.push(['_trackPageLoadTime']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}
String.prototype.hashCode = function(){
	var hash = 0;
	if (this.length == 0) return this;
	for (i = 0; i < this.length; i++) {
		character = this.charCodeAt(i);
		hash = 31*hash+character;
		hash = hash & hash; // Convert to 32bit integer
	}
	return hash;
}
function dump(obj) {
    var out = '';
    for (var i in obj) {
        out += i + ": " + obj[i] + "\n";
    }

    alert(out);

    // or, if you wanted to avoid alerts...

    var pre = document.createElement('pre');
    pre.innerHTML = out;
    document.body.appendChild(pre)
}
// implement JSON.stringify serialization
var JSON = {};
JSON.stringify = JSON.stringify || function (obj) {
    var t = typeof (obj);
    if (t != "object" || obj === null) {
        // simple data type
        if (t == "string") obj = '"'+obj+'"';
        return String(obj);
    }
    else {
        // recurse array or object
        var n, v, json = [], arr = (obj && obj.constructor == Array);
        for (n in obj) {
            v = obj[n]; t = typeof(v);
            if (t == "string") v = '"'+v+'"';
            else if (t == "object" && v !== null) v = JSON.stringify(v);
            json.push((arr ? "" : '"' + n + '":') + String(v));
        }
        return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
    }
};

