// constants
var ACCORDIONHEIGHT = 'auto';
var TOOLTIPFADEIN = 250;
var TOOLTIPPREDELAY = 250;
var NAVIFADEIN = 200;
var TIMEOUTSHOW = 180;
var TIMEOUTHIDE = 500;
var MAXNAVILEVEL = 2;

$(document).ready(function() {

  // tooltips
  $('span.tooltipActuator, a.iconPatentList[title]').tooltip({
    onShow: function() {
      $('h1').css("zIndex", "0"); //tool tip should cover h1
      this.getTip().css({
        display: "none"
      }).fadeIn(TOOLTIPFADEIN);
    },
    onHide: function() {
       $('h1').css("zIndex", "1000");   // restore
    },
    tipClass: "dijitTooltipContainer",
    position: 'bottom right',
    offset: [17, -12], // 17px down, 12px left
    predelay: TOOLTIPPREDELAY
  });

  $('.tooltipWithLinks').tooltip({
    onShow: function() {
      this.getTip().css({
        display: "none"
      }).fadeIn(TOOLTIPFADEIN);
    },
    tipClass: "dijitTooltipContainer",
    position: 'bottom right',
    offset: [0, 0], 
    delay: 200
  });

  
  $('div.epoToolBar a[title], div.epoAccordionContainer a[title]').tooltip({
    onShow: function() {
      $('h1').css("zIndex", "0"); //tool tip should cover h1
      this.getTip().css({
        display: "none"
      }).fadeIn(TOOLTIPFADEIN);
    },
    onHide: function() {
       $('h1').css("zIndex", "1000");   // restore
    },
    tipClass: "dijitTooltipContainer",
    position: 'bottom center',
    offset: [17, 80],
    predelay: TOOLTIPPREDELAY
  });

  // selects
  $("div.formElement select").combobox({
    comboboxContainerClass: "selectContainer",
    comboboxValueContentContainerClass: "selectValueContainer",
    comboboxValueContentClass: "selectValueContent",
    comboboxDropDownClass: "selectDropDownContainer",
    comboboxDropDownButtonClass: "selectDropDownButton",
    comboboxDropDownItemClass: "selectItem",
    comboboxDropDownItemHoverClass: "selectItemHover",
    comboboxDropDownGroupItemHeaderClass: "selectGroupItemHeader",
    comboboxDropDownGroupItemContainerClass: "selectGroupItemContainer",
    animationType: "none"
  });
  //we have to create this select separately as a last one because there is a bug in update() function in jquery.combobox.js - it updates only combobox which was created last
  $("#sortColumn").combobox({
    comboboxContainerClass: "selectContainer",
    comboboxValueContentContainerClass: "selectValueContainer",
    comboboxValueContentClass: "selectValueContent",
    comboboxDropDownClass: "selectDropDownContainer",
    comboboxDropDownButtonClass: "selectDropDownButton",
    comboboxDropDownItemClass: "selectItem",
    comboboxDropDownItemHoverClass: "selectItemHover",
    comboboxDropDownGroupItemHeaderClass: "selectGroupItemHeader",
    comboboxDropDownGroupItemContainerClass: "selectGroupItemContainer",
    animationType: "none"
  });

  // accordions
  $('.epoAccordionContainer').Accordion({
    headerSelector: 'div.dijitAccordionTitle',
    panelSelector: 'div.dijitContentPane',
    activeClass: 'dijitAccordionTitle-selected',
    hoverClass: 'dijitAccordionTitle-hover',
    panelHeight: ACCORDIONHEIGHT,
    onShow: activatePaneTooltip
  });

  // expandable inputs
  $("textarea.expandable").expandableinput();

  // horizontal menu
  $('div.lvl1ul ul.primary > li').bind('mouseover', handleOpenMenu);
  $('div.lvl1ul ul.primary > li').bind('mouseleave', handleCloseMenu);

  // hide history toolbar 'li' before width checker so it is not counted
  if ($(".former").length == 0) {
    $(".epoToolBar #historyButton").parent("li").hide();
    $(".epoToolBar #histSeparator").hide();
  }
  else {
    $(".former").hide();
   }

  // autoresize window
  widthChecker();

  // focus on first form input
  $("form input:first, form textarea.expandable:first").focus();

  //IE6 does not expand default panel
  if (getInternetExplorerVersion() == 6) {
     $(".dijitAccordionText").mouseout();
  }

});

