var t_right = 'http://images.tidbits.com/images/nav_triangle_closed.gif';
var t_open = 'http://images.tidbits.com/images/nav_triangle_open.gif';
var b_right = 'http://images.tidbits.com/images/summary_triangle_right.gif';
var b_open = 'http://images.tidbits.com/images/summary_triangle_down.gif';
var host_prefix = '';
var host_domain = '';
var hn = '';
if (location.hostname.match(/staging/)) {
	host_prefix = "_staging";
	host_domain = 'staging.tidbits.com';
	hn = "staging";
} else {
	host_domain = '.tidbits.com';
	hn = "";
}
var ish_types = new Array("tpre", "tish", "hpre", "hish");

// regexp for URL cleaning
var strip = /<a href\=\"[^\"]+\">([^<]+)<\/a>/gm;
var urlexp = /(http:\/\/[^\s\r\n<]+)(<|\s+|$)/gm;

// toggle image display on print friendly pages
function toggle_print_images (image_ids) {
 	var shp = document.getElementById('show_hide_print');
 	var showhide;
	if (shp.innerHTML == 'Off') {
		shp.innerHTML = 'On';
		showhide = 1;
	} else {
		shp.innerHTML = 'Off';
	}
	var image_ids_array = image_ids.split(",");
	for (var loop=0; loop < image_ids_array.length; loop++) {
		var b = document.getElementById('image_show_' + image_ids_array[loop]);
		var c = document.getElementById('image_link_' + image_ids_array[loop]);
		// alert ("Image: " + b.style.display);
		if (showhide == 1) {
			b.style.display = 'block';
			c.style.display = 'none';
		} else {
			b.style.display = 'none';
			c.style.display = 'block';
		}

	}
	return false;
}

// generic box show/hide
function generic_show_hide(place) {
	if ($(place).style.display == 'none') {
		$(place).style.display = '';
	} else {
		$(place).style.display = 'none';
	}
	return false;
}

// generic box visible invisible
function generic_visibility(place) {
	if ($(place).style.visibility == 'visible') {
		$(place).style.visibility = 'hidden';
	} else {
		$(place).style.visibility = 'visible';
	}
	return false;
}

// open on a clickthrough from home or section page
function open_if_linked(article_link) {
	if (window.location.search.match(/follow_link/)) {
		window.open(article_link, 'new_tidbits_link');
	}
	return;
}

// swap out class for link hover boxes
function link_hover_swap(getbits, inout, search) {

	var summary = document.cookie.match(/showsumm\=([^;]+)/);
	if (summary > 0 && summary[1] ==0) { return; }

	var search_add = '';
	if (search == 's') {
		search_add = "_s";
	}
	var place = 'link_box_right_' + getbits;
	generic_visibility(place);
	var enc = 'link_box_full_' + getbits;
	var title = 'link_hover_title_' + getbits;
	var styleHover;
	var styleLink;
	if (inout == 'out') {
		styleHover = 'link_hover' + search_add;
		styleLink = '#000';
	} else {
		styleHover = 'link_hover_over' + search_add;
		styleLink = '#990000';
	}
	$(enc).className = styleHover;
	$(title).style.color = styleLink;
}

// toggle blurb results with summary text
function blurb_show(id) {
	var b = document.getElementById('blurb_' + id);
	var s = document.getElementById('blurb_show_text_' + id);
	if (b.style.display == 'none') {
		b.style.display = 'block';
		s.innerHTML = 'Hide&nbsp;summary';
	} else {
		b.style.display = 'none';
		s.innerHTML = 'Show&nbsp;summary';
	}
	return false;
}

// toggle blurb results with triangle (search results)
function blurb_triangle_show(id) {
	var b = document.getElementById('blurb_' + id);
	var s = document.getElementById('blurb_show_text_' + id);
	if (b.style.display == 'none') {
		s.setAttribute("src", b_open);
		b.style.display = 'block';
	} else {
		s.setAttribute("src", b_right);
		b.style.display = 'none';
	}
	return false;
}

// toggle summary
function set_summary_show(load) {
	var summary = document.cookie.match(/showsumm\=([^;]+)/);
	var show;
	if (!summary) {
		if (load) {
			set_cookie('showsumm', '1', '3650', '/', '.tidbits.com', '');
			show = 1;
		}
	} else {
		if (load) {
			show = summary[1]; 
		} else { 
			show = (summary[1] == 1) ? 0 : 1;
		}
		set_cookie('showsumm', show, '3650', '/', '.tidbits.com', '');
	}
	
	var display = 'none';
	if (show == 1) {
		display = '';
		$('blurb_toggle_line').innerHTML = 'Hide summaries of articles';
	} else {
		$('blurb_toggle_line').innerHTML = 'Show summaries of articles';
	}
	
	var elem = document.getElementsByTagName('div'), i = 0, e;
	var pattern = /^blurb_(\d+)/;
	var j = 1;
	var cc = '';
	if (elem) {
		while (e = elem[i++]) {
			if (e.className == 'article_preview') { 
				var result = e.id.match(pattern);
				if (result != 'undefined') {
	// 				if ($('blurb_link_' + result[1]) != null) {
	// 					setTimeout("$('blurb_link_' + " + result[1] + ").style.display == '" + display + "';", 5000);
	// 				}
					$('blurb_' + result[1]).style.display = display;
				}
			}
		}
	}
}

// slide down/up blurb
function blurb_slide(id, sh) {
	var summary = document.cookie.match(/showsumm\=([^;]+)/);
	if (summary) { 
		var summary = document.cookie.match(/showsumm\=([^;]+)/);
		if (summary[1] == 1) { return; }
	}

	var b = 'blurb_' + id;
	var pb = 'blurb_popup_box';
	var pr = 'blurb_popup_right';
	var ab = 'article_item_box_' + id;
// 	var bl_link = 'blurb_link_' + id;
	if (sh == 'hide') { 
// 		if ($(bl_link) != null) { 
// 			$(bl_link).style.display = '';
// 		}
		$(pb).style.display = 'none';
		// $(ab).style.backgroundColor = '';
		// $(ab).style.paddingTop = '';
	} else {
		// $(ab).style.backgroundColor = '#dcd4e3';
// 		if ($(bl_link) != null) { 
// 			$(bl_link).style.display = 'none';
// 		}
		var lbr =  $('link_box_right_' + id);
		var binner = $(b).innerHTML;
		var pr_rep;
		if (lbr) { 
			pr_rep = "<div class='pop_link'><div class='lbr_pop'>" + lbr.innerHTML + "</div>" + binner + "</div>";
		} else { 
			pr_rep = binner;
		}		
		$(pr).innerHTML = pr_rep;
		$('popup_inner_' + id).className = 'blurb_popup_text';
		var vis = $(pb).style.display;
		if (vis == 'none') {
			$(pb).style.display = '';
			// $(pb).style.left = curX + "px";
		}
		// var half = $(pr).offsetHeight / 2; 
		var newtop = ($(ab).offsetTop - $(pb).offsetHeight + 25);
		//if (newtop < 0) { newtop = "325"; }
		newtop = newtop + "px";
		$(pb).style.top = newtop;
	}
	return false;
}


function set_cookie(name, value, expires, path, domain, secure) {
	var today = new Date();
	today.setTime( today.getTime() );
	
	if (expires) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	
	var new_cook = name + "=" + escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toUTCString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
	document.cookie = new_cook;
	
}

// swap triangle for summaries and articles
function triangle_blurb(id) {

	var tri = document.getElementById("blurb_show_text_" + id);
	var b = document.getElementById('blurb_' + id);
	if (b.style.display == 'none') {
		b.style.display = 'block';
		tri.setAttribute("src", t_open);
	} else {
		b.style.display = 'none';
		tri.setAttribute("src", t_right);
	}
}

