
/*
Script: Main.js
  Init-Function + Standard scripts

License:
  NetSkill AG
*/

window.addEvent('domready', function()
{
  listOfRequests = new Hash();
  autoSuggesting = false;
  autoSuggesting_req = false;
  
  // We'll just comment that out for now...
  // if ($('header_path'))
  //   {
  //     myHeaderPath = new HeaderPath();
  //   }
  
  if ($('google_search'))
  {
      google.load("search", "1");
      google.setOnLoadCallback(google_initialize);
  }


  elementEnhancer($('mysitenavi'));
  elementEnhancer($('change_language_navi'));

  //Flash Banner z-Index Bug-Fix
  $$('object').each(function(ele){
    myPutty = new Element('param', {'name': 'wmode', 'value': 'transparent'});
    myPutty.inject(ele);
    children = ele.getChildren("embed");

    if ($chk(children))
    {
      if ($chk(children[0]))
      {
        children[0].setProperty('wmode', 'transparent');;
      }
    }
    
    //ele.getParent().setStyles({"position": "relative", "z-index": 0});
    //ele.getParent().setStyles({"z-index": 0});
  });

  searchbar_toggle = true;
  
  banner_ready();
  
  // if ($$(".standard_portlethalf")[0])
  //   {
  //     links = $$(".standard_portlethalf")[0].getChildren()[1];
  //     rechts = $$(".standard_portlethalf_two")[0].getChildren()[1];
  //     links_c = links.getChildren()[0];
  //     rechts_c = rechts.getChildren()[0];
  //     
  //     h = links_c.getHeight();
  //     rh = rechts_c.getHeight();
  //     
  //     if (h < rh)
  //       h = rh;
  //       
  //     if (!Browser.Engine.trident)
  //       h += 10;
  //     
  //     //Set maximum height
  //     if (h > 160)
  //     {
  //       h = 160;
  //     }
  //     
  //     links.setStyle("height", h);
  //     rechts.setStyle("height", h);
  //   }
  
  if (!Browser.Engine.trident)
  {
    if ($$(".corpus_middle_main_content") && $$(".corpus_middle_main_content")[0] && $$(".corpus_middle_main_content")[0].getHeight() > $$(".corpus_middle_main_content_right")[0].getHeight())
    {
      $$(".corpus_middle_main_content_right")[0].setStyle("height", $$(".corpus_middle_main_content")[0].getHeight() - 10);
    }
  }
  if ($("ccBanner_5"))
  {
    $("ccBanner_5").addEvents({
      'mouseenter': function() {
        now = $("ccBanner_5").getStyle("background-image");
        $("ccBanner_5").setStyle("background", now.substring(0,now.lastIndexOf("/")+1) + "competence_edge_1.png) no-repeat top right");
      },
      'mouseleave': function() {
         now = $("ccBanner_5").getStyle("background-image");
        $("ccBanner_5").setStyle("background", now.substring(0,now.lastIndexOf("/")+1) + "competence_edge_2.png) no-repeat top right");
      }
    });
  }
  if (initial_scroll_to_a_name)
  {
    scroll_to_a_name_standard(initial_scroll_to_a_name);
  }

});

function banner_ready()
{
  if ($$('.competence_card_banner').length > 0)
  {
    $$('.competence_banner_div').each(function(peace){
      myID = peace.id;
      $(myID + "_word").setStyle("display", "none");
      
      peace.addEvent('mouseenter', function(){
        name_now = this.id;
        oldPath = $(name_now + "_peace").getAttribute('src');
        if (oldPath.substring(oldPath.length - 5, oldPath.length) != "b.png")
        {
          oldPath = oldPath.substring(0,oldPath.length - 4) + "b.png";
          $(name_now + "_peace").setAttribute('src', oldPath);
          $(name_now + "_word").setStyle("display", "block");
        }
      }, peace);
      
      peace.addEvent('mouseleave', function(){
        name_now = this.id;
        oldPath = $(name_now + "_peace").getAttribute('src');
        oldPath = oldPath.substring(0,oldPath.length - 5) + ".png";
        $(name_now + "_peace").setAttribute('src', oldPath);
        $(name_now + "_word").setStyle("display", "none");
      }, peace);
    });
  $$('.competence_banner_div')[0].fireEvent("mouseenter");
  }
}

