// onLoad handler
addDOMLoadEvent=(function(){var e=[],t,s,n,i,o,d=document,w=window,r='readyState',c='onreadystatechange',x=function(){n=1;clearInterval(t);while(i=e.shift())i();if(s)s[c]=''};return function(f){if(n)return f();if(!e[0]){d.addEventListener&&d.addEventListener("DOMContentLoaded",x,false);/*@cc_on@*//*@if(@_win32)d.write("<script id=__ie_onload defer src=//0><\/scr"+"ipt>");s=d.getElementById("__ie_onload");s[c]=function(){s[r]=="complete"&&x()};/*@end@*/if(/WebKit/i.test(navigator.userAgent))t=setInterval(function(){/loaded|complete/.test(d[r])&&x()},10);o=w.onload;w.onload=function(){x();o&&o()}}e.push(f)}})();

function throwSignInToVoteMsg() {
	$('hidden_poll_log_in_link').toggle();
}
function disablePESBtn() {
	$('poll_entry_submit_btn').disabled='disabled';
}

function remoteResourceCreationFailed(request){
	alert("There was an error with your request:\n"+request.responseText);	
}

function remoteInvitationCreationSuccessful(request){
	eval("var newInvite = "+request.responseText);
	var form_id = newInvite.attributes.invitable_type.toLowerCase()+"_"+newInvite.attributes.invitable_id+"_invitation";
	//$(form_id).elements["invitation_recipient_email"].value = '';
	//$(form_id+'_message').innerHTML = "An invitation has been sent to "+newInvite.attributes.recipient_email
	//Element.addClassName(form_id+'_message', 'attention')
	//$(form_id+"_submit").disabled = false;
	msg = "<fieldset class=\"clear\">";
	msg = msg + "<h2>Thank you</h2>This story has been sent to your friend.<br /><br />";
	msg = msg + "<button class=\"button_standard\" type=\"button\" onclick=\"Element.toggle('staf_container');\"><span>Close</span></button><br /></fieldset>";
	$(form_id).innerHTML = msg;
}

function remoteFlagCreationSuccessful(request){
	eval("var newFlag = "+request.responseText);	
	var form_id = "flag_"+newFlag.attributes.flaggable_type.toLowerCase()+"_"+newFlag.attributes.flaggable_id+"_"+newFlag.attributes.flag_name;
	$(form_id).innerHTML='You have flagged this item.';
	Element.addClassName(form_id, 'attention');
	$(form_id+'_submit').disabled = false;
}

function remotePasswordResetSuccessful(request, btn_id){
	alert(request.responseText);
	$(btn_id).childNodes[0].innerHTML = 'reset password';
	$(btn_id).disabled = false;
	$('wom_reset_password').hide();
}

function remotePasswordResetLoading(btn_id) {
	$(btn_id).disabled = true; 
	$(btn_id).childNodes[0].innerHTML = 'resetting password...';
}

function remotePasswordResetFailed(request, btn_id) {
	remoteResourceCreationFailed(request); 
	$(btn_id).childNodes[0].innerHTML = 'reset password'; 
	$(btn_id).disabled = false;
}

function validateRecipeSearchForm(){
	if($('recipe_category').value || $('recipe_product_id').value){
		return true 
	}else{
		alert('Please choose a recipe meal type, or related product');
		return false;
	} 
}
// This is called by flash to update the display number
// we dont update the label anymore, I think we can ditch this next time we update the challenge widget
function updateLogCount(num){
	$('challenge_entry_count').innerHTML = num;
	if(num == 1){
		$('challenge_entries_label').innerHTML = 'entry logged';
	}else if(num == 2){
		$('challenge_entries_label').innerHTML = 'entries logged'
	}	
}

function showPrimaryNav(){
	$$('#nav_bar li').each(function(e,i){Element.show(e)});
	$('nav_bar_toggler').onclick = hidePrimaryNav;
}

function hidePrimaryNav(){
	Element.addClassName('nav_bar_container','js_enabled'); // this triggers the style the first time the menu is hidden
	$$('#nav_bar li.false').each(function(e,i){Element.hide(e)});
	$('nav_bar_toggler').onclick = showPrimaryNav;
}

