/**
* jQuery Cookie plugin
*
* Copyright (c) 2010 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
jQuery.cookie = function (key, value, options) {

    // key and value given, set cookie...
    if (arguments.length > 1 && (value === null || typeof value !== "object")) {
        options = jQuery.extend({}, options);

        if (value === null) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? String(value) : encodeURIComponent(String(value)),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};


// my code
$(document).ready( function() {

	/* set up event handlers */

	/* important functionality */
	// form submit: validation etc
	$('form[0]').submit( function() {
		$("input[type='search']").focus(); // usability
		if ( $.trim($("input[type='search']").val()).length==0 )
		{
			return false;
		}
	});
	/* one-click searching stuff */
	function one_click_setup()
	{
		var is_one_click = $('#oneclick input').attr('checked');
		$.cookie('oneclick', is_one_click, { expires: 100, path: '/' });
		if (is_one_click)
		{
			$('body').addClass('oneclick');
			$('#options a').click( function() {
				$(this).parent().children('input').click();
				$('form[0]').submit();
				return false;
			});
		}
		else
		{
			$('body').removeClass('oneclick');
			$('#options a').unbind('click');
		}
	}
	$('#oneclick input').click( function() {
		one_click_setup();
		$("input[type='search']").focus(); // usability
		// logging
		if ($('#oneclick input').attr('checked'))
		{
			_gaq.push(['_trackEvent', 'Page Settings', 'One-click', 'turn on']);
		}
		else
		{
			_gaq.push(['_trackEvent', 'Page Settings', 'One-click', 'turn off']);
		}
	});
	/* form target stuff */
	function target_setup()
	{
		if ($('#newwindow input').attr('checked'))
		{
			$('form[0]').attr('target', '_blank');
			$.cookie('target', '_blank', { expires: 100, path: '/' });
		}
		else
		{
			$('form[0]').attr('target', '_self');
			$.cookie('target', '_self', { expires: 100, path: '/' });
		}
	}
	$('#newwindow input').click( function() {
		target_setup();
		$("input[type='search']").focus(); // usability
		// logging
		if ($('#newwindow input').attr('checked'))
		{
			_gaq.push(['_trackEvent', 'Page Settings', 'New window', 'turn on']);
		}
		else
		{
			_gaq.push(['_trackEvent', 'Page Settings', 'New window', 'turn off']);
		}
	});
	/* usability enhancements */
	// which tool is being used
	$('#searchtop').after('<div id="searchhelp"></div>');
	$('#options input').click( function() {
		$.cookie('tool', this.value, { expires: 100 });
		// for indicating which option is selected; remove selected state from everything then re-add to the selected item
		$('#options a').removeClass('selected');
		$(this).parent().children('a').addClass('selected');
		if ($('.tool_'+this.value).size()==1)
		{
			$('#searchhelp').html($(this).parent().children('a').html() + ' || ' + $('.tool_'+this.value).html());
		}
		else
		{
			$('#searchhelp').html('');
		}
		$("input[type='search']").focus(); // usability
	});
	// when user clicks on section name, select the first option in that section
	$('#options legend').click( function() {
		$(this).parent().find('input').first().click();
	});
	$(window).unload( function() {
		$.cookie('q', $("input[type='search']").val(), { path: '/' });
	});


	/* actually do stuff */
	// use cookie value for q (if no q already)

	if ($.trim($("input[type='search']").val())=='' && $.trim($.cookie('q')))
	{
		$("input[type='search']").attr('value', $.cookie('q'));
	}
	// sets focus if browser doesn't support html5's @autofocus
	if (!('autofocus' in document.createElement('input')))
	{
		$("input[type='search']").focus();
	}
	// one click stuff
	if ($.cookie('oneclick')=='true')
	{
		$('#oneclick input').attr('checked', 'checked');
		one_click_setup();
	}
	// form target stuff
	if ($.cookie('target') == '_blank')
	{
		$('#newwindow input').attr('checked', 'checked');
		target_setup();
	}
	// if there is no tool=FOO in the URL and there is a tool that is saved in the cookie and it isn't already checked, then check it
	var tool = /tool=([a-z0-9]+)/i.exec(location.href);
	if (!tool && $.cookie('tool') && !$("#options input[value='"+$.cookie('tool')+"']").attr('checked'))
	{
		$("#options input[value='"+$.cookie('tool')+"']").click();
	}



	if (screen.width < 1100)
	{
		$('body').css({'border-width': '0'});
		$('div#searchtop label').css({'float': 'inherit','margin-left': '0'});
		$('div#meta').css({'right': '0'});
		/*
		if ($('#options div').size()>3)
		{
			$('#options label, #options legend').css({'font-size': '9pt'});
		}
		*/
	}
	if ($('#options div').size()==4)
	{
		$('fieldset#options div').css({'margin-right': '4em'});
	}
	if ($('#options div').size()<4)
	{
		$('fieldset#options div').css({'margin-right': '6em'});
	}

});

// logging
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-13006445-2']);
_gaq.push(['_trackPageview']);
(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);
})();
