var lang = "";
if (document.URL.match(/\.(\w+)\.html/)) {
  lang = RegExp.$1;
};

// make jQuery compatible to scriptaculous
var $j = jQuery.noConflict();
// 

// extend prototype.js Element
Element.addMethods({
  center: function(element, x, y)
  {
    // center element on cooridantes
    element = $(element);
    w = element.getWidth();
    h = element.getHeight();
    
    element.absolutize();
    element.setStyle("top: "+(y-(h/2))+"px; left: "+(x-(w/2))+"px");
    return element;
  }
});


// Browser detection code from http://www.quirksmode.org/js/detect.html
var BrowserDetect = {
  init: function () {
    this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
    this.version = this.searchVersion(navigator.userAgent)
      || this.searchVersion(navigator.appVersion)
      || "an unknown version";
    this.OS = this.searchString(this.dataOS) || "an unknown OS";
  },
  searchString: function (data) {
    for (var i=0;i<data.length;i++) {
      var dataString = data[i].string;
      var dataProp = data[i].prop;
      this.versionSearchString = data[i].versionSearch || data[i].identity;
      if (dataString) {
        if (dataString.indexOf(data[i].subString) != -1)
          return data[i].identity;
      }
      else if (dataProp)
        return data[i].identity;
    }
  },
  searchVersion: function (dataString) {
    var index = dataString.indexOf(this.versionSearchString);
    if (index == -1) return;
    return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
  },
  dataBrowser: [
    {
      string: navigator.userAgent,
      subString: "Chrome",
      identity: "Chrome"
    },
    {   string: navigator.userAgent,
      subString: "OmniWeb",
      versionSearch: "OmniWeb/",
      identity: "OmniWeb"
    },
    {
      string: navigator.vendor,
      subString: "Apple",
      identity: "Safari",
      versionSearch: "Version"
    },
    {
      prop: window.opera,
      identity: "Opera"
    },
    {
      string: navigator.vendor,
      subString: "iCab",
      identity: "iCab"
    },
    {
      string: navigator.vendor,
      subString: "KDE",
      identity: "Konqueror"
    },
    {
      string: navigator.userAgent,
      subString: "Firefox",
      identity: "Firefox"
    },
    {
      string: navigator.vendor,
      subString: "Camino",
      identity: "Camino"
    },
    {   // for newer Netscapes (6+)
      string: navigator.userAgent,
      subString: "Netscape",
      identity: "Netscape"
    },
    {
      string: navigator.userAgent,
      subString: "MSIE",
      identity: "Explorer",
      versionSearch: "MSIE"
    },
    {
      string: navigator.userAgent,
      subString: "Gecko",
      identity: "Mozilla",
      versionSearch: "rv"
    },
    {     // for older Netscapes (4-)
      string: navigator.userAgent,
      subString: "Mozilla",
      identity: "Netscape",
      versionSearch: "Mozilla"
    }
  ],
  dataOS : [
    {
      string: navigator.platform,
      subString: "Win",
      identity: "Windows"
    },
    {
      string: navigator.platform,
      subString: "Mac",
      identity: "Mac"
    },
    {
      string: navigator.platform,
      subString: "Linux",
      identity: "Linux"
    }
  ]

};
BrowserDetect.init();
// EO browser detection code

var linkRelation = new Array('prev', 'next', 'up', 'home', 'index');

function getLink (relation) {
  // FIXME: this should switch out prev/next for arabic language!
  // relation should be prev/next/up/home
  if (linkRelation.indexOf(relation) == -1) {
    return false;
  }
  // it's a valid relation, search for the rel link
  if (lang=="ar") {
    // swap prev/next
    if (relation == "prev") {
      relation = "next";
    } else if (relation == "next") {
      relation = "prev";
    }
  };
  links = $$('link[rel="'+relation+'"]');
  if (links.length > 0) {
    // use first link
    l = links[0];
    return l.getAttribute('href');
  } else {
    return false;
  };
};

