// Array.indexOf für Internet Explorer nachreichen
if (!Array.indexOf) {
  Array.prototype.indexOf = function (obj, start) {
    for (var i = (start || 0); i < this.length; i++) {
      if (this[i] == obj) {
        return i;
      }
    }
    return -1;
  }
}

//provide function to escape regular expressions
RegExp.escape = function(text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
}

$(document).ready(function() {
  //Stylesheet-Changer
  initializeStyleSheetChanger();
  
  //Stylesheet-Menü
  initializeStylesheetMenu();

  //Fontstyle-Menü
  initializeFontstyleMenu();
  
  //Facebox
  initializeFacebox();
  
  // Navigation
  initializeNavigation();
  
  // Kommentierter Studienplan
  initializeKOST();
  
  //Abkürzungen etc.
  initializeDefinitions();
  
  //Skype-Addon deaktivieren
  disableSkypeAddon();

});

  if($.cookie("css-style")) {
    $("link.currentTheme").attr("href",$.cookie("css-style"));
  }

  if($.cookie("css-fontstyle")) {
    $("link.fontstyle").attr("href",$.cookie("css-fontstyle"));
  }

//style sheet changer
$(document).load(function() {

});


//get the corresponding URL of a file
function getUrl(url) {
  url = resolveUrl(url)
    return url;
}

//additional background
function setAdditionalBackground(element,pictureURL, position) {
  if ($(element).css('background-image') != 'none') {
      $(element).css('background-image', 'url(' +  getUrl(pictureURL) + '), ' + $(element).css('background-image'));
    if (position != '') {
        $(element).css('background-position', position);
      }
  }
}

// clear background
// clears the background of the additional (extra) style, so that the new style can be applied
function clearBackground(element) {
  $(element).css('background-image', '');
}

function initializeStyleSheetChanger() {
  $("#changeStylesheet ul li a").click(function() {
    
    clearBackground('#navigation'); // clears the background of the additional (extra) style, so that the new style can be applied
    clearBackground('#logoLink');
    clearBackground('#TOC');
    clearBackground('.stickyBox.extraStyle');
    
    $("link.currentTheme").attr("href",$(this).attr('rel'));
    $.cookie("css-style",$(this).attr('rel'), {expires: 365, path: '/'});
    if (setStyleBackground != undefined) { // tests if there is an additional (extra) style active
      setStyleBackground(); // sets the additional background of the extra style
    } 
    return false;
  });

  $("#changeFontsize ul li a").click(function() {
    $("link.fontsize").attr("href",$(this).attr('rel'));
    $.cookie("css-font",$(this).attr('rel'), {expires: 365, path: '/'});
    return false;
  });
  
  $("#changeFontstyle ul li a").click(function() {
    $("link.fontstyle").attr("href",$(this).attr('rel'));
    $.cookie("css-fontstyle",$(this).attr('rel'), {expires: 365, path: '/'});
    return false;
  });
  
}


function initializeStylesheetMenu() {
  hideStylesheetMenuExceptActive();
  
  $('ul#listStylesheets').hover(function() {
    $('ul#listStylesheets>li').show();
  }, function(){
    hideStylesheetMenuExceptActive();
  });
}

function hideStylesheetMenuExceptActive() {
  $('ul#listStylesheets>li').hide();
  $('ul#listStylesheets>li').each(function() {
    if ($(this).children('a').attr('rel') == $("link.currentTheme").attr('href')) {
          $(this).show();
        }
  });
}

function initializeFontstyleMenu() {
  hideFontstyleMenuExceptActive();
  
  $('ul#listFontstyle').hover(function() {
    $('ul#listFontstyle>li').show();
  }, function(){
    hideFontstyleMenuExceptActive();
  });
}

function hideFontstyleMenuExceptActive() {
  $('ul#listFontstyle>li').hide();
  $('ul#listFontstyle>li').each(function() {
    if ($(this).children('a').attr('rel') == $("link.fontstyle").attr('href')) {
          $(this).show();
        }
  });
}

