
$(document).ready(function(){
	setupSlider();
	setupRollovers();
	setupPrefs();
	setupReset();
	setPrefsFromCookies();
	setupDrawers();
	setInterval("setupFontChange()", 1000);
	setupHeaderButtons();
});


var height_test_height = $('#height_test').height();

function setupFontChange() {
	if (height_test_height !=  $('#height_test').height()) {
		height_test_height = $('#height_test').height();
		repositionDrawers();
	}

}


function changeMain(newColour) {
	newColour = newColour ||  curprefs['main'];
	// Change all content links, except those classed as "unchanged"
	$("a").filter(":not(.unchanged, .tabs a)").css('color',newColour);
	// If reverting to default, make some links go back to grey:
	if (newColour == prefs['pref-green']) {
		$("#nav a, .button-large-top a").css('color', '#3a3a3a');
	}
	curprefs['main'] = newColour;
	$.cookie('pref-main', newColour, cookieOptions);
	$.cookie('pref-slider', $("#slider").slider('value'), cookieOptions);
}
function changeHeading(newColour) {
	newColour = newColour ||  curprefs['heading'];
	$('#content :header, #header-notice :header').css('color',newColour);
	curprefs['heading'] = newColour;
	$.cookie('pref-heading', newColour, cookieOptions);
}
function changeBody(newColour) {
	newColour = newColour ||  curprefs['body'];
	$('#content,#right-col,#header-notice').css('color',newColour);
	curprefs['body'] = newColour;
	$.cookie('pref-body', newColour, cookieOptions);
}
function changeBg(newColour) {
	newColour = newColour ||  curprefs['bg'];
	$('#content,#right-col,#wrapper,#header-notice,.contentbox').css('backgroundColor',newColour);
	if (newColour == prefs['pref-white']) {
		// Set contentbox back to default
		$('.contentbox').css('backgroundColor','#f4f3f3');
	}
	curprefs['bg'] = newColour;
	$.cookie('pref-bg', newColour, cookieOptions);
}
function changeSize(newSize) {
	// Close keys drawer first...
	closeKey();
	newSize = newSize ||  curprefs['size'];
	//$('#content,#right-col,#nav a,#prefs-body p').css('font-size', newSize);
	$('body').css('font-size', newSize);
	curprefs['size'] = newSize;
	//$('#key-wrapper').css('bottom',($('#footer').height()+$('#key-js-title').height())+"px");
	repositionDrawers();
	$.cookie('pref-size', newSize, cookieOptions);
}
function changeFont(newFont) {
	// Close keys drawer first...
	closeKey();
	newFont = newFont || curprefs['font'];
	//$('#content,#right-col,#nav a,#prefs-body p').css('font-size', newSize);
	$('body').css('fontFamily', newFont);
	curprefs['font'] = newFont;
	repositionDrawers();
	$.cookie('pref-font', newFont, cookieOptions);
}
function changeWidth(newWidth) {
	// Close keys drawer first...
	closeKey();
	newWidth = newWidth ||  curprefs['width'];
	if (newWidth == "medium") {
		$('body').css('background-image','url(/css/images/cogs-background-medium.gif)');
		$('#wrapper').css('width','758px');
		$('#content').css('width','516px');
		$('.contentCTA').css('marginLeft','13px');
	}
	else if (newWidth == "wide") {
		$('body').css('background-image','url(/css/images/cogs-background-wide.gif)');
		$('#wrapper').css('width','898px');
		$('#content').css('width','656px');
		$('.contentCTA').css('marginLeft','63px');
	}
	// Make sure drawers are in the right place by hiding then re-showing (FF bug):
	repositionDrawers();
	$('#prefs-wrapper,#key-wrapper').toggle();
	$('#prefs-wrapper,#key-wrapper').toggle();

	$.cookie('pref-width', newWidth, cookieOptions);
}

function setupSlider() {
	$("#slider").slider({
		'max':360,
		'value':79,
		'slide':function(e,ui){
			newColour = hsv2rgb(ui.value,87,61);
			changeMain(newColour);
		},
		'stop':function(e,ui){
			foo=1;
		}
	});
}

