function openWin(url,name,width,height) {
  if(name==null)
    name = "_blank";
  var win = window.open(url,name,'width='+width+',height='+height+',resizable=yes,scrollbars=yes,status=yes,toolbar=no,menubar=no,location=no');
  if (win) {
    if(win.opener == null){
      win.opener = self;
    }
    if (win.focus) win.focus();
  }
  else {
    ajaxCall (createURL ('administration/resource', 'alertResource', 0, 'resourcekey=popup_blocked'));
  }
}

function submitForm(obj) {
  if(obj==null)
    return;

  var form = null;
  var p = obj;
  while(p!=null){
    if(p.nodeName.toLowerCase()=='form'){
      form = p;
      break; 
    }
    p = p.parentNode;
  }
  
  if(form!=null){
    form.submit(); 
  }
}

function toggleTree (obj) {
	if (obj != null) {
		// the surrouding div class="treecomponent"
    var tree = obj;
    while(tree != null){
      if(tree.className=='treecomponent'){
        break; 
      }
      tree = tree.parentNode;
    }
    
		if (tree != null) {
			try {
				// the children
				var ul = tree.lastChild;
				// the bullet
				var img = tree.firstChild.firstChild;
				if (ul != null && img != null) {
					if (ul.style.display == null || ul.style.display.toLowerCase () == 'none') {
						// show the children
						ul.style.display = 'block';
						img.src = img.src.replace ('_off', '_on');
						// set url hash to remember the position
						if (tree.id && (location.hash + ':').indexOf (':' + tree.id + ':') == -1) {
							location.hash += ':' + tree.id;
						}
					}
					else {
						ul.style.display = 'none';
						img.src = img.src.replace ('_on', '_off');
						// set url hash to remember the position
						if (tree.id) {
							location.hash = location.hash.replace (':' + tree.id, '');
						}
					}
				}
			} catch (ex) {}
		}
	}
}

function initTreeComponent (id) {
	if ((location.hash + ':').indexOf (':tc_' + id + ':') >= 0) {
		// find the node and open it
		try {
			toggleTree (AJS.getElement ('tc_' + id).firstChild.firstChild);
		} catch (ex) {}
	}
}

function updateBVEventSelection (id, reload, disableToggle) {
	disableToggle = disableToggle || false;
	ajaxCall (createURL ('internet/bvevent', 'updateselection', null, 'id=' + id + '&reload=' + (reload ? 'true' : 'false') + '&disabletoggle=' + disableToggle));
}

function wabToggleAdditionalRestrictions (show) {
	if (show) {
		AJS.getElement ('wabClosedAdditionalRestrictions').style.display = 'none';
		AJS.getElement ('wabOpenAdditionalRestrictions').style.display = 'block';
		AJS.getElement ('addrestrictions').value = 1;
	}
	else {
		AJS.getElement ('wabClosedAdditionalRestrictions').style.display = 'block';
		AJS.getElement ('wabOpenAdditionalRestrictions').style.display = 'none';
		AJS.getElement ('addrestrictions').value = 0;
	}
}

// is used from AJS.getElement for ff and safari
function findObject (theObj, theDoc) {
	var p, i, foundObj;
	if (!theDoc) {
		theDoc = document;
	}
	if ((p = theObj.indexOf ("?")) > 0 && parent.frames.length) {
		theDoc = parent.frames[theObj.substring (p + 1)].document;
		theObj = theObj.substring (0, p);
	}
	if (!(foundObj = theDoc[theObj]) && theDoc.all) {
		foundObj = theDoc.all[theObj];
	}
	for (i = 0; !foundObj && i < theDoc.forms.length; i++) {
		foundObj = theDoc.forms[i][theObj];
	}
	for (i = 0; !foundObj && theDoc.layers && i < theDoc.layers.length; i++) {
		foundObj = findObj (theObj, theDoc.layers[i].document);
	}
	if (!foundObj && document.getElementById) {
		foundObj = document.getElementById (theObj);
	}
	return foundObj;
}

