var Experteer = {};

Experteer.withCsrfToken = function(fun) {
  var csrfToken = $$('meta[name=csrf-token]').first().readAttribute('content');
  fun(csrfToken);
};

/**
 * Guess what?
 * I don't know; maybe a badly formatted function that might have been commented meaningfully but was used for an insane joke instead? - 09.09.2008 - mow
 */
function fadeOutAlert(id)
{
    if(document.getElementById(id)) {
  setTimeout("new Effect.Fade('" + id + "')", 5000);
    }
}

/**
 * JSON multi AJAX updater
 */
function update_divs(request)
{
    var divs = eval('(' + request.responseText + ')');
    for (var div_id in divs) {
  if ($(div_id)) {
      $(div_id).innerHTML = divs[div_id];
  }
    }
}

/**
 * copy input field from hidden template
 *
 * ::: OPTIMIZABLE TO 1 FUNCTION :::
 */
function add_input(name, name_pl)
{
  template = document.getElementById("new_"+name);
  copy = template.cloneNode(true);
  copy.style.display = "";
  
  // get first unused id
  id = 1;
  input_x = document.getElementById(name + "_" + id);
  while(input_x) {
    id++;
    input_x = document.getElementById(name + "_" + id);
  }
  copy.id = name + "_" + id;
  input = copy.getElementsByTagName("input")[0];
  input.id = name + "_" + input.name + "_" + id;
  input.name = name_pl + "[" + id + "][" + input.name + "]";
  template.parentNode.insertBefore(copy, template);
  return id;
}

function add_input_company(name, name_pl)
{
  template = document.getElementById("new_"+name);
  copy = template.cloneNode(true);
  copy.style.display = "";
  
  // get first unused id
  id = 1;
  input_x = document.getElementById(name + "_" + id);
  while(input_x) {
    id++;
    input_x = document.getElementById(name + "_" + id);
  }
  copy.id = name + "_" + id;
  input = copy.getElementsByTagName("input")[0];
  input.id = name + "_" + id + "_" + input.name;
  input.name = name_pl + "[" + id + "][" + input.name + "]";
  autocomplete = copy.getElementsByTagName("div")[0];
  autocomplete.id = input.id + "_auto_complete";
  template.parentNode.insertBefore(copy, template);
  new Ajax.Autocompleter('company_name_' + id + '_name', 'company_name_' + id + '_name_auto_complete', '/auto_complete/goal_company/desire', {callback:function(element, value) { return 'complete=' + $('company_name_' + id + '_name').value } });
  return id;
}

/**
 *
 */
function set_select(id, value)
{
  sel = $(id);
  for ( i=0; i < sel.options.length; i++ ) {
    if ( sel.options[i].value == value ) {
      sel.options[i].selected = true;
    }
  }
}

/**
 * slider2range
 *
 * calculate km range from slider position ( 25 .. 205 )
 * this function is repeated in ruby (search_value)
 */
function slider2range(n, unit, unlimited)
{
  if(!unit) {
    unit = 'km';
  }
  
  if(!unlimited) {
    unlimited = 'unbegrenzt';
  }
  
  if ( unit == 'km' ) {
    if ( n < 100 ) { n = ( Math.round( n / 5 ) * 5 ); return (n < 100 ? "&nbsp;" : "" ) + n.toString() + " km"; }
    if ( Math.round(n) <= 200 ) { return ( Math.round( ( 100 + 2 * (n-100) ) / 5 ) * 5 ).toString() + " km"; }
  }
  else {
    if ( n < 100 ) { n = ( Math.round( n / 5 ) * 5 ); return (n < 100 ? "&nbsp;" : "" ) + n.toString() + " mi"; }
  if ( Math.round(n) <= 200 ) { return ( Math.round( ( 100 + 2 * (n-100) ) / 5 ) * 5 ).toString() + " mi"; }
  }
  return unlimited;
}

/**
 *
 */
function days2date(days)
{
  days = Math.round(days);
  if ( days == 0 ) {
    return "heute";
  }
  date = new Date(new Date().getTime() - Math.round(days) * 24 * 3600 * 1000 );
  return "" + date.getDate() + "." + (date.getMonth()+1) + "." + date.getFullYear();
}

/**
 * ::: OPTIMIZABLE TO 1 FUNCTION :::
 */
function expSlider(n, labels)
{
  n = Math.round(n);
  if ( n >= 1 && n <= 4 ) {
    return labels[n];
  }
  else {
    return "--";
  }
}

function languageSkillSlider(n, labels)
{
  n = Math.round(n);
  if ( n >= 2 && n <= 4 ) {
    return labels[n];
  }
  return ''
}

/**
 * Toggle to skip the value of the input field
 */
function valFieldToggle(r, b, v)
{
  if (b) {
    if (r.value == v) {
      r.style.color="#525B65";
      r.value = "";
    }
  }
  else {
    if (r.value == "") {
      r.style.color="#8796AB";
      r.value = v;
    }
  }
}

/**
 * Display toggler
 *
 * ::: OPTIMIZABLE TO 1 FUNCTION :::
 */
