var Y = YAHOO;
var yui = Y.util;
var Dom = Y.util.Dom;
// hcl0807828: "Event" / "Selector" and prototype dont mix. Obacht! use yui.Event / yui.Selector instead. 

// first of all, set jsAvailable class
yui.Event.onAvailable("doc4", function () {
    Dom.removeClass('doc4', 'jsUnknown');
    Dom.addClass('doc4', 'jsAvailable');
});

// schnellzugang
var qAccess = {
  qmenu : {},
  init : function(){
    this.qmenu = document.getElementById("naviQuickBar");
    Dom.addClass(this.qmenu, 'inactive');
    this.qmenu.items = yui.Selector.query('.yuimenubaritem', this.qmenu);
    this.qmenu.links = yui.Selector.query('.yuimenubaritemlabel', this.qmenu);
    this.closeSubs();
    for (var i=0;i<this.qmenu.links.length;i++){
      this.qmenu.links[i].onclick = function(){
        qAccess.openSub(this.parentNode);
        this.blur();
      };
    }
  },
  toggle :  function(isClosed){
    if(Dom.hasClass(this.qmenu, 'inactive')){
      Dom.removeClass(this.qmenu, 'inactive');
    } else {
      Dom.addClass(this.qmenu, 'inactive');
    }
  },
  openSub : function(aMenu){
    var isClosed = Dom.hasClass(aMenu, 'inactive');
    this.closeSubs();
    if(isClosed) {
      Dom.removeClass(aMenu, 'inactive');
    }
  },
  closeSubs : function(){
    var items = this.qmenu.items;
    for(var i=0;i<items.length;i++){
      Dom.addClass(items[i], 'inactive');
    }
  }
};

// once hd is available initialize all head features
yui.Event.onContentReady("hd", function () {
  // hauptnavi
  var mMenuBar = new Y.widget.MenuBar("naviMain", {  
                                                  autosubmenudisplay: true,  
                                                  hidedelay: 90,  
                                                  zindex: 36,
                                                  lazyload: true }); 
  mMenuBar.render();
  // init schnellzugang
  qAccess.init();

  // sitesearch init
  // Wtf is this doing with the new?
  
  // TODO REACTIVATE ME AS SOON AS THE SEARCH CONTROLLER IS FIXED
  
  /*Y.example.ACJson = new function (){
    // Instantiate an XHR DataSource and define schema as an array:
    //     ["Multi-depth.object.notation.to.find.a.single.result.item",
    //     "Query Key",
    //     "Additional Param Name 1",
    //     ...
    //     "Additional Param Name n"]
    this.oACDS = new YAHOO.widget.DS_XHR("/search", ["ResultSet.Result","Term"]);
    this.oACDS.queryMatchContains = true;
    this.oACDS.scriptQueryAppend = "language=" + document.getElementById('language').value;
    //this.oACDS.scriptQueryAppend = "output=json&results=100"; // Needed for YWS
    
    // Instantiate AutoComplete
    for (var i = 1; i <= 2; i++) {
      this.oAutoComp = new YAHOO.widget.AutoComplete("searchinput"+i, "searchcontainer"+i, this.oACDS);
      this.oAutoComp.useShadow = true;
      this.oAutoComp.maxResultsDisplayed = 25;
      this.oAutoComp.formatResult = function(oResultItem, sQuery){
        return oResultItem[1].Term;
      };
      this.oAutoComp.doBeforeExpandContainer = function(oTextbox, oContainer, sQuery, aResults){
        var pos = Dom.getXY(oTextbox);
        pos[1] += Dom.get(oTextbox).offsetHeight + 2;
        Dom.setXY(oContainer, pos);
        return true;
      };
    }
    // Stub for form validation
    this.validateForm = function() {
        // Validation code goes here
        return true;
    };
  };*/
});

// contextmenu
var contextmenu = {
  init : function(){
    if (document.getElementById('kontextnavi')){
      naviroot = document.getElementById('kontextnavi');
      currentItem = yui.Selector.query('li.active', naviroot,true);
      if (currentItem){
        nextLevel = currentItem.parentNode;
        if(nextLevel.className == "folded") {
          nextLevel.className = "opened";
        }
        nextLevel = nextLevel.parentNode.parentNode;
        if(nextLevel.className == "folded") {
          nextLevel.className = "opened";
        }
      }
    }
  }
};