function printWABSelection (url) {
	// find checkboxes on page
	var cbs = AJS.getElementsByTagAndClassName ('input', 'wabcb');
	var idList = '';
	for (var i = 0; i < cbs.length; i++) {
		idList += (cbs[i].checked ? cbs[i].id.substr ('offer_'.length) + ';' : '');
	}
	//alert (url + '&print=yes&selectedids=' + idList);
	openWin (url + '&print=yes&selectedids=' + idList, 'printwindow', 650, 500);
}

function resetWABSelection () {
	// find checkboxes on page
	var cbs = AJS.getElementsByTagAndClassName ('input', 'wabcb');
	for (var i = 0; i < cbs.length; i++) {
		cbs[i].checked = false;
	}
}

function printLinkSelection (url) {
	// find checkboxes on page
	var cbs = AJS.getElementsByTagAndClassName ('input', 'linkcb');
	var idList = '';
	for (var i = 0; i < cbs.length; i++) {
		idList += (cbs[i].checked ? cbs[i].id.substr ('link_'.length) + ';' : '');
	}
	// alert (url + '&print=yes&selectedids=' + idList);
	openWin (url + '&print=yes&selectedids=' + idList, 'printwindow', 650, 500);
}

function resetLinkSelection () {
	// find checkboxes on page
	var cbs = AJS.getElementsByTagAndClassName ('input', 'linkcb');
	for (var i = 0; i < cbs.length; i++) {
		cbs[i].checked = false;
	}
}

function toggleCH (selectAll,init) {
	// if the function toggleCounty exists we are in a chmap context
	try {
		if (window.toggleCounty) {
			for (var i = 0; i < 30; i++) {
				var cb = AJS.getElement ('cb_countycode' + i);
				toggleCounty (cb.value, selectAll, init);
			}
		}
		else {
			for (var i = 0; i < 30; i++) {
				var cb = AJS.getElement ('cb_countycode' + i);
				if (cb) {
					cb.checked = selectAll;
				}
			}
		}
	} catch (ex) {
		for (var i = 0; i < 30; i++) {
			var cb = AJS.getElement ('cb_countycode' + i);
			if (cb) {
				cb.checked = selectAll;
			}
		}
	}
}

function schooltypeToggle(nbSchooltype, selectAll){
    for(var i=0;i<nbSchooltype;i++){
        var schooltype = AJS.getElement('cb_schooltype' + i);
        if(schooltype)
            schooltype.checked = selectAll;
    }
}

function countySchoolToggle(nbSchooltype, selectAll){
    for(var i=0;i<nbSchooltype;i++){
        var county = AJS.getElement('cb_county' + i);
        if(county)
            county.checked = selectAll;
    }
}

function test(msg){
    alert(msg);
    return false;
}

function checkSelection(msg){
    for(var i=0;i<document.getElementsByName('schooltype').length;i++){
        if(document.getElementsByName('schooltype')[i].checked){
            for(var j=0;j<document.getElementsByName('county').length;j++){
                if(document.getElementsByName('county')[j].checked)
                    return true;
            }
        }
    }
    alert(msg);
    return false;
}

// jf 26.11.2008
// check if at least one checkbox is checked
function checkSchoolType(msg){
    for(var i=0;i<document.getElementsByName('schoolnodetype').length;i++){
        if (document.getElementsByName('schoolnodetype')[i].checked)
            return true
    }
    alert(msg);
    return false;
}