// toggle blurb results
function arbitrary_showhide(id) {
	$(id).style.display = ($(id).style.display == 'none') ? 'block' : 'none';
	return false;
}

// toggle search parameters
function toggle_search_text(id, text_id) {
	$(text_id).innerHTML = ($(id).style.display == 'none') ? 'Hide search parameters' : 'Show search parameters';
	return arbitrary_showhide(id);
}

// toggle full article/blurb
function showhide_article(id) {
	var blurb = document.getElementById('article_blurb_' + id);
	var art = document.getElementById('article_text_' + id);
	var artbot = document.getElementById('article_text_bottom_' + id);
	if (art.style.display == 'none') {
		art.style.display = 'block';
		artbot.style.display = 'block';
		blurb.style.display = 'none';
	} else {
		art.style.display = 'none';
		artbot.style.display = 'none';
		blurb.style.display = 'block';
	}
	return false;
}

// show all or hide all search result blurbs
function showhidesearchdetail(count_ids, triangle) {
	var count_ids_array = count_ids.split(",");
	var showhide;
	var shs = document.getElementById('showhideall');
	if (shs.innerHTML.match(/Show/)) {
		showhide = 1;
		shs.innerHTML = "Hide&nbsp;all&nbsp;summaries";
	} else {
		showhide = 0;
		shs.innerHTML = "Show&nbsp;all&nbsp;summaries";
	}

	for (var loop=0; loop < count_ids_array.length; loop++) {
		var b = document.getElementById('blurb_' + count_ids_array[loop]);
		var s = document.getElementById('blurb_show_text_' + count_ids_array[loop]);
		if (showhide == 1) {
			b.style.display = 'block';
			if (triangle == 1) {
				s.setAttribute("src", b_open);
			} else {
				s.innerHTML = 'Hide&nbsp;summary';
			}
		} else {
			b.style.display = 'none';
			if (triangle == 1) {
				s.setAttribute("src", b_right);
			} else {
				s.innerHTML = 'Show&nbsp;summary';
			}
		}
	}
	return false;
}

// show all articles/show all blurbs for series/issue
function showhide_all_articles(shart) {
//	if (!shart.match(/,/)) { return false; }
	var shart_array = shart.split(",");
	var showhide;
	var shs = document.getElementById('showhide_arts_top');
	var shsb = document.getElementById('showhide_arts_bottom');
	if (shs.innerHTML.match(/Show/)) {
		showhide = 1;
		shs.innerHTML = "Hide the full text of all articles";
		shsb.innerHTML = "Hide the full text of all articles";
	} else {
		showhide = 0;
		shs.innerHTML = "Show the full text of all articles";
		shsb.innerHTML = "Show the full text of all articles";
	}

	for (var loop=0; loop < shart_array.length; loop++) {
		var b = document.getElementById('article_blurb_' + shart_array[loop]);
		var s = document.getElementById('article_text_' + shart_array[loop]);
		var sb = document.getElementById('article_text_bottom_' + shart_array[loop]);
		if (showhide == 1) {
			b.style.display = 'none';
			s.style.display = 'block';
			sb.style.display = 'block';
		} else {
			b.style.display = 'block';
			s.style.display = 'none';
			sb.style.display = 'none';
		}
	}
	return false;
}

function showhide(id, display) {
	var sidebars = new Array(3);
	sidebars[0] = "accounts";
	sidebars[1] = "articleslist";
	sidebars[2] = "stafflist";
	sidebars[3] = "abouttidbits";
	sidebars[4] = "issuelist";
	sidebars[5] = "tidbitstalklist";
	// + _triangle is the triangle span
	
	var d = document.getElementById(id); 
	if (!d) {
		d = document.getElementById('articleslist');
		id = 'articleslist';
		
	}
	if (d.style.display == 'none' || display == 'show') { 
		//new Effect.SlideDown(d);
		d.style.display = 'block';
		triangle(id + '_tri_image', "open");
	} else {
		//new Effect.SlideUp(d);
		d.style.display = 'none';
		triangle(id + '_tri_image', "close");
	}
	var i = 0;
	for (x = 0; x <= 4; x++) {
		if (id != sidebars[x]) { 
			var h = document.getElementById(sidebars[x]);
			if (h) {
//			if (h.style.display != 'none') { 
				// new Effect.SlideUp(h, { queue: 'end'});
				h.style.display = 'none';
				triangle(sidebars[x] + "_tri_image", "close");
			}
		}
	}
	return false;
}

function triangle(location, direction) {
	var t_right = 'http://images.tidbits.com/images/nav_triangle_closed.gif'
	var t_mid = 'http://images.tidbits.com/images/nav_triangle_mid.gif'
	var t_open = 'http://images.tidbits.com/images/nav_triangle_open.gif'

	var tri = document.getElementById(location);
//	var tri = document.location;
	if (direction == 'close') {
		tri.setAttribute("src", t_right);
//		tri.innerHTML = '<img border="0" src="' + t_right + '" class=\"navtriangle\" />';
		return;
	} else if (direction == 'open') {
		tri.setAttribute("src", t_open);
//		tri.innerHTML = '<img border="0" src="' + t_open + '" class=\"navtriangle\" />';
		return;
	}
	
/*	if (direction == 'close_2') {
		tri.innerHTML = '<img border="0" src="' + t_right + '" />';
		return;
	} else if (direction == 'open_2') {
		tri.innerHTML = '<img border="0" src="' + t_open + '" />';
		return;
	} else {
		tri.innerHTML = '<img border="0" src="' + t_mid + '" />';
		setTimeout("triangle('" + location + "','" + direction + "_2');", 300);
		return;
	} */
}

function markdown_copy(at, ad, gb) { 
	var brackets = "\"[" + unescape(at) + "][*],\" " + ad + "\n\n[*]: http://tidbits.com/article/" + gb;
	$('article_ref_box').value = brackets;
	ShowPopupContent('article_reference', 50)
	return false;
}

function recommend_this(thumb_rec) {
	var url = '/short.cgi?command=thumb&amp;id=' + thumb_rec;
	var r_ref = 'recommend_' + thumb_rec;
	var rb_ref = 'recommend_eoac_' + thumb_rec;
	var c_ref = 'count_' + thumb_rec;
	var cb_ref = 'count_eoac_' + thumb_rec;

	var r = document.getElementById(r_ref);
	var c = document.getElementById(c_ref);
	var rb = document.getElementById(rb_ref);
	var cb = document.getElementById(cb_ref);

	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
			var thumbs = transport.responseText.match(/thumb\: (\d+),(.+)/);
			if(thumbs) {
				// not 0, but 1... see javascript regex docs
				c.innerHTML = '&nbsp;+' + thumbs[1];
				if (cb) { cb.innerHTML = thumbs[1]; }
				r.innerHTML= "Thanks!";
				//if (rb) { rb.innerHTML= "Thanks!"; }
			}
		},
		onFailure: function() {
			r.innerHTML = " +0";
			if (rb) { rb.innerHTML = "0"; }
		}
	});
	return false;
}

