/*
* @copyright Copyright 2010 Adolf Würth GmbH & Co. KG
* @link  http://www.wuerth.de
* @version  0.1
* @lastmodified    2010-02-17
*/

/*BUGFIX onmouseover, onmouseout with child elements*/
function containsDOM (container, containee) {
  var isParent = false;
  do {
    if ((isParent = container == containee))
      break;
    containee = containee.parentNode;
  }
  while (containee != null);
  return isParent;
}

function checkMouseEnter (element, evt) {
  if (element.contains && evt.fromElement) {
    return !element.contains(evt.fromElement);
  }
  else if (evt.relatedTarget) {
    return !containsDOM(element, evt.relatedTarget);
  }
}

function checkMouseLeave (element, evt) {
  if (element.contains && evt.toElement) {
    return !element.contains(evt.toElement);
  }
  else if (evt.relatedTarget) {
    return !containsDOM(element, evt.relatedTarget);
  }
}
/*END BUGFIX onmouseover, onmouseout with child elements*/

/*
* replace search select by fake select for having more opportunities
* in styling the select.
* call it like this: <body onload="prepareSearchSelect();" onclick="hideFakeSelect(event);">
* and fill in the needed IDs...to avoid DOM flickering some CSS things need
* to be done
*/
//avoid DOM flickering => see CSS
document.documentElement.className += ' js';