function replaceRelLinks() {
  // check all links, if they have a 'rel' attribute, fetch right url
  var links = $$('a[rel]');
  // alert("links found: "+links.length);
  while (e = links.shift()) {
    var relatt = e.getAttribute('rel');
    if (linkRelation.indexOf(relatt) != -1) {
      // it's a supported link attribute
      var url = getLink(relatt);
      // alert("rellink found: "+url);
      if (url != false) {
        e.href = url;  
      } else {
        // no link found, disable element
        if (e.firstChild.tagName.toUpperCase() == 'IMG') {
          // replace link with image
          e.firstChild.className = "opacity25";
          // e.replace(e.innerHTML);
          e.className = 'inactive';
          e.onclick = function () {return false;};
        }
        //  else {
        //   // replace link with text
        //   e.parentNode.className = "opacity25";
        //   // e.replace(e.innerHTML);
        //   e.className = 'inactive';
        // };
      };
    };
  };
};

function toggleStylesheet(title) {
  var i, a, main;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("href") == "css/"+title+".css") {
      a.disabled = !a.disabled;
    }
  }
  return false;
}

function showRight (id) {
  var p = $(id).parentNode;
  var c = p.getElementsBySelector("div");
  // move contentleft to the left
  $('contentleft').setStyle({"width": "49%"});
  // hide all direct children of parent
  c.each(function(v,i) {
    v.setStyle({"display": "none"});
  })
  // show div#id
  $(id).setStyle({"display": "block"});
  // make parent visible
  p.setStyle({ "display": "block", "width": "49%" });
  $('navigation_bottom').setStyle({"width": "100%"});
  return false;
}

function hideRight () {
  $('contentright').setStyle({"display": "none"});
  $('contentleft').setStyle({"width": "100%"});
  return false;
}

function displayImageSwitchers () {
  // find all divs with imageswitch as class
  var is = $$("div.imageswitch");
  for (var i=0; i < is.length; i++) {
    var parent = is[i];
    var count = parent.getAttribute('rel');
    var switcher = parent.getElementsBySelector("div.switcher")[0];
    var firstImage = parent.getElementsBySelector("img")[0].getAttribute('src');
    var match = firstImage.match(/^(.*_)(\d+)(\.\w{3})$/);
    var image_prefix=match[1];
    var c_len = match[2].length;
    var image_suffix=match[3];
    var links = '';
    for (var i=1; i <= count; i++) {
      links += "<a href='#' ";
      if (i == 1) { links += "class='active' "};
      links += "onclick='showImage(\""+parent.id+"\", \""+image_prefix+i.toPaddedString(c_len)+image_suffix+"\", "+i+"); return false;'>"+i+"<\/a>\n";
    };
    switcher.innerHTML=links;
  };
}

function showImage (parent, path, index) {
  var p = $(parent);
  var image = p.getElementsBySelector("img")[0];
  image.src=path;
  // highlight active element
  var s = $(parent).getElementsBySelector("div.switcher")[0];
  var sl = s.getElementsBySelector("a");
  for (var i=0; i < sl.length; i++) {
    sl[i].className='';
  };
  sl[index-1].className='active';
}

function copyCaptions () {
  // loop over all div class=picture, copy caption if there is one, add to thickbox link as title attribute
  pics = $$("div.picture");
  for (var i=0; i < pics.length; i++) {
    p = pics[i];
    cd = p.getElementsBySelector("div.caption");
    a = p.getElementsBySelector("a.thickbox");
    if (cd.length == 1 && a.length == 1) {
      a[0].name = "<small>"+cd[0].innerHTML+"</small>";
    };
  };

  // same thing for imageswitcher images
  pics = $$("div.imageswitch div.image");
  for (var i=0; i < pics.length; i++) {
    p = pics[i];
    cd = p.getElementsBySelector("div.caption");
    a = p.getElementsBySelector("a.thickbox");
    if (cd.length == 1 && a.length == 1) {
      a[0].name = "<small>"+cd[0].innerHTML+"</small>";
    };
  };

}

function showIndepth (obj) {
  var p = $(obj.parentNode);
  var c = p.select("div.content")[0];
  Element.toggleClassName(p, 'border');
  Element.toggle(p.select("span.expandme")[0]);
  Element.toggle(p.select("span.hideme")[0]);
  // Effect.toggle(c, 'slide');
  Element.toggle(c);
  Element.toggleClassName(obj, 'closed');
  return false;
}