function email_article() {

	// shorten form
	var f = $('send_article_link');

	// empty comments
	$('emailart_message_box').style.display = 'none';
	$('emailart_top_message').innerHTML = '';

	// check for empty comment
	if (!f.emailart_sendto.value || !f.emailart_sendfrom.value || !f.emailart_sendname.value) { 
		alert("Please enter fill in required fields before submitting."); 
		return false;
	}

	// disable button
	$('submit_article_forward').disabled = true;
	$('submit_article_forward').value = 'Please Wait';
	
	var uni_ea_msg;
	var uni_ea_name;
    if (encodeURIComponent) {
        uni_ea_name = encodeURIComponent(f.emailart_sendname.value);
        uni_ea_msg = encodeURIComponent(f.emailart_sendmessage.value);
    } else {
        uni_ea_name = escape(f.emailart_sendname.value);
        uni_ea_msg = escape(f.emailart_sendmessage.value);
    }
    
    var ps = (f.ps ? f.ps.value : '');
    
	var url = "/short.cgi?command=email_article&amp;ps=" + escape(ps) + "&amp;article_id=" + escape(f.emailart_article_id.value) + "&amp;sendto=" + escape(f.emailart_sendto.value) + "&amp;sendfrom=" + escape(f.emailart_sendfrom.value) + "&amp;sendname=" + uni_ea_name + "&amp;message=" + uni_ea_msg;

	// append recaptcha info if present
	if ($('emailart_recaptcha')) { 
		url += '&amp;challenge=' + escape(f.recaptcha_challenge_field.value) + '&amp;response=' + escape(f.recaptcha_response_field.value);
	}

	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
			var code_match = transport.responseText.match(/([a-z\_]+)/);
			var code = (code_match ? code_match[1] : '');
			
			$('emailart_message_box').style.display = '';

			if (code == 'sent') {
				$('emailart_formencloser').style.display = 'none';
				$('submit_article_forward').value = 'Sent!';
				$('submit_article_forward').disabled = false;
				$('emailart_top_message').innerHTML = 'Email sent!';
				f.emailart_sendto.value = '';
				// close down article mail box and remove background
				var box = 'emailart_' + f.emailart_article_id.value;
				setTimeout('Effect.Fade("' + box + '", { duration: 2.7, from: 1.0, to: 0.0 });', 500);
				setTimeout('fade_background()', 700);
				
				setTimeout('reset_emailart_box()', 3000);
				

			} else {
				if ($('emailart_recaptcha')) { 
					display_captcha(1, 'emailart_recaptcha');
				}
				
				if (code == 'failed_captcha') { 
					$('emailart_top_message').innerHTML = 'The letters you entered for the verification below did not match. Please try this new one.';
				} else if (code == 'failed_art') {
					$('emailart_top_message').innerHTML = 'There is an error on this page that prevents the article from being sent. The webmaster has been notified.';
				} else if (code == 'invalid_sendto') {
					$('emailart_top_message').innerHTML = 'Please check the address to which you are sending this article. It appears to have characters in it that do not appear in email addresses.';
				} else if (code == 'invalid_sendfrom') {
					$('emailart_top_message').innerHTML = 'Please check the address you have set as the one from which this message should be sent. It appears to have characters in it that do not appear in email addresses.';
				} else {
					// something wrong with submission
					alert ("Something went wrong:" + transport.responseText);
				}
			}
			$('submit_article_forward').disabled = false;
			$('submit_article_forward').value = 'Forward This Article!';

        },
		onFailure: function() {
			$(dd).style.display = '';
			$(dd).innerHTML = 'Something went wrong when we tried to send out your message.';
		}
	});
	
	return false;
}
function reset_emailart_box () {
	$('big_ole_background').style.top = "0px";
	$('submit_article_forward').value = 'Forward This Article!';
	$('emailart_top_message').innerHTML = '';
	$('emailart_formencloser').style.display = '';
}

function quick_captcha_check(form, captcha_id) {
	var url = "/short.cgi?command=captcha_checker&amp;challenge=" + escape($(form).recaptcha_challenge_field.value) + '&amp;response=' + escape($(form).recaptcha_response_field.value);
	
	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
			var code_match = transport.responseText.match(/1/);
			if (code_match && code_match == '1') {
				if ($(form).dealbits_frond) {
					$(form).dealbits_frond.value = 'triste';
				}
				$(form).submit();
			} else {
				alert("Please try to enter the distorted text again.");
				if ($(captcha_id)) { 
					display_captcha(1, captcha_id);
				}
				return false;
			}
        },
		onFailure: function() {
		}
	});
	
	return false;
}

function load_votes(count_ids) {
	var url = '/short.cgi?command=count&amp;id=' + count_ids;
	if (count_ids.match(/^A/)) { count_ids = count_ids.substr(1); }
	
	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
		    var count_ids_array = count_ids.split(",");
			for (var loop=0; loop < count_ids_array.length; loop++) {
				var count_m = new RegExp('count: ' + count_ids_array[loop] + ',(\\d+)');
				var counts = transport.responseText.match(count_m);
				if(counts) {
					// not 0, but 1... see javascript regex docs
					var c_ref = 'count_' + count_ids_array[loop];
					var c = document.getElementById(c_ref);
					c.innerHTML = " +" + counts[1];
					var cb_ref = 'count_eoac_' + count_ids_array[loop];
					var cb = document.getElementById(cb_ref);
					if (cb) { cb.innerHTML = "" + counts[1]; }
 				} else {
					var c_ref = 'count_' + count_ids_array[loop];
					var c = document.getElementById(c_ref);
					c.innerHTML = " +0";
					var cb_ref = 'count_eoac_' + count_ids_array[loop];
					var cb = document.getElementById(cb_ref);
					if (cb) { cb.innerHTML = "0"; }
				}			
			}
        },
		onFailure: function() {
		}
	});
	return false;
}	

function open_podcast_window(url) {
	newwindow=window.open(url,'TidBITS Podcast','height=200,width=200');
	if (window.focus) {newwindow.focus()}
}


// box popup code
// Thanks to Geoff Duncan!
var curX = 0; var curY = 0; var cliY = 0; var rX = 0; var rY = 0;

function UpdateCursorPosition(e) {
	// relative location
	if (typeof(e.pageX) == 'number') {
		curX = e.pageX; 
		curY = e.pageY; 
	} else {
		curX = e.clientX; 
		curY = e.clientY; 
	}
	cliY = e.clientY	
}

document.onmousemove = UpdateCursorPosition;

function AssignPosition(d, offset) {
	
	var width, height;
	if (navigator.appName.indexOf("Microsoft")!=-1) {
		width = document.body.offsetWidth;
		// height = document.body.offsetHeight;
	} else {
		width = window.innerWidth;
		// height = window.innerHeight;
	}

	var add_width = offset;
	if (curX < 270) { add_width = 50; }
	var new_left = (curX - 250 + add_width);
	if (new_left < 50) { new_left = 50; }
	if (new_left > 450) { new_left = 450; }
	d.style.left = new_left + "px";
	d.style.top = (curY - cliY + 40) + "px";

	return (curY - cliY + 40);
	// alert(d.style.left + "," + d.style.top);
}


function HidePopupContent(d, base_ref, base_id) {
	if (d.length < 1) {
		return;
	}
	fade_background();
	$('big_ole_background').style.top = "0px";

	document.getElementById(d).style.display = "none";
	if (base_id > 0) { 
		base_id = "_" + base_id;
		var inn = document.getElementById(base_ref + "_innards" + base_id);
		var inn_alt = document.getElementById(base_ref + "_innards_alt" + base_id);
		var s = document.getElementById(base_ref + "_message_box" + base_id);
		s.style.display = 'none';
		if (inn) {
			inn.style.display = "block";
		} 
		if (inn_alt) {
			inn_alt.style.display = "none";
		}
	}
}
function fade_background() {
	Effect.Fade('big_ole_background', { duration: 0.7, from: 0.65 });
}

