
// ===================================================================================
//  js_geber_lib
// ===================================================================================

var geber_lib_onloadFuncArray;

function geber_lib_addLoadEvent(func) 
{
    if (document.all)
    {
        try { attachEvent("onload", func); return;}
        catch (e) 
        { }
    }
    else
    {
        window.addEventListener("load", func, true);
        return;
    }


/*
   // special case for IE on Mac. Ignore all others
   var agt = navigator.userAgent.toLowerCase();
   if ((agt.indexOf("mac") < 0) || (agt.indexOf("opera") >= 0) || (agt.indexOf("msie") < 0))
   {

       window.onload = func;
       return;
   }
*/

  // initialise the onload handler
  if (geber_lib_onloadFuncArray == null)
  {
      geber_lib_onloadFuncArray = new Array();

      var oldonload = window.onload;
      window.onload = function() 
      {
          for (var funcIdx=0; funcIdx <  geber_lib_onloadFuncArray.length; funcIdx++)
               geber_lib_onloadFuncArray[funcIdx]();
      }
  }

  geber_lib_onloadFuncArray[geber_lib_onloadFuncArray.length] = func;
}




   // geber_lib_stripTags
   // ---------------------------------------------------------------------------------------------------------------------------------------------------------
   /**
    * stripps all the tags from the provided text
    */
    function geber_lib_stripTags(text)
    {
        if (!text || (typeof text != "string") || (text.length <= 0)) 
            return "";

        // strip off all javascript tags
        text = text.replace(/<script.*<\/script[^>]*>/, "");


        // strip off all stye tags
        text = text.replace(/<style.*<\/style[^>]*>/, "");

        // strip off all other tags
        text = text.replace(/<[^>]*>/, "");

        // strip off all invalid characters
        text = text.replace(/[-\w+|"'\.]/, "");

        return text;
    }


    function geber_lib_Numsort(a,b)
    { return a-b; }


function geber_lib_getQueryParameter(paramName)
{
       var query = window.location.search.toString();

       if (!query || (query.length <= 0)) 
           return "";

       if ((paramName == null) || (typeof(paramName) != "string") || (paramName.length <= 0))
         paramName = "q";

       query = query.match(new RegExp("^(.*[?&])?" + paramName + "=(.*)$"));
       if (!query) return "";

       query = query[2];
     
       // remove the trailing parameters that are not part of this queryparam
       var nextParamIdx = query.indexOf("&");
       while (nextParamIdx >= 0)
       {
           // this is no parameter delimiter in case "&amp;" has been found
           if ((query.length > (nextParamIdx+4)) && (query.substring(nextParamIdx, nextParamIdx+4).toLowerCase() == "&amp"))
               nextParamIdx = query.indexOf("&", nextParamIdx+4)
           else
           {
               query = query.substring(0, nextParamIdx);
               nextParamIdx = -1;
           }
       }

       // clean up the query string
       query = unescape(query);
       query = geber_lib_stripTags(query);
       query = query.replace(/[^-_:;,\w\/\.=]/, "");
       return query;
}


function geber_lib_writeDocument(htmlText)
{
    document.write(htmlText);
}


function print_setImg() {   
    var a = document.getElementById("mainbar");
    for(var i = 0; i < a.getElementsByTagName("img").length; i++) {
      if (document.formular.setImg[0].checked) 
        a.getElementsByTagName("img")[i].style.display="inline";
      if (document.formular.setImg[1].checked) 
        a.getElementsByTagName("img")[i].style.display="none";
    }
  }

function print_hideLinks() {
    // resize print window
    try {resizePrintPopUp();} catch(e) {}

    var mainbar = document.getElementById("mainbar");
    var docLinks = mainbar.getElementsByTagName("a");
    for (var i=0; i<docLinks.length; i++) {
      docLinks[i].href="#";
    }
  }




function onLoadSetBaseURLParameters(pagePath)
{

	  var siemensNixdorfBasePath = "http://www.wincor-nixdorf.com/static/finanzberichte/gb2005-2006";

    // *** set the sendthispage base URL to the proper URL of this page
    var sendthispageElem = document.getElementById("sendthispage");
    if (sendthispageElem && !window.location.protocol.match(/^File/i)) {
    	  var siemensNixdorfBasePathRegEx  = siemensNixdorfBasePath.replace(/\//g, "\\/");
        eval("sendthispageElem.href = sendthispageElem.href.replace(/" + siemensNixdorfBasePathRegEx + "[^&]*/, window.location.href);" );
    }


    // *** calculate base URL path of the page    
    var basePath = String(window.location.href);
    basePath = basePath.replace(/\.html?/, "");
    
    if (pagePath && (typeof(pagePath) == "string") && pagePath != "/") {
    	  pagePath = pagePath.replace(/^\s+/, "");
    	  pagePath = pagePath.replace(/\s+$/, "");
    	  pagePath = pagePath.replace(/\//g, "\\/")
        eval("basePath = basePath.replace(/" + pagePath + "/gi, \"\");");
    }
    
    // *** set the search parameter
    var searchPathParam = document.getElementById("searchBaseDir");
    if (searchPathParam && basePath && basePath.length > 0) {
    	  searchPathParam.value = basePath;
    }   
}


function onSubmitSearch(searchForm)
{

  if (window.location.href.match(/iedit.geber.at/))
    return;
    
  var w = 700;
  var h = 430;
  
  /* increase size because status bar is always visible on Windows XP */
  var Ergebnis = navigator.userAgent.match(/Windows NT ([5-9]).([0-9])/);
  if (navigator.userAgent.match(/ MSIE/) && Ergebnis && Ergebnis[2] && Ergebnis[1] && ((Ergebnis[2] >= 1) || (Ergebnis[2] > 5))) 
    h = h+10;

  // redirect target of the search form to it
  if (searchForm)
  {
      try {
          var targetWindowName = "searchresultpopup" + String(Math.round(Math.random()*99999));

          try { searchForm.target = targetWindowName; }
          catch (ex) {}

          if (searchForm.target.charAt(0) != "_")
          {
              var popUpWindow = window.open('', searchForm.target, 'resizable=yes, status=no, toolbar=no, scrollbars, width='+w+', height='+h);
              popUpWindow.resizeTo(w, h);
              popUpWindow.focus();
          }
      } catch (e) {}
  }

}

var operabar = (window.opera ? "=yes" : "");

function sendPopUp(newLocation) {
  var w = 570;
  var h = 540;
 	
  return PopUpOpenWindow(newLocation, 'popup', 'resizable=yes, status=no, toolbar=no, scrollbars' + operabar, w, h); 
}

function printPopUp(newLocation) {
  var w = 666;
  var h = 560;
  
  var operabar = "";
  if (window.opera) operabar = "=yes";
  
   return PopUpOpenWindow(newLocation, 'popup', 'resizable=yes, status=no, toolbar=no, scrollbars' + operabar, w, h); 
}

function resizePrintPopUp() {
  var w = 666;
  var h = 560;

  h = h + 15;
  if (opener)
      window.resizeTo(w, h);
}

function glossaryPopUp(newLocation) {
  var h = 350;
  var w = 500;
 
  return PopUpOpenWindow(newLocation, 'glossary', 'resizable=yes, status=no, toolbar=no, scrollbars' + operabar, w, h);
}


function tablePopUp(newLocation, preferedWidth) {

  var w = (preferedWidth && !isNaN(preferedWidth))? preferedWidth : 800;
  var h = 500;

  return PopUpOpenWindow(newLocation, 'tablePopUp', 'scrollbars,resizable=yes,location=no,status=no,toolbar=no,', w, h);
}

function imagePopUp(newLocation, w, h) 
{
  w += 15;
  h += 32;
   return PopUpOpenWindow(newLocation, 'imagePopUp', 'resizable=yes,location=no,status=no,toolbar=no,', w, h);
}

function PopUpOpenWindow(newLocation, name, specialFeatures, w, h)
{
  var popUpWindow;

  /* increase size because status bar is always visible on Windows XP */
  h = h + 15;


  try
  {
    popUpWindow = window.open(newLocation, name, specialFeatures, width='+w+', height='+h');
  }
  catch (e)
  {
    return false;
  }  
  
  try
  {
    popUpWindow.resizeTo(w, h);
  }
  catch (e) {}
  
  try
  {
    popUpWindow.focus();
  }
  catch (e) {}

  return true;

}

// ===================================================================================
//  js_highlightsearch
// ===================================================================================

var contentElementIDs = new Array('headerContent', 'searchTop5', 'bodyContent');
var contentElementNoHitMarkerID = new Array('searchNoHits');
var lastIDIfFound = "searchTop5";


/*
 * This is the function that actually highlights a text string by
 * adding HTML tags before and after all occurrences of the search
 * term. You can pass your own tags if you'd like, or if the
 * highlightStartTag or highlightEndTag parameters are omitted or
 * are empty strings then the default <font> tags will be used.
 */
function doHighlight(bodyText, searchTerm, highlightStartTag, highlightEndTag)
{
    // calc searchTerm length
    var searchTermLen = searchTerm.length ;

    // the highlightStartTag and highlightEndTag parameters are optional
    if ((!highlightStartTag) || (!highlightEndTag))
    {
        highlightStartTag = "<span class=\"se_hilite\">" ;
        highlightEndTag = "</span>" ;
    }

    // find all occurences of the search term in the given text,
    // and add some "highlight" tags to them (we're not using a
    // regular expression search, because we want to filter out
    // matches that occur within HTML tags and script blocks, so
    // we have to do a little extra validation)
    var newText = "";
    var i = -1;
    var lcSearchTerm = searchTerm.toLowerCase();
    var lcBodyText = bodyText.toLowerCase();

    while (bodyText.length > 0)
    {
        i = lcBodyText.indexOf(lcSearchTerm, i+1);

        if (i < 0)
        {
            newText += bodyText;
            bodyText = "";
        }
        else
        {
            // skip anything inside an HTML tag
            if (bodyText.lastIndexOf(">", i) >= bodyText.lastIndexOf("<", i))
            {
                // skip anything inside a <script> block
                if (lcBodyText.lastIndexOf("/script>", i) >=
                        lcBodyText.lastIndexOf("<script", i))
                {
                    newText += bodyText.substring(0, i) + highlightStartTag +
                        this.encode_umlauts(bodyText.substr(i, searchTermLen)) + highlightEndTag;
                    bodyText = bodyText.substr(i + searchTermLen);
                    lcBodyText = bodyText.toLowerCase();
                    i = -1;
                }
            }
        }
    }

   // return the result
   return newText ;
}

/*
 * This is sort of a wrapper function to the doHighlight function.
 * It takes the searchText that you pass, optionally splits it into
 * separate words, and transforms the text on the current web page.
 * Only the "searchText" parameter is required; all other parameters
 * are optional and can be omitted.
 */
function highlightSearchTerms(searchText, warnOnFailure, highlightStartTag,
                highlightEndTag)
{

   // if a no search hit marker exists, do not highlight anything
   if (contentElementNoHitMarkerID)
   {
       for (var k=0; k < contentElementNoHitMarkerID.length; k++)
       {
         if (document.getElementById(contentElementNoHitMarkerID[i])) return;
       }
   }

    var searchAndArray = new Array() ;
    var searchOrArray  = new Array() ;

    // validate search entry
    if (searchText == null || searchText == "")
    {
        searchText = window.location.search ;

        // get search entry
        searchText = this.get_search_entry(searchText) ;

        if (searchText != null && searchText != "")
        {
            // exact match
            var re = new RegExp("\%22(.*)\%22") ;
            var exact_match = searchText.match(re) ;

            if (exact_match != null && exact_match[1] != null)
            {
                exact_match = exact_match[1] ;

                // delete exact match string from search string
                searchText = searchText.replace(re, '') ;

                // replace '%20' chars with ' ' char
                re = new RegExp("\%20|\\+") ;
                re.global = true ;
                exact_match = exact_match.replace(re, ' ') ;
            }
            else { exact_match = "" ; }

            searchText     = this.strip_junk(searchText) ;
            searchAndArray = this.get_tokens(searchText, '+') ;
            searchOrArray  = this.get_tokens(searchText, '|') ;
        }
        else { return ; }
    }


    if (!document.body || typeof(document.body.innerHTML) == "undefined")
    {
        if (warnOnFailure)
        {
//            alert("Sorry, for some reason the text of this page is " +
//                "unavailable. Searching will not work.");
        }
        return false;
    }
    for (var k=0; k < contentElementIDs.length; k++)
    {
      var contentElem = document.getElementById(contentElementIDs[k]);

      if (contentElem && contentElem.innerHTML)
      {
        var bodyText = contentElem.innerHTML;


        // mark exact match
        if (exact_match != null && exact_match != "")
        {
            bodyText = this.doHighlight(bodyText, exact_match,
                        highlightStartTag, highlightEndTag);
        }

        // iterate through 'and' array
        for (var i = 0; i < searchAndArray.length; i++)
        {
            if (searchAndArray[i] && searchAndArray[i] != null && searchAndArray[i] != "")
            {
                bodyText = this.doHighlight(bodyText, searchAndArray[i],
                           highlightStartTag, highlightEndTag);
            }
        }

        // iterate through 'or' array
        for (var i = 0; i < searchOrArray.length; i++)
        {
            if (searchOrArray[i] && searchOrArray[i] != null && searchOrArray[i] != "")
            {
                bodyText = this.doHighlight(bodyText, searchOrArray[i],
                           highlightStartTag, highlightEndTag);
            }
        }

        contentElem.innerHTML = bodyText;

        if (lastIDIfFound && (lastIDIfFound == contentElementIDs[k])) break;
      }

    }
    return true;
}


/**
 * Deletes extra chars and formats a string in a valid search string.
 *
 * Abbr.: + - 'and', '-' - not, '|' - or
 *
 * Conversion rules:
 *  +- = -, -| = |, +| = |
 *
 * @param str - string to format
 */
function strip_junk(str)
{
    // validate param
    if (str && str != null && str != "")
    {
        str = unescape(str) ;

        // strip extra spaces
        var re = new RegExp("\\s+") ;
        re.global = true;
        str = str.replace(re, ' ') ;

        // strip quotes
//        var re = new RegExp("\"") ;
//        re.global = true;
//        str = str.replace(re, '') ;

        // delete repeated control chars
        re = new RegExp("\\++") ;   // delete repeated 'and' chars
        re.global = true;
        str = str.replace(re, '+') ;
        re = new RegExp(" --+") ;     // delete repeated 'not' chars
        re.global = true;
        str = str.replace(re, ' -') ;
        re = new RegExp("\\|+") ;   // delete repeated 'or' chars
        re.global = true;
        str = str.replace(re, '-') ;
        re = new RegExp("\\|+") ;   // delete repeated 'or' chars
        re.global = true;
        str = str.replace(re, '|') ;

        // replace spaces with '+' (i.e. 'and')
        re = new RegExp("\\s") ;
        re.global = true;
        str = str.replace(re, "+") ;

        // replace '+-" or '-+' through '-' (i.e. 'not')
        re = new RegExp("\\+-") ;
        re.global = true;
        str = str.replace(re, "!") ;
        re = new RegExp("-\\+") ;
        re.global = true;
        str = str.replace(re, "!") ;

        // replace '-|' or '|-' or '+|' or '|+' through '|' (i.e. 'or')
        re = new RegExp("-\\|") ;
        re.global = true;
        str = str.replace(re, "|") ;
        re = new RegExp("\\|-") ;
        re.global = true;
        str = str.replace(re, "|") ;
        re = new RegExp("\\+\\|") ;
        re.global = true;
        str = str.replace(re, "|") ;
        re = new RegExp("\\|\\+") ;
        re.global = true;
        str = str.replace(re, "|") ;

        // strip off non alpha chars
        re = new RegExp("[^a-zA-Z0-9-ÜÖÄüöäß\\s\\+]") ;
        re.global = true ;

	// fucking javascript
        while (str.match(re))
        {
            str = str.replace(re, "") ;
        }


        // add '+' for easy parsing
        str = '+' + str ;
    }

    // well, I hope it is what u want :)
    return str ;
}


/**
 * Returns all 'and' tokens found in a provided string
 * e.g. 'Hello+Servus-Ciao|Welcome' the function will return the following
 * tokens: 'Hello' and 'Servus'
 *
 * @param str     - string to process
 * @param divider - string distinguishing divider
 */
function get_tokens(str, divider)
{
    // array with 'and' tokens
    var tokens = new Array() ;


    // validate param
    if (str != null || str != "")
    {
        // otherwise, it sucks
        str += "\n" ;

        var re = new RegExp("\\" + divider + "([a-zA-Z0-9-ÜÖÄüöäß]*)") ;
        re.global = true;

        var i = 0 ;

        while (matched_str = str.match(re))
        {
            // delete token
            var reg = new RegExp("\\" + divider + "([a-zA-Z0-9-ÜÖÄüöäß]*)") ;

            // delete token
            str = str.replace(reg, "") ;
            tokens[i++] = matched_str[1] ;

            // safety procedure in order to avoid eternal loop
            if (i > 10) { break ; }
        }
    }
    return tokens ;
}


/**
 * Parses URI and returns back only search entry
 */
function get_search_entry(search_entry, search_token)
{
    // return var = only search entry
    // e.g.: search_entry == '?q=Hello' returns only 'Hello'
    var result = "" ;


    // validate search_token
    if (search_token == null || search_token == '')
    {
        search_token = 'q' ;
    }

    // validate params
    if (search_entry != null && search_entry != "" && search_entry.charAt(0) == '?')
    {
        var re = new RegExp("(\\?|&)" + search_token + "=([^&]+)") ;

        // validate search_entry
        if (regexResult = search_entry.match(re))
        {
            result = regexResult[2];

            // get rid off additional params
            re = new RegExp("&.*") ;
            re.global = true ;
            result = result.replace(re, '') ;

            // get normal space char
            re = new RegExp("\\+") ;
            re.global = true ;
            result = result.replace(re, " ") ;

            // oe
            re = new RegExp("%F6") ;
            re.global = true ;
            result = result.replace(re, "ö") ;

            // OE
            re = new RegExp("%D6") ;
            re.global = true ;
            result = result.replace(re, "Ö") ;

            // ae
            re = new RegExp("%E4") ;
            re.global = true ;
            result = result.replace(re, "ä") ;

            // AE
            re = new RegExp("%C4") ;
            re.global = true ;
            result = result.replace(re, "Ä") ;

            // ue
            re = new RegExp("%FC") ;
            re.global = true ;
            result = result.replace(re, "ü") ;

            // UE
            re = new RegExp("%DC") ;
            re.global = true ;
            result = result.replace(re, "Ü") ;

            // ss
            re = new RegExp("%DF") ;
            re.global = true ;
            result = result.replace(re, "ß") ;
        }
    }

    return result ;
}

function doHighlightSearchTerms()
{
   highlightSearchTerms();
}

/**
 * Encode umlauts
 */
function encode_umlauts(str)
{
    if (str && str != "")
    {
        // oe
        var re = new RegExp("ö") ;
        re.global = true ;
        re.multiline = true ;
        str = str.replace(re, "ö") ;

        // OE
        re = new RegExp("Ö") ;
        re.global = true ;
        re.multiline = true ;
        str = str.replace(re, "Ö") ;

        // ae
        re = new RegExp("ä") ;
        re.global = true ;
        re.multiline = true ;
        str = str.replace(re, "ä") ;

        // AE
        re = new RegExp("Ä") ;
        re.global = true ;
        re.multiline = true ;
        str = str.replace(re, "Ä") ;

        // ue
        re = new RegExp("ü") ;
        re.global = true ;
        re.multiline = true ;
        str = str.replace(re, "ü") ;

        // UE
        re = new RegExp("Ü") ;
        re.global = true ;
        re.multiline = true ;
        str = str.replace(re, "Ü") ;

        // ss
        re = new RegExp("ß") ;
        re.global = true ;
        re.multiline = true ;
        str = str.replace(re, "ß") ;
    }

    return str ;
}


// -----------------------------------------------------------------------------------------------
// statistics
// -----------------------------------------------------------------------------------------------

function geber_preLoadGWSImage(simple)
{
    var pageURL = escape(window.location);

    var donotgws = pageURL;
    var Ergebnis = donotgws.search(/laut.iedit.geber.at./);
    if (Ergebnis != -1)
          return;


    var referrer = document["referrer"]==null?'':escape(document.referrer);
    var imageURL = "http://gws.geber.at/wincor/gws.gif?ref=" +
                  referrer + "&pg=" + pageURL;

    imageURL += "&screen=" + screen.width + "x" + screen.height;
    var myImg = new Image();
    myImg.src = imageURL;
}

function geber_perfomOnLoad()
{
   try {
       doHighlightSearchTerms();
   } catch (e) {}
   try {
      // for the glossary popups
      tt_RegisterEventHandlers();
   } catch (e) {}
}

geber_lib_addLoadEvent(geber_perfomOnLoad);