function setupRollovers() {
	// Make all non-content links (except those classed as "unchanged") have
	// the slider colour as their rollover
	//$("a").filter(":not(#content a)").filter(":not(.unchanged, .tabs a)").hover(function(){
	$(".button-large-top a, #nav a, #key-body a").hover(function(){
			if (curprefs['main'] == prefs['pref-green']) {
				$(this).css('color',curprefs['main']);
			}
			else {
				$(this).css('color',"#3a3a3a");
			}
		},function() {
			if (curprefs['main'] == prefs['pref-green']) {
				$(this).css('color','#3a3a3a');
			}
			else {
				$(this).css('color',curprefs['main']);
			}
		})
	.focus(function(){
		if (curprefs['main'] == prefs['pref-green']) {
			$(this).css('color',curprefs['main']);
		}
		else {
			$(this).css('color',"#3a3a3a");
		}
	})
	.blur(function() {
		if (curprefs['main'] == prefs['pref-green']) {
			$(this).css('color','#3a3a3a');
		}
		else {
			$(this).css('color',curprefs['main']);
		}
	});
	// Do the slider links too (these are "unchanged" so they stay grey,
	// but need the rollover changing)
	$("#prefs-slide,#prefs-help,#prefs-reset,#prefs-save").hover(function(){
			$(this).css('color',curprefs['main']);
		},function() {
			$(this).css('color','#3a3a3a');
		})
	.focus(function(){
		$(this).css('color',curprefs['main']);
	})
	.blur(function() {
		$(this).css('color','#3a3a3a');
	});
}


function setupPrefs() {
	$('.pref-main').click(function() {
		var newColour = prefs[$(this).attr('class').split(' ').slice(-1)];
		changeMain(newColour);		
		return(false);
	});
	$('.pref-heading').click(function() {
		var newColour = prefs[$(this).attr('class').split(' ').slice(-1)];
		changeHeading(newColour);
		if (shades[curprefs['heading']] == shades[curprefs['bg']]) {
			// Oops, heading now matches background
			// If we're now dark, make bg white, and if body is light then make body black
			// If we're now light, make bg black, and if body is dark then make body like us
			if (shades[curprefs['heading']] == "dark") {
				changeBg(prefs['pref-white']);
				if (shades[curprefs['body']] == "light") {
					changeBody(curprefs['heading']);
				}
			}
			else if (shades[curprefs['heading']] == "light") {
				changeBg(prefs['pref-black']);
				if (shades[curprefs['body']] == "dark") {
					changeBody(curprefs['heading']);
				}
			}
		}
		return(false);
	});
	$('.pref-body').click(function() {
		var newColour = prefs[$(this).attr('class').split(' ').slice(-1)];
		changeBody(newColour);
		if (shades[curprefs['body']] == shades[curprefs['bg']]) {
			// Oops, heading now matches background
			// If we're now dark, make bg white, and if heading is light then make heading like us
			// If we're now light, make bg black, and if heading is dark then make heading like us
			if (shades[curprefs['body']] == "dark") {
				changeBg(prefs['pref-white']);
				if (shades[curprefs['heading']] == "light") {
					changeHeading(curprefs['body']);
				}
			}
			else if (shades[curprefs['body']] == "light") {
				changeBg(prefs['pref-black']);
				if (shades[curprefs['heading']] == "dark") {
					changeHeading(curprefs['body']);
				}
			}
		}
		return(false);
	});
	$('.pref-bg').click(function() {
		var newColour = prefs[$(this).attr('class').split(' ').slice(-1)];
		changeBg(newColour);
		// Check if bg now matches body text:
		if (shades[curprefs['bg']] == shades[curprefs['body']]) {
			if (shades[curprefs['bg']] == "dark") {
				changeBody(prefs['pref-white']);
			}
			else if (shades[curprefs['bg']] == "light") {
				changeBody(prefs['pref-black']);
			}
		}
		// Check if bg now matches headings:
		if (shades[curprefs['bg']] == shades[curprefs['heading']]) {
			if (shades[curprefs['bg']] == "dark") {
				changeHeading(prefs['pref-white']);
			}
			else if (shades[curprefs['bg']] == "light") {
				changeHeading(prefs['pref-black']);
			}
		}
		return(false);
	});
	$('.pref-size').click(function() {
		var newSize = prefs[$(this).attr('class').split(' ').slice(-1)];
		changeSize(newSize);
		return false;
	});
	$('.pref-font').click(function() {
		var newFont = prefs[$(this).attr('class').split(' ').slice(-1)];
		changeFont(newFont);
		return false;
	});
	$('.pref-width').click(function() {
		var newWidth = prefs[$(this).attr('class').split(' ').slice(-1)];
		changeWidth(newWidth);
		return false;
	});
}

function setupReset() {
	$('#prefs-reset').click(function() {
		curprefs['main'] = prefs['pref-green'];
		curprefs['heading'] = prefs['pref-black'];
		curprefs['body'] = prefs['pref-black'];
		curprefs['bg'] = prefs['pref-white'];
		curprefs['size'] = prefs['pref-medium'];
		curprefs['font'] = prefs['pref-sans'];
		curprefs['width'] = prefs['pref-width-wide'];
		$("#slider").slider('value',79);
		changeMain();
		changeHeading();
		changeBody();
		changeBg();
		changeSize();
		changeFont();
		changeWidth();
		return false;
	});
}