function toggleDisplayExt(id, arr, partner_sufix, scrollto)
{
  elb = $(id);
  var display = elb.style.display ? '' : 'none';
  elb.style.display = display;
  
  els = $(id + '_collapse_sign');
  
  if (elb.style.display == 'none') {
    if (partner_sufix) {
      els.src = '/images/shorty/' + partner_sufix + '/icoTriClosed.gif';
    } else {
      els.src = '/images/icoTriClosed.gif';
    }
  } else {
    if (partner_sufix) {
      els.src = '/images/shorty/' + partner_sufix + '/icoTriOpen.gif';
    } else {
      els.src = '/images/icoTriOpen.gif';
    }
  }
  
  if (arr.length > 0) {
    for (i = 0; i < arr.length; i++) {
      if ($(arr[i]) != null) {
        $(arr[i]).style.display = 'none';
        if ($(arr[i] + '_collapse_sign') != null) {
          if (partner_sufix) {
            $(arr[i] + '_collapse_sign').src = '/images/shorty/' + partner_sufix + '/icoTriClosed.gif';
          } else {
            $(arr[i] + '_collapse_sign').src = '/images/icoTriClosed.gif';
          }
        }
      }
    }
  }
  
  if (scrollto) {
    var elbParent = Element.ancestors(elb)[0];
    Element.scrollTo( elbParent );
  }
}

function toggleDisplay(id, cid, partner_sufix)
{
  elo = $(id + 'Wrapper');
  var display = elo.style.display ? '' : 'none';
  elo.style.display = display;
  
  elf = $(id + 'CollapseFlag');
  els = $(id + 'CollapseSign');
  if (elf.value == '0' || elf.value == '') {
    elf.value = '1';
    if (partner_sufix) {
      els.src = '/images/shorty/' + partner_sufix + '/icoTriOpen.gif';
    } else {
      els.src = '/images/icoTriOpen.gif';
    }
  } else {
    elf.value = '0';
    if (partner_sufix) {
      els.src = '/images/shorty/' + partner_sufix + '/icoTriClosed.gif';
    } else {
      els.src = '/images/icoTriClosed.gif';
    }
  }
  
  if(cid) {
    elc = $(cid + 'Wrapper');
    elc.style.display = 'none';
    
    elf = $(cid + 'CollapseFlag');
    els = $(cid + 'CollapseSign');
    
    elf.value = '0';
    if (partner_sufix) {
      els.src = '/images/shorty/' + partner_sufix + '/icoTriClosed.gif';
    } else {
      els.src = '/images/icoTriClosed.gif';
    }
  }

  /*
  elo = $(id + 'Wrapper');
  var display = elo.style.display ? '' : 'none';
  if (display == "") {
    Effect.SlideDown(elo);
  } else {
    Effect.SlideUp(elo);
  }
  
  elf = $(id + 'CollapseFlag');
  els = $(id + 'CollapseSign');
  if (elf.value == '0' || elf.value == '') {
    elf.value = '1';
    els.src = '/images/icoTriOpen.gif';
  } else {
    elf.value = '0';
    els.src = '/images/icoTriClosed.gif';
  }
  
  if(cid) {
    elc = $(cid + 'Wrapper');
    var display = elc.style.display ? '' : 'none';
    
    if (display != "") {
      Effect.SlideUp(elc);
    
      elf = $(cid + 'CollapseFlag');
      els = $(cid + 'CollapseSign');
    
      elf.value = '0';
      els.src = '/images/icoTriClosed.gif';
    }
  }
  */
}

function cbToggleDisplay(id, cid, partner_image_path, teaser_toggle)
{
  
  elo = $(id + 'Wrapper');
  var display = elo.style.display ? '' : 'none';
  
  var tri_open = 'ico_tri_open';
  var tri_closed = 'ico_tri_closed';
  
  elo.style.display = display;
  
  elf = $(id + 'CollapseFlag');
  els = $(id + 'CollapseSign');
  
  if (elf.value == '0' || elf.value == '') {
    elf.value = '1';
    els.src = partner_image_path + tri_open + '.gif';
    
    if(teaser_toggle) {
      $('visual_teaser_container').style.display='none';
    }
  } else {
    elf.value = '0';
    els.src = partner_image_path + tri_closed + '.gif';
    
    if(teaser_toggle) {
      $('visual_teaser_container').style.display='';
    }
  }
  
  if(cid) {
    elc = $(cid + 'Wrapper');
    elc.style.display = 'none';
    
    elf = $(cid + 'CollapseFlag');
    els = $(cid + 'CollapseSign');
    
    elf.value = '0';
    els.src = partner_image_path + tri_closed + '.gif';
  }
}

function toggleHelpDisplay(id)
{
  elo = $(id);
  var display = elo.style.display ? '' : 'none';
  elo.style.display = display;
}

/**
 * show/hide toggle
 */
function action(_element, _action)
{
  var tbl = _element + "_tbl";
  var btn = _element + "_btn";
  
  var thisTable = document.getElementById(tbl);
  var thisButton = document.getElementById(btn);
  
  if (_action == "hide") { 
    thisTable.style.display = "none";
    thisButton.firstChild.nodeValue = "+";
    thisButton.setAttribute("href", "javascript:action('" + _element + "','show');");
  } else {
    thisTable.style.display = "block";
    thisButton.firstChild.nodeValue = "-";
    thisButton.setAttribute("href", "javascript:action('" + _element + "','hide');");
  }
}

