
/* === staticv3_10_cookie === */

/* let exdays empty for Session-Cookie */
function set_cookie(c_name, value, exdays)
{
  var path = '/';
  var exdate=new Date();
  exdate.setDate(exdate.getDate() + exdays);
  var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString())+"; path="+path;
  document.cookie=c_name + "=" + c_value;
}

function delete_cookie(c_name)
{
  var exdate=new Date('1970/01/01');
  var c_value=escape(false) + "; expires=" + exdate.toUTCString() + "; path=/";
  document.cookie=c_name + "=" + c_value;
}

function get_cookie(c_name)
{
  var i,x,y,ARRcookies=document.cookie.split(";");
  for (i=0;i<ARRcookies.length;i++)
  {
    x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
    y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
    x=x.replace(/^\s+|\s+$/g,"");
    if (x==c_name)
    {
      return unescape(y);
    }
  }
}


/* === staticv3_10_json === */

/**
 * Implements JSON stringify and parse functions
 * v1.0
 *
 * By Craig Buckler, Optimalworks.net
 *
 * As featured on SitePoint.com
 * Please use as you wish at your own risk.
*
 * Usage:
 *
 * // serialize a JavaScript object to a JSON string
 * var str = JSON.stringify(object);
 *
 * // de-serialize a JSON string to a JavaScript object
 * var obj = JSON.parse(str);
 */


var JSON = JSON || {};

// implement JSON.stringify serialization
JSON.stringify = JSON.stringify || function (obj) {

  var t = typeof (obj);
  if (t != "object" || obj === null) {

    // simple data type
    if (t == "string") obj = '"'+obj+'"';
    return String(obj);

  }
  else {

    // recurse array or object
    var n, v, json = [], arr = (obj && obj.constructor == Array);

    for (n in obj) {
      v = obj[n]; t = typeof(v);

      if (t == "string") v = '"'+v+'"';
      else if (t == "object" && v !== null) v = JSON.stringify(v);

      json.push((arr ? "" : '"' + n + '":') + String(v));
    }

    return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
  }
};


// implement JSON.parse de-serialization
JSON.parse = JSON.parse || function (str) {
  if (str === "") str = '""';
  eval("var p=" + str + ";");
  return p;
};

(function($){
     $.fn.extend({
          center: function (options) {
               var options =  $.extend({ // Default values
                    inside: window, // element, center into window
                    transition: 0, // millisecond, transition time
                    minX:0, // pixel, minimum left element value
                    minY:0, // pixel, minimum top element value
                    withScrolling:true, // booleen, take care of the scrollbar (scrollTop)
                    vertical:true, // booleen, center vertical
                    horizontal:true // booleen, center horizontal
               }, options);
               return this.each(function() {
                    var props = {position:'absolute'};
                    if (options.vertical) {
                         var top = ($(options.inside).height() - $(this).outerHeight()) / 2;
                         if (options.withScrolling) top += $(options.inside).scrollTop() || 0;
                         top = (top > options.minY ? top : options.minY);
                         $.extend(props, {top: top+'px'});
                    }
                    if (options.horizontal) {
                          var left = ($(options.inside).width() - $(this).outerWidth()) / 2;
                          if (options.withScrolling) left += $(options.inside).scrollLeft() || 0;
                          left = (left > options.minX ? left : options.minX);
                          $.extend(props, {left: left+'px'});
                    }
                    /*
                    console.log("container width: " + $(options.inside).width() );
                    console.log("container height: " + $(options.inside).height() );
                    console.log("this width: " + $(this).outerWidth() );
                    console.log("this height: " + $(this).outerHeight());
                    */
                    if (options.transition > 0) $(this).animate(props, options.transition);
                    else $(this).css(props);
                    return $(this);
               });
          }
     });
})(jQuery);

function maximizer_template_inline_sublist(id)
{
  var container = $('#' + id);
  var body = $('div.body',container);
  var icon = $('div.expander',container);
  
  icon.toggleClass("expanded");
  body.slideToggle("slow");
}

function maximizer_template_inline_teaser(id)
{
  var container = $('#' + id);
  var body = $('div.body',container);
  var part = $('p.text_part',container);
  
  part.hide();
  body.show();
}


function maximizer_template_communication_box_body_wrapper(id)
{
  var container = $('#' + id);
  var template = $('div.communication_box_body_wrapper',container);
  var body = $('div.body',container);
  
  template.toggle();
  body.toggle();
}

function maximizer_template_communication_box_body_wrapper_toggle_button(selector)
{
  var container = $(selector);
  var button_row = $('div.data_row_2_action',container);
  
  var the_button = $('<a>'+javascript_cancel+'</a>');
  the_button.css({
    float: "right",
    height: "28px",
    margin: "10px"
  });
  
  the_button.bind('click.std',function(event){
    maximizer_template_communication_box_body_wrapper( container.closest("div.maximizer").attr("id"));
  });
  
  if(button_row)
  {
    button_row.append(the_button);  
  }
}

function maximizer_template_communication_box_body_wrapper_minimize(selector)
{
  var container = $(selector); 
  maximizer_template_communication_box_body_wrapper( container.closest("div.maximizer").attr("id"));
}

function maximizer_template_action_competence_card(id)
{
  var container = $('#' + id);
  var body = $('div.body',container);
  
  body.toggleClass("css_hidden");
  
  var overlay = $('div.overlay',container);
  var overlay_box = $('div.overlay_box',container);
  
  overlay_box.center(
    {
      inside: overlay 
    }
  );
}


/**
 * jQuery Maxlength plugin
 * @version   $Id: jquery.maxlength.js 18 2009-05-16 15:37:08Z emil@anon-design.se $
 * @package   jQuery maxlength 1.0.5
 * @copyright Copyright (C) 2009 Emil Stjerneman / http://www.anon-design.se
 * @license   GNU/GPL, see LICENSE.txt
 */

(function($) 
{

  $.fn.maxlength = function(options)
  {
    var settings = jQuery.extend(
    {
      events:             [], // Array of events to be triggerd
      maxCharacters:      10, // Characters limit
      status:             true, // True to show status indicator bewlow the element
      statusClass:        "maxlength_status", // The class on the status div
      statusTextPrefix:   "",
      statusTextSuffix:   "character left", // The status text
      notificationClass:  "css_highlighted", // Will be added to the emement when maxlength is reached
      showAlert:          false, // True to show a regular alert message
      alertText:          "You have typed too many characters.", // Text in the alert message
      slider:             true // Use counter slider
    }, options );
    
    // Add the default event
    $.merge(settings.events, ['keyup']);

    return this.each(function() 
    {
      var item = $(this);
      var charactersLength = $(this).val().length;
      
      // Update the status text
      function updateStatus()
      {
        var charactersLeft = settings.maxCharacters - charactersLength;
        
        if(charactersLeft < 0) 
        {
          charactersLeft = 0;
        }

        item.next("div").html(settings.statusTextPrefix + " " + charactersLeft + " " + settings.statusTextSuffix);
      }

      function checkChars() 
      {
        var valid = true;
        
        // Too many chars?
        if(charactersLength >= settings.maxCharacters) 
        {
          // Too may chars, set the valid boolean to false
          valid = false;
          
          // Add the notifycation class when we have too many chars
          //item.addClass(settings.notificationClass);
          //competence-site changes
          item.parent('div').addClass(settings.notificationClass);
          
          // Cut down the string
          item.val(item.val().substr(0,settings.maxCharacters));
          // Show the alert dialog box, if its set to true
          showAlert();
        } 
        else 
        {
          // Remove the notification class
          if(item.parent('div').hasClass(settings.notificationClass)) 
          {
            item.parent('div').removeClass(settings.notificationClass);
          }
        }

        if(settings.status)
        {
          updateStatus();
        }
      }
            
      // Shows an alert msg
      function showAlert() 
      {
        if(settings.showAlert)
        {
          alert(settings.alertText);
        }
      }

      // Check if the element is valid.
      function validateElement() 
      {
        var ret = false;
        
        if(item.is('textarea')) {
          ret = true;
        } else if(item.filter("input[type=text]")) {
          ret = true;
        } else if(item.filter("input[type=password]")) {
          ret = true;
        }

        return ret;
      }

      // Validate
      if(!validateElement()) 
      {
        return false;
      }
      
      // Loop through the events and bind them to the element
      $.each(settings.events, function (i, n) {
        item.bind(n, function(e) {
          charactersLength = item.val().length;
          checkChars();
        });
      });

      // Insert the status div
      if(settings.status) 
      {
        item.after($("<div/>").addClass(settings.statusClass).html('-'));
        updateStatus();
      }

      // Remove the status div
      if(!settings.status) 
      {
        var removeThisDiv = item.next("div."+settings.statusClass);
        
        if(removeThisDiv) {
          removeThisDiv.remove();
        }

      }

      // Slide counter
      if(settings.slider) {
        item.next().hide();
        
        item.focus(function(){
          item.next().slideDown('fast');
        });

        item.blur(function(){
          item.next().slideUp('fast');
        }); 
      }

    });
  };
})(jQuery);




function internal__menu_fill_up_params( params )
{
  if( params && params.menu_id )
  {
    params.navi=$('#' + params.menu_id + '_navi');
    params.body=$('#' + params.menu_id + '_body');
    params.body_items = $("> *", params.body);
    params.navi_items = $("> *", params.navi);
    return params;
  }
  return {};
}

function internal__menu_basic_event_method( event )
{
  event.data.index = $(this).attr('id').substring( $(this).attr('id').lastIndexOf('_')  + 1 );

  event.data.body_items.addClass("css_hidden");
  event.data.body_items.removeClass("activated");

  event.data.navi_items.removeClass("activated");
  $(event.data.navi_items[event.data.index]).addClass("activated");

  $(event.data.body_items[event.data.index]).removeClass("css_hidden");
  $(event.data.body_items[event.data.index]).addClass("activated");

  $("input[type='radio']", event.data.navi_items).removeAttr("checked");
  $("input[type='radio']", $(event.data.navi_items[event.data.index])).attr("checked","checked");
  
  event.data.navi_items.each(function(index,item){
    
    $(item).removeClass("left_of_active");
    $(item).removeClass("right_of_active");
    
    if( index < event.data.index )
    {
      $(item).addClass("left_of_active");
    }
    else if(index > event.data.index)
    {
      $(item).addClass("right_of_active");
    } 
    
  });    
}

/* basic menu action event */
function menu_init( params, event_type )
{
  if( params && params.menu_id )
  {
    params = internal__menu_fill_up_params( params );
    $(params.navi_items).each(function(index,item){
      $(item).bind(event_type + '.menu_basic_event_method', params, internal__menu_basic_event_method);
    });    
  }
  return params;
}

/* initialize menu_template radio + support for body_item_template body_ajax */
function menu_template_radio_init( params )
{
  if( params && params.menu_id )
  {
    params = menu_init( params, "change" );
    
    // ajax support
    if( params.body_item_template == "body_ajax" )
    {
      $("input[type='radio']",$( 'ul.menu_template_radio_navi',$('#' + params.menu_id))).each ( function ( index, item )
      {
        $(item).bind('change.ajax_request',params,function(event){
          body_index=$(this).attr("value");
          func_name = event.data.menu_id + "_body_item_" + body_index + "_ajax";
          eval(func_name + "()");
        });
        
      });
    } 
  }
}


function menu_template_tiny_init(params)
{
  if( params && params.menu_id )
  {
    params = menu_init( params, "click" );
    
    $(params.navi_items).each(function(index,item){
      
      $(item).bind('click.tiny_arrow', params, function(event){
        
        event.data.index = $(this).attr('id').substring( $(this).attr('id').lastIndexOf('_')  + 1 );
        
        event.data.navi.find("div[title=arrow_container]").removeClass("arrow");
        $(this).find("div[title=arrow_container]").addClass("arrow");  
        
        //set margin-bottom to parent div, because of overflow hidden (HACK)
        menu_body_height = $($("> div",$('div.menu_template_tiny_body',$('#' + event.data.menu_id ))).toArray()[event.data.index]).height() - 60;
        $(this).closest('div.data_row_2_edit').css('margin-bottom',menu_body_height + 'px');
        
      });
      
    });
  
  }
}


/**
@copyright florian brueggemann fbrueg@gmx.de
@author florian brueggemann
@version 1
@packacke JQuery nattylist

 */


(function($) {
      $.fn.extend({
          
        nattylist: function( options ) {
          
          /* defaults */
          var settings = {
            'range'      : 3,
            'mode'  : 'more_bottom', // more_top more_bottom up_and_down
            'debug'      : true,
            'mode__more_link_caption': 'more',
            'mode__up_and_down_top_link_caption' : 'up',
            'mode__up_and_down_bottom_link_caption': 'down',
            'pointer' :0 ,
            'url' : '',
            'page': '1'
          };
          
          /* own instance */ 
          var $this = null;
          
          /* item pointer */
          var pointer = 0;
          
          /* the list items*/
          var list_items = {};
          
          /* the mode__more_link (button, etc) */
          var mode__more_link = $('<a class="nattylist_more"/>');
          
          /* mode more onclick counter */
          var mode__more_onclick_counter = 0;
          
          var mode__up_and_down_top_link =  $('<a class="nattylist_more"/>');
          var mode__up_and_down_bottom_link =  $('<a class="nattylist_more"/>');
          var mode__up_and_down_allready_loaded_pages = {};
          
          /* current page */
          var page = 0;
          
          /* for debugging */
          function log(msg)
          {
             if(typeof console != "undefined" && settings.debug == true)
             {
               console.log(msg);  
             }
          }
          
          /* get listsize */
          function get_list_size()
          {
            return $this.children().length;
          }
          
         
         function show_list_items(start,length,hide_others)
         {                      
           list_items.each(function(index,item) {
             
             if( start > index || index >= (start + length) )
             {
               if ( hide_others )
               {
                 $(item).hide(); 
                 log("show_list_items: hide " + index );
               }         
             }
             else
             {
               $(item).show();
               log("show_list_items: show " + index );
             }       
           });            
         }
          
         function hide_list_items(start,length,show_others)
         {             
           
           list_items.each(function(index,item) {
             
             if( start > index || index >= (start + length) )
             {
               if ( show_others )
               {
                 $(item).show(); 
                 log("hide_list_items: show " + index );
               }         
             }
             else
             {
               $(item).hide();
               log("hide_list_items: hide " + index );
             }       
           });            
         }
         
         function get_more_list_items(page)
         {
           result = {};
           
           $.ajax({
             type: "POST",
             url: settings.url + "&page=" + page,
             global: false,
             dataType: "html",
             async: false,
             success: function(data) {
               result = $("ul:first-child",data).children();
             }
             
           });
           return result;
         }
         
         
         
         function onclick_mode__more_top(event)
         {
           if(event) event.preventDefault();
        
           pointer = get_list_size() - ( (mode__more_onclick_counter + 1) * settings.range);
           
           log("onclick pointer    : " + pointer);
           
           if (pointer <= 0 ) 
           {
             log("onclick_mode__more_top - need more list-items");
             mode__more_link.hide();
             page ++;
           }
          
           show_list_items(pointer,settings.range);
           
           mode__more_onclick_counter++;
           
           return false;
         }
           
         function onclick_mode__more_bottom(event)
         {
           if(event) event.preventDefault();
           
           pointer = mode__more_onclick_counter * settings.range;
           
           log("onclick pointer    : " + pointer);
           
           if ( pointer > (get_list_size() - settings.range) )
           {
             log("onclick_mode__more_bottom - need more list-items");
             mode__more_link.hide();
             page ++;
           }
           
           show_list_items(pointer,settings.range);
           
           mode__more_onclick_counter++;
           return false;
         }
            
         function onclick_mode__up_and_down_top_link(event)
         {
           if(event) event.preventDefault();
           
           hide_list_items(pointer, settings.range,false);
           
           
           switch (true)
           {
             case ( pointer >= settings.range ) :
             //default mode
               pointer -= settings.range;
               break;
             case ( pointer < settings.range && pointer > 0) :
               pointer= 0;
               break;
             case ( pointer == 0) :
               log("end of list ... pointer is " + pointer);
               break;
           }
           
           show_list_items(pointer, settings.range, false);
           
           
           return false;
         }
         
         function onclick_mode__up_and_down_bottom_link(event)
         {

           if(event) event.preventDefault();
             
           hide_list_items(pointer, settings.range,false);
           
           max_pointer = get_list_size() - settings.range;
          
           
           switch (true)
           {
             case ( pointer < max_pointer  ) :
             //default mode
               pointer += settings.range;
               log("up_and_down_bottom - default: " + pointer );
               show_list_items(pointer, settings.range, false);
               break;
             case ( pointer < get_list_size() && pointer > max_pointer) :
               pointer= max_pointer;
               log("up_and_down_bottom - between: " + pointer );
               show_list_items(pointer, settings.range, false);
               break;
             case ( pointer == max_pointer ) :
               log("end of list ... pointer is " + pointer);
               //show_list_items(get_list_size() - settings.range, settings.range, false);
               show_list_items(pointer.range, settings.range, false);
               break;
           }
           
           
           
           return false;
         }
         
        /* plugin main */
        return this.each(function() {
          
          $this = $(this);
          
          if ( options ) { 
            $.extend( settings, options );
          }
          
          page = settings.page;
          mode__up_and_down_allready_loaded_pages[page] = true;
          
          log(mode__up_and_down_allready_loaded_pages);
          
          if( settings.range < get_list_size() )
          {
          
            list_items = $this.children();
          
            
            switch(settings.mode)
            {
              case 'more_top':
                
                pointer = get_list_size() - settings.range;
                
                // show the first itemset
                show_list_items(pointer,settings.range,true);
                mode__more_onclick_counter =  1;
                
              //debug
                log( "initial listsize : " + get_list_size() );
                log( "initial pointer  : " + pointer );
                
                mode__more_link.html( settings.mode__more_link_caption );
                mode__more_link.click( function(event){
                  return onclick_mode__more_top(event);
                } );
                
                $this.before(mode__more_link);
                
                break;
              
              case 'more_bottom':
                
                pointer = 0;
                
                // show the first itemset
                show_list_items(pointer,settings.range,true);
                mode__more_onclick_counter =  1;
                
              //debug
                log( "initial listsize : " + get_list_size() );
                log( "initial pointer  : " + pointer );
                
                mode__more_link.html( settings.mode__more_link_caption );
                mode__more_link.click( function(event){
                  return onclick_mode__more_bottom(event);
                } );
                
                $this.after(mode__more_link);
                
                break;
              
              case 'up_and_down':
               
                pointer = settings.pointer;
                
                // show the first itemset
                show_list_items(pointer,settings.range,true);
                
              //debug
                log( "initial listsize : " + get_list_size() );
                log( "initial pointer  : " + pointer );

                mode__up_and_down_top_link.html(  settings.mode__up_and_down_top_link_caption ) ;
                mode__up_and_down_bottom_link.html(  settings.mode__up_and_down_bottom_link_caption  ) ;
                
                mode__up_and_down_top_link.click( function(event){
                  return onclick_mode__up_and_down_top_link(event);
                } );
                mode__up_and_down_bottom_link.click( function(event){
                  return onclick_mode__up_and_down_bottom_link(event);
                } );
                
                $this.before(mode__up_and_down_top_link);
                $this.after(mode__up_and_down_bottom_link);
                
                break;
                
            }
           
          }            

          
        });

          }
      });
     })(jQuery);