window.addEvent('load', function()
{
  if ($('showWarningBox'))
    {
    if(!Browser.Engine.trident4)
    {
      showWarningBox();
    }
    }
});

function scroll_to_a_name(myName)
{
  position = $$("a[name="+ myName +"]")[0].getPosition().y - 150;
  $$(".download_button")[0].removeProperty("href");

  window.scrollTo(0, position);
  return false;
}
//WarningBox
function showWarningBox()
{
    test = new Element('div', {
    'id': 'test',
    'styles': {'position': 'fixed','background': 'gray','height': '100%','width': '100%','z-index': '500','top': '0px','left': '0px','opacity': '0'},
    'onclick': 'hideWarningBox()'
    });
    
    $('body').adopt(test);
    $('body').adopt($$('.user_message_portlet')[0]);
    // $('user_message').dispose();
    var myFx = new Fx.Tween($(test)).start('opacity',0.7);
    $$('.user_message_portlet')[0].inject($('body'), 'top');
    $$('.user_message_portlet')[0].setStyles({'position': 'fixed', 'z-index': '9999', 'top': '40px', 'left': ($('body').getSize().x)/2-490, 'width': '980px'});
}
function hideWarningBox()
{
  element = $('test');
  if ($$('.user_message_portlet') != "")
  {
    $$('.user_message_portlet')[0].dispose();
  }
  if ($$('.user_message_portletajax') != "")
  {
    $$('.user_message_portletajax')[0].dispose();
  }
  if ($('user_message'))
  {
    $('user_message').dispose();
  }
  if (element)
  {
    var myFx = new Fx.Tween($(element)).start('opacity',0).chain(function(){$(element).dispose()});
  }
}

/*
* Simple functions
  A Collection of little helper scripts used everywhere
*/

//elementEnhancer is an effect used for the mySite + LanguageSelection Boxes
function elementEnhancer (element)
{
  if (element)
  {
    element.addEvents({
      'click': function () {
        element.getChildren(".dropdown").each(function(ele){
          ele.setStyle("display", "block");
        });
      },
      'mouseleave': function () {
        element.getChildren(".dropdown").each(function(ele){
          ele.setStyle("display", "none");
        });
      }
    });
  }

}
function set_content(Div_ID, new_Content)
{
  $(Div_ID).innerHTML = new_Content;
}

function fillitup(target_id, suggestions_list_id, key)
{
  // put value into input field
  $(target_id).value = key;

  // undisplay suggestions
  $(suggestions_list_id).setStyle('display', 'none');
}