// Checkbox labels are also clickable. Use <span class="clickable"> on those labels.
function toggle_checkmark(id,hiddenFieldName){
	field = $(id);
	button = $(id+"_button");
	theForm = field.form;
	hiddenInputs = theForm.getInputs('hidden');
	// update the hidden field rails creates for checkboxes as well
	for(i=0;i<hiddenInputs.length;i++){
		if (hiddenInputs[i].name == hiddenFieldName){
			theFieldToUpdate = hiddenInputs[i];
		}
	}

	if(field.checked == true){
		field.value = "0";
		field.checked = false;
		if (hiddenFieldName != "none") {theFieldToUpdate.value = "0";}
	}else{
		field.value = "1";
		field.checked = true;
		if (hiddenFieldName != "none") {theFieldToUpdate.value = "1";}
	}
}

function dropdownLink(loc) {
	if (loc.length > 0) {
		location.href=loc;
	}
}
// converts a ul into a javascript drop-down, to allow for graceful fall-back
function listToDropDown(listid, label, select_id, select_index){
	var button_label = label || 'GO';
	var list = $(listid);
	//var form = '<form action="#" onChange="location.href=this.elements[0].value;return false;">';
	var form = '<form action="#">';
	form += '<select onChange="dropdownLink(this.value);return false;" id="';
	if (select_id) {
		form += select_id;
	} else {
		// foo
	}
	form += '">';
	form += '<option value=""></option>';
	$A(list.getElementsByTagName('li')).each(function(li, index){
		var link = li.getElementsByTagName('a')[0];
		if(link) {
			form += '<option value="'+link.href+'">'+link.innerHTML+'</option>';		
		}	
	})
	if(button_label == 'GO'){
		form += '</select><input type="submit" class="go_button" value="Go" /></form>';
	}else if(button_label == -1){
		form += '</select></form>'
	}else{
		form += '</select><button type="submit">'+button_label+'</button></form>';
	}
	
	Element.replace(list, form);
	if (select_index && $(select_id)) {
		$(select_id).selectedIndex = select_index;
	}
}

function stylizeCheckbox(object, method, checked){
	// change this to a div or span or something
	if(navigator.userAgent.toLowerCase().indexOf('msie') == -1){
		var id = object ? object+'_'+method : method;		
		new Insertion.After(id, '<div id="'+id+'_button" '+
														'class="clickable checkbox '+(checked ? 'true' : '')+'" '+
										 				'onclick="toggle_checkmark(\''+id+'\');"/>');
		if(!$(id).checked) $(id).value = '0';
		$(id).type = 'hidden';
	}		
}


// Looks for text that wraps and appends an ellipses (...) to the end
function trimEllipsis(){
	$$('.textoverflow span').each(function(e,i){
		if(e.offsetHeight > e.parentNode.offsetHeight+5){ //+5 gives it a little leway for various browsers
			e.innerHTML+='<span class="ellipsis" style="left:'+(e.offsetWidth+3)+'px">&hellip;</span>';
		}
	});
}

addDOMLoadEvent(trimEllipsis);

function clickclear(thisfield, defaulttext) {
	if (thisfield.value == defaulttext) {
		thisfield.value = "";
	}
}

function clickrecall(thisfield, defaulttext) {
	if (thisfield.value == "") {
		thisfield.value = defaulttext;
	}
}

/* Handles click events for our captcha */
function captchaClickHandler(evt){
	// get the element that fired the event
	var ele = Event.element(evt);
	// make sure we've got a direct decendant of the captcha ul
	while(ele.up().id != "captcha"){ ele = ele.up(); }
	// get the numeral on the end of our id string
	var id = ele.id.substr(ele.id.length-1);
	// read the hidden fields value and store each value as sepearte array elements
	var captcha_values = $('user_captcha').value.split(",");
	
	// remove the blank array elements if we've have any
	while(captcha_values.indexOf("") > -1){
		captcha_values.splice(captcha_values.indexOf(""), 1);
	}
	
	// if the clicked element is already selected
	if(captcha_values.indexOf(id) > -1){
		// remove it's value from the array of selected values
		captcha_values.splice(captcha_values.indexOf(id), 1);
		// remove the selected box from around it
		ele.down().removeClassName("selected");
	// if the clicked element is not currently selected
	}else{
		// dont do anything if we're already at our limit
		if(captcha_values.length < 2){
			// otherwise push the value of the current element onto our captcha_values array
			captcha_values.push(id);
			// and place the selected box around the element
			ele.down().addClassName("selected");
		}
	}
	// finally store our captcha values back in the hidden element as comma seperated values
	$('user_captcha').value = captcha_values.join(",");
	return false;
};

