var active_nav_tab = 0;

function sb_activate_tab(tab) {
['sidebar_body_' + active_nav_tab].each(Element.hide);
Element.show("sidebar_body_" + tab);
$('sidebar').removeClassName('tab' + active_nav_tab + '_active');
$('sidebar_top_tab_'+active_nav_tab).removeClassName('active');
$('sidebar_top_tab_'+active_nav_tab+'_link').removeClassName('sidebar_top_tab_active');
$('sidebar_top_tab_'+active_nav_tab+'_link').addClassName('sidebar_top_tab');
$('sidebar').addClassName('tab' + tab + '_active');
Element.addClassName("sidebar_top_tab_" + tab, "active");
Element.addClassName("sidebar_top_tab_" + tab + "_link", "sidebar_top_tab_active");
active_nav_tab = tab; 
return false;
}

var ub_menu_open = false;
var ub_menu_dim = [0,0,0,0];

function init_ub_menu() {
if (ub_menu_dim[0] > 0) return false;

var rl = $('ub_right_links');
var rlos = Position.cumulativeOffset(rl);

var menu = $('ub_menu');
var menuos = Position.cumulativeOffset(menu);

var left  = menuos[0];
var right = menuos[0] + menu.getWidth();

var ubm_top = rlos[1];
var bottom = menuos[1] + menu.getHeight();

ub_menu_dim = [ubm_top,right,bottom,left];
}

function open_ub_menu() {
 document.getElementById('ub_menu').style.visibility = 'visible';
 document.getElementById('ub_menu').style.display = 'block';
 init_ub_menu();
 ub_menu_open = true;	
}

function close_unless_between_nickname_and_menu(e)	{
if (!ub_menu_open) return true;

cx = Event.pointerX(e);
cy = Event.pointerY(e);	

//[ubm_top,right,bottom,left] = ub_menu_dim;
if (cx <= (ub_menu_dim[3] + 1) || cx >= ub_menu_dim[1] || cy < ub_menu_dim[0] || cy > ub_menu_dim[2])
close_ub_menu();	
}

function close_ub_menu() { 
document.getElementById('ub_menu').style.visibility = 'hidden';
ub_menu_open = false; 	
}




// Play a sound
function playSound(surl) {
  document.getElementById("soundvibe").innerHTML=
    "<embed src='"+surl+"' hidden=true autostart=true loop=false>";
}

function submitonce(theform){
  //if IE 4+ or NS 6+
  if (document.all||document.getElementById){
  //screen thru every element in the form, and hunt down "submit" and "reset"
  for (i=0;i<theform.length;i++){
    var tempobj=theform.elements[i];
    if (tempobj.type == undefined) continue; 
    if(tempobj.type.toLowerCase()=="submit"||tempobj.type.toLowerCase()=="reset"||(tempobj.type.toLowerCase()=="button" && (tempobj.name=="submit" || tempobj.name=="submit_button")))
      //disable em
      tempobj.disabled=true;
    }
  }
}
// resize for message to field
function sz(t) {
if (t.scrollHeight <= 64)
  t.style.height = t.scrollHeight + 'px';
}

function shout_editor(shoutable_type, shoutable_id) {
    editor = new Ajax.InPlaceEditor('shout_text', '/shout/create', {okText:'Save', formClassName:"set_status", clickToEditText:'Click to post', rows: '3', cols: '20', maxLength: 512, refresh: 'true', emptyText: 'Add to the Grapevine!',callback: function(form, value) { return 'version=fulls&shout[shoutable_id]='+ shoutable_id + '&shout[shoutable_type]=' + shoutable_type + '&shout[text]=' + escape(value) }})
	}