function suggestItToMe(target, suggestions_list_id, myURL)
{
  if (autoSuggesting)
  {
    $clear(autoSuggesting);
    if (autoSuggesting_req)
    {
      autoSuggesting_req.cancel();
    }
  }
  if (target.value.length > 2)
  {
    var myHelper = function(target, suggestions_list_id, myURL){
      autoSuggesting_req = new Request.JSON({url: myURL, onComplete: function(auto){
          var myList = new Hash(auto);

          $$("#"+suggestions_list_id+" ul")[0].set('html', "");

          myList.each(function(value, key){
            link = new Element('a', {
              'html': key,
              'href': 'javascript:fillitup(\''+target.id+'\',\''+suggestions_list_id+'\',\''+key+'\')'
            });

            ele = new Element('li');

            link.inject(ele);

            ele.inject($$("#"+suggestions_list_id+" ul")[0]);
          });

          $(suggestions_list_id).setStyle('display', 'block');

          target.addEvent('keydown', function(e){
            suggestions_list_ul_li = $$("#"+suggestions_list_id+" ul li");
            selected = $$('.suggestion_selected')[0];
            if (e.key == 'down')
            {
              if (selected)
              {
                myid = parseFloat(selected.id) + 1;
                selected.removeClass("suggestion_selected");
                if (!suggestions_list_ul_li[myid])
                {
                  myid = 0;
                }
                suggestions_list_ul_li[myid].id = myid;
                suggestions_list_ul_li[myid].addClass("suggestion_selected");
              }
              else
              {
                suggestions_list_ul_li[0].id = 0;
                suggestions_list_ul_li[0].addClass("suggestion_selected");
              }
              return false;
            }
            else if (e.key == 'up')
            {
              if (selected)
              {
                myid = parseFloat(selected.id) - 1;
                selected.removeClass("suggestion_selected");
                if (!suggestions_list_ul_li[myid])
                {
                  myid = suggestions_list_ul_li.length - 1;
                }
                suggestions_list_ul_li[myid].id = myid;
                suggestions_list_ul_li[myid].addClass("suggestion_selected");
              }
              else
              {
                suggestions_list_ul_li[suggestions_list_ul_li.length - 1 ].id = suggestions_list_ul_li.length - 1;
                suggestions_list_ul_li[suggestions_list_ul_li.length - 1].addClass("suggestion_selected");
              }
              return false;
            }
            else if (e.key == 'enter')
            {
              myString = $$('.suggestion_selected a')[0].get('href');

              while (myString != myString.replace("%20"," "))
              {
                myString = myString.replace("%20"," ");
              }

              eval(myString);
              return false;
            }
          })
          autoSuggesting = false;
          autoSuggesting_req = false;
      }}).post({"value": target.value});
    }
    autoSuggesting = myHelper.delay(250, this, [target, suggestions_list_id, myURL]);
  }
  else
  {
    $(suggestions_list_id).setStyle('display', 'none');
  }
}

function check_count(Form, relation, count)
{
  //counter checked with count
  var counter = 0;

  tags = $$('.' + relation);

  //get count of checked boxes
  tags.each (function(element)
  {
    if (element.checked)
    {
      counter = counter + 1;
    }
  });

  $('count_more_center').innerHTML = 10 - counter;

  //compare counter with allowed count
  if (counter >= count)
  {
    tags.each (function(element)
    {
      if (!element.checked)
      {
        element.disabled = 'disabled';
      }
    });
  }

  if (counter < count)
  {
    tags.each (function(element)
    {
      element.disabled = '';
    });
  }
}

function check_country(field, field_region)
{
  country = $(field);

  region = $(field_region);
  if (country.value == 's_area_ctry_germany_de')
  {
    $('address_region').style.display = 'block';
  }
  else
  {
    $('address_region').style.display = 'none';
    region.value = '';
  }
}

function submit_checkbox(form_name, relation, value)
{
  var checkboxes = document.forms[form_name].elements['object[' + relation + '][]'];

  for (var i=0; i<checkboxes.length; i++)
  {
    if (checkboxes[i].value == value)
    {
      if (checkboxes[i].checked)
      {
        checkboxes[i].checked = "";
      }
      else
      {
        checkboxes[i].checked = "checked";
      }
    }
  }
}

function clear_hint_as_value(element)
{
  if (typeof( element.clear_on_click ) == "undefined") {element.clear_on_click = true;}
  if (element.clear_on_click)
  {
    element.value = "";
    element.style.color = "#000000";
    element.clear_on_click = false;
  }
}

function show_hint_as_value(element, hint)
{
  if (element.value == "")
  {
    element.value = hint;
    element.style.color = "#888888";
    element.clear_on_click = true;
  }
}

function disable_button(ID)
{
  var button_height = $("button_" + ID).getHeight();
  var button_width = $("button_" + ID).getWidth();

  $("disable_button_" + ID).setStyle("height", button_height);
  $("disable_button_" + ID).setStyle("width", button_width);
  $("disable_button_" + ID).style.display = '';
}
function set_hight_right_column ()
{
  $$(".corpus_middle_main_content_right")[0].setStyle('height', 'auto');
}
function expand_div(ID, new_height)
{
  $(ID).setStyle("height", new_height);
  $("expand_button_" + ID).setStyle("display", "none");
}
function cc_switch(id) {
  $$('.competence_card_switch_content_element').each(function(ele){
    ele.setStyle('display', 'none');
  });
  $(id).setStyle('display', 'block');
  $$('.competence_card_switch_button').each(function(ele){
    ele.removeClass('competence_card_switch_button_active');
  });
  $(id + "_button").addClass('competence_card_switch_button_active');
  return false;
}

