var firstTickBoxIndex = 2, ready = false, oi = 0;

function check () {
	if (!ready) {
		alert("Please wait for page to finish loading!");
		return false;
	}
	if (f.search.value == "") {
		alert("You haven't entered anything to search for!");
		return false;
	}
	var e = f.elements;
	var s = "";
	for (var i = firstTickBoxIndex; i < e.length; i++) {
		if (e[i].type == "checkbox" && e[i].checked) {
			s += " " + e[i].value;
		}
	}
	if (s == "") {
		alert("You haven't selected any sites to search!");
		return false;
	}
	f.sites.value = s.substring(1);
	return true;
}

function tick (tfa) {
	var isTF = typeof tfa == "boolean";
	if (!isTF) { tfa = "," + tfa + ","; } // makes searching easier!
	var tf, idx = 0;
	for (var i = firstTickBoxIndex; i < f.length; i++) {
		if (f.elements[i].type == "checkbox") {
			tf = isTF ? tfa : (tfa.indexOf("," + f.elements[i].value + ",") >= 0);
			if (f.elements[i].disabled) { tf = false; }
			idx++;
			f.elements[i].checked = tf;
		}
	}
	return void(0);
}

var formats = ['dvd', 'hddvd', 'bluray', 'cd', 'mp3', 'game'];
var prependTo = ['cd', 'mp3', 'game'];
var format, scopes, scope, f;
function loaded () {
	f = $('searchForm');
	f.search.focus();
	f.search.select();
	format = f.format.value = "";
	scope = f.scope.value = "";
	var toHover = $$('.option');
	for (var i = 0; i < toHover.length; i++) {
		var e = $(toHover[i]);
		e.setStyle({ opacity: 0.25 }); // For IE, else they're not grey :-(
		setHover(e);
	}
	$('hide1').setStyle({ opacity: 0 });
	$('hide2').setStyle({ opacity: 0 });
	$('withinPad').hide();
	$('within').show();
	maxPages = f['max-pages'].value = 1;
	$('depth1').setStyle({ opacity: 1 });
	setFormat(firstFormat, true);
	setSize(true);
	$('ajaxY').setStyle({ opacity: 1 });
	Event.observe(window, 'resize', setSize);
	$('go').disabled = false;
	ready = true;
	if (numOffers > 1) { setInterval(showOffer, 5000); }
	$('query').observe('keyup', searchHelp);
}

var helpTimeout;
function searchHelp (event) {
	if (helpTimeout != null) {
		clearTimeout(helpTimeout);
	}
	helpTimeout = setTimeout(searchHelp2, 1000);
}

var reSeries  = /\b(?:series|season)\b/i;
var reSeries2 = /\b(?:series|season)\s*\d+\b/i;
var reNumber  = /\b\d+\b/;
var reNumLtr  = /[a-z]\d|\d[a-z]/i;
var reAnd     = /(?:\band\b|&)/i;
var reThe     = /\bthe\b/i;
function searchHelp2 () {
	helpTimeout = null;
	var q = $('query').value;
	var li = new Array();
	if (q.match(reSeries2)) {
		li.push(new Element('li').update('Don\'t use phrases like <i>series 2</i> or <i>season 2</i> as you can\'t tell which words a website will use &#8211; it could be even be listed as <i>second season</i>, for example.'));
	} else if (q.match(reSeries)) {
		li.push(new Element('li').update('Don\'t use the words <i>series</i> or <i>season</i> as you can\'t tell which one a website will use.'));
	}
	if (q.match(reNumber)) {
		li.push(new Element('li').update('Only use a number if you\'re sure it will be written exactly that way in the name &#8211; <i>2</i> won\'t match <i>two</i> or <i>second</i>, for example.'));
	}
	if (q.match(reNumLtr)) {
		li.push(new Element('li').update('Be careful using letters and numbers together without spaces between &#8211; it must match exactly what you\'ve written.'));
	}
	if (q.match(reAnd)) {
		li.push(new Element('li').update('Avoid using <i>and</i> or <i>&amp;</i> because you can\'t tell which a website will use.'));
	}
	if (q.match(reThe)) {
		li.push(new Element('li').update('Don\'t use the word <i>the</i> unless you\'re sure it will be in that position &#8211; <i>the west wing</i> might be listed on some websites as <i>west wing, the</i> for example.'));
	}
	if (li.length != 0) {
		var ul = new Element('ul');
		for (var i = 0; i < li.length; i++) {
			ul.appendChild(li[i]);
		}
		$('help').update(ul);
		if (!$('helpP').visible()) {
			$('helpP').appear({ duration: 0.5 });
		}
	} else {
		if ($('helpP').visible()) {
			$('helpP').fade({ duration: 0.5 });
		}
	}
}