var TabMenu = Class.create();
TabMenu.prototype = {
  initialize: function(element) {
    var options = Object.extend({
      starteffect: function(element) { 
         new Effect.SlideUp(element, {duration:0.2}); 
      },
      endeffect: function(element) { 
         new Effect.SlideDown(element, {duration:0.2}); 
      }
    }, arguments[1] || {});

    this.element  = $(element);
    this.tabs = this.element.getElementsByTagName('LI');
    for (i = 0; i < this.tabs.length; i++){
      if(this.tabs[i].firstChild.className == 'active'){
        this.active = i;
        this.hilite = i;
        hilite =  document.getElementById('tabmenu_'+(this.hilite+1));
        hilite.style.display = this.tabs[i].firstChild.style.display;
      }
    }
  
    this.eventMouseOver = this.change.bindAsEventListener(this);
    this.registerEvents();
  },
  destroy: function() {
    Event.stopObserving(this.element, "mouseover", this.eventMouseOver);
  },
  registerEvents: function() {
    Event.observe(this.element, "mouseover", this.eventMouseOver);
  },
  change: function(event) {
    var src = Event.element(event);
    if (src.tagName != 'LI')
      src = src.parentNode;
    if (src.tagName != 'LI')
    return false
    
    for (i = 0; i < this.tabs.length; i++){
      if (this.tabs[i].firstChild.className == 'hilite')
        this.tabs[i].firstChild.className = '';
      if(this.tabs[i] == src){
        tab = i;
        if (i != this.active)
          this.tabs[i].firstChild.className = 'hilite';
      }
    }
    
    if (this.hilite != tab) {
      selected = document.getElementById('tabmenu_'+(tab+1));
      hilite =  document.getElementById('tabmenu_'+(this.hilite+1));
      if (hilite != undefined)
	 new Effect.Fade(hilite, {duration:0.2});
      new Effect.Appear(selected, {delay: 0.2,duration:0.2});
      this.hilite=tab;
    }
    Event.stop(event);
  }
}

var RadioMenu = Class.create();
RadioMenu.prototype = {
  initialize: function(element) {
    var options = Object.extend({
      starteffect: function(element) { 
         new Effect.SlideUp(element, {duration:0.2}); 
      },
      endeffect: function(element) { 
         new Effect.SlideDown(element, {duration:0.2}); 
      }
    }, arguments[1] || {});

    this.element  = $(element);
    this.id = this.element.id;
    this.status = $(this.id + '_status');
    this.text = this.status.getElementsByTagName('SPAN')[0];
    this.image = this.status.getElementsByTagName('IMG')[0];
    this.tabs = this.element.getElementsByTagName('LI');
    this.texts = this.element.getElementsByTagName('SPAN');
    this.images = this.element.getElementsByTagName('IMG');
    this.buttons = this.element.getElementsByTagName('INPUT');
    for (i = 0; i < this.tabs.length; i++){
      if(this.buttons[i].checked == true) {
        this.active = i;
        this.tabs[i].className = 'active';
      }
    }
  
    this.eventMouseOver = this.over.bindAsEventListener(this);
    this.eventMouseOut = this.out.bindAsEventListener(this);
    this.eventClick = this.click.bindAsEventListener(this);
    this.registerEvents();
  },
  destroy: function() {
    Event.stopObserving(this.element, "mouseover", this.eventMouseOver);
    Event.stopObserving(this.element, "mouseout", this.eventMouseOut);
    Event.stopObserving(this.element, "click", this.eventClick);
  },
  registerEvents: function() {
    Event.observe(this.element, "mouseover", this.eventMouseOver);
    Event.observe(this.element, "mouseout", this.eventMouseOut);
    Event.observe(this.element, "click", this.eventClick);
  },
  over: function(event) {
    var src = Event.element(event);
    while (src.tagName != 'LI')
      src = src.parentNode;
    
    for (i = 0; i < this.tabs.length; i++){
      if (this.tabs[i].className == 'hilite')
        this.tabs[i].className = '';
      if(this.tabs[i] == src){
        if (i != this.active)
          this.tabs[i].className = 'hilite';
      }
    }
    Event.stop(event);
  },
  out: function(event) {
    for (i = 0; i < this.tabs.length; i++){
      if (this.tabs[i].className == 'hilite')
        this.tabs[i].className = '';
    }
    Event.stop(event);
  },
  click: function(event) {
    var src = Event.element(event);
    while (src.tagName != 'LI')
      src = src.parentNode;
    
    for (i = 0; i < this.tabs.length; i++){
      if (this.tabs[i].className == 'active')
        this.tabs[i].className = '';
      if(this.tabs[i] == src){
        if (i != this.active){
          this.tabs[i].className = 'active';
          this.buttons[i].checked = true;
          this.active = i;
          this.text.innerHTML = this.texts[i].innerHTML;
          this.image.src = this.images[i].src;
        }
      }
    }
    Event.stop(event);
  }
}