function apprenticeshipSetFieldAndSubmit(fieldName, value){
  var bbnet = document.getElementById('bbnet');
  if(bbnet==null)
    return;
  var forms = bbnet.getElementsByTagName ('form');
  if(forms==null)
    return;
  var form = forms[0];
  if(form==null)
    return;
  var h = findObject(fieldName,form);
  if(h==null)
    return;
  h.value = value;
  apprenticeshipReset(fieldName);
  form.submit();
}
function apprenticeshipReset(fieldName){
  var bbnet = document.getElementById('bbnet');
  if(bbnet==null)
    return;
  var forms = bbnet.getElementsByTagName ('form');
  if(forms==null)
    return;
  var form = forms[0];
  if(form==null)
    return;
  if(fieldName==null || fieldName!='searchabc'){
    var s = findObject('searchabc',form);
    if(s!=null){
      s.value = '';
    }
  }
  if(fieldName==null || fieldName!='search'){
    var s = findObject('search',form);
    if(s!=null){
      s.value = '';
    }
  }
  if(fieldName==null || fieldName!='id_section'){
    var s = findObject('id_section',form);
    if(s!=null){
      s.value = '';
    }
  }
  if(fieldName==null || fieldName!='swissdoc'){
    var fields = AJS.getElementsByTagAndClassName ('input', null, form);
		for (i = 0; i < fields.length; i++) {
			if(fields[i].id!=null && fields[i].id.indexOf('swissdoc_')==0){
        fields[i].checked = false; 
      }
    }
  }
}

window.selectedApprenticeshipSearchOption = 1;
function apprenticeshipOnClickSearchOption(which){
  if(apprenticeshipHasSelectedCounties()){
     apprenticeshipToggleSearchOption(which);
  }
}

function apprenticeshipToggleSearchOption(which,open){
  var i=1;
  var obj=document.getElementById('searchoption_'+i);
  while(obj!=null){
    if(i==which){
      obj.style.display = (obj.style.display!='block'||open)?'block':'none';
    }
    else {
      obj.style.display = 'none';
    }
    i++;
    obj = document.getElementById('searchoption_'+i);
  }
  
  if(which!=null){
    window.selectedApprenticeshipSearchOption = which;
  }
}
function apprenticeshipMapListener(code,checked,init){
  if(!checked && !init && window.emptyLectureGroups !=null && emptyLectureGroups[code.toLowerCase()]!=null){
    alert(emptyLectureGroups[code.toLowerCase()]);
  }
  if(apprenticeshipHasSelectedCounties()){
     apprenticeshipToggleSearchOption(window.selectedApprenticeshipSearchOption,true);
     window.clearTimeout(window.aiid);
     window.aiid = window.setTimeout('apprenticeshipUpdateStat()',500);
  }
  else {
    apprenticeshipToggleSearchOption(null);
  }
}
function apprenticeshipHasSelectedCounties(){
  var arr = apprenticeshipGetSelectedCounties();
  return arr!=null && arr.length>0;
}

function apprenticeshipGetSelectedCounties(){
  var i=0;
  var obj=document.getElementById('cb_countycode'+i);
  var arr = new Array();
  while(obj!=null){
    if(obj.checked){
      arr.push(obj.value);
    }
    i++;
    obj=document.getElementById('cb_countycode'+i);
  }
  return arr;
}

function apprenticeshipUpdateStat(){
  var arr = apprenticeshipGetSelectedCounties();
  if(arr==null || arr.length==0)
    return;
  
  var url = createURL('internet/apprenticeships', 'updatestat', null, 'countycode='+arr.toString());
  var req = AJS.getRequest (url, null, 'GET');
  req.addCallback (apprenticeshipUpdateStatCallback);
	req.addErrback (function (data, req) { });
	req.sendReq ();
}

