var rgb = new Array('r','g','b');
var areas = new Array('header','square','content','contentfooter','menuicon','menutext','rightmenuicon','rightmenutext','panel');
var areasUpdated = new Array();
var currentlyEditingId = false;

var globSliderLeft;
// calculate the left-hand-edge of the sliderWrapper div
// if we do this while dragging the slider, it's too slow

function setColour(colour) {
	if (currentlyEditingId) {
		document.getElementById('mainblock').style.backgroundImage = 'none';
		document.getElementById('mainblock').style.backgroundColor = colour;
		var reg = /rgb\((\d+), *(\d+), *(\d+)\)/;
		var matches = colour.match(reg);
		for (i=0; i<rgb.length; i++) {
			document.getElementById(rgb[i] + 'slider').style.left = sliderConversion('rgbtoslider',matches[i+1])+ 'px';
		}
		update();
		// update runs through all the updatable blocks on the page -- does it? er...
		// -- check this, it might be a bit of a bodge
	}
}

function update() {
	var r = sliderConversion('slidertorgb',parseInt(document.getElementById('rslider').style.left));
	var g = sliderConversion('slidertorgb',parseInt(document.getElementById('gslider').style.left));
	var b = sliderConversion('slidertorgb',parseInt(document.getElementById('bslider').style.left));
	if (!isNaN(r + g + b)) {
		var colour = 'rgb('+r+','+g+','+b+')';
		document.getElementById('mainblock').style.backgroundColor = colour;
		preview(currentlyEditingId,colour);
	}
}


function sliderConversion(type,n) {
	var r;
	slotWidth = parseInt(document.getElementById('r').style.width);
	sliderWidth = parseInt(document.getElementById('rslider').style.width);
	if (type == 'rgbtoslider') {
		r = parseInt(((slotWidth - sliderWidth)/255) * n);
	}
	else if (type == 'slidertorgb') {
		r = parseInt((255/(slotWidth - sliderWidth)) * n);
//		r = 255-r;
	}
	return r;
}

var drag = new Array();
drag['r'] = false;
drag['g'] = false;
drag['b'] = false;

function _sliderOver(t) {
	t.style.backgroundColor = '#ff0000';
}
function _sliderOut(t) {
	t.style.backgroundColor = '#990000';
}
function startSlide(rgbindex) {
	// reinitialise the position of the sliderwrapper -- this is necessary
	// if the user has just changed to a stylesheet that affects the location
	// of the slider wrapper [eg, flip.css].
	globSliderLeft = findPosX(document.getElementById('sliderwrapper'));
	drag[rgbindex] = true;
}
function stopSlide(rgbindex) {
	drag[rgbindex] = false;
}

function initCP() {
	document.getElementById('b').onmousemove=sliderMove;
	document.getElementById('g').onmousemove=sliderMove;
	document.getElementById('r').onmousemove=sliderMove;
	// This is slight duplication of setColour(), but I don't think it matters:
	var b = document.getElementById('mainblock').style.backgroundColor;
	var reg = /rgb\((\d+), *(\d+), *(\d+)\)/;
	var matches = b.match(reg);
	for (i=0; i<rgb.length; i++) {
		document.getElementById(rgb[i] + 'slider').style.left = sliderConversion('rgbtoslider',matches[i+1])+ 'px';
	}	
	// initialise the position of the sliderwrapper:
	globSliderLeft = findPosX(document.getElementById('sliderwrapper'));
}

function sliderMove(e) {
	mydrag = drag[this.id];
	/* OLD STUFF -- hopefully redundant, just need to check in IE/PC: */
	// var h = document.getElementById('header');
	// var w = h.offsetWidth+10;	
	// right -- this calculates the left-point of the sliderwrapper
	// by getting the width of the header and adding ten [the page indent]
	// surely I can just get the x-coordinate of the sliderwrapper itself?
	//debug(findPosX(document.getElementById('sliderwrapper')) + ',' + w + ':');
	//w = findPosX(document.getElementById('sliderwrapper'));
	w = globSliderLeft;
	if (!e) {
		var e=window.event;
	}
	if (mydrag) {
		var x = e.clientX - w;
		var halfSlider = parseInt(document.getElementById('rslider').style.width)/2;
		var slotWidth = parseInt(document.getElementById('r').style.width);
		var sliderIndent = 20;
		// technically, .sliderlabel width, plus 4px for border/padding of outerdiv, plus a 6px indent [.rgbslider padding]

		if (x > (sliderIndent+halfSlider-1) && x < (slotWidth+sliderIndent-halfSlider+1)) {
			x -= halfSlider;
			x -= sliderIndent;
			document.getElementById(this.id + 'slider').style.left = x + 'px';
			x = sliderConversion('slidertorgb',x);
			update();
		}
	}
}

