// all scripts which are necessary for rendering the page

/**
 * oft genutzte Objekte in DHTML:
 *  Coord
 *  Canvas
 * oft genutzt Funktionen in DHTML
 *  @return LayerReference getLayerRef(String ID)
 *  @return void setPosition(LayerReference objLayer, Coord coords)  
 *  @return void setVisibility(LayerReference objLayer, boolean visible)
 *  @return Coord getMouseXY(evt)
 *  @return void setVisibility4DivByPrefix(prefix, visible)
 */

// Objekte
function Coord(x, y){
  this.x = (!x)?0:x;
  this.y = (!y)?0:y;
  
  this.toString = objToString;
  this.equals = equalsCoord;
}

function Canvas(x, y, width, height){
  this.width = (!width)?0:width;
  this.height = (!height)?0:height;
  
  this.Coord = Coord;
  this.Coord(x, y);
  
  this.equalsCoord = this.equals;
  this.equals = equalsCanvas;
}

function objToString(){
  var ret = "{";
  for(p in this ){
    if (typeof this[p] == "function" || typeof this[p] == "object") continue;
    if(ret.length > 1)
      ret += ",";
    ret += p + ":" + this[p];
  }
  return ret + "}";
}

function equalsCoord(/*Coord*/ c){
  return (this.x == c.x && this.y == c.y);
}
function equalsCanvas(/*Canvas*/ c){
  return ( this.equalsCoord == c.equalsCoord && this.width == c.width && this.height == c.height);
}

// Funktionen

function getLayerRef (id, document) {
  if (!document)
    document = window.document;
  if (document.layers) {
    for (var l = 0; l < document.layers.length; l++)
      if (document.layers[l].id == id)
        return document.layers[l];
    for (var l = 0; l < document.layers.length; l++) {
      var result = getLayerRef(id, document.layers[l].document);
      if (result)
        return result;
    }
    return null;
  }
  else if (document.all) {
    return document.all[id];
  }
  else if (document.getElementById) {
    return document.getElementById(id);
  }
}

function setPosition(objLayer, coords){

    if (document.layers) {
      objLayer.top = coords.y;
      objLayer.left = coords.x;
    } else if (window.opera) {
      objLayer.style.top = coords.y;
      objLayer.style.left = coords.x;
    } else if (document.all) {
      objLayer.style.top = coords.y;
      objLayer.style.pixelLeft = coords.x;
    } else if (document.getElementById) {
      objLayer.style.top = coords.y + 'px'; 
      objLayer.style.left = coords.x + 'px';
    }
}

function setVisibility4DivByPrefix(prefix, visible, d){
  if (!d)
    d = window.document;

  if(document.layers){
    for (var l = 0; l < d.layers.length; l++){
      if(d.layers[l].id.substr(0, prefix.length ) == prefix)
        setVisibility(d.layers[l], visible);
      setVisibility4DivByPrefix(prefix, 
                                visible, 
                                d.layers[l].document);
    }

  } else if(document.all) {

    var layers = document.all.tags("div"); 
    for(i=0; i < layers.length; i++) { 
      if(layers[i].id.substr(0, prefix.length ) == prefix )
        setVisibility(document.all.tags("div")[i], visible);
    }

  } else if(document.getElementsByTagName) {

    var layers = document.getElementsByTagName("div");
    for(i=0; i < layers.length; i++){
      if(layers[i].id.substr(0, prefix.length ) == prefix)
        setVisibility(layers[i], visible);
    }

  }
}

function getMouseXY(evt) {
  e = evt || window.event;
  if(!e) return null;
  
  if(document.layers) {
    return new Coord(e.pageX, e.pageY);
  }else if(window.opera){
    return new Coord(e.clientX, e.clientY);
  }else if(document.all ) {
    return new Coord(e.clientX + document.body.scrollLeft, e.clientY + document.body.scrollTop);
  }else if(document.getElementById) {
    return new Coord(e.pageX , e.pageY );
  }
}

function setVisibility( /* Layer */ objLayer, 
                        /* boolean */ visible ) {
  if(document.layers){
  	 objLayer.visibility  = (visible == true) ? 'show' : 'hide';
  } else {
    objLayer.style.visibility = (visible == true) ? 'visible' : 'hidden';
  }
}