function activatePaneTooltip(){
 $('div.epoAccordionContainer a[title]').tooltip({
    onShow: function() {
        $('h1').css("zIndex", "0"); //tool tip should cover h1
        this.getTip().css({
        display: "none"
      }).fadeIn(TOOLTIPFADEIN);
    },
    onHide: function() {
       $('h1').css("zIndex", "1000");   // restore
    },
    tipClass: "dijitTooltipContainer",
    position: 'bottom center',
    offset: [17, 80], // 17px down, 12px left
    predelay: TOOLTIPPREDELAY
  });
}

// equals method for jquery
(function($) {

  jQuery.fn.equals = function(selector) {
    return $(this).get(0) == $(selector).get(0);
  };

})(jQuery);



var openSel = 0;
var closeSel = 0;
var tmpTimerShow = null;
var tmpTimerHide = null;
var activeNavItems = [null, null];


function handleCloseMenu(e) {
  e.stopPropagation()
  clearTimeout(tmpTimerShow);
  closeSel = this;

  tmpTimerHide = setTimeout(function() {
    hideOpenSubNavis(null);
  }, TIMEOUTHIDE);
}

function handleOpenMenu(e) {
  e.stopPropagation();
  var target = e.target;

  clearTimeout(tmpTimerHide);
  clearTimeout(tmpTimerShow);

  openSel = this;

  // Show sub navigation after a delay
  tmpTimerShow = setTimeout(function() {

    //showSubNavi(target);
    showSubNavi($(openSel).children("a:first"));
  }, TIMEOUTSHOW);

}

function hideOpenSubNavis(untilLevel) {
  var i = 2;
  isLevelSet = untilLevel || false;
  untilLevel = untilLevel || 0;

  // Close all sub navis until
  // the value of untilLevel
  while (--i >= untilLevel) {
    var subNavi = getSubNavi(activeNavItems[i]);
    activeNavItems[i] = null;
    if (subNavi != null) {
      makeSubNaviHidden(subNavi);
    }
  }

  // We want that the menu returns to its start status therefore
  // we search the selected 2nd level item
  /*  if (isLevelSet === false) {

   var subNavi = EPO.Navi.GetSubNavi(EPO.Globals.ActiveNavItems[0]);

   if (subNavi != null) {

   EPO.Navi.MakeSubNaviHidden(subNavi);

   }

   // Search the "open" class the select the selected navi

   // and show it

   var selectedNavi = dojo.query(".mainNavi ul.open");

   if (selectedNavi != null && selectedNavi.length > 0) {

   EPO.Globals.ActiveNavItems[0] = selectedNavi[0].parentNode;

   EPO.Globals.ActiveNavItems[0].childNodes[0].className = "sel";

   var newSubNavi = EPO.Navi.GetSubNavi(EPO.Globals.ActiveNavItems[0]);

   EPO.Navi.MakeSubNaviVisible(newSubNavi);

   }

   }

   */

}

function makeSubNaviHidden(objSubNavi) {
  // Restore the z-index of the breadcumb
  // dojo.query('#epoBreadcrumbs').style("zIndex", 999);

  // Hide Subnavi
  objSubNavi.css("display", "none");
  objSubNavi.children("ul.level2, ul.level3").css("display", "none");
  objSubNavi.children("ul.level2, ul.level3").css("visibility", "hidden");

  $(".activeNavItem").removeClass("activeNavItem");
  objSubNavi.children("div.flyoutSpacer").remove();
}