function editArea(id) {
	
	// if this is the first time we've edited an area, turn the buttons "on" etc:
	if (!currentlyEditingId) {
		toggleInterface(true);
	}
	// right, the relevant style rules are either:
	// .[id] div -- for standard divs
	// [id]colour div -- for divs that appear multiple times, such as the menu icons and options
	// .sub[id] -- for divs that have a uniquely-named inner, such as the content div
	// SO:
	
	var c = document.getElementById(id + '_preview').style.backgroundColor;
	if (!c) {
		var styleRule;
		var styleRules = new Array('.' + id + ' div','.' + id + 'colour div','.sub' + id);
		for (a=0; a<areas.length; a++) {
			if (id == areas[a]) {
				var sf;
				for (s=0; s<styleRules.length; s++) {
					sf = findStyleRule(styleRules[s]);
					if (sf) {
						c = sf.style.backgroundColor;
					}
				}
			}
		}
	}
	currentlyEditingId = id;
	areasUpdated.push(id);
	setColour(c);
	
}
function preview(i,c) {
	var headeroptions = false;
	var squareoptions = false;
	var contentoptions = false;
	var contentfooteroptions = false;
//	var menuiconoptions = new Array('home','why','how','demos','portfolio','cost','contact','footer');
	var menuiconoptions = new Array('home','cv','portfolio','demo','contact','footer');
	var menutextoptions = menuiconoptions;
	var rightmenuiconoptions = new Array('colours','edit');
	var rightmenutextoptions = new Array('colours','edit','footer');
	var paneloptions = new Array('left','right','colourscheme');
	var previewid = new Array();
	for (a=0; a<areas.length; a++) {
		if (i == areas[a]) {
			if (eval(i + 'options')) { // if we've got an array of multiple divs for this area
				for (m=0; m<eval(i + 'options').length; m++) {
					previewid.push('sub' + i + '_' + eval(i + 'options')[m]);
				}
			}
			else {
				previewid.push('sub' + areas[a]);
			}
			previewid.push(areas[a] + '_preview');
		}
	}
	for (u=0; u<previewid.length; u++) {
		document.getElementById(previewid[u]).style.backgroundColor = c;
		if (isDark(c)) {
			document.getElementById(previewid[u]).style.color = '#ffffff';
		}
		else {
			document.getElementById(previewid[u]).style.color = '#000000';
		}
	}
}

function findStyleRule(styleName) {
	var s;
	for (i=0; i<document.styleSheets.length; i++ ) {
		// This shouldn't be necessary -- how do you refer to a stylesheet by name/id?
		if (document.styleSheets[i].title == getActiveStyleSheet()) {
			s = document.styleSheets[i];
		}
	}
	var r = (s.rules)?s.rules:s.cssRules;
	if (styleName.match(/ /) && s.rules) {
		// if we're looking for a nested style and using IE:
		var sn = styleName.split(' ');
		styleName = sn[0] + ' ' + sn[1].toUpperCase();
	}
	for (j = 0; j < r.length; j++) {
		if (r[j].selectorText == styleName) {
			return r[j];
		}
	}
	return false;
}

function mySend() {
	window.open('cmail.php','emailme','width=306,height=134');
}

function myReset() {
	setActiveStyleSheet('default');
	document.location = 'demo.php?cssCLEAR=1';
}

function mySave(send) {
	var post = '';
/*	for (d=0; d<areasUpdated.length; d++) {
		var c = document.getElementById(areasUpdated[d] + '_preview').style.backgroundColor;
		var reg = /rgb\((\d+), *(\d+), *(\d+)\)/;
		var matches = c.match(reg);
		post += areasUpdated[d]+'.'+matches[1]+','+matches[2]+','+matches[3];
		post = (d==areasUpdated.length-1)?post:post+'#';
	} */
	for (a=0; a<areas.length; a++) {
		// DUPLICATE CODE from editArea() above...
		var id = areas[a];
		var c = document.getElementById(id + '_preview').style.backgroundColor;
		if (!c) {
			var styleRule;
			var styleRules = new Array('.' + id + ' div','.' + id + 'colour div','.sub' + id);
			var sf;
			for (s=0; s<styleRules.length; s++) {
				sf = findStyleRule(styleRules[s]);
				if (sf) {
					c = sf.style.backgroundColor;
				}
			}
		}
		var reg = /rgb\((\d+), *(\d+), *(\d+)\)/;
		var matches = c.match(reg);
		post += areas[a]+'.'+matches[1]+','+matches[2]+','+matches[3];
		post = (a==areas.length-1)?post:post+'#';
	}	
	document.getElementById('fmUpdate').value = post;
	document.getElementById('fmSend').value = send;
	document.getElementById('fm').submit();
}	

function debug(d) {
	window.status=d;
}

function toggleInterface(d) {
	
	var buttons = new Array('save');
	for (bb=0; bb<buttons.length; bb++) {
		// Why on earth does IE get in a mood if I use b and not bb?
		document.getElementById(buttons[bb]).disabled = !d;
	}
	
	for (c=0; c<rgb.length; c++) {
		if (!d) {
			document.getElementById(rgb[c]).style.backgroundColor = '#dddddd';
			document.getElementById(rgb[c] + 'slider').style.visibility = 'hidden';
			document.getElementById(rgb[c] + 'sliderlabel').style.color = '#666666';
		}
		else {
			document.getElementById(rgb[c]).style.backgroundColor = '#ffffff';
			document.getElementById(rgb[c] + 'slider').style.visibility = 'visible';
			document.getElementById(rgb[c] + 'sliderlabel').style.color = '#000000';
		}
	} 
}

function isDark(c) {
	var reg = /rgb\((\d+), *(\d+), *(\d+)\)/;
	var matches = c.match(reg);
	var total = parseInt(matches[1]) + parseInt(matches[2]) + parseInt(matches[3]);
	if (total < 180) {
		return true;
	}
	return false;
}

function findPosX(obj) {
	var curleft = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x) {
		curleft += obj.x;
	}
	return curleft;
}