/**
 * Some scripts for tab_box (communication)
 */


/*
function tab_box_show(container_id , css_class, visible_id)
{
  
  active_index = 0; 
  counter = 0;
  
  $('#' + container_id +' .'+ css_class +'_tab' ).each(function(index,value) {
    
    if(value.id + '_body'  == visible_id)
    {
        active_index = index;
        $('#' + value.id + '_body').show();
        //$('#' + value.id + '_body').slideDown('slow');
        $('#' + value.id).addClass(css_class + '_tab_active');
        $('#' + value.id).removeClass(css_class + '_tab_inactive');
        $('#' + value.id).css('color','#606060');
        
        $('#' + value.id + '_body').find('input[id$=active_index]').attr('value',active_index);
        
        
    }
    else
    {
        $('#' + value.id + '_body').hide();  
        //$('#' + value.id + '_body').slideUp('slow');
        $('#' + value.id).removeClass(css_class + '_tab_active');
        $('#' + value.id).addClass(css_class + '_tab_inactive');
        $('#' + value.id).css('color','#B1B1B1');
    }
    counter ++;
  });
  
  //add the seperator class
  
  if(counter > 1)
  {
    if(active_index == 0)
    {
      $($('#' + container_id +' .'+ css_class +'_tab' )[1]).addClass(css_class + '_tab_right_of_active');
    }
    else if((active_index +1) == counter)
    {
      $($('#' + container_id +' .'+ css_class +'_tab' )[active_index -1]).addClass(css_class + '_tab_left_of_active');
    }
    else
    {
      $($('#' + container_id +' .'+ css_class +'_tab' )[active_index -1]).addClass(css_class + '_tab_left_of_active');
      $($('#' + container_id +' .'+ css_class +'_tab' )[active_index +1]).addClass(css_class + '_tab_right_of_active');
    }
  }
  
//remve the seperator class
  left_of= active_index -1;
  right_of = active_index +1;
  
  for(i=0;i<counter;i++) 
  {
    if(i== left_of)
    {
      $($('#' + container_id +' .'+ css_class +'_tab' )[i]).removeClass(css_class + '_tab_right_of_active');
    }
    else if(i == right_of)
    {
      $($('#' + container_id +' .'+ css_class +'_tab' )[i]).removeClass(css_class + '_tab_left_of_active');
    }
    else
    {
      $($('#' + container_id +' .'+ css_class +'_tab' )[i]).removeClass(css_class + '_tab_left_of_active');
      $($('#' + container_id +' .'+ css_class +'_tab' )[i]).removeClass(css_class + '_tab_right_of_active');
    }
  }
}
*/
/*
function tab_box_init( container_id , css_class, active_index){
  //initial run, handle visiblility
  $('#' + container_id +' .'+ css_class +'_tab' ).each(function(index,value) {
    //only the active_index-item (body) is visible
    if(index !== active_index)
    {
        $('#' + value.id + '_body').hide();  
        $('#' + value.id).addClass(css_class + '_tab_inactive');
        if(index == active_index + 1)
        {
          $('#' + value.id).addClass(css_class + '_tab_right_of_active');
        }
        if(index == active_index - 1)
        {
          $('#' + value.id).addClass(css_class + '_tab_left_of_active');
        }
       
    }
    else
    {
        $('#' + value.id + '_body').show();
       
        $('#' + value.id).addClass(css_class + '_tab_active');
    }
    
  });

  // add events
  $('#' + container_id +' .'+ css_class +'_tab' ).each(function(index,value) {
    $('#' + value.id).click(function(){
      tab_box_show(container_id,css_class,this.id + '_body');
    });
    
    $('#' + value.id).mouseenter(function(){
      $('#' + value.id).css('color','#606060');
    });
    
    $('#' + value.id).mouseleave(function(){
      if( $('#' + value.id).hasClass('tab_box_tab_inactive')  ||
          $('#' + value.id).hasClass('communication_box_tab_inactive'))
      {
        $('#' + value.id).css('color','#B1B1B1');
        
      }  
    });
  });
  
  //plugin maxlength for textarea and textfields
  
  $('#' + container_id ).find('input[type="text"][name="object[s_retp_obje_has_ass_1_name_mstr]"]').maxlength(
      {
        maxCharacters: 100,
        statusTextPrefix: "(",
        statusTextSuffix: "| 100 ) Zeichen"
      }
  );
  //$('#' + container_id ).find('textarea').maxlength();
  
  
}
*/


function replace_list (list_id, url, loader_id, slide)
{
  var myLoader = "<img id='list_loader' style=\"width: 18px; height: 18px; vertical-align: middle;\" border='0' align='center' src='"+config_ajaxloadergfx+"'>";
  
  $("#" + loader_id).append(myLoader); 
  $.ajax({
    url: url,
    
    beforeSend: function (dummy)
    {
      $('#' + loader_id).addClass('deactivate_clickevent');     
    },
    
    success: function(data){
      if(slide)
      {
          data = $( "<div>" + data + "</div>");
          data.hide();
          $('#' + list_id).replaceWith( data );
          $("#"+ loader_id + "_icon_sublist_expander").toggleClass("expanded");
          data.slideDown("slow");

      }
      else
      {
        $('#' + list_id).replaceWith(data);
      }
      
      $('#list_loader').remove();
      
      
      $('#' + loader_id).removeClass('deactivate_clickevent');
    }
  });
}


function add_reload_list_to_clickevent(tab_id,replace_id,url)
{
  tab = $('#' + tab_id);
 
  tab.click(function(event) {

   list_id = $('#' + replace_id).find('div[id^=module_list_]').attr('id');
   
   if( ! list_id )
   {
    // keine kommunikationsobjekte gefunden in '<p>'
     $('#' + replace_id).find('p').attr('id','replace_me_on_success');
     list_id = 'replace_me_on_success';
   }
   
   if( ! $('#' + tab_id).hasClass('deactivate_clickevent') )
   {
     replace_list(list_id,url,tab_id,false);
   }
   
  });
}


function toggle_sublist(id, parent_container_type, url)
{
  action_div   = $('#' + id).parent('div');
  list_item    = action_div.parent(parent_container_type);
  extender_div = list_item.find('div[class="list_item_extender"]');
  replace_div  = extender_div.find('div');
  replace_div.attr("id","relace_me"+id);
  replace_id = replace_div.attr("id");
 
  
  
  if(action_div.hasClass('clicked'))
  {
    $('#' + replace_id).slideToggle("slow");
    $("#"+ id + "_icon_sublist_expander").toggleClass("expanded");

  }
  else
  {
    action_div.addClass('clicked');
    replace_list(replace_id, url, id,true) ;
  }
}




/* temporary json storage  */


function internal_action_build_storage_for(form_id,identifier)
{
  $( "#" + form_id ).append($("<input type='hidden' name='object[" +  identifier + "]'/>"));
}

function internal_action_add_data_to_storage(data,data_id,form_id, identifier)
{
  storage_html = $("#" + form_id + " input[type='hidden'][name='object[" + identifier + "]']");
  storage = jQuery.parseJSON(storage_html.val());
  
  if(storage == null)
  {
    storage = new Object(); 
  }
  storage[data_id] = data;
  storage = JSON.stringify(storage);
  storage_html.val(storage);
}

function internal_action_remove_data_from_storage(data_id,form_id, identifier)
{
  storage_html = $("#" + form_id + " input[type='hidden'][name='object[" + identifier + "]']");
  storage = jQuery.parseJSON(storage_html.val());
  
  if(storage == null)
  {
    storage = new Object(); 
  }
  if(storage[data_id])
    {
  delete storage[data_id];
    }
  storage = JSON.stringify(storage);
  storage_html.val(storage);
}


function action_show_create_link(container_id,form_id,link)
{

  
    form=$('#' + form_id);
    id= new Date().getTime();
    internal_action_add_data_to_storage(link,id,form_id,"link");
  
    /* view in form*/
  
    //tiny link for view
    tiny_link = new String(link);
    if(tiny_link.length > 50 )
    {
        tiny_link = tiny_link.substr(0,50) + "...";
    }
    
    internal_action_preview_storage_data(container_id,form_id,"link",id,javascript_link + ": ", tiny_link);
   
}

function action_show_add_center(container_id,form_id,center_id,center_label)
{
  form=$('#' + form_id);
  id= new Date().getTime();
  internal_action_add_data_to_storage(center_id,id,form_id,"center");
  
  internal_action_preview_storage_data(container_id,form_id,"center",id,javascript_center + ": ", center_label);
}

function action_show_add_file(container_id,form_id,json_data,label)
{
  form=$('#' + form_id);
  id= new Date().getTime();
  internal_action_add_data_to_storage(json_data,id,form_id,"file");
  
  internal_action_preview_storage_data(container_id,form_id,"file",id,javascript_file + ": ", label);
}


function action_show_add_email(container_id,form_id,label)
{
  form=$('#' + form_id);
  id= new Date().getTime();
  internal_action_add_data_to_storage(label,id,form_id,"email");
  
  internal_action_preview_storage_data(container_id,form_id,"email",id,  javascript_email + ": ", label);
}


/*
 * function internal_action_preview_storage_data
 * 
 * container_id: (string) id of the preview_container
 * form_id:      (string) id of the parent form
 * storage_name: (string) namespace of storage-type
 * storage_id:   (string) id of the data storage
 * label:        (string) label of the caption
 * caption:      (string) preview caption
 */

function internal_action_preview_storage_data(container_id,form_id,storage_name,storage_id,label,caption)
{
  preview_container_id = "x_" + storage_id + "_preview";
  preview_container = $('<div class="preview_container"></div>');
  
  label_container   = $('<div class="label">' + label + '</div>'); 
  caption_container = $('<div class="caption">' + caption + '</div>');
  remove_container  = $('<div class="remove">&nbsp</div>');
  
  remove_container.bind('click.remove_from_storage',function(event){
    
    internal_action_remove_data_from_storage(storage_id,form_id, storage_name);
    $(this).closest("div.preview_container").detach();
    
  });
  
  preview_container.append(label_container);
  preview_container.append(caption_container);
  preview_container.append(remove_container);
  $("#" + container_id).append(preview_container);
 
}







function toggle_sublist2(event,url)
{
  var url = new String(url);
  var wrapper = $((event.currentTarget) ? event.currentTarget : event.srcElement).closest("div.wrapper");
  var sublist_wrapper = wrapper.find("div.sublist");
  var icon_div = wrapper.find("div.expander");
  
  var loader = "<img id='list_loader' style=\"width: 18px; height: 18px; vertical-align: middle;\" border='0' align='center' src='"+config_ajaxloadergfx+"'>";
  
  if ( wrapper.hasClass("allready_clicked") )
  {
    sublist_wrapper.slideToggle("slow");
    icon_div.toggleClass("expanded"); 
  }
  else
  {
  
    $.ajax({
      url: url,
      
      beforeSend: function (dummy)
      {
        wrapper.append(loader);   
      },
      
      success: function(data){
        sublist_wrapper.html(data);
        icon_div.toggleClass("expanded");
        wrapper.addClass("allready_clicked");
        wrapper.find("img#list_loader").hide();
      }
   });
    
  }  
}



function multi_input_email_invite_person(form_id, html_input_type_text_selector,container_id)
{
  internal_action_build_storage_for(form_id,"email")
  
  html_input_type_text = $(html_input_type_text_selector);
 
  // add view-container after input-field
  $('<div id="' + container_id + '"class="additional_action_pane invite_person"></div>').insertAfter(html_input_type_text);
  
  html_input_type_text.bind('keypress.enter_add_email',function(event){
        
    
    if(event)
    {
      code = (event.keyCode ? event.keyCode : event.which);
      if(code == 13)
      {
        //enter
        email = new String($(this).val());
        email_pattern = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
        
        //validation
        if( email_pattern.test(email)  )
        {
          $(this).val("");
          
          action_show_add_email(container_id,form_id,email);
          return false;    
         
        }
        else
        {
          alert(javascript_invalid_email_pattern);
          return false;
        }
        
      }     
    } 
      
    
  });
  
  
}


/* === staticv3_70_filter === */

/**  jQuery plugin "tree_filter"
 * 
 * Options: 
 *       structure : tree-structure with: 
 *            'id' - the id of the node (used for selected_path)
 *            'sub' - array of subnodes
 *            ... further attributes used by build_node_callback
 *       selected_path : array of IDs from top to bottom
 *       build_node_callback : callback that returns a filter node (structure is passed as arg)
 *       parent_auto : if a node is collapsed, then "expand" expands the parent, so all siblings are visible. Usefull only when initial_view=='branch'
 *       children_auto : if a node is expanded, "collapse" hides all children of its children before expanding.
 *       siblings_auto : if a node is expanded, "collapse" collapses all its siblings, "hide" hides all its children. 'hide' only usefull with initial_view=branch
 *       hide_collapser : if true, the [-] is not displayed, but [>]. Use only when siblings_auto is 'hide'
 *       initial_view : 'branch' or 'fisheye'
 *       
 * Methods:
 *       expand
 *       collapse
 * 
 */

/*
initial_view
  branch - nur der aktueller Pfad initial sichtbar
  fisheye - alle Geschwister entlang des aktuellen Pfades initial sichtbar
  selected - nur der aktueller Pfad ohne Kinder/Geschwister initial sichtbar
 
children_auto
  collapse - Wenn ein Knoten ausgeklappt wird, sind alle Kinder eingeklappt, unabhängig davon, ob sie vorher ausgeklappt waren.
 
siblings_auto
  hide - Wenn ein Knoten ausgeklappt wird, werden alle Geschwister versteckt. Nur der Pfad ist dann sichtbar. (Sinnvoll nur bei initial_view=branch)
  collapse - Wenn ein Knoten ausgeklappt wird, klappen alle Geschwister zu (sind aber weiterhin sichtbar).
  
parent_auto
  expand - wenn ein Knoten eingeklappt wird, werden alle seine Geschwister automatisch angezeigt. (Sinnvoll nur bei initial_view=branch)
*/  
  