/**
 * 24.03.2006 - mow
 *
 * toggle visibilty of element
 */
function toggleVisibility(element)
{
  current = $(element).style.display;
  if ( current == 'none' ) {
    $(element).style.display = '';
  }
  else {
    $(element).style.display = 'none';
  }
}

/**
 * used in recruiting/add_position
 */
function reset_and_toggle(field_name)
{
  if (field_name == 'industry') {
    if ($('job[industry_id]')) {
      $('job[industry_id]').value = '';
    }
    if ($('job_industry_id')) {
      $('job_industry_id').value = '';
    }
    $('selected_industry').style.display = 'none';
    $('job_industry').style.display = '';
  } else if (field_name == 'geocode') {
    if ($('job[geocode_id]')) {
      $('job[geocode_id]').value = '';
    }
    if ($('job_geocode_id')) {
      $('job_geocode_id').value = '';
    }
    $('selected_geocode').style.display = 'none';
    $('job_geocode').style.display = '';
  } else if (field_name == 'company') {
    if ($('job[company_id]')) {
      $('job[company_id]').value = '';
    }
    if ($('job[company_name]')) {
      $('job[company_name]').value = '';
    }
    $('selected_company').style.display = 'none';
    $('job_company').style.display = '';
  }
}

function wrap_selection(element, content)
{
  var element = $(element);
  var empty   = true
  
  if (content != '' && content != null) empty = false;

  if (!empty) {
    var div     = document.createElement('div');
    div.setAttribute('class', 'boxBodyWithBorder');
    div.setAttribute('id'   , element.id + '_wrapper');
    div.setAttribute('style', 'margin-bottom:0');
  
    if (element.parentNode.id != element.id + '_wrapper') {
      element.parentNode.replaceChild(div, element);
      div.appendChild(element);
    }
  }
  else if (element.parentNode.id == element.id + '_wrapper') {
    var parent = element.parentNode;
    parent.parentNode.replaceChild(element, parent);
  }
}

/**
 * show selection/remove of an entry in function/industry selections 
 * in search forms 
 */
function show_selection(sect, prefix, id, text)
{
  if ( $(prefix + '_' + id).checked ) {
    current =  $(sect).innerHTML;
    $(sect).innerHTML = current + (current=='' ? '' : '<span id="' + prefix + '_sep_' + id + '"> | </span>') + '<span id="' + prefix + '_sel_' + id + '">' + text + '</span>';
  } 
  else {
    parentx = $(sect);
    childx = $(prefix + '_sel_' + id);
    sep = $(prefix + '_sep_' + id);
    parentx.removeChild(childx);
    if (sep) {
      parentx.removeChild(sep);
    }
    else if ( parentx.firstChild ) {
      parentx.removeChild(parentx.firstChild);
    }
  }
  
  wrap_selection(sect, $(sect).innerHTML)
}

/**
 * alternative show selection introduced for added display of frequencies
 * here we copy the check box label instead of displaying a text provided 
 * in the call; thus the span for frequency display gets copied as well
 * 09.12.2008 - mow
 */
function show_selection_from_element(sect, prefix, id, ref_id)
{
  if ( $(prefix + '_' + id).checked ) {
    current =  $(sect).innerHTML;
    seperator = (current=='' ? '' : '<span id="' + prefix + '_sep_' + id + '"> | </span>')
    $(sect).innerHTML = current + seperator + '<span id="' + prefix + '_sel_' + id + '">' + $(ref_id).innerHTML + '</span>';
  } 
  else {
    parentx = $(sect);
    childx = $(prefix + '_sel_' + id);
    sep = $(prefix + '_sep_' + id);
    if ( childx ) {
      parentx.removeChild(childx);
    }
    if (sep) {
      parentx.removeChild(sep);
    }
    else if ( parentx.firstChild ) {
      parentx.removeChild(parentx.firstChild);
    }
  }
  
  wrap_selection(sect, $(sect).innerHTML)
}

function updateSearchSortValue(arg)
{
  el=document.getElementById('search_sort');
  el.value=arg;
  
  ajaxUpdater();
}
  
function remove_list_item(item_id, list_id)
{
  if ($(list_id).hasChildNodes) {
    $(list_id).removeChild($(item_id));
  }
}

function check_double_selected(item_id, list_id)
{
  var selected_items = $(list_id)
  var found = false;

  if (selected_items.hasChildNodes) {
    var children = selected_items.childNodes;
    for(var i=0; i < children.length; i++){
      if (children[i].id == item_id) {
        found = true;
      }
    }
  }
  return found;
}

/**
 * Get X and Y position of an element
 */
function findPosX(obj)
{
  var curleft = 0;
  if (obj.offsetParent) {
    while (obj.offsetParent) {
      curleft += obj.offsetLeft
      obj = obj.offsetParent;
    }
  }
  else if (obj.x)
    curleft += obj.x;
  return curleft;
}

function findPosY(obj)
{
  var curtop = 0;
  if (obj && obj.offsetParent) {
    while (obj.offsetParent) {
      curtop += obj.offsetTop
      obj = obj.offsetParent;
    }
  } else if ( obj && obj.y) {
    curtop += obj.y;
  }
  return curtop;
}