function showSubNavi(target) {
  // Get Items from event
  var currentA = null;
  var currentLi = null;
  var currentUl = null;

  // ?   clearTimeout(EPO.Globals.TimerLevel3);

  switch (target.get(0).nodeName.toLowerCase()) {
    case "a":
      currentA = target;
      currentLi = currentA.parent("li");
      currentUl = currentLi.parent("ul");
      break;
    case "li":
      currentLi = target;
      currentA = currentLi.children("a");
      currentUl = currentLi.parent("ul");
      break;
    case "ul":
      //         if (target.className.indexOf("level2") > -1) {
      //            EPO.Navi.HideOpenSubNavis(1);
      //         }
      return;default:
      return;  }

  // Get level of current menu
  var naviLevel = getLevel(currentUl);

  // Shorter Syntax helper (Pointer)
  var navs = activeNavItems;

  //	Check if the level returned is between our level bariers
  var isBetweenLevel = naviLevel < MAXNAVILEVEL;

  // If navigation level is o.k.
  if (naviLevel > -1 && isBetweenLevel == true) {

    // Get sub navigation if one exists
    // else null is returned
    var activeSubNavi = getSubNavi(navs[naviLevel]);

    // Get sub navigation of the current item if one exists
    // else null is returned
    var newSubNavi = getSubNavi(currentLi);

    var isVisible = (newSubNavi != null) && (newSubNavi.css("display") != "none");

    // Hide the currently active sub navigation if the
    // current item in upper level has changed


    if (navs[naviLevel] != null && !navs[naviLevel].equals(currentLi)) {
      if (activeSubNavi != null) {
        makeSubNaviHidden(activeSubNavi);
      }
    }

    // Show sub navigation if the
    // current item in the level has changed
    if (navs[naviLevel] == null || navs[naviLevel] != currentLi || (navs[naviLevel] == currentLi && isVisible == false)) {
      makeSubNaviVisible(newSubNavi, true);
    }

    // Set the new current active item for this level
    navs[naviLevel] = currentLi;
  }
}


function makeSubNaviVisible(objSubNavi, doFade) {
  if (objSubNavi == null || typeof objSubNavi == "undefined") { return; }

  var doFade = doFade || false;

  //   var opacity = (doFade) ? "0" : "1";

  // dropdown should cover headers
  $('h1').css("zIndex", "1");
  objSubNavi.parent().addClass("activeNavItem");

  // fade in animation
  (doFade) ? objSubNavi.fadeIn(NAVIFADEIN) : "";
  objSubNavi.css({
    'visibility': 'visible',
    'display': 'block'
  });

  // flyout div
  var top = objSubNavi[0].offsetHeight + objSubNavi[0].offsetTop;
  var width = objSubNavi[0].offsetWidth;
  objSubNavi.parent().append("<div class=\"flyoutSpacer\" style=\"width:" + width + "px; top:" + top + "px;\"></div>")
}

function getSubNavi(itemLi) {
  if (itemLi == null || !itemLi.children("a:first").hasClass("hasSubMenu")) { return null; }

  return itemLi.children("div.epoMenu");
  // return (itemLi != null && typeof itemLi.childNodes[2] != "undefined") ? itemLi.childNodes[2] : null;
}

function getLevel(itemUl) {

  var level = itemUl.attr('class');
  //dirty fix for the "Other online services" menu item in the toolbar 
  if('primary' == level) return 0;
  //end of dirty fix
  level = level.substr(3, 1);
  level = parseInt(level);
  
  return isNaN(level) ? -1 : (level - 1);
}



function widthChecker() {
  // Variables
  var screen = $("#body");
  var noSiteExtension = $(".noSiteExtension");

  // 1) break early if we are on the sample overviewpage where is no #body.
  // 2) break early is class noSiteExtension is added in div#body
  if (screen == null || noSiteExtension == null) { return; }
  else {
    var usableScreenSize = screen.width();
  }


  // break early, if screen size is below 761px as then we are not in application context but in normal website,
  // where screen resizing is not supported(see concept)
  //if (usableScreenSize < 761) {
  //  return;
  //}

  var largestElementSize = 0;
  var sumToolbar = 0;
  var sumTable = 0;

  // Check if there is a toolbar
  var epoToolbarElements = $(".epoToolBar ul li");


  // Check if there is table with TD or TH in first row, before doing so check if there is a thead set or not!
  var epoTableHead = $("table thead");
  if (!epoTableHead.length) {

    var epoTableCell = $("table tr:first-child th");
    if (!epoTableCell.length) {
      var epoTableCell = $("table tr:first-child td");
    }
  }
  else {
    var epoTableCell = $("table thead tr:first-child th");
    if (!epoTableCell.length) {
      var epoTableCell = $("table thead tr:first-child td");
    }
  }

  // break early if there is neither a toolbar nor a table
  if (!epoToolbarElements.length && !epoTableCell.length) { return; }


  // Check widths of toolbar and table...
  if (epoToolbarElements != null) {
    sumToolbar = returnToolbarWidthh();
  }
  if (epoTableCell != null) {
    sumTable = returnTableWidthh();
  }

  // ...and determine largest element
  if (sumToolbar < sumTable) {
    largestElementSize = sumTable;
  }
  else {
    largestElementSize = sumToolbar;
  }

  // Check if the width of largest element is larger than width of screen and if necessary reset screen width
  var minScreenWidth = 761;
  if (getInternetExplorerVersion() > -1)  minScreenWidth = 920;
  if (largestElementSize > minScreenWidth) {
    setScreenWidthh(largestElementSize);
  } else setScreenWidthh(minScreenWidth);

}