function showQuelle (argument) {
  // body...
}

function switchImage (link, newimg, caption, thumbnail) {
  // switch to a different image
  var l = $(link);
  var switcher = $(l.parentNode);
  var sl = switcher.getElementsBySelector("a");
  var outerdiv = $(switcher.parentNode);
  for (var i=0; i < sl.length; i++) {
    sl[i].className='';
  };
  l.className='active';
  var image = outerdiv.getElementsBySelector("img")[0];
  // if a thumbnail link is provided, change to that image
  if (thumbnail) {
    // alert("Using thumbnail image: "+thumbnail);
    image.src = thumbnail;
  } else {
    image.src = newimg;
  }
  // if this uses a link to the image, update that href, too
  var imglink = outerdiv.getElementsBySelector("div.image a")[0];
  if (imglink) { imglink.href = newimg };
  // update caption, if given
  if (caption) {
    var capdiv = outerdiv.getElementsBySelector("div.caption")[0];
    if (capdiv) {
      capdiv.innerHTML = caption;
      if (imglink) {
        imglink.title = caption;
      };
    };
  };
}

var image_play_target;
var image_play_images;
var image_play_duration;
var image_play_nextImage;
var image_play_timer;
var image_play_cnt = 0;
function playImages (l, duration, images) {
  // switch images after click and duration
  l = $(l);
  l.onclick = stopPlayImages;
  l.innerHTML = "Stop";
  switcher = l.parentNode
  outerdiv = switcher.parentNode;
  image_play_target = outerdiv.getElementsBySelector("img")[0];
  image_play_images = images;
  image_play_duration = duration;
  // alert("target: "+image_play_target+ " images: "+image_play_images+" duration: "+image_play_duration)
  image_play_nextImage = new Image();
  image_play_nextImage.src = image_play_images[image_play_cnt];
  // alert(image_play_images);
  playSwitchImage();
}

function playSwitchImage () {
  if (this != window) {
    this.onclick = stopPlayImages;
    this.innerHTML = "Stop";
  }
  image_play_cnt = (image_play_cnt+1) % image_play_images.length;
  // alert("counter:"+image_play_cnt);
  // alert(image_play_nextImage.src);
  image_play_target.src = image_play_nextImage.src;
  image_play_target.title = image_play_nextImage.src;
  image_play_nextImage = new Image();
  image_play_nextImage.src = image_play_images[image_play_cnt];
  // alert(image_play_nextImage.src);
  image_play_timer = setTimeout("playSwitchImage()", image_play_duration*1000);
}

function stopPlayImages () {
  this.innerHTML="Play"
  // this.onclick="playImages("+this+", "+image_play_duration+", "+image_play_images+")";
  this.onclick=playSwitchImage;
  // alert(image_play_timer);
  clearTimeout(image_play_timer);
  return false;
}

function showAnswer (l) {
  l = $(l);
  scholar = l.parentNode.parentNode.getElementsBySelector("div.scholarinput")[0];
  solution = l.parentNode.parentNode.getElementsBySelector("div.solution")[0];
  // alert(solution.className);
  Element.toggle(scholar);
  Element.toggle(solution);
  if (l.innerHTML == "Show solution") {
    l.innerHTML = "Hide solution";
  } else {
    l.innerHTML = "Show solution";
  }
}