function ptp (){setVisibility(getLayerRef('ptp'), true); return false;}
function allproducts (){setVisibility(getLayerRef('allproducts'), true); return false;}
function searchsuggest (){setVisibility(getLayerRef('searchsuggestcontent'), true); return false;}
function savecartastemplate (){setVisibility(getLayerRef('savecartastemplate'), true); return false;}
function sendcartasemail (){setVisibility(getLayerRef('sendcartasemail'), true); return false;}
function alternatives (){setVisibility(getLayerRef('alternatives'), true); return false;}
function accessories (){setVisibility(getLayerRef('accessories'), true); return false;}
function altacc (){setVisibility(getLayerRef('altacc'), true); return false;}
function umfrage_layer (){setVisibility(getLayerRef('umfrage_layer'), true); return false;}

/** 
 * getStreamingObject(); 
 * liefert ein Flash HTML Object zur�ck 
 */ 

function getStreamingObject(file,width,height,autoplay) {
    return
        '<object type="application/x-shockwave-flash"' +
        ' data="/is-bin/intershop.static/WFS/Merck-International-Site/-/en_US/flash/dcdflvplayer.swf"' +
        ' id="flvplayer" width="' + width + '" height="' + height + '">' +
        '<param name="movie"' +
        ' value="/is-bin/intershop.static/WFS/Merck-International-Site/-/en_US/flash/dcdflvplayer.swf" />' +
        '<param name="allowFullScreen" value="true" />' +
        '<param name="FlashVars" value="width=' + width + '&amp;height=' + height + '&amp;autoplay=' + autoplay +
        '&amp;autoload=1&amp;volume=100&amp;titlesize=12&amp;playercolor=ebeef3&amp;loadingcolor=003399' +
        '&amp;bgcolor=FFFFFF&amp;bgcolor1=93a6c1&amp;bgcolor2=ebeef3&amp;buttoncolor=003399' +
        '&amp;buttonovercolor=cc0033&amp;slidercolor1=003399&amp;slidercolor2=003399&amp;sliderovercolor=cc0033' +
        '&amp;videobgcolor=000000&amp;showstop=1&amp;showvolume=1&amp;showtime=1&amp;showplayer=1&amp;showloading=1' +
        '&amp;showfullscreen=1&amp;showmouse=autohide&amp;loadonstop=1&amp;ondoubleclick=fullscreen&amp;shortcut=1' +
        '&amp;playeralpha=0&amp;flv=' + file +'" />' +
        '</object>';
}


/* lib_ext.js *****************************************************************************/

// Javascript for hiding and displaying detailed product information via styles
//
function displayBlock(element){
   document.getElementById(element).style.display="block";
}
function hideBlock(element){
   document.getElementById(element).style.display="none";
}


// Functions used on the portal page to show/hide some layers
//
/* should be not in use (Perfromance clean-up 06. April 2010
function showLayer(strLayerId){
   document.getElementById(strLayerId).style.display='block';
}
function closeAllLayer(){

   document.getElementById('hiddensub01').style.display='none';

   if(document.getElementById('hiddensub02')){
   document.getElementById('hiddensub02').style.display='none';
   }
   if(document.getElementById('hiddensub03')){
   document.getElementById('hiddensub03').style.display='none';
   }
   if(document.getElementById('hiddensub04')){
   document.getElementById('hiddensub04').style.display='none';
   }
}
*/

// Functions used at the express order template(s).
//
function addRows(val, actionUrl)
{
   document.xpressOrder.action=actionUrl;
   document.xpressOrder.additionalOrderPositions.value=val;
   document.xpressOrder.submit();
}
function setMinQuantity(val)
{
   if(document.getElementById(val).value=='')
   {
      document.getElementById(val).value=1;
   }
}