/**
 * Help functionality
 *
 * ::: OPTIMIZABLE TO 1 FUNCTION :::
 */
function posHelp(obj, top, content, txtmove, offset)
{
  var newContainerX = findPosX($(top)) + $(top).offsetWidth + 20;
  var newContainerY = findPosY($(top));
  
  var helpBox = $('helpBox');
  
  helpBox.style.top = newContainerY + 'px';
  helpBox.style.left = newContainerX + 'px';
  helpBox.style.height = $(top).offsetHeight + 'px';
  
  helpBox.style.height = $(top).offsetHeight + 'px';
  
  helpBox.style.display = 'block';
  
  var newThumbX = newContainerX - 9;
  var newThumbY = findPosY(obj);
  
  $('helpThumb').style.top = newThumbY + 'px';
  $('helpThumb').style.left = newThumbX + 'px';
  $('helpThumb').style.display = 'block';
  
  $('helpTxt').innerHTML = $(content).innerHTML;
  
  if (txtmove != null) {
    if (offset != null) {
      offset = 23 + offset;
    } else {
      offset = 23;
    }
    $('helpTxt').style.top = (newThumbY - newContainerY - offset) + 'px';
  } else {
    $('helpTxt').style.top = '6px';
  }
  
  $('helpTxt').style.display = 'block';
}

function posHelpShort(obj, top, content, txtmove, offset)
{
  var newContainerX = findPosX($(top));
  var newContainerY = findPosY(obj) + 20;
  
  var helpBox = $('helpBox');
  
  helpBox.style.top = newContainerY + 'px';
  helpBox.style.left = newContainerX + 'px';
  helpBox.style.width =  '492px';
  helpBox.style.zIndex =  '1000';
  helpBox.style.display = 'block';
  
  $('helpTxt').innerHTML = $(content).innerHTML;
  
  $('helpTxt').style.display = 'block';
}

function posHelpCatalogue(obj, top, content, txtmove, offset)
{
  var newContainerX = findPosX($(top)) + $(top).offsetWidth + 20;
  var newContainerY = findPosY($(top));
  
  var helpBox = $('helpBox');
  
  helpBox.style.top = newContainerY + 'px';
  helpBox.style.left = (newContainerX - 605) + 'px';
  helpBox.style.height = $(top).offsetHeight + 'px';
  helpBox.style.display = 'block';
  
  var newThumbX = newContainerX - 9;
  var newThumbY = findPosY(obj);
  
  $('helpThumb').style.top = newThumbY + 'px';
  $('helpThumb').style.left = (newThumbX-366) + 'px';
  $('helpThumb').style.display = 'block';
  
  $('helpTxt').innerHTML = $(content).innerHTML;
  
  if (txtmove != null) {
    if (offset != null) {
      offset = 23 + offset;
    } else {
      offset = 23;
    }
    $('helpTxt').style.top = (newThumbY - newContainerY - offset) + 'px';
  } else {
    $('helpTxt').style.top = '6px';
  }
  
  $('helpTxt').style.display = 'block';
}

function hideHelp()
{
  var helpBox = $('helpBox');
  
  helpBox.style.display = 'none';
  if ($('helpThumb')) {
    $('helpThumb').style.display = 'none';
  }
  $('helpTxt').style.display = 'none';
}

/**
 * Tooltip
 *
 * ::: OPTIMIZABLE TO 1 FUNCTION :::
 */
function displayTooltip(el1, el2, y, x, delay)
{
  if (!document.getElementById) return;
  
  var objX = findPosX(el1);
  var objY = findPosY(el1);
  
  var tt = $(el2);
  
  /*
  if (delay == null) {
    delay = 0;
  }
  else {
    delay = delay * 1000;
  }
  
  window.setTimeout(function() {
    if (tt) {
      tt.style.top = (objY-y) + 'px';
      tt.style.left = (objX+x) + 'px';
      tt.style.display = 'block';
    }
  }, delay);
  */
  
  if (tt) {
    tt.style.top = (objY-y) + 'px';
    tt.style.left = (objX+x) + 'px';
    tt.style.display = 'block';
  }
  
  return false;
}

/**
 * New Tooltip
 *
 * optimized class tooltip. all methods in one place.
 */