//Facebox
function initializeFacebox() {
    $('img.facebox').each(function() {
        parent = $(this).parent('a');
        
        if (!parent.hasClass('facebox')) {
            parent.addClass('facebox');
        }
    });
    
    $('a.facebox')
      .attr('rel', 'facebox');

    $('a[rel*=facebox]').facebox({
        loadingImage : resolveUrl('~/umbraco/images/design/loading.gif'),
        closeImage   : resolveUrl('~/umbraco/images/design/closelabel.png')
    });
}

// resolveUrl für Facebox
function resolveUrl(url) {
    if (url.indexOf("~/") == 0) {
        url = baseUrl + url.substring(2);
    }
    return url;
}

// Navigation
function initializeNavigation() {
    initializeNavigationLayout();
    initializeNavigationExpand();
    $('ul.level1 ul').css('visibility', 'visible');
}

function initializeNavigationLayout() {
    $('ul.level2>li, ul.level4>li').show();
  
    $('ul.level4').each(function() {
        currentItem = $(this);
        
        //set width manually to prevent it from being capped later
        currentItem.width(currentItem.width());
        
        maxWidth = 0;
        
        currentItem.parents('ul.level1>li').find('ul.level2, ul.level3').each(function() {
            if ($(this).width() > maxWidth) {
                maxWidth = $(this).width();
            }
        });
        
        currentItem.css('left', maxWidth + 22 + 'px');
    currentItem.data('expandedTop', currentItem.parents('ul.level3>li').position().top + 'px');
        currentItem.css('top', '0px');
    });
}

function initializeNavigationExpand() {
    prepareNavigationExpand();
  
  //prepare navigation bar
    navigationBar = $('#navigation');
  navigationBarHeight = prepareNavigationHeight(navigationBar);
    
    //hover level1 & level3
    initializeNavigationHoverLevel1(navigationBar);
  initializeNavigationHoverLevel3();
    
    //make level3 link red on mouseOver
  initializeLevel3Highlight();
    
    //hide navigation if #navigation is left
    initializeHideNavigationOnMouseLeave(navigationBar);
}

function prepareNavigationExpand() {
  //save level2 height to each ul
    $('ul.level2').each(function() {
        $(this).data('height', $(this).height());
    });
    
    //hide all level2>li, level3>li and level4>li elements that are not part of the current navigation path
    $('ul.level2>li, ul.level3>li, ul.level4>li').not('.currentNavigationPath').hide();
}

function prepareNavigationHeight(navigationBar) {
  navigationHeightRaw = navigationBar.height();
    navigationHeight = navigationHeightRaw + $('ul.level1>li.currentNavigationPath>ul.level2').height();
    navigationBar.height(navigationHeight);
  
  return navigationHeight;
}

function initializeNavigationHoverLevel1(navigationBar) {
  $('ul.level1>li').hover(function() {
    $(this).find('ul.level4').each(function() {
      $(this).css('top', $(this).data('expandedTop'));
    });
    
    //fade out ul.level4 if hovered item is part of the current navigation path
        if ($(this).find('ul.level4>li:visible').length == 1 && ($(this).find('ul.level4>li:visible').siblings().length > 0 && $(this).find('ul.level4>li:visible').siblings(':visible').length == 0)) {
            $('ul.level4>li').hide();
            clearLevel3Hover();
        }
    
        //hide only if hovered item isn't visible anyway (prevent hide/show cycle if current item is already visible)
        if ($(this).find('ul.level2>li').length == 0 || $(this).find('ul.level2>li').css('display') == 'none') {
            $('ul.level2>li').hide();
             $('ul.level4>li').hide();
            clearLevel3Hover();
        }
        
        //show current sub-navigation    
        navigationItemHeight = 0;
        
        if ($(this).children('ul.level2').length > 0) {
            navigationItemHeight = $(this).children('ul.level2').data('height');
        }
        
        navigationBar.clearQueue().animate({height: navigationHeightRaw + navigationItemHeight}, 'fast');
        $(this).find('ul.level2>li, ul.level3>li').fadeIn(10);
        
    }, function () {});
}

