
function showSuccess( e ) {
  $(e.id+'-success').show();
  $(e.id+'-failure').hide();  
}
function showFailure( e, msg ) {
  $(e.id+'-success').hide();
  $(e.id+'-failure').show();  
  $(e.id+'-failure-text').innerHTML = msg;
}


function validateLength( e, len, msg ) {
  if( msg == null )
    msg = "must be at least "+len+" chars";    
  if (e.value.length >= len) {
    showSuccess( e );
  } else {
    showFailure( e, msg )
  }
}

function validateMatchesField( e, match_e, msg ) {
  if( msg == null )
    msg = "does not match";
  if (e.value == $F( match_e ) ) {
    showSuccess( e );
  } else {
    showFailure( e, msg )
  }
}

function assertImageFile( str ) {
    ext = str.substring( str.length-3, str.length );
    ext = ext.toLowerCase();
    //  console.debug( ext );
    if(ext == '') {
        alert('Please select a file to upload!')
        return false;
    }
    else if (!ext.match(/jpg|png|gif|peg/)) {
        alert('Please select a JPEG, PNG, or GIF file!');
        return false;
    } else {
        $('uploading').show();
        $('update_profile_submit').click();
        return true;  
    }
}

function enableIfPresent( id, req_ids ) {  
    elm = $( id );
    req_ids.each( function(e) {
        if( !$(e).present() ) {
          elm.disabled = true;
          throw $break;
        } else {
            elm.disabled = false;
        }
    });

}

function setFocus() {
    var inputs = $$("input");
    inputs[0].focus();
}

function saveField( input ) {
    var action = input.form.action;
    new Ajax.Request(action, {asynchronous:true, evalScripts:true, parameters:input.name + '=' + Form.Element.getValue(input) });
}

function toggle_checkboxes( id ) {
    $$('#'+id+' input[type=checkbox]').each( function(e) { e.checked = !e.checked } );
}


Event.observe( window, 'load', function() {
    $$('form.no-enter').each( function( form ) {
        form.getInputs().each( function (e) {
            if(e.type != 'submit' && e.type != 'button')    e.setAttribute('onkeypress', 'return disableEnterKey(event)');
        })
    });  
});

function disableEnterKey( e )
{   
    var key;
    if(window.event)
        key = window.event.keyCode;     //IE
    else {
        key = e.which;     //firefox
    }
    if(key == 13)
        return false;
    else
        return true;
}

function fade_and_remove( elm ) {
    new Effect.Fade( elm, { afterFinish: function() { Element.remove(elm) } } );
}



// slight autocomplete modifications (search for INTERNAUT)


