/* Use Object Detection to detect IE6 */
var ie6 = document.uniqueID      /*IE*/
       && document.compatMode    /*>=IE6*/ 
       && !window.XMLHttpRequest /*<=IE6*/
       && document.execCommand;
try {
  if(!!ie6) {
    ie6("BackgroundImageCache", false, true) /* = IE6 only */
  }
} catch(e) {};


// First active history item: Default text
var activeHistoryItem = 'history-default';

// Active item in continent list
var activeContinent = null;
var activeContinentHotspot = null;

if (loginGuid == "") {
    // Load ULI on every page
    window.onload = function() { showLine() };
}

/**
 * IE save function to get all nodes with a given name
 *
 * @param name, String, value of the name attribute to be found
 * @param tagName, String, tagName of the used element
 *
 * @return Array, found elements
 *
 */
function getElementsByName(name, tagName)
{
  var a = new Array();
  for(i = 0; i < document.getElementsByTagName(tagName).length; i++)
  {
    if(document.getElementsByTagName(tagName)[i].getAttribute('name') == name)
      a.push(document.getElementsByTagName(tagName)[i]);
  }
  return a;
}

function openPrintView(fileName)
{
  window.open(fileName,'Printview');
}

function openPrintDialog()
{
  window.print();
}

/**
 * toggles visibility of metaNavigation elements, also changes headline to
 * display an open/close arrow
 *
 * @param index, int, # of the element to toggle
 * @param name, String, name attribute value of all elements to toggle
 * @param tag, String, tagName of all elements to toggle
 * @param classOpen, String, name of the class for open state
 * @param classClosed, String, name of the class for closed state
 *
 */
function toggle(index, name, tag, classOpen, classClosed)
{
  var elements = getElementsByName(name,tag);

  if(elements[index].className == classClosed)
  {
    //close all elements of given type
    for(var i=0; i<elements.length; i++)
    {
        elements[i].className = classClosed;
    }

    //open the selected element
    elements[index].className = classOpen;
  } else {
    //close only the selected element
    elements[index].className = classClosed;
  }
  
if(loginGuid == "") {
  saveSetting(name,index);
} 

  return false;
}

/**
 * Returns the value of a GET parameter
 * Example: bar = getUrlParameter('foo')
 *
 * @author  http://www.netlobo.com
 */
function getUrlParameter(name)
{
  var regexS  = "[\\?&]"+name+"=([^&#]*)";
  var regex   = new RegExp( regexS );
  var tmpURL  = (arguments.length == 2) ? arguments[1] : window.location.href;
  var results = regex.exec( tmpURL );
  return (results == null) ? '' : results[1];
}

/**
 * Open a URL in a PopUp Window
 *
 * @author Markus Küfner
 */
function openWindow(url, width, height, windowName)
{
   w = window.open(url, windowName, "width="+width+",height="+height+",status=no,scrollbars=no,resizable=yes");
   w.focus();
}


/**
 * Attaches the name of the active continent to the 'Back to Overview' link
 *
 * @param  activeContinent  Name of the currently active continent DIV
 */