function ShowPopupContent(d, offset) {
	if (d.length < 1) {
		return;
	}
	var dd = document.getElementById(d);
	var bigtop = AssignPosition(dd, 0);
	if (bigtop > 400) { 
		$('big_ole_background').style.top = (bigtop - 200) + "px";
	}
	Effect.Appear('big_ole_background', { duration: 0.7, from: 0.2, to: 0.65 });
	dd.style.display = "block";
}

function ReversePopupDisplay(d) {
	if (d.length < 1) {
		return;
	}
	var dd = document.getElementById(d);
	AssignPosition(dd);
	if (dd.style.display == "none") {
		dd.style.display = "block";
	}
	else {
		dd.style.display = "none";
		Effect.Fade('big_ole_background', { duration: 0.7, from: 0.65 });
		$('big_ole_background').style.top = "0px";
	}
}
// end box popup code

// show popup box and insert recaptcha
function ShowTipBox(tip_pop, tip_recapt, offset, field_focus) {

	if (tip_recapt) {
		Recaptcha.create("6LcsmMcSAAAAAN2IBAgKZjIlgqI0GQeGmfibCQAY",
		tip_recapt, {
		   theme: "red"
		});
	}
	ShowPopupContent(tip_pop, offset);
	if (field_focus) {
		$(field_focus).focus();
	}
	return false;
}

function handle_tip_submission(base_ref, base_id, form, type) {

	var fail = 0;
	var msg_box;
	var msg_contents;
	
	if (base_id > 0) { 
		base_id = "_" + base_id;
	} else {
		base_id = '';
	}
	var tip_recapt = base_ref + "_recaptcha" + base_id;
	var d = document.getElementById(base_ref + "_top_message" + base_id);
	var s = document.getElementById(base_ref + "_message_box" + base_id);
	var inn = document.getElementById(base_ref + "_innards" + base_id);
	var inn_alt = document.getElementById(base_ref + "_innards_alt" + base_id);
	inn.style.display = "block";
	if (inn_alt) { 
		inn_alt.style.display = "none";
	}
	var small_response = document.getElementById(base_ref + "_small_response" + base_id);
	var url = '/tipsubmit.cgi?challenge=' + escape(form.recaptcha_challenge_field.value) + '&amp;response=' + escape(form.recaptcha_response_field.value);

	// reset embedded innards
	s.style.display = 'none';
	
	if (type == 'tip') {
		if (form.tip_title.value == '' || form.tip_text.value == '' || form.tip_reader_email.value == '' || form.tip_reader_name.value == '') {
			d.innerHTML = 'You did not enter a required field. Please check your input.';
			s.style.display = "block";
			return false;
		}
			
		var email = escape(form.tip_reader_email.value);
		email = email.replace(new RegExp( "\\+", "g" ),"%2B");
	
		url = url + '&amp;tip_title=' + escape(form.tip_title.value) + '&amp;tip_reader_name=' + escape(form.tip_reader_name.value) + '&amp;tip_reader_email=' + email + '&amp;tip_text=' + escape(form.tip_text.value) + '&amp;tip_link_label=' + escape(form.tip_link_label.value) + '&amp;tip_link_url=' + escape(form.tip_link_url.value);
		
	} else if (type == 'comment') {
		if (form.article_id == '') { 
			d.innerHTML = 'Something is wrong with our system. Please report this error with the URL you\'re viewing to <a href="mailto:glenn@tidbits.com">our system administrator</a>.';
			s.style.display = "block";
			return false;
		}
		url = url + "&amp;tbtalk=" + form.getbits.value;
	} else if (type == 'email') { 
		url = url + "&amp;email=" + form.author_id.value;
	}

	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
			var message;
			var invalid = transport.responseText.match(/bad_captcha/);
			var bademail = transport.responseText.match(/bad_email/);
			var general_bad = transport.responseText.match(/bad_response/);

			if(invalid) {
				message = 'The text you entered does not match the text in the image. Please try again.';
			} else if (bademail) {
				message = 'The email address you entered does not appear to be a valid address. Please re-enter';
			} else if (general_bad) {
				message = 'Something went wrong that we can\'t determine. Sorry.';
			}
			if (invalid || bademail || general_bad) {
				d.innerHTML = message;
				display_captcha(1, tip_recapt);
				s.style.display = "block";
			} else {
				s.style.display = "block";
				display_captcha(0, tip_recapt);
				if (type == 'tip') {
					d.innerHTML = '';
					d.style.background = '#000000';
					//Effect.Appear(d, { duration: 0.7, from: 1.0, to: 0.3 });
					form.tip_title.value = '';
					form.tip_text.value = '';
					form.tip_link_label.value = '';
					form.tip_link_url.value = '';
					display_captcha(1, tip_recapt);
					Effect.Appear('popup_box_thanks', { duration: 0.7, from: 0.0, to: 1.0 });
					Effect.Fade('ts_innards', { duration: 0.7, from: 1.0, to: 0.4 });
				} else if (type == 'comment') {
					d.innerHTML = 'Your thread has been created. Please wait and you will be redirected to our discussion site.';
					display_captcha(0, tip_recapt);
					window.location = "http://" + hn + ".tidbits.com/discuss/" + form.getbits.value;
				} else if (type == 'email') {
					display_captcha(0, tip_recapt);
					var e = transport.responseText;
					var ae = e.match(/(.+)\:(.+)/);
					s.style.display = "none";
					var f = ae[1].replace(/[\n\s]+/g, '');
					inn.style.display = "none";
					inn_alt.style.display = "block";
					small_response.innerHTML = 'Click <a href="mailto:' + f + '" onClick="HidePopupContent(\'' + base_ref + base_id + '\')">' + f + '</a> to send email to ' + ae[2] + '.';
				}
			}
		},
		onFailure: function() {
			d.innerHTML = "<p><span class='required_field'>An unknown error has occurred</span></p>";
			display_captcha(1, tip_recapt);
		}
	});
	return false;
}

function close_popup_thanks(tnx, prefix) {
	if ($(tnx).style.display == 'visible' || $(tnx).style.display == '') {
		Effect.Fade(tnx, { duration: 0.7, from: 1.0, to: 0.0 });
		if (prefix == 'ts') {
			var innards = prefix + "_innards";
			Effect.Appear(innards, { duration: 0.7, from: 0.4, to: 1.0 });
		} else {
			Effect.Fade(prefix, { duration: 0.7, from: 1.0, to: 0.0 });
			Effect.Fade('big_ole_background', { duration: 0.5, from: 0.65 });
			$('big_ole_background').style.top = "0px";
		}
	}
}

function check_tip_close() {
	if ($('ts').style.display == 'visible' || $('ts').style.display == '') {
		Effect.Fade('big_ole_background', { duration: 0.7, from: 0.65 });
		document.getElementById('ts').style.display = "none";
	}
}		

function display_captcha(fail, tip_recapt) {

	if (fail == 1) {
		Recaptcha.create("6LcsmMcSAAAAAN2IBAgKZjIlgqI0GQeGmfibCQAY",
			tip_recapt, {
			   theme: "red",
			   callback: Recaptcha.focus_response_field
			});
	} else {
		var tr = document.getElementById(tip_recapt);
		tr.style.display = 'none';
	}
	return true;

}

function fill_preview(new_box, old_box, form) {
	var ob = document.getElementById(old_box);
	var nb = document.getElementById(new_box);

	$('p_tips_title').innerHTML = form.tip_title.value;
	var tips_text = form.tip_text.value;
	$('p_tips_text').innerHTML = '<p>' + tips_text.replace(/[\n\r]+/g, "</p><p>") + '</p>';
	$('p_url').href = form.tip_link_url.value;
	$('p_label').innerHTML = form.tip_link_label.value;
	$('p_reader').innerHTML = form.tip_reader_name.value;
	
	preview_box(new_box, old_box);
	return false;
}