var tooltip = {
  /* for registering a timeout */
  activeTimeout: null,
  
  /**
   * Display the tooltip
   *
   * anchor:  Element for which the tooltip should be shown
   * tooltip: The tooltip bubble
   * offsety: Y offset for the tooltip
   * offsetx: X offset for the tooltip
   */
  display: function(anchor, tooltip, offsety, offsetx) {
    posx = this.getXCoord(anchor);
    posy = this.getYCoord(anchor);
    
    $(tooltip).style.top     = posy - offsety + 'px';
    $(tooltip).style.left    = posx + offsetx + 'px';
    
    Effect.Appear(tooltip);
  },
  
  /**
   * Hide the tooltip
   *
   * tooltip: Which tooltip should be hidden
   */
  hide: function (tooltip) {
    this.clearTooltipTimeout;
    
    Effect.Fade(tooltip);
  },
  
  /**
   * Display the tooltip with a pause
   *
   * Same as display tooltip except pause
   * pause: How long you have to stay before the tooltip is shown
   */
  timeout: function () {
    this.clearTooltipTimeout;
    
    if (arguments.length > 2) {
      var anchor  = arguments[0];
      var tooltip = arguments[1];
      var offsety = arguments[2];
      var offsetx = arguments[3];
      var pause   = arguments[4];
      
      this.activeTimeout = setTimeout(this.display.bind(this,
                                                        anchor,
                                                        tooltip,
                                                        offsety,
                                                        offsetx), pause);
    }
    else {
      var tooltip = arguments[0];
      var pause   = arguments[1];
      
      this.activeTimeout = setTimeout(this.hide.bind(this, tooltip), pause);
    }
  },
  
  clearTooltipTimeout: function() {
    if (this.activeTimeout != null) {
      clearTimeout(this.activeTimeout);
      this.activeTimeout = null;
    }
  },
  
  /**
   * Get the x coordinate for an element
   */
  getXCoord: function (elem) {
    var left = 0;
    
    if (elem.offsetParent) {
      while (elem.offsetParent) {
        left += elem.offsetLeft;
        elem = elem.offsetParent;
      }
    }
    else if (elem.x) { left += elem.x; }
    
    return left;
  },
  
  /**
   * Get the y coordinate for an element
   */
  getYCoord: function (elem) {
    var top = 0;
    
    if (elem.offsetParent) {
      while (elem.offsetParent) {
        top += elem.offsetTop;
        elem = elem.offsetParent;
      }
    }
    else if (elem.y) { top += elem.y; }
    
    return top;
  }
}

function displayTooltipShort(el1, el2, y, x, offset)
{
  if (!document.getElementById) return;
  
  var objX = findPosX(el1);
  var objY = findPosY(el1);
  
  if (navigator.appName=="Microsoft Internet Explorer" && offset) {
    objX -= 263;
  }
  
  var tt = $(el2);
  
  if (tt) {
    tt.style.top = (objY-y) + 'px';
    tt.style.left = (objX+x) + 'px';
    tt.style.display = 'block';
  }
  
  return false;
}

function hideTooltip(el, delay)
{
  if (!document.getElementById) return;
  
  var tt = $(el);
  
  /*
  if (delay == null) {
    delay = 0;
  }
  else {
    delay = delay * 1000;
  }
  
  window.setTimeout(function() {
    if (tt) {
      if (tt) {
        tt.style.display = 'none';
      }
    }
  }, delay);
  */
  
  if (tt) {
    tt.style.display = 'none';
  }
  
  return false;
}

/**
 * 10.03.2006 - mow
 *
 * set completenes indicator for some profile input section  
 */
function update_profile_completeness(section, complete)
{
  elem1 = $('profile_complete_wiz_' + section)
  
  if (elem1) {
    $('profile_complete_wiz_' + section).innerHTML = complete ? '<img alt="" src="/images/icoProfileComplete.gif" />' : '<img alt="" src="/images/icoProfileUncomplete.gif" />';
  }
  
}

/**
 * 16.03.2006 - mow
 *
 * update function for edit_positions in job desire input
 */
function insert_edit_job_desire(request, sliderPosition, unit, unlimited)
{
  var txt = request.responseText;

  $('desire_main').innerHTML = txt.stripScripts();
  setTimeout(function() {txt.evalScripts()}, 10);

  var distance_slider = new Control.Slider('distance_slider_handle','distance_slider_track', {
    sliderValue:sliderPosition,
  range:$R(25,205),
  restricted:true,
    onSlide:function(v){$('distance_range').innerHTML=slider2range(v, unit, unlimited)},
  onChange:function(v){$('distance_range').innerHTML=slider2range(v, unit, unlimited); 
           $('position_distance').value = v; 
      } } );
  $('distance_range').innerHTML=slider2range(sliderPosition, unit, unlimited);
}

/**
 * unselect all selected options in a 
 * multi-select selection box
 */
function unselect_multiselect(id)
{
  sel = $(id);
  for ( i=0; i < sel.options.length; i++ ) {
    if ( sel.options[i].selected ) {
      changed = true;
    }
    sel.options[i].selected = false;
  }
}

/**
 * popup content
 */
function popContent(file, w, h)
{
  var sb = "scrollbars=no";
        var na = "popcontent";
  
  if(arguments.length > 3) { sb = arguments[3]; }
  if(arguments.length > 4) { na = arguments[4]; }
  
  var top = ((screen.height - h) / 2);
  var left = ((screen.width - w) / 2);
  var ref = window.open(file, na, "status=no,"+sb+",scrolling=0,resizable=no,width="+w+",height="+h+",top="+top+",left="+left+",locationbar=no");
        return ref;
}


function open_popunder( url, name, width, height )
{
  props = get_props();
  if (!(props.get('signup_popunder'))) {
    s_popunder = popContent(url, width, height, 'scrollbars=no', name);
    s_popunder.blur();
    window.focus();
    props.set('signup_popunder', 'open');
    set_props(props);
  }
}