function setPrefsFromCookies() {
	curprefs['main'] = 	$.cookie('pref-main') || prefs['pref-green'];
	curprefs['heading'] = $.cookie('pref-heading') || prefs['pref-black'];
	curprefs['body'] = $.cookie('pref-body') || prefs['pref-black'];
	curprefs['bg'] = $.cookie('pref-bg') || prefs['pref-white'];
	curprefs['size'] = $.cookie('pref-size') || prefs['pref-medium'];
	curprefs['font'] = $.cookie('pref-font') || prefs['pref-arialnarrow'];
	curprefs['width'] = $.cookie('pref-width') || prefs['pref-width-wide'];

	sliderVal = $.cookie('pref-slider') || 79;
	$("#slider").slider('value',sliderVal);
	changeMain();
	changeHeading();
	changeBody();
	changeBg();
	changeSize();
	changeFont();
	changeWidth();
}



function setupDrawers() {
	// Work around strange IE bug where these buttons get shown before the animation's finished...
	$('#prefs-reset,#prefs-save').css('visibility','hidden');

	// Remove IE6-specific top border:
	$('#prefs-wrapper').css('borderTop',0);

	// Move and repad the prefs box to be a drawer, not a rhc box
	$('#prefs-tohide').css('padding-top','20px');
	$('#prefs-wrapper').css({
		float:'none',
		position:'absolute',
		marginBottom:0,
		right:'9px',
		top:getPrefsDrawerOffset()+"px",
		zIndex:'2'
	});
	$('#prefs-reset').css({
		margin:0,
		float:'left'
	});
	$('#prefs-wrapper').prependTo($('#wrapper'));

	if (!$('#prefs-body').css('backgroundImage').match(/prefs-body-ie6/)) {
		// Hide slider from IE6
		$('#nonjs-slider, .non-js-separator').css('display','none');
		$('#slider-wrapper').toggle();
	}
	$('#prefs-tohide,#prefs-nonjs-title,#prefs-js-title,#prefs-top,#prefs-save').toggle();

	$('#right-col').css('paddingTop',($('#prefs-slide').height()+30)+"px");

	// Set up click event to show/hide the prefs drawer
	$('.prefs-slide,#prefs-reset,#prefs-save').click(function(e){
		e.preventDefault();
		if ($('#prefs-tohide').is(':visible')) {
			// Work around strange IE bug
			$('#prefs-reset,#prefs-save').css('visibility','hidden');
		}
		if (!$('#prefs-tohide').is(':visible')) {
			// Make us on top of key
			$('#prefs-wrapper').css('position','static');
			$('#prefs-wrapper').css('position','absolute');
			$('#prefs-wrapper').css('z-index',4);
			$('#key-wrapper').css('z-index',2);
		}
		$('#prefs-tohide').slideToggle(400, function(){
			if ($('#prefs-tohide').is(':visible')) {
				// Work around strange IE bug
				$('#prefs-reset,#prefs-save').css('visibility','visible');
			}
		});
		// Set the right column to be properly padded to allow
		// the content to be seen below the prefs tab
		$('#right-col').animate({paddingTop:($('#prefs-slide').height()+30)+"px"},0,0,function(){
			$('#key-wrapper').css('bottom',getKeyDrawerOffset()+'px');
		});
		return(false);
	});


	// Make the key drawer visible
	$('#key-wrapper').toggle()
	
	$('#footer').css('margin-top',($('#key-wrapper').height()+10)+"px");
	$('.key-slide,#key-top,#key-body,#key-close').click(function(){
		if (!$('#key-tohide').is(':visible')) {
			// Make us on top of prefs
			$('#key-wrapper').css('z-index',3);
			$('#prefs-wrapper').css('z-index',2);
		}
		$('#key-tohide').slideToggle(400, function(){
		});
		return false;
	});

	// repad the key drawer
	$('#key-wrapper').css('bottom',getKeyDrawerOffset()+'px');

	// Get IE6 to put the drawer in the right place...
	$('#key-wrapper').css('z-index',2);
}


function getKeyDrawerOffset() {
	// Add 20 on because the height() function doesn't seem to include the padding
	return $('#footer-wrapper').height();
}
function getPrefsDrawerOffset() {
	return $('#header-wrapper').height();
}

function repositionDrawers() {
	$('#key-wrapper').css('bottom',getKeyDrawerOffset()+'px');
	$('#prefs-wrapper').css('top',getPrefsDrawerOffset()+'px');
}

function closeKey() {
	if ($('#key-tohide').is(':visible')) {
		$('#key-tohide').toggle();
	}
}