function preview_box(new_box, old_box) {
	var ob = document.getElementById(old_box);
	var nb = document.getElementById(new_box);
	nb.style.left = ob.style.left;
	nb.style.top = ob.style.top;
// 	ob.style.display = 'none';
//  	nb.style.display = 'block';
	
	Effect.SlideUp(old_box, { duration: 1.2 });
	Effect.SlideDown(new_box, { duration: 1.2 });
	return false;
}

function slidedown_hello() {
	if (!($('slidedown_surround'))) { return false; }

	// bypass slidedown for a day after viewing one
	var comm_regexp = new RegExp("skip_slidedown" + host_prefix + "\=([^;]+)", "");
	var skip_cookie = document.cookie.match(comm_regexp);
	if (!skip_cookie || skip_cookie[1] != '1') {	
		setTimeout('slidedown_delay()', 1);
		// add condition to skip for paid subscribers
		// if (document.referrer && !(document.referrer.match(/tidbits\.com/i))) {
			set_cookie('skip_slidedown' + host_prefix, '1', 1, '/', hn + '.tidbits.com', '');
		//}
	}	
}
function slidedown_delay() {
	Effect.SlideDown('slidedown_surround', { duration: 1.6 });
	Effect.SlideDown('slidedown_bottom_margin', { duration: 0.8 });
}
function slidedown_goodbye() {
	Effect.SlideUp('slidedown_surround', { duration: 1.1 });
	Effect.SlideUp('slidedown_bottom_margin', { duration: 2.0 });
}

function search_tipbits(field, show) {
	var url = '/short.cgi?command=search_tipbits&amp;id=' + escape($(field).value);
	
	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
			var text_results = "<div id='tip_insert'><div id='tip_pagehead2'>TipBITS Search Results</div>" + transport.responseText + "</div>";
			if (show == "") {
				$('center_ajax_sub').innerHTML = text_results;
			} else {
				$('center_ajax_sub').innerHTML = text_results;
				$(show).style.display = '';
			}
			window.scrollTo(0,0) 
        },
		onFailure: function() {
			alert ('A problem occurred from which no recovery seems possible.');
		}
	});
	return false;

}

function redirect_issue(form) {
	var num = form.issue_number.value; 
	if (num > 0) {
		window.location = 'http://tidbits.com/issue/' + num; 
	} 
}

function expand_textarea(form, id) {
	if (id == 'new') {
		var t_name = 'cb_item_add_' + id;
		var cbf = $(t_name);
		cbf.rows = 4; 
		if (cbf.value == 'What do you think?') { 
			cbf.value = '';
		}
		cbf.style.color = 'black'; 
		cbf.style.fontStyle = 'normal'; 
	}
	$('cb_add_dropdown_' + id).style.display = '';
}
function contract_textarea(form, id) {
	var t_name = 'cb_item_add_' + id;
	var cbf = $(t_name);
	if (cbf.value == '') { 
		cbf.rows = 1; 
	}
	// $('cb_add_dropdown_' + id).style.display = 'none';
}

function swap_cb_dropdown(form,id) {
	var drop = $('cb_add_dropdown_' + id);
	var t_name = 'cb_item_add_' + id;
	if (drop.style.display == 'none') { 
		drop.style.display = ''; 
		$(t_name).rows = 4;
	} else { 
		drop.style.display = 'none'; 
	}
}

function count_insert(field, counter) {
	var cbf = $(field);
	var b = cbf.value.length;
	if (b < 1) { b = 0; }
	var l = ($('sparameter').value == 1 ? 5000 : 1000);
	
	// need to add token or authentication test here, of course
	if (b >= l) { 
		cbf.value = cbf.value.substring(0,l);
		$(counter).style.color = 'red';
		$(counter).style.fontStyle = 'italic';
	} else {
		$(counter).style.color = 'black';
		$(counter).style.fontStyle = 'normal';
	}
	if (b > l) { b = l; }
	$(counter).innerHTML = (l-b);

}

function cb_post_submit(apple) {

	// shorten form
	var f = $('post_comment');

	// check for empty comment
	var cb_text = f.cb_item_add.value;
	if (cb_text == '') { 
		alert("Please enter a comment before submitting."); 
		return false;
	}
	// escape line endings
	cb_text = cb_text.replace(/(\r\n|\r|\n)/g, "<br />");
	cb_text = cb_text.replace(/\&amp;/g, "&");
	// cb_text = clean_unicode(cb_text);

	// increment nesting level, checking for NaN
	var nest = f.comment_nest.value;
	if (nest != nest || nest == undefined || isNaN(nest)) { nest = 0; }
	nest = Number(nest) + 1;

	// token if stored in cookie for commenter
	var comm_regexp = new RegExp("tbcomm" + host_prefix + "\=([^;]+)", "");
	var token_cookie = document.cookie.match(comm_regexp);
	var token;
	// ignore null array returns
	if (token_cookie === null) { token = 0; } else { token = token_cookie[1]; }

	// name of commenter, email
	var cb_name;
	if (f.cb_add_name != null && f.cb_add_name != undefined) {
		cb_name = f.cb_add_name.value;
	}
	var cb_email;
	if (f.cb_add_email != null && f.cb_add_email != undefined) { 
		cb_email = f.cb_add_email.value;
	}
	
	// check for empty name or no token
	if (!cb_name && !token) { 
		alert ("Please enter your name to be associated with this comment.");
		return false;
	}
	if (!cb_email && !token) {
		alert ("You must enter an email address to post this comment.");
		return false;
	}
	
	$('comm_post_comment').disabled = true;
	$('comm_post_comment').value = 'Please Wait';
	
	var uni_cb_text;
	var uni_cb_name;
    if (encodeURIComponent) {
        uni_cb_text = encodeURIComponent(cb_text);
        uni_cb_name = encodeURIComponent(cb_name);
    } else {
        uni_cb_text = escape(cb_text);
        uni_cb_name = escape(cb_name);
    }
    
	var url = '/short.cgi?command=post_comment&amp;article_id=' + escape(f.article_id.value) + '&amp;token=' + escape(token) + '&amp;cb_name=' + uni_cb_name + '&amp;cb_email=' + escape(cb_email) + '&amp;cb_text=' + uni_cb_text + '&amp;parent_id=' + escape(f.comment_id.value) + '&amp;nest=' + escape(nest) + "&amp;edit=" + escape(f.edit.value);
	var dd = 'comm_message_box';
	var ct = 'comment_thanks';

	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
			var inuse = transport.responseText.match(/inuse/);
			if (inuse) { 
				$(dd).style.display = '';
				$(dd).innerHTML = "This email address is already used by a registered TidBITS account. Please use our <a href=\'/account\'>account page</a> to log in before commenting. (Copy your comment\'s text as it will otherwise be lost when you click the account page link.)";
				$('comm_post_comment').value = 'Please Login';
				return false;
			}
			
			var respCheck = transport.responseText.match(/([a-z]+)/);
			var respMatch = '';
			if (respCheck) {
				respMatch = respCheck[1];
			}
				
			if (respMatch == 'post' || respMatch == 'edited') { 
				// close down comments box and remove background
				$(dd).style.display = '';
				Effect.Fade('comm', { duration: 0.7, from: 1.0, to: 0.0 });
				fade_background();
				$('big_ole_background').style.top = "0px";

				// insert new comment in the right place
				var pid = f.comment_id.value;
				var insert_block = 'cb_item_insert_' + pid;
				
				if (respMatch == 'post') {
					var post = transport.responseText.match(/post\|(.*)\|(.*)\|(.*)\|(.*)/);
					var new_date = post[1];
					var cid = post[2];
					var ib = post[3];
					var urlok = post[4];
					if (pid == 'new' && !ib) { ib = 'new'; }
					//alert ("cid " + cid + ", new insertion before " + ib + ", nest " + nest);
					
					var new_cb_text = cb_text;
					if (urlok > 0) { 
						new_cb_text = cb_text.replace(strip, "$1");
						new_cb_text = new_cb_text.replace(urlexp, "<a href=\"$1\">$1<\/a>$2");
					}

					var new_text = '<div class="cb_item_meta"><span class="cb_item_author">' + $('commenter_name_inserted').innerHTML + '</span> ' + (apple ? '&nbsp;&nbsp;<IMG class="shift_down" src="http://tidbits.com/images/membership/memberapple_' + apple + '_16x16.png"> ' : '') + '<span class="cb_item_date" id="cb_item_date_insert_' +  cid + '">' + new_date + '</span></div><div class="cb_buttons_offset"><div class="cb_item_text" id="cb_item_text_' + cid + '" style="padding-left: 10px;">' + new_cb_text + '</div><div class="cb_buttons_offset" style="padding-left: 10px"><span class="cb_reply_icon"><span class="cb_action" onClick="ShowCommentPopup(\'' + cid + '\', \'' + nest + '\', \'' + f.article_id.value + '\')">Reply</span><span  class="cb_action" onClick="EditComment(\'' + cid + '\')">Edit</span></div>';
										
					// insert new comment
					var new_row = document.createElement("div");
					var new_id = 'cb_item_' + cid;
					new_row.setAttribute("id", new_id);
					$('insert_before_' + ib).appendChild(new_row);
					$(new_id).style.display = 'none';
					$(new_id).innerHTML = "<div>" + new_text + "</div>";
					$(new_id).style.paddingBottom = '22px';
					$(new_id).className = 'cb_indent_' + nest;
					Effect.BlindDown(new_id, { duration: 0.7 });

					// insert new node into which to insert another comment
					var new_row2 = document.createElement("div");
					var new_id2 = 'insert_before_' + cid;
					new_row2.setAttribute("id", new_id2);
					$('insert_before_' + ib).appendChild(new_row2);
					$(new_id2).innerHTML = '';
					
					// delete no comments message if comments are added
					if ($('no_comments')) {
						$('no_comments').innerHTML = '';
					}
					$('comm_post_comment').value = 'Post Comment';
					$('comm_post_comment').disabled = false;
					
					Effect.ScrollTo(new_id2);

				} else {
					var new_cb_text = cb_text.replace(strip, "$1");
					new_cb_text = new_cb_text.replace(urlexp, "<a href=\"$1\">$1<\/a>$2");
					$('cb_item_text_' + pid).innerHTML = new_cb_text;
				}
					
			} else if (respMatch == 'held') { 
				$('comm_innards').style.display = 'none';
				new Effect.Appear('comment_thanks', { duration: 0.3, from: 0.0, to: 1.0 });
				setTimeout('fade_comm()', 5000);
				
			} else if (respMatch == 'banned') {
				$(dd).style.display = '';
				$(dd).innerHTML = 'Your ability to post comments has been disabled. Contact us for more information.';
				set_cookie('tbcomm' + host_prefix, '', -1, '/', hn + '.tidbits.com', '');
			} else {
				$(dd).style.display = '';
				$(dd).innerHTML = 'Something went wrong when you attempted to post a comment. You have our sincere apologies.';
			}
        },
		onFailure: function() {
			$(dd).style.display = '';
			$(dd).innerHTML = 'Our commenting system isn\'t working correctly at the moment. Please try again later.';
		}
	});
	
	$('comm_post_comment').name = "Thanks!";
	$('comm_post_comment').onClick = '';
	return false;
}