//maps stuff
function getAdjustedMapBounds(map, mapContainer) {
  var adjBounds = {};
  var topDead = 25;
  var leftDead = 10;
  var rightDead = 5;
  var bounds = map.getBounds();
  var lonPerPix = (bounds.getNorthEast().lng() - bounds.getSouthWest().lng())/mapContainer.clientWidth;
  var latPerPix = (bounds.getNorthEast().lat() - bounds.getSouthWest().lat())/mapContainer.clientHeight;
  
  adjBounds['minlon'] = bounds.getSouthWest().lng() + leftDead*lonPerPix;
  adjBounds['maxlon'] = bounds.getNorthEast().lng() - rightDead*lonPerPix;
  adjBounds['minlat'] = bounds.getSouthWest().lat();
  adjBounds['maxlat'] = bounds.getNorthEast().lat() - topDead*latPerPix;
  return adjBounds;
}
function makeCopyrightSmaller() {
  if (map.isLoaded()) 
  {
    for(var i = 0; i < map.getContainer().childNodes.length; ++i) {
      if(map.getContainer().childNodes[i].innerHTML.indexOf(String.fromCharCode(169)) !== -1){
            map.getContainer().childNodes[i].style.fontSize = '9px';
            window.clearInterval(copyrightTimer);
            break;
        }
      }
    }
}

// custom radio/checkboxes
var safari = (navigator.userAgent.toLowerCase().indexOf('safari') != -1) ? true : false;
var gebtn = function(parEl,child) { return parEl.getElementsByTagName(child); };
// setboxes = function(parent) {
//     var ls = gebtn(parent,'label');
//     for (var i = 0; i < ls.length; i++) {
//         var l = ls[i];
//         if (l.className.indexOf('label_') == -1) continue;
//         var inp = gebtn(l,'input')[0];
//         if (l.className == 'label_check') {
//             l.className = (safari && inp.checked == true || inp.checked) ? 'label_check c_on' : 'label_check c_off';
//             l.onclick = check_it;
//             if (l.parentNode.parentNode.tagName == 'TR')
//             l.parentNode.parentNode.className = (safari && inp.checked == true || inp.checked) ? 'selected' : '';
//         };
//         if (l.className == 'label_radio') {
//             l.className = (safari && inp.checked == true || inp.checked) ? 'label_radio r_on' : 'label_radio r_off';
//             l.onclick = turn_radio;
//         };
//     };
// };
var check_it = function() {
    var inp = gebtn(this,'input')[0];
    if (this.className == 'label_check c_off' || (!safari && inp.checked)) {
        this.className = 'label_check c_on';
        if (safari) inp.checked = true;
        if (this.parentNode.parentNode.tagName == 'TR')
          this.parentNode.parentNode.className = 'selected'
    } else {
        this.className = 'label_check c_off';
        if (safari) inp.checked = false;
        if (this.parentNode.parentNode.tagName == 'TR')
          this.parentNode.parentNode.className = ''
    };
};
var turn_radio = function() {
    var inp = gebtn(this,'input')[0];
    if (this.className == 'label_radio r_off' || inp.checked) {
        var ls = gebtn(this.parentNode,'label');
        for (var i = 0; i < ls.length; i++) {
            var l = ls[i];
            if (l.className.indexOf('label_radio') == -1)  continue;
            l.className = 'label_radio r_off';
        };
        this.className = 'label_radio r_on';
        if (safari) inp.checked = true;
    } else {
        this.className = 'label_radio r_off';
        if (safari) inp.checked = false;
    };
};
function checkAll()
{
  for (var i = 0; i < document.forms.activeform.elements.length; i++)
    if (document.forms.activeform.elements[i].type == 'checkbox') {
      if (!document.forms.activeform.elements[i].disabled) {
        document.forms.activeform.elements[i].checked = !(document.forms.activeform.elements[i].checked);
        // document.forms.activeform.elements[i].parentNode.onclick();
      }
    }
}

