// common JS functions for MARBEF Integrated Data System (MarIDaS)

var maxRoleID=0;
var eurobisprefix="eurobis";

// check if we have SVG support. Currently only IE5+ supports SVG well
//
function checkBrowser(no_output){
 var version=0;
 if (navigator.appVersion.indexOf("MSIE")!=-1){
  var temp=navigator.appVersion.split("MSIE");
  version=parseFloat(temp[1]);
 }
 if ((navigator.appName != 'Microsoft Internet Explorer') || (version < 5) ){
  if(!no_output) document.write('<font size=2 color="red">This page will only work 100% on <b>Internet Explorer 5+</b>. Other browsers have no or poor SVG support. Your browser is ' + navigator.appName + ' ' +  navigator.appVersion + ' (' + navigator.userAgent +')</font><br><br>');
  return false;
 }
 return true;
}

// get *any* object in the child or grand-child window 
// gets first the object by id, if its not found, it returns the first object with the name
//
function getObj(name){
 var obj;
 var objs;
 if (window.opener && !window.opener.closed){
  if (document.getElementById){ obj = opener.document.getElementById(name);}
  else if (document.all) { obj = opener.document.all[name]; }
  else if (document.layers) { obj = opener.document.layers[name]; }
  if(!obj && document.getElementsByName) { objs = opener.document.getElementsByName(name); obj=objs[0]; }
 }else{
  if (document.getElementById){ obj = document.getElementById(name);}
  else if (document.all) { obj = document.all[name]; }
  else if (document.layers) { obj = document.layers[name]; }
  if(!obj && document.getElementsByName) { objs = document.getElementsByName(name); obj=objs[0]; }
 }
 return obj;
}


// Popup Window
//
function OpenLink(URL,wd,hg,l,t,scroll){
 if (!hg) hg=555;	
 if (!wd) wd=640;
 if (!l) l=250;
 if (!t) t=100;
 var sb="yes";
 if (scroll==0 || scroll==false || scroll=="no") sb="no";   
 //if (winDetail) winDetail.close();
 var winname="win"+Math.round(Math.random()*100);
 var winDetail = window.open(URL,winname,"width="+wd+",height="+hg+",left="+l+",top="+t+",resizable=yes,scrollbars="+sb); 
 winDetail.focus();
}


// similar to the PHP urldecode
//
function urldecode(ch) {
  if (ch) ch = ch.replace(/[+]/g," ")
  return unescape(ch)
}

// Close the current popup for adding the layer if it's possible
//
function closeLayerPopup(){
 if (!(!window.opener || window.opener.closed)){
  window.opener.location.href = eurobisprefix + "search.php";   
 }else{
  alert("The original window is closed, the layer is not added.")
 }
 window.close(); 
}


// Fill in ERMS taxon into EurOBIS search field
//
function fillinTaxon(id,taxon){
 if (!(!window.opener || !window.opener.location)){
  if (window.opener.document.layerinfo){
   window.opener.layerinfo.tName.value= urldecode(taxon);
   window.opener.layerinfo.layername.value= urldecode(taxon);
   window.opener.layerinfo.id.value= id;  
  }
  if (opener.document.datainventory){
   opener.document.datainventory.TaxTerm.value= ((window.opener.datainventory.TaxTerm.value)?window.opener.datainventory.TaxTerm.value+" | ":"") +urldecode(taxon);
  }
 }else{
  alert("The original window is closed, the taxon is not selected.");
 }
 window.close(); 
}


// fill in LatLon into eurobisaddlayer.php
//
function fillinLL(){
 if (window.opener && !window.opener.closed){
  if (window.opener.search.MinLatD.value && window.opener.search.MinLatD.value!=window.opener.search.MaxLatD.value){
   document.layerinfo.MinLatD.value=window.opener.search.MinLatD.value;
   document.layerinfo.MinLatM.value=window.opener.search.MinLatM.value;
   document.layerinfo.MinLatS.value=window.opener.search.MinLatS.value;
   document.layerinfo.MaxLatD.value=window.opener.search.MaxLatD.value;
   document.layerinfo.MaxLatM.value=window.opener.search.MaxLatM.value;
   document.layerinfo.MaxLatS.value=window.opener.search.MaxLatS.value;
   document.layerinfo.MinLongD.value=window.opener.search.MinLongD.value;
   document.layerinfo.MinLongM.value=window.opener.search.MinLongM.value;
   document.layerinfo.MinLongS.value=window.opener.search.MinLongS.value;
   document.layerinfo.MaxLongD.value=window.opener.search.MaxLongD.value;
   document.layerinfo.MaxLongM.value=window.opener.search.MaxLongM.value;
   document.layerinfo.MaxLongS.value=window.opener.search.MaxLongS.value;
  }
 }
 return false;

}

// Deletes a EurOBIS layer from cache
//
function delLayer(layerid){
 window.location.href=eurobisprefix + "layerinfo.php?action=dellayer&layerid="+layerid;
 if (window.opener && !window.opener.closed){ 
  window.opener.location.href= eurobisprefix + "search.php";
 }
}

// Moves a EurOBIS layer up/down
//
function moveLayer(direction,layerid){
 window.location.href= eurobisprefix + "layerinfo.php?action=movelayer&layerid="+layerid +"&direction="+direction;
 if (window.opener && !window.opener.closed){
  window.opener.location.href= eurobisprefix + "search.php";
 }
}


// for the DAS-input-form
//
function last_choice(selection) {
 return selection.selectedIndex==selection.length - 1; 
}

// for the DAS-input-form
//
function activate(field) {
 field.disabled=false;
 if(document.styleSheets)field.style.visibility  = 'visible';
 field.focus(); 
}