(function( $ ){
  
  var methods = {
    init : function( options ) {
      
      var settings = {
          level: 0,
          visible: true,
          filter_id: '_tree_filter_' + Math.floor(Math.random()*5).toString(),
          parent_auto: false,
          children_auto: false,
          siblings_auto: false,
          hide_collapser: false,
          initial_view: 'selected'
      };
      
      return this.each(function() {
        // If options exist, lets merge them
        // with our default settings
        if ( options ) { 
          $.extend( settings, options );
        }

        var selected_path = settings.selected_path;
        
        var visible = settings.visible;
        var initial_view = settings.initial_view;
        
        var $this = $(this);
        var data = {
          structure: settings.structure,
          build_node_callback: settings.build_node_callback,
          parent_auto: settings.parent_auto,
          children_auto: settings.children_auto,
          siblings_auto: settings.siblings_auto,
          hide_collapser: settings.hide_collapser,
          filter_id: settings.filter_id,
          children_build_state: 'none',
          children_show_state: 'none',
          one_expanded_child_structure: null,
          level: settings.level
        };

        var my_root;
        var my_expander;
        var my_row;
        if (data.structure.id)
        {
          my_root = $('<li id=\''+data.filter_id+'_root_'+data.structure.id+'\'></li>');
          if (!visible)
          {
            my_root.hide();
          }
          $this.append(my_root);
          data.my_parent = $this;
        
          my_row = $('<div id=\''+data.filter_id+'_item_'+data.structure.id+'\' class="filter_item clearfix level_'+data.level.toString()+'"></div>');
          my_root.append(my_row);
        
          my_expander = $('<a class="expander"></a>');
          my_row.append(my_expander);
          data.my_expander = my_expander;
        
          if (typeof(data.build_node_callback) != 'undefined')
          {
            my_row.append(data.build_node_callback(data.structure));
          }
          
          if (data.structure.sub)
          {
            var self = $('<ul id=\''+data.filter_id+'_node_'+data.structure.id+'\'></ul>');
            my_root.append(self);
            data.my_node = self;
            
            self.data('tree_filter', data);
            
            // add parent to each child
            for (child_index in data.structure.sub)
            {
              var child_structure = data.structure.sub[child_index].parent = data.structure;
            };            
          }
        }
        else
        {
          // no id. plain list without root
          data.my_node = $this;
          //data.level -= 1;
          $this.data('tree_filter', data);
        }
              
        if (typeof(data.structure.id) == 'undefined' || selected_path[0] == data.structure.id)
        {
          if (typeof(data.structure.id) != 'undefined')
          {
            // remove myself from selected path
            selected_path.shift();
          }
          
          // init flag
          var render_all_children = false;
          
          // am I the last in the selected path?
          if (selected_path.length>0)
          {
            // I am not the last
            
            switch (initial_view)
            {
            case 'branch':
              
              // find selected child
              var selected_child_structure;
  
              for (child_index in data.structure.sub)
              {
                var child_structure = data.structure.sub[child_index];
                if (child_structure.id == selected_path[0])
                {
                  selected_child_structure = child_structure;
                  break;
                }
              };
  
              // has the seleted child children?
              if (selected_child_structure.sub)
              {
                // yes. render only selected child
                data.my_node.tree_filter({
                    structure: selected_child_structure,
                    selected_path: selected_path,
                    build_node_callback: data.build_node_callback,
                    parent_auto: data.parent_auto,
                    children_auto: data.children_auto,
                    siblings_auto: data.siblings_auto,
                    hide_collapser: data.hide_collapser,
                    filter_id: data.filter_id,
                    initial_view: initial_view,
                    level: data.level + 1
                });
                
                data.children_build_state='one';
                data.children_show_state='one';
                data.one_expanded_child_structure=selected_child_structure;
                
                if (my_expander)
                {
                  my_expander.addClass('expander_active');
                  my_expander.bind('click.tree_filter', function() {
                    data.my_node.tree_filter('expand');
                  });
                }
              }
              else
              {
                // no. render all siblings of the selected child
                render_all_children = true;
              }
              
              break;
              
            case 'selected':
              
              // find selected child
              var selected_child_structure;
  
              for (child_index in data.structure.sub)
              {
                var child_structure = data.structure.sub[child_index];
                if (child_structure.id == selected_path[0])
                {
                  selected_child_structure = child_structure;
                  break;
                }
              };
  
              // render only selected child
              data.my_node.tree_filter({
                  structure: selected_child_structure,
                  selected_path: selected_path,
                  build_node_callback: data.build_node_callback,
                  parent_auto: data.parent_auto,
                  children_auto: data.children_auto,
                  siblings_auto: data.siblings_auto,
                  hide_collapser: data.hide_collapser,
                  filter_id: data.filter_id,
                  initial_view: initial_view,
                  level: data.level + 1
              });
              
              data.children_build_state='one';
              data.children_show_state='one';
              data.one_expanded_child_structure=selected_child_structure;
              
              my_expander.addClass('expander_active');
              my_expander.bind('click.tree_filter', function() {
                data.my_node.tree_filter('expand');
              });
              
              break;
              
            case 'fisheye':
            default:
              render_all_children = true;
              break;
              
            }
          }
          else
          {
            // last selected
            if (my_row)
            {
              my_row.addClass('css_current');
            }
            
            switch (initial_view)
            {
            case 'selected':
              if (data.structure.sub)
              {
                // there are children - show expander
                if (my_expander)
                {
                  my_expander.addClass('expander_active');
                  my_expander.bind('click.tree_filter', function() {
                    data.my_node.tree_filter('expand');
                  });
                }
              }
              
              break;
            
            case 'branch':
            case 'fisheye':
            default:
              render_all_children = true;
              break;
              
            }
          }
          
          if (data.structure.sub && render_all_children)
          {
            for (child_index in data.structure.sub)
            {
              data.my_node.tree_filter({
                structure: data.structure.sub[child_index],
                selected_path: selected_path,
                build_node_callback: data.build_node_callback,
                parent_auto: data.parent_auto,
                children_auto: data.children_auto,
                siblings_auto: data.siblings_auto,
                hide_collapser: data.hide_collapser,
                filter_id: data.filter_id,
                initial_view: initial_view,
                level: data.level + 1
              });
            };

            data.children_build_state='all';
            data.children_show_state='all';
            data.one_expanded_child_structure=null;

            if ( ! data.hide_collapser)
            {
              if (my_expander)
              {
                my_expander.addClass('collapser_active');
                my_expander.bind('click.tree_filter', function() {
                  data.my_node.tree_filter('collapse');
                });
              }
            }
          }
        }
        else
        {
          // not selected sibling
          
          // are there children?
          if (data.structure.sub)
          {
            if (my_expander)
            {
              my_expander.addClass('expander_active');
              my_expander.bind('click.tree_filter', function() {
                data.my_node.tree_filter('expand');
              });
            }
          }
        }
        
        
      });
    },
        
    expand : function( ) {
      return this.each(function() {
        var $this = $(this);
        var data = $this.data('tree_filter');
//console.log("expand "+data.structure.id);        
        if (data.children_auto && data.children_auto=='collapse')
        {
          switch (data.children_show_state)
          {
            case 'all':
              // nothing to do
              break;
            
            case 'one':
              // hide all children of the expanded child animated
              $('#'+data.filter_id+'_node_'+data.one_expanded_child_structure.id).tree_filter('hide_all_children_animated');
              break;
              
            case 'none':
              // hide all children of the children quick
              for (child_index in data.structure.sub)
              {
                var child_structure = data.structure.sub[child_index];
                $('#'+data.filter_id+'_node_'+child_structure.id).tree_filter('hide_all_children_quick');
              };            
              break;
          }
        }
                
        // show all my children
        $this.tree_filter('show_all_children');

        // hide my siblings
        if (data.siblings_auto)
        {
          switch (data.siblings_auto)
          {
          case 'hide':
            data.my_parent.tree_filter('show_one_child_hide_other', data.structure);
            break;
            
          case 'collapse':
            data.my_parent.tree_filter('collapse_all_children_except_one', data.structure);
            break;
          }
        }
        
      });
    },
    
    collapse : function( ) {
      return this.each(function() {
        var $this = $(this);        
        var data = $this.data('tree_filter');
        
        var animation_callback = null;
        
        if (data.parent_auto && data.parent_auto=='expand')
        {
          if (typeof(data.my_parent) != 'undefined')
          {
/*            
            animation_callback = function() {
              data.my_parent.tree_filter('show_all_children');
            };
*/            
            data.my_parent.tree_filter('show_all_children');
          }
        }
        
// console.log("collapse "+data.structure.id);        
        $this.tree_filter('hide_all_children_animated', animation_callback);
        
        
      });
    },

/*    
    open_path : function( selected_path ) {
      return this.each(function( ) {
        var root_node = $($(this).children()[0]).children('ul');
        root_node.tree_filter('open_path_recursive', selected_path);        
      });
    },
*/    
    ///// NOW INTERNAL METHODS ////////
    
    show_all_children : function( ) {
      return this.each(function() {
        var $this = $(this);
        var data = $this.data('tree_filter');
// console.log("show_all_children "+data.structure.id);
        
        if (data)
        {
          // take care for not yet built children
          switch (data.children_build_state)
          {
            case 'all':
              // already built
              break;
            
            case 'one':
              // detach all children and create in proper order
              expanded_child_root = $this.children().detach();
              
              for (child_index in data.structure.sub)
              {
                var child_structure = data.structure.sub[child_index];
                if (expanded_child_root.attr('id') ==  data.filter_id+'_root_'+child_structure.id)
                {
                  $this.append(expanded_child_root);
                }
                else
                {
                  $this.tree_filter({
                    structure: child_structure,
                    selected_path: [],
                    build_node_callback: data.build_node_callback,
                    parent_auto: data.parent_auto,
                    children_auto: data.children_auto,
                    siblings_auto: data.siblings_auto,
                    hide_collapser: data.hide_collapser,
                    filter_id: data.filter_id,
                    level: data.level + 1,
                    visible: false
                  });
                }
              };
              break;
              
            case 'none':
              for (child_index in data.structure.sub)
              {
                $this.tree_filter({
                  structure: data.structure.sub[child_index],
                  selected_path: [],
                  build_node_callback: data.build_node_callback,
                  parent_auto: data.parent_auto,
                  children_auto: data.children_auto,
                  siblings_auto: data.siblings_auto,
                  hide_collapser: data.hide_collapser,
                  filter_id: data.filter_id,
                  level: data.level + 1,
                  visible: false
                });
              };
              break;
          }
          data.children_build_state = 'all';
          
          switch (data.children_show_state)
          {
            case 'all':
              // nothing to do
  // alert("showing all, but all already expanded");
              break;
            
            case 'one':
              for (child_index in data.structure.sub)
              {
                var child_structure = data.structure.sub[child_index];
                var child_root = $('#'+data.filter_id+'_root_'+child_structure.id);
                if (child_root.css('display') != 'none')
                {
                  // child already visible
                }
                else
                {
  // console.log("sliding down "+child_structure.id);
                  child_root.slideDown(cns_animation_duration);
                }
              };            
              break;
              
            case 'none':
  // console.log("sliding down all li of "+data.structure.id);
              
              $this.children().slideDown(cns_animation_duration);
              break;
          }
          data.children_show_state = 'all';
          data.one_expanded_child_structure = null;
          
          var my_expander = data.my_expander;
          if (my_expander)
          {
            my_expander.removeClass('expander_active');
            my_expander.unbind('click.tree_filter');

            if ( ! data.hide_collapser)
            {
              my_expander.addClass('collapser_active');
              my_expander.bind('click.tree_filter', function() {
                $this.tree_filter('collapse');
              });
            }
          }
        }
      });
    },
    
    hide_all_children_animated : function( callback ) {
      return this.each(function() {
        var $this = $(this);
        var data = $this.data('tree_filter');

// console.log("hide_all_children_animated "+data.structure.id);
        
        if (data)
        {
          $this.children().slideUp(cns_animation_duration, callback);
          data.children_show_state = 'none';
          data.one_expanded_child_structure = null;
          
          var my_expander = data.my_expander;
          if (my_expander)
          {
            my_expander.removeClass('collapser_active');
            my_expander.unbind('click.tree_filter');
            my_expander.addClass('expander_active');
            my_expander.bind('click.tree_filter', function() {
              $this.tree_filter('expand');
            });
          }
        }
      });
    },
    
    hide_all_children_quick : function( ) {
      return this.each(function() {
        var $this = $(this);
        var data = $this.data('tree_filter');

// console.log("hide_all_children_quick "+data.structure.id);
        if (data)
        {
          $this.children().hide();
          data.children_show_state = 'none';
          data.one_expanded_child_structure = null;
          
          var my_expander = data.my_expander;
          if (my_expander)
          {
            my_expander.removeClass('collapser_active');
            my_expander.unbind('click.tree_filter');
            my_expander.addClass('expander_active');
            my_expander.bind('click.tree_filter', function() {
              $this.tree_filter('expand');
            });
          }
        }
      });
    },
    
    show_one_child_hide_other : function( one_expanded_child_structure ) {
      return this.each(function() {
        var $this = $(this);
        var data = $this.data('tree_filter');
// console.log("show_one_child_hide_other "+data.structure.id+' '+one_expanded_child_structure.id);        
        
        if (data)
        {
          switch (data.children_show_state)
          {
            case 'all':
              for (child_index in data.structure.sub)
              {
                var child_structure = data.structure.sub[child_index];
                
                if (child_structure.id == one_expanded_child_structure.id) continue;
                
// console.log("sliding down "+child_structure.id);
                var child_root = $('#'+data.filter_id+'_root_'+child_structure.id);
                child_root.slideUp(cns_animation_duration);                
              };
              break;
            
            case 'one':
if (data.one_expanded_child_structure.id != one_expanded_child_structure.id)
{
  alert('expanding one, but another is already expanded');
}
else
{
  // console.log(data.structure.id+" already ok");
}
              break;
              
            case 'none':
              //alert('expanding one, but none expanded. Expected all.')
              break;
          }
          data.children_show_state = 'one';
          data.one_expanded_child_structure = one_expanded_child_structure;
          
          var my_expander = data.my_expander;
          if (my_expander)
          {
            my_expander.removeClass('collapser_active');
            my_expander.addClass('expander_active');
            my_expander.unbind('click.tree_filter');
            my_expander.bind('click.tree_filter', function() {
              $this.tree_filter('expand');
            });
          }
        }
        
      });
    },
    
    collapse_all_children_except_one : function( one_expanded_child_structure ) {
      return this.each(function() {
        var $this = $(this);
        var data = $this.data('tree_filter');
        
        if (data)
        {
//console.log("collapse_all_children_except_one "+data.structure.id+' '+one_expanded_child_structure.id);        

          switch (data.children_show_state)
          {
            case 'all':
              for (child_index in data.structure.sub)
              {
                var child_structure = data.structure.sub[child_index];
                
                if (child_structure.id == one_expanded_child_structure.id) continue;
                
                var child_node = $('#'+data.filter_id+'_node_'+child_structure.id);
                child_node.tree_filter('hide_all_children_animated');
              };
              break;
            
            case 'one':
if (data.one_expanded_child_structure.id != one_expanded_child_structure.id)
{
  alert('expanding one, but another is already expanded');
}
else
{
  // console.log(data.structure.id+" already ok");
}
              break;
              
            case 'none':
alert('internal error: expanding one, but none expanded. Expected all.');
              break;
          }
          
          // keep current show state
        }
        
      });
    }
/*    
    open_path_recursive : function( selected_path ) {
      return this.each(function( ) {
        var $this = $(this);
        
        var data = $this.data('tree_filter');

        if (data)
        {
          console.log(data);
          $this.tree_filter('expand');
          
          if (selected_path.length>0)
          {
            if (selected_path[0] == data.structure.id)
            {
              // remove myself from selected path
              selected_path.shift();
              
              if (selected_path.length>0)
              {
                // there are children
                var child_structure;

                for (index in data.structure.sub)
                {
                  if (data.structure.sub[index].id == selected_path[0])
                  {
                    child_structure = data.structure.sub[index];
                    break;
                  }
                }

                //$this.tree_filter('show_one_child_hide_other', child_structure);
                
                var child_node = $('#'+data.filter_id+'_node_'+child_structure.id);
                child_node.tree_filter('open_path_recursive', selected_path);                
              }
              else
              {
                // this is the last one
              }
            }
          }
        }
      });
    }
*/    
  };
  
  $.fn.tree_filter = function(method) {
    
    // Method calling logic
    if ( methods[method] ) {
      return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist on jQuery.tooltip' );
    }    
    
    
  };
  
})( jQuery );



/**
 * returns the selected_path as needed for tree_filter
 * 
 * @param struct structure as passed to tree_filter
 * @param current the 'id' to be matched in struct
 */
function get_selected_path_by_id(struct, current)
{
//console.log("enter '"+struct.id+"' ("+current+")");
  var res = [];
  var sub_path;
  var index;
  
  if (typeof(struct.id) != 'undefined'
       && struct.id == current
     )
  {
    //This is the leaf of the selected path
//console.log(res);
    res = [struct.id];
//console.log('struct.id: '+struct.id);        
//console.log(res);
  }
  else if (typeof(struct.sub) != 'undefined')
  {
    for (index in struct.sub)
    {
//console.log("enter recursion");
      sub_path = get_selected_path_by_id(struct.sub[index], current);
//console.log("return from recursion");
      if (sub_path.length > 0)
      {
//console.log("adding self");
        // we are in the selected path
        res = sub_path;
        if (typeof(struct.id) != 'undefined')
        {
//console.log(struct.id);
//console.log(sub_path);
          res.unshift(struct.id);
//console.log("check 2");
//console.log(res);
        }
        
        // stop the loop
        break;
      }
    }
  }
  
//console.log("res of '"+struct.id+"':");
//console.log(res);
  return res;
}


/**
 * returns the selected_path as needed for tree_filter
 * 
 * @param struct structure as passed to tree_filter
 * @param current the 'url' to be matched in struct
 */
function get_selected_path_by_url(struct, current)
{
//console.log("enter '"+struct.id+"' ("+current+")");
  var res = [];
  var sub_path;
  var index;
  
  if (typeof(struct.url) != 'undefined'
       && struct.url == current
     )
  {
    //This is the leaf of the selected path
//console.log(res);
    res = [struct.id];
//console.log('struct.id: '+struct.id);        
//console.log(res);
  }
  else if (typeof(struct.sub) != 'undefined')
  {
    for (index in struct.sub)
    {
//console.log("enter recursion");
      sub_path = get_selected_path_by_url(struct.sub[index], current);
//console.log("return from recursion");
      if (sub_path.length > 0)
      {
//console.log("adding self");
        // we are in the selected path
        res = sub_path;
        if (typeof(struct.id) != 'undefined')
        {
//console.log(struct.id);
//console.log(sub_path);
          res.unshift(struct.id);
//console.log("check 2");
//console.log(res);
        }
        
        // stop the loop
        break;
      }
    }
  }
  
//console.log("res of '"+struct.id+"':");
//console.log(res);
  return res;
}


/* === staticv3_71_filter_object === */

var initial_title;

function switch_to_area(event)
{
  var new_hash = this.hash;

  // hide current, show new area
  $('#multiarea').multiarea('update', new_hash);
  
  // highlight current selection
  $('#filter_for_current_object .css_current').removeClass('css_current');
  $('#_tree_filter_object_navi_item_'+new_hash.substr(1)).addClass('css_current');

  // adjust title of competence card
  adjust_title_of_competence_card(new_hash.substr(1));
  
  // autoclose Competence Card
  // $( "#competence_card_body" ).closable('close');    

  // Trick: remove id from target, so the browser doesn't jump
  var target_node=$(this.hash);
  target_node.removeAttr('id');
  window.location.hash=new_hash;
  target_node.attr('id', new_hash.substr(1));

/*    
  // duration in ms
  //var duration=cns_animation_duration;
  var duration=1000;

  // easing values: swing | linear
  var easing='swing';

  //var target=$(this.hash).offset().top;
  var target=$('#competence_card').offset().top;
  
     // set selector
     if($.browser.safari) var animationSelector='body:not(:animated)';
     else var animationSelector='html:not(:animated)';

     // animate to target and set the hash to the window.location after the animation
     $(animationSelector).animate({ scrollTop: target }, duration, easing, function() {

        // add new hash to the browser location
        //window.location.hash=new_hash;
     });
*/

  // expand filter
  $( "#_tree_filter_object_navi_node_"+new_hash.substr(1) ).tree_filter('expand');
  
  // cancel default click action
  return false;
}

function adjust_title_of_competence_card(id)
{
  var current_caption = $('#_tree_filter_object_navi_root_'+id+' .caption').html();
  if (current_caption && current_caption.length > 0)
  {
    $('#competence_card h1').html(initial_title+', '+current_caption);
  }
  else
  {
    $('#competence_card h1').html(initial_title);
  }
  
}

  







/* === staticv3_71_multiarea === */

/* plugin for controlling of showing/hinding areas of page
 * like accordeon, but without captions
 * Controlling is done from outside, for example through filter_object
 * 
 * options:
 *   id_list: list of IDs of elements that mark areas e.g. ['#latest', 'basisdata', ...]
 */

(function( $ ){
  
  var methods = {
    init : function( options ) {
      
      var settings = {
          current: 0
      };
      
      return this.each(function() {

        // If options exist, lets merge them
        // with our default settings
        if ( options ) { 
          $.extend( settings, options );
        }

        var $this = $(this);
        var data = {
          id_list: settings.id_list
        };
        $this.data('multiarea', data);
        
/*        
        // register callback on hash change
        $(window).hashchange( function(){
          $this.multiarea('update');
        });
*/        
        // trigger once
        $this.multiarea('update');
        
        // scroll to top if the page is called first time with hash
        if (location.hash)
        {
/*          
          if($.browser.safari) var animationSelector='body:not(:animated)';
          else var animationSelector='html:not(:animated)';
*/  
          if($.browser.safari) var animationSelector='body';
          else var animationSelector='html';
  
          $(animationSelector).scrollTop(0);
        }
        
      });
    },
    
    /**
     * display areay identified by hash and hide other
     * @param new_hash optional. If not given, then location.hash is used
     */
    update: function(new_hash) {     
      return this.each(function() {
        var $this = $(this);
        var data = $this.data('multiarea');

        var current;
        if (new_hash)
        {
          current = new_hash;
        }
        else
        {
          current = location.hash;
        }
        
        if (!current) 
        {
          current = data.id_list[0];
        }
        
        var areas = data.id_list;
        var found = false;
        for (index in areas)
        {
          var area_id = areas[index];
          if (area_id == current)
          {
            $(area_id).show();
            //$(area_id).slideDown(cns_animation_duration);
            found = true;
          }
          else
          {
            $(area_id).hide();
            //$(area_id).slideUp(cns_animation_duration);
          }
        };
        
        if (!found)
        {
          $(data.id_list[0]).show();
          //$(data.id_list[0]).slideDown(cns_animation_duration);
        }
        
      });
    }
        
  };
  
  $.fn.multiarea = function(method) {
    
    // Method calling logic
    if ( methods[method] ) {
      return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist on jQuery.tooltip' );
    }    
    
    
  };
  
})( jQuery );

/* === staticv3_72_panes === */

/* lightwight "tabs" plugin whith slide animation
 * options:
 *   captions: list of elements with subelement "a" that has got a href with link to id of the body
 *   current: index of the current tab (0-based)
 */