function checkUncheckSome(controller,theElements) {
	//Programmed by Shawn Olson
	//Copyright (c) 2006-2007
	//Updated on August 12, 2007
	//Permission to use this function provided that it always includes this credit text
	//  http://www.shawnolson.net

	//Find more JavaScripts at http://www.shawnolson.net/topics/Javascript/

	//theElements is an array of objects designated as a comma separated list of their IDs
	//If an element in theElements is not a checkbox, then it is assumed
	//that the function is recursive for that object and will check/uncheck
	//all checkboxes contained in that element

  var formElements = theElements.split(',');
	var theController = document.getElementById(controller);
	for(var z=0; z<formElements.length;z++){
	  theItem = document.getElementById(formElements[z]);
	  if(theItem.type){
	    if (theItem.type=='checkbox') {
	    	theItem.checked=theController.checked;
	    }
	  } else {
	  	theInputs = theItem.getElementsByTagName('input');
	  	for(var y=0; y<theInputs.length; y++){
	  		if(theInputs[y].type == 'checkbox' && theInputs[y].id != theController.id){
	    		theInputs[y].checked = theController.checked;
	    	}
	  	}
	  }
  }

}

// grid button actions
function doAction(act) {
  document.activeform.command.value = act; 
  document.activeform.submit();
};

function confirmAction(act,msg) {
  if (confirm(msg)) { doAction(act) };
};

// Progress Bar
function progressPercent(bar, percentage) {
  document.getElementById(bar).style.width =  parseInt(percentage*2)+"px";
  document.getElementById(bar).innerHTML= "<div align='center'>"+percentage+"%</div>"
};


// Accordian Effect
// Copyright (c) 2006-2007 Aaron Eisenberger (http://zaadz.com)
// Adapted from 2006 Bruce Williams (http://codefluency.com)
Effect.Accordian =  function(element) {
  element = $(element);
  var options = Object.extend({
    headingClass: 'heading',
    sectionClass: 'section',
    showSection: 1,
    duration: 0.5
  }, arguments[1] || {});
  element.headings = element.select("." + options.headingClass);//document.getElementsByClassName(options.headingClass,element)
  element.sections = element.select("." + options.sectionClass);//document.getElementsByClassName(options.sectionClass,element)
  function showSection(section) {
    if(section.visible()) return false;
    element.sections.each(function(e){
      if(e == section) {
        e.visualEffect('appear', {duration:options.duration});
        e.visualEffect('blind_down', {duration:options.duration});  
      } else {
        e.visualEffect('fade', {duration:options.duration});
        e.visualEffect('blind_up', {duration:options.duration});
      }
    })
  }
  element.headings.each(function(e,index){
    e.style.cursor = 'pointer';
    e.onclick = function(){ 
      element.headings.each(function(h){ h.removeClassName('active'); })
      this.addClassName('active');
      showSection(element.sections[index]); 
    };
  });
  element.sections.each(function(s,ind){ 
    if(!options.showSection || (ind + 1 != options.showSection))
      s.hide(); 
    else
      s.show();
  });
  if(options.showSection) {
    element.headings[options.showSection - 1].addClassName('active');
  }
}