function init_advisor_scroll() {
  if ($('advisor_list_scroll')) {
    advisor_list = $('advisor_list_scroll');
    if (advisor_list.children.length > 7) {
      for (i = 7; i < advisor_list.children.length; i++) {
        advisor_list.children[i].style.display = "none";
      }
    }
    advisor_list_position = 0;
  }  
}

function scroll_right() {
  if ( typeof( advisor_list ) == "undefined") init_advisor_scroll();
  if ( typeof( advisor_list.children[advisor_list_position + 7]) != "undefined" ) {
    advisor_list.children[advisor_list_position].style.display = "none";
    advisor_list.children[advisor_list_position + 7].style.display = "block";
    advisor_list_position++;
  }
}

function scroll_left() {
  if ( typeof( advisor_list ) == "undefined") init_advisor_scroll();
  if ( advisor_list_position > 0 && typeof( advisor_list.children[advisor_list_position - 1]) != "undefined") {
    advisor_list.children[advisor_list_position - 1].style.display = "block";
    advisor_list.children[advisor_list_position + 6].style.display = "none";
    advisor_list_position--;
  }
}

/**
 * HeaderPath
 *
 * Contains the new HeaderPath Class for switching the header
 *
 * Author        Version  Date      Comment
 * ------------  -------  --------  --------------------------------------------
 * L.Dohmen      0.9      13.06.08  first version, not cleaned up
 * L.Dohmen      1.0      13.06.08  cleaned up
 * L.Dohmen      1.1      16.06.08  Mootools 1.2 ready
 * L.Dohmen      1.2      18.08.08  Renamed to HeaderPath, only title-switch remains
 * L.Dohmen      1.3      19.08.08  Added functionality for ie6 (without transition)
 * L.Dohmen      1.4      20.03.09  Banner Switch only for Center
 * L.Dohmen      1.5      02.04.09  Due to marketing decissions this is commented out
 *
 * @version     1.3
 * @author      L.Dohmen
 * @package     Javascript
 */

// var HeaderPath = new Class({
// 
// 	competence_header1: $('header_1'),
// 	competence_header2: $('header_2'),
// 
// 	initialize: function()
// 	{
// 		if (toggle_welcome_banner)
// 		{
// 			if (!Browser.Engine.trident4)
// 			{
// 				this.header_switch.periodical(5000, this);
// 			}
// 			else
// 			{
// 				//IE6 doesnt support opacity
// 				this.header_switch_no_animation.periodical(5000, this);
// 			}
// 		}
// 	},
// 	header_switch: function()
// 	{
// 		if (this.competence_header1.getStyle('display') == 'none') {
//       		this.competence_header1.setStyle('display', 'block');
//       		this.competence_header2.setStyle('display', 'none');
//     	}
//     	else
//     	{
//       		this.competence_header1.setStyle('display', 'none');
//       		this.competence_header2.setStyle('display', 'block');
//     	}
// 	},
// 	header_switch_no_animation: function()
// 	{
// 		if (this.competence_header1.getStyle('display') == 'none') {
// 			this.competence_header1.setStyle('display', 'block');
// 			this.competence_header2.setStyle('display', 'none');
// 		}
// 		else
// 		{
// 			this.competence_header1.setStyle('display', 'none');
// 			this.competence_header2.setStyle('display', 'block');
// 		}
// 	}
// });
function toggle_div(Div_ID)
{
	if ($(Div_ID).getStyle('display') == 'none')
	{
		$(Div_ID).setStyle('display', '');
	}
	else
	{
		$(Div_ID).setStyle('display', 'none');
	}
}