function fade_comm() {
	Effect.Fade('comm', { duration: 0.7, from: 1.0, to: 0.0 }),
	fade_background();
	$('big_ole_background').style.top = "0px";
}


function ShowCommentPopup(cid, nest, aid, apple) {
	var f = $('post_comment'); 
	$('comm_post_comment').name = "Post Comment";
	$('comm_post_comment').onClick = 'cb_post_submit("' + apple + '"); return false;';
	$('comm_headline').innerHTML = "Post Comment";
	$('comment_thanks').style.display = 'none';
	$('comm_innards').style.display = '';
	$('comm_post_comment').value = 'Post Comment';
	$('comm_post_comment').disabled = false;
	
	new Draggable('comm', { snap: false } );

	f.comment_id.value = cid;
	f.comment_nest.value = nest;
	f.edit.value = '';
	f.cb_item_add.value = '';
	if (f.cb_add_name != null && f.cb_add_name != undefined) {
		f.cb_add_name.value = '';
		f.cb_add_email.value = '';
	}	
	var cb_quote = 'cb_item_text_' + cid;
	if (cid == 'new') {
		$('cb_quoted').innerHTML = $('article_blurb_for_insert').innerHTML;
	} else {
		$('cb_quoted').innerHTML = $(cb_quote).innerHTML;
	}
	$('comm_message_box').innerHTML = '';
	ShowPopupContent('comm', 100);
	count_insert('cb_item_add','cb_char_count');
	f.cb_item_add.focus();
}

function EditComment(cid) {
	ShowCommentPopup(cid, '', '');
	var cb_text = 'cb_item_text_' + cid;
	var cb_text_inner = $(cb_text).innerHTML.replace(/<br>/g, "\n\n");
	cb_text_inner = cb_text_inner.replace(/[\n\s\r]{2}$/gm, "");
	cb_text_inner = cb_text_inner.replace(/[\n\s\r]+$/g, "");
	cb_text_inner = cb_text_inner.replace(strip, "$1");

	// alert(cb_text_inner);

	$('cb_item_add').value = cb_text_inner;
	$('post_comment').edit.value = 1;
	$('comm_headline').innerHTML = "Edit Comment";
}

function DeleteComment(cid) {

	var yes = confirm("Are you sure you want to delete this comment?");
	if (yes == false) {
		return false; 
	}
	var token_regexp = new RegExp("token" + host_prefix + "\=([^;]+)", "");
	var token = document.cookie.match(token_regexp);
	var url = '/short.cgi?command=delete_comment&amp;cid=' + cid + '&amp;token=' + escape(token[1]);

	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
			var success = transport.responseText.match(/success/);

			if (success) {
				var c = 'cb_item_' + cid;
				$(c).style.display = 'none';
				$(c).style.textDecoration = line-through;
				$(c).color = 'Gray';
			} else {
				alert("The system failed in deleting the comment. Tell Glenn!");
			}
        },
		onFailure: function() {
			alert("The system failed in deleting the comment. Tell Glenn!");
		}
	});
	return false;
}

function BanUser(cer_id) {

	var yes = confirm("Are you sure you want to ban this user? All comments by this user ever made will be unpublished (but not deleted from our database).");
	if (yes == false) {
		return false; 
	}
	var token_regexp = new RegExp("token" + host_prefix + "\=([^;]+)", "");
	var token = document.cookie.match(token_regexp);
	var url = '/short.cgi?command=ban_user&amp;cer_id=' + cer_id + '&amp;token=' + escape(token[1]);

	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
			var success = transport.responseText.match(/success/);

			if (success) {
				alert("This user's comments have all been unpublished from TidBITS. Reload the page to see his or her comments removed here.");
			} else {
				alert("The system failed in deleting the comment. Tell Glenn!");
			}
        },
		onFailure: function() {
			alert("The system failed in deleting the comment. Tell Glenn!");
		}
	});
	return false;
}