function rbTimeToJsDate(dateString){
	return new Date(dateString.replace(/\s[\d\:]+$/, '').replace(/-/g, ','));
}

function prettyPrintDate(date){
	return date.toString().substr(4,11);
}

function prettyPrintRbTime(rbTimeOrDateString){
	return prettyPrintDate(rbTimeToJsDate(rbTimeOrDateString));
}

function removeTeamFromPledgeForm(whichTeam){
	$('challenge_team_form').hide();
	var teamOptions = $A($('team_challenge_pledge_team_id').options);
	if(teamOptions.length < 2){
		$('accept_team_challenge_form').innerHTML = "<p>You have already accepted this challenge with all your teams.</p>";
	}else{
		var bla = teamOptions.reject(function(opt,i){
			return opt.value == whichTeam;
		}).map(function(opt,i){
			return '<option value="'+opt.value+'">'+opt.innerHTML+'</option>';
		});
		$('team_challenge_pledge_team_id').innerHTML = bla
		$('accept_team_challenge_form_submit').disabled = false;
	}
}
function updateTeamPledgeForm(whichPledge){
	var pledge = pledges.find(function(p,i){return p.id == whichPledge;});
	$('pledge_acceped_on').innerHTML = prettyPrintRbTime(pledge.created_at);	
	$('pledge_entry_log_date').innerHTML = $A(pledge.loggable_dates).map(function(v,i){
																						return '<option value="'+v+'">'+prettyPrintRbTime(v)+'</option>';
																					}).join("\n");
																					
}
function validateTeamInvitation(){
	var username = $('invitation_username').value.strip();
	var email = $('invitation_email').value.strip();
	if((username != '' && email != '') || 
		(username == '' && email == '')){
		alert("Please enter a Kashi.com username OR and email address.");
		return false;
	}else if(email != ''){
		if(email.match(/^\S+@\S+\.\w+$/i)){
			return true;
		}else{
			alert("The email address "+email+" is not valid.");
			return false;
		}
	}else{
		return true;
	}
}

function getCookieValue (cookieName) {
  var exp = new RegExp (escape(cookieName) + "=([^;]+)");
  if (exp.test (document.cookie + ";")) {
    exp.exec (document.cookie + ";");
    return unescape(RegExp.$1);
  }
  else return false;
}

function testSessionCookie () {
  document.cookie ="testSessionCookie=Enabled";
  if (getCookieValue ("testSessionCookie")=="Enabled")
    return true 
  else
    return false;
}

// tells links with rel="external" to open in a new window
function externalLinks () { 
	if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName("a");
	for (var i=0; i<anchors.length; i++) {
		var anchor = anchors[i];
		if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external"){
			anchor.target = "_blank"; 
		}
	}
}



function makeButtonHoverState() {
	
	// Its ugly, yes, but it gives these buttons :hover state for ie6
	// had to target both the brownbuttons AND button_standards becasue of ie6 refusing to recognize multiple classes in CSS
	// had to target the buttons AND their span elements becuase of the way we coded and styled those elements

	
	if ($('poll_entry_submit_btn')){
		$('poll_entry_submit_btn').addClassName('button_standardHover').removeClassName('button_standardHover');

	}
	
	/* we should be able to remove all but this bit after redesign is complete, no more gabillion styles of buttons */
	theButtons = $$('button');
	theButtons.each(function(s) {
		s.observe('mouseover', function(event){
			Event.element(event).addClassName('hover');
		}).observe('mouseout', function(event){
			Event.element(event).removeClassName('hover');
		});	
	});
	theButtonsSpan = $$('button span');
	theButtonsSpan.each(function(s) {
		s.observe('mouseover', function(event){
			Event.element(event).addClassName('hover');
		}).observe('mouseout', function(event){
			Event.element(event).removeClassName('hover');
		});	
	});
	
	
	
	theBrownButtons = $$('button.brownbutton');
	theBrownButtons.each(function(s) {
		s.observe('mouseover', function(event){
			Event.element(event).addClassName('brownbuttonHover');
		}).observe('mouseout', function(event){
			Event.element(event).removeClassName('brownbuttonHover');
		});	
	});
	
	theBrownButtonsSpan = $$('button.brownbutton span');
	theBrownButtonsSpan.each(function(s) {
		s.observe('mouseover', function(event){
			Event.element(event).up(0).addClassName('brownbuttonHover');
		}).observe('mouseout', function(event){
			Event.element(event).up(0).removeClassName('brownbuttonHover');
		});	
	});

	theStandardButtons = $$('button.button_standard');
	theStandardButtons.each(function(s) {
		s.observe('mouseover', function(event){
			Event.element(event).addClassName('button_standardHover');
		}).observe('mouseout', function(event){
			Event.element(event).removeClassName('button_standardHover');
		});	
	});
	
	theStandardButtonsSpan = $$('button.button_standard span');
	theStandardButtonsSpan.each(function(s) {
		s.observe('mouseover', function(event){
			Event.element(event).up(0).addClassName('button_standardHover');
		}).observe('mouseout', function(event){
			Event.element(event).up(0).removeClassName('button_standardHover');
		});	
	});	
	
	$('util_search_submit').observe('mouseover', function(event){
		Event.element(event).addClassName('hover');
	}).observe('mouseout', function(event){
		Event.element(event).removeClassName('hover');
	});

}