function select_center(Div_ID, center_name, center_id, count_more_center, select_box_id)
{
	delete_button = '<a><image type="image" src="http://tg-local.net/gfx/action_delete_relation.png" name="object" onclick="javascript:$(\'' + Div_ID + '\').removeChild($(\'' + Div_ID + '_' + center_id + '\')); $(\'' + select_box_id + '\').removeAttribute(\'disabled\');" class="float_right"></a>';
	input_field = '<input type="hidden" name="object[i_retp_coop_has_ass_1_center_cntr][]" value="' + center_id + '">';
	selected_center = '<div style="margin: 2px" id="' + Div_ID + '_' + center_id + '">' + center_name + delete_button + input_field + '</div>';
	count_selected_centers = $(Div_ID).childNodes.length;
	
	$(Div_ID).innerHTML = $(Div_ID).innerHTML + selected_center;
	$('count_more_center').innerHTML = count_more_center - count_selected_centers; 
	
	if (count_selected_centers >= count_more_center)
	{
		$(select_box_id).disabled = 'disabled';
	}
	else
	{
		$(select_box_id).removeChild('disabled');
	}
}

function div_ajax(Div_ID, myURL, relation, toggle)
{
	//Use parent if div class="ajax" is available
	if ($(Div_ID).parentNode.className == "ajax")
  {
    update_div = $(Div_ID).parentNode;
  }
  else
  {
    update_div = $(Div_ID);
  }
	
	
	var myAjax = new Request.HTML({url: myURL, update: update_div, evalScripts: true});
	
	if (listOfRequests.has(Div_ID))
	{
		old = listOfRequests.get(Div_ID);
		if (toggle)
		{
		  old[1].cancel();
		}
		if (old[0] == myURL)
		{
			if (toggle)
			{
			  listOfRequests.erase(Div_ID);
			  $(Div_ID).innerHTML = " ";
			}
		}
		else
		{
			div_ajax_helper(Div_ID, myURL, myAjax);
		}
	}
	else
	{
		div_ajax_helper(Div_ID, myURL, myAjax);
	}
}

function div_ajax_only(Div_ID, myURL, relation)
{
  update_div = $(Div_ID);

  var myAjax = new Request.HTML({url: myURL, update: update_div, evalScripts: true});
  
  div_ajax_helper(Div_ID, myURL, myAjax);
}

function div_ajax_helper_new(Div_ID, myURL, myAjax)
{
  do_inactive(Div_ID);
  listOfRequests.set(Div_ID, [myURL, myAjax]);
  myAjax.get();
  myAjax.onSuccess = do_active();
}

function div_ajax_helper(Div_ID, myURL, myAjax)
{
	showLoader(Div_ID);
	listOfRequests.set(Div_ID, [myURL, myAjax]);
	myAjax.get();
	
}

function div_ajax_new(Div_ID, myURL, relation, warning)
{
	
	if (warning)
	{
		changes = false;
		checkArray = new Hash();
		
		$$('#' + Div_ID + ' textarea').each(function(item) {
			checkArray.set(item.name, item.id);
		});
		
		$$('#' + Div_ID + ' input').each(function(item) {
			if (item.type == "hidden")
			{
				if(checkArray.has(item.name.substring(3)))
				{
					if ($(checkArray.get(item.name.substring(3))).value != item.value)
					{
						changes = true;
					}
				}
			}
		});
		
		if (changes)
		{
			
			if (confirm("Ohne speichern zurueck?"))
			{
				div_ajax(Div_ID, myURL, relation);
			}
		}
		else
		{
			div_ajax(Div_ID, myURL, relation);
		}
	}
	else
	{
		div_ajax(Div_ID, myURL, relation);
	}
}

function showLoader(name)
{
	if ($$('#' + name + ' .ajax_loader_icon').length == 0)
	{
		e = $(name);
		myLeft = e.getSize().x/2 - 10;
		myImage = new Element('img', {'src': config_ajaxloadergfx, 'class': 'ajax_loader_icon', 'styles': {'left': myLeft, 'position': 'relative', 'margin':'5px'}});
		myLoader = new Element('div', myImage);
		myLoader.inject(e);
	}
}

function showLoaderCentered(name)
{
	if ($$('#' + name + ' .ajax_loader_icon').length == 0)
	{
		e = $(name);
		myLeft = e.getPosition().x + e.getSize().x/2 - 10;
		myRight = e.getPosition().y + e.getSize().y/2 - 10;
		myLoader = new Element('img', {'src': config_ajaxloadergfx, 'class': 'ajax_loader_icon', 'styles': {'left': myLeft, 'right': myRight, 'position': 'relative', 'margin':'5px'}});
		myLoader.inject(e);
	}
}