function apprenticeshipUpdateStatCallback(data, req){
  if (data != null && data.length > 0) {
    eval (data);
    var list = AJS.getElementsByTagAndClassName ('span', '_stat_');
    if(list!=null){
      for(var i=0;i<list.length;i++){
        if(list[i].id==null)
          continue;
        
        var id = null;
        if(list[i].id.indexOf('_')!=-1){
          id = list[i].id.substring(list[i].id.lastIndexOf('_')+1);
        }
        if(id==null)
          continue;
        
        if(list[i].id.indexOf('swissdoc_nbr')!=-1){
          var disabled = false;
          if(swissdocStat!=null && swissdocStat[id]!=null){
            list[i].innerHTML = swissdocStat[id];
            disabled = false;
          }
          else {
            list[i].innerHTML = '0';
            disabled = true;
          }
          
          var cbs = list[i].parentNode.getElementsByTagName('input');
          if(cbs!=null){
            for(var j=0;j<cbs.length;j++){
              cbs[j].disabled = disabled;   
            }
          }
        }
        else if(list[i].id.indexOf('section_nbr')!=-1){
          var disabled = false;
          if(sectionStat!=null && sectionStat[id]!=null){
            list[i].innerHTML = sectionStat[id];
            disabled = false;
          }
          else {
            list[i].innerHTML = '0';
            disabled = true;
          }
          
          var anchors = list[i].parentNode.getElementsByTagName('a');
          if(anchors!=null){
            for(var j=0;j<anchors.length;j++){
              if(anchors[j].inithref==null){
                anchors[j].inithref = anchors[j].href; 
              }
              if(disabled){
                anchors[j].style.opacity=0.5; 
                anchors[j].style.filter='alpha(opacity = 50)';
                anchors[j].href = 'javascript:void(0)';  
              }
              else {
                anchors[j].style.opacity=1; 
                anchors[j].style.filter='alpha(opacity = 100)';
                anchors[j].href = anchors[j].inithref;  
              }
            }
          }
        }
      }
    }
	}
}


// LogBook
window.LogBook = new Object();
window.LogBook.getInputFields = function(elm){
  var types = new Array('input','textarea','select');
  var arr = new Array();
  if(elm==null)
    return arr;
  for(var i=0;i<types.length;i++){
    var elms = elm.getElementsByTagName(types[i]);
    if(elms!=null && elms.length>0){
      for(var j=0;j<elms.length;j++){
        arr.push(elms[j]);
      } 
    }
  }
  return arr;
}
window.LogBook.addRow = function(obj){
  if(obj==null)
    return;
  var table = AJS.getParentBytc(obj, 'table');
  if(table==null)
    return;
  var trs = AJS.getElementsByTagAndClassName('tr', 'cloneable', table);
  if(trs==null || trs.length==0)
    return;
  var tr = trs[0];
  var newTR = tr.cloneNode (true);
  newTR.className = tr.className;
  AJS.insertAfter(newTR,trs[trs.length-1]);
  
  var re = new RegExp('_[0-9]*$','gi');
  
  var elms = LogBook.getInputFields(newTR);
  if(elms!=null){
    for(var i=0;i<elms.length;i++){
      elms[i].value = ''; 
      if(elms[i].checked!=null){
        elms[i].checked = false;
      }
      if(elms[i].name!=null){
        elms[i].name = elms[i].name.replace(re,'_'+trs.length);
      }
      if(elms[i].id!=null){
        elms[i].id = elms[i].id.replace(re,'_'+trs.length);
      }
    } 
  }
  
  return newTR;
}
window.LogBook.deleteRow = function(obj){
  if(obj==null)
    return;
  var tr = AJS.getParentBytc(obj, 'tr');
  if(tr==null)
    return;
  var elms = LogBook.getInputFields(tr);
  if(elms!=null){
    for(var i=0;i<elms.length;i++){
      elms[i].value = ''; 
    } 
  }
  tr.style.display = 'none';
}
window.LogBook.addRowFromSelect = function(selectId, inputName, multipleAllowed){
  var select = document.getElementById(selectId);
  if(select==null || select.value=='')
    return;
  var table = AJS.getParentBytc(select, 'table');
  if(table==null)
    return;
  //Already added ?
  if(!multipleAllowed){
    var elms = table.getElementsByTagName('input');
    if(elms!=null && elms.length>0){
      for(var j=0;j<elms.length;j++){
        if(elms[j].name.indexOf(inputName+'_')==0){
          if(elms[j].value == select.value){
            return;
          }
        }
      }
    }
  }
  
  //Is 0 already used
  var tr = null;
  var zero = findObject (inputName+'_0');
  if(zero!=null && zero.value==''){
     tr = AJS.getParentBytc(zero, 'tr');
  }
  else {
    tr = LogBook.addRow(select);
  }
  
  tr.style.display = AJS.isIe()?'block':'table-row';
  
  var txt = AJS.getElementsByTagAndClassName('h3', 'text', tr, true);
  if(txt!=null){
    txt.innerHTML = select.options[select.selectedIndex].text; 
  }
  
  var elms = tr.getElementsByTagName('input');
  //Set value
  if(elms!=null && elms.length>0){
    for(var j=0;j<elms.length;j++){
      if(elms[j].name.indexOf(inputName+'_')==0){
         elms[j].value = select.value;
         break;
      }
    }
  }
  
  return tr;
}