function contentTypeToolTip() {
	articleTitles = $$("a.article_icon_title");
	articleTitles.each(function(s) {
		new Tooltip(s, s.title);		
	});
}

var Tooltip = Class.create();
Tooltip.prototype = {
	initialize: function(element, tool_tip) {
		
		var options = Object.extend({
			min_distance_x: -16,
			min_distance_y: 35,
			delta_x: 0,
			delta_y: 0,
			zindex: 1000
		}, arguments[2] || {});
		
		this.options = options;		
		this.element = $(element);
		this.element.title="";
		this.tool_tip = $(document.createElement("div"));
		this.tool_tip_text = $(document.createElement("span")); 
		this.tool_tip_end = $(document.createElement("span")); 
		document.body.appendChild(this.tool_tip);
		document.body.appendChild(this.tool_tip_text);
		document.body.appendChild(this.tool_tip_end);
		this.tool_tip.addClassName("articleTooltip");
		this.tool_tip_text.addClassName("articleTooltipText");
		this.tool_tip_end.addClassName("articleTooltipEnd");
		
		this.tool_tip.appendChild(this.tool_tip_text);
		this.tool_tip.appendChild(this.tool_tip_end);
		this.tool_tip_text.appendChild(document.createTextNode(tool_tip));

		this.tool_tip.hide();

		this.eventMouseOver = this.showTooltip.bindAsEventListener(this);
		this.eventMouseOut   = this.hideTooltip.bindAsEventListener(this);
		this.eventMouseMove  = this.moveTooltip.bindAsEventListener(this);

		this.registerEvents();
	},

	destroy: function() {
		Event.stopObserving(this.element, "mouseover", this.eventMouseOver);
		Event.stopObserving(this.element, "mouseout", this.eventMouseOut);
		Event.stopObserving(this.element, "mousemove", this.eventMouseMove);
	},

	registerEvents: function() {
		Event.observe(this.element, "mouseover", this.eventMouseOver);
		Event.observe(this.element, "mouseout", this.eventMouseOut);
		Event.observe(this.element, "mousemove", this.eventMouseMove);
	},

	moveTooltip: function(event){
		Event.stop(event);
		// get Mouse position
		var mouse_x = Event.pointerX(event);
		var mouse_y = Event.pointerY(event);
		mouse_x = mouse_x + this.options.min_distance_x;
		mouse_y = mouse_y - this.options.min_distance_y;

		// now set the right styles
		this.setStyles(mouse_x, mouse_y);
	},
	
		
	showTooltip: function(event) {
		Event.stop(event);
		this.moveTooltip(event);
		new Element.show(this.tool_tip);
	},
  
	setStyles: function(x, y){
		// set the right styles to position the tool tip
		Element.setStyle(this.tool_tip, {
			position:'absolute',
			top:y + this.options.delta_y + "px",
			left:x + this.options.delta_x + "px",
			zindex:this.options.zindex
		});
	
	},

	hideTooltip: function(event){
		new Element.hide(this.tool_tip);
	}

}