// Functions used during the request/order process.
function denied()
{
 return false;
}
function saveAsTemplate(actionUrl)
{
   document.CurrentReqGeneralForm.action=actionUrl;
   document.CurrentReqGeneralForm.ReqTemplateForm_Name.value=document.saveAsTemplateForm.Name.value;
   document.CurrentReqGeneralForm.ReqTemplateForm_Description.value=document.saveAsTemplateForm.Description.value;
   document.CurrentReqGeneralForm.submit();
}
function saveAsTemplate1(actionUrl)
{
	document.CurrentReqGeneralForm.action=actionUrl;
	document.CurrentReqGeneralForm.ReqTemplateForm_Name.value=document.saveAsTemplateForm1.Name.value;
	document.CurrentReqGeneralForm.ReqTemplateForm_Description.value=document.saveAsTemplateForm1.Description.value;
	document.CurrentReqGeneralForm.submit();
}
function sendmail(actionUrl)
{
   document.CurrentReqGeneralForm.sendername.value=document.cartasemailform.sendername.value;
   document.CurrentReqGeneralForm.senderemail.value=document.cartasemailform.senderemail.value;
   document.CurrentReqGeneralForm.recipientname.value=document.cartasemailform.recipientname.value;
   document.CurrentReqGeneralForm.recipientemail.value=document.cartasemailform.recipientemail.value;
   document.CurrentReqGeneralForm.comments.value=document.cartasemailform.comments.value;
   document.CurrentReqGeneralForm.action=actionUrl;
   document.CurrentReqGeneralForm.submit();
}
function proceedToCheckout(actionUrl)
{
   document.CurrentReqGeneralForm.action=actionUrl;
   document.CurrentReqGeneralForm.submit();
}


/* start swfobject.js *****************************************************************************/
/**
 * SWFObject v1.4.4: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2006 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * **SWFObject is the SWF embed script formerly known as FlashObject. The name was changed for
 *   legal reasons.
 */
if(typeof deconcept=="undefined"){var deconcept=new Object();}
if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}
if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}
deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a,_b){if(!document.getElementById){return;}
this.DETECT_KEY=_b?_b:"detectflash";
this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);
this.params=new Object();
this.variables=new Object();
this.attributes=new Array();
if(_1){this.setAttribute("swf",_1);}
if(id){this.setAttribute("id",id);}
if(w){this.setAttribute("width",w);}
if(h){this.setAttribute("height",h);}
if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}
this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();
if(c){this.addParam("bgcolor",c);}
var q=_8?_8:"high";
this.addParam("quality",q);
this.setAttribute("useExpressInstall",_7);
this.setAttribute("doExpressInstall",false);
var _d=(_9)?_9:window.location;
this.setAttribute("xiRedirectUrl",_d);
this.setAttribute("redirectUrl","");
if(_a){this.setAttribute("redirectUrl",_a);}};
deconcept.SWFObject.prototype={setAttribute:function(_e,_f){
this.attributes[_e]=_f;
},getAttribute:function(_10){
return this.attributes[_10];
},addParam:function(_11,_12){
this.params[_11]=_12;
},getParams:function(){
return this.params;
},addVariable:function(_13,_14){
this.variables[_13]=_14;
},getVariable:function(_15){
return this.variables[_15];
},getVariables:function(){
return this.variables;
},getVariablePairs:function(){
var _16=new Array();
var key;
var _18=this.getVariables();
for(key in _18){_16.push(key+"="+_18[key]);}
return _16;},getSWFHTML:function(){var _19="";
if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){
if(this.getAttribute("doExpressInstall")){
this.addVariable("MMplayerType","PlugIn");}
_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\"";
_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";
var _1a=this.getParams();
for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}
var _1c=this.getVariablePairs().join("&");
if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";
}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");}
_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\">";
_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";
var _1d=this.getParams();
for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}
var _1f=this.getVariablePairs().join("&");
if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}
return _19;
},write:function(_20){
if(this.getAttribute("useExpressInstall")){
var _21=new deconcept.PlayerVersion([6,0,65]);
if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){
this.setAttribute("doExpressInstall",true);
this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));
document.title=document.title.slice(0,47)+" - Flash Player Installation";
this.addVariable("MMdoctitle",document.title);}}
if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){
var n=(typeof _20=="string")?document.getElementById(_20):_20;
n.innerHTML=this.getSWFHTML();return true;
}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}
return false;}};
deconcept.SWFObjectUtil.getPlayerVersion=function(){
var _23=new deconcept.PlayerVersion([0,0,0]);
if(navigator.plugins&&navigator.mimeTypes.length){
var x=navigator.plugins["Shockwave Flash"];
if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}
}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}
catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}
catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}
catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}
return _23;};
deconcept.PlayerVersion=function(_27){
this.major=_27[0]!=null?parseInt(_27[0]):0;
this.minor=_27[1]!=null?parseInt(_27[1]):0;
this.rev=_27[2]!=null?parseInt(_27[2]):0;
};
deconcept.PlayerVersion.prototype.versionIsValid=function(fv){
if(this.major<fv.major){return false;}
if(this.major>fv.major){return true;}
if(this.minor<fv.minor){return false;}
if(this.minor>fv.minor){return true;}
if(this.rev<fv.rev){
return false;
}return true;};
deconcept.util={getRequestParameter:function(_29){
var q=document.location.search||document.location.hash;
if(q){var _2b=q.substring(1).split("&");
for(var i=0;i<_2b.length;i++){
if(_2b[i].substring(0,_2b[i].indexOf("="))==_29){
return _2b[i].substring((_2b[i].indexOf("=")+1));}}}
return "";}};
deconcept.SWFObjectUtil.cleanupSWFs=function(){if(window.opera||!document.all){return;}
var _2d=document.getElementsByTagName("OBJECT");
for(var i=0;i<_2d.length;i++){_2d[i].style.display="none";for(var x in _2d[i]){
if(typeof _2d[i][x]=="function"){_2d[i][x]=function(){};}}}};
deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};
__flash_savedUnloadHandler=function(){};
if(typeof window.onunload=="function"){
var _30=window.onunload;
window.onunload=function(){
deconcept.SWFObjectUtil.cleanupSWFs();_30();};
}else{window.onunload=deconcept.SWFObjectUtil.cleanupSWFs;}};
if(typeof window.onbeforeunload=="function"){
var oldBeforeUnload=window.onbeforeunload;
window.onbeforeunload=function(){
deconcept.SWFObjectUtil.prepUnload();
oldBeforeUnload();};
}else{window.onbeforeunload=deconcept.SWFObjectUtil.prepUnload;}
if(Array.prototype.push==null){
Array.prototype.push=function(_31){
this[this.length]=_31;
return this.length;};}
var getQueryParamValue=deconcept.util.getRequestParameter;
var FlashObject=deconcept.SWFObject;
var SWFObject=deconcept.SWFObject;
/* end swfobject.js */