window.LogBook.addZihlmann = function(){
  LogBook.addRowFromSelect('id_zihlmann','main_idzihlmann',false);
}
window.LogBook.addSourceType = function(selectId, inputName){
  var tr = LogBook.addRowFromSelect(selectId, inputName,true);
  /*
  if(tr!=null){
    var ta = AJS.getElementsByTagAndClassName('textarea', null, tr, true);
    if(ta!=null){
      ta.onfocus = function(){
        if(this.dateset){
          return;
        } 
        this.name = this.name.replace(/\* /,'');
        var now = new Date();
        this.value = now.getDate()+'.'+(now.getMonth()+1)+'.'+now.getFullYear()+"\n"; 
        if (this.createTextRange){
          var fr = this.createTextRange();
          fr.moveStart('character', this.value.length);
          fr.collapse();
          fr.select();
        }
        this.dateset=true;
      };
    }
  }
  */
}
window.LogBook.moveProfession = function(id,moveUp){
  var h = document.getElementById(id);
  if(h==null){
    return; 
  }
  var div = AJS.getParentBytc(h, 'div');
  if(div==null){
    return;
  }
  var divs = AJS.getElementsByTagAndClassName('div', 'profession', div.parentNode);
  if(divs==null){
    return; 
  }
  //Find current pos
  var pos = -1;
  for(var i=0;i<divs.length;i++){
    if(divs[i]==div){
      pos = i;
      break; 
    }
  }
  //Not found
  if(pos==-1){
    return; 
  }
  
  var newPos = pos + (moveUp?-1:1);
  if(newPos>=divs.length || newPos<0){
    return;    
  }

  if(newPos==0){
    AJS.insertBefore(div,divs[0]);
  }
  else {
    AJS.insertAfter(div,divs[newPos+(moveUp?-1:0)]);
  }
}
window.LogBook.deleteItem = function(id){
  var h = document.getElementById(id);
  if(h==null){
    return; 
  }
  h.value = '';
  var div = AJS.getParentBytc(h, 'div');
  if(div!=null){
    div.style.display = 'none'; 
  }
  var form = AJS.getParentBytc(h, 'form');
  if(form!=null){
    form.submit(); 
  }
}


/*  
    JF 05.08.2005 
    for careers on internet
*/
function careerGetSelectedInterest(){
  var i=0;
  var obj=document.getElementById('interest_'+i);
  var arr = new Array();
  while(obj!=null){
    if(obj.checked){
      arr.push(obj.value);
    }
    i++;
    obj=document.getElementById('interest_'+i);
  }
  return arr;
}

function careerUpdateStat(){
  var arr = careerGetSelectedInterest();
  if(arr==null || arr.length==0){
    var url = createURL('internet/career', 'updatestat', null, '');
    }
  else{
    var url = createURL('internet/career', 'updatestat', null, 'interestcode='+arr.toString());
    
    }
	
  var req = AJS.getRequest (url, null, 'GET');
  req.addCallback (careerUpdateStatCallback);
  req.addErrback (function (data, req) { });
  req.sendReq ();
}

function careerUpdateStatCallback(data, req){
  if (data != null && data.length > 0) {
    eval (data);
    var elem = document.getElementById('text_career');
    if(elem != null){
        elem.innerHTML = text_career;
    }
  }
}

function unscrambleVerification(domId, input) {
    var str = "";
    input = input.split(',');
    for (var i in input) {
        str += String.fromCharCode(input[i]);
    }
    var elm = document.getElementById(domId);
    if (elm) {
        if (elm.parentNode) {
            elm.parentNode.innerHTML = str;
        }
        else {
            elm.innerHTML = str;
        }
    }
}