/* for visualizer ajax */
function throw_delete_comment_btns(userid) {
	$$('.accomplishment_actions.user'+userid).each(function(div,index){
		var accomplishment_id = div.id.replace(/accomplishment_actions_/, '');
		div.innerHTML = "<a class=\"delete_accomplishment_link\" title=\"delete this accomplishment\" onclick=\"if (confirm('Are you sure you want to delete this accomplishment?')) { var f = document.createElement('form'); f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = this.href;var m = document.createElement('input'); m.setAttribute('type', 'hidden'); m.setAttribute('name', '_method'); m.setAttribute('value', 'delete'); f.appendChild(m);f.submit(); };return false;\" href=\"/accomplishments/ACCOMPLISHMENT_ID\"> </a>".replace(/ACCOMPLISHMENT_ID/, accomplishment_id);
	});
}



/* new comments JS */

// Wonky. Last minute. Needs a thorough implementation revisit.
//
function mod_comment_count(step) {

	if (!$('num_comments')) { return; };

	var count = 0;
	
	if ($('num_comments').innerHTML.match(/No comments yet/i)) {
		count = step;
	} else {
		count = parseInt($('num_comments').innerHTML) + step;
	}
	
	if (count < 1) {
		$('num_comments').innerHTML = "No comments yet. <span>Have something to say? Share it here.</span>";
	} else {
		$('num_comments').innerHTML = count + ((count == 1) ? ' comment' : ' comments');
	}
	$$('.extender_num_comments').each(function(ele,idx) {
		ele.innerHTML = count;
	});
}

function toggle_comment_reply_form(id) {
	// alert('toggle!');
	if ($("comment_"+id+"_reply_form_block").visible()) {
		Effect.BlindUp("comment_"+id+"_reply_form_block");
		//$("comment_"+id+"_reply_form_block").toggle();
		$('comment_reply_'+id+'_body_ta').value = "";
		$("reply_to_comment_"+id+"_toggle_action").removeClassName('open');
		
	} else {
		Effect.BlindDown("comment_"+id+"_reply_form_block");
		//$("comment_"+id+"_reply_form_block").toggle();
		$('comment_reply_'+id+'_body_ta').value = "";
		$("reply_to_comment_"+id+"_toggle_action").addClassName('open');
	}
	return false;
	Event.stop();
}

function toggle_hidden_comment_replies(root_id) {
	//alert(root_id);
	browserIsIE = (navigator.appName == "Microsoft Internet Explorer")?true:false;
	if(browserIsIE) {
		$('expand_'+root_id+'_block').hide();
		$('comment_'+root_id+'_hidden_children').show();
	} else {
		Effect.Fade('expand_'+root_id+'_block', {duration: 1.0, queue: 'last'});
		Effect.BlindDown('comment_'+root_id+'_hidden_children', {duration: 1.0, queue: 'first'});
	}
}

function toggle_hidden_comments() {
	Effect.BlindDown('hidden_root_comments');
	Effect.Fade('comments_pull_down_block');
	return false;
}

function setup_heights(id) {
	elem_height = $('comment_'+id+'_comment').getHeight();
	$('comment_'+id+'_comment').setStyle({height: elem_height+'px'});
}
function toggle_comment_edit_block(c_id) {
	
	$('comment_'+c_id+'_comment_wrapper').toggle().up("li.comment").toggleClassName('editing');
	$('comment_'+c_id+'_form_block').toggle();
	
	/*
	if($('comment_'+c_id+'_form_block').visible()) { // edit comment mode
		var some_height = $('comment_'+c_id+'_comment').getStyle('height');
		var height_string = some_height+";";
		Effect.Fade('comment_'+c_id+'_form_block', {duration: 0.5});
		$('comment_'+c_id+'_comment_wrapper').morph('height:'+height_string, {duration: 0.5, delay: 0.4});
		Effect.Appear('comment_'+c_id+'_comment_wrapper', {duration: 0.5, delay: 0.5});
	} else { // comment view
		// fade/close comment and appear form
		setup_heights(c_id);
		var to_height = $('comment_'+c_id+'_form_block').getHeight();
		$('comment_'+c_id+'_comment_wrapper').morph('height:'+to_height+'px;', {duration: 0.5});
		Effect.Fade('comment_'+c_id+'_comment_wrapper', {duration: 1.0});
		Effect.Appear('comment_'+c_id+'_form_block', {duration: 0.5, delay: 0.95});
	}
	*/
	reset_ta_val(c_id);
}