/* start HighlightHTML.js *****************************************************************************/
/**
 * Copyright (C) 2008 Intershop Communications AG, all rights reserved.
 *
 * A highlighting class that supports cross-element hightlight spans.
 *
 * Integration is usually done with the attachOnLoad function. For pages that include embedded resources which may
 * take a while to load - like galleries or overloaded web-bug servers - a timing mechanism ist started immediately
 * that waits for the node to be highlighted to appear in the document even before the window is completely loaded.
 * Note that this mechanism is only effective when the node to be highlighted is referenced by its node id.
 *
 * The getFlow() function and its flow assoc define how special nodes are handled. This should be synchronized
 * with the interpretation of HTML tags that is used during search index generation. Currently, there are two
 * interpretations for special nodes implemented:
 * <ol>
 * <li>"block": the node is treated as block-level element that starts a new line.</li>
 * <li>"space": text of the node and all child nodes is ignored, and replaced by a single space.</li>
 * <li>"skip": the node and all child nodes are ignored entirely, and replaced by an empty string.</li>
 * </ol>
 *
 * Property names in the flow assoc must be upper-case; there is no case-conversion during tree traversal for
 * performance reasons. It will be ignored if the configuration specifies an alternative function for getFlow().
 *
 * @param config
 *          An object specifying the following options:<ul>
 *          <li>node: string or DOM node to parse, defaults to document.body</li>
 *          <li>tagName: tag name to wrap highlighted text, defaults to "em"</li>
 *          <li>className: CSS class name to use, defaults to "highlight"</li>
 *          <li>getFlow: function to classify nodes, defaults to getFlow</li>
 *          <li>flow: object with flow properties for tag names</li>
 *          </ul>
 */
function HighlightHTML(config) {
    this.config = config;
    this.flow = this.getProperty(config, "flow", this.flow);
    this.getFlow = this.getProperty(config, "getFlow", this.getFlow);
}