(function( $ ){
  
  var methods = {
    init : function( options ) {
      
      var settings = {
          captions: $( ".multiportlet_caption li", this ),
          current: 0
      };
      
      return this.each(function() {
        // If options exist, lets merge them
        // with our default settings
        if ( options ) { 
          $.extend( settings, options );
        }

        var current = settings.current;
        
        var $this = $(this);
        var data = {
          captions: settings.captions,
          current: settings.current
        };
        $this.data('tabs', data);
          
        var tabs = settings.captions;
        tabs.each(function(index)
        {
          var tab = tabs[index];
          
          $('a', tab).bind('click.tabs', function() {
            $this.panes('select', index);
            return false;
          });
          
        });
        
        // minimize body-height
       
       // set auto-height
       $($('a',$(tabs[current])).attr('href')).height("auto");
       //get current height
       var curr_height = $($('a',$(tabs[current])).attr('href')).height();
       // set all to current height
       $('div.multiportlet_bodies > div',$this).height("1px");
       // set current to auto-height
       $($('a',$(tabs[current])).attr('href')).height("auto");       
         
      });
    },
    
    select: function( index ) {     
      return this.each(function() {
        var $this = $(this);
        var data = $this.data('tabs');
        if (index != data.current)
        {
          var tabs = data.captions;
          
          $(tabs[data.current]).removeClass('current');
          $(tabs[index]).addClass('current');
          tabs.each(function(i)
          {
            $(tabs[i]).removeClass('left_of_current');
            $(tabs[i]).removeClass('right_of_current');
            if (i < index)
            {
              $(tabs[i]).addClass('left_of_current');
            }
            else if (i > index)
            {
              $(tabs[i]).addClass('right_of_current');
            }
          });
          
          var current_body = $($('a', tabs[data.current]).attr('href'));
          var selected_body = $($('a', tabs[index]).attr('href'));
          
          var current = data.current;          
          data.current = index;
          
          var animation_options = {
            duration: cns_animation_duration,
            easing: 'easeInOutQuad'
          };

          // now animate
          var step=10; // = 100% / 10
          if (current < index)
          {
            current_body.css('left', ((current+0)*(-step)).toString()+'%');
            current_body.animate({
              left: ((current+1)*(-step)).toString()+'%'
            }, animation_options);
            
            selected_body.css('left', ((index-1)*(-step)).toString()+'%');
            selected_body.animate({
              left: ((index+0)*(-step)).toString()+'%'
            }, animation_options);

          }
          else
          {
            current_body.css('left', ((current+0)*(-step)).toString()+'%');
            current_body.animate({
              left: ((current-1)*(-step)).toString()+'%'            
            }, animation_options);
            
            selected_body.css('left', ((index+1)*(-step)).toString()+'%');
            selected_body.animate({
              left: ((index+0)*(-step)).toString()+'%'
            }, animation_options);
          }
          
          
          // minimize body-height  
          //first step , set auto-height
          selected_body.height("auto");
          //second step, get div height
          var curr_height = selected_body.height();
          
          $('div.multiportlet_bodies > div',$this).each(function(key,value){           
            if( $(value).attr("id") == selected_body.attr("id") )
            { 
              $(value).css('height','auto');
            }
            else if($(value).attr("id") == current_body.attr("id"))
            {
              // animate current to fixed-height
              $(value).animate({
                height: "1px"
              });
              //$(value).css('height',curr_height);
            }
            else
            {
              // set other to fixed-height
              $(value).css('height',"1px");
            }
          });
          
          
        }
        
        
      });
    }
        
  };
  
  $.fn.panes = function(method) {
    
    // Method calling logic
    if ( methods[method] ) {
      return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist on jQuery.tooltip' );
    }    
    
    
  };
  
})( jQuery );

/* === staticv3_80_history === */

// JQuery plugin visited_pages_history
// needed get_cookie() and set_cookie() functions

(function( $ ){
  var version = '1.1';
  var cookie_name = 'last_viewed';
  
  /* maximal number of history items to remember */
  var max_pages = 10;
  
  var cookie_object_dummy = {
      'ver' : version,
      'list' : []
  };
  
  var methods = {
    init : function( options ) {
    },

    /**
     * View visited pages as a list in a portlet
     * @param caption for the portlet header
     */
    view_list : function( caption ) {
      return this.each(function() {
        var $this = $(this);

        var cookie = get_cookie(cookie_name);

        if (cookie)
        {
          var cookie_object = JSON.parse(cookie);
          
          if (cookie_object.ver == version)
          {

            var history_list = cookie_object.list;
  
            if (history_list && history_list.length > 0)
            {
              $this.after('\
                <div class="css_portlet clearfix">\
                  <div class="headline clearfix">\
                    <strong>'+caption+'</strong>\
                  </div>\
                  <ul class="css_visited_pages_history clearfix">\
                  </ul>\
                </div>\
              ');
              
              for (index in history_list)
              {
                $( ".css_visited_pages_history" ).append('\
                    <li><span class="'+history_list[index].icon+'"></span><a href="'+history_list[index].url+'">'+history_list[index].title+'</a></li>\
                ');
              }
            }
          }
        }
        
        // cleanup
        $this.remove();
        
      });
    },
    
    /**
     * View visited pages as a breadcrumb
     * @param max maximal number of items in the list to display
     */
    view_as_breadcrumb : function( max_list_size ) {
      var max_char_size = 30;
      
      return this.each(function() {
        var $this = $(this);
        
        var cookie = get_cookie(cookie_name);

        if (cookie)
        {
          var cookie_object = JSON.parse(cookie);
          
          if (cookie_object.ver == version)
          {

            var history_list = cookie_object.list;
  
            if (history_list && history_list.length > 0)
            {
              var my_root = $('\
                  <ul class="css_breadcrumb clearfix">\
                  </ul>\
                ');
              
              var list_length = history_list.length;
                
              if (list_length > max_list_size)
              {
                list_length = max_list_size;
              }
              var index = list_length-1;
              for (index=list_length-1; index>=0; index--)
              {
                var short_title = html_decode(history_list[index].title);
                var title = '';
                if (short_title.length > max_char_size)
                {
                  short_title = html_encode(short_title.substr(0,max_char_size-3)+'...');
                  title = ' title="'+history_list[index].title+'"';
                }
                else
                {
                  short_title = html_encode(short_title);
                }
                
                var item_html = '<li><a href="'+history_list[index].url+'"'+title+'>'+short_title+'</a></li>';
                my_root.append(item_html);
              }
              
              $this.replaceWith(my_root);
                            
            }
          }
        }
        
      });
    },
    
    /**
     * Add current page to visited pages history
     * @param title string to display as the title of the current page in history
     * @param icon_class CSS class to be used for icon
     */
    add : function( title, icon_class ) {
        // we do not use document.location.href to avoid taking the location.hash into account
        var url = document.location.protocol+'//'
                 +document.location.host
                 +document.location.pathname
                 +document.location.search;

        var new_item = {
          'title': title,
          'url': url,
          'icon': icon_class
        };

        // init
        var cookie_object = cookie_object_dummy;
        
        var cookie = get_cookie(cookie_name);

        if (cookie)
        {
          cookie_object = JSON.parse(cookie);
          if (cookie_object.ver != version)
          {
            // version doesn't match => reset
            cookie_object = cookie_object_dummy;
          }
        }
        
        var history_list = cookie_object.list;
        
        // remove if already there
        for (index in history_list)
        {
          if (history_list[index].url == url)
          {
            // remove
            history_list.splice(index,1);
            break;
          }
        }
        // add at the beginning
        history_list.splice(0,0,new_item);
        
        // crop to max
        history_list.splice(max_pages-1, 99);
        
        set_cookie(cookie_name, JSON.stringify(cookie_object));
    }
    
  };
  
  $.fn.visited_pages_history = function(method) {
    
    // Method calling logic
    if ( methods[method] ) {
      return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist on jQuery.tooltip' );
    }    
    
    
  };
  
})( jQuery );


/* === staticv3_80_input_hint === */

/**
* @author Remy Sharp
* @url http://remysharp.com/2007/01/25/jquery-tutorial-text-box-hints/
*/

(function ($) {

$.fn.hint = function (blurClass) {
  if (!blurClass) { 
    blurClass = 'blur';
  }
    
  return this.each(function () {
    // get jQuery version of 'this'
    var $input = $(this),
    
    // capture the rest of the variable to allow for reuse
      title = $input.attr('title'),
      $form = $(this.form),
      $win = $(window);

    function remove() {
      if ($input.val() === title && $input.hasClass(blurClass)) {
        $input.val('').removeClass(blurClass);
      }
    }

    // only apply logic if the element has the attribute
    if (title) { 
      // on blur, set value to title attr if text is blank
      $input.blur(function () {
        if (this.value === '') {
          $input.val(title).addClass(blurClass);
        }
      }).focus(remove).blur(); // now change all inputs to title
      
      // clear the pre-defined text when form is submitted
      $form.submit(remove);
      $win.unload(remove); // handles Firefox's autocomplete
    }
  });
};

})(jQuery);

/* === staticv3_80_portlet === */

/*  jQuery plugin "closable" */

(function( $ ){
  var methods = {
    init : function( options ) {

      var settings = {
        'opener' : '',
        'closer' : ''
      };
      
      return this.each(function() {
        // If options exist, lets merge them
        // with our default settings
        if ( options ) { 
          $.extend( settings, options );
        }
        
        var $this = $(this);

        $this.data('closable', {
          opener: settings.opener,
          closer: settings.closer
        });
        
        settings.opener.bind('click.open_body', function() {
          $this.closable('open');
        });


        settings.closer.bind('click.close_body', function() {
          $this.closable('close');
        });        
        
      });
    },
    
    open : function( ) {
      return this.each(function() {
        var $this = $(this);
        var data = $this.data('closable');
        
        $this.slideDown(cns_animation_duration);
        data.opener.hide();
        data.closer.show();
      });
    },
    
    close : function( ) {
      return this.each(function() {
        var $this = $(this);
        var data = $this.data('closable');
        
        $this.slideUp(cns_animation_duration);
        data.opener.show();
        data.closer.hide();
      });
    }
  };
  
  $.fn.closable = function(method) {
    
    // Method calling logic
    if ( methods[method] ) {
      return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist on jQuery.tooltip' );
    }    
    
    
  };
  
})( jQuery );


/**
 * AJAX Upload ( http://valums.com/ajax-upload/ ) 
 * Copyright (c) Andrew Valums
 * Licensed under the MIT license 
 */