function setupHeaderButtons() {
	// Set up any buttons in the header (e.g. "Yes", "no", "maybe")
	if ($('#header-buttons').length > 0) {
		$('#header-buttons a img').each(function(){
			//preload rollovers:
			$('<img>').attr('src',this.src.replace(/(\.[^.]+)$/, "-rolled$1"));
		});
		$('#header-buttons a img').hover(function(){
			this.src = this.src.replace(/(\.[^.]+)$/, "-rolled$1");
		},function(){
			this.src = this.src.replace(/-rolled(\.[^.]+)$/, "$1");
		});	
	}
	// Also just preload the tab images here...
	if ($('.tabs ul').length > 0) {
		$('<img>').attr('src', '/css/images/tab-active.gif');
		$('<img>').attr('src', '/css/images/tab.gif');
	}
}



function rgb2hex (rP, gP, bP) {
  var conv = function (x) {
    x = new Number(x);
    var s = x.toString(16);
    while(s.length < 2) { s = "0" + s; }
    return s;
  };
  if (rP instanceof Array) {
    var rgb = rP;
  }
  else { var rgb = [rP, gP, bP]; }
  var hex = [];
  for (var i = 0; i < rgb.length; i++) {
    hex.push(conv(rgb[i]));
  }
  hex.unshift("#");
  return hex.join('');
};

// Credits: Based on C Code in "Computer Graphics --
// Principles and Practice," Foley et al, 1996, p. 593.
// Input is h (0-360), s (0-100), v (0-100),
//    or [h,s,v] with same ranges
// Output is 0-255 range for each of [r,g,b]
function hsv2rgb (hP, sP, vP) {
  var h = null; var s = null; var v = null;
  if (hP instanceof Array) {
    h = hP[0] || 0;
    s = hP[1] || 0;
    v = hP[2] || 0;
  }
  else { h = hP; s = sP; v = vP; }
  if (h == 360) { h = 0; }
  s /= 100; v /= 100;
  var r = null; var g = null; var b = null;

  if (s == 0) {
    // Color is on black-and-white center line
    // achromatic: shades of gray
    r = v; g = v; b = v;
  }
  else {
    // Chromatic color
    var hTemp = h / 60;    // h is now IN [0,6]
    var i = Math.floor(hTemp);  // largest integer <= h
    var f = hTemp - i;    // fractional part of h
    var p = v * (1 - s);
    var q = v * (1 - (s * f));
    var t = v * (1 - (s * (1 - f)));

    switch(i) {
      case 0: r = v; g = t; b = p; break;
      case 1: r = q; g = v; b = p; break;
      case 2: r = p; g = v; b = t; break;
      case 3: r = p; g = q; b = v; break;
      case 4: r = t; g = p; b = v; break;
      case 5: r = v; g = p; b = q; break;
    }
  }

  r = Math.round(r * 255);
  g = Math.round(g * 255);
  b = Math.round(b * 255);
  //alert(r+" "+b+" "+g);
  return rgb2hex(r, g, b);
};



function hsv2rgb2(h,s,v) {
// Adapted from http://www.easyrgb.com/math.html
// hsv values = 0 - 1, rgb values = 0 - 255
var r, g, b;
var RGB = new Array();
if(s==0){
  RGB['red']=RGB['green']=RGB['blue']=Math.round(v*255);
}else{
  // h must be < 1
  var var_h = h * 6;
  if (var_h==6) var_h = 0;
  //Or ... var_i = floor( var_h )
  var var_i = Math.floor( var_h );
  var var_1 = v*(1-s);
  var var_2 = v*(1-s*(var_h-var_i));
  var var_3 = v*(1-s*(1-(var_h-var_i)));
  if(var_i==0){ 
    var_r = v; 
    var_g = var_3; 
    var_b = var_1;
  }else if(var_i==1){ 
    var_r = var_2;
    var_g = v;
    var_b = var_1;
  }else if(var_i==2){
    var_r = var_1;
    var_g = v;
    var_b = var_3
  }else if(var_i==3){
    var_r = var_1;
    var_g = var_2;
    var_b = v;
  }else if (var_i==4){
    var_r = var_3;
    var_g = var_1;
    var_b = v;
  }else{ 
    var_r = v;
    var_g = var_1;
    var_b = var_2
  }
  //rgb results = 0 ÷ 255  
  RGB['red']=(Math.round(var_r * 255 / 17) * 17).toString(16);
  RGB['red'] = RGB['red'].length == 2 ? RGB['red'] : "0"+RGB['red'];
  RGB['green']=(Math.round(var_g * 255 / 17) * 17).toString(16);
  RGB['green'] = RGB['green'].length == 2 ? RGB['green'] : "0"+RGB['green'];
  RGB['blue']=(Math.round(var_b * 255 / 17) * 17).toString(16);
  RGB['blue'] = RGB['blue'].length == 2 ? RGB['blue'] : "0"+RGB['blue'];
//  RGB['green']=Math.round(var_g * 255);
//  RGB['blue']=Math.round(var_b * 255);
  }
return "#"+RGB['red']+RGB['green']+RGB['blue'];  
};