/**
 * Attach a handler to the onload event on <var>win</var> that will highlight the terms in <var>query</var>.
 *
 * @param win
 *         Window where to attach to the onload event.
 * @param query
 *         An array of query terms, or a string used as regular expression to highlight.
 */
HighlightHTML.prototype.attachOnLoad = function(win, query) {
    var t = this;
    var handler = function() {
        var s = arguments.callee;
        if (s.trigger) {
            win.clearTimeout(s.trigger);
            var node = t.getProperty(t.config, "node", document.body);
            if (typeof node !== "string") {
                // Not referenced by id, must wait for completion.
                return;
            } else {
                node = document.getElementById(node);
            }
            if (node) {
                s.trigger = null;
                t.highlight(node,  query);
                return;
            }
            // Not yet loaded, wait for it.
            if (s.delay > 2000) {
                // Give up
                return;
            } else if (s.delay > 0) {
                s.delay = s.delay * 2;
            } else {
                s.delay = 100;
            }
            s.trigger = win.setTimeout(s, s.delay);
        }
    };

    handler.trigger = win.setTimeout(handler, 50);

    if (win.addEventListener) {
        win.addEventListener('load', handler, false);
    } else if (win.attachEvent) {
        win.attachEvent('onload', handler);
    } else {
        var prior = win.onload;
        win.onload = function() {
            handler();
            if (prior) {
                prior();
            }
        };
    }
};

HighlightHTML.prototype.createTreeText = function(node, tree, text, size, next) {
    var length = 0;
    var flow = this.getFlow(node);
    if (flow == "skip") {
        return 0;
    } else if (flow == "space") {
        length = 1;
        next.push(1);
        tree.push(null);
        text.push(" ");
        size.push(length);
    } else if (node.nodeType == 3) { // Text Node
        next.push(1);
        tree.push(node);
        if (node.data) {
            text.push(node.data);
            length += node.data.length;
        }
        size.push(length);
    } else if (node.nodeType == 1) { // Element Node
        var index = next.length;
        next.push(1);
        tree.push(node);
        size.push(0);
        if (flow == "block") {
            // Insert synthetic spacer for block element start.
            length += 1;
            next.push(1);
            tree.push(null);
            text.push("\n");
            size.push(1);
        }
        for (var i = node.firstChild; i; i = i.nextSibling) {
            length += arguments.callee.call(this, i, tree, text, size, next);
        }
        next[index] = node.nextSibling ? next.length - index: 0;
        size[index] = length;
    } else {
        // Unknown node type, ignore.
        return 0;
    }
    return length;
};

HighlightHTML.prototype.flow = {
    ADDRESS: "block",
    BLOCKQUOTE: "block",
    BR: "space",
    CENTER: "block",
    DIR: "block",
    DIR: "block",
    DD: "block",
    DL: "block",
    DT: "block",
    FIELDSET: "block",
    FORM: "block",
    H1: "block",
    H2: "block",
    H3: "block",
    H4: "block",
    H5: "block",
    H6: "block",
    HR: "space",
    ISINDEX: "block",
    LI: "block",
    MENU: "block",
    NOFRAMES: "block",
    NOSCRIPT: "block",
    OBJECT: "skip",
    OL: "block",
    P: "block",
    PRE: "block",
    SCRIPT: "skip",
    STYLE: "skip",
    TABLE: "block",
    TBODY: "block",
    TD: "block",
    TEXTAREA: "skip",
    TFOOT: "block",
    TH: "block",
    THEAD: "block",
    TR: "block"
};

/**
 * Classify nodes by their tag name. The default implementation just looks up the tag name in this.flow.
 *
 * @return "skip" for nodes that should be ignored entirely when parsing the DOM.
 */
HighlightHTML.prototype.getFlow = function(node) {
    if (node) {
        return this.flow[node.tagName];
    }
};

HighlightHTML.prototype.getProperty = function(scope, name, fallback) {
    return scope && scope[name] !== undefined ? scope[name] : fallback;
};

