function register_onload(func) {
  Event.observe(window, 'load', func, false);
}

function show_dates_as_local_time() {
  var spans = document.getElementsByTagName('span');
  for (var i=0; i<spans.length; i++) {
    if (spans[i].className.match(/\btypo_date\b/i)) {
      spans[i].innerHTML = get_local_time_for_date(spans[i].title);
    }
  }
}

function get_local_time_for_date(time) {
  system_date = new Date(time);
  user_date = new Date();
  delta_minutes = Math.floor((user_date - system_date) / (60 * 1000));
  if (Math.abs(delta_minutes) <= (8*7*24*60)) { // eight weeks... I'm lazy to count days for longer than that
    distance = distance_of_time_in_words(delta_minutes);
    if (delta_minutes < 0) {
      return distance + ' from now';
    } else {
      return distance + ' ago';
    }
  } else {
    return 'on ' + system_date.toLocaleDateString();
  }
}

// a vague copy of rails' inbuilt function, 
// but a bit more friendly with the hours.
function distance_of_time_in_words(minutes) {
  if (minutes.isNaN) return "";
  minutes = Math.abs(minutes);
  if (minutes < 1) return ('less than a minute');
  if (minutes < 50) return (minutes + ' minute' + (minutes == 1 ? '' : 's'));
  if (minutes < 90) return ('about one hour');
  if (minutes < 1080) return (Math.round(minutes / 60) + ' hours');
  if (minutes < 1440) return ('one day');
  if (minutes < 2880) return ('about one day');
  else return (Math.round(minutes / 1440) + ' days')
}

function commentAdded(request) {
  Element.cleanWhitespace('commentList');
  new Effect.BlindDown($('commentList').lastChild);
  if ($('dummy_comment')) { Element.remove('dummy_comment'); }
  $('commentform').elements["comment_body"].value = '';
  $('commentform').elements["comment_body"].focus();
}

function failure(request) {
  $('errors').innerHTML = request.responseText;
  new Effect.Highlight('errors');
}

function loading() {
  $('form-submit-button').disabled = true;
  Element.show('comment_loading');
  new Element.hide('preview');
}

function complete(request) {
  Element.hide('comment_loading');
  Element.show('commentform');
  $('form-submit-button').disabled = false;  

  if (request.status == 200) { commentAdded() };  
}

function popup(mylink, windowname)
{
  if (! window.focus) return true;
  var href;
  window.open(mylink, windowname, 'width=400,height=500,scrollbars=yes');
  return false;
}

// From http://www.shawnolson.net/scripts/public_smo_scripts.js
function check_all(checkbox) {
 var form = checkbox.form, z = 0;
 for(z=0; z<form.length;z++){
  if(form[z].type == 'checkbox' && form[z].name != 'checkall'){
  form[z].checked = checkbox.checked;
  }
 }
}

function toggle_checkboxes(classname) {
 var checkboxes = document.getElementsByClassName(classname), z= 0;
 if (checkboxes[0].checked == true)
 {    
 for(z=0; z<checkboxes.length;z++){
  checkboxes[z].checked = false;}
 }
 else
 {
 for(z=0; z<checkboxes.length;z++){
  checkboxes[z].checked = true;}
 }
}
 
function toggle_category (x, CatID) {
  var el = document.getElementById('category_'+ CatID);
  if( el.className == 'collapsed')
  {
     el.className = 'expanded'
  }
  else
  {
     el.className = 'collapsed'
  }
}

 function toggle_class (ClassName) {
  var category_items = document.getElementsByClassName(ClassName);
  if(category_items.length > 0){
  if(category_items[0].style.display == 'none')
  {
	for(var i=0;i<category_items.length;i++){
     Element.show( category_items[i] );
     }
  }
  else
  {
	for(var i=0;i<category_items.length;i++){
     Element.hide( category_items[i] );
     }
  }
  }
}

function toggle_area (x, CatID) {
  if(x.className == 'open')
  {
    Element.show( 'toggle_area_'+ CatID );
    x.className = 'close'
  }
  else
  {
    Element.hide( 'toggle_area_'+ CatID );
    x.className = 'open'
  }
}

function ajax_form_complete() {
      Element.hide('spinner');
      Form.reset('ajax-form');
      Element.hide('quick-post');
}

function ajax_complete_with_ids(spinner, form_id, div_id) {
      Element.hide(spinner);
      Form.reset(form_id);
      Element.hide(div_id);
}

function ajax_complete_with_ids_no_hide(form_id, div_id) {
      Form.reset(form_id);
      Element.hide(div_id);
}