function throw_user_comment_actions(userid) {
	var counter = 0;
	$$('.comment_actions.user'+userid).each(function(div,index){
		var comment_id = div.parentNode.parentNode.parentNode.parentNode.id.replace(/comment_/, '');
		var foo_height = $('comment_'+comment_id).getHeight();
		var foo_width = $('comment_'+comment_id).getWidth();
		//$('comment_'+comment_id).setStyle({height: foo_height+"px", width: foo_width+"px", backgroundColor: 'white'});
		div.innerHTML = "<a class=\"edit_comment_link\" href=\"#\" onclick=\"toggle_comment_edit_block("+comment_id+");return false;\">Edit</a>";
		div.innerHTML += " | ";
		div.innerHTML += "<a class=\"delete_comment_link\" onclick=\"if (confirm('Are you sure you want to delete this comment?')) { new Ajax.Request('/comments/"+comment_id+"', {asynchronous:true, evalScripts:true, method:'delete', onLoading:function(request){handle_comment_deletion("+comment_id+")}}); }; return false;\" href='#'>Delete</a>";
	});
}

function throw_comment_reply_links(userid) {
	$$('a.reply_to_comment').each(function(a_elem,index) {
		var a_elem_id = a_elem.id;
		var this_comment_id = parseInt(a_elem_id.sub('reply_to_comment_','').sub('_toggle_action',''));
		a_elem.writeAttribute('onclick', 'Event.stop();return false;');
		a_elem.onclick = 'Event.stop();return false;';
		a_elem.onclick = function() { return false; };
		Event.observe($(a_elem),'click',function(){
			toggle_comment_reply_form(this_comment_id);
			return false;
		});
	});
}
function comment_loading(id) {
	//$('comment_'+id+'_submit_button').disable();
}
function comment_posted(id) {
	track_comment_event();	
	$('comment_'+id+'_submit_button').disabled = false;
	$('comment_'+id+'_body_ta').value = "";
}
function rep_ta_val(elem, val) {
	$(elem).value = val;
}
function reset_ta_val(id) {
	var b_elem = $('comment_'+id+'_body');
	var f_elem = $('comment_'+id+'_body_ta');
	f_elem.value = b_elem.firstChild.innerHTML;
}

function handle_comment_update(id,body) {
	$('comment_'+id+'_comment_wrapper').toggle().up("li.comment").toggleClassName('editing');
	$('comment_'+id+'_form_block').toggle();
}
function handle_comment_deletion(id) {
	var del_base_elem = $('comment_'+id);
	del_base_elem.setStyle({height: del_base_elem.getHeight()+"px"});
	var elem_children = del_base_elem.childElements();
	new Effect.Opacity('comment_'+id, { from: 1.0, to: 0.5, duration: 0.9 });
	//	elem_children.each(function(e){alert("can IE really do recursion?: "+e.inspect());}); //Element.remove(e)
	//$('comment_'+id).setStyle({textAlign: 'center', height: '30px', marginBottom: '5px'});
	//$('comment_'+id).insert("<img src='/assets/images/chrome/loading.gif' />");
}
function do_comment_deletion(id) {
	browserIsIE = (navigator.appName == "Microsoft Internet Explorer")?true:false;
	if(browserIsIE) {
		$('comment_'+id).remove();
	}	else {
		Effect.BlindUp('comment_'+id);
	}
}
function handle_comment_loading(id, is_reply) {
	if (is_reply) {
	//if ($('comment_'+id+'_child_form_submit_btn_block') && $('comment_'+id+'_child_form_submit_btn_block').visible()) {
		var base_elem = $('comment_'+id+'_child_form_submit_btn_block');
		var elems = base_elem.childElements();
		var elem_0 = elems[0];
		elem_0.toggle();
		var elem_1 = elems[1];
		elem_1.toggle();
	} else { 
	//if ($('comment_'+id+'_form_submit_btn_block') && $('comment_'+id+'_form_submit_btn_block').visible()) {
		var base_elem = $('comment_'+id+'_form_submit_btn_block');
		var elems = base_elem.childElements();
		var elem_0 = elems[0];
		elem_0.toggle();
		var elem_1 = elems[1];
		elem_1.toggle();
	}
}