function close_popunder(name)
{
  props = get_props()
  if (props.get('signup_popunder') == 'open') {
    s_popunder = popContent('about:blank', 5, 5, 'scrollbars=no', name);
    s_popunder.close();
    props.set('signup_popunder','closed');
    set_props(props);
  }
}

/**
 * used to set a status string while ajaxing, e.g.
 * ... :loading => "ajax_status('added_tag_msg','Updating...')" ...
 */
function ajax_status(node, status_string, replace)
{
  if (!node) return false;
  if (typeof node == 'string') node = document.getElementById(node);
  if (node) {
    if (replace)
      node.innerHTML = status_string
    else
      node.innerHTML = status_string + node.innerHTML 
  }
}

/**
 * check if some text might be a complete zipcode
 * 16.10.2006 - mow
 */
function checkZip(country_id, zip)
{
  var pattern4 = /^\d{4}$/; /* CH, BE, DK, NL, NO, AT */
  var patternl4 = /^L-\d{4}$/; /* LU */
  var pattern5 = /^\d{5}$/; /* FR, ES, FI, IT, SE, DE */
  /* no check for UK; sorry, postal codes are to irregular */
  return ( ( ( country_id == 23 || country_id == 43 || country_id == 158 || country_id == 164 || country_id == 166 || country_id == 191 ) && pattern4.test(zip) ) || ( ( country_id == 44 || country_id == 55 || country_id == 56 || country_id == 88 || country_id == 190 || country_id == 200 ) && pattern5.test(zip) ) || ( country_id == 126 && patternl4.test(zip) ) );
}

/**
 * Equal Column Height, accepts a Class name and tag
 */
function equalColHeightClass(classn, tag)
{
  var mx=0;
  var theval;
  var theeles = new Array();
  if(document.getElementById){
    theeles =getElementsByTagClass(tag, classn);
    var numa= theeles.length;
    for(var a=0; a < numa; a++){
      if(theeles[a].offsetHeight){
        theval=parseInt(theeles[a].offsetHeight);
        if(theval > mx){
          mx=theval;
        }
      }
      else{
        return false;
      }
    }
    for(var n=0; n < numa; n++){
      theeles[n].style.height=mx+'px';
    }
  }
}
 
/**
 * returns an array of elements of a given tag and classname
 */
function getElementsByTagClass(tag, classn)
{
  var allElements = document.getElementsByTagName(tag);
  var classed = new Array();
  var i, j, c;
  
  for (i=0, j=0; i < allElements.length; i++){
    c = " " + allElements[i].className + " "; 
    if (c.indexOf(" " + classn + " ") != -1){
      classed[j++] = allElements[i];
    }
  }
  return classed;
}

/**
 * 
 */
function newImage(arg)
{
  if (document.images) {
    rslt        = new Image();
    rslt.src    = arg;
    return rslt;
  }
}


/**
 * Function for toggling messages in profile after AJAX updates
 */
function profile_msg_toggle(id, content)
{
  e = $(id);
  
  if (e) { e.innerHTML = content }
}

/*###########################################################################
#
# NEED TO BE CHECKED IF THIS FUNCTIONS ARE STILL IN USE
#
###########################################################################*/

/**
 * select/deselect all checkboxes
 */
function checkBox(b)
{
  for (i = 0; i < document.forms.length; i++) {
    if (document.forms[i].name.substr(0,6) == "choose") {
      for (j = 0; j   < document.forms[i].elements.length; j++) {
        if (b == "true") {
          document.forms[i].elements[j].checked = true;
        } else {
          document.forms[i].elements[j].checked = false;
        }
      }
    }
  }
}

/**
 * another show/hide toggle: 
 * show: id from the element you want to show
 * hide: id from the element you want to hide 
 */
function toggle( show, hide )
{
  var show = ( document.layers ) ? document.show : document.getElementById( show ).style;
  var hide = ( document.layers ) ? document.hide : document.getElementById( hide ).style;
  show.display = "block";
  hide.display = "none";
}

function add_input2(name, name_pl)
{
  template = document.getElementById("new_"+name);
  copy = template.cloneNode(true);
  copy.style.display = "";
  
  // get first unused id
  id = 1
    input_x = document.getElementById(name + "_" + id);
  while ( input_x ) {
    id++;
    input_x = document.getElementById(name + "_" + id);
  }
  copy.id = name + "_" + id;
  input = copy.getElementsByTagName("input")[0];
  input.id = name + "_" + input.name + "_" + id;
  input.name = name_pl + "[]";
  template.parentNode.insertBefore(copy, template);
  return id;
}

function unselect_select(id, form_id, update, url, update_hint)
{
  changed = false;
  sel = $(id);
  for ( i=0; i < sel.options.length; i++ ) {
    if ( sel.options[i].selected ) {
      changed = true;
    }
    sel.options[i].selected = false;
  }
  
  if ( changed ) {
    if ( update_hint ) {
      $(update_hint).style.visibility = 'visible';
    }
    
    new Ajax.Updater(update, url, {asynchronous:true, evalScripts:true, parameters:Form.serialize($(form_id))});
  }
}