/* works but not used
// replaces a div with the given id by busy-icon
function showBusy(busy_icon_div_id)
{
   myLoader = new Element('div', {'styles': {'text-align': 'center'}});
	 myLoader_image = new Element('img', {'src': config_ajaxloadergfx, 'class': 'ajax_loader_icon', 'styles': {}});
	 myLoader.appendChild(myLoader_image);
	 
	 myLoader.replaces(busy_icon_div_id);
}
*/

// replaces the children of the element with the given id by busy-icon
function replaceContentByBusyIcon(root_div_id)
{
  root_div = $(root_div_id);
  
  // remove all children
  children = root_div.getChildren();
  children.each (function(item) {
    root_div.removeChild(item);
  }, this);

  // create div for centering the icon
  myLoader = new Element('div', {'styles': {'text-align': 'center'}});
  myLoader_image = new Element('img', {'src': config_ajaxloadergfx, 'class': 'ajax_loader_icon', 'styles': {}});
  myLoader.appendChild(myLoader_image);
  
  // append the icon to the root
  root_div.appendChild(myLoader);
}

// function scroll_to_element_if_not_in_sight(element) {
//     element = $(element);
//     if (!element) return; // element invalid, not found
// 
//   	var dims_div = element.getCoordinates();
//   	win_div = Math.abs(window.getScroll().y - dims_div.top + 118);
//   	
// 	var scroll = new Fx.Scroll(window, {
//     	wait: false,
//     	duration: win_div,
//     	offset: {'x': -50, 'y': 0},
//     	transition: Fx.Transitions.Quad.easeInOut
//   	});
// 	
// 	scroll.start(0, dims_div.top - 118);
// }

var Check;

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_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 form_element_set_error(inputfield, errordiv, is_error) {
  inputfield = $(inputfield);
  errordiv = $(errordiv);
  if (!inputfield || !errordiv) return;
  
  var color = is_error?"#ff6c44":"white";
  var display = is_error?"block":"none";

	inputfield.style.background = color;
	errordiv.style.display = display;
}

//Check if email is correct
function checkemail(email)
{
	return checkRegExList([/^[a-z0-9\-\_\.]+@[a-z0-9\-\_\.]+\.[a-z0-9\-\_\.]+$/i], email);
}

//Check Quality of Password
function qualityCheck(word)
{
	password0 = checkRegExList([/[a-zA-Z]/, /.{5}/], word);
	password1 = checkRegExList([/[0-9]/], word);
	password2 = checkRegExList([/[^a-zA-Z0-9]/], word);
	
	if (!password0)
		returnVal = 0;
	else if(!password1)
		returnVal = 1;
	else if(!password2)
		returnVal = 2;
	else
		returnVal = 3;
	return returnVal;
}

//Helper Function: Checks a word against an Array of regExes
function checkRegExList(regExList, word)
{
	passed = true;
	regExList.each(function(regEx)
	{
		if (!regEx.exec(word))
		{
			passed = false;
		}
	});
	return passed;
}

/**
 * Set all checkboxes with class="classname" checked or
 * unchecked
 * @param string classname
 * @param boolean checked
 */
function setCheckBoxes(classname, checked) 
{
  checked = checked?true:false; // make sure its boolean
  $$(classname).each(function(elem) {
    elem.checked = checked;
  });
}

/**
 * Set all checkboxes with class="classname" checked or
 * unchecked
 * @param string classname
 * @param boolean checked
 */
function setCheckBoxesNew(classname, checked) 
{
  classname = "." + classname;
  
  $$(classname).each(function(elem) {
    elem.checked = checked;
  });
}

/**
 * Set background of all elements with
 * class="classname"
 * @param string classname
 * @param string background
 * 'url("/gfx/button_black_113.png") no-repeat scroll 0 0 transparent';
 */
function changeBackground(classname, background) 
{
  classname = "." + classname;
  
  $$(classname).each(function(elem) {
    elem.style.background = 'url("/gfx/' + background + '") no-repeat scroll 0 0 transparent';
  });
}