function PauseUser(cid, cer_id) {

	if (!cer_id) {
		alert ("A user ID is missing. Please alert Glenn, as this shouldn't happen.");
		return false;
	}
	var yes;
	var action;
	var cstatus = 'cb_pause_user_' + cid;
	if ($(cstatus).innerHTML.match(/Resume/)) {
		yes = confirm("Are you sure you want to allow this user to resume commenting?");
		action = 'start';
	} else {
		yes = confirm("Are you sure you want to prevent this user from commenting in the future?");
		action = 'pause';
	}
	if (yes == false) {
		return false; 
	}
	var token_regexp = new RegExp("token" + host_prefix + "\=([^;]+)", "");
	var token = document.cookie.match(token_regexp);
	var url = '/short.cgi?command=pause_user&amp;status=' + action + '&amp;cer_id=' + cer_id + '&amp;token=' + escape(token[1]);

	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
			var success = transport.responseText.match(/success/);

			if (success) {
				if (action == 'start') {
					$(cstatus).innerHTML = "Pause User";
				} else {
					$(cstatus).innerHTML = "Resume User";
				}
			} else {
				alert("The system failed to pause this user's ability to comment. Tell Glenn!");
			}
        },
		onFailure: function() {
			alert("The system failed to pause this user's ability to comment. Tell Glenn!");
		}
	});
	return false;
}

function UpdateNames(cer_id, new_name) {
	var classElements = new Array();
	var els = document.getElementsByTagName('span');
	var elsLen = els.length;
	var q = 0;
	var pattern = new RegExp('(^|\\\\s)'+'cb_item_author'+'(\\\\s|$)');
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			var cirs = els[i].id.match(/cb_item_author_edit_(\d+)_/);
			if (cirs[1] == cer_id) {
				$(els[i]).innerHTML = new_name.innerHTML;
			}
		}
	}

}

function clean_unicode(text) {

	return text;
	
	// this is now handled by UTF8 encoding in the AJAX script
	var replacements = new Array;
	replacements = {
		"\u00a9": "(c)",
		"\u201c": '"',
		"\u201d": '"',
		"\u2026": "...",
		"\u2002": " ",
		"\u2003": " ",
		"\u2009": " ",
		"\u2013": "-",
		"\u2014": "--",
		"\u2018": "'",
		"\u2019": "'",
		"\u2122": "(tm)"    
    };
	var regex = new Array;

	for (var key in replacements) {
		regex[key] = new RegExp(key, 'g');
		text.replace(regex[key], replacements[key]);
	}
	
	return text;
}

function dealbits_process(db_id) {

	var token_result = user_token();
	
	var email = $('db_email_id_' + db_id);
	var name = $('db_name_id_' + db_id);
	var signup = $('dbca_' + db_id);

	if (email) { 
		var bad_email = check_valid_email(email.value);
		if (bad_email == 1) {
			alert("Please enter a complete email address in the form: yourname@yourdomain.com")
			email.focus();
			return false;
		}
		if (!name.value) {
			alert("Please enter your full name so the lawyers don't get mad at us.")
			name.focus();
			return false
		}
	}
	
	var uni_name;
	if (name) {
		if (encodeURIComponent) {
			uni_name = encodeURIComponent(name.value);
		} else {
			uni_name = escape(name.value);
		}
	}

	var url = '/short.cgi?command=dealbits_entry&amp;db_id=' + escape(db_id) + '&amp;db_email=' + escape((email ? email.value : '')) + "&amp;db_name=" + uni_name + "&amp;db_signup=" + ((signup ? (signup.checked == true ? '1' : '') : '')) + '&amp;tbu_token=' + escape(token_result);

	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
			var result = transport.responseText.match(/^(.*)/);
			if (!result || result[1] == 'missing' || result[1] == 'failure') {
				alert("Something went wrong in submitting your DealBITS entry. Our apologies.");
				return false;
			}
			if (result[1] == 'success') {
				new Effect.SlideUp('db_entry_block_' + db_id);
				new Effect.SlideDown('db_thanks_' + db_id);
			} else if (result[1] == 'duplicate') {
				alert("You have already entered the drawing using this information.");
			}
        },
		onFailure: function() {
			alert("Failure in our system. Sorry.");
		}
	});
	return false;
}

function validate_dealbits_sponsor() {
	if (!$('db_fromAddress')) { 
		alert ("Please enter an email address.");
		return false;
	} else { 
		if (check_valid_email($('db_fromAddress').value)) { 
			alert ("Please re-enter your email address in a valid format.");
			return false;
		}
	}
	return true;
}

function check_valid_email(email) {
	var e_index = email.indexOf("@");
	var bad_email = 0;
	if (e_index > 0) {
		var p_index = email.indexOf(".", e_index);
		if ((p_index < e_index+1) || (email.length < p_index+1)) {
			bad_email = 1;
		}		
	} else {
		bad_email = 1;
	}
	return bad_email;
}


function check_create_account() {
	// check that password and verify password match
	// check that the password is not empty

	if (!$('tb_password').value) { 
		alert("You must enter a password to create an account.");
		return false;
	} else if ($('tb_password_verify').value != $('tb_password').value) { 
		alert ("Your password was not entered identically in the two password fields.");
		return false;
	}
	return true;
}

function reset_bounces() { 
	var token_result = user_token();

	var url = '/short.cgi?command=tba_reset_bounces&amp;tbu_token=' + escape(token_result);

	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
			var success = transport.responseText.match(/success/);
			if (success) { 
				fade_msg('tba_bounce_message');
			} else {
				alert ("An error occurred in making changes. Please contact us.");
			}
        },
		onFailure: function() {
			alert("Something went wrong on our end. Please contact us.");
		}
	});
	return false;
}

