var active_skin = 'skin01';
$(document).ready(function(){
	resetAccessibility();

	if ($.cookie('accessibility') == null) {
		setAccessibility();
	}

	if ($.cookie('accessibility') != null) {
		var access_settings = $.evalJSON($.cookie('accessibility'));
		if (access_settings.skin == '1') {
			active_skin = 'skin01';
		} else if (access_settings.skin == '2') {
			active_skin = 'skin02';
		} else if (access_settings.skin == '3') {
			active_skin = 'skin03';
		} else {
			active_skin = 'skin01';
		}
		initAccessibility();
	}

	$('DIV.access02 INPUT[type=radio]').unbind('mouseup mousedown click change').bind('mouseup mousedown click change',function(){
		$(this).parents('UL').eq(0).find('LABEL').removeClass('active');
		$(this).parents('LABEL').eq(0).addClass('active');
	});

	$('IMG[src*="skin01"]').each(function(i, v){
		try {
			if ($(v).attr('src').indexOf('img/skin01/') != -1) {
				$(v).attr('src', $(v).attr('src').replace('/skin01/', '/' + active_skin + '/'));
			}
		} catch (e) { }
	});

	if(access_settings.skin && access_settings.colorsdisabled != true && access_settings.stylesdisabled != true) {
		setTimeout(function() {
			setStylesheet(access_settings.skin);
		}, 1000);
	} else {
		setTimeout(function() {
			setStylesheet(0);
			if (access_settings.stylesdisabled == true) {
				$('link[rel*=stylesheet]').attr('disabled','disabled');
			}
		}, 1000);
	}

	setTimeout("resetAccessibility();", 1000);
});

function setStylesheet(no) {
	$('#skin01').attr('disabled', 'disabled').attr('disabled',(no == '1' ? '' : 'disabled'));
	$('#skin02').attr('disabled', 'disabled').attr('disabled',(no == '2' ? '' : 'disabled'));
	$('#skin03').attr('disabled', 'disabled').attr('disabled',(no == '3' ? '' : 'disabled'));
}

