/* 
    Copyright 2004 - 2011 DB Systel GmbH
*/

      /******************************************************************************************************************
 * functions for highlighting the searchwords on a page
 *****************************************************************************************************************/
// global switch. pages can set this to false, if they don't want their text to be
// highlighted.
var doHighlight = true;
//
function highlightSearchWords(){
    var words = extractSearchWords();

          if (words == null || words.length == 0) {
        return;
    }

        
    var node = document.getElementById("col3_content");

        
    for (var i = 0; i <= words.length; i++) {
        highlightWords(node, words[i], i);
    }
}

      // extract the search words from the referrer
function extractSearchWords() {
    var words = new Array();
    var ref = document.referrer;
    var loc = document.location.href;

        
    if (loc.indexOf('q') > 0) {
        return;
    }

        
    if (ref == null || ref == "") {
        return;
    }

        
    if (ref.indexOf('?') == -1) {
        return;
    }

          if (loc.indexOf('?s=') > 0) {
        return;
    }

          if (loc.indexOf('?view=') > 0) {
        return;
    }
/*
        if (loc.indexOf('type=searchResult') == -1)  {
            return;
        }
*/
    var query = ref.substr(ref.indexOf('?') + 1);
    var params = query.split('&');

        
    for (var i=0; i < params.length; i++) {
        if (params[i].indexOf("q=") > -1) {
            words = words.concat(params[i].substr(params[i].indexOf('=')+1).split('+'));
        }
    }

        
    for (var i=0; i < words.length; i++) {
        words[i] = decodeURIComponent(words[i].toLowerCase());
    }

        
    return words;
}

      function highlightWords(node, word, numColor) {
    // some guards
    if (word == null || word.length == 0) {
        return;
    }

        
    if (node == null) {
        return;
    }

          if (node.className == "dlBox") {
        return;
    }

          // there are only 10 colors in our stylesheet.
    numColor = numColor % 10;

        
    // iterate through all child nodes
    if (node.hasChildNodes()) {
        var nodeNum;

        
        for (nodeNum = 0; nodeNum < node.childNodes.length; nodeNum++) {
            var childNode = node.childNodes[nodeNum];
            var className = childNode.className;

        
            if (className == null || className.indexOf("searchword") == -1) {
                highlightWords(childNode, word, numColor);
            }
        }
    }

          // if a text node contains the search word, split it in three nodes:
    // - text node with text up to the word
    // - <span> with the word
    // - text node with text after the word
    if (node.nodeType == 3) { // only for text nodes
        if (node.nodeValue != null && node.nodeValue.length != 0) {
            var result  = matchWord(node.nodeValue, word);
            if (result != null && result.length != 0) {
                var index = node.nodeValue.toLowerCase().indexOf(result.toLowerCase());

        
                if (index != -1) {
                    nodeText = node.nodeValue;
                    before = document.createTextNode(nodeText.substr(0, index));
                    wordNode = nodeText.substr(index, result.length);
                    after = document.createTextNode(nodeText.substr(index + result.length));

                          wordNode = document.createElement("strong");
                    wordNode.className = "searchword" + numColor;
                    wordNode.appendChild(document.createTextNode(nodeText.substr(index, result.length)));

        
                    parentNode = node.parentNode;
                    parentNode.insertBefore(before, node);
                    parentNode.insertBefore(wordNode, node);
                    parentNode.insertBefore(after, node); 
                    parentNode.removeChild(node);
                }
            }
        }
    }
}

      function matchWord(text, word) {
    // convert all predefined search wild-cards of the variable 'word' to a regular expression...
    var expression = word;

          // first of all, clean up the search string
    expression = cleanUpSearchString(expression);

          // after that, convert it to a regexp
    expression = expression.replace(/\*/gi, "[^\\s]*");
    expression = expression.replace(/\?/gi, "[^\\s]");
    expression = expression.replace(/~/gi, "");
    expression = "(" + expression + ")";

          // now, match the expression...
    var search = new RegExp(expression, 'gi');
    search.exec(text);

          var result = RegExp.$1;

          return result;
}

      function cleanUpSearchString(expression) {
    expression = expression.replace(/\./gi, "");
    expression = expression.replace(/\$/gi, "");
    expression = expression.replace(/\\/gi, "");
    expression = expression.replace(/\^/gi, "");
    expression = expression.replace(/\+/gi, "");

        
    return expression;
}

      /******************************************************************************************************************
 *  Functions for resetting of forms
 * @requires jQuery - tested with 1.4.2 
 *****************************************************************************************************************/

        