//START functions to handle keyboard actions
function onFakeSelectKeypress2(event){
  //CONFIG
  //real select
  var mySelect = document.getElementById(this.selectId);
  //area for the fake select
  var myReplace = document.getElementById(this.replaceId);
   //show text of fake selection
  var myCurrent = document.getElementById(this.currentTextId);
  //fake selection options
  var myOptions = document.getElementById(this.fakeOptionsId);

  if(mySelect != null && myReplace != null && myCurrent != null && myOptions != null){
    //just the active one
    if(myOptions.style.display == 'block'){
      switch(event.keyCode){
        case Event.KEY_UP:
          setIndexOfSelectedFakeOption(myOptions, getIndexOfSelectedFakeOption(myOptions, this.bconover, this.bconout), 'up', this.bconover, this.bconout, this.attr, this.attrNoAction);
          if(event.preventDefault) event.preventDefault(); else return false;
          return;
        case Event.KEY_DOWN:
          setIndexOfSelectedFakeOption(myOptions, getIndexOfSelectedFakeOption(myOptions, this.bconover, this.bconout), 'down', this.bconover, this.bconout, this.attr, this.attrNoAction);
          if(event.preventDefault) event.preventDefault(); else return false;
          return;
        case Event.KEY_ESC:
          myOptions.style.display = 'none';
          return;
        case Event.KEY_RETURN:
          var tmpDecider = getInfoFromSelectedFakeOption(myOptions, this.attr, 'rel', this.bconover, this.bconout, this.maxLength);
          if(tmpDecider != this.attrNoAction){
            mySelect.value = getInfoFromSelectedFakeOption(myOptions, this.attr, 'rel', this.bconover, this.bconout, this.maxLength);
            setSearchArea2(mySelect.value, this.selectId);
            //update the current text with the text of the fake select
            myCurrent.innerHTML = getInfoFromSelectedFakeOption(myOptions, this.attr, 'html', this.bconover, this.bconout, this.maxLength);
            myOptions.style.display = 'none';
            afterUpdateFakeSelect(this.functionCall, this.functionParams);
          }
          return false;
      }
    }
  }
  return;
}
function getInfoFromSelectedFakeOption(optionElement, attr, type, bconover, bconout, maxLength){
   var myOptions = optionElement;
   var liArray = myOptions.getElementsByTagName('li');
   var index = getIndexOfSelectedFakeOption(optionElement, bconover, bconout);
   if(index >= 0){
     if(type.toLowerCase() == 'html') return shortenFakeSelectText(liArray[index].innerHTML,maxLength);
     if(type.toLowerCase() == 'rel') return liArray[index].getAttribute(attr);
   }
   return '';
}
function clearAllSelectedFakeOptions(optionElement, bconover, bconout){
  var myOptions = optionElement;
  var liArray = myOptions.getElementsByTagName('li');
  for (var i = 0; i < liArray.length; i++) {
    liArray[i].style.backgroundColor = bconout;
  }
}
function getIndexOfSelectedFakeOption(optionElement, bconover, bconout){
   var myOptions = optionElement;
   var liArray = myOptions.getElementsByTagName('li');
   for (var i = 0; i < liArray.length; i++) {
     if(liArray[i].style.backgroundColor != bconout) return i;
   }
   return 0;
}
function setIndexOfSelectedFakeOption(optionElement, index, type, bconover, bconout, attr, attrNoAction){
   var myOptions = optionElement;
   var liArray = myOptions.getElementsByTagName('li');
   if(index >= 0){
     if(type == 'up' && index > 0 && liArray[index-1] != null && liArray[index-1] != undefined){
         liArray[index-1].style.backgroundColor = bconover;
     }
     if(type == 'down' && liArray[index+1] != null && liArray[index+1] != undefined){
         liArray[index+1].style.backgroundColor = bconover;
     }
     liArray[index].style.backgroundColor = bconout;
   }
}
//END functions to handle keyboard actions
//prepare a fake select with divs
//functionParams only comma separated...e.g. 'foo,bar,test'
function prepareSearchSelect(selectId, replaceId, currentTextId, fakeOptionsId, functionCall, functionParams, cutText, width) {
  //CONFIG
  //onmouseover background color
  var bconover = '#DEDEDE';
  //onmouseout background color
  var bconout = '';
  //attribute of fake option (li) used like "value" of real select
  var attr = 'rel';
  //attribute where nothing should happen (rel="aaa") => separator in drop-down
  var attrNoAction = 'aaa';
  //max length of characters before cutting them off
  var maxLength = 33;
  if(cutText != '' && cutText != null) maxLength = cutText;
  //width of select
  var selectWidth = '';
  if(width != '' && width != null) selectWidth = width + 'px';
  //real select
  var mySelect = document.getElementById(selectId);
  //area for the fake select
  var myReplace = document.getElementById(replaceId);
  //show text of fake selection
  var myCurrent = document.getElementById(currentTextId);
  //fake selection options
  var myOptions = document.getElementById(fakeOptionsId);
  //object for event handling function
  var obj = {
    selectId:selectId,
    replaceId:replaceId,
    currentTextId:currentTextId,
    fakeOptionsId:fakeOptionsId,
    functionCall:functionCall,
    functionParams:functionParams,
    bconover:bconover,
    bconout:bconout,
    attr:attr,
    attrNoAction:attrNoAction,
    maxLength:maxLength,
    width:width
  };
  if(navigator.userAgent.toLowerCase().indexOf('MSIE'.toLowerCase())>-1){
    //IE can handle replaceId => but error is shown in browser
    //Event.observe(document, 'keypress', onFakeSelectKeypress2.bindAsEventListener(obj));
    Event.observe(document, 'keydown', onFakeSelectKeypress2.bindAsEventListener(obj));
  } else {
    Event.observe(document, 'keydown', onFakeSelectKeypress2.bindAsEventListener(obj));
  }

  //do it only if all IDs are valid
  if(mySelect != null && myReplace != null && myOptions != null && myCurrent != null){
    myCurrent.innerHTML = shortenFakeSelectText(myCurrent.innerHTML, maxLength);
    myCurrent.style.width = selectWidth;
    myOptions.style.width = selectWidth;

    mySelect.style.display = 'none';
    myReplace.style.display = 'inline';

    var liArray = myOptions.getElementsByTagName('li');
    for (var i = 0; i < liArray.length; i++) {
      liArray[i].style.width = selectWidth;
      liArray[i].innerHTML = shortenFakeSelectText(liArray[i].innerHTML,maxLength);


      //update of hidden real select after page reload
      /*
      <?if(isset($_GET['sc'])){?>
      if(liArray[i].getAttribute(attr) == '<?echo $_GET['sc'];?>'){
        //give hidden select the value of the chosen fake select
        mySelect.value = liArray[i].getAttribute(attr);
        //update the current text with the text of the fake select
        myCurrent.innerHTML = shortenFakeSelectText(liArray[i].innerHTML,maxLength);
        myOptions.style.display = 'none';
      }
      <?}?>
      */

      //what happens if clicking on an option of the fake select
      liArray[i].onclick = function() {
        //do not do sth. when selecting "----------------"
        if(this.getAttribute(attr) != attrNoAction){
          //give hidden select the value of the chosen fake select
          mySelect.value = this.getAttribute(attr);
          setSearchArea2(this.getAttribute(attr), selectId);
          //update the current text with the text of the chosen fake select
          myCurrent.innerHTML = shortenFakeSelectText(this.innerHTML,maxLength);
          //do something after update the fake select => like "onchange"
          afterUpdateFakeSelect(functionCall, functionParams);
        }
      }

      //what happens if moving mouse on an option of the fake select
      liArray[i].onmouseover = function() {
        clearAllSelectedFakeOptions(myOptions, bconover, bconout);
        this.style.backgroundColor = bconover;
      }

      //what happens if moving mouse away from an option of the fake select
      liArray[i].onmouseout = function() {
        this.style.backgroundColor = bconout;
      }
    }
    //open fake select by clicking on it
    myReplace.onclick = function() {
      if(myOptions.style.display == 'block'){
        //hide fake if it is displayed
        myOptions.style.display = 'none';
      } else {
        //show fake
        myOptions.style.display = 'block';
      }
    }
  }
}
//function for shortening of text
function shortenFakeSelectText(string, maxLength){
  if(string.indexOf('-') != 0){
    if(substr_count(string, '&nbsp;') > 0){
      var split = string.split('&nbsp;');
      if(split.length == 2){
        if(split[1].length >= maxLength){
          var tmpString = split[0] + '&nbsp;' + split[1].substr(0, (maxLength - 3)) + '...';
          return tmpString;
        }
      }
    } else {
      if(string.length >= maxLength){
        var tmpString = string.substr(0, (maxLength - 3)) + '...';
        return tmpString;
      }
    }
  }
  return string;
}