// MODAL WINDOW TOGGLE, POSITION. It is a fixed width, variable height.
function show_modal_win(elem){
	$('modal_bkg').toggle().setStyle({zIndex:900});
	var section = $(elem);
	var psize = document.viewport.getDimensions();
	var pscroll = document.viewport.getScrollOffsets();
	if (pscroll[0] == "") { pscroll[0] = 0; }
	if (pscroll[1] == "") { pscroll[1] = 0; }
	var x = pscroll[0] + ((psize.width-600) / 2) + 'px';
	var eHeight = section.getHeight();
	var y = pscroll[1] + ((psize.height-eHeight) / 2) + 'px';
	section.setStyle({top:y,left:x, zIndex:901});
	section.toggle();
}
function hide_modal_win(elem){
	$('modal_bkg').toggle();
	var section = $(elem);
	section.toggle();
	// clear errors from modal windows upon closing
	var sectionChildren = section.getElementsByTagName('*');
	for (i=0;i<sectionChildren.length;i++){
		var thing = $(sectionChildren[i]);
		if (thing.hasClassName('inputWithErrors')){
			thing.removeClassName('inputWithErrors');
		}
		if (thing.hasClassName('error_messages')){
			// don't remove the parent error message div, though, because we just write to its innerHTML and don't alter its classNames, etc
			if (thing.identify() == "authenticate_errors" || sectionChildren[i].identify() == "forgot_pass_errors" || sectionChildren[i].identify() =="login_errors") {
				thing.innerHTML = "";
				thing.toggle();
			}else{
				thing.removeClassName('error_messages');
			}
		}
	}
}
function rewriteLoginLink(){
	// add the anchor element that should invoke the modal login window to the end of this list
	login_links = $$('#log_in_header_link', '#log_in_challenge_link', '#log_in_comment_link', '#log_in_rating_link', '#log_in_poll_link', '#log_in_accomplishment_link', '#toolbox_staf a.logged_out', '.log_in_challenge_link');
	
	// 	for each login link, prevent the link from goign to /login and show the modal window
	login_links.each(function(s){
		s.observe('click', function(event){
			event.preventDefault();
			show_modal_win('sign_in');
		})		
	});
	
}


function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

// Tucks all external links into a fake pageview in google analytics.
function trackOutgoingLinks(){
	var links = $$('a'); // Get all the links.
	links.each(function(l){
		var link = l.getAttribute("href");
		if(link && !link.include('kashi.com') && link.startsWith('http')){
			if(typeof(pageTracker) != 'undefined'){ pageTracker._trackPageview('/ext/' + link); }
			if(typeof(pageTracker2) != 'undefined'){ pageTracker2._trackPageview('/ext/' + link); }		
			if(typeof(pageTracker3) != 'undefined'){ pageTracker3._trackPageview('/ext/' + link); }			
		}
	});
}

function manageCookies(){
	// If they haven't visited yet...
	if(!readCookie('__kashi_visit')){
		createCookie('__initial_referrer', document.referrer, 0); // Record the referrer.
		createCookie('__kashi_visit', 1, 0); // Flag them as having visted.
	}
}
// For Variety Fiber Campaign
function toggleArrow(e){
	elem = $(e);
	if (elem.hasClassName('arrow')){
		elem.removeClassName('arrow');
		elem.addClassName('arrowExpanded');
	}else{
		elem.removeClassName('arrowExpanded');
		elem.addClassName('arrow');
	}
	elem.blur();
}

function track_comment_event(){
	// The category is based on the URL's root directory, e.g: /articles/103 => articles.
	var category = window.location.pathname.split('/')[1];
	var action = 'comment_post';
	trackEvent(category, action);
}

// Observe any print buttons on the page and GA track them.
function trackPrintActions(e){
	$$('.print').invoke('observe', 'click', function(e){
		track_event_for_page('print')
	});
}

// Given a category and an action, send the event to all 3 of our tracking accounts.
// If the category is the standard -- the first part of the URL -- use track_event_for_page().
function trackEvent(category, action){
	if(typeof(pageTracker) != 'undefined'){ pageTracker._trackEvent(category, action); }
	if(typeof(pageTracker2) != 'undefined'){ pageTracker2._trackEvent(category, action); }		
	if(typeof(pageTracker3) != 'undefined'){ pageTracker3._trackEvent(category, action); }	
}