function setBackLink(activeContinent)
{
  if (document.getElementById('back2OverviewBarTop') == null) return;
  var backLink = document.getElementById('back2OverviewBarTop').href;
  if (getUrlParameter('continent', backLink) != null)
  {
    backLink = backLink.replace(/continent=([^&#]*)/, 'continent=' + activeContinent);
  } else {
    backLink += (backLink.lastIndexOf('?') == -1) ? '?' : '&amp;';
    backLink += 'continent=' + activeContinent;
  }
}       


/**
 * Toggles visibility for address overview
 *
 * @param  continentId  Id of the DIV to be toggled
 */
function showContinent(continentId, continentHotspot)
{
  if (activeContinent != null) document.getElementById(activeContinent).style.display = 'none';
  if (activeContinentHotspot != null) activeContinentHotspot.className = '';

  document.getElementById(continentId).style.display = 'block';
  continentHotspot.className = 'activeHotspot';

  // setBackLink(continentId);
  activeContinent = continentId;
  activeContinentHotspot = continentHotspot;
}


/**
 * Shows a history page item and hides any previously visible history item
 * 
 * @param itemId  Id of the history item container (e.g. history1)
 */   
function showHistoryItem(itemId)
{
  if (document.getElementById(itemId))
  {
    // hide current history item if item is set
    if (activeHistoryItem != null)
    {
      if (document.getElementById(activeHistoryItem)) document.getElementById(activeHistoryItem).display = 'none';
    }

    // show new history item
    document.getElementById(itemId).display = 'block';
    activeHistoryItem = itemId;
  }
}

/**
 * Jumps to an url passed though a dropdown
 *
 * Example: <select onchange="jumpToDropdownLink(this)">
 * @param dropdownItem  referrer to the select-object
 */
function jumpToDropdownLink(dropdownItem)
{
  var url = dropdownItem.options[dropdownItem.options.selectedIndex].value;
  if (url != '#' && url != undefined) window.location.href = url;
}

/**
 * Set the form action url to an url passed though a dropdown
 *
 * Example: <select onchange="changeFormActionToDropdownLink(this)">
 * @param dropdownItem  referrer to the select-object
 */
function changeFormActionToDropdownLink(dropdownItem)
{
  var url = dropdownItem.options[dropdownItem.options.selectedIndex].value;
  if (url != '#' && url != undefined)
  {
    dropdownItem.form.action = url;
  }
}


/**
 * PROTOTYPE: Removes white spaces at the beginnning and end of a string
 */
String.prototype.trim = function () {
  return (this.replace(/\s+$/,"").replace(/^\s+/,""));
};
    

/**
 * PROTOTYPE: Removes duplicates in an array
 */
Array.prototype.unique = function()
{
  for (var i = 0; i < this.length; i++)
  {
    for (var j = (i + 1); j <= this.length; j++) if (this[i] === this[j]) this.splice(j, 1);
  }
};


/**
 * Extracts filter categories from a string
 * i.e. REDDOT_PAGE_GUID.category1.subcategory1;REDDOT_PAGE_GUID.category1.subcategory2; ...
 *
 * @param  categoryString      string containing category information
 * @return array               category names
 */  
function getCategories(categoryString) 
{
  categoryString = categoryString.trim();
  
  // Replace multiple occasions of divider chars (just to be sure)
  categoryString.replace(/;+/g, ';');
  categoryString.replace(/\.+/g, '.');
  
  categoryString = categoryString.slice(0, categoryString.length-1);

  var tmpCategoryArray = categoryString.split(';');
  var categoryArray = new Array();
    
  for (var i=0; i<tmpCategoryArray.length; i++)
  {
    var tmpSubcategoryArray = tmpCategoryArray[i].split('.');
        
    // Ignore the first part of the string, it's the RedDot page GUID.            
    if (tmpSubcategoryArray.length > 1) categoryArray.push(tmpSubcategoryArray[1]);
  }
  categoryArray.sort();
  categoryArray.unique();
  return categoryArray;
}


/**
 * Fills the category dropdown. Only for use in RedDot SmartEdit!
 *
 * @param  dropdownId      Id of the html select-tag to be filled
 * @param  categoryString  String containing the category information
 */
function fillReddotCategoryDropdown(dropdownId, categoryString)
{
  var categories = new Array();
  categories = getCategories(categoryString);
  categories.unique();

  // Only start the filling if select-tag was found
  if (document.getElementById(dropdownId))
  {
    for (var i=0; i<categories.length; i++)
    {
      var newDropdownOption = new Option(categories[i], '', false, false);
      document.getElementById(dropdownId).options[document.getElementById(dropdownId).length] = newDropdownOption;
    }
  }
}


/**
 * Add and remove classnames
 *
 * @author www.hesido.com
 */
function changeClass(elem, addClass, remClass)
{
  if (!elem.className) elem.className = '';
  var clsnm = elem.className;
  if (addClass && !clsnm.match(RegExp("\\b"+addClass+"\\b"))) clsnm = clsnm.replace(/(\S$)/,'$1 ')+addClass;
  if (remClass) clsnm = clsnm.replace(RegExp("(\\s*\\b"+remClass+"\\b(\\s*))*","g"),'$2');
  elem.className=clsnm;
}


/**
 * Returns all elements with a certain class name
 *
 * @param  tagName    Tag names to search (use '*' as wildcard)
 * @param  className  Class name to seach
 * @return Array with elements or NULL
 */
function getElementsByClassName(tagName, className)
{
  var allElements = document.getElementsByTagName(tagName);
  var returnElements = new Array();
  var searchTerm = new RegExp("\\b" + className + "\\b");
    
  for (var i=0; i<allElements.length; i++)
  {
    if (allElements[i].className.match(searchTerm)) returnElements.push(allElements[i]);
  }
    
  return (returnElements.length > 0) ? returnElements : null;
}


/**
 * Inits the mouseover effect for teaser navigation elements
 */
function initTeaserNavigation()
{
  var teaserNav = getElementsByClassName('td', 'teaserText');
  if (teaserNav != null)
  {
    for (var i=0; i<teaserNav.length; i++)
    {
      teaserNav[i].onmouseover = function () { 
    //  changeClass(this, 'teaserTextHover', 'teaserText'); alert(this.className); return false;  
            switch (this.className) {
              case "teaserText textLeft":
                this.className ="teaserText teaserTextLeftHover";
                break;
              case "teaserText textRight":
                this.className = 'teaserText teaserTextRightHover';
                break;
              case "teaserText text":
                this.className = 'teaserText teaserTextHover';
                break;
            }
      }

      teaserNav[i].onmouseout  = function () {
    // changeClass(this, 'teaserText', 'teaserTextHover'); return false;
            switch (this.className) {
              case "teaserText teaserTextLeftHover":
                this.className ="teaserText textLeft";
                break;
              case "teaserText teaserTextRightHover":
                this.className = 'teaserText textRight';
                break;
              case "teaserText teaserTextHover":
                this.className = 'teaserText text';
                break;
            }
      }
   }
}
}

/**
 * Removes href attribute from empty 72dpi/300dpi image links
 *
 * @param  imageLink  a-tag of the image link
 */
function removeEmptyImageLink(imageLink)
{
  if (imageLink.href && imageLink.href.lastIndexOf('/') == imageLink.href.length-1) imageLink.removeAttribute('href');
}


/**
 * Returns all elements with a certain class name
 *
 * @param  className  Class name to seach
 * @param  tagName    Tag names to search (use '*' as wildcard)
 * @return Array with elements or NULL
 */
document.getElementsByClassName = function (className, tagName)
{
  var allElements = document.getElementsByTagName(tagName);
  var returnElements = new Array();
  var searchTerm = new RegExp("\\b" + className + "\\b");
    
  for (var i=0; i<allElements.length; i++)
  {
    if (allElements[i].className.match(searchTerm)) returnElements.push(allElements[i]);
  }
    
  return (returnElements.length > 0) ? returnElements : null;
}


/**
 * Displays the ULI between the top level navigation and subnavigation
 */
function showLine()
{
  var header = document.getElementById("header");
  var mainNav = document.getElementById("mainNavigation");
  var leftNav = document.getElementById("leftNavigation");

  // Exit if the left navigation is empty
  if (leftNav.getElementsByTagName("a").length == 0) return false;

  // Calculate the height of the upper part
  try
  {
    for(i = 0; (mainNav.getElementsByTagName("li")[i].className != "active") && (i < mainNav.getElementsByTagName("li").length);i++) {}
  } catch(e) {
    return false;
  }
  var curNav = mainNav.getElementsByTagName("li")[i];
  var topLineHeight = header.offsetHeight - curNav.parentNode.offsetTop - curNav.offsetTop - (curNav.offsetHeight/2);

  var topLine = document.createElement("div");
  topLine.id = 'navigationLine';
  topLine.style.height = topLineHeight + 'px'; //document.getElementById("header").clientHeight;
  header.appendChild(topLine);

  // Create the upper part
  var bottomLine = document.createElement("div");
  bottomLine.id = 'navigationLineBottom';
  bottomLine.style.top = header.offsetHeight + 'px';

  // Create the lower part
  var leftNavHeadline = leftNav.getElementsByTagName("h1")[0];
  bottomLineHeight = leftNav.offsetTop - header.offsetHeight + (leftNavHeadline.offsetHeight/2);
  bottomLine.style.height = bottomLineHeight + 'px'; //document.getElementById("header").clientHeight;
  document.body.appendChild(bottomLine);
}


/**
 * Inits the selection information for the country selection in Form Editor
 * @author  EuKr
 */
function showInformation(infoId, countryDescription, selectedEntry) {
  document.getElementById(infoId).style.display = (countryDescription == selectedEntry) ? 'block' : 'none';
}


/**
 * Fill dropdowns of FastTrack Navigation with content of hidden DIVs
 */
function fillFasttrackDropdowns() {
  var linkArrayProduct = document.getElementById("LinkArrayProduct");
  var dropdownProduct  = document.getElementById("ProductBrandDropdown");    
  if (linkArrayProduct && dropdownProduct) 
  {
    for (var i=0; i < linkArrayProduct.childNodes.length; i++)
    {
      dropdownProduct.options[i+1] = new Option(linkArrayProduct.childNodes[i].innerHTML.replace(/&amp;/g, "&"), linkArrayProduct.childNodes[i].getAttribute('href'), false, false);
    }
    dropdownProduct.selectedIndex = 0;
  }    
    
  var linkArrayTopic = document.getElementById("LinkArrayTopic");
  var dropdownTopic  = document.getElementById("TopicDropdown");  
  if (linkArrayTopic && dropdownTopic)
  {
    for (var i=0; i < linkArrayTopic.childNodes.length; i++)
    {
      dropdownTopic.options[i+1] = new Option(linkArrayTopic.childNodes[i].innerHTML.replace(/&amp;/g, "&"), linkArrayTopic.childNodes[i].getAttribute('href'), false, false);
    }
    dropdownTopic.selectedIndex = 0;
  }

  var linkArrayWebsiteSelector = document.getElementById("LinkArrayWebsiteSelector");
  var dropdownWebsiteSelector  = document.getElementById("WebsiteSelectorDropdown");    
  if (linkArrayWebsiteSelector && dropdownWebsiteSelector) 
  {
    for (var i=0; i < linkArrayWebsiteSelector.childNodes.length; i++)
    {
      dropdownWebsiteSelector.options[i+1] = new Option(linkArrayWebsiteSelector.childNodes[i].innerHTML.replace(/&amp;/g, "&"), linkArrayWebsiteSelector.childNodes[i].getAttribute('href'), false, false);
    }
    dropdownWebsiteSelector.selectedIndex = 0;
  }

}
 
/**
 * eTracker WPC Implementation
 * @author  GeCa
 */
function removeMultipleSpacesAndTrim(str) {
    return str.replace(/\s+/g, " ").replace (/^\s+/, '').replace (/\s+$/, '');
}
var WPC_Information = false;
function edorasGetWebsitemainContent()
{
    var mainContent = "";
    try {
      mainContent = $("#mainContent h1:first").text();
      mainContent = "_Hybris_" + removeMultipleSpacesAndTrim(mainContent);
    } catch(e) { }
    return mainContent;
}

/*
 * VideoPlayer 
 * @author MaRi
 */        
$.buildPlayer = function(options) {
    //#### Variablen
    this.set = jQuery.extend({
            id:"videoplayerli",
            height: 226,
            width: 367,
            allowfullscreen: "true",
            allowscriptaccess: "always",
            file: "",
            player: '/us/content_data/player.swf'
    }, options);
    this.object = $("#"+this.set.id);
    this.fallbackcontent = this.object.html();
    
    //Create the Player in Container
    this.createPlayer = function() {
        var player = new SWFObject(this.set.player,'ply'+this.set.id,this.set.width,this.set.height,'9');
        player.addParam('allowfullscreen',this.set.allowfullscreen);
        player.addParam('allowscriptaccess',this.set.allowscriptaccess);
        player.addParam('flashvars','file='+this.set.file);
        player.write(this.set.id);
    };
    
    //Remove any Player in Container
    this.removePlayer = function() {
        if(this.object != null) {
            this.object.empty();
            this.object.append(this.fallbackcontent);
        }
    };
    //Clear Container
    this.removePlayer();
    //Create Player
    this.createPlayer();
};
 

/* PHMU temporary industrial popup */
function openindustrialpopup(url) {
 fenster = window.open(url, "fenster1", "width=450,height=400,status=yes,scrollbars=yes,resizable=yes");
 fenster.focus();
}
 

/**
 * @projectDescription
 * 
 * jCookie provides an convenient api for CRUD-related cookie handling.
 * 
 * @example:
 *  Create,update:
 *  jQuery.jCookie('cookie','value');
 *  Delete:
 *  jQuery.jCookie('cookie',null);
 *  Read:
 *  jQuery.jCookie('cookie');
 * 
 * Copyright (c) 2008-2010 Martin Krause (jquery.public.mkrause.info)
 * Dual licensed under the MIT and GPL licenses.
 *
 * @author Martin Krause public@mkrause.info
 * @copyright Martin Krause (jquery.public.mkrause.info)
 * @license MIT http://www.opensource.org/licenses/mit-license.php
 * @license GNU http://www.gnu.org/licenses/gpl-3.0.html
 * 
 */
// start plugin closure
/**
 * 
 * @param {String} sCookieName_, the cookie name
 * @param {Object} [oValue_], the cokie value
 * @param {String, Number} [oExpires_], the expire date as string ('session') or number 
 * @param {Object} [oOptions_], additionale cookie options { path: {String}, domain: {String}, secure {Bool} } 
 */
jQuery.jCookie = function(sCookieName_, oValue_, oExpires_, oOptions_) {
    
    // cookies disabled
    if (!navigator.cookieEnabled) { return false; }
    
    // enfoce params, even if just an object has been passed
    var oOptions_ = oOptions_ || {};
    if (typeof(arguments[0]) !== 'string' && arguments.length === 1) {
        oOptions_ = arguments[0];
        sCookieName_ = oOptions_.name;
        oValue_ = oOptions_.value;
        oExpires_ = oOptions_.expires;
    }
    
    // escape characters
    sCookieName_ = encodeURI(sCookieName_);
    
    // basic error handling 
    if (oValue_ && (typeof(oValue_) !== 'number' && typeof(oValue_) !== 'string' && oValue_ !== null)) { return false; }
    
    // force values 
    var _sPath = oOptions_.path ? "; path=" + oOptions_.path : "";
    var _sDomain = oOptions_.domain ? "; domain=" + oOptions_.domain : "";
    var _sSecure = oOptions_.secure ? "; secure" : "";
    var sExpires_ = "";
    
    // write ('n delete ) cookie even in case the value === null 
    if (oValue_ || (oValue_ === null && arguments.length == 2)) {
    
        // set preceding expire date in case: expires === null, or the arguments have been (STRING,NULL)  
        oExpires_ = (oExpires_ === null || (oValue_ === null && arguments.length == 2)) ? -1 : oExpires_;
        
        // calculate date in case it's no session cookie (expires missing or expires equals 'session' )
        if (typeof(oExpires_) === 'number' && oExpires_ != 'session' && oExpires_ !== undefined) {
            var _date = new Date();
            _date.setTime(_date.getTime() + (oExpires_ * 24 * 60 * 60 * 1000));
            sExpires_ = ["; expires=", _date.toGMTString()].join("");
        }
        // write cookie
        document.cookie = [sCookieName_, "=", encodeURI(oValue_), sExpires_, _sDomain, _sPath, _sSecure].join("");
        
        return true;
    }
    
    // read cookie 
    if (!oValue_ && typeof(arguments[0]) === 'string' && arguments.length == 1 && document.cookie && document.cookie.length) {
        // get the single cookies 
        var _aCookies = document.cookie.split(';');
        var _iLenght = _aCookies.length;
        // parse cookies
        while (_iLenght--) {
            var _aCurrrent = _aCookies[_iLenght].split("=");
            // find the requested one 
            if (jQuery.trim(_aCurrrent[0]) === sCookieName_) { return decodeURI(_aCurrrent[1]); }
        }
    }
    
    return false;
};