function changeType(classname, type)
{
  classname = "." + classname;
  
  $$(classname).each(function(elem) {
    //elem.type = type;
    var newO = document.createElement('input');
    newO.setAttribute('type',type);
    newO.setAttribute('class',elem.getAttribute('class'));
    newO.setAttribute('name',elem.getAttribute('name'));
    newO.setAttribute('value',elem.getAttribute('value'));
    newO.setAttribute('style',elem.getAttribute('style'));
    elem.parentNode.replaceChild(newO, elem);
    newO.focus();
  });
}

function checkChecked(myclass, classname, element, backgroundEn, backgroundDis) 
{
  myclass = "." + myclass;
  checked_elements = false;
  
  $$(myclass).each(function(elem) {
    if (elem.checked == true) {
    	checked_elements = true;
    }
  });
    if (checked_elements == true) {
      changeBackground(classname, backgroundEn);
      changeType(classname, 'image');
    }
    else {
      changeBackground(classname, backgroundDis);
      changeType(classname, 'reset');
    }
}


/** maybe will get reintegrated...
 *
 * adds receiver fields to according div. belongs to module_message_new,
 * needs edit_row_autocomplete
 * @param string inputfield_id
 * @param {Object} entry containing name, id, image
 
function module_message_new_addreceiver(inputfield_id, entry){
  var input_field = $(inputfield_id);
  var divId = 'mailreceiver_' + entry.id;
  if (!$(divId)) {
    // receiver not in list, so add
    var resultdiv = $(input_field.id + '_autocomplete_results');
    var elementdiv = new Element('div', {id: divId, value: entry}).set('text', entry.name).addClass('receiver');
    // add image
    var imgdiv = new Element('div').addClass('image').inject(elementdiv, 'top');
    if (entry.image) {
      new Element('img', {src: entry.image}).inject(imgdiv);
    } else {
      imgdiv.set('text', ' ');
    }
    // add remove button
    new Element('input', {type: 'button'}).addEvent('click', function(evnt) {
      $(divId).dispose();
    }).addClass('removeButton').inject(elementdiv, 'top');
    // add hidden fields
    new Element('input', {type: 'hidden', name: 'object[Receiver][id][' + entry.id + ']', value: entry.id}).inject(elementdiv);
    new Element('input', {type: 'hidden', name: 'preobject[Receiver][id][' + entry.id + ']', value: ''}).inject(elementdiv);
    elementdiv.inject(resultdiv);
  }
}*/

/*
Script: set_relation.js
	Init-Function + Standard scripts

License:
	NetSkill AG
*/

function get_module_set_relation_result(target, myURL, text_fields)
{
	if (autoSuggesting)
	{
		$clear(autoSuggesting);

		if (autoSuggesting_req)
		{
			autoSuggesting_req.cancel();
		}
	}
	
	//Get Search Term
	search_term = $(text_fields).value;

	//Check if search term is more than 3
	if (search_term.length > 2)
	{
		myURL = myURL.replace("--search_term--", (typeof(encodeURIComponent)=="function")?encodeURIComponent(search_term):escape(search_term));

		showLoader(target);
		var myHelper = function(target, myURL, text_fields){
		
			autoSuggesting_req = new Request.HTML({url: myURL, update: target, evalScripts: true, onComplete: function(auto){
					var myList = new Hash(auto);
					autoSuggesting = false;
					autoSuggesting_req = false;
			}}).get();
		}
		
		autoSuggesting = myHelper.delay(250, this, [target, myURL, text_fields]);
	}
	else
	{
      $(target).innerHTML = "";
	}
}