var xanthippe = {
  types : {
    big : {
      itemW : 149,
      itemH : 110,
      visItems : 3,
      zoomH : 174,
      zoomW : 206
    },
    wide : {
      itemW : 118,
      itemH : 78,
      visItems : 4,
      zoomH : 135,
      zoomW : 191
    },
    tall : {
      itemW : 66,
      itemH : 78,
      visItems : 8,
      zoomH : 135,
      zoomW : 92
    },
    xtall : {
      itemW : 37,
      itemH : 78,
      visItems : 15,
      zoomH : 135,
      zoomW : 45
    }
  },
  activeXanthippe : {},
  init : function(aRoot){
    rootElement = (aRoot)?aRoot:"doc4";
    xXs = Dom.getElementsByClassName('xrow', 'div', rootElement);
    for (var i=0;i<xXs.length;i++){
      theX = xXs[i];
      theX.id = rootElement+"xanthippe-"+i;
      theX.ul = yui.Selector.query('ul', theX, true);
      theX.lis = yui.Selector.query('li', theX); 
      
//      if(location.href.indexOf(':3000')>0) {
//        imgs = yui.Selector.query('img', theX);
//        for(img=0;img<imgs.length;img++){
//          imgs[img].src="/images/dummy/xanthippe.jpg"
//        }
//      }
      
      this.setUpScrolling(theX);
      
      theX.zoomEnabled = !Dom.hasClass(theX, 'nozoom');
      if(theX.zoomEnabled){
        this.setUpZooming(theX);
      }
    }  
  },
  setUpScrolling : function(aX){
    aX.stg = yui.Selector.query('.xstage', aX, true);
    //
    // extract function to retrieve type from class name via types hash. Esp. dont fail if other classes are defined
    theType = aX.ul.className;
    aX.type = this.types[theType]; 
    //
    aX.w = aX.type.itemW * aX.type.visItems;
    fullwidth = aX.type.itemW * (aX.lis.length + 1);
    aX.ul.style.width = fullwidth+"px";
    //
    aX.currentPage = 1;
    aX.currentFirst = 0;
    aX.maxPage = Math.ceil((aX.lis.length-1)/aX.type.visItems);
    arrows = Dom.getElementsByClassName('arrow', 'a', aX);
    aX.leftArrow = arrows[0];
    aX.rightArrow = arrows[1];
    
    var myStageId = aX.stg.id;
    if (myStageId.indexOf("jump-No-")>=0) {
        myInitPos = myStageId.substr(myStageId.indexOf("jump-No-")+8);
        this.jump(aX, myInitPos);
    } else if (myStageId.indexOf("jump-Id-")>=0) {
        myInitId = myStageId.substr(myStageId.indexOf("jump-Id-")+8);
        theX.links = yui.Selector.query('a.assetlink', theX.ul);
        myInitPos = 0;
        for(var j=0;j<theX.links.length;j++){
          if (theX.links[j].id == myInitId) {
            myInitPos = j;
          }
        }
        this.jump(aX, myInitPos);
    } else {
      aX.leftArrow.className = "arrow prevdimmed";
      if(aX.maxPage < 2) {
        aX.rightArrow.className = "arrow nextdimmed";
      }
    }
  },
  trackMouseH : function(e){
    var my_e = e;
    var posx = 0;
    if (!my_e) {
      my_e = window.event;
    }
    if (my_e.pageX)  {
      posx = my_e.pageX;
    }
    else if (my_e.clientX)   {
      posx = my_e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
    }
    this.mouseX = posx - Dom.getX(this);
  },
  setUpZooming : function(aX){
    yui.Event.addListener(aX, "mousemove",xanthippe.trackMouseH);
    yui.Event.addListener(aX, "mouseover",xanthippe.trackMouseH);
    for (var j=0;j<aX.lis.length;j++){
      theLi = aX.lis[j];
      theLi.ndx = j;
      theLi.x = aX;
      theLi.ximg = yui.Selector.query('img', theLi,true);
      theLi.xa = yui.Selector.query('a', theLi,true);
      theLi.xasstlink = yui.Selector.query('a.assetlink', theLi,true);
      theLi.xzoomlink = yui.Selector.query('a.zoomlink', theLi,true);
    }
    aX.zoom = document.createElement("ul");
    aX.zoom.id = "zozo";//+i; // WTF?
    aX.zoom.className = "xZoomLayer z"+aX.ul.className;
    aX.zoom.hasText = !Dom.hasClass(theX, 'notext');
    aX.appendChild(aX.zoom);
    
    aX.ratio = aX.type.itemH / aX.type.itemW;
    
    aX.onmouseover = function(){
      xanthippe.over(this);
    };
    aX.onmouseout = function(){
      xanthippe.out(this);
    };
    this.loadZoomItems(aX);
  },
  out : function(aX){
    aX.mouseX = -1;
  },
  over : function(aX){
    if (this.activeXanthippe != aX) {
      if (this.activeXanthippe != {}){
        this.terminateXzoom(this.activeXanthippe);
      }
      this.activeXanthippe = aX;
      window.setTimeout("xanthippe.zoomLoop()",300);
    }
  },
  loadZoomItems : function(aX){
    aX.zoom.innerHTML = "";
    for(var zI=0;zI<=aX.type.visItems;zI++){
      sourceLi = aX.lis[aX.currentFirst+zI];
      if(sourceLi){
        var newLi = document.createElement("li");
        newLi.a = document.createElement("a");
        newLi.img = document.createElement("img");
        newLi.descr = document.createElement("div");
        
        newLi.img.src = sourceLi.xzoomlink.href;
        
        ///   hack to handle wrong zoomlinks (>>flv/swf)
        var zoomFile = newLi.img.src.toLowerCase();
        if(zoomFile.indexOf(".jpg")<0 && zoomFile.indexOf(".png")<0){
          zoomSrc = sourceLi.ximg.src;
          newLi.img.src = zoomSrc;
        }
        ///  - end hack
        
        if(sourceLi.ximg.id) newLi.img.id = sourceLi.ximg.id+ "_zoom";
        newLi.a.href = sourceLi.xa.href;
        newLi.a.targetA = sourceLi.xa;
        newLi.a.onclick = function(){
              this.targetA.onclick();
              return false;
            };
        if (aX.zoom.hasText) {
          newText = (sourceLi.ximg.alt)?sourceLi.ximg.alt:"";
          newText += (sourceLi.xa.title)?"<br />&copy;" + sourceLi.xa.title:"";
          newLi.descr.innerHTML = newText;
        }
        newLi.className = "isHidden";
        newLi.style.left = "-3000px";
        
        newLi.appendChild(newLi.a);
        newLi.a.appendChild(newLi.img);
        if (newLi.descr.innerHTML) newLi.appendChild(newLi.descr);
        aX.zoom.appendChild(newLi);
      }
    }
  },
  zoomLoop : function(){
    theX = this.activeXanthippe;
    if (theX.mouseX > 20 && theX.mouseX < 616){
      highPos = (theX.mouseX-20-theX.type.itemW/2)/(theX.type.itemW);
      zoomItems = theX.zoom.childNodes;
      baseY = Dom.getY(theX) + theX.type.itemH / 2;
      for(var x=0;x<zoomItems.length;x++){
        dist = highPos-x;
        distA = Math.abs(dist);
        if (distA > 1.5) {
          newClassname = "isHidden";
          newW = 0;
        } else if (distA > 0.4) {
          zoomFaktor = 3/(1.65+distA);
          newW = Math.floor( theX.type.itemW * zoomFaktor );
          newClassname = "isFloating";
          zoomItems[x].style.width = newW + "px";
          zoomItems[x].style.zIndex = Math.floor(305-distA)+"";
        } else {
          newClassname = "isOntop";
          newW = theX.type.zoomW; // will be changed to actual settings
          zoomItems[x].style.width = newW + "px";
          zoomItems[x].style.zIndex = "305";
        }
        if (newW > 0) {
          //xAdjust = -2*highPos+highPos;  adjustment for NOT hiding arrows
         // w.add(Math.floor(highPos));
          xAdjust = 18 + (theX.type.itemW - newW)*highPos/(theX.type.visItems+1); 
          newX = theX.type.itemW*x + Dom.getX(theX) + xAdjust;
          newH = newW * theX.ratio / 2;
          newY = 18+baseY-newH;
          newXY = [newX,newY];
          Dom.setXY(zoomItems[x],newXY);
        }
        zoomItems[x].className = newClassname;
      }
      this.draw = true;
      this.zLoop = window.setTimeout("xanthippe.zoomLoop()",150);
    } else {
      window.clearTimeout(this.zLoop);
      this.terminateXzoom(theX);
    }
  },
  terminateXzoom : function(aX){
    if (aX.zoom){
      zoomItems = aX.zoom.childNodes;
      for(var x=0;x<zoomItems.length;x++){
          zoomItems[x].className = "isHidden";
      }
    }
    if (this.activeXanthippe == aX) {
      this.activeXanthippe = {};
    }
  },
  jump : function(theX, thePosition){
    var myTargetPage = Math.ceil(thePosition / theX.type.visItems);
    if (myTargetPage < 1) {
        myTargetPage = 1;
    }
    if (myTargetPage > theX.maxPage) {
        myTargetPage = theX.maxPage;
    }
    oldpos = Dom.getX(theX.ul);
    newpos = oldpos + (-theX.w*(myTargetPage-theX.currentPage));
    Dom.setX(theX.ul, newpos);
    theX.currentPage = myTargetPage;
    theX.currentFirst = (theX.currentPage-1) * theX.type.visItems;
    
    links = yui.Selector.query('.arrow', theX);
    if (theX.currentPage == 1) {
      links[0].className = "arrow prevdimmed";
      links[1].className = "arrow next";
    } else if(theX.currentPage == theX.maxPage) {
      links[0].className = "arrow prev";
      links[1].className = "arrow nextdimmed";
    } else {
      links[0].className = "arrow prev";
      links[1].className = "arrow next";
    }
  },
  scroll : function(theX,direction){
    if (theX.currentPage + direction > 0 && theX.currentPage + direction <= theX.maxPage ){
      oldpos = Dom.getX(theX.ul);
      newpos = oldpos +(-theX.w*direction);
      activeXanthippe = theX;
      this.anim(oldpos,newpos);
    }
  },
  scrollDone : function(theX,direction){
      theX.currentPage = theX.currentPage + direction;
      theX.currentFirst = (theX.currentPage-1) * theX.type.visItems;
      
      if(theX.zoomEnabled){
        this.loadZoomItems(theX);
      }
      activeXanthippe = {};
      
      links = yui.Selector.query('.arrow', theX);
      if (theX.currentPage == 1) {
        links[0].className = "arrow prevdimmed";
        links[1].className = "arrow next";
      } else if(theX.currentPage == theX.maxPage) {
        links[0].className = "arrow prev";
        links[1].className = "arrow nextdimmed";
      } else {
        links[0].className = "arrow prev";
        links[1].className = "arrow next";
      }
  },
  anim : function(x,end){
    theX = activeXanthippe;
    Dom.setX(theX.ul, x);
    dir = (x-end)/Math.abs(x-end);
    newX=(x<end)?x+50:x-50;
    if(Math.abs(x-end)>60){
      setTimeout("xanthippe.anim("+newX+","+end+")",30);
    } else {
      Dom.setX(theX.ul, end);
      this.scrollDone(theX,dir);
    }
  }
};