Ajax.DropSelect = Class.create();
Object.extend(Object.extend(Ajax.DropSelect.prototype, Autocompleter.Base.prototype), {
  initialize: function(element, url, options) {
    this.button = "<div id=\"" + $(element).id + "_button\" class=\"dropselect-button\">&nbsp;</div>"
    new Insertion.After(element, this.button)
    this.button = $(element).id + "_button";
    this.update = "<div id=\"" + $(element).id + "_options\" class=\"autocomplete\"></div>" 
    new Insertion.After(element, this.update)
    this.baseInitialize(element, $(element).id + "_options", options);
    this.options.asynchronous  = true;
    this.options.onComplete    = this.onComplete.bind(this);
    this.options.defaultParams = this.options.parameters || null;
    this.url                   = url;
    Event.observe($(element).id + "_button", "click", this.doClick.bindAsEventListener(this));
    Event.observe($(element).id + "_button", "mouseover", this.doHover.bindAsEventListener(this));
    Event.observe($(element).id + "_button", "mouseout", this.doOut.bindAsEventListener(this));
  },
  
  hide: function() {
    this.stopIndicator();
    if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
    if(this.iefix) Element.hide(this.iefix);
    Element.removeClassName(this.button,"dropselect-button-over");
    this.open = false;
  },
  
  doClick: function() {
    if (this.open) {
      this.hide();
    } else {
      this.open = true;
      this.activate();
    }
  },
  
  doHover: function() {
    Element.addClassName(this.button,"dropselect-button-over")
  },
  
  doOut: function() {
    if (!this.open)
      Element.removeClassName(this.button,"dropselect-button-over");
  },

  getUpdatedChoices: function() {
    if (!this.loaded) {
      entry = encodeURIComponent(this.getToken());

      this.options.parameters = this.options.callback ?
        this.options.callback(this.element, entry) : entry;

      if(this.options.defaultParams) 
        this.options.parameters += '&' + this.options.defaultParams;

      new Ajax.Request(this.url, this.options);
    } else {
      this.render();
    }
  },
  
  updateChoices: function(choices) {
    if(!this.changed && this.hasFocus) {
      this.update.innerHTML = choices;
      this.entries = $$("option", this.update)
      this.entryCount = this.entries.length
      for (var i = 0; i < this.entryCount; i++) {
        var entry = this.getEntry(i);
        entry.autocompleteIndex = i;
        this.addObservers(entry);
      }
      
      this.stopIndicator();
      this.index = 0;
      
      if(this.entryCount==1 && this.options.autoSelect) {
        this.selectEntry();
        this.hide();
      } else {
        this.render();
      }
      
    }
  },
  
  getEntry: function(index) {
    return this.entries[index];
  },
  
  onBlur: function(event) {
    return;
  },
  
  onKeyPress: function(event) {
    return;
  },

  onComplete: function(request) {
    this.updateChoices(request.responseText);
    this.loaded = true;
  }

});

 //  http://nullstyle.com/2007/06/02/caching-time_ago_in_words/ see application_helper.rb
 function time_ago_in_words(from, about) {
   return distance_of_time_in_words(new Date().getTime(), from, about) 
  }

  function distance_of_time_in_words(to, from, about) {
    seconds_ago = ((to  - from) / 1000);
    minutes_ago = Math.floor(seconds_ago / 60)

    if(minutes_ago == 0) { return "less than a minute";}
    if(minutes_ago == 1) { return "a minute";}
    if(minutes_ago < 45) { return minutes_ago + " minutes";}
    if(minutes_ago < 90) { return about ? "about 1 hour" : "1 hour";}
    hours_ago  = Math.round(minutes_ago / 60);
    if(minutes_ago < 1440) { return ( about ? "about " : "") + hours_ago + " hours";}
    if(minutes_ago < 2880) { return "1 day";}
    days_ago  = Math.round(minutes_ago / 1440);
    if(minutes_ago < 43200) { return days_ago + " days";}
    if(minutes_ago < 86400) { return (about ? "about " : "") + "1 month";}
    months_ago  = Math.round(minutes_ago / 43200);
    if(minutes_ago < 525960) { return months_ago + " months";}
    if(minutes_ago < 1051920) { return (about ? "about " : "")  + "1 year";}
    years_ago  = Math.round(minutes_ago / 525960);
    return "over " + years_ago + " years" 
  }
  
  /*

  Project:	Input Placeholder Text
  Title:		Automatic population of form fields with contents of title attributes
  Created:	13 August 2005 by Jon Gibbins (aka dotjay)
  Modified:	13 November 2006 by Jon Gibbins (aka dotjay)


  Potential additions:

  Add in handling of default text if an initial value is detected (line 60, line 93, etc) using something like:
  if (!el.defaultValue) continue;
  el.onfocus = function() {
  	if (this.value == this.defaultValue) this.value = "";
  }
  el.onblur = function() {
  	if (this.value == "") this.value = this.defaultValue;
  }

  Notes:

  Add the following classes to text inputs or textareas to get the desired behaviour:

  auto-select
  	Will pre-populate the input with the title attribute and select the text when it receives focus.

  auto-clear
  	Will pre-populate the input with the title attribute and clear the text when it receives focus.
  	Note: if auto-select and auto-clear are set, auto-select takes precedence.

  populate
  	Will just populate the input with the title attribute.

  */

  window.onload = function () {

  	if (!document.getElementsByTagName) return true;

  	ourForms = document.getElementsByTagName('form');

  	// go through each form
  	var numForms = ourForms.length;
  	for (var i=0;i<numForms;i++) {

  		// go through each form element
  		var numFormElements = ourForms[i].elements.length;
  		for (var j=0;j<numFormElements;j++) {

  			var el = ourForms[i].elements[j];

  			// ignore submit buttons
  			if (el.type == "submit") continue;

  			// if we got a text type input
  			if (el.type == "text" || el.type == "password") {
  				// only populate if we want it to
  				// note: might want title attribute but no pre-population of inputs
  				var ourClassName = el.className;
  				if (ourClassName.match('auto-select') || ourClassName.match('auto-clear') || ourClassName.match('populate')) {
  					// only populate if empty
  					if (el.value == '') el.value = el.title;
  				}

  				// add auto select if class contains auto-select
  				// note: else if below so auto-select takes precedence (assuming select is better than clear)
  				if (el.className.match('auto-select')) {
  					el.onfocus = function () {
  						if (this.value == this.title) this.select();
  					}
  					if (el.captureEvents) el.captureEvents(Event.FOCUS);
  				}

  				// add auto clear if class contains auto-clear
  				else if (el.className.match('auto-clear')) {
  					el.onfocus = function () {
  						if (this.value == this.title) this.value = '';
  					}
  					if (el.captureEvents) el.captureEvents(Event.FOCUS);

  					el.onblur = function () {
  						if (this.value == '') this.value = this.title;
  					}
  					if (el.captureEvents) el.captureEvents(Event.BLUR);
  				}
  			}

  			// if we got a textarea
  			if (el.type == "textarea") {
  				// only populate if we want it to
  				// note: might want title attribute but no pre-population of inputs
  				var ourClassName = el.className;
  				if (ourClassName.match('auto-select') || ourClassName.match('auto-clear') || ourClassName.match('populate')) {
  					// only populate if empty
  					if (el.value == '') el.value = el.title;
  				}

  				// add auto select if class contains auto-select
  				if (el.className.match('auto-select')) {
  					el.onfocus = function () {
  						if (this.value == this.title) this.select();
  					}
  					if (el.captureEvents) el.captureEvents(Event.FOCUS);
  				}

  				// add auto clear if class contains auto-clear
  				else if (el.className.match('auto-clear')) {
  					el.onfocus = function () {
  						if (this.value == this.title) this.value = '';
  					}
  					if (el.captureEvents) el.captureEvents(Event.FOCUS);

  					el.onblur = function () {
  						if (this.value == '') this.value = this.title;
  					}
  					if (el.captureEvents) el.captureEvents(Event.BLUR);
  				}
  			}

  		}

  	}

  }