HighlightHTML.prototype.highlight = function(node, query) {
    if (typeof node === "string") {
        node = document.getElementById(node);
    }
    if (!node || !query) {
        return;
    }
    if (typeof query !== "string") {
        var buffer = [];
        for (var i in query) {
            var value = query[i];
            if (value) {
                // Quote meta-characters.
                value = String(value).replace(/[\\\/{}()\[\].*?]/, "\\$&");
                // Make space match any white space.
                value = value.replace(/ +/, "\\s+");
                buffer.push(value);
            }
        }
        query = buffer.join("|");
    }
//    var re = new RegExp(query, "gim");
    var tree = [];
    var text = [];
    var size = [];
    var next = [];
    this.createTreeText(node, tree, text, size, next);
    text = text.join("");

    for (var badchar in this.config.charmap)
    {
    	var myregex = new RegExp(badchar, "gm");
    	text = text.replace(myregex, this.config.charmap[badchar]);
    	query = query.replace(myregex, this.config.charmap[badchar]);
    }
    var re = new RegExp(query, "gim");

    var mark;
    while ((mark = re.exec(text)) != null) {
        this.wrapText(0, mark.index, mark[0].length, tree, size, next);
    }
};

HighlightHTML.prototype.wrapText = function(index, off, len, tree, size, next) {
    while (off + len > 0 && index < next.length) {
        if (size[index] > off) {
            var node = tree[index];
            if (!node) {
                // This node was already split up all the way to the end.
            } else if (node.nodeType == 3) {  // Text Node
                var length = node.data.length
                // Adjust for length of already split nodes.
                var cut = size[index] - length;
                var start = off - cut;
                var end = off + len - cut;
                if (start < 0) {
                    start = 0;
                }
                if (end > length) {
                    end = length;
                }
                if (end > start) {
                    var chunk = node.splitText(start);
                    if (end < length) {
                        tree[index] = chunk.splitText(end - start);
                    } else {
                        tree[index] = null;
                    }
                    var wrapper = chunk.ownerDocument.createElement(this.getProperty(this.config, "tagName", "em"));
                    wrapper.className = this.getProperty(this.config, "className", "highlight");
                    chunk.parentNode.replaceChild(wrapper, chunk);
                    wrapper.appendChild(chunk);
                }
            } else if (node.nodeType == 1 && next[index] != 1) { // Element Node
                this.wrapText(index + 1, off, len, tree, size, next);
            }
        }
        if (next[index]) {
            off -= size[index];
            index += next[index];
        } else {
            break;
        }
    }
};

/* end HighlightHTML.js */


/* ajaxRequests.js *****************************************************************************/
function createAjaxRequest(productSKU, url) {
	$.ajax({
		type: "GET",
		url: url,
		dataType: "html",
		success: function(html) {
			document.getElementById('QuantityForm_' + productSKU + '_Container').innerHTML = html;
		}
	});
}

function toggleContent(objId) {
	$('#'+objId).toggle('slide',{direction:'up',speed:'slow'});
}

function submitAvailablityFormWithAjax(formActionUrl,formid, formcontainerid) {
	var formparams = getFormData(document.getElementById(formid));
	$.ajax({
		type: "POST",
		url: formActionUrl,
		data: formparams,
		traditional: true,
		dataType: "html",
		success: function(html) {document.getElementById(formcontainerid).innerHTML = html;
		}
	});
}


function getFormData(obj) {

	var formparams = {};

	for (i = 0; i < obj.elements.length; i++) {
		if (obj.elements[i].tagName == "INPUT") {
			if ((obj.elements[i].type == "text")
					|| (obj.elements[i].type == "hidden")
					|| (obj.elements[i].type == "submit")) {

				addFormParameter(formparams, obj.elements[i].name, obj.elements[i].value)
			}
			if (obj.elements[i].type == "checkbox") {
				if (obj.elements[i].checked) {

					addFormParameter(formparams, obj.elements[i].name, obj.elements[i].value)
				}
			}
			if (obj.elements[i].type == "radio") {
				if (obj.elements[i].checked) {
					addFormParameter(formparams, obj.elements[i].name, obj.elements[i].value)
				}
			}
		}

		if (obj.elements[i].tagName == "SELECT") {
			var sel = obj.elements[i];
			addFormParameter(formparams, sel.name, sel.options[sel.selectedIndex].value)
		}

	}
	return formparams;
}