function resetForm() {
    // The identifier for an radio box attribute to set it selected or unselected
    var targetAttributeRadioCheck = "checked";
    // The type identifier for a radio box
    var targetRadioIdentifier = "radio";
    // The type identifier for a check box
    var targetCheckBoxIdentifier = "checkbox";
    // The group name to hold; like "interessensgebiete" or "medientypen"
    var groupName = '';
    // The group value; like "Herr" or "Frau"
    var groupValue = '';
    // The control for which to set the default value
    var targetControl = '';
    var formId = document.getElementById('formId').value;

        
    // iterate over each element within the input settings hidden divs
    $.each($("#defaultSettings :input"), function(i, defaultControl) {
        // if the name does not contain ":", then go the normale way for a usual textbox
        if(defaultControl.name.indexOf(':') == -1) {
            //set the default value into textbox, identified by its name;
            $('#' + formId + ' :input[name='+ defaultControl.name +']').attr('value', defaultControl.value);
        } else {
            // Split up to get the category (e.g. "newsletter") and the precise element (print, tv, new media)
            groupName = defaultControl.name.split(':')[0];
            groupValue = defaultControl.name.split(':')[1];

                  // Get the targetControl for which to set the default values
            targetControl = $('#' + formId + ' :input[name='+ groupName +'][value=' + groupValue + ']');

        
            if (defaultControl.value == 1) {
                // if its a radio box or check box, set the default value
                if (targetControl.attr('type') == targetRadioIdentifier || targetControl.attr('type') == targetCheckBoxIdentifier) {
                    targetControl.attr(targetAttributeRadioCheck, defaultControl.value);
                } else {
                    // drop down are handled slightly different...
                    $("select[name=" + groupName + "]").val(groupValue);
                }
            } else if(defaultControl.value == 0) {
                // clear the other, previous selections
                if (targetControl.attr('type') == targetRadioIdentifier || targetControl.attr('type') == targetCheckBoxIdentifier) {
                    targetControl.removeAttr(targetAttributeRadioCheck);
                }
            }
        }
    });
}

      /******************************************************************************************************************
 *  Functions for handling of overlays without using shadowbox
 * @requires jQuery - tested with 1.4.2
 *****************************************************************************************************************/

      var close_loe = function(id) {
    jQuery('#'+id).hide();
    jQuery('.overlayBG').hide();
}

      var show_loe = function(id) {
    jQuery('#'+id).show();
    jQuery('.overlayBG').show();
}

      var update_loe = function() {
    jQuery('.overlayBG').height(jQuery(window).height());
    jQuery('.overlayBG').width(jQuery(window).width());
}

      var open_loe = function(id, posX, posY, width, height, src) {    
    if (!jQuery('.overlayBG').length) {
        jQuery('body').append('<div style="width:' +
                               jQuery(window).width() +
                               'px;height:' + 
                               jQuery(window).height() +
                               'px;" class="overlayBG opacity65"></div>');
        jQuery(window).resize(update_loe);
    }

          if (!src) {
        jQuery('#'+id).css({
            top:posY+"px",
            left:posX+"px"
        });

        
        if (height) {
            jQuery('#'+id).css({
                height:height+"px"
            });
        }

              if (width) {
            jQuery('#'+id).css({
                width:width+"px"
            });
        }

              show_loe(id);
    } else {
        if (jQuery('#'+id) && jQuery('#'+id).length > 0) {
            jQuery('#'+id).html('<iframe width="' +
                                width +
                                '" height="' +
                                height +
                                '" src="' +
                                src +
                                '" frameborder="0" scrolling="no" marginwidth="0" marginheight="0"></iframe><div class="closeOverlay"><a class="close" href="javascript://">&nbsp;</a></div>');
            show_loe(id);
        } else {
            jQuery('body').append('<div id="' + 
                                  id + 
                                  '" class="overlayContent" style="top:' +
                                  posY +
                                  'px;left:' +
                                  posX +
                                  'px;"><iframe width="' + 
                                  width +
                                  '" height="' +
                                  height + 
                                  '" src="' + 
                                  src + 
                                  '" frameborder="0" scrolling="no" marginwidth="0" marginheight="0"></iframe><div class="closeOverlay"><a class="close" href="javascript://">&nbsp;</a></div></div>');
            show_loe(id);
        }
    }

        
    jQuery('.overlayBG').click(function() {
        close_loe(id);
    });

        
    jQuery('.closeOverlay').click(function(){
        close_loe(id);
    });
}

      /******************************************************************************************************************
 *  Functions for handling cookies
 *  Based on code examples from http://www.quirksmode.org/js/cookies.html
 *****************************************************************************************************************/

      function checkCookie(pContentID, pPosX, pPosY, pWidth, pHeight, pDuration) {
    if (readCookie('loe_' + pContentID) == null) {
        createCookie('loe_' + pContentID, 1, pDuration);
        open_loe('loe_' + pContentID + '_0', pPosX, pPosY, pWidth, pHeight);

        
        return false;
    }
}

      function createCookie(pName, pValue, pDays) {
    if (pDays) {
        var date = new Date();
        date.setTime(date.getTime() + (pDays * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    } else {
        var expires = "";
    }

          document.cookie = pName + "=" + pValue + expires + "; path=/";
}

      function readCookie(pName) {
    var nameEQ = pName + "=";
    var ca = document.cookie.split(';');

        
    for (var i=0; i < ca.length; i++) {
        var c = ca[i];

        
        while (c.charAt(0)==' ') {
            c = c.substring(1, c.length);
        }

        
        if (c.indexOf(nameEQ) == 0) {
            return c.substring(nameEQ.length, c.length);
        }
    }

        
    return null;
}

      function eraseCookie(pName) {
    createCookie(pName, "", -1);
}

    