var Apps = {};
Apps.Gaia = {
  version: '0.1',
  submitOnce: function(formClass) {
    $$('form.' + formClass).invoke("observe", "submit", function(event) {
      var el = Event.element(event);
      el.getElementsBySelector('input[type="submit"]', 'input[type="reset"]').invoke("disable");
    });
  },
  
  Swapper: {
    swap: function(element, alternate) { 
      Element.toggle(element); Element.toggle(alternate); 
    },

    swapify: function(element) {
  		this.swapHelper = Class.create();
  		this.swapHelper.prototype = {
  			initialize: function(element) {
  			  this.el = $(element);
  		    this.mainEvent = $(this.el.id + "_hidden");
  		    
		    this.alternateEvent = $(this.el.id + "_shown");
  		    this.swapLink = $(this.el.id + "_link");
  		    this.showText = this.swapLink.innerHTML;
  		    this.hideText = this.swapLink.readAttribute('alt_text');

          Event.observe(this.swapLink.id, "click", this.toggle.bindAsEventListener(this));
  		    this.shown = false;
  			},

  			toggle: function(event) {
  		    if (this.shown) {
  		      this.vanish();
  		    } else {
  		      this.reveal();
  		    }
  		    Event.stop(event);
  		  },

  		  reveal: function() {
  		    this.swapLink.innerHTML = this.hideText;
  		    this.mainEvent.show();
		    if (this.alternateEvent) this.alternateEvent.hide();	
  		    this.shown = true;
  		  },

  		  vanish: function() {
  		    this.swapLink.innerHTML = this.showText;
  		    this.mainEvent.hide();
		    if (this.alternateEvent) this.alternateEvent.show();	
  		    this.shown = false;
  		  }
  		};
  		return new swapHelper(element);
    }

  }
  
};
  
Element.addMethods(Apps.Gaia.Swapper);
Apps.Gaia.submitOnce('submitonce');

//http://webdesign.torn.be/tutorials/javascript/prototype/auto-expand-contract-textarea/js/autoExpandContract.js