(function () {
    /**
     * Attaches event to a dom element.
     * @param {Element} el
     * @param type event name
     * @param fn callback This refers to the passed element
     */
    function addEvent(el, type, fn){
        if (el.addEventListener) {
            el.addEventListener(type, fn, false);
        } else if (el.attachEvent) {
            el.attachEvent('on' + type, function(){
                fn.call(el);
          });
      } else {
            throw new Error('not supported or DOM not loaded');
        }
    }   
    
    /**
     * Attaches resize event to a window, limiting
     * number of event fired. Fires only when encounteres
     * delay of 100 after series of events.
     * 
     * Some browsers fire event multiple times when resizing
     * http://www.quirksmode.org/dom/events/resize.html
     * 
     * @param fn callback This refers to the passed element
     */
    function addResizeEvent(fn){
        var timeout;
               
      addEvent(window, 'resize', function(){
            if (timeout){
                clearTimeout(timeout);
            }
            timeout = setTimeout(fn, 100);                        
        });
    }    
    
    // Needs more testing, will be rewriten for next version        
    // getOffset function copied from jQuery lib (http://jquery.com/)
    if (document.documentElement.getBoundingClientRect){
        // Get Offset using getBoundingClientRect
        // http://ejohn.org/blog/getboundingclientrect-is-awesome/
        var getOffset = function(el){
            var box = el.getBoundingClientRect();
            var doc = el.ownerDocument;
            var body = doc.body;
            var docElem = doc.documentElement; // for ie 
            var clientTop = docElem.clientTop || body.clientTop || 0;
            var clientLeft = docElem.clientLeft || body.clientLeft || 0;
             
            // In Internet Explorer 7 getBoundingClientRect property is treated as physical,
            // while others are logical. Make all logical, like in IE8. 
            var zoom = 1;            
            if (body.getBoundingClientRect) {
                var bound = body.getBoundingClientRect();
                zoom = (bound.right - bound.left) / body.clientWidth;
            }
            
            if (zoom > 1) {
                clientTop = 0;
                clientLeft = 0;
            }
            
            var top = box.top / zoom + (window.pageYOffset || docElem && docElem.scrollTop / zoom || body.scrollTop / zoom) - clientTop, left = box.left / zoom + (window.pageXOffset || docElem && docElem.scrollLeft / zoom || body.scrollLeft / zoom) - clientLeft;
            
            return {
                top: top,
                left: left
            };
        };        
    } else {
        // Get offset adding all offsets 
        var getOffset = function(el){
            var top = 0, left = 0;
            do {
                top += el.offsetTop || 0;
                left += el.offsetLeft || 0;
                el = el.offsetParent;
            } while (el);
            
            return {
                left: left,
                top: top
            };
        };
    }
    
    /**
     * Returns left, top, right and bottom properties describing the border-box,
     * in pixels, with the top-left relative to the body
     * @param {Element} el
     * @return {Object} Contains left, top, right,bottom
     */
    function getBox(el){
        var left, right, top, bottom;
        var offset = getOffset(el);
        left = offset.left;
        top = offset.top;
        
        right = left + el.offsetWidth;
        bottom = top + el.offsetHeight;
        
        return {
            left: left,
            right: right,
            top: top,
            bottom: bottom
        };
    }
    
    /**
     * Helper that takes object literal
     * and add all properties to element.style
     * @param {Element} el
     * @param {Object} styles
     */
    function addStyles(el, styles){
        for (var name in styles) {
            if (styles.hasOwnProperty(name)) {
                el.style[name] = styles[name];
            }
        }
    }
        
    /**
     * Function places an absolutely positioned
     * element on top of the specified element
     * copying position and dimentions.
     * @param {Element} from
     * @param {Element} to
     */    
    function copyLayout(from, to){
      var box = getBox(from);
        
        addStyles(to, {
          position: 'absolute',                    
          left : box.left + 'px',
          top : box.top + 'px',
          width : from.offsetWidth + 'px',
          height : from.offsetHeight + 'px'
      });        
    }

    /**
    * Creates and returns element from html chunk
    * Uses innerHTML to create an element
    */
    var toElement = (function(){
        var div = document.createElement('div');
        return function(html){
            div.innerHTML = html;
            var el = div.firstChild;
            return div.removeChild(el);
        };
    })();
            
    /**
     * Function generates unique id
     * @return unique id 
     */
    var getUID = (function(){
        var id = 0;
        return function(){
            return 'ValumsAjaxUpload' + id++;
        };
    })();        
 
    /**
     * Get file name from path
     * @param {String} file path to file
     * @return filename
     */  
    function fileFromPath(file){
        return file.replace(/.*(\/|\\)/, "");
    }
    
    /**
     * Get file extension lowercase
     * @param {String} file name
     * @return file extenstion
     */    
    function getExt(file){
        return (-1 !== file.indexOf('.')) ? file.replace(/.*[.]/, '') : '';
    }

    function hasClass(el, name){        
        var re = new RegExp('\\b' + name + '\\b');        
        return re.test(el.className);
    }    
    function addClass(el, name){
        if ( ! hasClass(el, name)){   
            el.className += ' ' + name;
        }
    }    
    function removeClass(el, name){
        var re = new RegExp('\\b' + name + '\\b');                
        el.className = el.className.replace(re, '');        
    }
    
    function removeNode(el){
        el.parentNode.removeChild(el);
    }

    /**
     * Easy styling and uploading
     * @constructor
     * @param button An element you want convert to 
     * upload button. Tested dimentions up to 500x500px
     * @param {Object} options See defaults below.
     */
    window.AjaxUpload = function(button, options){
        this._settings = {
            // Location of the server-side upload script
            action: 'upload.php',
            // File upload name
            name: 'userfile',
            // Select & upload multiple files at once FF3.6+, Chrome 4+
            multiple: false,
            // Additional data to send
            data: {},
            // Submit file as soon as it's selected
            autoSubmit: true,
            // The type of data that you're expecting back from the server.
            // html and xml are detected automatically.
            // Only useful when you are using json data as a response.
            // Set to "json" in that case. 
            responseType: false,
            // Class applied to button when mouse is hovered
            hoverClass: 'hover',
            // Class applied to button when button is focused
            focusClass: 'focus',
            // Class applied to button when AU is disabled
            disabledClass: 'disabled',            
            // When user selects a file, useful with autoSubmit disabled
            // You can return false to cancel upload      
            onChange: function(file, extension){
            },
            // Callback to fire before file is uploaded
            // You can return false to cancel upload
            onSubmit: function(file, extension){
            },
            // Fired when file upload is completed
            // WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
            onComplete: function(file, response){
            }
        };
                        
        // Merge the users options with our defaults
        for (var i in options) {
            if (options.hasOwnProperty(i)){
                this._settings[i] = options[i];
            }
        }
                
        // button isn't necessary a dom element
        if (button.jquery){
            // jQuery object was passed
            button = button[0];
        } else if (typeof button == "string") {
            if (/^#.*/.test(button)){
                // If jQuery user passes #elementId don't break it          
                button = button.slice(1);                
            }
            
            button = document.getElementById(button);
        }
        
        if ( ! button || button.nodeType !== 1){
            throw new Error("Please make sure that you're passing a valid element"); 
        }
                
        if ( button.nodeName.toUpperCase() == 'A'){
            // disable link                       
            addEvent(button, 'click', function(e){
                if (e && e.preventDefault){
                    e.preventDefault();
                } else if (window.event){
                    window.event.returnValue = false;
                }
            });
        }
                    
        // DOM element
        this._button = button;        
        // DOM element                 
        this._input = null;
        // If disabled clicking on button won't do anything
        this._disabled = false;
        
        // if the button was disabled before refresh if will remain
        // disabled in FireFox, let's fix it
        this.enable();        
        
        this._rerouteClicks();
    };
    
    // assigning methods to our class
    AjaxUpload.prototype = {
        setData: function(data){
            this._settings.data = data;
        },
        disable: function(){            
            addClass(this._button, this._settings.disabledClass);
            this._disabled = true;
            
            var nodeName = this._button.nodeName.toUpperCase();            
            if (nodeName == 'INPUT' || nodeName == 'BUTTON'){
                this._button.setAttribute('disabled', 'disabled');
            }            
            
            // hide input
            if (this._input){
                if (this._input.parentNode) {
                    // We use visibility instead of display to fix problem with Safari 4
                    // The problem is that the value of input doesn't change if it 
                    // has display none when user selects a file
                    this._input.parentNode.style.visibility = 'hidden';
                }
            }
        },
        enable: function(){
            removeClass(this._button, this._settings.disabledClass);
            this._button.removeAttribute('disabled');
            this._disabled = false;
            
        },
        /**
         * Creates invisible file input 
         * that will hover above the button
         * <div><input type='file' /></div>
         */
        _createInput: function(){ 
            var self = this;
                        
            var input = document.createElement("input");
            input.setAttribute('type', 'file');
            input.setAttribute('name', this._settings.name);
            if(this._settings.multiple) input.setAttribute('multiple', 'multiple');
            
            addStyles(input, {
                'position' : 'absolute',
                // in Opera only 'browse' button
                // is clickable and it is located at
                // the right side of the input
                'right' : 0,
                'margin' : 0,
                'padding' : 0,
                'fontSize' : '480px',
                // in Firefox if font-family is set to
                // 'inherit' the input doesn't work
                'fontFamily' : 'sans-serif',
                'cursor' : 'pointer'
            });            

            var div = document.createElement("div");                        
            addStyles(div, {
                'display' : 'block',
                'position' : 'absolute',
                'overflow' : 'hidden',
                'margin' : 0,
                'padding' : 0,                
                'opacity' : 0,
                // Make sure browse button is in the right side
                // in Internet Explorer
                'direction' : 'ltr',
                //Max zIndex supported by Opera 9.0-9.2
                'zIndex': 2147483583
            });
            
            // Make sure that element opacity exists.
            // Otherwise use IE filter            
            if ( div.style.opacity !== "0") {
                if (typeof(div.filters) == 'undefined'){
                    throw new Error('Opacity not supported by the browser');
                }
                div.style.filter = "alpha(opacity=0)";
            }            
            
            addEvent(input, 'change', function(){
                 
                if ( ! input || input.value === ''){                
                    return;                
                }
                            
                // Get filename from input, required                
                // as some browsers have path instead of it          
                var file = fileFromPath(input.value);
                                
                if (false === self._settings.onChange.call(self, file, getExt(file))){
                    self._clearInput();                
                    return;
                }
                
                // Submit form when value is changed
                if (self._settings.autoSubmit) {
                    self.submit();
                }
            });            

            addEvent(input, 'mouseover', function(){
                addClass(self._button, self._settings.hoverClass);
            });
            
            addEvent(input, 'mouseout', function(){
                removeClass(self._button, self._settings.hoverClass);
                removeClass(self._button, self._settings.focusClass);
                
                if (input.parentNode) {
                    // We use visibility instead of display to fix problem with Safari 4
                    // The problem is that the value of input doesn't change if it 
                    // has display none when user selects a file
                    input.parentNode.style.visibility = 'hidden';
                }
            });   
                        
            addEvent(input, 'focus', function(){
                addClass(self._button, self._settings.focusClass);
            });
            
            addEvent(input, 'blur', function(){
                removeClass(self._button, self._settings.focusClass);
            });
            
          div.appendChild(input);
            document.body.appendChild(div);
              
            this._input = input;
        },
        _clearInput : function(){
            if (!this._input){
                return;
            }            
                             
            // this._input.value = ''; Doesn't work in IE6                               
            removeNode(this._input.parentNode);
            this._input = null;                                                                   
            this._createInput();
            
            removeClass(this._button, this._settings.hoverClass);
            removeClass(this._button, this._settings.focusClass);
        },
        /**
         * Function makes sure that when user clicks upload button,
         * the this._input is clicked instead
         */
        _rerouteClicks: function(){
            var self = this;
            
            // IE will later display 'access denied' error
            // if you use using self._input.click()
            // other browsers just ignore click()

            addEvent(self._button, 'mouseover', function(){
                if (self._disabled){
                    return;
                }
                                
                if ( ! self._input){
                  self._createInput();
                }
                
                var div = self._input.parentNode;                            
                copyLayout(self._button, div);
                div.style.visibility = 'visible';
                                
            });
            
            
            // commented because we now hide input on mouseleave
            /**
             * When the window is resized the elements 
             * can be misaligned if button position depends
             * on window size
             */
            //addResizeEvent(function(){
            //    if (self._input){
            //        copyLayout(self._button, self._input.parentNode);
            //    }
            //});            
                                         
        },
        /**
         * Creates iframe with unique name
         * @return {Element} iframe
         */
        _createIframe: function(){
            // We can't use getTime, because it sometimes return
            // same value in safari :(
            var id = getUID();            
             
            // We can't use following code as the name attribute
            // won't be properly registered in IE6, and new window
            // on form submit will open
            // var iframe = document.createElement('iframe');
            // iframe.setAttribute('name', id);                        
 
            var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />');
            // src="javascript:false; was added
            // because it possibly removes ie6 prompt 
            // "This page contains both secure and nonsecure items"
            // Anyway, it doesn't do any harm.            
            iframe.setAttribute('id', id);
            
            iframe.style.display = 'none';
            document.body.appendChild(iframe);
            
            return iframe;
        },
        /**
         * Creates form, that will be submitted to iframe
         * @param {Element} iframe Where to submit
         * @return {Element} form
         */
        _createForm: function(iframe){
            var settings = this._settings;
                        
            // We can't use the following code in IE6
            // var form = document.createElement('form');
            // form.setAttribute('method', 'post');
            // form.setAttribute('enctype', 'multipart/form-data');
            // Because in this case file won't be attached to request                    
            var form = toElement('<form method="post" enctype="multipart/form-data"></form>');
                        
            form.setAttribute('action', settings.action);
            form.setAttribute('target', iframe.name);                                   
            form.style.display = 'none';
            document.body.appendChild(form);
            
            // Create hidden input element for each data key
            for (var prop in settings.data) {
                if (settings.data.hasOwnProperty(prop)){
                    var el = document.createElement("input");
                    el.setAttribute('type', 'hidden');
                    el.setAttribute('name', prop);
                    el.setAttribute('value', settings.data[prop]);
                    form.appendChild(el);
                }
            }
            return form;
        },
        /**
         * Gets response from iframe and fires onComplete event when ready
         * @param iframe
         * @param file Filename to use in onComplete callback 
         */
        _getResponse : function(iframe, file){            
            // getting response
            var toDeleteFlag = false, self = this, settings = this._settings;   
               
            addEvent(iframe, 'load', function(){                
                
                if (// For Safari 
                    iframe.src == "javascript:'%3Chtml%3E%3C/html%3E';" ||
                    // For FF, IE
                    iframe.src == "javascript:'<html></html>';"){                                                                        
                        // First time around, do not delete.
                        // We reload to blank page, so that reloading main page
                        // does not re-submit the post.
                        
                        if (toDeleteFlag) {
                            // Fix busy state in FF3
                            setTimeout(function(){
                                removeNode(iframe);
                            }, 0);
                        }
                                                
                        return;
                }
                
                var doc = iframe.contentDocument ? iframe.contentDocument : window.frames[iframe.id].document;
                
                // fixing Opera 9.26,10.00
                if (doc.readyState && doc.readyState != 'complete') {
                   // Opera fires load event multiple times
                   // Even when the DOM is not ready yet
                   // this fix should not affect other browsers
                   return;
                }
                
                // fixing Opera 9.64
                if (doc.body && doc.body.innerHTML == "false") {
                    // In Opera 9.64 event was fired second time
                    // when body.innerHTML changed from false 
                    // to server response approx. after 1 sec
                    return;
                }
                
                var response;
                
                if (doc.XMLDocument) {
                    // response is a xml document Internet Explorer property
                    response = doc.XMLDocument;
                } else if (doc.body){
                    // response is html document or plain text
                    response = doc.body.innerHTML;
                    
                    if (settings.responseType && settings.responseType.toLowerCase() == 'json') {
                        // If the document was sent as 'application/javascript' or
                        // 'text/javascript', then the browser wraps the text in a <pre>
                        // tag and performs html encoding on the contents.  In this case,
                        // we need to pull the original text content from the text node's
                        // nodeValue property to retrieve the unmangled content.
                        // Note that IE6 only understands text/html
                        if (doc.body.firstChild && doc.body.firstChild.nodeName.toUpperCase() == 'PRE') {
                            doc.normalize();
                            response = doc.body.firstChild.firstChild.nodeValue;
                        }
                        
                        if (response) {
                            response = eval("(" + response + ")");
                        } else {
                            response = {};
                        }
                    }
                } else {
                    // response is a xml document
                    response = doc;
                }
                
                settings.onComplete.call(self, file, response);
                
                // Reload blank page, so that reloading main page
                // does not re-submit the post. Also, remember to
                // delete the frame
                toDeleteFlag = true;
                
                // Fix IE mixed content issue
                iframe.src = "javascript:'<html></html>';";
            });            
        },        
        /**
         * Upload file contained in this._input
         */
        submit: function(){                        
            var self = this, settings = this._settings;
            
            if ( ! this._input || this._input.value === ''){                
                return;                
            }
                                    
            var file = fileFromPath(this._input.value);
            
            // user returned false to cancel upload
            if (false === settings.onSubmit.call(this, file, getExt(file))){
                this._clearInput();                
                return;
            }
            
            // sending request    
            var iframe = this._createIframe();
            var form = this._createForm(iframe);
            
            // assuming following structure
            // div -> input type='file'
            removeNode(this._input.parentNode);            
            removeClass(self._button, self._settings.hoverClass);
            removeClass(self._button, self._settings.focusClass);
                        
            form.appendChild(this._input);
                        
            form.submit();

            // request set, clean up                
            removeNode(form); form = null;                          
            removeNode(this._input); this._input = null;            
            
            // Get response from iframe and fire onComplete event when ready
            this._getResponse(iframe, file);            

            // get ready for next request            
            this._createInput();
        }
    };
})(); 


/* cns specific methods*/


function fileupload_set_image(container_selector,image)
{
  container = $(container_selector);

  image.load(function(){
    
    image.center(
        {
          "withScrolling": false, 
          "inside"       : container 
        }
    );
    
  });
  container.html(image);
}

function fileupload_get_image(url)
{ 
  if( ! url  || url == 'anonymous')
  {
    image = $('<img src="/gfx/classic/anonymous.png">');
  }
  else if( url == 'loader')
  {
    image = $('<img src="' + config_ajaxloadergfx + '">');
  }
  else
  {
    image = $('<img src="' + url + '">');
  }
  
  return image;
}


function fileupload_set_hidden_field(fileupload_container,key,value,id)
{
  container = $(fileupload_container);
  input_hidden = $('input[type="hidden"][id="' + id + '"]',container);
  input_hidden.attr('name',key);
  input_hidden.attr('value',value);
}


function fileupload_clear_data(fileupload_container)
{
  fileupload_set_hidden_field(
      fileupload_container,
      '',
      '',
      'file_id_container'
  );
  fileupload_set_hidden_field(
      fileupload_container,
      '',
      '',
      'new_object_flag_container'
  );
  
  fileupload_set_image(
      $(".fileupload_image_placeholder",fileupload_container),
      fileupload_get_image()
  );
  
}


function fileuploader_init( selector , controller)
{
  
  input_file = $( selector  ); 
  input_file_name = input_file.attr('name');
  
  var fileupload_wrapper = $('<div class="fileupload_wrapper">');
  the_button             = $('<div id="upload_image" class="fileupload_button">');
  the_hidden_field       = $('<input type="hidden" id="file_id_container">');
  the_hidden_field2      = $('<input type="hidden" id="new_object_flag_container">');
  
  input_file.replaceWith(
    fileupload_wrapper
  );
  
  fileupload_wrapper.append('<div class="fileupload_image_placeholder">');
  fileupload_wrapper.append(the_button);
  fileupload_wrapper.append(the_hidden_field);
  fileupload_wrapper.append(the_hidden_field2);
 
  var image_container = $(".fileupload_image_placeholder", fileupload_wrapper);
  
  anonymous = fileupload_get_image();
  
  anonymous.css("margin", "12px");
  
  image_container.html(
     anonymous
  );
  
  
  //"object[s_retp_file_has_ass_1_filename_flnm]",
  new AjaxUpload( the_button, {
    
    action: controller,
    name: "object[s_retp_file_has_ass_1_filename_flnm]",
    data: { "name": input_file_name},
    
    onChange : function(file , ext)
    {
      if (! (ext && /^(jpg|png|jpeg|gif)$/i.test(ext)))
      {
        alert( javascript_fileupload_invalid_file_type );
        return false;
      }
      else
      {
        fileupload_set_image(
          image_container,
          fileupload_get_image("loader")
        );
      }
      
    },
    
    onComplete: function(file, response) 
    {
      res = JSON.parse(response);
      
      fileupload_set_hidden_field(
          fileupload_wrapper,
          res.name,
          res.value,
          'file_id_container'
      );
      
      fileupload_set_hidden_field(
          fileupload_wrapper,
          'file_upload_controller_NEW_FILE',
          res.new_object,
          'new_object_flag_container'
      );
      
      fileupload_set_image(
          image_container,
          fileupload_get_image(res.url)
      );

    }
    
    
  });
  
  
}
/* 
 * dci advertising
 * used by module_dci.cns
 * 
 */

/* === staticv3_90_google === */

/**
 * @author sherting
 */
function google_initialize() {
	var gsControl = new google.search.SearchControl();
	var gsOptions = new google.search.SearcherOptions();
	gsOptions.setExpandMode(google.search.SearchControl.EXPAND_MODE_OPEN);
	gsControl.addSearcher(new google.search.WebSearch(), gsOptions);
	//gsControl.setOnKeepCallback(this, cnsKeepHandler,"&Uuml;bernehmen");
	gsControl.draw(document.getElementById("gwsearchcontrol"));
	gsControl.execute(searchstring);
}
function cnsKeepHandler(result) {
	$('google_url').value = result.url;
	$('form_externalurl').submit();
}
/* === staticv3_90_googlemap === */

var counter_all = 0;
var counter_index = 0;
var descrcount = 0;
var points = new Array();
var description  = new Array();
var link = new Array();
var pic = new Array();
var type = new Array();
var iconurl = null;

function createMarker(point,html)
{
  var icon = new GIcon();
    icon.image =iconImageUrl;
    icon.iconSize = new GSize(32, 37);
    icon.shadow = iconShadowUrl;
    icon.shadowSize = new GSize(51,37);
    icon.iconAnchor = new GPoint(16,35);
    icon.infoWindowAnchor = new GPoint(32, 0);
  var marker = new GMarker(point,icon);
//	var marker = new GMarker(point);
  GEvent.addListener(marker, 'click', function() {marker.openInfoWindowHtml(html);});
  return marker;
}//createMarker(point,html)

function getPoint(addr,descr,linke,pice,typee,quantity)
{//getPoint(adresse für geocoding,adresse für beschreibung,bild url,csprofil url,priorität);
  var geocoder = new GClientGeocoder();
  type[descrcount]=typee;
  link[descrcount]=linke;
  pic[descrcount]=pice;
  description[descrcount]=descr;
  descrcount=descrcount+1;
  geocoder.getLatLng(addr,function(point)
      {
        if (point)
        {
          points[counter_index]=point;
          counter_index++;
        }
        counter_all++;
        if(counter_all==quantity)
        {
          setmarker();
        }
      });
}//getPoint(addr,descr)

function setmarker()
{
  var bounds = new google.maps.LatLngBounds();
  var map = new GMap2(document.getElementById("map-container"));
  var checkedtwins = new Array();
  var checkedpoints = new Array();
  var checkcount =0;
  var index =0;
  var maxtype =0;
  for (var i=0;i<points.length;i++)
  {
    equalindex = new Array()
    for (var k=0;k<points.length;k++)
    {//findet alle identsichen points
      if(points[i].lat()==points[k].lat() && points[i].lng()==points[k].lng())
      {
        equalindex.push(k);
      }
    }
    maxtype=0;
    index=0;
    //gleiche punkte sortieren
    var changer;
    for (var k =0;k<equalindex.length;k++)
    {
      for(var j = k+1;j<equalindex.length;j++)
      {
        if(type[equalindex[k]]<type[equalindex[j]])
        {//nicht einfach tauschen sondern reihenfolge beibehalten
          for(var y = j;y>k;y--)
          {
            changer = equalindex[y-1];
            equalindex[y-1] = equalindex[y];
            equalindex[y] = changer;
          }
        }
      }
    }
    checkedtwins[i]=new Array();
    if(equalindex.length>1)
    {// wenn points[i] wichtigster ist, dann auf liste der marker die generiert werden
      if(i==equalindex[0])
        {
          checkedpoints[checkcount]=equalindex[0];
          checkcount++;
          for(var k=0;k<equalindex.length;k++)
            {
              if(equalindex[k]!=index) checkedtwins[i].push(equalindex[k]);
            }
        }
    }
    else
    {//keine gleichen punkte -> auf liste
        checkedpoints[checkcount]=i;
        checkcount++;
        checkedtwins[i].push(equalindex[0]);
    }
  }
  
  for(j=0;j<points.length;j++)
  {
    var flag = false;
    for(var k=0;k<checkedpoints.length;k++)
    { //jeden marker nur 1 mal erstellen
      if(checkedpoints[k]==j) flag = true;
    }
    if (flag)
    {
      var marker = new Array();
      var html = "";
      if(checkedtwins[j].length>1) html+="<div style=\"width:300px;height:300px;overflow:auto;\">";
      for (var i=0;i<checkedtwins[j].length;i++)
        {
           html += "<p><a href=\""+link[checkedtwins[j][i]]+"\" target=\"_blank\" align=\"left\"><img border=\"0\" src=\""+pic[checkedtwins[j][i]]+"\"></a></p>"+description[checkedtwins[j][i]];
           if(checkedtwins[j].length>1 && checkedtwins[j].length-1!==i) html +="<hr style=\" background: lightgrey;color:lightgrey; height:15px; width:280px;\"> ";
        }
      if(checkedtwins[j].length>1) html+="</div>";
      marker[j] = createMarker(points[j],html)     
      map.addOverlay(marker[j]);
      marker[j].openInfoWindowHtml(html);
      marker[j].closeInfoWindow();
      bounds.extend(points[j]);
    }
  }

  //bei kleinerer karte zoomlevel -1
  map.setCenter(bounds.getCenter(),map.getBoundsZoomLevel(bounds)-1,G_HYBRID_MAP);
  // Navigationselemente einblenden
  map.addControl(new GLargeMapControl());
  // Kartentypen einblenden
  map.addControl(new GMapTypeControl());
  // Übersichtskarte einblenden
  map.addControl(new GOverviewMapControl());
  // Massstab einblenden
  map.addControl(new GScaleControl());
}//function setmarker()

/* cns-methods for plugin uploadify */

/* event-methods for preedit in menu-templates */

function uploadify_preedit_on_complete(event, queueID, fileObj, response_json, data)
{
  // input_file element
  my_input_file = $( (event.currentTarget) ? event.currentTarget : event.srcElement );
  
  // the form
  my_form = my_input_file.closest('form');
  
  // get the container id
  my_container_id = $('div.additional_action_pane' , my_form ).attr('id');
  
  //response_data 
  data = JSON.parse(response_json);
  
  if( typeof data.error != 'undefined' )
  {
    alert(data.error);
  }
  else
  {
   
   action_show_add_file(
     my_container_id,
     my_form.attr('id'),
     response_json,
     data.s_retp_file_has_ass_1_filename_flnm
   );
   
  }
}