// medialayer
var medialayer = {
  init : function(){
    // all initial values are now at highslide js
  },
  loaded : function(aId){
    xId = aId.replace(/\?id=/,"");
    if(document.getElementById(xId)){
      xanthippe.init(xId);
    }
  }
};

var jumpTo = function(aAnchor){
  window.location.hash=aAnchor;
};

var w = {
  init : function(){
    rootDiv = document.getElementById("doc4");
    testDiv = document.createElement("div");
    testDiv.id="testDiv";
    testDiv.innerHTML = this.closer;
    if(location.href.indexOf(':3000')>0 && location.href.indexOf('test')>0) {
      rootDiv.appendChild(testDiv);
    }
  },
  out : function(anArg){
    if(location.href.indexOf(':3000')>0) {
      testDiv.style.right = "0";
      testDiv.innerHTML = anArg+this.closer;
    }
  },
  add : function(anArg){
    if(location.href.indexOf(':3000')>0) {
      testDiv.style.right = "0";
      testDiv.innerHTML = anArg+"<hr />"+testDiv.innerHTML+this.closer;
    }
  },
  closer : "<hr /><a href='javascript:w.close()'>close</a>",
  close : function(){
    testDiv.style.left="-1000px";
  }
};

// Change Style for external links
var change_link_style = function(el) {
    var currentHref = el.getAttribute("href");
    if (currentHref.indexOf("http://" + window.document.location.hostname ) !== -1) {
        //Noop
    } else if (currentHref.indexOf("http://") !== -1) {
        Dom.addClass(el, "extern");
        el.target = "_blank";
    }
};

var highlight_external_links = function() {
    Dom.getElementsBy(change_link_style, "a");
};

var initPage = function(){
  w.init();
  contextmenu.init();
  xanthippe.init();
  //medialayer.init();
  highlight_external_links();
  
  a = document.location.search;
  if (a.indexOf("jump_to")>0){
    a = a.replace(/.*jump_to=/,"");
    window.setTimeout("jumpTo('"+a+"')",10);
  }
};
 
yui.Event.onDOMReady(initPage);