/*
document.observe("dom:loaded", function() {

	// we get all elements with a class set to 'expand'.
	var elements = $$('.expand');
	// size() uses the array's native length property
	// if the array has more than 0 items, we do the loop
	if (elements.size() > 0) {
	    for (var index = 0, length = elements.size(); index < length; ++index){
		autoExpandContract(elements[index]);
	    }
	}
	
})
*/

	function getStyleFromCSS(el, style) {
	    
	    var value = $(el).getStyle(style);
	    
	    if(!value) {
		
		if(document.defaultView) {
		    value = document.defaultView.getComputedStyle(el, null).getPropertyValue(style);
		    
		    // for IE
		} else if(el.currentStyle) {
		    value = el.currentStyle[style];
		    if (value.substring(value.length-2,value.length) == "px") {
			alert('style' + style);
			value = value+'px';
		    }
		}
	    }
	    
	    if(value.length > 0){
		
		if (value.charAt(value.length-1) == "x") {
		    
		    value = parseInt(value.substring(0,value.length-2)) 
			} 
	    }
	    return value;
	    
	} // end getStyleFromCSS()

	function autoExpandContract(el) {

	    var __heightFromElement = el.offsetHeight;
	    
	    var __heightFromCSS = parseInt(getStyleFromCSS(el, 'height'));
	    
	    if (__heightFromCSS > 0) {
		__heightFromElement = __heightFromCSS;
	    }

	    $(el).setStyle({overflow: 'hidden', overflowX: 'auto'});
	    
	    el.style.width = getStyleFromCSS(el, 'width')+'px';
	    el.style.height = getStyleFromCSS(el, 'height')+'px';


	    var dummy_id = Math.floor(Math.random()*99999) + '_dummy';
	    var div = document.createElement('div');
	    
	    // we use setAttribute(attr, value) here instead of writeAttribute which is a prototype method (IE6 = fail)
	    div.setAttribute('id',dummy_id);
	    document.body.appendChild(div);
	    var dummy = $(dummy_id);
	    
	    dummy.style.fontFamily = getStyleFromCSS(el, 'font-family');
	    dummy.style.fontWeight = getStyleFromCSS(el, 'font-weight');
	    dummy.style.fontSize = getStyleFromCSS(el, 'font-size')+'px';
	    // fornicate with IE (not a check for IE7 though, just IE6)
	    if (navigator.userAgent.indexOf('MSIE') !=-1) {
		dummy.style.width = getStyleFromCSS(el, 'width');
            
		// Play  nice with the good browsers
	    } else {
		dummy.style.width = getStyleFromCSS(el, 'width')+'px';
	    }
	    dummy.style.padding = getStyleFromCSS(el, 'padding');
	    dummy.style.margin = getStyleFromCSS(el, 'margin');
	    dummy.style.overflowX = 'auto';
	    // hide the created div away
	    dummy.style.position = 'absolute';
	    dummy.style.top = '0px';
	    dummy.style.left = '-9999px';
	    dummy.innerHTML = '&nbsp;42';
	    
	    var __lineHeight = dummy.offsetHeight;
	    
	    var checkExpandContract = function(){
		// place text inside the element in a new var called html
		var html = el.value;
		html = html.replace(/\n/g, '<br />');
		if (dummy.innerHTML != html) {
		    dummy.innerHTML = html;
		    var __dummyHeight = dummy.offsetHeight;
		    var __elHeight = el.offsetHeight;
		    
		    if (__elHeight != __dummyHeight) {
			
			if (__dummyHeight > __heightFromElement) {
			    
			    el.style.height = (__dummyHeight+__lineHeight) + 'px';

			} else {
			    el.style.height = __heightFromElement+'px';

			}
		    }
		}
	    }
	    
	    var expandElement = function(){
		interval = window.setInterval(function() {checkExpandContract()}, 250);
	    }
	    
	    var contractElement = function() {
		clearInterval(interval);
	    }
	    
	    // Put eventListeners to our elements 
	    $(el).observe('focus', expandElement);
	    $(el).observe('blur', contractElement);
	    checkExpandContract();
	} // end autoExpandContract()

//http://www.dynamicdrive.com/dynamicindex16/maxlength.htm
function ismaxlength(obj){
    var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
	if (obj.getAttribute && obj.value.length>mlength)
	    obj.value=obj.value.substring(0,mlength)
}		