// Tracks the event, using the first chunk of the URL as the category. Only requires an action.
// e.g: /articles/103 => articles.
function track_event_for_page(action){
	var category = window.location.pathname.split('/')[1];	
	if(typeof(pageTracker) != 'undefined'){ pageTracker._trackEvent(category, action); }
	if(typeof(pageTracker2) != 'undefined'){ pageTracker2._trackEvent(category, action); }		
	if(typeof(pageTracker3) != 'undefined'){ pageTracker3._trackEvent(category, action); }	
}


function toggle_filter_item(items) {
	var filter_items = $$('.filter-on');
	items.each(function(item) {
		filter_items.each (function(i) {
			if (i.identify() != 'filter-'+item && i.identify() != 'filter-'+items[0] && i.identify() != 'filter-'+items[1]) {
				i.removeClassName('filter-on');
			}
		});
		
		if(!$('filter-'+item).hasClassName('filter-on')) {
			$('filter-'+item).addClassName('filter-on');
		}
	});
}

function toggle_super_topic(elem) {
	var elem_parent = $(elem).parentNode;
	var display_type = "none";
	if( $(elem) && $(elem).getStyle('display') == 'none') {
		display_type = "block";
		$(elem_parent).addClassName('active');
	} else {
		$(elem_parent).removeClassName('active');
	}
	$(elem).setStyle({display:display_type});
}

// Send To A Friend
var STAF = {
	init: function() {
		STAF.container = $('staf_container');
		if (!STAF.container) return;
		STAF.toolbox_staf = $$('#toolbox_staf a.logged_in')[0];
		if (!STAF.toolbox_staf) return;
		STAF.the_form = STAF.container.down('form');
		STAF.submit_button = STAF.the_form.select('button')[0];
		STAF.another_friend = $('another_friend');
		STAF.add_another = $('add_another');
		STAF.form_cancel = $('form_cancel');
		STAF.invitation_recipient_email = $('invitation_recipient_email');
		STAF.invitation_recipient_email2 = $('invitation_recipient_email2');
		
		STAF.submit_button.observe('click', function(event){
			track_event_for_page('staf_send');
		});
		
		STAF.toolbox_staf.observe('click', function(event){
			track_event_for_page('staf_show');
			STAF.container.show();
			event.preventDefault();
		});		
		STAF.add_another.observe('click', function(event){
			STAF.add_another.hide();
			STAF.add_field();
			event.preventDefault();
		});
		STAF.form_cancel.observe('click', function(event){
			STAF.reset_form();
			event.preventDefault();
		});
		
	},
	add_field: function(){
		STAF.invitation_recipient_email2.enable();
		STAF.another_friend.show();
	},
	reset_form: function(){
		STAF.container.toggle();
		STAF.another_friend.hide();
		STAF.invitation_recipient_email.value = "";
		STAF.invitation_recipient_email2.value = "";
		STAF.invitation_recipient_email2.disable();
		STAF.add_another.show();
	}
}

function ratings_helper () {
	ratings_block_links = $$('#star-ratings-block ul.star-rating li a');
	if (!ratings_block_links) return;
	
	ratings_header = $$('#star-ratings-block h3')[0];
	
	ratings_block_links.each(function(s){
		s.observe('mouseover', function(event){
			ratings_header.update('<em>Click to rate</em>');
		}).observe('mouseout', function(event){
			ratings_header.update('Community Rating');
		});
	});	
}

function searchResultHighlighting () {
	s_results = $$('#search_results .search_result');
	if (s_results.length == 0) return;
	
	s_results.each(function(s){
		s.observe('mouseover', function(event){
			s.addClassName('hover');
		}).observe('mouseout', function(event){
			s.removeClassName('hover');
		}).observe('click', function(event){
			s.removeClassName('hover');
			url = s.down("h2 a");
			document.location.href = url;			
		})
	});
		
}

Event.observe(window, 'load', function() {	
	isIE = (navigator.appName == "Microsoft Internet Explorer")?true:false;
	isIE7 = (isIE && document.documentElement && typeof document.documentElement.style.maxHeight!="undefined")?true:false;
	isIE6 = (isIE && !isIE7)?true:false;
	externalLinks();
	contentTypeToolTip();
	if(isIE6){
		makeButtonHoverState();
	}
	manageCookies();
	trackPrintActions();
	rewriteLoginLink();
	STAF.init();
	ratings_helper();
	// searchResultHighlighting(); taking this out, rolling back search for now
});