function highlight () {
	fade(format, 1);
	var pre = prependTo.member(format) ? format + '-' : '';
	fade(pre + scope, 1);
	hi(format);
	hi(pre + scope);
}

function hi (e) {
	new Effect.Highlight(e, { delay: 0.5, startcolor: '#ffff000', endcolor: '#8fbfbf' });
}

function fade (e, o) {
	if (e == null || e == '') { return; }
	var o0 = $(e).getStyle('opacity');
	if (o0 == null || o0 != o) {
		new Effect.Fade(e, { to: o, duration: 0.25 });
	}
}

function setYN (name, yn) {
	if (yn) {
		fade(name + 'N', 0.25);
		fade(name + 'Y', 1);
		f[name].value = 'true';
	} else {
		fade(name + 'Y', 0.25);
		fade(name + 'N', 1);
		f[name].value = 'false';
	}
}

function setFormat (fmt, first) {
	if (format == fmt) {
		f.search.focus();
		f.search.select();
		return;
	}
	if (first) {
		format = f.format.value = fmt;
		new Effect.Appear(scopes = getScopes(), { duration: 0.25, afterFinish: highlight });
	} else {
		fade(format, 0.25);
		fade(format = f.format.value = fmt, 1);
		var scps = getScopes();
		if (scps != scopes) {
			new Effect.Fade(scopes, { duration: 0.25, afterFinish: function () { new Effect.Appear(scopes = scps, { duration: 0.25 }); } });
		}
	}
	scope = fs.get(format);
	setScope(null);
}

function getScopes () {
	return format == 'cd' ? 'cdScope' : (format == 'game' ? 'gameScope' : (format == 'mp3' ? 'mp3Scope' : 'noScope'));
}

function setScope (scp) {
	if (scope == scp) {
		f.search.focus();
		f.search.select();
		return;
	}
	var pre = prependTo.member(format) ? format + '-' : '';
	if (scp == null) {
		$(pre + scope).setStyle({ opacity: 1 });
		f.scope.value = scope;
	} else {
		fade(pre + scope, 0.25);
		fade(pre + (scope = f.scope.value = scp), 1);
	}
	fs.set(format, scope);
	fadeSites();
	f.search.focus();
	f.search.select();
}

function fadeSites () {
	var impl = ',' + media.get(format + '-' + scope) + ','; // makes searching easier!
	for (var i = 0; i < sites.length; i++) {
		fade($('site' + sites[i]), (impl != null && impl.indexOf(',' + sites[i] + ',') >= 0) ? 1 : 0.33);
	}
}

function overMe (event) {
	Event.element(event).setStyle({ backgroundColor: 'white' });
}

function notOverMe (event) {
	Event.element(event).setStyle({ backgroundColor: 'transparent' });
}

function setHover (e) {
	Event.observe(e, 'mouseover', overMe);
	Event.observe(e, 'mouseout', notOverMe);
}