function initializeNavigationHoverLevel3() {
  $('ul.level3>li>a').hover(function() {
        //hide/unhide only if hovered item isn't visible anyway (prevent hide/show cycle if current item is already visible)
        if ($(this).parent().find('ul.level4>li').length == 0 || $(this).parent().find('ul.level4>li').css('display') == 'none') {
            $('ul.level4>li').hide();
        }
        
        //show current sub-navigation    
        $(this).siblings('ul.level4').children('li').fadeIn(10);
    }, function() {});
}

function initializeLevel3Highlight() {
    $('ul.level3>li>a').hover(function() {
        clearLevel3Hover();
    
        if ($(this).siblings('ul.level4').length > 0) {
            $(this).parent('ul.level3>li').addClass('hover');
        }
    }, function() {});
}


function initializeHideNavigationOnMouseLeave(navigationBar) {
  $('#navigation').hover(function() {}, function() {
        $('ul.level2>li, ul.level3>li, ul.level4>li').not('.currentNavigationPath').hide();
        $('li.currentNavigationPath').fadeIn(10);
        navigationBar.clearQueue().animate({height: navigationHeight}, 'fast');
        
        clearLevel3Hover();
    
    $('ul.level4').css('top', '0px');
    });
}

function clearLevel3Hover() {
    $('ul.level3>li').removeClass('hover');
}

// Kommentierter Studienplan

function initializeKOST() {
  $('a.showComments').click(toggleKOST);
}


function toggleKOST() {
  if ($(this).hasClass('hideComments')) {
    hideComments($(this));
  }
  else {
    showComments($(this));
  }
}

function hideComments() {
  $('a.hideComments').addClass('showComments');
  $('a.hideComments').removeClass('hideComments');
  $('a.showComments').html('Kommentare und zusätzliche Informationen anzeigen');
  $('div.description').slideUp('10');
  $('li.lehrveranstaltung div.fill').slideUp('10');
  $('li.exam div.fill').slideUp('10');
  $('li.paper div.fill').slideUp('10');
  $('div#kost').addClass('view-collapsed');
  $('div#kost').removeClass('view-expanded');
}

function showComments() {
  $('a.showComments').addClass('hideComments');
  $('a.showComments').removeClass('showComments');
  $('a.hideComments').html('Kommentare und zusätzliche Informationen verbergen');
  $('li.lehrveranstaltung div.fill').slideDown('10');
  $('li.exam div.fill').slideDown('10');
  $('li.paper div.fill').slideDown('10');
  $('div.description').slideDown('10');
  $('div#kost').addClass('view-expanded');
  $('div#kost').removeClass('view-collapsed');
}

function initializeDefinitions() { //definitions in definitions.js
  var currentDefinition;
  var definitionRegex;
  
  $(definitions).each(function() {
    currentDefinition = this;
    definitionRegex = new RegExp('\\b' + RegExp.escape(currentDefinition[0]) + '\\b', 'g'); //nichts oder nichtA-z
    
    $('#content *:not(h2,h3,h4,h5,h6)')
    .contents()
    //test if node is textnode
    .filter(function() {
      return this.nodeType == 3;
    })
    //test if node contains definition
    .filter(function() {
      return this.nodeValue.indexOf(currentDefinition[0]) != -1;
    })
    .each(function() {
      if (currentDefinition[2] == '1') {
        $(this).replaceWith(this.nodeValue.replace(definitionRegex, '<abbr title="' + currentDefinition[1] + '">$&</abbr>'));
      }
      else if (currentDefinition[2] == '2') {
        $(this).replaceWith(this.nodeValue.replace(definitionRegex, '<accronym title="' + currentDefinition[1] + '">$&</accronym>'));
      }
      else if (currentDefinition[2] == '3') {
        $(this).replaceWith(this.nodeValue.replace(definitionRegex, '<span class="explanation" title="' + currentDefinition[1] + '">$&</span>'));
      }
    });
    
  });
}



//Skype-AddOn deaktivieren

function disableSkypeAddon() {
  window.setTimeout(function() {
    $('.skype_pnh_container').html('');
    $('.skype_pnh_print_container').removeClass('skype_pnh_print_container');
  }, 800);
}