// Init styles before content rendering
function initAccessibility() {
	if ($.cookie('accessibility') != null) {
		var accessdefaults = $.evalJSON($.cookie('accessibility'));
		var tmpclass = $('BODY')[0].className;
		tmpclass = tmpclass.replace(/ fontsize([0-9])/, '');
		tmpclass = tmpclass.replace(/ lineheight([0-9])/, '');
		//tmpclass = tmpclass.replace(/ skin([0-9])/, '');
		setStylesheet(accessdefaults.skin);
		
		if (accessdefaults.stylesdisabled == true) { $('link[rel*=stylesheet]').attr('disabled','disabled'); }
		if (accessdefaults.colorsdisabled == true) { setStylesheet(0); }
		$('BODY')[0].className = tmpclass;
		$('BODY').addClass('fontsize' + accessdefaults.fontsize).addClass('lineheight' + accessdefaults.lineheight);
		if (accessdefaults.highlight == true) {
			setHighlight(1);
		} else {
			setHighlight(0);
		}
	}
}
// Set cookie and new styles
function setAccessibility() {
	var tmpclass = $('BODY')[0].className;
	tmpclass = tmpclass.replace(/ fontsize([0-9])/, '');
	tmpclass = tmpclass.replace(/ lineheight([0-9])/, '');
	// tmpclass = tmpclass.replace(/ skin([0-9])/, '');
	$('BODY')[0].className = tmpclass;
	$('BODY')
		.addClass('fontsize' + $('#access-fontsize INPUT:checked').val() )
		.addClass('lineheight' + $('#access-lineheight INPUT:checked').val() )
	;
	if ($('#access-stylesdisabled').is(':checked')) {
		$('link[rel*=stylesheet]').attr('disabled','disabled');
		setStylesheet(0);
	} else {
		$('link[rel*=stylesheet]').attr('disabled','');
		setStylesheet(($('#access-skin INPUT:checked').val() ? $('#access-skin INPUT:checked').val() : 1));

		if ($('#access-colorsdisabled').is(':checked')) {
			setStylesheet(0);
		} else {
			setStylesheet(($('#access-skin INPUT:checked').val() ? $('#access-skin INPUT:checked').val() : 1));
		}
	}
	if ($('#access-highlight').is(':checked')) {
		setHighlight(1);
	} else {
		setHighlight(0);
	}
	
	var accessdefaults = {
		fontsize: $('#access-fontsize INPUT:checked').val(),
		lineheight: $('#access-lineheight INPUT:checked').val(),
		skin: ($('#access-skin INPUT:checked').val() ? $('#access-skin INPUT:checked').val() : 1),
		stylesdisabled: $('#access-stylesdisabled').is(':checked') ? true : false,
		colorsdisabled: $('#access-colorsdisabled').is(':checked') ? true : false,
		highlight: $('#access-highlight').is(':checked') ? true : false
	}
	//$.cookie('accessibility', $.toJSON(accessdefaults), {path: js_site_url, expires: 999});
	document.cookie = 'accessibility='+$.toJSON(accessdefaults)+';path='+js_site_url;
}
// Cancel changes and reset to initial state
function resetAccessibility() {
	if ($.cookie('accessibility') != null) {
		var accessdefaults = $.evalJSON($.cookie('accessibility'));
		$('DIV.access02 LABEL.active').removeClass('active');
		$('DIV.access02 INPUT:checked').attr('checked',false);
		$('#access-fontsize LABEL.fs' + accessdefaults.fontsize).addClass('active').find('INPUT').attr('checked',true);
		$('#access-lineheight LABEL.fs' + accessdefaults.lineheight).addClass('active').find('INPUT').attr('checked',true);
		$('#access-skin LABEL.skin' + accessdefaults.skin).addClass('active').find('INPUT').attr('checked',true);
		if(accessdefaults.stylesdisabled == true){ $('#access-stylesdisabled').attr('checked',true); } else { $('#access-stylesdisabled').attr('checked',false); }
		if(accessdefaults.colorsdisabled == true){ $('#access-colorsdisabled').attr('checked',true); } else { $('#access-colorsdisabled').attr('checked',false); }
		if(accessdefaults.highlight == true){ $('#access-highlight').attr('checked',true); } else { $('#access-highlight').attr('checked',false); }
	}
}
function defaultAccessibility(){
	$('DIV.access02 LABEL.active').removeClass('active');
	$('DIV.access02 INPUT:checked').attr('checked',false);
	$('#access-fontsize LABEL.fs2').addClass('active').find('INPUT').attr('checked',true);
	$('#access-lineheight LABEL.fs2').addClass('active').find('INPUT').attr('checked',true);
	$('#access-skin LABEL.skin1').addClass('active').find('INPUT').attr('checked',true);
	$('#access-stylesdisabled').attr('checked',false);
	$('#access-colorsdisabled').attr('checked',false);
}

// Set container parents
function setAccessibilityOption(ref, type, val) {
	var $ref = $(ref);
	$ref.parents('UL').eq(0).find('.active').removeClass('active');
	$ref.addClass('active');
	return false;
}

// Access panel display function
function showAccess() {
	if ($('#accessibilitypanel').length == 0) {
		$('BODY').prepend('<div id="accessibilitypanel"></div>');
		$('#accesslink').parents('LI').eq(0).addClass('active');
		$('#access01 DIV.access01').clone(true).prependTo('#accessibilitypanel');
		$('#access01 DIV.access01').remove();
		$('DIV.access02 INPUT[type=radio]').unbind('mouseup mousedown click change').bind('mouseup mousedown click change',function(){
			$(this).parents('UL').eq(0).find('LABEL').removeClass('active');
			$(this).parents('LABEL').eq(0).addClass('active');
		});
		window.location = '#accessibility';
	} else {
		$('#accessibilitypanel DIV.access01').clone(true).prependTo('#access01');
		$('#accessibilitypanel').remove();
		$('#accesslink').parents('LI').eq(0).removeClass('active');
	}
	// IE Fix: reset selected values
	if ($.browser.msie) {
		resetAccessibility();
	}
	return false;
}

function setHighlight(n){
	if(n == 1){
		$('BODY').addClass('stronghighlight');
	} else {
		$('BODY').removeClass('stronghighlight');
	}
}

/*jslint browser: true */ /*global jQuery: true */

/**
 * 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
 *
 */

// TODO JsDoc