function ajax_reset_and_maintain_checkbox(form_id, div_id, checkbox_id) {
      var check_b = document.getElementById(checkbox_id);
	  var check_status = check_b.checked;
      Form.reset(form_id);
	  check_b.checked = check_status;
      Element.hide(div_id);
}

function ajax_reset_and_restore_budget(form_id, div_id, lbl_1, lbl_2, lbl_3, lbl_4, lbl_5) {
      budget_line_expense(lbl_1, lbl_2, lbl_3, lbl_4, lbl_5);
	  Form.reset(form_id);
      Element.hide(div_id);
}

function ajax_reset_and_unhide_fields(form_id, div_id, classname) {
      var hidden = document.getElementsByClassName(classname);
	  for(z=0; z<hidden.length;z++){
	  Element.show(hidden[z]) }
      Form.reset(form_id);
      Element.hide(div_id);
}

register_onload(function() {
  if ($('commentform')) {
	var _author = getCookie('author');
	var _url = getCookie('url');

    if(_author != null) { $('commentform').elements['comment[author]'].value = _author }
    if(_url != null) { $('commentform').elements['comment[url]'].value = _url }
    
    if ($('commentform').elements['comment[url]'].value != ''
        || $('commentform').elements['comment[email]'].value != '') {
      Element.show('guest_url'); Element.show('guest_email');
    }
  }
})
register_onload(function() { if ($('q')) {$('q').setAttribute('autocomplete', 'off');} })

///DOUBLE LIST FUNCTIONS////
function fnSelectAll(src,dst){
	var selSrc = document.getElementById(src);
	var selDst = document.getElementById(dst);
	for(var i=0;i<selSrc.options.length;i++){
		fnAddItem(selDst,selSrc.options[i]);
	}
}

function fnSelect(src,dst){
	var selSrc = document.getElementById(src);
	var selDst = document.getElementById(dst);
	for(var i=0;i<selSrc.options.length;i++){
		if(selSrc.options[i].selected)
			fnAddItem(selDst,selSrc.options[i]);
	}
}

function fnRemoveAll(src,dst){	
	var selDst = document.getElementById(dst);
	selDst.options.length = 0;
}

// Remove selected items from a list.
function fnRemove(src,dst)
{
    try
    {
        var selDst = document.getElementById(dst);
        var counter = 1;
	    
	    for(var i=0;i<selDst.options.length;i++)
	    {
            if (selDst.options[i].selected)
            {
                selDst.removeChild(selDst.options[i]);
                // sync the index with the options number.
                i = i-1;
            }
	    } 
	}
	catch(e)
	{
	    alert(e);
	}
}
function fnAddItem(list,item){
	if(!fnContainsItem(list,item)){
		list.options[list.length] = new Option(getObjInnerText(item),item.value);
	}
}
function fnContainsItem(list,item){
	for(var i=0;i<list.options.length;i++){
		if(list.options[i].value==item.value)
			return true;
	}
	return false;
}
function fnSelectOptions(dst,countriesID){
	var selDst = document.getElementById(dst);
	var inpCountries = document.getElementById(countriesID);
	inpCountries.value = "";
	var delim = "";
	for(var i=0;i<selDst.options.length;i++){
		selDst.options[i].selected = true;		
		inpCountries.value += delim + selDst.options[i].text;
		delim = ",";
	}
}

//////////////////////////////////////////////////////////////////////////////////////////////////
//			From Alex - special for IE-Firefox compatibility
//////////////////////////////////////////////////////////////////////////////////////////////////
// read innerText
function getObjInnerText(obj){
	if (window.navigator.appName.toLowerCase().indexOf("microsoft") > -1) {
		// IE;
		return obj.innerText;
	}
	else{
		if (window.navigator.appName.toLowerCase().indexOf("netscape") > -1)
		{
		// Firefox
		return obj.textContent; 
		}
		else
		alert("Error: This application does not support your browser.  Try again using IE or Firefox.");
	}
} 
// write innerText
function setObjInnerText(obj,txt,add){
	if (window.navigator.appName.toLowerCase().indexOf("microsoft") > -1) {
		// IE;
		(add)?(obj.innerText += txt):(obj.innerText = txt);
	}
	else{
		if (window.navigator.appName.toLowerCase().indexOf("netscape") > -1)
		{
		// Firefox
		(add)?(obj.textContent += txt):(obj.textContent = txt); 
		}
		else
		alert("Error: This application does not support your browser.  Try again using IE or Firefox.");
	}
}

// Selection - invoked on submit
function selIt(dst) {
	var pickList = document.getElementById(dst);
	var pickOptions = pickList.options;
	var pickOLength = pickOptions.length;
	for (var i = 0; i < pickOLength; i++) {
	  pickOptions[i].selected = true;
	}
	return true;
} 


