
$(document).ready(function () {
    // Grab the current date and hour to check against
    var currentDate = new Date();
    var currentHour = currentDate.getHours();

    // Grab the 'tsCookie' (we'll check if it was actually set later)
    var tsCookie = null;
    tsCookie = $.cookies.get('tsCookie');

    // Check if 'tsCookie' has a value...
    if (tsCookie != null) {
        // If it does, load that CSS file
        switchCSS(tsCookie);
    }
    else {
        // If not, load the appropriate CSS file depending on the current hour
        if (currentHour < 8 || currentHour >= 17) {
            switchCSS('night');
        }
        else {
            switchCSS('day');
        }
    }

    // Bind click events to swtiching links...
    $('#tsNightSwitch').click(function (e) {
        // Stop the normal "click" event stuff from happening to the user doesn't get taken to another page!
        e.preventDefault();
        // Set the 'tsCookie' to whatever CSS we're switching to
        $.cookies.set('tsCookie','night');
        // Do the switch!
        switchCSS('night');
    });
    $('#tsDaySwitch').click(function (e) {
        e.preventDefault();
        $.cookies.set('tsCookie','day');
        switchCSS('day');
    });
});

// Function that does the switches
function switchCSS(filename) {

	// For some reason, Safari 5.1 needs special treatment
	if ( $.browser.webkit )
	{
		$('link[title]').each(function () {
			var href = $(this).attr('href');

			if ( href.indexOf('main') == -1 )
			{
				if ( href.indexOf(filename) != -1 )
				{
					// Activate the selected stylesheet
					$(this).attr('disabled', false);
					// Extra fix for Safari 5.1
					$(this).attr('title','');
					$(this).attr('rel', 'stylesheet');
				}
				else
				{
					// Deactivate all other stylesheets
					$(this).attr('disabled', true);
					// Extra fix for Safari 5.1
					$(this).attr('title', filename);
					$(this).attr('rel', 'alternate stylesheet');
				}
			}
		});
	}
	else
	{
		// Disable all stylesheets with a 'title' attribute
		$('link[title]').attr('disabled', true);
		// Enable the stylesheet to switch to
		$('link[title=' + filename + ']').attr('disabled', false);
	}

}