function addFormParameter(paramsArray, key, value) {

    if(!paramsArray[key]){
    	paramsArray[key] = new Array();
    }
    paramsArray[key].push(value);
}
/* end ajaxRequests.js */


/* prudsys.js *****************************************************************************/
//sends ajax request to RE
function sendRequestToEngine(url, products, PrudsysBasketRecomm, form) {
	if (url == null) return;
	$.ajax({
		url: url,
		dataType: "json",
		success: function(data) {
			var productNumbers = '';
			if (data != null)
			{
				for (var i=0;i<data[0].Products.length;i++)
				{
					var product = data[0].Products[i];
					if (i == 0)
						productNumbers = product.product_nr;
					else
						productNumbers = productNumbers + ',' + product.product_nr;
				}
				var formparams = {};
				formparams['ProductList'] = productNumbers;
				formparams['PrudsysBasketRecomm'] = PrudsysBasketRecomm;
				$.ajax({
					type: "POST",
					url: products,
					data: formparams,
					dataType: "html",
					success: function(html) {
						$('#renderTable').html(html);
					}
				});
			}
			if (form != null)
				$(form).submit();
		},
		error: function() {
			if (form != null)
				$(form).submit();
			else
				$('#renderTable').hide('slow');
		}
		});
}

//builds URL for ajax request
function getPrudsysProductRecommendations(engineURL, itemIDs, templateName, sessionID, productsURL, PrudsysBasketRecomm) {	
	var recommType = recommType;
	if (itemIDs != null && itemIDs != "" && templateName != null && templateName != "" && sessionID != null && sessionID != "" && productsURL != null && productsURL != "")
	{
		var URL = engineURL + "/recomm/" + templateName + "/sid/" + sessionID + "?item=" + itemIDs;
		sendRequestToEngine(URL, productsURL, PrudsysBasketRecomm);
	}
	else
	{
		$('#renderTable').hide('fast');
	}
}

//Basket Event
function sendPrudsysBasketEvent(engineURL, itemIDs, quantities, sessionID) {	

	if (itemIDs != null && itemIDs != "" && quantities != null && quantities != "" && sessionID != null && sessionID != "")
	{
		quantities = quantities.replace(/\./g, '');
		var URL = engineURL + "/event/basket/sid/" + sessionID + "?itemids=" + itemIDs + "&quantity=" + quantities;
		sendRequestToEngine(URL);
	}
	else
	{
		//nothing to do
	}
}

//Order Event
function sendPrudsysOrderEvent(engineURL, itemIDs, quantities, sessionID) {

	if (itemIDs != null && itemIDs != "" && quantities != null && quantities != "" && sessionID != null && sessionID != "")
	{
		quantities = quantities.replace(/\./g, '');
		var URL = engineURL + "/event/order/sid/" + sessionID + "?itemids=" + itemIDs + "&quantity=" + quantities;
		sendRequestToEngine(URL);
	}
	else
	{
		//nothing to do
	}
}

function getSIDFromURL() {

	var sid = "";
	var url = window.location.href;
	var searchFor = ";sid="
	var startIndex = url.indexOf(searchFor);
	var endIndex = 0;

	if ( startIndex > -1 )
	{
		startIndex = startIndex + searchFor.length;
		url = url.substring(startIndex, url.length);
		endIndex = url.indexOf("=");
		sid = url.substring(0, endIndex+1);
	}
	return sid;
}

function getSIDFromCookie() {
	
	var sid = "";
	var cookies = document.cookie;
	var searchFor = "sid=";
	var startIndex = cookies.indexOf(searchFor);
	var endIndex = 0;

	if (startIndex > -1 && (startIndex == 0 || cookies.charAt(startIndex-1) == " " || cookies.charAt(startIndex-1) == ";"))
	{
		startIndex = startIndex + searchFor.length;
		cookies = cookies.substring(startIndex, cookies.length);
		endIndex = cookies.indexOf("=");
		sid = cookies.substring(0, endIndex+1);
	}
	return sid;
}

function getSID() {

	sid = getSIDFromURL();
	if ( sid == null || sid.length == 0 )
	{
		sid = getSIDFromCookie();
	}
	return sid;
}

/* end prudsys.js */