//function toggle_budget_line_form(lbl_1, lbl_2, lbl_3, lbl_4, lbl_5){ 
//    var input = document.getElementById('budget_line_is_income');
//    var requested = document.getElementById('requested');
//    var allocated = document.getElementById('allocated');
//    var used = document.getElementById('used');
//    var used_input = document.getElementById('used_fields');
//    if (input.checked){
//         requested.innerHTML = lbl_1
//         allocated.innerHTML = lbl_2
//         used.innerHTML = ''
//         Element.hide(used_input)
//      	}
//  	else{
//         requested.innerHTML = lbl_3
//         allocated.innerHTML = lbl_4
//         used.innerHTML = lbl_5
//         Element.show(used_input)
//  	}
//}

function budget_line_expense(lbl_1, lbl_2, lbl_3, lbl_4, lbl_5){ 
    var input = document.getElementById('budget_line_is_income');
    var requested = document.getElementById('requested');
    var allocated = document.getElementById('allocated');
    var used = document.getElementById('used');
    var used_input = document.getElementById('used_fields');
     requested.innerHTML = lbl_3
     allocated.innerHTML = lbl_4
     used.innerHTML = lbl_5
     Element.show(used_input)
}

function budget_line_income(lbl_1, lbl_2, lbl_3, lbl_4, lbl_5){ 
    var input = document.getElementById('budget_line_is_income');
    var requested = document.getElementById('requested');
    var allocated = document.getElementById('allocated');
    var used = document.getElementById('used');
    var used_input = document.getElementById('used_fields');
     requested.innerHTML = lbl_1
     allocated.innerHTML = lbl_2
     used.innerHTML = ''
     Element.hide(used_input)
}

  function addInput() {
    var list = $('filefields'), copyFrom = list.down();
    var newNode = copyFrom.cloneNode(true), files = list.getElementsByTagName('li');
    var close = document.getElementsByClassName('remove-file', newNode)[0]; 
    //Element.remove(document.getElementsByClassName('tagsall', newNode)[0]);
    Event.observe(close, 'click', function(e) { 
      Event.findElement(e, 'li').remove(); 
      //if(tagsall.visible() && files.length == 1) tagsall.hide();
    });
    close.show();
    //if(!tagsall.visible() && files.length > 0) tagsall.show();
    list.appendChild(newNode);
  }
  
  function toggle_selection_checkboxes(classname, flag) {
 var checkboxes = document.getElementsByClassName(classname), z= 0;
 var allchecked = true;
 if (flag == true)
 {    
 for(z=0; z<checkboxes.length;z++){
  if (checkboxes[z].checked == false){
  	allchecked = false;}
  }
 }
 if ((flag == false) || (allchecked == true))
 {
 for(z=0; z<checkboxes.length;z++){
  checkboxes[z].checked = false;}}
  else {
  for(z=0; z<checkboxes.length;z++){
  checkboxes[z].checked = true;}
 }
}


function fnGetSelectedcontacts(chb_class,chb_class_text,toList){	
		try{	
			var target = document.getElementById(toList);
			var chb = document.getElementsByClassName(chb_class);
			var chb_labels = document.getElementsByClassName(chb_class_text)
				
			
			for(var i=0;i<chb.length;i++){
					if(chb[i].checked){
							fnAddItemFromCheckbox(target,chb[i], chb_labels[i].innerHTML);
					}
			}
		}
		catch(e){}
}

function fnAddItemFromCheckbox(list,item,itemtext){
	if(!fnContainsItem(list,item)){
		list.options[list.length] = new Option(itemtext,item.value);				
		}
}

function handleEnter (field, event) {
		var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
		if (keyCode == 13) {
			return false;
		} 
		else
		return true;
	}      

function fnRemovecontacts(dst)
{
    try
    {
        var selDst = document.getElementById(dst);
        var counter = 1;
	    
	    for(var i=0;i<selDst.options.length;i++)
	    {
            if (selDst.options[i].selected)
            {
                selDst.removeChild(selDst.options[i]);
                // sync the index with the options number.
                i = i-1;
            }
	    } 
	}
	catch(e)
	{
	    alert(e);
	}
}

function showSectionPicture(vThis)
{

vParent = vThis.parentNode;
vSibling = vParent.nextSibling;
while (vSibling.nodeType==3) { 
vSibling = vSibling.nextSibling;
};
if(vSibling.style.display == "none")
{

vSibling.style.display = "block";
} else {	
vSibling.style.display = "none";

}
return;
}

function mark_for_destroy(element) { 
  $(element).next('.should_destroy').value = 1 
  $(element).up('.section').hide(); 
}