function uploadify_preedit_on_all_complete(event, queueID, fileObj, response_json, data)
{
  // input_file element
  my_input_file = $( (event.currentTarget) ? event.currentTarget : event.srcElement );

  // autohide hintbox (tiny menu)
  my_form = my_input_file.closest('form');
  my_input_file.closest("div.menu_template_tiny_body div.body_item").addClass("css_hidden");
  $("#" + my_form.attr('id') ).find("ul.menu_template_tiny_navi li div[title=arrow_container]").removeClass("arrow");

}
//######################################################################
// TOOLTIPS
//######################################################################

$('#competence_card_actions #actionsbox .css_action').tooltip({ 
    delay: 0, 
    showURL: false, 
    bodyHandler: function() { 
        return $("<div/>").html($(this).find('input').attr('value')); 
    } 
});


// CC-Aktions
$('#competence_card_actions .competence_card_action').tooltip({ 
  delay: 0, 
  showURL: false, 
  bodyHandler: function() {
    if ($(this).find('.hidden_tooltip').html() != '')
    {
      return $("<div/>").html($(this).find('.hidden_tooltip').html());
    }
    else
    {
      return "";
    }
  }
});

// Action Switch Left
$('#competence_card_actions .switch_actions .switch_left').tooltip({ 
  delay: 0, 
  showURL: false, 
  bodyHandler: function() {
    if ($(this).find('.hidden_tooltip').html() != '')
    {
      return $("<div/>").html($(this).find('.hidden_tooltip').html()); 
    }
    else
    {
      return "";
    }
  }
});

// Action Switch Right
$('#competence_card_actions .switch_actions .switch_right').tooltip({ 
  delay: 0, 
  showURL: false, 
  bodyHandler: function() {
    if ($(this).find('.hidden_tooltip').html() != '')
    {
      return $("<div/>").html($(this).find('.hidden_tooltip').html());
    }
    else
    {
      return "";
    }
  }
});

// external Links in networking_bar
$('.networking_element.external_link_button').tooltip({ 
  delay: 0, 
  showURL: false, 
  bodyHandler: function() {
    return $("<div/>").html($(this).find('a').attr('href'));
  }
});



//######################################################################

function load_to_div (Div_ID, url)
{
  $('#' + Div_ID).load(url);
}

function load_url_to_div_json (json_data)
{
  if(json_data && json_data.id && json_data.url)
  {
    replace_with_loader_image(json_data.id);
    
    $.ajax({
      url: json_data.url,
      success: function(data){
        $('#' + json_data.id).html(data);
      }
    });
  }
}



function replace_div (Div_ID, url)
{
  $.ajax({
    url: url,
    success: function(data){
      $('#' + Div_ID).replaceWith(data);
    }
  });
}

/*
 * append loader gif animation on the given element
 */
function append_loader_image(Div_ID)
{
  var myLoader = "<img id='loader' border='0' align='center' src='"+config_ajaxloadergfx+"'>";
  // $.create('img', {'src': 'http://www.competence-site.de/gfx/action_move_to_s_plac_center_mgr_medium.png', 'class': 'ajax_loader_icon', 'styles': {'left': '50%', 'position': 'relative', 'margin':'5px'}});
  
  if ($('#' + Div_ID).find('#loader').length == 0)
  {
    /* if there is a div with class "loader_position", place the loader at the defined position*/
    if($('#' + Div_ID).find('.loader_position').length > 0)
    { 
      $('#' + Div_ID).find('.loader_position').each(function(index,value) { 
          $(value).append(myLoader);     
      });
    }
    else
    {
      $('#' + Div_ID).append(myLoader);
    }
  }
}

/*
 * prepend loader gif animation on the given element
 */
function prepend_loader_image(Div_ID)
{
  var myLoader = "<img id='loader' border='0' align='center' src='"+config_ajaxloadergfx+"'>";
  // $.create('img', {'src': 'http://www.competence-site.de/gfx/action_move_to_s_plac_center_mgr_medium.png', 'class': 'ajax_loader_icon', 'styles': {'left': '50%', 'position': 'relative', 'margin':'5px'}});
  
  if ($('#' + Div_ID).find('#loader').length == 0)
  {
    $('#' + Div_ID).prepend(myLoader);
  }
}

function replace_with_loader_image(Div_ID)
{
  var myLoader = $("<img id='loader' border='0' src='"+config_ajaxloadergfx+"' style='margin-left: 10px;'>");
  $('#' + Div_ID).html(myLoader);
  
}

function load_url_to_div (Div_ID, url)
{
  append_loader_image(Div_ID);
  load_to_div (Div_ID, url);
}

function toggle_tabbar (pane)
{
  $('.navibar_subtype').addClass('css_hidden'); // css("display", "none");
  $('#navibar_subtype_' + pane).removeClass('css_hidden');
  /*
  if ($('#navibar_subtype_' + pane).css("display") == 'none')
  {
    $('#navibar_subtype_' + pane).css("display", "block");
  }
  */
}

function toggle_div(Div_ID)
{
  if ($('#' + Div_ID).css("display") == 'none')
  {
    $('#' + Div_ID).css("display", "");
  }
  else
  {
    $('#' + Div_ID).css("display", "none");
  }
}

// hide Div_ID if no checkbox is checked
function toggle_div_check(Div_ID, check_box_ID)
{
  if ($('#' + check_box_ID + ":checked").length == 0)
  {
    $('#' + Div_ID).hide();
  }
  else
  {
    $('#' + Div_ID).show();
  }
}

function toggle_classes(class_1, class_2, slide)
{
  if ($('.' + class_1).css("display") == 'none')
  {
    if (slide == true)
    {
      $('.' + class_1).slideDown('slow');
      $('.' + class_2).slideUp('slow');
    }
    else
    {
      $('.' + class_1).css("display", "");
      $('.' + class_2).css("display", "none");
    }
  }
  else
  {
    if (slide == true)
    {
      $('.' + class_1).slideUp('slow');
      $('.' + class_2).slideDown('slow');
    }
    else
    {
      $('.' + class_1).css("display", "none");
      $('.' + class_2).css("display", "");
    }
  }
}

function toggle_classes_caption(class_1, class_2, slide, caption_1, caption_2, element_id)
{
  if ($('.' + class_1).css("display") == 'none')
  {
	$('#' + element_id).html(caption_1);
	
    if (slide == true)
    {
      $('.' + class_1).slideDown('slow');
      $('.' + class_2).slideUp('slow');
    }
    else
    {
      $('.' + class_1).css("display", "");
      $('.' + class_2).css("display", "none");
    }
  }
  else
  {
    $('#' + element_id).html(caption_2);
	
    if (slide == true)
    {
      $('.' + class_1).slideUp('slow');
      $('.' + class_2).slideDown('slow');
    }
    else
    {
      $('.' + class_1).css("display", "none");
      $('.' + class_2).css("display", "");
    }
  }
}

function toggle_3_classes_caption(class_1, class_2, class_3, slide, caption_1, caption_2, caption_3, element_id)
{
  var size_class_1 = $('.' + class_1).size();
  var size_class_2 = $('.' + class_2).size();
  var size_class_3 = $('.' + class_3).size();
  
  var available_class_1 = false;
  var available_class_2 = false;
  var available_class_3 = false;
  
  var visible_class_1 = false;
  var visible_class_2 = false;
  var visible_class_3 = false;
  
  if (size_class_1 > 0)
  {
    available_class_1 = true;
    
    if ($('.' + class_1).css("display") != 'none')
    {
      visible_class_1 = true;
    }
  }
  
  if (size_class_2 > 0)
  {
    available_class_2 = true;
    
    if ($('.' + class_2).css("display") != 'none')
    {
      visible_class_2 = true;
    }
  }
  
  if (size_class_3 > 0)
  {
    available_class_3 = true;
    
    if ($('.' + class_3).css("display") != 'none')
    {
      visible_class_3 = true;
    }
  }
  
  var display_class     = "";
  var hide_class_first  = "";
  var hide_class_second = "";
  var caption = "";
  
  if (visible_class_1)
  {
    if (available_class_2)
    {
      // display class_2
      display_class = class_2;
      hide_class_first  = class_1;
      hide_class_second = class_3;
      
      if (available_class_3)
      {
        caption = caption_3;
      }
      else
      {
        caption = caption_1;
      }
    }
    else
    {
      caption = caption_1;
      
      if (available_class_3)
      {
        // display class_3
        display_class = class_3;
        hide_class_first  = class_1;
        hide_class_second = class_2;
      }
    }
  }

  if (visible_class_2)
  {
    if (available_class_3)
    {
      // display class_3
      display_class = class_3;
      hide_class_first  = class_1;
      hide_class_second = class_2;
      
      if (available_class_1)
      {
        caption = caption_1;
      }
      else
      {
        caption = caption_2;
      }
    }
    else
    {
      caption = caption_2;
      
      if (available_class_1)
      {
        // display class_1
        display_class = class_1;
        hide_class_first  = class_2;
        hide_class_second = class_3;
      }
    }
  }
  
  if (visible_class_3)
  {
    if (available_class_1)
    {
      // display class_1
      display_class = class_1;
      hide_class_first  = class_2;
      hide_class_second = class_3;
      
      if (available_class_2)
      {
        caption = caption_2;
      }
      else
      {
        caption = caption_3;
      }
    }
    else
    {
      caption = caption_3;
      
      if (available_class_2)
      {
        // display class_2
        display_class = class_2;
        hide_class_first  = class_1;
        hide_class_second = class_3;
      }
    }
  }
  
  $('#' + element_id).html(caption);
  
  if (slide == true)
  {
    $('.' + display_class).slideDown('slow');
    $('.' + hide_class_first).slideUp('slow');
    $('.' + hide_class_second).slideUp('slow');
  }
  else
  {
    $('.' + display_class).css("display", "");
    $('.' + hide_class_first).css("display", "none");
    $('.' + hide_class_second).css("display", "none");
  }
}

function toggle_caption_class(class_1, class_2, caption_1, caption_2, element_id)
{
  if ($('.' + class_1).css("display") == 'none')
  {
    $('#' + element_id).html(caption_2);
  }
  else
  {
    $('#' + element_id).html(caption_1);
  }
}

function toggle_divs(Div_ID_1, Div_ID_2)
{
  if ($('#' + Div_ID_1).css("display") == 'none')
  {
    $('#' + Div_ID_1).css("display", "");
    $('#' + Div_ID_2).css("display", "none");
  }
  else
  {
    $('#' + Div_ID_1).css("display", "none");
    $('#' + Div_ID_2).css("display", "");
  }
}

function toggle_caption(Div_ID_1, Div_ID_2, caption_1, caption_2, element_id)
{
  if ($('#' + Div_ID_1).css("display") == 'none')
  {
    $('#' + element_id).html(caption_2);
  }
  else
  {
    $('#' + element_id).html(caption_1);
  }
}

function hide_show_part(Div_ID, height, link_id, string_all, string_min)
{
  if ($('#' + Div_ID + ' .box').css('height') == '' + height + 'px')
  {
    $('#' + Div_ID + ' .box').animate({height: $('#' + Div_ID + ' .box' + ' .default_height').html()}, 500);
    $('#' + Div_ID + ' .dots').slideUp('slow');
    $('#' + link_id +  ' a').html(string_min);
  }
  else
  {
    $('#' + Div_ID + ' .box').animate({height:'' + height + 'px'}, 500);
    $('#' + Div_ID + ' .dots').slideDown('slow');
    $('#' + link_id +  ' a').html(string_all);
  }
}

function jump_to_id(Div_ID)
{
  $('html,body').animate({scrollTop: $("#" + Div_ID).offset().top},'slow');
}

function click_on_filter_item(href)
{
  $('#filter_for_current_object').find('a[class="caption"][href="#' + href + '"]').trigger('click');
}

/* not used
function toggle_login_div(Div_ID)
{
  if ($('#' + Div_ID).css("display") == 'none')
  {
    $('#' + Div_ID).css("display", "");
    $('#link_login_arrow').attr("class", "link_login_arrow_up");
  }
  else
  {
    $('#' + Div_ID).css("display", "none");
    $('#link_login_arrow').attr("class", "link_login_arrow");
  }
}
*/

/**
 * Send a form with post by ajax
 * usage: within <form> tag: onsubmit="ajax_event(event, '<result_name>');
 * variabel event is set by browser
 * form name must be: form_<name>
 * @param {Object} e
 * @param {Object} name the name of the form tag must be form_<name>, the name of the result tag <name>_result 
 * @param string check if "checkform", call check_form() and do not send request if it returns false
 * @param {Object} disable_mcr_id passed to check_form()
 */

function ajax_event(e, name, check, disable_mcr_id)
{
  //manually form submission for tinyMCE in case of ajax-request
  if(window.tinyMCE !== undefined)
  {
    tinyMCE.triggerSave();
  }
  
  //Check form for mandatory fields, datetime, email, ...
  var checkform = true;
  if (check == "checkform") 
  {
      checkform = check_form('form_' + name, disable_mcr_id);
  }
  
  var my_event = new Event(e);
  my_event.stop();
  var my_form = new Element(my_event.target);
  
  while (!my_form.match('form')) {
    my_form = my_form.getParent();
  }
  
  //Set update Div
  var my_output;
  
  if ($(name + '_result').parentNode.className == "ajax")
  {
    my_output = $(name + '_result').parentNode;
  }
  else
  {
    my_output = $(name + '_result');
  }
  
  if (checkform == true)
  {
    var myHTMLRequest = new Request.HTML({update: my_output, evalScripts: true, url:my_form.action});
    ajax_event_helper(name + '_result', my_form.action, myHTMLRequest, my_form);
  }
}

function save_file(iframe_ID, url, Div_ID, form_ID)
{
  append_loader_image(Div_ID);

  $('#' + iframe_ID).load(function() {
    var newContent = $('#'+iframe_ID).contents().find('body').html();
    $('#' + Div_ID).replaceWith(newContent);
  });
  
  //$('#' + form_ID).submit();
  return true;
}

function ajax_event_helper(Div_ID, myURL, myAjax, my_form)
{
  showLoader(Div_ID);
  listOfRequests.set(Div_ID, [myURL, '']);
  myAjax.post(my_form);
  
}


/* mehrwerte create link */
function action_validate_link(link)
{
  link = new String(link);
  
  var pattern = new RegExp('^(https?:\\/\\/)?'+ // protocol
    '((([a-zäüö\\d]([a-zäüö\\d-]*[a-zäüö\\d])*)\\.)+[a-zäüö]{2,}|'+ // domain name
    '((\\d{1,3}\\.){3}\\d{1,3}))'+        // OR ip (v4) address
    '(\\:\\d+)?(\\/[-a-zäüö\\d%_.;,~+\?=\!&]*)*'+ // port and path
    '(\\?[;&a-zäüö\\d%_.;,~+\?=\!&]*)?'+        // query string
    '(\\#[-a-zäüö\\d%_.;,~+\/\?=\!&]*)?$','i');    // fragment locater
    
  if(!pattern.test(link)) {
    return false;
  }
  else
  {
    pref = link.substr(0,4);
    
    if( pref == "http" || pref == "www.")
    {
       return true;  
    }
  }
  
  return false;
}


function submit_form(form_id)
{
  if (check_form(form_id))
  {
    $('#' + form_id).submit();
  }
}

function check_form(form_id)
{
  var ok = true;
  var radio_button_check_storage = "undefined";
  // loop over all input fields with class mandatory
 
  $('#' + form_id).find('input[class~="css_mandatory"], select[class~="css_mandatory"]').each(function(){
    
    var current_ok = true;
    
    // Textfields
    if (($(this).attr('type') == 'text') || ($(this).attr('type') == 'password'))
    {
      if ($(this).val() == '')
      {
        ok = false;
        current_ok = false;
      }
    }
    else
    {
      if ($(this).attr('type') == 'checkbox')
      {
        if (($(this).attr('checked') == false) || ($(this).attr('checked') == ''))
        {
          ok = false;
          current_ok = false;
        }
        else
        {
          if ($(this).attr('checked'))
          {
            
          }
          else
          {
            ok = false;
            current_ok = false;
          }
        }
      }
      
      else if ($(this).attr('type') == 'radio')
      {
        if(radio_button_check_storage == "undefined")
        {
          radio_button_check_storage = new Array();
        
        }
        curr_radio_name = $(this).attr('name');
        curr_radio_checked = $(this).attr('checked');
        
        if( radio_button_check_storage[curr_radio_name] == null)
        {
          radio_button_check_storage[curr_radio_name] = curr_radio_checked;
        }
        
        if( radio_button_check_storage[curr_radio_name] == "undefined")
        {
          radio_button_check_storage[curr_radio_name] = curr_radio_checked;
        }

      }
      
      else
      {
        if ($(this).val() == '__not_set__')
        {
          ok = false;
          current_ok = false;
        }
      }
    }
    
    // mark incorrect field
    if (current_ok == false)
    {
      $(this).parent().addClass('css_highlighted');
      if ($(this).attr('type') != 'checkbox')
      {
        $(this).parent().parent().addClass('css_highlighted');
      }
    }
    else
    {
      $(this).parent().removeClass('css_highlighted');
      if ($(this).attr('type') != 'checkbox')
      {
        $(this).parent().parent().removeClass('css_highlighted');
      }
    }
  });
  
  // validate radiobuttons
  if(radio_button_check_storage != "undefined")
  {
    for (var name in radio_button_check_storage)
    {
      value = radio_button_check_storage[name];
      if(value != "checked")
      {
        ok=false;
        radio_input = $('#' + form_id).find('input[class~="css_mandatory"][type="radio"][name="' + name +'"]')[0];
        $(radio_input).parent().parent().parent().addClass('css_highlighted');
      }
      else
      {
        radio_input = $('#' + form_id).find('input[class~="css_mandatory"][type="radio"][name="' + name +'"]')[0];
        $(radio_input).parent().parent().parent().removeClass('css_highlighted');
      }
    }  
  }
  
  // loop over all input fields for phone numbers
  $('#' + form_id).find('input[class~="edit_row_text"][name*="[phno]"]').each(function(){
    
    //var filter = /^(?:+?([0-9]{3}))?[ ]?(?([0-9]{3}))?[ ]?([0-9]{10})[ ]$/;
	//var filter = /^(?:+?([0-9]{3}))?[-. ]?(?([0-9]{3}))?[-. ]?([0-9]{10})[-. ]$/;
	//var filter = /^((\(44\))( )?|(\(\+44\))( )?|(\+44)( )?|(44)( )?)?((0)|(\(0\)))?( )?(((1[0-9]{3})|(7[1-9]{1}[0-9]{2})|(20)( )?[7-8]{1})( )?([0-9]{3}[ -]?[0-9]{3})|(2[0-9]{2}( )?[0-9]{3}[ -]?[0-9]{4}))$/;
    var filter = /^([\+]{1})([0-9]{2,3})([\ ]{1})([1-9]{1})([0-9]+)([\ ]{1})([0-9]+)([\-]*)([0-9]*)$/;
    
    if (($(this).attr('value') != '') && ($(this).attr('value') != 'z.B. +49 123 123456-78'))
    {
      if (filter.test($(this).val()))
      {
        $(this).parent().removeClass('css_highlighted');
        $(this).parent().parent().removeClass('css_highlighted');
      }
      else
      {
        $(this).parent().addClass('css_highlighted');
        $(this).parent().parent().addClass('css_highlighted');
        ok = false;
      }
    }
    else
    {
      $(this).parent().removeClass('css_highlighted');
      $(this).parent().parent().removeClass('css_highlighted');
    }
  });
  
  // loop over all input fields for email
  $('#' + form_id).find('input[class~="email"]').each(function(){
    
    var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
    
    if (filter.test($(this).val()))
    {
      $(this).parent().removeClass('css_highlighted');
      $(this).parent().parent().removeClass('css_highlighted');
    }
    else
    {
      
      //json container handling
      if($(this).closest("form").find("input[type='hidden'][name='object[email]'][value!='']").length > 0)
      {
        $(this).parent().removeClass('css_highlighted');
        $(this).parent().parent().removeClass('css_highlighted');
        ok = true;
      }
      else
      {
        $(this).parent().addClass('css_highlighted');
        $(this).parent().parent().addClass('css_highlighted');
        ok = false; 
      }
      
      
    }
  });
  
  // loop over all input fields for urls
  $('#' + form_id).find('input[name="object[s_retp_obje_has_ass_1_url_urls]"]').each(function(){
	
	url_string = new String($(this).attr('value'));
	
	if (action_validate_link(url_string))
    {
      $(this).parent().removeClass('css_highlighted');
      $(this).parent().parent().removeClass('css_highlighted');
    }
    else
    {
      $(this).parent().addClass('css_highlighted');
      $(this).parent().parent().addClass('css_highlighted');
      ok = false;
    }
  });
  
  if (ok == false)
  {
    alert(config_form_check_error);
  }
  else
  {
    // check password and retype password fields
    $('#' + form_id).find('input[type="password"][name="object[RetypePassword]"]').each(function(){
      if ($(this).val() != $('#' + form_id + ' input[type="password"][name="object[s_retp_pers_has_ass_1_password_md5h]"]').val())
      {
        $(this).parent().addClass('css_highlighted');
        $(this).parent().parent().addClass('css_highlighted');
        ok = false;
        
        $('#' + form_id + ' input[type="password"][name="object[s_retp_pers_has_ass_1_password_md5h]"]').parent().addClass('css_highlighted');
        $('#' + form_id + ' input[type="password"][name="object[s_retp_pers_has_ass_1_password_md5h]"]').parent().parent().addClass('css_highlighted');
        alert(config_password_check_error);
      }
    });
  }
  
  
  if(ok == false)
  {
    // set new clickevent to form-save-button (added by the doppelclickpolizei (flo) )
    save_button = $('#' + form_id).find('div[class~="css_action_save"]');
    if(save_button)
    {
      save_button.bind('click',function(event){ 
        submit_form($(this).closest('form').attr('id'));
        $(this).unbind(event);
      });
    } 
  }
  
  return ok;
}