function selection_add_counts(id, values)
{
  selection = $(id)
  for ( i=0; i<selection.options.length; i++ ) {
    count = 0;
    option = selection.options[i]
    value = option.value;
    if ( value != '' ) {
      value = Number(value);
      if ( value < values.length ) {
  count = values[value]
      }
      sel = option.selected // MSIE forgets selection state when changing text
      if ( option.text.search(/\([0-9]*\)/) >= 0 ) {
  option.text = option.text.replace(/\([0-9]*\)/,"(" + count + ")");
      }
      else {
  option.text += " (" + count + ")";
      }
      option.selected = sel
    }
  }
}

/* obsolete: 10.07.2007 - mow 
function salary(n)
{
  n = Math.round(n);
  if ( n == 160 ) {
    n = "> 150";
  }
  return n;
}*/

/**
 * This function will not return until (at least)
 * the specified number of milliseconds have passed.
 * NOTE: It does a busy-wait loop.
 */
function pause(numberMillis)
{
  var now = new Date();
  var exitTime = now.getTime() + numberMillis;
  while(true) {
    now = new Date();
    if(now.getTime() > exitTime)
      return;
  }
}

/**
 * obsolete: 2008-01-07 - sfr
 */
/*function posContainer(obj, hlp, xDelay, yDelay, width)
{
  if (xDelay == null) {
    xDelay = 0;
  }
  
  if (yDelay == null) {
    yDelay = 0;
  }
  
  var newX = findPosX(obj);
  var newY = findPosY(obj);
  
  $(hlp).style.top = newY + yDelay + 'px';
  $(hlp).style.left = newX + xDelay + 'px';
  
  if (width != null) {
    $(hlp).style.width = width + 'px';
  }
  
  $(hlp).style.display = 'block';
}

function hideContainer(hlp)
{
  $(hlp).style.display = 'none';
}*/

/**
 * obsolete: 2008-01-07 - sfr
 */
/*function pop_content_w_scrollbar(file, w, h)
{
  var top = ((screen.height - h) / 2);
  var left = ((screen.width - w) / 2);
  var ref = window.open(file, "popcontent", "status=no,scrollbars=yes,scrolling=0,resizable=no,width="+w+",height="+h+",top="+top+",left="+left+",locationbar=no");
}*/

/**
 * obsolete: 2008-01-11 - sfr
 *
 * Image Preloader
 *
 * ::: OPTIMIZABLE - BETTER IMAGE HANDLING :::
 */
/*var preloadToggle = false;

function preloadImage()
{
  if (document.images) {
    bgProfilheadView_a1 = newImage("/images/bgProfilheadView_a1.gif");
    bgProfilheadView_a2 = newImage("/images/bgProfilheadView_a2.gif");
    bgProfilheadView_a3 = newImage("/images/bgProfilheadView_a3.gif");
    bgProfilheadView_i1 = newImage("/images/bgProfilheadView_i1.gif");
    bgProfilheadView_i2 = newImage("/images/bgProfilheadView_i2.gif");
    bgProfilheadView_i3 = newImage("/images/bgProfilheadView_i3.gif");
    preloadToggle  = true;
  }
}*/

/**
 * obsolete: 2008-01-11 - sfr
 *
 * Image Toggle
 */
/*function changeImage()
{
  if (document.images && (preloadToggle == true)) {    
    for (var i=0; i< changeImage.arguments.length; i+=2) {
      document.images[changeImage.arguments[i]].src = changeImage.arguments[i+1];
    }
  }
}*/

 /**
get properties from pjpp_prop cookie and return a hash of values
  */