// FIXME: This might be easier with ysing the BrowserDetect thingie
function checkForMathPlayer() {
  // first test platform, as the MathPlayer-specific code only works in IE
  if( ($j("math").length > 0)) {
    // check browser version since MathPlayer 2 requires IE 6
    if (isIEWindows() && ieVersion() >= 6.0) {
      if (isMPInstalled()) {       
        var start = navigator.appVersion.indexOf("MathPlayer");
        if (start != -1) { 
          // notify reader their browser is properly set up
        }
        else {             
          // notify reader they need to upgrade to MathPlayer 2
        }
      } else {               
        // direct reader to MathPlayer installation page
        // alert("You need to install MathPlayer to see all formulas on these webpages!");
        var message = "<div class='mathplayermissing'>You don't have MathPlayer installed, so you won't be able to see the formula on these pages properly. Please download Mathplayer from <a href='http://www.dessci.com/en/products/mathplayer/download.htm' target='_blank'>http://www.dessci.com/en/products/mathplayer/download.htm</a> and activate it.</div>";
        if (lang == 'nl') {
          message = "<div class='mathplayermissing'>Je hebt MathPlayer niet geïnstalleerd. Dus je zult niet in staat zijn om de formules op deze pagina’s goed te zien. Gelieve Mathplayer te downloaden van <a href='http://www.dessci.com/en/products/mathplayer/download.htm' target='_blank'>http://www.dessci.com/en/products/mathplayer/download.htm</a> en dit te activeren.</div>";
        } else if (lang == 'fr') {
          message = "<div class='mathplayermissing'>Les formules de cette page ne s&#39;affichent pas bien car vous n&#39;avez pas encore install&eacute; MathPlayer. Merci de t&eacute;l&eacute;charger et d&#39;activer gratuitement MathPlayer depuis <a href='http://www.dessci.com/en/products/mathplayer/download.htm' target='_blank'>http://www.dessci.com/en/products/mathplayer/download.htm</a>.</div>";
        };
        $('headline').insert(message);
      }
    } else { 
      // other browsers
      if (BrowserDetect.browser == "Safari") {
        $('headline').insert("<div class='mathplayermissing'>This page uses MathML to display formula. Unfortunately, Safari does not support this technology. Please use <a href='http://www.getfirefox.com/' target='_blank'>Firefox</a> or Internet Explorer 7 with the <a href='http://www.dessci.com/en/products/mathplayer/' target='_blank'>MathPlayer</a> plugin to view this page!</div>");
      };
    }
  }
}

function isMPInstalled() {
  try {
    var oMP = new ActiveXObject("MathPlayer.Factory.1");
    return true;
  }
  catch(e) {
    return false;
  }
}

function isIEWindows() {
  return( (navigator.appName=="Microsoft Internet Explorer") && 
    (navigator.appVersion.indexOf("Windows") != -1) );
}

function ieVersion() {
  var ieVer = 0;
  var start = navigator.appVersion.indexOf("MSIE "); 
  if (start != -1) { 
    ieVer = parseFloat(navigator.appVersion.substring(start+5)); 
  }
  return ieVer;
}