/**
 * Create a cookie with the given key and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String key The key of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given key.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String key The key of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
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;
};
/*
 * jQuery JSON Plugin
 * version: 2.1 (2009-08-14)
 *
 * This document is licensed as free software under the terms of the
 * MIT License: http://www.opensource.org/licenses/mit-license.php
 *
 * Brantley Harris wrote this plugin. It is based somewhat on the JSON.org
 * website's http://www.json.org/json2.js, which proclaims:
 * "NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.", a sentiment that
 * I uphold.
 *
 * It is also influenced heavily by MochiKit's serializeJSON, which is
 * copyrighted 2005 by Bob Ippolito.
 */

 (function($) {
	/** jQuery.toJSON( json-serializble )
	 Converts the given argument into a JSON respresentation.
	 If an object has a "toJSON" function, that will be used to get the representation.
	 Non-integer/string keys are skipped in the object, as are keys that point to a function.
	 json-serializble:
	 The *thing* to be converted.
	 **/
	$.toJSON = function(o) {
		if (typeof(JSON) == 'object' && JSON.stringify)
			return JSON.stringify(o);
		var type = typeof(o);
		if (o === null)
			return "null";
		if (type == "undefined")
			return undefined;
		if (type == "number" || type == "boolean")
			return o + "";
		if (type == "string")
			return $.quoteString(o);
		if (type == 'object') {
			if (typeof o.toJSON == "function")
				return $.toJSON(o.toJSON());
			if (o.constructor === Date) {
				var month = o.getUTCMonth() + 1;
				if (month < 10)
					month = '0' + month;
				var day = o.getUTCDate();
				if (day < 10)
					day = '0' + day;
				var year = o.getUTCFullYear();
				var hours = o.getUTCHours();
				if (hours < 10)
					hours = '0' + hours;
				var minutes = o.getUTCMinutes();
				if (minutes < 10)
					minutes = '0' + minutes;
				var seconds = o.getUTCSeconds();
				if (seconds < 10)
					seconds = '0' + seconds;
				var milli = o.getUTCMilliseconds();
				if (milli < 100)
					milli = '0' + milli;
				if (milli < 10)
					milli = '0' + milli;
				return '"' + year + '-' + month + '-' + day + 'T' + hours + ':' + minutes + ':' + seconds + '.' + milli + 'Z"';
			}
			if (o.constructor === Array) {
				var ret = [];
				for (var i = 0; i < o.length; i++)
					ret.push($.toJSON(o[i]) || "null");
				return "[" + ret.join(",") + "]";
			}
			var pairs = [];
			for (var k in o) {
				var name;
				var type = typeof k;
				if (type == "number")
					name = '"' + k + '"';
				else if (type == "string")
					name = $.quoteString(k);
				else
					continue;
				//skip non-string or number keys
				if (typeof o[k] == "function")
					continue;
				//skip pairs where the value is a function.
				var val = $.toJSON(o[k]);
				pairs.push(name + ":" + val);
			}
			return "{" + pairs.join(", ") + "}";
		}
	};
	/** jQuery.evalJSON(src)
	 Evaluates a given piece of json source.
	 **/
	$.evalJSON = function(src) {
		if (typeof(JSON) == 'object' && JSON.parse)
			return JSON.parse(src);
		return eval("(" + src + ")");
	};
	/** jQuery.secureEvalJSON(src)
	 Evals JSON in a way that is *more* secure.
	 **/
	$.secureEvalJSON = function(src) {
		if (typeof(JSON) == 'object' && JSON.parse)
			return JSON.parse(src);
		var filtered = src;
		filtered = filtered.replace(/\\["\\\/bfnrtu]/g, '@');
		filtered = filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
		filtered = filtered.replace(/(?:^|:|,)(?:\s*\[)+/g, '');
		if (/^[\],:{}\s]*$/.test(filtered))
			return eval("(" + src + ")");
		else
			throw new SyntaxError("Error parsing JSON, source is not valid.");
	};
	/** jQuery.quoteString(string)
	 Returns a string-repr of a string, escaping quotes intelligently.
	 Mostly a support function for toJSON.
	 Examples:
	 >>> jQuery.quoteString("apple")
	 "apple"
	 >>> jQuery.quoteString('"Where are we going?", she asked.')
	 "\"Where are we going?\", she asked."
	 **/
	$.quoteString = function(string) {
		if (string.match(_escapeable)) {
			return '"' + string.replace(_escapeable, function(a) {
				var c = _meta[a];
				if (typeof c === 'string')
					return c;
				c = a.charCodeAt();
				return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
			}) + '"';
		}
		return '"' + string + '"';
	};
	var _escapeable = /["\\\x00-\x1f\x7f-\x9f]/g;
	var _meta = {
		'\b': '\\b',
		'\t': '\\t',
		'\n': '\\n',
		'\f': '\\f',
		'\r': '\\r',
		'"': '\\"',
		'\\': '\\\\'
	};
})(jQuery);