function account_update(sub) {
	var token_result = user_token();
	var url;

	if (!sub) {
	
		var dbf = $('tb_account_details'); 
		var email = dbf.tba_email.value;
		if (!email.match("\@", "")) {
			alert("Please enter a valid email address to update.");
			return false;
		}

		if (dbf.tba_password.value != '' && dbf.tba_password.value != dbf.tba_password_confirm.value) { 
			alert("Entries in the two passwords fields do not match. Please re-enter.");
			dbf.tba_password.value = '';
			dbf.tba_password_confirm.value = '';
			return false;
		}

		var name = dbf.tba_name.value;
		var uni_name;
		var uni_url;
		var uni_ackname;
		var source_url = (dbf.tba_ackurl ? dbf.tba_ackurl.value : '');
		var source_ackname = (dbf.tba_ackname ? dbf.tba_ackname.value : '');
		
		if (encodeURIComponent) {
			uni_name = encodeURIComponent(name);
			uni_url = encodeURIComponent(source_url);
			uni_ackname = encodeURIComponent(source_ackname);
		} else {
			uni_name = escape(name);
			uni_url = escape(source_url);
			uni_ackname = escape(source_ackname);
		}
	
		url = '/short.cgi?command=tba_update&amp;tba_email=' + escape(email) + '&amp;tba_name=' + uni_name + '&amp;tba_password=' + escape(dbf.tba_password.value) +  '&amp;tbu_token=' + escape(token_result) + '&amp;tba_ack_y=' + ($('tba_ack_y') ? $('tba_ack_y').checked : '') + '&amp;tba_ackname=' + uni_ackname + '&amp;tba_ackurl=' + uni_url;

	} else {
	
		var check_seq = '';
		for (var i = 0; i < 4; i++) { 
			if ($(ish_types[i]).checked == true) {
				check_seq += 'y'; 
			} else {
				check_seq += 'n';
			}
		}
		var hose;
		if ($('tbhose')) { 
			hose = ($('tbhose').checked == true ? '1' : '0');
		}
		url = '/short.cgi?command=tba_update&amp;tbu_token=' + escape(token_result) + "&amp;tba_hose=" + hose + "&amp;tba_checks=" + check_seq;
	}
	
	
	$('update_account_button').disable = true;
	$('update_account_button').value = 'Making Changes';
	$('account_changes_none').style.display = 'none';
	$('account_changes_confirm').style.display = 'none';
	if ($('email_changes_msg')) {
		new Effect.Fade('email_changes_msg', { duration: 0.3, from: 1.0, to: 0.0 });
	}
	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
			$('update_account_button').disable = false;
			$('update_account_button').value = 'Update Account';
			var text = transport.responseText.match(/(^[a-z\_]+)/);
			if (!text) { 
				$('email_changes_msg_inner').innerHTML = "An error occurred in making changes. Please contact us.";
				show_email_msg();
				return;
			} else if (text[1] == 'in_use') { 
				$('email_changes_msg_inner').innerHTML = "This email address is in use by an existing account. If this address is yours, you may need to associate the address with your main account. Please read <a href=\"http://www.takecontrolbooks.com/faq#account0\">our explanation</a> of this at the Take Control Web page, which is where we manage multiple email addresses for a single account.";
				show_email_msg();
				return;
			} else if (text[1] == 'invalid') { 
				$('email_changes_msg_inner').innerHTML = "The email address you entered is not in the correct format. Please correct it and click Update Account again.";
				show_email_msg();
			} else if (text[1] == 'success') { 
				new Effect.SlideDown('account_changes_confirm');
				setTimeout("fade_msg('account_changes_confirm');", 5000);
			} else if (text[1] == 'no_changes') { 
				new Effect.SlideDown('account_changes_none');
				setTimeout("fade_msg('account_changes_none');", 5000);
			} else if (text[1] == 'pending') {
				$('email_changes_msg_inner').innerHTML = "You have already requested to change the address for your account, but have not confirmed the previous request. Please check your mail program for the message. Contact us if you do not find it.";
				show_email_msg();
			} else if (text[1] == 'confirm') {
				$('email_changes_msg_inner').innerHTML = "Please check your email for a message to activate the new address you provided. Your account will continue to use the current email until the link in the message we sent is followed.";
				show_email_msg();
			} else { 
				$('email_changes_msg_inner').innerHTML = "An error occurred in making changes. Please contact us.";
				show_email_msg();
			}

        },
		onFailure: function() {
			alert("Something went wrong on our end. Please contact us.");
		}
	});
	return false;
}

function fade_msg(id) {
	new Effect.SlideUp(id);
	return;
}
function show_email_msg() {
	new Effect.Appear('email_changes_msg', { duration: 0.6, from: 0.0, to: 1.0 });
}

function login_popup() {
	var e = $('tb_login_pup_form').tb_email_pup.value;
	var p = $('tb_login_pup_form').tb_password_pup.value;	
	var url = '/short.cgi?command=tb_popup_login&amp;email=' + escape(e) + "&amp;password=" + escape(p);

	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
			var token = transport.responseText.match(/token\=(\d+)\,paid\=(yes|no)/);
			if (token) {
				set_cookie("tbuser" + host_prefix,token[1],'3650','/',host_domain);
				$('tb_login_pup_form').tb_email_pup.value = '';
				$('tb_login_pup_form').tb_password_pup.value = '';
				$('logged_in_sidebar').style.display = '';
				$('logged_out_sidebar').style.display = 'none';
				$('lin_1_innards').style.visibility = 'hidden';
				$('logged_in_display').style.display = '';
				// alert('logged in for ' + token[1]);
				setTimeout("HidePopupContent('lin_1', 'lin', '1')", 1000);
				// reload article pages
				var hrefregexp = /(\/article\/\d+|\/account)/i;
				if (token[2] == 'yes' || location.href.match(hrefregexp) ) {
					setTimeout("location.reload()", 1000);
				} else if ($('homepage_redirect').value == 1) {
					setTimeout("window.location = '/'", 1000);
				}
			} else if (transport.responseText.indexOf('unverified') != -1) {
				$('lin_msg').style.display = '';
				$('lin_small_response').innerHTML = 'Your account has not yet been verified via email. Please check your email for a verification link. Contact us if you did not receive this email or need assistance.';
				setTimeout("fade_msg('lin_msg');", 5000);
			} else {
				$('lin_msg').style.display = '';
				$('lin_small_response').innerHTML = 'That combination of email address and password does not match our records.';
				setTimeout("fade_msg('lin_msg');", 5000);
			}
        },
		onFailure: function() {
			alert("Something went wrong on our end. Please contact us.");
		}
	});
	return false;
}

function cancel_email_cx() {

	var token_result = user_token();
	if (token_result === null) { return false; }

	url = '/short.cgi?command=tba_cancel_email_cx&amp;tbu_token=' + escape(token_result);
	
	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
			var text = transport.responseText.match(/success/);
			if (text) { 
				new Effect.SlideDown('account_changes_confirm');
				setTimeout("fade_msg('account_changes_confirm');", 5000);
				new Effect.Fade('outstanding_email_change', { duration: 1 });
			} else {
				alert("Something went wrong on our end. Please contact us.");
			}
        },
		onFailure: function() {
			alert("Something went wrong on our end. Please contact us.");
		}
	});
	return false;
}

function account_logout(type) {
	set_cookie("tbuser" + host_prefix,'',-1,'/',host_domain);
	set_cookie("tbcomm" + host_prefix,'',-1,'/',host_domain);
	if (type == 'sidebar') {
		$('logged_in_sidebar').style.display = 'none';
		$('logged_out_sidebar').style.display = '';
	} else { 
		$('lin_1_innards').style.visibility = 'hidden';
		$('logged_in_display').innerHTML = 'Logged out!';
		$('logged_in_display').style.display = '';
		ShowPopupContent('lin_1','lin_recaptcha', 0);		
		setTimeout("HidePopupContent('lin_1', 'lin', '1')", 1650);
		if (location.href.match(/\/cxemail\//)) {
			setTimeout("window.location = '/'", 1650);
		} else {
			setTimeout("location.reload()", 1650);
		}
	}
	return false;
}

function static_login_popup() {
	$('homepage_redirect').value = 1; 
	ShowPopupContent('lin_1','lin_recaptcha', 0); 
	setTimeout('$("tb_email_pup").focus()',750);
	return false;
}

function comments_track(aid, choice) {

	var token_result = user_token();
	if (token_result === null) { return false; }
	
	// set switch

	url = '/short.cgi?command=comments_track&amp;tbu_token=' + escape(token_result) + "&amp;article_id=" + escape(aid) + "&amp;choice=" + escape(choice);
	$('ct_off_' + aid).style.color = '#c0c0c0';
	$('ct_on_' + aid).style.color = '#c0c0c0';
	
	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
			var success = transport.responseText.match(/success/);
			if (success) {
				if (choice == 0) {
					$('ct_off_' + aid).style.display = '';
					$('ct_on_' + aid).style.display = 'none';
				} else {
					$('ct_off_' + aid).style.display = 'none';
					$('ct_on_' + aid).style.display = '';
				}
				$('ct_off_' + aid).style.color = '#000';
				$('ct_on_' + aid).style.color = '#000';
			} else {
				alert("Something went wrong on our end. Please contact us.");
			}
        },
		onFailure: function() {
			alert("Something went wrong on our end. Please contact us.");
		}
	});
	return false;
}

function user_token() { 
	var token_regexp = new RegExp("tbuser" + host_prefix + "\=([^;]+)", "");
	var token = document.cookie.match(token_regexp);
	var token_result;
	if (token === null) { token_result = 0; } else { token_result = token[1]; }
	return token_result;
}