function toggleNavigation () {
  // show the navigation
  // FIXME: switch between teacher/normal view
  e = $$("#navigationDropDown ul")[0];
  if (e) {
    e.getElementsBySelector("li ul").invoke('hide');
    
    // find current page and open it's ul, highlight current li
    fn = document.URL+"";
    fn = fn.replace(/.*\//,'');
    // fn = "marinepollution-c02-p02.html"; // DEBUG
    
    links = $$("#navigationDropDown a");
    for (var i = links.length - 1; i >= 0; i--) {
      l = links[i];
      if (l.href.match(fn)) {
        // current page found
        // alert("page found: "+l.href);
        $(l.parentNode.parentNode).show();
        $(l.parentNode).addClassName("current");
        break;
      };
    };
    
    
    $("navigationDropDown").setStyle('height:' + (document.viewport.getHeight() - 80) +'px;');
    $("navigationDropDown").toggle();
  };
}

function prepareNavigation () {
  // add a div element for the navigation
  $$('#header h1')[0].insert({before: new Element("input", {'id': "navigationButton", 'type': 'image', 'src': '.images/rose.png', 'width': '30', 'height': '30', 'alt': 'Navigation', 'title': 'Navigation'})});
  $$('#header h1')[0].insert({before: new Element("div", {'id': "navigationDropDown", 'style': 'display: none'})});
  $('navigationButton').onclick = toggleNavigation;
  // load the correct language navigation file
  var nav = "navigation.html";
  if (lang != '') {
    nav = "navigation."+lang+".html"
  };
  new Ajax.Updater("navigationDropDown", nav);
}

function navShow (element) {
  d = $(element);
  $(d.parentNode).getElementsBySelector("ul")[0].toggle();
}

function addDraftSign () {
  // add a "Draft Version" image to all pages
  $$('#header h1')[0].insert({before: new Element("img", {'id': "draftversion", 'src': ".images/draft-version-sign.png"})});
}

function loadglossary () {
  // load clossary items, when defined replace words in content
  var e = document.createElement("script");
  e.src = ".js/glossaryitems.js";
  e.type="text/javascript";
  $$('#header')[0].insert({before: e});
  // document.getElementsByTagName("head")[0].appendChild(e);
  // document.getElementsByTagName("head")[0].removeChild(e);
}

function glossary () {
  // replace all occurences of words in glossary with links to the definition
  // alert(GlossaryItems.length);
  if (typeof(GlossaryItems)!="undefined") {
    // replace manual glossary links
    $$('span.glossarylink').each(function(s) {
      glossary = "http://www.seos-project.eu/trac/wiki/Glossary/";
      title = s.getAttribute('title');
      if (GlossaryItems.indexOf(title) != -1) {
        link = document.createElement('a');
        Element.extend(link);
        link.addClassName('glossary');
        link.href=glossary+title;
        link.target="_blank";
        link.title="Glossary definition of "+title;
        link.innerHTML = s.innerHTML;
        s.replace(link);
      };
    })
    
    // replace all (english) glossary links
      for (var i = GlossaryItems.length - 1; i >= 0; i--){
        var r = new RegExp("\\s("+GlossaryItems[i]+")(s?)(\\.|\\,|\\;|\\:|\\!|\\?)?\\s","gi");
      $$('#content p').each(function(s) {
        temp = s.innerHTML;
        temp = temp.replace(r," <a class='glossary' href='http://www.seos-project.eu/trac/wiki/Glossary/"+GlossaryItems[i]+"' target='_blank' title='Glossary definition of \"$1\"'>$1$2</a>$3 ");
        
        if (s.innerHTML != temp) {
          s.innerHTML = temp;
          throw $break; // only replace the first occurrence
        };
      });
    };
      
  }
}

/*
* This functions returns an array containing 36 points to draw an
* ellipse.
*
* @param x {double} X coordinate
* @param y {double} Y coordinate
* @param a {double} Semimajor axis
* @param b {double} Semiminor axis
* @param angle {double} Angle of the ellipse
*
* Taken from http://en.wikipedia.org/wiki/Ellipse
*/
function calculateEllipse(x, y, a, b, angle, steps) {
  if (steps == null)
    steps = 36;
  var points = [];

  // Angle is given by Degree Value
  var beta = -angle * (Math.PI / 180); //(Math.PI/180) converts Degree Value into Radians
  var sinbeta = Math.sin(beta);
  var cosbeta = Math.cos(beta);

  for (var i = 0; i < 360; i += 360 / steps) 
  {
    var alpha = i * (Math.PI / 180) ;
    var sinalpha = Math.sin(alpha);
    var cosalpha = Math.cos(alpha);

    var X = x + (a * cosalpha * cosbeta - b * sinalpha * sinbeta);
    var Y = y + (a * cosalpha * sinbeta + b * sinalpha * cosbeta);

    points.push([X,Y]);
   }

  return points;
}

function arrangeInCircle () {
  // find circle div, arrange found image divs in an ellipse

  // get center of circle div
  var c = $('circle');
  var left = c.cumulativeOffset()[0]
  var top = c.cumulativeOffset()[1]
  var width = c.getWidth();
  var height = c.getHeight();
  var cx = (left+width/2).floor();
  var cy = (top+height/2).floor();
  var shrink = 95; // how many pixels to substract from "radius"
  

  $('center').center(cx,cy);

  var images = $('circle').getElementsBySelector("div.image");
  e = calculateEllipse(cx, cy, height/2-shrink, width/2-shrink, 90, images.length);
  
  // alert(images);
  
  for (var i=0; i < images.length; i++) {
    img = images[i];
    img.center(e[i][0],e[i][1]);
  };
  
}

function browserWarning () {
  // Check browser variant and versions, and display an error message if something unsupported is used
  // alert(BrowserDetect.browser + Number(BrowserDetect.version));
  if (!((BrowserDetect.browser == "Firefox" && Number(BrowserDetect.version) >= 3) || 
        (BrowserDetect.browser == "Mozilla" && Number(BrowserDetect.version) >= 1.9) ||
        (BrowserDetect.browser == "Explorer" && Number(BrowserDetect.version) >= 7) ||
        (BrowserDetect.browser == "Safari" && Number(BrowserDetect.version) >= 3) )) {
    $('headline').insert("<div id='browserwarning' class='mathplayermissing flushleft'><p class='textcentered'>You are using a browser which is not optimal for viewing the SEOS pages!</p><p>You are currently using "+BrowserDetect.browser+" version "+BrowserDetect.version+" which will not display the pages correctly. Please use to one of the following browsers:</p><ul><li>Firefox 3 or newer: <a href='http://getfirefox.com/' target='_blank'>http://getfirefox.com</a></li><li>Internet Explorer 7 or newer: <a href='http://www.microsoft.com/windows/downloads/ie/getitnow.mspx' target='_blank'>http://www.microsoft.com/windows/downloads/ie/getitnow.mspx</a></li></ul><p>Other Browser like Safari, Opera, Google Chrome or Konqueror should display most pages, but might not display the embedded formula correctly.</p><a href='#' onclick='$(\"browserwarning\").hide()' title='Hide this message'>hide this message</a></div>");
  };
}

function addHomeLink () {
  var homelink = new Element('a', {'id': 'homeLink', href: 'http://www.seos-project.eu/', "title": "SEOS Homepage" });
  $$('#header h1')[0].insert({before: homelink});
}

function checkLang () {
  if (lang == "ar") {
    // increase font-size
    var fs = "14px";
    jQuery('body').css("font-size", fs);
    jQuery('#details.caption p').css("font-size", fs);
    jQuery('div.description h2 span.textfull strong').css("font-size", fs);
    jQuery('#header h1').css("font-size", "22pt");
    
    // add CSS rules for global overrides (needed for dynamic content)
    var CSS = "<style type='text/css'>"+
      "#TB_ajaxContent { direction: rtl; text-align: right }"+
    "</style>";
    
    jQuery("head").append(CSS);
    
    // swap arrow descriptions
    p = $$('a[rel=prev]')[0].getAttribute('title');
    n = $$('a[rel=next]')[0].getAttribute('title');
    $$('a[rel=prev]').each(function(a) {
      a.setAttribute('title', n)
    });
    $$('a[rel=next]').each(function(a) {
      a.setAttribute('title', p)
    });
  } else if (lang == 'nl') {
    if ((document.URL.indexOf("world-of-images") != -1) && (!document.URL.match(/\d\d-ws\d\d/))) {
      jQuery("div.description #details p").css("font-size", "11px");
    }
  };
}

function onBodyLoad () {
  // glossary has to be called here, since otherwise the glossaryItems variable is not defined.
  glossary();
}

// jQuery onbodyload code
jQuery(function($) {
  // hide the last image
  $('div.changeimage img:last').hide();
  $('div.changeimage').bind('click', function(event) {
    $('img:last', this).attr({src: $('img:last', this).attr("src")});
    $('img', this).toggle();
  });
  
  // add imprint link
  $('#navigation_bottom a[rel="license"]').wrap('<div class="pageinfo"></div>').after(' <a href="http://www.seos-project.eu/imprint" class="imprint">Imprint</a>');
  if (window.location.host == "lms.seos-project.eu") {
    $('a.imprint').attr('href', 'http://lms.seos-project.eu/imprint/')
  };
});


document.observe("dom:loaded", function() {
  checkLang();
  loadglossary();
  if ((document.URL.indexOf("world-of-images") == -1) && (!document.URL.match(/\d\d-ws\d\d/))) {
    prepareNavigation();
  };
  addHomeLink();
  // addDraftSign();
  replaceRelLinks();
  // displayImageSwitchers();
  copyCaptions();
  checkForMathPlayer();
  browserWarning();
  if ($('circle')) {
    arrangeInCircle();
    $j(window).resize(arrangeInCircle);
  };
});