var Autocompleter = { }
Autocompleter.Base = Class.create({
  baseInitialize: function(element, update, options) {
    element          = $(element)
    this.element     = element; 
    this.update      = $(update);  
    this.hasFocus    = false; 
    this.changed     = false; 
    this.active      = false; 
    this.index       = 0;     
    this.entryCount  = 0;
    this.oldElementValue = this.element.value;

    if(this.setOptions)
      this.setOptions(options);
    else
      this.options = options || { };

    this.options.paramName    = this.options.paramName || this.element.name;
    this.options.tokens       = this.options.tokens || [];
        // INTERNAUT ::  make autocomplete appear faster
        //    this.options.frequency    = this.options.frequency || 0.4;
    this.options.frequency    = this.options.frequency || 0.2;
    this.options.minChars     = this.options.minChars || 1;
    this.options.onShow       = this.options.onShow || 
      function(element, update){ 
        if(!update.style.position || update.style.position=='absolute') {
          update.style.position = 'absolute';
          Position.clone(element, update, {
            setHeight: false, 
            offsetTop: element.offsetHeight
          });
        }
                // INTERNAUT :: remove the effect to speed things up
                //          Effect.Appear(update,{duration:0.15});
                update.show();
      };
    this.options.onHide = this.options.onHide || 
      function(element, update){ new Effect.Fade(update,{duration:0.15}) };

    if(typeof(this.options.tokens) == 'string') 
      this.options.tokens = new Array(this.options.tokens);
    // Force carriage returns as token delimiters anyway
    if (!this.options.tokens.include('\n'))
      this.options.tokens.push('\n');

    this.observer = null;
    
    this.element.setAttribute('autocomplete','off');

    Element.hide(this.update);

    Event.observe(this.element, 'blur', this.onBlur.bindAsEventListener(this));
    Event.observe(this.element, 'keypress', this.onKeyPress.bindAsEventListener(this));
  },

  show: function() {
    if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
    if(!this.iefix && 
      (Prototype.Browser.IE) &&
      (Element.getStyle(this.update, 'position')=='absolute')) {
      new Insertion.After(this.update, 
       '<iframe id="' + this.update.id + '_iefix" '+
       'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
       'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
      this.iefix = $(this.update.id+'_iefix');
    }
    if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50);
  },
  
  fixIEOverlapping: function() {
    Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)});
    this.iefix.style.zIndex = 1;
    this.update.style.zIndex = 2;
    Element.show(this.iefix);
  },

  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);
  },

  startIndicator: function() {
    if(this.options.indicator) Element.show(this.options.indicator);
  },

  stopIndicator: function() {
    if(this.options.indicator) Element.hide(this.options.indicator);
  },

  onKeyPress: function(event) {
    if(this.active)
      switch(event.keyCode) {
       case Event.KEY_TAB:
       case Event.KEY_RETURN:
         this.selectEntry();
         Event.stop(event);
       case Event.KEY_ESC:
         this.hide();
         this.active = false;
         Event.stop(event);
         return;
       case Event.KEY_LEFT:
       case Event.KEY_RIGHT:
         return;
       case Event.KEY_UP:
         this.markPrevious();
         this.render();
         if(Prototype.Browser.WebKit) Event.stop(event);
         return;
       case Event.KEY_DOWN:
         this.markNext();
         this.render();
         if(Prototype.Browser.WebKit) Event.stop(event);
         return;
      }
     else 
       if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN || 
         (Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return;

    this.changed = true;
    this.hasFocus = true;

    if(this.observer) clearTimeout(this.observer);
      this.observer = 
        setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
  },

  activate: function() {
    this.changed = false;
    this.hasFocus = true;
    this.getUpdatedChoices();
  },

  onHover: function(event) {
    var element = Event.findElement(event, 'LI');
    if(this.index != element.autocompleteIndex) 
    {
        this.index = element.autocompleteIndex;
        this.render();
    }
    Event.stop(event);
  },
  
  onClick: function(event) {
    var element = Event.findElement(event, 'LI');
    this.index = element.autocompleteIndex;
    this.selectEntry();
    this.hide();
  },
  
  onBlur: function(event) {
    // needed to make click events working
    setTimeout(this.hide.bind(this), 250);
    this.hasFocus = false;
    this.active = false;     
  }, 
  
  render: function() {
    if(this.entryCount > 0) {
      for (var i = 0; i < this.entryCount; i++)
        this.index==i ? 
          Element.addClassName(this.getEntry(i),"selected") : 
          Element.removeClassName(this.getEntry(i),"selected");
      if(this.hasFocus) { 
        this.show();
        this.active = true;
      }
    } else {
      this.active = false;
      this.hide();
    }
  },
  
  markPrevious: function() {
    if(this.index > 0) this.index--
      else this.index = this.entryCount-1;
    this.getEntry(this.index).scrollIntoView(true);
  },
  
  markNext: function() {
    if(this.index < this.entryCount-1) this.index++
      else this.index = 0;
    this.getEntry(this.index).scrollIntoView(false);
  },
  
  getEntry: function(index) {
    return this.update.firstChild.childNodes[index];
  },
  
  getCurrentEntry: function() {
    return this.getEntry(this.index);
  },
  
  selectEntry: function() {
    this.active = false;
    this.updateElement(this.getCurrentEntry());
  },

  updateElement: function(selectedElement) {
    if (this.options.updateElement) {
      this.options.updateElement(selectedElement);
      return;
    }
    var value = '';
    if (this.options.select) {
      var nodes = $(selectedElement).select('.' + this.options.select) || [];
      if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
    } else
      value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
    
    var bounds = this.getTokenBounds();
    if (bounds[0] != -1) {
      var newValue = this.element.value.substr(0, bounds[0]);
      var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/);
      if (whitespace)
        newValue += whitespace[0];
      this.element.value = newValue + value + this.element.value.substr(bounds[1]);
    } else {
      this.element.value = value;
    }
    this.oldElementValue = this.element.value;
    this.element.focus();
    
    if (this.options.afterUpdateElement)
      this.options.afterUpdateElement(this.element, selectedElement);
  },

  updateChoices: function(choices) {
    if(!this.changed && this.hasFocus) {
      this.update.innerHTML = choices;
      Element.cleanWhitespace(this.update);
      Element.cleanWhitespace(this.update.down());

      if(this.update.firstChild && this.update.down().childNodes) {
        this.entryCount = 
          this.update.down().childNodes.length;
        for (var i = 0; i < this.entryCount; i++) {
          var entry = this.getEntry(i);
          entry.autocompleteIndex = i;
          this.addObservers(entry);
        }
      } else { 
        this.entryCount = 0;
      }

      this.stopIndicator();
      this.index = 0;
      
      if(this.entryCount==1 && this.options.autoSelect) {
        this.selectEntry();
        this.hide();
      } else {
        this.render();
      }
    }
  },

  addObservers: function(element) {
    Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this));
    Event.observe(element, "click", this.onClick.bindAsEventListener(this));
  },

  onObserverEvent: function() {
    this.changed = false;   
    this.tokenBounds = null;
    if(this.getToken().length>=this.options.minChars) {
      this.getUpdatedChoices();
    } else {
      this.active = false;
      this.hide();
    }
    this.oldElementValue = this.element.value;
  },

  getToken: function() {
    var bounds = this.getTokenBounds();
    return this.element.value.substring(bounds[0], bounds[1]).strip();
  },

  getTokenBounds: function() {
    if (null != this.tokenBounds) return this.tokenBounds;
    var value = this.element.value;
    if (value.strip().empty()) return [-1, 0];
    var diff = arguments.callee.getFirstDifferencePos(value, this.oldElementValue);
    var offset = (diff == this.oldElementValue.length ? 1 : 0);
    var prevTokenPos = -1, nextTokenPos = value.length;
    var tp;
    for (var index = 0, l = this.options.tokens.length; index < l; ++index) {
      tp = value.lastIndexOf(this.options.tokens[index], diff + offset - 1);
      if (tp > prevTokenPos) prevTokenPos = tp;
      tp = value.indexOf(this.options.tokens[index], diff + offset);
      if (-1 != tp && tp < nextTokenPos) nextTokenPos = tp;
    }
    return (this.tokenBounds = [prevTokenPos + 1, nextTokenPos]);
  }
});