var maxPagesOpts = [1, 2, 3, 4, 5, 10, 25, 0];
function setMaxPages (v) { // v is something like 'depth5' => 5
	v = v.substring(5) - 0;
	if (maxPages == v) { return; }
	if (v == 0) {
		if (!confirm("Are you absolutely sure you DON'T want to limit the number of pages searched?	 Sometimes there can be hundreds, and that would take ages to search!	 Surely 25 would be enough, wouldn't it?\n\nClick OK if you're really, really sure, or Cancel to choose 25 pages instead.")) { v = 25; }
	}
	maxPages = f['max-pages'].value = v;
	fadeMaxPages();
}
function fadeMaxPages () {
	for (var i = 0; i < maxPagesOpts.length; i++) {
		fade($('depth' + maxPagesOpts[i]), (maxPagesOpts[i] == maxPages) ? 1 : 0.25);
	}
}
function reset () {
	var s = f.search.value;
	f.reset();
	f.search.value = s;
	return void(0);
}
function invertBox (box) {
	box.checked = !box.checked;
}

var togglingIcons = false;
function toggleIcons () {
	if (togglingIcons) { return; }
	togglingIcons = true;
	var icons = $('icons');
	if (icons.visible()) {
		new Effect.BlindUp(icons, { afterFinish: function () { togglingIcons = false; $('iHide').hide(); $('iShow').show(); setSize(); } });
	} else {
		new Effect.BlindDown(icons, { afterFinish: function () { togglingIcons = false; $('iShow').hide(); $('iHide').show(); setSize(); } });
	}
}

var togglingOptions = false;
function toggleOptions () {
	if (togglingOptions) { return; }
	togglingOptions = true;
	var options = $('options');
	if ($('helpP').visible()) {
		$('helpP').fade({ duration: 0.5 });
	}
	if (options.visible()) {
		new Effect.BlindUp(options, { afterFinish: function () { togglingOptions = false; $('oHide').hide(); $('oShow').show(); } });
	} else {
		new Effect.BlindDown(options, { afterFinish: function () { togglingOptions = false; $('oShow').hide(); $('oHide').show(); } });
	}
}

var ssTimeout;
function setSize (now) {
	if (now != null && now == true) {
		setSize2(true);
	} else {
		if (ssTimeout != null) { clearTimeout(ssTimeout); }
		ssTimeout = setTimeout('setSize2(true)', 500);
	}
}

function setSize2 (again) {
	// Get the size of the main form
	var wh = $('formDiv').getDimensions();
	// Make sure the 'options' form covers the whole main form area
	$('options').setStyle({ width: (wh.width - 30) + 'px' });
	$('icons').setStyle({ width: (wh.width - 30) + 'px' }); // For Firefox!!
	$('helpP').setStyle({ width: ($('queryP').getWidth() - 15) + 'px' }); // For IE (but helps the other browsers)
	// See if there's enough room for the logo to the left of the form (logo width + padding = 212px)...
	if (document.body.getWidth() - wh.width < 212) {
		// If there's not enough room, centre the form and make the main text flow around the logo
		$('formDiv').setStyle({ float: 'none', width: (wh.width - 30) + 'px', marginLeft: 'auto', marginRight: 'auto' });
		$('logo').setStyle({ float: 'left', marginLeft: 0, marginRight: '12px' });
	} else {
		// If there is now enough room, centre the logo and make the main text flow around the form
		$('formDiv').setStyle({ float: 'right', width: 'auto', marginLeft: '12px', marginRight: 0 });
		$('logo').setStyle({ float: 'none', marginLeft: 'auto', marginRight: 'auto' });
	}
	// Set the size again, just in case it was squashed horizontally before
	if (again) { setTimeout('setSize2(false)', 100); }
}

function showInfo (id) {
	$(id).timeout = setTimeout("$('"+id+"').show()", 500);
}

function hideInfo (id) {
	clearTimeout($(id).timeout);
	$(id).hide();
}

function showOffer () {
	var oldOi = oi;
	oi = (oi + 1) % numOffers;
	new Effect.Fade('offer' + oldOi, {
		duration: 0.5,
		afterFinish: function () {
			new Effect.Appear('offer' + oi), {
				duration: 0.5
			}
		}
	});
}