function setScreenWidthh(largestElementSize) {

  var pageWrap = $(".pageWrap");
  var epoContentLeft = $("#epoContentLeft");

  // Check if there's a epoContentLeft Navigation Bar
  //if epoContentLeft is not "", there is a left contentbar and we have to add that space
  if (epoContentLeft == null) {
    screenWidth = largestElementSize;
  }
  else {
    screenWidth = largestElementSize + 201;
  }


  //add little extra space
  screenWidth += 50;

  //set screen size
  pageWrap.width(screenWidth);
}

function returnTableWidthh(epoElement) {

   var tables = $("table");
    var sum = 0;
   tables.each(function(index) {

      var tmpSum = 0;
      var epoTableHead = $(this).children("thead");
        if (!epoTableHead.length) {
          var epoTableCell = $(this).find("tr:first-child th");
          if (!epoTableCell.length) {
            var epoTableCell = $(this).find("tr:first-child td");
          }
        }
        else {
          var epoTableCell = $(this).find("thead tr:first-child th");
          if (!epoTableCell.length) {
            var epoTableCell = $(this).find("thead tr:first-child td");
          }
        }

      epoTableCell.each(function(index) {
          tmpSum += $(this).outerWidth(true); // include padding, border, margin
      });

      if (tmpSum > sum) {
         sum = tmpSum;
      }
   });

     if (getInternetExplorerVersion() > -1) {
        sum += 25;
     };

     sum += 21; // right margin
     return sum;
   }

function returnToolbarWidthh() {
  var sum = 0;
  var iever = getInternetExplorerVersion();

  $(".epoToolBar ul li").each(function(index) {
    if ($(this).css("display") != "none") {
      sum += $(this).outerWidth(true); // include padding, border, margin
      if (iever > -1) {
        sum += 10;
      }
      if (isSafari() || isOpera()) {
        sum += 15;
      }
    }
  });

  sum += 21; // right margin
  return sum;
}

function getInternetExplorerVersion() {

  var rv = -1; // Return value assumes failure.
  if (navigator.appName == 'Microsoft Internet Explorer') {
    var ua = navigator.userAgent;
    var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat(RegExp.$1);
  }
  return rv;
}

function isSafari() {
  return (navigator.userAgent.indexOf('Safari') != -1 && !isChrome());
}

function isOpera() {
  return (navigator.userAgent.indexOf('Opera') != -1);
}

function isChrome() {
  return Boolean(window.chrome);;
}

function isFirefox() {
  return (navigator.userAgent.indexOf("Firefox")!=-1);
}

function submitenter(myfield, e) {
  var keycode;
  if (window.event)
    keycode = window.event.keyCode;
  else if (e)
    keycode = e.which;
  else
    return true;

  if (keycode == 13)
    return gotoPage(myfield.value);
  else
    return true;
}

function trim(selector) {
   $(selector).val($.trim($(selector).val()));
   return $.trim($(selector).val());
}

function getPage(){
  var q = window.location.pathname;
  var p = q.split('/');
  return p[p.length-1];
}

function setQueryVariable(url, variable, value) {
     var vars = url.split("&");
     for (var i=0;i<vars.length;i++) {
       var pair = vars[i].split("=");
       if (pair[0] == variable) {
         return url.replace("&"+pair[0]+"="+pair[1], "&"+pair[0]+"="+value);
       }
     }
      return url+"&"+variable+"="+value;
   }

function removeQueryVariable(url, variable) {
     var vars = url.split("&");
     for (var i=0;i<vars.length;i++) {
       var pair = vars[i].split("=");
       if (pair[0] == variable) {
         return url.replace("&"+pair[0]+"="+pair[1], "");
       }
     }
      return url;
   }