Autocompleter.Base.prototype.getTokenBounds.getFirstDifferencePos = function(newS, oldS) {
  var boundary = Math.min(newS.length, oldS.length);
  for (var index = 0; index < boundary; ++index)
    if (newS[index] != oldS[index])
      return index;
  return boundary;
};

Ajax.Autocompleter = Class.create(Autocompleter.Base, {
  initialize: function(element, update, url, options) {
    this.baseInitialize(element, update, options);
    this.options.asynchronous  = true;
    this.options.onComplete    = this.onComplete.bind(this);
    this.options.defaultParams = this.options.parameters || null;
    this.url                   = url;
  },

  getUpdatedChoices: function() {
    this.startIndicator();
    
    var entry = encodeURIComponent(this.options.paramName) + '=' + 
      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);
  },

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

// TO MAKE THE DOCUMENT GET THE FOCUS WHEN LOADED
function requestDocumentFocus()
{
    var formList = document.forms;
    if( formList != 'undefined' && formList.length > 0 ) {
        var elementList = formList[ 0 ].elements;
        if( elementList != 'undefined' && elementList.length > 0 ) {
            elementList[ 0 ].focus();
        }
    }
}
var home_qi_current_link = null;
var home_qi_current_content = null;

function show_quickidea_content(link, targetName, url) {
    
    var target = document.getElementById(targetName);
    
    link.className = "active";
    target.className = "active_content";

    Element.update('idea_link', url)

    if (!home_qi_current_link) {
        home_qi_current_link = document.getElementById('qi_tab_recent');
    }
    
    if (!home_qi_current_content) {
        home_qi_current_content = document.getElementById('qi_recent')
    }

    if (home_qi_current_link) 
        home_qi_current_link.className = "inactive";
    if (home_qi_current_content)
        home_qi_current_content.className = "inactive_content";

    home_qi_current_link = link;
    home_qi_current_content = target;
}

var home_companies_current_link = null;
var home_companies_current_content = null;

function show_companies_content(link, targetName, url) {
    var target = document.getElementById(targetName);
    
    link.className = "active";
    target.className = "active_content";
    
    Element.update('companies_link', url) 
    
    if (!home_companies_current_link) {
        home_companies_current_link = document.getElementById('companies_tab_falling');
    }
    
    if (!home_companies_current_content) {
        home_companies_current_content = document.getElementById('companies_falling')
    }

    if (home_companies_current_link)
        home_companies_current_link.className = "inactive";
    if (home_companies_current_content)
        home_companies_current_content.className = "inactive_content";

    home_companies_current_link = link;
    home_companies_current_content = target;
}