function get_module_set_relation_double_result(target, myURL, text_field, text_fields)
{
  if (autoSuggesting)
  {
    $clear(autoSuggesting);
    if (autoSuggesting_req)
    {
      autoSuggesting_req.cancel();
    }
  }
  
  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]).value.length > 0)
    {
      get_object = true;
    }
  }
  input_value = $(text_field).value;

  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]).value;
	  
	  if (i < text_fields_array.length - 1)
	  {
		  search_term = search_term + "--trenner--";
	  }
	}
	
	//Set Ajax request
	myURL = myURL.replace("--search_term--", search_term);
	myURL = encodeURI(myURL);

	showLoader(target);
	var myHelper = function(target, myURL, text_fields){
		autoSuggesting_req = new Request.HTML({url: myURL, update: target, evalScripts: true, onComplete: function(auto){
				var myList = new Hash(auto);
				autoSuggesting = false;
				autoSuggesting_req = false;
		}}).post({"search_term": search_term});
	}
	
	autoSuggesting = myHelper.delay(250, this, [target, myURL, text_fields]);
  }
  else
  {
    $(target).innerHTML = "";
  }
}
function close_set_relation_searchbox(searchbox)
{
  searchbox_array = $$('.' + searchbox);
  searchbox_count = searchbox_array.length;
  
  for (i = 0; i < searchbox_count;i++)
  {
    searchbox_array[i].innerHTML = "";
  }
}

function change_link_primary_type(link_primary_type)
{
  $$('.module_set_relation_lpt').setStyle('color', '#346B87');
  
  $(link_primary_type).style.color = 'black';
}






function get_module_set_relation_result_old(DIV, URL, text_fields)
{
  search_term = $(text_fields).value;
  
  if (search_term.length > 3)
  {
    URL = URL.replace("--search_term--", search_term);
    
    //Set Ajax request
    update_div = $(DIV);

    var myAjax = new Request.HTML({url: URL, update: update_div, evalScripts: true});
    
    div_ajax_helper(Div_ID, URL, myAjax);
  }
}

/**
 * used by searchbox.cns
 * @param string mode "simple" or "advanced"
 * @param string type e.g. "person"
 * @param object structure js_perspective_definitions
 * @param object all_id_list js_field_names
 */
function search_switch_to(mode, type, structure, all_id_list) {
//console.log("switch to \""+mode+"\" \""+type+"\"");
  if (type == '' || type == '__no_value__') type='all';

  if (type=="current") type = this.current_type;
  else this.current_type = type;

  if (mode=="current") mode = this.current_mode;
  else this.current_mode = mode;
    
  var actions;
  
  // go through all
  for (var id in all_id_list)
  {
//console.log("id \""+id+"\"");
	  if (structure[mode] && structure[mode][type] && structure[mode][type][id])
	  {
	    // show field
	    open_tag (id);
	    actions = structure[mode][type][id];
	  }
	  else
	  {  
	    // hide field
	    close_tag(id);
	    actions = all_id_list[id];
	  }
	
		// execute actions
		var index = 0;
	  while (true)
	  {
      if (actions[index])
      {
		    var action = actions[index];
		    switch (action.action)
		    {
		      case 'set_caption':
//console.log("set_caption of "+action.id+" to \""+action.content+"\"");
		        set_content(action.id, action.content);
		        break;
		        
		      case 'activate':
//console.log("activate "+action.id);
		        $(action.id).disabled = false;
		        break;
		        
		      case 'deactivate':
//console.log("deactivate "+action.id);
		        $(action.id).disabled = true;
		        break;
		        
		      case 'set_options':
//console.log("set_options of "+action.id);
		        $(action.id).options.length = 0;
		        for (var i = 0; i < action.options.length; i++)
		        {
		          if (action.options[i]["selected"])
		          {
		            selected = true;
		          }
		          else
		          {
		            selected = false;
		          }
		          $(action.id).options[i] = new Option(action.options[i]["text"], action.options[i]["value"], selected, selected);
		        }
		        break;
		    }
		  }
		  else
		  {
		    // break loop
		    break; 
		  }
		  
		  index++;
	  }
	}

	$$(".competence_card_content_inner")[0].setStyle("height", "auto");
	if ($$(".competence_card_content_inner")[0].getHeight() <  212)
		$$(".competence_card_content_inner")[0].setStyle("height", "212px");

  $$(".competence_card")[0].setStyle("height", "auto");
  if ($$(".competence_card")[0].getHeight() <  280)
    $$(".competence_card")[0].setStyle("height", "280px");

}