// for the DAS-input-form
//
function process_choice(selection,textfield) {
  if(last_choice(selection)) {
    activate(textfield); }
  else {
    textfield.disabled = true;    
    if(document.styleSheets)textfield.style.visibility  = 'hidden';
    textfield.value = ''; }
}

// for the DAS-input-form
//
function addField(obj) { 
  var field=getObj(obj);
  var newfield = field.cloneNode(true); 
  newfield.style.display = 'block';
  var insertHere=getObj(obj+'_more');
  //for RoleID[][] we need to edit the name, so we have a straightforward Array
  insertHere.parentNode.insertBefore(newfield,insertHere);  
  if(obj=="Ownership"){
   maxRoleID++;
   newfield.childNodes[0].childNodes[0].childNodes[0].childNodes[1].childNodes[1].value='';
   newfield.childNodes[0].childNodes[0].childNodes[0].childNodes[0].childNodes[1].value='';
   newfield.childNodes[0].childNodes[0].childNodes[0].childNodes[2].childNodes[1].name='RoleID['+maxRoleID+'][]';
   newfield.childNodes[0].childNodes[0].childNodes[0].childNodes[3].childNodes[1].style.visibility='';
  }
  if ((obj=="ref_usedin" || obj=="ref_basedon")){
   newfield.childNodes[2].style.visibility='';
   newfield.childNodes[0].value='';
  }  
}

// remove an item from the DAS-input-form
//
function delField(instance) { 
 instance.parentNode.parentNode.removeChild(instance.parentNode); 
} 


// Check if form is filled in correctly
//
function checkForm(){
 if (document.datainventory.StandardTitle.value && document.datainventory.ContactEmail.value && document.datainventory.Pers_Ownership_Fillin.value &&  document.datainventory.EngAbstract.value && document.datainventory.searchGeotdas.value && document.datainventory.Citation.value){
   document.datainventory.submit();
 }else{
  alert("Please fill in all necessary fields (marked with *) !");
 }
 return;
}


// Function to change any property of the MM-menu on the fly
//
function mm_changeItemProperty(menuName, itemName, codeRef, newValue, updateDisplay) { 
  menuName = menuName.toLowerCase(); 
  for (i=0; i<_mi.length; i++) 
    if (_mi[i][1].replace(/\&nbsp\;/ig,' ') == itemName && _m[_mi[i][0]][1] == menuName) break; 
  if (i == _mi.length) return; 
  _mi[i][codeRef] = newValue; 
  if (updateDisplay) BDMenu(_mi[i][0]); 
}


// Function to delete a MM-menu-item on the fly
//
/*
function mm_removeItem(menuName, itemName) 
{ 
  menuName = menuName.toLowerCase(); 
  for (var i=0; i<_mi.length; i++) 
    if (_mi[i][1].replace(/\&nbsp\;/ig,' ') == itemName && _m[_mi[i][0]][1] == menuName) break; 
  if (i == _mi.length) return; 

  var idx = 0; 
  newItemArr = new Array(); 
  for (var j=0; j<_m[_mi[i][0]][0].length; j++) 
    if (_m[_mi[i][0]][0][j] != i) 
      newItemArr[idx++] = _m[_mi[i][0]][0][j]; 
  _m[_mi[i][0]][0] = newItemArr; 

  BDMenu(_mi[i][0]); 
}
*/



//Fill in APHIA id + names in taxon update page
//
function fillinTaxUpdate(to){
 //var choice=getObj('choice');
 if (choiceform.choice.selectedIndex>=0) {
  var both=choiceform.choice.options[choiceform.choice.selectedIndex].value;
  both = both.split('|');
  var id= both[0];
  var dn= both[1];
  sendText(dn,to,0);
  sendText(id,to+'_id',0); 
 }else{ 
  alert('Please select a taxon'); 
 }
}


// close popup+reload window.opener
//
function closeRefresh(){
 if (window.opener && !window.opener.closed){
  window.opener.location.href = window.opener.location.href;   
 }
 window.close(); 
}

// set cookie to accept Data Policy
//

function acceptDataPolicy(val){
 if(val==1){
  var date = new Date();
  date.setTime(date.getTime()+(30*24*60*60*1000)); //expires in 1 month
  setCookie('dp_accept',val,date);
  if (getCookie('dp_accept')==null) { 
    //try to store session cookie
    setCookie('dp_accept',val,null);
    if (getCookie('dp_accept')==null) {
     alert('You need to have cookies enabled to visit this website');
    }
   }
  document.location.href=document.location.href; //refresh
 }else{
  document.location.href="http://www.marbef.org"
 }
}

/**
 * Sets a Cookie with the given name and value.
 *
 * name       Name of the cookie
 * value      Value of the cookie
 * [expires]  Expiration date of the cookie (default: end of current session)
 * [path]     Path where the cookie is valid (default: path of calling document)
 * [domain]   Domain where the cookie is valid
 *              (default: domain of calling document)
 * [secure]   Boolean value indicating if the cookie transmission requires a
 *              secure transmission
 */
function setCookie(name, value, expires, path, domain, secure)
{
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}



// this function gets the cookie, if it exists
//
function getCookie(name) {
	
 var start = document.cookie.indexOf( name + "=" );
 var len = start + name.length + 1;
 if ( ( !start ) &&
 ( name != document.cookie.substring( 0, name.length ) ) )
 {
 return null;
 }
 if ( start == -1 ) return null;
 var end = document.cookie.indexOf(";",len);
 if ( end == -1 ) end = document.cookie.length;
 return unescape( document.cookie.substring(len,end));
}


// select or unselect all datasets in addlayer.php (EurOBIS)
//
function selectAllDS(val){
 els = document.getElementsByTagName('input');
 for (var i = 0; i < els.length; i++){
  if (els.item(i).name =='dataprovider[]') els.item(i).checked = val;
 }
}