/**
 * Check request and display message, if downgrade is requested
 * @param string id of form
 */
function check_and_submit_user_level_form(form_id, downgrade_question, downgrade_pos, downgrade_neg, no_qualification_selected, submitted)
{
  var ok = true;
  
  // check if requested level is lower than current level
  
  $('#' + form_id).find('.list_item.level.current').each(function(){
    if (($('#' + form_id).find('input[name="object[s_retp_obje_has_ass_1_req_comp_level_cplv]"]:checked').attr('value')) < ($(this).find('input[type="hidden"]').attr('value')))
    {
      var answer = confirm (downgrade_question);
      if (answer)
      {
      //  alert (downgrade_pos);
        ok = true;
      }
      else
      {
        alert (downgrade_neg);
        ok = false;
      }
    }
    else
    {
      ok = true;
    }
  });
  
  // check if level 11 and no qualification was selected
  $('input[value="s_cplv_11_qualified"]:checked').each(function() {
    
    var quali_selected = false;
    
    $('input[name="object[s_retp_pers_has_ass_m_qualification_prql][]"]:checked').each(function() {
      quali_selected = true;
    });
    
    if (!quali_selected)
    {
      alert(no_qualification_selected);
      ok = false;
    }
  });
  
  if (ok)
  {
    submit_form(form_id);
  //  alert(submitted);
  }
}






/**
 * Send a form with post by ajax
 * usage: within <form> tag: onsubmit="ajax_event_new(event, '<result_name>');
 * variable event is set by browser
 * @param {Object} e browser event object
 * @param {Object} result_name name of tag where to put the result. If the parent is of class "ajax", then parent is used.
 * @param {Object} form_name
 * @param boolean check if true, call check_form() and do not send request if it returns false
 * @param {Object} disable_mcr_id passed to check_form()
 */
function ajax_event_new(event, result_name, form_name, disable_mcr_id, load_into_result_name, loader_position, additional_success_function, additional_success_params)
{
  //alert(event.type);
  
  //alert("disable_mcr_id: " + disable_mcr_id);
//  $('#' + disable_mcr_id).attr('onclick', 'return false;');
  
  var e = event;
  // alert(e);
  if ( !e ) {
    return;
  }
  
  // if stopPropagation exists run it on the original event
  if ( e.stopPropagation ) {
    e.stopPropagation();
  }
  
  // otherwise set the cancelBubble property of the original event to true (IE)
  e.cancelBubble = true; 
  
  //manually form submission for tinyMCE in case of ajax-request
  if(window.tinyMCE !== undefined)
  {
    window.tinyMCE.triggerSave();
  }
  
  //alert("result_name: " + result_name);
  if (jQuery.isEmptyObject(loader_position))
  {
    append_loader_image(result_name);
  }
  else
  {
    if (loader_position == 'top')
    {
      prepend_loader_image(result_name);
    }
    else
    {
      append_loader_image(result_name);
    }
  }
  
  //alert("form_name: " + form_name);
  //alert("serial: " + $('#' + form_name).serialize());
  //alert("action: " + $('#' + form_name).attr("action"));
  //alert("load_into_result_name: " + load_into_result_name);
  
  if (load_into_result_name == "")
  {
    $.ajax({
      type: "POST",
      url: $('#' + form_name).attr("action"),
      global: false,
      data: $('#' + form_name).serialize(),
      dataType: "html",
      success: function(data, textStatus, jqXHR) {
        $('#' + result_name).replaceWith(data);
        
        if(additional_success_function)
        {
          if(additional_success_params)
          {
            additional_success_function(additional_success_params);
          }
          else
          {
            additional_success_function();
          }
        }
        
      },
      async: true
    });
  }
  else
  {
    $.ajax({
      type: "POST",
      url: $('#' + form_name).attr("action"),
      global: false,
      data: $('#' + form_name).serialize(),
      dataType: "html",
      success: function(data, textStatus, jqXHR) {
        $('#' + result_name).html(data);
        
        if(additional_success_function)
        {
          if(additional_success_params)
          {
            additional_success_function(additional_success_params);
          }
          else
          {
            additional_success_function();
          }
        }
      },
      async: true
    });
  }
  
  return false;
  
  /*
  var i = 0;
  
  while (i < 1)
  {
    alert("Before " + event.bubbles);
    event.stopImmediatePropagation();
    alert("After stopImmediatePropagation " + event.bubbles);
    event.stopPropagation();
    alert("After stopPropagation " + event.bubbles);
    //alert(event.isPropagationStopped());
    event.cancelBubble = true;
    alert("After cancelBubble " + event.bubbles);
    i = i + 1;
  }
  
      if (event.bubbles === undefined) {  // Internet Exlorer
          alert("Internet Explorer");
              // always cancel bubbling
          event.cancelBubble = true;
          alert ("The propagation of the " + event.name + " event is stopped.");
      }
      else {        // Firefox, Opera, Google Chrome and Safari
          if (event.bubbles) {
            alert("Firefox");
              event.stopPropagation ();
              alert ("The propagation of the " + eventName + " event is stopped.");
          }
          else {
            alert("last");
              alert ("The " + eventName + " event cannot propagate up the DOM hierarchy.");
          }
      }
  */

  
  //Check form for mandatory fields, datetime, email, ...
  // var checkform = true;
  //if (check == true) 
  //{
  //    checkform = check_form(form_name, disable_mcr_id);
  //}
  
  //event.stopPropagation();
  //var my_event = new Event(e);
  
  // alert($('#' + form_name).attr("action"));
  // alert($('#' + form_name).serialize());
  // alert($('#' + result_name).attr("id"));
  
  /*
  $.ajax({
      type: "POST",
      url: $('#' + form_name).attr("action"),
      data: $('#' + form_name).serialize(),
      success: function() {
        $('#' + result_name).load(next_url);
      }
    });
  
  $.post($('#' + form_name).attr("action"), $('#' + form_name).serialize(), function(data) {
    $('#' + result_name).load(next_url)});
  */
  /*
  $.ajax({
      url: "script.php",
      global: false,
      type: "POST",
      data: ({id : this.getAttribute('id')}),
      dataType: "html",
      async:false,
      success: function(msg){
         alert(msg);
      }
   }
  )
  */
  //alert("READY");
  /*
  $.ajax({
    type: "POST",
    url: $('#' + form_name).attr("action"),
    data: $('#' + form_name).serialize(),
    context: $('#' + result_name)
  });
  */
  //my_event.stop();
  // var my_form = new Element(my_event.target);
  
/*  $('#' + form_name).validate({
    submitHandler: function(form) {
      // do other stuff for a valid form
      alert("set submit handler");
      // $.ajax({ type: "POST", url: $('#' + form_name).attr("action"), context: $('#' + result_name)});
      // $.post($('#' + form_name).attr("action"), $('#' + form_name).serialize(), function(data) {
      //   $('#' + result_name).html(data);
      // });
    }
  });
*/
  
  // alert("Fast fertig: event.bubbles " + event.bubbles);
  // alert("FERTIG");
  // alert("Fertig: event.bubbles " + event.bubbles);
  
  // while (!my_form.match('form')) {
  // my_form = my_form.getParent();
  // alert("match");
  // }
  
  // var my_output;
  // if ($(result_name).parentNode.className == "ajax")
  // {
  //   my_output = $(result_name).parentNode;
  // }
  // else
  // {
  //   my_output = $(result_name);
  // }
/*  
  if (checkform == true)
  { alert("my_output");
    showLoader(result_name);
    dump($('#' + result_name).attr('id'));
  //  var myHTMLRequest = new Request.HTML({update: my_output, evalScripts: true, url:my_form.action}).post(my_form);
    //  $.ajax({ type: "POST", url: $('#' + form_name).attr("action"), context: $('#' + result_name), success: function(){
    //      alert("done");
    //    }});
    //  $.ajax({ type: "POST", url: $('#' + form_name).attr("action"), context: $('#' + result_name)});
  }
  */
}

function share_by_mail(email_input_id, subject_input_id, body_input_id, link_field_id)
{
  mailto = 'mailto:' + $('#' + email_input_id).val() + '?subject=' + $('#' + subject_input_id).html() + '&body=' + $('#' + body_input_id).html() + '';
  
  //code = "location.href='" + mailto + "'";
  
  $('#' + link_field_id).attr('href', '' + mailto);
}

function fillitup(target_id, suggestions_list_id, key)
{
  // put value into input field
  $('#' + target_id).value = key;

  // undisplay suggestions
  $('#' + suggestions_list_id).css('display', 'none');
}

/* not used anymore
function suggestItToMe(target, suggestions_list_id, myURL, field_id)
{
  if ($('#' + target).attr('value').length > 1)
  {
    if (autoSuggesting_req)
    {
      autoSuggesting_req.abort();
    }
    
    var itemList = new Array();
    
    var url = myURL + "&value=" + $('#' + target).attr('value');
    
    var counter = 0;
    autoSuggesting_req = $.getJSON(url, function(data) {
      $.each(data, function(key, val) {
      
        // on click set text of input field to clicked value, hide suggestion list and do not follow the link
        var onclick = "$(\"#" + target + "\").attr(\"value\", \"" + key + "\"); $(\"#" + suggestions_list_id + "\").css(\"display\", \"none\");";
        if (field_id)
        {
          onclick += "$(\"#" + field_id + "\").attr(\"value\", \"" + val + "\");";
        }
        onclick += "$(this).closest(\"form\").submit();";
        onclick += "return false;";
        
        var element = "<a href='/" + val + "' onclick='" + onclick + "'>" + key + "</a>";
        // alert(element);
        itemList[counter] = element;
        // alert(itemList);
        counter += 1;
        // alert(counter);
      });
      
      var itemList_html = "";
      var newString = "";
      var display_value = "none";
      // alert(counter);
      var newCounter = 0;
      if (counter > 0)
      {
        itemList_html = "<ul>";
        // alert(itemList_html);
        while (newCounter < counter)
        {
          newString = itemList_html + "<li>" + itemList[newCounter] + "</li>";
          itemList_html = newString;
          // alert(itemList_html);
          newCounter++;
        }
        
        newString = itemList_html + "</ul>";
        itemList_html = newString;
        // alert(itemList_html);
        display_value = "block";
      }
      // alert(itemList_html);
      $('#' + suggestions_list_id).html(itemList_html);
      $('#' + suggestions_list_id).css('display', display_value);
      // alert("FERTIG");
      
    });

  }
  else
  {
    $('#' + suggestions_list_id).html("");
    $('#' + suggestions_list_id).css('display', 'none');
  }
}
*/


//HELPER- do not call directly
function get_module_set_relation_delayed (target, myURL, text_fields)
{
  // show loader image
  append_loader_image(target);
  
  // send ajax request
  autoSuggesting_req = $.ajax({
    type: "GET",
    url: myURL,
    global: false,
    dataType: "html",
    async: true,
    success: function(data, textStatus, jqXHR) {
        $('#' + target).html(data);
      }
  });
};

function get_module_set_relation_result(target, myURL, text_fields)
{
  if (autoSuggesting)
  {
    window.clearTimeout(autoSuggesting);
    delete autoSuggesting;
  }
  
  if (autoSuggesting_req)
  {
    autoSuggesting_req.abort();
    delete autoSuggesting_req;
  }
  
  //Get Search Term
  search_term = $('#' + text_fields).attr('value');
    
  //Check if search term is more than 3
  if (search_term.length > 0)
  {
    // replace placeholder
    myURL = myURL.replace("--search_term--", (typeof(encodeURIComponent)=="function")?encodeURIComponent(search_term):escape(search_term));
        
    // call with delay
    autoSuggesting = setTimeout("get_module_set_relation_delayed('"+target+"', '"+myURL+"', '"+text_fields+"')", 250);
  }
  else
  {
    $('#' + target).html("");
  }
}


function get_module_set_relation_double_result(target, myURL, text_field, text_fields)
{
  if (typeof autoSuggesting != "undefined")
  {
    // cancel delayd call
    window.clearTimeout(autoSuggesting);
    delete autoSuggesting;
  }
  
  if (typeof autoSuggesting_req != "undefined")
  {
    // cancel aready sent request
    autoSuggesting_req.abort();
    delete autoSuggesting_req;
  }
  
  var get_object = false;
  
  var text_fields_array = text_fields.split(",");
  
  //Get all input fields and create search term
  for (var i=0; i<text_fields_array.length; i++)
  {
    if ($('#' + text_fields_array[i]).attr('value').length > 0)
    {
      get_object = true;
    }
  }
  
  var search_term = "";
  
  if (get_object == true)
  {
    //Get all input fields and create search term
    for (var i=0; i<text_fields_array.length; i++)
    {
      search_term = search_term + $('#' + text_fields_array[i]).attr('value');
      console.log(search_term);
      //alert(search_term);
      if (i < text_fields_array.length - 1)
      {
        search_term = search_term + "--trenner--";
      }
    }
  
    // replace placeholder
    myURL = myURL.replace("--search_term--", (typeof(encodeURIComponent)=="function")?encodeURIComponent(search_term):escape(search_term));

    // call with delay
    autoSuggesting = setTimeout("get_module_set_relation_delayed('"+target+"', '"+myURL+"', '"+text_fields+"')", 250);
  }
  else
  {
    $('#' + target).html("");
  }
}

function html_encode(value){
  return value.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#039;');
}

function html_decode(value){
  return value.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&quot;/g,'"').replace(/&#039;/g,'\'');
}

// old check_form from static_5_form.js
/*
function check_form (Forms, disable_button_mcr_id)
{
  Check = 1;
  var CheckObject = false;
  if (document.forms[Forms].elements && document.forms[Forms].elements['check_field'])
  {
    CheckObject = document.forms[Forms].elements['check_field'];
  }
  
  if (CheckObject)
  {
    if (CheckObject && !CheckObject.length)
    {
      CheckObjectLength = 1;
    }
    else if (CheckObject && CheckObject.length)
    {
      CheckObjectLength = CheckObject.length;
    }
    else
    {
      CheckObjectLength = 0;
    }
    
    var input_field_old = "";
    
    for (var i=0;i<CheckObjectLength;i++)
      {
        var StringCheck;
        if (CheckObjectLength == 1)
        {
          StringCheck = CheckObject.value.split(",");
        }
        else
        {
          StringCheck = CheckObject[i].value.split(",");
        }
    
        var input_field = $(StringCheck[0]);
        if (input_field != input_field_old)
        {
          field_error = false;
        }
        
        input_field_old = input_field;
        
        if (StringCheck[1] == "ismandatory")
        {
          if (input_field.value == "")
          {
            field_error = true;
            Check = 0
            form_element_set_error(input_field, StringCheck[0] + "_ismandatory", true);
          } else {
            form_element_set_error(input_field, StringCheck[0] + "_ismandatory", false);
          }
        }
  
        // multiselect box like addressbook selection for receiver
        if (StringCheck[1] == "ismandatory_multiselect")
        {
          if (input_field.value == "")
          {
            Check = 0
            form_element_set_error(input_field, StringCheck[0] + "_ismandatory_multiselect", true);
          } else {
            form_element_set_error(input_field, StringCheck[0] + "_ismandatory_multiselect", false);
          }
        }
  
        // special treatment for autocomplete fields: input field must be empty, hidden fields must exist
        if (StringCheck[1] == "ismandatory_autocomplete")
        {
          var error = false;
    
          if (input_field.get('text').trim().length != 0) {
            error = true; // input field mus be empty before submit
          } else if ($(StringCheck[0] + "_autocomplete_results").getChildren().length == 0) {
            error = true; // no autocompleted entries there
          }
          if (error)
          {
            Check = 0;
                form_element_set_error(input_field, StringCheck[0] + "_ismandatory_autocomplete", true);
          }
          else
          {
                form_element_set_error(input_field, StringCheck[0] + "_ismandatory_autocomplete", false);
          }
        }
  
        if (StringCheck[1] == "checked")
        {
          if (input_field.checked == "")
          {
            Check = 0;
                form_element_set_error(input_field, StringCheck[0] + "_ismandatory", true);
          }
          else
          {
                form_element_set_error(input_field, StringCheck[0] + "_ismandatory", false);
          }
        }
        if (StringCheck[1] == "emailaddress" && input_field.value != "")
        {
          
          var email_check = checkemail(input_field.value);
          
          if (email_check == false)
          {
            Check = 0;
                form_element_set_error(input_field, StringCheck[0] + "_emailaddress", true);
          }
          else
          {
            form_element_set_error(input_field, StringCheck[0] + "_emailaddress", false);
          }
        }
        
      if (StringCheck[1].substring(0,6) == "length")
      {
        if (input_field.value.length > parseInt(StringCheck[1].substring(6)))
        {
          Check = 0;
          form_element_set_error(input_field, StringCheck[0] + "_length", true);
        }
        else if (!field_error)
        {
          form_element_set_error(input_field, StringCheck[0] + "_length", false);
        }
      }
    }
  }
  if (Check == 1)
  {
    if ($(Forms + "_result"))
    {
      $(Forms + "_result").display = "none";
    }
    
    //Disable button
    if (disable_button_mcr_id)
    {
      disable_button (disable_button_mcr_id);
    }
    return true;
  }
  else
  {
    if ($(Forms + "_result"))
    {
      $(Forms + "_result").style.display = "block";
    }
    return false;
  }
}
*/