function afterUpdateFakeSelect(functionCall, functionParams){
  if(function_exists(functionCall)){
    var thisParams = '';
    if(functionParams != '' && functionParams != null){
      thisParams = '\'' + str_replace(',', '\',\'', functionParams) + '\'';
    }
    eval(functionCall + '(' + thisParams + ');');
  }
}

//hide fake select if you click somewhere
function hideFakeSelect(e, replaceId, fakeOptionsId) {
  //area for the fake select
  var myReplace = replaceId;
  //fake selection options
  var myOptions = fakeOptionsId;
  var eve = e.target ? e.target : e.srcElement;
  if(eve.parentNode.id != myOptions && eve.parentNode.id != myReplace){
    var el = document.getElementById(myOptions);
    if(el != null) el.style.display = 'none';
  }
}

function getSearchArea(){
	var sc = '';
	var sel = document.getElementById('sc');
	if(sel != null){
		for(var i = 0; i < sel.options.length; i++){
      if(sel.options[i].selected == true){
        sc = sel.options[i].value;
        break;
      }
	  }
	}
	return sc;
}

function setSearchArea(val){
	var sel = document.getElementById('sc');
	if(sel != null){
		for(var i = 0; i < sel.options.length; i++){
      if(sel.options[i].value == val){
        sel.options[i].selected = true;
        break;
      }
    }
	}
}

function setSearchArea2(val, element){
	var sel = document.getElementById(element);
	if(sel != null){
		for(var i = 0; i < sel.options.length; i++){
      if(sel.options[i].value == val){
        sel.options[i].selected = true;
        break;
      }
    }
	}
}

function setFakeAndSearchArea(value, optionsId, currentId, selectId, attr, maxLength){
	var myOptions = document.getElementById(optionsId);
	var mySelect = document.getElementById(selectId);
	var myCurrent = document.getElementById(currentId);
	if(myOptions != null && mySelect != null && myCurrent != null){
		//see config vars in function prepareSearchSelect
		if(maxLength == '') maxLength = 33;
		if(attr == '') attr = 'rel';
		var liArray = myOptions.getElementsByTagName('li');
		for (var i = 0; i < liArray.length; i++) {
			if(liArray[i].getAttribute(attr) == value){
				//give hidden select the value of the chosen fake select
				mySelect.value = value;
				setSearchArea2(value, selectId);
				//update the current text with the text of the fake select
				myCurrent.innerHTML = shortenFakeSelectText(liArray[i].innerHTML,maxLength);
				myOptions.style.display = 'none';
				break;
			}
		}
	}
}

function submitForm(elementId){
	var el = document.getElementById(elementId);
	if(el != null){
		el.submit();
	}
}

function switchLanguages(elementId){
	var el = document.getElementById(elementId);
	if(el != null){
		var ellang = el.elements['scLang'];
		if(ellang != null){
			if (langUrls){
				window.location.href = langUrls[ellang.value];
			}
		}
	}
	return false;
}