function get_props() {
    value = '';
    cookies = document.cookie;
    start = cookies.indexOf("pjpp_props=");
    if ( start != -1 ) {
  start+=11;
  end = cookies.indexOf(";", start);
  if ( end == -1 ) {
      end = cookies.length;
  }
  value = unescape(cookies.substring(start,end));
    }
    props = {};
    vars = value.split(',');
    $A(vars).each( function(v,i) { 
      if ( v != '' ) {
    vv = v.split(':');
    name = vv[0].replace(/\"/g,"");
    val = vv[1];
    props[name] = val;
      }
  } );
    return $H(props);
}

/**
 * store properties (hash) to pjpp_props cookie
 */
function set_props( props ) {
    props_str = '';
    props.keys().each( function(n) 
           { props_str += '"' + n + '":' + props.get(n) + ',' } );
    document.cookie = 'pjpp_props=' + escape(props_str) + ';path=/';
}

function switchElementsVisibility( id_to_hide, id_to_show )
{
  document.getElementById( id_to_hide).style.display = "none";
  document.getElementById( id_to_show).style.display = "";
}

/**
 * returns the selected country in a country selection list as
 * used in searches
 * this is complicated as the list might contain a optgroup of states
 * in which case the value of the first entry of the optgroup (representing
 * the country as a whole) needs to be used
 * 09.09.2008 - mow
 */
function getCountryIdInSearch( selection_id ) {
    selection = $(selection_id);
    selected = selection.options[selection.selectedIndex];
    if ( selected.parentNode.nodeName == 'OPTGROUP' ) {
  selected = selected.parentNode.getElementsByTagName('OPTION')[0]
    }
    return selected.value;
}

/*
 super special variant of Form.EventObserver: provide event that caused the callback to be called to the callback
*/
 Form.XEventObserver = Class.create(Abstract.EventObserver, {
    getValue: function() {
      return Form.serialize(this.element);
  },
    onElementEvent: function( event ) {
      var value = this.getValue();
      if (this.lastValue != value) {
    this.callback(this.element, value, event);
    this.lastValue = value;
      }
  },
    registerCallback: function(element) {
      if (element.type) {
    switch (element.type.toLowerCase()) {
    case 'checkbox':
    case 'radio':
    Event.observe(element, 'click', this.onElementEvent.bindAsEventListener(this));
    break;
    default:
    Event.observe(element, 'change', this.onElementEvent.bindAsEventListener(this));
    break;
    }
      }
  }
    });

/* set the options in a select element.
  from http://elmicoxcodes.blogspot.com/2007/02/innerhtml-and-select-option-in-ie.html
*/
function select_innerHTML(objeto,innerHTML,tempsuffix){
/******
* select_innerHTML - corrige o bug do InnerHTML em selects no IE
* Veja o problema em: http://support.microsoft.com/default.aspx?scid=kb;en-us;276228
* Versão: 2.1 - 04/09/2007
* Autor: Micox - Náiron José C. Guimarães - micoxjcg@yahoo.com.br
* @objeto(tipo HTMLobject): o select a ser alterado
* @innerHTML(tipo string): o novo valor do innerHTML
*******/
  objeto.innerHTML = "";
  tempid = "micoxselect"
  if( tempsuffix != undefined ) {
    tempid += tempsuffix
  }

  var selTemp = document.createElement(tempid);
  var opt;
  selTemp.id=tempid;
  document.body.appendChild(selTemp);
  selTemp = $(tempid);
  selTemp.hide();

  innerHTML = innerHTML.replace(/<option/g,"<span").replace(/<\/option/g,"</span");
  innerHTML = innerHTML.replace(/<optgroup/g,"<div").replace(/<\/optgroup/g,"</div");
  selTemp.innerHTML = innerHTML;
    
  
  for( var i=0; i < selTemp.childNodes.length; i++ ) {
    var spantemp = selTemp.childNodes[i];

    if( spantemp.tagName ) {     
      opt = ( spantemp.tagName == 'SPAN' ) ? 
              document.createElement("OPTION") :
              document.createElement("OPTGROUP");

      objeto.appendChild(opt);

      //getting attributes
      for(var j = 0; j < spantemp.attributes.length; j++){
        var attrName = spantemp.attributes[j].nodeName;
        var attrVal  = spantemp.attributes[j].nodeValue;

        if(attrVal){
          try{
            opt.setAttribute(attrName,attrVal);
            opt.setAttributeNode(spantemp.attributes[j].cloneNode(true));
          }catch(e){}
        }
      }

      //getting styles
      if(spantemp.style){
        for(var y in spantemp.style){
          try{
            opt.style[y] = spantemp.style[y];
          }catch(e){}
        }
      }
      //value and text
      opt.value = spantemp.getAttribute("value");
      if( opt.tagName == 'OPTION' ) {
        opt.text = spantemp.innerHTML;
      } else {
        select_innerHTML( opt, spantemp.innerHTML, "foo" );
        opt.label = spantemp.getAttribute('label');
        i += opt.childNodes.length;
      }

      //IE
      opt.selected = spantemp.getAttribute('selected');
      opt.className = spantemp.className;
    } 
  }    
  document.body.removeChild(selTemp);
  selTemp = null;
}

/**
 * returns the the wanted url parameter
 * 
 * http://www.experteer.com/search/candidates?foo=123&bar=321#top
 * var foo_param = gup( 'foo' );
 * foo_param now contains 123
 * 
 * 02.07.2009 - sfr
 */
function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function stripeline(table,options) {
  options = options || {};
  var classnames= options.classnames || ['odd_row','even_row','head_row'];
  var hoverClassName = options.hoverClassName || ['hover']
  var tagname = options.tagname || 'tr'
  var rownum=classnames.length-1; // we begin at the end and switch between the last two
  table.select(tagname).each(function(row) {
    //remove all classnames (should we remove the highlighted,too?)
    for(var idx=0; idx<classnames.length ;idx++ ) {
      row.removeClassName(classnames[idx]);
    }
    var normal_cname=classnames[rownum];
    row.addClassName(normal_cname);
    row.observe('mouseover', function() {
      row.addClassName(hoverClassName)
    });

    row.observe('mouseout',function() {
      row.removeClassName(hoverClassName);
    });
    
    rownum = Math.abs(rownum-1);
  });
};

// experteer new navigation 

sfHover = function() {
  var navigation=$('expnavigation');
  if (navigation) {
    var sfEls = navigation.select("li");
    for (var i=0; i<sfEls.length; i++) {
      sfEls[i].onmouseover=function() {
        this.className+=" sfhover";
      }
      sfEls[i].onmouseout=function() {
        this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
      }
    }
  }
}
if (window.attachEvent) window.attachEvent("onload", sfHover);

function fieldColorValueToggle(r, b, v)
{
  if (b) {
    if (r.value == v) {
      r.style.color="#525b65";
      r.value = "";
    }
  }
  else {
    if (r.value == "") {
      r.style.color="#8796ab";
      r.value = v;
    }
  }
}