function check_and_submit_form(Forms, disable_button_mcr_id)
{
    Check = 1;
    var CheckObject = false; alert(Forms);
    if (document.forms[Forms].elements && document.forms[Forms].elements['check_field'])
    {
      CheckObject = document.forms[Forms].elements['check_field'];
    }
    
    if (CheckObject)
    {
      if (CheckObject && !CheckObject.length)
      {
        CheckObjectLength = 1;
      }
      else if (CheckObject && CheckObject.length)
      {
        CheckObjectLength = CheckObject.length;
      }
      else
      {
        CheckObjectLength = 0;
      }
      
      var input_field_old = "";
      
      for (var i=0;i<CheckObjectLength;i++)
        {
          var StringCheck;
          if (CheckObjectLength == 1)
          {
            StringCheck = CheckObject.value.split(",");
          }
          else
          {
            StringCheck = CheckObject[i].value.split(",");
          }
      
          var input_field = $(StringCheck[0]);
          if (input_field != input_field_old)
          {
            field_error = false;
          }
          
          input_field_old = input_field;
          
          if (StringCheck[1] == "ismandatory")
          {
            if (input_field.value == "")
            {
              field_error = true;
              Check = 0;
              form_element_set_error(input_field, StringCheck[0] + "_ismandatory", true);
            } else {
              form_element_set_error(input_field, StringCheck[0] + "_ismandatory", false);
            }
          }
    
          // multiselect box like addressbook selection for receiver
          if (StringCheck[1] == "ismandatory_multiselect")
          {
            if (input_field.value == "")
            {
              Check = 0;
              form_element_set_error(input_field, StringCheck[0] + "_ismandatory_multiselect", true);
            } else {
              form_element_set_error(input_field, StringCheck[0] + "_ismandatory_multiselect", false);
            }
          }
    
          // special treatment for autocomplete fields: input field must be empty, hidden fields must exist
          if (StringCheck[1] == "ismandatory_autocomplete")
          {
            var error = false;
      
            if (input_field.get('text').trim().length != 0) {
              error = true; // input field mus be empty before submit
            } else if ($(StringCheck[0] + "_autocomplete_results").getChildren().length == 0) {
              error = true; // no autocompleted entries there
            }
            if (error)
            {
              Check = 0;
                  form_element_set_error(input_field, StringCheck[0] + "_ismandatory_autocomplete", true);
            }
            else
            {
                  form_element_set_error(input_field, StringCheck[0] + "_ismandatory_autocomplete", false);
            }
          }
    
          if (StringCheck[1] == "checked")
          {
            if (input_field.checked == "")
            {
              Check = 0;
                  form_element_set_error(input_field, StringCheck[0] + "_ismandatory", true);
            }
            else
            {
                  form_element_set_error(input_field, StringCheck[0] + "_ismandatory", false);
            }
          }
          if (StringCheck[1] == "emailaddress" && input_field.value != "")
          {
            
            var email_check = checkemail(input_field.value);
            
            if (email_check == false)
            {
              Check = 0;
                  form_element_set_error(input_field, StringCheck[0] + "_emailaddress", true);
            }
            else
            {
              form_element_set_error(input_field, StringCheck[0] + "_emailaddress", false);
            }
          }
          
        if (StringCheck[1].substring(0,6) == "length")
        {
          if (input_field.value.length > parseInt(StringCheck[1].substring(6)))
          {
            Check = 0;
            form_element_set_error(input_field, StringCheck[0] + "_length", true);
          }
          else if (!field_error)
          {
            form_element_set_error(input_field, StringCheck[0] + "_length", false);
          }
        }
      }
    }
    if (Check == 1)
    {
      if ($(Forms + "_result"))
      {
        $(Forms + "_result").display = "none";
      }
      
      //Disable button
      if (disable_button_mcr_id)
      {
        disable_button (disable_button_mcr_id);
      }
      $(this).closest('form').submit();
    }
    else
    {
      if ($(Forms + "_result"))
      {
        $(Forms + "_result").style.display = "block";
      }
      return false;
    }
}

function check_input_field (field, check)
{
  var check_result = true;
  //Input field to be checked
  var input_field = $(field);
  
  //check for
  var checks = check.split(",");
  var field_error = false;
  
  for (i=0; i< checks.length; i++)
  {
    if (checks[i] == "ismandatory")
    {
      if (input_field.value == "")
      {
            field_error = true;
            form_element_set_error(input_field, field + "_ismandatory", true);
      }
      else
      {
            form_element_set_error(input_field, field + "_ismandatory", false);
      }
    }
    
    if (checks[i] == "checked")
    {
      if (input_field.checked == "")
      {
            form_element_set_error(input_field, field + "_ismandatory", true);
      }
      else
      {
            form_element_set_error(input_field, field + "_ismandatory", false);
      }
      
    }
    if (checks[i] == "email" && input_field.value != "")
    {
      check_result = checkemail(input_field.value);
      if (check_result == false)
      {
            form_element_set_error(input_field, field + "_emailaddress", true);
      }
      else
      {
            form_element_set_error(input_field, field + "_emailaddress", false);
      }
    }
    if (checks[i] == "password")
    {
      firstPasswordField = input_field;
      for (i = 0; i < 3; i++) {$(field + "_password" + i).style.display = "none";}
      if (input_field.value != "")
        $(field + "_password" + qualityCheck(input_field.value)).style.display = "block";
      if (qualityCheck(input_field.value) == 0)
        input_field.style.background = "#ff6c44";
      else
        input_field.style.background = "white";
    }
    if (checks[i] == "repassword" && input_field.value != "")
    {
      if (typeof(firstPasswordField) != "undefined")
      {
        if (input_field.value == firstPasswordField.value)
        {
          form_element_set_error(input_field, field + "_repassword", false);
        }
        else
        {
          form_element_set_error(input_field, field + "_repassword", true);
        }
      }
    }
    
    if (checks[i].substring(0,6) == "length")
    {
      if (input_field.value.length > parseInt(checks[i].substring(6)))
      {
        form_element_set_error(input_field, field + "_length", true);
      }
      else if (!field_error)
      {
            form_element_set_error(input_field, field + "_length", false);
      }
    }
  }
}
function open_tag(Div_ID)
{
  $('#'+Div_ID).show();
}
function close_tag(Div_ID)
{
  $('#'+Div_ID).hide();
}

function select_center(Div_ID, center_name, center_id, count_more_center, count_more_center_id, select_box_id)
{
  delete_button = '<div class="css_item_inline_action css_normal"><div class="css_inline_action_delete" name="object" onclick="unselect_center(\'' + Div_ID + '\', \'' + center_name + '\', \'' + center_id + '\', ' + count_more_center + ', \'' + count_more_center_id + '\', \'' + select_box_id + '\');" class="float_right"><div class="inner">Entfernen</div></div></div>';
  
  input_field = '<input type="hidden" name="object[i_retp_coop_has_ass_1_center_cntr][]" value="' + center_id + '">';
  
  selected_center = '<li class="list_item half" id="' + Div_ID + '_' + center_id + '">' + delete_button + input_field + '<span class="css_icon css_topic">&nbsp;</span><a class="list_item_title tiny">' + center_name + '</a></li>';
  
  count_selected_centers = $('#' + Div_ID).children().length + 1;
  
  newHtmlContent = $('#' + Div_ID).html() + selected_center;
  
  $('#' + Div_ID).html(newHtmlContent);
  var diff = 10 - count_selected_centers;
  
  $('#' + count_more_center_id).html('' + diff);
  $('#' + select_box_id + " option[value='" + center_id + "']").remove();
  
  if (count_selected_centers >= count_more_center)
  {
    $('#' + select_box_id).attr('disabled', 'disabled');
  }
  else
  {
    $('#' + select_box_id).remove('disabled');
  }
}

function unselect_center(Div_ID, center_name, center_id, count_more_center, count_more_center_id, select_box_id)
{
//  delete_button = '<div class="css_item_inline_action css_normal"><div class="css_inline_action_delete" name="object" onclick="javascript:$(\"#" + Div_ID + '_' + center_id + '\').remove(); $(\"#" + select_box_id + '\').removeAttr(\'disabled\');" class="float_right"><div class="inner">Entfernen</div></div></div>';
  
//  input_field = '<input type="hidden" name="object[i_retp_coop_has_ass_1_center_cntr][]" value="' + center_id + '">';
  
  $('#' + Div_ID + '_' + center_id).remove();
  $('#' + select_box_id).removeAttr('disabled');
  
  count_selected_centers = $('#' + Div_ID).children().length;
  
  var diff = 10 - count_selected_centers;
  
  $('#' + count_more_center_id).html('' + diff);
  
  $('#' + select_box_id).append('<option value="' + center_id + '">' + center_name + '</option>');
  
  var selectedVal = $('#' + select_box_id).val();
  
  var $first_element = $('#' + select_box_id + " option[value='__not_set__']").html();
  $('#' + select_box_id + " option[value='__not_set__']").remove();
  
  // Sort options in selectbox
  
  //get the select
  var $dd = $('#' + select_box_id);
  if ($dd.length > 0) { // make sure we found the select we were looking for

      // save the selected value
      // var selectedVal = $dd.val();

      // get the options and loop through them
      var $options = $('option', $dd);
      var arrVals = [];
      $options.each(function(){
          // push each option value and text into an array
          arrVals.push({
              val: $(this).val(),
              text: $(this).text()
          });
      });

      // sort the array by the value (change val to text to sort by text instead)
      arrVals.sort(function(a, b){
        if(a.text>b.text){
          return 1;
      }
      else if (a.text==b.text){
          return 0;
      }
      else {
          return -1;
      }
  });

      // <option value="__not_set__">Bitte auswaehlen</option>
      // $($options[0]).val('__not_set__').text('Bitte auswaehlen');
      $($options[0]).html($first_element);
      
      // loop through the sorted array and set the text/values to the options
      for (var i = 0, l = arrVals.length; i < l; i++) {
          $($options[i + 1]).val(arrVals[i].val).text(arrVals[i].text);
      }

    // set the selected value back
    $dd.val(selectedVal);
  }
  
}

function cut_textextract(max_chars) {
  
  var max = max_chars;

  $('#module_textfields_result p').each(function(index, value) {

    var id = $(value).attr("id");
    var text = $(value).text();
    
    //remove multiple whitespaces  
    while ( text.search(/\s\s+/) != -1 )
    {
        text = text.replace(/\s\s+/,' ');
    }
   
    var length = text.length;
    
    if (length > max) {
      var text_part_1 = text.substr(0, max);

      var minimal_view = $('<p></p>');
      minimal_view.attr('id', id);
      minimal_view.text(text_part_1 + "... ");

      var maximal_view = $('<p></p>');
      maximal_view.attr('id', id);
      maximal_view.text(text);

      var more = $('<a>'+javascript_more+'</a>');
      more.click(function() {
        $('#' + id).replaceWith(maximal_view);
      });
      minimal_view.append(more);

      $(value).replaceWith(minimal_view);
    }
  });
}

function checkChecked(myclass, classname, element, backgroundEn, backgroundDis) 
{
  checked_elements = false;
  
  $('.' + myclass).each(function() {
    if ($(this).attr('checked')) {
      checked_elements = true;
    }
  });
  
  if (checked_elements == true) {
    $('.' + classname).each(function() {
      $(this).removeClass('css_disabled');
      $(this).unbind('click');
      $(this).click(function() {
        submit_form($(this).closest('form').attr('id'));
      });// 'javascript:submit_form($(this).closest(\"form\").attr(\"id\"));');
    });
  }
  else {
    $('.' + classname).each(function() {
      $(this).addClass('css_disabled');
      $(this).unbind('click');
    });
  }
}


/**
 * Set all checkboxes with class="classname" checked or
 * unchecked
 * @param string classname
 * @param boolean checked
 */
function setCheckBoxesNew(classname, checked) 
{
  $('.' + classname).each(function() {
    $(this).attr('checked', checked);
  });
}

function changeButton(classname, mode)
{
  if (mode == 'disabled')
  {
    $('.' + classname).each(function() {
      $(this).addClass('css_disabled');
    });
  }
  
  if (mode == 'enabled')
  {
    $('.' + classname).each(function() {
      $(this).removeClass('css_disabled');
    });
  }
}

/**
 * Select s_cplv_11_qualified if qualification was checked
 * Unselect it if no qualification was selected
 */
function checkQualification()
{
  var quali_selected = false;
  
  $('input[name="object[s_retp_pers_has_ass_m_qualification_prql][]"]:checked').each(function() { 
    quali_selected = true;
  });
  
  $('input[name="object[s_retp_obje_has_ass_1_req_comp_level_cplv]"]').attr('checked', quali_selected);
}

/**
 * Uncheck qualifications if not s_cplv_11_qualified was selected
 */
function checkLevel()
{
  $('input[name="object[s_retp_obje_has_ass_1_req_comp_level_cplv]"]:checked').each(function() { 
    if ($(this).attr('value') < 's_cplv_11')
    {
      $('input[name="object[s_retp_pers_has_ass_m_qualification_prql][]"]:checked').each(function() { 
        $(this).attr('checked', false);
      });
    }
  });
}

function hide_display_offerer_center_form(Div_id, colv, form_id)
{
  if (colv == 'i_colv_00_basic')
  {
    $('#' + Div_id).css('display', 'none');
    $('#' + form_id).find('.edit_element.button').css('display', 'block');
  }
  else
  {
    $('#' + Div_id).css('display', 'block');
    
    if (($('#' + form_id).find('.view_element').css('display') != 'none') && ($('#' + form_id).find('.css_toggle_showtype').html() == ''))
    {
      $('#' + form_id).find('.edit_element.button').css('display', 'none');
    }
    else
    {
      if ($('#' + form_id).find('.css_toggle_showtype').html() == '')
      {
        $('#' + form_id).find('.edit_element.button').css('display', 'block');
      }
      else
      {
        $('#' + form_id).find('.edit_element.button').css('display', 'none');
      }
    }
  }
}

function valid_object_id (object_id)
{
  var string = '' + object_id;
  
  if (!object_id.match(/^[a-z]_[a-z]{4}_[0-9]+/))
  {
    // object id is wrong
    return false;
  }
  else
  {
    // correct object id (x_xxx_n...)
    return true;
  }
}

function submit_on_valid_id(event, input_field_id, hidden_field_id, form_name, question)
{
  // keyCode == 13 => Enter-Key
  if (event.keyCode == 13)
  {
    if (valid_object_id($('#' + input_field_id).val()))
    {
      check = confirm(question + '.');
      if(check == true){
    	$('#' + hidden_field_id).attr('value', $('#' + input_field_id).val());
        $('form[name=' + form_name + ']').submit();
      }
    }
  }
}

function submit_on_enter(event, input_field_id, hidden_field_id, form_name, question_valid_id, primary_type_id )
{
  // keyCode == 13 => Enter-Key
  if (event.keyCode == 13)
  {
    if (valid_object_id($('#' + input_field_id).val()))
    {
      check = confirm(question_valid_id + '.');
      if(check == true){
      $('#' + hidden_field_id).attr('value', "!!?check?!!" + $('#' + input_field_id).val());
        $('form[name=' + form_name + ']').submit();
      }
    }
    else
    {
      console.log($('.ui-active-menuitem_last').length);
      console.log($('.ui-active-menuitem_last'));
      if ($('.ui-active-menuitem_last').length > 0)
      {
        console.log("exists");
        $('.ui-active-menuitem_last').click();
      }
      else
      {
        console.log("create_new_item");
        $('#' + hidden_field_id).attr('value', "!!?create---" + primary_type_id + "?!!" + $('#' + input_field_id).val());
        $('form[name=' + form_name + ']').submit();
      }
    }
  }
}

function select_autocomplete(event, autocomplete_box_id)
{
  // keyCode == 13 => Enter-Key
  if (event.keyCode == 13)
  {
    $('.ui-active-menuitem_last').removeClass('ui-active-menuitem_last');
    if ($('#ui-active-menuitem').length > 0)
    {
      console.log("exists_2");
      $('#ui-active-menuitem').addClass('ui-active-menuitem_last');
      $('#' + autocomplete_box_id).css('display', 'none');
      return false;
    }
  }
}

function autocomplete_nus_en_passant(form_id,primary_type_id)
{
  the_form              = $('#' + form_id);
  text_field_first_name = $('div.edit_row_row_2_float_left input[type="text"]',the_form);
  text_field_last_name  = $('div.edit_row_row_2_float_right input[type="text"]',the_form);
  hidden_value_field    = $('input[type="hidden"][name*="object[s_retp_"]',the_form);
  
  hidden_field_value = '!!?create---' + 
                       primary_type_id + 
                       "?!!" + 
                       text_field_first_name.val() + 
                       "|||" + 
                       text_field_last_name.val();
  
  hidden_value_field.attr("value",hidden_field_value);
  
  $('div.suggestions_list',the_form).hide();

}

function bulletin_board_create_object_menu(container_id,url)
{
  replace_with_loader_image(container_id);
  load_to_div (container_id, url);
}

function add_clickevent_to_multiportlet(data)
{
  for (var key in data) {
    if (data.hasOwnProperty(key)) {
      var container = data[key];
      value_begins_with = '#' + key + "_"; 
      current_link = $('a[href^="' + value_begins_with + '"]');
      current_link.bind('click.additional_clickevent', container, function(event) {    
        load_url_to_div_json( event.data );  
      });
    }
  }
}

function set_object_property(url,target_id,post_data)
{
  $.ajax({
    type: "POST",
    url: url,
    global: false,
    data: post_data,
    dataType: "html",
    async: true,
    success: function(data, textStatus, jqXHR) {
      replace_with_loader_image(target_id);  
      $('#' + target_id).html(data);
    }  
  });
}

